index.ts 30 KB

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