@indigoai-us/hq-cli 5.62.1 → 5.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,19 +21,24 @@
21
21
  * and status routes that exist. Renaming an Outpost is not a backend capability.
22
22
  */
23
23
 
24
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b01c6828-502e-5f7a-b15c-acafef4fa143")}catch(e){}}();
24
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d99c091a-e57f-55a6-a666-fdc339c83aab")}catch(e){}}();
25
25
  import chalk from "chalk";
26
+ import { loadCachedTokens } from "@indigoai-us/hq-cloud";
26
27
  import { ensureCognitoToken } from "../utils/cognito-session.js";
27
28
  import { vaultApiFetch } from "../utils/vault-api.js";
29
+ import { OUTPOST_PRICE_CENTS, confirmChargeOrExit, parseBillingPayload, surfaceBillingRequired, } from "../utils/billing-gate.js";
28
30
  /** A non-2xx from the `/outpost/*` control plane. Carries status + `step`. */
29
31
  export class OutpostHttpError extends Error {
30
32
  status;
31
33
  step;
32
- constructor(status, message, step) {
34
+ /** hq-pro's billing envelope on a `402 billing_required` provision block. */
35
+ billing;
36
+ constructor(status, message, step, billing) {
33
37
  super(message);
34
38
  this.name = "OutpostHttpError";
35
39
  this.status = status;
36
40
  this.step = step;
41
+ this.billing = billing;
37
42
  }
38
43
  }
39
44
  /**
@@ -52,10 +57,30 @@ export async function outpostRequest(opts) {
52
57
  : typeof body.error === "string"
53
58
  ? body.error
54
59
  : res.statusText;
55
- throw new OutpostHttpError(res.status, message, body.step);
60
+ throw new OutpostHttpError(res.status, message, body.step, parseBillingPayload(body));
56
61
  }
57
62
  return (await res.json());
58
63
  }
64
+ /**
65
+ * Provision the caller's Outpost. Sends the cached Cognito refresh token so the
66
+ * box can authenticate AS the caller (the same body the console's
67
+ * `provisionMyOutpost` sends). Idempotent server-side: a caller already at their
68
+ * per-person cap gets their existing box back rather than a duplicate. The
69
+ * refresh token is sent over HTTPS and NEVER printed.
70
+ */
71
+ export async function provisionOutpost(token, input) {
72
+ return outpostRequest({
73
+ token,
74
+ path: "/outpost/provision",
75
+ method: "POST",
76
+ body: {
77
+ refreshToken: input.refreshToken,
78
+ ...(input.clientIp ? { clientIp: input.clientIp } : {}),
79
+ ...(input.diskSizeGb ? { diskSizeGb: input.diskSizeGb } : {}),
80
+ ...(input.agentRuntime ? { agentRuntime: input.agentRuntime } : {}),
81
+ },
82
+ });
83
+ }
59
84
  export async function listOutposts(token) {
60
85
  const data = await outpostRequest({
61
86
  token,
@@ -117,6 +142,68 @@ export function registerOutpostsCommand(program) {
117
142
  const outposts = program
118
143
  .command("outposts")
119
144
  .description("Manage your personal HQ Outposts (EC2 boxes)");
145
+ outposts
146
+ .command("provision")
147
+ .alias("create")
148
+ .description("Provision a new Outpost ($80/month — requires --yes)")
149
+ .option("--runtime <runtime>", "Agent runtime: claude | codex (default claude)")
150
+ .option("--disk <gb>", "Root disk size in GB (EC2 only)")
151
+ .option("--client-ip <ip>", "Your public IP for the box's SSH ingress (optional; server derives it otherwise)")
152
+ .option("--yes", "Confirm the $80/month charge (required to provision)")
153
+ .action(async function (opts) {
154
+ try {
155
+ const agentRuntime = opts.runtime === "codex"
156
+ ? "codex"
157
+ : opts.runtime
158
+ ? "claude"
159
+ : undefined;
160
+ let diskSizeGb;
161
+ if (opts.disk !== undefined) {
162
+ diskSizeGb = Number(opts.disk);
163
+ if (!Number.isFinite(diskSizeGb) || diskSizeGb <= 0) {
164
+ console.error(chalk.red(`Invalid --disk '${opts.disk}': must be a positive number of GB.`));
165
+ process.exit(1);
166
+ }
167
+ }
168
+ // Paid gate: print the monthly cost and require --yes before any call.
169
+ confirmChargeOrExit({
170
+ resource: "Outpost",
171
+ unitCents: OUTPOST_PRICE_CENTS,
172
+ yes: opts.yes,
173
+ });
174
+ // The box authenticates AS the caller using the cached refresh token —
175
+ // the same body the console sends. Never printed.
176
+ const refreshToken = loadCachedTokens()?.refreshToken;
177
+ if (!refreshToken) {
178
+ console.error(chalk.red("No cached session found — run `hq login` first, then re-run."));
179
+ process.exit(1);
180
+ }
181
+ const token = await ensureCognitoToken();
182
+ try {
183
+ await provisionOutpost(token, {
184
+ refreshToken,
185
+ ...(opts.clientIp ? { clientIp: opts.clientIp } : {}),
186
+ ...(diskSizeGb ? { diskSizeGb } : {}),
187
+ ...(agentRuntime ? { agentRuntime } : {}),
188
+ });
189
+ console.log(chalk.green("Provisioning started for your Outpost."));
190
+ console.log(chalk.dim("Track it: hq outposts status"));
191
+ }
192
+ catch (err) {
193
+ // No card on file → surface the shareable payment link, not an opaque 402.
194
+ if (err instanceof OutpostHttpError &&
195
+ err.status === 402 &&
196
+ err.billing) {
197
+ await surfaceBillingRequired(token, err.billing);
198
+ process.exit(1);
199
+ }
200
+ throw err;
201
+ }
202
+ }
203
+ catch (err) {
204
+ fail(err);
205
+ }
206
+ });
120
207
  outposts
121
208
  .command("list")
122
209
  .description("List every Outpost you own")
@@ -252,4 +339,4 @@ export function registerOutpostsCommand(program) {
252
339
  });
253
340
  }
254
341
  //# sourceMappingURL=outposts.js.map
255
- //# debugId=b01c6828-502e-5f7a-b15c-acafef4fa143
342
+ //# debugId=d99c091a-e57f-55a6-a666-fdc339c83aab
package/dist/main.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // MUST be first: guard the Node version before any dependency that needs a
6
6
  // Node 20+ API (e.g. util.styleText) or a newer native ABI is evaluated.
7
7
 
8
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d089113e-52b9-5313-a256-63f054d8e72a")}catch(e){}}();
8
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1cc9f0b6-d8a8-54ea-a85f-44437f67b856")}catch(e){}}();
9
9
  import "./node-preflight.js";
10
10
  import { Command } from "commander";
11
11
  import { initSentry, Sentry } from "./sentry.js";
@@ -56,6 +56,7 @@ import { registerCrmCommand } from "./commands/crm.js";
56
56
  import { registerCompanyCommand } from "./commands/company.js";
57
57
  import { registerAgentsCommand } from "./commands/agents.js";
58
58
  import { registerOutpostsCommand } from "./commands/outposts.js";
59
+ import { registerBillingCommand } from "./commands/billing.js";
59
60
  import { registerDbCommand } from "./commands/db.js";
60
61
  import { sanitizeArgv } from "./utils/feedback-diagnostics.js";
61
62
  import { environmentalFsErrorMessage } from "./utils/environmental-error.js";
@@ -209,6 +210,10 @@ registerAgentsCommand(program);
209
210
  // enable Codex on, refresh login for, and destroy your EC2 boxes via the hq-pro
210
211
  // /outpost/* control plane.
211
212
  registerOutpostsCommand(program);
213
+ // Billing (subcommand group — `hq billing …`). Check subscription/card state and
214
+ // mint a shareable Stripe card-capture link — the client side of the paid-
215
+ // provisioning gate for agents & Outposts.
216
+ registerBillingCommand(program);
212
217
  export async function runCli() {
213
218
  try {
214
219
  Sentry.addBreadcrumb({
@@ -269,4 +274,4 @@ export async function runCli() {
269
274
  }
270
275
  }
271
276
  //# sourceMappingURL=main.js.map
272
- //# debugId=d089113e-52b9-5313-a256-63f054d8e72a
277
+ //# debugId=1cc9f0b6-d8a8-54ea-a85f-44437f67b856
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Billing gate for paid provisioning (agents & Outposts).
3
+ *
4
+ * hq-pro enforces billing server-side: a provision call for a resource whose
5
+ * payer has no card on file returns `402` with a `billing` payload carrying a
6
+ * `setup` action that names EXACTLY which checkout endpoint to hit. That
7
+ * endpoint returns `{ url }` — a Stripe-hosted card-capture link.
8
+ *
9
+ * This module wires the client-side experience around that contract:
10
+ * 1. `confirmChargeOrExit` — print the monthly cost and require `--yes`
11
+ * BEFORE any paid provisioning call is made.
12
+ * 2. `surfaceBillingRequired` — when the backend answers `402 billing_required`,
13
+ * mint the card-capture link and print a plain, shareable message instead
14
+ * of an opaque failure.
15
+ * 3. `hq billing checkout` (see commands/billing.ts) reuses `mintPaymentLink`
16
+ * to hand out the same link proactively.
17
+ *
18
+ * Prices mirror the console's authoritative constants
19
+ * (hq-console `src/lib/billing-pricing.ts`): amounts are in the smallest
20
+ * currency unit (US cents) to match Stripe's wire shape.
21
+ */
22
+ /** Per-Agent monthly list price, in cents ($100.00 / agent / month). */
23
+ export declare const AGENT_PRICE_CENTS = 10000;
24
+ /** Per-Outpost monthly list price, in cents ($80.00 / Outpost / month). */
25
+ export declare const OUTPOST_PRICE_CENTS = 8000;
26
+ /** Render a cents amount as a `$X.YZ` USD string. */
27
+ export declare function formatUsd(cents: number): string;
28
+ /**
29
+ * The server-supplied "how to add a card" action on a `402 billing_required`.
30
+ * Mirrors hq-pro `src/billing/activation-billing.ts` `BillingSetupAction` and
31
+ * the console's `src/lib/billing-setup.ts`.
32
+ */
33
+ export interface BillingSetupAction {
34
+ payerType: "company" | "person";
35
+ path: "/v1/billing/checkout/org" | "/v1/billing/checkout/person";
36
+ method: "POST";
37
+ body?: {
38
+ companyUid?: string;
39
+ };
40
+ }
41
+ /** The `billing` envelope hq-pro attaches to a billing-blocked provision. */
42
+ export interface BillingErrorPayload {
43
+ status: string;
44
+ setup?: BillingSetupAction;
45
+ }
46
+ /** Narrow an unknown value to a usable `BillingSetupAction`. */
47
+ export declare function isBillingSetupAction(value: unknown): value is BillingSetupAction;
48
+ /** Pull a `BillingErrorPayload` out of a decoded hq-pro error body, if present. */
49
+ export declare function parseBillingPayload(body: unknown): BillingErrorPayload | undefined;
50
+ export type PaidResource = "agent" | "Outpost";
51
+ /**
52
+ * Gate a paid provisioning call behind an explicit, informed `--yes`. Prints the
53
+ * monthly charge in full prose (this is a paid, outward action — Auto-Clarity)
54
+ * and exits non-zero when the caller has not passed `--yes`. Returns normally
55
+ * once approved so the caller proceeds to provision.
56
+ */
57
+ export declare function confirmChargeOrExit(opts: {
58
+ resource: PaidResource;
59
+ unitCents: number;
60
+ quantity?: number;
61
+ yes?: boolean;
62
+ }): void;
63
+ /**
64
+ * Mint a Stripe-hosted card-capture link for a `BillingSetupAction`. Returns the
65
+ * hosted URL the payer opens to add a card. Throws on a non-2xx (the caller
66
+ * decides how to surface it) — never swallows.
67
+ */
68
+ export declare function mintPaymentLink(token: string, setup: BillingSetupAction): Promise<string>;
69
+ /**
70
+ * The provision was blocked because the payer has no card on file. Mint the
71
+ * card-capture link the backend pointed us at and print a plain, shareable
72
+ * message so the user can add a card (or hand the link to whoever owns billing)
73
+ * and re-run. Returns the URL, or `null` when the server gave no `setup` action
74
+ * to act on. Never prints tokens or secrets.
75
+ */
76
+ export declare function surfaceBillingRequired(token: string, billing: BillingErrorPayload): Promise<string | null>;
77
+ //# sourceMappingURL=billing-gate.d.ts.map
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Billing gate for paid provisioning (agents & Outposts).
3
+ *
4
+ * hq-pro enforces billing server-side: a provision call for a resource whose
5
+ * payer has no card on file returns `402` with a `billing` payload carrying a
6
+ * `setup` action that names EXACTLY which checkout endpoint to hit. That
7
+ * endpoint returns `{ url }` — a Stripe-hosted card-capture link.
8
+ *
9
+ * This module wires the client-side experience around that contract:
10
+ * 1. `confirmChargeOrExit` — print the monthly cost and require `--yes`
11
+ * BEFORE any paid provisioning call is made.
12
+ * 2. `surfaceBillingRequired` — when the backend answers `402 billing_required`,
13
+ * mint the card-capture link and print a plain, shareable message instead
14
+ * of an opaque failure.
15
+ * 3. `hq billing checkout` (see commands/billing.ts) reuses `mintPaymentLink`
16
+ * to hand out the same link proactively.
17
+ *
18
+ * Prices mirror the console's authoritative constants
19
+ * (hq-console `src/lib/billing-pricing.ts`): amounts are in the smallest
20
+ * currency unit (US cents) to match Stripe's wire shape.
21
+ */
22
+
23
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="89efd1d4-af26-50e1-b94f-72b1b5533e3f")}catch(e){}}();
24
+ import chalk from "chalk";
25
+ import { vaultApiFetch } from "./vault-api.js";
26
+ /** Per-Agent monthly list price, in cents ($100.00 / agent / month). */
27
+ export const AGENT_PRICE_CENTS = 10_000;
28
+ /** Per-Outpost monthly list price, in cents ($80.00 / Outpost / month). */
29
+ export const OUTPOST_PRICE_CENTS = 8_000;
30
+ /** Render a cents amount as a `$X.YZ` USD string. */
31
+ export function formatUsd(cents) {
32
+ return `$${(Math.max(0, Math.round(cents)) / 100).toFixed(2)}`;
33
+ }
34
+ /** Narrow an unknown value to a usable `BillingSetupAction`. */
35
+ export function isBillingSetupAction(value) {
36
+ if (!value || typeof value !== "object")
37
+ return false;
38
+ const setup = value;
39
+ const body = setup.body;
40
+ return ((setup.payerType === "company" || setup.payerType === "person") &&
41
+ (setup.path === "/v1/billing/checkout/org" ||
42
+ setup.path === "/v1/billing/checkout/person") &&
43
+ setup.method === "POST" &&
44
+ (body === undefined || (typeof body === "object" && body !== null)));
45
+ }
46
+ /** Pull a `BillingErrorPayload` out of a decoded hq-pro error body, if present. */
47
+ export function parseBillingPayload(body) {
48
+ if (!body || typeof body !== "object")
49
+ return undefined;
50
+ const raw = body.billing;
51
+ if (!raw || typeof raw !== "object")
52
+ return undefined;
53
+ const status = raw.status;
54
+ if (typeof status !== "string")
55
+ return undefined;
56
+ const setup = raw.setup;
57
+ return {
58
+ status,
59
+ ...(isBillingSetupAction(setup) ? { setup } : {}),
60
+ };
61
+ }
62
+ /**
63
+ * Gate a paid provisioning call behind an explicit, informed `--yes`. Prints the
64
+ * monthly charge in full prose (this is a paid, outward action — Auto-Clarity)
65
+ * and exits non-zero when the caller has not passed `--yes`. Returns normally
66
+ * once approved so the caller proceeds to provision.
67
+ */
68
+ export function confirmChargeOrExit(opts) {
69
+ const quantity = opts.quantity ?? 1;
70
+ const total = opts.unitCents * quantity;
71
+ const each = quantity > 1 ? ` (${formatUsd(opts.unitCents)} each × ${quantity})` : "";
72
+ const noun = quantity > 1 ? `${opts.resource}s` : opts.resource;
73
+ const article = /^[aeiou]/i.test(opts.resource) ? "an" : "a";
74
+ const subject = quantity > 1 ? `${quantity} ${noun}` : `${article} ${noun}`;
75
+ if (!opts.yes) {
76
+ console.error(chalk.yellow(`Provisioning ${subject} adds a recurring charge of ` +
77
+ `${formatUsd(total)}/month${each} to the payer on file. This is a ` +
78
+ `paid resource.\n` +
79
+ `Re-run with --yes to confirm you want to incur this charge.`));
80
+ process.exit(1);
81
+ }
82
+ console.log(chalk.dim(`Confirmed: ${formatUsd(total)}/month for ${quantity} ${noun}. Provisioning…`));
83
+ }
84
+ /**
85
+ * Mint a Stripe-hosted card-capture link for a `BillingSetupAction`. Returns the
86
+ * hosted URL the payer opens to add a card. Throws on a non-2xx (the caller
87
+ * decides how to surface it) — never swallows.
88
+ */
89
+ export async function mintPaymentLink(token, setup) {
90
+ const res = await vaultApiFetch({
91
+ token,
92
+ path: setup.path,
93
+ method: "POST",
94
+ body: setup.body?.companyUid ? { companyUid: setup.body.companyUid } : {},
95
+ });
96
+ if (!res.ok) {
97
+ const body = (await res.json().catch(() => ({})));
98
+ throw new Error(`Failed to mint a payment link: ${body.error ?? body.message ?? res.statusText}`);
99
+ }
100
+ const data = (await res.json());
101
+ if (!data.url) {
102
+ throw new Error("Payment link response did not include a checkout URL.");
103
+ }
104
+ return data.url;
105
+ }
106
+ /**
107
+ * The provision was blocked because the payer has no card on file. Mint the
108
+ * card-capture link the backend pointed us at and print a plain, shareable
109
+ * message so the user can add a card (or hand the link to whoever owns billing)
110
+ * and re-run. Returns the URL, or `null` when the server gave no `setup` action
111
+ * to act on. Never prints tokens or secrets.
112
+ */
113
+ export async function surfaceBillingRequired(token, billing) {
114
+ if (!billing.setup) {
115
+ console.error(chalk.yellow("Provisioning is blocked on billing, but the server didn't return a " +
116
+ "payment link. Add a card in the console billing page, then re-run."));
117
+ return null;
118
+ }
119
+ const url = await mintPaymentLink(token, billing.setup);
120
+ console.log(chalk.yellow("No card on file — provisioning is blocked until one is added."));
121
+ console.log("Add a card here (safe to share with whoever owns billing):\n " +
122
+ chalk.cyan(url));
123
+ console.log(chalk.dim("Once a card is added, re-run the same command."));
124
+ return url;
125
+ }
126
+ //# sourceMappingURL=billing-gate.js.map
127
+ //# debugId=89efd1d4-af26-50e1-b94f-72b1b5533e3f
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.62.1",
3
+ "version": "5.63.0",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -19,7 +19,7 @@
19
19
  "clean": "rm -rf dist"
20
20
  },
21
21
  "dependencies": {
22
- "@indigoai-us/hq-cloud": "^6.12.1",
22
+ "@indigoai-us/hq-cloud": "^6.14.2",
23
23
  "@indigoai-us/hq-onboarding": "^0.1.0",
24
24
  "@sentry/node": "^10.49.0",
25
25
  "better-sqlite3": "^12.11.1",
@@ -295,3 +295,87 @@ describe("hq agents status", () => {
295
295
  ).rejects.toThrow("process.exit(1)");
296
296
  });
297
297
  });
