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

requests.ts

1,434 lines50.9 KB

1import { RUN_CANCEL_REASON } from '@tanstack/ai'
2import { changedEntry } from '../session-entry'
3import { OperationImpl } from '../operation'
4import { parseTraceparent } from '../observability'
5import { HARNESS_EVENTS, InputRejectedError } from '../types'
6import { timeOf } from '../waits'
7import {
8 signInConnector,
9 createInputId,
10 customEvent,
11 errorText,
12 inputKey,
13 isSameSender,
14 SHUTDOWN_REASON,
15} from './helpers'
16import { SessionState } from './state'
17import type { InferSchemaType, ModelMessage, SchemaInput } from '@tanstack/ai'
18import type { SessionIndexEntry } from '@tanstack/ai-persistence'
19import type { PluginSessionApi, Question } from '../commands'
20import type { AnyHarness, HarnessToolInput, HarnessToolsOf } from '../define'
21import type {
22 AgentSendOptions,
23 CancelOptions,
24 ChatTurnResult,
25 Cursor,
26 HarnessInput,
27 Operation,
28 HarnessUser,
29 Receipt,
30 ResetOptions,
31 ResolveOptions,
32 SendForRunOptions,
33 SendOptions,
34 TurnOverrides,
35 UserInput,
36 WaitingInput,
37} from '../types'
38import type {
39 HarnessChild,
40 QueuedTurn,
41 ResolveForRunOptions,
42 WaitingSteer,
43} from './types'
44import type { Admission } from './inputs'
45import type { HeldPlugins } from './helpers'
46​
47/**
48 * A layer of {@link HarnessSession}: prompt, steer, follow-up, continue, reset,
49 * resolve, and cancel.
50 */
51export abstract class SessionRequests<
52 THarness extends AnyHarness = AnyHarness,
53> extends SessionState<THarness> {
54 /**
55 * The plugins of turns that are not disposed yet: a turn, or a run that it
56 * started, still runs. `close()` disposes them.
57 */
58 protected readonly turnPlugins = new Set<HeldPlugins>()
59​
60 // ===========================
61 // Inputs
62 // ===========================
63​
64 /**
65 * Send a message to the session, or to one of its agent runs.
66 *
67 * `mode` is how it runs. `'prompt'` (default) starts a chat turn, or
68 * queues it while one runs (see `busy`). `'steer'` adds it to the running
69 * turn at its next model call, and the operation ends with that turn.
70 * With no turn running, it runs as its own turn. `'followUp'` runs a turn
71 * after all current work.
72 *
73 * `to` is the operation id of an agent run. The message goes to that run,
74 * as `AgentRun.send` does: a steer waits for the run's next model call, a
75 * follow-up runs the agent again after the run ends. The operation ends
76 * with the run that gets the message. An unknown run, or one that another
77 * host runs, is rejected with `'not_running'`.
78 *
79 * `inputId` is an id you choose. A second send with the same id and the
80 * same message returns the first input's operation and does not run again.
81 * The same id with another message is rejected with `'conflict'`.
82 * `await operation.receipt` resolves when the input is stored.
83 *
84 * `overrides` changes the adapter or model, model options, reasoning,
85 * prompt cache, or tools of this turn only (see `TurnOverrides`). The log
86 * keeps the JSON ones, so a turn that recovery runs again uses them. A
87 * steer that joins the running turn uses the overrides of that turn, and
88 * its own are ignored.
89 *
90 * `user` is who sent the message. Default: the user that opened
91 * the session. The log keeps it, and the turn runs with its credentials
92 * and provider keys. A steer that joins the running turn runs with the
93 * credentials of that turn's sender. An input the log stored with no
94 * user runs with no user. It does not take the user of the session
95 * that owns the thread. A host with access refuses that input.
96 *
97 * `context` is JSON data from the client, stored with the input. Tools
98 * get it in their context (see `HarnessConfig.context`). Do not trust it.
99 *
100 * `ephemeral` are messages that each model call of this turn gets, after
101 * the transcript and the new user message, before the messages that the
102 * turn adds (answers, tool results, steers). The transcript does not
103 * keep them. The log keeps them with the input, so a turn that recovery
104 * runs again has them too. Like `overrides`, they are not part of the
105 * input: the `inputId` duplicate check does not read them, so a retry with
106 * other ephemeral messages gets the first input's operation and its own
107 * are dropped. A steer that joins the running turn ignores them.
108 *
109 * `systemPreamble` are system prompts that this turn gets ahead of the
110 * harness prompts, for example memory that the host adds. They are kept
111 * like `overrides`, and only server code sets them. A client input cannot
112 * set them.
113 *
114 * `outputSchema` goes to the `chat()` call of the turn, as
115 * `chat({ outputSchema })`. The result has the checked value as
116 * `structured`. A failed check fails the turn with the `chat()` error code
117 * and the model text (`rawText`). Only server code sets it. The log does
118 * not keep it, so a turn that recovery runs again runs without it, and
119 * the session warns. A steer that joins the running turn ignores it.
120 *
121 * `as: 'operator'` is the reply of a person who took over after a handoff
122 * to a person. It goes in the transcript as an assistant message, and no
123 * model turn runs. It needs the `operator` access action and an open
124 * `human` wait of a handoff, else the receipt is rejected with
125 * `'no_human_wait'`. While that wait is open, other messages go in the
126 * transcript, and no model turn runs either: the turn settles
127 * `interrupted`.
128 *
129 * @example
130 * ```ts
131 * await session.send('I refunded order 42.', { as: 'operator' })
132 * ```
133 */
134 send(message: UserInput, options: AgentSendOptions): Operation<unknown>
135 send<TSchema extends SchemaInput>(
136 message: UserInput,
137 options: SendOptions & { outputSchema: TSchema },
138 ): Operation<ChatTurnResult<InferSchemaType<TSchema>>>
139 send(
140 message: UserInput,
141 options?: SendOptions & { outputSchema?: undefined },
142 ): Operation<ChatTurnResult<undefined>>
143 send(message: UserInput, options?: SendOptions): Operation<ChatTurnResult>
144 send(
145 message: UserInput,
146 options?: SendOptions | AgentSendOptions,
147 ): Operation<unknown> {
148 if (options?.to !== undefined) return this.sendToRun(message, options)
149 return this.sendForRun(message, options)
150 }
151​
152 /**
153 * @internal `send` of a message to the session, with the AG-UI `runId` of
154 * a `POST run` request: the turn runs as it. The HTTP handler and an
155 * offered prompt call it.
156 */
157 override sendForRun(
158 message: UserInput,
159 options?: SendForRunOptions,
160 ): Operation<ChatTurnResult> {
161 const context = options?.context
162 const mode = options?.mode ?? 'prompt'
163 const input: HarnessInput =
164 mode === 'prompt'
165 ? {
166 op: 'prompt',
167 message,
168 busy: options?.busy ?? this.harness.busy ?? 'queue',
169 ...(context !== undefined ? { context } : {}),
170 ...(options?.as ? { as: options.as } : {}),
171 }
172 : mode === 'steer'
173 ? {
174 op: 'steer',
175 message,
176 ...(context !== undefined ? { context } : {}),
177 }
178 : {
179 op: 'followUp',
180 message,
181 ...(context !== undefined ? { context } : {}),
182 }
183 return this.startTurn(input, options)
184 }
185​
186 /**
187 * Start the turn of `input` (a prompt, a steer, or a follow-up), with its
188 * operation. `wake`: the harness wakes the session with the message (a
189 * background job ended), so its user message is marked, not shown as
190 * something the user said.
191 */
192 protected startTurn(
193 input: HarnessInput & { op: 'prompt' | 'steer' | 'followUp' },
194 options?: SendForRunOptions & { wake?: boolean },
195 ): Operation<ChatTurnResult> {
196 const inputId = options?.inputId ?? createInputId()
197 const overrides = options?.overrides
198 const systemPreamble = options?.systemPreamble
199 const ephemeral = options?.ephemeral
200 const outputSchema = options?.outputSchema
201 const user = this.actor(options?.user)
202 const wake = options?.wake === true
203 const stored: typeof input =
204 input.op === 'followUp' && wake ? { ...input, wake: true } : input
205 const known = this.knownTurn(inputId, stored, user)
206 if (known) return known
207 const runId = options?.runId
208 // A prompt that this host offered comes back from the lane when no live
209 // host owns the log. It runs on the operation that its caller holds.
210 const passed = this.offeredInputs.has(inputId)
211 ? this.turnOperations.get(inputId)
212 : undefined
213 // A run id must not take the id of another operation.
214 if (
215 !passed &&
216 runId !== undefined &&
217 (this.operations.has(runId) || this.retiredIds.has(runId))
218 ) {
219 const refused = this.createTurnOperation()
220 this.refuse(refused, { inputId, status: 'rejected', reason: 'conflict' })
221 return refused
222 }
223 const operation = passed ?? this.createTurnOperation(runId)
224 this.bindTurn(inputId, operation)
225 const traceparent = options?.traceparent
226 void this.admitting(() =>
227 this.accept(inputId, stored, user, {
228 // An offered turn runs as the operation of this host.
229 runId: operation.id,
230 turn: { overrides, systemPreamble, ephemeral, outputSchema },
231 // As the W3C rules say, an invalid `traceparent` is dropped.
232 ...(traceparent !== undefined && parseTraceparent(traceparent)
233 ? { traceparent }
234 : {}),
235 }).then(
236 async ({ admission, input: accepted }) => {
237 if (admission !== 'new') {
238 this.answerDuplicate(operation, inputId, admission)
239 return
240 }
241 // `acceptInput` can change the input.
242 const { message, context } = accepted
243 const busy =
244 accepted.op === 'prompt'
245 ? accepted.busy
246 : accepted.op === 'steer'
247 ? 'steer'
248 : 'queue'
249 // A client run id must be new in the log of this thread.
250 if (runId !== undefined && this.isRunTaken(runId)) {
251 this.reject(inputId, 'conflict')
252 this.refuse(operation, {
253 inputId,
254 status: 'rejected',
255 reason: 'conflict',
256 })
257 return
258 }
259 const isWaiting =
260 this.activeTurn !== undefined || this.queue.length > 0
261 if (accepted.op === 'prompt' && accepted.as === 'operator') {
262 // An operator reply runs no model. It needs an open handoff to
263 // a person.
264 if (!this.humanHandoff()) {
265 this.refuse(operation, this.reject(inputId, 'no_human_wait'))
266 return
267 }
268 this.answerTurn(operation, {
269 inputId,
270 status: isWaiting ? 'queued' : 'accepted',
271 operationId: operation.id,
272 })
273 this.enqueueTurn({
274 operation,
275 message,
276 inputId,
277 user,
278 operator: true,
279 })
280 return
281 }
282 if (this.activeTurn && busy === 'reject') {
283 this.reject(inputId, 'busy')
284 this.refuse(operation, {
285 inputId,
286 status: 'rejected',
287 reason: 'busy',
288 })
289 return
290 }
291 // A steer joins the running turn, so the receipt names that turn.
292 const running = busy === 'steer' ? this.activeTurn : undefined
293 if (!running && this.waitsForInterrupts()) {
294 this.reject(inputId, 'pending_interrupts')
295 this.refuse(operation, {
296 inputId,
297 status: 'rejected',
298 reason: 'pending_interrupts',
299 })
300 return
301 }
302 // Without canJoin, a steer of another sender never joins (see
303 // claimJoins): it waits, and runs as its own operation.
304 const joins =
305 running &&
306 (this.harness.turn?.canJoin !== undefined ||
307 isSameSender(user, this.sender()))
308 this.answerTurn(operation, {
309 inputId,
310 status: isWaiting && !joins ? 'queued' : 'accepted',
311 operationId: joins ? running.id : operation.id,
312 })
313 const sent = {
314 user,
315 context,
316 ...(wake ? { wake } : {}),
317 ...(outputSchema ? { outputSchema } : {}),
318 }
319 if (running) {
320 this.steerQueue.push({
321 inputId,
322 message,
323 operation,
324 overrides,
325 ephemeral,
326 ...sent,
327 })
328 this.publishQueued(inputId, 'steer')
329 return
330 }
331 this.enqueueTurn({
332 operation,
333 message,
334 inputId,
335 overrides,
336 systemPreamble,
337 ephemeral,
338 ...sent,
339 })
340 },
341 (error: unknown) => {
342 // The input was not stored. After a log failure, say why the
343 // session stopped.
344 const failure = this.logFailure ?? error
345 this.answerTurn(operation, {
346 inputId,
347 status: 'rejected',
348 reason:
349 failure instanceof Error ? failure.message : String(failure),
350 })
351 operation.fail('failed', failure)
352 },
353 ),
354 )
355 return operation
356 }
357​
358 /**
359 * Run one tool with no model, for example from a schedule or a webhook.
360 * It runs as a chat turn whose only model call asks for the tool, so the
361 * call goes through middleware, the input check, and `permissions()`, and
362 * the call and its result join the transcript. A tool that asks for
363 * approval stops the turn with an interrupt. `meta` is echoed as a
364 * `tanstack.injection` custom event. The turn waits behind a running turn.
365 * While interrupts wait, it is refused with `'pending_interrupts'`.
366 *
367 * `args` is typed from the input schema of a harness tool. A plugin tool
368 * takes any `args`, and its input schema checks them. `inputId` and
369 * `user` mean the same as in `send`.
370 *
371 * @example
372 * ```ts
373 * const turn = session.runTool({ name: 'sync_inbox', args: { folder: 'INBOX' } })
374 * ```
375 */
376 runTool<
377 TName extends HarnessToolsOf<THarness>['name'] | (string & {}),
378 >(options: {
379 name: TName
380 args?: HarnessToolInput<THarness, TName>
381 meta?: Record<string, unknown>
382 inputId?: string
383 user?: HarnessUser
384 }): Operation<ChatTurnResult> {
385 const inputId = options.inputId ?? createInputId()
386 const user = this.actor(options.user)
387 const input = {
388 op: 'tool' as const,
389 name: options.name,
390 ...(options.args !== undefined ? { args: options.args } : {}),
391 ...(options.meta ? { meta: options.meta } : {}),
392 }
393 const known = this.knownTurn(inputId, input, user)
394 if (known) return known
395 const operation = this.createTurnOperation()
396 this.bindTurn(inputId, operation)
397 void this.admitting(() =>
398 this.accept(inputId, input, user).then(
399 ({ admission, input: accepted }) => {
400 if (admission !== 'new') {
401 this.answerDuplicate(operation, inputId, admission)
402 return
403 }
404 // `acceptInput` can change the input.
405 const { name, args, meta } = accepted
406 // As a prompt: the open interrupts are answered first.
407 if (this.waitsForInterrupts()) {
408 this.reject(inputId, 'pending_interrupts')
409 this.refuse(operation, {
410 inputId,
411 status: 'rejected',
412 reason: 'pending_interrupts',
413 })
414 return
415 }
416 const isWaiting =
417 this.activeTurn !== undefined || this.queue.length > 0
418 this.answerTurn(operation, {
419 inputId,
420 status: isWaiting ? 'queued' : 'accepted',
421 operationId: operation.id,
422 })
423 this.enqueueTurn({
424 operation,
425 inputId,
426 user,
427 tool: { name, args, ...(meta ? { meta } : {}) },
428 })
429 },
430 (error: unknown) => {
431 const failure = this.logFailure ?? error
432 this.answerTurn(operation, {
433 inputId,
434 status: 'rejected',
435 reason: errorText(failure),
436 })
437 operation.fail('failed', failure)
438 },
439 ),
440 )
441 return operation
442 }
443​
444 /** `send` to an agent run: the session agents layer implements it. */
445 protected abstract sendToRun(
446 message: UserInput,
447 options: AgentSendOptions,
448 ): Operation<unknown>
449​
450 /**
451 * Start a chat turn from the stored transcript, with no new message. While
452 * a turn runs, it queues. When it starts, the transcript must end with a
453 * user or a tool message. Else the input is rejected with
454 * `'nothing_to_continue'`. `inputId`, `overrides`, `user`,
455 * `context`, and `ephemeral` mean the same as in `prompt`. Each model call
456 * gets the `ephemeral` messages after the transcript.
457 *
458 * @example
459 * ```ts
460 * await session.appendRecords({
461 * records: [{ type: 'app.signal', text: 'The build failed.' }],
462 * })
463 * await session.continueWithoutMessage({ inputId: 'after-signal' })
464 * ```
465 */
466 continueWithoutMessage(options?: {
467 inputId?: string
468 overrides?: TurnOverrides
469 user?: HarnessUser
470 context?: unknown
471 ephemeral?: ReadonlyArray<ModelMessage>
472 }): Operation<ChatTurnResult> {
473 const inputId = options?.inputId ?? createInputId()
474 const user = this.actor(options?.user)
475 const sent = options?.context
476 const input = {
477 op: 'continue' as const,
478 ...(sent !== undefined ? { context: sent } : {}),
479 }
480 const known = this.knownTurn(inputId, input, user)
481 if (known) return known
482 const operation = this.createTurnOperation()
483 this.bindTurn(inputId, operation)
484 const turn = {
485 ...(options?.overrides ? { overrides: options.overrides } : {}),
486 ...(options?.ephemeral ? { ephemeral: options.ephemeral } : {}),
487 }
488 void this.admitting(() =>
489 this.accept(inputId, input, user, { turn }).then(
490 ({ admission, input: accepted }) => {
491 if (admission !== 'new') {
492 this.answerDuplicate(operation, inputId, admission)
493 return
494 }
495 // `acceptInput` can change the input.
496 const { context } = accepted
497 const isWaiting =
498 this.activeTurn !== undefined || this.queue.length > 0
499 this.answerTurn(operation, {
500 inputId,
501 status: isWaiting ? 'queued' : 'accepted',
502 operationId: operation.id,
503 })
504 this.enqueueTurn({
505 operation,
506 inputId,
507 overrides: options?.overrides,
508 ephemeral: options?.ephemeral,
509 user,
510 context,
511 isContinue: true,
512 })
513 },
514 (error: unknown) => {
515 // As in `prompt`: the input was not stored.
516 const failure = this.logFailure ?? error
517 this.answerTurn(operation, {
518 inputId,
519 status: 'rejected',
520 reason: errorText(failure),
521 })
522 operation.fail('failed', failure)
523 },
524 ),
525 )
526 return operation
527 }
528​
529 /**
530 * Start a fresh model context. From the next turn, the model sees only
531 * `note` (when you give one) and what comes after the reset.
532 * `transcript()` keeps every message: the reset adds a user message with
533 * `metadata.harness.reset`, whose content is the note.
534 *
535 * While a turn runs, the reset waits and applies when that turn ends,
536 * before the next queued turn. A thread that waits for interrupts is
537 * refused with `'pending_interrupts'`: resolve them first. `user` and
538 * `inputId` mean the same as in `prompt`.
539 *
540 * @example
541 * ```ts
542 * await session.reset({ note: 'The user wants a new plan.' })
543 * ```
544 */
545 async reset(
546 options?: ResetOptions & { user?: HarnessUser },
547 ): Promise<Receipt> {
548 return this.admitting(async () => {
549 const note = options?.note
550 const inputId = options?.inputId ?? createInputId()
551 const user = this.actor(options?.user)
552 // An empty note is no note: the model never gets an empty message.
553 const sent = note?.trim() ? note : undefined
554 const { admission, input } = await this.accept(
555 inputId,
556 { op: 'reset', ...(sent !== undefined ? { note: sent } : {}) },
557 user,
558 )
559 if (admission !== 'new') return this.duplicateReceipt(inputId, admission)
560 // `acceptInput` can change the input.
561 const text = input.note?.trim() ? input.note : undefined
562 const isRunning = this.activeTurn !== undefined
563 if (this.waitsForInterrupts())
564 return this.reject(inputId, 'pending_interrupts')
565 const operation = this.queueReset(inputId, text, user, 'front')
566 return this.keep({
567 inputId,
568 status: isRunning ? 'queued' : 'accepted',
569 operationId: operation.id,
570 })
571 })
572 }
573​
574 /**
575 * Answer the interrupts of the last turn. One resume must answer every open
576 * interrupt of that turn (the AG-UI rule). `user` is who answers: the
577 * log keeps it. The turn that continues still runs as the user who sent
578 * it, with that user's credentials.
579 *
580 * @example
581 * ```ts
582 * await session.resolve({
583 * resume: [{ interruptId, status: 'resolved', payload: { approved: true } }],
584 * })
585 * ```
586 */
587 resolve(options: ResolveOptions & { user?: HarnessUser }): Promise<Receipt> {
588 return this.resolveForRun(options)
589 }
590​
591 /**
592 * The `harnessAgent` child that waits for every id of `waitIds`, or
593 * `undefined`. A child lists the waits of its own children too.
594 */
595 protected childOfWaits(
596 waitIds: ReadonlyArray<string>,
597 ): HarnessChild | undefined {
598 if (waitIds.length === 0) return undefined
599 for (const child of this.harnessChildren.values()) {
600 const waits = child.session.snapshot().pendingWaits
601 const open = new Set(waits.map((wait) => wait.waitId))
602 if (waitIds.every((id) => open.has(id))) return child
603 }
604 return undefined
605 }
606​
607 /**
608 * @internal `resolve`, with the AG-UI `runId` of a `POST run` request: the
609 * turn runs as it. The HTTP handler and an offered resolve call it.
610 */
611 override async resolveForRun(
612 options: ResolveForRunOptions,
613 ): Promise<Receipt> {
614 // The waits of a `harnessAgent` child: the child takes the answers, and
615 // its run goes on, still for the user of the run that started it. The
616 // AG-UI run id names a run of this session only.
617 const child = this.childOfWaits(
618 options.resume.map((item) => item.interruptId),
619 )
620 if (child) {
621 const { inputId } = options
622 return child.answer({
623 resume: options.resume,
624 ...(inputId !== undefined ? { inputId } : {}),
625 })
626 }
627 return this.admitting(async () => {
628 const inputId = options.inputId ?? createInputId()
629 const user = this.actor(options.user)
630 const runId = options.runId
631 const { admission, input } = await this.accept(
632 inputId,
633 { op: 'resolve', resume: options.resume },
634 user,
635 runId !== undefined ? { runId } : {},
636 )
637 // `acceptInput` can change the input.
638 const { resume } = input
639 if (admission !== 'new') {
640 const receipt = this.duplicateReceipt(inputId, admission)
641 // The owner runs an offered resume as `runId`.
642 return admission === 'offered' &&
643 runId !== undefined &&
644 receipt.status !== 'rejected'
645 ? { ...receipt, operationId: runId }
646 : receipt
647 }
648 // A run id must not take the id of another operation or stored run.
649 const isTaken =
650 runId !== undefined &&
651 (this.operations.has(runId) ||
652 this.retiredIds.has(runId) ||
653 this.isRunTaken(runId))
654 if (isTaken) {
655 this.reject(inputId, 'conflict')
656 return { inputId, status: 'rejected', reason: 'conflict' }
657 }
658 // The waits of a background agent run: the log ends them, and the
659 // run goes on (see `resumeWaitingRuns`).
660 const logged = resume.map((item) => this.loggedWait(item.interruptId))
661 const open = logged.flatMap((state) =>
662 state !== undefined &&
663 state.outcome === undefined &&
664 state.live === undefined
665 ? [state]
666 : [],
667 )
668 const interrupts = this.logWriter?.state.thread.interrupts
669 // A `step.ask` question and the `human` wait of a handoff have no
670 // interrupt: `answer` checks their schema, keeps a secret out of the
671 // log, and ends the handoff.
672 if (
673 open.some(
674 ({ wait }) => interrupts?.get(wait.waitId)?.status !== 'pending',
675 )
676 ) {
677 this.reject(inputId, 'use_answer')
678 return { inputId, status: 'rejected', reason: 'use_answer' }
679 }
680 if (open.length > 0) {
681 // The access check saw the run of the first item: every item must
682 // be a wait of that run.
683 const runId = open[0]?.wait.runId
684 const isOneRun =
685 open.length === resume.length &&
686 open.every(({ wait }) => wait.runId === runId)
687 if (!isOneRun) {
688 this.reject(inputId, 'mixed_runs')
689 return { inputId, status: 'rejected', reason: 'mixed_runs' }
690 }
691 // Another answer ends one of these waits now.
692 if (open.some(({ wait }) => this.answering.has(wait.waitId))) {
693 this.reject(inputId, 'unknown_question')
694 return { inputId, status: 'rejected', reason: 'unknown_question' }
695 }
696 const ids = open.map(({ wait }) => wait.waitId)
697 for (const id of ids) this.answering.add(id)
698 try {
699 // The input ends here, in the append that ends the waits.
700 await this.settleWith(
701 [{ inputId, outcome: 'completed' }],
702 resume.flatMap((item) =>
703 item.status === 'resolved'
704 ? this.waitEndRecords(
705 item.interruptId,
706 'answered',
707 item.payload,
708 )
709 : this.waitEndRecords(item.interruptId, 'cancelled'),
710 ),
711 )
712 } finally {
713 for (const id of ids) this.answering.delete(id)
714 }
715 for (const item of resume) await this.afterWaitEnd(item.interruptId)
716 return this.keep({
717 inputId,
718 status: 'accepted',
719 ...(runId !== undefined ? { operationId: runId } : {}),
720 })
721 }
722 const answers = this.interrupted
723 if (!answers) {
724 this.reject(inputId, 'no_pending_interrupts')
725 return { inputId, status: 'rejected', reason: 'no_pending_interrupts' }
726 }
727 // A client answers on RUN_FINISHED, while the interrupted turn still
728 // ends. The resolve runs right after it.
729 const isEnding = this.activeTurn?.id === answers.runId
730 if (
731 (this.activeTurn && !isEnding) ||
732 this.queue.some((turn) => turn.answers?.runId === answers.runId)
733 ) {
734 this.reject(inputId, 'busy')
735 return { inputId, status: 'rejected', reason: 'busy' }
736 }
737 // A cancelled sign-in fails its tool when the turn runs it again.
738 for (const entry of resume) {
739 const connector = signInConnector(
740 answers.interrupts.find((item) => item.id === entry.interruptId),
741 )
742 if (connector && entry.status === 'cancelled')
743 this.declinedSignIns.add(connector)
744 }
745 const operation = this.createTurnOperation(runId)
746 this.bindTurn(inputId, operation)
747 // The turn goes on as its sender, with the context its input sent:
748 // an owner who answers the turn of a member does not lend the member
749 // the owner's keys. A copy from an older version has no sender.
750 const turn: QueuedTurn = {
751 operation,
752 resume,
753 inputId,
754 answers,
755 user: answers.user ?? user,
756 ...(user ? { sender: user } : {}),
757 context: answers.context,
758 }
759 if (isEnding) this.queue.unshift(turn)
760 else this.enqueueTurn(turn)
761 return this.keep({
762 inputId,
763 status: 'accepted',
764 operationId: operation.id,
765 })
766 })
767 }
768​
769 /**
770 * Stop the operation `operationId`, or the running turn without it. A turn
771 * that waits in the queue never runs. Refused with `'not_running'` when
772 * nothing runs or the operation ended. `inputId` means the same as in
773 * `send`: a second cancel with the same id is a duplicate. `user` is
774 * who cancels. Default: the user that opened the session. The log
775 * keeps it.
776 *
777 * @example
778 * ```ts
779 * await session.cancel({ operationId: turn.id })
780 * ```
781 */
782 async cancel(
783 options?: CancelOptions & { inputId?: string; user?: HarnessUser },
784 ): Promise<Receipt> {
785 const inputId = options?.inputId ?? createInputId()
786 const { admission, input } = await this.accept(
787 inputId,
788 { op: 'cancel', operationId: options?.operationId },
789 this.actor(options?.user),
790 )
791 if (admission !== 'new') return this.duplicateReceipt(inputId, admission)
792 // `acceptInput` can change the input.
793 const { operationId } = input
794 const target = operationId
795 ? this.operations.get(operationId)
796 : this.activeTurn
797 if (!target || target.isSettled()) {
798 return this.reject(inputId, 'not_running')
799 }
800 const waitingSteer = this.steerQueue.find(
801 (steer) => steer.operation === target,
802 )
803 // A join took it, so it ends with the running turn, as a joined steer.
804 if (waitingSteer && this.joining.has(waitingSteer.inputId)) {
805 return this.reject(inputId, 'not_running')
806 }
807 const targetInput = this.operationInputs.get(target.id)
808 // A prompt that joined the running turn ends with it, as a joined steer.
809 const hasJoined =
810 targetInput !== undefined &&
811 [...this.turnJoins.values()].some((joined) =>
812 joined.includes(targetInput),
813 )
814 if (hasJoined) return this.reject(inputId, 'not_running')
815 // It never joins now, and settles when the running turn ends.
816 if (waitingSteer) this.abortedSteers.add(waitingSteer.inputId)
817 if (targetInput) {
818 await this.writer.append([
819 { type: 'harness.input.abort', inputId: targetInput },
820 ])
821 }
822 if (waitingSteer) {
823 await this.markApplied(inputId, target.id)
824 return { inputId, status: 'accepted', operationId: target.id }
825 }
826 const chain = this.chainOf.get(target.id)
827 const waiting =
828 chain?.followUps.findIndex((item) => item.operation === target) ?? -1
829 if (chain && waiting >= 0) {
830 // A follow-up that did not start never runs.
831 const [item] = chain.followUps.splice(waiting, 1)
832 if (item) {
833 await this.settle({
834 inputId: item.inputId,
835 outcome: 'aborted',
836 operationId: target.id,
837 })
838 }
839 target.fail('cancelled', new Error('Cancelled before it started.'))
840 this.publishFinished(target)
841 await this.markApplied(inputId, target.id)
842 this.checkIdle()
843 return { inputId, status: 'accepted', operationId: target.id }
844 }
845 // A run's children stop first, bottom-up.
846 for (const child of chain?.children ?? []) {
847 if (!child.current.operation.isSettled()) {
848 await this.cancel({ operationId: child.current.operation.id })
849 }
850 }
851 const queued = this.queue.findIndex((turn) => turn.operation === target)
852 if (queued >= 0) {
853 this.queue.splice(queued, 1)
854 if (targetInput) {
855 await this.settle({
856 inputId: targetInput,
857 outcome: 'aborted',
858 operationId: target.id,
859 })
860 }
861 await this.refreshTurnInterrupts(target)
862 target.fail('cancelled', new Error('Cancelled before it started.'))
863 this.publishFinished(target)
864 } else {
865 // A question of this turn gets no answer now.
866 for (const [questionId, question] of [...this.questions]) {
867 if (question.operationId !== target.id) continue
868 await this.endQuestion(questionId, 'cancelled', new Error('Cancelled.'))
869 }
870 target.abortController.abort(RUN_CANCEL_REASON)
871 }
872 await this.markApplied(inputId, target.id)
873 return { inputId, status: 'accepted', operationId: target.id }
874 }
875​
876 /**
877 * @internal Cancel the queued and running work that the user `userId`
878 * started: `host.sessions.unshare` and `host.revoke` stop it. `user`
879 * is who cancels, and the log keeps it.
880 */
881 async cancelWorkOf({
882 userId,
883 user,
884 }: {
885 userId: string
886 user: HarnessUser | undefined
887 }): Promise<void> {
888 const theirs = [...this.operations.values()].filter(
889 (operation) =>
890 !operation.isSettled() &&
891 this.startedBy(operation.id).userId === userId,
892 )
893 for (const operation of theirs) {
894 await this.cancel({
895 operationId: operation.id,
896 ...(user ? { user } : {}),
897 })
898 }
899 }
900​
901 /**
902 * Cancel an input that waits, so it never runs, also after a restart. It
903 * settles `aborted`. An input that started, or that joins the running
904 * turn now, is refused with `not_waiting`: stop it with
905 * `cancel({ operationId })`. `user` is who cancels. Default: the
906 * user that opened the session. The log keeps it.
907 *
908 * @example
909 * ```ts
910 * await session.send('Then write the tests.', { mode: 'followUp', inputId: 'tests' })
911 * await session.cancelInput({ inputId: 'tests' })
912 * ```
913 */
914 cancelInput(options: {
915 inputId: string
916 user?: HarnessUser
917 }): Promise<Receipt> {
918 return this.applyCancelInput(options)
919 }
920​
921 /**
922 * `cancelInput`, with `controlId`: the id of an offered input, so a replay
923 * is a duplicate.
924 */
925 protected override async applyCancelInput({
926 inputId: sent,
927 user,
928 controlId,
929 }: {
930 inputId: string
931 user?: HarnessUser
932 controlId?: string
933 }): Promise<Receipt> {
934 const inputId = controlId ?? createInputId()
935 const { admission, input } = await this.accept(
936 inputId,
937 { op: 'cancelInput', inputId: sent },
938 this.actor(user),
939 )
940 if (admission !== 'new') return this.duplicateReceipt(inputId, admission)
941 // `acceptInput` can change the input.
942 const target = input.inputId
943 const taken = this.takeWaiting(target) ?? this.takeQueuedContinue(target)
944 if (!taken) return this.reject(inputId, 'not_waiting')
945 await this.applyControl(inputId, {
946 type: 'harness.input.abort',
947 inputId: target,
948 })
949 const { operation } = taken
950 await this.settle({
951 inputId: target,
952 outcome: 'aborted',
953 ...(operation ? { operationId: operation.id } : {}),
954 })
955 if (operation) {
956 operation.fail('cancelled', new Error('Cancelled before it started.'))
957 this.publishFinished(operation)
958 }
959 return { inputId, status: 'accepted' }
960 }
961​
962 /**
963 * Move an input that waits. `'steer'` joins it to the running turn at the
964 * next model call. `'queue'` runs it as its own turn, after the queued
965 * turns. An input that started, or that joins the running turn now, is
966 * refused with `not_waiting`. The log keeps the delivery, and a restart
967 * honors it.
968 * `user` is who moves it. Default: the user that opened the
969 * session. The log keeps it.
970 *
971 * @example
972 * ```ts
973 * await session.send('Use tabs, not spaces.', { mode: 'followUp', inputId: 'style' })
974 * await session.changeInputDelivery({ inputId: 'style', delivery: 'steer' })
975 * ```
976 */
977 changeInputDelivery(options: {
978 inputId: string
979 delivery: WaitingInput['delivery']
980 user?: HarnessUser
981 }): Promise<Receipt> {
982 return this.applySetDelivery(options)
983 }
984​
985 /**
986 * `changeInputDelivery`, with `controlId`: the id of an offered input, so a replay
987 * is a duplicate.
988 */
989 protected override async applySetDelivery({
990 user,
991 controlId,
992 ...sent
993 }: {
994 inputId: string
995 delivery: WaitingInput['delivery']
996 user?: HarnessUser
997 controlId?: string
998 }): Promise<Receipt> {
999 const inputId = controlId ?? createInputId()
1000 const { admission, input: accepted } = await this.accept(
1001 inputId,
1002 { op: 'setDelivery', inputId: sent.inputId, delivery: sent.delivery },
1003 this.actor(user),
1005 if (admission !== 'new') return this.duplicateReceipt(inputId, admission)
1006 // `acceptInput` can change the input.
1007 const { inputId: target, delivery } = accepted
1008 const current = this.waitingInputs().find(
1009 (input) => input.inputId === target,
1011 if (current?.delivery !== delivery) {
1012 const taken = this.takeWaiting(target)
1013 if (!taken) return this.reject(inputId, 'not_waiting')
1014 if (delivery === 'steer' && this.activeTurn) this.steerQueue.push(taken)
1015 else this.enqueueTurn(this.steerTurn(taken))
1017 await this.applyControl(inputId, {
1018 type: 'harness.input.delivery',
1019 inputId: target,
1020 delivery,
1021 })
1022 this.feed.publish(
1023 'session',
1024 customEvent(HARNESS_EVENTS.inputDelivery, { inputId: target, delivery }),
1026 return { inputId, status: 'accepted' }
1028​
1029 /**
1030 * A saved credential can answer the sign-ins the last turn waits for. When
1031 * every open interrupt is a sign-in and each of their connectors has a
1032 * credential of the turn's sender now, the turn goes on as that sender and
1033 * its tools run again. The input id comes from the interrupts, so a second
1034 * save does not resolve them twice.
1035 */
1036 protected override async resumeSignIns(): Promise<void> {
1037 const stopped = this.interrupted
1038 const waiting = stopped?.interrupts ?? []
1039 const connectors = waiting.map(signInConnector)
1040 if (waiting.length === 0) return
1041 // Another user's credential never answers this sign-in.
1042 const user = stopped?.user
1043 const credentials = this.credentialsOf(user)
1044 for (const connector of connectors) {
1045 if (!connector || !(await credentials.get(connector))) return
1047 if (this.interrupted !== stopped) return
1048 await this.resolve({
1049 resume: waiting.map((interrupt, index) => ({
1050 interruptId: interrupt.id,
1051 status: 'resolved',
1052 payload: { connector: connectors[index] },
1053 })),
1054 inputId: `sign-in:${waiting.map((item) => item.id).join(',')}`,
1055 ...(user ? { user } : {}),
1056 })
1058​
1059 /**
1060 * End the waits of the last turn when one of them expired. A batch of
1061 * interrupts resumes as one, so the first expiry ends them all: the turn
1062 * goes on, and its model gets each call cancelled ("no answer"). chat()
1063 * refuses any answer to an interrupt past its own `expiresAt`, so then the
1064 * turn cannot go on: its interrupts end cancelled, and the thread takes
1065 * new turns again. Only the owner of the log ends them.
1066 */
1067 // ponytail: a turn that cannot go on keeps the tool calls with no result
1068 // in its transcript. chat() repairs them at the next turn.
1069 protected async expireInterrupted(): Promise<void> {
1070 const stopped = this.interrupted
1071 if (!stopped || this.activeTurn || this.queue.length > 0) return
1072 const now = Date.now()
1073 const isDue = (at: number | undefined) => at !== undefined && at <= now
1074 const { interrupts } = stopped
1075 if (!interrupts.some((item) => isDue(this.interruptExpiry(item)))) return
1076 if (!(await this.writer.own()) || this.interrupted !== stopped) return
1077 const resume = interrupts.map((interrupt) => ({
1078 interruptId: interrupt.id,
1079 status: 'cancelled' as const,
1080 }))
1081 if (interrupts.some((interrupt) => isDue(timeOf(interrupt.expiresAt)))) {
1082 await this.consumeResume(resume)
1083 this.interrupted = undefined
1084 await this.saveInterrupted(undefined)
1085 this.checkIdle()
1086 return
1088 const user = stopped.user
1089 await this.resolve({
1090 resume,
1091 inputId: `expired:${interrupts.map((item) => item.id).join(',')}`,
1092 ...(user ? { user } : {}),
1093 })
1095​
1096 /**
1097 * The session API of plugins. With `user` (a command, a turn plugin),
1098 * it acts for that user. Without it (a session plugin), it acts for the
1099 * owner of the session entry, else for the user that opened the
1100 * session. A `user` option of `send` and `note` wins: a plugin passes
1101 * the user whose work the turn continues. With `operationId` (a command, a
1102 * turn plugin), its questions belong to that operation.
1103 */
1104 protected override pluginApi(
1105 user?: HarnessUser,
1106 metadataSchema?: SchemaInput,
1107 operationId?: string,
1108 ): PluginSessionApi {
1109 // A session plugin acts for the owner of the entry, not for whoever
1110 // opened the session first on this host. The owner is known only after
1111 // the session read its entry, so it is read at each call. A turn of
1112 // `send` or `note` never follows the sender of the running turn: that
1113 // user did not start the work of the plugin.
1114 const owner = () => user ?? this.owner ?? this.user
1115 return {
1116 threadId: this.threadId,
1117 get user() {
1118 return owner()
1119 },
1120 snapshot: () => this.snapshot(),
1121 // A plugin turn always waits its turn. It cannot see a busy rejection.
1122 send: (text, options) =>
1123 this.startTurn(
1124 { op: 'prompt', message: text, busy: 'queue' },
1125 { user: options?.user ?? owner() },
1126 ),
1127 note: async (text, options) => {
1128 await this.addNote(text)
1129 if (options?.wake) {
1130 const receipt = await this.startTurn(
1131 { op: 'followUp', message: text },
1132 { user: options.user ?? owner(), wake: true },
1133 ).receipt
1134 if (receipt.status === 'rejected')
1135 throw new InputRejectedError(receipt)
1137 },
1138 transcript: () => this.transcript(),
1139 keptRecords: async (type) => this.keptRecords(type),
1140 // `messages` comes from `transcript()`, not from the model context.
1141 replaceTranscript: (messages) =>
1142 this.writer.commit({ messages, asTranscript: true }),
1143 indexEntry: () => this.index.get(this.indexKey),
1144 updateIndexEntry: (update) => {
1145 // Only these fields: a plugin cannot change the owner, the parent,
1146 // or the pin.
1147 const pick = (
1148 change:
1149 | Pick<SessionIndexEntry, 'title' | 'metadata' | 'usage'>
1150 | undefined,
1151 ) =>
1152 change && {
1153 title: change.title,
1154 metadata: change.metadata,
1155 usage: change.usage,
1157 return this.index.update(this.indexKey, (entry) =>
1158 changedEntry(
1159 entry,
1160 typeof update === 'function'
1161 ? (current) => pick(update(current))
1162 : pick(update),
1163 this.harness.metadataSchema,
1164 metadataSchema,
1165 ),
1167 },
1168 // The public type narrows the answer from the schema. A live wait
1169 // belongs to the run of its tool call, never to the run of this API.
1170 ask: ((question: Question<SchemaInput | undefined>) =>
1171 this.ask(question)) as PluginSessionApi['ask'],
1172 authRequired: (info) => {
1173 this.feed.publish(
1174 'session',
1175 customEvent(HARNESS_EVENTS.authRequired, { ...info }),
1177 // The OAuth login of a command is a live wait of that command.
1178 if (operationId !== undefined) this.openSignIn(info, operationId)
1179 },
1180 setPluginSetting: (change) =>
1181 this.setPluginSetting({ ...change, user: owner() }),
1182 threadSettings: () => this.threadSettings(),
1183 putMedia: (upload) => this.putMedia(upload),
1186​
1187 /** Operations that follow an input another host runs, or that ran before. */
1188 private readonly followers = new Set<OperationImpl<ChatTurnResult>>()
1189​
1190 /**
1191 * @internal Close the session for every handle: stop every running
1192 * operation, wait for them, then dispose session plugins. Safe to call
1193 * twice. The host calls it (`host.close`, the idle close, and
1194 * `host.sessions.delete`). The `close()` of a handle releases only that
1195 * handle.
1197 * With `recoverable`, the running turns and agent runs stop as on a host
1198 * crash: the log gets none of their later writes, so they do not settle
1199 * and their runs get no aborted state. The host gives the log up, so the
1200 * next host that opens the thread runs them again at once. `host.close`
1201 * passes it when a host shuts down, for example for a deploy.
1202 */
1203 close(options?: { recoverable?: boolean }): Promise<void> {
1204 this.closing ??= (async () => {
1205 // Before the stop, so no write of the stopped work lands.
1206 // A session whose open failed before the log opened has no writer.
1207 if (options?.recoverable) this.logWriter?.close()
1208 for (const turn of this.queue.splice(0)) {
1209 await this.refreshTurnInterrupts(turn.operation)
1210 turn.operation.fail('cancelled', new Error('Session closed.'))
1212 // A follower waits for a settlement in the log. The log view closes
1213 // with the session, so it ends now.
1214 for (const operation of this.followers) {
1215 if (!operation.isSettled())
1216 operation.fail('cancelled', new Error('Session closed.'))
1218 this.followers.clear()
1219 const running = [...this.operations.values()].filter(
1220 (operation) => !operation.isSettled(),
1222 for (const operation of running) {
1223 operation.abortController.abort(
1224 options?.recoverable ? SHUTDOWN_REASON : RUN_CANCEL_REASON,
1227 // Nobody can answer a live question now. The log gets the end, when
1228 // it still takes writes.
1229 await Promise.all(
1230 [...this.questions.keys()].map((questionId) =>
1231 this.endQuestion(
1232 questionId,
1233 'cancelled',
1234 new Error('Session closed.'),
1235 ),
1236 ),
1238 await Promise.allSettled(
1239 running.map((operation) => Promise.resolve(operation)),
1241 // The turn plugins that a run still held, before the feed closes.
1242 await Promise.all([...this.turnPlugins].map((held) => held.dispose()))
1243 // The events from before the close land first, so the next host has
1244 // the text of a cut answer.
1245 if (options?.recoverable)
1246 await this.logWriter
1247 ?.flush()
1248 .catch((error: unknown) => this.warnSession('harness:log', error))
1249 // A reload that mounts plugins now ends first, so its plugins are
1250 // disposed below.
1251 await this.reloads
1252 this.lifetime.abort()
1253 try {
1254 await this.sessionPlugins?.dispose()
1255 } finally {
1256 this.feed.close()
1257 this.eventListeners.clear()
1258 this.onClose()
1260 })()
1261 return this.closing
1263​
1264 // ===========================
1265 // Chat turns
1266 // ===========================
1267​
1268 /**
1269 * `id`: a stored or chosen run id. `startedCursor`: the start of a run
1270 * that a restart rebuilds from the log.
1271 */
1272 protected createTurnOperation(
1273 id?: string,
1274 startedCursor?: Cursor,
1275 ): OperationImpl<ChatTurnResult> {
1276 const operation = new OperationImpl<ChatTurnResult>(
1277 'chat',
1278 this.feed,
1279 (target) => {
1280 // A cancel on the turn itself acts as its sender, not as the
1281 // user that opened the session. A handle passes its own.
1282 const user = this.userOfRun(target.id)
1283 return this.cancel({
1284 operationId: target.id,
1285 ...(user ? { user } : {}),
1286 })
1287 },
1288 undefined,
1289 id,
1290 startedCursor,
1292 this.track(operation as OperationImpl<unknown>)
1293 return operation
1295​
1296 /**
1297 * Steers a turn never reached run next, before other queued turns (after
1298 * a resolve of that turn). A steer with an abort request settles `aborted`
1299 * instead.
1300 */
1301 protected requeueWaitingSteers(): void {
1302 this.joining.clear()
1303 const waiting = this.steerQueue.splice(0)
1304 const aborted = waiting.filter((steer) =>
1305 this.isAbortRequested(steer.inputId),
1307 const rest = waiting.filter((steer) => !aborted.includes(steer))
1308 for (const steer of aborted) {
1309 this.abortedSteers.delete(steer.inputId)
1310 const { operation } = steer
1311 // Not awaited: the session goes on to the next turn at once. The
1312 // settlement lands before the operation ends.
1313 void this.settle({
1314 inputId: steer.inputId,
1315 outcome: 'aborted',
1316 ...(operation ? { operationId: operation.id } : {}),
1317 })
1318 .catch(() => {})
1319 .then(() => {
1320 if (!operation) return
1321 operation.fail('cancelled', new Error('Cancelled before it started.'))
1322 this.publishFinished(operation)
1323 })
1325 if (this.closing) {
1326 // close() ended the queued turns already. These end the same way.
1327 for (const steer of rest) {
1328 steer.operation?.fail('cancelled', new Error('Session closed.'))
1330 return
1332 this.queue.splice(
1333 this.frontOfQueue(),
1334 0,
1335 ...rest.map((steer) => this.steerTurn(steer)),
1338​
1339 /** A waiting steer as its own turn, with its own operation. */
1340 protected steerTurn(steer: WaitingSteer) {
1341 const operation = steer.operation ?? this.createTurnOperation()
1342 this.bindTurn(steer.inputId, operation)
1343 const turn: QueuedTurn = { ...steer, operation }
1344 return turn
1346​
1347 /**
1348 * The operation for a prompt whose id is known: the live one, one that
1349 * settles from the log, or a refused one for another payload.
1350 */
1351 protected knownTurn(
1352 inputId: string,
1353 input: HarnessInput,
1354 user: HarnessUser | undefined,
1355 ) {
1356 const payload = inputKey(input, user)
1357 const local = this.admitted.get(inputId)
1358 const logged = this.writer.state.inputs.get(inputId)
1359 const stored =
1360 local ?? (logged ? inputKey(logged.input, logged.user) : undefined)
1361 if (stored === undefined) return undefined
1362 if (
1363 stored !== payload &&
1364 this.inputRecords.screened.get(inputId) !== payload
1365 ) {
1366 const refused = this.createTurnOperation()
1367 this.refuse(refused, { inputId, status: 'rejected', reason: 'conflict' })
1368 return refused
1370 const live = this.turnOperations.get(inputId)
1371 if (live) return live
1372 // A join of the replayed turn reads its events from its run start.
1373 const replay = this.createTurnOperation(
1374 logged?.operationId,
1375 this.runStart(logged?.operationId),
1377 this.answerDuplicate(replay, inputId, 'duplicate')
1378 return replay
1380​
1381 /** Settle `operation` like the earlier input with the same id. */
1382 protected answerDuplicate(
1383 operation: OperationImpl<ChatTurnResult>,
1384 inputId: string,
1385 admission: Exclude<Admission, 'new'>,
1386 ) {
1387 const receipt = this.duplicateReceipt(inputId, admission)
1388 if (receipt.status === 'rejected') {
1389 this.refuse(operation, receipt)
1390 return
1392 operation.resolveReceipt(receipt)
1393 this.followers.add(operation)
1394 void this.settled({ inputId })
1395 .then(
1396 (settlement) => this.settleOperation(operation, settlement),
1397 (error: unknown) => operation.fail('failed', error),
1399 .finally(() => this.followers.delete(operation))
1401​
1402 /**
1403 * Queue a reset: at the front for a new one (it applies when the running
1404 * turn ends), at the end for one from before a restart (in its admission
1405 * order). Its operation is a command, so clients do not see a chat turn.
1406 */
1407 protected queueReset(
1408 inputId: string,
1409 note: string | undefined,
1410 user: HarnessUser | undefined,
1411 at: 'front' | 'end',
1412 ) {
1413 const operation = new OperationImpl<ChatTurnResult>(
1414 'command',
1415 this.feed,
1416 (target) => this.cancel({ operationId: target.id }),
1418 this.track(operation as OperationImpl<unknown>)
1419 this.bindTurn(inputId, operation)
1420 const turn: QueuedTurn = {
1421 operation,
1422 inputId,
1423 user,
1424 reset: note !== undefined ? { note } : {},
1426 this.queue.splice(
1427 at === 'front' ? this.frontOfQueue() : this.queue.length,
1428 0,
1429 turn,
1431 this.drain()
1432 return operation