index.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. /**
  2. * Concrete agent-loop plugin: creates scoped ReactLoopAgents, publishes them
  3. * through the agent/session registries, and owns their ordered teardown.
  4. *
  5. * @module @deepseek-ai/dsh-agent-loop
  6. */
  7. import { Context, FiberState, Service } from '@deepseek-ai/cordis'
  8. import { randomUUID } from 'node:crypto'
  9. import z from '@deepseek-ai/schemastery'
  10. import { emitAgentEvent } from '@deepseek-ai/dsh-agent'
  11. import type {
  12. Agent,
  13. AgentFactory,
  14. AgentHandle,
  15. AgentOptions,
  16. AgentSetup,
  17. CreateAgentOptions,
  18. ResumeAgentOptions,
  19. SessionStartSource,
  20. } from '@deepseek-ai/dsh-agent'
  21. import { errorChain, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
  22. import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings'
  23. import { SessionId, SessionPreparation } from '@deepseek-ai/dsh-session'
  24. import type { Session, SessionHeader } from '@deepseek-ai/dsh-session'
  25. import type {} from '@deepseek-ai/dsh-system-prompt'
  26. import type {} from '@deepseek-ai/dsh-tools'
  27. import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
  28. import { ReactLoopAgent } from './agent.ts'
  29. import { DEFAULT_MAX_PARALLEL_TOOL_CALLS } from './constants.ts'
  30. /** Fiber states that cannot own or serve a new lifecycle. */
  31. const INACTIVE_STATES: ReadonlySet<FiberState> = new Set([
  32. FiberState.UNLOADING,
  33. FiberState.DISPOSED,
  34. FiberState.FAILED,
  35. ])
  36. /** Factory-level ownership: live agent teardowns plus config startup work. */
  37. class FactoryOwnership {
  38. private accepting = true
  39. private readonly teardown = new AbortController()
  40. private readonly inactive = Promise.withResolvers<void>()
  41. private readonly liveAgents = new Set<() => Promise<void>>()
  42. private startupTasks = new Set<Promise<void>>()
  43. constructor(private readonly fiber: Context['fiber']) {}
  44. /** Aborts (reason: `agent loop is not active` error) when factory teardown begins. */
  45. get signal(): AbortSignal {
  46. return this.teardown.signal
  47. }
  48. isActive(): boolean {
  49. return this.accepting && !INACTIVE_STATES.has(this.fiber.state)
  50. }
  51. /** Track one live agent's shared teardown until it has run. */
  52. track(dispose: () => Promise<void>): () => void {
  53. this.liveAgents.add(dispose)
  54. return () => { this.liveAgents.delete(dispose) }
  55. }
  56. /** Join config startup work that begins before an agent exists. */
  57. trackStartup(job: Promise<void>): void {
  58. this.startupTasks.add(job)
  59. const forget = () => { this.startupTasks.delete(job) }
  60. void job.then(forget, forget)
  61. }
  62. /** Join one public create/resume continuation; factory dispose awaits its settlement. */
  63. trackWrapper(job: Promise<unknown>): void {
  64. this.trackStartup(job.then(() => undefined, () => undefined))
  65. }
  66. /** Resolve `task`, or stop waiting when factory teardown begins. */
  67. async waitWhileActive(job: Promise<void>): Promise<void> {
  68. await Promise.race([job, this.inactive.promise])
  69. }
  70. async dispose(): Promise<void> {
  71. this.accepting = false
  72. this.teardown.abort(new Error('agent loop is not active'))
  73. this.inactive.resolve()
  74. await Promise.all([
  75. ...[...this.liveAgents].map(dispose => dispose()),
  76. ...this.startupTasks,
  77. ])
  78. }
  79. }
  80. /** Await `operation`, or throw the signal's reason as soon as it aborts. */
  81. async function raceAbort<T>(operation: PromiseLike<T> | T, signal: AbortSignal, id: SessionId): Promise<T> {
  82. const toAbortError = (): Error => signal.reason instanceof Error
  83. ? signal.reason
  84. : new Error(`agent "${id}" creation aborted`, { cause: signal.reason })
  85. if (signal.aborted) throw toAbortError()
  86. const aborted = Promise.withResolvers<never>()
  87. const listener = (): void => { aborted.reject(toAbortError()) }
  88. signal.addEventListener('abort', listener, { once: true })
  89. try {
  90. return await Promise.race([Promise.resolve(operation), aborted.promise])
  91. } finally {
  92. signal.removeEventListener('abort', listener)
  93. }
  94. }
  95. /** Start an abortable operation and release a value that arrives after cancellation. */
  96. async function raceAbortCall<T>(
  97. operation: () => PromiseLike<T> | T,
  98. signal: AbortSignal,
  99. id: SessionId,
  100. releaseAbandoned?: (value: T) => void,
  101. ): Promise<T> {
  102. if (signal.aborted) {
  103. throw signal.reason instanceof Error
  104. ? signal.reason
  105. : new Error(`agent "${id}" creation aborted`, { cause: signal.reason })
  106. }
  107. const pending = Promise.resolve().then(operation)
  108. try {
  109. return await raceAbort(pending, signal, id)
  110. } catch (error: unknown) {
  111. // oxlint-disable-next-line typescript/no-unnecessary-condition -- the signal can abort while the operation is awaited.
  112. if (signal.aborted && releaseAbandoned !== undefined) {
  113. void pending.then(releaseAbandoned, () => undefined)
  114. }
  115. throw error
  116. }
  117. }
  118. /** Resolve the deployment-wide scheduler cap at the owning config boundary. */
  119. function resolveMaxParallelToolCalls(value: number | undefined): number {
  120. const maxParallelToolCalls = value ?? DEFAULT_MAX_PARALLEL_TOOL_CALLS
  121. if (!Number.isInteger(maxParallelToolCalls) || maxParallelToolCalls < 1) {
  122. throw new Error('maxParallelToolCalls must be a positive integer')
  123. }
  124. return maxParallelToolCalls
  125. }
  126. /** Reject an output-token cap that cannot be represented exactly on the request wire. */
  127. function assertAgentOptions(options: AgentOptions): void {
  128. if (options.maxTokens !== undefined
  129. && (!Number.isSafeInteger(options.maxTokens) || options.maxTokens <= 0)) {
  130. throw new TypeError('agent maxTokens must be a positive safe integer')
  131. }
  132. }
  133. /** Prepared-but-unpublished agent resources sharing one memoized teardown. */
  134. interface PreparedAgent {
  135. agent: ReactLoopAgent
  136. /** Aborts when the factory unloads, the caller cancels, or teardown begins — ends any setup await. */
  137. signal: AbortSignal
  138. /** Enter registries, announce, notify session-start, and start the machine. */
  139. publish(source: SessionStartSource): AgentHandle
  140. /** Reverse teardown: stop the machine, unregister, unwind the scope. Memoized. */
  141. dispose(): Promise<void>
  142. }
  143. declare module '@deepseek-ai/cordis' {
  144. interface Context {
  145. agentLoop: AgentLoop
  146. /**
  147. * Launcher-owned exact session identities for configured agents, keyed by
  148. * the agent's config `id` and set with `ctx.provide()` before any Loader
  149. * entry mounts (see {@link CONFIGURED_AGENT_IDENTITIES_KEY}). A launcher
  150. * owns identity because only it knows whether the session already exists,
  151. * while the `cordis.yml` row keeps the model route as ordinary patchable
  152. * config. An entry with no matching key keeps its configured identity.
  153. */
  154. configuredAgentIdentities?: ConfiguredAgentIdentities
  155. }
  156. interface Events {
  157. /**
  158. * A declarative agent entry failed before it could publish a live agent.
  159. * Consumers that buffer work for the configured identity use this
  160. * transient signal to reject that work instead of waiting forever. Normal
  161. * factory teardown suppresses failures from the cancelled startup attempt.
  162. * @param payload.sessionId - exact shared agent/session identity that failed startup.
  163. * @param payload.error - persistence, setup, or publication failure.
  164. * @mode emit
  165. */
  166. 'agent-loop/config-start-failed'(payload: { sessionId: SessionId; error: unknown }): void
  167. }
  168. }
  169. export { DEFAULT_MAX_PARALLEL_TOOL_CALLS }
  170. /**
  171. * One launcher-selected session identity for a configured agent. `resume`
  172. * distinguishes rehydrating existing persisted history from creating the
  173. * session fresh under that exact id, which the two config keys express as
  174. * `resumeSessionId` and `sessionId`.
  175. */
  176. export interface LauncherAgentIdentity {
  177. /** Exact session id to create fresh or resume. */
  178. id: SessionId
  179. /** Resume existing persisted history instead of creating the session fresh. */
  180. resume: boolean
  181. }
  182. /** Launcher-selected identities keyed by the configured agent's `id`. */
  183. export interface ConfiguredAgentIdentities extends Readonly<Record<string, LauncherAgentIdentity>> {}
  184. /**
  185. * Context key a launcher sets before any Loader entry mounts
  186. * (`ctx.provide(CONFIGURED_AGENT_IDENTITIES_KEY, identities)`) to fix
  187. * configured agents' session identities without a config key, so an overlay
  188. * repointing the row's model route cannot drop them.
  189. */
  190. export const CONFIGURED_AGENT_IDENTITIES_KEY = 'configuredAgentIdentities'
  191. /**
  192. * Apply launcher-owned identities over the configured agents, replacing both
  193. * identity keys for every entry the launcher named so a config-supplied
  194. * identity can never survive alongside a launcher-supplied one.
  195. * @param agents - the configured agent entries.
  196. * @param identities - launcher identities keyed by configured agent `id`, or `undefined`.
  197. * @returns the entries with launcher-owned identities applied.
  198. */
  199. function applyLauncherIdentities(
  200. agents: Config['agents'],
  201. identities: ConfiguredAgentIdentities | undefined,
  202. ): Config['agents'] {
  203. if (identities === undefined) return agents
  204. return agents.map((agent) => {
  205. const identity = identities[agent.id]
  206. if (identity === undefined) return agent
  207. const { sessionId: _sessionId, resumeSessionId: _resumeSessionId, ...rest } = agent
  208. return identity.resume
  209. ? { ...rest, resumeSessionId: identity.id }
  210. : { ...rest, sessionId: identity.id }
  211. })
  212. }
  213. /** Settings namespace carrying the tool-call parallelism a user owns. */
  214. export const AGENT_LOOP_SETTINGS_NAMESPACE = settingsNamespace('agent-loop')
  215. /**
  216. * The agent-loop fields a user owns. Deliberately a strict subset of
  217. * {@link Config}: `agents` is a boot-time composition array consumed once when
  218. * the service starts, so a stored change could only look like it had an effect.
  219. */
  220. export interface AgentLoopSettings {
  221. /** Maximum parallel-safe calls in flight per agent step. */
  222. maxParallelToolCalls: number
  223. }
  224. /** Schema of the agent-loop settings section. */
  225. export const AGENT_LOOP_SETTINGS_SCHEMA: z<AgentLoopSettings> = z.object({
  226. maxParallelToolCalls: z.number().step(1).min(1).default(DEFAULT_MAX_PARALLEL_TOOL_CALLS),
  227. })
  228. /** Agent-loop plugin configuration. */
  229. export interface Config {
  230. /**
  231. * Maximum parallel-safe calls in flight per agent step. `1` is serial;
  232. * omission defaults to {@link DEFAULT_MAX_PARALLEL_TOOL_CALLS}.
  233. */
  234. maxParallelToolCalls?: number
  235. /** Agents created or resumed at plugin startup. */
  236. agents: (AgentOptions & {
  237. /** Stable config label used in logs and as the fresh combined-id prefix. */
  238. id: string
  239. /** Optional stable identity; remounts resume its materialized history, while first use creates it fresh. */
  240. sessionId?: SessionId
  241. /** Optional workspace for a fresh session. */
  242. cwd?: string
  243. /** Persisted session to resume instead of creating a fresh session. */
  244. resumeSessionId?: SessionId
  245. })[]
  246. }
  247. /** Agent-loop configuration after defaults and load-time validation. */
  248. type ResolvedConfig = Config & { maxParallelToolCalls: number }
  249. /** Reject self-contained identity conflicts before any configured agent starts. */
  250. function validateConfiguredAgents(agents: Config['agents']): void {
  251. const exactIdentities = new Map<SessionId, string>()
  252. for (const { id, sessionId, resumeSessionId } of agents) {
  253. const hasResumeId = resumeSessionId !== undefined && resumeSessionId !== ''
  254. if (sessionId !== undefined && hasResumeId) {
  255. throw new Error(`agent "${id}": sessionId and resumeSessionId are mutually exclusive`)
  256. }
  257. const exactIdentity = hasResumeId ? resumeSessionId : sessionId
  258. if (exactIdentity === undefined) continue
  259. const firstId = exactIdentities.get(exactIdentity)
  260. if (firstId !== undefined) {
  261. throw new Error(`agents "${firstId}" and "${id}" use duplicate exact session identity "${exactIdentity}"`)
  262. }
  263. exactIdentities.set(exactIdentity, id)
  264. }
  265. }
  266. /** Concrete agent factory and driver service. */
  267. export class AgentLoop extends Service implements AgentFactory {
  268. static inject = ['agents', 'sessions', 'llm', 'tools', 'systemPrompt']
  269. /** Runtime schema for declarative agents. */
  270. static Config = z.object({
  271. maxParallelToolCalls: z.number().step(1).min(1).default(DEFAULT_MAX_PARALLEL_TOOL_CALLS),
  272. agents: z.array(z.object({
  273. id: z.string().required(),
  274. sessionId: z.string().min(1),
  275. provider: z.string(),
  276. model: z.string(),
  277. reasoningEffort: z.string().min(1) as z<ReturnType<typeof ReasoningEffortId>>,
  278. maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER),
  279. cwd: z.string(),
  280. resumeSessionId: z.string(),
  281. })).default([]),
  282. }) as z<Config>
  283. /** Validated configuration owned by the agent-loop service. */
  284. readonly config: ResolvedConfig
  285. private readonly ownership: FactoryOwnership
  286. /** Plain holder prevents Cordis from re-tracing the factory's dependency context through a caller shadow. */
  287. private readonly runtime: { ctx: Context }
  288. constructor(ctx: Context, config: Config) {
  289. super(ctx, 'agentLoop')
  290. const entry: AgentLoopSettings = {
  291. maxParallelToolCalls: resolveMaxParallelToolCalls(config.maxParallelToolCalls),
  292. }
  293. let source: () => AgentLoopSettings = () => entry
  294. this.config = {
  295. ...config,
  296. agents: applyLauncherIdentities(config.agents, ctx.get(CONFIGURED_AGENT_IDENTITIES_KEY)),
  297. // Read through on every scheduler decision: `tool-calls.ts` destructures
  298. // this at the start of each group, so a committed change caps the next
  299. // group without disturbing the one in flight.
  300. get maxParallelToolCalls() {
  301. return source().maxParallelToolCalls
  302. },
  303. }
  304. installSettingsSection(ctx, AGENT_LOOP_SETTINGS_NAMESPACE, AGENT_LOOP_SETTINGS_SCHEMA, entry, {
  305. // The schema admits any integer above zero; `resolveMaxParallelToolCalls`
  306. // owns the whole rule, so refusing here keeps the running scheduler on
  307. // its last good cap instead of failing at the next tool group.
  308. validate: value => void resolveMaxParallelToolCalls(value.maxParallelToolCalls),
  309. setSource: (current) => {
  310. source = current
  311. },
  312. // Nothing is derived from the cap: the getter above is the only reader.
  313. onChange: () => {},
  314. })
  315. validateConfiguredAgents(this.config.agents)
  316. this.ownership = new FactoryOwnership(ctx.fiber)
  317. this.runtime = { ctx }
  318. ctx.effect(() => () => this.ownership.dispose(), 'agentLoop.transactions()')
  319. ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()')
  320. ctx.systemPrompt.variable('provider', context => context.agent?.options.provider)
  321. ctx.systemPrompt.variable('model', context => context.agent?.options.model)
  322. ctx.systemPrompt.variable('cwd', context => context.agent?.session.header.cwd)
  323. for (const { id, sessionId, cwd, resumeSessionId, ...options } of this.config.agents) {
  324. const meta = cwd === undefined ? {} : { cwd }
  325. if (resumeSessionId === undefined || resumeSessionId === '') {
  326. const configuredId = sessionId ?? SessionId(`${id}-session-${randomUUID()}`)
  327. const persistence = sessionId === undefined ? undefined : ctx.get('sessionPersistence')
  328. if (persistence === undefined) {
  329. this.create(configuredId, options, meta)
  330. } else {
  331. const startup = this.restoreOrCreateConfigured(ctx, persistence, configuredId, options, meta).catch((error: unknown) => {
  332. this.reportConfiguredStartupFailure(id, 'restore', configuredId, error)
  333. })
  334. this.ownership.trackStartup(startup)
  335. }
  336. continue
  337. }
  338. ctx.effect(() => {
  339. const fiber = ctx.inject(['sessionPersistence'], (childCtx: Context) => {
  340. void this.resumeWith(ctx, childCtx.sessionPersistence, {
  341. resumeSessionId,
  342. agentOptions: options,
  343. }).catch((error: unknown) => {
  344. this.reportConfiguredStartupFailure(id, 'resume', resumeSessionId, error)
  345. })
  346. })
  347. return fiber.dispose
  348. }, `agentLoop.resume(${id})`)
  349. }
  350. }
  351. /** Report a contained declarative-start failure to identity-bound consumers. */
  352. private reportConfiguredStartupFailure(
  353. configId: string,
  354. action: 'restore' | 'resume',
  355. sessionId: SessionId,
  356. error: unknown,
  357. ): void {
  358. if (!this.ownership.isActive()) return
  359. this.ctx.logger.warn(`agent "${configId}": config-driven ${action} of "${sessionId}" failed: ${errorChain(error)}`)
  360. const args: unknown[] = ['agent-loop/config-start-failed', { sessionId, error }]
  361. for (const callback of this.ctx.events.dispatch('emit', args)) {
  362. try {
  363. const returned: unknown = callback(...args)
  364. void Promise.resolve(returned).catch((listenerError: unknown) => {
  365. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener rejected: ${errorChain(listenerError)}`)
  366. })
  367. } catch (listenerError: unknown) {
  368. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener threw: ${errorChain(listenerError)}`)
  369. }
  370. }
  371. }
  372. /** Restore a materialized exact config identity on remount, or create it on first use. */
  373. private async restoreOrCreateConfigured(
  374. ownerCtx: Context,
  375. persistence: SessionPersistence,
  376. sessionId: SessionId,
  377. agentOptions: AgentOptions,
  378. meta: Pick<SessionHeader, 'cwd'>,
  379. ): Promise<void> {
  380. await this.waitForDrainingConfiguredIdentity(ownerCtx, sessionId)
  381. if (!this.ownership.isActive()) return
  382. try {
  383. await this.resumeWith(ownerCtx, persistence, { resumeSessionId: sessionId, agentOptions })
  384. return
  385. } catch (error: unknown) {
  386. if (!this.ownership.isActive()) return
  387. // A load is the per-id serialization barrier for eager write-behind and
  388. // lifecycle retirement. Only a genuinely absent artifact falls back to
  389. // first creation; corruption and backend failures stay loud.
  390. const exists = (await persistence.list()).some(header => header.id === sessionId)
  391. if (exists) throw error
  392. }
  393. this.create(sessionId, agentOptions, meta)
  394. }
  395. /** Wait for a draining same-id lifecycle to finish registry teardown. */
  396. private async waitForDrainingConfiguredIdentity(ownerCtx: Context, sessionId: SessionId): Promise<void> {
  397. // Only an id still occupying a registry needs waiting for; a live healthy
  398. // occupant is a collision the create/resume below will surface itself.
  399. if (ownerCtx.agents.get(sessionId) === undefined && ownerCtx.sessions.get(sessionId) === undefined) return
  400. const released = Promise.withResolvers<void>()
  401. const checkReleased = (): void => {
  402. if (ownerCtx.agents.get(sessionId) === undefined && ownerCtx.sessions.get(sessionId) === undefined) {
  403. released.resolve()
  404. }
  405. }
  406. const disposeAgentListener = ownerCtx.on('agent/disposed', () => { checkReleased() })
  407. const disposeSessionListener = ownerCtx.on('session/disposed', checkReleased)
  408. try {
  409. checkReleased()
  410. await this.ownership.waitWhileActive(released.promise)
  411. } finally {
  412. disposeAgentListener()
  413. disposeSessionListener()
  414. }
  415. }
  416. /**
  417. * Construct the driver, scope, and one memoized reverse teardown for a new
  418. * agent. The teardown is registered with the factory and the owner fiber
  419. * BEFORE publication, so a mid-setup unload rolls everything back; `signal`
  420. * fuses caller cancellation with lifecycle teardown for setup awaits.
  421. */
  422. private prepare(ownerCtx: Context, id: SessionId, options: AgentOptions, session: Session, callerSignal?: AbortSignal): PreparedAgent {
  423. assertAgentOptions(options)
  424. ownerCtx.fiber.assertActive()
  425. // Every caller reaches prepare() synchronously from a service method
  426. // whose Cordis dispatch already requires the live factory fiber, or
  427. // re-checks ownership itself after its awaits (resume's load barrier).
  428. /* v8 ignore next -- unreachable backstop, see above */
  429. if (!this.ownership.isActive()) throw new Error('agent loop is not active')
  430. if (callerSignal?.aborted) {
  431. throw callerSignal.reason instanceof Error
  432. ? callerSignal.reason
  433. : new Error(`agent "${id}" creation aborted`, { cause: callerSignal.reason })
  434. }
  435. const loopCtx = this.runtime.ctx
  436. // Deactivation fuses three owners, each with its own reason: the caller's
  437. // cancellation signal, the owner fiber's unload, and factory teardown.
  438. // It is registered BEFORE any resource exists, over mutable slots, so an
  439. // unload arriving while the scope is still minting finds a working
  440. // disposer instead of a leak.
  441. const abort = new AbortController()
  442. const onCallerAbort = (): void => {
  443. abort.abort(callerSignal?.reason instanceof Error
  444. ? callerSignal.reason
  445. : new Error(`agent "${id}" creation aborted`, { cause: callerSignal?.reason }))
  446. }
  447. const onFactoryTeardown = (): void => { abort.abort(this.ownership.signal.reason) }
  448. callerSignal?.addEventListener('abort', onCallerAbort, { once: true })
  449. this.ownership.signal.addEventListener('abort', onFactoryTeardown, { once: true })
  450. let machine: ReactLoopAgent | undefined
  451. let detachSession: (() => void) | undefined
  452. let detachAgent: (() => void) | undefined
  453. let disposing: Promise<void> | undefined
  454. const machineReady = Promise.withResolvers<void>()
  455. // Reverse teardown, memoized so every racing owner awaits one quiescence:
  456. // stop the machine, leave the registries, unwind the scope, release
  457. // bookkeeping.
  458. const dispose = (ownerTriggered = false): Promise<void> => (disposing ??= (async () => {
  459. abort.abort(new Error(`agent "${id}" lifecycle disposed`))
  460. callerSignal?.removeEventListener('abort', onCallerAbort)
  461. this.ownership.signal.removeEventListener('abort', onFactoryTeardown)
  462. try {
  463. // Disposal IS a disposed-cause cancel followed by quiescence. New work
  464. // sent after this point is the sender's bug — the registries are about
  465. // to drop the agent, so nothing should still hold it.
  466. if (machine === undefined) await machineReady.promise
  467. if (machine !== undefined) {
  468. machine.cancel({ kind: 'disposed' })
  469. await machine.whenIdle()
  470. await machine.scope.dispose()
  471. }
  472. } finally {
  473. try {
  474. detachAgent?.()
  475. detachSession?.()
  476. } finally {
  477. untrack()
  478. if (!ownerTriggered) await unfollowOwner()
  479. }
  480. }
  481. })())
  482. const untrack = this.ownership.track(dispose)
  483. let unfollowOwner: () => Promise<void> | void
  484. try {
  485. unfollowOwner = ownerCtx.effect(() => () => {
  486. // Owner disposal owns the same quiescence boundary. Its teardown skips
  487. // unregistering this already-running owner effect from inside itself.
  488. if (disposing !== undefined) return
  489. abort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`))
  490. return dispose(true)
  491. }, `agentLoop.lifecycle(${id})`)
  492. /* v8 ignore start -- ctx.effect throws only on an inactive fiber, which assertActive() above already rejected */
  493. } catch (error: unknown) {
  494. untrack()
  495. callerSignal?.removeEventListener('abort', onCallerAbort)
  496. this.ownership.signal.removeEventListener('abort', onFactoryTeardown)
  497. throw error
  498. }
  499. /* v8 ignore stop */
  500. const assertLive = (): void => {
  501. if (!abort.signal.aborted) return
  502. // Every fused abort source carries an Error reason: onCallerAbort and
  503. // raceAbort wrap non-Error caller reasons, and the factory/lifecycle
  504. // owners abort with constructed Errors.
  505. /* v8 ignore next -- unreachable String() arm, see above */
  506. throw abort.signal.reason instanceof Error ? abort.signal.reason : new Error(String(abort.signal.reason))
  507. }
  508. try {
  509. const agent = machine = new ReactLoopAgent(loopCtx, id, options, session)
  510. machineReady.resolve()
  511. assertLive()
  512. return {
  513. agent,
  514. signal: abort.signal,
  515. publish: (source) => {
  516. assertLive()
  517. detachSession = agent.ctx.sessions.enter(session)
  518. detachAgent = loopCtx.agents.enter(agent, ownerCtx.agent)
  519. agent.ctx.sessions.announce(session)
  520. assertLive()
  521. loopCtx.agents.announce(agent)
  522. assertLive()
  523. // A synchronous announce/session-start listener may have started
  524. // teardown; the machine is already live (delivery works from the
  525. // session-start extension point), so only the liveness recheck is owed.
  526. emitAgentEvent(loopCtx, agent, 'agent/session-start', { source })
  527. assertLive()
  528. return { agent, dispose }
  529. },
  530. dispose,
  531. }
  532. } catch (error: unknown) {
  533. machineReady.resolve()
  534. void dispose()
  535. throw error
  536. }
  537. }
  538. /**
  539. * Create an agent and session under one caller-supplied identity, owned by
  540. * the accessing fiber. Constructor-driven config calls mint a fresh combined
  541. * id before entering this boundary.
  542. * @param id - shared agent/session identity.
  543. * @param options - concrete loop options.
  544. * @param meta - optional fresh-session workspace metadata.
  545. * @returns the published running agent.
  546. */
  547. create(id: SessionId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): Agent {
  548. using preparation = SessionPreparation.create(this.runtime.ctx.sessions.prepare(id, { meta }))
  549. const prepared = this.prepare(this.ctx, id, options, preparation.session)
  550. try {
  551. return prepared.publish('startup').agent
  552. } catch (error: unknown) {
  553. void prepared.dispose()
  554. throw error
  555. }
  556. }
  557. /**
  558. * Create an owned agent on a caller-supplied session id.
  559. * @param ownerCtx - caller context that structurally owns the lifecycle.
  560. * @param options - identities, session seed/metadata, loop options, setup, and cancellation.
  561. * @returns the published handle.
  562. */
  563. async createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> {
  564. const preparation = SessionPreparation.create(this.runtime.ctx.sessions.prepare(options.sessionId, {
  565. ...options.seed === undefined ? {} : { seed: options.seed },
  566. ...options.meta === undefined ? {} : { meta: options.meta },
  567. }))
  568. const published = this.setupAndPublish(
  569. ownerCtx,
  570. options.sessionId,
  571. preparation,
  572. options.agentOptions ?? {},
  573. options.setup,
  574. options.signal,
  575. 'startup',
  576. )
  577. this.ownership.trackWrapper(published)
  578. return published
  579. }
  580. /** Prepare one Agent around an acquired Session, run setup, and publish it. */
  581. private async setupAndPublish(
  582. ownerCtx: Context,
  583. id: SessionId,
  584. preparation: SessionPreparation,
  585. agentOptions: AgentOptions,
  586. setup: AgentSetup | undefined,
  587. signal: AbortSignal | undefined,
  588. source: SessionStartSource,
  589. ): Promise<AgentHandle> {
  590. using ownedPreparation = preparation
  591. const session = ownedPreparation.session
  592. const prepared = this.prepare(ownerCtx, id, agentOptions, session, signal)
  593. try {
  594. const setupCommit = await raceAbort(setup?.(prepared.agent.ctx), prepared.signal, id)
  595. setupCommit?.commit()
  596. return prepared.publish(source)
  597. } catch (error: unknown) {
  598. await prepared.dispose()
  599. throw error
  600. }
  601. }
  602. /**
  603. * Resume an owned agent from the configured persistence service.
  604. * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.
  605. * @param options - persisted identity, loop options, setup, and cancellation.
  606. * @returns the published handle.
  607. */
  608. async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle> {
  609. const persistence = this.runtime.ctx.get('sessionPersistence')
  610. if (persistence === undefined) {
  611. throw new Error('cannot resume: session persistence is not configured (load a dsh-session-persistence backend)')
  612. }
  613. return this.resumeWith(ownerCtx, persistence, options)
  614. }
  615. /** Resume through an explicit persistence handle used by the deferred config path. */
  616. private resumeWith(
  617. ownerCtx: Context,
  618. persistence: SessionPersistence,
  619. options: ResumeAgentOptions,
  620. ): Promise<AgentHandle> {
  621. const id = options.resumeSessionId
  622. const published = (async () => {
  623. // The load may outlive its owner: race it against caller cancellation,
  624. // owner-fiber unload, and factory teardown so a never-settling backend
  625. // cannot pin the identity.
  626. const ownerAbort = new AbortController()
  627. const unfollowOwner = ownerCtx.effect(() => () => {
  628. ownerAbort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`))
  629. }, `agentLoop.resume-load(${id})`)
  630. const fused = AbortSignal.any([
  631. ...options.signal === undefined ? [] : [options.signal],
  632. ownerAbort.signal,
  633. this.ownership.signal,
  634. ])
  635. let preparation: SessionPreparation | undefined
  636. try {
  637. try {
  638. preparation = await raceAbortCall(
  639. () => persistence.prepare(id, fused),
  640. fused,
  641. id,
  642. (abandoned) => { abandoned[Symbol.dispose]() },
  643. )
  644. } finally {
  645. await unfollowOwner()
  646. }
  647. ownerCtx.fiber.assertActive()
  648. if (!this.ownership.isActive()) throw new Error('agent loop is not active')
  649. return await this.setupAndPublish(
  650. ownerCtx,
  651. id,
  652. preparation,
  653. options.agentOptions ?? {},
  654. options.setup,
  655. options.signal,
  656. 'resume',
  657. )
  658. } finally {
  659. preparation?.[Symbol.dispose]()
  660. }
  661. })()
  662. this.ownership.trackWrapper(published)
  663. return published
  664. }
  665. }
  666. export default AgentLoop