index.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /**
  2. * Agent registry service. Tracks live agents so plugins can find them without
  3. * depending on the concrete loop package. Agent creation belongs to the loop.
  4. *
  5. * @module @deepseek-ai/dsh-agent
  6. */
  7. import { Context, getTraceable, Service, symbols } from 'cordis'
  8. import { scopeTarget } from '@deepseek-ai/dsh-scope'
  9. import type { Scoped } from '@deepseek-ai/dsh-scope'
  10. import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session'
  11. import type { Agent, AgentId, AgentOptions } from './types.ts'
  12. export * from './types.ts'
  13. export { agentEvents, assembleContextFor } from './dispatch.ts'
  14. export type { AgentEventDispatch, AgentSubjectEvent } from './dispatch.ts'
  15. declare module 'cordis' {
  16. interface Context {
  17. agents: AgentRegistry
  18. /**
  19. * The agent association installed as an own property on `Agent.ctx`, or
  20. * `undefined` on a plain context. Contexts derived from `Agent.ctx` inherit
  21. * the association; a deliberately nested scope may carry a nearer
  22. * `dsh-scope` tag while retaining it, so this field is DX context rather
  23. * than the scope resolver. {@link AgentRegistry} registers a root accessor
  24. * defaulting to `undefined`, and core packages below the agent layer use
  25. * `scopeOf()` for layer selection instead of reading this field.
  26. */
  27. agent?: Agent
  28. }
  29. }
  30. /** Options for creating an agent and its caller-named session. */
  31. export interface CreateAgentOptions {
  32. /** The agent's id (the registry handle). */
  33. readonly agentId: AgentId
  34. /** The live session's id (NOT derived from agentId). */
  35. readonly sessionId: SessionId
  36. /** Durable session metadata, validated and detached before setup. */
  37. readonly meta?: { readonly cwd?: string; readonly parentSession?: SessionId; readonly seedLength?: number }
  38. /** Balanced contiguous event prefix for a forked session. */
  39. readonly seed?: readonly SessionEvent[]
  40. /** Per-agent options (model, …). */
  41. readonly agentOptions?: AgentOptions
  42. /** Optional creation-only cancellation signal; detached before the returned handle becomes visible. */
  43. readonly signal?: AbortSignal
  44. /**
  45. * Compose the unpublished scoped context before lifecycle announcements.
  46. * Failure rolls back without publishing either id; setup must not drive the agent.
  47. */
  48. readonly setup?: (agentCtx: Context) => Promise<void> | void
  49. }
  50. /**
  51. * Options for resuming an agent on a persisted session
  52. * ({@link AgentRegistry.resume}).
  53. */
  54. export interface ResumeAgentOptions {
  55. /** The agent's id (the registry handle). */
  56. readonly agentId: AgentId
  57. /** The persisted session id to load and resume on. */
  58. readonly resumeSessionId: SessionId
  59. /** Per-agent options (model, …). */
  60. readonly agentOptions?: AgentOptions
  61. /** Optional creation-only cancellation signal for persistence load/setup; detached before return. */
  62. readonly signal?: AbortSignal
  63. /** Compose after persistence load under the same unpublished rollback contract as create. */
  64. readonly setup?: (agentCtx: Context) => Promise<void> | void
  65. }
  66. /**
  67. * Holder-owned agent capability. Disposal stops and drains the loop and idle
  68. * flushes before unregistering the agent, detaching its session, and unwinding
  69. * its scoped context. Provider unload reaches the same quiescence boundary;
  70. * registry observers receive only the bare {@link Agent}.
  71. */
  72. export interface AgentHandle {
  73. agent: Agent
  74. dispose(): Promise<void>
  75. }
  76. /**
  77. * The agent-creation factory the loop implementation provides to the registry
  78. * via {@link AgentRegistry.setFactory}. Kept on the `dsh-agent` interface so
  79. * consumers (e.g. the ACP bridge) program against `ctx.agents` without
  80. * depending on the concrete `dsh-agent-loop` package.
  81. */
  82. export interface AgentFactory {
  83. /**
  84. * Create and compose under caller ownership, publish and announce session then
  85. * agent, emit session-start, and start the driver. Rollback pairs any creation
  86. * announcement that began.
  87. * @param ownerCtx - caller-bound context that owns the transaction and live handle.
  88. * @param options - agent/session identity, configuration, and optional setup.
  89. * @returns the owned handle after setup, both announcements, and loop start complete.
  90. */
  91. createAgent(ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle>
  92. /**
  93. * Load, compose, publish, announce, and resume an agent under caller ownership.
  94. * @param ownerCtx - caller-bound context that owns load, setup, and the live handle.
  95. * @param options - persisted identity, configuration, and optional setup.
  96. * @returns the owned handle after setup, both announcements, and loop start complete.
  97. */
  98. resume(ownerCtx: Context, options: ResumeAgentOptions): Promise<AgentHandle>
  99. }
  100. /** Thrown when create/resume is called before an agent factory is registered. */
  101. const NO_FACTORY_MESSAGE = 'no agent factory registered (load an agent-loop plugin)'
  102. /** All mutable lifecycle state for one exact registry entry. */
  103. interface AgentEntry {
  104. readonly id: AgentId
  105. readonly agent: Agent
  106. readonly carrier: Scoped<Agent>
  107. announced: boolean
  108. announcing: boolean
  109. detachRequested: boolean
  110. }
  111. /** Plain holder prevents Cordis from tracing the factory field before the caller context is known. */
  112. interface FactorySlot {
  113. readonly target: AgentFactory
  114. }
  115. /**
  116. * Agent registry (`ctx.agents`): tracks live agents so UI, hook, and
  117. * orchestrator plugins can find them without depending on the concrete loop
  118. * package. Agent *creation* is provided by whichever plugin implements the
  119. * {@link AgentFactory} (`@deepseek-ai/dsh-agent-loop`), registered via
  120. * {@link setFactory}.
  121. */
  122. export class AgentRegistry extends Service {
  123. private store = new Map<AgentId, AgentEntry>()
  124. // TODO(agent-entry-mirror): derive exact-object checks from store.get(agent.id)
  125. // plus entry.agent identity; this WeakMap mirrors the authoritative id map.
  126. private entries = new WeakMap<Agent, AgentEntry>()
  127. private factory: FactorySlot | undefined
  128. constructor(ctx: Context) {
  129. super(ctx, 'agents')
  130. // Agent contexts shadow this plain-context default with an own property.
  131. ctx.accessor('agent', { get: () => undefined })
  132. }
  133. /**
  134. * Register the effect-scoped creation factory, rejecting a duplicate. Service
  135. * factories are retraced through each create/resume caller for ownership.
  136. * @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
  137. * @returns the exact Cordis effect disposer.
  138. */
  139. setFactory(factory: AgentFactory): () => void {
  140. const dispose = this.ctx.effect(() => {
  141. if (this.factory !== undefined) throw new Error('an agent factory is already registered')
  142. // Store the concrete service; calls are retraced through their owner.
  143. const target = (factory as AgentFactory & { [symbols.original]?: AgentFactory })[symbols.original] ?? factory
  144. this.factory = { target }
  145. return () => { this.factory = undefined }
  146. }, 'agents.setFactory()')
  147. // Return the exact disposer so composite effects preserve teardown order.
  148. // eslint-disable-next-line @typescript-eslint/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
  149. return dispose
  150. }
  151. /** Return the active creation factory. */
  152. private requireFactory(): FactorySlot {
  153. if (this.factory === undefined) throw new Error(NO_FACTORY_MESSAGE)
  154. return this.factory
  155. }
  156. /**
  157. * Create and publish an owned agent and session through the active factory.
  158. * Rejects if no factory is registered or creation, setup, or publication fails.
  159. * @param options - agent id, session id/seed/metadata, and agent options.
  160. * @returns the handle after setup, rollback-covered publication, and loop start complete.
  161. */
  162. async create(options: CreateAgentOptions): Promise<AgentHandle> {
  163. const ownerCtx = this.ctx
  164. // Bind service effects to this caller while preserving factory dependencies.
  165. const { target } = this.requireFactory()
  166. const receiver = getTraceable(ownerCtx, target)
  167. // eslint-disable-next-line @typescript-eslint/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
  168. return Reflect.apply(target.createAgent, receiver, [ownerCtx, options])
  169. }
  170. /**
  171. * Load a persisted session and resume an agent on it through the registered
  172. * factory. Rejects if no factory is registered; the factory rejects if
  173. * session persistence is not configured or persistence/setup fails.
  174. * @param options - persisted identity, configuration, and optional setup.
  175. * @returns the handle after setup, rollback-covered publication, and loop start complete.
  176. */
  177. async resume(options: ResumeAgentOptions): Promise<AgentHandle> {
  178. const ownerCtx = this.ctx
  179. const { target } = this.requireFactory()
  180. const receiver = getTraceable(ownerCtx, target)
  181. // eslint-disable-next-line @typescript-eslint/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
  182. return Reflect.apply(target.resume, receiver, [ownerCtx, options])
  183. }
  184. /**
  185. * Register a live agent in the calling effect scope, with scope-filtered
  186. * creation and disposal events. Duplicate ids throw.
  187. * @param agent - the already-constructed agent to record in the store.
  188. * @returns the exact Cordis effect disposer for nested teardown ordering.
  189. */
  190. register(agent: Agent): () => void {
  191. const dispose = this.ctx.effect(function* (this: AgentRegistry) {
  192. yield this.enter(agent)
  193. this.announce(agent)
  194. }.bind(this), 'agents.register()')
  195. // eslint-disable-next-line @typescript-eslint/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
  196. return dispose
  197. }
  198. /**
  199. * Insert an unpublished agent for an ordered factory transaction.
  200. * @param agent - the prepared, unpublished agent.
  201. * @returns an idempotent closure that removes this exact entry and emits the
  202. * paired disposal edge; detachment during creation dispatch is deferred.
  203. */
  204. enter(agent: Agent): () => void {
  205. const id = agent.id
  206. const carrier = scopeTarget(agent, agent)
  207. // Prepared transactions arbitrate identity at this publication boundary.
  208. if (this.entries.has(agent) || this.store.has(id)) throw new Error(`agent "${id}" is already registered`)
  209. const entry: AgentEntry = {
  210. id,
  211. agent,
  212. carrier,
  213. announced: false,
  214. announcing: false,
  215. detachRequested: false,
  216. }
  217. this.store.set(id, entry)
  218. this.entries.set(agent, entry)
  219. let entered = true
  220. const detach = (): void => {
  221. if (!entered) return
  222. entered = false
  223. // Creation listeners observe one stable entry before paired disposal.
  224. if (entry.announcing) {
  225. entry.detachRequested = true
  226. return
  227. }
  228. this.detachEntered(entry)
  229. }
  230. return detach
  231. }
  232. /** Remove one exact entered agent and emit its paired disposal when announced. */
  233. private detachEntered(entry: AgentEntry): void {
  234. entry.detachRequested = false
  235. // A stale capability can never delete a later same-id lifecycle. The
  236. // captured entry identity is the final boundary.
  237. /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
  238. if (this.store.get(entry.id) !== entry) return
  239. this.store.delete(entry.id)
  240. this.entries.delete(entry.agent)
  241. // An insertion rolled back before announce was never externally created,
  242. // so emitting disposed would invent an impossible lifecycle edge. Marking
  243. // happens before the created emit: if a later created listener throws,
  244. // earlier listeners may already have observed it and must see disposal.
  245. if (!entry.announced) return
  246. this.emitDisposed(entry)
  247. }
  248. /** Emit the paired disposal edge through the entry's stable carrier. */
  249. private emitDisposed(entry: AgentEntry): void {
  250. const args: unknown[] = [entry.carrier, 'agent/disposed', entry.agent]
  251. for (const callback of this.ctx.events.dispatch('emit', args)) {
  252. try {
  253. const returned: unknown = callback(...args)
  254. void Promise.resolve(returned).catch((error: unknown) => {
  255. this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener rejected: ${String(error)}`)
  256. })
  257. } catch (error: unknown) {
  258. this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener threw: ${String(error)}`)
  259. }
  260. }
  261. }
  262. /**
  263. * Announce an agent previously inserted with {@link enter}.
  264. * @param agent - the live inserted agent to announce.
  265. * @throws if `agent` is not the exact live registry entry for its id, or its
  266. * creation announcement already began (including a reentrant call from a
  267. * creation listener).
  268. */
  269. announce(agent: Agent): void {
  270. const entry = this.entries.get(agent)
  271. if (entry === undefined || this.store.get(entry.id) !== entry) {
  272. throw new Error(`agent "${agent.id}" is not live in this registry`)
  273. }
  274. if (entry.announced || entry.announcing) {
  275. throw new Error(`agent "${entry.id}" was already announced`)
  276. }
  277. // Mark before dispatch so a listener cannot recursively create a second
  278. // lifecycle edge; detach still pairs a partially delivered first edge.
  279. entry.announcing = true
  280. entry.announced = true
  281. const args: unknown[] = [entry.carrier, 'agent/created', entry.agent]
  282. try {
  283. for (const callback of this.ctx.events.dispatch('emit', args)) {
  284. // A synchronous creation failure vetoes publication and rolls back.
  285. // Returned-promise rejection happens after this synchronous boundary, so
  286. // observe and report it instead of leaking an unhandled rejection.
  287. const returned: unknown = callback(...args)
  288. void Promise.resolve(returned).catch((error: unknown) => {
  289. this.ctx.logger.warn(`agent "${entry.id}": agent/created listener rejected: ${String(error)}`)
  290. })
  291. }
  292. } finally {
  293. entry.announcing = false
  294. if (entry.detachRequested) this.detachEntered(entry)
  295. }
  296. }
  297. /**
  298. * Look up a live agent.
  299. * @param id - the agent id to look up.
  300. * @returns the agent, or undefined when no live agent has that id.
  301. */
  302. get(id: AgentId): Agent | undefined {
  303. return this.store.get(id)?.agent
  304. }
  305. /**
  306. * All live agents, in registration order.
  307. * @returns a fresh array; mutating it does not affect the registry.
  308. */
  309. list(): Agent[] {
  310. return [...this.store.values()].map(entry => entry.agent)
  311. }
  312. }
  313. export default AgentRegistry