@indigoai-us/hq-cli 5.32.0 → 5.33.1

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.
@@ -0,0 +1,517 @@
1
+ /**
2
+ * hq publish <skill-or-worker-path> — marketplace packer + authenticated upload
3
+ * (US-004, hq-creator-marketplace).
4
+ *
5
+ * Flow:
6
+ * 1. Refuse if not logged in (cached Cognito session absent/expired) — uploads
7
+ * nothing. The author uid is read from the cached idToken's `sub`.
8
+ * 2. Validate package.yaml with the canonical 10-rule validator
9
+ * (`validateManifest` from pack-install.ts) — never duplicate that logic.
10
+ * On failure, print the validation error and upload nothing.
11
+ * 3. Stamp `author` (uid from the idToken `sub`, plus handle/displayName) into
12
+ * the pack's package.yaml (AC1). The server re-derives author from the
13
+ * Cognito sub too, but the CLI stamps it so the on-disk + published pack
14
+ * carry attribution.
15
+ * 4. Tar (gzip) the payload, base64-encode the bytes, and POST a JSON body to
16
+ * `/v1/listings` via vaultApiFetch with the access token. The deployed
17
+ * server JSON.parses the body and expects
18
+ * { type, name, slug, version, summary?, contributes(string)?,
19
+ * creatorHandle?, tarball(base64) }, returning the created listing id +
20
+ * `pending_review` status. A 409 (re-publishing the same version) is
21
+ * surfaced as a clear duplicate error.
22
+ * 5. Register/update `modules.yaml` provenance for the published source.
23
+ *
24
+ * Reuses the existing CLI plumbing:
25
+ * - cognito-session.ts (token cache / access token)
26
+ * - vault-api.ts (vaultApiFetch — authed JSON POST to /v1/listings)
27
+ * - pack-install.ts:validateManifest (the 10 validation rules)
28
+ * - manifest.ts (modules.yaml read/write for provenance)
29
+ */
30
+
31
+ import * as fs from 'fs';
32
+ import * as os from 'os';
33
+ import * as path from 'path';
34
+ import * as yaml from 'js-yaml';
35
+ import { execFileSync } from 'child_process';
36
+ import { Command } from 'commander';
37
+ import chalk from 'chalk';
38
+ import { loadCachedTokens, isExpiring } from '@indigoai-us/hq-cloud';
39
+ import { ensureCognitoToken } from '../utils/cognito-session.js';
40
+ import { vaultApiFetch } from '../utils/vault-api.js';
41
+ import { validateManifest } from './pack-install.js';
42
+ import { findHqRoot, readManifest, writeManifest } from '../utils/manifest.js';
43
+ import type { PackManifest, PackModuleDefinition, ModulesManifest } from '../types.js';
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Identity
47
+ // ---------------------------------------------------------------------------
48
+
49
+ export interface IdTokenClaims {
50
+ sub?: string;
51
+ email?: string;
52
+ /** Cognito custom attributes / standard claims used for attribution. */
53
+ 'cognito:username'?: string;
54
+ preferred_username?: string;
55
+ name?: string;
56
+ }
57
+
58
+ /**
59
+ * Decode a Cognito idToken's payload (no signature verification — this is a
60
+ * local read of an already-trusted cached token, mirroring whoami.ts/login.ts).
61
+ * Pure → unit-testable.
62
+ */
63
+ export function peekIdToken(idToken: string): IdTokenClaims {
64
+ try {
65
+ const payload = idToken.split('.')[1];
66
+ if (!payload) return {};
67
+ const pad = payload.length % 4 === 0 ? '' : '='.repeat(4 - (payload.length % 4));
68
+ const normalized = payload.replace(/-/g, '+').replace(/_/g, '/') + pad;
69
+ const decoded = JSON.parse(Buffer.from(normalized, 'base64').toString('utf-8'));
70
+ return decoded as IdTokenClaims;
71
+ } catch {
72
+ return {};
73
+ }
74
+ }
75
+
76
+ export interface ResolvedAuthor {
77
+ uid: string;
78
+ handle: string;
79
+ displayName: string;
80
+ }
81
+
82
+ /**
83
+ * Build the pack `author` block from idToken claims. `uid` is the Cognito
84
+ * `sub` (AC1). `handle`/`displayName` fall back gracefully so a thin token
85
+ * still produces a well-shaped author that passes `validateManifest`. Throws
86
+ * if there is no `sub` (caller is treated as logged-out). Pure.
87
+ */
88
+ export function resolveAuthor(claims: IdTokenClaims): ResolvedAuthor {
89
+ const uid = claims.sub?.trim();
90
+ if (!uid) {
91
+ throw new Error('Cached session has no subject (sub) claim — run `hq login` again.');
92
+ }
93
+ const handle =
94
+ claims.preferred_username?.trim() ||
95
+ claims['cognito:username']?.trim() ||
96
+ claims.email?.split('@')[0]?.trim() ||
97
+ uid;
98
+ const displayName =
99
+ claims.name?.trim() || claims.email?.trim() || handle;
100
+ return { uid, handle, displayName };
101
+ }
102
+
103
+ // ---------------------------------------------------------------------------
104
+ // package.yaml author stamping
105
+ // ---------------------------------------------------------------------------
106
+
107
+ /**
108
+ * Stamp `author` into a parsed manifest object, returning the YAML text to
109
+ * write. Existing `author` is overwritten with the resolved attribution so the
110
+ * publisher's own identity always wins (the server enforces this too). Pure.
111
+ */
112
+ export function stampAuthorYaml(
113
+ manifest: Record<string, unknown>,
114
+ author: ResolvedAuthor,
115
+ ): string {
116
+ const stamped = { ...manifest, author };
117
+ return yaml.dump(stamped, { lineWidth: -1 });
118
+ }
119
+
120
+ /** Read package.yaml, stamp author, write it back. Returns the stamped author. */
121
+ export function stampAuthorIntoPackage(
122
+ payloadDir: string,
123
+ author: ResolvedAuthor,
124
+ ): void {
125
+ const manifestPath = path.join(payloadDir, 'package.yaml');
126
+ const parsed = yaml.load(fs.readFileSync(manifestPath, 'utf-8')) as Record<string, unknown>;
127
+ fs.writeFileSync(manifestPath, stampAuthorYaml(parsed, author));
128
+ }
129
+
130
+ // ---------------------------------------------------------------------------
131
+ // Tarball
132
+ // ---------------------------------------------------------------------------
133
+
134
+ /**
135
+ * Create a gzipped tarball of `payloadDir` and return its bytes. Uses the same
136
+ * `tar` argv approach as pack-install.ts (no shell, no new dep). The archive is
137
+ * written to a tmp file, read back, then removed.
138
+ */
139
+ export function tarballPayload(payloadDir: string): Uint8Array {
140
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hq-publish-tar-'));
141
+ const tarPath = path.join(tmpDir, 'pack.tar.gz');
142
+ try {
143
+ // `-C payloadDir .` packs the directory contents at the archive root
144
+ // (package.yaml + skills/ etc. at top level), excluding VCS/junk.
145
+ execFileSync(
146
+ 'tar',
147
+ [
148
+ '-czf',
149
+ tarPath,
150
+ '-C',
151
+ payloadDir,
152
+ '--exclude=.git',
153
+ '--exclude=node_modules',
154
+ '--exclude=.DS_Store',
155
+ '.',
156
+ ],
157
+ { stdio: ['ignore', 'ignore', 'inherit'] },
158
+ );
159
+ return fs.readFileSync(tarPath);
160
+ } finally {
161
+ fs.rmSync(tmpDir, { recursive: true, force: true });
162
+ }
163
+ }
164
+
165
+ // ---------------------------------------------------------------------------
166
+ // Server-contract field derivation (POST /v1/listings, JSON body)
167
+ // ---------------------------------------------------------------------------
168
+
169
+ /** The marketplace listing type the server enforces (VALID_TYPES). */
170
+ export type ListingType = 'skill' | 'worker';
171
+
172
+ /**
173
+ * Infer the listing `type` the server requires (exactly "skill" | "worker").
174
+ *
175
+ * Rules:
176
+ * - An explicit `type` hint in package.yaml wins if it is already a valid
177
+ * listing type (lets a pack author override the inference deterministically).
178
+ * - Otherwise: a pack that contributes workers → "worker"; one that
179
+ * contributes skills → "skill".
180
+ * - Ambiguous/both/neither → "skill" (the documented default).
181
+ * Pure → unit-testable.
182
+ */
183
+ export function inferListingType(pkg: PackManifest): ListingType {
184
+ const hint = (pkg as unknown as { type?: unknown }).type;
185
+ if (hint === 'skill' || hint === 'worker') return hint;
186
+
187
+ const contributes = pkg.contributes ?? {};
188
+ const hasWorkers = (contributes.workers?.length ?? 0) > 0;
189
+ const hasSkills = (contributes.skills?.length ?? 0) > 0;
190
+
191
+ // Prefer skill when ambiguous (both) or when neither is present.
192
+ if (hasWorkers && !hasSkills) return 'worker';
193
+ return 'skill';
194
+ }
195
+
196
+ /**
197
+ * Derive the marketplace slug from the pack name. By convention pack names are
198
+ * `^hq-pack-[a-z0-9][a-z0-9-]*$`, so we strip the leading `hq-pack-` to get a
199
+ * short, valid, non-empty slug (e.g. `hq-pack-demo` → `demo`). If the name does
200
+ * not carry that prefix we fall back to the full name. Pure.
201
+ */
202
+ export function deriveSlug(packName: string): string {
203
+ const stripped = packName.replace(/^hq-pack-/, '');
204
+ return stripped.length > 0 ? stripped : packName;
205
+ }
206
+
207
+ /**
208
+ * Build the SHORT STRING `contributes` summary the server expects (it stores a
209
+ * string, NOT the structured object). Lists each non-empty contribute category
210
+ * with its entries, e.g. "workers: alpha, beta; skills: demo". Pure.
211
+ */
212
+ export function summarizeContributes(
213
+ contributes: PackManifest['contributes'],
214
+ ): string {
215
+ const parts: string[] = [];
216
+ for (const [key, entries] of Object.entries(contributes ?? {})) {
217
+ if (Array.isArray(entries) && entries.length > 0) {
218
+ parts.push(`${key}: ${entries.join(', ')}`);
219
+ }
220
+ }
221
+ return parts.join('; ');
222
+ }
223
+
224
+ // ---------------------------------------------------------------------------
225
+ // Provenance — modules.yaml upsert
226
+ // ---------------------------------------------------------------------------
227
+
228
+ /**
229
+ * Register or update a `package`-strategy module entry in modules.yaml so the
230
+ * published source has on-disk provenance (AC4). Returns the updated manifest.
231
+ * Pure (operates on an in-memory manifest); the disk read/write is done by the
232
+ * caller via `recordProvenance`.
233
+ */
234
+ export function upsertPackProvenance(
235
+ manifest: ModulesManifest | null,
236
+ entry: PackModuleDefinition,
237
+ ): ModulesManifest {
238
+ const next: ModulesManifest = manifest ?? { version: '1', modules: [] };
239
+ const idx = next.modules.findIndex((m) => m.name === entry.name);
240
+ if (idx >= 0) {
241
+ next.modules[idx] = entry;
242
+ } else {
243
+ next.modules.push(entry);
244
+ }
245
+ return next;
246
+ }
247
+
248
+ /** Read modules.yaml, upsert the provenance entry, write it back. */
249
+ export function recordProvenance(
250
+ hqRoot: string,
251
+ pkg: PackManifest,
252
+ source: string,
253
+ ): void {
254
+ const entry: PackModuleDefinition = {
255
+ name: pkg.name,
256
+ strategy: 'package',
257
+ source,
258
+ version: pkg.version,
259
+ installed_at_iso: new Date().toISOString(),
260
+ // PackManifest.access is 'public'|'private'; module AccessLevel uses
261
+ // 'public'|'team'|'role:*'. A private pack maps to team scope.
262
+ access: pkg.access === 'private' ? 'team' : 'public',
263
+ };
264
+ const updated = upsertPackProvenance(readManifest(hqRoot), entry);
265
+ writeManifest(hqRoot, updated);
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Listing-response formatting
270
+ // ---------------------------------------------------------------------------
271
+
272
+ export interface ListingResponse {
273
+ id?: string;
274
+ listingId?: string;
275
+ status?: string;
276
+ /** Server-resolved creator handle (prefers the caller's claimed handle). */
277
+ creatorHandle?: string;
278
+ }
279
+
280
+ /**
281
+ * Unwrap the `POST /v1/listings` SUCCESS envelope. The deployed server returns
282
+ * the created listing WRAPPED: `{ listing: { listingId, creatorHandle, status,
283
+ * … } }`. Older/mocked responses return the listing fields at the TOP level.
284
+ * This reads `body.listing` when present and falls back to the top-level `body`
285
+ * for backwards-compat. Pure.
286
+ */
287
+ export function unwrapListing(body: Record<string, unknown>): ListingResponse {
288
+ const inner = body?.listing;
289
+ if (inner && typeof inner === 'object') {
290
+ return inner as ListingResponse;
291
+ }
292
+ return body as ListingResponse;
293
+ }
294
+
295
+ /**
296
+ * Map a `POST /v1/listings` response into a user-facing success notice. Pure.
297
+ * Throws a clear error on a duplicate (409) or any non-2xx status so the caller
298
+ * prints it and exits non-zero.
299
+ *
300
+ * The notice uses the REAL listing id and the SERVER-resolved `creatorHandle`
301
+ * from the (possibly `{ listing }`-wrapped) response body — not the
302
+ * locally-resolved author handle — falling back gracefully when the server
303
+ * omits either field.
304
+ */
305
+ export function buildListingNotice(
306
+ status: number,
307
+ body: Record<string, unknown>,
308
+ packName: string,
309
+ packVersion: string,
310
+ ): string {
311
+ if (status === 409) {
312
+ throw new Error(
313
+ `${packName}@${packVersion} is already published (duplicate version). ` +
314
+ `Bump the version in package.yaml and re-run \`hq publish\`.`,
315
+ );
316
+ }
317
+ if (status === 401 || status === 403) {
318
+ throw new Error('Not authorized to publish — run `hq login` and ensure your creator account is verified.');
319
+ }
320
+ if (status < 200 || status >= 300) {
321
+ const msg =
322
+ (body.error as string) ?? (body.message as string) ?? `HTTP ${status}`;
323
+ throw new Error(`Publish failed: ${msg}`);
324
+ }
325
+ const listing = unwrapListing(body);
326
+ const id = listing.listingId ?? listing.id ?? '(unknown id)';
327
+ const listingStatus = listing.status ?? 'pending_review';
328
+ const serverHandle = listing.creatorHandle?.trim();
329
+ const attribution = serverHandle ? ` Attributed to @${serverHandle}.` : '';
330
+ return `Published ${packName}@${packVersion} — listing ${id} (${listingStatus}).${attribution}`;
331
+ }
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // Publish flow (testable core)
335
+ // ---------------------------------------------------------------------------
336
+
337
+ /**
338
+ * The exact JSON body the deployed `POST /v1/listings` handler expects. Field
339
+ * shapes mirror the server contract: `type` ∈ {skill,worker}, `contributes` is
340
+ * a STRING summary (not the structured object), `tarball` is base64 gzip bytes.
341
+ */
342
+ export interface ListingRequest {
343
+ type: ListingType;
344
+ name: string;
345
+ slug: string;
346
+ version: string;
347
+ summary?: string;
348
+ contributes?: string;
349
+ creatorHandle?: string;
350
+ /** Base64-encoded gzip pack tarball (pack.tar.gz bytes). */
351
+ tarball: string;
352
+ }
353
+
354
+ export interface PublishDeps {
355
+ /** Returns the cached idToken, or null/expired if not logged in. */
356
+ loadIdToken: () => string | null;
357
+ /** Returns a non-interactive access token. */
358
+ getAccessToken: () => Promise<string>;
359
+ /**
360
+ * POSTs the listing as a JSON body to `/v1/listings` and returns the parsed
361
+ * { status, body }. `tarball` is the BASE64-encoded gzip pack bytes — the
362
+ * server JSON.parses the body and base64-decodes the tarball.
363
+ */
364
+ upload: (args: {
365
+ token: string;
366
+ listing: ListingRequest;
367
+ }) => Promise<{ status: number; body: Record<string, unknown> }>;
368
+ hqRoot: string;
369
+ /** Reads core.yaml hqVersion for the validator (null when absent). */
370
+ hqVersion: string | null;
371
+ }
372
+
373
+ export interface PublishResult {
374
+ notice: string;
375
+ author: ResolvedAuthor;
376
+ pkg: PackManifest;
377
+ /** True when the success notice already carries the server's attribution. */
378
+ serverAttributed: boolean;
379
+ }
380
+
381
+ /**
382
+ * Core publish logic, dependency-injected so it can be unit-tested with mocked
383
+ * network + a tmp filesystem (no real API, no browser login). Returns the
384
+ * success notice; throws (uploading nothing) on logged-out or validation
385
+ * failure.
386
+ */
387
+ export async function runPublish(
388
+ targetPath: string,
389
+ deps: PublishDeps,
390
+ ): Promise<PublishResult> {
391
+ // 1. Logged-in gate — refuse BEFORE any packing/upload.
392
+ const idToken = deps.loadIdToken();
393
+ if (!idToken) {
394
+ throw new Error('Not logged in — run `hq login` before publishing. Nothing was uploaded.');
395
+ }
396
+ const author = resolveAuthor(peekIdToken(idToken));
397
+
398
+ // Resolve a payload dir. We stamp/validate against a temp copy so we never
399
+ // mutate the user's working tree's package.yaml.
400
+ const absTarget = path.resolve(process.cwd(), targetPath);
401
+ if (!fs.existsSync(absTarget) || !fs.statSync(absTarget).isDirectory()) {
402
+ throw new Error(`Not a directory: ${absTarget}`);
403
+ }
404
+ const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hq-publish-'));
405
+ const payloadDir = path.join(workDir, 'payload');
406
+ try {
407
+ fs.cpSync(absTarget, payloadDir, { recursive: true });
408
+
409
+ // 2. Stamp author (AC1) BEFORE validation so the stamped author is what
410
+ // gets validated, packed, and recorded.
411
+ if (!fs.existsSync(path.join(payloadDir, 'package.yaml'))) {
412
+ throw new Error(`package.yaml missing from ${absTarget} — nothing was uploaded.`);
413
+ }
414
+ stampAuthorIntoPackage(payloadDir, author);
415
+
416
+ // 3. Validate with the canonical 10-rule validator. Throws on any failure;
417
+ // we have uploaded nothing at this point.
418
+ const pkg = validateManifest(payloadDir, deps.hqVersion);
419
+
420
+ // 4. Tar + base64 + authenticated JSON upload. The deployed server
421
+ // JSON.parses the body, so we send the gzip tarball base64-encoded
422
+ // inside a JSON listing request (NOT a raw octet-stream body).
423
+ const tarballBytes = tarballPayload(payloadDir);
424
+ const token = await deps.getAccessToken();
425
+ const listing: ListingRequest = {
426
+ type: inferListingType(pkg),
427
+ name: pkg.name,
428
+ slug: deriveSlug(pkg.name),
429
+ version: pkg.version,
430
+ summary: pkg.description,
431
+ contributes: summarizeContributes(pkg.contributes) || undefined,
432
+ // Server prefers the caller's claimed creator handle, but we stamp our
433
+ // resolved handle as a backwards-compat fallback.
434
+ creatorHandle: author.handle,
435
+ tarball: Buffer.from(tarballBytes).toString('base64'),
436
+ };
437
+ const { status, body } = await deps.upload({ token, listing });
438
+ const notice = buildListingNotice(status, body, pkg.name, pkg.version);
439
+ // Unwrap the `{ listing }` success envelope the server sends so attribution
440
+ // reads the server's resolved handle (fall back to top-level for compat).
441
+ const serverHandle = unwrapListing(body).creatorHandle?.trim();
442
+
443
+ // 5. Provenance (only after a successful upload).
444
+ recordProvenance(deps.hqRoot, pkg, absTarget);
445
+
446
+ return { notice, author, pkg, serverAttributed: Boolean(serverHandle) };
447
+ } finally {
448
+ fs.rmSync(workDir, { recursive: true, force: true });
449
+ }
450
+ }
451
+
452
+ // ---------------------------------------------------------------------------
453
+ // Command wiring
454
+ // ---------------------------------------------------------------------------
455
+
456
+ function readHqVersion(hqRoot: string): string | null {
457
+ const p = path.join(hqRoot, 'core.yaml');
458
+ if (!fs.existsSync(p)) return null;
459
+ try {
460
+ const c = yaml.load(fs.readFileSync(p, 'utf-8')) as { hqVersion?: string };
461
+ return c?.hqVersion ?? null;
462
+ } catch {
463
+ return null;
464
+ }
465
+ }
466
+
467
+ export function registerPublishCommand(program: Command): void {
468
+ program
469
+ .command('publish <path>')
470
+ .description(
471
+ 'Package a skill/worker pack and submit it to the HQ marketplace (POST /v1/listings).',
472
+ )
473
+ .action(async (targetPath: string) => {
474
+ try {
475
+ const hqRoot = findHqRoot();
476
+ const result = await runPublish(targetPath, {
477
+ loadIdToken: () => {
478
+ const cached = loadCachedTokens();
479
+ if (!cached || isExpiring(cached, 0)) return null;
480
+ return cached.idToken;
481
+ },
482
+ getAccessToken: () => ensureCognitoToken({ interactive: false }),
483
+ upload: async ({ token, listing }) => {
484
+ // JSON body (application/json) — the deployed handler JSON.parses
485
+ // the body and base64-decodes `listing.tarball`. vaultApiFetch
486
+ // sends application/json + the bearer token.
487
+ const res = await vaultApiFetch({
488
+ token,
489
+ path: '/v1/listings',
490
+ method: 'POST',
491
+ body: listing as unknown as Record<string, unknown>,
492
+ });
493
+ const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
494
+ return { status: res.status, body: json };
495
+ },
496
+ hqRoot,
497
+ hqVersion: readHqVersion(hqRoot),
498
+ });
499
+ console.log(chalk.green(result.notice));
500
+ // Only print the locally-resolved author as a fallback when the server
501
+ // did NOT return its own resolved handle (already in the notice).
502
+ if (!result.serverAttributed) {
503
+ console.log(
504
+ chalk.dim(
505
+ ` Attributed to ${result.author.displayName} (@${result.author.handle}).`,
506
+ ),
507
+ );
508
+ }
509
+ } catch (err) {
510
+ console.error(
511
+ chalk.red('Error:'),
512
+ err instanceof Error ? err.message : String(err),
513
+ );
514
+ process.exit(1);
515
+ }
516
+ });
517
+ }