298
+
299
+ describe("hq agents provision (billing gate)", () => {
300
+ it("refuses without --yes, prints the cost, and makes NO API call", async () => {
301
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
302
+ await expect(
303
+ run(["agents", "--company", "acme", "provision", "Ops Bot"]),
304
+ ).rejects.toThrow("process.exit(1)");
305
+ expect(fetchSpy).not.toHaveBeenCalled();
306
+ const printed = errSpy.mock.calls
307
+ .map((c) => c.map(String).join(" "))
308
+ .join("\n");
309
+ expect(printed).toMatch(/\$100\.00\/month/);
310
+ });
311
+
312
+ it("POSTs /v1/agents with slugified name + idempotency key when --yes", async () => {
313
+ fetchSpy.mockResolvedValueOnce(
314
+ jsonResponse(200, { uid: "agt_new", slug: "ops-bot" }),
315
+ );
316
+ await run(["agents", "--company", "acme", "provision", "Ops Bot", "--yes"]);
317
+ const [url, init] = fetchSpy.mock.calls[0];
318
+ expect(String(url)).toContain("/v1/agents");
319
+ expect(init?.method).toBe("POST");
320
+ const sent = JSON.parse(init?.body as string);
321
+ expect(sent.companyUid).toBe("cmp_acme");
322
+ expect(sent.name).toBe("Ops Bot");
323
+ expect(sent.slug).toBe("ops-bot");
324
+ expect(sent.codexAuthMode).toBe("subscription");
325
+ expect(typeof sent.idempotencyKey).toBe("string");
326
+ expect(sent.idempotencyKey.length).toBeGreaterThan(0);
327
+ });
328
+
329
+ it("mints a card-capture link on 402 billing_required and exits 1", async () => {
330
+ fetchSpy
331
+ .mockResolvedValueOnce(
332
+ jsonResponse(402, {
333
+ error: "payment required",
334
+ code: "BILLING_REQUIRED",
335
+ billing: {
336
+ status: "billing_required",
337
+ setup: {
338
+ payerType: "company",
339
+ path: "/v1/billing/checkout/org",
340
+ method: "POST",
341
+ body: { companyUid: "cmp_acme" },
342
+ },
343
+ },
344
+ }),
345
+ )
346
+ .mockResolvedValueOnce(
347
+ jsonResponse(200, { url: "https://checkout.stripe.com/card" }),
348
+ );
349
+
350
+ const logSpyLocal = vi.spyOn(console, "log").mockImplementation(() => {});
351
+ await expect(
352
+ run(["agents", "--company", "acme", "provision", "Ops Bot", "--yes"]),
353
+ ).rejects.toThrow("process.exit(1)");
354
+
355
+ // Second call mints the checkout link the 402 pointed at.
356
+ expect(String(fetchSpy.mock.calls[1][0])).toContain(
357
+ "/v1/billing/checkout/org",
358
+ );
359
+ expect(JSON.parse(fetchSpy.mock.calls[1][1]?.body as string)).toEqual({
360
+ companyUid: "cmp_acme",
361
+ });
362
+ const printed = logSpyLocal.mock.calls.map((c) => String(c[0])).join("\n");
363
+ expect(printed).toContain("https://checkout.stripe.com/card");
364
+ });
365
+
366
+ it("requires --api-key-env for --auth-mode apiKey (before any charge)", async () => {
367
+ await expect(
368
+ run([
369
+ "agents",
370
+ "--company",
371
+ "acme",
372
+ "provision",
373
+ "Ops Bot",
374
+ "--auth-mode",
375
+ "apiKey",
376
+ "--yes",
377
+ ]),
378
+ ).rejects.toThrow("process.exit(1)");
379
+ expect(fetchSpy).not.toHaveBeenCalled();
380
+ });
381
+ });
@@ -24,8 +24,16 @@
24
24
 
