@dudousxd/nestjs-agent 1.39.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +14 -7
  2. package/dist/a2ui/index.cjs +1 -0
  3. package/dist/a2ui/index.cjs.map +1 -1
  4. package/dist/a2ui/index.d.cts +3 -2
  5. package/dist/a2ui/index.d.ts +3 -2
  6. package/dist/a2ui/index.js +2 -1
  7. package/dist/a2ui/index.js.map +1 -1
  8. package/dist/{chat-queue.service-YjiKVTKE.d.ts → chat-queue.service-BjPCw4Pf.d.ts} +104 -43
  9. package/dist/{chat-queue.service-fopUN313.d.cts → chat-queue.service-C49HIuEV.d.cts} +104 -43
  10. package/dist/durable/index.cjs +13572 -1754
  11. package/dist/durable/index.cjs.map +1 -1
  12. package/dist/durable/index.d.cts +6 -6
  13. package/dist/durable/index.d.ts +6 -6
  14. package/dist/durable/index.js +12228 -390
  15. package/dist/durable/index.js.map +1 -1
  16. package/dist/genui/index.cjs.map +1 -1
  17. package/dist/genui/index.d.cts +4 -6
  18. package/dist/genui/index.d.ts +4 -6
  19. package/dist/genui/index.js.map +1 -1
  20. package/dist/{index-BJFM1tG8.d.cts → index-BBkyvNUi.d.cts} +1 -1
  21. package/dist/{index-De98CGXa.d.ts → index-CRCbsO6E.d.ts} +1 -1
  22. package/dist/index.cjs +12408 -450
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +318 -18
  25. package/dist/index.d.ts +318 -18
  26. package/dist/index.js +12313 -346
  27. package/dist/index.js.map +1 -1
  28. package/dist/media/index.cjs +4 -9
  29. package/dist/media/index.cjs.map +1 -1
  30. package/dist/media/index.d.cts +14 -3
  31. package/dist/media/index.d.ts +14 -3
  32. package/dist/media/index.js +6 -11
  33. package/dist/media/index.js.map +1 -1
  34. package/dist/workflows/index.cjs +1496 -0
  35. package/dist/workflows/index.cjs.map +1 -0
  36. package/dist/workflows/index.d.cts +158 -0
  37. package/dist/workflows/index.d.ts +158 -0
  38. package/dist/workflows/index.js +1464 -0
  39. package/dist/workflows/index.js.map +1 -0
  40. package/package.json +39 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/vite/index.ts","../../src/genui/kit.ts","../../src/a2ui/index.ts","../../src/a2ui/a2ui.adapter.ts","../../src/agent-service.token.ts","../../src/controller/reader-gone.ts","../../src/genui/agent-genui.module.ts","../../src/functional-tool.ts","../../src/genui/agent-genui.token.ts"],"sourcesContent":["/**\n * `@dudousxd/nestjs-agent/vite` — `genuiSandboxKit()`, the Vite plugin that puts the app's design\n * system (its styles, its components, its providers) inside the sandbox, whatever the stack:\n *\n * ```ts\n * // vite.config.ts (the SPA that talks to the agent)\n * import { genuiSandboxKit } from '@dudousxd/nestjs-agent/vite'\n * export default defineConfig({\n * plugins: [react(), genuiSandboxKit({ styles: 'src/index.css', components: 'src/components/ui' })],\n * })\n * ```\n *\n * Then `AgentGenuiModule.forRoot({ sandbox: { kit: true } })` finds what it built: the descriptor\n * the dev server writes (`.genui/sandbox-kit.json`) in dev, the Vite manifest in production (see\n * `AgentGenuiOptions.sandboxKit`).\n */\nimport {\n type GenuiSandboxKitApi,\n type GenuiSandboxKitOptions,\n type GenuiSandboxKitPlugin,\n SANDBOX_KIT_DEV_PREFIX,\n SANDBOX_KIT_MANIFEST_KEYS,\n SANDBOX_KIT_UPDATE_EVENT,\n createGenuiSandboxKitPlugin,\n} from '@dudousxd/nestjs-agent-core/genui/kit';\n\n/**\n * Where the dev descriptor is written, relative to the Vite root — and where the server reads it,\n * relative to its working directory (run both from the project root, or point\n * `sandboxKit.descriptor` at it). Add `.genui/` to `.gitignore`.\n */\nexport const NEST_SANDBOX_KIT_DESCRIPTOR = '.genui/sandbox-kit.json';\n\n/**\n * The sandbox kit plugin: `styles` (the app's style entries — default, the stylesheets among its\n * Vite entrypoints or `index.html`), `components` (modules or globs exporting React components —\n * default, the first `components/ui` folder), `wrapper` (a module whose default export wraps the\n * model's App). See {@link GenuiSandboxKitOptions}.\n */\nexport function genuiSandboxKit(options: GenuiSandboxKitOptions = {}): GenuiSandboxKitPlugin {\n return createGenuiSandboxKitPlugin(options, {\n descriptor: NEST_SANDBOX_KIT_DESCRIPTOR,\n rendererImport: /@dudousxd\\/nestjs-agent-react/,\n });\n}\n\nexport {\n type GenuiSandboxKitApi,\n type GenuiSandboxKitOptions,\n type GenuiSandboxKitPlugin,\n SANDBOX_KIT_DEV_PREFIX,\n SANDBOX_KIT_MANIFEST_KEYS,\n SANDBOX_KIT_UPDATE_EVENT,\n};\n","/**\n * The sandbox kit in a Nest app. No Vite runs in the Nest process, so the kit is found in files:\n * the descriptor `genuiSandboxKit()` (`@dudousxd/nestjs-agent/vite`) writes while the dev server\n * runs, and in production the Vite manifest the build wrote (`genui-sandbox-kit.json` and the assets\n * it names). Node-only: loaded by {@link AgentGenuiModule} only when a sandbox is configured.\n */\nimport { resolve } from 'node:path';\nimport {\n type SandboxKitDiscovery,\n sandboxKitDescriptorPath,\n sandboxKitDiscovery,\n} from '@dudousxd/nestjs-agent-core/genui/kit';\nimport { NEST_SANDBOX_KIT_DESCRIPTOR } from '../vite/index.js';\nimport type { AgentGenuiSandboxKitOptions } from './agent-genui.module.js';\n\n/** Where the production Vite manifest is looked for by default, and the directory it is relative to. */\nexport const NEST_SANDBOX_KIT_MANIFEST = Object.freeze({\n file: 'public/.vite/manifest.json',\n outDir: 'public',\n});\n\n/**\n * Find the kit for `AgentGenuiModule.forRoot({ sandbox: { kit: true } })` — a named kit's\n * (`genuiSandboxKit({ name })`, `sandbox: { kit: true, kitName }`) with `name`.\n */\nexport function nestSandboxKitDiscovery(\n options: AgentGenuiSandboxKitOptions = {},\n name?: string,\n): SandboxKitDiscovery {\n const manifest = options.manifest ?? NEST_SANDBOX_KIT_MANIFEST;\n return sandboxKitDiscovery({\n root: resolve(options.root ?? process.cwd()),\n ...(name !== undefined ? { name } : {}),\n descriptor: sandboxKitDescriptorPath(options.descriptor ?? NEST_SANDBOX_KIT_DESCRIPTOR, name),\n ...(manifest !== false ? { manifest: { file: manifest.file, outDir: manifest.outDir } } : {}),\n ...(options.kitUrl !== undefined ? { kitUrl: options.kitUrl } : {}),\n ...(options.cssUrl !== undefined ? { cssUrl: options.cssUrl } : {}),\n ...(options.tailwindUrl !== undefined ? { tailwindUrl: options.tailwindUrl } : {}),\n ...(options.production !== undefined ? { production: options.production } : {}),\n });\n}\n","/**\n * `@dudousxd/nestjs-agent/a2ui` — A2UI (https://a2ui.org, v0.9) for the agent: the `a2uiAdapter()`\n * route (JSON Lines of A2UI messages), and the framework-free pieces it is built from (re-exported\n * from `@dudousxd/nestjs-agent-core/a2ui`) — the `ui` frame → A2UI converter, the builtin →\n * basic-catalog mappings, the catalog export, the inbound action reader. For A2UI over AG-UI, pass\n * `a2ui: true` to `agUiAdapter()`.\n */\n\nexport * from '@dudousxd/nestjs-agent-core/a2ui';\nexport { type A2uiAdapterOptions, A2uiRunHandler, a2uiAdapter } from './a2ui.adapter.js';\n","import { AGENT_ACTOR_RESOLVER, type ActorResolver } from '@dudousxd/nestjs-agent-core';\nimport {\n A2UI_APPROVE_ACTION,\n A2UI_REJECT_ACTION,\n A2uiProjector,\n type A2uiServerMessage,\n type A2uiStreamOptions,\n a2uiThreadReplay,\n negotiateA2uiCatalog,\n readA2uiAction,\n readA2uiClientCapabilities,\n} from '@dudousxd/nestjs-agent-core/a2ui';\nimport {\n agUiEvents,\n agUiFramesFromNdjson,\n decodeInterruptId,\n} from '@dudousxd/nestjs-agent-core/ag-ui';\nimport {\n type Catalog,\n type UiAction,\n type UiCapabilities,\n uiActionText,\n validateUiCapabilities,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n BadRequestException,\n Body,\n Controller,\n ForbiddenException,\n Get,\n HttpCode,\n Inject,\n Optional,\n Param,\n Post,\n Query,\n Req,\n Res,\n} from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport { AGENT_SERVICE } from '../agent-service.token.js';\nimport type { AgentService } from '../agent.service.js';\nimport { readerGone } from '../controller/reader-gone.js';\nimport { GENUI_CATALOG } from '../genui/agent-genui.module.js';\nimport type { AgentProtocolAdapter } from '../protocol-adapter.js';\n\nexport interface A2uiAdapterOptions extends A2uiStreamOptions {\n /** Where the route mounts, under the agent's path. Default `'a2ui'` → `POST <path>/a2ui`. */\n path?: string;\n /** As `agUiAdapter`'s: how long a run waiting on a person may stay silent before the stream ends. */\n quietMs?: number;\n /** Largest action accepted, as JSON, in bytes. Default 8192. */\n maxActionBytes?: number;\n /** Largest `a2uiClientDataModel` accepted, as JSON, in bytes. Default 32768. */\n maxDataModelBytes?: number;\n}\n\n/** The surface an A2UI decision is recorded as having come through. */\nconst A2UI_VIA = 'a2ui';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(code: string, message: string): BadRequestException {\n return new BadRequestException({ statusCode: 400, code, message });\n}\n\n/** A field of the body, or of its A2A-style `metadata` (where A2UI puts client capabilities). */\nfunction bodyField(body: Record<string, unknown>, key: string): unknown {\n if (body[key] !== undefined) return body[key];\n return isRecord(body.metadata) ? body.metadata[key] : undefined;\n}\n\n/** `a2uiClientDataModel` (`{ version, surfaces: { <surfaceId>: model } }`): its surfaces, or why not. */\nfunction readDataModel(\n raw: unknown,\n maxBytes: number,\n): Record<string, unknown> | undefined | string {\n if (raw === undefined) return undefined;\n if (!isRecord(raw) || !isRecord(raw.surfaces)) {\n return 'a2uiClientDataModel carries { version, surfaces }';\n }\n let size: number;\n try {\n size = new TextEncoder().encode(JSON.stringify(raw.surfaces)).length;\n } catch {\n return 'a2uiClientDataModel must be JSON';\n }\n if (size > maxBytes) {\n return `a2uiClientDataModel may be at most ${maxBytes} bytes (this one is ${size})`;\n }\n return Object.keys(raw.surfaces).length > 0 ? raw.surfaces : undefined;\n}\n\n/**\n * Serves the agent as an A2UI agent. Not mounted directly — {@link a2uiAdapter} mounts a subclass at\n * the configured path — but exported so a host can extend it under a route of its own.\n */\nexport class A2uiRunHandler {\n constructor(\n protected readonly agent: AgentService,\n protected readonly actorResolver: ActorResolver,\n protected readonly projection: A2uiStreamOptions,\n protected readonly quietMs: number | undefined,\n protected readonly maxActionBytes: number | undefined,\n protected readonly maxDataModelBytes: number | undefined = undefined,\n ) {}\n\n /**\n * `GET <path>/a2ui/threads/:threadId`: a stored thread as `{ threadId, entries }`\n * (`a2uiThreadReplay`) — what a client draws again after a reload. Owner-scoped; a thread nobody\n * has answers `{ entries: [] }`. `?catalog=<id>` names the client's basic catalog id.\n */\n async replay(\n req: Request,\n threadId: string,\n catalog: unknown,\n ): Promise<{ threadId: string; entries: ReturnType<typeof a2uiThreadReplay> }> {\n const actor = await this.actorResolver.resolve(req);\n const owner = await this.agent.threadOwner(threadId);\n if (owner === null) return { threadId, entries: [] };\n const thread = await this.agent.getThread(actor, threadId);\n const supported =\n typeof catalog === 'string'\n ? [catalog]\n : Array.isArray(catalog)\n ? catalog.filter((id): id is string => typeof id === 'string')\n : undefined;\n return {\n threadId,\n entries: a2uiThreadReplay(\n thread?.messages ?? [],\n negotiateA2uiCatalog(this.projection, supported),\n ),\n };\n }\n\n async handle(req: Request, res: Response, raw: unknown): Promise<void> {\n const body = isRecord(raw) ? raw : {};\n const agentName =\n typeof body.agent === 'string' && body.agent.length > 0 ? body.agent : undefined;\n const actor = await this.actorResolver.resolve(req);\n // The basic catalog under the id this client advertises (`a2uiClientCapabilities`).\n const projection = negotiateA2uiCatalog(\n this.projection,\n readA2uiClientCapabilities(bodyField(body, 'a2uiClientCapabilities')),\n );\n const dataModel = readDataModel(\n bodyField(body, 'a2uiClientDataModel'),\n this.maxDataModelBytes ?? 32768,\n );\n if (typeof dataModel === 'string') throw invalid('invalid_data_model', dataModel);\n\n let action: UiAction | undefined;\n if (body.action !== undefined) {\n const read = isRecord(body.action)\n ? readA2uiAction(body.action, {\n ...(this.maxActionBytes !== undefined ? { maxBytes: this.maxActionBytes } : {}),\n })\n : 'action must be an A2UI action message';\n if (typeof read === 'string') throw invalid('invalid_action', read);\n action = read;\n }\n\n // Deciding the approval a stream ended on: settle it, then stream the rest of the run.\n if (action?.name === A2UI_APPROVE_ACTION || action?.name === A2UI_REJECT_ACTION) {\n const interruptId = action.context.interruptId;\n const address = typeof interruptId === 'string' ? decodeInterruptId(interruptId) : undefined;\n if (address === undefined || address === null || address.kind === 'elicitation') {\n throw invalid('invalid_action', 'an approval action carries the interruptId it decides');\n }\n // An independent proposal: decided through the proposal service (its own run is not\n // waiting), as an AG-UI resume decides it, and answered with the configured reply.\n if (address.kind === 'proposal') {\n if (address.proposalId === undefined || address.threadId === undefined) {\n throw invalid('invalid_action', 'the interruptId names no proposal');\n }\n const decided = await this.agent.decideActionProposal(\n actor,\n address.threadId,\n address.proposalId,\n {\n decision: action.name === A2UI_APPROVE_ACTION ? 'approved' : 'rejected',\n via: A2UI_VIA,\n },\n );\n this.writeHead(res, { 'X-Agent-Thread-Id': address.threadId });\n const projector = new A2uiProjector(projection);\n const messageId = `proposal-${address.proposalId}`;\n for (const event of [\n { type: 'TEXT_MESSAGE_START' as const, messageId, role: 'assistant' as const },\n { type: 'TEXT_MESSAGE_CONTENT' as const, messageId, delta: decided.text },\n ]) {\n for (const message of projector.project(event)) res.write(`${JSON.stringify(message)}\\n`);\n }\n res.end();\n return;\n }\n // The same checks an AG-UI resume makes: the run is the actor's and still waiting, and the\n // actor may decide this call.\n await this.agent.assertResumable(actor, address.stream);\n await this.agent.checkDecision(actor, address.toolCallId);\n if (action.name === A2UI_APPROVE_ACTION) {\n await this.agent.approve(actor, address.toolCallId, { via: A2UI_VIA });\n } else {\n await this.agent.reject(actor, address.toolCallId, undefined, { via: A2UI_VIA });\n }\n await this.stream(res, address.stream, {\n skip: address.position,\n answered: [address.toolCallId],\n projection,\n });\n return;\n }\n\n const message = typeof body.message === 'string' ? body.message : '';\n const text = action !== undefined ? uiActionText(action) : message;\n if (text.trim().length === 0) {\n throw invalid('no_user_message', 'send a message or an action');\n }\n const threadId =\n typeof body.threadId === 'string' && body.threadId.length > 0 ? body.threadId : undefined;\n const owner = threadId !== undefined ? await this.agent.threadOwner(threadId) : null;\n if (owner !== null && owner !== actor.id) {\n throw new ForbiddenException('thread belongs to another actor');\n }\n let uiCapabilities: UiCapabilities | undefined;\n if (Object.hasOwn(body, 'uiCapabilities')) {\n try {\n uiCapabilities = validateUiCapabilities(body.uiCapabilities);\n } catch (error) {\n throw invalid('invalid_input', (error as Error).message);\n }\n }\n const started = await this.agent.chat({\n actor,\n message: text,\n ...(threadId === undefined ? {} : owner !== null ? { threadId } : { newThreadId: threadId }),\n ...(agentName !== undefined ? { agentName } : {}),\n ...(uiCapabilities !== undefined ? { uiCapabilities } : {}),\n ...(dataModel !== undefined ? { pageContext: { a2uiDataModel: dataModel } } : {}),\n });\n await this.stream(res, started.runId, { threadId: started.threadId, projection });\n }\n\n /** Open the JSON Lines response. */\n protected writeHead(res: Response, extra: Record<string, string>): void {\n res.status(200);\n res.setHeader('Content-Type', 'application/jsonl; charset=utf-8');\n res.setHeader('Cache-Control', 'no-cache, no-transform');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n for (const [name, value] of Object.entries(extra)) res.setHeader(name, value);\n res.flushHeaders();\n }\n\n /** Write one run as A2UI JSON Lines, until it ends or stops to ask. */\n protected async stream(\n res: Response,\n runId: string,\n options: {\n threadId?: string;\n skip?: number;\n answered?: string[];\n projection?: A2uiStreamOptions;\n },\n ): Promise<void> {\n this.writeHead(res, {\n 'X-Agent-Run-Id': runId,\n ...(options.threadId !== undefined ? { 'X-Agent-Thread-Id': options.threadId } : {}),\n });\n const projector = new A2uiProjector(options.projection ?? this.projection);\n const write = (messages: A2uiServerMessage[]) => {\n for (const message of messages) res.write(`${JSON.stringify(message)}\\n`);\n };\n try {\n const frames = agUiFramesFromNdjson(this.agent.subscribe(runId, readerGone(res)));\n for await (const event of agUiEvents(frames, {\n threadId: options.threadId ?? runId,\n runId,\n streamRunId: runId,\n ...(options.threadId !== undefined ? { streamThreadId: options.threadId } : {}),\n ...(options.skip !== undefined ? { skip: options.skip } : {}),\n ...(options.answered !== undefined ? { answered: options.answered } : {}),\n ...(this.quietMs !== undefined ? { quietMs: this.quietMs } : {}),\n })) {\n write(projector.project(event));\n }\n } catch {\n write(projector.project({ type: 'RUN_ERROR', message: 'The run could not be followed.' }));\n }\n res.end();\n }\n}\n\n/**\n * Serve the agent as an A2UI (https://a2ui.org, v0.9) agent: `POST <path>/a2ui` answers with the\n * run as a JSON Lines stream of A2UI server-to-client messages — `createSurface`,\n * `updateComponents`, `updateDataModel`, `deleteSurface` — that any A2UI renderer draws.\n *\n * ```ts\n * import { a2uiAdapter } from '@dudousxd/nestjs-agent/a2ui'\n *\n * AgentModule.forRoot({ model, adapters: [a2uiAdapter()] })\n * ```\n *\n * The body is `{ threadId?, message?, action?, uiCapabilities?, a2uiClientCapabilities?,\n * a2uiClientDataModel?, agent? }` (the two A2UI fields also read from `metadata`, A2A-style):\n * - `message` — the user's text;\n * - `action` — an A2UI client message (`{ version: 'v0.9', action: { name, surfaceId,\n * sourceComponentId, timestamp, context } }`, or v0.8's `{ userAction }`): it becomes the turn\n * (`uiActionText`). `agora.approve` / `agora.reject` with `context.interruptId` decide the\n * approval a previous stream ended on, and stream the rest of that run (an independent\n * proposal is decided through the proposal service and answered with its reply);\n * - `threadId` — continue that thread (its owner is checked), or start one under that id;\n * - `a2uiClientCapabilities` — the catalogs the client draws (`{ 'v0.9': { supportedCatalogIds } }`,\n * what `MessageProcessor.getRendererCapabilities()` builds): the basic catalog is sent under the\n * id the client lists for it;\n * - `a2uiClientDataModel` — the data models of surfaces created with `sendDataModel`, handed to the\n * prompt builder as `pageContext.a2uiDataModel`.\n *\n * `GET <path>/a2ui/threads/:threadId` answers a stored thread as `{ threadId, entries }`\n * (`a2uiThreadReplay`): what a client draws again after a reload.\n *\n * Response headers name the library's ids: `X-Agent-Thread-Id`, `X-Agent-Run-Id`. Authenticated by\n * the module's `actorResolver`, guarded by its `guards` and owner-scoped exactly as `chat` is.\n * Components nothing maps are drawn as their text, from the `AgentGenuiModule` catalog when there\n * is one (or `catalog` here).\n */\nexport function a2uiAdapter(options: A2uiAdapterOptions = {}): AgentProtocolAdapter {\n const path = (options.path ?? 'a2ui').replace(/^\\/+|\\/+$/g, '');\n const { path: _path, quietMs, maxActionBytes, maxDataModelBytes, ...projection } = options;\n\n @Controller()\n class A2uiController extends A2uiRunHandler {\n constructor(\n // Tokens, never classes: this entry is its own bundle (see AGENT_SERVICE).\n @Inject(AGENT_SERVICE) agent: AgentService,\n @Inject(AGENT_ACTOR_RESOLVER) actorResolver: ActorResolver,\n @Optional() @Inject(GENUI_CATALOG) catalog?: Catalog,\n ) {\n super(\n agent,\n actorResolver,\n projection.catalog === undefined && catalog !== undefined\n ? { ...projection, catalog }\n : projection,\n quietMs,\n maxActionBytes,\n maxDataModelBytes,\n );\n }\n\n @Get(`${path}/threads/:threadId`)\n thread(\n @Req() req: Request,\n @Param('threadId') threadId: string,\n @Query('catalog') catalog: unknown,\n ): ReturnType<A2uiRunHandler['replay']> {\n return this.replay(req, threadId, catalog);\n }\n\n @Post(path)\n @HttpCode(200)\n run(@Req() req: Request, @Res() res: Response, @Body() body: unknown): Promise<void> {\n return this.handle(req, res, body);\n }\n }\n\n return { name: 'a2ui', controllers: [A2uiController] };\n}\n","/**\n * `AgentService`, as the controllers of a secondary entry (`@dudousxd/nestjs-agent/a2ui`) ask for it.\n *\n * A token rather than the class: every entry is its own bundle with its own copy of every class it\n * imports, so the class used as an injection token there is not the one `AgentModule` provides.\n * `Symbol.for` is the same value in every bundle.\n */\nexport const AGENT_SERVICE = Symbol.for('@dudousxd/nestjs-agent:agent-service');\n","import type { Response } from 'express';\n\n/**\n * Subscribe options that abort once the response's connection closes — the reader went away, or\n * the response finished (when aborting has nothing left to stop).\n */\nexport function readerGone(res: Response): { signal: AbortSignal } {\n const controller = new AbortController();\n res.once('close', () => controller.abort());\n return { signal: controller.signal };\n}\n","import type { ToolPresentation } from '@dudousxd/nestjs-agent-core';\nimport type {\n Catalog,\n GenuiAbility,\n GenuiCatalogScope,\n GenuiChannels,\n GenuiStreaming,\n GenuiTelemetryOptions,\n GenuiToolsOptions,\n SandboxClientConfig,\n TreeLimits,\n TreeSchemaMode,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n type DefineSandboxOptions,\n type SandboxDefinition,\n assertGenuiChannels,\n defineCatalog,\n defineSandbox,\n genuiTools,\n sandboxPolicyOf,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n type DynamicModule,\n type FactoryProvider,\n Inject,\n Module,\n type ModuleMetadata,\n type Provider,\n type Type,\n} from '@nestjs/common';\nimport { provideAgentTools } from '../functional-tool.js';\nimport { AGENT_GENUI, AgentGenui } from './agent-genui.token.js';\n\nexport { AGENT_GENUI, AgentGenui } from './agent-genui.token.js';\n\n/** The app's genui catalog — `@InjectGenuiCatalog()` it anywhere; `overrideProvider` it in tests. */\nexport const GENUI_CATALOG = Symbol.for('@dudousxd/nestjs-agent:genui-catalog');\n\n/** The resolved {@link AgentGenuiOptions} (without the resolver). */\nexport const GENUI_OPTIONS = Symbol.for('@dudousxd/nestjs-agent:genui-options');\n\n/** The sandbox and channels as boot resolved them (kit, Tailwind and theme found). Internal. */\nconst GENUI_RESOLVED = Symbol.for('@dudousxd/nestjs-agent:genui-resolved');\n\n/** Inject the app's genui catalog ({@link GENUI_CATALOG}). */\nexport const InjectGenuiCatalog = (): ParameterDecorator & PropertyDecorator =>\n Inject(GENUI_CATALOG);\n\n/**\n * Picks the catalog for ONE request — a tenant's own, versioned components. Consulted when a genui\n * call is validated and when the turn's tool list is described to the model, so components can\n * change without rebuilding tools at boot. Cache in here if resolving costs a round trip: it runs\n * once per turn per genui tool, and once per call.\n *\n * Provide it through `AgentGenuiModule.forRoot({ resolver })` (a class, resolved with DI, or an\n * instance); it is then injectable, and replaceable in a test with\n * `overrideProvider(GenuiCatalogResolver)`.\n */\nexport abstract class GenuiCatalogResolver {\n abstract resolve(scope: GenuiCatalogScope): Catalog | Promise<Catalog>;\n}\n\n/** What {@link AgentGenuiModule} builds tools from. */\nexport interface AgentGenuiOptions {\n /**\n * The catalog. With a {@link GenuiCatalogResolver} it is the boot-time one — it names the\n * per-component tools — and may be empty. Default: an empty catalog.\n */\n catalog?: Catalog;\n /**\n * `tree` (default): one `ui__render` tool taking a composed tree (a single node is pushed as that\n * component). `per-component`: one `ui__show_<snake>` tool per component.\n */\n mode?: 'per-component' | 'tree';\n /** `ui__render`'s input schema: `'strict'` (default, a `$defs` union per component) or `'loose'`. */\n treeSchema?: TreeSchemaMode;\n /**\n * Tree mode: `'complete'` (default) draws the tree once the call has run; `'partial'` streams it\n * as `partial` ui frames while the model writes it. A component's own `streaming` overrides it.\n */\n streaming?: GenuiStreaming;\n /** Least time between two partial tree frames of one call, in ms. Default 100. */\n streamingThrottleMs?: number;\n /** End the model's turn once a genui call succeeds (no narrating follow-up call). */\n terminal?: boolean;\n /** Tool name in `tree` mode. Default `ui__render`. */\n treeToolName?: string;\n /** Text prepended to the tree tool's description. */\n treeInstructions?: string;\n treeLimits?: TreeLimits;\n /**\n * Tree mode: components that ALSO get a flat tool whose input IS their props —\n * `componentTools: ['Sandbox']` adds `ui__sandbox`, so a model writing a big component on its own\n * has no `{ type, props }` envelope to leave out.\n */\n componentTools?: readonly string[];\n /** Tool-name prefix for `componentTools`. Default `ui__` (`Sandbox` → `ui__sandbox`). */\n componentToolPrefix?: string;\n /** Tool-name prefix in `per-component` mode. Default `ui__show_`. */\n namePrefix?: string;\n /**\n * Also register ONE generic tool taking `{ component, props }`, validated against the request's\n * catalog — how a model reaches a tenant's own components, which no boot-time tool names. `true`\n * names it `ui__show`.\n */\n showTool?: boolean | string;\n /** Text prepended to the show tool's description. */\n showInstructions?: string;\n /** Roles allowed to call the tools. Undefined → the roles policy default. */\n roles?: string[];\n /**\n * The authorization ability the UI tools declare (`ToolSpec.ability`), for an ability-aware\n * authorizer such as `authzToolAuthorizer`, which denies a tool with none. A string for every\n * tool; a map by tool name (`{ ui__render: 'genui.render', ui__sandbox: 'genui.sandbox' }`, a tool\n * left out declares none); or a function of `{ name, component }`. The authorizer decides.\n */\n ability?: GenuiAbility;\n /** Override the generated presentation per component (or per tree / show tool name). */\n presentation?: (component: string) => ToolPresentation | undefined;\n /**\n * Add the sandbox component (`Sandbox`): the model may write HTML, CSS and JS for a one-off\n * interactive answer when no catalog component fits. `true` for the defaults (no network), or\n * the {@link DefineSandboxOptions} (a policy listing origins, extra instructions). Off by default.\n * The browser's catalog should carry the same definition (`defineSandbox(...)` in the shared\n * catalog file) so the renderer enforces the same policy.\n *\n * `theme` (default on) and `kit` put the app's design system in the frame: `kit: true` turns on\n * whatever `genuiSandboxKit()` built (styles, Tailwind, components, wrapper, docs), found through\n * `sandboxKit`: the descriptor\n * `genuiSandboxKit()` (`@dudousxd/nestjs-agent/vite`) writes in dev, the Vite manifest in\n * production — and `GET <base>/config` tells the renderer where the assets are.\n */\n sandbox?: boolean | DefineSandboxOptions;\n /**\n * Per-channel generative UI: each entry sets the mode, streaming, sandbox and rendering of one\n * channel (`web`, `mobile`, `whatsapp`, `telegram`, `email`, or `default` for the rest), over the\n * top-level options. A text channel (`@dudousxd/nestjs-agent-channels`) configured here draws the\n * components natively (reply buttons, lists, images). Omitted → every channel is served by the\n * top-level options, as before.\n */\n channels?: GenuiChannels;\n /**\n * Where the sandbox kit is found (with `sandbox: { kit: true }` or the theme's names). No Vite\n * runs in the Nest process, so: the descriptor the dev plugin writes, or the production Vite\n * manifest — in production the manifest first, otherwise whichever was written last.\n */\n sandboxKit?: AgentGenuiSandboxKitOptions;\n /**\n * Generative-UI telemetry, recorded by the loop for every UI call (the dashboard's \"Generative UI\"\n * page): tool, channel, mode, attempt, validity, error category, tokens and cost, time to first and\n * complete frame. Metadata only by default — the generated HTML/JSX and props are NEVER stored\n * unless `samplePayloads: true` (debugging; keep it off where a view may show personal data).\n * `false` records nothing. Needs a store that records it (`recordGenuiCalls`).\n */\n telemetry?: GenuiTelemetryOptions | false;\n}\n\n/** {@link AgentGenuiOptions.sandboxKit}. Relative paths resolve against `root`. */\nexport interface AgentGenuiSandboxKitOptions {\n /** Default `process.cwd()`. */\n root?: string;\n /**\n * The dev descriptor `genuiSandboxKit()` writes. Default `.genui/sandbox-kit.json` — for a named\n * kit (`genuiSandboxKit({ name })`, picked with `kitName`), `.genui/sandbox-kit.<name>.json`.\n */\n descriptor?: string;\n /**\n * The production Vite manifest, and the directory its `file`s are relative to. Default\n * `{ file: 'public/.vite/manifest.json', outDir: 'public' }`; `false` → none.\n */\n manifest?: { file: string; outDir: string } | false;\n /** An explicit kit url (an SPA served from elsewhere), over what is found. */\n kitUrl?: string;\n /** An explicit url of the compiled styles, over what is found (the same SPA case). */\n cssUrl?: string;\n /** An explicit url of the Tailwind browser runtime, over what is found (the same SPA case). */\n tailwindUrl?: string;\n /** Read the manifest first (else the freshest of the two). Default: `NODE_ENV === 'production'`. */\n production?: boolean;\n}\n\ntype ResolverOption = Type<GenuiCatalogResolver> | GenuiCatalogResolver;\n\nexport interface AgentGenuiModuleOptions extends AgentGenuiOptions {\n /** Per-request catalogs. A class is instantiated with DI (its dependencies must be global or exported to the root). */\n resolver?: ResolverOption;\n}\n\nexport interface AgentGenuiModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {\n inject?: FactoryProvider['inject'];\n useFactory: (...deps: any[]) => AgentGenuiOptions | Promise<AgentGenuiOptions>;\n /** Per-request catalogs. A class resolves its dependencies from `imports`. */\n resolver?: ResolverOption;\n}\n\nfunction resolverProviders(resolver: ResolverOption | undefined): Provider[] {\n if (resolver === undefined) return [];\n return [\n typeof resolver === 'function'\n ? { provide: GenuiCatalogResolver, useClass: resolver }\n : { provide: GenuiCatalogResolver, useValue: resolver },\n ];\n}\n\n/** The sandbox and channels with the kit and theme names found ({@link GENUI_RESOLVED}). */\ninterface ResolvedGenui {\n sandbox?: boolean | DefineSandboxOptions;\n /** A kit sandbox the catalog itself defines, resolved (under its own name). */\n catalogSandbox?: DefineSandboxOptions;\n channels?: GenuiChannels;\n sandboxClient?: () => SandboxClientConfig;\n}\n\n/** What every configured sandbox (top level and channels) needs from the browser, together. */\nfunction mergeSandboxClients(clients: Array<() => SandboxClientConfig>): SandboxClientConfig {\n const merged: SandboxClientConfig = { theme: false };\n for (const client of clients) {\n const one = client();\n merged.theme ||= one.theme;\n if (one.name !== undefined && merged.kit === undefined && one.kit !== undefined)\n merged.name = one.name;\n if (one.kit !== undefined) merged.kit ??= one.kit;\n if (one.css !== undefined) merged.css ??= one.css;\n if (one.tailwind !== undefined) merged.tailwind ??= one.tailwind;\n }\n return merged;\n}\n\n/** Resolve the sandbox (top level and per channel) against the kit discovery. */\nasync function resolveGenui(options: AgentGenuiOptions): Promise<ResolvedGenui> {\n const { sandbox: asked, channels: askedChannels } = options;\n assertGenuiChannels(askedChannels);\n // A sandbox's kit (styles, components, wrapper) and theme names are found through the app's Vite output.\n const clients: Array<() => SandboxClientConfig> = [];\n const discoveries = new Map<\n string,\n import('@dudousxd/nestjs-agent-core/genui/kit').SandboxKitDiscovery\n >();\n const resolveSandbox = async (\n value: boolean | DefineSandboxOptions | undefined,\n ): Promise<boolean | DefineSandboxOptions | undefined> => {\n if (value === undefined || value === false) return value;\n // Node-only, and only with a sandbox: loaded when one is configured.\n const [{ nestSandboxKitDiscovery }, { resolveSandboxServer }] = await Promise.all([\n import('./kit.js'),\n import('@dudousxd/nestjs-agent-core/genui/kit'),\n ]);\n const kitName = value === true ? undefined : value.kitName;\n let discovery = discoveries.get(kitName ?? '');\n if (discovery === undefined) {\n discovery = nestSandboxKitDiscovery(options.sandboxKit, kitName);\n discoveries.set(kitName ?? '', discovery);\n }\n const resolved = resolveSandboxServer(value, discovery);\n clients.push(resolved.client);\n return resolved.define;\n };\n const sandbox = await resolveSandbox(asked);\n // A kit sandbox defined in the (shared) catalog itself: found the same way, and put\n // back under its own name, so the browser's copy of the catalog validates what the model writes.\n const own = options.catalog?.components.find((each) => sandboxPolicyOf(each) !== undefined) as\n | SandboxDefinition\n | undefined;\n const ownOptions =\n asked === undefined && own?.sandboxOptions !== undefined && own.sandboxView?.kit === true\n ? await resolveSandbox({ ...own.sandboxOptions, name: own.name })\n : undefined;\n let channels: GenuiChannels | undefined;\n if (askedChannels !== undefined) {\n channels = {};\n for (const [name, entry] of Object.entries(askedChannels)) {\n if (entry === undefined) continue;\n const own = await resolveSandbox(entry.sandbox);\n channels[name] = { ...entry, ...(own !== undefined ? { sandbox: own } : {}) };\n }\n }\n return {\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(typeof ownOptions === 'object' ? { catalogSandbox: ownOptions } : {}),\n ...(channels !== undefined ? { channels } : {}),\n ...(clients.length > 0 ? { sandboxClient: () => mergeSandboxClients(clients) } : {}),\n };\n}\n\nfunction perRequest(\n resolver: GenuiCatalogResolver | undefined,\n): GenuiToolsOptions['resolveCatalog'] | undefined {\n return resolver === undefined ? undefined : (scope: GenuiCatalogScope) => resolver.resolve(scope);\n}\n\nfunction toolOptions(\n options: AgentGenuiOptions,\n resolved: ResolvedGenui,\n resolver: GenuiCatalogResolver | undefined,\n): GenuiToolsOptions {\n const {\n catalog: _catalog,\n sandbox: _sandbox,\n channels: _channels,\n sandboxKit: _sandboxKit,\n ...rest\n } = options;\n const resolveCatalog = perRequest(resolver);\n return {\n ...rest,\n ...(resolved.channels !== undefined ? { channels: resolved.channels } : {}),\n ...(resolved.sandbox !== undefined ? { sandbox: resolved.sandbox } : {}),\n ...(resolveCatalog !== undefined ? { resolveCatalog } : {}),\n };\n}\n\n/** The configured catalog, with the sandbox component added when `sandbox` asks for it. */\nfunction withSandbox(options: AgentGenuiOptions, resolved: ResolvedGenui): Catalog {\n const base = options.catalog ?? defineCatalog([]);\n const { sandbox, catalogSandbox } = resolved;\n if (sandbox === undefined || sandbox === false)\n return catalogSandbox !== undefined ? base.extend([defineSandbox(catalogSandbox)]) : base;\n return base.extend([defineSandbox(sandbox === true ? {} : sandbox)]);\n}\n\nfunction coreProviders(resolver: ResolverOption | undefined): Provider[] {\n return [\n {\n provide: GENUI_RESOLVED,\n useFactory: (options: AgentGenuiOptions) => resolveGenui(options),\n inject: [GENUI_OPTIONS],\n },\n {\n provide: GENUI_CATALOG,\n useFactory: (options: AgentGenuiOptions, resolved: ResolvedGenui) =>\n withSandbox(options, resolved),\n inject: [GENUI_OPTIONS, GENUI_RESOLVED],\n },\n {\n provide: AGENT_GENUI,\n useFactory: (\n options: AgentGenuiOptions,\n catalog: Catalog,\n resolved: ResolvedGenui,\n resolverInstance?: GenuiCatalogResolver,\n ) =>\n new AgentGenui(\n catalog,\n perRequest(resolverInstance),\n resolved.channels,\n {\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n ...(options.streaming !== undefined ? { streaming: options.streaming } : {}),\n ...(resolved.sandbox !== undefined ? { sandbox: resolved.sandbox } : {}),\n },\n resolved.sandboxClient,\n ),\n inject: [\n GENUI_OPTIONS,\n GENUI_CATALOG,\n GENUI_RESOLVED,\n { token: GenuiCatalogResolver, optional: true },\n ],\n },\n ...resolverProviders(resolver),\n // The generated tools, registered by the agent module's discovery like any `provideAgentTool`.\n // Built from the injected catalog, so `overrideProvider(GENUI_CATALOG)` changes them too.\n provideAgentTools(\n (\n options: AgentGenuiOptions,\n catalog: Catalog,\n resolved: ResolvedGenui,\n perRequestResolver?: GenuiCatalogResolver,\n ) => genuiTools(catalog, toolOptions(options, resolved, perRequestResolver)),\n [\n GENUI_OPTIONS,\n GENUI_CATALOG,\n GENUI_RESOLVED,\n { token: GenuiCatalogResolver, optional: true },\n ],\n ),\n ];\n}\n\nconst EXPORTS = [GENUI_CATALOG, GENUI_OPTIONS, AGENT_GENUI];\n\n/**\n * Generative UI for the agent: registers the tools that let the model push catalog components\n * (one `ui__render` tree tool, or `ui__show_<component>` per component, and/or the generic\n * `ui__show`), and makes the catalog\n * injectable. Global, like `AgentModule`; import it once, next to it.\n *\n * ```ts\n * AgentGenuiModule.forRoot({ catalog, mode: 'tree', terminal: true })\n * ```\n */\n@Module({})\nexport class AgentGenuiModule {\n static forRoot(options: AgentGenuiModuleOptions = {}): DynamicModule {\n const { resolver, ...rest } = options;\n return {\n module: AgentGenuiModule,\n global: true,\n providers: [{ provide: GENUI_OPTIONS, useValue: rest }, ...coreProviders(resolver)],\n exports: resolver === undefined ? EXPORTS : [...EXPORTS, GenuiCatalogResolver],\n };\n }\n\n static forRootAsync(options: AgentGenuiModuleAsyncOptions): DynamicModule {\n return {\n module: AgentGenuiModule,\n global: true,\n imports: options.imports ?? [],\n providers: [\n { provide: GENUI_OPTIONS, useFactory: options.useFactory, inject: options.inject ?? [] },\n ...coreProviders(options.resolver),\n ],\n exports: options.resolver === undefined ? EXPORTS : [...EXPORTS, GenuiCatalogResolver],\n };\n }\n}\n","import {\n type FunctionalToolDefinition,\n type ToolHandler,\n type ToolSpec,\n createFunctionalTool,\n} from '@dudousxd/nestjs-agent-core';\nimport type { FactoryProvider, Provider } from '@nestjs/common';\n\n/**\n * Brand stamped onto a functional-tool provider instance so `AiToolDiscoveryService` picks it up\n * when it walks every provider at boot — the declarative alternative to a manual `registry.register`.\n */\nexport const AGENT_TOOL_BRAND = Symbol.for('@dudousxd/nestjs-agent:functional-tool');\n\n/** A tool expressed as data + handler (e.g. from `createExecuteSqlTool`), not an `@AiTool` class. */\nexport interface FunctionalTool {\n spec: ToolSpec;\n handler: ToolHandler;\n}\n\n/** A {@link FunctionalTool} carrying {@link AGENT_TOOL_BRAND} — what a provider resolves to. */\nexport interface BrandedFunctionalTool extends FunctionalTool {\n readonly [AGENT_TOOL_BRAND]: true;\n}\n\nfunction brand(tool: FunctionalTool): BrandedFunctionalTool {\n return { [AGENT_TOOL_BRAND]: true, spec: tool.spec, handler: tool.handler };\n}\n\n/** Narrows a provider instance to a branded functional tool for boot-time registration. */\nexport function isBrandedFunctionalTool(value: object): value is BrandedFunctionalTool {\n return AGENT_TOOL_BRAND in value && 'spec' in value && 'handler' in value;\n}\n\n/**\n * Registers a functional tool declaratively — drop the returned provider in a module's `providers`\n * and `AiToolDiscoveryService` auto-registers it at boot. Each call uses a fresh, unique provide\n * token so the same tool can be provided many times without collisions.\n *\n * Two forms: a static tool (`useValue`) or a factory with `inject` for DI-resolved dependencies\n * (`useFactory`). Either way the resolved instance is branded with {@link AGENT_TOOL_BRAND}.\n */\nexport function provideAgentTool(tool: FunctionalTool): Provider;\nexport function provideAgentTool(\n factory: (...deps: never[]) => FunctionalTool,\n inject?: FactoryProvider['inject'],\n): Provider;\nexport function provideAgentTool(\n factoryOrTool: FunctionalTool | ((...deps: never[]) => FunctionalTool),\n inject?: FactoryProvider['inject'],\n): Provider {\n const provide = Symbol('nestjs-agent:functional-tool-instance');\n if (typeof factoryOrTool === 'function') {\n return {\n provide,\n useFactory: (...deps: never[]) => brand(factoryOrTool(...deps)),\n inject: inject ?? [],\n };\n }\n return { provide, useValue: brand(factoryOrTool) };\n}\n\n/**\n * Registers a LIST of functional tools from one factory — for a producer whose tool count is only\n * known once its dependencies resolve (a catalog loaded from config, one tool per entry). The\n * factory's result is branded element by element; `AiToolDiscoveryService` registers each.\n */\nexport function provideAgentTools(\n factory: (...deps: never[]) => readonly FunctionalTool[] | Promise<readonly FunctionalTool[]>,\n inject?: FactoryProvider['inject'],\n): Provider {\n return {\n provide: Symbol('nestjs-agent:functional-tool-list'),\n useFactory: async (...deps: never[]) => (await factory(...deps)).map(brand),\n inject: inject ?? [],\n };\n}\n\n/** Author a functional tool with inferred Standard Schema input and domain output. */\nexport const defineTool = createFunctionalTool;\nexport type { FunctionalToolDefinition };\n","import type {\n Catalog,\n GenuiCatalogScope,\n GenuiChannelBase,\n GenuiChannels,\n SandboxClientConfig,\n} from '@dudousxd/nestjs-agent-core/genui';\n\n/**\n * The app's genui setup ({@link AgentGenui}): the catalog, the per-channel options and what the\n * sandbox renderer is told — what the text channels (`@dudousxd/nestjs-agent-channels`) and\n * `GET <base>/config` read.\n */\nexport const AGENT_GENUI = Symbol.for('@dudousxd/nestjs-agent:genui');\n\n/**\n * The app's genui setup, bound to {@link AGENT_GENUI}: what a text channel draws with\n * (`catalog`, `channels`, `base`) and what the sandbox renderer is told (`sandboxClient`).\n */\nexport class AgentGenui {\n constructor(\n readonly catalog: Catalog,\n readonly resolveCatalog?: (scope: GenuiCatalogScope) => Catalog | Promise<Catalog>,\n /** `AgentGenuiModule.forRoot({ channels })`, when configured. */\n readonly channels?: GenuiChannels,\n /** The top-level options a channel falls back to. */\n readonly base: GenuiChannelBase = {},\n /** What the sandbox renderer is told, when a sandbox is configured. */\n readonly sandboxClient?: () => SandboxClientConfig,\n ) {}\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,SAIEA,wBACAC,2BACAC,0BACAC,mCACK;AAxBP,IA+BaC;AA/Bb;;;AA+BO,IAAMA,8BAA8B;;;;;AC/B3C;;;;;AAMA,SAASC,eAAe;AACxB,SAEEC,0BACAC,2BACK;AAcA,SAASC,wBACdC,UAAuC,CAAC,GACxCC,MAAa;AAEb,QAAMC,WAAWF,QAAQE,YAAYC;AACrC,SAAOL,oBAAoB;IACzBM,MAAMR,QAAQI,QAAQI,QAAQC,QAAQC,IAAG,CAAA;IACzC,GAAIL,SAASM,SAAY;MAAEN;IAAK,IAAI,CAAC;IACrCO,YAAYX,yBAAyBG,QAAQQ,cAAcC,6BAA6BR,IAAAA;IACxF,GAAIC,aAAa,QAAQ;MAAEA,UAAU;QAAEQ,MAAMR,SAASQ;QAAMC,QAAQT,SAASS;MAAO;IAAE,IAAI,CAAC;IAC3F,GAAIX,QAAQY,WAAWL,SAAY;MAAEK,QAAQZ,QAAQY;IAAO,IAAI,CAAC;IACjE,GAAIZ,QAAQa,WAAWN,SAAY;MAAEM,QAAQb,QAAQa;IAAO,IAAI,CAAC;IACjE,GAAIb,QAAQc,gBAAgBP,SAAY;MAAEO,aAAad,QAAQc;IAAY,IAAI,CAAC;IAChF,GAAId,QAAQe,eAAeR,SAAY;MAAEQ,YAAYf,QAAQe;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AKiB,KAAKzC,IAAAA;IAC/B;EACF;;WAdU4G,IAAAA,oBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBjC,SAAO;IAAE5D,MAAM;IAAQiE,aAAa;MAACF;;EAAgB;AACvD;AAzCgBJ;","names":["SANDBOX_KIT_DEV_PREFIX","SANDBOX_KIT_MANIFEST_KEYS","SANDBOX_KIT_UPDATE_EVENT","createGenuiSandboxKitPlugin","NEST_SANDBOX_KIT_DESCRIPTOR","resolve","sandboxKitDescriptorPath","sandboxKitDiscovery","nestSandboxKitDiscovery","options","name","manifest","NEST_SANDBOX_KIT_MANIFEST","root","process","cwd","undefined","descriptor","NEST_SANDBOX_KIT_DESCRIPTOR","file","outDir","kitUrl","cssUrl","tailwindUrl","production","Object","freeze","AGENT_ACTOR_RESOLVER","A2UI_APPROVE_ACTION","A2UI_REJECT_ACTION","A2uiProjector","a2uiThreadReplay","negotiateA2uiCatalog","readA2uiAction","readA2uiClientCapabilities","agUiEvents","agUiFramesFromNdjson","decodeInterruptId","uiActionText","validateUiCapabilities","BadRequestException","Body","Controller","ForbiddenException","Get","HttpCode","Inject","Optional","Param","Post","Query","Req","Res","AGENT_SERVICE","Symbol","for","readerGone","res","controller","AbortController","once","abort","signal","assertGenuiChannels","defineCatalog","defineSandbox","genuiTools","sandboxPolicyOf","Inject","Module","createFunctionalTool","AGENT_TOOL_BRAND","Symbol","for","brand","tool","spec","handler","provideAgentTools","factory","inject","provide","Symbol","useFactory","deps","map","brand","AGENT_GENUI","Symbol","for","AgentGenui","catalog","resolveCatalog","channels","base","sandboxClient","GENUI_CATALOG","Symbol","for","GENUI_OPTIONS","GENUI_RESOLVED","GenuiCatalogResolver","resolverProviders","resolver","undefined","provide","useClass","useValue","mergeSandboxClients","clients","merged","theme","client","one","name","kit","css","tailwind","resolveGenui","options","sandbox","asked","channels","askedChannels","assertGenuiChannels","discoveries","Map","resolveSandbox","value","nestSandboxKitDiscovery","resolveSandboxServer","Promise","all","kitName","discovery","get","sandboxKit","set","resolved","push","define","own","catalog","components","find","each","sandboxPolicyOf","ownOptions","sandboxOptions","sandboxView","entry","Object","entries","catalogSandbox","length","sandboxClient","perRequest","scope","resolve","toolOptions","_catalog","_sandbox","_channels","_sandboxKit","rest","resolveCatalog","withSandbox","base","defineCatalog","extend","defineSandbox","coreProviders","GENUI_RESOLVED","useFactory","inject","GENUI_OPTIONS","GENUI_CATALOG","AGENT_GENUI","resolverInstance","AgentGenui","mode","streaming","token","optional","provideAgentTools","perRequestResolver","genuiTools","EXPORTS","AgentGenuiModule","forRoot","module","global","providers","exports","forRootAsync","imports","A2UI_VIA","isRecord","value","Array","isArray","invalid","code","message","BadRequestException","statusCode","bodyField","body","key","undefined","metadata","readDataModel","raw","maxBytes","surfaces","size","TextEncoder","encode","JSON","stringify","length","Object","keys","A2uiRunHandler","agent","actorResolver","projection","quietMs","maxActionBytes","maxDataModelBytes","replay","req","threadId","catalog","actor","resolve","owner","threadOwner","entries","thread","getThread","supported","filter","id","a2uiThreadReplay","messages","negotiateA2uiCatalog","handle","res","agentName","readA2uiClientCapabilities","dataModel","action","read","readA2uiAction","name","A2UI_APPROVE_ACTION","A2UI_REJECT_ACTION","interruptId","context","address","decodeInterruptId","kind","proposalId","decided","decideActionProposal","decision","via","writeHead","projector","A2uiProjector","messageId","event","type","role","delta","text","project","write","end","assertResumable","stream","checkDecision","toolCallId","approve","reject","skip","position","answered","uiActionText","trim","ForbiddenException","uiCapabilities","hasOwn","validateUiCapabilities","error","started","chat","newThreadId","pageContext","a2uiDataModel","runId","extra","status","setHeader","flushHeaders","options","frames","agUiFramesFromNdjson","subscribe","readerGone","agUiEvents","streamRunId","streamThreadId","a2uiAdapter","path","replace","_path","A2uiController","run","controllers"]}
1
+ {"version":3,"sources":["../../src/vite/index.ts","../../src/genui/kit.ts","../../src/a2ui/index.ts","../../src/a2ui/a2ui.adapter.ts","../../src/agent-service.token.ts","../../src/controller/reader-gone.ts","../../src/genui/agent-genui.module.ts","../../src/functional-tool.ts","../../src/genui/agent-genui.token.ts"],"sourcesContent":["/**\n * `@dudousxd/nestjs-agent/vite` — `genuiSandboxKit()`, the Vite plugin that puts the app's design\n * system (its styles, its components, its providers) inside the sandbox, whatever the stack:\n *\n * ```ts\n * // vite.config.ts (the SPA that talks to the agent)\n * import { genuiSandboxKit } from '@dudousxd/nestjs-agent/vite'\n * export default defineConfig({\n * plugins: [react(), genuiSandboxKit({ styles: 'src/index.css', components: 'src/components/ui' })],\n * })\n * ```\n *\n * Then `AgentGenuiModule.forRoot({ sandbox: { kit: true } })` finds what it built: the descriptor\n * the dev server writes (`.genui/sandbox-kit.json`) in dev, the Vite manifest in production (see\n * `AgentGenuiOptions.sandboxKit`).\n */\nimport {\n type GenuiSandboxKitApi,\n type GenuiSandboxKitOptions,\n type GenuiSandboxKitPlugin,\n SANDBOX_KIT_DEV_PREFIX,\n SANDBOX_KIT_MANIFEST_KEYS,\n SANDBOX_KIT_UPDATE_EVENT,\n createGenuiSandboxKitPlugin,\n} from '@dudousxd/nestjs-agent-core/genui/kit';\n\n/**\n * Where the dev descriptor is written, relative to the Vite root — and where the server reads it,\n * relative to its working directory (run both from the project root, or point\n * `sandboxKit.descriptor` at it). Add `.genui/` to `.gitignore`.\n */\nexport const NEST_SANDBOX_KIT_DESCRIPTOR = '.genui/sandbox-kit.json';\n\n/**\n * The sandbox kit plugin: `styles` (the app's style entries — default, the stylesheets among its\n * Vite entrypoints or `index.html`), `components` (modules or globs exporting React components —\n * default, the first `components/ui` folder), `wrapper` (a module whose default export wraps the\n * model's App). See {@link GenuiSandboxKitOptions}.\n */\nexport function genuiSandboxKit(options: GenuiSandboxKitOptions = {}): GenuiSandboxKitPlugin {\n return createGenuiSandboxKitPlugin(options, {\n descriptor: NEST_SANDBOX_KIT_DESCRIPTOR,\n rendererImport: /@dudousxd\\/nestjs-agent-react/,\n });\n}\n\nexport {\n type GenuiSandboxKitApi,\n type GenuiSandboxKitOptions,\n type GenuiSandboxKitPlugin,\n SANDBOX_KIT_DEV_PREFIX,\n SANDBOX_KIT_MANIFEST_KEYS,\n SANDBOX_KIT_UPDATE_EVENT,\n};\n","/**\n * The sandbox kit in a Nest app. No Vite runs in the Nest process, so the kit is found in files:\n * the descriptor `genuiSandboxKit()` (`@dudousxd/nestjs-agent/vite`) writes while the dev server\n * runs, and in production the Vite manifest the build wrote (`genui-sandbox-kit.json` and the assets\n * it names). Node-only: loaded by {@link AgentGenuiModule} only when a sandbox is configured.\n */\nimport { resolve } from 'node:path';\nimport {\n type SandboxKitDiscovery,\n sandboxKitDescriptorPath,\n sandboxKitDiscovery,\n} from '@dudousxd/nestjs-agent-core/genui/kit';\nimport { NEST_SANDBOX_KIT_DESCRIPTOR } from '../vite/index.js';\nimport type { AgentGenuiSandboxKitOptions } from './agent-genui.module.js';\n\n/** Where the production Vite manifest is looked for by default, and the directory it is relative to. */\nexport const NEST_SANDBOX_KIT_MANIFEST = Object.freeze({\n file: 'public/.vite/manifest.json',\n outDir: 'public',\n});\n\n/**\n * Find the kit for `AgentGenuiModule.forRoot({ sandbox: { kit: true } })` — a named kit's\n * (`genuiSandboxKit({ name })`, `sandbox: { kit: true, kitName }`) with `name`.\n */\nexport function nestSandboxKitDiscovery(\n options: AgentGenuiSandboxKitOptions = {},\n name?: string,\n): SandboxKitDiscovery {\n const manifest = options.manifest ?? NEST_SANDBOX_KIT_MANIFEST;\n return sandboxKitDiscovery({\n root: resolve(options.root ?? process.cwd()),\n ...(name !== undefined ? { name } : {}),\n descriptor: sandboxKitDescriptorPath(options.descriptor ?? NEST_SANDBOX_KIT_DESCRIPTOR, name),\n ...(manifest !== false ? { manifest: { file: manifest.file, outDir: manifest.outDir } } : {}),\n ...(options.kitUrl !== undefined ? { kitUrl: options.kitUrl } : {}),\n ...(options.cssUrl !== undefined ? { cssUrl: options.cssUrl } : {}),\n ...(options.tailwindUrl !== undefined ? { tailwindUrl: options.tailwindUrl } : {}),\n ...(options.production !== undefined ? { production: options.production } : {}),\n });\n}\n","/**\n * `@dudousxd/nestjs-agent/a2ui` — A2UI (https://a2ui.org, v0.9) for the agent: the `a2uiAdapter()`\n * route (JSON Lines of A2UI messages), and the framework-free pieces it is built from (re-exported\n * from `@dudousxd/nestjs-agent-core/a2ui`) — the `ui` frame → A2UI converter, the builtin →\n * basic-catalog mappings, the catalog export, the inbound action reader. For A2UI over AG-UI, pass\n * `a2ui: true` to `agUiAdapter()`.\n */\n\nexport * from '@dudousxd/nestjs-agent-core/a2ui';\nexport { type A2uiAdapterOptions, A2uiRunHandler, a2uiAdapter } from './a2ui.adapter.js';\n","import { AGENT_ACTOR_RESOLVER, type ActorResolver, CanAnyone } from '@dudousxd/nestjs-agent-core';\nimport {\n A2UI_APPROVE_ACTION,\n A2UI_REJECT_ACTION,\n A2uiProjector,\n type A2uiServerMessage,\n type A2uiStreamOptions,\n a2uiThreadReplay,\n negotiateA2uiCatalog,\n readA2uiAction,\n readA2uiClientCapabilities,\n} from '@dudousxd/nestjs-agent-core/a2ui';\nimport {\n agUiEvents,\n agUiFramesFromNdjson,\n decodeInterruptId,\n} from '@dudousxd/nestjs-agent-core/ag-ui';\nimport {\n type Catalog,\n type UiAction,\n type UiCapabilities,\n uiActionText,\n validateUiCapabilities,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n BadRequestException,\n Body,\n Controller,\n ForbiddenException,\n Get,\n HttpCode,\n Inject,\n Optional,\n Param,\n Post,\n Query,\n Req,\n Res,\n} from '@nestjs/common';\nimport type { Request, Response } from 'express';\nimport { AGENT_SERVICE } from '../agent-service.token.js';\nimport type { AgentService } from '../agent.service.js';\nimport { readerGone } from '../controller/reader-gone.js';\nimport { GENUI_CATALOG } from '../genui/agent-genui.module.js';\nimport type { AgentProtocolAdapter } from '../protocol-adapter.js';\n\nexport interface A2uiAdapterOptions extends A2uiStreamOptions {\n /** Where the route mounts, under the agent's path. Default `'a2ui'` → `POST <path>/a2ui`. */\n path?: string;\n /** As `agUiAdapter`'s: how long a run waiting on a person may stay silent before the stream ends. */\n quietMs?: number;\n /** Largest action accepted, as JSON, in bytes. Default 8192. */\n maxActionBytes?: number;\n /** Largest `a2uiClientDataModel` accepted, as JSON, in bytes. Default 32768. */\n maxDataModelBytes?: number;\n}\n\n/** The surface an A2UI decision is recorded as having come through. */\nconst A2UI_VIA = 'a2ui';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction invalid(code: string, message: string): BadRequestException {\n return new BadRequestException({ statusCode: 400, code, message });\n}\n\n/** A field of the body, or of its A2A-style `metadata` (where A2UI puts client capabilities). */\nfunction bodyField(body: Record<string, unknown>, key: string): unknown {\n if (body[key] !== undefined) return body[key];\n return isRecord(body.metadata) ? body.metadata[key] : undefined;\n}\n\n/** `a2uiClientDataModel` (`{ version, surfaces: { <surfaceId>: model } }`): its surfaces, or why not. */\nfunction readDataModel(\n raw: unknown,\n maxBytes: number,\n): Record<string, unknown> | undefined | string {\n if (raw === undefined) return undefined;\n if (!isRecord(raw) || !isRecord(raw.surfaces)) {\n return 'a2uiClientDataModel carries { version, surfaces }';\n }\n let size: number;\n try {\n size = new TextEncoder().encode(JSON.stringify(raw.surfaces)).length;\n } catch {\n return 'a2uiClientDataModel must be JSON';\n }\n if (size > maxBytes) {\n return `a2uiClientDataModel may be at most ${maxBytes} bytes (this one is ${size})`;\n }\n return Object.keys(raw.surfaces).length > 0 ? raw.surfaces : undefined;\n}\n\n/**\n * Serves the agent as an A2UI agent. Not mounted directly — {@link a2uiAdapter} mounts a subclass at\n * the configured path — but exported so a host can extend it under a route of its own.\n */\nexport class A2uiRunHandler {\n constructor(\n protected readonly agent: AgentService,\n protected readonly actorResolver: ActorResolver,\n protected readonly projection: A2uiStreamOptions,\n protected readonly quietMs: number | undefined,\n protected readonly maxActionBytes: number | undefined,\n protected readonly maxDataModelBytes: number | undefined = undefined,\n ) {}\n\n /**\n * `GET <path>/a2ui/threads/:threadId`: a stored thread as `{ threadId, entries }`\n * (`a2uiThreadReplay`) — what a client draws again after a reload. Owner-scoped; a thread nobody\n * has answers `{ entries: [] }`. `?catalog=<id>` names the client's basic catalog id.\n */\n async replay(\n req: Request,\n threadId: string,\n catalog: unknown,\n ): Promise<{ threadId: string; entries: ReturnType<typeof a2uiThreadReplay> }> {\n const actor = await this.actorResolver.resolve(req);\n const owner = await this.agent.threadOwner(threadId);\n if (owner === null) return { threadId, entries: [] };\n const thread = await this.agent.getThread(actor, threadId);\n const supported =\n typeof catalog === 'string'\n ? [catalog]\n : Array.isArray(catalog)\n ? catalog.filter((id): id is string => typeof id === 'string')\n : undefined;\n return {\n threadId,\n entries: a2uiThreadReplay(\n thread?.messages ?? [],\n negotiateA2uiCatalog(this.projection, supported),\n ),\n };\n }\n\n async handle(req: Request, res: Response, raw: unknown): Promise<void> {\n const body = isRecord(raw) ? raw : {};\n const agentName =\n typeof body.agent === 'string' && body.agent.length > 0 ? body.agent : undefined;\n const actor = await this.actorResolver.resolve(req);\n // The basic catalog under the id this client advertises (`a2uiClientCapabilities`).\n const projection = negotiateA2uiCatalog(\n this.projection,\n readA2uiClientCapabilities(bodyField(body, 'a2uiClientCapabilities')),\n );\n const dataModel = readDataModel(\n bodyField(body, 'a2uiClientDataModel'),\n this.maxDataModelBytes ?? 32768,\n );\n if (typeof dataModel === 'string') throw invalid('invalid_data_model', dataModel);\n\n let action: UiAction | undefined;\n if (body.action !== undefined) {\n const read = isRecord(body.action)\n ? readA2uiAction(body.action, {\n ...(this.maxActionBytes !== undefined ? { maxBytes: this.maxActionBytes } : {}),\n })\n : 'action must be an A2UI action message';\n if (typeof read === 'string') throw invalid('invalid_action', read);\n action = read;\n }\n\n // Deciding the approval a stream ended on: settle it, then stream the rest of the run.\n if (action?.name === A2UI_APPROVE_ACTION || action?.name === A2UI_REJECT_ACTION) {\n const interruptId = action.context.interruptId;\n const address = typeof interruptId === 'string' ? decodeInterruptId(interruptId) : undefined;\n if (address === undefined || address === null || address.kind === 'elicitation') {\n throw invalid('invalid_action', 'an approval action carries the interruptId it decides');\n }\n // An independent proposal: decided through the proposal service (its own run is not\n // waiting), as an AG-UI resume decides it, and answered with the configured reply.\n if (address.kind === 'proposal') {\n if (address.proposalId === undefined || address.threadId === undefined) {\n throw invalid('invalid_action', 'the interruptId names no proposal');\n }\n const decided = await this.agent.decideActionProposal(\n actor,\n address.threadId,\n address.proposalId,\n {\n decision: action.name === A2UI_APPROVE_ACTION ? 'approved' : 'rejected',\n via: A2UI_VIA,\n },\n );\n this.writeHead(res, { 'X-Agent-Thread-Id': address.threadId });\n const projector = new A2uiProjector(projection);\n const messageId = `proposal-${address.proposalId}`;\n for (const event of [\n { type: 'TEXT_MESSAGE_START' as const, messageId, role: 'assistant' as const },\n { type: 'TEXT_MESSAGE_CONTENT' as const, messageId, delta: decided.text },\n ]) {\n for (const message of projector.project(event)) res.write(`${JSON.stringify(message)}\\n`);\n }\n res.end();\n return;\n }\n // The same checks an AG-UI resume makes: the run is the actor's and still waiting, and the\n // actor may decide this call.\n await this.agent.assertResumable(actor, address.stream);\n await this.agent.checkDecision(actor, address.toolCallId);\n if (action.name === A2UI_APPROVE_ACTION) {\n await this.agent.approve(actor, address.toolCallId, { via: A2UI_VIA });\n } else {\n await this.agent.reject(actor, address.toolCallId, undefined, { via: A2UI_VIA });\n }\n await this.stream(res, address.stream, {\n skip: address.position,\n answered: [address.toolCallId],\n projection,\n });\n return;\n }\n\n const message = typeof body.message === 'string' ? body.message : '';\n const text = action !== undefined ? uiActionText(action) : message;\n if (text.trim().length === 0) {\n throw invalid('no_user_message', 'send a message or an action');\n }\n const threadId =\n typeof body.threadId === 'string' && body.threadId.length > 0 ? body.threadId : undefined;\n const owner = threadId !== undefined ? await this.agent.threadOwner(threadId) : null;\n if (owner !== null && owner !== actor.id) {\n throw new ForbiddenException('thread belongs to another actor');\n }\n let uiCapabilities: UiCapabilities | undefined;\n if (Object.hasOwn(body, 'uiCapabilities')) {\n try {\n uiCapabilities = validateUiCapabilities(body.uiCapabilities);\n } catch (error) {\n throw invalid('invalid_input', (error as Error).message);\n }\n }\n const started = await this.agent.chat({\n actor,\n message: text,\n ...(threadId === undefined ? {} : owner !== null ? { threadId } : { newThreadId: threadId }),\n ...(agentName !== undefined ? { agentName } : {}),\n ...(uiCapabilities !== undefined ? { uiCapabilities } : {}),\n ...(dataModel !== undefined ? { pageContext: { a2uiDataModel: dataModel } } : {}),\n });\n await this.stream(res, started.runId, { threadId: started.threadId, projection });\n }\n\n /** Open the JSON Lines response. */\n protected writeHead(res: Response, extra: Record<string, string>): void {\n res.status(200);\n res.setHeader('Content-Type', 'application/jsonl; charset=utf-8');\n res.setHeader('Cache-Control', 'no-cache, no-transform');\n res.setHeader('Connection', 'keep-alive');\n res.setHeader('X-Accel-Buffering', 'no');\n for (const [name, value] of Object.entries(extra)) res.setHeader(name, value);\n res.flushHeaders();\n }\n\n /** Write one run as A2UI JSON Lines, until it ends or stops to ask. */\n protected async stream(\n res: Response,\n runId: string,\n options: {\n threadId?: string;\n skip?: number;\n answered?: string[];\n projection?: A2uiStreamOptions;\n },\n ): Promise<void> {\n this.writeHead(res, {\n 'X-Agent-Run-Id': runId,\n ...(options.threadId !== undefined ? { 'X-Agent-Thread-Id': options.threadId } : {}),\n });\n const projector = new A2uiProjector(options.projection ?? this.projection);\n const write = (messages: A2uiServerMessage[]) => {\n for (const message of messages) res.write(`${JSON.stringify(message)}\\n`);\n };\n try {\n const frames = agUiFramesFromNdjson(this.agent.subscribe(runId, readerGone(res)));\n for await (const event of agUiEvents(frames, {\n threadId: options.threadId ?? runId,\n runId,\n streamRunId: runId,\n ...(options.threadId !== undefined ? { streamThreadId: options.threadId } : {}),\n ...(options.skip !== undefined ? { skip: options.skip } : {}),\n ...(options.answered !== undefined ? { answered: options.answered } : {}),\n ...(this.quietMs !== undefined ? { quietMs: this.quietMs } : {}),\n })) {\n write(projector.project(event));\n }\n } catch {\n write(projector.project({ type: 'RUN_ERROR', message: 'The run could not be followed.' }));\n }\n res.end();\n }\n}\n\n/**\n * Serve the agent as an A2UI (https://a2ui.org, v0.9) agent: `POST <path>/a2ui` answers with the\n * run as a JSON Lines stream of A2UI server-to-client messages — `createSurface`,\n * `updateComponents`, `updateDataModel`, `deleteSurface` — that any A2UI renderer draws.\n *\n * ```ts\n * import { a2uiAdapter } from '@dudousxd/nestjs-agent/a2ui'\n *\n * AgentModule.forRoot({ model, adapters: [a2uiAdapter()] })\n * ```\n *\n * The body is `{ threadId?, message?, action?, uiCapabilities?, a2uiClientCapabilities?,\n * a2uiClientDataModel?, agent? }` (the two A2UI fields also read from `metadata`, A2A-style):\n * - `message` — the user's text;\n * - `action` — an A2UI client message (`{ version: 'v0.9', action: { name, surfaceId,\n * sourceComponentId, timestamp, context } }`, or v0.8's `{ userAction }`): it becomes the turn\n * (`uiActionText`). `agora.approve` / `agora.reject` with `context.interruptId` decide the\n * approval a previous stream ended on, and stream the rest of that run (an independent\n * proposal is decided through the proposal service and answered with its reply);\n * - `threadId` — continue that thread (its owner is checked), or start one under that id;\n * - `a2uiClientCapabilities` — the catalogs the client draws (`{ 'v0.9': { supportedCatalogIds } }`,\n * what `MessageProcessor.getRendererCapabilities()` builds): the basic catalog is sent under the\n * id the client lists for it;\n * - `a2uiClientDataModel` — the data models of surfaces created with `sendDataModel`, handed to the\n * prompt builder as `pageContext.a2uiDataModel`.\n *\n * `GET <path>/a2ui/threads/:threadId` answers a stored thread as `{ threadId, entries }`\n * (`a2uiThreadReplay`): what a client draws again after a reload.\n *\n * Response headers name the library's ids: `X-Agent-Thread-Id`, `X-Agent-Run-Id`. Authenticated by\n * the module's `actorResolver`, guarded by its `guards` and owner-scoped exactly as `chat` is.\n * Components nothing maps are drawn as their text, from the `AgentGenuiModule` catalog when there\n * is one (or `catalog` here).\n */\nexport function a2uiAdapter(options: A2uiAdapterOptions = {}): AgentProtocolAdapter {\n const path = (options.path ?? 'a2ui').replace(/^\\/+|\\/+$/g, '');\n const { path: _path, quietMs, maxActionBytes, maxDataModelBytes, ...projection } = options;\n\n @CanAnyone()\n @Controller()\n class A2uiController extends A2uiRunHandler {\n constructor(\n // Tokens, never classes: this entry is its own bundle (see AGENT_SERVICE).\n @Inject(AGENT_SERVICE) agent: AgentService,\n @Inject(AGENT_ACTOR_RESOLVER) actorResolver: ActorResolver,\n @Optional() @Inject(GENUI_CATALOG) catalog?: Catalog,\n ) {\n super(\n agent,\n actorResolver,\n projection.catalog === undefined && catalog !== undefined\n ? { ...projection, catalog }\n : projection,\n quietMs,\n maxActionBytes,\n maxDataModelBytes,\n );\n }\n\n @Get(`${path}/threads/:threadId`)\n thread(\n @Req() req: Request,\n @Param('threadId') threadId: string,\n @Query('catalog') catalog: unknown,\n ): ReturnType<A2uiRunHandler['replay']> {\n return this.replay(req, threadId, catalog);\n }\n\n @Post(path)\n @HttpCode(200)\n run(@Req() req: Request, @Res() res: Response, @Body() body: unknown): Promise<void> {\n return this.handle(req, res, body);\n }\n }\n\n return { name: 'a2ui', controllers: [A2uiController] };\n}\n","/**\n * `AgentService`, as the controllers of a secondary entry (`@dudousxd/nestjs-agent/a2ui`) ask for it.\n *\n * A token rather than the class: every entry is its own bundle with its own copy of every class it\n * imports, so the class used as an injection token there is not the one `AgentModule` provides.\n * `Symbol.for` is the same value in every bundle.\n */\nexport const AGENT_SERVICE = Symbol.for('@dudousxd/nestjs-agent:agent-service');\n","import type { Response } from 'express';\n\n/**\n * Subscribe options that abort once the response's connection closes — the reader went away, or\n * the response finished (when aborting has nothing left to stop).\n */\nexport function readerGone(res: Response): { signal: AbortSignal } {\n const controller = new AbortController();\n res.once('close', () => controller.abort());\n return { signal: controller.signal };\n}\n","import type { ToolPresentation } from '@dudousxd/nestjs-agent-core';\nimport type {\n Catalog,\n GenuiCan,\n GenuiCatalogScope,\n GenuiChannels,\n GenuiStreaming,\n GenuiTelemetryOptions,\n GenuiToolsOptions,\n SandboxClientConfig,\n TreeLimits,\n TreeSchemaMode,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n type DefineSandboxOptions,\n type SandboxDefinition,\n assertGenuiChannels,\n defineCatalog,\n defineSandbox,\n genuiTools,\n sandboxPolicyOf,\n} from '@dudousxd/nestjs-agent-core/genui';\nimport {\n type DynamicModule,\n type FactoryProvider,\n Inject,\n Module,\n type ModuleMetadata,\n type Provider,\n type Type,\n} from '@nestjs/common';\nimport { provideAgentTools } from '../functional-tool.js';\nimport { AGENT_GENUI, AgentGenui } from './agent-genui.token.js';\n\nexport { AGENT_GENUI, AgentGenui } from './agent-genui.token.js';\n\n/** The app's genui catalog — `@InjectGenuiCatalog()` it anywhere; `overrideProvider` it in tests. */\nexport const GENUI_CATALOG = Symbol.for('@dudousxd/nestjs-agent:genui-catalog');\n\n/** The resolved {@link AgentGenuiOptions} (without the resolver). */\nexport const GENUI_OPTIONS = Symbol.for('@dudousxd/nestjs-agent:genui-options');\n\n/** The sandbox and channels as boot resolved them (kit, Tailwind and theme found). Internal. */\nconst GENUI_RESOLVED = Symbol.for('@dudousxd/nestjs-agent:genui-resolved');\n\n/** Inject the app's genui catalog ({@link GENUI_CATALOG}). */\nexport const InjectGenuiCatalog = (): ParameterDecorator & PropertyDecorator =>\n Inject(GENUI_CATALOG);\n\n/**\n * Picks the catalog for ONE request — a tenant's own, versioned components. Consulted when a genui\n * call is validated and when the turn's tool list is described to the model, so components can\n * change without rebuilding tools at boot. Cache in here if resolving costs a round trip: it runs\n * once per turn per genui tool, and once per call.\n *\n * Provide it through `AgentGenuiModule.forRoot({ resolver })` (a class, resolved with DI, or an\n * instance); it is then injectable, and replaceable in a test with\n * `overrideProvider(GenuiCatalogResolver)`.\n */\nexport abstract class GenuiCatalogResolver {\n abstract resolve(scope: GenuiCatalogScope): Catalog | Promise<Catalog>;\n}\n\n/** What {@link AgentGenuiModule} builds tools from. */\nexport interface AgentGenuiOptions {\n /**\n * The catalog. With a {@link GenuiCatalogResolver} it is the boot-time one — it names the\n * per-component tools — and may be empty. Default: an empty catalog.\n */\n catalog?: Catalog;\n /**\n * `tree` (default): one `ui__render` tool taking a composed tree (a single node is pushed as that\n * component). `per-component`: one `ui__show_<snake>` tool per component.\n */\n mode?: 'per-component' | 'tree';\n /** `ui__render`'s input schema: `'strict'` (default, a `$defs` union per component) or `'loose'`. */\n treeSchema?: TreeSchemaMode;\n /**\n * Tree mode: `'complete'` (default) draws the tree once the call has run; `'partial'` streams it\n * as `partial` ui frames while the model writes it. A component's own `streaming` overrides it.\n */\n streaming?: GenuiStreaming;\n /** Least time between two partial tree frames of one call, in ms. Default 100. */\n streamingThrottleMs?: number;\n /** End the model's turn once a genui call succeeds (no narrating follow-up call). */\n terminal?: boolean;\n /** Tool name in `tree` mode. Default `ui__render`. */\n treeToolName?: string;\n /** Text prepended to the tree tool's description. */\n treeInstructions?: string;\n treeLimits?: TreeLimits;\n /**\n * Tree mode: components that ALSO get a flat tool whose input IS their props —\n * `componentTools: ['Sandbox']` adds `ui__sandbox`, so a model writing a big component on its own\n * has no `{ type, props }` envelope to leave out.\n */\n componentTools?: readonly string[];\n /** Tool-name prefix for `componentTools`. Default `ui__` (`Sandbox` → `ui__sandbox`). */\n componentToolPrefix?: string;\n /** Tool-name prefix in `per-component` mode. Default `ui__show_`. */\n namePrefix?: string;\n /**\n * Also register ONE generic tool taking `{ component, props }`, validated against the request's\n * catalog — how a model reaches a tenant's own components, which no boot-time tool names. `true`\n * names it `ui__show`.\n */\n showTool?: boolean | string;\n /** Text prepended to the show tool's description. */\n showInstructions?: string;\n /** Roles allowed to call the tools. Undefined → the roles policy default. */\n roles?: string[];\n /**\n * The `@nestjs/authorization` abilities the UI tools require (`ToolSpec.can`). One list for every\n * tool; a map by tool name (a tool left out requires none); or a function of `{ name, component }`.\n */\n can?: GenuiCan;\n /** Override the generated presentation per component (or per tree / show tool name). */\n presentation?: (component: string) => ToolPresentation | undefined;\n /**\n * Add the sandbox component (`Sandbox`): the model may write HTML, CSS and JS for a one-off\n * interactive answer when no catalog component fits. `true` for the defaults (no network), or\n * the {@link DefineSandboxOptions} (a policy listing origins, extra instructions). Off by default.\n * The browser's catalog should carry the same definition (`defineSandbox(...)` in the shared\n * catalog file) so the renderer enforces the same policy.\n *\n * `theme` (default on) and `kit` put the app's design system in the frame: `kit: true` turns on\n * whatever `genuiSandboxKit()` built (styles, Tailwind, components, wrapper, docs), found through\n * `sandboxKit`: the descriptor\n * `genuiSandboxKit()` (`@dudousxd/nestjs-agent/vite`) writes in dev, the Vite manifest in\n * production — and `GET <base>/config` tells the renderer where the assets are.\n */\n sandbox?: boolean | DefineSandboxOptions;\n /**\n * Per-channel generative UI: each entry sets the mode, streaming, sandbox and rendering of one\n * channel (`web`, `mobile`, `whatsapp`, `telegram`, `email`, or `default` for the rest), over the\n * top-level options. A text channel (`@dudousxd/nestjs-agent-channels`) configured here draws the\n * components natively (reply buttons, lists, images). Omitted → every channel is served by the\n * top-level options, as before.\n */\n channels?: GenuiChannels;\n /**\n * Where the sandbox kit is found (with `sandbox: { kit: true }` or the theme's names). No Vite\n * runs in the Nest process, so: the descriptor the dev plugin writes, or the production Vite\n * manifest — in production the manifest first, otherwise whichever was written last.\n */\n sandboxKit?: AgentGenuiSandboxKitOptions;\n /**\n * Generative-UI telemetry, recorded by the loop for every UI call (the dashboard's \"Generative UI\"\n * page): tool, channel, mode, attempt, validity, error category, tokens and cost, time to first and\n * complete frame. Metadata only by default — the generated HTML/JSX and props are NEVER stored\n * unless `samplePayloads: true` (debugging; keep it off where a view may show personal data).\n * `false` records nothing. Needs a store that records it (`recordGenuiCalls`).\n */\n telemetry?: GenuiTelemetryOptions | false;\n}\n\n/** {@link AgentGenuiOptions.sandboxKit}. Relative paths resolve against `root`. */\nexport interface AgentGenuiSandboxKitOptions {\n /** Default `process.cwd()`. */\n root?: string;\n /**\n * The dev descriptor `genuiSandboxKit()` writes. Default `.genui/sandbox-kit.json` — for a named\n * kit (`genuiSandboxKit({ name })`, picked with `kitName`), `.genui/sandbox-kit.<name>.json`.\n */\n descriptor?: string;\n /**\n * The production Vite manifest, and the directory its `file`s are relative to. Default\n * `{ file: 'public/.vite/manifest.json', outDir: 'public' }`; `false` → none.\n */\n manifest?: { file: string; outDir: string } | false;\n /** An explicit kit url (an SPA served from elsewhere), over what is found. */\n kitUrl?: string;\n /** An explicit url of the compiled styles, over what is found (the same SPA case). */\n cssUrl?: string;\n /** An explicit url of the Tailwind browser runtime, over what is found (the same SPA case). */\n tailwindUrl?: string;\n /** Read the manifest first (else the freshest of the two). Default: `NODE_ENV === 'production'`. */\n production?: boolean;\n}\n\ntype ResolverOption = Type<GenuiCatalogResolver> | GenuiCatalogResolver;\n\nexport interface AgentGenuiModuleOptions extends AgentGenuiOptions {\n /** Per-request catalogs. A class is instantiated with DI (its dependencies must be global or exported to the root). */\n resolver?: ResolverOption;\n}\n\nexport interface AgentGenuiModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {\n inject?: FactoryProvider['inject'];\n useFactory: (...deps: any[]) => AgentGenuiOptions | Promise<AgentGenuiOptions>;\n /** Per-request catalogs. A class resolves its dependencies from `imports`. */\n resolver?: ResolverOption;\n}\n\nfunction resolverProviders(resolver: ResolverOption | undefined): Provider[] {\n if (resolver === undefined) return [];\n return [\n typeof resolver === 'function'\n ? { provide: GenuiCatalogResolver, useClass: resolver }\n : { provide: GenuiCatalogResolver, useValue: resolver },\n ];\n}\n\n/** The sandbox and channels with the kit and theme names found ({@link GENUI_RESOLVED}). */\ninterface ResolvedGenui {\n sandbox?: boolean | DefineSandboxOptions;\n /** A kit sandbox the catalog itself defines, resolved (under its own name). */\n catalogSandbox?: DefineSandboxOptions;\n channels?: GenuiChannels;\n sandboxClient?: () => SandboxClientConfig;\n}\n\n/** What every configured sandbox (top level and channels) needs from the browser, together. */\nfunction mergeSandboxClients(clients: Array<() => SandboxClientConfig>): SandboxClientConfig {\n const merged: SandboxClientConfig = { theme: false };\n for (const client of clients) {\n const one = client();\n merged.theme ||= one.theme;\n if (one.name !== undefined && merged.kit === undefined && one.kit !== undefined)\n merged.name = one.name;\n if (one.kit !== undefined) merged.kit ??= one.kit;\n if (one.css !== undefined) merged.css ??= one.css;\n if (one.tailwind !== undefined) merged.tailwind ??= one.tailwind;\n }\n return merged;\n}\n\n/** Resolve the sandbox (top level and per channel) against the kit discovery. */\nasync function resolveGenui(options: AgentGenuiOptions): Promise<ResolvedGenui> {\n const { sandbox: asked, channels: askedChannels } = options;\n assertGenuiChannels(askedChannels);\n // A sandbox's kit (styles, components, wrapper) and theme names are found through the app's Vite output.\n const clients: Array<() => SandboxClientConfig> = [];\n const discoveries = new Map<\n string,\n import('@dudousxd/nestjs-agent-core/genui/kit').SandboxKitDiscovery\n >();\n const resolveSandbox = async (\n value: boolean | DefineSandboxOptions | undefined,\n ): Promise<boolean | DefineSandboxOptions | undefined> => {\n if (value === undefined || value === false) return value;\n // Node-only, and only with a sandbox: loaded when one is configured.\n const [{ nestSandboxKitDiscovery }, { resolveSandboxServer }] = await Promise.all([\n import('./kit.js'),\n import('@dudousxd/nestjs-agent-core/genui/kit'),\n ]);\n const kitName = value === true ? undefined : value.kitName;\n let discovery = discoveries.get(kitName ?? '');\n if (discovery === undefined) {\n discovery = nestSandboxKitDiscovery(options.sandboxKit, kitName);\n discoveries.set(kitName ?? '', discovery);\n }\n const resolved = resolveSandboxServer(value, discovery);\n clients.push(resolved.client);\n return resolved.define;\n };\n const sandbox = await resolveSandbox(asked);\n // A kit sandbox defined in the (shared) catalog itself: found the same way, and put\n // back under its own name, so the browser's copy of the catalog validates what the model writes.\n const own = options.catalog?.components.find((each) => sandboxPolicyOf(each) !== undefined) as\n | SandboxDefinition\n | undefined;\n const ownOptions =\n asked === undefined && own?.sandboxOptions !== undefined && own.sandboxView?.kit === true\n ? await resolveSandbox({ ...own.sandboxOptions, name: own.name })\n : undefined;\n let channels: GenuiChannels | undefined;\n if (askedChannels !== undefined) {\n channels = {};\n for (const [name, entry] of Object.entries(askedChannels)) {\n if (entry === undefined) continue;\n const own = await resolveSandbox(entry.sandbox);\n channels[name] = { ...entry, ...(own !== undefined ? { sandbox: own } : {}) };\n }\n }\n return {\n ...(sandbox !== undefined ? { sandbox } : {}),\n ...(typeof ownOptions === 'object' ? { catalogSandbox: ownOptions } : {}),\n ...(channels !== undefined ? { channels } : {}),\n ...(clients.length > 0 ? { sandboxClient: () => mergeSandboxClients(clients) } : {}),\n };\n}\n\nfunction perRequest(\n resolver: GenuiCatalogResolver | undefined,\n): GenuiToolsOptions['resolveCatalog'] | undefined {\n return resolver === undefined ? undefined : (scope: GenuiCatalogScope) => resolver.resolve(scope);\n}\n\nfunction toolOptions(\n options: AgentGenuiOptions,\n resolved: ResolvedGenui,\n resolver: GenuiCatalogResolver | undefined,\n): GenuiToolsOptions {\n const {\n catalog: _catalog,\n sandbox: _sandbox,\n channels: _channels,\n sandboxKit: _sandboxKit,\n ...rest\n } = options;\n const resolveCatalog = perRequest(resolver);\n return {\n ...rest,\n ...(resolved.channels !== undefined ? { channels: resolved.channels } : {}),\n ...(resolved.sandbox !== undefined ? { sandbox: resolved.sandbox } : {}),\n ...(resolveCatalog !== undefined ? { resolveCatalog } : {}),\n };\n}\n\n/** The configured catalog, with the sandbox component added when `sandbox` asks for it. */\nfunction withSandbox(options: AgentGenuiOptions, resolved: ResolvedGenui): Catalog {\n const base = options.catalog ?? defineCatalog([]);\n const { sandbox, catalogSandbox } = resolved;\n if (sandbox === undefined || sandbox === false)\n return catalogSandbox !== undefined ? base.extend([defineSandbox(catalogSandbox)]) : base;\n return base.extend([defineSandbox(sandbox === true ? {} : sandbox)]);\n}\n\nfunction coreProviders(resolver: ResolverOption | undefined): Provider[] {\n return [\n {\n provide: GENUI_RESOLVED,\n useFactory: (options: AgentGenuiOptions) => resolveGenui(options),\n inject: [GENUI_OPTIONS],\n },\n {\n provide: GENUI_CATALOG,\n useFactory: (options: AgentGenuiOptions, resolved: ResolvedGenui) =>\n withSandbox(options, resolved),\n inject: [GENUI_OPTIONS, GENUI_RESOLVED],\n },\n {\n provide: AGENT_GENUI,\n useFactory: (\n options: AgentGenuiOptions,\n catalog: Catalog,\n resolved: ResolvedGenui,\n resolverInstance?: GenuiCatalogResolver,\n ) =>\n new AgentGenui(\n catalog,\n perRequest(resolverInstance),\n resolved.channels,\n {\n ...(options.mode !== undefined ? { mode: options.mode } : {}),\n ...(options.streaming !== undefined ? { streaming: options.streaming } : {}),\n ...(resolved.sandbox !== undefined ? { sandbox: resolved.sandbox } : {}),\n },\n resolved.sandboxClient,\n ),\n inject: [\n GENUI_OPTIONS,\n GENUI_CATALOG,\n GENUI_RESOLVED,\n { token: GenuiCatalogResolver, optional: true },\n ],\n },\n ...resolverProviders(resolver),\n // The generated tools, registered by the agent module's discovery like any `provideAgentTool`.\n // Built from the injected catalog, so `overrideProvider(GENUI_CATALOG)` changes them too.\n provideAgentTools(\n (\n options: AgentGenuiOptions,\n catalog: Catalog,\n resolved: ResolvedGenui,\n perRequestResolver?: GenuiCatalogResolver,\n ) => genuiTools(catalog, toolOptions(options, resolved, perRequestResolver)),\n [\n GENUI_OPTIONS,\n GENUI_CATALOG,\n GENUI_RESOLVED,\n { token: GenuiCatalogResolver, optional: true },\n ],\n ),\n ];\n}\n\nconst EXPORTS = [GENUI_CATALOG, GENUI_OPTIONS, AGENT_GENUI];\n\n/**\n * Generative UI for the agent: registers the tools that let the model push catalog components\n * (one `ui__render` tree tool, or `ui__show_<component>` per component, and/or the generic\n * `ui__show`), and makes the catalog\n * injectable. Global, like `AgentModule`; import it once, next to it.\n *\n * ```ts\n * AgentGenuiModule.forRoot({ catalog, mode: 'tree', terminal: true })\n * ```\n */\n@Module({})\nexport class AgentGenuiModule {\n static forRoot(options: AgentGenuiModuleOptions = {}): DynamicModule {\n const { resolver, ...rest } = options;\n return {\n module: AgentGenuiModule,\n global: true,\n providers: [{ provide: GENUI_OPTIONS, useValue: rest }, ...coreProviders(resolver)],\n exports: resolver === undefined ? EXPORTS : [...EXPORTS, GenuiCatalogResolver],\n };\n }\n\n static forRootAsync(options: AgentGenuiModuleAsyncOptions): DynamicModule {\n return {\n module: AgentGenuiModule,\n global: true,\n imports: options.imports ?? [],\n providers: [\n { provide: GENUI_OPTIONS, useFactory: options.useFactory, inject: options.inject ?? [] },\n ...coreProviders(options.resolver),\n ],\n exports: options.resolver === undefined ? EXPORTS : [...EXPORTS, GenuiCatalogResolver],\n };\n }\n}\n","import {\n type FunctionalToolDefinition,\n type ToolHandler,\n type ToolSpec,\n createFunctionalTool,\n} from '@dudousxd/nestjs-agent-core';\nimport type { FactoryProvider, Provider } from '@nestjs/common';\n\n/**\n * Brand stamped onto a functional-tool provider instance so `AiToolDiscoveryService` picks it up\n * when it walks every provider at boot — the declarative alternative to a manual `registry.register`.\n */\nexport const AGENT_TOOL_BRAND = Symbol.for('@dudousxd/nestjs-agent:functional-tool');\n\n/** A tool expressed as data + handler (e.g. from `createExecuteSqlTool`), not an `@AiTool` class. */\nexport interface FunctionalTool {\n spec: ToolSpec;\n handler: ToolHandler;\n}\n\n/** A {@link FunctionalTool} carrying {@link AGENT_TOOL_BRAND} — what a provider resolves to. */\nexport interface BrandedFunctionalTool extends FunctionalTool {\n readonly [AGENT_TOOL_BRAND]: true;\n}\n\nfunction brand(tool: FunctionalTool): BrandedFunctionalTool {\n return { [AGENT_TOOL_BRAND]: true, spec: tool.spec, handler: tool.handler };\n}\n\n/** Narrows a provider instance to a branded functional tool for boot-time registration. */\nexport function isBrandedFunctionalTool(value: object): value is BrandedFunctionalTool {\n return AGENT_TOOL_BRAND in value && 'spec' in value && 'handler' in value;\n}\n\n/**\n * Registers a functional tool declaratively — drop the returned provider in a module's `providers`\n * and `AiToolDiscoveryService` auto-registers it at boot. Each call uses a fresh, unique provide\n * token so the same tool can be provided many times without collisions.\n *\n * Two forms: a static tool (`useValue`) or a factory with `inject` for DI-resolved dependencies\n * (`useFactory`). Either way the resolved instance is branded with {@link AGENT_TOOL_BRAND}.\n */\nexport function provideAgentTool(tool: FunctionalTool): Provider;\nexport function provideAgentTool(\n factory: (...deps: never[]) => FunctionalTool,\n inject?: FactoryProvider['inject'],\n): Provider;\nexport function provideAgentTool(\n factoryOrTool: FunctionalTool | ((...deps: never[]) => FunctionalTool),\n inject?: FactoryProvider['inject'],\n): Provider {\n const provide = Symbol('nestjs-agent:functional-tool-instance');\n if (typeof factoryOrTool === 'function') {\n return {\n provide,\n useFactory: (...deps: never[]) => brand(factoryOrTool(...deps)),\n inject: inject ?? [],\n };\n }\n return { provide, useValue: brand(factoryOrTool) };\n}\n\n/**\n * Registers a LIST of functional tools from one factory — for a producer whose tool count is only\n * known once its dependencies resolve (a catalog loaded from config, one tool per entry). The\n * factory's result is branded element by element; `AiToolDiscoveryService` registers each.\n */\nexport function provideAgentTools(\n factory: (...deps: never[]) => readonly FunctionalTool[] | Promise<readonly FunctionalTool[]>,\n inject?: FactoryProvider['inject'],\n): Provider {\n return {\n provide: Symbol('nestjs-agent:functional-tool-list'),\n useFactory: async (...deps: never[]) => (await factory(...deps)).map(brand),\n inject: inject ?? [],\n };\n}\n\n/** Author a functional tool with inferred Standard Schema input and domain output. */\nexport const defineTool = createFunctionalTool;\nexport type { FunctionalToolDefinition };\n","import type {\n Catalog,\n GenuiCatalogScope,\n GenuiChannelBase,\n GenuiChannels,\n SandboxClientConfig,\n} from '@dudousxd/nestjs-agent-core/genui';\n\n/**\n * The app's genui setup ({@link AgentGenui}): the catalog, the per-channel options and what the\n * sandbox renderer is told — what the text channels (`@dudousxd/nestjs-agent-channels`) and\n * `GET <base>/config` read.\n */\nexport const AGENT_GENUI = Symbol.for('@dudousxd/nestjs-agent:genui');\n\n/**\n * The app's genui setup, bound to {@link AGENT_GENUI}: what a text channel draws with\n * (`catalog`, `channels`, `base`) and what the sandbox renderer is told (`sandboxClient`).\n */\nexport class AgentGenui {\n constructor(\n readonly catalog: Catalog,\n readonly resolveCatalog?: (scope: GenuiCatalogScope) => Catalog | Promise<Catalog>,\n /** `AgentGenuiModule.forRoot({ channels })`, when configured. */\n readonly channels?: GenuiChannels,\n /** The top-level options a channel falls back to. */\n readonly base: GenuiChannelBase = {},\n /** What the sandbox renderer is told, when a sandbox is configured. */\n readonly sandboxClient?: () => SandboxClientConfig,\n ) {}\n}\n"],"mappings":";;;;;;;;;;;;AAgBA,SAIEA,wBACAC,2BACAC,0BACAC,mCACK;AAxBP,IA+BaC;AA/Bb;;;AA+BO,IAAMA,8BAA8B;;;;;AC/B3C;;;;;AAMA,SAASC,eAAe;AACxB,SAEEC,0BACAC,2BACK;AAcA,SAASC,wBACdC,UAAuC,CAAC,GACxCC,MAAa;AAEb,QAAMC,WAAWF,QAAQE,YAAYC;AACrC,SAAOL,oBAAoB;IACzBM,MAAMR,QAAQI,QAAQI,QAAQC,QAAQC,IAAG,CAAA;IACzC,GAAIL,SAASM,SAAY;MAAEN;IAAK,IAAI,CAAC;IACrCO,YAAYX,yBAAyBG,QAAQQ,cAAcC,6BAA6BR,IAAAA;IACxF,GAAIC,aAAa,QAAQ;MAAEA,UAAU;QAAEQ,MAAMR,SAASQ;QAAMC,QAAQT,SAASS;MAAO;IAAE,IAAI,CAAC;IAC3F,GAAIX,QAAQY,WAAWL,SAAY;MAAEK,QAAQZ,QAAQY;IAAO,IAAI,CAAC;IACjE,GAAIZ,QAAQa,WAAWN,SAAY;MAAEM,QAAQb,QAAQa;IAAO,IAAI,CAAC;IACjE,GAAIb,QAAQc,gBAAgBP,SAAY;MAAEO,aAAad,QAAQc;IAAY,IAAI,CAAC;IAChF,GAAId,QAAQe,eAAeR,SAAY;MAAEQ,YAAYf,QAAQe;IAAW,IAAI,CAAC;EAC/E,CAAA;AACF;AAxCA,IAgBaZ;AAhBb;;;AAYA;AAIO,IAAMA,4BAA4Ba,OAAOC,OAAO;MACrDP,MAAM;MACNC,QAAQ;IACV,CAAA;AAMgBZ;;;;;ACjBhB,cAAc;;;ACRd,SAASmB,sBAA0CC,iBAAiB;AACpE,SACEC,qBACAC,oBACAC,eAGAC,kBACAC,sBACAC,gBACAC,kCACK;AACP,SACEC,YACAC,sBACAC,yBACK;AACP,SAIEC,cACAC,8BACK;AACP,SACEC,q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andboxKitDescriptorPath","sandboxKitDiscovery","nestSandboxKitDiscovery","options","name","manifest","NEST_SANDBOX_KIT_MANIFEST","root","process","cwd","undefined","descriptor","NEST_SANDBOX_KIT_DESCRIPTOR","file","outDir","kitUrl","cssUrl","tailwindUrl","production","Object","freeze","AGENT_ACTOR_RESOLVER","CanAnyone","A2UI_APPROVE_ACTION","A2UI_REJECT_ACTION","A2uiProjector","a2uiThreadReplay","negotiateA2uiCatalog","readA2uiAction","readA2uiClientCapabilities","agUiEvents","agUiFramesFromNdjson","decodeInterruptId","uiActionText","validateUiCapabilities","BadRequestException","Body","Controller","ForbiddenException","Get","HttpCode","Inject","Optional","Param","Post","Query","Req","Res","AGENT_SERVICE","Symbol","for","readerGone","res","controller","AbortController","once","abort","signal","assertGenuiChannels","defineCatalog","defineSandbox","genuiTools","sandboxPolicyOf","Inject","Module","createFunctionalTool","AGENT_TOOL_BRAND","Symbol","for","brand","tool","spec","handler","provideAgentTools","factory","inject","provide","Symbol","useFactory","deps","map","brand","AGENT_GENUI","Symbol","for","AgentGenui","catalog","resolveCatalog","channels","base","sandboxClient","GENUI_CATALOG","Symbol","for","GENUI_OPTIONS","GENUI_RESOLVED","GenuiCatalogResolver","resolverProviders","resolver","undefined","provide","useClass","useValue","mergeSandboxClients","clients","merged","theme","client","one","name","kit","css","tailwind","resolveGenui","options","sandbox","asked","channels","askedChannels","assertGenuiChannels","discoveries","Map","resolveSandbox","value","nestSandboxKitDiscovery","resolveSandboxServer","Promise","all","kitName","discovery","get","sandboxKit","set","resolved","push","define","own","catalog","components","find","each","sandboxPolicyOf","ownOptions","sandboxOptions","sandboxView","entry","Object","entries","catalogSandbox","length","sandboxClient","perRequest","scope","resolve","toolOptions","_catalog","_sandbox","_channels","_sandboxKit","rest","resolveCatalog","withSandbox","base","defineCatalog","extend","defineSandbox","coreProviders","GENUI_RESOLVED","useFactory","inject","GENUI_OPTIONS","GENUI_CATALOG","AGENT_GENUI","resolverInstance","AgentGenui","mode","streaming","token","optional","provideAgentTools","perRequestResolver","genuiTools","EXPORTS","AgentGenuiModule","forRoot","module","global","providers","exports","forRootAsync","imports","A2UI_VIA","isRecord","value","Array","isArray","invalid","code","message","BadRequestException","statusCode","bodyField","body","key","undefined","metadata","readDataModel","raw","maxBytes","surfaces","size","TextEncoder","encode","JSON","stringify","length","Object","keys","A2uiRunHandler","agent","actorResolver","projection","quietMs","maxActionBytes","maxDataModelBytes","replay","req","threadId","catalog","actor","resolve","owner","threadOwner","entries","thread","getThread","supported","filter","id","a2uiThreadReplay","messages","negotiateA2uiCatalog","handle","res","agentName","readA2uiClientCapabilities","dataModel","action","read","readA2uiAction","name","A2UI_APPROVE_ACTION","A2UI_REJECT_ACTION","interruptId","context","address","decodeInterruptId","kind","proposalId","decided","decideActionProposal","decision","via","writeHead","projector","A2uiProjector","messageId","event","type","role","delta","text","project","write","end","assertResumable","stream","checkDecision","toolCallId","approve","reject","skip","position","answered","uiActionText","trim","ForbiddenException","uiCapabilities","hasOwn","validateUiCapabilities","error","started","chat","newThreadId","pageContext","a2uiDataModel","runId","extra","status","setHeader","flushHeaders","options","frames","agUiFramesFromNdjson","subscribe","readerGone","agUiEvents","streamRunId","streamThreadId","a2uiAdapter","path","replace","_path","A2uiController","run","controllers"]}
@@ -1,7 +1,8 @@
1
- import { ResolveToolUiCatalog, ToolUiChannelGuide, ModelProvider, AgentStore, ToolRegistry, RolesPolicy, ApprovalPolicy, QuotaStore, TokenStreamSink, PromptBuilder, PromptContributor, Persona, ToolTransientRetrySetting, Retriever, AgentPricingStore, HistoryPolicy, InputProcessor, OutputProcessor, AgentIntake, SkillsConfig, MemoryConfig, ToolSpec, ToolHandler, createFunctionalTool, QuotaProvider, QuotaQuery, QuotaReport, ActionApprovalMode, BackgroundActorResolver, ActionProposal, ActionProposalOutcome, TextActionProposalConfig, PriceCatalogOptions, ModelCatalog, EmptyRoles, ActorResolver, AgentHistoryWindow, SkillProvider, ScopeResolver, MemoryProvider, AgentRegistry, PersonaCatalogEntry, Actor, AttachmentStagingStore, ChatQueueStore, ChatQueueState, AgentRunner, AgentRunInput, AgentStreamEvent, QueuePauseReason } from '@dudousxd/nestjs-agent-core';
1
+ import { ResolveToolUiCatalog, ToolUiChannelGuide, ModelProvider, AgentStore, ToolRegistry, RolesPolicy, ApprovalPolicy, QuotaStore, TokenStreamSink, PromptBuilder, PromptContributor, Persona, ToolTransientRetrySetting, Retriever, AgentPricingStore, HistoryPolicy, InputProcessor, OutputProcessor, AgentIntake, SkillsConfig, MemoryConfig, ToolSpec, ToolHandler, createFunctionalTool, QuotaProvider, QuotaQuery, QuotaReport, Actor, AiToolCtx, ActionApprovalMode, BackgroundActorResolver, ActionProposal, ActionProposalOutcome, TextActionProposalConfig, PriceCatalogOptions, ModelCatalog, EmptyRoles, ActorResolver, AgentHistoryWindow, SkillProvider, ScopeResolver, MemoryProvider, AgentRegistry, PersonaCatalogEntry, AttachmentStagingStore, ChatQueueStore, ChatQueueState, AgentRunner, AgentRunInput, AgentStreamEvent, QueuePauseReason } from '@dudousxd/nestjs-agent-core';
2
2
  import { Catalog } from '@dudousxd/nestjs-agent-core/genui';
3
3
  import { StandardSchemaV1 } from '@standard-schema/spec';
4
- import { Provider, InjectionToken, Type, FactoryProvider, CanActivate, ModuleMetadata, OptionalFactoryDependency } from '@nestjs/common';
4
+ import { Provider, InjectionToken, Type, FactoryProvider, ModuleMetadata, OptionalFactoryDependency } from '@nestjs/common';
5
+ import { AiCaller } from '@nestjs/ai';
5
6
  import { GenuiCatalogResolver, AgentGenui } from './genui/index.js';
6
7
 
7
8
  /** Everything `runAgentLoop` needs, minus the per-run `day` the runner stamps. */
@@ -177,6 +178,19 @@ declare class LedgerQuotaProvider implements QuotaProvider {
177
178
  private window;
178
179
  }
179
180
 
181
+ /** Who an `@AgentFunction()` call acts for, from the actor of the turn. */
182
+ /**
183
+ * `ctx` is the call's, when there is one; it is absent where the agent asks `@nestjs/authorization`
184
+ * about the actor before any call (whether to offer a tool).
185
+ */
186
+ type AgentFunctionCaller = (actor: Actor, ctx?: AiToolCtx) => AiCaller;
187
+ /**
188
+ * The default {@link AgentFunctionCaller}: the actor is the `user` (what `@nestjs/ai`'s guards read
189
+ * where there is no request, as in a durable run). No `scopes`: the agent gates tools by roles, so a
190
+ * function that requires scopes is refused unless `agentFunctionCaller` maps the actor to them.
191
+ */
192
+ declare const defaultAgentFunctionCaller: AgentFunctionCaller;
193
+
180
194
  /**
181
195
  * A wire protocol other than the native one, served over the same runs — what `adapters` on
182
196
  * `AgentModule.forRoot` takes. An adapter contributes controllers, mounted under the agent's
@@ -201,11 +215,12 @@ interface AgentProtocolAdapter {
201
215
  * each load `AgentModule` without either one doing the other's job:
202
216
  *
203
217
  * - `'both'` (default): today's behavior, unconditionally — every controller AND the full durable
204
- * engine wiring (when `durable: true`). Zero-config single-pod deployments never touch this.
218
+ * engine wiring (when `durable` is on). Zero-config single-pod deployments never touch this.
205
219
  * - `'http'`: mounts every controller (chat/threads/tool-call/quota/agents/attachments) so the HTTP
206
- * surface is fully functional, but under `durable: true` this pod must never EXECUTE agent work —
207
- * see `AgentDurableModuleOptions.surface` (`@dudousxd/nestjs-agent/durable`), which is where the
208
- * actual step-handler exclusion happens; this flag only controls the controllers here.
220
+ * surface is fully functional, but under `durable` this pod must never EXECUTE agent work. On the
221
+ * `'workflows'` engine that is `WorkflowsModule.forRoot({ worker: false })`; on `'aviary'`,
222
+ * `AgentDurableModuleOptions.surface` (`@dudousxd/nestjs-agent/durable`). This flag only controls
223
+ * the controllers here.
209
224
  * - `'engine'`: mounts NO controllers (an API pod's routes have no business existing on a worker
210
225
  * pod that never receives HTTP traffic) — everything else (registry/tools/model/store/sinks, the
211
226
  * `agent.run` workflow, and its dispatched steps under `AgentDurableModule`) stays wired exactly
@@ -216,6 +231,29 @@ interface AgentProtocolAdapter {
216
231
  * metadata can't be computed from a runtime-injected value).
217
232
  */
218
233
  type AgentSurface = 'http' | 'engine' | 'both';
234
+ /**
235
+ * The durable engine `AgentModuleOptions.durable` runs turns on.
236
+ *
237
+ * - `'workflows'` (what `durable: true` means): NestJS's `@nestjs/workflows`. Import
238
+ * `WorkflowsModule.forRoot()` and `AgentWorkflowsModule` (`@dudousxd/nestjs-agent/workflows`).
239
+ * An API pod that must not run turns imports `WorkflowsModule.forRoot({ worker: false })`.
240
+ * - `'aviary'`: `@dudousxd/nestjs-durable`. Import `DurableModule` and `AgentDurableModule`
241
+ * (`@dudousxd/nestjs-agent/durable`). Choose it for what `@nestjs/workflows` does not do: steps
242
+ * dispatched to a separate fleet over a transport (BullMQ, SQS, ...), Python workers, the
243
+ * SQLite/MikroORM stores, `ctx.patched` for changing a running turn's code in place.
244
+ */
245
+ interface AgentDurableOptions {
246
+ /** Default `'workflows'`. */
247
+ engine?: 'workflows' | 'aviary';
248
+ /**
249
+ * `'workflows'` only: model calls per workflow instance. After that many, the turn goes on in a
250
+ * child instance, so no instance's journal grows past what one segment writes (the same idea as
251
+ * `@nestjs/ai`'s `AiAgents` `stepsPerInstance`). Default 10.
252
+ */
253
+ stepsPerInstance?: number;
254
+ }
255
+ /** Which durable engine `durable` names: `undefined` when the turns run in-process. */
256
+ declare function durableEngineOf(durable: boolean | AgentDurableOptions | undefined): 'workflows' | 'aviary' | undefined;
219
257
  /**
220
258
  * `AgentModuleOptions.attachments` — limits for `POST <base>/attachments`, when the bound
221
259
  * `AGENT_ATTACHMENT_STAGING` store does not declare its own (`AgentMediaAttachmentsModule` does, and
@@ -330,11 +368,25 @@ interface AgentModuleOptions {
330
368
  */
331
369
  actionProposalText?: TextActionProposalConfig;
332
370
  /**
333
- * The LLM provider — `aiSdkModel(openai('gpt-5-mini'))`, or `aiSdkModels({ … })` for a model
334
- * picker (its catalog is used when `models` is omitted). Required unless an `engine` runs the
335
- * turns instead.
371
+ * The LLM provider. Omit it to run on `@nestjs/ai`: the turns use the models of the application's
372
+ * `AiModule.forRoot({ models })` (the picker lists them by name, `default` first), with each
373
+ * model's settings, `retry` / `timeout` / `resilience`, `fallback`, `pricing` and `onUsage`. Set
374
+ * it to replace them — a `FakeModelProvider` in tests, `aiSdkModel(…)` outside `AiModule`. Not
375
+ * needed when an `engine` runs the turns.
336
376
  */
337
377
  model?: ModelProvider;
378
+ /**
379
+ * Offer the application's `@nestjs/ai` `@AgentFunction()` methods as agent tools (default), each
380
+ * governed by this library's `@AgentFunction()` options and run through `AiTools.call`, so its guards, interceptors, pipes
381
+ * and filters apply. `false` leaves them to `@nestjs/ai`'s own calls.
382
+ */
383
+ agentFunctions?: boolean;
384
+ /**
385
+ * Who an `@AgentFunction()` call acts for, from the turn's actor — what its guards read. Default:
386
+ * `{ user: actor }`, with no `scopes` (the agent gates by roles); map the actor to scopes here for
387
+ * functions that declare `scopes`.
388
+ */
389
+ agentFunctionCaller?: AgentFunctionCaller;
338
390
  /**
339
391
  * Where a configured model with no price row gets one, at boot. On application bootstrap every
340
392
  * model the `model` provider describes (`aiSdkModel` / `aiSdkModels`) that the bound
@@ -443,22 +495,21 @@ interface AgentModuleOptions {
443
495
  /** Route prefix the controllers mount under. Defaults to `'agent'` (→ `/agent/chat`, …). */
444
496
  path?: string;
445
497
  /**
446
- * Run each turn as a durable workflow instead of in-process. Requires importing
447
- * `AgentDurableModule` from `@dudousxd/nestjs-agent/durable` and a configured `DurableModule`.
498
+ * Run each turn as a durable workflow instead of in-process: each model call and each tool call
499
+ * is a journaled step, a turn parked on a person survives restarts, and a crashed turn resumes
500
+ * where it was. See {@link AgentDurableOptions} for the two engines; `true` is
501
+ * `{ engine: 'workflows' }`, NestJS's own `@nestjs/workflows`.
448
502
  *
449
- * The turn's model call and its tool executions are dispatched steps
450
- * (`AgentRunSteps.llm` / `AgentRunSteps.tool`), so a `@AiTool` handler runs in whichever worker
451
- * serves the routed group rather than in the pod that took the request. A handler that resolves
452
- * anything per invocation from its caller's execution context — a request-scoped ORM
453
- * EntityManager, an AsyncLocalStorage tenant, a CLS transaction — must establish that context
454
- * itself (`@CreateRequestContext`/`@EnsureRequestContext` under MikroORM), exactly as a `@Step`
455
- * handler does.
503
+ * A `@AiTool` handler runs in whichever worker runs the step rather than in the pod that took the
504
+ * request. A handler that resolves anything per invocation from its caller's execution context (a
505
+ * request-scoped ORM EntityManager, an AsyncLocalStorage tenant, a CLS transaction) must
506
+ * establish that context itself.
456
507
  *
457
508
  * Multi-pod fleets MUST also wire a cross-process token sink (e.g. a Redis pub/sub
458
- * `TokenStreamSink`): the turn runs on whichever worker takes `agent.run`, which may not be the
459
- * pod holding the SSE connection.
509
+ * `TokenStreamSink`): the turn runs on whichever worker claims it, which may not be the pod
510
+ * holding the SSE connection.
460
511
  */
461
- durable?: boolean;
512
+ durable?: boolean | AgentDurableOptions;
462
513
  /**
463
514
  * Static functional tools (`{ spec, handler }`, e.g. from `createExecuteSqlTool`) to register at
464
515
  * boot. For tools that need DI-resolved dependencies, use `provideAgentTool(factory, inject)` in a
@@ -574,14 +625,20 @@ interface AgentModuleOptions {
574
625
  */
575
626
  defaultAgent?: string;
576
627
  /**
577
- * Guard(s) applied uniformly to EVERY controller this module mounts (chat, threads, tool-call,
578
- * quota, agents, attachments, config, …). Third-party controller
579
- * classes can't be annotated with `@UseGuards` by consumers, so without this option every route is
580
- * open beyond whatever `actorResolver` itself enforces. Guard classes are added to this module's
581
- * `providers` so Nest can DI-instantiate them; if a guard has its own dependencies, make sure they
582
- * resolve from this module's imports or a global module.
628
+ * Class decorators applied to EVERY controller this module mounts — the ecosystem's convention,
629
+ * like `@nestjs/mcp`'s own `decorators`: decide who reaches the agent's routes with the official
630
+ * tools, e.g. `[UseGuards(AuthenticationGuard), Can(AgentPolicy, 'chat')]` from
631
+ * `@nestjs/authentication` / `@nestjs/authorization`. Applied to a subclass of each controller made
632
+ * for this registration, so nothing sticks to the shared classes. The controllers are open to
633
+ * `@nestjs/authorization`'s deny-by-default guard otherwise (`CanAnyone()`), and a `@Can()` passed
634
+ * here is still checked. Static wiring.
635
+ *
636
+ * A guard class in `UseGuards(...)` is built by Nest inside this module, so it needs no provider
637
+ * entry, but what it injects must resolve here: from a global module, or (with `forRootAsync`)
638
+ * from a module in `imports` that exports it. The removed `guards` option registered the guard
639
+ * class itself as a provider; nothing does now.
583
640
  */
584
- guards?: Type<CanActivate>[];
641
+ decorators?: ClassDecorator[];
585
642
  /** Upload limits when the staging store declares none. Omit → 20 MiB and the default types. */
586
643
  attachments?: AgentAttachmentsOptions;
587
644
  /**
@@ -590,9 +647,18 @@ interface AgentModuleOptions {
590
647
  * which controllers exist at module-build time, not something a request can flip.
591
648
  */
592
649
  surface?: AgentSurface;
650
+ /**
651
+ * `false` mounts none of the agent's routes, while everything else runs — the way NestJS's own
652
+ * packages leave routes to you (`@nestjs/authentication`'s "routes of your own"): serve them from
653
+ * controllers of your own, protected with the official tools. Either call `AgentService` from
654
+ * them, or extend the exported controllers under your own path and decorators:
655
+ * `@Controller('ops/agent/threads') @Can(AgentPolicy, 'chat') class Threads extends ThreadsController {}`.
656
+ * Static wiring, like `surface`.
657
+ */
658
+ routes?: boolean;
593
659
  /**
594
660
  * Wire protocols served alongside the native one, over the same runs — e.g. `[agUiAdapter()]`
595
- * mounts `POST <path>/ag-ui` (AG-UI 1.0). Their controllers mount under `path`, behind `guards`,
661
+ * mounts `POST <path>/ag-ui` (AG-UI 1.0). Their controllers mount under `path`, behind `decorators`,
596
662
  * and not at all on `surface: 'engine'`. STATIC, like `surface`.
597
663
  */
598
664
  adapters?: AgentProtocolAdapter[];
@@ -606,26 +672,21 @@ interface AgentModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
606
672
  */
607
673
  path?: string;
608
674
  /**
609
- * Run each turn as a durable workflow. Static wiring metadata (which `AGENT_RUNNER` to bind), so
610
- * it lives here rather than in the async factory result — the factory resolves too late to swap
611
- * the runner. Requires importing `AgentDurableModule` and a configured `DurableModule`.
612
- */
613
- durable?: boolean;
614
- /**
615
- * Guard(s) applied uniformly to every controller this module mounts. A STATIC field on the async
616
- * config object itself — NOT part of what `useFactory` resolves — because controllers (and the
617
- * enhancers bound to them) are wired at module build time, before any async factory has run. If a
618
- * guard needs async-resolved config (e.g. a secret from a `ConfigService`), have the guard inject
619
- * that service via DI (see `imports`/`inject` above) rather than trying to thread it through
620
- * `useFactory`. Same default-open caveat as `AgentModuleOptions.guards`.
675
+ * Run each turn as a durable workflow (see {@link AgentModuleOptions.durable}). Static wiring
676
+ * metadata (which `AGENT_RUNNER` to bind), so it lives here rather than in the async factory
677
+ * result: the factory resolves too late to swap the runner.
621
678
  */
622
- guards?: Type<CanActivate>[];
679
+ durable?: boolean | AgentDurableOptions;
680
+ /** As {@link AgentModuleOptions.decorators}: static, so it lives here, not in `useFactory`'s result. */
681
+ decorators?: ClassDecorator[];
623
682
  /**
624
683
  * Which half of the module this process mounts (see {@link AgentSurface}). Same static-wiring
625
684
  * reasoning as `durable` above — `useFactory` resolves too late to decide
626
685
  * which controllers exist. Omit → `'both'`, today's behavior with zero change.
627
686
  */
628
687
  surface?: AgentSurface;
688
+ /** As {@link AgentModuleOptions.routes}: static, so it lives here. */
689
+ routes?: boolean;
629
690
  /** Wire protocols served alongside the native one — see `AgentModuleOptions.adapters`. STATIC. */
630
691
  adapters?: AgentProtocolAdapter[];
631
692
  /**
@@ -859,4 +920,4 @@ declare class ChatQueueService {
859
920
  private freshAttachments;
860
921
  }
861
922
 
862
- export { AgentDepsFactory as A, ChatQueueService as C, type FunctionalTool as F, LedgerQuotaProvider as L, type QueuePlan as Q, type AgentSurface as a, type AgentModuleOptions as b, type AgentModuleAsyncOptions as c, type AgentProtocolAdapter as d, type AgentSkillsOptions as e, AGENT_TOOL_BRAND as f, type AgentAttachmentsOptions as g, type AgentDeps as h, type AgentEngine as i, type AgentMemoryOptions as j, type QueueSettleOutcome as k, type QueuedTurn as l, type QueuedTurnStarter as m, type QuotaLimits as n, type QuotaWindowLimits as o, defineTool as p, delegateToolName as q, provideAgentTool as r, provideAgentTools as s, utcDay as u };
923
+ export { AgentDepsFactory as A, ChatQueueService as C, type FunctionalTool as F, LedgerQuotaProvider as L, type QueuePlan as Q, type AgentSurface as a, type AgentModuleOptions as b, type AgentModuleAsyncOptions as c, type AgentProtocolAdapter as d, type AgentSkillsOptions as e, AGENT_TOOL_BRAND as f, type AgentAttachmentsOptions as g, type AgentDeps as h, type AgentDurableOptions as i, type AgentEngine as j, type AgentFunctionCaller as k, type AgentMemoryOptions as l, type QueueSettleOutcome as m, type QueuedTurn as n, type QueuedTurnStarter as o, type QuotaLimits as p, type QuotaWindowLimits as q, defaultAgentFunctionCaller as r, defineTool as s, delegateToolName as t, durableEngineOf as u, provideAgentTool as v, provideAgentTools as w, utcDay as x };