@hivemagnus/ardent-client 0.0.0-stage → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,120 @@
1
+ import { executionHeaders, parseExecutionContext } from '@hivemagnus/hive-common/execution';
2
+ import { Connection } from './transport.js';
3
+ import { followTask } from './follow.js';
4
+ import { downloadArtifact } from './download.js';
5
+ import { NotFoundError } from './errors.js';
6
+ import { uuidFromKey } from './sha256.js';
7
+ const segment = (value, label) => {
8
+ if (typeof value !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(value))
9
+ throw new NotFoundError('NOT_FOUND', `Invalid ${label}`, { status: 404 });
10
+ return encodeURIComponent(value);
11
+ };
12
+ const digest = (value) => {
13
+ if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))
14
+ throw new NotFoundError('NOT_FOUND', 'Invalid artifact digest', { status: 404 });
15
+ return value;
16
+ };
17
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
18
+ /** A random UUID; `randomUUID` exists only in secure browser contexts, so fall back to random bytes. */
19
+ const randomKey = () => {
20
+ if (typeof globalThis.crypto.randomUUID === 'function')
21
+ return globalThis.crypto.randomUUID();
22
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(16));
23
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
24
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
25
+ const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
26
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
27
+ };
28
+ /** Create a client for one Ardent profile. */
29
+ export function createArdentClient(options) {
30
+ const connection = new Connection(options.transport, { signal: options.signal, retryPolicy: options.retryPolicy, deadlineMs: options.execution?.deadline_ms });
31
+ const magnus = connection.kind === 'magnus';
32
+ const defaultExecution = options.execution === undefined ? undefined : parseExecutionContext(options.execution);
33
+ const read = (path, call, extra = {}) => connection.read({ path, ...extra }, call?.signal);
34
+ const tasks = {
35
+ async submit(input) {
36
+ const key = input.idempotencyKey ?? randomKey();
37
+ const execution = input.execution === undefined ? defaultExecution : parseExecutionContext(input.execution);
38
+ const body = { prompt: input.prompt, idempotency_key: magnus && !UUID.test(key) ? uuidFromKey(key) : key, ...(input.sessionId !== undefined ? { session_id: input.sessionId } : {}) };
39
+ return connection.action({ path: 'tasks', body, magnus: { action: 'task-submit', body }, execution, effect: 'idempotent',
40
+ headers: executionHeaders(execution) }, input.signal);
41
+ },
42
+ get: async (id, call) => read(`tasks/${segment(id, 'task ID')}`, call),
43
+ list: async (call = {}) => (await read('tasks', call, { query: { limit: call.limit } })).tasks,
44
+ events: async (id, call = {}) => (await read(`tasks/${segment(id, 'task ID')}/events`, call, { query: { after: call.after } })).events,
45
+ cancel: async (id, call) => connection.action({ path: `tasks/${segment(id, 'task ID')}/cancel`, magnus: { action: 'task-cancel', target: id }, effect: 'idempotent' }, call?.signal),
46
+ pause: async (id, call) => connection.action({ path: `tasks/${segment(id, 'task ID')}/pause`, magnus: { action: 'task-pause', target: id }, effect: 'idempotent' }, call?.signal),
47
+ resume: async (id, call) => connection.action({ path: `tasks/${segment(id, 'task ID')}/resume`, magnus: { action: 'task-resume', target: id }, effect: 'idempotent' }, call?.signal),
48
+ async follow(id, follow = {}) {
49
+ segment(id, 'task ID');
50
+ await followTask(connection, id, follow);
51
+ return tasks.get(id, follow.signal ? { signal: follow.signal } : {});
52
+ },
53
+ };
54
+ const sessions = {
55
+ list: async (call = {}) => (await read('sessions', call, { query: { context: call.context } })).sessions,
56
+ async open(key, call = {}) {
57
+ const body = { key, ...(call.reset !== undefined ? { reset: call.reset } : {}), ...(call.context !== undefined ? { context: call.context } : {}) };
58
+ return connection.action({ path: 'sessions', body, magnus: { action: 'session-open', body }, effect: call.reset ? 'unknown' : 'idempotent' }, call.signal);
59
+ },
60
+ messages: async (id, call) => (await read(`sessions/${segment(id, 'session ID')}/messages`, call)).messages,
61
+ };
62
+ const recovery = {
63
+ async get(id, call) {
64
+ try {
65
+ return await read(`tasks/${segment(id, 'task ID')}/recovery`, call, { gate: 'recovery' });
66
+ }
67
+ catch (error) {
68
+ // Ardent answers 404 both for a missing task and for one that was never interrupted.
69
+ if (!(error instanceof NotFoundError))
70
+ throw error;
71
+ const task = await tasks.get(id, call);
72
+ return task.recovery ?? null;
73
+ }
74
+ },
75
+ async decide(id, decision, call) {
76
+ const body = { action: decision.action, ...(decision.callId !== undefined ? { call_id: decision.callId } : {}),
77
+ ...(decision.result !== undefined ? { result: decision.result } : {}), ...(decision.note !== undefined ? { note: decision.note } : {}),
78
+ ...(decision.deadlineSeconds !== undefined ? { deadline_seconds: decision.deadlineSeconds } : {}) };
79
+ return connection.action({ path: `tasks/${segment(id, 'task ID')}/recovery`, body, gate: 'recovery',
80
+ magnus: { action: 'task-recovery', target: id, body }, effect: 'idempotent' }, call?.signal);
81
+ },
82
+ };
83
+ const renditions = async (sha, call) => (await read(`artifacts/${digest(sha)}/renditions`, call, { gate: 'artifact_transfer' })).renditions;
84
+ async function manifest(sha, call = {}) {
85
+ return call.v2 ? read(`artifacts/${digest(sha)}/manifest/v2`, call, { gate: 'artifact_transfer' })
86
+ : read(`artifacts/${digest(sha)}/manifest`, call);
87
+ }
88
+ const artifacts = {
89
+ list: async (taskId, call) => (await read(`tasks/${segment(taskId, 'task ID')}/artifacts`, call)).artifacts,
90
+ manifest,
91
+ renditions,
92
+ download: async (sha, download = {}) => downloadArtifact(connection, sha, download, (original, signal) => renditions(original, signal ? { signal } : {})),
93
+ import: (request, call) => connection.action({ path: 'artifacts/imports', body: request, gate: 'artifact_transfer',
94
+ magnus: { action: 'artifact-import', body: request }, effect: 'unknown' }, call?.signal),
95
+ imports: async (call = {}) => (await read('artifacts/imports', call, { gate: 'artifact_transfer', query: { limit: call.limit } })).imports,
96
+ importStatus: async (id, call) => read(`artifacts/imports/${segment(id, 'import ID')}`, call, { gate: 'artifact_transfer' }),
97
+ };
98
+ const status = (call) => read('status', call);
99
+ return {
100
+ tasks, sessions, recovery, artifacts, status,
101
+ lineage: async (id, call) => read(`tasks/${segment(id, 'task ID')}/lineage`, call, { gate: 'lineage' }),
102
+ async capabilities(call) {
103
+ const current = await status(call);
104
+ const transfer = typeof current.capabilities?.artifact_transfer === 'number' ? current.capabilities.artifact_transfer : 1;
105
+ // Recovery counts came with recovery, lineage and execution ancestry.
106
+ const runtime = { recovery: current.recovery !== undefined, transfer: transfer >= 2 };
107
+ const report = await connection.magnusReport();
108
+ const via = async (gate) => !magnus || await connection.advertises(gate);
109
+ const [recoveryRoute, lineageRoute, transferRoute] = await Promise.all([via('recovery'), via('lineage'), via('artifact_transfer')]);
110
+ return {
111
+ transport: connection.kind, version: current.version, profile: current.profile, backend: current.backend, artifactTransfer: transfer,
112
+ features: {
113
+ recovery: runtime.recovery && recoveryRoute, lineage: runtime.recovery && lineageRoute, execution: runtime.recovery && lineageRoute,
114
+ artifactContent: runtime.transfer && transferRoute, renditions: runtime.transfer && transferRoute, imports: runtime.transfer && transferRoute,
115
+ },
116
+ ...(report?.capabilities ? { magnus: { capabilities: report.capabilities, installedVersion: report.version } } : {}),
117
+ };
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,41 @@
1
+ import { type RenditionRequest } from '@hivemagnus/hive-common/artifact';
2
+ import { type Connection } from './transport.js';
3
+ import type { ArtifactRendition } from './types.js';
4
+ /** Bytes of an earlier, interrupted download of the same artifact, from its first byte. */
5
+ export type ResumeSource = Blob | ArrayBuffer | ArrayBufferView | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
6
+ export interface DownloadProgress {
7
+ /** Bytes of the artifact received, including those from `resumeFrom`. */
8
+ readonly received: number;
9
+ readonly total: number;
10
+ /** Times the transfer was resumed after a dropped connection. */
11
+ readonly resumes: number;
12
+ }
13
+ export interface DownloadOptions {
14
+ /** Pick a rendition (preview, model input) instead of the original; `download` always resolves to the original. */
15
+ readonly rendition?: RenditionRequest;
16
+ /**
17
+ * The bytes you already hold from an interrupted download of this artifact. They are hashed
18
+ * again as a stream, and the transfer continues after them with `Range` and `If-Range`, so
19
+ * the final digest still covers the whole file.
20
+ */
21
+ readonly resumeFrom?: ResumeSource;
22
+ readonly onProgress?: (progress: DownloadProgress) => void;
23
+ readonly signal?: AbortSignal;
24
+ /** Resumptions after dropped connections before the download fails. Default 5. */
25
+ readonly maxResumes?: number;
26
+ }
27
+ export interface ArtifactDownload {
28
+ /**
29
+ * The bytes after `offset`. It closes only after the whole file hashed to `sha256`; on a
30
+ * mismatch it errors with `DigestMismatchError`, and the bytes must be discarded.
31
+ */
32
+ readonly stream: ReadableStream<Uint8Array>;
33
+ /** The digest of the bytes being downloaded (the chosen rendition's, when one was asked for). */
34
+ readonly sha256: string;
35
+ readonly size: number;
36
+ /** Bytes taken from `resumeFrom`; the stream starts after them. */
37
+ readonly offset: number;
38
+ readonly mime: string;
39
+ readonly filename: string | undefined;
40
+ }
41
+ export declare function downloadArtifact(connection: Connection, sha: string, options: DownloadOptions, renditions: (sha: string, signal?: AbortSignal) => Promise<ArtifactRendition[]>): Promise<ArtifactDownload>;
@@ -0,0 +1,185 @@
1
+ import { backoffDelay, sleepAbortable } from '@hivemagnus/hive-common/retry';
2
+ import { parseReprDigest, selectRendition } from '@hivemagnus/hive-common/artifact';
3
+ import { anySignal } from './transport.js';
4
+ import { ArdentClientError, DigestMismatchError, NotFoundError, TransportError } from './errors.js';
5
+ import { Sha256 } from './sha256.js';
6
+ async function* read(stream) {
7
+ // Readers rather than async iteration: not every browser iterates a ReadableStream.
8
+ const reader = stream.getReader();
9
+ try {
10
+ for (;;) {
11
+ const { done, value } = await reader.read();
12
+ if (done)
13
+ return;
14
+ yield value;
15
+ }
16
+ }
17
+ finally {
18
+ reader.releaseLock();
19
+ }
20
+ }
21
+ function isAsyncIterable(value) {
22
+ return typeof value === 'object' && value !== null && Symbol.asyncIterator in value;
23
+ }
24
+ async function* chunks(source) {
25
+ if (source instanceof ArrayBuffer)
26
+ yield new Uint8Array(source);
27
+ else if (ArrayBuffer.isView(source))
28
+ yield new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
29
+ else if (source instanceof ReadableStream)
30
+ yield* read(source);
31
+ else if (typeof Blob !== 'undefined' && source instanceof Blob)
32
+ yield* read(source.stream());
33
+ else if (isAsyncIterable(source))
34
+ yield* source;
35
+ else
36
+ throw new ArdentClientError('invalid_request', 'resumeFrom must be a Blob, ArrayBuffer, typed array, ReadableStream or async iterable', { status: 400 });
37
+ }
38
+ function contentRange(value) {
39
+ const partial = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(value ?? '');
40
+ if (partial)
41
+ return { start: Number(partial[1]), end: Number(partial[2]), size: Number(partial[3]) };
42
+ const unsatisfied = /^bytes \*\/(\d+)$/.exec(value ?? '');
43
+ return unsatisfied ? { size: Number(unsatisfied[1]) } : undefined;
44
+ }
45
+ function filename(disposition) {
46
+ const match = /filename="((?:[^"\\]|\\.)*)"/i.exec(disposition ?? '');
47
+ return match ? match[1].replace(/\\(.)/g, '$1') : undefined;
48
+ }
49
+ export async function downloadArtifact(connection, sha, options, renditions) {
50
+ if (!/^[a-f0-9]{64}$/.test(sha))
51
+ throw new ArdentClientError('invalid_request', 'An artifact is named by its lowercase hex SHA-256', { status: 400 });
52
+ const signal = anySignal(connection.signal, options.signal);
53
+ let target = sha;
54
+ if (options.rendition) {
55
+ const chosen = selectRendition(await renditions(sha, signal), options.rendition);
56
+ if (!chosen)
57
+ throw new NotFoundError('NOT_FOUND', 'No rendition of the artifact fits the request', { status: 404 });
58
+ target = chosen.sha256;
59
+ }
60
+ const hash = new Sha256();
61
+ if (options.resumeFrom !== undefined)
62
+ for await (const chunk of chunks(options.resumeFrom)) {
63
+ if (signal?.aborted)
64
+ throw signal.reason;
65
+ hash.update(chunk);
66
+ }
67
+ const offset = hash.length;
68
+ const url = connection.url(`artifacts/${target}/content`);
69
+ const etag = `"${target}"`;
70
+ const open = async (from) => {
71
+ const response = await connection.raw({ url, gate: 'artifact_transfer', allow: [416], signal,
72
+ headers: from > 0 ? { range: `bytes=${from}-`, 'if-range': etag } : {} });
73
+ const declared = response.headers.get('x-content-sha256') ?? parseReprDigest(response.headers.get('repr-digest'));
74
+ if (declared && declared !== target) {
75
+ await response.body?.cancel().catch(() => undefined);
76
+ throw new DigestMismatchError(target, declared);
77
+ }
78
+ const range = contentRange(response.headers.get('content-range'));
79
+ if (response.status === 416) {
80
+ await response.body?.cancel().catch(() => undefined);
81
+ if (!range || range.size !== from)
82
+ throw new ArdentClientError('RANGE_NOT_SATISFIABLE', 'The artifact is shorter than the bytes already held', { status: 416 });
83
+ return { response: undefined, size: range.size, skip: 0 };
84
+ }
85
+ if (response.status === 206) {
86
+ if (!range || !('start' in range) || range.start !== from) {
87
+ await response.body?.cancel().catch(() => undefined);
88
+ throw new TransportError('invalid_response', 'The server answered a different byte range', { status: 502 });
89
+ }
90
+ return { response, size: range.size, skip: 0 };
91
+ }
92
+ // A whole representation: the server ignored the range, so skip the bytes already held.
93
+ const length = Number(response.headers.get('content-length') ?? NaN);
94
+ return { response, size: Number.isSafeInteger(length) ? length : -1, skip: from };
95
+ };
96
+ const first = await open(offset);
97
+ const size = first.size;
98
+ if (size >= 0 && offset > size)
99
+ throw new ArdentClientError('RANGE_NOT_SATISFIABLE', 'The artifact is shorter than the bytes already held', { status: 416 });
100
+ const mime = first.response?.headers.get('content-type') ?? 'application/octet-stream';
101
+ const name = filename(first.response?.headers.get('content-disposition') ?? null);
102
+ const maxResumes = options.maxResumes ?? 5;
103
+ let position = offset;
104
+ let resumes = 0;
105
+ let failuresWithoutProgress = 0;
106
+ let current = { reader: first.response?.body?.getReader(), skip: first.skip };
107
+ let finished = false;
108
+ const finish = (controller) => {
109
+ finished = true;
110
+ const actual = hash.hex();
111
+ if (actual !== target)
112
+ controller.error(new DigestMismatchError(target, actual));
113
+ else
114
+ controller.close();
115
+ };
116
+ const resume = async (cause) => {
117
+ await current.reader?.cancel().catch(() => undefined);
118
+ current = { reader: undefined, skip: 0 };
119
+ if (signal?.aborted)
120
+ throw signal.reason;
121
+ if (resumes >= maxResumes || failuresWithoutProgress >= 3)
122
+ throw new TransportError('download_interrupted', `The download was interrupted ${resumes + 1} times`, { status: 503, cause });
123
+ resumes++;
124
+ failuresWithoutProgress++;
125
+ const delay = backoffDelay(failuresWithoutProgress, { ...connection.retryPolicy, maxAttempts: Number.MAX_SAFE_INTEGER }) ?? connection.retryPolicy.maxMs;
126
+ await sleepAbortable(delay, signal);
127
+ const next = await open(position);
128
+ current = { reader: next.response?.body?.getReader(), skip: next.skip };
129
+ };
130
+ const stream = new ReadableStream({
131
+ pull: async (controller) => {
132
+ for (;;) {
133
+ if (finished)
134
+ return;
135
+ if (!current.reader) {
136
+ if (size >= 0 && position === size) {
137
+ finish(controller);
138
+ return;
139
+ }
140
+ await resume(new Error('No response body'));
141
+ continue;
142
+ }
143
+ let read;
144
+ try {
145
+ read = await current.reader.read();
146
+ }
147
+ catch (error) {
148
+ if (signal?.aborted)
149
+ throw signal.reason;
150
+ await resume(error);
151
+ continue;
152
+ }
153
+ if (read.done) {
154
+ if (size < 0 || position === size) {
155
+ finish(controller);
156
+ return;
157
+ }
158
+ // A body that ended early is a dropped transfer.
159
+ await resume(new Error('The response ended early'));
160
+ continue;
161
+ }
162
+ let chunk = read.value;
163
+ if (current.skip) {
164
+ const skipped = Math.min(current.skip, chunk.length);
165
+ current.skip -= skipped;
166
+ chunk = chunk.subarray(skipped);
167
+ if (!chunk.length)
168
+ continue;
169
+ }
170
+ if (size >= 0 && position + chunk.length > size) {
171
+ await current.reader.cancel().catch(() => undefined);
172
+ throw new TransportError('invalid_response', 'The artifact is longer than its declared size', { status: 502 });
173
+ }
174
+ hash.update(chunk);
175
+ position += chunk.length;
176
+ failuresWithoutProgress = 0;
177
+ options.onProgress?.({ received: position, total: size, resumes });
178
+ controller.enqueue(chunk);
179
+ return;
180
+ }
181
+ },
182
+ cancel: async (reason) => { finished = true; await current.reader?.cancel(reason).catch(() => undefined); },
183
+ });
184
+ return { stream, sha256: target, size, offset, mime, filename: name };
185
+ }
@@ -0,0 +1,59 @@
1
+ import { HiveError, type HiveErrorOptions } from '@hivemagnus/hive-common/errors';
2
+ /**
3
+ * Every error the client raises. It is a `HiveError`, so `status`, `code`, `details` and
4
+ * `requestId` follow the suite error envelope, and `HiveError.is(error, code)` works across
5
+ * package copies.
6
+ */
7
+ export declare class ArdentClientError extends HiveError {
8
+ readonly name: string;
9
+ constructor(code: string, message: string, options?: HiveErrorOptions);
10
+ }
11
+ /** The token was refused, also after `getToken()` was asked for a fresh one. */
12
+ export declare class UnauthorizedError extends ArdentClientError {
13
+ readonly name: string;
14
+ }
15
+ /** The task, session, artifact or recovery does not exist. */
16
+ export declare class NotFoundError extends ArdentClientError {
17
+ readonly name: string;
18
+ }
19
+ /**
20
+ * The request conflicts with the current state: a finished task cannot pause, a recovery was
21
+ * decided differently, or (`idempotency: true`) the idempotency key was already used for a
22
+ * different task.
23
+ */
24
+ export declare class ConflictError extends ArdentClientError {
25
+ readonly name: string;
26
+ readonly idempotency: boolean;
27
+ constructor(code: string, message: string, options?: HiveErrorOptions & {
28
+ idempotency?: boolean;
29
+ });
30
+ }
31
+ /**
32
+ * The route is not available through this transport: Magnus does not allow it yet, or the
33
+ * profile runs an Ardent that predates it. `capability` names what is missing.
34
+ */
35
+ export declare class UnsupportedCapabilityError extends ArdentClientError {
36
+ readonly name: string;
37
+ readonly capability: string;
38
+ readonly requiredVersion: string | undefined;
39
+ readonly installedVersion: string | undefined;
40
+ constructor(capability: string, message: string, options?: HiveErrorOptions & {
41
+ requiredVersion?: string | undefined;
42
+ installedVersion?: string | undefined;
43
+ });
44
+ }
45
+ /**
46
+ * The request did not complete: a network failure, a dropped stream that could not be
47
+ * resumed, an unavailable dependency (502, 503, 504) or a response that is not what the API
48
+ * documents.
49
+ */
50
+ export declare class TransportError extends ArdentClientError {
51
+ readonly name: string;
52
+ }
53
+ /** The downloaded bytes do not hash to the artifact's SHA-256. Discard them. */
54
+ export declare class DigestMismatchError extends ArdentClientError {
55
+ readonly name: string;
56
+ readonly expected: string;
57
+ readonly actual: string;
58
+ constructor(expected: string, actual: string, options?: HiveErrorOptions);
59
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,68 @@
1
+ import { HiveError } from '@hivemagnus/hive-common/errors';
2
+ /**
3
+ * Every error the client raises. It is a `HiveError`, so `status`, `code`, `details` and
4
+ * `requestId` follow the suite error envelope, and `HiveError.is(error, code)` works across
5
+ * package copies.
6
+ */
7
+ export class ArdentClientError extends HiveError {
8
+ name = 'ArdentClientError';
9
+ constructor(code, message, options = {}) {
10
+ super(code, message, options);
11
+ }
12
+ }
13
+ /** The token was refused, also after `getToken()` was asked for a fresh one. */
14
+ export class UnauthorizedError extends ArdentClientError {
15
+ name = 'UnauthorizedError';
16
+ }
17
+ /** The task, session, artifact or recovery does not exist. */
18
+ export class NotFoundError extends ArdentClientError {
19
+ name = 'NotFoundError';
20
+ }
21
+ /**
22
+ * The request conflicts with the current state: a finished task cannot pause, a recovery was
23
+ * decided differently, or (`idempotency: true`) the idempotency key was already used for a
24
+ * different task.
25
+ */
26
+ export class ConflictError extends ArdentClientError {
27
+ name = 'ConflictError';
28
+ idempotency;
29
+ constructor(code, message, options = {}) {
30
+ super(code, message, options);
31
+ this.idempotency = options.idempotency ?? false;
32
+ }
33
+ }
34
+ /**
35
+ * The route is not available through this transport: Magnus does not allow it yet, or the
36
+ * profile runs an Ardent that predates it. `capability` names what is missing.
37
+ */
38
+ export class UnsupportedCapabilityError extends ArdentClientError {
39
+ name = 'UnsupportedCapabilityError';
40
+ capability;
41
+ requiredVersion;
42
+ installedVersion;
43
+ constructor(capability, message, options = {}) {
44
+ super('unsupported_capability', message, { ...options, details: { capability, ...options.details } });
45
+ this.capability = capability;
46
+ this.requiredVersion = options.requiredVersion;
47
+ this.installedVersion = options.installedVersion;
48
+ }
49
+ }
50
+ /**
51
+ * The request did not complete: a network failure, a dropped stream that could not be
52
+ * resumed, an unavailable dependency (502, 503, 504) or a response that is not what the API
53
+ * documents.
54
+ */
55
+ export class TransportError extends ArdentClientError {
56
+ name = 'TransportError';
57
+ }
58
+ /** The downloaded bytes do not hash to the artifact's SHA-256. Discard them. */
59
+ export class DigestMismatchError extends ArdentClientError {
60
+ name = 'DigestMismatchError';
61
+ expected;
62
+ actual;
63
+ constructor(expected, actual, options = {}) {
64
+ super('DIGEST_MISMATCH', 'The downloaded artifact does not match its SHA-256', { status: 502, ...options, details: { expected, actual } });
65
+ this.expected = expected;
66
+ this.actual = actual;
67
+ }
68
+ }
@@ -0,0 +1,26 @@
1
+ import { type Connection } from './transport.js';
2
+ import type { TaskEvent, TaskText } from './types.js';
3
+ export interface FollowOptions {
4
+ /** Resume after this event sequence (the `sequence` of the last event you handled). */
5
+ readonly after?: number;
6
+ /** Every journaled event, in order, exactly once across reconnects. */
7
+ readonly onEvent?: (event: TaskEvent) => void | Promise<void>;
8
+ /**
9
+ * Live reply text. It is not journaled: after a reconnect a `text` snapshot of the current
10
+ * step replaces what `delta`s built up.
11
+ */
12
+ readonly onText?: (text: TaskText) => void | Promise<void>;
13
+ /** Called on every (re)connection with the cursor it resumes from. */
14
+ readonly onConnect?: (cursor: number | undefined, reconnect: number) => void;
15
+ readonly signal?: AbortSignal;
16
+ }
17
+ /**
18
+ * Follow a task's event stream until `task.done`. Ardent closes a stream after 60 seconds
19
+ * and a network may drop it; both reconnect from the last event sequence (`after` and
20
+ * `Last-Event-ID`), so no journaled event is lost or repeated. Resolves with the task's state
21
+ * in `task.done`.
22
+ */
23
+ export declare function followTask(connection: Connection, id: string, options: FollowOptions): Promise<{
24
+ id: string;
25
+ state: string;
26
+ }>;
package/dist/follow.js ADDED
@@ -0,0 +1,90 @@
1
+ import { followSse, SseStatusError } from '@hivemagnus/hive-common/sse';
2
+ import { anySignal, isRecord } from './transport.js';
3
+ import { ArdentClientError, NotFoundError, TransportError } from './errors.js';
4
+ const PERMANENT = (status) => status !== 408 && status !== 429 && status < 500;
5
+ function parse(data) {
6
+ let value;
7
+ try {
8
+ value = JSON.parse(data);
9
+ }
10
+ catch (error) {
11
+ throw new TransportError('invalid_response', 'The task stream sent an event that is not JSON', { status: 502, cause: error });
12
+ }
13
+ if (!isRecord(value))
14
+ throw new TransportError('invalid_response', 'The task stream sent an event that is not a JSON object', { status: 502 });
15
+ return value;
16
+ }
17
+ function isTaskEvent(value) {
18
+ return typeof value['sequence'] === 'number' && typeof value['task_id'] === 'string' && typeof value['kind'] === 'string' && typeof value['created_ms'] === 'number';
19
+ }
20
+ /**
21
+ * Follow a task's event stream until `task.done`. Ardent closes a stream after 60 seconds
22
+ * and a network may drop it; both reconnect from the last event sequence (`after` and
23
+ * `Last-Event-ID`), so no journaled event is lost or repeated. Resolves with the task's state
24
+ * in `task.done`.
25
+ */
26
+ export async function followTask(connection, id, options) {
27
+ const signal = anySignal(connection.signal, options.signal);
28
+ let cursor = options.after !== undefined ? String(options.after) : undefined;
29
+ let refresh = false;
30
+ let refreshed = false;
31
+ for (;;) {
32
+ let refusal;
33
+ try {
34
+ const result = await followSse(connection.url(`tasks/${encodeURIComponent(id)}/stream`), {
35
+ headers: async () => { const headers = await connection.headers(refresh); refresh = false; return headers; },
36
+ ...(cursor !== undefined ? { after: cursor } : {}),
37
+ cursorParam: 'after',
38
+ ...(signal ? { signal } : {}),
39
+ policy: connection.retryPolicy,
40
+ // A permanent refusal keeps its mapped error (the SSE helper only reports the status).
41
+ fetch: async (url, init) => {
42
+ const response = await connection.fetcher(url, { ...init, redirect: 'error' });
43
+ if (response.ok || !PERMANENT(response.status))
44
+ return response;
45
+ refusal = await connection.error(response);
46
+ return new Response(null, { status: response.status });
47
+ },
48
+ ...(options.onConnect ? { onConnect: (from, reconnect) => options.onConnect?.(from === undefined ? undefined : Number(from), reconnect) } : {}),
49
+ onEvent: async (event) => {
50
+ if (event.id !== undefined)
51
+ cursor = event.id;
52
+ if (event.event === 'task.event') {
53
+ const value = parse(event.data);
54
+ if (!isTaskEvent(value))
55
+ throw new TransportError('invalid_response', 'The task stream sent a malformed event', { status: 502 });
56
+ await options.onEvent?.(value);
57
+ }
58
+ else if (event.event === 'task.text' || event.event === 'task.delta') {
59
+ const value = parse(event.data);
60
+ if (typeof value['step'] !== 'number' || typeof value['text'] !== 'string')
61
+ throw new TransportError('invalid_response', 'The task stream sent malformed text', { status: 502 });
62
+ await options.onText?.({ kind: event.event === 'task.text' ? 'text' : 'delta', step: value['step'], text: value['text'] });
63
+ }
64
+ },
65
+ isTerminal: event => event.event === 'task.done',
66
+ });
67
+ const done = result.terminal ? parse(result.terminal.data) : undefined;
68
+ if (!done || typeof done['state'] !== 'string')
69
+ throw new TransportError('invalid_response', 'The task stream ended without a final state', { status: 502 });
70
+ if (done['state'] === 'missing')
71
+ throw new NotFoundError('NOT_FOUND', 'Task not found', { status: 404 });
72
+ return { id, state: done['state'] };
73
+ }
74
+ catch (error) {
75
+ if (signal?.aborted)
76
+ throw error;
77
+ if (error instanceof SseStatusError) {
78
+ if (error.status === 401 && !refreshed) {
79
+ refreshed = true;
80
+ refresh = true;
81
+ continue;
82
+ }
83
+ throw refusal ?? new ArdentClientError('stream_refused', error.message, { status: error.status });
84
+ }
85
+ if (error instanceof ArdentClientError)
86
+ throw error;
87
+ throw new TransportError('stream_failed', `The task stream could not be resumed: ${error instanceof Error ? error.message : String(error)}`, { status: 503, cause: error });
88
+ }
89
+ }
90
+ }