@happyvertical/smrt-agents 0.62.4 → 0.62.6
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.
- package/AGENTS.md +2 -1
- package/README.md +12 -0
- package/agents/data-surface-denials.md +14 -0
- package/agents/principal-binding.md +23 -0
- package/dist/chunks/{execute-as-principal-tnjcjKIp.js → execute-as-principal-D9XLi1tk.js} +39 -1
- package/dist/chunks/execute-as-principal-D9XLi1tk.js.map +1 -0
- package/dist/execute-as-principal.d.ts +41 -0
- package/dist/execute-as-principal.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/server/data-surface-actions.d.ts +23 -0
- package/dist/server/data-surface-actions.d.ts.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server.js +27 -2
- package/dist/server.js.map +1 -1
- package/dist/smrt-knowledge.json +13 -7
- package/dist/smrt-knowledge.okf.md +6 -2
- package/package.json +12 -12
- package/dist/chunks/execute-as-principal-tnjcjKIp.js.map +0 -1
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,16 +3,17 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-agents",
|
|
6
|
-
"packageVersion": "0.62.
|
|
6
|
+
"packageVersion": "0.62.6",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "8454c51e7bda246c99ccf3146f84bcb6474e4adcc4271877c2497babce8939e3",
|
|
11
|
+
"packageJson": "c284b5e65f15852ae8af8207a05885ac5c7c4b5f168e30b84c2cc68241f3d85d",
|
|
12
|
+
"agents": "c69351bccb44f5f87b4b112a2a52cd4ace8efac760dcca8f0ab0fc9c95714bb2",
|
|
13
13
|
"moduleDoc:agents/data-surface-discovery.md": "322415405529a3ef941691588306ef1140b7e714a6bb875330c94a0d6423c5d1",
|
|
14
14
|
"moduleDoc:agents/lazy-config.md": "f4bb02ee228e2cf43b4680e71a15732ed2e19eadcc38223be775f3e421fcb05c",
|
|
15
|
-
"moduleDoc:agents/
|
|
15
|
+
"moduleDoc:agents/principal-binding.md": "ce3cf4198cfb4b0394d00b81993b17f6926d07c1a8e430828634611f48fea1fa",
|
|
16
|
+
"moduleDoc:agents/data-surface-denials.md": "63c10bdfe5d551d43646bad918c5f509ca66efcb6814cff836e5980c5e6611b3"
|
|
16
17
|
},
|
|
17
18
|
"exports": [
|
|
18
19
|
".",
|
|
@@ -1875,7 +1876,7 @@
|
|
|
1875
1876
|
"polymorphicAssociations": 0,
|
|
1876
1877
|
"uuidColumns": 18
|
|
1877
1878
|
},
|
|
1878
|
-
"agentDoc": "# @happyvertical/smrt-agents\n\nAgent framework for autonomous actors with inter-agent messaging, interest-based object discovery, scheduling, and multi-tenant bindings.\n\n## Modules\n\n| Module | Contract |\n| --- | --- |\n| [Data-surface discovery](agents/data-surface-discovery.md) | Summary discovery, row-count hints, allowed values, `id`/request aliases |\n| [Lazy agent_config](agents/lazy-config.md) | `$env` sentinels, class `configResolvers`, resolver context and precedence (#1161, #2806) |\n\n## Agent Lifecycle\n\n`initialize()` → `validate()` → `run()` → `shutdown()`\n\n- Extend `Agent` (which extends `SmrtObject`) and implement `run()`\n- Status tracking: `idle → initializing → running → error/skipped/shutdown`\n- `execute()` runs the full lifecycle automatically\n- `AI_UNAVAILABLE` (#4757): `execute()` ends the run `skipped`\n (`runRecord` `{ reason, mode }`), never rethrown or retried; interests\n stop; learning neither reinforces nor decays. Direct `run()` (jobs)\n throws it, `retryable: false`. Agents read only the tenant's mode and\n binding (`inferenceUserScope()` is `null`).\n- Process signal handling is opt-in (`manageProcessSignals: true`), for single-agent processes\n\n## DispatchBus — Inter-Agent Communication\n\nAgents communicate via persistent async messaging through core's DispatchBus:\n\n```typescript\n// Emitting (in any agent)\nconst bus = await this.getDispatch();\nawait bus.emit('campaign.completed', { campaignId: '123' }, { source: 'Suasor' });\n\n// Subscribing (in receiving agent)\nasync handleDispatch(payload: unknown, metadata: DispatchMetadata): Promise<void> {\n if (metadata.type === 'campaign.completed') await this.recordRevenue(payload);\n}\nasync run() { await this.processDispatches(); } // processes via handleDispatch()\n```\n\nCLI: `smrt dispatch:list`, `dispatch:process --subscriber Fiscus`, `dispatch:retry`, `dispatch:cleanup`\n\n## Interests — Object Discovery\n\nAgents query objects they care about via declarative filters:\n\n```typescript\nconstructor(options) {\n super({ ...options, interests: {\n objects: { Meeting: { filter: { status: 'upcoming' }, handler: async (m) => ({ action: 'recap' }) } },\n qualify: async (items) => items.filter(/* AI-based post-filter */),\n }});\n}\nasync run() { for (const { type, data } of await this.interesting()) { ... } }\n```\n\n## Configuration\n\n- **File-based**: `getModuleConfig('agent-name', defaults)` from `smrt.config.ts`\n- **DB-persisted**: `saveSlotConfig(slotId, data)` for UI overrides. Persona-backed\n agents use `AgentOptions.personaId` as the durable config owner; legacy agents\n use the saved Agent row id.\n- **Merged**: `getMergedConfig('slotId')` — DB overrides file config\n- **AI usage (#3077)**: `initialize()` wraps `options.ai` in `withAiUsage()`;\n `resolveAgentAIOptions({ db })` attaches a recorder, so per-call `getAI()`\n clients record for the run's tenant ([ai-usage](../core/agents/ai-usage.md)).\n- **Inference bindings (#4756)**: without `apiKey`/`apiKeySecretName`,\n `resolveAgentAIClientOptions()` takes the stored tenant binding (core\n `resolveInferenceTarget({ appBindings: false, userId: null })`), tags on\n usage rows; never a user's (options outlive the run) or an app tier\n binding. `initialize()` re-resolves, so rotated keys are never kept.\n- **UI slots**: `static uiSlots` declares admin panels (id, label, icon, order,\n `scope`, optional versioned `settingsSchema`). Without a registered custom\n component, `AgentSettingsForm` renders that schema.\n\n## TenantAgent — Multi-Tenant Bindings\n\nJunction table (`tenant_agents`) binding agents to tenants with permission overrides and hierarchy resolution:\n- Explicit binding: row exists for tenant (source: 'explicit')\n- Inherited: walks up tenant hierarchy (source: 'inherited')\n- Permissions: manifest defaults merged with per-tenant overrides\n\n### Config owner id and the #1092 key repair\n\nA binding with no Agent row owns slot configs under\n`tenantAgentConfigOwnerId(tenantId, type)` = `<tenant>:<canonical type>`\n(`serializeResolvedAgent()` uses it). Seeders and schedule sync must compose it\nwith the helper. Rows keyed `<tenant>:<Class>` (pre-#1092) or bindings under a\nbare/renamed type are moved by `repairTenantAgentConfigKeys(db, { aliases,\napply })` (`src/migrations/tenant-agent-config-keys.ts`): dry run by default,\ncounted totals, blocked rows (two spellings of one binding/slot) refuse the\napply, one transaction with a ledger and a post-check; idempotent. Register the\nhost's agent classes (or pass `aliases`) before running it.\n\n## Create entries\n\n`static createEntries: AgentCreateEntry[]` (literal array; the scanner captures\nit into `agent.createEntries`) lets an agent contribute \"create\" options: `id`,\n`type`, `format`, `label`, `description`, `icon`, `route` (relative to the\nhost base path), `order`, `availability` (`permission`, `accessLevels`,\n`requires`). `SerializedAgent.createEntries` carries them;\n`resolveAgentCreateEntries(agents, { basePath, accessLevel, capabilities })`\nfrom `./ui` filters, builds `href`, and sorts. Non-relative routes are dropped.\n\n## AgentSchedule\n\nCron-based scheduling stored in `_smrt_agent_schedules`. Fields: `agentType`, `cron`, `timezone` (IANA, default `UTC`; blank → `UTC`), `method` (default: 'run'), `maxConcurrent`, `timeout`. Executed by ScheduleRunner from smrt-jobs. `calculateNextRun()` and the runner re-arm share smrt-jobs' `getNextCronDate(cron, timezone)`, so both evaluate the cron in the row's zone, DST-correct (#3859); an unknown zone sets `status: 'error'` with the parser message in `lastError`.\n\n## Lazy agent_config Resolution (issue #1161)\n\n`$env` sentinels and `static configResolvers` re-resolve persisted `agent_config` at execute time. Resolvers receive the instance's identity and its own persisted value (#2806). Keep a per-agent credential with `preferPersisted()`, and never select an agent by scanning the tenant's rows. See [agents/lazy-config.md](agents/lazy-config.md).\n\n## Learning Trait (issue #1886) — opt-in\n\nAny agent can opt into a confidence-scored **recall-before / capture-after** loop backed by core's `LearningMemory` (over `_smrt_contexts` + `_smrt_embeddings`). **Off by default** — a non-opted agent behaves byte-for-byte as today; the lifecycle's learning branches are never entered.\n\n```typescript\n@smrt()\nclass InvoiceAgent extends Agent {\n static override learning = true; // or { minConfidence: 0.8, scope: 'invoices', ... }\n protected config = {};\n\n async run() {\n // recall-before-run already populated `recalledMemories` (confidence >= floor)\n const cached = this.recalledMemories.find((m) => m.key === this.docUrl);\n const strategy = cached?.value ?? (await this.generateStrategy());\n\n // stage the episode; the lifecycle reinforces it after run()\n this.stageLearning({ scope: this.learningScope(), key: this.docUrl, value: strategy });\n\n // a validated failure decays the memory without throwing\n if (!ok) this.reportLearningOutcome({ success: false, error: 'no match' });\n }\n}\n```\n\n- **`capture` semantics** (`LearningMemory`): success strengthens `confidence` toward 1.0 and increments `success_count`; failure decays toward `failureConfidence` (0.3) and increments `failure_count`. A single failure drops a confident memory below the reuse floor (0.7), so recall stops returning it. Refreshes `last_used_at`; honours `expires_at` and optional time-decay.\n- **Memory isolation**: bound to `(agentType, agentInstanceId)` as `(owner_class, owner_id)`, so two tenants on the same agent class never share memory. `tenantId` is threaded into the optional semantic-search `where`.\n- **Seams to override**: `learningScope()`, `recallForRun(memory)`, `captureForRun(memory, outcome)`, `getLearningSemanticSearch()`. Helpers for `run()`: `stageLearning(episode)`, `reportLearningOutcome(outcome)`, `getLearningMemory()`, and the `recalledMemories` field.\n- **Config**: `static learning: boolean | AgentLearningConfig` — `{ enabled?, scope?, minConfidence?, successConfidence?, failureConfidence?, reinforcement?, decayHalfLifeMs? }`. `LearningMemory` and its types are re-exported from `@happyvertical/smrt-core`.\n\n## Multi-Instance Agents (issue #1890) — opt-in\n\n`static multiInstance = false` by default: a class is a **singleton** (the N=1 case) and is byte-for-byte unchanged — one dispatch subscriber keyed by the agent type, one memory scope, class-wide interests. Set `static multiInstance = true` to run N durable instances (personas, from `@happyvertical/smrt-personas`) of one class per tenant, each independent.\n\nThe framework provides only the per-instance **identity**; a package scopes its own dispatch/interests to the instance's config by overriding the seams.\n\n- **`AgentOptions.personaId`** — durable persona/settings identity, including\n the default persona. Independent from execution instance identity.\n- **`AgentOptions.instanceKey`** — the durable execution-instance key (typically\n the persona id, but null for the default persona). Honored **only** when\n `multiInstance` is true, so passing it to a non-opted agent is a no-op.\n- **`getInstanceKey()`** → the key, or `null` for a singleton (opt-in off, or no key).\n- **`getDispatchSubscriber()`** → `` `${agentType}#${key}` `` for a multi-instance agent, the bare `agentType` for a singleton. Used everywhere the agent subscribes/seeds/processes, so each instance has its own subscription rows and pending-dispatch queue — two instances never compete for or double-process each other's dispatches. Composed by the exported `instanceScopedSubscriber(agentType, key)`.\n- **`learningScope()`** — suffixed with `#<key>` for a multi-instance agent, so instances learn independently (singleton scope unchanged).\n- **Seams to override** (both default to singleton behavior):\n - `resolveSignalSubscriptions()` — derive **instance-scoped** signal types from the instance config so an emit meant for one instance only matches its subscription.\n - `instanceInterestFilter()` — an `ObjectFilter` AND-merged (as the base layer) into every `interesting()` query so instances partition the objects they process.\n\nThe **`default` persona reuses the singleton identity** (a `null` key), which is what makes the singleton→multi upgrade non-destructive — see `@happyvertical/smrt-personas` (`personaInstanceKey`, `upgradeSingletonToDefaultPersona`).\n\n## Principal Execution (issue #1888)\n\n`executeAsPrincipal(options, fn)` runs agent work **AS a persona's bound user**, reusing the existing RBAC cascade: permissions resolve live unless the caller passes an explicit `permissions` snapshot, which the run then carries as `run.permissionSnapshot`. `agents.invoke` propagates that snapshot as the `DelegationEnvelope.permissions` ceiling, and `executeDelegatedInvocation` runs the worker with ceiling ∩ live grants, so a narrowed run cannot widen through delegation and a tampered persisted ceiling cannot exceed live RBAC (#2978). It publishes `(user_id, tenant_id, permissions[])` onto the DB session (Postgres RLS then bounds every query per-`(table, action)` and per-tenant) and hands `fn` a `PrincipalRun` whose `assertToolAllowed()` / `assertOperation()` enforce the persona tool ceiling and the RLS-off catalog gate. Effective authority = **bound-user RBAC ∩ agent-class ceiling ∩ persona `allowedTools`**. Actions audit as on-behalf-of the originating user via a `PrincipalAuditSink`.\n\n## Data Surface Read Tools (issue #2447)\n\n`createDataSurfaceTools()` produces the `data.discover`, `data.inspect`, and\n`data.query` `PrincipalTool`s consumed through chat's `extraTools` seam. The\ncaller supplies a server-owned surface catalog and executor; the tools copy\n`userId`, `tenantId`, database, and permissions only from the live\n`PrincipalRun`. Discovery and inspection first assert the collection's read\ncatalog permission and omit denied surfaces/fields. Query requests and results\nare normalized with the core bounded data-query protocol, including projection,\ncursor/page, row/byte, fingerprint, freshness, total, and truncation rules.\nSensitive/read-permission fields are removed from descriptors, and\n`DataSurfaceField` policy metadata is stripped before the core schema validator.\nExecutor-provided paginated rows retain their order and are validated with a\nstable identity tie-breaker (including type-aware numeric/date comparisons),\nwhile internal sort keys are stripped when they were not requested in the\nprojection. Execution has a bounded deadline; public executor/result failures\nuse stable generic errors while optional `onFailure` telemetry receives the\nauthenticated/delegated principal and detailed server-side error. Hidden field\nrequest failures also use a stable public error. Tool arguments never contain\nprincipal or tenant authority. `data.query` takes `{surfaceId, request}` or the\nflat form; a key beside `request` (a misplaced `filter`) is a 400\n`DataSurfaceRequestError` (`DATA_QUERY_ARGUMENTS_UNEXPECTED`), never silently\ndropped (#4378). A `surfaceId` nested in `request` (or a `query` wrapper) is\nlifted; two different ids are `DATA_QUERY_SURFACE_ID_CONFLICT`, none is\n`DATA_QUERY_SURFACE_ID_REQUIRED` (400s, not denials). Every request error ends with a one-line valid example for\nthe surface (placeholders only, no caller values).\nNull tests (#4448): the SMRT collection adapter (and content's mirror) adds\n`isNull`/`isNotNull` to a field's `filterOperators` when its manifest column is\nneither `notNull` nor the primary key (`nullableColumnFieldIds`,\n`NULL_TEST_FILTER_OPERATORS`), lowered to `{ field: null }` / `{ 'field !=':\nnull }`; JSON fields stay unfilterable, and a null test on a UUID column skips\nthe id-value check. A rejected filter that looks like a null test on a field\ndeclaring `isNull` (`eq`/`ne` with `null`, `\"null\"`, `\"\"` or `[]`; a `not` naming\n`field`; an `exists`-style kind/operator) gets a hint naming `isNull`/\n`isNotNull` with that field, and the valid example uses it; polarity follows\n`ne` and enclosing `not`s. Grammar: [core data-query](../core/agents/data-query.md#null-tests-4448).\nRefusals (#4387: action-specific denials, the `{ action }` catalog argument,\n`onDenied`, audit `denied` entries, missing executors):\n[agents/data-surface-denials.md](agents/data-surface-denials.md).\n\n\n## Playbook Preflight (issue #2590)\n\n`createPlaybookPreflightTool()` produces the `playbooks.preflight`\n`PrincipalTool`. It resolves a playbook through the caller's own layer chain on\nthe `server` plane and reports a per-step verdict from the two predicates\n`PrincipalRun` already exposes — `isToolAllowed(tool)` and `assertOperation`\n(which evaluates the catalog permission without performing the operation). It\nexecutes nothing.\n\n**Advisory only: preflight predicts, it never grants.** Name gates entry;\ndecomposition gates every step. Preflight computes that intersection ahead of\ntime and replaces neither gate, so a permission revoked between the prediction\nand the execution still denies at execution — proven in\n`playbook-preflight.test.ts`, which lets a cached `allow` stand and shows\n`assertOperation` refusing anyway.\n\n- Step → gating tool slug and permission collection are seams (`toolSlug`,\n `collection`), defaulting to the registered collection slug for the step's\n qualified model (`playbookStepToolSlug` / `playbookStepCollection`).\n- The cache partition key comes from the **live run context**, never the tool\n arguments, so one principal's prediction can never be served to another.\n- An unknown key and an unauthorized key return the same uniform unavailable\n report — the tool is not an enumeration oracle.\n- `filterPlaybooksByPreflight()` hides playbooks a caller could not run from a\n listing. It is a listing convenience and **never** load-bearing for\n authorization; a key it lets through is still authorized step by step.\n\n## Report Data-Surface Tools (issue #2462)\n\n`createReportDataSurfaceTools()` maps server-owned report definitions into the\ngeneric `data.discover`, `data.inspect`, and `data.query` catalog, and adds\nprincipal-bound `reports.query`, `reports.refresh`, `reports.drilldown`, and\n`reports.export` tools. It reuses the reports package's materialized-query,\nlifecycle, drilldown, and snapshot contracts rather than reimplementing them.\nReport ids, collections, query seams, browser delivery, background queues, and\naction hosts come only from the configured server catalog; tool arguments never\ncarry principal, tenant, or report-constructor authority.\n\n- Generic discovery excludes sensitive and permission-gated report columns.\n- Discovered report fields retain safe `kind`, `filterScope`, and capability\n metadata, while the surface reports its available actions and lifecycle\n freshness support. Actions are filtered by the current tool allow-list and\n effective permissions. This lets agents distinguish dimensions/buckets\n (`where`) from measures (`having`) without exposing hidden columns or\n authority.\n- Silent reads do not change browser state; visible reads require a host-bound\n acknowledgement whose post-command revision is not older than the requested\n compare-and-swap revision; background requests contain no principal or tenant\n payload.\n- Read results request the tenant-safe report lifecycle whenever an\n authenticated database is available, so `freshness` and the redacted\n lifecycle state cover stale and lock-skipped materializations.\n- Refresh and export use app-owned action hosts for live authorization and\n auditing. Export captures an opaque immutable snapshot and preserves the\n reports package's preview/confirmation protocol.\n- Drilldown re-reads a single accessible materialized row before it builds the\n inherited source query, so callers cannot inject row values from another\n tenant.\n\n## Agent Orchestration (issue #1892) — invoke-agent + principal delegation\n\nA conversational (orchestrator) agent can invoke worker agents with **principal delegation**. This is *not* a new engine — it is a standard `invoke-agent` tool plus a completion-dispatch convention on top of `executeAsPrincipal` + the DispatchBus.\n\n```typescript\nimport { createInvokeAgentTool, rootDelegationEnvelope } from '@happyvertical/smrt-agents';\n\nconst tool = createInvokeAgentTool({\n db,\n parentEnvelope: rootDelegationEnvelope({ runAsUserId, tenantId, onBehalfOfUserId }),\n worker: async ({ run, agentClass, task }) => runWorker(run, agentClass, task),\n});\n// Offered through the chat tool loop as an `extraTools` entry, gated by the\n// persona's allowedTools like any other tool (slug: 'agents.invoke').\n```\n\n- **`DelegationEnvelope`** carries the **immutable principal** (`runAsUserId` + `tenantId` + originating `onBehalfOfUserId`) and a bounded `depth`. `deriveDelegationEnvelope()` copies the principal verbatim and asserts `depth <= MAX_DELEGATION_DEPTH` (3) — a worker cannot invoke a further worker under a broader principal (`PrincipalWideningError` / `DelegationDepthExceededError`).\n- **`createInvokeAgentTool()`** → a `PrincipalTool` whose handler derives the child envelope with the principal taken **from the live run context, never the tool args**, so the invoke-agent tool is structurally immune to principal widening.\n- **`executeDelegatedInvocation()`** runs the worker via `executeAsPrincipal` under that same principal and emits a correlated `agent.completed` dispatch; **`surfaceAgentCompletions(bus, correlationId)`** reads it back into the conversation.\n- **Transports** (pluggable): the default `inlineInvokeAgentTransport` runs the worker in-process (completion surfaces in the same turn); `createDispatchInvokeTransport(bus)` emits an `agent.invoke` signal a worker processes via `processAgentInvocations()` (async). A job-queue transport (enqueue on the `agents` queue) is a consumer-supplied `InvokeAgentTransport` — orchestration never hard-depends on `@happyvertical/smrt-jobs`, which sits *below* agents in the dependency graph.\n\n## Server Entry Points Stay Svelte-Free (issue #2924)\n\n`SmrtDataSurfaceActionTask`, `DataSurfaceActionTokenState`, and\n`DataSurfaceActionIdempotencyState` stamp `@happyvertical/smrt-agents/server`\nas their manifest `importPath`, so core's consumer plugin emits that specifier\nverbatim into a consumer's generated `.smrt/register.js` — which the `smrt` CLI\nloads with a bare `import()` under plain Node for `db:migrate`. **No module\nreachable from `./server` (or from the package root, or `./vite`) may import a\nSvelte component barrel.** A Vite build of the same graph succeeds, so this\nregresses silently and then breaks `db:migrate` for every object in the\nconsuming app, not just this package's.\n\n- Import shared data-surface protocol limits from the Svelte-free\n `@happyvertical/smrt-ui/data-surface`, never `@happyvertical/smrt-ui/data`\n (a component barrel that re-exports `.svelte` files).\n- `src/server/__tests__/node-entry-loadability.integration.test.ts` imports\n every server-side subpath in a fresh plain-Node process; it needs a built\n `dist/` (turbo's `test` task supplies it).\n- `scripts/verify-manifest-exports.mjs` fails a publish when any **non-root**\n manifest `importPath` is unloadable under plain Node. A bundler-only *root*\n barrel is still only a warning.\n\n## Key Files\n\n| File | Purpose |\n|------|---------|\n| `src/agent.ts` | Base Agent class — lifecycle, dispatch, interests, config, opt-in learning trait, multi-instance identity |\n| `src/execute-as-principal.ts` | `executeAsPrincipal` / `PrincipalRun` — run agent work as a persona's bound user (#1888) |\n| `src/report-data-surface.ts` | Principal-bound report discovery, query, lifecycle, drilldown, and export tools (#2462) |\n| `src/smrt-collection-data-surface.ts` | `createSmrtCollectionDataSurfaceDefinition()`: registry-driven collection → `DataSurfaceDefinition` adapter ([contract](agents/data-surface-discovery.md#collection-adapter-2905)) |\n| `src/delegation.ts` | `DelegationEnvelope` — immutable principal + bounded delegation depth (#1892) |\n| `src/invoke-agent.ts` | `invoke-agent` tool, worker executor, completion-dispatch convention, transports (#1892) |\n| `src/playbook-preflight.ts` | `playbooks.preflight` PrincipalTool — advisory per-step verdicts, never a grant (#2590) |\n| `src/learning.ts` | `AgentLearningConfig` + `resolveAgentLearning()` declaration normalisation |\n| `src/schedule.ts` | AgentSchedule model — cron, execution tracking |\n| `src/tenant-agent.ts` | TenantAgent — junction table, hierarchical resolution |\n| `src/interests.ts` | Interest filter types and configuration |\n| `src/config.ts` | File + DB config management, UI slots |\n\nProtected schedules persist the public `ScheduleAdmissionPolicy` in\n`methodArgs._scheduleAdmissionPolicy` (version, required integrity, queue, keyId).\nOrdinary saves preserve it; trusted hosts use loaded-model\n`reconfigureAdmissionPolicy(policyOrNull, { authorize })` for an explicitly\ncurrent-authorized change. See [durable required admission](../jobs/agents/scheduling.md#durable-required-admission-3346).\nThe owning write guard binds canonical stored JSON and composes with tenancy;\nnever set authorization from constructor options, request JSON or persisted args.\n",
|
|
1879
|
+
"agentDoc": "# @happyvertical/smrt-agents\n\nAgent framework for autonomous actors with inter-agent messaging, interest-based object discovery, scheduling, and multi-tenant bindings.\n\n## Modules\n\n| Module | Contract |\n| --- | --- |\n| [Data-surface discovery](agents/data-surface-discovery.md) | Summary discovery, row-count hints, allowed values, `id`/request aliases |\n| [Lazy agent_config](agents/lazy-config.md) | `$env` sentinels, class `configResolvers`, resolver context and precedence (#1161, #2806) |\n\n## Agent Lifecycle\n\n`initialize()` → `validate()` → `run()` → `shutdown()`\n\n- Extend `Agent` (which extends `SmrtObject`) and implement `run()`\n- Status tracking: `idle → initializing → running → error/skipped/shutdown`\n- `execute()` runs the full lifecycle automatically\n- `AI_UNAVAILABLE` (#4757): `execute()` ends the run `skipped`\n (`runRecord` `{ reason, mode }`), never rethrown or retried; interests\n stop; learning neither reinforces nor decays. Direct `run()` (jobs)\n throws it, `retryable: false`. Agents read only the tenant's mode and\n binding (`inferenceUserScope()` is `null`).\n- Process signal handling is opt-in (`manageProcessSignals: true`), for single-agent processes\n\n## DispatchBus — Inter-Agent Communication\n\nAgents communicate via persistent async messaging through core's DispatchBus:\n\n```typescript\n// Emitting (in any agent)\nconst bus = await this.getDispatch();\nawait bus.emit('campaign.completed', { campaignId: '123' }, { source: 'Suasor' });\n\n// Subscribing (in receiving agent)\nasync handleDispatch(payload: unknown, metadata: DispatchMetadata): Promise<void> {\n if (metadata.type === 'campaign.completed') await this.recordRevenue(payload);\n}\nasync run() { await this.processDispatches(); } // processes via handleDispatch()\n```\n\nCLI: `smrt dispatch:list`, `dispatch:process --subscriber Fiscus`, `dispatch:retry`, `dispatch:cleanup`\n\n## Interests — Object Discovery\n\nAgents query objects they care about via declarative filters:\n\n```typescript\nconstructor(options) {\n super({ ...options, interests: {\n objects: { Meeting: { filter: { status: 'upcoming' }, handler: async (m) => ({ action: 'recap' }) } },\n qualify: async (items) => items.filter(/* AI-based post-filter */),\n }});\n}\nasync run() { for (const { type, data } of await this.interesting()) { ... } }\n```\n\n## Configuration\n\n- **File-based**: `getModuleConfig('agent-name', defaults)` from `smrt.config.ts`\n- **DB-persisted**: `saveSlotConfig(slotId, data)` for UI overrides. Persona-backed\n agents use `AgentOptions.personaId` as the durable config owner; legacy agents\n use the saved Agent row id.\n- **Merged**: `getMergedConfig('slotId')` — DB overrides file config\n- **AI usage (#3077)**: `initialize()` wraps `options.ai` in `withAiUsage()`;\n `resolveAgentAIOptions({ db })` attaches a recorder, so per-call `getAI()`\n clients record for the run's tenant ([ai-usage](../core/agents/ai-usage.md)).\n- **Inference bindings (#4756)**: without `apiKey`/`apiKeySecretName`,\n `resolveAgentAIClientOptions()` takes the stored tenant binding (core\n `resolveInferenceTarget({ appBindings: false, userId: null })`), tags on\n usage rows; never a user's (options outlive the run) or an app tier\n binding. `initialize()` re-resolves, so rotated keys are never kept.\n- **UI slots**: `static uiSlots` declares admin panels (id, label, icon, order,\n `scope`, optional versioned `settingsSchema`). Without a registered custom\n component, `AgentSettingsForm` renders that schema.\n\n## TenantAgent — Multi-Tenant Bindings\n\nJunction table (`tenant_agents`) binding agents to tenants with permission overrides and hierarchy resolution:\n- Explicit binding: row exists for tenant (source: 'explicit')\n- Inherited: walks up tenant hierarchy (source: 'inherited')\n- Permissions: manifest defaults merged with per-tenant overrides\n\n### Config owner id and the #1092 key repair\n\nA binding with no Agent row owns slot configs under\n`tenantAgentConfigOwnerId(tenantId, type)` = `<tenant>:<canonical type>`\n(`serializeResolvedAgent()` uses it). Seeders and schedule sync must compose it\nwith the helper. Rows keyed `<tenant>:<Class>` (pre-#1092) or bindings under a\nbare/renamed type are moved by `repairTenantAgentConfigKeys(db, { aliases,\napply })` (`src/migrations/tenant-agent-config-keys.ts`): dry run by default,\ncounted totals, blocked rows (two spellings of one binding/slot) refuse the\napply, one transaction with a ledger and a post-check; idempotent. Register the\nhost's agent classes (or pass `aliases`) before running it.\n\n## Create entries\n\n`static createEntries: AgentCreateEntry[]` (literal array; the scanner captures\nit into `agent.createEntries`) lets an agent contribute \"create\" options: `id`,\n`type`, `format`, `label`, `description`, `icon`, `route` (relative to the\nhost base path), `order`, `availability` (`permission`, `accessLevels`,\n`requires`). `SerializedAgent.createEntries` carries them;\n`resolveAgentCreateEntries(agents, { basePath, accessLevel, capabilities })`\nfrom `./ui` filters, builds `href`, and sorts. Non-relative routes are dropped.\n\n## AgentSchedule\n\nCron-based scheduling stored in `_smrt_agent_schedules`. Fields: `agentType`, `cron`, `timezone` (IANA, default `UTC`; blank → `UTC`), `method` (default: 'run'), `maxConcurrent`, `timeout`. Executed by ScheduleRunner from smrt-jobs. `calculateNextRun()` and the runner re-arm share smrt-jobs' `getNextCronDate(cron, timezone)`, so both evaluate the cron in the row's zone, DST-correct (#3859); an unknown zone sets `status: 'error'` with the parser message in `lastError`.\n\n## Lazy agent_config Resolution (issue #1161)\n\n`$env` sentinels and `static configResolvers` re-resolve persisted `agent_config` at execute time. Resolvers receive the instance's identity and its own persisted value (#2806). Keep a per-agent credential with `preferPersisted()`, and never select an agent by scanning the tenant's rows. See [agents/lazy-config.md](agents/lazy-config.md).\n\n## Learning Trait (issue #1886) — opt-in\n\nAny agent can opt into a confidence-scored **recall-before / capture-after** loop backed by core's `LearningMemory` (over `_smrt_contexts` + `_smrt_embeddings`). **Off by default** — a non-opted agent behaves byte-for-byte as today; the lifecycle's learning branches are never entered.\n\n```typescript\n@smrt()\nclass InvoiceAgent extends Agent {\n static override learning = true; // or { minConfidence: 0.8, scope: 'invoices', ... }\n protected config = {};\n\n async run() {\n // recall-before-run already populated `recalledMemories` (confidence >= floor)\n const cached = this.recalledMemories.find((m) => m.key === this.docUrl);\n const strategy = cached?.value ?? (await this.generateStrategy());\n\n // stage the episode; the lifecycle reinforces it after run()\n this.stageLearning({ scope: this.learningScope(), key: this.docUrl, value: strategy });\n\n // a validated failure decays the memory without throwing\n if (!ok) this.reportLearningOutcome({ success: false, error: 'no match' });\n }\n}\n```\n\n- **`capture` semantics** (`LearningMemory`): success strengthens `confidence` toward 1.0 and increments `success_count`; failure decays toward `failureConfidence` (0.3) and increments `failure_count`. A single failure drops a confident memory below the reuse floor (0.7), so recall stops returning it. Refreshes `last_used_at`; honours `expires_at` and optional time-decay.\n- **Memory isolation**: bound to `(agentType, agentInstanceId)` as `(owner_class, owner_id)`, so two tenants on the same agent class never share memory. `tenantId` is threaded into the optional semantic-search `where`.\n- **Seams to override**: `learningScope()`, `recallForRun(memory)`, `captureForRun(memory, outcome)`, `getLearningSemanticSearch()`. Helpers for `run()`: `stageLearning(episode)`, `reportLearningOutcome(outcome)`, `getLearningMemory()`, and the `recalledMemories` field.\n- **Config**: `static learning: boolean | AgentLearningConfig` — `{ enabled?, scope?, minConfidence?, successConfidence?, failureConfidence?, reinforcement?, decayHalfLifeMs? }`. `LearningMemory` and its types are re-exported from `@happyvertical/smrt-core`.\n\n## Multi-Instance Agents (issue #1890) — opt-in\n\n`static multiInstance = false` by default: a class is a **singleton** (the N=1 case) and is byte-for-byte unchanged — one dispatch subscriber keyed by the agent type, one memory scope, class-wide interests. Set `static multiInstance = true` to run N durable instances (personas, from `@happyvertical/smrt-personas`) of one class per tenant, each independent.\n\nThe framework provides only the per-instance **identity**; a package scopes its own dispatch/interests to the instance's config by overriding the seams.\n\n- **`AgentOptions.personaId`** — durable persona/settings identity, including\n the default persona. Independent from execution instance identity.\n- **`AgentOptions.instanceKey`** — the durable execution-instance key (typically\n the persona id, but null for the default persona). Honored **only** when\n `multiInstance` is true, so passing it to a non-opted agent is a no-op.\n- **`getInstanceKey()`** → the key, or `null` for a singleton (opt-in off, or no key).\n- **`getDispatchSubscriber()`** → `` `${agentType}#${key}` `` for a multi-instance agent, the bare `agentType` for a singleton. Used everywhere the agent subscribes/seeds/processes, so each instance has its own subscription rows and pending-dispatch queue — two instances never compete for or double-process each other's dispatches. Composed by the exported `instanceScopedSubscriber(agentType, key)`.\n- **`learningScope()`** — suffixed with `#<key>` for a multi-instance agent, so instances learn independently (singleton scope unchanged).\n- **Seams to override** (both default to singleton behavior):\n - `resolveSignalSubscriptions()` — derive **instance-scoped** signal types from the instance config so an emit meant for one instance only matches its subscription.\n - `instanceInterestFilter()` — an `ObjectFilter` AND-merged (as the base layer) into every `interesting()` query so instances partition the objects they process.\n\nThe **`default` persona reuses the singleton identity** (a `null` key), which is what makes the singleton→multi upgrade non-destructive — see `@happyvertical/smrt-personas` (`personaInstanceKey`, `upgradeSingletonToDefaultPersona`).\n\n## Principal Execution (issue #1888)\n\n`executeAsPrincipal(options, fn)` runs agent work **AS a persona's bound user** via the existing RBAC cascade: permissions resolve live unless the caller passes an explicit `permissions` snapshot, which the run then carries as `run.permissionSnapshot`. `agents.invoke` propagates that snapshot as the `DelegationEnvelope.permissions` ceiling, and `executeDelegatedInvocation` runs the worker with ceiling ∩ live grants, so a narrowed run cannot widen via delegation and a tampered ceiling cannot exceed live RBAC (#2978). It publishes `(user_id, tenant_id, permissions[])` onto the DB session (RLS then bounds every query per-`(table, action)` and per-tenant) and hands `fn` a `PrincipalRun` whose `assertToolAllowed()` / `assertOperation()` enforce the persona tool ceiling and the RLS-off catalog gate. Effective authority = **bound-user RBAC ∩ agent-class ceiling ∩ persona `allowedTools`**. Actions audit as on-behalf-of the originating user via a `PrincipalAuditSink`. See [principal-binding](agents/principal-binding.md).\n\n## Data Surface Read Tools (issue #2447)\n\n`createDataSurfaceTools()` produces the `data.discover`, `data.inspect`, and\n`data.query` `PrincipalTool`s consumed through chat's `extraTools` seam. The\ncaller supplies a server-owned surface catalog and executor; the tools copy\n`userId`, `tenantId`, database, and permissions only from the live\n`PrincipalRun`. Discovery and inspection first assert the collection's read\ncatalog permission and omit denied surfaces/fields. Query requests and results\nare normalized with the core bounded data-query protocol, including projection,\ncursor/page, row/byte, fingerprint, freshness, total, and truncation rules.\nSensitive/read-permission fields are removed from descriptors, and\n`DataSurfaceField` policy metadata is stripped before the core schema validator.\nExecutor-provided paginated rows retain their order and are validated with a\nstable identity tie-breaker (including type-aware numeric/date comparisons),\nwhile internal sort keys are stripped when they were not requested in the\nprojection. Execution has a bounded deadline; public executor/result failures\nuse stable generic errors while optional `onFailure` telemetry receives the\nauthenticated/delegated principal and detailed server-side error. Hidden field\nrequest failures also use a stable public error. Tool arguments never contain\nprincipal or tenant authority. `data.query` takes `{surfaceId, request}` or the\nflat form; a key beside `request` (a misplaced `filter`) is a 400\n`DataSurfaceRequestError` (`DATA_QUERY_ARGUMENTS_UNEXPECTED`), never silently\ndropped (#4378). A `surfaceId` nested in `request` (or a `query` wrapper) is\nlifted; two different ids are `DATA_QUERY_SURFACE_ID_CONFLICT`, none is\n`DATA_QUERY_SURFACE_ID_REQUIRED` (400s, not denials). Every request error ends with a one-line valid example for\nthe surface (placeholders only, no caller values).\nNull tests (#4448): the SMRT collection adapter (and content's mirror) adds\n`isNull`/`isNotNull` to a field's `filterOperators` when its manifest column is\nneither `notNull` nor the primary key (`nullableColumnFieldIds`,\n`NULL_TEST_FILTER_OPERATORS`), lowered to `{ field: null }` / `{ 'field !=':\nnull }`; JSON fields stay unfilterable, and a null test on a UUID column skips\nthe id-value check. A rejected filter that looks like a null test on a field\ndeclaring `isNull` (`eq`/`ne` with `null`, `\"null\"`, `\"\"` or `[]`; a `not` naming\n`field`; an `exists`-style kind/operator) gets a hint naming `isNull`/\n`isNotNull` with that field, and the valid example uses it; polarity follows\n`ne` and enclosing `not`s. Grammar: [core data-query](../core/agents/data-query.md#null-tests-4448).\nRefusals (#4387: action-specific denials, the `{ action }` catalog argument,\n`onDenied`, audit `denied` entries, missing executors):\n[agents/data-surface-denials.md](agents/data-surface-denials.md).\nAction `visibleTo`: [#2986](agents/data-surface-denials.md#action-visibility-2986).\n\n\n## Playbook Preflight (issue #2590)\n\n`createPlaybookPreflightTool()` produces the `playbooks.preflight`\n`PrincipalTool`. It resolves a playbook through the caller's own layer chain on\nthe `server` plane and reports a per-step verdict from the two predicates\n`PrincipalRun` already exposes — `isToolAllowed(tool)` and `assertOperation`\n(which evaluates the catalog permission without performing the operation). It\nexecutes nothing.\n\n**Advisory only: preflight predicts, it never grants.** Name gates entry;\ndecomposition gates every step. Preflight computes that intersection ahead of\ntime and replaces neither gate, so a permission revoked between the prediction\nand the execution still denies at execution — proven in\n`playbook-preflight.test.ts`, which lets a cached `allow` stand and shows\n`assertOperation` refusing anyway.\n\n- Step → gating tool slug and permission collection are seams (`toolSlug`,\n `collection`), defaulting to the registered collection slug for the step's\n qualified model (`playbookStepToolSlug` / `playbookStepCollection`).\n- The cache partition key comes from the **live run context**, never the tool\n arguments, so one principal's prediction can never be served to another.\n- An unknown key and an unauthorized key return the same uniform unavailable\n report — the tool is not an enumeration oracle.\n- `filterPlaybooksByPreflight()` hides playbooks a caller could not run from a\n listing. It is a listing convenience and **never** load-bearing for\n authorization; a key it lets through is still authorized step by step.\n\n## Report Data-Surface Tools (issue #2462)\n\n`createReportDataSurfaceTools()` maps server-owned report definitions into the\ngeneric `data.discover`, `data.inspect`, and `data.query` catalog, and adds\nprincipal-bound `reports.query`, `reports.refresh`, `reports.drilldown`, and\n`reports.export` tools. It reuses the reports package's materialized-query,\nlifecycle, drilldown, and snapshot contracts rather than reimplementing them.\nReport ids, collections, query seams, browser delivery, background queues, and\naction hosts come only from the configured server catalog; tool arguments never\ncarry principal, tenant, or report-constructor authority.\n\n- Generic discovery excludes sensitive and permission-gated report columns.\n- Discovered report fields retain safe `kind`, `filterScope`, and capability\n metadata, while the surface reports its available actions and lifecycle\n freshness support. Actions are filtered by the current tool allow-list and\n effective permissions. This lets agents distinguish dimensions/buckets\n (`where`) from measures (`having`) without exposing hidden columns or\n authority.\n- Silent reads do not change browser state; visible reads require a host-bound\n acknowledgement whose post-command revision is not older than the requested\n compare-and-swap revision; background requests contain no principal or tenant\n payload.\n- Read results request the tenant-safe report lifecycle whenever an\n authenticated database is available, so `freshness` and the redacted\n lifecycle state cover stale and lock-skipped materializations.\n- Refresh and export use app-owned action hosts for live authorization and\n auditing. Export captures an opaque immutable snapshot and preserves the\n reports package's preview/confirmation protocol.\n- Drilldown re-reads a single accessible materialized row before it builds the\n inherited source query, so callers cannot inject row values from another\n tenant.\n\n## Agent Orchestration (issue #1892) — invoke-agent + principal delegation\n\nA conversational (orchestrator) agent can invoke worker agents with **principal delegation**. This is *not* a new engine — it is a standard `invoke-agent` tool plus a completion-dispatch convention on top of `executeAsPrincipal` + the DispatchBus.\n\n```typescript\nimport { createInvokeAgentTool, rootDelegationEnvelope } from '@happyvertical/smrt-agents';\n\nconst tool = createInvokeAgentTool({\n db,\n parentEnvelope: rootDelegationEnvelope({ runAsUserId, tenantId, onBehalfOfUserId }),\n worker: async ({ run, agentClass, task }) => runWorker(run, agentClass, task),\n});\n// Offered through the chat tool loop as an `extraTools` entry, gated by the\n// persona's allowedTools like any other tool (slug: 'agents.invoke').\n```\n\n- **`DelegationEnvelope`** carries the **immutable principal** (`runAsUserId` + `tenantId` + originating `onBehalfOfUserId`) and a bounded `depth`. `deriveDelegationEnvelope()` copies the principal verbatim and asserts `depth <= MAX_DELEGATION_DEPTH` (3) — a worker cannot invoke a further worker under a broader principal (`PrincipalWideningError` / `DelegationDepthExceededError`).\n- **`createInvokeAgentTool()`** → a `PrincipalTool` whose handler derives the child envelope with the principal taken **from the live run context, never the tool args**, so the invoke-agent tool is structurally immune to principal widening.\n- **`executeDelegatedInvocation()`** runs the worker via `executeAsPrincipal` under that same principal and emits a correlated `agent.completed` dispatch; **`surfaceAgentCompletions(bus, correlationId)`** reads it back into the conversation.\n- **Transports** (pluggable): the default `inlineInvokeAgentTransport` runs the worker in-process (completion surfaces in the same turn); `createDispatchInvokeTransport(bus)` emits an `agent.invoke` signal a worker processes via `processAgentInvocations()` (async). A job-queue transport (enqueue on the `agents` queue) is a consumer-supplied `InvokeAgentTransport` — orchestration never hard-depends on `@happyvertical/smrt-jobs`, which sits *below* agents in the dependency graph.\n\n## Server Entry Points Stay Svelte-Free (issue #2924)\n\n`SmrtDataSurfaceActionTask`, `DataSurfaceActionTokenState`, and\n`DataSurfaceActionIdempotencyState` stamp `@happyvertical/smrt-agents/server`\nas their manifest `importPath`, so core's consumer plugin emits that specifier\nverbatim into a consumer's generated `.smrt/register.js` — which the `smrt` CLI\nloads with a bare `import()` under plain Node for `db:migrate`. **No module\nreachable from `./server` (or from the package root, or `./vite`) may import a\nSvelte component barrel.** A Vite build of the same graph succeeds, so this\nregresses silently and then breaks `db:migrate` for every object in the\nconsuming app, not just this package's.\n\n- Import shared data-surface protocol limits from the Svelte-free\n `@happyvertical/smrt-ui/data-surface`, never `@happyvertical/smrt-ui/data`\n (a component barrel that re-exports `.svelte` files).\n- `src/server/__tests__/node-entry-loadability.integration.test.ts` imports\n every server-side subpath in a fresh plain-Node process; it needs a built\n `dist/` (turbo's `test` task supplies it).\n- `scripts/verify-manifest-exports.mjs` fails a publish when any **non-root**\n manifest `importPath` is unloadable under plain Node. A bundler-only *root*\n barrel is still only a warning.\n\n## Key Files\n\n| File | Purpose |\n|------|---------|\n| `src/agent.ts` | Base Agent class — lifecycle, dispatch, interests, config, opt-in learning trait, multi-instance identity |\n| `src/execute-as-principal.ts` | `executeAsPrincipal` / `PrincipalRun` — run agent work as a persona's bound user (#1888) |\n| `src/report-data-surface.ts` | Principal-bound report discovery, query, lifecycle, drilldown, and export tools (#2462) |\n| `src/smrt-collection-data-surface.ts` | `createSmrtCollectionDataSurfaceDefinition()`: registry-driven collection → `DataSurfaceDefinition` adapter ([contract](agents/data-surface-discovery.md#collection-adapter-2905)) |\n| `src/delegation.ts` | `DelegationEnvelope` — immutable principal + bounded delegation depth (#1892) |\n| `src/invoke-agent.ts` | `invoke-agent` tool, worker executor, completion-dispatch convention, transports (#1892) |\n| `src/playbook-preflight.ts` | `playbooks.preflight` PrincipalTool — advisory per-step verdicts, never a grant (#2590) |\n| `src/learning.ts` | `AgentLearningConfig` + `resolveAgentLearning()` declaration normalisation |\n| `src/schedule.ts` | AgentSchedule model — cron, execution tracking |\n| `src/tenant-agent.ts` | TenantAgent — junction table, hierarchical resolution |\n| `src/interests.ts` | Interest filter types and configuration |\n| `src/config.ts` | File + DB config management, UI slots |\n\nProtected schedules persist the public `ScheduleAdmissionPolicy` in\n`methodArgs._scheduleAdmissionPolicy` (version, required integrity, queue, keyId).\nOrdinary saves preserve it; trusted hosts use loaded-model\n`reconfigureAdmissionPolicy(policyOrNull, { authorize })` for an explicitly\ncurrent-authorized change. See [durable required admission](../jobs/agents/scheduling.md#durable-required-admission-3346).\nThe owning write guard binds canonical stored JSON and composes with tenancy;\nnever set authorization from constructor options, request JSON or persisted args.\n",
|
|
1879
1880
|
"moduleDocs": [
|
|
1880
1881
|
{
|
|
1881
1882
|
"path": "agents/data-surface-discovery.md",
|
|
@@ -1887,10 +1888,15 @@
|
|
|
1887
1888
|
"module": "lazy-config",
|
|
1888
1889
|
"content": "# Lazy agent_config resolution (#1161, #2806)\n\nPersisted `agent_config` snapshots env-derived values at sync time, so rotated env vars don't reach already-stored schedule rows. Two complementary mechanisms unfreeze them:\n\n1. **`$env` sentinels in persisted config** — register a global resolver and reference it from the JSON:\n\n ```ts\n import { registerConfigResolver } from '@happyvertical/smrt-agents';\n registerConfigResolver('sharedAssetStorage', () => resolveSharedAssetStorage());\n // persisted: { \"assetStorage\": { \"$env\": \"sharedAssetStorage\" } }\n ```\n\n2. **`static configResolvers` on the agent class** — declarative, discoverable via the class itself:\n\n ```ts\n class Praeco extends Agent {\n static override configResolvers = {\n assetStorage: () => resolveSharedAssetStorage(),\n };\n }\n ```\n\nThe TaskRunner calls `resolveLazyConfig()` immediately before constructing the agent, so live values always win over snapshotted ones. Re-exported from `@happyvertical/smrt-core` (`resolveLazyConfig`, `registerConfigResolver`, `getClassConfigResolvers`, …) for cases where agents isn't on the import path.\n\n**Resolver context and precedence (#2806).** Every resolver receives a frozen `ConfigResolverContext`. It holds this instance's `agentId` (the job's `objectId`), canonical `agentClass`, `tenantId`, `scheduleId` and `jobId`. Class resolvers also get the instance's own persisted value for the key (`persisted`, `hasPersisted`); sentinel resolvers get the value's `path`. Precedence:\n1. a non-null resolver result;\n2. the persisted value, kept on `undefined` / `null`;\n3. absent.\n\nA deployment fallback that must not clobber an agent's own value, such as its provider credential, uses `preferPersisted(fallback)` or returns `undefined` when `context.hasPersisted`. Never select an agent by scanning the tenant's `agent_configs` rows: with several agents of one class per tenant, that leaks one agent's credential to another. Use `context.agentId`. Zero-argument resolvers remain valid.\n\nCaveats:\n- `scheduleId` is echoed from job args without verification, so never key a per-agent value on it.\n- `persisted` is neither copied nor deep-frozen. Treat it as read-only.\n- Only `undefined` / `null` count as absent for `preferPersisted`. A present but empty value such as `{}` is kept.\n"
|
|
1889
1890
|
},
|
|
1891
|
+
{
|
|
1892
|
+
"path": "agents/principal-binding.md",
|
|
1893
|
+
"module": "principal-binding",
|
|
1894
|
+
"content": "# PrincipalBinding server-set facts (#2944)\n\n`PrincipalBinding` takes optional **server-set** `sessionId`, `credentialKind`\n(`'session' | 'device' | 'api-key' | 'oauth' | 'service' | string`), and\n`bindingMetadata` (JSON record). They reach `PrincipalRun` as:\n\n- `run.sessionId` and `run.context.sessionId` (plumbed through\n `withPrincipalPermissionContext({ sessionId })`; `context.session` stays\n `null` — no session object is loaded or fabricated; absent means `null`),\n- `run.credentialKind` (absent when not supplied),\n- `run.bindingMetadata`: a frozen deep clone, so a run cannot mutate the\n binding (absent when not supplied).\n\nHosts must set these from verified server auth state, never from browser or\nuser input. They are descriptive passthroughs: they never feed `allowedTools`\n(still fail-closed) or permission resolution. Use them instead of encoding\n\"how did this run authenticate\" as a marker slug in `allowedTools`.\n\n`sessionId` is an **unverified server-set label**, not an authenticated\nsession: `smrt.session_id` (the Postgres RLS GUC) stays empty for principal\nruns, since only a loaded session may populate it. `bindingMetadata` must be\nJSON-safe; Date, Map, typed arrays, class instances, and cycles throw a clear\n`TypeError` before the run starts.\n"
|
|
1895
|
+
},
|
|
1890
1896
|
{
|
|
1891
1897
|
"path": "agents/data-surface-denials.md",
|
|
1892
1898
|
"module": "data-surface-denials",
|
|
1893
|
-
"content": "# Data-surface refusals (#4387)\n\nModule doc for `src/data-surface.ts`, linked from `packages/agents/AGENTS.md`.\n\na surface visible for a lesser action (`discover`/`inspect`)\nbut not the requested one gets `DataSurfaceActionDeniedError` naming the action\nand that visible id; an invisible surface keeps the generic\n`DataSurfaceDeniedError`. A function catalog receives `{ action }` (the report\ntools forward it to a `reports` function); on the denial path only, it is\nre-evaluated for the lesser actions (at most two calls, once each, a throw\nreported to `onFailure`), and a lesser action counts only when its own tool is\nallowed. Limit an action through the per-action catalog, never by leaving out\nthe executor: a visible surface with no executor is a configuration failure\n(`onFailure`, `DataSurfaceQueryError`). Allow-list refusals and surface denials\ngo to `onDenied` (action, visible surface id only, the model's `requestId`,\nthe run's user when it has one, `reason`: `not_visible` |\n`action_not_permitted` | `tool_not_allowed`) and to the audit sink as an\nentry with `denied: true` and the same `action` as a call — audit consumers\nmust branch on `denied`. A run without a user gets no audit entry (as on\nsuccess); a throwing audit sink is reported to `onFailure` and the refusal\nstands. `onDenied` is separate from `onFailure`: a denial is an authorization\noutcome, not a server error. Request errors (including hidden fields, which\nget `DATA_QUERY_FIELD_NOT_ALLOWED`) are not denials.\n"
|
|
1899
|
+
"content": "# Data-surface refusals (#4387)\n\nModule doc for `src/data-surface.ts`, linked from `packages/agents/AGENTS.md`.\n\na surface visible for a lesser action (`discover`/`inspect`)\nbut not the requested one gets `DataSurfaceActionDeniedError` naming the action\nand that visible id; an invisible surface keeps the generic\n`DataSurfaceDeniedError`. A function catalog receives `{ action }` (the report\ntools forward it to a `reports` function); on the denial path only, it is\nre-evaluated for the lesser actions (at most two calls, once each, a throw\nreported to `onFailure`), and a lesser action counts only when its own tool is\nallowed. Limit an action through the per-action catalog, never by leaving out\nthe executor: a visible surface with no executor is a configuration failure\n(`onFailure`, `DataSurfaceQueryError`). Allow-list refusals and surface denials\ngo to `onDenied` (action, visible surface id only, the model's `requestId`,\nthe run's user when it has one, `reason`: `not_visible` |\n`action_not_permitted` | `tool_not_allowed`) and to the audit sink as an\nentry with `denied: true` and the same `action` as a call — audit consumers\nmust branch on `denied`. A run without a user gets no audit entry (as on\nsuccess); a throwing audit sink is reported to `onFailure` and the refusal\nstands. `onDenied` is separate from `onFailure`: a denial is an authorization\noutcome, not a server error. Request errors (including hidden fields, which\nget `DATA_QUERY_FIELD_NOT_ALLOWED`) are not denials.\n\n## Action visibility (#2986)\n\n`DataSurfaceServerActionDefinition.visibleTo?({ run, descriptor, action })` is\nthe per-principal gate for actions that exist on a surface but that this\nprincipal may neither see nor run. `createDataSurfaceActionAdapter` evaluates it\nin `resolveInvocation` before the descriptor/map consistency check: a false,\nnon-`true`, throwing, or rejecting result refuses `denied` (fail closed); an id\nabsent from the surface's action map still refuses `unsupported`. `denied` vs\n`unsupported` is therefore a truthful existence signal, so a host that must not\nreveal an action's existence should omit it from the surface instead.\nDescribe-style reads return `visibleDataSurfaceDescriptor(run, surface)`, which\ndrops hidden actions from the descriptor. Without the seam behaviour is\nunchanged.\n"
|
|
1894
1900
|
}
|
|
1895
1901
|
],
|
|
1896
1902
|
"browser": {
|
|
@@ -5,10 +5,10 @@ description: "Agent framework for building autonomous actors in the SMRT ecosyst
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-17T19:38:34Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:4237702881c12f769b5d4195a67e2c4e476df7c743e9cb9f8ac3cf39fbe54b2e"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/agents/package.json"
|
|
@@ -25,6 +25,9 @@ sources:
|
|
|
25
25
|
- id: "agents-4"
|
|
26
26
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/agents/agents/lazy-config.md"
|
|
27
27
|
title: "@happyvertical/smrt-agents packages/agents/agents/lazy-config.md"
|
|
28
|
+
- id: "agents-5"
|
|
29
|
+
resource: "https://github.com/happyvertical/smrt/blob/main/packages/agents/agents/principal-binding.md"
|
|
30
|
+
title: "@happyvertical/smrt-agents packages/agents/agents/principal-binding.md"
|
|
28
31
|
---
|
|
29
32
|
|
|
30
33
|
# @happyvertical/smrt-agents
|
|
@@ -42,6 +45,7 @@ sources:
|
|
|
42
45
|
- `packages/agents/agents/data-surface-denials.md`
|
|
43
46
|
- `packages/agents/agents/data-surface-discovery.md`
|
|
44
47
|
- `packages/agents/agents/lazy-config.md`
|
|
48
|
+
- `packages/agents/agents/principal-binding.md`
|
|
45
49
|
|
|
46
50
|
## Framework dependencies
|
|
47
51
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-agents",
|
|
3
|
-
"version": "0.62.
|
|
3
|
+
"version": "0.62.6",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"smrtRawPrimitives": "strict",
|
|
@@ -61,21 +61,21 @@
|
|
|
61
61
|
"@happyvertical/ai": "^0.113.0",
|
|
62
62
|
"@happyvertical/files": "^0.113.0",
|
|
63
63
|
"@happyvertical/logger": "^0.113.0",
|
|
64
|
-
"@happyvertical/smrt-config": "0.62.
|
|
65
|
-
"@happyvertical/smrt-core": "0.62.
|
|
66
|
-
"@happyvertical/smrt-jobs": "0.62.
|
|
67
|
-
"@happyvertical/smrt-playbooks": "0.62.
|
|
68
|
-
"@happyvertical/smrt-reports": "0.62.
|
|
69
|
-
"@happyvertical/smrt-secrets": "0.62.
|
|
70
|
-
"@happyvertical/smrt-tenancy": "0.62.
|
|
71
|
-
"@happyvertical/smrt-types": "0.62.
|
|
72
|
-
"@happyvertical/smrt-ui": "0.62.
|
|
73
|
-
"@happyvertical/smrt-users": "0.62.
|
|
64
|
+
"@happyvertical/smrt-config": "0.62.6",
|
|
65
|
+
"@happyvertical/smrt-core": "0.62.6",
|
|
66
|
+
"@happyvertical/smrt-jobs": "0.62.6",
|
|
67
|
+
"@happyvertical/smrt-playbooks": "0.62.6",
|
|
68
|
+
"@happyvertical/smrt-reports": "0.62.6",
|
|
69
|
+
"@happyvertical/smrt-secrets": "0.62.6",
|
|
70
|
+
"@happyvertical/smrt-tenancy": "0.62.6",
|
|
71
|
+
"@happyvertical/smrt-types": "0.62.6",
|
|
72
|
+
"@happyvertical/smrt-ui": "0.62.6",
|
|
73
|
+
"@happyvertical/smrt-users": "0.62.6",
|
|
74
74
|
"@happyvertical/sql": "^0.113.0",
|
|
75
75
|
"@happyvertical/utils": "^0.113.0"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
|
-
"@happyvertical/smrt-vitest": "0.62.
|
|
78
|
+
"@happyvertical/smrt-vitest": "0.62.6",
|
|
79
79
|
"@happyvertical/sql": "^0.113.0",
|
|
80
80
|
"@sentry/node": "^10.75.0",
|
|
81
81
|
"@sveltejs/package": "^2.5.8",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execute-as-principal-tnjcjKIp.js","names":["tenantId"],"sources":["../../src/identity.ts","../../src/config.ts","../../src/execute-as-principal.ts"],"sourcesContent":["import { getClassName, ObjectRegistry } from '@happyvertical/smrt-core';\n\n/**\n * Return the canonical agent type identifier for storage and dispatch routing.\n *\n * Uses the registry's qualified name when available and falls back to the input\n * name for dynamically defined or unregistered classes.\n */\nexport function getAgentTypeName(name: string): string {\n const registered = ObjectRegistry.getClass(name);\n return registered?.qualifiedName || registered?.name || name;\n}\n\n/**\n * Return the human-readable class name for UI and logs.\n */\nexport function getAgentClassName(name: string): string {\n const registered = ObjectRegistry.getClass(name);\n return registered?.name || getClassName(name);\n}\n\n/**\n * Return all meaningful aliases for an agent type.\n *\n * The qualified name is first so persistence lookups prefer canonical rows,\n * while the simple class name keeps legacy rows discoverable during migration.\n */\nexport function getAgentTypeAliases(name: string): string[] {\n return Array.from(\n new Set([getAgentTypeName(name), getAgentClassName(name)].filter(Boolean)),\n );\n}\n\n/**\n * Compose a per-instance dispatch subscriber identity from an agent type and an\n * optional instance key (#1890).\n *\n * Multiple durable instances of one agent class each need their own subscriber\n * name so their dispatch subscriptions and pending dispatches never collide —\n * that is what keeps two instances from double-processing each other's work.\n *\n * Returns the bare `agentType` when `instanceKey` is nullish/empty, so a\n * **singleton** agent's subscriber is byte-for-byte unchanged (the N=1 default).\n * When a key is present the identity is `` `${agentType}#${instanceKey}` `` — a\n * stable, reversible composition (the type never contains `#`).\n */\nexport function instanceScopedSubscriber(\n agentType: string,\n instanceKey?: string | null,\n): string {\n return instanceKey ? `${agentType}#${instanceKey}` : agentType;\n}\n\n/**\n * The `agent_configs.agent_id` that owns a tenant-bound agent's slot config\n * when the binding has no persisted Agent row: `<tenantId>:<agentType>`,\n * with the type canonicalized through {@link getAgentTypeName} (qualified\n * `@scope/package:Class` when the class is registered).\n *\n * `serializeResolvedAgent()` gives a resolved agent this id, and the admin\n * settings panels read and save slot configs under it, so seeders, schedule\n * sync, and any other writer must compose it with this helper rather than by\n * hand. Before smrt #1092 the id used the bare class name\n * (`<tenant>:Praeco`); `repairTenantAgentConfigKeys()` moves such rows.\n */\nexport function tenantAgentConfigOwnerId(\n tenantId: string,\n agentType: string,\n): string {\n return `${tenantId}:${getAgentTypeName(agentType)}`;\n}\n\n/**\n * Split a {@link tenantAgentConfigOwnerId} for a known tenant: the stored\n * agent type after `<tenantId>:`, or null when the owner id is not\n * tenant-derived (a persona id, an Agent row id, another tenant's key).\n */\nexport function parseTenantAgentConfigOwnerId(\n ownerId: string,\n tenantId: string,\n): string | null {\n if (!tenantId) return null;\n const prefix = `${tenantId}:`;\n if (!ownerId.startsWith(prefix)) return null;\n const agentType = ownerId.slice(prefix.length);\n return agentType || null;\n}\n","/**\n * AgentConfig - Persistent configuration storage for agents\n *\n * This module provides database-backed configuration for agents,\n * enabling consuming apps to persist agent settings.\n *\n * @module\n */\n\nimport {\n field,\n type SmrtClassOptions,\n SmrtCollection,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport {\n queryGlobal,\n queryWithGlobals,\n TenantScoped,\n tenantId,\n} from '@happyvertical/smrt-tenancy';\nimport { getAgentTypeName } from './identity.js';\n\n/**\n * AgentConfig stores agent configuration in the database\n *\n * Each config record maps to a UI slot for an agent configuration owner:\n * - agentId: The durable config owner ID (persona ID for persona-backed\n * instances; Agent STI row ID for legacy/singleton instances)\n * - agentClass: The canonical agent type (qualified name when available)\n * - slotId: The configuration slot (e.g., 'sources', 'settings')\n * - configData: JSON object containing the configuration\n *\n * @example\n * ```typescript\n * // Save config for an agent slot\n * const config = new AgentConfig({\n * agentId: agent.id,\n * agentClass: 'Praeco',\n * slotId: 'sources',\n * configData: { scrapers: ['civicweb', 'govstack'] },\n * db: options.db\n * });\n * await config.initialize();\n * await config.save();\n * ```\n */\n@TenantScoped({ mode: 'optional' })\n@smrt({\n tableName: 'agent_configs',\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class AgentConfig extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-agents\";\n /**\n * Tenant ID for multi-tenant isolation\n * Nullable to support both tenant-scoped and global agent configs\n */\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n /**\n * Durable configuration owner ID.\n *\n * The database column retains the historical `agent_id` name for backward\n * compatibility. Persona-backed runtimes store their `AgentPersona.id` here;\n * legacy runtimes store the persisted Agent STI row id.\n */\n @field({ type: 'text' })\n agentId: string = '';\n\n /**\n * Canonical agent type for this config (qualified name when available)\n */\n @field({ type: 'text' })\n agentClass: string = '';\n\n /**\n * UI slot ID (e.g., 'sources', 'settings', 'reports')\n */\n @field({ type: 'text' })\n slotId: string = '';\n\n /**\n * Configuration data stored as JSON\n *\n * Sensitive (#1540) for backward compatibility with legacy blobs, so this is\n * excluded from generated API/MCP responses and rejected as a `where` filter\n * key. New settings schemas must keep credentials in a dedicated secrets\n * service rather than this field.\n */\n @field({ type: 'json', sensitive: true })\n configData: Record<string, unknown> = {};\n\n /**\n * Schema version for future migrations\n */\n @field({ type: 'integer' })\n schemaVersion: number = 1;\n\n /**\n * Load all configs for a specific agent\n *\n * @param agentId - Agent instance ID\n * @param options - Database options\n * @returns Map of slotId → configData\n */\n static async forAgent(\n agentId: string,\n options: SmrtClassOptions,\n ): Promise<Map<string, Record<string, unknown>>> {\n const configsByAgent = await AgentConfig.forAgents([agentId], options);\n return configsByAgent.get(agentId) ?? new Map();\n }\n\n /**\n * Load configs for multiple agents in a single query.\n *\n * @param agentIds - Agent instance IDs\n * @param options - Database options\n * @returns Map of agentId -> (slotId -> configData)\n */\n static async forAgents(\n agentIds: string[],\n options: SmrtClassOptions,\n ): Promise<Map<string, Map<string, Record<string, unknown>>>> {\n const configsByAgent = new Map<\n string,\n Map<string, Record<string, unknown>>\n >();\n if (agentIds.length === 0) {\n return configsByAgent;\n }\n\n const collection = await AgentConfigCollection.create(options);\n const configs = await collection.list({\n where: { 'agentId in': agentIds },\n });\n\n for (const config of configs) {\n if (!configsByAgent.has(config.agentId)) {\n configsByAgent.set(config.agentId, new Map());\n }\n configsByAgent.get(config.agentId)?.set(config.slotId, config.configData);\n }\n\n return configsByAgent;\n }\n\n /**\n * Load config for a specific agent and slot\n *\n * @param agentId - Agent instance ID\n * @param slotId - UI slot ID\n * @param options - Database options\n * @returns Config data or undefined if not found\n */\n static async forSlot(\n agentId: string,\n slotId: string,\n options: SmrtClassOptions,\n ): Promise<Record<string, unknown> | undefined> {\n const collection = await AgentConfigCollection.create(options);\n const configs = await collection.list({\n where: { agentId, slotId },\n limit: 1,\n });\n return configs[0]?.configData;\n }\n\n /**\n * Save or update config for an agent slot\n *\n * @param data - Config data including agentId, agentClass, slotId, configData\n * @param options - Database options\n * @returns Saved AgentConfig instance\n */\n static async saveSlot(\n data: {\n agentId: string;\n agentClass: string;\n slotId: string;\n configData: Record<string, unknown>;\n },\n options: SmrtClassOptions,\n ): Promise<AgentConfig> {\n const normalizedAgentClass = getAgentTypeName(data.agentClass);\n const collection = await AgentConfigCollection.create(options);\n\n // Check for existing config using list with where clause\n const existingConfigs = await collection.list({\n where: { agentId: data.agentId, slotId: data.slotId },\n limit: 1,\n });\n\n if (existingConfigs.length > 0) {\n // Update existing\n const existing = existingConfigs[0];\n existing.configData = data.configData;\n existing.agentClass = normalizedAgentClass;\n await existing.save();\n return existing;\n }\n\n // Create new\n const config = await collection.create({\n agentId: data.agentId,\n agentClass: normalizedAgentClass,\n slotId: data.slotId,\n configData: data.configData,\n slug: `${data.agentId}-${data.slotId}`,\n });\n await config.save();\n return config;\n }\n}\n\n/**\n * Collection for AgentConfig objects\n */\nexport class AgentConfigCollection extends SmrtCollection<AgentConfig> {\n static readonly _itemClass = AgentConfig;\n\n /**\n * Find all configs for a specific tenant\n * @param tenantId - Tenant ID to filter by\n * @returns Array of AgentConfig objects for the tenant\n */\n async findByTenant(tenantId: string): Promise<AgentConfig[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global configs (not associated with any tenant).\n *\n * Routes through the shared tenant-global helper so it does not throw under\n * an active tenant context (an explicit `tenant_id IS NULL` filter would be\n * flagged as an isolation violation). (#1600)\n *\n * @returns Array of global AgentConfig objects\n */\n async findGlobal(): Promise<AgentConfig[]> {\n return queryGlobal<AgentConfig>(this);\n }\n\n /**\n * Find configs for a tenant including global configs.\n *\n * Fails closed if an active tenant context requests a different tenant's\n * rows; the admin/system path keeps the cross-tenant capability. (#1600)\n *\n * @param tenantId - Tenant ID to include\n * @returns Array of AgentConfig objects for the tenant and global configs\n */\n async findWithGlobals(tenantId: string): Promise<AgentConfig[]> {\n return queryWithGlobals<AgentConfig>(\n this,\n tenantId,\n 'AgentConfig.findWithGlobals',\n );\n }\n}\n","/**\n * ExecuteAsPrincipal — run an agent's work AS its persona's bound user.\n *\n * This is deliberately NOT a new authorization layer. It reuses the framework's\n * existing principal-context machinery:\n *\n * - {@link withPrincipalPermissionContext} resolves the bound user's *live*\n * permission set (the standard {@link PermissionResolver} cascade) and\n * publishes `(smrt.user_id, smrt.tenant_id, smrt.permissions[])` onto the DB\n * session. With Postgres RLS enabled, the manifest-derived policies then bound\n * every query the agent makes per-`(table, action)` and per-tenant — through\n * any door (in-process \"side door\", REST, MCP), with no per-call re-checking.\n *\n * - Because RLS is Postgres-only and opt-in, the exec/tool seam must ALSO assert\n * the catalog permission for the `(collection, action)` when RLS is off\n * (SQLite/dev). {@link PrincipalRun.assertOperation} wraps\n * `assertOperationPermission` for exactly that, so the authority bound holds\n * on every adapter.\n *\n * The effective authority of an agent action is therefore:\n *\n * bound-user RBAC ∩ agent-class capability ceiling ∩ persona allowedTools\n *\n * where the RBAC half is enforced at the data layer (RLS) or the catalog seam\n * (`assertOperation`), and the tool half is enforced by\n * {@link PrincipalRun.assertToolAllowed} against `allowedTools` — which a\n * resolved persona has already intersected with the `TenantAgent` ceiling.\n *\n * Actions audit as on-behalf-of the originating user (see {@link PrincipalAuditEntry}).\n *\n * @packageDocumentation\n */\n\nimport { createLogger, type Logger } from '@happyvertical/logger';\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport {\n assertOperationPermission,\n type OperationPermissionCollectionInput,\n type OperationPermissionDecision,\n type PermissionResolver,\n type SessionPermissionRuntimeContext,\n withPrincipalPermissionContext,\n} from '@happyvertical/smrt-users';\n\n/**\n * The bound principal an agent runs as. A resolved persona structurally\n * satisfies this once its optional `runAsUserId` has been narrowed to a\n * concrete id — `allowedTools` on a `ResolvedPersona` is already the persona's\n * tools intersected with the `TenantAgent` capability ceiling.\n */\nexport interface PrincipalBinding {\n /** The user whose live permissions bound this execution. Required. */\n runAsUserId: string;\n /** Tenant the principal acts within. */\n tenantId: string | null;\n /**\n * The persona's tool allow-list (already capped by the agent-class ceiling).\n * This is a **fail-closed** whitelist, mirroring\n * `@happyvertical/smrt-chat`'s `AgentSession.isToolAllowed()` (S5 #1392): an\n * absent (`undefined`) or empty allow-list permits **NO** tools, never all of\n * them, so forgetting to pass it can only tighten authority. Resolved personas\n * always provide a concrete `string[]`.\n */\n allowedTools?: string[];\n /** Optional acting `Bot` profile id, recorded in the audit entry. */\n actsAsProfileId?: string | null;\n}\n\n/**\n * A single audit record describing an agent action performed by the bound\n * principal (`actorUserId`) on behalf of the originating user\n * (`onBehalfOfUserId`).\n */\nexport interface PrincipalAuditEntry {\n /** Action label, e.g. `'agent.run'`. */\n action: string;\n /** The persona's bound user the work ran as. */\n actorUserId: string;\n /** The user who triggered the agent, if known. */\n onBehalfOfUserId: string | null;\n /** Tenant the action ran within. */\n tenantId: string | null;\n /** Canonical agent class, when the caller supplies it. */\n agentClass?: string;\n /** Acting profile id, when the persona sets one. */\n actsAsProfileId?: string | null;\n /** Free-form additional context. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Sink that records a {@link PrincipalAuditEntry}. Provide one to persist audit\n * rows (e.g. via `AuditLog.record`); when omitted, the entry is emitted as a\n * structured log line.\n */\nexport type PrincipalAuditSink = (\n entry: PrincipalAuditEntry,\n) => void | Promise<void>;\n\n/**\n * Options for {@link executeAsPrincipal}.\n */\nexport interface ExecuteAsPrincipalOptions extends SmrtClassOptions {\n /** The bound principal to run as. */\n principal: PrincipalBinding;\n /** The originating user the action is performed on behalf of (for audit). */\n onBehalfOfUserId?: string | null;\n /** Canonical agent class, recorded in the audit entry. */\n agentClass?: string;\n /** Audit action label. Defaults to `'agent.run'`. */\n action?: string;\n /** Extra audit metadata merged into the emitted entry. */\n auditMetadata?: Record<string, unknown>;\n /**\n * Pre-resolved permission slugs. When omitted, the principal's permissions\n * are resolved live so role changes reflect on the next execution.\n */\n permissions?: string[];\n /** Reuse an initialized resolver across executions. */\n resolver?: PermissionResolver;\n /** Opt into Postgres RLS transaction wrapping (defaults to package config). */\n postgresRls?: boolean;\n /**\n * Enter tenant context so tenant auto-filtering applies on every adapter.\n * Defaults to `true` whenever the principal has a tenant.\n */\n enterTenantContext?: boolean;\n /** Audit sink. Defaults to a structured log line. */\n audit?: PrincipalAuditSink;\n /** Logger used for the default audit sink. */\n logger?: Logger;\n}\n\n/**\n * Thrown when the persona attempts a tool outside its `allowedTools`.\n */\nexport class PrincipalToolNotAllowedError extends Error {\n readonly tool: string;\n readonly status = 403;\n\n constructor(tool: string) {\n super(`Tool '${tool}' is not permitted for this persona.`);\n this.name = 'PrincipalToolNotAllowedError';\n this.tool = tool;\n }\n}\n\n/**\n * The handle passed to the {@link executeAsPrincipal} body. Its\n * session-permission {@link context} is already published for the principal, so\n * data operations are bounded by RLS on Postgres. The assertions enforce the\n * remaining two authority dimensions.\n */\nexport interface PrincipalRun {\n /** The published session-permission runtime context for the principal. */\n context: SessionPermissionRuntimeContext;\n /** The principal's published (snapshot) permission slugs. */\n permissions: string[];\n /**\n * Present only when the caller bound this run to an explicit `permissions`\n * snapshot (rather than live resolution). Delegation carries it forward as a\n * ceiling so a narrowed run cannot widen through a worker (#2978).\n */\n permissionSnapshot?: readonly string[];\n /**\n * The effective, fail-closed tool allow-list — always a concrete array (an\n * absent binding allow-list normalizes to `[]`, i.e. no tools).\n */\n allowedTools: string[];\n /**\n * Whether `tool` is within the fail-closed allow-list. An empty allow-list,\n * or an empty/non-string tool name, permits nothing.\n */\n isToolAllowed(tool: string): boolean;\n /** Throw {@link PrincipalToolNotAllowedError} unless `tool` is allowed. */\n assertToolAllowed(tool: string): void;\n /**\n * Assert the principal holds the catalog permission for `(collection,\n * action)`, authorizing against the **published** principal set\n * (`context.permissionSet`) — the same snapshot the RLS session enforces — so\n * the bound is adapter-independent. This is the door-agnostic teeth for the\n * RLS-off adapters; under Postgres RLS it is a redundant (but harmless)\n * second gate. Throws `OperationPermissionError` on denial.\n */\n assertOperation(\n collection: OperationPermissionCollectionInput,\n action: string,\n extraOptions?: SmrtClassOptions,\n ): Promise<OperationPermissionDecision>;\n}\n\nasync function emitAudit(\n entry: PrincipalAuditEntry,\n audit: PrincipalAuditSink | undefined,\n logger: Logger | undefined,\n): Promise<void> {\n if (audit) {\n await audit(entry);\n return;\n }\n const log = logger ?? createLogger({ level: 'info' });\n log.info('agent action executed on behalf of originating user', {\n ...entry,\n });\n}\n\n/**\n * Run `fn` AS the persona's bound principal.\n *\n * Resolves the bound user's live permissions, publishes them onto the DB\n * session (so Postgres RLS bounds every query per-`(table, action)`), emits an\n * on-behalf-of audit entry, and hands `fn` a {@link PrincipalRun} whose\n * assertions enforce the persona tool ceiling and the RLS-off catalog gate.\n *\n * @example\n * ```typescript\n * await executeAsPrincipal(\n * {\n * db,\n * principal: {\n * runAsUserId: persona.runAsUserId,\n * tenantId: persona.tenantId,\n * allowedTools: persona.allowedTools,\n * },\n * onBehalfOfUserId: triggeringUserId,\n * agentClass: persona.agentClass,\n * },\n * async (run) => {\n * run.assertToolAllowed('articles.publish');\n * await run.assertOperation('articles', 'update');\n * await agent.run();\n * },\n * );\n * ```\n */\nexport async function executeAsPrincipal<T>(\n options: ExecuteAsPrincipalOptions,\n fn: (run: PrincipalRun) => Promise<T>,\n): Promise<T> {\n const {\n principal,\n onBehalfOfUserId = null,\n agentClass,\n action = 'agent.run',\n auditMetadata,\n permissions,\n resolver,\n postgresRls,\n enterTenantContext,\n audit,\n logger,\n ...smrtOptions\n } = options;\n\n const { runAsUserId, tenantId, actsAsProfileId = null } = principal;\n\n // Fail-closed tool allow-list (mirrors chat's AgentSession, S5 #1392): an\n // absent or non-array binding allow-list normalizes to `[]` — no tools — so a\n // missing ceiling can only tighten authority, never open it up.\n const toolWhitelist = Array.isArray(principal.allowedTools)\n ? principal.allowedTools\n : [];\n const isToolAllowed = (tool: string): boolean =>\n typeof tool === 'string' && tool.length > 0 && toolWhitelist.includes(tool);\n\n await emitAudit(\n {\n action,\n actorUserId: runAsUserId,\n onBehalfOfUserId,\n tenantId,\n agentClass,\n actsAsProfileId,\n metadata: auditMetadata,\n },\n audit,\n logger,\n );\n\n return withPrincipalPermissionContext(\n {\n ...smrtOptions,\n userId: runAsUserId,\n tenantId,\n permissions,\n resolver,\n postgresRls,\n enterTenantContext: enterTenantContext ?? tenantId !== null,\n },\n async (context) => {\n const run: PrincipalRun = {\n context,\n permissions: context.permissions,\n ...(permissions !== undefined\n ? { permissionSnapshot: [...context.permissions] }\n : {}),\n allowedTools: toolWhitelist,\n isToolAllowed,\n assertToolAllowed(tool: string): void {\n if (!isToolAllowed(tool)) {\n throw new PrincipalToolNotAllowedError(tool);\n }\n },\n async assertOperation(\n collection: OperationPermissionCollectionInput,\n operationAction: string,\n extraOptions?: SmrtClassOptions,\n ): Promise<OperationPermissionDecision> {\n return assertOperationPermission({\n ...smrtOptions,\n ...extraOptions,\n collection,\n action: operationAction,\n // Authorize against the PUBLISHED principal set (the same snapshot\n // Postgres RLS enforces for this context), not a fresh live\n // re-resolve — keeps the RLS-off gate adapter-independent.\n permissionSet: context.permissionSet,\n });\n },\n };\n return fn(run);\n },\n );\n}\n"],"mappings":"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"}
|