index.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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 } 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. maxTokens: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER),
  278. cwd: z.string(),
  279. resumeSessionId: z.string(),
  280. })).default([]),
  281. }) as z<Config>
  282. /** Validated configuration owned by the agent-loop service. */
  283. readonly config: ResolvedConfig
  284. private readonly ownership: FactoryOwnership
  285. /** Plain holder prevents Cordis from re-tracing the factory's dependency context through a caller shadow. */
  286. private readonly runtime: { ctx: Context }
  287. constructor(ctx: Context, config: Config) {
  288. super(ctx, 'agentLoop')
  289. const entry: AgentLoopSettings = {
  290. maxParallelToolCalls: resolveMaxParallelToolCalls(config.maxParallelToolCalls),
  291. }
  292. let source: () => AgentLoopSettings = () => entry
  293. this.config = {
  294. ...config,
  295. agents: applyLauncherIdentities(config.agents, ctx.get(CONFIGURED_AGENT_IDENTITIES_KEY)),
  296. // Read through on every scheduler decision: `tool-calls.ts` destructures
  297. // this at the start of each group, so a committed change caps the next
  298. // group without disturbing the one in flight.
  299. get maxParallelToolCalls() {
  300. return source().maxParallelToolCalls
  301. },
  302. }
  303. installSettingsSection(ctx, AGENT_LOOP_SETTINGS_NAMESPACE, AGENT_LOOP_SETTINGS_SCHEMA, entry, {
  304. // The schema admits any integer above zero; `resolveMaxParallelToolCalls`
  305. // owns the whole rule, so refusing here keeps the running scheduler on
  306. // its last good cap instead of failing at the next tool group.
  307. validate: value => void resolveMaxParallelToolCalls(value.maxParallelToolCalls),
  308. setSource: (current) => {
  309. source = current
  310. },
  311. // Nothing is derived from the cap: the getter above is the only reader.
  312. onChange: () => {},
  313. })
  314. validateConfiguredAgents(this.config.agents)
  315. this.ownership = new FactoryOwnership(ctx.fiber)
  316. this.runtime = { ctx }
  317. ctx.effect(() => () => this.ownership.dispose(), 'agentLoop.transactions()')
  318. ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()')
  319. ctx.systemPrompt.variable('provider', context => context.agent?.options.provider)
  320. ctx.systemPrompt.variable('model', context => context.agent?.options.model)
  321. ctx.systemPrompt.variable('cwd', context => context.agent?.session.header.cwd)
  322. for (const { id, sessionId, cwd, resumeSessionId, ...options } of this.config.agents) {
  323. const meta = cwd === undefined ? {} : { cwd }
  324. if (resumeSessionId === undefined || resumeSessionId === '') {
  325. const configuredId = sessionId ?? SessionId(`${id}-session-${randomUUID()}`)
  326. const persistence = sessionId === undefined ? undefined : ctx.get('sessionPersistence')
  327. if (persistence === undefined) {
  328. this.create(configuredId, options, meta)
  329. } else {
  330. const startup = this.restoreOrCreateConfigured(ctx, persistence, configuredId, options, meta).catch((error: unknown) => {
  331. this.reportConfiguredStartupFailure(id, 'restore', configuredId, error)
  332. })
  333. this.ownership.trackStartup(startup)
  334. }
  335. continue
  336. }
  337. ctx.effect(() => {
  338. const fiber = ctx.inject(['sessionPersistence'], (childCtx: Context) => {
  339. void this.resumeWith(ctx, childCtx.sessionPersistence, {
  340. resumeSessionId,
  341. agentOptions: options,
  342. }).catch((error: unknown) => {
  343. this.reportConfiguredStartupFailure(id, 'resume', resumeSessionId, error)
  344. })
  345. })
  346. return fiber.dispose
  347. }, `agentLoop.resume(${id})`)
  348. }
  349. }
  350. /** Report a contained declarative-start failure to identity-bound consumers. */
  351. private reportConfiguredStartupFailure(
  352. configId: string,
  353. action: 'restore' | 'resume',
  354. sessionId: SessionId,
  355. error: unknown,
  356. ): void {
  357. if (!this.ownership.isActive()) return
  358. this.ctx.logger.warn(`agent "${configId}": config-driven ${action} of "${sessionId}" failed: ${errorChain(error)}`)
  359. const args: unknown[] = ['agent-loop/config-start-failed', { sessionId, error }]
  360. for (const callback of this.ctx.events.dispatch('emit', args)) {
  361. try {
  362. const returned: unknown = callback(...args)
  363. void Promise.resolve(returned).catch((listenerError: unknown) => {
  364. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener rejected: ${errorChain(listenerError)}`)
  365. })
  366. } catch (listenerError: unknown) {
  367. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener threw: ${errorChain(listenerError)}`)
  368. }
  369. }
  370. }
  371. /** Restore a materialized exact config identity on remount, or create it on first use. */
  372. private async restoreOrCreateConfigured(
  373. ownerCtx: Context,
  374. persistence: SessionPersistence,
  375. sessionId: SessionId,
  376. agentOptions: AgentOptions,
  377. meta: Pick<SessionHeader, 'cwd'>,
  378. ): Promise<void> {
  379. await this.waitForDrainingConfiguredIdentity(ownerCtx, sessionId)
  380. if (!this.ownership.isActive()) return
  381. try {
  382. await this.resumeWith(ownerCtx, persistence, { resumeSessionId: sessionId, agentOptions })
  383. return
  384. } catch (error: unknown) {
  385. if (!this.ownership.isActive()) return
  386. // A load is the per-id serialization barrier for eager write-behind and
  387. // lifecycle retirement. Only a genuinely absent artifact falls back to
  388. // first creation; corruption and backend failures stay loud.
  389. const exists = (await persistence.list()).some(header => header.id === sessionId)
  390. if (exists) throw error
  391. }
  392. this.create(sessionId, agentOptions, meta)
  393. }
  394. /** Wait for a draining same-id lifecycle to finish registry teardown. */
  395. private async waitForDrainingConfiguredIdentity(ownerCtx: Context, sessionId: SessionId): Promise<void> {
  396. // Only an id still occupying a registry needs waiting for; a live healthy
  397. // occupant is a collision the create/resume below will surface itself.
  398. if (ownerCtx.agents.get(sessionId) === undefined && ownerCtx.sessions.get(sessionId) === undefined) return
  399. const released = Promise.withResolvers<void>()
  400. const checkReleased = (): void => {
  401. if (ownerCtx.agents.get(sessionId) === undefined && ownerCtx.sessions.get(sessionId) === undefined) {
  402. released.resolve()
  403. }
  404. }
  405. const disposeAgentListener = ownerCtx.on('agent/disposed', () => { checkReleased() })
  406. const disposeSessionListener = ownerCtx.on('session/disposed', checkReleased)
  407. try {
  408. checkReleased()
  409. await this.ownership.waitWhileActive(released.promise)
  410. } finally {
  411. disposeAgentListener()
  412. disposeSessionListener()
  413. }
  414. }
  415. /**
  416. * Construct the driver, scope, and one memoized reverse teardown for a new
  417. * agent. The teardown is registered with the factory and the owner fiber
  418. * BEFORE publication, so a mid-setup unload rolls everything back; `signal`
  419. * fuses caller cancellation with lifecycle teardown for setup awaits.
  420. */
  421. private prepare(ownerCtx: Context, id: SessionId, options: AgentOptions, session: Session, callerSignal?: AbortSignal): PreparedAgent {
  422. assertAgentOptions(options)
  423. ownerCtx.fiber.assertActive()
  424. // Every caller reaches prepare() synchronously from a service method
  425. // whose Cordis dispatch already requires the live factory fiber, or
  426. // re-checks ownership itself after its awaits (resume's load barrier).
  427. /* v8 ignore next -- unreachable backstop, see above */
  428. if (!this.ownership.isActive()) throw new Error('agent loop is not active')
  429. if (callerSignal?.aborted) {
  430. throw callerSignal.reason instanceof Error
  431. ? callerSignal.reason
  432. : new Error(`agent "${id}" creation aborted`, { cause: callerSignal.reason })
  433. }
  434. const loopCtx = this.runtime.ctx
  435. // Deactivation fuses three owners, each with its own reason: the caller's
  436. // cancellation signal, the owner fiber's unload, and factory teardown.
  437. // It is registered BEFORE any resource exists, over mutable slots, so an
  438. // unload arriving while the scope is still minting finds a working
  439. // disposer instead of a leak.
  440. const abort = new AbortController()
  441. const onCallerAbort = (): void => {
  442. abort.abort(callerSignal?.reason instanceof Error
  443. ? callerSignal.reason
  444. : new Error(`agent "${id}" creation aborted`, { cause: callerSignal?.reason }))
  445. }
  446. const onFactoryTeardown = (): void => { abort.abort(this.ownership.signal.reason) }
  447. callerSignal?.addEventListener('abort', onCallerAbort, { once: true })
  448. this.ownership.signal.addEventListener('abort', onFactoryTeardown, { once: true })
  449. let machine: ReactLoopAgent | undefined
  450. let detachSession: (() => void) | undefined
  451. let detachAgent: (() => void) | undefined
  452. let disposing: Promise<void> | undefined
  453. const machineReady = Promise.withResolvers<void>()
  454. // Reverse teardown, memoized so every racing owner awaits one quiescence:
  455. // stop the machine, leave the registries, unwind the scope, release
  456. // bookkeeping.
  457. const dispose = (ownerTriggered = false): Promise<void> => (disposing ??= (async () => {
  458. abort.abort(new Error(`agent "${id}" lifecycle disposed`))
  459. callerSignal?.removeEventListener('abort', onCallerAbort)
  460. this.ownership.signal.removeEventListener('abort', onFactoryTeardown)
  461. try {
  462. // Disposal IS a disposed-cause cancel followed by quiescence. New work
  463. // sent after this point is the sender's bug — the registries are about
  464. // to drop the agent, so nothing should still hold it.
  465. if (machine === undefined) await machineReady.promise
  466. if (machine !== undefined) {
  467. machine.cancel({ kind: 'disposed' })
  468. await machine.whenIdle()
  469. await machine.scope.dispose()
  470. }
  471. } finally {
  472. try {
  473. detachAgent?.()
  474. detachSession?.()
  475. } finally {
  476. untrack()
  477. if (!ownerTriggered) await unfollowOwner()
  478. }
  479. }
  480. })())
  481. const untrack = this.ownership.track(dispose)
  482. let unfollowOwner: () => Promise<void> | void
  483. try {
  484. unfollowOwner = ownerCtx.effect(() => () => {
  485. // Owner disposal owns the same quiescence boundary. Its teardown skips
  486. // unregistering this already-running owner effect from inside itself.
  487. if (disposing !== undefined) return
  488. abort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`))
  489. return dispose(true)
  490. }, `agentLoop.lifecycle(${id})`)
  491. /* v8 ignore start -- ctx.effect throws only on an inactive fiber, which assertActive() above already rejected */
  492. } catch (error: unknown) {
  493. untrack()
  494. callerSignal?.removeEventListener('abort', onCallerAbort)
  495. this.ownership.signal.removeEventListener('abort', onFactoryTeardown)
  496. throw error
  497. }
  498. /* v8 ignore stop */
  499. const assertLive = (): void => {
  500. if (!abort.signal.aborted) return
  501. // Every fused abort source carries an Error reason: onCallerAbort and
  502. // raceAbort wrap non-Error caller reasons, and the factory/lifecycle
  503. // owners abort with constructed Errors.
  504. /* v8 ignore next -- unreachable String() arm, see above */
  505. throw abort.signal.reason instanceof Error ? abort.signal.reason : new Error(String(abort.signal.reason))
  506. }
  507. try {
  508. const agent = machine = new ReactLoopAgent(loopCtx, id, options, session)
  509. machineReady.resolve()
  510. assertLive()
  511. return {
  512. agent,
  513. signal: abort.signal,
  514. publish: (source) => {
  515. assertLive()
  516. detachSession = agent.ctx.sessions.enter(session)
  517. detachAgent = loopCtx.agents.enter(agent, ownerCtx.agent)
  518. agent.ctx.sessions.announce(session)
  519. assertLive()
  520. loopCtx.agents.announce(agent)
  521. assertLive()
  522. // A synchronous announce/session-start listener may have started
  523. // teardown; the machine is already live (delivery works from the
  524. // session-start extension point), so only the liveness recheck is owed.
  525. emitAgentEvent(loopCtx, agent, 'agent/session-start', { source })
  526. assertLive()
  527. return { agent, dispose }
  528. },
  529. dispose,
  530. }
  531. } catch (error: unknown) {
  532. machineReady.resolve()
  533. void dispose()
  534. throw error
  535. }
  536. }
  537. /**
  538. * Create an agent and session under one caller-supplied identity, owned by
  539. * the accessing fiber. Constructor-driven config calls mint a fresh combined
  540. * id before entering this boundary.
  541. * @param id - shared agent/session identity.
  542. * @param options - concrete loop options.
  543. * @param meta - optional fresh-session workspace metadata.
  544. * @returns the published running agent.
  545. */
  546. create(id: SessionId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): Agent {
  547. using preparation = SessionPreparation.create(this.runtime.ctx.sessions.prepare(id, { meta }))
  548. const prepared = this.prepare(this.ctx, id, options, preparation.session)
  549. try {
  550. return prepared.publish('startup').agent
  551. } catch (error: unknown) {
  552. void prepared.dispose()
  553. throw error
  554. }
  555. }
  556. /**
  557. * Create an owned agent on a caller-supplied session id.
  558. * @param ownerCtx - caller context that structurally owns the lifecycle.
  559. * @param options - identities, session seed/metadata, loop options, setup, and cancellation.
  560. * @returns the published handle.
  561. */
  562. async createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> {
  563. const preparation = SessionPreparation.create(this.runtime.ctx.sessions.prepare(options.sessionId, {
  564. ...options.seed === undefined ? {} : { seed: options.seed },
  565. ...options.meta === undefined ? {} : { meta: options.meta },
  566. }))
  567. const published = this.setupAndPublish(
  568. ownerCtx,
  569. options.sessionId,
  570. preparation,
  571. options.agentOptions ?? {},
  572. options.setup,
  573. options.signal,
  574. 'startup',
  575. )
  576. this.ownership.trackWrapper(published)
  577. return published
  578. }
  579. /** Prepare one Agent around an acquired Session, run setup, and publish it. */
  580. private async setupAndPublish(
  581. ownerCtx: Context,
  582. id: SessionId,
  583. preparation: SessionPreparation,
  584. agentOptions: AgentOptions,
  585. setup: AgentSetup | undefined,
  586. signal: AbortSignal | undefined,
  587. source: SessionStartSource,
  588. ): Promise<AgentHandle> {
  589. using ownedPreparation = preparation
  590. const session = ownedPreparation.session
  591. const prepared = this.prepare(ownerCtx, id, agentOptions, session, signal)
  592. try {
  593. const setupCommit = await raceAbort(setup?.(prepared.agent.ctx), prepared.signal, id)
  594. setupCommit?.commit()
  595. return prepared.publish(source)
  596. } catch (error: unknown) {
  597. await prepared.dispose()
  598. throw error
  599. }
  600. }
  601. /**
  602. * Resume an owned agent from the configured persistence service.
  603. * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.
  604. * @param options - persisted identity, loop options, setup, and cancellation.
  605. * @returns the published handle.
  606. */
  607. async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle> {
  608. const persistence = this.runtime.ctx.get('sessionPersistence')
  609. if (persistence === undefined) {
  610. throw new Error('cannot resume: session persistence is not configured (load a dsh-session-persistence backend)')
  611. }
  612. return this.resumeWith(ownerCtx, persistence, options)
  613. }
  614. /** Resume through an explicit persistence handle used by the deferred config path. */
  615. private resumeWith(
  616. ownerCtx: Context,
  617. persistence: SessionPersistence,
  618. options: ResumeAgentOptions,
  619. ): Promise<AgentHandle> {
  620. const id = options.resumeSessionId
  621. const published = (async () => {
  622. // The load may outlive its owner: race it against caller cancellation,
  623. // owner-fiber unload, and factory teardown so a never-settling backend
  624. // cannot pin the identity.
  625. const ownerAbort = new AbortController()
  626. const unfollowOwner = ownerCtx.effect(() => () => {
  627. ownerAbort.abort(new Error(`agent "${id}" setup aborted: owner disposed during setup`))
  628. }, `agentLoop.resume-load(${id})`)
  629. const fused = AbortSignal.any([
  630. ...options.signal === undefined ? [] : [options.signal],
  631. ownerAbort.signal,
  632. this.ownership.signal,
  633. ])
  634. let preparation: SessionPreparation | undefined
  635. try {
  636. try {
  637. preparation = await raceAbortCall(
  638. () => persistence.prepare(id, fused),
  639. fused,
  640. id,
  641. (abandoned) => { abandoned[Symbol.dispose]() },
  642. )
  643. } finally {
  644. await unfollowOwner()
  645. }
  646. ownerCtx.fiber.assertActive()
  647. if (!this.ownership.isActive()) throw new Error('agent loop is not active')
  648. return await this.setupAndPublish(
  649. ownerCtx,
  650. id,
  651. preparation,
  652. options.agentOptions ?? {},
  653. options.setup,
  654. options.signal,
  655. 'resume',
  656. )
  657. } finally {
  658. preparation?.[Symbol.dispose]()
  659. }
  660. })()
  661. this.ownership.trackWrapper(published)
  662. return published
  663. }
  664. }
  665. export default AgentLoop