index.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 { createScope } from '@deepseek-ai/dsh-scope'
  11. import type { Scope } from '@deepseek-ai/dsh-scope'
  12. import { agentEvents } from '@deepseek-ai/dsh-agent'
  13. import type {
  14. Agent,
  15. AgentFactory,
  16. AgentHandle,
  17. AgentOptions,
  18. CreateAgentOptions,
  19. ResumeAgentOptions,
  20. SessionStartSource,
  21. } from '@deepseek-ai/dsh-agent'
  22. import type {} from '@deepseek-ai/dsh-llm'
  23. import { SessionId } 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 {
  29. bindReactLoopAgentContext,
  30. prepareReactLoopAgent,
  31. ReactLoopAgent,
  32. } from './agent.ts'
  33. import type { PreparedReactLoopAgent } from './agent.ts'
  34. /** Fiber states that cannot own or serve a new lifecycle. */
  35. const INACTIVE_STATES: ReadonlySet<FiberState> = new Set([
  36. FiberState.UNLOADING,
  37. FiberState.DISPOSED,
  38. FiberState.FAILED,
  39. ])
  40. /** Render an arbitrary thrown value without letting coercion escape containment. */
  41. function renderThrown(value: unknown): string {
  42. try {
  43. return String(value)
  44. } catch {
  45. return '<unrenderable thrown value>'
  46. }
  47. }
  48. /** Factory-level ownership of every preparing or live transaction. */
  49. class FactoryOwnership {
  50. private accepting = true
  51. private readonly inactive = Promise.withResolvers<void>()
  52. private transactions = new Set<AgentCreationTransaction>()
  53. private startupTasks = new Set<Promise<void>>()
  54. constructor(private readonly fiber: Context['fiber']) {}
  55. isActive(): boolean {
  56. return this.accepting && !INACTIVE_STATES.has(this.fiber.state)
  57. }
  58. track(transaction: AgentCreationTransaction): () => void {
  59. this.transactions.add(transaction)
  60. return () => { this.transactions.delete(transaction) }
  61. }
  62. /** Join config startup work that begins before an agent transaction exists. */
  63. trackStartup(task: Promise<void>): void {
  64. this.startupTasks.add(task)
  65. const forget = () => { this.startupTasks.delete(task) }
  66. void task.then(forget, forget)
  67. }
  68. /** Resolve `task`, or stop waiting when factory teardown begins. */
  69. async waitWhileActive(task: Promise<void>): Promise<void> {
  70. await Promise.race([task, this.inactive.promise])
  71. }
  72. async dispose(): Promise<void> {
  73. this.accepting = false
  74. this.inactive.resolve()
  75. const reason = new Error('agent loop is not active')
  76. await Promise.all([
  77. ...[...this.transactions].map(transaction => transaction.disposeForFactory(reason)),
  78. ...this.startupTasks,
  79. ])
  80. }
  81. }
  82. /** Build the public cancellation error while preserving a caller-supplied cause. */
  83. function signalAbortError(id: SessionId, signal: AbortSignal): Error {
  84. if (signal.reason instanceof Error) return signal.reason
  85. return new Error(`agent "${id}" creation aborted`, { cause: signal.reason })
  86. }
  87. /**
  88. * Caller-owned create/resume transaction through rollback-covered publication
  89. * and quiescent teardown. Resources remain private until the final registry
  90. * entry arbitrates identity.
  91. */
  92. class AgentCreationTransaction {
  93. private active = true
  94. private failure: Error | undefined
  95. private readonly deactivation = Promise.withResolvers<void>()
  96. private readonly publication = Promise.withResolvers<void>()
  97. private readonly torndown = Promise.withResolvers<void>()
  98. private readonly wrapperCompletion = Promise.withResolvers<void>()
  99. private preparing: Promise<void> | undefined
  100. private driver: PreparedReactLoopAgent | undefined
  101. private scope: Scope | undefined
  102. private session: Session | undefined
  103. private lifecycleDispose: (() => Promise<void> | void) | undefined
  104. private detachSession: (() => void) | undefined
  105. private detachAgent: (() => void) | undefined
  106. private publishing = false
  107. private cleanupTask: Promise<void> | undefined
  108. private ownerFollowing = true
  109. private readonly ownerDispose: () => Promise<void> | void
  110. private readonly untrackFactory: () => void
  111. private readonly abortListener: (() => void) | undefined
  112. readonly ownerAgent: Context['agent']
  113. readonly ownerFiber: Context['fiber']
  114. constructor(
  115. private readonly loopCtx: Context,
  116. private readonly ownerCtx: Context,
  117. private readonly ownership: FactoryOwnership,
  118. readonly id: SessionId,
  119. signal?: AbortSignal,
  120. ) {
  121. ownerCtx.fiber.assertActive()
  122. this.ownerAgent = ownerCtx.agent
  123. this.ownerFiber = ownerCtx.fiber
  124. if (!ownership.isActive()) throw new Error('agent loop is not active')
  125. this.ownerDispose = ownerCtx.effect(() => () => {
  126. if (!this.ownerFollowing) return
  127. return this.dispose(new Error(`agent "${id}" setup aborted: owner disposed during setup`))
  128. }, `agentLoop.owner(${id})`)
  129. this.untrackFactory = ownership.track(this)
  130. if (signal === undefined) {
  131. this.abortListener = undefined
  132. } else {
  133. this.abortListener = () => {
  134. /* v8 ignore next 3 -- transaction teardown contains callback/driver failures; rejection is a future-drift backstop. */
  135. void this.dispose(signalAbortError(id, signal)).catch((error: unknown) => {
  136. this.loopCtx.logger.error(error)
  137. })
  138. }
  139. signal.addEventListener('abort', this.abortListener, { once: true })
  140. if (signal.aborted) this.deactivate(signalAbortError(id, signal))
  141. }
  142. this.signal = signal
  143. }
  144. private readonly signal: AbortSignal | undefined
  145. /** Whether caller, provider, and optional parent-agent ownership remain live. */
  146. isActive(): boolean {
  147. return this.active
  148. && this.ownership.isActive()
  149. && this.ownerFiber.uid !== null
  150. && !INACTIVE_STATES.has(this.ownerFiber.state)
  151. && this.ownerAgent?.status !== 'disposed'
  152. }
  153. /** Fail synchronously at every real lifecycle boundary after deactivation. */
  154. assertActive(): void {
  155. if (this.isActive()) return
  156. if (!this.ownership.isActive()) throw new Error('agent loop is not active')
  157. throw this.failure ?? new Error(`agent "${this.id}" setup aborted: owner disposed during setup`)
  158. }
  159. /** Race an external async operation against structural/signal deactivation. */
  160. async waitFor<T>(operation: PromiseLike<T> | T): Promise<T> {
  161. this.assertActive()
  162. return await Promise.race([
  163. Promise.resolve(operation),
  164. this.deactivation.promise.then(() => {
  165. /* v8 ignore next -- deactivate() assigns failure before resolving deactivation. */
  166. throw this.failure ?? new Error(`agent "${this.id}" creation deactivated`)
  167. }),
  168. ])
  169. }
  170. /** Construct the driver and scope, then install their complete ordered lifecycle. */
  171. prepare(options: AgentOptions, session: Session): ReactLoopAgent {
  172. this.assertActive()
  173. const gate = Promise.withResolvers<void>()
  174. this.preparing = gate.promise
  175. try {
  176. this.session = session
  177. const driver = prepareReactLoopAgent(this.loopCtx, this.id, options, session)
  178. this.driver = driver
  179. const agent = driver.agent
  180. const scope = createScope(this.loopCtx, agent)
  181. this.scope = scope
  182. bindReactLoopAgentContext(agent, scope.ctx.extend({ agent }))
  183. this.installLifecycle(scope, driver)
  184. this.assertActive()
  185. return agent
  186. } catch (error: unknown) {
  187. if (!this.isActive() && error instanceof Error && /inactive context/.test(error.message)) {
  188. throw this.failure ?? this.disposalReason()
  189. }
  190. throw error
  191. } finally {
  192. gate.resolve()
  193. this.preparing = undefined
  194. }
  195. }
  196. /** Register the exact scope disposer inside the ordered transaction effect. */
  197. private installLifecycle(scope: Scope, driver: PreparedReactLoopAgent): void {
  198. this.lifecycleDispose = this.ownerCtx.effect(function* (this: AgentCreationTransaction) {
  199. // First yielded, disposed last.
  200. yield () => { this.finish() }
  201. yield scope.rawDispose
  202. yield () => {
  203. this.detachSession?.()
  204. this.detachSession = undefined
  205. }
  206. yield () => {
  207. this.detachAgent?.()
  208. this.detachAgent = undefined
  209. }
  210. // Last yielded, disposed first.
  211. yield () => {
  212. this.deactivate(this.disposalReason())
  213. if (this.publishing) {
  214. return this.publication.promise.then(() => driver.dispose())
  215. }
  216. return driver.dispose()
  217. }
  218. }.bind(this), `agentLoop.lifecycle(${this.id})`)
  219. }
  220. /** Publish the exact prepared objects and start the driver. */
  221. publish(source: SessionStartSource): AgentHandle {
  222. this.assertActive()
  223. const driver = this.driver
  224. /* v8 ignore next -- publish() is private and every caller invokes prepare() first. */
  225. if (driver === undefined) throw new Error(`agent "${this.id}" is not prepared`)
  226. const agent = driver.agent
  227. const session = this.session
  228. /* v8 ignore next -- prepare() assigns the session before it can produce the driver above. */
  229. if (session === undefined) throw new Error(`agent "${this.id}" has no prepared session`)
  230. this.publishing = true
  231. try {
  232. this.detachSession = agent.ctx.sessions.enter(session)
  233. this.detachAgent = this.loopCtx.agents.enter(agent, this.ownerAgent)
  234. agent.ctx.sessions.announce(session)
  235. this.assertActive()
  236. this.loopCtx.agents.announce(agent)
  237. this.assertActive()
  238. driver.markPublished()
  239. agentEvents(this.loopCtx, agent).emit('agent/session-start', source)
  240. this.assertActive()
  241. driver.startDriver()
  242. return { agent, dispose: () => this.dispose() }
  243. } finally {
  244. this.publishing = false
  245. this.publication.resolve()
  246. }
  247. }
  248. /** Mark the transaction inactive exactly once and wake load/setup races. */
  249. private deactivate(reason: Error): void {
  250. if (!this.active) return
  251. this.active = false
  252. this.failure = reason
  253. this.deactivation.resolve()
  254. }
  255. /** Choose the structural cause when an owner/factory effect starts teardown first. */
  256. private disposalReason(): Error {
  257. if (this.failure !== undefined) return this.failure
  258. if (!this.ownership.isActive()) return new Error('agent loop is not active')
  259. if (this.ownerFiber.uid === null || INACTIVE_STATES.has(this.ownerFiber.state) || this.ownerAgent?.status === 'disposed') {
  260. return new Error(`agent "${this.id}" setup aborted: owner disposed during setup`)
  261. }
  262. return new Error(`agent "${this.id}" lifecycle disposed`)
  263. }
  264. /** Complete ownership bookkeeping after every resource reached quiescence. */
  265. private finish(): void {
  266. this.untrackFactory()
  267. this.ownerFollowing = false
  268. void this.ownerDispose()
  269. this.torndown.resolve()
  270. }
  271. /**
  272. * Deactivate and quiesce this transaction. The promise is memoized because
  273. * Cordis effect disposers are single-shot while handles promise shared
  274. * quiescence to every racing owner.
  275. */
  276. dispose(reason = new Error(`agent "${this.id}" lifecycle disposed`)): Promise<void> {
  277. this.deactivate(reason)
  278. return (this.cleanupTask ??= (async () => {
  279. if (this.preparing !== undefined) await this.preparing
  280. if (this.lifecycleDispose !== undefined) {
  281. await this.lifecycleDispose()
  282. await this.torndown.promise
  283. return
  284. }
  285. try {
  286. await this.driver?.dispose()
  287. } finally {
  288. try {
  289. await this.scope?.dispose()
  290. } finally {
  291. this.finish()
  292. }
  293. }
  294. })())
  295. }
  296. /** Mark the public create/resume continuation settled and detach its creation-only signal. */
  297. finishWrapper(): void {
  298. if (this.signal !== undefined && this.abortListener !== undefined) {
  299. this.signal.removeEventListener('abort', this.abortListener)
  300. }
  301. this.wrapperCompletion.resolve()
  302. }
  303. /** Factory shutdown joins both resource teardown and the public wrapper's deactivation continuation. */
  304. async disposeForFactory(reason: Error): Promise<void> {
  305. await this.dispose(reason)
  306. await this.wrapperCompletion.promise
  307. }
  308. }
  309. declare module 'cordis' {
  310. interface Context {
  311. agentLoop: AgentLoop
  312. }
  313. interface Events {
  314. /**
  315. * A declarative agent entry failed before it could publish a live agent.
  316. * Consumers that buffer work for the configured identity use this
  317. * transient signal to reject that work instead of waiting forever. Normal
  318. * factory teardown suppresses failures from the cancelled startup attempt.
  319. * @param sessionId - exact shared agent/session identity that failed startup.
  320. * @param error - persistence, setup, or publication failure.
  321. * @mode emit
  322. */
  323. 'agent-loop/config-start-failed'(sessionId: SessionId, error: unknown): void
  324. }
  325. }
  326. /** Plugin configuration for declarative startup agents. */
  327. export interface Config {
  328. /** Agents created or resumed at plugin startup. */
  329. agents: (AgentOptions & {
  330. /** Stable config label used in logs and as the fresh combined-id prefix. */
  331. id: string
  332. /** Optional stable identity; remounts resume its materialized history, while first use creates it fresh. */
  333. sessionId?: SessionId
  334. /** Optional workspace for a fresh session. */
  335. cwd?: string
  336. /** Persisted session to resume instead of creating a fresh session. */
  337. resumeSessionId?: SessionId
  338. })[]
  339. }
  340. /** Concrete agent factory and driver service. */
  341. export class AgentLoop extends Service implements AgentFactory {
  342. static inject = ['agents', 'sessions', 'llm', 'tools', 'systemPrompt']
  343. /** Runtime schema for declarative agents. */
  344. static Config = z.object({
  345. agents: z.array(z.object({
  346. id: z.string().required(),
  347. sessionId: z.string().min(1),
  348. model: z.string(),
  349. cwd: z.string(),
  350. resumeSessionId: z.string(),
  351. })).default([]),
  352. }) as unknown as z<Config>
  353. private readonly ownership: FactoryOwnership
  354. /** Plain holder prevents Cordis from re-tracing the factory's dependency context through a caller shadow. */
  355. private readonly runtime: { ctx: Context }
  356. constructor(ctx: Context, public config: Config) {
  357. super(ctx, 'agentLoop')
  358. this.ownership = new FactoryOwnership(ctx.fiber)
  359. this.runtime = { ctx }
  360. ctx.effect(() => () => this.ownership.dispose(), 'agentLoop.transactions()')
  361. ctx.effect(() => ctx.agents.setFactory(this), 'agentLoop.setFactory()')
  362. ctx.systemPrompt.variable('model', context => context.agent?.options.model)
  363. ctx.systemPrompt.variable('cwd', context => context.agent?.session.header.cwd)
  364. for (const { id, sessionId, cwd, resumeSessionId, ...options } of config.agents) {
  365. const meta = cwd === undefined ? {} : { cwd }
  366. if (resumeSessionId === undefined || resumeSessionId === '') {
  367. const configuredId = sessionId ?? SessionId(`${id}-session-${randomUUID()}`)
  368. const persistence = sessionId === undefined ? undefined : ctx.get('sessionPersistence')
  369. if (persistence === undefined) {
  370. this.create(configuredId, options, meta)
  371. } else {
  372. const startup = this.restoreOrCreateConfigured(ctx, persistence, configuredId, options, meta).catch((error: unknown) => {
  373. this.reportConfiguredStartupFailure(id, 'restore', configuredId, error)
  374. })
  375. this.ownership.trackStartup(startup)
  376. }
  377. continue
  378. }
  379. if (sessionId !== undefined) {
  380. throw new Error(`agent "${id}": sessionId and resumeSessionId are mutually exclusive`)
  381. }
  382. ctx.effect(() => {
  383. const fiber = ctx.inject(['sessionPersistence'], (childCtx: Context) => {
  384. void this.resumeWith(ctx, childCtx.sessionPersistence, {
  385. resumeSessionId,
  386. agentOptions: options,
  387. }).catch((error: unknown) => {
  388. this.reportConfiguredStartupFailure(id, 'resume', resumeSessionId, error)
  389. })
  390. })
  391. return fiber.dispose
  392. }, `agentLoop.resume(${id})`)
  393. }
  394. }
  395. /** Report a contained declarative-start failure to identity-bound consumers. */
  396. private reportConfiguredStartupFailure(
  397. configId: string,
  398. action: 'restore' | 'resume',
  399. sessionId: SessionId,
  400. error: unknown,
  401. ): void {
  402. if (!this.ownership.isActive()) return
  403. this.ctx.logger.warn(`agent "${configId}": config-driven ${action} of "${sessionId}" failed: ${renderThrown(error)}`)
  404. const args: unknown[] = ['agent-loop/config-start-failed', sessionId, error]
  405. for (const callback of this.ctx.events.dispatch('emit', args)) {
  406. try {
  407. const returned: unknown = callback(...args)
  408. void Promise.resolve(returned).catch((listenerError: unknown) => {
  409. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener rejected: ${renderThrown(listenerError)}`)
  410. })
  411. } catch (listenerError: unknown) {
  412. this.ctx.logger.warn(`agent "${configId}": config-start-failed listener threw: ${renderThrown(listenerError)}`)
  413. }
  414. }
  415. }
  416. /** Restore a materialized exact config identity on remount, or create it on first use. */
  417. private async restoreOrCreateConfigured(
  418. ownerCtx: Context,
  419. persistence: SessionPersistence,
  420. sessionId: SessionId,
  421. agentOptions: AgentOptions,
  422. meta: Pick<SessionHeader, 'cwd'>,
  423. ): Promise<void> {
  424. await this.waitForDrainingConfiguredIdentity(ownerCtx, sessionId)
  425. if (!this.ownership.isActive()) return
  426. const exists = (await persistence.list()).some(header => header.id === sessionId)
  427. if (!this.ownership.isActive()) return
  428. if (exists) {
  429. await this.resumeWith(ownerCtx, persistence, { resumeSessionId: sessionId, agentOptions })
  430. return
  431. }
  432. this.create(sessionId, agentOptions, meta)
  433. }
  434. /** Wait for an already-disposed same-id lifecycle to finish registry teardown. */
  435. private async waitForDrainingConfiguredIdentity(ownerCtx: Context, sessionId: SessionId): Promise<void> {
  436. const current = ownerCtx.agents.get(sessionId)
  437. if (current?.status !== 'disposed') return
  438. const released = Promise.withResolvers<void>()
  439. const checkReleased = (): void => {
  440. if (ownerCtx.agents.get(sessionId) === undefined && ownerCtx.sessions.get(sessionId) === undefined) {
  441. released.resolve()
  442. }
  443. }
  444. const disposeAgentListener = ownerCtx.on('agent/disposed', checkReleased)
  445. const disposeSessionListener = ownerCtx.on('session/disposed', checkReleased)
  446. try {
  447. checkReleased()
  448. await this.ownership.waitWhileActive(released.promise)
  449. } finally {
  450. disposeAgentListener()
  451. disposeSessionListener()
  452. }
  453. }
  454. /**
  455. * Create an agent and session under one caller-supplied identity, owned by
  456. * the accessing fiber. Constructor-driven config calls mint a fresh combined
  457. * id before entering this boundary.
  458. * @param id - shared agent/session identity.
  459. * @param options - concrete loop options.
  460. * @param meta - optional fresh-session workspace metadata.
  461. * @returns the published running agent.
  462. */
  463. create(id: SessionId, options: AgentOptions = {}, meta: Pick<SessionHeader, 'cwd'> = {}): Agent {
  464. const loopCtx = this.runtime.ctx
  465. const transaction = new AgentCreationTransaction(loopCtx, this.ctx, this.ownership, id)
  466. try {
  467. const session = loopCtx.sessions.prepare(id, { meta })
  468. const agent = transaction.prepare(options, session)
  469. transaction.publish('startup')
  470. return agent
  471. } catch (error: unknown) {
  472. void transaction.dispose(error instanceof Error ? error : new Error(String(error)))
  473. throw error
  474. } finally {
  475. transaction.finishWrapper()
  476. }
  477. }
  478. /**
  479. * Create an owned agent on a caller-supplied session id.
  480. * @param ownerCtx - caller context that structurally owns the transaction.
  481. * @param options - identities, session seed/metadata, loop options, setup, and cancellation.
  482. * @returns the published handle.
  483. */
  484. async createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> {
  485. const transaction = new AgentCreationTransaction(
  486. this.runtime.ctx,
  487. ownerCtx,
  488. this.ownership,
  489. options.sessionId,
  490. options.signal,
  491. )
  492. try {
  493. const session = this.runtime.ctx.sessions.prepare(options.sessionId, {
  494. ...options.seed === undefined ? {} : { seed: options.seed },
  495. ...options.meta === undefined ? {} : { meta: options.meta },
  496. })
  497. const agent = transaction.prepare(options.agentOptions ?? {}, session)
  498. await transaction.waitFor(options.setup?.(agent.ctx))
  499. transaction.assertActive()
  500. return transaction.publish('startup')
  501. } catch (error: unknown) {
  502. await transaction.dispose(error instanceof Error ? error : new Error(String(error)))
  503. throw error
  504. } finally {
  505. transaction.finishWrapper()
  506. }
  507. }
  508. /**
  509. * Resume an owned agent from the configured persistence service.
  510. * @param ownerCtx - caller context that owns load, setup, and the live lifecycle.
  511. * @param options - persisted identity, loop options, setup, and cancellation.
  512. * @returns the published handle.
  513. */
  514. async resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle> {
  515. const persistence = this.runtime.ctx.get('sessionPersistence')
  516. if (persistence === undefined) {
  517. throw new Error('cannot resume: session persistence is not configured (load a dsh-session-persistence backend)')
  518. }
  519. return this.resumeWith(ownerCtx, persistence, options)
  520. }
  521. /** Resume through an explicit persistence handle used by the deferred config path. */
  522. private async resumeWith(
  523. ownerCtx: Context,
  524. persistence: SessionPersistence,
  525. options: ResumeAgentOptions,
  526. ): Promise<AgentHandle> {
  527. const transaction = new AgentCreationTransaction(
  528. this.runtime.ctx,
  529. ownerCtx,
  530. this.ownership,
  531. options.resumeSessionId,
  532. options.signal,
  533. )
  534. try {
  535. const loaded = await transaction.waitFor(persistence.load(options.resumeSessionId))
  536. transaction.assertActive()
  537. const session = this.runtime.ctx.sessions.prepare(options.resumeSessionId, {
  538. seed: loaded.events,
  539. meta: {
  540. createdAt: loaded.meta.createdAt,
  541. ...loaded.meta.cwd === undefined ? {} : { cwd: loaded.meta.cwd },
  542. ...loaded.meta.parentSession === undefined ? {} : { parentSession: loaded.meta.parentSession },
  543. ...loaded.meta.seedLength === undefined ? {} : { seedLength: loaded.meta.seedLength },
  544. },
  545. })
  546. const agent = transaction.prepare(options.agentOptions ?? {}, session)
  547. await transaction.waitFor(options.setup?.(agent.ctx))
  548. transaction.assertActive()
  549. return transaction.publish('resume')
  550. } catch (error: unknown) {
  551. await transaction.dispose(error instanceof Error ? error : new Error(String(error)))
  552. throw error
  553. } finally {
  554. transaction.finishWrapper()
  555. }
  556. }
  557. }
  558. export default AgentLoop