index.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /**
  2. * Agent service: live registry, factory delegation, and process-local
  3. * initiator scope. Concrete creation and driving belong to the loop.
  4. *
  5. * @module @deepseek-ai/dsh-agent
  6. */
  7. import { Context, FiberState, getTraceable, Service, symbols } from 'cordis'
  8. import type { Fiber } from 'cordis'
  9. import { AsyncLocalStorage } from 'node:async_hooks'
  10. import { isPromise } from 'node:util/types'
  11. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  12. import type { Scoped } from '@deepseek-ai/dsh-scope'
  13. import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  14. import type { Agent, AgentOptions } from './types.ts'
  15. export * from './types.ts'
  16. export * from './llm-target.ts'
  17. export { agentCarrier, agentEvents, assembleContextFor, emitAgentEvent } from './dispatch.ts'
  18. export type { AgentEventDispatch, AgentSubjectEvent } from './dispatch.ts'
  19. declare module 'cordis' {
  20. interface Context {
  21. agents: AgentRegistry
  22. /**
  23. * The agent association installed as an own property on `Agent.ctx`, or
  24. * `undefined` on a plain context. Contexts derived from `Agent.ctx` inherit
  25. * the association; a deliberately nested scope may carry a nearer
  26. * `dsh-scope` tag while retaining it, so this field is DX context rather
  27. * than the scope resolver. {@link AgentRegistry} registers a root accessor
  28. * defaulting to `undefined`, and core packages below the agent layer use
  29. * `scopeOf()` for layer selection instead of reading this field.
  30. */
  31. agent?: Agent
  32. }
  33. }
  34. /**
  35. * Options for programmatically creating an agent through the registry factory
  36. * ({@link AgentRegistry.create}). The caller supplies the single live
  37. * `sessionId` shared by the agent registry and session log (e.g. an
  38. * ACP-generated id), plus optional session metadata (the validated `cwd`, fork
  39. * lineage); the factory creates the session and agent under that identity.
  40. */
  41. export interface CreateAgentOptions {
  42. /** The live agent/session identity. */
  43. readonly sessionId: SessionId
  44. /**
  45. * Session creation metadata: validated absolute `cwd`, `parentSession`
  46. * fork lineage, the `seedLength` seed boundary, and the `delegationDepth`
  47. * recursion budget. Mirrors the
  48. * `cwd`/`parentSession`/`seedLength`/`delegationDepth` fields of
  49. * {@link CreateSessionOptions.meta} in dsh-session (the internal-only
  50. * `createdAt`, used when reconstructing a persisted session, is deliberately
  51. * excluded — a factory caller never sets it). This is durable session data,
  52. * so the session boundary validates and snapshots it before asynchronous
  53. * setup begins.
  54. */
  55. readonly meta?: {
  56. readonly cwd?: string
  57. readonly parentSession?: SessionId
  58. readonly seedLength?: number
  59. readonly delegationDepth?: number
  60. }
  61. /**
  62. * Initial replay/fork history. A fork supplies a balanced completed-turn
  63. * prefix of the parent's log. The complete seed must be contiguous from seq
  64. * 0, carry only lossless-JSON data, and contain no open turn/step or dangling
  65. * tool call. The factory passes it to the session's durable
  66. * validator/snapshot boundary before publication.
  67. */
  68. readonly seed?: readonly SessionEvent[]
  69. /** Per-agent options (model, …). */
  70. readonly agentOptions?: AgentOptions
  71. /** Optional creation-only cancellation signal; detached before the returned handle becomes visible. */
  72. readonly signal?: AbortSignal
  73. /**
  74. * Creation-time composition of the agent's scoped world. The factory awaits
  75. * setup after minting `agentCtx` but BEFORE inserting or announcing either
  76. * the session or agent, so observers can never see a partially configured
  77. * world. Everything registered through `agentCtx` (scoped tools, prompt
  78. * sections/variables, `restrict()`, listeners, awaited child plugins) exists
  79. * before `session/created`, `agent/created`, `agent/session-start`, and the
  80. * first prompt assembly. A throw/rejection or owner disposal rolls the scope
  81. * back without publishing either id.
  82. *
  83. * **Setup composes, it never drives**: the callback is trusted same-process
  84. * code and receives the full scoped context, so this is a contract rather
  85. * than a runtime restriction. Drive the agent only after creation resolves.
  86. */
  87. readonly setup?: (agentCtx: Context) => Promise<void> | void
  88. }
  89. /**
  90. * Options for resuming an agent on a persisted session
  91. * ({@link AgentRegistry.resume}).
  92. */
  93. export interface ResumeAgentOptions {
  94. /** The persisted session id to load and use as the live agent/session identity. */
  95. readonly resumeSessionId: SessionId
  96. /** Per-agent options (model, …). */
  97. readonly agentOptions?: AgentOptions
  98. /** Optional creation-only cancellation signal for persistence load/setup; detached before return. */
  99. readonly signal?: AbortSignal
  100. /**
  101. * Resume-time composition of the agent's fresh scoped world. Persistence is
  102. * loaded first; the factory then mints `agentCtx` and awaits setup while the
  103. * reconstructed session and agent remain unpublished. The callback has the
  104. * same trusted composition-only contract as
  105. * {@link CreateAgentOptions.setup}: all registrations exist before either
  106. * creation announcement, and rejection or owner disposal rolls the
  107. * transaction back without publishing either id.
  108. */
  109. readonly setup?: (agentCtx: Context) => Promise<void> | void
  110. }
  111. /**
  112. * An owned agent plus its disposer, returned by {@link AgentRegistry.create} /
  113. * {@link AgentRegistry.resume}. The disposer is a CAPABILITY: among consumers,
  114. * only the holder can tear this agent down. The registered factory provider is
  115. * also a structural owner because the scoped agent depends on that provider's
  116. * service surface; provider unload stops and drains every live handle it made.
  117. * `dispose()` stops the loop, awaits its exit, unregisters the agent, removes
  118. * its session from the store, and finally unwinds its scoped world.
  119. *
  120. * `ctx.agents.get(id)` still returns a bare {@link Agent} — the handle is
  121. * exposed only to the consumer owner that created it; the structural provider
  122. * reaches the same teardown internally. Config-created agents (the loop's own
  123. * startup) are owned by the loop fiber and never need a handle.
  124. */
  125. export interface AgentHandle {
  126. agent: Agent
  127. dispose(): Promise<void>
  128. }
  129. /**
  130. * The agent-creation factory the loop implementation provides to the registry
  131. * via {@link AgentRegistry.setFactory}. Kept on the `dsh-agent` interface so
  132. * consumers (e.g. the ACP bridge) program against `ctx.agents` without
  133. * depending on the concrete `dsh-agent-loop` package.
  134. */
  135. export interface AgentFactory {
  136. /**
  137. * Create a new agent on a caller-supplied session id. Async because creation
  138. * awaits unpublished setup, inserts both session and agent, emits their
  139. * creation notifications in order, emits `agent/session-start`, and only
  140. * then starts the loop. The sequence is
  141. * rollback-covered, but notifications delivered before a later listener
  142. * failure remain observable; every agent or session creation announcement
  143. * that began is paired by `agent/disposed` or `session/disposed` during
  144. * rollback. The owner disposes the resolved handle to stop/drain,
  145. * unregister, remove the session, and unwind the scope.
  146. * The registry passes a context carrying the `create()` caller's fiber and
  147. * scope as `ownerCtx`. The implementation attaches the unpublished
  148. * transaction and resulting lifecycle to that owner; it must not infer
  149. * ownership from the factory object's registration context.
  150. * @param ownerCtx - caller-bound context that owns the transaction and live handle.
  151. * @param options - agent/session identity, configuration, and optional setup.
  152. * @returns the owned handle after setup, both announcements, and loop start complete.
  153. */
  154. createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle>
  155. /**
  156. * Load a persisted session and resume an agent on it. Async because it awaits
  157. * both `ctx.sessionPersistence.load` and the optional unpublished setup
  158. * transaction; must be called after that service exists (consumers inject
  159. * `sessionPersistence`). Publication follows the same ordered boundary as
  160. * {@link createAgent}.
  161. * @param ownerCtx - caller-bound context that owns load, setup, and the live handle.
  162. * @param options - persisted identity, configuration, and optional setup.
  163. * @returns the owned handle after setup, both announcements, and loop start complete.
  164. */
  165. resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle>
  166. }
  167. /** Thrown when create/resume is called before an agent factory is registered. */
  168. const NO_FACTORY_MESSAGE = 'no agent factory registered (load an agent-loop plugin)'
  169. const NO_INITIATOR_MESSAGE = 'no initiating agent is active'
  170. const DISPOSED_INITIATOR_MESSAGE = 'agent initiator scope is disposed'
  171. /** All mutable lifecycle state for one exact registry entry. */
  172. interface AgentEntry {
  173. readonly id: SessionId
  174. readonly agent: Agent
  175. /** Runtime creator-agent ownership; independent of durable session lineage. */
  176. readonly owner: Agent | undefined
  177. readonly carrier: Scoped<Agent>
  178. announced: boolean
  179. announcing: boolean
  180. detachRequested: boolean
  181. }
  182. /** One tracked boundary plus its inherited nesting chain. */
  183. interface InitiatorRun {
  184. active: boolean
  185. readonly parent: InitiatorRun | undefined
  186. }
  187. /** Plain holder prevents Cordis from tracing the factory field before the caller context is known. */
  188. interface FactorySlot {
  189. readonly target: AgentFactory
  190. }
  191. /**
  192. * Agent service (`ctx.agents`): tracks live agents and carries the initiating
  193. * Agent through one process-local asynchronous driver chain. Agent *creation*
  194. * is provided by whichever plugin implements the {@link AgentFactory}
  195. * (`@deepseek-ai/dsh-agent-loop`), registered via {@link setFactory}.
  196. *
  197. * Initiator methods provide same-process causal attribution only. Ambient
  198. * presence is neither liveness proof nor authorization; subjects and owners
  199. * remain explicit, as does identity at worker, process, persistence, and wire
  200. * boundaries. Returned Promise boundaries drain during teardown, except a
  201. * nested lineage that starts an owning-fiber unload is excluded from its own drain.
  202. */
  203. export class AgentRegistry extends Service {
  204. private store = new Map<SessionId, AgentEntry>()
  205. private factory: FactorySlot | undefined
  206. private readonly initiators = new AsyncLocalStorage<Agent | undefined>()
  207. private readonly initiatorRuns = new AsyncLocalStorage<InitiatorRun>()
  208. private initiatorState: 'active' | 'closing' | 'disposed' = 'active'
  209. private activeInitiatorRuns = 0
  210. private initiatorDrain: PromiseWithResolvers<void> | undefined
  211. private initiatorDisposal: Promise<void> | undefined
  212. constructor(ctx: Context) {
  213. super(ctx, 'agents')
  214. // The `ctx.agent` DX accessor: default `undefined` on every context, so a
  215. // plain plugin context reads cleanly instead of hitting the Cordis
  216. // unknown-property throw. Each Agent.ctx shadows it with an own property
  217. // (own properties resolve before the context proxy is consulted), so the
  218. // accessor body never needs to resolve a scope itself. Effect-scoped:
  219. // unwinds with this service's fiber.
  220. ctx.accessor('agent', { get: () => undefined })
  221. ctx.on('internal/status', (fiber) => {
  222. if (fiber.state === FiberState.UNLOADING && this.hasLifecycleAncestor(fiber)) {
  223. this.closeInitiators()
  224. }
  225. })
  226. ctx.effect(function* (this: AgentRegistry) {
  227. yield () => this.disposeInitiators()
  228. yield () => { this.closeInitiators() }
  229. }.bind(this), 'agents.initiatorLifecycle()')
  230. }
  231. /**
  232. * Read the Agent that initiated the inherited asynchronous driver chain.
  233. * Use this optional form for logging, tracing, metrics, or host attribution
  234. * that also supports agentless calls. When a parent creates a child, setup
  235. * reports the causal parent while `agentCtx.agent` identifies the child.
  236. * @returns the inherited Agent, or `undefined` outside an initiator boundary
  237. * and inside an explicit clearing boundary.
  238. * @throws when this service instance has been disposed.
  239. */
  240. currentInitiator(): Agent | undefined {
  241. this.assertInitiatorsReadable()
  242. return this.initiators.getStore()
  243. }
  244. /**
  245. * Read the initiating Agent and fail when no initiator boundary is active.
  246. * Use this for private helpers contractually below a driver, or for a
  247. * deployment-owned outbound request whose contract forbids agentless calls.
  248. * Generic or direct-call seams use optional lookup or explicit request fields.
  249. * @returns the inherited Agent.
  250. * @throws when no initiator is active or this service instance has been disposed.
  251. */
  252. requireInitiator(): Agent {
  253. const agent = this.currentInitiator()
  254. if (agent === undefined) throw new Error(NO_INITIATOR_MESSAGE)
  255. return agent
  256. }
  257. /**
  258. * Run an operation with one exact Agent as its process-local initiator. The
  259. * exact synchronous value or Promise returned by the operation is preserved.
  260. * Custom drivers and test harnesses wrap their complete returned foreground
  261. * lifetime.
  262. * A queue or wire receiver may establish this boundary only after validating
  263. * explicit identity and resolving the exact live Agent; this method does neither.
  264. * Detached work remains owned by the subsystem that starts it.
  265. * @param agent - initiating Agent to inherit; presence is neither liveness proof nor authorization.
  266. * @param operation - synchronous or asynchronous operation to invoke.
  267. * @returns the exact value returned by `operation`.
  268. * @throws when the initiator scope is closing/disposed, or when `operation` throws.
  269. */
  270. withInitiator<T>(agent: Agent, operation: () => T): T {
  271. return this.runWithInitiator(agent, operation)
  272. }
  273. /**
  274. * Run an operation inside a boundary that hides any inherited initiating
  275. * Agent. The exact synchronous value or Promise is preserved.
  276. * Use this while creating lazy shared timers, queue pumps, pool maintenance,
  277. * watchers, or exporters so they do not inherit the first Agent that happens
  278. * to initialize them. It clears only initiator attribution, not explicit
  279. * fields, and does not own or drain detached resources.
  280. * @param operation - synchronous or asynchronous operation to invoke without an initiator.
  281. * @returns the exact value returned by `operation`.
  282. * @throws when the initiator scope is closing/disposed, or when `operation` throws.
  283. */
  284. withoutInitiator<T>(operation: () => T): T {
  285. return this.runWithInitiator(undefined, operation)
  286. }
  287. /**
  288. * Register the agent-creation factory (the loop calls this on construction,
  289. * effect-scoped). A traced Cordis service is canonicalized to its concrete
  290. * target; each create/resume call is then traced through that caller's
  291. * context so ownership follows the caller without stacking proxy layers.
  292. * Throws if a factory is already registered. Returns the disposer; on
  293. * dispose the factory slot is cleared.
  294. * @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
  295. * @returns the disposer that clears the factory slot. The exact
  296. * Cordis effect disposer (single-shot): composite (generator) effects may
  297. * yield it directly — exact identity nests the teardown in order.
  298. */
  299. setFactory(factory: AgentFactory): () => void {
  300. const dispose = this.ctx.effect(() => {
  301. if (this.factory !== undefined) throw new Error('an agent factory is already registered')
  302. // Avoid stacking two Cordis shadow layers when a caller passes a Service
  303. // already read through a context. Calls are re-traced through their
  304. // actual owner context below.
  305. const target = (factory as AgentFactory & { [symbols.original]?: AgentFactory })[symbols.original] ?? factory
  306. this.factory = { target }
  307. return () => { this.factory = undefined }
  308. }, 'agents.setFactory()')
  309. // The exact cordis effect disposer (the agents.register() convention): a
  310. // caller's composite effect can yield it for in-order teardown; the
  311. // loop's constructor effect returns it directly, identity-nesting the
  312. // registration under that effect.
  313. // eslint-disable-next-line @typescript-eslint/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
  314. return dispose
  315. }
  316. /** Return the active creation factory. */
  317. private requireFactory(): FactorySlot {
  318. if (this.factory === undefined) throw new Error(NO_FACTORY_MESSAGE)
  319. return this.factory
  320. }
  321. /**
  322. * Create and publish a new agent through the registered factory.
  323. * Distinct from {@link register} (which records an already-constructed
  324. * agent): this constructs the agent and its session. Rejects if no factory is
  325. * registered or creation/setup fails. The resolved {@link AgentHandle} lets
  326. * the owner tear down exactly this agent.
  327. * @param options - shared identity, session seed/metadata, and agent options.
  328. * @returns the handle after setup, rollback-covered publication, and loop start complete.
  329. */
  330. async create(options: CreateAgentOptions): Promise<AgentHandle> {
  331. const ownerCtx = this.ctx
  332. // Re-trace a Service-backed factory through the accessing context
  333. // explicitly. This preserves AgentLoop's dependency origin while binding
  334. // its effects to ownerCtx; plain factories receive ownerCtx as an explicit
  335. // capability and need no Cordis tracker magic.
  336. const { target } = this.requireFactory()
  337. const receiver = getTraceable(ownerCtx, target)
  338. // eslint-disable-next-line @typescript-eslint/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
  339. return Reflect.apply(target.createAgent, receiver, [ownerCtx, options])
  340. }
  341. /**
  342. * Load a persisted session and resume an agent on it through the registered
  343. * factory. Rejects if no factory is registered; the factory rejects if
  344. * session persistence is not configured or persistence/setup fails.
  345. * @param options - persisted identity, configuration, and optional setup.
  346. * @returns the handle after setup, rollback-covered publication, and loop start complete.
  347. */
  348. async resume(options: ResumeAgentOptions): Promise<AgentHandle> {
  349. const ownerCtx = this.ctx
  350. const { target } = this.requireFactory()
  351. const receiver = getTraceable(ownerCtx, target)
  352. // eslint-disable-next-line @typescript-eslint/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
  353. return Reflect.apply(target.resume, receiver, [ownerCtx, options])
  354. }
  355. /**
  356. * Register a live agent. Throws if an agent with the same id is already
  357. * registered. Emits `agent/created` on registration and `agent/disposed`
  358. * when the calling fiber is disposed — both with the agent's scope carrier
  359. * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the
  360. * emits are scope-filtered regardless of which context invoked `register`
  361. * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always
  362. * requires passing the carrier). Returns the disposer.
  363. * @param agent - the already-constructed agent to record in the store.
  364. * @returns the EXACT Cordis effect disposer (single-shot; a repeat call
  365. * returns undefined without awaiting an in-flight teardown). Exact
  366. * identity is load-bearing: a composite (generator) effect that owns a
  367. * teardown ORDER — the agent factory's lifecycle chain — must yield THIS
  368. * function so Cordis nests the unregistration at that yield position;
  369. * yielding a wrapper would leave it disposing as a concurrent sibling on
  370. * owner unload, unregistering the agent (and emitting `agent/disposed`)
  371. * while its final turn is still draining.
  372. */
  373. register(agent: Agent): () => void {
  374. const dispose = this.ctx.effect(function* (this: AgentRegistry) {
  375. yield this.enter(agent, this.ctx.agent)
  376. this.announce(agent)
  377. }.bind(this), 'agents.register()')
  378. // eslint-disable-next-line @typescript-eslint/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
  379. return dispose
  380. }
  381. /**
  382. * Insert an already-constructed agent without announcing it. This is the
  383. * advanced ordered-lifecycle primitive used by the async agent factory: it
  384. * first completes setup while the agent is unpublished, then assigns the
  385. * returned detach closure into its pre-installed composite teardown before
  386. * calling {@link announce}. Ordinary callers use {@link register}.
  387. * @param agent - the prepared, unpublished agent.
  388. * @param owner - live agent whose scoped context created this agent, or
  389. * undefined for a top-level runtime root. This is runtime ownership, not
  390. * the resumed session's durable parent lineage.
  391. * @returns an idempotent closure that removes this exact entry and emits
  392. * `agent/disposed` with listener failures contained. When called from a
  393. * synchronous `agent/created` listener, removal and disposal wait until
  394. * that creation dispatch unwinds.
  395. */
  396. enter(agent: Agent, owner: Agent | undefined): () => void {
  397. const id = agent.id
  398. if (id !== agent.session.id) {
  399. throw new Error(`agent id "${id}" does not match session id "${agent.session.id}"`)
  400. }
  401. const carrier = scopeTarget(agent, agent)
  402. // This is the authoritative collision boundary. Concurrent create/resume
  403. // operations may both prepare, but only one exact entry can publish.
  404. if (this.store.has(id)) throw new Error(`agent "${id}" is already registered`)
  405. const entry: AgentEntry = {
  406. id,
  407. agent,
  408. owner,
  409. carrier,
  410. announced: false,
  411. announcing: false,
  412. detachRequested: false,
  413. }
  414. this.store.set(id, entry)
  415. let entered = true
  416. const detach = (): void => {
  417. if (!entered) return
  418. entered = false
  419. // Every callback reached by this creation dispatch must observe the same
  420. // live entry, and disposal must follow creation. A listener may own
  421. // the advanced detach capability, so make that ordering structural:
  422. // visibility and the paired disposal are deferred until announce()'s
  423. // synchronous dispatch has unwound.
  424. if (entry.announcing) {
  425. entry.detachRequested = true
  426. return
  427. }
  428. this.detachEntered(entry)
  429. }
  430. return detach
  431. }
  432. /** Remove one exact entered agent and emit its paired disposal when announced. */
  433. private detachEntered(entry: AgentEntry): void {
  434. entry.detachRequested = false
  435. // A stale capability can never delete a later same-id lifecycle. The
  436. // captured entry identity is the final boundary.
  437. /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
  438. if (this.store.get(entry.id) !== entry) return
  439. this.store.delete(entry.id)
  440. // An insertion rolled back before announce was never externally created,
  441. // so emitting disposed would invent an impossible lifecycle edge. Marking
  442. // happens before the created emit: if a later created listener throws,
  443. // earlier listeners may already have observed it and must see disposal.
  444. if (!entry.announced) return
  445. this.emitDisposed(entry)
  446. }
  447. /** Emit the paired disposal edge through the entry's stable carrier. */
  448. private emitDisposed(entry: AgentEntry): void {
  449. const args: unknown[] = [entry.carrier, 'agent/disposed', entry.agent]
  450. for (const callback of this.ctx.events.dispatch('emit', args)) {
  451. try {
  452. const returned: unknown = callback(...args)
  453. void Promise.resolve(returned).catch((error: unknown) => {
  454. this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener rejected: ${String(error)}`)
  455. })
  456. } catch (error: unknown) {
  457. this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener threw: ${String(error)}`)
  458. }
  459. }
  460. }
  461. /**
  462. * Announce an agent previously inserted with {@link enter}.
  463. * @param agent - the live inserted agent to announce.
  464. * @throws if `agent` is not the exact live registry entry for its id, or its
  465. * creation announcement already began (including a reentrant call from a
  466. * creation listener).
  467. */
  468. announce(agent: Agent): void {
  469. const entry = this.store.get(agent.id)
  470. if (entry === undefined || entry.agent !== agent) {
  471. throw new Error(`agent "${agent.id}" is not live in this registry`)
  472. }
  473. if (entry.announced || entry.announcing) {
  474. throw new Error(`agent "${entry.id}" was already announced`)
  475. }
  476. // Mark before dispatch so a listener cannot recursively create a second
  477. // lifecycle edge; detach still pairs a partially delivered first edge.
  478. entry.announcing = true
  479. entry.announced = true
  480. const args: unknown[] = [entry.carrier, 'agent/created', entry.agent]
  481. try {
  482. for (const callback of this.ctx.events.dispatch('emit', args)) {
  483. // A synchronous creation failure vetoes publication and rolls back.
  484. // Returned-promise rejection happens after this synchronous boundary, so
  485. // observe and report it instead of leaking an unhandled rejection.
  486. const returned: unknown = callback(...args)
  487. void Promise.resolve(returned).catch((error: unknown) => {
  488. this.ctx.logger.warn(`agent "${entry.id}": agent/created listener rejected: ${String(error)}`)
  489. })
  490. }
  491. } finally {
  492. entry.announcing = false
  493. if (entry.detachRequested) this.detachEntered(entry)
  494. }
  495. }
  496. /**
  497. * Look up a live agent.
  498. * @param id - the shared agent/session id to look up.
  499. * @returns the agent, or undefined when no live agent has that id.
  500. */
  501. get(id: SessionId): Agent | undefined {
  502. return this.store.get(id)?.agent
  503. }
  504. /**
  505. * Test whether a live agent was created through one exact parent agent's
  506. * scoped context. Runtime ownership is independent of durable session
  507. * lineage and remains unambiguous when unrelated providers reuse an id.
  508. * @param id - the candidate child agent's shared agent/session id.
  509. * @param owner - the expected runtime creator agent.
  510. * @returns true only while the exact child entry is live under that owner.
  511. */
  512. isOwnedBy(id: SessionId, owner: Agent): boolean {
  513. return this.store.get(id)?.owner === owner
  514. }
  515. /**
  516. * All live agents, in registration order.
  517. * @returns a fresh array; mutating it does not affect the registry.
  518. */
  519. list(): Agent[] {
  520. return [...this.store.values()].map(entry => entry.agent)
  521. }
  522. /**
  523. * All live top-level agents in registration order. A top-level agent was
  524. * created without an owning agent context; durable session lineage does not
  525. * affect this runtime relation, so a resumed fork may still be a root.
  526. * @returns a fresh array; mutating it does not affect the registry.
  527. */
  528. roots(): Agent[] {
  529. return [...this.store.values()]
  530. .filter(entry => entry.owner === undefined)
  531. .map(entry => entry.agent)
  532. }
  533. /** Reject new initiator boundaries while inherited continuations drain. */
  534. private closeInitiators(): void {
  535. if (this.initiatorState === 'active') this.initiatorState = 'closing'
  536. }
  537. /** Wait for returned-Promise boundaries, then invalidate retained references. */
  538. private disposeInitiators(): Promise<void> {
  539. return (this.initiatorDisposal ??= (async () => {
  540. this.closeInitiators()
  541. this.releaseReentrantInitiatorRuns()
  542. if (this.activeInitiatorRuns !== 0) {
  543. this.initiatorDrain ??= Promise.withResolvers<void>()
  544. await this.initiatorDrain.promise
  545. }
  546. this.initiatorState = 'disposed'
  547. this.initiators.disable()
  548. this.initiatorRuns.disable()
  549. })())
  550. }
  551. /** Establish one tracked initiator or clearing boundary. */
  552. private runWithInitiator<T>(agent: Agent | undefined, operation: () => T): T {
  553. if (this.initiatorState !== 'active') throw new Error(DISPOSED_INITIATOR_MESSAGE)
  554. const run: InitiatorRun = {
  555. active: true,
  556. parent: this.initiatorRuns.getStore(),
  557. }
  558. this.activeInitiatorRuns += 1
  559. let result: T
  560. try {
  561. result = this.initiatorRuns.run(run, () => this.initiators.run(agent, operation))
  562. } catch (error: unknown) {
  563. this.releaseInitiatorRun(run)
  564. throw error
  565. }
  566. if (isPromise(result)) {
  567. try {
  568. void Promise.prototype.then.call(
  569. result,
  570. () => { this.releaseInitiatorRun(run) },
  571. () => { this.releaseInitiatorRun(run) },
  572. )
  573. } catch {
  574. // A branded Promise may expose a failing @@species. Observer setup did
  575. // not attach, so preserve the exact return without leaking the run.
  576. this.releaseInitiatorRun(run)
  577. }
  578. } else {
  579. this.releaseInitiatorRun(run)
  580. }
  581. return result
  582. }
  583. /** Whether one unloading fiber owns this service's lifecycle. */
  584. private hasLifecycleAncestor(candidate: Fiber): boolean {
  585. let fiber = this.ctx.fiber
  586. while (true) {
  587. if (fiber === candidate) return true
  588. const parent = fiber.parent.fiber
  589. if (parent === fiber) return false
  590. fiber = parent
  591. }
  592. }
  593. private assertInitiatorsReadable(): void {
  594. if (this.initiatorState === 'disposed') throw new Error(DISPOSED_INITIATOR_MESSAGE)
  595. }
  596. /** Exclude the boundary chain that initiated this teardown from its own drain. */
  597. private releaseReentrantInitiatorRuns(): void {
  598. let run = this.initiatorRuns.getStore()
  599. while (run !== undefined) {
  600. this.releaseInitiatorRun(run)
  601. run = run.parent
  602. }
  603. }
  604. private releaseInitiatorRun(run: InitiatorRun): void {
  605. if (!run.active) return
  606. run.active = false
  607. this.activeInitiatorRuns -= 1
  608. if (this.activeInitiatorRuns !== 0) return
  609. this.initiatorDrain?.resolve()
  610. this.initiatorDrain = undefined
  611. }
  612. }
  613. export default AgentRegistry