Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

inputs.ts

1,499 lines49.3 KB

1import { EventType } from '@tanstack/ai'
2import { isRecord } from '../utils'
3import { isHumanTarget } from '../log-records'
4import { LogOwnedElsewhereError } from '../ownership'
5import { HARNESS_EVENTS, InputRejectedError } from '../types'
6import {
7 createInputId,
8 customEvent,
9 errorText,
10 storedUser,
11 inputKey,
12 isOfferedInputRecord,
13 loggedExtras,
14 offeredInputRecord,
15 turnRecords,
16 CHAT_OPS,
17 WORK_OPS,
18 lastAssistantText,
19 checkHostRecords,
20 dropOldest,
21} from './helpers'
22import { SessionBase } from './base'
23import { acceptedAs } from '../access'
24import type { AcceptedInput, AccessRun, AccessWait } from '../access'
25import type { OperationImpl } from '../operation'
26import type { LogRecord, OfferedInput } from '@tanstack/ai-persistence'
27import type { HarnessRecord, InputState } from '../log'
28import type { AnyHarness } from '../define'
29import type {
30 ChatTurnResult,
31 HarnessInput,
32 OfferedHarnessInput,
33 InputSettlement,
34 HarnessUser,
35 Receipt,
36 SessionEvent,
37 UserInput,
38 WaitingInput,
39} from '../types'
40import type { OfferedInputRecord, TurnExtras } from './helpers'
41import type { QueuedTurn, WaitingSteer } from './types'
42​
43/**
44 * How `accept` took an input. `offered`: another host owns the log, and the
45 * input waits for that host in the input lane of the log. `refused`: the
46 * `acceptInput` hook of the host refused it, with this reason. Nothing is
47 * stored.
48 */
49export type Admission =
50 | 'new'
51 | 'duplicate'
52 | 'conflict'
53 | 'closed'
54 | 'offered'
55 | 'deleted'
56 | { refused: string }
57​
58/** What `accept` stores with an input besides the input itself. */
59interface AcceptOptions {
60 /**
61 * The id that the input runs with: the AG-UI run id of a turn, or the
62 * operation id of an agent run. An offered input runs with it on the
63 * owner, so this host follows that id in the log.
64 */
65 runId?: string
66 /** The overrides, preamble, and ephemeral messages of a turn. */
67 turn?: TurnExtras
68 /** A valid W3C `traceparent` of the caller. The input record keeps it. */
69 traceparent?: string
70 /**
71 * The input that goes to the owner when another host owns the log, if it
72 * is not the input that this host logs. It throws to refuse the input.
73 */
74 offer?: () => Promise<OfferedHarnessInput>
75 /** More records for the append of a new input. */
76 records?: Array<HarnessRecord>
78​
79/** The offer that the next `accept` applies. See `applyOffer`. */
80interface ApplyingOffer {
81 inputId: string
82 /** Called when `accept` ends: the input is stored, or refused. */
83 stored: () => void
85​
86/**
87 * The access check of one input, before `accept` stores it: the input, and
88 * the run that an answer or a cancel targets. It throws to refuse the input.
89 * It can return the input to store (see `acceptInput`), or a refusal.
90 */
91export type InputCheck = (check: {
92 input: HarnessInput
93 run: AccessRun | undefined
94 /** The wait that an answer answers, when the session knows it. */
95 wait?: AccessWait
96}) => Promise<AcceptedInput | void>
97​
98/**
99 * A layer of {@link HarnessSession}: admitting inputs, receipts, and
100 * settlements.
101 */
102export abstract class SessionInputs<
103 THarness extends AnyHarness = AnyHarness,
104> extends SessionBase<THarness> {
105 /**
106 * Inputs that this host offered to the owner of the log. `settled` waits
107 * for them. The oldest ids go, as in the window of settled operations.
108 */
109 protected readonly offeredInputs = new Set<string>()
110​
111 /** The running turn that each joined steer operation ends with. */
112 protected readonly joinedTo = new WeakMap<
113 object,
114 OperationImpl<ChatTurnResult>
115 >()
116​
117 /** The check that the next `accept` runs. See `checked`. */
118 private pendingCheck: InputCheck | undefined
119 /** The offer that the next `accept` applies. See `applyOffer`. */
120 private applying: ApplyingOffer | undefined
121 /** The drain of the input lane that runs. See `drainOffers`. */
122 private draining: Promise<void> | undefined
123 /** An offer came while the drain ran: the drain reads the lane again. */
124 private drainAgain = false
125 /** The session opened: it can apply offers. Plugins and recovery are ready. */
126 protected acceptsOffers = false
127​
128 /**
129 * @internal Run `call`, and run `check` on the input that it stores,
130 * before the input is stored. The handle of `host.open` checks access
131 * through it. Each method that stores an input calls `accept` before its
132 * first `await`, so the check reaches the input of `call` and no other. A
133 * call that returns before `accept` stores nothing.
134 */
135 checked<T>(check: InputCheck, call: () => T): T {
136 this.pendingCheck = check
137 try {
138 return call()
139 } finally {
140 this.pendingCheck = undefined
141 }
142 }
143​
144 /**
145 * @internal The message of the input `inputId` in the log, or `undefined`.
146 * A client that sends an input again sends this message, so its inline
147 * media is not stored again and the duplicate check matches.
148 */
149 // ponytail: reads the log only. A retry that comes while the first copy
150 // is still being stored stores its media again.
151 knownMessage(inputId: string): UserInput | undefined {
152 const input = this.writer.state.inputs.get(inputId)?.input
153 return input && 'message' in input ? input.message : undefined
154 }
155​
156 /**
157 * The run that `input` answers or cancels, and who started it, when the
158 * session knows. Other inputs target no run.
159 */
160 protected runOf(input: HarnessInput): AccessRun | undefined {
161 switch (input.op) {
162 case 'resolve': {
163 // The interrupt of a background agent run: the log keeps its wait.
164 const first = input.resume[0]
165 const wait = first && this.loggedWait(first.interruptId)?.wait
166 if (wait) return { runId: wait.runId, ...idOf(wait.user) }
167 const stopped = this.interrupted
168 if (!stopped) return undefined
169 return { runId: stopped.runId, ...idOf(stopped.user) }
170 }
171 case 'answer': {
172 // The log keeps the wait with its run, so any host knows it.
173 const wait = this.loggedWait(input.questionId)?.wait
174 if (wait) return { runId: wait.runId, ...idOf(wait.user) }
175 const operationId = this.questions.get(input.questionId)?.operationId
176 return operationId === undefined
177 ? undefined
178 : this.startedBy(operationId)
179 }
180 case 'cancel': {
181 const operationId = input.operationId ?? this.activeTurn?.id
182 return operationId === undefined
183 ? undefined
184 : this.startedBy(operationId)
185 }
186 case 'cancelInput':
187 return { runId: input.inputId, ...idOf(this.senderOf(input.inputId)) }
188 case 'prompt':
189 case 'steer':
190 case 'followUp':
191 case 'continue':
192 case 'tool':
193 case 'reset':
194 case 'command':
195 case 'agent':
196 case 'agentMessage':
197 case 'setDelivery':
198 case 'background':
199 case 'append':
200 case 'configure':
201 case 'config':
202 case 'revert':
203 case 'unrevert':
204 return undefined
205 }
206 }
207​
208 /** The wait `waitId` that the log keeps, or `undefined`. */
209 protected loggedWait(waitId: string) {
210 return this.logWriter?.state.thread.waits.get(waitId)
211 }
212​
213 /**
214 * The wait that `input` answers, for the access check. An operator reply
215 * goes to the `human` wait of the handoff to a person. A resolve goes to
216 * a `human` wait that it ends.
217 */
218 protected waitOf(input: HarnessInput): AccessWait | undefined {
219 if (input.op === 'prompt' && input.as === 'operator') {
220 const paused = this.humanHandoff()
221 return paused ? { waitId: paused.waitId, kind: 'human' } : undefined
222 }
223 // A resolve that ends a `human` wait needs an operator too.
224 if (input.op === 'resolve') {
225 const human = input.resume
226 .map((item) => this.loggedWait(item.interruptId)?.wait)
227 .find((wait) => wait?.kind === 'human')
228 return human ? { waitId: human.waitId, kind: 'human' } : undefined
229 }
230 if (input.op !== 'answer') return undefined
231 const wait = this.loggedWait(input.questionId)?.wait
232 return wait ? { waitId: wait.waitId, kind: wait.kind } : undefined
233 }
234​
235 /**
236 * The handoff to a person that pauses the session, while its `human` wait
237 * is open. A user message then starts no model turn.
238 */
239 protected humanHandoff() {
240 const active = this.logWriter?.state.thread.activeAgent
241 return isHumanTarget(active) ? active : undefined
242 }
243​
244 /** The operation `operationId`, with the id of who started it when known. */
245 protected startedBy(operationId: string): AccessRun {
246 return { runId: operationId, ...idOf(this.userOfRun(operationId)) }
247 }
248​
249 /** Who started the operation `operationId`, when the session knows. */
250 protected userOfRun(operationId: string) {
251 const chain = this.chainOf.get(operationId)
252 const agentRun = [...(chain?.runs ?? []), ...(chain?.followUps ?? [])].find(
253 (run) => run.operation.id === operationId,
254 )
255 const inputId = this.operationInputs.get(operationId)
256 if (this.activeTurn?.id === operationId) return this.turnUser
257 if (agentRun) return agentRun.user
258 if (inputId !== undefined) return this.senderOf(inputId)
259 // A command: the log has the input that it runs.
260 return [...(this.logWriter?.state.inputs.values() ?? [])].find(
261 (input) => input.operationId === operationId,
262 )?.user
263 }
264​
265 /** Who sent the input `inputId`: from the log, or from what waits. */
266 protected senderOf(inputId: string) {
267 return (
268 this.writer.state.inputs.get(inputId)?.user ??
269 this.steerQueue.find((steer) => steer.inputId === inputId)?.user ??
270 this.queue.find((turn) => turn.inputId === inputId)?.user
271 )
272 }
273​
274 /**
275 * Append host records to the session log, in one batch after the events
276 * that wait. A `type` that starts with `harness.` is refused: the harness
277 * owns those.
278 * A record can name another session of the same log with `thread`. The
279 * append is all or nothing.
280 *
281 * With `durability.addRecordsToModelContext` on the harness, a record can change the model context. The
282 * running turn sees the change at its next model call.
283 *
284 * With `inputId`, the append is an input, as a `send` is: a second append
285 * with the same id is a duplicate and writes nothing, so a client can
286 * send it again after a lost answer. Without it, the append gets a new
287 * input id. `user` is who appends. Default: the user that
288 * opened the session. The receipt has the input id, as the log keeps it.
289 *
290 * @example
291 * ```ts
292 * await session.appendRecords({
293 * records: [{ type: 'app.signal', text: 'The build failed.' }],
294 * })
295 * ```
296 */
297 async appendRecords({
298 records,
299 inputId = createInputId(),
300 user,
301 }: {
302 records: ReadonlyArray<LogRecord>
303 inputId?: string
304 user?: HarnessUser
305 }): Promise<Receipt> {
306 checkHostRecords(records)
307 const { admission, input } = await this.accept(
308 inputId,
309 { op: 'append', records: [...records] },
310 this.actor(user),
311 )
312 if (admission !== 'new') return this.duplicateReceipt(inputId, admission)
313 // `acceptInput` can change the records.
314 if (input.records !== records) checkHostRecords(input.records)
315 // In the append of the applied record: a crash keeps both or neither.
316 await this.applied(inputId, 'session', input.records)
317 // Kept, so a duplicate gets the same receipt.
318 return this.keep({ inputId, status: 'accepted' })
319 }
320​
321 /**
322 * Cancel one operation, or the running chat turn. The abort request is
323 * stored first, so a turn that a crash stops later settles `aborted` and
324 * does not run again.
325 */
326 /**
327 * Move a running tool call to the background: the call returns at once,
328 * and the job keeps running. When it ends, a note tells the model and
329 * wakes an idle session. Without `toolCallId`, it moves every running
330 * call that supports it, such as `bash` and the agent tools.
331 * With no such call, the receipt is rejected with `not_running`.
332 * `user` is who moves it. Default: the user that opened the
333 * session. The `harness.job` record of each moved call keeps it. A handle
334 * of `host.open` checks that it is the user of the handle. The move
335 * stores no input.
336 *
337 * @example
338 * ```ts
339 * await session.moveToolCallToBackground()
340 * await session.moveToolCallToBackground({ toolCallId: 'call_1' })
341 * ```
342 */
343 async moveToolCallToBackground({
344 toolCallId,
345 user,
346 }: {
347 toolCallId?: string
348 user?: HarnessUser
349 } = {}): Promise<Receipt> {
350 const inputId = createInputId()
351 const ids =
352 toolCallId === undefined ? [...this.detachable.keys()] : [toolCallId]
353 const moves = ids.flatMap((id) => this.detachable.get(id) ?? [])
354 if (moves.length === 0) {
355 return { inputId, status: 'rejected', reason: 'not_running' }
356 }
357 for (const id of ids) this.detachable.delete(id)
358 for (const move of moves) move(user ?? this.user)
359 return { inputId, status: 'accepted' }
360 }
361​
362 /**
363 * The inputs that wait, in the order they run: first the steers for the
364 * running turn, then the queued turns. Change one with `cancelInput` or
365 * `changeInputDelivery`.
366 *
367 * @example
368 * ```ts
369 * for (const input of session.waitingInputs()) {
370 * if (input.delivery === 'queue') {
371 * await session.cancelInput({ inputId: input.inputId })
372 * }
373 * }
374 * ```
375 */
376 waitingInputs() {
377 const waiting: Array<WaitingInput> = []
378 // A steer with an abort request never runs. It settles with the turn.
379 for (const steer of this.steerQueue) {
380 if (this.isAbortRequested(steer.inputId)) continue
381 waiting.push({
382 inputId: steer.inputId,
383 delivery: 'steer',
384 message: steer.message,
385 })
386 }
387 // A resolve has no new message. Nor does a turn that recovery runs
388 // again, when the transcript has its message.
389 for (const turn of this.queue) {
390 if (turn.inputId === undefined || turn.message === undefined) continue
391 waiting.push({
392 inputId: turn.inputId,
393 delivery: 'queue',
394 message: turn.message,
395 })
396 }
397 return waiting
398 }
399​
400 /**
401 * How a chat input ended: `completed`, `failed`, `aborted`, or
402 * `interrupted` (the turn waits for human input). It waits until the input
403 * ends. It reads the log, so it also works after a restart and from
404 * another host that opens the thread. It also takes the input id of an
405 * agent run from the log.
406 *
407 * Rejects with `InputRejectedError` when the session refused the input,
408 * with an error for an id this session does not know, and with the reason
409 * of `signal` when it aborts first.
410 *
411 * @example
412 * ```ts
413 * const turn = session.send('Summarize the report.', { inputId: 'req-42' })
414 * const { outcome } = await session.settled({
415 * inputId: 'req-42',
416 * signal: AbortSignal.timeout(60_000),
417 * })
418 * ```
419 */
420 async settled({
421 inputId,
422 signal,
423 }: {
424 inputId: string
425 signal?: AbortSignal
426 }): Promise<InputSettlement> {
427 const known = this.knownSettlement(inputId)
428 if (known) return known
429 if (!this.isChatInput(inputId)) {
430 throw new Error(
431 `The session knows no chat input with the id ${JSON.stringify(inputId)}.`,
432 )
433 }
434 signal?.throwIfAborted()
435 // A refused input ends too: the owner on another host writes only its
436 // rejected record, and `knownSettlement` throws for it.
437 const settledEvent = (entry: SessionEvent) =>
438 entry.event.type === EventType.CUSTOM &&
439 (entry.event.name === HARNESS_EVENTS.inputSettled ||
440 entry.event.name === HARNESS_EVENTS.inputRejected) &&
441 isRecord(entry.event.value) &&
442 entry.event.value.inputId === inputId
443 for await (const entry of this.feed.read({
444 from: this.feed.head(),
445 filter: settledEvent,
446 ...(signal ? { signal } : {}),
447 })) {
448 // The owner refused the offer of this host: the log has another input
449 // with this id, and only this host ends with the refusal.
450 const value = entry.event.type === EventType.CUSTOM && entry.event.value
451 if (
452 isRecord(value) &&
453 value.offered === true &&
454 this.offeredInputs.has(inputId)
455 ) {
456 throw new InputRejectedError({
457 inputId,
458 status: 'rejected',
459 reason: typeof value.reason === 'string' ? value.reason : 'conflict',
460 })
461 }
462 const settlement = this.knownSettlement(inputId)
463 if (settlement) return settlement
464 }
465 signal?.throwIfAborted()
466 throw new Error('The session closed before the input ended.')
467 }
468​
469 protected enqueueTurn(turn: QueuedTurn): void {
470 this.queue.push(turn)
471 this.drain()
472 }
473​
474 /**
475 * Where a turn that runs next goes: after a resolve that answers the turn
476 * that just ended, and after the resets that wait, in their order.
477 */
478 protected frontOfQueue(): number {
479 const at = this.queue.findIndex((turn) => !turn.answers && !turn.reset)
480 return at < 0 ? this.queue.length : at
481 }
482​
483 protected isAbortRequested(inputId: string) {
484 return (
485 this.writer.state.inputs.get(inputId)?.abortRequested === true ||
486 this.abortedSteers.has(inputId)
487 )
488 }
489​
490 /**
491 * `steer` joined the running turn `operationId`: it settles with that
492 * turn, and a prompt that joined gets the turn's result.
493 */
494 protected join(
495 operationId: string,
496 steer: { inputId: string; operation?: OperationImpl<ChatTurnResult> },
497 ) {
498 const joined = this.turnJoins.get(operationId) ?? []
499 joined.push(steer.inputId)
500 this.turnJoins.set(operationId, joined)
501 const running = this.activeTurn
502 // The follower stays in `operations`, so `session.operation(id)` finds
503 // it. It ends as the running turn ends.
504 if (steer.operation && running) {
505 const follower = steer.operation
506 this.joinedTo.set(follower, running)
507 running.then(
508 (result) =>
509 follower.finish(
510 running.status() === 'interrupted' ? 'interrupted' : 'completed',
511 result,
512 ),
513 (error: unknown) =>
514 follower.fail(
515 running.status() === 'cancelled' ? 'cancelled' : 'failed',
516 error,
517 ),
518 )
519 }
520 this.feed.publish(
521 operationId,
522 customEvent(HARNESS_EVENTS.inputApplied, {
523 inputId: steer.inputId,
524 operationId,
525 }),
526 )
527 }
528​
529 /** The inputs that joined the turn of `hostInput` (or operation). */
530 protected joinedInputs(operationId: string, hostInput: string | undefined) {
531 if (hostInput !== undefined) {
532 return [...this.writer.state.inputs.values()]
533 .filter(
534 (input) => input.status === 'joined' && input.into === hostInput,
535 )
536 .map((input) => input.inputId)
537 }
538 return this.turnJoins.get(operationId) ?? []
539 }
540​
541 /**
542 * Take a waiting input out of the steers or the queue, so it does not run
543 * from there. `undefined` when it does not wait: it started, a join holds
544 * it, it has an abort request, or the id is not known.
545 */
546 protected takeWaiting(inputId: string) {
547 const steer = this.steerQueue.find(
548 (item) =>
549 item.inputId === inputId &&
550 !this.joining.has(inputId) &&
551 !this.isAbortRequested(inputId),
552 )
553 // This shifts the later steers. `claimJoins` sees that and skips them.
554 if (steer) {
555 this.steerQueue.splice(this.steerQueue.indexOf(steer), 1)
556 return steer
557 }
558 const turn = this.queue.find((item) => item.inputId === inputId)
559 const message = turn?.message
560 if (!turn || message === undefined) return undefined
561 this.queue.splice(this.queue.indexOf(turn), 1)
562 const taken: WaitingSteer = {
563 inputId,
564 message,
565 operation: turn.operation,
566 overrides: turn.overrides,
567 ephemeral: turn.ephemeral,
568 ...(turn.outputSchema ? { outputSchema: turn.outputSchema } : {}),
569 user: turn.user,
570 context: turn.context,
571 ...(turn.wake ? { wake: true } : {}),
572 }
573 return taken
574 }
575​
576 /** Take a queued `continueWithoutMessage()` out of the queue, for `cancelInput`. */
577 protected takeQueuedContinue(
578 inputId: string,
579 ): Pick<WaitingSteer, 'operation'> | undefined {
580 const turn = this.queue.find(
581 (item) => item.inputId === inputId && item.isContinue,
582 )
583 if (!turn) return undefined
584 this.queue.splice(this.queue.indexOf(turn), 1)
585 return { operation: turn.operation }
586 }
587​
588 /**
589 * The thread waits for interrupts and nothing queued or running can
590 * resolve them, so a new turn would fail with `pending_interrupts`.
591 */
592 protected waitsForInterrupts(): boolean {
593 return (
594 this.interrupted !== undefined &&
595 this.activeTurn === undefined &&
596 this.queue.length === 0
597 )
598 }
599​
600 /**
601 * Mark a `cancelInput` or `setDelivery` input applied. `change` lands in
602 * the same append, so a crash never keeps one without the other.
603 */
604 protected async applyControl(inputId: string, change: HarnessRecord) {
605 // Also an input that recovery took: it has no other end.
606 this.inputRecords.end(inputId)
607 await this.writer.append([
608 change,
609 {
610 type: 'harness.input.applied',
611 inputId,
612 operationId: 'session',
613 attempt: 1,
614 },
615 ])
616 }
617​
618 // ===========================
619 // Inputs and lifecycle events
620 // ===========================
621​
622 /**
623 * Store an input, unless its id is known. The check before the first
624 * `await` is synchronous, so a second call with the same id in the same
625 * tick is a duplicate too. `user` is who sent it. The access check of
626 * a `checked` call runs first: a refused input is not stored, and the
627 * error rejects this call. The `turn` record goes in the append of the
628 * input, so a crash keeps both or neither.
629 *
630 * When another host owns the log, the input goes to that host through the
631 * input lane (`offered`). An input from the lane (see `applyOffer`)
632 * consumes its offer in the same append.
633 */
634 protected async accept<TInput extends HarnessInput>(
635 inputId: string,
636 input: TInput,
637 user: HarnessUser | undefined,
638 options: AcceptOptions = {},
639 ): Promise<{ admission: Admission; input: TInput }> {
640 // Before the first `await`: only this call takes them.
641 const offer = this.applying?.inputId === inputId ? this.applying : undefined
642 if (offer) this.applying = undefined
643 const check = this.pendingCheck
644 this.pendingCheck = undefined
645 try {
646 const accepted = check ? await this.checkInput(check, input) : input
647 if ('refuse' in accepted) {
648 return { admission: { refused: accepted.refuse }, input }
649 }
650 const admission = await this.admit({
651 inputId,
652 input: accepted,
653 user,
654 options,
655 offer,
656 })
657 // A retry with the input as its caller sent it is the same input.
658 if (admission === 'new' && accepted !== input) {
659 this.inputRecords.screened.set(
660 inputId,
661 inputKey(input, storedUser(user).user),
662 )
663 }
664 return { admission, input: accepted }
665 } finally {
666 offer?.stored()
667 }
668 }
669​
670 /** Run the access check and `acceptInput` of `check` on `input`. */
671 private async checkInput<TInput extends HarnessInput>(
672 check: InputCheck,
673 input: TInput,
674 ): Promise<TInput | { refuse: string }> {
675 const wait = this.waitOf(input)
676 const accepted = await check({
677 input,
678 run: this.runOf(input),
679 ...(wait ? { wait } : {}),
680 })
681 return accepted ? acceptedAs(input, accepted) : input
682 }
683​
684 private async admit({
685 inputId,
686 input,
687 user,
688 options,
689 offer,
690 }: {
691 inputId: string
692 input: HarnessInput
693 user: HarnessUser | undefined
694 options: AcceptOptions
695 offer: ApplyingOffer | undefined
696 }): Promise<Admission> {
697 const sender = storedUser(user)
698 const traced =
699 options.traceparent === undefined
700 ? {}
701 : { traceparent: options.traceparent }
702 const known = this.knownAdmission(inputId, inputKey(input, sender.user))
703 const consumes = offer ? [inputId] : []
704 if (known) {
705 // The input ran before: its offer goes, and it does not run again.
706 // An offer with another payload is refused, so its host stops waiting.
707 if (offer && known === 'conflict') await this.refuseOffer(inputId)
708 else if (offer) await this.writer.append([], { consumes })
709 return known
710 }
711 // A closing session runs no new work. Nothing is stored. An offer stays
712 // for the next owner.
713 if (this.closing && WORK_OPS.has(input.op)) return 'closed'
714 this.admitted.set(inputId, inputKey(input, sender.user))
715 try {
716 const records = [
717 ...(options.turn ? turnRecords(inputId, options.turn) : []),
718 ...(options.records ?? []),
719 ]
720 await this.writer.append(
721 [
722 {
723 type: 'harness.input',
724 inputId,
725 input,
726 at: Date.now(),
727 ...sender,
728 ...traced,
729 },
730 ...records,
731 ],
732 { consumes },
733 )
734 } catch (error) {
735 // Not stored, so a retry with the same id is a new input.
736 this.admitted.delete(inputId)
737 if (!(error instanceof LogOwnedElsewhereError)) throw error
738 // Another host owns the log. An offer stays for it. Else the input
739 // goes to it.
740 if (offer) return 'offered'
741 return await this.offerInput({ inputId, input, user, options })
742 }
743 // An input with no work to run (a cancel, a setting) ends once stored.
744 if (!WORK_OPS.has(input.op)) this.inputRecords.end(inputId)
745 this.feed.publish(
746 'session',
747 // The feed scrubs the session's secrets from the message.
748 customEvent(HARNESS_EVENTS.inputAccepted, {
749 inputId,
750 op: input.op,
751 ...('message' in input ? { message: input.message } : {}),
752 }),
753 )
754 return 'new'
755 }
756​
757 /**
758 * `duplicate` or `conflict` for an input id that is known, else
759 * `undefined`. The log keeps an input without the secrets of the session,
760 * so both sides are compared without them: a retry with a secret in it is
761 * a duplicate.
762 */
763 private knownAdmission(inputId: string, payload: string) {
764 const logged = this.writer.state.inputs.get(inputId)
765 const known =
766 this.admitted.get(inputId) ??
767 (logged ? inputKey(logged.input, logged.user) : undefined)
768 if (known === undefined) return undefined
769 const { scrub } = this.redactor
770 return scrub(known) === scrub(payload) ? 'duplicate' : 'conflict'
771 }
772​
773 /**
774 * Another host owns the log: offer the input to it. The owner runs it, and
775 * this host reads how it ends in the log. The receipt is `queued`.
776 */
777 private async offerInput({
778 inputId,
779 input,
780 user,
781 options,
782 }: {
783 inputId: string
784 input: HarnessInput
785 user: HarnessUser | undefined
786 options: AcceptOptions
787 }): Promise<Admission> {
788 const { offer, ...extras } = options
789 const record = offeredInputRecord({
790 inputId,
791 input: offer ? await offer() : input,
792 user,
793 ...extras,
794 })
795 const offered = await this.writer.offer(inputId, record)
796 // The thread was deleted: the input is refused with the reason `deleted`.
797 if (offered === 'conflict' || offered === 'deleted') return offered
798 this.offeredInputs.add(inputId)
799 dropOldest(this.offeredInputs, this.retention.keepSettledOperations)
800 return 'offered'
801 }
802​
803 /**
804 * Apply the inputs that other hosts offered to this thread, in offer
805 * order: the input lane. Only the owner of the log applies them. This host
806 * gets the log first, and does nothing while another live host owns it.
807 * Each input runs as if it came to this host. Its record consumes its
808 * offer in the same append, so it never runs twice. One call runs at a
809 * time: a call while a drain runs makes that drain read the lane again.
810 * The thread is busy while a drain runs, so it does not close on idle
811 * before it applied the offers.
812 */
813 protected drainOffers(): Promise<void> {
814 if (this.draining) {
815 this.drainAgain = true
816 return this.draining
817 }
818 const run = async () => {
819 do {
820 this.drainAgain = false
821 await this.drainOnce()
822 } while (this.drainAgain && !this.closing)
823 }
824 this.draining = this.admitting(run).finally(() => {
825 this.draining = undefined
826 })
827 return this.draining
828 }
829​
830 private async drainOnce(): Promise<void> {
831 const writer = this.logWriter
832 const isReady =
833 writer !== undefined &&
834 this.acceptsOffers &&
835 !this.closing &&
836 !this.logFailure
837 if (!isReady) return
838 try {
839 // ponytail: a host that waits for its own offer reads the lane after
840 // each append of the owner. A store that can say "offer" in its
841 // notification could skip those reads.
842 if ((await writer.offered()).length === 0) return
843 if (!(await writer.own())) return
844 } catch (error) {
845 this.warnSession('harness:inputs', error)
846 return
847 }
848 try {
849 // This host takes the log from an owner that stopped. Its work runs
850 // first, as on an open.
851 if (this.recoveryDeferred) {
852 this.recoveryDeferred = false
853 try {
854 await this.recoverFromLog(writer)
855 } catch (error) {
856 this.recoveryDeferred = true
857 throw error
858 }
859 }
860 // Read again as the owner: no other host consumes offers now.
861 const offers = await writer.offered()
862 for (const offer of offers) {
863 if (this.closing || this.logFailure || writer.fenced) return
864 await this.applyOffer(offer)
865 }
866 } catch (error) {
867 this.warnSession('harness:inputs', error)
868 }
869 }
870​
871 /**
872 * Apply one offer, and wait until `accept` stored or refused its input.
873 * An offer that no `accept` takes (a record of another kind, or a call
874 * that ends before `accept`, such as a duplicate prompt) goes, so the
875 * lane does not keep it. A record of `host.transfer` is appended as it is.
876 */
877 private async applyOffer(offer: OfferedInput) {
878 const { inputId, record } = offer
879 const isInput = isOfferedInputRecord(record) && record.inputId === inputId
880 if (isInput) {
881 let stored = () => {}
882 const done = new Promise<void>((resolve) => {
883 stored = resolve
884 })
885 this.applying = { inputId, stored }
886 let isTaken = false
887 try {
888 this.applyOffered(record)
889 } finally {
890 isTaken = this.applying === undefined
891 this.applying = undefined
892 }
893 if (isTaken) {
894 await done
895 return
896 }
897 // A prompt with a known id ends before `accept`. One with another
898 // payload is refused, so the host that offered it stops waiting.
899 const payload = inputKey(record.input, record.user)
900 if (this.knownAdmission(inputId, payload) === 'conflict') {
901 await this.refuseOffer(inputId)
902 return
903 }
904 }
905 // `host.transfer` on a host that does not own the log offers records
906 // here: the source end of the transfer, and the usage of its summary.
907 // They go in the log as they are. A transfer that the log has already
908 // only drops its offer. An unshare or a revoke offers the end of the
909 // schedules of the user, so they go from the list at once.
910 const isLaneRecord =
911 record.type === 'harness.usage' ||
912 record.type === 'harness.transferred' ||
913 record.type === 'harness.schedule.done'
914 const isKnown =
915 record.type === 'harness.transferred' &&
916 typeof record.transferId === 'string' &&
917 this.writer.state.thread.transfers.has(record.transferId)
918 const records = isLaneRecord && !isKnown ? [record] : []
919 await this.writer.append(records, { consumes: [inputId] })
920 for (const each of records) this.publishTransferred(each)
921 }
922​
923 /**
924 * Run an offered input as if it came to this host. Nobody here waits for
925 * its result: the host that offered it reads the log. Each call reaches
926 * `accept` before its first `await`, so `accept` takes the offer.
927 */
928 private applyOffered(record: OfferedInputRecord): void {
929 const session = this.self()
930 const { input, inputId, user } = record
931 const asUser = user ? { user } : {}
932 const run = record.runId !== undefined ? { runId: record.runId } : {}
933 const turn = record.overrides ? loggedExtras(record.overrides) : {}
934 const traced =
935 record.traceparent !== undefined
936 ? { traceparent: record.traceparent }
937 : {}
938 const sent = {
939 inputId,
940 ...asUser,
941 ...('context' in input && input.context !== undefined
942 ? { context: input.context }
943 : {}),
944 }
945 const ignore = (work: PromiseLike<unknown>) => {
946 work.then(
947 () => {},
948 () => {},
949 )
950 }
951 // A host with access does not run an input that names no user.
952 if (!user && this.hasAccess) {
953 ignore(this.refuseOffer(inputId, 'no_user'))
954 return
955 }
956 // Set before the switch: each call reads `actor` before its first await.
957 this.anonymousOffer = !user
958 try {
959 switch (input.op) {
960 case 'prompt':
961 ignore(
962 this.sendForRun(input.message, {
963 ...sent,
964 ...turn,
965 ...(input.busy ? { busy: input.busy } : {}),
966 ...(input.as ? { as: input.as } : {}),
967 ...run,
968 ...traced,
969 }),
970 )
971 return
972 case 'continue':
973 ignore(session.continueWithoutMessage({ ...sent, ...turn }))
974 return
975 case 'steer':
976 ignore(
977 session.send(input.message, {
978 ...sent,
979 ...turn,
980 ...traced,
981 mode: 'steer',
982 }),
983 )
984 return
985 case 'followUp':
986 ignore(
987 this.startTurn(input, {
988 ...sent,
989 ...turn,
990 ...traced,
991 mode: 'followUp',
992 ...(input.wake ? { wake: true } : {}),
993 }),
994 )
995 return
996 case 'resolve':
997 ignore(this.resolveForRun({ resume: input.resume, ...sent, ...run }))
998 return
999 case 'reset':
1000 ignore(session.reset({ note: input.note, ...sent }))
1001 return
1002 case 'configure':
1003 ignore(
1004 session.updateThreadSettings({ settings: input.settings, ...sent }),
1006 return
1007 case 'agentMessage':
1008 ignore(
1009 session.send(input.message, {
1010 ...sent,
1011 to: input.operationId,
1012 mode: input.mode,
1013 }),
1015 return
1016 case 'agent':
1017 ignore(
1018 this.runAgent(input.agent, input.input, {
1019 ...asUser,
1020 ...(input.detached ? { startTurnWhenDone: true } : {}),
1021 ...(input.runAgainAfterCrash ? { runAgainAfterCrash: true } : {}),
1022 ...(input.addResultNote === false
1023 ? { addResultNote: false }
1024 : {}),
1025 offered: { inputId, ...run },
1026 }),
1028 return
1029 case 'cancel':
1030 ignore(
1031 session.cancel({
1032 operationId: input.operationId,
1033 inputId,
1034 ...asUser,
1035 }),
1037 return
1038 case 'cancelInput':
1039 ignore(
1040 this.applyCancelInput({
1041 inputId: input.inputId,
1042 controlId: inputId,
1043 ...asUser,
1044 }),
1046 return
1047 case 'setDelivery':
1048 ignore(
1049 this.applySetDelivery({
1050 inputId: input.inputId,
1051 delivery: input.delivery,
1052 controlId: inputId,
1053 ...asUser,
1054 }),
1056 return
1057 case 'command':
1058 ignore(
1059 session.runCommand({
1060 name: input.name,
1061 input: input.input,
1062 inputId,
1063 ...asUser,
1064 }),
1066 return
1067 case 'answer':
1068 ignore(
1069 this.applyAnswer({
1070 questionId: input.questionId,
1071 value: input.value,
1072 ...(input.ref !== undefined ? { ref: input.ref } : {}),
1073 controlId: inputId,
1074 ...asUser,
1075 }),
1077 return
1078 case 'config':
1079 ignore(
1080 this.applyConfig({
1081 key: input.key,
1082 value: input.value,
1083 controlId: inputId,
1084 ...asUser,
1085 }),
1087 return
1088 case 'tool':
1089 ignore(
1090 session.runTool({
1091 name: input.name,
1092 // Wire args are unknown here. The tool's input schema checks them.
1093 args: input.args as never,
1094 inputId,
1095 ...asUser,
1096 ...(input.meta ? { meta: input.meta } : {}),
1097 }),
1099 return
1100 case 'append':
1101 // Only an append with an input id is an input that a host offers.
1102 ignore(
1103 session.appendRecords({
1104 records: input.records,
1105 inputId,
1106 ...asUser,
1107 }),
1109 return
1110 case 'revert':
1111 case 'unrevert':
1112 case 'background':
1113 // These run only where they are called. No host offers them.
1114 return
1116 } finally {
1117 this.anonymousOffer = false
1120​
1121 /**
1122 * Does the log of this thread have a run with this id? A client run id
1123 * must not reuse it. The log id has the tenant, so another tenant's run
1124 * with this id is not here.
1125 */
1126 protected isRunTaken(runId: string) {
1127 return this.writer.state.thread.runs.has(runId)
1129​
1130 /**
1131 * Record that `operationId` runs the input, and count the attempt.
1132 * `records` go first in the same append, so a crash keeps both or neither.
1133 * `deadline`: an epoch ms time limit of the run (an agent run's own limit,
1134 * or its parent's). The earlier of it and `durability.timeoutMs` wins.
1135 */
1136 protected async markApplied(
1137 inputId: string,
1138 operationId: string,
1139 records: ReadonlyArray<LogRecord> = [],
1140 deadline?: number,
1141 ): Promise<void> {
1142 const logged = this.writer.state.inputs.get(inputId)
1143 const timeoutMs = this.harness.durability?.timeoutMs
1144 const limits = [
1145 ...(timeoutMs !== undefined ? [Date.now() + timeoutMs] : []),
1146 ...(deadline !== undefined ? [deadline] : []),
1148 // Stamped once, at the first apply. Retries do not move it.
1149 const timeoutAt =
1150 logged?.timeoutAt ?? (limits.length > 0 ? Math.min(...limits) : undefined)
1151 await this.writer.append([
1152 ...records,
1154 type: 'harness.input.applied',
1155 inputId,
1156 operationId,
1157 attempt: (logged?.attempt ?? 0) + 1,
1158 ...(timeoutAt !== undefined ? { timeoutAt } : {}),
1159 },
1160 ])
1162​
1163 /** {@link markApplied}, then the `harness.input.applied` event. */
1164 protected async applied(
1165 inputId: string,
1166 operationId: string,
1167 records: ReadonlyArray<LogRecord> = [],
1168 deadline?: number,
1169 ): Promise<void> {
1170 await this.markApplied(inputId, operationId, records, deadline)
1171 this.feed.publish(
1172 operationId,
1173 customEvent(HARNESS_EVENTS.inputApplied, { inputId, operationId }),
1176​
1177 /** Refuse an input. Returns its rejected receipt. */
1178 protected reject(inputId: string, reason: string) {
1179 void this.writer
1180 .append([{ type: 'harness.input.rejected', inputId, reason }])
1181 .catch(() => {})
1182 const receipt: Receipt = { inputId, status: 'rejected', reason }
1183 this.inputRecords.reject(receipt)
1184 this.feed.publish(
1185 'session',
1186 customEvent(HARNESS_EVENTS.inputRejected, { inputId, reason }),
1188 return receipt
1190​
1191 /**
1192 * Refuse an offer whose id the log has with another payload. The record
1193 * consumes the offer in the same append. The input in the log does not
1194 * change: the event has `offered`, so only the host that offered the
1195 * input ends its wait with the refusal.
1196 */
1197 private async refuseOffer(inputId: string, reason = 'conflict') {
1198 await this.writer.append(
1199 [{ type: 'harness.offer.rejected', inputId, reason }],
1200 { consumes: [inputId] },
1202 this.feed.publish(
1203 'session',
1204 customEvent(HARNESS_EVENTS.inputRejected, {
1205 inputId,
1206 reason,
1207 offered: true,
1208 }),
1211​
1212 /**
1213 * Record how inputs ended, all in one append: a turn and the inputs that
1214 * joined it settle together. Clients get a `harness.input.settled` event.
1215 */
1216 protected settle(...settlements: Array<InputSettlement>): Promise<void> {
1217 return this.settleWith(settlements, [])
1219​
1220 /** {@link settle}, with `records` first in the same append. */
1221 protected async settleWith(
1222 settlements: ReadonlyArray<InputSettlement>,
1223 records: ReadonlyArray<LogRecord>,
1224 ): Promise<void> {
1225 await this.writer.append([
1226 ...records,
1227 ...settlements.map((settlement) => ({
1228 type: 'harness.input.settled',
1229 ...settlement,
1230 })),
1231 ])
1232 for (const settlement of settlements) {
1233 this.inputRecords.settle(settlement)
1234 this.feed.publish(
1235 settlement.operationId ?? 'session',
1236 customEvent(HARNESS_EVENTS.inputSettled, { ...settlement }),
1240​
1241 /** How a chat input ended, when it did. Throws for a refused input. */
1242 protected knownSettlement(inputId: string): InputSettlement | undefined {
1243 const logged = this.writer.state.inputs.get(inputId)
1244 if (logged?.settlement) return logged.settlement
1245 const refused =
1246 logged?.status === 'rejected'
1247 ? {
1248 inputId,
1249 status: 'rejected' as const,
1250 reason: rejectedReason(logged),
1252 : this.inputRecords.receipt(inputId)
1253 if (refused?.status === 'rejected') throw new InputRejectedError(refused)
1254 return this.inputRecords.settlement(inputId)
1256​
1257 protected isChatInput(inputId: string) {
1258 const input = this.writer.state.inputs.get(inputId)?.input
1259 // A reset, an agent run, and a message to an agent run in the log
1260 // settle their input too.
1261 if (input)
1262 return (
1263 CHAT_OPS.has(input.op) ||
1264 input.op === 'reset' ||
1265 input.op === 'agent' ||
1266 input.op === 'agentMessage'
1268 return (
1269 this.turnOperations.has(inputId) ||
1270 this.inputRecords.receipt(inputId) !== undefined ||
1271 this.offeredInputs.has(inputId)
1274​
1275 /** Link a turn operation and its input. */
1276 protected bindTurn(
1277 inputId: string,
1278 operation: OperationImpl<ChatTurnResult>,
1279 ) {
1280 this.inputRecords.bind(inputId, operation)
1282​
1283 /** Keep a chat input's receipt, for a duplicate of the input. */
1284 protected keep(receipt: Receipt) {
1285 return this.inputRecords.keep(receipt)
1287​
1288 /** Resolve a turn's receipt, and keep it for a duplicate. */
1289 protected answerTurn(
1290 operation: OperationImpl<ChatTurnResult>,
1291 receipt: Receipt,
1292 ) {
1293 operation.resolveReceipt(this.keep(receipt))
1294 // Only the owner answers a turn, so the input waits in its queue.
1295 if (receipt.status === 'queued') {
1296 this.publishQueued(receipt.inputId, 'queue')
1299​
1300 /** The input `inputId` waits behind the running turn, or the turns before it. */
1301 protected publishQueued(inputId: string, delivery: WaitingInput['delivery']) {
1302 this.feed.publish(
1303 'session',
1304 customEvent(HARNESS_EVENTS.inputQueued, { inputId, delivery }),
1307​
1308 /**
1309 * Publish `harness.transferred` for the transfer end `record`, after this
1310 * host appended it. Other records get no event.
1311 */
1312 protected publishTransferred(record: LogRecord) {
1313 if (record.type !== 'harness.transferred') return
1314 const { transferId, from, to } = record
1315 if (typeof transferId !== 'string') return
1316 const threadOf = (link: unknown) =>
1317 isRecord(link) && typeof link.threadId === 'string'
1318 ? { threadId: link.threadId }
1319 : undefined
1320 const source = threadOf(from)
1321 const target = threadOf(to)
1322 this.feed.publish(
1323 'session',
1324 customEvent(HARNESS_EVENTS.transferred, {
1325 transferId,
1326 ...(source ? { from: source } : {}),
1327 ...(target ? { to: target } : {}),
1328 }),
1331​
1332 protected refuse(operation: OperationImpl<ChatTurnResult>, receipt: Receipt) {
1333 // A conflict refuses a second payload. The id stays with the input that
1334 // has it, so `settled()` of that input does not read this refusal.
1335 const id = receipt.inputId
1336 const isOtherInput =
1337 receipt.status === 'rejected' &&
1338 receipt.reason === 'conflict' &&
1339 (this.admitted.has(id) || this.writer.state.inputs.has(id))
1340 if (isOtherInput) operation.resolveReceipt(receipt)
1341 else this.answerTurn(operation, receipt)
1342 operation.fail('failed', new InputRejectedError(receipt))
1344​
1345 /** What a duplicate or a conflicting chat input gets back. */
1346 protected duplicateReceipt(
1347 inputId: string,
1348 admission: Exclude<Admission, 'new'>,
1349 ): Receipt {
1350 if (typeof admission === 'object') {
1351 return { inputId, status: 'rejected', reason: admission.refused }
1353 if (admission !== 'duplicate' && admission !== 'offered') {
1354 return { inputId, status: 'rejected', reason: admission }
1356 if (admission === 'offered') return { inputId, status: 'queued' }
1357 const kept = this.inputRecords.receipt(inputId)
1358 if (kept) return kept
1359 const operationId = this.writer.state.inputs.get(inputId)?.operationId
1360 return {
1361 inputId,
1362 status: 'accepted',
1363 ...(operationId ? { operationId } : {}),
1366​
1367 /** End `operation` with a stored settlement. */
1368 protected settleOperation(
1369 operation: OperationImpl<ChatTurnResult>,
1370 settlement: InputSettlement,
1371 ) {
1372 const text = this.turnText(settlement.inputId)
1373 switch (settlement.outcome) {
1374 case 'completed':
1375 operation.finish('completed', { text, media: [] })
1376 return
1377 case 'interrupted': {
1378 // The interrupts wait still only when this turn stopped last.
1379 const stopped = this.interrupted
1380 const interrupts =
1381 stopped && stopped.runId === settlement.operationId
1382 ? stopped.interrupts
1383 : []
1384 operation.finish('interrupted', { text, interrupts, media: [] })
1385 return
1387 case 'aborted':
1388 operation.fail('cancelled', new Error('Cancelled.'))
1389 return
1390 case 'failed':
1391 operation.fail(
1392 'failed',
1393 new Error(settlement.error?.message ?? 'The input failed.'),
1395 return
1398​
1399 /**
1400 * The answer of the turn that ran `inputId`, from the log: the last
1401 * assistant text from where that turn started to where the next one
1402 * started. A joined input reads the turn it joined. Empty when the log
1403 * does not know where the turn started.
1404 */
1405 // ponytail: positions in the transcript. A revert that drops messages
1406 // moves them, and a note added after the turn counts as its text. Keep the
1407 // answer on the settlement record if that matters.
1408 protected turnText(inputId: string): string {
1409 const { state } = this.writer
1410 const own = state.inputs.get(inputId)
1411 const from = (own?.into ? state.inputs.get(own.into) : own)?.appliedAt
1412 if (from === undefined) return ''
1413 // Only a turn or a reset starts a new part of the transcript. An answer,
1414 // a command, or an agent run is applied during a turn too.
1415 const starts = [...state.inputs.values()]
1416 .filter(
1417 (input) => CHAT_OPS.has(input.input.op) || input.input.op === 'reset',
1419 .map((input) => input.appliedAt ?? -1)
1420 .filter((at) => at > from)
1421 // `appliedAt` is a transcript position.
1422 const to = Math.min(state.transcript.length, ...starts)
1423 return lastAssistantText(state.transcript.slice(from, to))
1425​
1426 protected publishStarted(
1427 operation: OperationImpl<unknown> | OperationImpl<ChatTurnResult>,
1428 ): void {
1429 operation.publish(
1430 customEvent(HARNESS_EVENTS.operationStarted, {
1431 operationId: operation.id,
1432 kind: operation.kind,
1433 ...(operation.agent ? { agent: operation.agent } : {}),
1434 }),
1436 if (this.tracing) {
1437 // A turn has its input: its record keeps the `traceparent` of the
1438 // caller, also when another host took the input.
1439 const inputId = this.inputRecords.operationInputs.get(operation.id)
1440 const logged =
1441 inputId === undefined
1442 ? undefined
1443 : this.logWriter?.state.inputs.get(inputId)
1444 this.tracing.started(operation, {
1445 parentRunId: this.parentRunOf(operation.id),
1446 traceparent: logged?.traceparent,
1447 })
1450​
1451 protected publishFinished(
1452 operation: OperationImpl<unknown> | OperationImpl<ChatTurnResult>,
1453 ): void {
1454 operation.publish(
1455 customEvent(HARNESS_EVENTS.operationFinished, {
1456 operationId: operation.id,
1457 status: operation.status(),
1458 }),
1461​
1462 /**
1463 * A store write threw where no code catches it. Fail the operation, so no
1464 * caller waits for it forever.
1465 */
1466 protected failOperation(
1467 operation: OperationImpl<unknown> | OperationImpl<ChatTurnResult>,
1468 error: unknown,
1469 ): void {
1470 if (operation.isSettled()) return
1471 // A cancelled operation ends cancelled. Its cancel event is out already.
1472 // A log failure aborts operations too, but they fail and say why.
1473 if (operation.abortController.signal.aborted && !this.logFailure) {
1474 operation.fail('cancelled', this.logFailure ?? error)
1475 } else {
1476 operation.publish({
1477 type: EventType.RUN_ERROR,
1478 message: this.scrub(errorText(this.logFailure ?? error)),
1479 timestamp: Date.now(),
1480 })
1481 operation.fail('failed', this.logFailure ?? error)
1483 this.publishFinished(operation)
1486​
1487/** The `userId` field of an {@link AccessRun}, when the run has a user. */
1488const idOf = (user: { id: string } | undefined) =>
1489 user ? { userId: user.id } : {}
1490​
1491/** The reason of a rejected input record. A rejected record always has one. */
1492function rejectedReason(logged: InputState): string {
1493 if (logged.reason === undefined) {
1494 throw new Error(
1495 `The log has a rejected input "${logged.inputId}" with no reason.`,
1498 return logged.reason