@artis-lab/cli 0.11.0 → 0.13.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.
@@ -1,1411 +0,0 @@
1
- import {
2
- VerifyUnavailableError,
3
- formatVerifyReport,
4
- verifyHtml
5
- } from "./chunk-IKP5TJZP.js";
6
- import {
7
- artisCliVersion
8
- } from "./chunk-IZYFOV2K.js";
9
- import {
10
- CliError,
11
- exitCodeForResponse,
12
- exitCodes,
13
- usageError
14
- } from "./chunk-WQDTNA6L.js";
15
- import {
16
- getRememberedBase,
17
- rememberBase
18
- } from "./chunk-Q4UVVKZI.js";
19
- import {
20
- ARTIS_DEFAULT_HOST,
21
- findProfileForHost,
22
- getConfigPath,
23
- normalizeHost,
24
- readCliConfig,
25
- saveDefaultProfile
26
- } from "./chunk-QNS7GLAA.js";
27
- import {
28
- installSkillFromCli
29
- } from "./chunk-MX2ASLZR.js";
30
- import {
31
- collectFlagValues,
32
- hasFlag,
33
- parseFlagValue
34
- } from "./chunk-U3ZF6SRR.js";
35
-
36
- // packages/cli/src/lib/cli.ts
37
- import { spawn } from "node:child_process";
38
- import { readFile, writeFile } from "node:fs/promises";
39
- import { basename, extname } from "node:path";
40
-
41
- // packages/api-contract/src/client.ts
42
- var htmlUploadContentType = "text/html; charset=utf-8";
43
- var ApiError = class extends Error {
44
- constructor(status, code, message, body, headers) {
45
- super(message);
46
- this.status = status;
47
- this.code = code;
48
- this.body = body;
49
- this.name = "ApiError";
50
- const retryAfter = Number(headers?.get("retry-after"));
51
- this.retryAfter = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : void 0;
52
- }
53
- };
54
- function appendQuery(query, name, value) {
55
- if (value === void 0 || value === null) {
56
- return;
57
- }
58
- if (Array.isArray(value)) {
59
- for (const item of value) appendQuery(query, name, item);
60
- return;
61
- }
62
- query.append(
63
- name,
64
- typeof value === "object" ? JSON.stringify(value) : String(value)
65
- );
66
- }
67
- function buildRequest(baseUrl, key, input = {}) {
68
- const space = key.indexOf(" ");
69
- const method = key.slice(0, space);
70
- const path = key.slice(space + 1).replace(/\{([^}]+)\}/g, (_, name) => {
71
- const value = input.params?.[name];
72
- if (value === void 0) {
73
- throw new Error(`${key}: missing path parameter ${name}`);
74
- }
75
- return encodeURIComponent(value);
76
- });
77
- const query = new URLSearchParams();
78
- for (const [name, value] of Object.entries(input.query ?? {})) {
79
- appendQuery(query, name, value);
80
- }
81
- const search = query.toString();
82
- const headers = {};
83
- let body;
84
- if (typeof input.body === "string" || input.body instanceof Uint8Array) {
85
- const bytes = typeof input.body === "string" ? new TextEncoder().encode(input.body) : input.body;
86
- headers["content-type"] = htmlUploadContentType;
87
- headers["content-length"] = String(bytes.byteLength);
88
- body = bytes;
89
- } else if (input.body !== void 0) {
90
- headers["content-type"] = "application/json";
91
- body = JSON.stringify(input.body);
92
- }
93
- return {
94
- url: `${baseUrl.replace(/\/+$/, "")}${path}${search ? `?${search}` : ""}`,
95
- init: {
96
- method,
97
- headers: { ...headers, ...input.headers },
98
- ...body === void 0 ? {} : { body }
99
- }
100
- };
101
- }
102
- async function readBody(response) {
103
- const text = await response.text();
104
- if (!text) {
105
- return void 0;
106
- }
107
- const type = response.headers.get("content-type") ?? "";
108
- if (!/json/i.test(type)) {
109
- return text;
110
- }
111
- try {
112
- return JSON.parse(text);
113
- } catch {
114
- return text;
115
- }
116
- }
117
- function errorOf(response, body) {
118
- const record = body && typeof body === "object" && !Array.isArray(body) ? body : void 0;
119
- const message = typeof record?.["error"] === "string" ? record["error"] : `Request failed with ${response.status}.`;
120
- const code = typeof record?.["code"] === "string" ? record["code"] : "http_error";
121
- return new ApiError(response.status, code, message, record, response.headers);
122
- }
123
- function createApiClient(options) {
124
- const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
125
- async function send(key, input = {}) {
126
- const { url, init } = buildRequest(
127
- options.baseUrl,
128
- key,
129
- input
130
- );
131
- const headers = init.headers;
132
- if (options.auth && options.auth !== "cookie") {
133
- headers["authorization"] = `Bearer ${options.auth.bearer}`;
134
- }
135
- const response = await fetchImpl(url, {
136
- ...init,
137
- ...options.auth === "cookie" ? { credentials: "include" } : {},
138
- ...input["signal"] ? { signal: input["signal"] } : {}
139
- });
140
- const body = await readBody(response);
141
- if (!response.ok) {
142
- throw errorOf(response, body);
143
- }
144
- return { status: response.status, body, headers: response.headers };
145
- }
146
- return {
147
- send,
148
- call: (async (key, input) => (await send(key, input)).body),
149
- withAuth: (auth) => createApiClient({ ...options, auth })
150
- };
151
- }
152
-
153
- // packages/sdk/src/lib/annotation.ts
154
- function annotationIdFromIri(iri) {
155
- return iri.replace(/\/+$/, "").split("/").pop() ?? iri;
156
- }
157
-
158
- // packages/sdk/src/lib/sdk.ts
159
- var artifactShareRoles = [
160
- "viewer",
161
- "commenter",
162
- "contributor",
163
- "editor"
164
- ];
165
- var artifactListLimits = { default: 50, max: 100 };
166
- var artifactKinds = [
167
- "incident-timeline",
168
- "migration-plan",
169
- "generated-dashboard",
170
- "architecture-explainer",
171
- "animated-report",
172
- "ui-prototype",
173
- "pr-review",
174
- "custom-html"
175
- ];
176
- function formatRevisionConflictMessage(message, details) {
177
- if (!details?.currentRevisionId) {
178
- return message;
179
- }
180
- let text = `${message} Current revision: ${details.currentRevisionId}.`;
181
- if (typeof details.currentVersion === "number") {
182
- const [firstLine] = revisionSummaryLines(details.currentSummary ?? "");
183
- text += firstLine ? ` Version ${details.currentVersion}: ${firstLine}` : ` Version ${details.currentVersion}.`;
184
- }
185
- return text;
186
- }
187
- function revisionSummaryLines(summary) {
188
- return summary.split(/\r?\n/).map((line) => line.replace(/^\s*(?:[-*•]\s+)?/, "").trim()).filter(Boolean);
189
- }
190
-
191
- // packages/sdk/src/lib/guidelines.ts
192
- var cliNpmPackage = "@artis-lab/cli";
193
- var cliInstallCommand = `npm install -g ${cliNpmPackage}`;
194
-
195
- // packages/cli/src/lib/cli.ts
196
- function isRootAnnotation(annotation) {
197
- return annotation.motivation === "commenting";
198
- }
199
- async function readHtmlUpload(filePath, what) {
200
- const bytes = await readFile(filePath);
201
- if (!/<html/i.test(bytes.toString("latin1"))) {
202
- throw new Error(`${what} must be self-contained HTML including <html>.`);
203
- }
204
- return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
205
- }
206
- var commands = [
207
- "annotate",
208
- "annotation",
209
- "artifact",
210
- "guidelines",
211
- "help",
212
- "install-skill",
213
- "login",
214
- "publish",
215
- "reply",
216
- "revise",
217
- "share",
218
- "version",
219
- "watch",
220
- "whoami"
221
- ];
222
- var cliVisibilityOptions = ["public", "unlisted", "private"];
223
- var cliAnnotationStatusOptions = [
224
- "open",
225
- "needs-revision",
226
- "resolved"
227
- ];
228
- var valueFlags = /* @__PURE__ */ new Set([
229
- "--api-key",
230
- "--author",
231
- "--comment",
232
- "--css",
233
- "--cursor",
234
- "--description",
235
- "--dir",
236
- "--email",
237
- "--harness",
238
- "--host",
239
- "--kind",
240
- "--limit",
241
- "--output",
242
- "--pin-label",
243
- "--quote",
244
- "--quote-prefix",
245
- "--quote-suffix",
246
- "--query",
247
- "--rect",
248
- "--requested-change",
249
- "--resolve",
250
- "--revision",
251
- "--role",
252
- "--since",
253
- "--status",
254
- "--base",
255
- "--capabilities",
256
- "--contract",
257
- "--summary",
258
- "--tag",
259
- "--text-end",
260
- "--text-start",
261
- "--timeout",
262
- "--title",
263
- "--types",
264
- "--url",
265
- "--visibility"
266
- ]);
267
- function getPositionals(args) {
268
- const positionals = [];
269
- for (let index = 0; index < args.length; index += 1) {
270
- const arg = args[index];
271
- if (arg.startsWith("-")) {
272
- if (valueFlags.has(arg)) {
273
- index += 1;
274
- }
275
- continue;
276
- }
277
- positionals.push(arg);
278
- }
279
- return positionals;
280
- }
281
- function inferTitleFromPath(filePath) {
282
- const fileName = basename(filePath);
283
- const extension = extname(fileName);
284
- return extension ? fileName.slice(0, -extension.length) : fileName;
285
- }
286
- function parseVisibility(value) {
287
- if (cliVisibilityOptions.includes(value)) {
288
- return value;
289
- }
290
- throw usageError(
291
- `Invalid visibility "${value}". Expected one of: ${cliVisibilityOptions.join(", ")}`
292
- );
293
- }
294
- async function parseCapabilitiesFlag(value) {
295
- if (value === void 0) {
296
- return void 0;
297
- }
298
- let source = value;
299
- if (!value.trim().startsWith("{")) {
300
- try {
301
- source = await readFile(value, "utf8");
302
- } catch {
303
- throw usageError(
304
- `--capabilities must be a JSON object or a path to a JSON file; could not read "${value}".`
305
- );
306
- }
307
- }
308
- let parsed;
309
- try {
310
- parsed = JSON.parse(source);
311
- } catch {
312
- throw usageError("--capabilities is not valid JSON.");
313
- }
314
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
315
- throw usageError(
316
- `--capabilities must be a JSON object, e.g. '{"<name>":true}' ({} clears them on revise).`
317
- );
318
- }
319
- return parsed;
320
- }
321
- function parseContractFlag(value) {
322
- if (value === void 0) {
323
- return void 0;
324
- }
325
- if (value === "latest") {
326
- return value;
327
- }
328
- if (/^\d+$/.test(value)) {
329
- return Number(value);
330
- }
331
- throw usageError(
332
- `Invalid --contract "${value}". Expected a version number or latest.`
333
- );
334
- }
335
- function parseKind(value) {
336
- if (artifactKinds.includes(value)) {
337
- return value;
338
- }
339
- throw usageError(
340
- `Invalid kind "${value}". Expected one of: ${artifactKinds.join(", ")}`
341
- );
342
- }
343
- function parseAnnotationStatus(value) {
344
- if (cliAnnotationStatusOptions.includes(value)) {
345
- return value;
346
- }
347
- throw usageError(
348
- `Invalid status "${value}". Expected one of: ${cliAnnotationStatusOptions.join(", ")}`
349
- );
350
- }
351
- function parseShareRole(value) {
352
- if (artifactShareRoles.includes(value)) {
353
- return value;
354
- }
355
- throw usageError(
356
- `Invalid role "${value}". Expected one of: ${artifactShareRoles.join(", ")}`
357
- );
358
- }
359
- function parseRectSelector(value) {
360
- if (!value) {
361
- return void 0;
362
- }
363
- const parts = value.split(",").map((part) => Number(part.trim()));
364
- if (parts.length !== 2 && parts.length !== 4 || parts.some((part) => !Number.isFinite(part))) {
365
- throw usageError(
366
- `Invalid --rect "${value}". Expected "x,y" or "x,y,w,h" percentages.`
367
- );
368
- }
369
- const [x, y, width = 0, height = 0] = parts;
370
- return {
371
- type: "FragmentSelector",
372
- conformsTo: "http://www.w3.org/TR/media-frags/",
373
- value: `xywh=percent:${x},${y},${width},${height}`
374
- };
375
- }
376
- function buildAnnotationSelectors(args) {
377
- const selectors = [];
378
- const quote = parseFlagValue(args, "--quote");
379
- if (quote) {
380
- const textQuote = {
381
- type: "TextQuoteSelector",
382
- exact: quote
383
- };
384
- const prefix = parseFlagValue(args, "--quote-prefix");
385
- const suffix = parseFlagValue(args, "--quote-suffix");
386
- if (prefix) {
387
- textQuote.prefix = prefix;
388
- }
389
- if (suffix) {
390
- textQuote.suffix = suffix;
391
- }
392
- selectors.push(textQuote);
393
- }
394
- const textStart = parseFlagValue(args, "--text-start");
395
- const textEnd = parseFlagValue(args, "--text-end");
396
- if (textStart !== void 0 && textEnd !== void 0) {
397
- const start = Number(textStart);
398
- const end = Number(textEnd);
399
- if (!Number.isFinite(start) || !Number.isFinite(end)) {
400
- throw usageError("--text-start and --text-end must be numbers.");
401
- }
402
- selectors.push({ type: "TextPositionSelector", start, end });
403
- }
404
- const css = parseFlagValue(args, "--css");
405
- if (css) {
406
- selectors.push({ type: "CssSelector", value: css });
407
- }
408
- const rect = parseRectSelector(parseFlagValue(args, "--rect"));
409
- if (rect) {
410
- selectors.push(rect);
411
- }
412
- return selectors;
413
- }
414
- function resolveBaseUrl(args, config) {
415
- const host = parseFlagValue(args, "--host") || parseFlagValue(args, "--url") || process.env["ARTIS_URL"] || config?.defaultHost || ARTIS_DEFAULT_HOST;
416
- return normalizeHost(host);
417
- }
418
- function resolveApiKey(args, config, baseUrl) {
419
- const flagApiKey = parseFlagValue(args, "--api-key");
420
- if (flagApiKey) {
421
- return { apiKey: flagApiKey, apiKeySource: "flag" };
422
- }
423
- if (process.env["ARTIS_API_KEY"]) {
424
- return { apiKey: process.env["ARTIS_API_KEY"], apiKeySource: "env" };
425
- }
426
- const profileApiKey = findProfileForHost(config, baseUrl)?.apiKey;
427
- if (profileApiKey) {
428
- return { apiKey: profileApiKey, apiKeySource: "config" };
429
- }
430
- return {};
431
- }
432
- async function resolveCredentials(args) {
433
- const config = await readCliConfig();
434
- const baseUrl = resolveBaseUrl(args, config);
435
- const { apiKey } = resolveApiKey(args, config, baseUrl);
436
- if (!apiKey) {
437
- throw new CliError(
438
- `Missing API key. Run "artis login --host ${baseUrl}" or set ARTIS_API_KEY.`,
439
- exitCodes.auth
440
- );
441
- }
442
- return { apiKey, baseUrl };
443
- }
444
- async function resolveOptionalTarget(args) {
445
- const config = await readCliConfig();
446
- const baseUrl = resolveBaseUrl(args, config);
447
- const { apiKey, apiKeySource } = resolveApiKey(args, config, baseUrl);
448
- return { apiKey, apiKeySource, baseUrl };
449
- }
450
- async function guidelinesFromCli(args) {
451
- const [section] = getPositionals(args);
452
- const contract = parseContractFlag(parseFlagValue(args, "--contract"));
453
- const config = await readCliConfig();
454
- const baseUrl = resolveBaseUrl(args, config);
455
- const query = new URLSearchParams({ section: section ?? "index" });
456
- if (contract !== void 0) {
457
- query.set("contract", String(contract));
458
- }
459
- const response = await fetch(`${baseUrl}/skills.md?${query.toString()}`);
460
- const text = await response.text();
461
- if (!response.ok) {
462
- throw new CliError(
463
- text.trim() || `Guidelines request failed with ${response.status}.`,
464
- exitCodeForResponse(response.status)
465
- );
466
- }
467
- process.stdout.write(text.endsWith("\n") ? text : `${text}
468
- `);
469
- }
470
- async function parsePublishOptions(args) {
471
- const [filePath] = getPositionals(args);
472
- if (!filePath) {
473
- throw usageError("Missing artifact HTML file path.");
474
- }
475
- const credentials = await resolveCredentials(args);
476
- const visibility = parseVisibility(
477
- parseFlagValue(args, "--visibility") ?? "unlisted"
478
- );
479
- return {
480
- filePath,
481
- apiKey: credentials.apiKey,
482
- baseUrl: credentials.baseUrl,
483
- title: parseFlagValue(args, "--title"),
484
- description: parseFlagValue(args, "--description") ?? "Published from Artis CLI.",
485
- visibility,
486
- authorName: parseFlagValue(args, "--author") ?? "Artis CLI",
487
- kind: parseKind(parseFlagValue(args, "--kind") ?? "custom-html"),
488
- capabilities: await parseCapabilitiesFlag(
489
- parseFlagValue(args, "--capabilities")
490
- ),
491
- contract: parseContractFlag(parseFlagValue(args, "--contract")),
492
- json: hasFlag(args, "--json")
493
- };
494
- }
495
- function cliErrorOf(error) {
496
- if (!(error instanceof ApiError)) {
497
- return error;
498
- }
499
- let message = formatRevisionConflictMessage(error.message, error.body);
500
- if (error.status === 429 && error.retryAfter) {
501
- message += ` Retry after ${error.retryAfter} s.`;
502
- }
503
- return new CliError(message, exitCodeForResponse(error.status, error.code));
504
- }
505
- function apiClient(target) {
506
- return createApiClient({
507
- baseUrl: target.baseUrl,
508
- auth: target.apiKey ? { bearer: target.apiKey } : void 0
509
- });
510
- }
511
- async function apiCall(credentials, key, ...input) {
512
- try {
513
- return await apiClient(credentials).call(key, ...input);
514
- } catch (error) {
515
- throw cliErrorOf(error);
516
- }
517
- }
518
- async function apiCallOptional(target, key, ...input) {
519
- try {
520
- return await apiClient(target).call(key, ...input);
521
- } catch (error) {
522
- if (!(error instanceof ApiError) || error.status !== 401 || !target.apiKey || target.apiKeySource !== "config") {
523
- throw cliErrorOf(error);
524
- }
525
- }
526
- try {
527
- const result = await apiClient({ baseUrl: target.baseUrl }).call(
528
- key,
529
- ...input
530
- );
531
- console.warn(
532
- `Saved API key was rejected by ${target.baseUrl}; retried without credentials. Run "artis login --host ${target.baseUrl}" to refresh local credentials.`
533
- );
534
- return result;
535
- } catch (error) {
536
- throw cliErrorOf(error);
537
- }
538
- }
539
- function assertSafeLoginUrl(url, baseUrl) {
540
- let parsed;
541
- try {
542
- parsed = new URL(url);
543
- } catch {
544
- throw new Error("Login host returned an invalid verification URL.");
545
- }
546
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
547
- throw new Error("Login host returned an unsafe verification URL scheme.");
548
- }
549
- let expected;
550
- try {
551
- expected = new URL(baseUrl);
552
- } catch {
553
- throw new Error("Configured login host is not a valid URL.");
554
- }
555
- if (parsed.hostname !== expected.hostname || parsed.port !== expected.port) {
556
- throw new Error(
557
- "Login host returned a verification URL that does not match the configured host."
558
- );
559
- }
560
- }
561
- function openBrowser(url) {
562
- let protocol;
563
- try {
564
- protocol = new URL(url).protocol;
565
- } catch {
566
- throw new Error("Refusing to open an invalid URL in the browser.");
567
- }
568
- if (protocol !== "http:" && protocol !== "https:") {
569
- throw new Error("Refusing to open a non-http(s) URL in the browser.");
570
- }
571
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
572
- const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
573
- const child = spawn(command, args, {
574
- detached: true,
575
- stdio: "ignore"
576
- });
577
- child.unref();
578
- }
579
- function sleep(ms) {
580
- return new Promise((resolve) => setTimeout(resolve, ms));
581
- }
582
- function buildArtifactUrl(baseUrl, pathOrUrl) {
583
- return pathOrUrl.startsWith("http") ? pathOrUrl : `${baseUrl}${pathOrUrl}`;
584
- }
585
- function getCliHelp() {
586
- return `artis
587
-
588
- Host, share, and collaborate on AI-generated HTML artifacts.
589
-
590
- Usage:
591
- artis --version
592
- artis login [--host <url>]
593
- artis whoami [--host <url>]
594
- artis guidelines [section] [--contract <n|latest>] [--host <url>]
595
- artis install-skill [--harness <id>]... [--yes] [--dir <path>] [--force] [--list] [--json]
596
- artis publish artifact.html [options]
597
- artis artifact get <artifact-id-or-slug> [--json]
598
- artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>] [--json]
599
- artis artifact feedback <artifact-id-or-slug> [--json] [--revision <revision-id>]
600
- artis artifact list [--query <text>] [--kind <value>] [--tag <tag>] [--limit <n>] [--cursor <cursor>] [--json]
601
- artis artifact visibility <artifact-id-or-slug> <public|unlisted|private> [--json]
602
- artis artifact delete <artifact-id-or-slug> --yes
603
- artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]
604
- artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter|contributor|editor>] [--remove]
605
- artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>] [--resolve <annotation-id>] [--capabilities <json|file>] [--contract <n|latest>]
606
- artis annotate <artifact-id-or-slug> --comment <text> [anchor options]
607
- artis reply <annotation-id> --comment <text>
608
- artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]
609
- artis annotation retract <annotation-id>
610
- artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self] [--types <families>]
611
-
612
- Options:
613
- --api-key <key> API key. Defaults to ARTIS_API_KEY or ~/.artis/config.json. Run "artis login" to obtain one.
614
- --host, --url <url> Artis server URL. Falls back to ARTIS_URL, then a saved login, then https://artis.xiispace.eu.org.
615
- --title <title> Artifact title. Defaults to the file name.
616
- --description <text> Artifact description.
617
- --visibility <value> public, unlisted, or private. Defaults to unlisted.
618
- --kind <value> Artifact kind. Defaults to custom-html.
619
- --author <name> Artifact author/agent name. Defaults to Artis CLI.
620
- --summary <text> Revision summary. Write one change per line; they render as a list.
621
- --base <revision-id> Revision the file was edited from. Defaults to the revision this machine last published, read (artifact html), or revised. Refuses the revise if someone revised since.
622
- --resolve <annotation-id> Mark an annotation resolved when revising. Repeatable.
623
- --capabilities <json|file> Page capabilities as a JSON object or JSON file (publish, revise). Revise keeps the previous set without it; '{}' clears it.
624
- --contract <n|latest> Page contract version (publish, revise, guidelines). Publish defaults to latest; revise keeps the pinned version.
625
- --comment <text> Annotation or reply comment text (annotate, reply).
626
- --requested-change <text> Structured change request for the artifact author (annotate).
627
- --status <value> Annotation status: open, needs-revision, or resolved. Defaults to open.
628
- --quote <text> Exact artifact text to anchor to (annotate, TextQuoteSelector).
629
- --quote-prefix <text> Text just before --quote, to disambiguate repeats.
630
- --quote-suffix <text> Text just after --quote, to disambiguate repeats.
631
- --css <selector> CSS selector to anchor to (annotate, CssSelector).
632
- --text-start <n> Document offset where the quote starts (annotate, TextPositionSelector).
633
- --text-end <n> Document offset where the quote ends (annotate, TextPositionSelector).
634
- --rect <x,y,w,h> Canvas point/rect as percentages (annotate, FragmentSelector). w,h default to 0.
635
- --pin-label <text> Short label shown on the artifact canvas pin (annotate).
636
- --output <path> Write the artifact HTML to this file (artifact html). Without it, the document goes to stdout.
637
- --revision <revision-id> Revision to read (artifact html, artifact feedback). Defaults to the current revision.
638
- --query <text> Text to find in your artifacts' titles and descriptions (artifact list).
639
- --tag <tag> Only your artifacts carrying this tag (artifact list). --kind filters by kind.
640
- --limit <n> Artifacts per page, 1-100 (artifact list). Defaults to 50.
641
- --cursor <cursor> Continue after the page that printed it (artifact list).
642
- --email <email> Email address for artis share.
643
- --role <role> Share role: viewer, commenter, contributor or editor. Defaults to viewer.
644
- --remove Remove the email from an artifact share list.
645
- --harness <id> Agent harness to install the artis skill into (install-skill). Repeatable: claude-code, cursor, codex, openclaw, pi, hermes.
646
- --yes Install the skill into every detected harness (install-skill); confirm a delete (artifact delete).
647
- --dir <path> Install the skill into a custom skills directory (install-skill).
648
- --force Overwrite an already-installed skill (install-skill).
649
- --list List harnesses, detection, and install paths (install-skill).
650
- --since <cursor> Feedback cursor to watch from (watch). Defaults to now; 0 replays every event.
651
- --once Exit after the first batch of events, printed as {events, cursor} (watch).
652
- --timeout <duration> Give up after this long, e.g. 30s, 10m (watch). Exits 6 if nothing happened.
653
- --include-self Also report events caused by this API key (watch).
654
- --types <families> Only these event families, comma-separated: annotation, revision (watch). Defaults to all.
655
- --json Print machine-readable JSON for supported commands.
656
-
657
- Exit codes:
658
- 0 success, 1 error, 2 usage, 3 auth, 4 not found, 5 revision conflict, 6 watch timeout, 7 rate limited, 8 verify found problems.
659
-
660
- Examples (--host is optional; without it commands target https://artis.xiispace.eu.org):
661
- artis publish report.html
662
- artis login
663
- artis publish report.html --host https://artis.example.com --visibility private
664
- artis share artifact-slug --host https://artis.example.com --email reviewer@example.com --role commenter
665
- artis artifact get artifact-slug --host https://artis.example.com --json
666
- artis artifact html artifact-slug --output report.html
667
- artis verify report.html
668
- artis artifact feedback artifact-slug --host https://artis.example.com --json
669
- artis annotate artifact-slug --host https://artis.example.com --comment "Tighten this heading" --quote "Checkout latency" --requested-change "Add the affected checkout count"
670
- artis reply annotation-123 --host https://artis.example.com --comment "Addressed in the latest revision"
671
- artis annotation edit annotation-123 --host https://artis.example.com --comment "Corrected: the latency spike is on checkout, not search"
672
- artis annotation retract annotation-123 --host https://artis.example.com
673
- artis watch artifact-slug --since 42
674
- artis guidelines authoring
675
- artis install-skill --yes
676
- artis revise artifact-slug report.html --host https://artis.example.com --summary "Addressed open feedback" --base revision-abc --resolve annotation-123`;
677
- }
678
- async function publishArtifactFromCli(args) {
679
- const options = await parsePublishOptions(args);
680
- const html = await readHtmlUpload(options.filePath, "Artifact file");
681
- const title = options.title ?? inferTitleFromPath(options.filePath);
682
- const { result } = await apiCall(
683
- { apiKey: options.apiKey, baseUrl: options.baseUrl },
684
- "POST /api/artifacts",
685
- {
686
- query: {
687
- title,
688
- description: options.description,
689
- visibility: options.visibility,
690
- authorName: options.authorName,
691
- source: "cli",
692
- kind: options.kind,
693
- capabilities: options.capabilities,
694
- contract: options.contract
695
- },
696
- body: html
697
- }
698
- );
699
- await rememberBase(
700
- options.baseUrl,
701
- [result.artifactId, result.slug],
702
- result.revisionId
703
- );
704
- return {
705
- artifactId: result.artifactId,
706
- revisionId: result.revisionId,
707
- title,
708
- url: buildArtifactUrl(options.baseUrl, result.url),
709
- visibility: options.visibility
710
- };
711
- }
712
- async function loginFromCli(args) {
713
- const config = await readCliConfig();
714
- const baseUrl = resolveBaseUrl(args, config);
715
- const api = apiClient({ baseUrl });
716
- let login;
717
- try {
718
- login = await api.call("POST /api/cli/auth/start");
719
- } catch (error) {
720
- throw cliErrorOf(error);
721
- }
722
- assertSafeLoginUrl(login.verificationUrl, baseUrl);
723
- console.log(`Opening ${login.verificationUrl}`);
724
- console.log(`Code: ${login.userCode}`);
725
- try {
726
- openBrowser(login.verificationUrl);
727
- } catch {
728
- console.log("Could not open a browser automatically.");
729
- }
730
- const intervalMs = login.intervalSeconds * 1e3;
731
- while (Date.now() < Date.parse(login.expiresAt)) {
732
- await sleep(intervalMs);
733
- let poll;
734
- try {
735
- poll = await api.call("POST /api/cli/auth/poll", {
736
- body: { deviceCode: login.deviceCode }
737
- });
738
- } catch (error) {
739
- if (error instanceof ApiError && error.status === 429) {
740
- await sleep((error.retryAfter ?? 10) * 1e3);
741
- continue;
742
- }
743
- throw cliErrorOf(error);
744
- }
745
- if (poll.status === "pending") {
746
- continue;
747
- }
748
- await saveDefaultProfile({ apiKey: poll.token, host: baseUrl });
749
- console.log(`Saved artis credentials to ${getConfigPath()}`);
750
- return;
751
- }
752
- throw new Error("Login expired. Run artis login again.");
753
- }
754
- async function whoamiFromCli(args) {
755
- const credentials = await resolveCredentials(args);
756
- const result = await apiCall(credentials, "GET /api/me");
757
- console.log(
758
- `Signed in to ${credentials.baseUrl} as ${result.principal.name ?? result.principal.userId}`
759
- );
760
- console.log(`Principal: ${result.principal.kind}`);
761
- }
762
- async function getArtifactFromCli(args) {
763
- const [artifactId] = getPositionals(args);
764
- if (!artifactId) {
765
- throw usageError("Missing artifact id or slug.");
766
- }
767
- const target = await resolveOptionalTarget(args);
768
- const result = await apiCallOptional(
769
- target,
770
- "GET /api/artifacts/{artifactId}",
771
- { params: { artifactId } }
772
- );
773
- if (hasFlag(args, "--json")) {
774
- console.log(JSON.stringify(result, null, 2));
775
- return;
776
- }
777
- console.log(`${result.artifact.metadata.title}`);
778
- console.log(`Artifact: ${result.artifact.id}`);
779
- console.log(`Revision: ${result.artifact.currentRevisionId}`);
780
- console.log(
781
- `Open annotations: ${result.annotations.filter((annotation) => isRootAnnotation(annotation) && annotation["artis:status"] !== "resolved").length}`
782
- );
783
- }
784
- async function getArtifactHtmlFromCli(args) {
785
- const [artifactId] = getPositionals(args);
786
- if (!artifactId) {
787
- throw usageError(
788
- "Usage: artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>]"
789
- );
790
- }
791
- const target = await resolveOptionalTarget(args);
792
- const result = await apiCallOptional(
793
- target,
794
- "GET /api/artifacts/{artifactId}/html",
795
- {
796
- params: { artifactId },
797
- query: { revisionId: parseFlagValue(args, "--revision") }
798
- }
799
- );
800
- if (typeof result.html !== "string") {
801
- throw new Error("Artifact response did not include revision HTML.");
802
- }
803
- await rememberBase(
804
- target.baseUrl,
805
- [artifactId, result.artifactId],
806
- result.revisionId
807
- );
808
- if (result.isLatest === false) {
809
- console.error(
810
- `Note: version ${result.version} is not the latest. The latest is version ${result.latestVersion} (revision ${result.latestRevisionId}); a revise based on this one will be refused.`
811
- );
812
- }
813
- if (hasFlag(args, "--json")) {
814
- console.log(JSON.stringify(result, null, 2));
815
- return;
816
- }
817
- const outputPath = parseFlagValue(args, "--output");
818
- if (!outputPath) {
819
- process.stdout.write(result.html);
820
- return;
821
- }
822
- await writeFile(outputPath, result.html, "utf8");
823
- console.log(`Wrote ${outputPath}`);
824
- console.log(`Revision: ${result.revisionId}`);
825
- console.log(`Version: ${result.version}`);
826
- }
827
- async function verifyFromCli(args) {
828
- const [target] = getPositionals(args);
829
- if (!target) {
830
- throw usageError(
831
- "Usage: artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]"
832
- );
833
- }
834
- let html;
835
- let label;
836
- const looksLikePath = /[\\/]/.test(target) || /\.html?$/i.test(target);
837
- const local = await readFile(target, "utf8").catch(
838
- (error) => error
839
- );
840
- if (typeof local === "string" || looksLikePath) {
841
- if (typeof local !== "string") {
842
- throw local.code === "ENOENT" ? new CliError(`File not found: ${target}`, exitCodes.notFound) : usageError(`Cannot read ${target}: ${local.message}`);
843
- }
844
- if (parseFlagValue(args, "--revision")) {
845
- throw usageError(
846
- "--revision applies to a published artifact, not a local file."
847
- );
848
- }
849
- html = local;
850
- label = target;
851
- } else {
852
- const remote = await resolveOptionalTarget(args);
853
- const result = await apiCallOptional(
854
- remote,
855
- "GET /api/artifacts/{artifactId}/html",
856
- {
857
- params: { artifactId: target },
858
- query: { revisionId: parseFlagValue(args, "--revision") }
859
- }
860
- );
861
- html = result.html;
862
- label = `${target} v${result.version}`;
863
- }
864
- let report;
865
- try {
866
- report = await verifyHtml(html);
867
- } catch (error) {
868
- if (error instanceof VerifyUnavailableError) {
869
- throw new CliError(error.message, exitCodes.error);
870
- }
871
- throw error;
872
- }
873
- if (hasFlag(args, "--json")) {
874
- console.log(JSON.stringify(report, null, 2));
875
- } else {
876
- console.log(`Verified ${label}`);
877
- for (const line of formatVerifyReport(report)) {
878
- console.log(line);
879
- }
880
- }
881
- if (!report.ok) {
882
- throw new CliError("", exitCodes.verifyFailed);
883
- }
884
- }
885
- async function listArtifactsFromCli(args) {
886
- const credentials = await resolveCredentials(args);
887
- const query = parseFlagValue(args, "--query");
888
- const kind = parseFlagValue(args, "--kind");
889
- const tag = parseFlagValue(args, "--tag");
890
- const limit = parseFlagValue(args, "--limit");
891
- const cursor = parseFlagValue(args, "--cursor");
892
- if (limit !== void 0 && (!/^\d+$/.test(limit) || Number(limit) < 1 || Number(limit) > artifactListLimits.max)) {
893
- throw usageError(
894
- `Invalid --limit "${limit}". Pass a whole number from 1 to ${artifactListLimits.max}.`
895
- );
896
- }
897
- const result = await apiCall(credentials, "GET /api/artifacts", {
898
- query: {
899
- owner: "me",
900
- q: query || void 0,
901
- kind: kind ? parseKind(kind) : void 0,
902
- tag: tag || void 0,
903
- limit: limit ? Number(limit) : void 0,
904
- cursor: cursor || void 0
905
- }
906
- });
907
- if (hasFlag(args, "--json")) {
908
- console.log(JSON.stringify(result, null, 2));
909
- return;
910
- }
911
- const { artifacts } = result;
912
- if (!artifacts.length) {
913
- console.log(
914
- cursor ? "No more artifacts." : query || kind || tag ? "No artifacts match." : "You have no artifacts yet."
915
- );
916
- return;
917
- }
918
- for (const artifact of artifacts) {
919
- const tags = artifact.metadata.tags?.length ? ` #${artifact.metadata.tags.join(" #")}` : "";
920
- console.log(
921
- `${artifact.slug} ${artifact.metadata.visibility} ${artifact.metadata.kind} ${artifact.metadata.title}${tags}`
922
- );
923
- }
924
- if (result.nextCursor) {
925
- console.log(
926
- `More artifacts: rerun with --cursor ${result.nextCursor} (same filters).`
927
- );
928
- }
929
- }
930
- async function getArtifactFeedbackFromCli(args) {
931
- const [artifactId] = getPositionals(args);
932
- if (!artifactId) {
933
- throw usageError("Missing artifact id or slug.");
934
- }
935
- const target = await resolveOptionalTarget(args);
936
- const result = await apiCallOptional(
937
- target,
938
- "GET /api/artifacts/{artifactId}/feedback",
939
- {
940
- params: { artifactId },
941
- query: { revisionId: parseFlagValue(args, "--revision") }
942
- }
943
- );
944
- if (hasFlag(args, "--json")) {
945
- console.log(JSON.stringify(result, null, 2));
946
- return;
947
- }
948
- console.log(result.prompt);
949
- console.log(
950
- `
951
- Feedback cursor: ${result.cursor} (artis watch ${artifactId} --since ${result.cursor})`
952
- );
953
- }
954
- async function shareArtifactFromCli(args) {
955
- const [artifactId] = getPositionals(args);
956
- if (!artifactId) {
957
- throw usageError(
958
- "Usage: artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter|contributor|editor>] [--remove]"
959
- );
960
- }
961
- const email = parseFlagValue(args, "--email")?.trim().toLowerCase();
962
- const credentials = await resolveCredentials(args);
963
- if (!email) {
964
- const result2 = await apiCall(
965
- credentials,
966
- "GET /api/artifacts/{artifactId}/shares",
967
- { params: { artifactId } }
968
- );
969
- if (hasFlag(args, "--json")) {
970
- console.log(JSON.stringify(result2, null, 2));
971
- return;
972
- }
973
- const { shares } = result2;
974
- if (!shares.length) {
975
- console.log("No invited people yet.");
976
- return;
977
- }
978
- for (const share of shares) {
979
- console.log(`${share.email} ${share.role}`);
980
- }
981
- return;
982
- }
983
- if (hasFlag(args, "--remove")) {
984
- await apiCall(
985
- credentials,
986
- "DELETE /api/artifacts/{artifactId}/shares/{email}",
987
- { params: { artifactId, email } }
988
- );
989
- console.log(`Removed ${email}`);
990
- return;
991
- }
992
- const role = parseShareRole(parseFlagValue(args, "--role") ?? "viewer");
993
- const result = await apiCall(
994
- credentials,
995
- "POST /api/artifacts/{artifactId}/shares",
996
- { params: { artifactId }, body: { email, role } }
997
- );
998
- if (hasFlag(args, "--json")) {
999
- console.log(JSON.stringify(result, null, 2));
1000
- return;
1001
- }
1002
- console.log(`Shared with ${result.share.email} as ${result.share.role}`);
1003
- }
1004
- async function setArtifactVisibilityFromCli(args) {
1005
- const [artifactId, value] = getPositionals(args);
1006
- if (!artifactId || !value) {
1007
- throw usageError(
1008
- `Usage: artis artifact visibility <artifact-id-or-slug> <${cliVisibilityOptions.join("|")}>`
1009
- );
1010
- }
1011
- const visibility = parseVisibility(value);
1012
- const credentials = await resolveCredentials(args);
1013
- const result = await apiCall(
1014
- credentials,
1015
- "PATCH /api/artifacts/{artifactId}",
1016
- { params: { artifactId }, body: { visibility } }
1017
- );
1018
- if (hasFlag(args, "--json")) {
1019
- console.log(JSON.stringify(result, null, 2));
1020
- return;
1021
- }
1022
- console.log(`Visibility: ${result.artifact.metadata.visibility}`);
1023
- }
1024
- async function deleteArtifactFromCli(args) {
1025
- const [artifactId] = getPositionals(args);
1026
- if (!artifactId) {
1027
- throw usageError(
1028
- "Usage: artis artifact delete <artifact-id-or-slug> --yes"
1029
- );
1030
- }
1031
- if (!hasFlag(args, "--yes")) {
1032
- throw usageError(
1033
- "Deleting an artifact removes every revision, annotation and share, and cannot be undone. Pass --yes to confirm."
1034
- );
1035
- }
1036
- const credentials = await resolveCredentials(args);
1037
- await apiCall(credentials, "DELETE /api/artifacts/{artifactId}", {
1038
- params: { artifactId }
1039
- });
1040
- console.log(`Deleted ${artifactId}`);
1041
- }
1042
- async function reviseArtifactFromCli(args) {
1043
- const [artifactId, filePath] = getPositionals(args);
1044
- const summary = parseFlagValue(args, "--summary");
1045
- if (!artifactId || !filePath) {
1046
- throw usageError(
1047
- "Usage: artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>]"
1048
- );
1049
- }
1050
- if (!summary) {
1051
- throw usageError("Missing --summary for revision.");
1052
- }
1053
- const capabilities = await parseCapabilitiesFlag(
1054
- parseFlagValue(args, "--capabilities")
1055
- );
1056
- const contract = parseContractFlag(parseFlagValue(args, "--contract"));
1057
- const credentials = await resolveCredentials(args);
1058
- const html = await readHtmlUpload(filePath, "Revision file");
1059
- const explicitBase = parseFlagValue(args, "--base");
1060
- const baseRevisionId = explicitBase ?? await getRememberedBase(credentials.baseUrl, artifactId);
1061
- const result = await apiCall(
1062
- credentials,
1063
- "POST /api/artifacts/{artifactId}/revisions",
1064
- {
1065
- params: { artifactId },
1066
- query: {
1067
- authorName: parseFlagValue(args, "--author") ?? "Artis CLI",
1068
- baseRevisionId,
1069
- resolvedAnnotationIds: collectFlagValues(args, "--resolve"),
1070
- source: "cli",
1071
- summary,
1072
- capabilities,
1073
- contract
1074
- },
1075
- body: html
1076
- }
1077
- );
1078
- await rememberBase(
1079
- credentials.baseUrl,
1080
- [artifactId],
1081
- result.revision.id,
1082
- baseRevisionId
1083
- );
1084
- if (hasFlag(args, "--json")) {
1085
- console.log(JSON.stringify({ revision: result.revision }, null, 2));
1086
- return;
1087
- }
1088
- console.log(`Revision ${result.revision.id}`);
1089
- console.log(`Version ${result.revision.version}`);
1090
- if (baseRevisionId && !explicitBase) {
1091
- console.log(`Base ${baseRevisionId} (remembered from this machine)`);
1092
- } else if (!baseRevisionId) {
1093
- console.log(
1094
- "No base revision: pass --base, or read the artifact with publish or artifact html first, so a concurrent revision is refused instead of overwritten."
1095
- );
1096
- }
1097
- }
1098
- async function createAnnotationFromCli(args) {
1099
- const [artifactId] = getPositionals(args);
1100
- const comment = parseFlagValue(args, "--comment");
1101
- if (!artifactId || !comment) {
1102
- throw usageError(
1103
- "Usage: artis annotate <artifact-id-or-slug> --comment <text> [--title <text>] [--quote <text>] [--css <selector>] [--text-start <n> --text-end <n>] [--rect <x,y,w,h>] [--pin-label <text>] [--requested-change <text>] [--status <open|needs-revision|resolved>]"
1104
- );
1105
- }
1106
- const selectors = buildAnnotationSelectors(args);
1107
- const credentials = await resolveCredentials(args);
1108
- const result = await apiCall(
1109
- credentials,
1110
- "POST /api/artifacts/{artifactId}/annotations",
1111
- {
1112
- params: { artifactId },
1113
- body: {
1114
- authorName: parseFlagValue(args, "--author") ?? "Artis CLI",
1115
- comment,
1116
- pinLabel: parseFlagValue(args, "--pin-label"),
1117
- requestedChange: parseFlagValue(args, "--requested-change"),
1118
- role: "agent",
1119
- selectors: selectors.length ? selectors : void 0,
1120
- status: parseAnnotationStatus(
1121
- parseFlagValue(args, "--status") ?? "open"
1122
- ),
1123
- title: parseFlagValue(args, "--title")
1124
- }
1125
- }
1126
- );
1127
- console.log(`Annotation ${annotationIdFromIri(result.annotation.id)}`);
1128
- console.log(`Status ${result.annotation["artis:status"]}`);
1129
- }
1130
- async function replyFromCli(args) {
1131
- const [annotationId] = getPositionals(args);
1132
- const comment = parseFlagValue(args, "--comment");
1133
- if (!annotationId || !comment) {
1134
- throw usageError("Usage: artis reply <annotation-id> --comment <text>");
1135
- }
1136
- const credentials = await resolveCredentials(args);
1137
- const result = await apiCall(
1138
- credentials,
1139
- "POST /api/annotations/{annotationId}/replies",
1140
- {
1141
- params: { annotationId },
1142
- body: {
1143
- authorName: parseFlagValue(args, "--author") ?? "Artis CLI",
1144
- comment,
1145
- role: "agent"
1146
- }
1147
- }
1148
- );
1149
- console.log(`Reply ${annotationIdFromIri(result.annotation.id)}`);
1150
- }
1151
- async function editAnnotationFromCli(args) {
1152
- const [annotationId] = getPositionals(args);
1153
- const comment = parseFlagValue(args, "--comment");
1154
- const title = parseFlagValue(args, "--title");
1155
- const requestedChange = parseFlagValue(args, "--requested-change");
1156
- if (!annotationId || comment === void 0 && title === void 0 && requestedChange === void 0) {
1157
- throw usageError(
1158
- "Usage: artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]"
1159
- );
1160
- }
1161
- const credentials = await resolveCredentials(args);
1162
- const result = await apiCall(
1163
- credentials,
1164
- "PATCH /api/annotations/{annotationId}",
1165
- { params: { annotationId }, body: { comment, title, requestedChange } }
1166
- );
1167
- console.log(`Annotation ${annotationIdFromIri(result.annotation.id)} edited`);
1168
- }
1169
- async function retractAnnotationFromCli(args) {
1170
- const [annotationId] = getPositionals(args);
1171
- if (!annotationId) {
1172
- throw usageError("Usage: artis annotation retract <annotation-id>");
1173
- }
1174
- const credentials = await resolveCredentials(args);
1175
- const result = await apiCall(
1176
- credentials,
1177
- "DELETE /api/annotations/{annotationId}",
1178
- { params: { annotationId } }
1179
- );
1180
- console.log(
1181
- `Annotation ${annotationIdFromIri(result.annotation.id)} retracted`
1182
- );
1183
- }
1184
- var watchMaxWaitSeconds = 25;
1185
- var watchInitialBackoffMs = 1e3;
1186
- var watchMaxBackoffMs = 6e4;
1187
- function parseDuration(value) {
1188
- const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
1189
- if (!match) {
1190
- throw usageError(
1191
- `Invalid duration "${value}". Use e.g. 30s, 5m, 1h, or 500ms.`
1192
- );
1193
- }
1194
- const unitMs = { ms: 1, s: 1e3, m: 6e4, h: 36e5 }[match[2] ?? "s"];
1195
- return Number(match[1]) * unitMs;
1196
- }
1197
- async function watchArtifactFromCli(args) {
1198
- const [artifactId] = getPositionals(args);
1199
- if (!artifactId) {
1200
- throw usageError(
1201
- "Usage: artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self] [--types <families>]"
1202
- );
1203
- }
1204
- const typesFlag = parseFlagValue(args, "--types");
1205
- const types = typesFlag?.split(",").map((type) => type.trim()).filter(Boolean);
1206
- let cursor = parseFlagValue(args, "--since");
1207
- if (cursor !== void 0 && !/^\d+$/.test(cursor)) {
1208
- throw usageError(
1209
- `Invalid --since "${cursor}". Pass a cursor from artifact feedback or a previous event.`
1210
- );
1211
- }
1212
- const timeoutFlag = parseFlagValue(args, "--timeout");
1213
- const deadline = timeoutFlag !== void 0 ? Date.now() + parseDuration(timeoutFlag) : void 0;
1214
- const once = hasFlag(args, "--once");
1215
- const includeSelf = hasFlag(args, "--include-self");
1216
- const credentials = await resolveCredentials(args);
1217
- const api = apiClient(credentials);
1218
- let backoffMs = watchInitialBackoffMs;
1219
- let delivered = false;
1220
- const timedOut = () => new CliError(
1221
- `No feedback events within ${timeoutFlag}.${cursor ? ` Resume with --since ${cursor}.` : ""}`,
1222
- exitCodes.watchTimeout
1223
- );
1224
- const backOff = async () => {
1225
- const remaining = deadline === void 0 ? Infinity : deadline - Date.now();
1226
- if (remaining <= backoffMs) {
1227
- if (delivered) {
1228
- return false;
1229
- }
1230
- throw timedOut();
1231
- }
1232
- await sleep(backoffMs);
1233
- backoffMs = Math.min(backoffMs * 2, watchMaxBackoffMs);
1234
- return true;
1235
- };
1236
- for (let attempt = 0; ; attempt += 1) {
1237
- const remainingMs = deadline === void 0 ? Infinity : deadline - Date.now();
1238
- if (attempt > 0 && remainingMs < 1e3) {
1239
- if (delivered) {
1240
- return;
1241
- }
1242
- throw timedOut();
1243
- }
1244
- let page;
1245
- try {
1246
- page = await api.call("GET /api/artifacts/{artifactId}/events", {
1247
- params: { artifactId },
1248
- query: {
1249
- wait: Math.min(watchMaxWaitSeconds, Math.floor(remainingMs / 1e3)),
1250
- since: cursor,
1251
- includeSelf: includeSelf || void 0,
1252
- types
1253
- }
1254
- });
1255
- } catch (error) {
1256
- if (!(error instanceof ApiError)) {
1257
- if (await backOff()) {
1258
- continue;
1259
- }
1260
- return;
1261
- }
1262
- if ((error.status === 429 || error.status >= 500) && !once) {
1263
- if (await backOff()) {
1264
- continue;
1265
- }
1266
- return;
1267
- }
1268
- throw new CliError(
1269
- error.status === 410 ? `${error.message} Re-read feedback (artis artifact feedback ${artifactId} --json) and watch from its cursor.` : error.message,
1270
- exitCodeForResponse(error.status, error.code)
1271
- );
1272
- }
1273
- backoffMs = watchInitialBackoffMs;
1274
- const { events } = page;
1275
- cursor = page.cursor;
1276
- if (events.length === 0) {
1277
- continue;
1278
- }
1279
- if (once) {
1280
- console.log(JSON.stringify({ events, cursor }));
1281
- return;
1282
- }
1283
- for (const event of events) {
1284
- process.stdout.write(`${JSON.stringify(event)}
1285
- `);
1286
- }
1287
- delivered = true;
1288
- }
1289
- }
1290
- async function runArtisCli(args = process.argv.slice(2)) {
1291
- const [command, ...rest] = args;
1292
- if (command === "version" || command === "--version" || command === "-v") {
1293
- console.log(`artis ${artisCliVersion}`);
1294
- return;
1295
- }
1296
- if (!command || command === "help" || hasFlag(args, "--help")) {
1297
- console.log(getCliHelp());
1298
- return;
1299
- }
1300
- if (command === "install-skill") {
1301
- await installSkillFromCli(rest);
1302
- return;
1303
- }
1304
- if (command === "login") {
1305
- await loginFromCli(rest);
1306
- return;
1307
- }
1308
- if (command === "whoami") {
1309
- await whoamiFromCli(rest);
1310
- return;
1311
- }
1312
- if (command === "guidelines") {
1313
- await guidelinesFromCli(rest);
1314
- return;
1315
- }
1316
- if (command === "publish") {
1317
- const published = await publishArtifactFromCli(rest);
1318
- if (hasFlag(rest, "--json")) {
1319
- console.log(JSON.stringify(published, null, 2));
1320
- return;
1321
- }
1322
- console.log(`Published "${published.title}"`);
1323
- console.log(`Artifact: ${published.artifactId}`);
1324
- console.log(`Revision: ${published.revisionId}`);
1325
- console.log(`Visibility: ${published.visibility}`);
1326
- console.log(published.url);
1327
- return;
1328
- }
1329
- if (command === "artifact" && rest[0] === "get") {
1330
- await getArtifactFromCli(rest.slice(1));
1331
- return;
1332
- }
1333
- if (command === "artifact" && rest[0] === "html") {
1334
- await getArtifactHtmlFromCli(rest.slice(1));
1335
- return;
1336
- }
1337
- if (command === "verify") {
1338
- await verifyFromCli(rest);
1339
- return;
1340
- }
1341
- if (command === "artifact" && rest[0] === "list") {
1342
- await listArtifactsFromCli(rest.slice(1));
1343
- return;
1344
- }
1345
- if (command === "artifact" && rest[0] === "visibility") {
1346
- await setArtifactVisibilityFromCli(rest.slice(1));
1347
- return;
1348
- }
1349
- if (command === "artifact" && rest[0] === "delete") {
1350
- await deleteArtifactFromCli(rest.slice(1));
1351
- return;
1352
- }
1353
- if (command === "artifact" && rest[0] === "feedback") {
1354
- await getArtifactFeedbackFromCli(rest.slice(1));
1355
- return;
1356
- }
1357
- if (command === "share") {
1358
- await shareArtifactFromCli(rest);
1359
- return;
1360
- }
1361
- if (command === "revise") {
1362
- await reviseArtifactFromCli(rest);
1363
- return;
1364
- }
1365
- if (command === "annotate") {
1366
- await createAnnotationFromCli(rest);
1367
- return;
1368
- }
1369
- if (command === "watch") {
1370
- await watchArtifactFromCli(rest);
1371
- return;
1372
- }
1373
- if (command === "reply") {
1374
- await replyFromCli(rest);
1375
- return;
1376
- }
1377
- if (command === "annotation" && rest[0] === "edit") {
1378
- await editAnnotationFromCli(rest.slice(1));
1379
- return;
1380
- }
1381
- if (command === "annotation" && rest[0] === "retract") {
1382
- await retractAnnotationFromCli(rest.slice(1));
1383
- return;
1384
- }
1385
- throw usageError(`Unknown command "${args.join(" ")}". Run artis help.`);
1386
- }
1387
-
1388
- export {
1389
- commands,
1390
- guidelinesFromCli,
1391
- assertSafeLoginUrl,
1392
- getCliHelp,
1393
- publishArtifactFromCli,
1394
- loginFromCli,
1395
- whoamiFromCli,
1396
- getArtifactFromCli,
1397
- getArtifactHtmlFromCli,
1398
- verifyFromCli,
1399
- listArtifactsFromCli,
1400
- getArtifactFeedbackFromCli,
1401
- shareArtifactFromCli,
1402
- setArtifactVisibilityFromCli,
1403
- deleteArtifactFromCli,
1404
- reviseArtifactFromCli,
1405
- createAnnotationFromCli,
1406
- replyFromCli,
1407
- editAnnotationFromCli,
1408
- retractAnnotationFromCli,
1409
- watchArtifactFromCli,
1410
- runArtisCli
1411
- };