@almyty/acp-server 1.5.7 → 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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,156 @@
1
+ /**
2
+ * An autonomous answer streams to the ACP client as it is written: each
3
+ * `llm.chunk` of the answering call goes out as an `agent_message_chunk`
4
+ * the moment it arrives, not the whole answer at the end. The working (a
5
+ * step that goes on to call tools) goes out as thought, never as answer,
6
+ * and the answer is not sent twice when the run's final output lands.
7
+ */
8
+ import { describe, it, expect } from 'vitest';
9
+ import { AlmytyAcpAgent } from '../agent.js';
10
+ import { autonomousTextStream, isTerminalEvent, mapStreamEvent } from '../events.js';
11
+ /** A runtime event as the run stream sends it: the event whole, with its place. */
12
+ const ev = (type, data, pos = '1-0') => ({
13
+ event: type,
14
+ data: { type, data, timestamp: 't', pos },
15
+ });
16
+ const RUN_EVENTS = [
17
+ ev('llm.started', { step: 0, answer: false }),
18
+ ev('llm.chunk', { step: 0, content: 'Looking up the order' }),
19
+ ev('llm.response', { step: 0, content: 'Looking up the order', toolCalls: [{ id: 't1', name: 'orders' }] }),
20
+ ev('tool.started', { step: 0, toolCallId: 't1', tool: 'orders' }),
21
+ ev('llm.started', { step: 1, answer: true }),
22
+ ev('llm.chunk', { step: 1, content: 'Your order' }),
23
+ ev('llm.chunk', { step: 1, content: ' ships Monday.' }),
24
+ ev('llm.response', { step: 1, content: 'Your order ships Monday.' }),
25
+ ev('run.completed', { output: 'Your order ships Monday.' }),
26
+ ];
27
+ function harness(events) {
28
+ const log = [];
29
+ const sent = [];
30
+ const proxy = {
31
+ getAgent: async () => ({ id: 'a1', name: 'Orders', mode: 'autonomous', status: 'active' }),
32
+ startRun: async () => ({ id: 'r1', status: 'running', conversationId: 'c1' }),
33
+ getRun: async () => ({ id: 'r1', status: 'completed', output: 'Your order ships Monday.' }),
34
+ cancelRun: async () => undefined,
35
+ async *streamRun() {
36
+ for (const event of events) {
37
+ log.push(`yield ${event.event}`);
38
+ yield event;
39
+ }
40
+ },
41
+ };
42
+ const agent = new AlmytyAcpAgent(proxy, 'a1', (msg) => {
43
+ sent.push(msg);
44
+ const update = msg?.params?.update;
45
+ if (update?.sessionUpdate)
46
+ log.push(`${update.sessionUpdate}|${update.content?.text ?? ''}`);
47
+ });
48
+ const call = async (id, method, params = {}) => {
49
+ await agent.handleMessage({ jsonrpc: '2.0', id, method, params });
50
+ return sent.find((m) => m.id === id);
51
+ };
52
+ return { log, sent, call };
53
+ }
54
+ describe('ACP: an autonomous answer streams as it is written', () => {
55
+ it('sends each answer chunk as it arrives, before the run ends, and the working as thought', async () => {
56
+ const h = harness(RUN_EVENTS);
57
+ await h.call(1, 'initialize', { protocolVersion: 1, clientCapabilities: {} });
58
+ const session = await h.call(2, 'session/new', { cwd: '/tmp' });
59
+ const reply = await h.call(3, 'session/prompt', {
60
+ sessionId: session.result.sessionId,
61
+ prompt: [{ type: 'text', text: 'Where is my order?' }],
62
+ });
63
+ const answerChunks = h.log.filter((l) => l.startsWith('agent_message_chunk'));
64
+ expect(answerChunks).toEqual(['agent_message_chunk|Your order', 'agent_message_chunk| ships Monday.']);
65
+ // Each chunk went out right after the event that carried it, ahead of the run's end.
66
+ const firstChunk = h.log.indexOf('agent_message_chunk|Your order');
67
+ expect(firstChunk).toBeGreaterThan(-1);
68
+ expect(firstChunk).toBeLessThan(h.log.indexOf('yield run.completed'));
69
+ expect(h.log[firstChunk - 1]).toBe('yield llm.chunk');
70
+ // The working is thought, never the answer.
71
+ expect(h.log).toContain('agent_thought_chunk|Looking up the order');
72
+ expect(answerChunks.join('')).not.toContain('Looking up');
73
+ // The prompt answers with the answer, once.
74
+ expect(reply.result.content).toEqual([{ type: 'text', text: 'Your order ships Monday.' }]);
75
+ });
76
+ it('a step the provider never classifies goes out whole when its response lands', () => {
77
+ const text = autonomousTextStream();
78
+ const out = [];
79
+ for (const event of [
80
+ ev('llm.chunk', { step: 0, content: 'Your order ' }),
81
+ ev('llm.chunk', { step: 0, content: 'ships Monday.' }),
82
+ ev('llm.response', { step: 0, content: 'Your order ships Monday.' }),
83
+ ]) {
84
+ out.push(...(text.map(event) ?? []));
85
+ }
86
+ expect(out).toEqual([{ type: 'agent_message_chunk', text: 'Your order ships Monday.' }]);
87
+ expect(text.answer()).toBe('Your order ships Monday.');
88
+ });
89
+ it('held chunks follow the provider’s verdict: text streams as answer, tool as thought', () => {
90
+ const text = autonomousTextStream();
91
+ const map = (event) => text.map(event) ?? [];
92
+ expect(map(ev('llm.chunk', { step: 0, content: 'Checking ' }))).toEqual([]);
93
+ expect(map(ev('llm.step_kind', { step: 0, kind: 'tool' }))).toEqual([{ type: 'agent_thought_chunk', text: 'Checking ' }]);
94
+ expect(map(ev('llm.chunk', { step: 1, content: 'Your order' }))).toEqual([]);
95
+ expect(map(ev('llm.step_kind', { step: 1, kind: 'text' }))).toEqual([{ type: 'agent_message_chunk', text: 'Your order' }]);
96
+ expect(map(ev('llm.chunk', { step: 1, content: ' ships.' }))).toEqual([{ type: 'agent_message_chunk', text: ' ships.' }]);
97
+ // The response adds only what the stream did not carry.
98
+ expect(map(ev('llm.response', { step: 1, content: 'Your order ships. Monday.' }))).toEqual([
99
+ { type: 'agent_message_chunk', text: ' Monday.' },
100
+ ]);
101
+ // Anything that is not model output is the caller's to map.
102
+ expect(text.map(ev('tool.started', { tool: 'orders' }))).toBeNull();
103
+ });
104
+ it('the rest of the final output that did not stream goes out at the end, and nothing twice', async () => {
105
+ const h = harness([
106
+ ev('llm.started', { step: 0, answer: true }),
107
+ ev('llm.chunk', { step: 0, content: 'Your order' }),
108
+ ev('run.completed', { output: { text: 'Your order ships Monday.' } }),
109
+ ]);
110
+ await h.call(1, 'initialize', { protocolVersion: 1, clientCapabilities: {} });
111
+ const session = await h.call(2, 'session/new', { cwd: '/tmp' });
112
+ const reply = await h.call(3, 'session/prompt', { sessionId: session.result.sessionId, prompt: [{ type: 'text', text: 'Hi' }] });
113
+ expect(h.log.filter((l) => l.startsWith('agent_message_chunk'))).toEqual([
114
+ 'agent_message_chunk|Your order',
115
+ 'agent_message_chunk| ships Monday.',
116
+ ]);
117
+ expect(reply.result.content).toEqual([{ type: 'text', text: 'Your order ships Monday.' }]);
118
+ });
119
+ });
120
+ describe('ACP: an autonomous run’s tool calls reach the editor', () => {
121
+ it('reads each event’s own fields from under `data`, as the run stream sends them', () => {
122
+ expect(mapStreamEvent(ev('tool.started', { step: 0, toolCallId: 't1', tool: 'search_orders' }))).toEqual([
123
+ { type: 'tool_call', toolCallId: 't1', title: 'search_orders', kind: 'search', status: 'running', rawInput: undefined },
124
+ ]);
125
+ expect(mapStreamEvent(ev('tool.result', { step: 0, toolCallId: 't1', tool: 'search_orders', success: true, executionTime: 40 }))).toEqual([
126
+ { type: 'tool_call_update', toolCallId: 't1', status: 'completed', content: undefined },
127
+ ]);
128
+ expect(mapStreamEvent(ev('tool.result', { step: 0, toolCallId: 't2', tool: 'refund', success: false, error: 'Card declined' }))).toEqual([
129
+ { type: 'tool_call_update', toolCallId: 't2', status: 'error', error: 'Card declined' },
130
+ ]);
131
+ });
132
+ it('a failed run says why, and ends the turn', () => {
133
+ const failed = ev('run.failed', { error: 'Provider unavailable' });
134
+ expect(mapStreamEvent(failed)).toEqual([{ type: 'agent_message_chunk', text: 'Error: Provider unavailable' }]);
135
+ expect(isTerminalEvent(failed)).toBe(true);
136
+ });
137
+ it('an event with no envelope (a workflow stream) is read as it is', () => {
138
+ const plain = { event: 'node.started', data: { nodeId: 'n1', nodeType: 'llm_call', label: 'Draft', data: { nested: true } } };
139
+ expect(mapStreamEvent(plain)).toEqual([
140
+ { type: 'tool_call', toolCallId: 'n1', title: 'Draft', kind: 'think', status: 'running', rawInput: undefined },
141
+ ]);
142
+ });
143
+ it('the editor sees the tool call start and finish during a prompt', async () => {
144
+ const h = harness([
145
+ ev('tool.started', { step: 0, toolCallId: 't1', tool: 'search_orders' }),
146
+ ev('tool.result', { step: 0, toolCallId: 't1', tool: 'search_orders', success: true }),
147
+ ...RUN_EVENTS.slice(4),
148
+ ]);
149
+ await h.call(1, 'initialize', { protocolVersion: 1, clientCapabilities: {} });
150
+ const session = await h.call(2, 'session/new', { cwd: '/tmp' });
151
+ await h.call(3, 'session/prompt', { sessionId: session.result.sessionId, prompt: [{ type: 'text', text: 'Where is my order?' }] });
152
+ const updates = h.sent.map((m) => m?.params?.update).filter(Boolean);
153
+ expect(updates).toContainEqual(expect.objectContaining({ sessionUpdate: 'tool_call', toolCallId: 't1', title: 'search_orders', status: 'running' }));
154
+ expect(updates).toContainEqual(expect.objectContaining({ sessionUpdate: 'tool_call_update', toolCallId: 't1', status: 'completed' }));
155
+ });
156
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,92 @@
1
+ /**
2
+ * An autonomous run's stream, followed across dropped connections: each
3
+ * connection names where the last one got to (`?after=<seq>&live=<pos>`),
4
+ * each event is yielded once and in order, an answer a retry would not
5
+ * change (404) ends it at once, and a network error or a 5xx is retried.
6
+ */
7
+ import { describe, it, expect, vi, afterEach } from 'vitest';
8
+ import { AlmytyProxy, isPermanentStatus } from '../proxy.js';
9
+ const BASE = 'https://api.test.almyty.com';
10
+ const STREAM = '/agents/a1/runs/r1/stream';
11
+ function serve(answers) {
12
+ const urls = [];
13
+ const fetchMock = vi.fn(async (url) => {
14
+ urls.push(url.replace(BASE, ''));
15
+ const answer = answers.shift();
16
+ if (!answer)
17
+ throw new Error('no more connections expected');
18
+ if ('status' in answer)
19
+ return new Response('Run not found', { status: answer.status });
20
+ const encoder = new TextEncoder();
21
+ const chunks = [...answer.frames];
22
+ const body = new ReadableStream({
23
+ pull(controller) {
24
+ if (chunks.length)
25
+ controller.enqueue(encoder.encode(chunks.shift()));
26
+ else if (answer.breaks)
27
+ controller.error(new TypeError('terminated'));
28
+ else
29
+ controller.close();
30
+ },
31
+ });
32
+ return new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } });
33
+ });
34
+ globalThis.fetch = fetchMock;
35
+ return { urls, fetchMock };
36
+ }
37
+ const log = (seq, status = 'running') => `id: ${seq}\nevent: run.log\ndata: ${JSON.stringify({ seq, type: 'step_committed', step: 0, payload: { status } })}\n\n`;
38
+ const live = (type, pos, data = {}) => `event: ${type}\ndata: ${JSON.stringify({ type, data, timestamp: 't', pos })}\n\n`;
39
+ async function collect(stream) {
40
+ const out = [];
41
+ for await (const event of stream)
42
+ out.push(event);
43
+ return out;
44
+ }
45
+ describe('AlmytyProxy.streamRun', () => {
46
+ const origFetch = globalThis.fetch;
47
+ afterEach(() => {
48
+ globalThis.fetch = origFetch;
49
+ });
50
+ it('reconnects from its last seq and place, and yields each event once, then done', async () => {
51
+ const { urls } = serve([
52
+ { frames: [log(1), live('tool.started', '10-0', { tool: 'crm' }), log(2)], breaks: true },
53
+ { frames: [log(2), live('tool.started', '10-0', { tool: 'crm' }), live('tool.completed', '10-1'), log(3, 'completed'), live('run.completed', '10-2')] },
54
+ ]);
55
+ const proxy = new AlmytyProxy(BASE, 'token');
56
+ const events = await collect(proxy.streamRun('a1', 'r1', undefined, { retryDelaysMs: [0] }));
57
+ expect(urls).toEqual([`${STREAM}?after=0&live=0`, `${STREAM}?after=2&live=10-0`]);
58
+ expect(events.map((e) => e.event)).toEqual(['tool.started', 'tool.completed', 'run.completed', 'done']);
59
+ });
60
+ it('stops on a 404 at once, with its status, and connects no more', async () => {
61
+ const { fetchMock } = serve([{ status: 404 }]);
62
+ const proxy = new AlmytyProxy(BASE, 'token');
63
+ const failure = await collect(proxy.streamRun('a1', 'r1', undefined, { retryDelaysMs: [0, 0] })).catch((e) => e);
64
+ expect(failure).toMatchObject({ status: 404 });
65
+ expect(isPermanentStatus(failure)).toBe(true);
66
+ expect(fetchMock).toHaveBeenCalledTimes(1);
67
+ });
68
+ it('retries a 5xx, then carries on from where it was', async () => {
69
+ const { urls } = serve([{ status: 503 }, { frames: [log(1, 'completed'), live('run.completed', '3-0')] }]);
70
+ const proxy = new AlmytyProxy(BASE, 'token');
71
+ const events = await collect(proxy.streamRun('a1', 'r1', undefined, { retryDelaysMs: [0] }));
72
+ expect(urls).toHaveLength(2);
73
+ expect(events.map((e) => e.event)).toEqual(['run.completed', 'done']);
74
+ });
75
+ it('the server ending at its time limit: straight back, its own done not taken for the run ending', async () => {
76
+ const { urls } = serve([
77
+ { frames: [log(1), live('llm.chunk', '4-0', { content: 'a' }), 'event: done\ndata: {}\n\n'] },
78
+ { frames: [live('run.completed', '4-1'), log(2, 'completed')] },
79
+ ]);
80
+ const proxy = new AlmytyProxy(BASE, 'token');
81
+ const events = await collect(proxy.streamRun('a1', 'r1', undefined, { retryDelaysMs: [] }));
82
+ expect(events.map((e) => e.event)).toEqual(['llm.chunk', 'run.completed', 'done']);
83
+ expect(urls[1]).toBe(`${STREAM}?after=1&live=4-0`);
84
+ });
85
+ it('a server that cannot resume: one connection, as before', async () => {
86
+ const { fetchMock } = serve([{ frames: [`event: run.completed\ndata: ${JSON.stringify({ type: 'run.completed', data: {} })}\n\n`] }]);
87
+ const proxy = new AlmytyProxy(BASE, 'token');
88
+ const events = await collect(proxy.streamRun('a1', 'r1'));
89
+ expect(events.map((e) => e.event)).toEqual(['run.completed', 'done']);
90
+ expect(fetchMock).toHaveBeenCalledTimes(1);
91
+ });
92
+ });
package/dist/agent.d.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  * session lifecycle, dispatches prompts to the correct execution engine,
6
6
  * and streams SessionUpdate notifications back to the client.
