index.ts 26 KB

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