pcific 0.0.0-stage → 0.2.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.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/dist/SKILL.md +127 -0
  4. package/dist/api/catalog.js +637 -0
  5. package/dist/api/run.js +960 -0
  6. package/dist/api/search.js +171 -0
  7. package/dist/api/shortcuts.js +799 -0
  8. package/dist/bin.js +648 -0
  9. package/dist/commands/auth.js +513 -0
  10. package/dist/commands/doctor.js +410 -0
  11. package/dist/commands/init.js +306 -0
  12. package/dist/commands/sync.js +214 -0
  13. package/dist/detect.js +214 -0
  14. package/dist/env.js +339 -0
  15. package/dist/goLive.js +629 -0
  16. package/dist/keyLink.js +305 -0
  17. package/dist/mcp/server.js +206 -0
  18. package/dist/mcp/tools.js +689 -0
  19. package/dist/python/template.js +793 -0
  20. package/dist/schema/discover.js +324 -0
  21. package/dist/schema/helpers.js +396 -0
  22. package/dist/schema/prismaToJsonSchema.js +197 -0
  23. package/dist/schema/push.js +570 -0
  24. package/dist/schema/tsToJsonSchema.js +405 -0
  25. package/dist/schema/zodToJsonSchema.js +442 -0
  26. package/dist/templates/openapi.json +1 -0
  27. package/dist/templates/sdk/auth.ts +139 -0
  28. package/dist/templates/sdk/client.ts +1059 -0
  29. package/dist/templates/sdk/errors.ts +76 -0
  30. package/dist/templates/sdk/generated-types.ts +5746 -0
  31. package/dist/templates/sdk/http.ts +359 -0
  32. package/dist/templates/sdk/index.ts +84 -0
  33. package/dist/templates/sdk/json.ts +24 -0
  34. package/dist/templates/sdk/kit.ts +516 -0
  35. package/dist/templates/sdk/multipart.ts +99 -0
  36. package/dist/templates/sdk/sse.ts +131 -0
  37. package/dist/templates/sdk/verify.ts +766 -0
  38. package/dist/templates/sdk-js/auth.d.ts +20 -0
  39. package/dist/templates/sdk-js/auth.js +85 -0
  40. package/dist/templates/sdk-js/client.d.ts +324 -0
  41. package/dist/templates/sdk-js/client.js +607 -0
  42. package/dist/templates/sdk-js/errors.d.ts +51 -0
  43. package/dist/templates/sdk-js/errors.js +48 -0
  44. package/dist/templates/sdk-js/generated-types.d.ts +5736 -0
  45. package/dist/templates/sdk-js/generated-types.js +5 -0
  46. package/dist/templates/sdk-js/http.d.ts +50 -0
  47. package/dist/templates/sdk-js/http.js +263 -0
  48. package/dist/templates/sdk-js/index.d.ts +9 -0
  49. package/dist/templates/sdk-js/index.js +7 -0
  50. package/dist/templates/sdk-js/json.d.ts +11 -0
  51. package/dist/templates/sdk-js/json.js +16 -0
  52. package/dist/templates/sdk-js/kit.d.ts +220 -0
  53. package/dist/templates/sdk-js/kit.js +208 -0
  54. package/dist/templates/sdk-js/multipart.d.ts +23 -0
  55. package/dist/templates/sdk-js/multipart.js +61 -0
  56. package/dist/templates/sdk-js/sse.d.ts +12 -0
  57. package/dist/templates/sdk-js/sse.js +99 -0
  58. package/dist/templates/sdk-js/verify.d.ts +114 -0
  59. package/dist/templates/sdk-js/verify.js +506 -0
  60. package/dist/templates.js +925 -0
  61. package/dist/ui.js +399 -0
  62. package/dist/webhooks/events.js +171 -0
  63. package/dist/webhooks/listen.js +772 -0
  64. package/package.json +32 -4
