Open History to see the last commit
1import { AccessDeniedError } from '../access'
2import { InputRejectedError } from '../types'
3import { isSameSender } from './helpers'
4import type {
5 AcceptedInput,
6 AccessAction,
7 AccessRun,
8 AccessWait,
9} from '../access'
10import type { AnyHarness } from '../define'
11import type {
12 AgentSendOptions,
13 HarnessInput,
14 Operation,
15 OperationKind,
16 HarnessUser,
17 SendOptions,
18 UserInput,
19} from '../types'
20import type { SessionImpl } from './harness-session'
21import type { AgentRunOptions, AgentStartOptions } from './types'
22
23/** What the handle of a host with access checks. */
24export interface HandleGuard {
25 /** Throws `AccessDeniedError` unless `authorize` allows `action` now. */
26 authorize: (
27 action: AccessAction,
28 run?: AccessRun,
29 wait?: AccessWait,
30 ) => Promise<void>
31 /** `host.revoke` took the access of the user of the handle. */
32 isRevoked: () => boolean
33 /**
34 * Call `listener` when `host.revoke` (or `unshare`) takes the access of
35 * the user of the handle. Returns a function that stops the calls.
36 */
37 onRevoke: (listener: () => void) => () => void
38}
39
40/**
41 * @internal The items of `read`, until `signal` aborts or `onRevoke` calls
42 * its listener. A revoke ends the read with `AccessDeniedError`, so a read
43 * that started before the revoke stops too. The listener is added at the
44 * call, not at the first pull, so a revoke between them ends the read too.
45 *
46 * ponytail: an iterable that is never read keeps its listener until the
47 * revoke.
48 */
49export function untilRevoked<T>({
50 onRevoke,
51 threadId,
52 signal,
53 read,
54}: {
55 onRevoke: HandleGuard['onRevoke']
56 threadId: string
57 signal: AbortSignal | undefined
58 read: (signal: AbortSignal) => AsyncIterable<T>
59}): AsyncGenerator<T> {
60 const revoked = new AbortController()
61 const stop = onRevoke(() => revoked.abort())
62 return (async function* () {
63 try {
64 yield* read(
65 signal ? AbortSignal.any([signal, revoked.signal]) : revoked.signal,
66 )
67 } finally {
68 stop()
69 }
70 if (revoked.signal.aborted) {
71 throw new AccessDeniedError({ action: 'read', threadId })
72 }
73 })()
74}
75
76/** How a handle reaches the shared session of its thread. The host gives one. */
77export interface HandleLease<THarness extends AnyHarness> {
78 /** The open session of the thread, or `undefined` when none is open now. */
79 current: () => SessionImpl<THarness> | undefined
80 /**
81 * Open the session of the thread again, with the checks of `host.open`.
82 * Throws at once when the host is closed.
83 */
84 reopen: () => Promise<SessionImpl<THarness>>
85 /**
86 * One holder less. `dropped`: the garbage collector dropped the handle,
87 * so the host warns. Resolves after the close that the release starts.
88 */
89 release: (options?: { dropped?: boolean }) => Promise<void>
90}
91
92/** What the finalizer of a handle needs. It must not hold the handle. */
93interface HandleToken {
94 isReleased: boolean
95 release: (options: { dropped: boolean }) => Promise<void>
96}
97
98/** Release a handle that its holder dropped without `close()`. */
99function releaseDropped(token: HandleToken) {
100 if (token.isReleased) return
101 token.isReleased = true
102 void token.release({ dropped: true })
103}
104
105const dropped = new FinalizationRegistry(releaseDropped)
106const tokens = new WeakMap<object, HandleToken>()
107
108/**
109 * @internal Run the finalizer of `handle`, as if the garbage collector
110 * dropped it. Tests use it, as a test cannot force a collection.
111 */
112export function finalizeHandle(handle: object) {
113 const token = tokens.get(handle)
114 if (!token) return
115 dropped.unregister(token)
116 releaseDropped(token)
117}
118
119/**
120 * @internal Throws `AccessDeniedError` unless `authorize` allows `input`. An
121 * answer or a resolve of a `human` wait needs the `operator` action, not
122 * `answer`.
123 */
124export async function authorizeInput({
125 authorize,
126 input,
127 run,
128 wait,
129}: {
130 authorize: HandleGuard['authorize']
131 input: HarnessInput
132 run: AccessRun | undefined
133 wait: AccessWait | undefined
134}) {
135 const action = actionOf(input)
136 // A `human` wait takes an operator, not the user who waits for a person.
137 const isHuman = action === 'answer' && wait?.kind === 'human'
138 await authorize(isHuman ? 'operator' : action, run, wait)
139}
140
141/** @internal The action that `authorize` gets for an input. */
142export function actionOf(input: HarnessInput): AccessAction {
143 switch (input.op) {
144 case 'resolve':
145 case 'answer':
146 return 'answer'
147 case 'cancel':
148 case 'cancelInput':
149 return 'cancel'
150 case 'configure':
151 case 'config':
152 return 'configure'
153 // An operator reply answers the `human` wait of a handoff.
154 case 'prompt':
155 return input.as === 'operator' ? 'operator' : 'send'
156 case 'steer':
157 case 'followUp':
158 case 'continue':
159 case 'tool':
160 case 'reset':
161 case 'command':
162 case 'agent':
163 case 'agentMessage':
164 case 'setDelivery':
165 case 'background':
166 case 'append':
167 case 'revert':
168 case 'unrevert':
169 return 'send'
170 }
171}
172
173/** A listener that waits for the operation of a session that opens again. */
174interface Waiting {
175 member: 'onEvent' | 'onMedia'
176 args: Array<unknown>
177 stop: (() => void) | undefined
178}
179
180/**
181 * The operation of a call on a session that opens again. `call` runs on the
182 * session once it opened, and each member waits for that. `id` is known only
183 * then: await `receipt` before you read it.
184 */
185function laterOperation<TSession, TOperation extends Operation<unknown>>({
186 kind,
187 agent,
188 opening,
189 call,
190}: {
191 kind: OperationKind
192 agent: string | undefined
193 opening: Promise<TSession>
194 call: (session: TSession) => TOperation
195}) {
196 let bound: TOperation | undefined
197 const waiting = new Set<Waiting>()
198 // Wrapped: an operation is thenable, so a promise of it would wait for its
199 // result.
200 const started = opening.then((session) => {
201 const operation = call(session)
202 bound = operation
203 for (const entry of waiting) {
204 entry.stop = Reflect.apply(operation[entry.member], operation, entry.args)
205 }
206 return { operation }
207 })
208 /** `use` of the operation, once it started. */
209 const ready = <R>(use: (operation: TOperation) => R) =>
210 started.then(({ operation }) => use(operation))
211 const receipt = ready((operation) => operation.receipt)
212 // A caller that never awaits a failed open gets no unhandled rejection.
213 receipt.catch(() => {})
214 const listen =
215 (member: Waiting['member']) =>
216 (...args: Array<unknown>) => {
217 if (bound) return Reflect.apply(bound[member], bound, args)
218 const entry: Waiting = { member, args, stop: undefined }
219 waiting.add(entry)
220 return () => {
221 waiting.delete(entry)
222 entry.stop?.()
223 }
224 }
225 async function* events(
226 options?: Parameters<Operation<unknown>['events']>[0],
227 ) {
228 const { operation } = await started
229 yield* operation.events(options)
230 }
231 async function* stream(
232 options?: Parameters<Operation<unknown>['stream']>[0],
233 ) {
234 const { operation } = await started
235 yield* operation.stream(options)
236 }
237 return {
238 get id() {
239 if (!bound) {
240 throw new Error(
241 'The session of this operation opens again. Await operation.receipt before you read operation.id.',
242 )
243 }
244 return bound.id
245 },
246 get kind() {
247 return bound?.kind ?? kind
248 },
249 get agent() {
250 return bound?.agent ?? agent
251 },
252 status: () => bound?.status() ?? 'accepted',
253 receipt,
254 then: <TResult1, TResult2>(
255 onfulfilled?: (value: unknown) => TResult1 | PromiseLike<TResult1>,
256 onrejected?: (reason: unknown) => TResult2 | PromiseLike<TResult2>,
257 ) => ready((operation) => operation).then(onfulfilled, onrejected),
258 events,
259 stream,
260 onEvent: listen('onEvent'),
261 onMedia: listen('onMedia'),
262 cancel: (reason?: string) => ready((operation) => operation.cancel(reason)),
263 // An agent run takes messages.
264 ...(kind === 'agent'
265 ? {
266 send: (...args: Array<unknown>) =>
267 ready((operation) =>
268 'send' in operation && typeof operation.send === 'function'
269 ? Reflect.apply(operation.send, operation, args)
270 : Promise.reject(new Error('This operation takes no message.')),
271 ),
272 }
273 : {}),
274 }
275}
276
277/**
278 * The members that read the stored state of the session. On a session that
279 * closed under a live handle, they open it again. The other members that
280 * return a value at once read the last state of the session.
281 */
282const REOPENING_READS: ReadonlySet<PropertyKey> = new Set([
283 'transcript',
284 'agentTranscript',
285 'logState',
286 'indexEntry',
287 'settled',
288])
289
290type Session<THarness extends AnyHarness> = SessionImpl<THarness>
291
292/**
293 * A handle to the shared session of a thread, that `host.open` returns,
294 * bound to `user`: a call that passes no `user` acts as it. It has
295 * every member of the session, and `this` stays the session.
296 *
297 * `close()` (or `await using`) releases only this handle: `lease` counts the
298 * handles, and the host closes the session when none holds it and it is
299 * idle. After `close()`, every call on the handle throws. A handle that its
300 * holder drops is released by the garbage collector, with a warning.
301 *
302 * A live handle holds its session, but the session can still close under
303 * it (its log failed, or `host.sessions.delete` ran). The next call opens
304 * it again through `lease`.
305 *
306 * With `guard` (the host has access), each action asks `authorize` first. An
307 * input is checked before the session stores it. `acceptInput` then gets
308 * the input, and returns the input to store or a refusal. A call that passes
309 * another user throws. After `host.revoke`, every call throws
310 * `AccessDeniedError`. Reads ask `authorize` once, when the host opens the
311 * handle, and again when it opens the session again.
312 */
313export function sessionHandle<THarness extends AnyHarness>({
314 session,
315 user,
316 guard,
317 acceptInput,
318 lease,
319}: {
320 session: Session<THarness>
321 user: HarnessUser | undefined
322 guard?: HandleGuard
323 /** The `acceptInput` of the host, for the user of this handle. */
324 acceptInput?: (input: HarnessInput) => Promise<AcceptedInput>
325 lease: HandleLease<THarness>
326}) {
327 const { threadId } = session
328 /** The last session that this handle used. */
329 let last = session
330 const token: HandleToken = {
331 isReleased: false,
332 release: (options) => lease.release(options),
333 }
334 /** Throws when this handle is closed, or a revoke took its access. */
335 const live = (action: AccessAction) => {
336 if (token.isReleased) {
337 throw new Error('This handle is closed. Call host.open again.')
338 }
339 if (guard?.isRevoked()) throw new AccessDeniedError({ action, threadId })
340 }
341 /** The open session, or `undefined` when it closed. */
342 const open = () => {
343 const current = lease.current()
344 if (current) last = current
345 return current
346 }
347 /** The open session. On a session that closed, open it again. */
348 const opened = async () => open() ?? (last = await lease.reopen())
349 /**
350 * Run `call` on the open session. On a session that closed, open it again.
351 * An open session gets the call in this tick.
352 */
353 const run = async <T>(call: (target: Session<THarness>) => Promise<T>) =>
354 call(open() ?? (last = await lease.reopen()))
355 /**
356 * `run` for a call that returns an operation at once. On a session that
357 * closed, the operation waits for the open.
358 */
359 const runOperation = <T extends Operation<unknown>>(
360 kind: OperationKind,
361 call: (target: Session<THarness>) => T,
362 agent?: string,
363 ) => {
364 const current = open()
365 if (current) return call(current)
366 // Called at once, so a closed host throws at once.
367 const opening = lease.reopen().then((reopened) => (last = reopened))
368 return laterOperation({ kind, agent, opening, call })
369 }
370 /** Who acts in a call that passes `passed`. */
371 const actor = (passed: HarnessUser | undefined) => {
372 if (passed === undefined) return user
373 const isOther = guard !== undefined && !isSameSender(passed, user)
374 if (isOther) {
375 throw new Error(
376 `This handle acts as ${JSON.stringify(user?.id)}. Open another handle for ${JSON.stringify(passed.id)}.`,
377 )
378 }
379 return passed
380 }
381 /** `options`, with the user that acts. */
382 const as = <T extends { user?: HarnessUser }>(options: T) => {
383 const acting = actor(options.user)
384 return acting ? { ...options, user: acting } : options
385 }
386 /** `call` on `target`, which stores an input: the session checks it first. */
387 const checkedOn = <T>(
388 target: Session<THarness>,
389 call: (target: Session<THarness>) => T,
390 ) =>
391 guard || acceptInput
392 ? target.checked(
393 async ({ input, run: accessRun, wait }) => {
394 if (guard) {
395 await authorizeInput({
396 authorize: guard.authorize,
397 input,
398 run: accessRun,
399 wait,
400 })
401 }
402 return acceptInput?.(input)
403 },
404 () => call(target),
405 )
406 : call(target)
407 /** A call that stores an input and resolves to its receipt. */
408 const storing = <T>(
409 action: AccessAction,
410 call: (target: Session<THarness>) => Promise<T>,
411 ) => {
412 live(action)
413 return run((target) => checkedOn(target, call))
414 }
415 /** The operations that `guarded` wrapped, so one operation gets one wrapper. */
416 const wrapped = new WeakMap<object, unknown>()
417 /**
418 * `operation`, with its `cancel` and `send` through this handle: they act
419 * as the user of the handle, after `authorize` allows them.
420 */
421 const guarded = <T extends Operation<unknown>>(operation: T): T => {
422 const known = wrapped.get(operation)
423 if (known) return known as T
424 const proxy = new Proxy(operation, {
425 get(target, key) {
426 if (key === 'cancel') {
427 return async () => cancel({ operationId: target.id })
428 }
429 const value: unknown = Reflect.get(target, key)
430 if (typeof value !== 'function') return value
431 if (key === 'send') {
432 return async (
433 message: UserInput,
434 options?: Omit<AgentSendOptions, 'to'>,
435 ) => {
436 const sent = send(message, { ...options, to: target.id })
437 const receipt = await sent.receipt
438 // A refused access check throws, as the calls of the handle do.
439 if (receipt.status === 'rejected') {
440 await Promise.resolve(sent).catch((error: unknown) => {
441 if (error instanceof AccessDeniedError) throw error
442 })
443 }
444 return receipt
445 }
446 }
447 return value.bind(target)
448 },
449 })
450 wrapped.set(operation, proxy)
451 return proxy
452 }
453 /** A call that stores an input and returns its operation. */
454 const storingOperation = <T extends Operation<unknown>>(
455 kind: OperationKind,
456 call: (target: Session<THarness>) => T,
457 agent?: string,
458 ) => {
459 live('send')
460 return runOperation(
461 kind,
462 (target) => guarded(checkedOn(target, call)),
463 agent,
464 )
465 }
466 /**
467 * A call that stores no input: it runs after `authorize` allows `action`.
468 * With a guard, `runOf` gives the run that the call targets, when it
469 * targets one.
470 */
471 const acting = <T>(
472 action: AccessAction,
473 call: (target: Session<THarness>) => Promise<T>,
474 runOf?: (
475 target: Session<THarness>,
476 ) => AccessRun | undefined | Promise<AccessRun | undefined>,
477 ) => {
478 live(action)
479 return run(async (target) => {
480 if (guard) await guard.authorize(action, await runOf?.(target))
481 return call(target)
482 })
483 }
484 const agentOf = (name: string) => ({
485 run: (input?: unknown, options?: AgentRunOptions) =>
486 storingOperation(
487 'agent',
488 (target) =>
489 target.agentHandle(name, actor(options?.user)).run(input, options),
490 name,
491 ),
492 start: (input?: unknown, options?: AgentStartOptions) =>
493 storingOperation(
494 'agent',
495 (target) =>
496 target.agentHandle(name, actor(options?.user)).start(input, options),
497 name,
498 ),
499 })
500 const agents = new Proxy(session.agents, {
501 get: (_target, name) =>
502 typeof name === 'string' ? agentOf(name) : undefined,
503 })
504 /** Release this handle. A second call does nothing. */
505 const close = () => {
506 if (token.isReleased) return Promise.resolve()
507 token.isReleased = true
508 dropped.unregister(token)
509 return lease.release()
510 }
511 type EventsOptions = Parameters<Session<THarness>['events']>[0]
512 /** `events` of a session that closed: it opens again first. */
513 async function* reopenedEvents(options: EventsOptions) {
514 yield* (await opened()).events(options)
515 }
516 const events = (options?: EventsOptions) => {
517 live('read')
518 const current = open()
519 const read = (next?: EventsOptions) =>
520 current ? current.events(next) : reopenedEvents(next)
521 if (!guard) return read(options)
522 // A revoke ends a read that runs now, not only the next call.
523 return untilRevoked({
524 onRevoke: guard.onRevoke,
525 threadId,
526 signal: options?.signal,
527 read: (signal) => read({ ...options, signal }),
528 })
529 }
530 const send = (message: UserInput, options?: SendOptions | AgentSendOptions) =>
531 storingOperation(options?.to === undefined ? 'chat' : 'agent', (target) =>
532 options?.to === undefined
533 ? target.send(message, as(options ?? {}))
534 : target.send(message, as(options)),
535 )
536 const sendForRun = (
537 message: UserInput,
538 options?: Parameters<Session<THarness>['sendForRun']>[1],
539 ) =>
540 storingOperation('chat', (target) =>
541 target.sendForRun(message, as(options ?? {})),
542 )
543 const cancel = (options?: Parameters<Session<THarness>['cancel']>[0]) =>
544 storing('cancel', (target) => target.cancel(as(options ?? {})))
545 /** The operation `id` of the session, through this handle. */
546 const operationOf = <T extends Operation<unknown>>(
547 find: (target: Session<THarness>) => T | undefined,
548 ) => {
549 live('read')
550 const found = find(open() ?? last)
551 return found && guarded(found)
552 }
553 const methods = new Map<PropertyKey, unknown>([
554 ...Object.entries({
555 send,
556 sendForRun,
557 // A returned operation cancels, and an agent run takes messages,
558 // through this handle too.
559 operation: (id: string) => operationOf((target) => target.operation(id)),
560 agentRun: (id: string) => operationOf((target) => target.agentRun(id)),
561 runTool: (options: Parameters<Session<THarness>['runTool']>[0]) =>
562 storingOperation('chat', (target) => target.runTool(as(options))),
563 continueWithoutMessage: (
564 options?: Parameters<Session<THarness>['continueWithoutMessage']>[0],
565 ) =>
566 storingOperation('chat', (target) =>
567 target.continueWithoutMessage(as(options ?? {})),
568 ),
569 runCommand: (options: Parameters<Session<THarness>['runCommand']>[0]) =>
570 storingOperation('command', (target) => target.runCommand(as(options))),
571 reset: (options?: Parameters<Session<THarness>['reset']>[0]) =>
572 storing('send', (target) => target.reset(as(options ?? {}))),
573 changeInputDelivery: (
574 options: Parameters<Session<THarness>['changeInputDelivery']>[0],
575 ) => storing('send', (target) => target.changeInputDelivery(as(options))),
576 resolve: (options: Parameters<Session<THarness>['resolve']>[0]) =>
577 storing('answer', (target) => target.resolve(as(options))),
578 resolveForRun: (
579 options: Parameters<Session<THarness>['resolveForRun']>[0],
580 ) => storing('answer', (target) => target.resolveForRun(as(options))),
581 answer: (options: Parameters<Session<THarness>['answer']>[0]) =>
582 storing('answer', (target) => target.answer(as(options))),
583 cancel,
584 cancelInput: (options: Parameters<Session<THarness>['cancelInput']>[0]) =>
585 storing('cancel', (target) => target.cancelInput(as(options))),
586 updateThreadSettings: (
587 options: Parameters<Session<THarness>['updateThreadSettings']>[0],
588 ) =>
589 storing('configure', (target) =>
590 target.updateThreadSettings(as(options)),
591 ),
592 setPluginSetting: (
593 options: Parameters<Session<THarness>['setPluginSetting']>[0],
594 ) =>
595 storing('configure', (target) => target.setPluginSetting(as(options))),
596 agents,
597 agent: (name: string) => {
598 live('read')
599 return (open() ?? last).agent(name) === undefined
600 ? undefined
601 : agentOf(name)
602 },
603 appendRecords: (
604 options: Parameters<Session<THarness>['appendRecords']>[0],
605 ) => storing('send', (target) => target.appendRecords(as(options))),
606 // These store no input, so the handle asks `authorize` itself.
607 revert: (options: Parameters<Session<THarness>['revert']>[0]) =>
608 acting('send', (target) => target.revert(as(options))),
609 unrevert: () => acting('send', (target) => target.unrevert()),
610 moveToolCallToBackground: (
611 options?: Parameters<Session<THarness>['moveToolCallToBackground']>[0],
612 ) =>
613 acting('send', (target) =>
614 target.moveToolCallToBackground(as(options ?? {})),
615 ),
616 putMedia: (upload: Parameters<Session<THarness>['putMedia']>[0]) =>
617 acting('send', (target) => target.putMedia(upload)),
618 updateIndexEntry: (
619 update: Parameters<Session<THarness>['updateIndexEntry']>[0],
620 ) => acting('configure', (target) => target.updateIndexEntry(update)),
621 reloadPlugins: () =>
622 acting('configure', (target) => target.reloadPlugins()),
623 // A schedule needs the action of the input it runs later. An answer or
624 // a cancel is checked with its run from the log, which must exist now.
625 schedule: (options: Parameters<Session<THarness>['schedule']>[0]) =>
626 acting(
627 actionOf(options.input),
628 (target) => target.schedule(as(options)),
629 async (target) => {
630 const found = await target.loggedRun(options.input)
631 if (found !== null) return found
632 // A user with no access to the action learns nothing of the run.
633 await guard?.authorize(actionOf(options.input))
634 throw new InputRejectedError({
635 inputId: `schedule:${options.scheduleId ?? 'new'}`,
636 status: 'rejected',
637 reason: 'unknown_run',
638 })
639 },
640 ),
641 cancelSchedule: (
642 options: Parameters<Session<THarness>['cancelSchedule']>[0],
643 ) =>
644 acting(
645 'cancel',
646 (target) => target.cancelSchedule(options),
647 (target) => target.scheduleRun(options.scheduleId),
648 ),
649 events,
650 close,
651 }),
652 [Symbol.asyncDispose, close],
653 ])
654 // ponytail: a Proxy, so the handle has every member of the session and
655 // stays an instance of it. Only the members above change. The other
656 // members run on the open session, or on the last one when it closed.
657 const handle = new Proxy(session, {
658 get(_target, key) {
659 if (methods.has(key)) return methods.get(key)
660 const target = open() ?? last
661 const value: unknown = Reflect.get(target, key)
662 if (typeof value !== 'function') return value
663 if (REOPENING_READS.has(key)) {
664 return (...args: Array<unknown>) => {
665 live('read')
666 return run(async (reopened) => {
667 const member: unknown = Reflect.get(reopened, key)
668 return typeof member === 'function'
669 ? Reflect.apply(member, reopened, args)
670 : member
671 })
672 }
673 }
674 return (...args: Array<unknown>) => {
675 live('read')
676 return Reflect.apply(value, target, args)
677 }
678 },
679 })
680 tokens.set(handle, token)
681 dropped.register(handle, token, token)
682 return handle
683}