agent.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. /**
  2. * The concrete Agent implementation: ReactLoopAgent plus its inbox. Everything
  3. * observable happens through session events and the agent/* event taxonomy —
  4. * plugins never need this class.
  5. *
  6. * @module dsh-agent-loop/agent
  7. */
  8. import { randomUUID } from 'node:crypto'
  9. import type { Context } from 'cordis'
  10. import { agentEvents, AgentMessageId } from '@deepseek-ai/dsh-agent'
  11. import type {
  12. Agent,
  13. AgentCancelCause,
  14. AgentOptions,
  15. AgentStatus,
  16. CancelOptions,
  17. HookContext,
  18. InjectOptions,
  19. ResolvedAgentInput,
  20. SendOptions,
  21. } from '@deepseek-ai/dsh-agent'
  22. import { deepFreeze, errorChain } from '@deepseek-ai/dsh-llm'
  23. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  24. import { snapshotJsonValue, type Session, type SessionId } from '@deepseek-ai/dsh-session'
  25. import { DISPOSED_INTERRUPT_REASON, TurnCancellation } from './cancellation.ts'
  26. import { Inbox, agentMessage, type InboxMessage } from './inbox.ts'
  27. import { isTurnOpen, lastTurnNumber, runLoop } from './loop.ts'
  28. /** Sessions already claimed by a concrete driver construction. */
  29. const claimedDriverSessions = new WeakSet<Session>()
  30. /** Module-private driver entry: its symbol is absent from the package surface. */
  31. const startDriver = Symbol('dsh.agent-loop.start-driver')
  32. /** Module-private quiescent stop, valid both before and after driver start. */
  33. const stopDriver = Symbol('dsh.agent-loop.stop-driver')
  34. /** Module-private context binding for the mutually referential agent scope. */
  35. const bindContext = Symbol('dsh.agent-loop.bind-context')
  36. /** Module-private publication marker. */
  37. const publishAgent = Symbol('dsh.agent-loop.publish-agent')
  38. /** Factory-owned controls that can operate only on the agent created with them. */
  39. export interface PreparedReactLoopAgent {
  40. /** The unpublished concrete agent. */
  41. agent: ReactLoopAgent
  42. /** Mark the agent public so teardown emits its status lifecycle. */
  43. markPublished(): void
  44. /** Stop the prepared instance even when publication has not started its loop. */
  45. dispose(): Promise<void> | void
  46. /**
  47. * Start its driver after publication and session-start notification.
  48. * The returned disposer reaches quiescence for both the loop and every
  49. * fire-and-forget idle-injection flush the agent started.
  50. */
  51. startDriver(): () => Promise<void> | void
  52. }
  53. /**
  54. * Construct an unpublished concrete agent with instance-bound lifecycle
  55. * controls. Only those paired controls can publish or start this instance.
  56. * @param ctx - the agent-loop service context used for driving and events.
  57. * @param id - the concrete agent identity.
  58. * @param options - loop options for the agent.
  59. * @param session - the prepared session the agent will own.
  60. * @param maxParallelToolCalls - resolved in-flight cap for this agent.
  61. * @returns the agent and closures bound only to that exact instance.
  62. */
  63. export function prepareReactLoopAgent(
  64. ctx: Context,
  65. id: SessionId,
  66. options: AgentOptions,
  67. session: Session,
  68. maxParallelToolCalls: number,
  69. ): PreparedReactLoopAgent {
  70. if (claimedDriverSessions.has(session)) {
  71. throw new Error(`session "${session.id}" already has a concrete agent driver`)
  72. }
  73. const agent = new ReactLoopAgent(ctx, id, options, session, maxParallelToolCalls)
  74. claimedDriverSessions.add(session)
  75. const dispose = () => agent[stopDriver]()
  76. return {
  77. agent,
  78. markPublished: () => { agent[publishAgent]() },
  79. dispose,
  80. startDriver: () => {
  81. agent[startDriver]()
  82. return dispose
  83. },
  84. }
  85. }
  86. /**
  87. * Install the concrete agent's scope context exactly once. Construction and
  88. * scope minting are mutually referential (the scope key is the agent), so the
  89. * factory performs this one post-construction binding before setup receives
  90. * the unpublished agent. The module-private binding rejects a second bind.
  91. * @param agent - the unpublished concrete agent to bind.
  92. * @param ctx - its fully extended agent scope context.
  93. */
  94. export function bindReactLoopAgentContext(agent: ReactLoopAgent, ctx: Context): void {
  95. agent[bindContext](ctx)
  96. }
  97. /**
  98. * The concrete {@link Agent} implementation owned by the agent-loop plugin.
  99. *
  100. * Owns the inbox (queued + steering FIFOs), turn cancellation, and
  101. * the loop driver. Everything observable happens through session events and
  102. * the agent/* event taxonomy — plugins never need this class.
  103. */
  104. export class ReactLoopAgent implements Agent {
  105. /** Queued + steering FIFOs; native-private so callers cannot bypass the public driving verbs. */
  106. readonly #inbox = new Inbox()
  107. /**
  108. * The agent's scope context ({@link Agent.ctx}), wired by the factory right
  109. * after the scope is minted — before the agent is registered, announced, or
  110. * driven, so no consumer can observe it unset. Definite-assignment (`!`)
  111. * expresses that two-phase construction: the agent object and its scope
  112. * context are mutually referential (the scope is keyed BY this agent), so
  113. * neither can exist strictly before the other.
  114. */
  115. private boundContext: Context | undefined
  116. /** The agent's scoped composition context, bound once by its factory. */
  117. get ctx(): Context {
  118. if (this.boundContext === undefined) throw new Error(`agent "${this.id}" context is not bound`)
  119. return this.boundContext
  120. }
  121. private _status: AgentStatus = 'idle'
  122. /** Active turn owner from pre-running publication through durability settlement. */
  123. private turnCancellation: TurnCancellation | undefined
  124. /** Whether runLoop has been installed into {@link done}. */
  125. private driverStarted = false
  126. /** Whether registry publication began and status disposal is externally visible. */
  127. private published = false
  128. /** Cause-less marker for queued work cancelled before the driver installs a turn owner. */
  129. private preRunCancelled = false
  130. private disposed: Promise<void>
  131. private resolveDisposed!: () => void
  132. /** Resolves when the driver loop has fully exited (tests/disposal). */
  133. done: Promise<void> = Promise.resolve()
  134. /**
  135. * Pending {@link whenIdle} waiters, resolved by {@link settleIdleWaiters} when
  136. * the agent next settles out of `running`. Kept as internal agent state (NOT
  137. * an effect-scoped `ctx.on` listener) so a concurrent fiber disposal — which
  138. * runs the agent's own listeners' disposers — cannot drop the waiter before
  139. * the `disposed` transition fires and leave the promise hanging.
  140. */
  141. private idleWaiters: (() => void)[] = []
  142. /** Maximum parallel-safe calls allowed in one step. */
  143. private readonly maxParallelToolCalls: number
  144. /**
  145. * Durability checkpoints started by idle {@link inject} calls. `inject()` is
  146. * synchronous, so it cannot await them itself; the driver disposer drains
  147. * this set before the lifecycle unregisters the agent or detaches its session.
  148. */
  149. private pendingIdleFlushes = new Set<Promise<void>>()
  150. /** Whether the current step is executing an assistant tool-call batch. */
  151. private toolBatchActive = false
  152. /** Open-turn injections waiting for the active assistant tool-call batch to close. */
  153. private deferredInjections: HookContext[] = []
  154. constructor(
  155. private loopCtx: Context,
  156. public readonly id: SessionId,
  157. public readonly options: AgentOptions,
  158. public readonly session: Session,
  159. maxParallelToolCalls: number,
  160. ) {
  161. this.maxParallelToolCalls = maxParallelToolCalls
  162. const { promise, resolve } = Promise.withResolvers<void>()
  163. this.disposed = promise
  164. this.resolveDisposed = resolve
  165. }
  166. get status(): AgentStatus {
  167. return this._status
  168. }
  169. private setStatus(status: AgentStatus): void {
  170. if (this._status === status || this._status === 'disposed') return
  171. this._status = status
  172. // Settle first so a throwing status listener cannot starve quiescence waiters.
  173. if (status !== 'running') this.settleIdleWaiters()
  174. agentEvents(this.loopCtx, this).emit('agent/status', status)
  175. }
  176. /**
  177. * Resolve and clear all pending {@link whenIdle} waiters. Called on a
  178. * running→idle transition (from {@link setStatus}) and on disposal (from the
  179. * internal driver disposer, which chains `done` for true loop-exit quiescence).
  180. */
  181. private settleIdleWaiters(): void {
  182. const waiters = this.idleWaiters
  183. this.idleWaiters = []
  184. for (const resolve of waiters) resolve()
  185. }
  186. /**
  187. * Accept one public message payload as a detached record. Lossless-JSON
  188. * materialization reads every nested field once; deep freeze prevents later
  189. * caller mutation before an inbox or deferred-injection queue drains it.
  190. */
  191. private snapshotMessage(id: AgentMessageId, input: ResolvedAgentInput): InboxMessage {
  192. const { content, source, contexts, wakeup, meta } = input
  193. const accepted = snapshotJsonValue({
  194. id, content, source, contexts, wakeup,
  195. ...meta !== undefined ? { meta } : {},
  196. })
  197. if (accepted === undefined) {
  198. throw new TypeError('agent message content, source, and contexts must be losslessly JSON-serializable')
  199. }
  200. return deepFreeze(accepted)
  201. }
  202. /** Detach one context before it can outlive its caller in the active-batch FIFO. */
  203. private acceptContext(context: HookContext): HookContext {
  204. const accepted = snapshotJsonValue(context)
  205. if (accepted === undefined) {
  206. throw new TypeError('agent context must be losslessly JSON-serializable')
  207. }
  208. return deepFreeze(accepted)
  209. }
  210. /** Reject a driving operation once teardown has synchronously closed the agent. */
  211. private assertNotDisposed(): void {
  212. if (this._status === 'disposed') throw new Error(`agent "${this.id}" is disposed`)
  213. }
  214. /** Accept one fully resolved agent input through the concrete driver's routing matrix. */
  215. send(input: ResolvedAgentInput): AgentMessageId {
  216. this.assertNotDisposed()
  217. const id = AgentMessageId(randomUUID())
  218. const { target, wakeup } = input
  219. // next-step/no-wakeup is injection: durable context without running the model.
  220. if (target === 'next-step' && !wakeup) { this.injectContext(input); return id }
  221. // next-step/wakeup is steering into the running turn; idle falls back to a
  222. // waking ordinary turn (there is no active turn to attach to).
  223. const steering = target === 'next-step' && this._status === 'running'
  224. const accepted = this.snapshotMessage(id, input)
  225. if (steering) {
  226. this.#inbox.steer(accepted)
  227. } else {
  228. this.#inbox.enqueue(accepted, wakeup)
  229. }
  230. agentEvents(this.loopCtx, this).emit('agent/inbox/enqueue', agentMessage(accepted, steering))
  231. return id
  232. }
  233. followup(content: ContentBlock[], options?: SendOptions): AgentMessageId {
  234. return this.send({
  235. content,
  236. target: 'next-turn',
  237. wakeup: true,
  238. source: options?.source ?? { kind: 'user' },
  239. contexts: options?.contexts ?? [],
  240. meta: options?.meta,
  241. })
  242. }
  243. queue(content: ContentBlock[], options?: SendOptions): AgentMessageId {
  244. return this.send({
  245. content,
  246. target: 'next-turn',
  247. wakeup: false,
  248. source: options?.source ?? { kind: 'user' },
  249. contexts: options?.contexts ?? [],
  250. meta: options?.meta,
  251. })
  252. }
  253. steer(content: ContentBlock[], options?: SendOptions): AgentMessageId {
  254. return this.send({
  255. content,
  256. target: 'next-step',
  257. wakeup: true,
  258. source: options?.source ?? { kind: 'user' },
  259. contexts: options?.contexts ?? [],
  260. meta: options?.meta,
  261. })
  262. }
  263. inject(content: ContentBlock[], options?: InjectOptions): AgentMessageId {
  264. return this.send({
  265. content,
  266. target: 'next-step',
  267. wakeup: false,
  268. source: options?.source ?? { kind: 'plugin', plugin: '' },
  269. contexts: [],
  270. meta: options?.meta,
  271. })
  272. }
  273. /** The `next-step`/no-wakeup injection path: durable context, no FIFO, no run. */
  274. private injectContext(input: Extract<ResolvedAgentInput, { target: 'next-step'; wakeup: false }>): void {
  275. const { content, source, meta } = input
  276. // Detach and validate the payload before any append, so malformed input
  277. // cannot open a one-shot turn or otherwise mutate the session.
  278. const accepted = this.acceptContext({
  279. content,
  280. source,
  281. ...meta !== undefined ? { meta } : {},
  282. })
  283. if (isTurnOpen(this.session)) {
  284. // Provider protocols require every assistant tool-call batch to be
  285. // followed only by its tool results. Historical interrupted batches do
  286. // not own new context; only the currently executing batch may defer it.
  287. if (this.toolBatchActive) {
  288. this.deferredInjections.push(accepted)
  289. return
  290. }
  291. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  292. return
  293. }
  294. // No turn open: wrap the injection in a one-shot turn so every event stays
  295. // turn-enclosed (the durability/replay boundary is the turn). The payload is
  296. // validated above, but `Session.append` can still reject a turn/start
  297. // pre-commit (append re-entrancy from a session/event listener, or an
  298. // internal-dispatch veto), so the finally owes a turn/end only when
  299. // turn/start actually committed.
  300. const turn = lastTurnNumber(this.session) + 1
  301. try {
  302. this.session.append('turn/start', { turn, trigger: { kind: 'injection', source } })
  303. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  304. } finally {
  305. // Close the turn if turn/start made it into the log. A pre-commit veto
  306. // must escape rather than being mistaken for a committed turn/end.
  307. if (isTurnOpen(this.session)) {
  308. this.session.append('turn/end', { turn, reason: { kind: 'completed' } })
  309. }
  310. // Checkpoint only an accepted one-shot turn: a turn/start rejected
  311. // pre-commit recorded nothing, so it owes no flush (and a spurious flush
  312. // would emit a phantom-turn agent/error). The payload is validated up
  313. // front, so a committed turn/start is always followed by its user/message.
  314. const turnRecorded = this.session.events.some(e => e.type === 'turn/start' && e.data.turn === turn)
  315. // Keep inject() synchronous: report checkpoint failures live instead of
  316. // rejecting the caller, and track the task so disposal still drains it.
  317. if (turnRecorded) {
  318. // Through the store's flush (the carrier owner), never a raw parallel.
  319. const flush = this.loopCtx.sessions.flush(this.session).catch((error: unknown) => {
  320. const rendered = errorChain(error)
  321. const err = error instanceof Error ? error : new Error(rendered)
  322. this.loopCtx.logger.warn(`agent "${this.id}": flush after idle injection failed: ${rendered}`)
  323. agentEvents(this.loopCtx, this).emit('agent/error', turn, 0, err)
  324. })
  325. this.pendingIdleFlushes.add(flush)
  326. // Retire on either settlement path.
  327. const retire = (): void => { this.pendingIdleFlushes.delete(flush) }
  328. void flush.then(retire, retire)
  329. }
  330. }
  331. }
  332. /** Append deferred open-turn injections after the loop closes a tool-result batch. */
  333. private drainDeferredInjections(): void {
  334. const pending = this.deferredInjections.splice(0)
  335. for (const accepted of pending) {
  336. this.session.append('user/message', accepted, { surfaceOp: 'append' })
  337. }
  338. }
  339. /**
  340. * Run one tool-call batch and drain its deferred context before settlement.
  341. * The loop-owned acceptor remains valid after public disposal begins because
  342. * the interrupted turn stays open until this batch settles.
  343. */
  344. private async withToolBatch<T>(
  345. run: (acceptContext: (context: HookContext) => void) => Promise<T>,
  346. ): Promise<T> {
  347. this.toolBatchActive = true
  348. const acceptContext = (context: HookContext): void => {
  349. this.deferredInjections.push(this.acceptContext(context))
  350. }
  351. try {
  352. return await run(acceptContext)
  353. } finally {
  354. this.toolBatchActive = false
  355. this.drainDeferredInjections()
  356. }
  357. }
  358. cancel(cause?: AgentCancelCause, options?: CancelOptions): void {
  359. const resolvedCause = cause ?? { kind: 'user' }
  360. const keepInbox = options?.keepInbox ?? false
  361. const cancellation = this.turnCancellation
  362. // keepInbox preserves pending work, so un-started items must not arm the
  363. // pre-run cancel path that would otherwise drop the next queued turn.
  364. const preRun = !keepInbox && cancellation === undefined
  365. && (this.#inbox.hasQueued || this.#inbox.hasSteering)
  366. if (cancellation !== undefined || preRun) {
  367. if (preRun) this.preRunCancelled = true
  368. // Coordination consumers must update their own state before this call
  369. // clears the inbox or aborts the turn. Notification failures are
  370. // contained by the fused dispatcher and cannot veto cancellation.
  371. agentEvents(this.loopCtx, this).emit('agent/cancel-requested', resolvedCause)
  372. }
  373. if (!keepInbox) {
  374. // Snapshot before clearing so the discard notification carries the exact
  375. // dropped items; a replacement synchronously enqueued by an
  376. // `agent/cancel-requested` observer belongs to the next turn, not here.
  377. const discarded = this.#inbox.pending()
  378. // Clear work already present before abort observers run.
  379. this.#inbox.clear()
  380. if (discarded.length > 0) {
  381. const items = discarded.map(({ message, steering }) => agentMessage(message, steering))
  382. agentEvents(this.loopCtx, this).emit('agent/inbox/discard', items)
  383. }
  384. // No idle-waiter settle here: a `whenIdle` waiter exists only while the
  385. // agent is `running` or a waking item is queued, and neither is left
  386. // quiescent by clearing the inbox — a lone quiet item takes `whenIdle`'s
  387. // fast path (no waiter), a waking item keeps the woken driver running,
  388. // and a running agent owns its own idle transition (including the
  389. // post-turn flush window).
  390. }
  391. cancellation?.request(resolvedCause)
  392. }
  393. /**
  394. * Resolve immediately when idle with no queued work, on the next quiescent
  395. * idle transition otherwise, or after driver exit when already disposed.
  396. * This observes quiescence; it does not own teardown.
  397. */
  398. whenIdle(): Promise<void> {
  399. if (this._status === 'disposed') return this.done
  400. // A lone quiet (`wakeup:false`) queued item leaves the agent quiescent — the
  401. // driver stays parked — so gate on hasWakingQueued, not hasQueued.
  402. if (this._status !== 'running' && !this.#inbox.hasWakingQueued) return Promise.resolve()
  403. // Agent-owned waiters survive concurrent fiber disposal.
  404. return new Promise<void>((resolve) => {
  405. this.idleWaiters.push(() => {
  406. resolve(this._status === 'disposed' ? this.done : undefined)
  407. })
  408. })
  409. }
  410. /** Bind the mutually referential scope context once. */
  411. private [bindContext](ctx: Context): void {
  412. if (this.boundContext !== undefined) throw new Error(`agent "${this.id}" context is already bound`)
  413. this.boundContext = ctx
  414. }
  415. /** Mark that public lifecycle publication began. */
  416. private [publishAgent](): void {
  417. this.published = true
  418. }
  419. /**
  420. * Start the driver loop. The prepared controller already owns its stable
  421. * disposer, so teardown can mark the agent disposed even in the narrow
  422. * publication window before this method runs.
  423. */
  424. [startDriver](): void {
  425. if (this._status === 'disposed') return
  426. this.driverStarted = true
  427. this.done = this.loopCtx.agents.withInitiator(this, () => runLoop(this.loopCtx, {
  428. inbox: this.#inbox,
  429. maxParallelToolCalls: this.maxParallelToolCalls,
  430. setStatus: (status) => { this.setStatus(status) },
  431. installTurnCancellation: () => {
  432. const cancellation = new TurnCancellation()
  433. this.turnCancellation = cancellation
  434. return cancellation
  435. },
  436. clearTurnCancellation: (cancellation) => {
  437. /* v8 ignore else -- the driver clears only the exact owner returned by its latest install. */
  438. if (this.turnCancellation === cancellation) this.turnCancellation = undefined
  439. },
  440. disposed: this.disposed,
  441. isDisposed: () => this._status === 'disposed',
  442. isPreRunCancelled: () => this.preRunCancelled,
  443. clearPreRunCancel: () => { this.preRunCancelled = false },
  444. withToolBatch: run => this.withToolBatch(run),
  445. // Pre-run cancellation settles queued-work waiters before publishing idle.
  446. settleIdle: () => { this.settleIdleWaiters() },
  447. }))
  448. }
  449. /**
  450. * Quiescent stop shared by pre-start rollback and live teardown. It marks the
  451. * agent disposed synchronously, contains an unexpected loop rejection, and
  452. * drains every idle-injection flush before resolving.
  453. */
  454. private [stopDriver](): Promise<void> | void {
  455. if (this._status !== 'disposed') {
  456. // Snapshot any still-pending inbox items, then CLEAR and mark disposed
  457. // BEFORE emitting the discard — mirroring cancel()'s snapshot→clear→emit
  458. // order so a re-entrant followup()/cancel() from a discard listener throws
  459. // `disposed` (or finds an empty inbox) instead of leaking or double-
  460. // discarding an id. `followup()` emits enqueue unconditionally, so the discard
  461. // is unconditional too (even on an unpublished rollback) to keep every
  462. // enqueued id matched.
  463. const discarded = this.#inbox.pending()
  464. this.#inbox.clear()
  465. this._status = 'disposed'
  466. this.resolveDisposed()
  467. if (discarded.length > 0) {
  468. const items = discarded.map(({ message, steering }) => agentMessage(message, steering))
  469. agentEvents(this.loopCtx, this).emit('agent/inbox/discard', items)
  470. }
  471. // Release whenIdle waiters BEFORE the (guarded) event emit — they are
  472. // internal state that must settle even if a listener throws below. Each
  473. // waiter chains `done`, so it resolves only once the loop actually exits.
  474. this.settleIdleWaiters()
  475. this.turnCancellation?.request(DISPOSED_INTERRUPT_REASON)
  476. // An unpublished rollback has no public status lifecycle to announce.
  477. // Once publication begins, disposed is part of the agent/status contract.
  478. if (this.published) {
  479. agentEvents(this.loopCtx, this).emit('agent/status', 'disposed')
  480. }
  481. }
  482. // Before runLoop starts there is normally nothing asynchronous to drain;
  483. // keep publication rollback synchronous so create() cannot throw while its
  484. // session/agent entries are still briefly live. A session-start listener
  485. // may have called inject(), however, so preserve
  486. // its durability checkpoint as a real quiescence boundary.
  487. if (!this.driverStarted && this.pendingIdleFlushes.size === 0) return
  488. return this.drainDriver()
  489. }
  490. /** Await the loop (when started) and every outstanding idle flush. */
  491. private async drainDriver(): Promise<void> {
  492. // An unexpected driver rejection must not skip registry/session/scope
  493. // cleanup. The normal loop contains turn failures itself; allSettled is the
  494. // final lifecycle backstop for anything outside those boundaries.
  495. await Promise.allSettled([this.done])
  496. // Repeat because settled flushes retire in adjacent promise reactions;
  497. // allSettled keeps reporting failures from skipping ownership teardown.
  498. while (this.pendingIdleFlushes.size > 0) {
  499. await Promise.allSettled([...this.pendingIdleFlushes])
  500. }
  501. }
  502. }