25
25
  import { Command } from "commander";
26
26
  import chalk from "chalk";
27
+ import { randomUUID } from "node:crypto";
27
28
  import { ensureCognitoToken } from "../utils/cognito-session.js";
28
29
  import { vaultApiFetch, getCompanyUid } from "../utils/vault-api.js";
30
+ import {
31
+ AGENT_PRICE_CENTS,
32
+ confirmChargeOrExit,
33
+ parseBillingPayload,
34
+ surfaceBillingRequired,
35
+ type BillingErrorPayload,
36
+ } from "../utils/billing-gate.js";
29
37
 
30
38
  /** Reasoning-effort values hq-pro accepts on `runtime-config`. */
31
39
  export const VALID_EFFORTS = new Set([
@@ -47,11 +55,19 @@ export const VALID_TIERS = new Set(["default", "priority"]);
47
55
  export class AgentsHttpError extends Error {
48
56
  status: number;
49
57
  code?: string;
50
- constructor(status: number, message: string, code?: string) {
58
+ /** hq-pro's billing envelope on a `402 billing_required` provision block. */
59
+ billing?: BillingErrorPayload;
60
+ constructor(
61
+ status: number,
62
+ message: string,
63
+ code?: string,
64
+ billing?: BillingErrorPayload,
65
+ ) {
51
66
  super(message);
52
67
  this.name = "AgentsHttpError";
53
68
  this.status = status;
54
69
  this.code = code;
70
+ this.billing = billing;
55
71
  }
56
72
  }
57
73
 
@@ -111,11 +127,45 @@ export async function agentsRequest<T>(opts: {
111
127
  res.status,
112
128
  body.error ?? body.message ?? res.statusText,
113
129
  body.code,
130
+ parseBillingPayload(body),
114
131
  );
115
132
  }
116
133
  return (await res.json()) as T;
117
134
  }
118
135
 
136
+ /** Slugify an agent name into a lowercase, hyphen-separated slug. */
137
+ export function slugifyAgentName(name: string): string {
138
+ return name
139
+ .toLowerCase()
140
+ .trim()
141
+ .replace(/[^a-z0-9]+/g, "-")
142
+ .replace(/^-+|-+$/g, "");
143
+ }
144
+
145
+ export interface ProvisionAgentInput {
146
+ companyUid: string;
147
+ name: string;
148
+ slug: string;
149
+ codexAuthMode: "subscription" | "apiKey";
150
+ provider?: "codex" | "grok";
151
+ codexApiKey?: string;
152
+ idempotencyKey: string;
153
+ title?: string;
154
+ description?: string;
155
+ }
156
+
157
+ export async function provisionAgent(
158
+ token: string,
159
+ input: ProvisionAgentInput,
160
+ ): Promise<{ uid?: string; slug?: string; [key: string]: unknown }> {
161
+ return agentsRequest({
162
+ token,
163
+ path: "/v1/agents",
164
+ method: "POST",
165
+ body: input as unknown as Record<string, unknown>,
166
+ });
167
+ }
168
+
119
169
  export async function listAgents(
120
170
  token: string,
121
171
  companyUid: string,
@@ -244,6 +294,112 @@ export function registerAgentsCommand(program: Command): void {
244
294
  (sub.opts().company as string | undefined) ??
245
295
  (agents.opts().company as string | undefined);
246
296
 
297
+ agents
298
+ .command("provision <name>")
299
+ .alias("new")
300
+ .description("Provision a new cloud agent ($100/month — requires --yes)")
301
+ .option("--company <slug>", "Company slug (resolves to companyUid)")
302
+ .option("--slug <slug>", "Agent slug (defaults to a slug of <name>)")
303
+ .option("--provider <provider>", "Runtime: codex | grok (default codex)")
304
+ .option(
305
+ "--auth-mode <mode>",
306
+ "Codex auth: subscription | apiKey (default subscription)",
307
+ "subscription",
308
+ )
309
+ .option(
310
+ "--api-key-env <VAR>",
311
+ "Env var holding the API key for --auth-mode apiKey (never pass the key as a flag)",
312
+ )
313
+ .option("--title <title>", "Org-chart job title")
314
+ .option("--description <text>", "Short description / bio")
315
+ .option("--yes", "Confirm the $100/month charge (required to provision)")
316
+ .action(async function (
317
+ this: Command,
318
+ name: string,
319
+ opts: {
320
+ slug?: string;
321
+ provider?: string;
322
+ authMode?: string;
323
+ apiKeyEnv?: string;
324
+ title?: string;
325
+ description?: string;
326
+ yes?: boolean;
327
+ },
328
+ ) {
329
+ try {
330
+ const authMode = opts.authMode === "apiKey" ? "apiKey" : "subscription";
331
+ const provider =
332
+ opts.provider === "grok" ? "grok" : opts.provider ? "codex" : undefined;
333
+
334
+ // Resolve the API key from the environment (never from a flag value) when
335
+ // apiKey mode is requested — validated BEFORE the paid gate so we don't
336
+ // charge and then fail.
337
+ let codexApiKey: string | undefined;
338
+ if (authMode === "apiKey") {
339
+ const envVar = opts.apiKeyEnv;
340
+ if (!envVar) {
341
+ console.error(
342
+ chalk.red(
343
+ "--auth-mode apiKey requires --api-key-env <VAR> naming the env var that holds the key.",
344
+ ),
345
+ );
346
+ process.exit(1);
347
+ }
348
+ codexApiKey = process.env[envVar];
349
+ if (!codexApiKey) {
350
+ console.error(
351
+ chalk.red(`Env var ${envVar} is empty or unset — no API key to use.`),
352
+ );
353
+ process.exit(1);
354
+ }
355
+ }
356
+
357
+ const token = await ensureCognitoToken();
358
+ const companyUid = await getCompanyUid(token, companyOf(this));
359
+
360
+ // Paid gate: print the monthly cost and require --yes before any call.
361
+ confirmChargeOrExit({
362
+ resource: "agent",
363
+ unitCents: AGENT_PRICE_CENTS,
364
+ yes: opts.yes,
365
+ });
366
+
367
+ const slug = opts.slug ?? slugifyAgentName(name);
368
+ try {
369
+ const result = await provisionAgent(token, {
370
+ companyUid,
371
+ name,
372
+ slug,
373
+ codexAuthMode: authMode,
374
+ ...(provider ? { provider } : {}),
375
+ ...(codexApiKey ? { codexApiKey } : {}),
376
+ idempotencyKey: `hq-cli-${randomUUID()}`,
377
+ ...(opts.title ? { title: opts.title } : {}),
378
+ ...(opts.description ? { description: opts.description } : {}),
379
+ });
380
+ const uid = typeof result.uid === "string" ? result.uid : slug;
381
+ console.log(chalk.green(`Provisioning started for agent "${name}".`));
382
+ console.log(
383
+ chalk.dim(`Track setup: hq agents status ${uid} --company <slug>`),
384
+ );
385
+ } catch (err) {
386
+ // No card on file → surface the shareable payment link instead of an
387
+ // opaque 402, then exit non-zero so scripts can react.
388
+ if (
389
+ err instanceof AgentsHttpError &&
390
+ err.status === 402 &&
391
+ err.billing
392
+ ) {
393
+ await surfaceBillingRequired(token, err.billing);
394
+ process.exit(1);
395
+ }
396
+ throw err;
397
+ }
398
+ } catch (err) {
399
+ fail(err);
400
+ }
401
+ });
402
+
247
403
  agents
248
404
  .command("list")
249
405
  .description("List the company's agents")