index.ts 30 KB

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