@artis-lab/cli 0.10.0 → 0.12.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.
package/src/lib/cli.js CHANGED
@@ -1,1206 +1,70 @@
1
- import { __awaiter } from "tslib";
2
- import { spawn } from 'node:child_process';
3
- import { readFile, writeFile } from 'node:fs/promises';
4
- import { basename, extname } from 'node:path';
5
- // `@artis/sdk` is a type-only dependency here: the CLI's tsc output can't
6
- // resolve the package specifier at runtime, so these two trivial helpers are
7
- // inlined rather than imported (they mirror the sdk's implementations).
8
- function annotationIdFromIri(iri) {
9
- var _a;
10
- return (_a = iri.replace(/\/+$/, '').split('/').pop()) !== null && _a !== void 0 ? _a : iri;
11
- }
12
- // Mirrors the sdk's formatRevisionConflictMessage.
13
- function formatRevisionConflictMessage(message, details) {
14
- var _a;
15
- if (!(details === null || details === void 0 ? void 0 : details.currentRevisionId)) {
16
- return message;
17
- }
18
- let text = `${message} Current revision: ${details.currentRevisionId}.`;
19
- if (typeof details.currentVersion === 'number') {
20
- const firstLine = ((_a = details.currentSummary) !== null && _a !== void 0 ? _a : '')
21
- .split(/\r?\n/)
22
- .map((line) => line.replace(/^\s*(?:[-*•]\s+)?/, '').trim())
23
- .find(Boolean);
24
- text += firstLine
25
- ? ` Version ${details.currentVersion}: ${firstLine}`
26
- : ` Version ${details.currentVersion}.`;
27
- }
28
- return text;
29
- }
30
- function isRootAnnotation(annotation) {
31
- return annotation.motivation === 'commenting';
32
- }
33
- import { ARTIS_DEFAULT_HOST, findProfileForHost, getConfigPath, normalizeHost, readCliConfig, saveDefaultProfile, } from './config.js';
34
- import { getRememberedBase, rememberBase } from './revision-bases.js';
35
- import { installSkillFromCli } from './skill-install.js';
36
- import { artisCliVersion } from './version.js';
37
- import { collectFlagValues, hasFlag, parseFlagValue } from './args.js';
38
- import { formatVerifyReport, verifyHtml, VerifyUnavailableError, } from './verify.js';
39
- import { CliError, exitCodeForResponse, exitCodes, usageError, } from './exit-codes.js';
40
- export { artisCliVersion };
41
- export { installSkillFromCli };
42
- export const commands = [
43
- 'annotate',
44
- 'annotation',
45
- 'artifact',
46
- 'guidelines',
47
- 'help',
48
- 'install-skill',
49
- 'login',
50
- 'publish',
51
- 'reply',
52
- 'revise',
53
- 'share',
54
- 'version',
55
- 'watch',
56
- 'whoami',
57
- ];
58
- /**
59
- * Mirrors the sdk's `ArtifactVisibility`, deliberately re-declared instead of
60
- * imported: this union reaches the published `.d.ts`, and `@artis/sdk` is a
61
- * workspace-only package that consumers of `@artis-lab/cli` cannot resolve.
62
- * `packages/sdk/src/lib/sdk.ts` stays the source of truth for these values.
63
- *
64
- * Importing sdk types is fine wherever they stay out of exported declarations;
65
- * `scripts/cli-unit.mjs` fails the build if any of them reach the emitted
66
- * `.d.ts`, so that boundary is enforced rather than remembered.
67
- */
68
- const cliVisibilityOptions = ['public', 'unlisted', 'private'];
69
- const cliArtifactKinds = [
70
- 'incident-timeline',
71
- 'migration-plan',
72
- 'generated-dashboard',
73
- 'architecture-explainer',
74
- 'animated-report',
75
- 'ui-prototype',
76
- 'pr-review',
77
- 'custom-html',
78
- ];
79
- const cliAnnotationStatusOptions = [
80
- 'open',
81
- 'needs-revision',
82
- 'resolved',
83
- ];
84
- const cliShareRoleOptions = ['viewer', 'commenter'];
85
- const valueFlags = new Set([
86
- '--api-key',
87
- '--author',
88
- '--comment',
89
- '--css',
90
- '--description',
91
- '--dir',
92
- '--email',
93
- '--harness',
94
- '--host',
95
- '--kind',
96
- '--output',
97
- '--pin-label',
98
- '--quote',
99
- '--quote-prefix',
100
- '--quote-suffix',
101
- '--query',
102
- '--rect',
103
- '--requested-change',
104
- '--resolve',
105
- '--revision',
106
- '--role',
107
- '--since',
108
- '--status',
109
- '--base',
110
- '--summary',
111
- '--tag',
112
- '--text-end',
113
- '--text-start',
114
- '--timeout',
115
- '--title',
116
- '--url',
117
- '--visibility',
118
- ]);
119
- function getPositionals(args) {
120
- const positionals = [];
121
- for (let index = 0; index < args.length; index += 1) {
122
- const arg = args[index];
123
- if (arg.startsWith('-')) {
124
- if (valueFlags.has(arg)) {
125
- index += 1;
126
- }
127
- continue;
128
- }
129
- positionals.push(arg);
130
- }
131
- return positionals;
132
- }
133
- function inferTitleFromPath(filePath) {
134
- const fileName = basename(filePath);
135
- const extension = extname(fileName);
136
- return extension ? fileName.slice(0, -extension.length) : fileName;
137
- }
138
- function parseVisibility(value) {
139
- if (cliVisibilityOptions.includes(value)) {
140
- return value;
141
- }
142
- throw usageError(`Invalid visibility "${value}". Expected one of: ${cliVisibilityOptions.join(', ')}`);
143
- }
144
- function parseKind(value) {
145
- if (cliArtifactKinds.includes(value)) {
146
- return value;
147
- }
148
- throw usageError(`Invalid kind "${value}". Expected one of: ${cliArtifactKinds.join(', ')}`);
149
- }
150
- function parseAnnotationStatus(value) {
151
- if (cliAnnotationStatusOptions.includes(value)) {
152
- return value;
153
- }
154
- throw usageError(`Invalid status "${value}". Expected one of: ${cliAnnotationStatusOptions.join(', ')}`);
155
- }
156
- function parseShareRole(value) {
157
- if (cliShareRoleOptions.includes(value)) {
158
- return value;
159
- }
160
- throw usageError(`Invalid role "${value}". Expected one of: ${cliShareRoleOptions.join(', ')}`);
161
- }
162
- /** Parse a `--rect x,y,w,h` percentage tuple into a Media Fragments
163
- * `xywh=percent:` FragmentSelector. Width/height default to 0 (a point pin). */
164
- function parseRectSelector(value) {
165
- if (!value) {
166
- return undefined;
167
- }
168
- const parts = value.split(',').map((part) => Number(part.trim()));
169
- if ((parts.length !== 2 && parts.length !== 4) ||
170
- parts.some((part) => !Number.isFinite(part))) {
171
- throw usageError(`Invalid --rect "${value}". Expected "x,y" or "x,y,w,h" percentages.`);
172
- }
173
- const [x, y, width = 0, height = 0] = parts;
174
- return {
175
- type: 'FragmentSelector',
176
- conformsTo: 'http://www.w3.org/TR/media-frags/',
177
- value: `xywh=percent:${x},${y},${width},${height}`,
178
- };
179
- }
180
- /** Assemble the annotate flags into a W3C selector array. Each anchor kind is
181
- * independent, so text quotes, offsets, an element selector, and a canvas
182
- * point/rect can all be supplied together. */
183
- function buildAnnotationSelectors(args) {
184
- const selectors = [];
185
- const quote = parseFlagValue(args, '--quote');
186
- if (quote) {
187
- const textQuote = {
188
- type: 'TextQuoteSelector',
189
- exact: quote,
190
- };
191
- const prefix = parseFlagValue(args, '--quote-prefix');
192
- const suffix = parseFlagValue(args, '--quote-suffix');
193
- if (prefix) {
194
- textQuote.prefix = prefix;
195
- }
196
- if (suffix) {
197
- textQuote.suffix = suffix;
198
- }
199
- selectors.push(textQuote);
200
- }
201
- const textStart = parseFlagValue(args, '--text-start');
202
- const textEnd = parseFlagValue(args, '--text-end');
203
- if (textStart !== undefined && textEnd !== undefined) {
204
- const start = Number(textStart);
205
- const end = Number(textEnd);
206
- if (!Number.isFinite(start) || !Number.isFinite(end)) {
207
- throw usageError('--text-start and --text-end must be numbers.');
208
- }
209
- selectors.push({ type: 'TextPositionSelector', start, end });
210
- }
211
- const css = parseFlagValue(args, '--css');
212
- if (css) {
213
- selectors.push({ type: 'CssSelector', value: css });
214
- }
215
- const rect = parseRectSelector(parseFlagValue(args, '--rect'));
216
- if (rect) {
217
- selectors.push(rect);
218
- }
219
- return selectors;
220
- }
221
- function resolveBaseUrl(args, config) {
222
- // `||` rather than `??` on purpose: an empty value (`--host ""`, `ARTIS_URL=`)
223
- // means "unset" here. With `??` it would pass through and every request would
224
- // be built against an empty origin, failing far from the actual mistake.
225
- const host = parseFlagValue(args, '--host') ||
226
- parseFlagValue(args, '--url') ||
227
- process.env['ARTIS_URL'] ||
228
- (config === null || config === void 0 ? void 0 : config.defaultHost) ||
229
- ARTIS_DEFAULT_HOST;
230
- return normalizeHost(host);
231
- }
232
- function resolveApiKey(args, config, baseUrl) {
233
- var _a;
234
- const flagApiKey = parseFlagValue(args, '--api-key');
235
- if (flagApiKey) {
236
- return { apiKey: flagApiKey, apiKeySource: 'flag' };
237
- }
238
- if (process.env['ARTIS_API_KEY']) {
239
- return { apiKey: process.env['ARTIS_API_KEY'], apiKeySource: 'env' };
240
- }
241
- const profileApiKey = (_a = findProfileForHost(config, baseUrl)) === null || _a === void 0 ? void 0 : _a.apiKey;
242
- if (profileApiKey) {
243
- return { apiKey: profileApiKey, apiKeySource: 'config' };
244
- }
245
- return {};
246
- }
247
- function resolveCredentials(args) {
248
- return __awaiter(this, void 0, void 0, function* () {
249
- const config = yield readCliConfig();
250
- const baseUrl = resolveBaseUrl(args, config);
251
- const { apiKey } = resolveApiKey(args, config, baseUrl);
252
- if (!apiKey) {
253
- throw new CliError(`Missing API key. Run "artis login --host ${baseUrl}" or set ARTIS_API_KEY.`, exitCodes.auth);
254
- }
255
- return { apiKey, baseUrl };
256
- });
257
- }
258
- function resolveOptionalTarget(args) {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- const config = yield readCliConfig();
261
- const baseUrl = resolveBaseUrl(args, config);
262
- const { apiKey, apiKeySource } = resolveApiKey(args, config, baseUrl);
263
- return { apiKey, apiKeySource, baseUrl };
264
- });
265
- }
266
- /**
267
- * Print the server's agent guidelines: the section index by default, or one
268
- * section (`authoring`, `revising`, …, or `all`). Same content as MCP
269
- * `get_authoring_guidelines`; served as `/skills.md?section=`.
270
- */
271
- export function guidelinesFromCli(args) {
272
- return __awaiter(this, void 0, void 0, function* () {
273
- const [section] = getPositionals(args);
274
- const config = yield readCliConfig();
275
- const baseUrl = resolveBaseUrl(args, config);
276
- const response = yield fetch(`${baseUrl}/skills.md?section=${encodeURIComponent(section !== null && section !== void 0 ? section : 'index')}`);
277
- const text = yield response.text();
278
- if (!response.ok) {
279
- throw new CliError(text.trim() || `Guidelines request failed with ${response.status}.`, exitCodeForResponse(response.status));
280
- }
281
- process.stdout.write(text.endsWith('\n') ? text : `${text}\n`);
282
- });
283
- }
284
- function parsePublishOptions(args) {
285
- return __awaiter(this, void 0, void 0, function* () {
286
- var _a, _b, _c, _d;
287
- const [filePath] = getPositionals(args);
288
- if (!filePath) {
289
- throw usageError('Missing artifact HTML file path.');
290
- }
291
- const credentials = yield resolveCredentials(args);
292
- const visibility = parseVisibility((_a = parseFlagValue(args, '--visibility')) !== null && _a !== void 0 ? _a : 'unlisted');
293
- return {
294
- filePath,
295
- apiKey: credentials.apiKey,
296
- baseUrl: credentials.baseUrl,
297
- title: parseFlagValue(args, '--title'),
298
- description: (_b = parseFlagValue(args, '--description')) !== null && _b !== void 0 ? _b : 'Published from Artis CLI.',
299
- visibility,
300
- authorName: (_c = parseFlagValue(args, '--author')) !== null && _c !== void 0 ? _c : 'Artis CLI',
301
- kind: parseKind((_d = parseFlagValue(args, '--kind')) !== null && _d !== void 0 ? _d : 'custom-html'),
302
- json: hasFlag(args, '--json'),
303
- };
304
- });
305
- }
306
- function readJsonResponse(response) {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- return response.json().catch(() => null);
309
- });
310
- }
311
- function apiFetch(credentials_1, path_1) {
312
- return __awaiter(this, arguments, void 0, function* (credentials, path, init = {}) {
313
- var _a;
314
- const response = yield fetch(`${credentials.baseUrl}${path}`, Object.assign(Object.assign({}, init), { headers: Object.assign({ authorization: `Bearer ${credentials.apiKey}`, 'content-type': 'application/json' }, init.headers) }));
315
- const payload = yield readJsonResponse(response);
316
- if (!response.ok) {
317
- const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${response.status}.`;
318
- // A revise conflict is only recoverable with the current revision id.
319
- throw new CliError(formatRevisionConflictMessage(message, payload), exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
320
- }
321
- return payload;
322
- });
323
- }
324
- function apiFetchOptional(target_1, path_1) {
325
- return __awaiter(this, arguments, void 0, function* (target, path, init = {}) {
326
- var _a;
327
- const headers = Object.assign(Object.assign(Object.assign({}, (target.apiKey ? { authorization: `Bearer ${target.apiKey}` } : {})), { 'content-type': 'application/json' }), init.headers);
328
- const response = yield fetch(`${target.baseUrl}${path}`, Object.assign(Object.assign({}, init), { headers }));
329
- let payload = yield readJsonResponse(response);
330
- let status = response.status;
331
- if (!response.ok &&
332
- response.status === 401 &&
333
- target.apiKey &&
334
- target.apiKeySource === 'config') {
335
- const retryResponse = yield fetch(`${target.baseUrl}${path}`, Object.assign(Object.assign({}, init), { headers: Object.assign({ 'content-type': 'application/json' }, init.headers) }));
336
- const retryPayload = yield readJsonResponse(retryResponse);
337
- if (retryResponse.ok) {
338
- console.warn(`Saved API key was rejected by ${target.baseUrl}; retried without credentials. Run "artis login --host ${target.baseUrl}" to refresh local credentials.`);
339
- return retryPayload;
340
- }
341
- payload = retryPayload;
342
- status = retryResponse.status;
343
- }
344
- if (status < 200 || status >= 300) {
345
- throw new CliError((_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Request failed with ${status}.`, exitCodeForResponse(status, payload === null || payload === void 0 ? void 0 : payload.code));
346
- }
347
- return payload;
348
- });
349
- }
350
- /**
351
- * Validate a login `verificationUrl` returned by the configured host before it
352
- * crosses a local process/shell boundary (Windows `cmd /c start`). A malicious
353
- * or compromised host could otherwise return a crafted URL that reaches the
354
- * shell. Requires an http(s) scheme and an origin matching `baseUrl`.
355
- */
356
- export function assertSafeLoginUrl(url, baseUrl) {
357
- let parsed;
358
- try {
359
- parsed = new URL(url);
360
- }
361
- catch (_a) {
362
- throw new Error('Login host returned an invalid verification URL.');
363
- }
364
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
365
- throw new Error('Login host returned an unsafe verification URL scheme.');
366
- }
367
- let expected;
368
- try {
369
- expected = new URL(baseUrl);
370
- }
371
- catch (_b) {
372
- throw new Error('Configured login host is not a valid URL.');
373
- }
374
- if (parsed.hostname !== expected.hostname || parsed.port !== expected.port) {
375
- throw new Error('Login host returned a verification URL that does not match the configured host.');
376
- }
377
- }
378
- function openBrowser(url) {
379
- // The URL crosses a shell boundary on Windows (`cmd /c start`), so this
380
- // guard lives here rather than at any single call site: every caller gets
381
- // it, whatever the URL's provenance.
382
- let protocol;
383
- try {
384
- protocol = new URL(url).protocol;
385
- }
386
- catch (_a) {
387
- throw new Error('Refusing to open an invalid URL in the browser.');
388
- }
389
- if (protocol !== 'http:' && protocol !== 'https:') {
390
- throw new Error('Refusing to open a non-http(s) URL in the browser.');
391
- }
392
- const command = process.platform === 'darwin'
393
- ? 'open'
394
- : process.platform === 'win32'
395
- ? 'cmd'
396
- : 'xdg-open';
397
- const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url];
398
- const child = spawn(command, args, {
399
- detached: true,
400
- stdio: 'ignore',
401
- });
402
- child.unref();
403
- }
404
- function sleep(ms) {
405
- return new Promise((resolve) => setTimeout(resolve, ms));
406
- }
407
- function buildArtifactUrl(baseUrl, pathOrUrl) {
408
- return pathOrUrl.startsWith('http') ? pathOrUrl : `${baseUrl}${pathOrUrl}`;
409
- }
410
- export function getCliHelp() {
411
- return `artis
412
-
413
- Host, share, and collaborate on AI-generated HTML artifacts.
414
-
415
- Usage:
416
- artis --version
417
- artis login [--host <url>]
418
- artis whoami [--host <url>]
419
- artis guidelines [section] [--host <url>]
420
- artis install-skill [--harness <id>]... [--yes] [--dir <path>] [--force] [--list] [--json]
421
- artis publish artifact.html [options]
422
- artis artifact get <artifact-id-or-slug> [--json]
423
- artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>] [--json]
424
- artis artifact feedback <artifact-id-or-slug> [--json] [--revision <revision-id>]
425
- artis artifact list [--query <text>] [--kind <value>] [--tag <tag>] [--json]
426
- artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]
427
- artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]
428
- artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>] [--resolve <annotation-id>]
429
- artis annotate <artifact-id-or-slug> --comment <text> [anchor options]
430
- artis reply <annotation-id> --comment <text>
431
- artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]
432
- artis annotation retract <annotation-id>
433
- artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self]
434
-
435
- Options:
436
- --api-key <key> API key. Defaults to ARTIS_API_KEY or ~/.artis/config.json. Run "artis login" to obtain one.
437
- --host, --url <url> Artis server URL. Falls back to ARTIS_URL, then a saved login, then https://artis.xiispace.eu.org.
438
- --title <title> Artifact title. Defaults to the file name.
439
- --description <text> Artifact description.
440
- --visibility <value> public, unlisted, or private. Defaults to unlisted.
441
- --kind <value> Artifact kind. Defaults to custom-html.
442
- --author <name> Artifact author/agent name. Defaults to Artis CLI.
443
- --summary <text> Revision summary. Write one change per line; they render as a list.
444
- --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.
445
- --resolve <annotation-id> Mark an annotation resolved when revising. Repeatable.
446
- --comment <text> Annotation or reply comment text (annotate, reply).
447
- --requested-change <text> Structured change request for the artifact author (annotate).
448
- --status <value> Annotation status: open, needs-revision, or resolved. Defaults to open.
449
- --quote <text> Exact artifact text to anchor to (annotate, TextQuoteSelector).
450
- --quote-prefix <text> Text just before --quote, to disambiguate repeats.
451
- --quote-suffix <text> Text just after --quote, to disambiguate repeats.
452
- --css <selector> CSS selector to anchor to (annotate, CssSelector).
453
- --text-start <n> Document offset where the quote starts (annotate, TextPositionSelector).
454
- --text-end <n> Document offset where the quote ends (annotate, TextPositionSelector).
455
- --rect <x,y,w,h> Canvas point/rect as percentages (annotate, FragmentSelector). w,h default to 0.
456
- --pin-label <text> Short label shown on the artifact canvas pin (annotate).
457
- --output <path> Write the artifact HTML to this file (artifact html). Without it, the document goes to stdout.
458
- --revision <revision-id> Revision to read (artifact html, artifact feedback). Defaults to the current revision.
459
- --query <text> Text to find in your artifacts' titles and descriptions (artifact list).
460
- --tag <tag> Only your artifacts carrying this tag (artifact list). --kind filters by kind.
461
- --email <email> Email address for artis share.
462
- --role <role> Share role: viewer or commenter. Defaults to viewer.
463
- --remove Remove the email from an artifact share list.
464
- --harness <id> Agent harness to install the artis skill into (install-skill). Repeatable: claude-code, cursor, codex, openclaw, pi, hermes.
465
- --yes Install the skill into every detected harness (install-skill).
466
- --dir <path> Install the skill into a custom skills directory (install-skill).
467
- --force Overwrite an already-installed skill (install-skill).
468
- --list List harnesses, detection, and install paths (install-skill).
469
- --since <cursor> Feedback cursor to watch from (watch). Defaults to now; 0 replays every event.
470
- --once Exit after the first batch of events, printed as {events, cursor} (watch).
471
- --timeout <duration> Give up after this long, e.g. 30s, 10m (watch). Exits 6 if nothing happened.
472
- --include-self Also report events caused by this API key (watch).
473
- --json Print machine-readable JSON for supported commands.
474
-
475
- Exit codes:
476
- 0 success, 1 error, 2 usage, 3 auth, 4 not found, 5 revision conflict, 6 watch timeout, 7 rate limited, 8 verify found problems.
477
-
478
- Examples (--host is optional; without it commands target https://artis.xiispace.eu.org):
479
- artis publish report.html
480
- artis login
481
- artis publish report.html --host https://artis.example.com --visibility private
482
- artis share artifact-slug --host https://artis.example.com --email reviewer@example.com --role commenter
483
- artis artifact get artifact-slug --host https://artis.example.com --json
484
- artis artifact html artifact-slug --output report.html
485
- artis verify report.html
486
- artis artifact feedback artifact-slug --host https://artis.example.com --json
487
- artis annotate artifact-slug --host https://artis.example.com --comment "Tighten this heading" --quote "Checkout latency" --requested-change "Add the affected checkout count"
488
- artis reply annotation-123 --host https://artis.example.com --comment "Addressed in the latest revision"
489
- artis annotation edit annotation-123 --host https://artis.example.com --comment "Corrected: the latency spike is on checkout, not search"
490
- artis annotation retract annotation-123 --host https://artis.example.com
491
- artis watch artifact-slug --since 42
492
- artis guidelines authoring
493
- artis install-skill --yes
494
- artis revise artifact-slug report.html --host https://artis.example.com --summary "Addressed open feedback" --base revision-abc --resolve annotation-123`;
495
- }
496
- // Annotated rather than inferred: the returned `visibility` flows through the
497
- // sdk's `CreateArtifactInput`, so declaration emit would otherwise print an
498
- // inline `import('@artis/sdk')` here. The `.d.ts` check in
499
- // `scripts/cli-unit.mjs` catches it if this annotation is ever dropped.
500
- export function publishArtifactFromCli(args) {
501
- return __awaiter(this, void 0, void 0, function* () {
502
- var _a;
503
- const options = yield parsePublishOptions(args);
504
- const html = yield readFile(options.filePath, 'utf8');
505
- if (!html.toLowerCase().includes('<html')) {
506
- throw new Error('Artifact file must be self-contained HTML including <html>.');
507
- }
508
- const payload = {
509
- title: (_a = options.title) !== null && _a !== void 0 ? _a : inferTitleFromPath(options.filePath),
510
- description: options.description,
511
- html,
512
- visibility: options.visibility,
513
- authorName: options.authorName,
514
- source: 'cli',
515
- kind: options.kind,
516
- };
517
- const result = yield apiFetch({ apiKey: options.apiKey, baseUrl: options.baseUrl }, '/api/artifacts', { method: 'POST', body: JSON.stringify(payload) });
518
- if (!(result === null || result === void 0 ? void 0 : result.result)) {
519
- throw new Error('Publish response did not include artifact details.');
520
- }
521
- yield rememberBase(options.baseUrl, [result.result.artifactId, result.result.slug], result.result.revisionId);
522
- return {
523
- artifactId: result.result.artifactId,
524
- revisionId: result.result.revisionId,
525
- title: payload.title,
526
- url: buildArtifactUrl(options.baseUrl, result.result.url),
527
- visibility: payload.visibility,
528
- };
529
- });
530
- }
531
- export function loginFromCli(args) {
532
- return __awaiter(this, void 0, void 0, function* () {
533
- var _a, _b, _c, _d;
534
- const config = yield readCliConfig();
535
- const baseUrl = resolveBaseUrl(args, config);
536
- const response = yield fetch(`${baseUrl}/api/cli/auth/start`, {
537
- method: 'POST',
538
- });
539
- const login = yield readJsonResponse(response);
540
- if (!response.ok ||
541
- !(login === null || login === void 0 ? void 0 : login.deviceCode) ||
542
- !login.userCode ||
543
- !login.verificationUrl ||
544
- !login.expiresAt) {
545
- throw new CliError((_a = login === null || login === void 0 ? void 0 : login.error) !== null && _a !== void 0 ? _a : `Login failed with ${response.status}.`, exitCodeForResponse(response.status));
546
- }
547
- // Validate the host-controlled verification URL before opening a browser.
548
- // A non-default or compromised host could otherwise return a crafted URL
549
- // that reaches a local shell (Windows `cmd /c start`). An unsafe URL aborts
550
- // login rather than opening anything.
551
- assertSafeLoginUrl(login.verificationUrl, baseUrl);
552
- console.log(`Opening ${login.verificationUrl}`);
553
- console.log(`Code: ${login.userCode}`);
554
- try {
555
- openBrowser(login.verificationUrl);
556
- }
557
- catch (_e) {
558
- console.log('Could not open a browser automatically.');
559
- }
560
- const intervalMs = ((_b = login.intervalSeconds) !== null && _b !== void 0 ? _b : 2) * 1000;
561
- while (Date.now() < Date.parse(login.expiresAt)) {
562
- yield sleep(intervalMs);
563
- const pollResponse = yield fetch(`${baseUrl}/api/cli/auth/poll`, {
564
- method: 'POST',
565
- headers: { 'content-type': 'application/json' },
566
- body: JSON.stringify({ deviceCode: login.deviceCode }),
567
- });
568
- const poll = yield readJsonResponse(pollResponse);
569
- if ((poll === null || poll === void 0 ? void 0 : poll.status) === 'pending') {
570
- continue;
571
- }
572
- if ((poll === null || poll === void 0 ? void 0 : poll.status) === 'approved' && poll.token) {
573
- yield saveDefaultProfile({ apiKey: poll.token, host: baseUrl });
574
- console.log(`Saved artis credentials to ${getConfigPath()}`);
575
- return;
576
- }
577
- throw new Error((_c = poll === null || poll === void 0 ? void 0 : poll.error) !== null && _c !== void 0 ? _c : `Login ${(_d = poll === null || poll === void 0 ? void 0 : poll.status) !== null && _d !== void 0 ? _d : 'failed'}.`);
578
- }
579
- throw new Error('Login expired. Run artis login again.');
580
- });
581
- }
582
- export function whoamiFromCli(args) {
583
- return __awaiter(this, void 0, void 0, function* () {
584
- var _a;
585
- const credentials = yield resolveCredentials(args);
586
- const result = yield apiFetch(credentials, '/api/me');
587
- if (!(result === null || result === void 0 ? void 0 : result.principal)) {
588
- throw new Error('whoami response did not include a principal.');
589
- }
590
- console.log(`Signed in to ${credentials.baseUrl} as ${(_a = result.principal.name) !== null && _a !== void 0 ? _a : result.principal.userId}`);
591
- console.log(`Principal: ${result.principal.kind}`);
592
- });
593
- }
594
- export function getArtifactFromCli(args) {
595
- return __awaiter(this, void 0, void 0, function* () {
596
- var _a;
597
- const [artifactId] = getPositionals(args);
598
- if (!artifactId) {
599
- throw usageError('Missing artifact id or slug.');
600
- }
601
- const target = yield resolveOptionalTarget(args);
602
- const result = yield apiFetchOptional(target, `/api/artifacts/${encodeURIComponent(artifactId)}`);
603
- if (hasFlag(args, '--json')) {
604
- console.log(JSON.stringify(result, null, 2));
605
- return;
606
- }
607
- if (!(result === null || result === void 0 ? void 0 : result.artifact)) {
608
- throw new Error('Artifact response did not include artifact details.');
609
- }
610
- console.log(`${result.artifact.metadata.title}`);
611
- console.log(`Artifact: ${result.artifact.id}`);
612
- console.log(`Revision: ${result.artifact.currentRevisionId}`);
613
- console.log(`Open annotations: ${((_a = result.annotations) !== null && _a !== void 0 ? _a : []).filter((annotation) => isRootAnnotation(annotation) && annotation['artis:status'] !== 'resolved').length}`);
614
- });
615
- }
616
- /**
617
- * Read a revision's stored HTML back. `revise` takes a complete replacement
618
- * document, so this is the way to edit an artifact that is no longer on disk:
619
- * `artis artifact html <id> --output report.html`, edit, then `artis revise`.
620
- */
621
- export function getArtifactHtmlFromCli(args) {
622
- return __awaiter(this, void 0, void 0, function* () {
623
- const [artifactId] = getPositionals(args);
624
- if (!artifactId) {
625
- throw usageError('Usage: artis artifact html <artifact-id-or-slug> [--output <path>] [--revision <revision-id>]');
626
- }
627
- const target = yield resolveOptionalTarget(args);
628
- const revisionId = parseFlagValue(args, '--revision');
629
- const query = revisionId
630
- ? `?revisionId=${encodeURIComponent(revisionId)}`
631
- : '';
632
- const result = yield apiFetchOptional(target, `/api/artifacts/${encodeURIComponent(artifactId)}/html${query}`);
633
- // Whatever was read is what an edit of it builds on: `revise` sends it as
634
- // the base, so a revision landing in between is refused, not overwritten.
635
- if (result === null || result === void 0 ? void 0 : result.revisionId) {
636
- yield rememberBase(target.baseUrl, [artifactId, result.artifactId], result.revisionId);
637
- }
638
- // Stderr, so piped HTML or JSON on stdout is unaffected. Strictly false:
639
- // an older server omits the field and must not trigger the hint.
640
- if ((result === null || result === void 0 ? void 0 : result.isLatest) === false) {
641
- console.error(`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.`);
642
- }
643
- if (hasFlag(args, '--json')) {
644
- console.log(JSON.stringify(result, null, 2));
645
- return;
646
- }
647
- if (!(result === null || result === void 0 ? void 0 : result.html)) {
648
- throw new Error('Artifact response did not include revision HTML.');
649
- }
650
- const outputPath = parseFlagValue(args, '--output');
651
- if (!outputPath) {
652
- // No --output: the document goes to stdout so it can be piped or
653
- // redirected. Progress lines would corrupt that, so print nothing else.
654
- process.stdout.write(result.html);
655
- return;
656
- }
657
- yield writeFile(outputPath, result.html, 'utf8');
658
- console.log(`Wrote ${outputPath}`);
659
- console.log(`Revision: ${result.revisionId}`);
660
- console.log(`Version: ${result.version}`);
661
- });
662
- }
663
- /**
664
- * Render a local HTML file, or a published artifact's stored HTML, in the
665
- * system Chrome at 1280 and 390 px in light and dark themes, and report
666
- * horizontal overflow, clipped SVG, console errors and CSP violations.
667
- * Exits 8 when it finds any.
668
- */
669
- export function verifyFromCli(args) {
670
- return __awaiter(this, void 0, void 0, function* () {
671
- const [target] = getPositionals(args);
672
- if (!target) {
673
- throw usageError('Usage: artis verify <artifact.html | artifact-id-or-slug> [--revision <revision-id>] [--json]');
674
- }
675
- // Anything that looks like a path (a separator, or an .html/.htm name) is
676
- // a local file, and a missing one is reported as such rather than sent to
677
- // the API as an artifact id. A bare name that exists on disk is a file
678
- // too; any other bare name is an artifact id or slug.
679
- let html;
680
- let label;
681
- const looksLikePath = /[\\/]/.test(target) || /\.html?$/i.test(target);
682
- const local = yield readFile(target, 'utf8').catch((error) => error);
683
- if (typeof local === 'string' || looksLikePath) {
684
- if (typeof local !== 'string') {
685
- throw local.code === 'ENOENT'
686
- ? new CliError(`File not found: ${target}`, exitCodes.notFound)
687
- : usageError(`Cannot read ${target}: ${local.message}`);
688
- }
689
- if (parseFlagValue(args, '--revision')) {
690
- throw usageError('--revision applies to a published artifact, not a local file.');
691
- }
692
- html = local;
693
- label = target;
694
- }
695
- else {
696
- const remote = yield resolveOptionalTarget(args);
697
- const revisionId = parseFlagValue(args, '--revision');
698
- const query = revisionId
699
- ? `?revisionId=${encodeURIComponent(revisionId)}`
700
- : '';
701
- const result = yield apiFetchOptional(remote, `/api/artifacts/${encodeURIComponent(target)}/html${query}`);
702
- if (!(result === null || result === void 0 ? void 0 : result.html)) {
703
- throw new Error('Artifact response did not include revision HTML.');
704
- }
705
- html = result.html;
706
- label = `${target} v${result.version}`;
707
- }
708
- let report;
709
- try {
710
- report = yield verifyHtml(html);
711
- }
712
- catch (error) {
713
- if (error instanceof VerifyUnavailableError) {
714
- throw new CliError(error.message, exitCodes.error);
715
- }
716
- throw error;
717
- }
718
- if (hasFlag(args, '--json')) {
719
- console.log(JSON.stringify(report, null, 2));
720
- }
721
- else {
722
- console.log(`Verified ${label}`);
723
- for (const line of formatVerifyReport(report)) {
724
- console.log(line);
725
- }
726
- }
727
- if (!report.ok) {
728
- throw new CliError('', exitCodes.verifyFailed);
729
- }
730
- });
731
- }
732
- /**
733
- * List your own artifacts, newest first, optionally searched by title and
734
- * description and filtered by kind and tag.
735
- */
736
- export function listArtifactsFromCli(args) {
737
- return __awaiter(this, void 0, void 0, function* () {
738
- var _a, _b;
739
- const credentials = yield resolveCredentials(args);
740
- const params = new URLSearchParams({ owner: 'me' });
741
- const query = parseFlagValue(args, '--query');
742
- const kind = parseFlagValue(args, '--kind');
743
- const tag = parseFlagValue(args, '--tag');
744
- if (query)
745
- params.set('q', query);
746
- if (kind)
747
- params.set('kind', parseKind(kind));
748
- if (tag)
749
- params.set('tag', tag);
750
- const result = yield apiFetch(credentials, `/api/artifacts?${params}`);
751
- if (hasFlag(args, '--json')) {
752
- console.log(JSON.stringify(result, null, 2));
753
- return;
754
- }
755
- const artifacts = (_a = result === null || result === void 0 ? void 0 : result.artifacts) !== null && _a !== void 0 ? _a : [];
756
- if (!artifacts.length) {
757
- console.log(query || kind || tag
758
- ? 'No artifacts match.'
759
- : 'You have no artifacts yet.');
760
- return;
761
- }
762
- for (const artifact of artifacts) {
763
- const tags = ((_b = artifact.metadata.tags) === null || _b === void 0 ? void 0 : _b.length)
764
- ? ` #${artifact.metadata.tags.join(' #')}`
765
- : '';
766
- console.log(`${artifact.slug} ${artifact.metadata.visibility} ${artifact.metadata.kind} ${artifact.metadata.title}${tags}`);
767
- }
768
- });
769
- }
770
- export function getArtifactFeedbackFromCli(args) {
771
- return __awaiter(this, void 0, void 0, function* () {
772
- const [artifactId] = getPositionals(args);
773
- if (!artifactId) {
774
- throw usageError('Missing artifact id or slug.');
775
- }
776
- const target = yield resolveOptionalTarget(args);
777
- const revisionId = parseFlagValue(args, '--revision');
778
- const query = revisionId
779
- ? `?revisionId=${encodeURIComponent(revisionId)}`
780
- : '';
781
- const result = yield apiFetchOptional(target, `/api/artifacts/${encodeURIComponent(artifactId)}/feedback${query}`);
782
- if (hasFlag(args, '--json')) {
783
- console.log(JSON.stringify(result, null, 2));
784
- return;
785
- }
786
- if (!(result === null || result === void 0 ? void 0 : result.prompt)) {
787
- throw new Error('Feedback response did not include a prompt.');
788
- }
789
- console.log(result.prompt);
790
- if (result.cursor !== undefined) {
791
- console.log(`\nFeedback cursor: ${result.cursor} (artis watch ${artifactId} --since ${result.cursor})`);
792
- }
793
- });
794
- }
795
- export function shareArtifactFromCli(args) {
796
- return __awaiter(this, void 0, void 0, function* () {
797
- var _a, _b, _c;
798
- const [artifactId] = getPositionals(args);
799
- if (!artifactId) {
800
- throw usageError('Usage: artis share <artifact-id-or-slug> [--email <email> --role <viewer|commenter>] [--remove]');
801
- }
802
- const email = (_a = parseFlagValue(args, '--email')) === null || _a === void 0 ? void 0 : _a.trim().toLowerCase();
803
- const credentials = yield resolveCredentials(args);
804
- const path = `/api/artifacts/${encodeURIComponent(artifactId)}/shares`;
805
- if (!email) {
806
- const result = yield apiFetch(credentials, path);
807
- if (hasFlag(args, '--json')) {
808
- console.log(JSON.stringify(result, null, 2));
809
- return;
810
- }
811
- const shares = (_b = result === null || result === void 0 ? void 0 : result.shares) !== null && _b !== void 0 ? _b : [];
812
- if (!shares.length) {
813
- console.log('No invited people yet.');
814
- return;
815
- }
816
- for (const share of shares) {
817
- console.log(`${share.email} ${share.role}`);
818
- }
819
- return;
820
- }
821
- if (hasFlag(args, '--remove')) {
822
- yield apiFetch(credentials, path, {
823
- method: 'DELETE',
824
- body: JSON.stringify({ email }),
825
- });
826
- console.log(`Removed ${email}`);
827
- return;
828
- }
829
- const role = parseShareRole((_c = parseFlagValue(args, '--role')) !== null && _c !== void 0 ? _c : 'viewer');
830
- const result = yield apiFetch(credentials, path, {
831
- method: 'POST',
832
- body: JSON.stringify({ email, role }),
833
- });
834
- if (!(result === null || result === void 0 ? void 0 : result.share)) {
835
- throw new Error('Share response did not include share details.');
836
- }
837
- if (hasFlag(args, '--json')) {
838
- console.log(JSON.stringify(result, null, 2));
839
- return;
840
- }
841
- console.log(`Shared with ${result.share.email} as ${result.share.role}`);
842
- });
843
- }
844
- export function reviseArtifactFromCli(args) {
845
- return __awaiter(this, void 0, void 0, function* () {
846
- var _a, _b;
847
- const [artifactId, filePath] = getPositionals(args);
848
- const summary = parseFlagValue(args, '--summary');
849
- if (!artifactId || !filePath) {
850
- throw usageError('Usage: artis revise <artifact-id-or-slug> artifact.html --summary <text> [--base <revision-id>]');
851
- }
852
- if (!summary) {
853
- throw usageError('Missing --summary for revision.');
854
- }
855
- const credentials = yield resolveCredentials(args);
856
- const html = yield readFile(filePath, 'utf8');
857
- if (!html.toLowerCase().includes('<html')) {
858
- throw new Error('Revision file must be self-contained HTML including <html>.');
859
- }
860
- const explicitBase = parseFlagValue(args, '--base');
861
- const baseRevisionId = explicitBase !== null && explicitBase !== void 0 ? explicitBase : (yield getRememberedBase(credentials.baseUrl, artifactId));
862
- const result = yield apiFetch(credentials, `/api/artifacts/${encodeURIComponent(artifactId)}/revisions`, {
863
- method: 'POST',
864
- body: JSON.stringify({
865
- authorName: (_a = parseFlagValue(args, '--author')) !== null && _a !== void 0 ? _a : 'Artis CLI',
866
- html,
867
- baseRevisionId,
868
- resolvedAnnotationIds: collectFlagValues(args, '--resolve'),
869
- source: 'cli',
870
- summary,
871
- }),
872
- });
873
- if (result === null || result === void 0 ? void 0 : result.revision) {
874
- yield rememberBase(credentials.baseUrl, [artifactId], result.revision.id, baseRevisionId);
875
- }
876
- if (hasFlag(args, '--json')) {
877
- console.log(JSON.stringify(result, null, 2));
878
- return;
879
- }
880
- if (!(result === null || result === void 0 ? void 0 : result.revision)) {
881
- throw new Error('Revision response did not include revision details.');
882
- }
883
- console.log(`Revision ${result.revision.id}`);
884
- console.log(`Version ${result.revision.version}`);
885
- // The anchored text of these is gone: the agent should check whether the
886
- // feedback was addressed or the text was lost by accident.
887
- const orphaned = (_b = result.orphanedAnnotationIds) !== null && _b !== void 0 ? _b : [];
888
- if (result.anchorStatusComputed === false) {
889
- console.log('Anchor status: could not be computed for this revision; check open annotations by hand.');
890
- }
891
- else if (orphaned.length) {
892
- console.log(`Orphaned annotations (anchored text removed): ${orphaned.length}`);
893
- for (const id of orphaned) {
894
- console.log(` ${id}`);
895
- }
896
- }
897
- if (baseRevisionId && !explicitBase) {
898
- console.log(`Base ${baseRevisionId} (remembered from this machine)`);
899
- }
900
- else if (!baseRevisionId) {
901
- console.log('No base revision: pass --base, or read the artifact with publish or artifact html first, so a concurrent revision is refused instead of overwritten.');
902
- }
903
- });
904
- }
905
- export function createAnnotationFromCli(args) {
906
- return __awaiter(this, void 0, void 0, function* () {
907
- var _a, _b;
908
- const [artifactId] = getPositionals(args);
909
- const comment = parseFlagValue(args, '--comment');
910
- if (!artifactId || !comment) {
911
- throw usageError('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>]');
912
- }
913
- const selectors = buildAnnotationSelectors(args);
914
- const credentials = yield resolveCredentials(args);
915
- const result = yield apiFetch(credentials, `/api/artifacts/${encodeURIComponent(artifactId)}/annotations`, {
916
- method: 'POST',
917
- body: JSON.stringify({
918
- authorName: (_a = parseFlagValue(args, '--author')) !== null && _a !== void 0 ? _a : 'Artis CLI',
919
- comment,
920
- pinLabel: parseFlagValue(args, '--pin-label'),
921
- requestedChange: parseFlagValue(args, '--requested-change'),
922
- role: 'agent',
923
- selectors: selectors.length ? selectors : undefined,
924
- status: parseAnnotationStatus((_b = parseFlagValue(args, '--status')) !== null && _b !== void 0 ? _b : 'open'),
925
- title: parseFlagValue(args, '--title'),
926
- }),
927
- });
928
- if (!(result === null || result === void 0 ? void 0 : result.annotation)) {
929
- throw new Error('Annotation response did not include annotation details.');
930
- }
931
- console.log(`Annotation ${annotationIdFromIri(result.annotation.id)}`);
932
- console.log(`Status ${result.annotation['artis:status']}`);
933
- });
934
- }
935
- export function replyFromCli(args) {
936
- return __awaiter(this, void 0, void 0, function* () {
937
- var _a;
938
- const [annotationId] = getPositionals(args);
939
- const comment = parseFlagValue(args, '--comment');
940
- if (!annotationId || !comment) {
941
- throw usageError('Usage: artis reply <annotation-id> --comment <text>');
942
- }
943
- const credentials = yield resolveCredentials(args);
944
- const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}/replies`, {
945
- method: 'POST',
946
- body: JSON.stringify({
947
- authorName: (_a = parseFlagValue(args, '--author')) !== null && _a !== void 0 ? _a : 'Artis CLI',
948
- comment,
949
- role: 'agent',
950
- }),
951
- });
952
- if (!(result === null || result === void 0 ? void 0 : result.annotation)) {
953
- throw new Error('Reply response did not include annotation details.');
954
- }
955
- console.log(`Reply ${annotationIdFromIri(result.annotation.id)}`);
956
- });
957
- }
958
- export function editAnnotationFromCli(args) {
959
- return __awaiter(this, void 0, void 0, function* () {
960
- const [annotationId] = getPositionals(args);
961
- const comment = parseFlagValue(args, '--comment');
962
- const title = parseFlagValue(args, '--title');
963
- const requestedChange = parseFlagValue(args, '--requested-change');
964
- if (!annotationId ||
965
- (comment === undefined &&
966
- title === undefined &&
967
- requestedChange === undefined)) {
968
- throw usageError('Usage: artis annotation edit <annotation-id> [--comment <text>] [--title <text>] [--requested-change <text>]');
969
- }
970
- const credentials = yield resolveCredentials(args);
971
- const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}`, {
972
- method: 'PATCH',
973
- body: JSON.stringify({ comment, title, requestedChange }),
974
- });
975
- if (!(result === null || result === void 0 ? void 0 : result.annotation)) {
976
- throw new Error('Annotation response did not include annotation details.');
977
- }
978
- console.log(`Annotation ${annotationIdFromIri(result.annotation.id)} edited`);
979
- });
980
- }
981
- export function retractAnnotationFromCli(args) {
982
- return __awaiter(this, void 0, void 0, function* () {
983
- const [annotationId] = getPositionals(args);
984
- if (!annotationId) {
985
- throw usageError('Usage: artis annotation retract <annotation-id>');
986
- }
987
- const credentials = yield resolveCredentials(args);
988
- const result = yield apiFetch(credentials, `/api/annotations/${encodeURIComponent(annotationId)}`, {
989
- method: 'DELETE',
990
- });
991
- if (!(result === null || result === void 0 ? void 0 : result.annotation)) {
992
- throw new Error('Annotation response did not include annotation details.');
993
- }
994
- console.log(`Annotation ${annotationIdFromIri(result.annotation.id)} retracted`);
995
- });
996
- }
997
- const watchMaxWaitSeconds = 25;
998
- const watchInitialBackoffMs = 1000;
999
- const watchMaxBackoffMs = 60000;
1000
- /** `30`, `30s`, `500ms`, `5m`, `1h` → milliseconds. A bare number is seconds. */
1001
- function parseDuration(value) {
1002
- var _a;
1003
- const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec(value.trim());
1004
- if (!match) {
1005
- throw usageError(`Invalid duration "${value}". Use e.g. 30s, 5m, 1h, or 500ms.`);
1006
- }
1007
- const unitMs = { ms: 1, s: 1000, m: 60000, h: 3600000 }[((_a = match[2]) !== null && _a !== void 0 ? _a : 's')];
1008
- return Number(match[1]) * unitMs;
1009
- }
1010
- /**
1011
- * Wait for annotation events on one artifact caused by anyone but this API
1012
- * key, by long-polling `GET /api/artifacts/:id/events` from a feedback
1013
- * cursor. Streams one JSON line per event until stopped; `--once` prints the
1014
- * first batch as `{events, cursor}` and exits 0. Network drops and rate
1015
- * limits are retried from the last cursor, so no event is lost or repeated.
1016
- */
1017
- export function watchArtifactFromCli(args) {
1018
- return __awaiter(this, void 0, void 0, function* () {
1019
- var _a, _b, _c;
1020
- const [artifactId] = getPositionals(args);
1021
- if (!artifactId) {
1022
- throw usageError('Usage: artis watch <artifact-id-or-slug> [--since <cursor>] [--once] [--timeout <duration>] [--include-self]');
1023
- }
1024
- let cursor = parseFlagValue(args, '--since');
1025
- if (cursor !== undefined && !/^\d+$/.test(cursor)) {
1026
- throw usageError(`Invalid --since "${cursor}". Pass a cursor from artifact feedback or a previous event.`);
1027
- }
1028
- const timeoutFlag = parseFlagValue(args, '--timeout');
1029
- const deadline = timeoutFlag !== undefined
1030
- ? Date.now() + parseDuration(timeoutFlag)
1031
- : undefined;
1032
- const once = hasFlag(args, '--once');
1033
- const includeSelf = hasFlag(args, '--include-self');
1034
- const credentials = yield resolveCredentials(args);
1035
- let backoffMs = watchInitialBackoffMs;
1036
- let delivered = false;
1037
- const timedOut = () => new CliError(`No feedback events within ${timeoutFlag}.${cursor ? ` Resume with --since ${cursor}.` : ''}`, exitCodes.watchTimeout);
1038
- // Sleep before retrying a transient failure. Returns false when the
1039
- // deadline would pass first and the stream already delivered (a clean end).
1040
- const backOff = () => __awaiter(this, void 0, void 0, function* () {
1041
- const remaining = deadline === undefined ? Infinity : deadline - Date.now();
1042
- if (remaining <= backoffMs) {
1043
- if (delivered) {
1044
- return false;
1045
- }
1046
- throw timedOut();
1047
- }
1048
- yield sleep(backoffMs);
1049
- backoffMs = Math.min(backoffMs * 2, watchMaxBackoffMs);
1050
- return true;
1051
- });
1052
- for (let attempt = 0;; attempt += 1) {
1053
- const remainingMs = deadline === undefined ? Infinity : deadline - Date.now();
1054
- // The first request always goes out, so a short --timeout still reports
1055
- // auth or not-found errors. After that, under a second left would only
1056
- // produce wait=0 requests in a tight loop.
1057
- if (attempt > 0 && remainingMs < 1000) {
1058
- // Exit 6 means "nothing happened"; a stream that delivered ends cleanly.
1059
- if (delivered) {
1060
- return;
1061
- }
1062
- throw timedOut();
1063
- }
1064
- const query = new URLSearchParams({
1065
- wait: String(Math.min(watchMaxWaitSeconds, Math.floor(remainingMs / 1000))),
1066
- });
1067
- if (cursor !== undefined) {
1068
- query.set('since', cursor);
1069
- }
1070
- if (includeSelf) {
1071
- query.set('includeSelf', 'true');
1072
- }
1073
- let response;
1074
- try {
1075
- response = yield fetch(`${credentials.baseUrl}/api/artifacts/${encodeURIComponent(artifactId)}/events?${query}`, { headers: { authorization: `Bearer ${credentials.apiKey}` } });
1076
- }
1077
- catch (_d) {
1078
- // Network drop: reconnect from the last cursor.
1079
- if (yield backOff()) {
1080
- continue;
1081
- }
1082
- return;
1083
- }
1084
- const payload = yield readJsonResponse(response);
1085
- // Rate limits and server errors are transient for a long-running stream.
1086
- if ((response.status === 429 || response.status >= 500) && !once) {
1087
- if (yield backOff()) {
1088
- continue;
1089
- }
1090
- return;
1091
- }
1092
- if (!response.ok) {
1093
- const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : `Watch request failed with ${response.status}.`;
1094
- throw new CliError(response.status === 410
1095
- ? `${message} Re-read feedback (artis artifact feedback ${artifactId} --json) and watch from its cursor.`
1096
- : message, exitCodeForResponse(response.status, payload === null || payload === void 0 ? void 0 : payload.code));
1097
- }
1098
- backoffMs = watchInitialBackoffMs;
1099
- const events = (_b = payload === null || payload === void 0 ? void 0 : payload.events) !== null && _b !== void 0 ? _b : [];
1100
- cursor = (_c = payload === null || payload === void 0 ? void 0 : payload.cursor) !== null && _c !== void 0 ? _c : cursor;
1101
- if (events.length === 0) {
1102
- continue;
1103
- }
1104
- if (once) {
1105
- console.log(JSON.stringify({ events, cursor }));
1106
- return;
1107
- }
1108
- for (const event of events) {
1109
- process.stdout.write(`${JSON.stringify(event)}\n`);
1110
- }
1111
- delivered = true;
1112
- }
1113
- });
1114
- }
1115
- export function runArtisCli() {
1116
- return __awaiter(this, arguments, void 0, function* (args = process.argv.slice(2)) {
1117
- const [command, ...rest] = args;
1118
- if (command === 'version' || command === '--version' || command === '-v') {
1119
- console.log(`artis ${artisCliVersion}`);
1120
- return;
1121
- }
1122
- if (!command || command === 'help' || hasFlag(args, '--help')) {
1123
- console.log(getCliHelp());
1124
- return;
1125
- }
1126
- if (command === 'install-skill') {
1127
- yield installSkillFromCli(rest);
1128
- return;
1129
- }
1130
- if (command === 'login') {
1131
- yield loginFromCli(rest);
1132
- return;
1133
- }
1134
- if (command === 'whoami') {
1135
- yield whoamiFromCli(rest);
1136
- return;
1137
- }
1138
- if (command === 'guidelines') {
1139
- yield guidelinesFromCli(rest);
1140
- return;
1141
- }
1142
- if (command === 'publish') {
1143
- const published = yield publishArtifactFromCli(rest);
1144
- if (hasFlag(rest, '--json')) {
1145
- console.log(JSON.stringify(published, null, 2));
1146
- return;
1147
- }
1148
- console.log(`Published "${published.title}"`);
1149
- console.log(`Artifact: ${published.artifactId}`);
1150
- console.log(`Revision: ${published.revisionId}`);
1151
- console.log(`Visibility: ${published.visibility}`);
1152
- console.log(published.url);
1153
- return;
1154
- }
1155
- if (command === 'artifact' && rest[0] === 'get') {
1156
- yield getArtifactFromCli(rest.slice(1));
1157
- return;
1158
- }
1159
- if (command === 'artifact' && rest[0] === 'html') {
1160
- yield getArtifactHtmlFromCli(rest.slice(1));
1161
- return;
1162
- }
1163
- if (command === 'verify') {
1164
- yield verifyFromCli(rest);
1165
- return;
1166
- }
1167
- if (command === 'artifact' && rest[0] === 'list') {
1168
- yield listArtifactsFromCli(rest.slice(1));
1169
- return;
1170
- }
1171
- if (command === 'artifact' && rest[0] === 'feedback') {
1172
- yield getArtifactFeedbackFromCli(rest.slice(1));
1173
- return;
1174
- }
1175
- if (command === 'share') {
1176
- yield shareArtifactFromCli(rest);
1177
- return;
1178
- }
1179
- if (command === 'revise') {
1180
- yield reviseArtifactFromCli(rest);
1181
- return;
1182
- }
1183
- if (command === 'annotate') {
1184
- yield createAnnotationFromCli(rest);
1185
- return;
1186
- }
1187
- if (command === 'watch') {
1188
- yield watchArtifactFromCli(rest);
1189
- return;
1190
- }
1191
- if (command === 'reply') {
1192
- yield replyFromCli(rest);
1193
- return;
1194
- }
1195
- if (command === 'annotation' && rest[0] === 'edit') {
1196
- yield editAnnotationFromCli(rest.slice(1));
1197
- return;
1198
- }
1199
- if (command === 'annotation' && rest[0] === 'retract') {
1200
- yield retractAnnotationFromCli(rest.slice(1));
1201
- return;
1202
- }
1203
- throw usageError(`Unknown command "${args.join(' ')}". Run artis help.`);
1204
- });
1205
- }
1206
- //# sourceMappingURL=cli.js.map
1
+ import {
2
+ assertSafeLoginUrl,
3
+ commands,
4
+ createAnnotationFromCli,
5
+ dataFromCli,
6
+ deleteArtifactFromCli,
7
+ editAnnotationFromCli,
8
+ getArtifactFeedbackFromCli,
9
+ getArtifactFilesFromCli,
10
+ getArtifactFromCli,
11
+ getArtifactHtmlFromCli,
12
+ getCliHelp,
13
+ guidelinesFromCli,
14
+ listArtifactsFromCli,
15
+ loginFromCli,
16
+ parseDataCommand,
17
+ publishArtifactFromCli,
18
+ replyFromCli,
19
+ retractAnnotationFromCli,
20
+ reviseArtifactFromCli,
21
+ runArtisCli,
22
+ setArtifactVisibilityFromCli,
23
+ shareArtifactFromCli,
24
+ typesFromCli,
25
+ verifyFromCli,
26
+ watchArtifactFromCli,
27
+ whoamiFromCli
28
+ } from "./chunk-YXGHBN47.js";
29
+ import {
30
+ installSkillFromCli
31
+ } from "./chunk-OBEJTKCR.js";
32
+ import "./chunk-YAZGW7Y4.js";
33
+ import {
34
+ artisCliVersion
35
+ } from "./chunk-IZYFOV2K.js";
36
+ import "./chunk-U3ZF6SRR.js";
37
+ import "./chunk-QDQQASRY.js";
38
+ import "./chunk-H32QAUSA.js";
39
+ import "./chunk-KY47KP5E.js";
40
+ import "./chunk-QNS7GLAA.js";
41
+ export {
42
+ artisCliVersion,
43
+ assertSafeLoginUrl,
44
+ commands,
45
+ createAnnotationFromCli,
46
+ dataFromCli,
47
+ deleteArtifactFromCli,
48
+ editAnnotationFromCli,
49
+ getArtifactFeedbackFromCli,
50
+ getArtifactFilesFromCli,
51
+ getArtifactFromCli,
52
+ getArtifactHtmlFromCli,
53
+ getCliHelp,
54
+ guidelinesFromCli,
55
+ installSkillFromCli,
56
+ listArtifactsFromCli,
57
+ loginFromCli,
58
+ parseDataCommand,
59
+ publishArtifactFromCli,
60
+ replyFromCli,
61
+ retractAnnotationFromCli,
62
+ reviseArtifactFromCli,
63
+ runArtisCli,
64
+ setArtifactVisibilityFromCli,
65
+ shareArtifactFromCli,
66
+ typesFromCli,
67
+ verifyFromCli,
68
+ watchArtifactFromCli,
69
+ whoamiFromCli
70
+ };