index.ts 29 KB

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