@@ -0,0 +1,799 @@
1
+ import { isJsonNumber, isJsonObject } from "./catalog.js";
2
+ import { BaseUrlError, CLI_USER_AGENT, DEFAULT_BASE_URL, buildQueryString, callPcificTestApi, formatApiError, isStreamTty, normalizeBaseUrl, readMergedEnv, redactSecrets, resolveTestKey, } from "./run.js";
3
+ function writeOut(stream, text) {
4
+ stream.write(`${redactSecrets(text)}\n`);
5
+ }
6
+ function writeShortcutError(stderr, useJson, payload) {
7
+ if (useJson) {
8
+ writeOut(stderr, JSON.stringify({ ok: false, ...payload }));
9
+ return;
10
+ }
11
+ const statusPart = payload.status ? ` (HTTP ${payload.status})` : "";
12
+ writeOut(stderr, `Error [${payload.code}]${statusPart}: ${payload.error}`);
13
+ writeOut(stderr, `Try this: ${payload.tryThis}`);
14
+ if (payload.requestId) {
15
+ writeOut(stderr, `Request ID: ${payload.requestId}`);
16
+ }
17
+ }
18
+ function readFlagValue(args, index, flag, tryThis) {
19
+ const token = args[index];
20
+ if (token.startsWith(`${flag}=`)) {
21
+ const value = token.slice(flag.length + 1);
22
+ if (!value) {
23
+ return {
24
+ ok: false,
25
+ code: "MISSING_FLAG_VALUE",
26
+ error: `Missing value for ${flag}.`,
27
+ tryThis,
28
+ };
29
+ }
30
+ return { ok: true, value, nextIndex: index };
31
+ }
32
+ const next = args[index + 1];
33
+ if (!next || next.startsWith("-")) {
34
+ return {
35
+ ok: false,
36
+ code: "MISSING_FLAG_VALUE",
37
+ error: `Missing value for ${flag}.`,
38
+ tryThis,
39
+ };
40
+ }
41
+ return { ok: true, value: next, nextIndex: index + 1 };
42
+ }
43
+ function resolveValidatedBaseUrl(raw, stderr, useJson) {
44
+ try {
45
+ return normalizeBaseUrl(raw);
46
+ }
47
+ catch (err) {
48
+ if (err instanceof BaseUrlError) {
49
+ writeShortcutError(stderr, useJson, {
50
+ code: err.code,
51
+ error: err.message,
52
+ tryThis: err.tryThis,
53
+ });
54
+ return null;
55
+ }
56
+ throw err;
57
+ }
58
+ }
59
+ function formatNumber(value) {
60
+ if (isJsonNumber(value)) {
61
+ return String(value);
62
+ }
63
+ return "0";
64
+ }
65
+ function buildUniqueQuery(pairs) {
66
+ const seen = new Set();
67
+ const out = [];
68
+ for (const [key, value] of pairs) {
69
+ if (!value || seen.has(key)) {
70
+ continue;
71
+ }
72
+ seen.add(key);
73
+ out.push([key, value]);
74
+ }
75
+ return out;
76
+ }
77
+ const USAGE_HELP = [
78
+ "Usage: pcific usage [--marketplace-id <id>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--json] [--plain]",
79
+ "",
80
+ "Show credit balance, this month's requests per tool, spend limits, and daily test cap.",
81
+ ].join("\n");
82
+ export async function runUsageCommand(args, options = {}) {
83
+ const cwd = options.cwd ?? process.cwd();
84
+ const stdout = options.stdout ?? process.stdout;
85
+ const stderr = options.stderr ?? process.stderr;
86
+ let jsonFlag = Boolean(options.json) || args.includes("--json");
87
+ let plainFlag = Boolean(options.plain) || args.includes("--plain");
88
+ let marketplaceIdFlag;
89
+ let fromFlag;
90
+ let toFlag;
91
+ let keyKindFlag;
92
+ let baseUrlFlag;
93
+ const getUseJson = () => jsonFlag || (!plainFlag && !isStreamTty(stdout));
94
+ for (let i = 0; i < args.length; i += 1) {
95
+ const arg = args[i];
96
+ if (arg === "--help" || arg === "-h") {
97
+ writeOut(stdout, USAGE_HELP);
98
+ return 0;
99
+ }
100
+ if (arg === "--json") {
101
+ jsonFlag = true;
102
+ continue;
103
+ }
104
+ if (arg === "--plain") {
105
+ plainFlag = true;
106
+ continue;
107
+ }
108
+ if (arg === "--marketplace-id" || arg.startsWith("--marketplace-id=")) {
109
+ const parsed = readFlagValue(args, i, "--marketplace-id", "Pass a shop ID, for example --marketplace-id <shop-id>.");
110
+ if (!parsed.ok) {
111
+ writeShortcutError(stderr, getUseJson(), parsed);
112
+ return 1;
113
+ }
114
+ i = parsed.nextIndex;
115
+ marketplaceIdFlag = parsed.value;
116
+ continue;
117
+ }
118
+ if (arg === "--from" || arg.startsWith("--from=")) {
119
+ const parsed = readFlagValue(args, i, "--from", "Pass a start date, for example --from 2026-01-01.");
120
+ if (!parsed.ok) {
121
+ writeShortcutError(stderr, getUseJson(), parsed);
122
+ return 1;
123
+ }
124
+ i = parsed.nextIndex;
125
+ fromFlag = parsed.value;
126
+ continue;
127
+ }
128
+ if (arg === "--to" || arg.startsWith("--to=")) {
129
+ const parsed = readFlagValue(args, i, "--to", "Pass an end date, for example --to 2026-01-31.");
130
+ if (!parsed.ok) {
131
+ writeShortcutError(stderr, getUseJson(), parsed);
132
+ return 1;
133
+ }
134
+ i = parsed.nextIndex;
135
+ toFlag = parsed.value;
136
+ continue;
137
+ }
138
+ if (arg === "--key-kind" || arg.startsWith("--key-kind=")) {
139
+ const parsed = readFlagValue(args, i, "--key-kind", "Pass a key kind (test or live), for example --key-kind test.");
140
+ if (!parsed.ok) {
141
+ writeShortcutError(stderr, getUseJson(), parsed);
142
+ return 1;
143
+ }
144
+ i = parsed.nextIndex;
145
+ keyKindFlag = parsed.value;
146
+ continue;
147
+ }
148
+ if (arg === "--base-url" || arg.startsWith("--base-url=")) {
149
+ const parsed = readFlagValue(args, i, "--base-url", `Pass a URL, for example --base-url ${DEFAULT_BASE_URL}.`);
150
+ if (!parsed.ok) {
151
+ writeShortcutError(stderr, getUseJson(), parsed);
152
+ return 1;
153
+ }
154
+ i = parsed.nextIndex;
155
+ baseUrlFlag = parsed.value;
156
+ continue;
157
+ }
158
+ writeShortcutError(stderr, getUseJson(), {
159
+ code: "UNKNOWN_FLAG",
160
+ error: `Unknown argument "${arg}" for pcific usage.`,
161
+ tryThis: "Run pcific usage --help to see supported options.",
162
+ });
163
+ return 1;
164
+ }
165
+ const useJson = getUseJson();
166
+ const keyResult = resolveTestKey(cwd, options.env);
167
+ if (!keyResult.ok) {
168
+ writeShortcutError(stderr, useJson, keyResult);
169
+ return 1;
170
+ }
171
+ const marketplaceId = marketplaceIdFlag ?? keyResult.marketplaceId;
172
+ const baseUrl = resolveValidatedBaseUrl(baseUrlFlag ?? options.baseUrl ?? keyResult.baseUrl, stderr, useJson);
173
+ if (!baseUrl) {
174
+ return 1;
175
+ }
176
+ const query = buildUniqueQuery([
177
+ ["marketplaceId", marketplaceId],
178
+ ["from", fromFlag],
179
+ ["to", toFlag],
180
+ ["keyKind", keyKindFlag],
181
+ ]);
182
+ try {
183
+ const res = await callPcificTestApi({
184
+ method: "GET",
185
+ path: "/api/v1/usage",
186
+ baseUrl,
187
+ apiKey: keyResult.apiKey,
188
+ query,
189
+ fetchFn: options.fetch,
190
+ });
191
+ if (!res.ok) {
192
+ writeShortcutError(stderr, useJson, res.error ?? formatApiError(res.status, res.body, res.requestId));
193
+ return 1;
194
+ }
195
+ if (useJson) {
196
+ writeOut(stdout, JSON.stringify(res.body));
197
+ return 0;
198
+ }
199
+ const data = isJsonObject(res.body) ? res.body : {};
200
+ const balance = isJsonObject(data.balance) ? data.balance : {};
201
+ const testCap = isJsonObject(data.testDailyCap) ? data.testDailyCap : {};
202
+ const thisMonth = isJsonObject(data.thisMonth) ? data.thisMonth : {};
203
+ const tools = Array.isArray(thisMonth.tools) ? thisMonth.tools : [];
204
+ writeOut(stdout, "PCIFIC Usage");
205
+ if (balance.unlimited) {
206
+ writeOut(stdout, " Credit balance: unlimited");
207
+ }
208
+ else {
209
+ writeOut(stdout, ` Credit balance: ${formatNumber(balance.credits)} credits`);
210
+ }
211
+ if (isJsonNumber(testCap.limit)) {
212
+ writeOut(stdout, ` Test daily AI cap: ${formatNumber(testCap.usedToday)}/${formatNumber(testCap.limit)} used today`);
213
+ }
214
+ if (tools.length > 0) {
215
+ writeOut(stdout, " This month by tool:");
216
+ for (const tool of tools) {
217
+ if (!isJsonObject(tool)) {
218
+ continue;
219
+ }
220
+ writeOut(stdout, ` - ${String(tool.tool ?? "unknown")}: ${formatNumber(tool.requests)} requests (${formatNumber(tool.succeeded)} ok, ${formatNumber(tool.failed)} failed, ${formatNumber(tool.credits)} credits)`);
221
+ }
222
+ }
223
+ return 0;
224
+ }
225
+ catch (err) {
226
+ writeShortcutError(stderr, useJson, {
227
+ code: "NETWORK_ERROR",
228
+ error: `Failed to fetch usage: ${err instanceof Error ? err.message : String(err)}`,
229
+ tryThis: `Check connectivity to ${baseUrl} and try again.`,
230
+ });
231
+ return 1;
232
+ }
233
+ }
234
+ const STATS_HELP = [
235
+ "Usage: pcific stats [--marketplace-id <id>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--json] [--plain]",
236
+ "",
237
+ "Show credit spend, per-tool totals, request outcomes, and recent failures from /api/v1/analytics and /api/v1/monitoring/summary.",
238
+ ].join("\n");
239
+ export async function runStatsCommand(args, options = {}) {
240
+ const cwd = options.cwd ?? process.cwd();
241
+ const stdout = options.stdout ?? process.stdout;
242
+ const stderr = options.stderr ?? process.stderr;
243
+ let jsonFlag = Boolean(options.json) || args.includes("--json");
244
+ let plainFlag = Boolean(options.plain) || args.includes("--plain");
245
+ let marketplaceIdFlag;
246
+ let fromFlag;
247
+ let toFlag;
248
+ let keyKindFlag;
249
+ let baseUrlFlag;
250
+ const getUseJson = () => jsonFlag || (!plainFlag && !isStreamTty(stdout));
251
+ for (let i = 0; i < args.length; i += 1) {
252
+ const arg = args[i];
253
+ if (arg === "--help" || arg === "-h") {
254
+ writeOut(stdout, STATS_HELP);
255
+ return 0;
256
+ }
257
+ if (arg === "--json") {
258
+ jsonFlag = true;
259
+ continue;
260
+ }
261
+ if (arg === "--plain") {
262
+ plainFlag = true;
263
+ continue;
264
+ }
265
+ if (arg === "--marketplace-id" || arg.startsWith("--marketplace-id=")) {
266
+ const parsed = readFlagValue(args, i, "--marketplace-id", "Pass a shop ID, for example --marketplace-id <shop-id>.");
267
+ if (!parsed.ok) {
268
+ writeShortcutError(stderr, getUseJson(), parsed);
269
+ return 1;
270
+ }
271
+ i = parsed.nextIndex;
272
+ marketplaceIdFlag = parsed.value;
273
+ continue;
274
+ }
275
+ if (arg === "--from" || arg.startsWith("--from=")) {
276
+ const parsed = readFlagValue(args, i, "--from", "Pass a start date, for example --from 2026-01-01.");
277
+ if (!parsed.ok) {
278
+ writeShortcutError(stderr, getUseJson(), parsed);
279
+ return 1;
280
+ }
281
+ i = parsed.nextIndex;
282
+ fromFlag = parsed.value;
283
+ continue;
284
+ }
285
+ if (arg === "--to" || arg.startsWith("--to=")) {
286
+ const parsed = readFlagValue(args, i, "--to", "Pass an end date, for example --to 2026-01-31.");
287
+ if (!parsed.ok) {
288
+ writeShortcutError(stderr, getUseJson(), parsed);
289
+ return 1;
290
+ }
291
+ i = parsed.nextIndex;
292
+ toFlag = parsed.value;
293
+ continue;
294
+ }
295
+ if (arg === "--key-kind" || arg.startsWith("--key-kind=")) {
296
+ const parsed = readFlagValue(args, i, "--key-kind", "Pass a key kind (test or live), for example --key-kind test.");
297
+ if (!parsed.ok) {
298
+ writeShortcutError(stderr, getUseJson(), parsed);
299
+ return 1;
300
+ }
301
+ i = parsed.nextIndex;
302
+ keyKindFlag = parsed.value;
303
+ continue;
304
+ }
305
+ if (arg === "--base-url" || arg.startsWith("--base-url=")) {
306
+ const parsed = readFlagValue(args, i, "--base-url", `Pass a URL, for example --base-url ${DEFAULT_BASE_URL}.`);
307
+ if (!parsed.ok) {
308
+ writeShortcutError(stderr, getUseJson(), parsed);
309
+ return 1;
310
+ }
311
+ i = parsed.nextIndex;
312
+ baseUrlFlag = parsed.value;
313
+ continue;
314
+ }
315
+ writeShortcutError(stderr, getUseJson(), {
316
+ code: "UNKNOWN_FLAG",
317
+ error: `Unknown argument "${arg}" for pcific stats.`,
318
+ tryThis: "Run pcific stats --help to see supported options.",
319
+ });
320
+ return 1;
321
+ }
322
+ const useJson = getUseJson();
323
+ const keyResult = resolveTestKey(cwd, options.env);
324
+ if (!keyResult.ok) {
325
+ writeShortcutError(stderr, useJson, keyResult);
326
+ return 1;
327
+ }
328
+ const marketplaceId = marketplaceIdFlag ?? keyResult.marketplaceId;
329
+ const baseUrl = resolveValidatedBaseUrl(baseUrlFlag ?? options.baseUrl ?? keyResult.baseUrl, stderr, useJson);
330
+ if (!baseUrl) {
331
+ return 1;
332
+ }
333
+ const query = buildUniqueQuery([
334
+ ["marketplaceId", marketplaceId],
335
+ ["from", fromFlag],
336
+ ["to", toFlag],
337
+ ["keyKind", keyKindFlag],
338
+ ]);
339
+ try {
340
+ const [analyticsRes, monitoringRes] = await Promise.all([
341
+ callPcificTestApi({
342
+ method: "GET",
343
+ path: "/api/v1/analytics",
344
+ baseUrl,
345
+ apiKey: keyResult.apiKey,
346
+ query,
347
+ fetchFn: options.fetch,
348
+ }),
349
+ callPcificTestApi({
350
+ method: "GET",
351
+ path: "/api/v1/monitoring/summary",
352
+ baseUrl,
353
+ apiKey: keyResult.apiKey,
354
+ query,
355
+ fetchFn: options.fetch,
356
+ }),
357
+ ]);
358
+ if (!analyticsRes.ok) {
359
+ writeShortcutError(stderr, useJson, analyticsRes.error ??
360
+ formatApiError(analyticsRes.status, analyticsRes.body, analyticsRes.requestId));
361
+ return 1;
362
+ }
363
+ if (!monitoringRes.ok) {
364
+ writeShortcutError(stderr, useJson, monitoringRes.error ??
365
+ formatApiError(monitoringRes.status, monitoringRes.body, monitoringRes.requestId));
366
+ return 1;
367
+ }
368
+ if (useJson) {
369
+ writeOut(stdout, JSON.stringify({
370
+ analytics: analyticsRes.body,
371
+ monitoring: monitoringRes.body,
372
+ }));
373
+ return 0;
374
+ }
375
+ const analytics = isJsonObject(analyticsRes.body) ? analyticsRes.body : {};
376
+ const monitoring = isJsonObject(monitoringRes.body) ? monitoringRes.body : {};
377
+ const balance = isJsonObject(analytics.balance) ? analytics.balance : {};
378
+ const monthToDate = isJsonObject(analytics.monthToDate) ? analytics.monthToDate : {};
379
+ const outcomes = isJsonObject(analytics.outcomes)
380
+ ? analytics.outcomes
381
+ : isJsonObject(monitoring.requests)
382
+ ? monitoring.requests
383
+ : {};
384
+ const tools = Array.isArray(analytics.tools)
385
+ ? analytics.tools
386
+ : Array.isArray(monitoring.tools)
387
+ ? monitoring.tools
388
+ : [];
389
+ const failures = Array.isArray(analytics.failures) ? analytics.failures : [];
390
+ writeOut(stdout, "PCIFIC Stats");
391
+ writeOut(stdout, ` Credits: balance ${balance.unlimited ? "unlimited" : formatNumber(balance.credits)}, spent this month ${formatNumber(monthToDate.credits)}`);
392
+ const totalReq = formatNumber(outcomes.total);
393
+ const okReq = formatNumber(outcomes.ok ?? outcomes.succeeded);
394
+ const failedReq = formatNumber(outcomes.failed);
395
+ const rate = isJsonNumber(outcomes.successRate) ? ` (${outcomes.successRate}% success)` : "";
396
+ writeOut(stdout, ` Outcomes: ${totalReq} total, ${okReq} ok, ${failedReq} failed${rate}`);
397
+ if (tools.length > 0) {
398
+ writeOut(stdout, " Per-tool totals:");
399
+ for (const tool of tools) {
400
+ if (!isJsonObject(tool)) {
401
+ continue;
402
+ }
403
+ const reqs = tool.requests ?? tool.total;
404
+ const creditPart = tool.credits !== undefined ? `, ${formatNumber(tool.credits)} credits` : "";
405
+ writeOut(stdout, ` - ${String(tool.tool ?? "unknown")}: ${formatNumber(reqs)} requests (${formatNumber(tool.succeeded)} ok, ${formatNumber(tool.failed)} failed${creditPart})`);
406
+ }
407
+ }
408
+ if (failures.length > 0) {
409
+ writeOut(stdout, " Recent failures:");
410
+ for (const failure of failures.slice(0, 5)) {
411
+ if (!isJsonObject(failure)) {
412
+ continue;
413
+ }
414
+ writeOut(stdout, ` - [${String(failure.status ?? "err")}] ${String(failure.method ?? "")} ${String(failure.route ?? "")} (${String(failure.errorCode ?? "unknown")}) requestId=${String(failure.requestId ?? "")}`);
415
+ }
416
+ }
417
+ else {
418
+ writeOut(stdout, " Recent failures: none");
419
+ }
420
+ return 0;
421
+ }
422
+ catch (err) {
423
+ writeShortcutError(stderr, useJson, {
424
+ code: "NETWORK_ERROR",
425
+ error: `Failed to fetch stats: ${err instanceof Error ? err.message : String(err)}`,
426
+ tryThis: `Check connectivity to ${baseUrl} and try again.`,
427
+ });
428
+ return 1;
429
+ }
430
+ }
431
+ const LOGS_HELP = [
432
+ "Usage: pcific logs [--limit N] [--id <requestId>] [--tool <name>] [--status <code|ok|failed>] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--marketplace-id <id>] [--json] [--plain]",
433
+ "",
434
+ "Inspect request logs via GET /api/v1/logs or GET /api/v1/logs/{requestId}.",
435
+ "Requires a test key with the explicit `logs` permission (off by default).",
436
+ ].join("\n");
437
+ export async function runLogsCommand(args, options = {}) {
438
+ const cwd = options.cwd ?? process.cwd();
439
+ const stdout = options.stdout ?? process.stdout;
440
+ const stderr = options.stderr ?? process.stderr;
441
+ let jsonFlag = Boolean(options.json) || args.includes("--json");
442
+ let plainFlag = Boolean(options.plain) || args.includes("--plain");
443
+ let limitFlag;
444
+ let idFlag;
445
+ let toolFlag;
446
+ let statusFlag;
447
+ let fromFlag;
448
+ let toFlag;
449
+ let marketplaceIdFlag;
450
+ let baseUrlFlag;
451
+ const getUseJson = () => jsonFlag || (!plainFlag && !isStreamTty(stdout));
452
+ for (let i = 0; i < args.length; i += 1) {
453
+ const arg = args[i];
454
+ if (arg === "--help" || arg === "-h") {
455
+ writeOut(stdout, LOGS_HELP);
456
+ return 0;
457
+ }
458
+ if (arg === "--json") {
459
+ jsonFlag = true;
460
+ continue;
461
+ }
462
+ if (arg === "--plain") {
463
+ plainFlag = true;
464
+ continue;
465
+ }
466
+ if (arg === "--limit" || arg === "-n" || arg.startsWith("--limit=")) {
467
+ const parsed = readFlagValue(args, i, "--limit", "Pass a positive integer, for example --limit 20.");
468
+ if (!parsed.ok) {
469
+ writeShortcutError(stderr, getUseJson(), parsed);
470
+ return 1;
471
+ }
472
+ i = parsed.nextIndex;
473
+ const numeric = Number.parseInt(parsed.value, 10);
474
+ if (!Number.isFinite(numeric) || numeric < 1) {
475
+ writeShortcutError(stderr, getUseJson(), {
476
+ code: "INVALID_LIMIT",
477
+ error: `Invalid --limit value "${parsed.value}".`,
478
+ tryThis: "Pass a positive integer, for example --limit 20.",
479
+ });
480
+ return 1;
481
+ }
482
+ limitFlag = String(numeric);
483
+ continue;
484
+ }
485
+ if (arg === "--id" || arg.startsWith("--id=")) {
486
+ const parsed = readFlagValue(args, i, "--id", "Pass a requestId from pcific logs or X-Request-Id, for example --id <requestId>.");
487
+ if (!parsed.ok) {
488
+ writeShortcutError(stderr, getUseJson(), parsed);
489
+ return 1;
490
+ }
491
+ i = parsed.nextIndex;
492
+ idFlag = parsed.value;
493
+ continue;
494
+ }
495
+ if (arg === "--tool" || arg.startsWith("--tool=")) {
496
+ const parsed = readFlagValue(args, i, "--tool", "Pass a tool name, for example --tool safeguard.");
497
+ if (!parsed.ok) {
498
+ writeShortcutError(stderr, getUseJson(), parsed);
499
+ return 1;
500
+ }
501
+ i = parsed.nextIndex;
502
+ toolFlag = parsed.value;
503
+ continue;
504
+ }
505
+ if (arg === "--status" || arg.startsWith("--status=")) {
506
+ const parsed = readFlagValue(args, i, "--status", "Pass a status filter, for example --status failed.");
507
+ if (!parsed.ok) {
508
+ writeShortcutError(stderr, getUseJson(), parsed);
509
+ return 1;
510
+ }
511
+ i = parsed.nextIndex;
512
+ statusFlag = parsed.value;
513
+ continue;
514
+ }
515
+ if (arg === "--from" || arg.startsWith("--from=")) {
516
+ const parsed = readFlagValue(args, i, "--from", "Pass a start date, for example --from 2026-01-01.");
517
+ if (!parsed.ok) {
518
+ writeShortcutError(stderr, getUseJson(), parsed);
519
+ return 1;
520
+ }
521
+ i = parsed.nextIndex;
522
+ fromFlag = parsed.value;
523
+ continue;
524
+ }
525
+ if (arg === "--to" || arg.startsWith("--to=")) {
526
+ const parsed = readFlagValue(args, i, "--to", "Pass an end date, for example --to 2026-01-31.");
527
+ if (!parsed.ok) {
528
+ writeShortcutError(stderr, getUseJson(), parsed);
529
+ return 1;
530
+ }
531
+ i = parsed.nextIndex;
532
+ toFlag = parsed.value;
533
+ continue;
534
+ }
535
+ if (arg === "--marketplace-id" || arg.startsWith("--marketplace-id=")) {
536
+ const parsed = readFlagValue(args, i, "--marketplace-id", "Pass a shop ID, for example --marketplace-id <shop-id>.");
537
+ if (!parsed.ok) {
538
+ writeShortcutError(stderr, getUseJson(), parsed);
539
+ return 1;
540
+ }
541
+ i = parsed.nextIndex;
542
+ marketplaceIdFlag = parsed.value;
543
+ continue;
544
+ }
545
+ if (arg === "--base-url" || arg.startsWith("--base-url=")) {
546
+ const parsed = readFlagValue(args, i, "--base-url", `Pass a URL, for example --base-url ${DEFAULT_BASE_URL}.`);
547
+ if (!parsed.ok) {
548
+ writeShortcutError(stderr, getUseJson(), parsed);
549
+ return 1;
550
+ }
551
+ i = parsed.nextIndex;
552
+ baseUrlFlag = parsed.value;
553
+ continue;
554
+ }
555
+ writeShortcutError(stderr, getUseJson(), {
556
+ code: "UNKNOWN_FLAG",
557
+ error: `Unknown argument "${arg}" for pcific logs.`,
558
+ tryThis: "Run pcific logs --help to see supported options.",
559
+ });
560
+ return 1;
561
+ }
562
+ const useJson = getUseJson();
563
+ const keyResult = resolveTestKey(cwd, options.env);
564
+ if (!keyResult.ok) {
565
+ writeShortcutError(stderr, useJson, keyResult);
566
+ return 1;
567
+ }
568
+ const marketplaceId = marketplaceIdFlag ?? keyResult.marketplaceId;
569
+ const baseUrl = resolveValidatedBaseUrl(baseUrlFlag ?? options.baseUrl ?? keyResult.baseUrl, stderr, useJson);
570
+ if (!baseUrl) {
571
+ return 1;
572
+ }
573
+ const endpointPath = idFlag ? `/api/v1/logs/${encodeURIComponent(idFlag)}` : "/api/v1/logs";
574
+ const query = idFlag
575
+ ? []
576
+ : buildUniqueQuery([
577
+ ["limit", limitFlag],
578
+ ["tool", toolFlag],
579
+ ["status", statusFlag],
580
+ ["from", fromFlag],
581
+ ["to", toFlag],
582
+ ["marketplaceId", marketplaceId],
583
+ ]);
584
+ try {
585
+ const res = await callPcificTestApi({
586
+ method: "GET",
587
+ path: endpointPath,
588
+ baseUrl,
589
+ apiKey: keyResult.apiKey,
590
+ query,
591
+ fetchFn: options.fetch,
592
+ });
593
+ if (!res.ok) {
594
+ const baseErr = res.error ?? formatApiError(res.status, res.body, res.requestId);
595
+ if (res.status === 403) {
596
+ writeShortcutError(stderr, useJson, {
597
+ ...baseErr,
598
+ error: `${baseErr.error} Reading /api/v1/logs requires the explicit \`logs\` permission (the \`read\` permission alone does not open logs).`,
599
+ tryThis: "Link or create a test key with the `logs` scope enabled (for example via `npx pcific init --reauth` or in Dashboard > Keys), then re-run `pcific logs`.",
600
+ });
601
+ return 1;
602
+ }
603
+ writeShortcutError(stderr, useJson, baseErr);
604
+ return 1;
605
+ }
606
+ if (useJson) {
607
+ writeOut(stdout, JSON.stringify(res.body));
608
+ return 0;
609
+ }
610
+ if (idFlag) {
611
+ writeOut(stdout, JSON.stringify(res.body, null, 2));
612
+ return 0;
613
+ }
614
+ const data = isJsonObject(res.body) ? res.body : {};
615
+ const requests = Array.isArray(data.requests) ? data.requests : [];
616
+ const total = formatNumber(data.total ?? requests.length);
617
+ writeOut(stdout, `PCIFIC Request Logs (${requests.length} of ${total}):`);
618
+ if (requests.length === 0) {
619
+ writeOut(stdout, " No matching request logs found.");
620
+ return 0;
621
+ }
622
+ for (const row of requests) {
623
+ if (!isJsonObject(row)) {
624
+ continue;
625
+ }
626
+ const errPart = row.errorCode ? ` error=${String(row.errorCode)}` : "";
627
+ writeOut(stdout, ` [${String(row.status ?? "-")}] ${String(row.method ?? "")} ${String(row.route ?? "")}${errPart} (${String(row.durationMs ?? 0)}ms) id=${String(row.requestId ?? row.id ?? "")}`);
628
+ }
629
+ return 0;
630
+ }
631
+ catch (err) {
632
+ writeShortcutError(stderr, useJson, {
633
+ code: "NETWORK_ERROR",
634
+ error: `Failed to fetch logs: ${err instanceof Error ? err.message : String(err)}`,
635
+ tryThis: `Check connectivity to ${baseUrl} and try again.`,
636
+ });
637
+ return 1;
638
+ }
639
+ }
640
+ const DOCS_HELP = [
641
+ "Usage: pcific docs [slug] [--quick] [--changelog] [--since YYYY-MM-DD] [--base-url <url>] [--json]",
642
+ "",
643
+ "Fetch plain-text PCIFIC documentation (no API key required).",
644
+ "",
645
+ "Examples:",
646
+ " pcific docs Fetch /llms.txt index",
647
+ " pcific docs safeguard Fetch /docs/safeguard.txt",
648
+ " pcific docs safeguard --quick Fetch /docs/safeguard/quick.txt",
649
+ " pcific docs --changelog Fetch /changelog.txt",
650
+ " pcific docs --changelog --since 2026-01-01",
651
+ ].join("\n");
652
+ const COMMON_DOC_SLUGS = [
653
+ "getting-started",
654
+ "build-it-yourself",
655
+ "api-keys",
656
+ "marketplace-configuration",
657
+ "listing-fields-by-hand",
658
+ "safeguard",
659
+ "listing-generation",
660
+ "ask-pcific",
661
+ "pixel-trace",
662
+ "message-check",
663
+ "dispute-pack",
664
+ "webhooks",
665
+ "errors-and-limits",
666
+ ];
667
+ export async function runDocsCommand(args, options = {}) {
668
+ const cwd = options.cwd ?? process.cwd();
669
+ const stdout = options.stdout ?? process.stdout;
670
+ const stderr = options.stderr ?? process.stderr;
671
+ let jsonFlag = Boolean(options.json) || args.includes("--json");
672
+ let quickFlag = false;
673
+ let changelogFlag = false;
674
+ let sinceFlag;
675
+ let baseUrlFlag;
676
+ let slug;
677
+ for (let i = 0; i < args.length; i += 1) {
678
+ const arg = args[i];
679
+ if (arg === "--help" || arg === "-h") {
680
+ writeOut(stdout, DOCS_HELP);
681
+ return 0;
682
+ }
683
+ if (arg === "--json") {
684
+ jsonFlag = true;
685
+ continue;
686
+ }
687
+ if (arg === "--plain") {
688
+ continue;
689
+ }
690
+ if (arg === "--quick") {
691
+ quickFlag = true;
692
+ continue;
693
+ }
694
+ if (arg === "--changelog") {
695
+ changelogFlag = true;
696
+ continue;
697
+ }
698
+ if (arg === "--since" || arg.startsWith("--since=")) {
699
+ const parsed = readFlagValue(args, i, "--since", "Pass a date in YYYY-MM-DD format, for example --since 2026-01-01.");
700
+ if (!parsed.ok) {
701
+ writeShortcutError(stderr, jsonFlag, parsed);
702
+ return 1;
703
+ }
704
+ i = parsed.nextIndex;
705
+ sinceFlag = parsed.value;
706
+ continue;
707
+ }
708
+ if (arg === "--base-url" || arg.startsWith("--base-url=")) {
709
+ const parsed = readFlagValue(args, i, "--base-url", `Pass a URL, for example --base-url ${DEFAULT_BASE_URL}.`);
710
+ if (!parsed.ok) {
711
+ writeShortcutError(stderr, jsonFlag, parsed);
712
+ return 1;
713
+ }
714
+ i = parsed.nextIndex;
715
+ baseUrlFlag = parsed.value;
716
+ continue;
717
+ }
718
+ if (arg.startsWith("-")) {
719
+ writeShortcutError(stderr, jsonFlag, {
720
+ code: "UNKNOWN_FLAG",
721
+ error: `Unknown flag "${arg}" for pcific docs.`,
722
+ tryThis: "Run pcific docs --help to see supported options.",
723
+ });
724
+ return 1;
725
+ }
726
+ if (!slug) {
727
+ slug = arg.trim();
728
+ }
729
+ }
730
+ const mergedEnv = readMergedEnv(cwd, options.env);
731
+ const baseUrl = resolveValidatedBaseUrl(baseUrlFlag ?? options.baseUrl ?? mergedEnv.get("PCIFIC_BASE_URL") ?? DEFAULT_BASE_URL, stderr, jsonFlag);
732
+ if (!baseUrl) {
733
+ return 1;
734
+ }
735
+ let docPath;
736
+ let query = [];
737
+ if (changelogFlag || slug === "changelog") {
738
+ docPath = "/changelog.txt";
739
+ query = buildUniqueQuery([["since", sinceFlag]]);
740
+ }
741
+ else if (slug) {
742
+ const cleanSlug = slug.replace(/^\/+|\/+$/g, "").replace(/\.txt$/, "");
743
+ docPath = quickFlag
744
+ ? `/docs/${encodeURIComponent(cleanSlug)}/quick.txt`
745
+ : `/docs/${encodeURIComponent(cleanSlug)}.txt`;
746
+ }
747
+ else {
748
+ docPath = "/llms.txt";
749
+ }
750
+ const url = `${baseUrl}${docPath}${buildQueryString(query)}`;
751
+ const fetchImpl = options.fetch ?? globalThis.fetch;
752
+ try {
753
+ const response = await fetchImpl(url, {
754
+ method: "GET",
755
+ headers: {
756
+ Accept: "text/plain",
757
+ "User-Agent": CLI_USER_AGENT,
758
+ },
759
+ });
760
+ const text = await response.text();
761
+ if (!response.ok) {
762
+ writeShortcutError(stderr, jsonFlag, {
763
+ status: response.status,
764
+ code: response.status === 404 ? "DOC_NOT_FOUND" : `HTTP_${response.status}`,
765
+ error: response.status === 404 && slug
766
+ ? `Documentation page "${slug}" was not found at ${url}.`
767
+ : `Failed to fetch documentation at ${url} (HTTP ${response.status}).`,
768
+ tryThis: response.status === 404
769
+ ? `Run \`pcific docs\` to see all available slugs, or try one of: ${COMMON_DOC_SLUGS.join(", ")}.`
770
+ : "Check the base URL and try again.",
771
+ });
772
+ return 1;
773
+ }
774
+ if (jsonFlag) {
775
+ const payload = {
776
+ url,
777
+ slug: slug ?? (changelogFlag ? "changelog" : "llms"),
778
+ quick: quickFlag,
779
+ changelog: changelogFlag || slug === "changelog",
780
+ content: text,
781
+ };
782
+ if (sinceFlag) {
783
+ payload.since = sinceFlag;
784
+ }
785
+ writeOut(stdout, JSON.stringify(payload));
786
+ return 0;
787
+ }
788
+ stdout.write(text.endsWith("\n") ? text : `${text}\n`);
789
+ return 0;
790
+ }
791
+ catch (err) {
792
+ writeShortcutError(stderr, jsonFlag, {
793
+ code: "NETWORK_ERROR",
794
+ error: `Failed to fetch docs from ${url}: ${err instanceof Error ? err.message : String(err)}`,
795
+ tryThis: `Check your internet connection and base URL (${baseUrl}), then retry.`,
796
+ });
797
+ return 1;
798
+ }
799
+ }