-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
232 lines (203 loc) · 6.94 KB
/
Copy pathruntime.ts
File metadata and controls
232 lines (203 loc) · 6.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import {
PROTOCOL_VERSION,
type CompletedItem,
type CompletedItemType,
type DurableProtocolEvent,
type InitializeResult,
type ProtocolEvent,
type ThreadSnapshot,
type TransientDeltaEvent,
type TurnSnapshot,
type TurnStatus,
} from './types.js';
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
export interface ThreadStore {
load(threadId: string): Promise<ThreadSnapshot | null>;
save(thread: ThreadSnapshot): Promise<void>;
}
export class MemoryThreadStore implements ThreadStore {
private readonly threads = new Map<string, ThreadSnapshot>();
saveCount = 0;
async load(threadId: string): Promise<ThreadSnapshot | null> {
const thread = this.threads.get(threadId);
return thread ? clone(thread) : null;
}
async save(thread: ThreadSnapshot): Promise<void> {
this.saveCount++;
this.threads.set(thread.id, clone(thread));
}
}
export interface ProtocolRuntimeOptions {
store: ThreadStore;
now?: () => string;
newId?: (prefix: 'thread' | 'turn' | 'item') => string;
onEvent?: (event: ProtocolEvent) => void;
configDiagnostics?: boolean;
}
export class ProtocolInvariantError extends Error {
constructor(message: string) {
super(message);
this.name = 'ProtocolInvariantError';
}
}
export class ProtocolRuntime {
private readonly now: () => string;
private readonly newId: (prefix: 'thread' | 'turn' | 'item') => string;
constructor(private readonly options: ProtocolRuntimeOptions) {
this.now = options.now ?? (() => new Date().toISOString());
this.newId =
options.newId ??
((prefix) =>
`${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
}
initialize(): InitializeResult {
return {
protocolVersion: PROTOCOL_VERSION,
capabilities: {
threadResume: true,
turnInterrupt: true,
completedItemPersistence: true,
transientDeltas: true,
structuredToolEvents: true,
interactiveRequests: true,
configDiagnostics: this.options.configDiagnostics ?? false,
},
};
}
async startThread(cwd: string): Promise<ThreadSnapshot> {
const now = this.now();
const thread: ThreadSnapshot = {
id: this.newId('thread'),
cwd,
createdAt: now,
updatedAt: now,
turns: [],
};
await this.options.store.save(thread);
this.emit({ type: 'thread.started', thread: clone(thread) });
return clone(thread);
}
readThread(threadId: string): Promise<ThreadSnapshot | null> {
return this.options.store.load(threadId);
}
async resumeThread(threadId: string): Promise<ThreadSnapshot> {
return this.requireThread(threadId);
}
async startTurn(threadId: string, input: Record<string, unknown>): Promise<TurnSnapshot> {
const thread = await this.requireThread(threadId);
if (thread.turns.some((turn) => turn.status === 'in_progress')) {
throw new ProtocolInvariantError(`Thread ${threadId} already has an active turn`);
}
const now = this.now();
const inputItem = this.completedItem('user_message', input, now);
const turn: TurnSnapshot = {
id: this.newId('turn'),
threadId,
status: 'in_progress',
startedAt: now,
items: [inputItem],
};
thread.turns.push(turn);
thread.updatedAt = now;
await this.options.store.save(thread);
this.emit({ type: 'turn.started', threadId, turn: clone(turn) });
this.emit({ type: 'item.completed', threadId, turnId: turn.id, item: clone(inputItem) });
return clone(turn);
}
async appendCompletedItem(
threadId: string,
turnId: string,
type: CompletedItemType,
payload: Record<string, unknown>,
): Promise<CompletedItem> {
const thread = await this.requireThread(threadId);
const turn = this.requireTurn(thread, turnId);
if (turn.status !== 'in_progress') {
throw new ProtocolInvariantError(`Cannot append to terminal turn ${turnId}`);
}
const item = this.completedItem(type, payload, this.now());
turn.items.push(item);
thread.updatedAt = item.completedAt;
await this.options.store.save(thread);
this.emit({ type: 'item.completed', threadId, turnId, item: clone(item) });
return clone(item);
}
publishDelta(event: Omit<TransientDeltaEvent, 'type'>): void {
this.emit({ type: 'item.delta', ...event });
}
completeTurn(threadId: string, turnId: string): Promise<TurnSnapshot> {
return this.finishTurn(threadId, turnId, 'completed');
}
interruptTurn(threadId: string, turnId: string): Promise<TurnSnapshot> {
return this.finishTurn(threadId, turnId, 'interrupted');
}
failTurn(threadId: string, turnId: string): Promise<TurnSnapshot> {
return this.finishTurn(threadId, turnId, 'failed');
}
private async finishTurn(
threadId: string,
turnId: string,
requested: Exclude<TurnStatus, 'in_progress'>,
): Promise<TurnSnapshot> {
const thread = await this.requireThread(threadId);
const turn = this.requireTurn(thread, turnId);
if (turn.status !== 'in_progress') return clone(turn);
const now = this.now();
turn.status = requested;
turn.completedAt = now;
thread.updatedAt = now;
await this.options.store.save(thread);
const type =
requested === 'completed'
? 'turn.completed'
: requested === 'interrupted'
? 'turn.interrupted'
: 'turn.failed';
this.emit({ type, threadId, turn: clone(turn) } as DurableProtocolEvent);
return clone(turn);
}
private async requireThread(threadId: string): Promise<ThreadSnapshot> {
const thread = await this.options.store.load(threadId);
if (!thread) throw new ProtocolInvariantError(`Thread not found: ${threadId}`);
return thread;
}
private requireTurn(thread: ThreadSnapshot, turnId: string): TurnSnapshot {
const turn = thread.turns.find((candidate) => candidate.id === turnId);
if (!turn) throw new ProtocolInvariantError(`Turn not found: ${turnId}`);
return turn;
}
private completedItem(
type: CompletedItemType,
payload: Record<string, unknown>,
completedAt: string,
): CompletedItem {
return { id: this.newId('item'), type, payload: clone(payload), completedAt };
}
private emit(event: ProtocolEvent): void {
this.options.onEvent?.(event);
}
}
export class ProtocolRecorder {
private readonly records: DurableProtocolEvent[] = [];
record(event: ProtocolEvent): void {
if (isDurableEvent(event)) this.records.push(clone(event));
}
replay(consumer: (event: DurableProtocolEvent) => void): void {
for (const event of this.records) consumer(clone(event));
}
snapshot(): DurableProtocolEvent[] {
return clone(this.records);
}
}
function isDurableEvent(event: ProtocolEvent): event is DurableProtocolEvent {
return (
event.type === 'thread.started' ||
event.type === 'turn.started' ||
event.type === 'item.completed' ||
event.type === 'turn.completed' ||
event.type === 'turn.interrupted' ||
event.type === 'turn.failed'
);
}