@almyty/client 1.5.6 → 1.5.8
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/README.md +23 -0
- package/dist/client.d.ts +81 -3
- package/dist/client.js +230 -13
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -22,6 +22,29 @@ const agents = await client.listAgents();
|
|
|
22
22
|
- `getOrgSlugFromToken(token)` -- extract org slug from JWT
|
|
23
23
|
- `loadCredentials()` -- raw file read
|
|
24
24
|
- `CREDENTIALS_FILE` -- path to `~/.almyty/credentials.json`
|
|
25
|
+
- `isPermanentStreamError(err)` -- whether a run stream failed in a way a retry would not change
|
|
26
|
+
|
|
27
|
+
## Following a run
|
|
28
|
+
|
|
29
|
+
`client.followRun(agentId, runId, handler, signal?, options?)` and the gateway's
|
|
30
|
+
`gw.streamRun(runId, handler, signal?, options?)` keep watching a run until it ends.
|
|
31
|
+
If the connection drops, they reconnect by themselves and carry on where they left
|
|
32
|
+
off: each event reaches `handler` once and in order, and `options.onLog` gets the
|
|
33
|
+
run's history one event at a time. If the run is gone, or not yours to see, they
|
|
34
|
+
stop at once and throw an error with its `status` (400, 401, 403, 404 or 410);
|
|
35
|
+
anything else (a network error, a server error) is retried a few times, waiting a
|
|
36
|
+
little longer each time.
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
const run = await client.followRun(agentId, runId, (event) => {
|
|
40
|
+
if (event.type === 'llm.chunk') process.stdout.write(String(event.data.content));
|
|
41
|
+
}, undefined, {
|
|
42
|
+
onLog: (logged) => console.error(`#${logged.seq} ${logged.type}`),
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
To pick up a run you were already following, pass the position you had:
|
|
47
|
+
`{ afterSeq, livePos }`, which `followRunStream` returns and `onReconnect` reports.
|
|
25
48
|
|
|
26
49
|
## About almyty
|
|
27
50
|
|
package/dist/client.d.ts
CHANGED
|
@@ -95,6 +95,45 @@ export declare function isAbortError(err: unknown): boolean;
|
|
|
95
95
|
* reply used to arrive as one block once the run had already finished.
|
|
96
96
|
*/
|
|
97
97
|
export declare function parseSseFrame(lines: string[]): StreamEvent | null;
|
|
98
|
+
/** One event of a run's log, as the run stream sends it (`run.log`). */
|
|
99
|
+
export interface RunLogEvent {
|
|
100
|
+
seq: number;
|
|
101
|
+
type: string;
|
|
102
|
+
step: number | null;
|
|
103
|
+
payload: Record<string, any>;
|
|
104
|
+
createdAt?: string;
|
|
105
|
+
}
|
|
106
|
+
/** Where a run stream got to: the last logged event's seq, the last runtime event's place. */
|
|
107
|
+
export interface RunStreamPosition {
|
|
108
|
+
afterSeq: number;
|
|
109
|
+
livePos: string;
|
|
110
|
+
}
|
|
111
|
+
export interface RunStreamOptions {
|
|
112
|
+
/** Resume after this logged event. Default 0: the run's whole log. */
|
|
113
|
+
afterSeq?: number;
|
|
114
|
+
/** Resume after this runtime event's place (`pos`). Default `0`: every one from the run's start. */
|
|
115
|
+
livePos?: string;
|
|
116
|
+
/** Each logged event, once, in seq order. */
|
|
117
|
+
onLog?: (event: RunLogEvent) => void;
|
|
118
|
+
/** Stop once the log shows the run waiting on a person, as pollRun does. */
|
|
119
|
+
stopOnWaitingInput?: boolean;
|
|
120
|
+
/** Waits before each retry after a failed connection, in ms; one entry per retry. */
|
|
121
|
+
retryDelaysMs?: number[];
|
|
122
|
+
/** Before each reconnect: where from, after how long, and what failed, if anything did. */
|
|
123
|
+
onReconnect?: (info: RunStreamPosition & {
|
|
124
|
+
delayMs: number;
|
|
125
|
+
error?: unknown;
|
|
126
|
+
}) => void;
|
|
127
|
+
}
|
|
128
|
+
/** Waits before each retry of a run stream that failed, in ms. */
|
|
129
|
+
export declare const RUN_STREAM_RETRY_DELAYS_MS: number[];
|
|
130
|
+
/**
|
|
131
|
+
* Answers that will not change on a retry: a bad position (400), not
|
|
132
|
+
* signed in or not allowed (401, 403), the run is gone (404, 410). A
|
|
133
|
+
* network error or a 5xx is worth retrying.
|
|
134
|
+
*/
|
|
135
|
+
export declare const PERMANENT_STREAM_STATUSES: ReadonlyArray<number>;
|
|
136
|
+
export declare function isPermanentStreamError(err: unknown): boolean;
|
|
98
137
|
export declare class AlmytyClient {
|
|
99
138
|
private readonly baseUrl;
|
|
100
139
|
private readonly token;
|
|
@@ -109,6 +148,32 @@ export declare class AlmytyClient {
|
|
|
109
148
|
* omitted, this is a GET.
|
|
110
149
|
*/
|
|
111
150
|
streamSSE(path: string, handler: StreamEventHandler, signal?: AbortSignal, init?: RequestInit): Promise<void>;
|
|
151
|
+
/**
|
|
152
|
+
* Read an SSE endpoint a frame (its lines) at a time until the server
|
|
153
|
+
* ends it or `onFrame` returns true. A non-2xx answer throws with its
|
|
154
|
+
* `status`.
|
|
155
|
+
*/
|
|
156
|
+
private readSseFrames;
|
|
157
|
+
/**
|
|
158
|
+
* Follow a run's stream until the run ends, picking up where it left
|
|
159
|
+
* off whenever the connection drops or the server ends it at its time
|
|
160
|
+
* limit. `path` is the run's stream: `/agents/:id/runs/:runId/stream`,
|
|
161
|
+
* or the gateway's `/:org/:agent/runs/:runId/stream`.
|
|
162
|
+
*
|
|
163
|
+
* Every connection names where the last one got to: the seq of the last
|
|
164
|
+
* logged event (`?after=`) and the place of the last runtime event
|
|
165
|
+
* (`?live=`). The server sends what came after both, so `handler` sees
|
|
166
|
+
* each runtime event (tokens, tool progress, the run's end) once and in
|
|
167
|
+
* order, and `onLog` each logged event once, in seq order. A logged
|
|
168
|
+
* event that skips ahead means one was missed: the connection is opened
|
|
169
|
+
* again from the last one applied.
|
|
170
|
+
*
|
|
171
|
+
* A network error or a 5xx is retried with backoff (`retryDelaysMs`); a
|
|
172
|
+
* 400, 401, 403, 404 or 410 will not change on a retry and is thrown
|
|
173
|
+
* (isPermanentStreamError). Resolves with the position reached once the
|
|
174
|
+
* run has ended (or, with `stopOnWaitingInput`, waits on a person).
|
|
175
|
+
*/
|
|
176
|
+
followRunStream(path: string, handler: StreamEventHandler, signal?: AbortSignal, options?: RunStreamOptions): Promise<RunStreamPosition>;
|
|
112
177
|
private unwrap;
|
|
113
178
|
listAgents(): Promise<AgentInfo[]>;
|
|
114
179
|
getAgent(id: string): Promise<AgentInfo>;
|
|
@@ -129,6 +194,14 @@ export declare class AlmytyClient {
|
|
|
129
194
|
}>;
|
|
130
195
|
sendRunInput(agentId: string, runId: string, input: string): Promise<void>;
|
|
131
196
|
cancelRun(agentId: string, runId: string): Promise<void>;
|
|
197
|
+
/**
|
|
198
|
+
* Follow a run as it goes: its logged events (`options.onLog`, each
|
|
199
|
+
* once, in seq order) and its live events (`handler`), until it ends,
|
|
200
|
+
* reconnecting where it left off when the connection drops. Resolves
|
|
201
|
+
* with the run as it ended. Throws on an answer a retry would not change
|
|
202
|
+
* (isPermanentStreamError: the run is gone, or not yours to see).
|
|
203
|
+
*/
|
|
204
|
+
followRun(agentId: string, runId: string, handler: StreamEventHandler, signal?: AbortSignal, options?: RunStreamOptions): Promise<AgentRun>;
|
|
132
205
|
/**
|
|
133
206
|
* Poll a run until it reaches a terminal status (or waiting_input).
|
|
134
207
|
*/
|
|
@@ -190,11 +263,16 @@ export declare class GatewayClient {
|
|
|
190
263
|
/**
|
|
191
264
|
* Stream run events via SSE. Calls handler for each event
|
|
192
265
|
* (llm.started, llm.chunk, llm.response, tool.started, tool.result,
|
|
193
|
-
* step.completed, run.completed, run.failed).
|
|
266
|
+
* step.completed, run.completed, run.failed), each once and in order.
|
|
194
267
|
* Returns when the run completes or fails.
|
|
195
|
-
*
|
|
268
|
+
*
|
|
269
|
+
* A dropped connection is picked up where it left off
|
|
270
|
+
* (AlmytyClient.followRunStream); `options` can start from a position a
|
|
271
|
+
* caller already has. An answer that will not change on a retry (the run
|
|
272
|
+
* is gone, or not this key's to see: 400, 401, 403, 404, 410) is thrown.
|
|
273
|
+
* Falls back to polling if the stream keeps failing otherwise.
|
|
196
274
|
*/
|
|
197
|
-
streamRun(runId: string, handler: StreamEventHandler, signal?: AbortSignal): Promise<AgentRun>;
|
|
275
|
+
streamRun(runId: string, handler: StreamEventHandler, signal?: AbortSignal, options?: RunStreamOptions): Promise<AgentRun>;
|
|
198
276
|
getConversationMessages(conversationId: string): Promise<Array<{
|
|
199
277
|
id: string;
|
|
200
278
|
role: string;
|
package/dist/client.js
CHANGED
|
@@ -70,6 +70,69 @@ export function parseSseFrame(lines) {
|
|
|
70
70
|
data: flat,
|
|
71
71
|
};
|
|
72
72
|
}
|
|
73
|
+
/** Waits before each retry of a run stream that failed, in ms. */
|
|
74
|
+
export const RUN_STREAM_RETRY_DELAYS_MS = [500, 1_000, 2_000, 5_000, 10_000];
|
|
75
|
+
/**
|
|
76
|
+
* Answers that will not change on a retry: a bad position (400), not
|
|
77
|
+
* signed in or not allowed (401, 403), the run is gone (404, 410). A
|
|
78
|
+
* network error or a 5xx is worth retrying.
|
|
79
|
+
*/
|
|
80
|
+
export const PERMANENT_STREAM_STATUSES = [400, 401, 403, 404, 410];
|
|
81
|
+
export function isPermanentStreamError(err) {
|
|
82
|
+
const status = err?.status;
|
|
83
|
+
return typeof status === 'number' && PERMANENT_STREAM_STATUSES.includes(status);
|
|
84
|
+
}
|
|
85
|
+
const RUN_ENDED_EVENTS = new Set(['run.completed', 'run.failed', 'run.cancelled']);
|
|
86
|
+
/** The `event:` name of one SSE frame. */
|
|
87
|
+
function sseEventName(lines) {
|
|
88
|
+
for (const line of lines)
|
|
89
|
+
if (line.startsWith('event:'))
|
|
90
|
+
return line.slice(6).trim();
|
|
91
|
+
return 'message';
|
|
92
|
+
}
|
|
93
|
+
/** A `run.log` frame's event, or null when it is not one. */
|
|
94
|
+
function parseRunLogFrame(lines) {
|
|
95
|
+
const data = lines
|
|
96
|
+
.filter((line) => line.startsWith('data:'))
|
|
97
|
+
.map((line) => line.slice(5).replace(/^ /, ''))
|
|
98
|
+
.join('\n');
|
|
99
|
+
try {
|
|
100
|
+
const parsed = JSON.parse(data);
|
|
101
|
+
return parsed && typeof parsed.seq === 'number' && typeof parsed.type === 'string' ? parsed : null;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Order two places on a run's event stream (`0`, or `<ms>-<n>`). */
|
|
108
|
+
function compareStreamPos(a, b) {
|
|
109
|
+
const parts = (pos) => {
|
|
110
|
+
const m = /^(\d+)-(\d+)$/.exec(pos);
|
|
111
|
+
return m ? [Number(m[1]), Number(m[2])] : [0, 0];
|
|
112
|
+
};
|
|
113
|
+
const [am, an] = parts(a);
|
|
114
|
+
const [bm, bn] = parts(b);
|
|
115
|
+
return am !== bm ? am - bm : an - bn;
|
|
116
|
+
}
|
|
117
|
+
function abortError() {
|
|
118
|
+
return Object.assign(new Error('Aborted'), { name: 'AbortError' });
|
|
119
|
+
}
|
|
120
|
+
/** Wait, unless the caller gives up first. */
|
|
121
|
+
function sleep(ms, signal) {
|
|
122
|
+
return new Promise((resolve, reject) => {
|
|
123
|
+
if (signal?.aborted)
|
|
124
|
+
return reject(abortError());
|
|
125
|
+
const timer = setTimeout(() => {
|
|
126
|
+
signal?.removeEventListener('abort', onAbort);
|
|
127
|
+
resolve();
|
|
128
|
+
}, ms);
|
|
129
|
+
const onAbort = () => {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
reject(abortError());
|
|
132
|
+
};
|
|
133
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
134
|
+
});
|
|
135
|
+
}
|
|
73
136
|
export class AlmytyClient {
|
|
74
137
|
baseUrl;
|
|
75
138
|
token;
|
|
@@ -124,6 +187,20 @@ export class AlmytyClient {
|
|
|
124
187
|
* omitted, this is a GET.
|
|
125
188
|
*/
|
|
126
189
|
async streamSSE(path, handler, signal, init = {}) {
|
|
190
|
+
await this.readSseFrames(path, (frame) => {
|
|
191
|
+
const event = parseSseFrame(frame);
|
|
192
|
+
if (!event)
|
|
193
|
+
return false;
|
|
194
|
+
handler(event);
|
|
195
|
+
return TERMINAL_EVENT_TYPES.has(event.type);
|
|
196
|
+
}, signal, init);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Read an SSE endpoint a frame (its lines) at a time until the server
|
|
200
|
+
* ends it or `onFrame` returns true. A non-2xx answer throws with its
|
|
201
|
+
* `status`.
|
|
202
|
+
*/
|
|
203
|
+
async readSseFrames(path, onFrame, signal, init = {}) {
|
|
127
204
|
const url = `${this.baseUrl}${path}`;
|
|
128
205
|
const res = await fetch(url, {
|
|
129
206
|
...init,
|
|
@@ -163,13 +240,10 @@ export class AlmytyClient {
|
|
|
163
240
|
const line = buffer.slice(0, nl).replace(/\r$/, '');
|
|
164
241
|
buffer = buffer.slice(nl + 1);
|
|
165
242
|
if (line === '') {
|
|
166
|
-
const
|
|
243
|
+
const lines = frame;
|
|
167
244
|
frame = [];
|
|
168
|
-
if (
|
|
169
|
-
|
|
170
|
-
if (TERMINAL_EVENT_TYPES.has(event.type))
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
245
|
+
if (lines.length && onFrame(lines))
|
|
246
|
+
return;
|
|
173
247
|
}
|
|
174
248
|
else {
|
|
175
249
|
frame.push(line);
|
|
@@ -181,9 +255,8 @@ export class AlmytyClient {
|
|
|
181
255
|
// frame worth reading.
|
|
182
256
|
if (buffer)
|
|
183
257
|
frame.push(buffer.replace(/\r$/, ''));
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
handler(tail);
|
|
258
|
+
if (frame.length)
|
|
259
|
+
onFrame(frame);
|
|
187
260
|
}
|
|
188
261
|
finally {
|
|
189
262
|
// Releasing the lock does not close the connection. A terminal
|
|
@@ -196,6 +269,131 @@ export class AlmytyClient {
|
|
|
196
269
|
reader.releaseLock();
|
|
197
270
|
}
|
|
198
271
|
}
|
|
272
|
+
/**
|
|
273
|
+
* Follow a run's stream until the run ends, picking up where it left
|
|
274
|
+
* off whenever the connection drops or the server ends it at its time
|
|
275
|
+
* limit. `path` is the run's stream: `/agents/:id/runs/:runId/stream`,
|
|
276
|
+
* or the gateway's `/:org/:agent/runs/:runId/stream`.
|
|
277
|
+
*
|
|
278
|
+
* Every connection names where the last one got to: the seq of the last
|
|
279
|
+
* logged event (`?after=`) and the place of the last runtime event
|
|
280
|
+
* (`?live=`). The server sends what came after both, so `handler` sees
|
|
281
|
+
* each runtime event (tokens, tool progress, the run's end) once and in
|
|
282
|
+
* order, and `onLog` each logged event once, in seq order. A logged
|
|
283
|
+
* event that skips ahead means one was missed: the connection is opened
|
|
284
|
+
* again from the last one applied.
|
|
285
|
+
*
|
|
286
|
+
* A network error or a 5xx is retried with backoff (`retryDelaysMs`); a
|
|
287
|
+
* 400, 401, 403, 404 or 410 will not change on a retry and is thrown
|
|
288
|
+
* (isPermanentStreamError). Resolves with the position reached once the
|
|
289
|
+
* run has ended (or, with `stopOnWaitingInput`, waits on a person).
|
|
290
|
+
*/
|
|
291
|
+
async followRunStream(path, handler, signal, options = {}) {
|
|
292
|
+
const delays = options.retryDelaysMs ?? RUN_STREAM_RETRY_DELAYS_MS;
|
|
293
|
+
let afterSeq = Math.max(0, Math.floor(options.afterSeq ?? 0));
|
|
294
|
+
let livePos = options.livePos ?? '0';
|
|
295
|
+
// Whether this server resumes at all: it sent a logged event or a
|
|
296
|
+
// runtime event's place. One that does not replays its live events
|
|
297
|
+
// from the start on every connection, so once anything has been
|
|
298
|
+
// handed on it is not connected to again.
|
|
299
|
+
let resumable = false;
|
|
300
|
+
let delivered = false;
|
|
301
|
+
let ended = false;
|
|
302
|
+
let failures = 0;
|
|
303
|
+
for (;;) {
|
|
304
|
+
let gap = false;
|
|
305
|
+
let waiting = false;
|
|
306
|
+
let progressed = false;
|
|
307
|
+
const connection = new AbortController();
|
|
308
|
+
const onAbort = () => connection.abort();
|
|
309
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
310
|
+
let failure = null;
|
|
311
|
+
try {
|
|
312
|
+
await this.readSseFrames(`${path}?after=${afterSeq}&live=${encodeURIComponent(livePos)}`, (lines) => {
|
|
313
|
+
if (sseEventName(lines) === 'run.log') {
|
|
314
|
+
const log = parseRunLogFrame(lines);
|
|
315
|
+
if (!log)
|
|
316
|
+
return false;
|
|
317
|
+
resumable = true;
|
|
318
|
+
if (log.seq <= afterSeq)
|
|
319
|
+
return false;
|
|
320
|
+
if (log.seq !== afterSeq + 1) {
|
|
321
|
+
gap = true;
|
|
322
|
+
return true;
|
|
323
|
+
}
|
|
324
|
+
afterSeq = log.seq;
|
|
325
|
+
progressed = true;
|
|
326
|
+
options.onLog?.(log);
|
|
327
|
+
const status = log.type === 'step_committed' ? String(log.payload?.status ?? '') : '';
|
|
328
|
+
// The server sends the rest of the log and closes; read on to it.
|
|
329
|
+
if (TERMINAL_STATUSES.has(status))
|
|
330
|
+
ended = true;
|
|
331
|
+
if (options.stopOnWaitingInput && (status === 'waiting_input' || log.type === 'waiting_input')) {
|
|
332
|
+
waiting = true;
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
const event = parseSseFrame(lines);
|
|
338
|
+
if (!event)
|
|
339
|
+
return false;
|
|
340
|
+
const pos = typeof event.data.pos === 'string' ? event.data.pos : undefined;
|
|
341
|
+
if (pos) {
|
|
342
|
+
resumable = true;
|
|
343
|
+
if (compareStreamPos(pos, livePos) <= 0)
|
|
344
|
+
return false;
|
|
345
|
+
livePos = pos;
|
|
346
|
+
}
|
|
347
|
+
// The server closing this connection, not the run ending.
|
|
348
|
+
if (event.type === 'done' || event.type === 'stream.timeout')
|
|
349
|
+
return false;
|
|
350
|
+
progressed = true;
|
|
351
|
+
delivered = true;
|
|
352
|
+
handler(event);
|
|
353
|
+
if (RUN_ENDED_EVENTS.has(event.type))
|
|
354
|
+
ended = true;
|
|
355
|
+
// A server that cannot resume ends here, as it always did.
|
|
356
|
+
return ended && !resumable;
|
|
357
|
+
}, connection.signal);
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
failure = err;
|
|
361
|
+
}
|
|
362
|
+
finally {
|
|
363
|
+
signal?.removeEventListener('abort', onAbort);
|
|
364
|
+
connection.abort();
|
|
365
|
+
}
|
|
366
|
+
if (signal?.aborted)
|
|
367
|
+
throw failure ?? abortError();
|
|
368
|
+
if (waiting || (ended && !gap))
|
|
369
|
+
return { afterSeq, livePos };
|
|
370
|
+
if (progressed)
|
|
371
|
+
failures = 0;
|
|
372
|
+
if (gap)
|
|
373
|
+
continue;
|
|
374
|
+
if (failure) {
|
|
375
|
+
if (isPermanentStreamError(failure))
|
|
376
|
+
throw failure;
|
|
377
|
+
if (delivered && !resumable)
|
|
378
|
+
throw failure;
|
|
379
|
+
}
|
|
380
|
+
else if (delivered && !resumable) {
|
|
381
|
+
// A server that cannot resume ended the stream: that was all of it.
|
|
382
|
+
return { afterSeq, livePos };
|
|
383
|
+
}
|
|
384
|
+
else if (progressed) {
|
|
385
|
+
// Ended at its time limit with the run still going: straight back.
|
|
386
|
+
options.onReconnect?.({ afterSeq, livePos, delayMs: 0 });
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
if (failures >= delays.length) {
|
|
390
|
+
throw failure ?? Object.assign(new Error('The run stream kept ending without anything new.'), { streamEnded: true });
|
|
391
|
+
}
|
|
392
|
+
const delayMs = delays[failures++];
|
|
393
|
+
options.onReconnect?.({ afterSeq, livePos, delayMs, error: failure ?? undefined });
|
|
394
|
+
await sleep(delayMs, signal);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
199
397
|
unwrap(data) {
|
|
200
398
|
return data?.data ?? data;
|
|
201
399
|
}
|
|
@@ -300,6 +498,17 @@ export class AlmytyClient {
|
|
|
300
498
|
async cancelRun(agentId, runId) {
|
|
301
499
|
await this.request(`/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' });
|
|
302
500
|
}
|
|
501
|
+
/**
|
|
502
|
+
* Follow a run as it goes: its logged events (`options.onLog`, each
|
|
503
|
+
* once, in seq order) and its live events (`handler`), until it ends,
|
|
504
|
+
* reconnecting where it left off when the connection drops. Resolves
|
|
505
|
+
* with the run as it ended. Throws on an answer a retry would not change
|
|
506
|
+
* (isPermanentStreamError: the run is gone, or not yours to see).
|
|
507
|
+
*/
|
|
508
|
+
async followRun(agentId, runId, handler, signal, options = {}) {
|
|
509
|
+
await this.followRunStream(`/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/stream`, handler, signal, options);
|
|
510
|
+
return this.getRun(agentId, runId);
|
|
511
|
+
}
|
|
303
512
|
/**
|
|
304
513
|
* Poll a run until it reaches a terminal status (or waiting_input).
|
|
305
514
|
*/
|
|
@@ -442,13 +651,18 @@ export class GatewayClient {
|
|
|
442
651
|
/**
|
|
443
652
|
* Stream run events via SSE. Calls handler for each event
|
|
444
653
|
* (llm.started, llm.chunk, llm.response, tool.started, tool.result,
|
|
445
|
-
* step.completed, run.completed, run.failed).
|
|
654
|
+
* step.completed, run.completed, run.failed), each once and in order.
|
|
446
655
|
* Returns when the run completes or fails.
|
|
447
|
-
*
|
|
656
|
+
*
|
|
657
|
+
* A dropped connection is picked up where it left off
|
|
658
|
+
* (AlmytyClient.followRunStream); `options` can start from a position a
|
|
659
|
+
* caller already has. An answer that will not change on a retry (the run
|
|
660
|
+
* is gone, or not this key's to see: 400, 401, 403, 404, 410) is thrown.
|
|
661
|
+
* Falls back to polling if the stream keeps failing otherwise.
|
|
448
662
|
*/
|
|
449
|
-
async streamRun(runId, handler, signal) {
|
|
663
|
+
async streamRun(runId, handler, signal, options = {}) {
|
|
450
664
|
try {
|
|
451
|
-
await this.client.
|
|
665
|
+
await this.client.followRunStream(`${this.prefix}/runs/${encodeURIComponent(runId)}/stream`, handler, signal, options);
|
|
452
666
|
// Stream ended — get final state
|
|
453
667
|
return this.getRun(runId);
|
|
454
668
|
}
|
|
@@ -458,6 +672,9 @@ export class GatewayClient {
|
|
|
458
672
|
// for the full five-minute poll window.
|
|
459
673
|
if (signal?.aborted || isAbortError(err))
|
|
460
674
|
throw err;
|
|
675
|
+
// Polling a run that is gone, or not ours, only says so again.
|
|
676
|
+
if (isPermanentStreamError(err))
|
|
677
|
+
throw err;
|
|
461
678
|
// SSE failed — fall back to polling until completion
|
|
462
679
|
return this.pollRun(runId, { signal });
|
|
463
680
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { AlmytyClient, GatewayClient, parseSseFrame, isAbortError } from './client.js';
|
|
2
|
-
export type { AgentInfo, AgentTool, AgentRun, PipelineNode, RunLimits, StreamEvent, StreamEventHandler, RunnerSummary, RunnerCodingAgent, CodingSession, } from './client.js';
|
|
1
|
+
export { AlmytyClient, GatewayClient, parseSseFrame, isAbortError, isPermanentStreamError, PERMANENT_STREAM_STATUSES, RUN_STREAM_RETRY_DELAYS_MS, } from './client.js';
|
|
2
|
+
export type { AgentInfo, AgentTool, AgentRun, PipelineNode, RunLimits, StreamEvent, StreamEventHandler, RunnerSummary, RunnerCodingAgent, CodingSession, RunLogEvent, RunStreamOptions, RunStreamPosition, } from './client.js';
|
|
3
3
|
export { loadCredentials, resolveCredentials, resolveCredentialsOrExit, getOrgSlugFromToken, credentialsExpired, CREDENTIALS_FILE, } from './credentials.js';
|
|
4
4
|
export type { StoredCredentials } from './credentials.js';
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { AlmytyClient, GatewayClient, parseSseFrame, isAbortError } from './client.js';
|
|
1
|
+
export { AlmytyClient, GatewayClient, parseSseFrame, isAbortError, isPermanentStreamError, PERMANENT_STREAM_STATUSES, RUN_STREAM_RETRY_DELAYS_MS, } from './client.js';
|
|
2
2
|
export { loadCredentials, resolveCredentials, resolveCredentialsOrExit, getOrgSlugFromToken, credentialsExpired, CREDENTIALS_FILE, } from './credentials.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@almyty/client",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.8",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
@@ -25,9 +25,9 @@
|
|
|
25
25
|
"author": "almyty",
|
|
26
26
|
"license": "Apache-2.0",
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@types/node": "^
|
|
28
|
+
"@types/node": "^26.6.6",
|
|
29
29
|
"typescript": "^5.3.0",
|
|
30
|
-
"vitest": "^
|
|
30
|
+
"vitest": "^5.0.5"
|
|
31
31
|
},
|
|
32
32
|
"homepage": "https://almyty.com",
|
|
33
33
|
"repository": {
|