index.ts 31 KB

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