mirror of
https://github.com/getcompanion-ai/co-mono.git
synced 2026-04-20 01:00:24 +00:00
- Add 'aborted' as a distinct stop reason separate from 'error'
- Change AssistantMessage.error to errorMessage for clarity
- Update error event to include reason field ('error' | 'aborted')
- Map provider-specific safety/refusal reasons to 'error' stop reason
- Reorganize utility functions into utils/ directory
- Rename agent.ts to agent-loop.ts for better clarity
- Fix error handling in all providers to properly distinguish abort from error
82 lines
2 KiB
TypeScript
82 lines
2 KiB
TypeScript
import type { AssistantMessage, AssistantMessageEvent } from "../types.js";
|
|
|
|
// Generic event stream class for async iteration
|
|
export class EventStream<T, R = T> implements AsyncIterable<T> {
|
|
private queue: T[] = [];
|
|
private waiting: ((value: IteratorResult<T>) => void)[] = [];
|
|
private done = false;
|
|
private finalResultPromise: Promise<R>;
|
|
private resolveFinalResult!: (result: R) => void;
|
|
|
|
constructor(
|
|
private isComplete: (event: T) => boolean,
|
|
private extractResult: (event: T) => R,
|
|
) {
|
|
this.finalResultPromise = new Promise((resolve) => {
|
|
this.resolveFinalResult = resolve;
|
|
});
|
|
}
|
|
|
|
push(event: T): void {
|
|
if (this.done) return;
|
|
|
|
if (this.isComplete(event)) {
|
|
this.done = true;
|
|
this.resolveFinalResult(this.extractResult(event));
|
|
}
|
|
|
|
// Deliver to waiting consumer or queue it
|
|
const waiter = this.waiting.shift();
|
|
if (waiter) {
|
|
waiter({ value: event, done: false });
|
|
} else {
|
|
this.queue.push(event);
|
|
}
|
|
}
|
|
|
|
end(result?: R): void {
|
|
this.done = true;
|
|
if (result !== undefined) {
|
|
this.resolveFinalResult(result);
|
|
}
|
|
// Notify all waiting consumers that we're done
|
|
while (this.waiting.length > 0) {
|
|
const waiter = this.waiting.shift()!;
|
|
waiter({ value: undefined as any, done: true });
|
|
}
|
|
}
|
|
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
while (true) {
|
|
if (this.queue.length > 0) {
|
|
yield this.queue.shift()!;
|
|
} else if (this.done) {
|
|
return;
|
|
} else {
|
|
const result = await new Promise<IteratorResult<T>>((resolve) => this.waiting.push(resolve));
|
|
if (result.done) return;
|
|
yield result.value;
|
|
}
|
|
}
|
|
}
|
|
|
|
result(): Promise<R> {
|
|
return this.finalResultPromise;
|
|
}
|
|
}
|
|
|
|
export class AssistantMessageEventStream extends EventStream<AssistantMessageEvent, AssistantMessage> {
|
|
constructor() {
|
|
super(
|
|
(event) => event.type === "done" || event.type === "error",
|
|
(event) => {
|
|
if (event.type === "done") {
|
|
return event.message;
|
|
} else if (event.type === "error") {
|
|
return event.error;
|
|
}
|
|
throw new Error("Unexpected event type for final result");
|
|
},
|
|
);
|
|
}
|
|
}
|