7
7
  */
8
- import type { AlmytyProxy } from './proxy.js';
8
+ import { type AlmytyProxy } from './proxy.js';
9
9
  /** JSON-RPC 2.0 request. */
10
10
  export interface JsonRpcRequest {
11
11
  jsonrpc: '2.0';
package/dist/agent.js CHANGED
@@ -5,8 +5,9 @@
5
5
  * session lifecycle, dispatches prompts to the correct execution engine,
6
6
  * and streams SessionUpdate notifications back to the client.
7
7
  */
8
+ import { isPermanentStatus } from './proxy.js';
8
9
  import { SessionManager } from './session.js';
9
- import { mapStreamEvent, buildPlanFromPipeline, isTerminalEvent, extractFinalOutput, } from './events.js';
10
+ import { mapStreamEvent, autonomousTextStream, runEventData, runOutputText, buildPlanFromPipeline, isTerminalEvent, extractFinalOutput, } from './events.js';
10
11
  // ── Standard JSON-RPC error codes ────────────────────────────────
11
12
  const PARSE_ERROR = -32700;
12
13
  const INVALID_REQUEST = -32600;
@@ -303,6 +304,7 @@ export class AlmytyAcpAgent {
303
304
  */
304
305
  async handleAutonomousPrompt(session, input, signal) {
305
306
  const collectedText = [];
307
+ const text = autonomousTextStream();
306
308
  try {
307
309
  let run;
308
310
  if (session.activeRunId) {
@@ -329,7 +331,9 @@ export class AlmytyAcpAgent {
329
331
  catch { /* best effort */ }
330
332
  return { stopReason: 'cancelled' };
331
333
  }
332
- const updates = mapStreamEvent(event);
334
+ // Model output streams as it is written: the answer as message
335
+ // chunks, the working as thought (events.ts autonomousTextStream).
336
+ const updates = text.map(event) ?? mapStreamEvent(event);
333
337
  for (const update of updates) {
334
338
  this.sendSessionUpdate(session.id, update);
335
339
  if (update.type === 'agent_message_chunk') {
@@ -337,8 +341,26 @@ export class AlmytyAcpAgent {
337
341
  }
338
342
  }
339
343
  if (isTerminalEvent(event)) {
340
- const finalOutput = extractFinalOutput(event);
341
- if (finalOutput && !collectedText.includes(finalOutput)) {
344
+ const streamed = text.answer();
345
+ const finalOutput = streamed
346
+ ? runOutputText(runEventData(event).output) ?? extractFinalOutput(event)
347
+ : extractFinalOutput(event);
348
+ if (finalOutput && streamed) {
349
+ // The answer already streamed. Whatever of the final text it
350
+ // did not carry goes out now; a final text that differs from
351
+ // what streamed is what the turn answers with.
352
+ if (finalOutput.startsWith(streamed)) {
353
+ const rest = finalOutput.slice(streamed.length);
354
+ if (rest) {
355
+ this.sendSessionUpdate(session.id, { type: 'agent_message_chunk', text: rest });
356
+ collectedText.push(rest);
357
+ }
358
+ }
359
+ else {
360
+ collectedText.splice(0, collectedText.length, finalOutput);
361
+ }
362
+ }
363
+ else if (finalOutput && !collectedText.includes(finalOutput)) {
342
364
  collectedText.push(finalOutput);
343
365
  }
344
366
  break;
@@ -346,6 +368,12 @@ export class AlmytyAcpAgent {
346
368
  }
347
369
  }
348
370
  catch (streamErr) {
371
+ // The run is gone, or not this token's: polling it would only say so
372
+ // again. The session lets go of it so the next prompt starts afresh.
373
+ if (isPermanentStatus(streamErr)) {
374
+ this.sessions.update(session.id, { activeRunId: undefined });
375
+ throw streamErr;
376
+ }
349
377
  // If streaming fails, fall back to polling the run status
350
378
  process.stderr.write(`[acp] Run streaming failed, polling: ${streamErr}\n`);
351
379
  const finalRun = await this.pollRunToCompletion(session.agentId, run.id, signal);
package/dist/events.d.ts CHANGED
@@ -58,9 +58,40 @@ export interface Plan {
58
58
  /**
59
59
  * Convert a single almyty StreamEvent into zero or more ACP SessionUpdate
60
60
  * payloads. Most events map 1:1, but some (like node.completed with output)
61
- * may produce both a tool_call_update and an agent_message_chunk.
61
+ * may produce both a tool_call_update and an agent_message_chunk. An
62
+ * autonomous run's events carry their fields under `data` (runEventData).
62
63
  */
63
64
  export declare function mapStreamEvent(event: StreamEvent): SessionUpdatePayload[];
65
+ /**
66
+ * An event's own fields. The run stream of an autonomous run sends each
67
+ * runtime event whole, `{ type, data, timestamp, pos }`, so what the event
68
+ * says is under `data`; an event without that envelope (a workflow's
69
+ * stream) is read as it is.
70
+ */
71
+ export declare function runEventData(event: StreamEvent): Record<string, any>;
72
+ /** A run's output as text: a string, or the `text` of an output object. */
73
+ export declare function runOutputText(output: unknown): string | undefined;
74
+ /**
75
+ * An autonomous run's model output as it is written, sorted into the
76
+ * answer (`agent_message_chunk`) and the working (`agent_thought_chunk`).
77
+ *
78
+ * Every step of an autonomous run streams its model output as `llm.chunk`,
79
+ * the steps that go on to call tools as much as the one that answers. The
80
+ * run says which is which: `llm.started` with `answer: true` is a call that
81
+ * writes the answer, `answer: false` one that works; a step announced
82
+ * neither way is held until the provider says what it is (`llm.step_kind`:
83
+ * `text` or `tool`), and a step whose provider never says goes out whole
84
+ * when its `llm.response` lands with no tool calls. The same rules the
85
+ * hosted chat applies to what a visitor sees (answer-stream.filter.ts on
86
+ * the server), except that here the working is shown too, as thought.
87
+ *
88
+ * `map` answers null for any event that is not model output, which the
89
+ * caller hands to mapStreamEvent; `answer()` is the answer text sent so far.
90
+ */
91
+ export declare function autonomousTextStream(): {
92
+ map(event: StreamEvent): SessionUpdatePayload[] | null;
93
+ answer(): string;
94
+ };
64
95
  /**
65
96
  * Build an ACP Plan from almyty pipeline nodes. Maps node types to
66
97
  * priorities and initializes all entries as "todo".
package/dist/events.js CHANGED
@@ -34,11 +34,12 @@ function inferKind(nodeType, toolName) {
34
34
  /**
35
35
  * Convert a single almyty StreamEvent into zero or more ACP SessionUpdate
36
36
  * payloads. Most events map 1:1, but some (like node.completed with output)
37
- * may produce both a tool_call_update and an agent_message_chunk.
37
+ * may produce both a tool_call_update and an agent_message_chunk. An
38
+ * autonomous run's events carry their fields under `data` (runEventData).
38
39
  */
39
40
  export function mapStreamEvent(event) {
40
41
  const updates = [];
41
- const data = event.data;
42
+ const data = runEventData(event);
42
43
  switch (event.event) {
43
44
  // ── Node lifecycle events (workflow agents) ──────────────────
44
45
  case 'node.started': {
@@ -147,6 +148,22 @@ export function mapStreamEvent(event) {
147
148
  });
148
149
  break;
149
150
  }
151
+ // An autonomous run's tool call ended: `success` says how, and a
152
+ // failure carries its `error`.
153
+ case 'tool.result': {
154
+ const toolCallId = String(data.toolCallId ?? data.id ?? data.callId ?? '');
155
+ const failed = data.success === false || !!data.error;
156
+ const result = data.result ?? data.output;
157
+ updates.push(failed
158
+ ? { type: 'tool_call_update', toolCallId, status: 'error', error: String(data.error ?? 'Tool execution failed') }
159
+ : {
160
+ type: 'tool_call_update',
161
+ toolCallId,
162
+ status: 'completed',
163
+ content: result != null ? (typeof result === 'string' ? result : JSON.stringify(result)) : undefined,
164
+ });
165
+ break;
166
+ }
150
167
  case 'tool.error': {
151
168
  const toolCallId = String(data.toolCallId ?? data.id ?? data.callId ?? '');
152
169
  updates.push({
@@ -163,6 +180,7 @@ export function mapStreamEvent(event) {
163
180
  case 'execution.error':
164
181
  case 'run.completed':
165
182
  case 'run.error':
183
+ case 'run.failed':
166
184
  case 'done':
167
185
  // Terminal events — the caller handles these to finalize the
168
186
  // PromptResponse. We optionally surface errors as message chunks.
@@ -186,6 +204,135 @@ export function mapStreamEvent(event) {
186
204
  }
187
205
  return updates;
188
206
  }
207
+ /**
208
+ * An event's own fields. The run stream of an autonomous run sends each
209
+ * runtime event whole, `{ type, data, timestamp, pos }`, so what the event
210
+ * says is under `data`; an event without that envelope (a workflow's
211
+ * stream) is read as it is.
212
+ */
213
+ export function runEventData(event) {
214
+ const raw = (event.data ?? {});
215
+ const enveloped = raw.type === event.event && raw.data && typeof raw.data === 'object' && !Array.isArray(raw.data);
216
+ return enveloped ? raw.data : raw;
217
+ }
218
+ /** A run's output as text: a string, or the `text` of an output object. */
219
+ export function runOutputText(output) {
220
+ if (typeof output === 'string')
221
+ return output || undefined;
222
+ if (output && typeof output === 'object' && typeof output.text === 'string')
223
+ return output.text || undefined;
224
+ return undefined;
225
+ }
226
+ /**
227
+ * An autonomous run's model output as it is written, sorted into the
228
+ * answer (`agent_message_chunk`) and the working (`agent_thought_chunk`).
229
+ *
230
+ * Every step of an autonomous run streams its model output as `llm.chunk`,
231
+ * the steps that go on to call tools as much as the one that answers. The
232
+ * run says which is which: `llm.started` with `answer: true` is a call that
233
+ * writes the answer, `answer: false` one that works; a step announced
234
+ * neither way is held until the provider says what it is (`llm.step_kind`:
235
+ * `text` or `tool`), and a step whose provider never says goes out whole
236
+ * when its `llm.response` lands with no tool calls. The same rules the
237
+ * hosted chat applies to what a visitor sees (answer-stream.filter.ts on
238
+ * the server), except that here the working is shown too, as thought.
239
+ *
240
+ * `map` answers null for any event that is not model output, which the
241
+ * caller hands to mapStreamEvent; `answer()` is the answer text sent so far.
242
+ */
243
+ export function autonomousTextStream() {
244
+ const steps = new Map();
245
+ let answer = '';
246
+ const stateOf = (step) => {
247
+ let state = steps.get(step);
248
+ if (!state) {
249
+ state = { kind: null, held: [], sent: '' };
250
+ steps.set(step, state);
251
+ }
252
+ return state;
253
+ };
254
+ const say = (state, text) => {
255
+ if (state)
256
+ state.sent += text;
257
+ answer += text;
258
+ return { type: 'agent_message_chunk', text };
259
+ };
260
+ const think = (text) => ({ type: 'agent_thought_chunk', text });
261
+ return {
262
+ answer: () => answer,
263
+ map(event) {
264
+ const data = runEventData(event);
265
+ const step = typeof data.step === 'number' ? data.step : null;
266
+ switch (event.event) {
267
+ case 'llm.started': {
268
+ if (step === null)
269
+ return [];
270
+ steps.delete(step);
271
+ if (data.answer === true)
272
+ steps.set(step, { kind: 'text', held: [], sent: '' });
273
+ else if (data.answer === false)
274
+ steps.set(step, { kind: 'tool', held: [], sent: '' });
275
+ return [];
276
+ }
277
+ case 'llm.chunk': {
278
+ const content = data.content;
279
+ if (step === null || typeof content !== 'string' || !content)
280
+ return [];
281
+ const state = stateOf(step);
282
+ if (state.kind === 'text')
283
+ return [say(state, content)];
284
+ if (state.kind === 'tool')
285
+ return [think(content)];
286
+ state.held.push(content);
287
+ return [];
288
+ }
289
+ case 'llm.step_kind': {
290
+ if (step === null)
291
+ return [];
292
+ const state = stateOf(step);
293
+ if (state.kind)
294
+ return [];
295
+ const held = state.held.join('');
296
+ state.held = [];
297
+ if (data.kind === 'tool') {
298
+ state.kind = 'tool';
299
+ return held ? [think(held)] : [];
300
+ }
301
+ if (data.kind === 'text') {
302
+ state.kind = 'text';
303
+ return held ? [say(state, held)] : [];
304
+ }
305
+ return [];
306
+ }
307
+ case 'llm.response': {
308
+ const state = step === null ? undefined : steps.get(step);
309
+ if (step !== null)
310
+ steps.delete(step);
311
+ const calledTools = Array.isArray(data.toolCalls) && data.toolCalls.length > 0;
312
+ const held = state?.held.join('') ?? '';
313
+ // Working, unless the run says this draft now stands as the answer.
314
+ if (calledTools || (state?.kind === 'tool' && data.answer !== true))
315
+ return held ? [think(held)] : [];
316
+ const content = data.content;
317
+ if (typeof content !== 'string' || !content)
318
+ return [];
319
+ const sent = state?.sent ?? '';
320
+ // What streamed is the start of the answer: the rest, if any.
321
+ if (content.startsWith(sent)) {
322
+ const rest = content.slice(sent.length);
323
+ return rest ? [say(null, rest)] : [];
324
+ }
325
+ // The stream and the response disagree. What was sent cannot be
326
+ // taken back here; the turn's final text (the run's output) is
327
+ // what the prompt answers with.
328
+ return [];
329
+ }
330
+ default:
331
+ return null;
332
+ }
333
+ },
334
+ };
335
+ }
189
336
  /**
190
337
  * Build an ACP Plan from almyty pipeline nodes. Maps node types to
191
338
  * priorities and initializes all entries as "todo".
@@ -226,6 +373,8 @@ export function isTerminalEvent(event) {
226
373
  'execution.error',
227
374
  'run.completed',
228
375
  'run.error',
376
+ 'run.failed',
377
+ 'run.cancelled',
229
378
  'done',
230
379
  ].includes(event.event);
231
380
  }
package/dist/proxy.d.ts CHANGED
@@ -37,6 +37,19 @@ export interface StreamEvent {
37
37
  event: string;
38
38
  data: Record<string, unknown>;
39
39
  }
40
+ /** Where to pick a run's stream up, and how hard to try. */
41
+ export interface RunStreamResume {
42
+ /** Resume after this logged event. Default 0: the run's whole log. */
43
+ afterSeq?: number;
44
+ /** Resume after this live event's place (`pos`). Default `0`: every one from the run's start. */
45
+ livePos?: string;
46
+ /** Waits before each retry after a failed connection, in ms; one entry per retry. */
47
+ retryDelaysMs?: number[];
48
+ }
49
+ /** Waits before each retry of a run stream that failed, in ms. */
50
+ export declare const RUN_STREAM_RETRY_DELAYS_MS: number[];
51
+ /** Whether a stream error is one a retry would not change. */
52
+ export declare function isPermanentStatus(err: unknown): boolean;
40
53
  export declare class AlmytyProxy {
41
54
  private readonly baseUrl;
42
55
  private readonly token;
@@ -55,10 +68,19 @@ export declare class AlmytyProxy {
55
68
  sendRunInput(agentId: string, runId: string, input: Record<string, unknown>): Promise<AgentRun>;
56
69
  cancelRun(agentId: string, runId: string): Promise<void>;
57
70
  /**
58
- * Stream an autonomous run via SSE. Similar to streamAgent but uses the
59
- * run-specific SSE endpoint.
71
+ * Stream an autonomous run via SSE, each event once and in order, until
72
+ * the run ends; then a final `done`.
73
+ *
74
+ * A dropped connection, or the server ending one at its time limit, is
75
+ * picked up where it left off: every connection names the seq of the
76
+ * last logged event (`?after=`) and the place of the last live event
77
+ * (`?live=`), and the server sends what came after both. The log itself
78
+ * is how this keeps its place and is not yielded. A network error or a
79
+ * 5xx is retried with backoff; an answer a retry would not change (400,
80
+ * 401, 403, 404, 410: the run is gone, or not this token's) is thrown,
81
+ * with its `status`.
60
82
  */
61
- streamRun(agentId: string, runId: string, signal?: AbortSignal): AsyncGenerator<StreamEvent>;
83
+ streamRun(agentId: string, runId: string, signal?: AbortSignal, options?: RunStreamResume): AsyncGenerator<StreamEvent>;
62
84
  private headers;
63
85
  private get;
64
86
  private post;
package/dist/proxy.js CHANGED
@@ -9,6 +9,44 @@ import { createParser } from 'eventsource-parser';
9
9
  /** Default timeouts (ms). */
10
10
  const DISCOVERY_TIMEOUT_MS = 15_000;
11
11
  const INVOKE_TIMEOUT_MS = 120_000;
12
+ /** Waits before each retry of a run stream that failed, in ms. */
13
+ export const RUN_STREAM_RETRY_DELAYS_MS = [500, 1_000, 2_000, 5_000, 10_000];
14
+ /** Answers a retry would not change: a bad position, not signed in, not allowed, gone. */
15
+ const PERMANENT_STATUSES = [400, 401, 403, 404, 410];
16
+ const RUN_FINISHED = ['completed', 'failed', 'cancelled', 'timeout'];
17
+ const RUN_ENDED = ['run.completed', 'run.failed', 'run.cancelled'];
18
+ /** Whether a stream error is one a retry would not change. */
19
+ export function isPermanentStatus(err) {
20
+ const status = err?.status;
21
+ return typeof status === 'number' && PERMANENT_STATUSES.includes(status);
22
+ }
23
+ /** Order two places on a run's event stream (`0`, or `<ms>-<n>`). */
24
+ function comparePos(a, b) {
25
+ const parts = (pos) => {
26
+ const m = /^(\d+)-(\d+)$/.exec(pos);
27
+ return m ? [Number(m[1]), Number(m[2])] : [0, 0];
28
+ };
29
+ const [am, an] = parts(a);
30
+ const [bm, bn] = parts(b);
31
+ return am !== bm ? am - bm : an - bn;
32
+ }
33
+ /** Wait, unless the caller gives up first. */
34
+ function sleep(ms, signal) {
35
+ return new Promise((resolve, reject) => {
36
+ const aborted = () => Object.assign(new Error('Aborted'), { name: 'AbortError' });
37
+ if (signal?.aborted)
38
+ return reject(aborted());
39
+ const timer = setTimeout(() => {
40
+ signal?.removeEventListener('abort', onAbort);
41
+ resolve();
42
+ }, ms);
43
+ const onAbort = () => {
44
+ clearTimeout(timer);
45
+ reject(aborted());
46
+ };
47
+ signal?.addEventListener('abort', onAbort, { once: true });
48
+ });
49
+ }
12
50
  export class AlmytyProxy {
13
51
  baseUrl;
14
52
  token;
@@ -58,11 +96,110 @@ export class AlmytyProxy {
58
96
  await this.post(`/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/cancel`, {}, DISCOVERY_TIMEOUT_MS);
59
97
  }
60
98
  /**
61
- * Stream an autonomous run via SSE. Similar to streamAgent but uses the
62
- * run-specific SSE endpoint.
99
+ * Stream an autonomous run via SSE, each event once and in order, until
100
+ * the run ends; then a final `done`.
101
+ *
102
+ * A dropped connection, or the server ending one at its time limit, is
103
+ * picked up where it left off: every connection names the seq of the
104
+ * last logged event (`?after=`) and the place of the last live event
105
+ * (`?live=`), and the server sends what came after both. The log itself
106
+ * is how this keeps its place and is not yielded. A network error or a
107
+ * 5xx is retried with backoff; an answer a retry would not change (400,
108
+ * 401, 403, 404, 410: the run is gone, or not this token's) is thrown,
109
+ * with its `status`.
63
110
  */
64
- async *streamRun(agentId, runId, signal) {
65
- yield* this.sseGet(`/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/stream`, signal);
111
+ async *streamRun(agentId, runId, signal, options = {}) {
112
+ const path = `/agents/${encodeURIComponent(agentId)}/runs/${encodeURIComponent(runId)}/stream`;
113
+ const delays = options.retryDelaysMs ?? RUN_STREAM_RETRY_DELAYS_MS;
114
+ let afterSeq = Math.max(0, Math.floor(options.afterSeq ?? 0));
115
+ let livePos = options.livePos ?? '0';
116
+ // A server that sends neither a seq nor a place cannot resume: it
117
+ // replays its live events on every connection, so once anything has
118
+ // been yielded it is not connected to again.
119
+ let resumable = false;
120
+ let delivered = false;
121
+ let ended = false;
122
+ let failures = 0;
123
+ for (;;) {
124
+ let gap = false;
125
+ let progressed = false;
126
+ let failure = null;
127
+ const connection = new AbortController();
128
+ const linked = signal ? AbortSignal.any([signal, connection.signal]) : connection.signal;
129
+ try {
130
+ for await (const event of this.sseGet(`${path}?after=${afterSeq}&live=${encodeURIComponent(livePos)}`, linked)) {
131
+ if (event.event === 'run.log') {
132
+ const seq = event.data.seq;
133
+ if (typeof seq !== 'number')
134
+ continue;
135
+ resumable = true;
136
+ if (seq <= afterSeq)
137
+ continue;
138
+ if (seq !== afterSeq + 1) {
139
+ gap = true;
140
+ break;
141
+ }
142
+ afterSeq = seq;
143
+ progressed = true;
144
+ const payload = event.data.payload;
145
+ if (event.data.type === 'step_committed' && RUN_FINISHED.includes(String(payload?.status)))
146
+ ended = true;
147
+ continue;
148
+ }
149
+ const pos = typeof event.data.pos === 'string' ? event.data.pos : undefined;
150
+ if (pos) {
151
+ resumable = true;
152
+ if (comparePos(pos, livePos) <= 0)
153
+ continue;
154
+ livePos = pos;
155
+ }
156
+ // The server closing this connection, not the run ending.
157
+ if (event.event === 'done' || event.event === 'stream.timeout')
158
+ continue;
159
+ progressed = true;
160
+ delivered = true;
161
+ yield event;
162
+ if (RUN_ENDED.includes(event.event)) {
163
+ ended = true;
164
+ if (!resumable)
165
+ break;
166
+ }
167
+ }
168
+ }
169
+ catch (err) {
170
+ failure = err;
171
+ }
172
+ finally {
173
+ connection.abort();
174
+ }
175
+ if (signal?.aborted)
176
+ throw failure ?? Object.assign(new Error('Aborted'), { name: 'AbortError' });
177
+ if (ended && !gap)
178
+ break;
179
+ if (progressed)
180
+ failures = 0;
181
+ if (gap)
182
+ continue;
183
+ if (failure) {
184
+ if (isPermanentStatus(failure))
185
+ throw failure;
186
+ if (delivered && !resumable)
187
+ throw failure;
188
+ }
189
+ else if (delivered && !resumable) {
190
+ break;
191
+ }
192
+ else if (progressed) {
193
+ continue;
194
+ }
195
+ if (failures >= delays.length) {
196
+ if (failure)
197
+ throw failure;
198
+ break;
199
+ }
200
+ await sleep(delays[failures++], signal);
201
+ }
202
+ yield { event: 'done', data: {} };
66
203
  }
67
204
  // ── Internal HTTP helpers ──────────────────────────────────────
68
205
  headers() {
@@ -164,7 +301,9 @@ export class AlmytyProxy {
164
301
  });
165
302
  if (!resp.ok) {
166
303
  const text = await resp.text().catch(() => '');
167
- throw new Error(`SSE GET ${path} failed (${resp.status}): ${text}`);
304
+ // The status rides on the error, so a caller can tell a run that is
305
+ // gone (404) from a network that is down.
306
+ throw Object.assign(new Error(`SSE GET ${path} failed (${resp.status}): ${text}`), { status: resp.status });
168
307
  }
169
308
  yield* this.consumeSse(resp);
170
309
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@almyty/acp-server",
3
- "version": "1.5.7",
3
+ "version": "1.5.8",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -31,14 +31,14 @@
31
31
  "author": "almyty",
32
32
  "license": "Apache-2.0",
33
33
  "dependencies": {
34
- "@almyty/client": "^1.5.6",
35
- "eventsource-parser": "^3.0.0"
34
+ "@almyty/client": "^1.5.7",
35
+ "eventsource-parser": "^4.1.2"
36
36
  },
37
37
  "devDependencies": {
38
- "@types/node": "^22.0.0",
38
+ "@types/node": "^26.6.6",
39
39
  "tsx": "^4.0.0",
40
40
  "typescript": "^5.7.0",
41
- "vitest": "^4.1.0"
41
+ "vitest": "^5.0.5"
42
42
  },
43
43
  "homepage": "https://almyty.com",
44
44
  "repository": {