index.ts 24 KB

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