-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
451 lines (361 loc) · 13 KB
/
agent.ts
File metadata and controls
451 lines (361 loc) · 13 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import type { ResponsesOptions } from '@xsai-ext/responses'
import type { AgentContext, Instructions, ItemParam } from '../types/base'
import type { AgentEvent } from '../types/event'
import type { AgentPlugin, AgentPluginApi, AgentPluginOption, PluginChannelListener, SessionInitOptions, SessionState } from '../types/plugin'
import type { AgentSession, SessionForkOptions } from './agent-session'
import { merge } from '@moeru/std/merge'
import { createAgentRuntime } from './agent-runtime'
export interface Agent<T> extends Omit<AgentSession<T>, 'fork' | 'id' | 'remove'> {
session: (options?: SessionOptions<T>) => AgentSession<T>
}
export interface CreateAgentOptions<T = unknown> {
context?: AgentContext<T>
input?: ItemParam[]
instructions: Instructions<T>
name: string
options: Omit<ResponsesOptions, 'abortSignal' | 'input' | 'instructions'>
plugins?: AgentPluginOption<T>[]
}
export interface SessionOptions<T> {
context?: Partial<AgentContext<T>>
episodic?: string
id?: string
input?: ItemParam[]
}
const DEFAULT_SESSION_ID = 'default'
const getSessionStorageKey = (agentName: string, sessionId: string) =>
JSON.stringify([agentName, sessionId])
const parseSessionState = <T>(value: null | string | undefined): SessionState<T> | undefined => {
if (value == null)
return undefined
try {
const state = JSON.parse(value) as Partial<SessionState<T>>
if (state == null || typeof state.episodic !== 'string' || typeof state.context !== 'object' || state.context == null)
return undefined
return state as SessionState<T>
}
catch {
return undefined
}
}
const normalizePlugins = <T>(plugins: AgentPluginOption<T>[]): AgentPlugin<T>[] =>
plugins.flatMap((plugin) => {
if (plugin == null || plugin === false)
return []
if (Array.isArray(plugin))
return normalizePlugins(plugin)
return [plugin]
})
const sortPlugins = <T>(plugins: AgentPluginOption<T>[]) => {
const order = { post: 2, pre: 0 } as const
return normalizePlugins(plugins).sort(
(a, b) => (order[a.enforce as keyof typeof order] ?? 1) - (order[b.enforce as keyof typeof order] ?? 1),
)
}
export const createAgent = <T = unknown>(options: CreateAgentOptions<T>): Agent<T> => {
const plugins = sortPlugins(options.plugins ?? [])
const channelListeners = new Map<string, Set<PluginChannelListener>>()
const sessions = new Map<string, AgentSession<T>>()
let context: AgentContext<T> = options.context ?? {} as AgentContext<T>
const pluginApi: AgentPluginApi = {
emit: (channel: string, event: unknown) => {
for (const listener of [...(channelListeners.get(channel) ?? [])]) {
try {
listener(event)
}
catch {}
}
},
subscribe: ((channel: string, listener: PluginChannelListener) => {
const listeners = channelListeners.get(channel) ?? new Set<PluginChannelListener>()
listeners.add(listener)
channelListeners.set(channel, listeners)
return () => listeners.delete(listener)
}) as AgentPluginApi['subscribe'],
}
const ready = (async () => {
for (const plugin of plugins)
await plugin.setup?.(pluginApi)
})()
void ready.catch(() => undefined)
const emit = (
sessionId: string,
turnId: string,
event: Omit<AgentEvent, 'sessionId' | 'turnId'>,
) => {
const fullEvent = { ...event, sessionId, turnId } as AgentEvent
for (const listener of [...(channelListeners.get('apeira') ?? [])]) {
try {
listener(fullEvent)
}
catch {}
}
void ready.then(async () => {
for (const plugin of plugins)
await plugin.onEvent?.(fullEvent)
}).catch(() => undefined)
}
const getContext: Agent<T>['getContext'] = () => context
const setContext: Agent<T>['setContext'] = nextContext =>
context = merge(context, nextContext)
const emitChannel: Agent<T>['emit'] = (channel, event) =>
pluginApi.emit(channel, event)
const subscribe = (channel: string, listener: PluginChannelListener) =>
pluginApi.subscribe(channel, listener)
const withSessionStorage = async (
sessionId: string,
fn: (storage: NonNullable<AgentPlugin<T>['storage']>, key: string) => Promise<void> | void,
) => {
const key = getSessionStorageKey(options.name, sessionId)
for (const plugin of plugins) {
if (plugin.storage == null)
continue
await fn(plugin.storage, key)
}
}
const saveSessionState = async (sessionId: string, state: SessionState<T>) => {
await withSessionStorage(sessionId, async (storage, key) => storage.setItem(key, JSON.stringify(state)))
}
const removeSessionState = async (sessionId: string) => {
await withSessionStorage(sessionId, async (storage, key) => storage.removeItem(key))
}
const createAgentSession = (id: string, sessionOptions: SessionOptions<T> = {}): AgentSession<T> => {
const initialSessionContext = sessionOptions.context ?? {}
let currentSessionContext = initialSessionContext
let removed = false
let removing = false
const sessionCleanups = new Set<() => boolean>()
const wrappedListeners = new WeakMap<PluginChannelListener, PluginChannelListener>()
const createRemovedSessionError = () =>
new Error(`Session removed: ${id}`)
const assertSessionOpen = () => {
if (removed || removing)
throw createRemovedSessionError()
}
const guard = <Args extends unknown[], Result>(fn: (...args: Args) => Result) =>
(...args: Args) => {
assertSessionOpen()
return fn(...args)
}
const guardAsync = <Args extends unknown[], Result>(fn: (...args: Args) => Promise<Result>) =>
async (...args: Args) => {
assertSessionOpen()
return fn(...args)
}
const resolveContext = (runContext?: Partial<AgentContext<T>>): AgentContext<T> =>
merge(merge(context, currentSessionContext), runContext)
let sessionReady: Promise<void> | undefined
const sessionCallbacks = {
ensureSessionReady: async (): Promise<void> => {},
}
const createSessionOptions = (send: (input: { context?: Partial<AgentContext<T>>, input: ItemParam, signal?: AbortSignal }) => string): SessionInitOptions<T> => ({
agentName: options.name,
context: resolveContext(),
send: input => send({ input }),
sessionId: id,
})
const loadSession = async (): Promise<SessionState<T> | undefined> => {
for (const plugin of plugins) {
if (plugin.storage == null)
continue
const value = await plugin.storage.getItem(getSessionStorageKey(options.name, id))
const state = parseSessionState<T>(value)
if (state != null) {
const mergedState = {
...state,
context: merge(initialSessionContext, state.context),
} satisfies SessionState<T>
currentSessionContext = mergedState.context
return mergedState
}
}
}
const saveSession = async (state: SessionState<T>) => {
currentSessionContext = state.context
await saveSessionState(id, state)
}
const runtime = createAgentRuntime({
agentName: options.name,
emit: (turnId, event) => emit(id, turnId, event),
episodic: sessionOptions.episodic,
getContext: resolveContext,
input: sessionOptions.input,
instructions: options.instructions,
loadSession,
onTurnDone: async (turnContext) => {
for (const plugin of plugins)
await plugin.onTurnDone?.(turnContext)
},
plugins,
ready: async () => sessionCallbacks.ensureSessionReady(),
responseOptions: options.options,
saveSession,
sessionContext: initialSessionContext,
sessionId: id,
})
sessionCallbacks.ensureSessionReady = async () => {
sessionReady ??= ready.then(async () => {
for (const plugin of plugins)
await plugin.onSessionInit?.(createSessionOptions(runtime.send))
})
return sessionReady
}
const subscribeSession = (channel: string, listener: PluginChannelListener) => {
const register = () => {
if (channel === 'apeira') {
let wrapped = wrappedListeners.get(listener)
if (!wrapped) {
wrapped = (event) => {
const agentEvent = event as AgentEvent
if (agentEvent.sessionId !== id)
return
const agentListener = listener as (event: AgentEvent) => void
agentListener(agentEvent)
}
wrappedListeners.set(listener, wrapped)
}
return pluginApi.subscribe('apeira', wrapped)
}
return pluginApi.subscribe(channel, listener)
}
const unsubscribe = register()
sessionCleanups.add(unsubscribe)
return () => {
sessionCleanups.delete(unsubscribe)
return unsubscribe()
}
}
const run: AgentSession<T>['run'] = guard((input, runOptions = {}) => {
const turnId = crypto.randomUUID()
let unsubscribe: (() => boolean) | undefined
return new ReadableStream<AgentEvent>({
cancel: () => {
unsubscribe?.()
},
start: (controller) => {
unsubscribe = subscribeSession('apeira', (event) => {
const agentEvent = event as AgentEvent
if (agentEvent.turnId !== turnId)
return
controller.enqueue(agentEvent)
if (
agentEvent.type === 'turn.aborted'
|| agentEvent.type === 'turn.done'
|| agentEvent.type === 'turn.failed'
) {
unsubscribe?.()
controller.close()
}
})
runtime.enqueueTurn({
context: runOptions.context,
id: turnId,
input,
signal: runOptions.signal,
})
},
})
})
const send: AgentSession<T>['send'] = guard((input, runOptions = {}) =>
runtime.send({
context: runOptions.context,
input,
signal: runOptions.signal,
}))
const interrupt: AgentSession<T>['interrupt'] = guard((reason) => {
runtime.interrupt(reason)
})
const setSessionContext: AgentSession<T>['setContext'] = guard((nextContext) => {
currentSessionContext = merge(currentSessionContext, nextContext)
runtime.setContext(nextContext)
})
const fork: AgentSession<T>['fork'] = guardAsync(async (forkOptions: SessionForkOptions<T> = {}) => {
const forkId = forkOptions.id ?? crypto.randomUUID()
if (sessions.has(forkId))
throw new Error(`Session already exists: ${forkId}`)
const snapshot = await runtime.snapshot()
const forkContext = merge(snapshot.context, forkOptions.context ?? {})
if (sessions.has(forkId))
throw new Error(`Session already exists: ${forkId}`)
const forked = createAgentSession(forkId, {
context: forkContext,
episodic: snapshot.episodic,
id: forkId,
})
sessions.set(forkId, forked)
try {
await saveSessionState(forkId, {
context: forkContext,
episodic: snapshot.episodic,
})
}
catch (error) {
sessions.delete(forkId)
throw error
}
return forked
})
const remove: AgentSession<T>['remove'] = async () => {
assertSessionOpen()
if (id === DEFAULT_SESSION_ID)
throw new Error(`Cannot remove default session: ${id}`)
removing = true
try {
await runtime.remove()
await removeSessionState(id)
for (const cleanup of sessionCleanups)
cleanup()
sessions.delete(id)
removed = true
}
catch (error) {
removing = false
throw error
}
}
return {
abort: guard(runtime.abort),
clear: guard(runtime.clear),
emit: guard(emitChannel),
fork,
getContext: guard(() => resolveContext()),
id,
interrupt,
remove,
run,
send,
setContext: setSessionContext,
subscribe: guard(subscribeSession) as AgentSession<T>['subscribe'],
}
}
const session: Agent<T>['session'] = (sessionOptions = {}) => {
const id = sessionOptions.id ?? crypto.randomUUID()
const existing = sessions.get(id)
if (existing != null) {
if (sessionOptions.input != null)
throw new Error(`Session already exists: ${id}`)
if (sessionOptions.context != null)
existing.setContext(sessionOptions.context)
return existing
}
const agentSession = createAgentSession(id, sessionOptions)
sessions.set(id, agentSession)
return agentSession
}
const defaultSession = session({
id: DEFAULT_SESSION_ID,
input: options.input,
})
return {
abort: reason => defaultSession.abort(reason),
clear: () => defaultSession.clear(),
emit: emitChannel,
getContext,
interrupt: reason => defaultSession.interrupt(reason),
run: (input, runOptions) => defaultSession.run(input, runOptions),
send: (input, runOptions) => defaultSession.send(input, runOptions),
session,
setContext,
subscribe: subscribe as Agent<T>['subscribe'],
}
}