@happyvertical/smrt-agents 0.57.31 → 0.57.33

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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-agents",
5
- "packageVersion": "0.57.31",
5
+ "packageVersion": "0.57.33",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-agents:Agent": {
8
8
  "name": "agent",
@@ -8,7 +8,7 @@
8
8
  */
9
9
  import { applyReportRefresh, buildReportAdapterDescriptor, type ReportAdapterDescriptor, type ReportAdapterOptions, type ReportBackgroundQueryTask, type ReportDataQueryResult, type ReportExportActionHost, type ReportExportSnapshotBinding, type ReportQueryOptions, type ReportRefreshActionHost } from '@happyvertical/smrt-reports';
10
10
  import type { DataQueryRequest } from '@happyvertical/smrt-types';
11
- import { type DataSurfaceDefinition, type DataSurfaceExecutionContext, type DataSurfaceToolsOptions } from './data-surface.js';
11
+ import { type DataSurfaceCatalogContext, type DataSurfaceDefinition, type DataSurfaceExecutionContext, type DataSurfaceToolsOptions } from './data-surface.js';
12
12
  import type { PrincipalRun } from './execute-as-principal.js';
13
13
  import type { PrincipalTool } from './invoke-agent.js';
14
14
  export declare const REPORT_QUERY_TOOL_SLUG = "reports.query";
@@ -82,6 +82,8 @@ export interface ReportDataSurfaceDefinition {
82
82
  collection: string;
83
83
  label?: string;
84
84
  description?: string;
85
+ /** Host-supplied discovery size hint; see `DataSurfaceDefinition`. */
86
+ rowCountHint?: DataSurfaceDefinition['rowCountHint'];
85
87
  adapter?: ReportAdapterOptions;
86
88
  /** Application-owned collection/lifecycle seam for materialized reads. */
87
89
  query?: (context: DataSurfaceExecutionContext) => ReportReadOptions | Promise<ReportReadOptions>;
@@ -102,7 +104,9 @@ export interface ReportDataSurfaceAuditEntry {
102
104
  tenantId: string | null;
103
105
  }
104
106
  export interface ReportDataSurfaceToolsOptions {
105
- reports: readonly ReportDataSurfaceDefinition[] | ((run: PrincipalRun) => readonly ReportDataSurfaceDefinition[] | Promise<readonly ReportDataSurfaceDefinition[]>);
107
+ reports: readonly ReportDataSurfaceDefinition[] | ((run: PrincipalRun,
108
+ /** Set when evaluated as the data-tool catalog (#4387). */
109
+ context?: DataSurfaceCatalogContext) => readonly ReportDataSurfaceDefinition[] | Promise<readonly ReportDataSurfaceDefinition[]>);
106
110
  /** Optional audit of agent-level handoffs; report action hosts audit mutations. */
107
111
  audit?: (entry: ReportDataSurfaceAuditEntry) => void | Promise<void>;
108
112
  /** Passed through to generic data.discover/data.inspect/data.query tools. */
@@ -1 +1 @@
1
- {"version":3,"file":"report-data-surface.d.ts","sourceRoot":"","sources":["../src/report-data-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAQH,OAAO,EAIL,kBAAkB,EAClB,4BAA4B,EAO5B,KAAK,uBAAuB,EAC5B,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC9B,KAAK,qBAAqB,EAC1B,KAAK,sBAAsB,EAE3B,KAAK,2BAA2B,EAEhC,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAE7B,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAElE,OAAO,EAGL,KAAK,qBAAqB,EAE1B,KAAK,2BAA2B,EAEhC,KAAK,uBAAuB,EAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,KAAK,EAAE,aAAa,EAAwB,MAAM,mBAAmB,CAAC;AAE7E,eAAO,MAAM,sBAAsB,kBAAkB,CAAC;AACtD,eAAO,MAAM,wBAAwB,oBAAoB,CAAC;AAC1D,eAAO,MAAM,0BAA0B,sBAAsB,CAAC;AAC9D,eAAO,MAAM,uBAAuB,mBAAmB,CAAC;AAExD,eAAO,MAAM,0BAA0B,kBAAkB,CAAC;AAC1D,eAA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AC,CAAC;CAC/E;AAED,qBAAa,6BAA8B,SAAQ,KAAK;gBAC1C,MAAM,CAAC,EAAE,MAAM;CAM5B;AAED,qBAAa,mCAAoC,SAAQ,KAAK;gBAChD,OAAO,EAAE,MAAM;CAI5B;AA4ND;;;;GAIG;AACH,wBAAsB,iCAAiC,CACrD,UAAU,EAAE,2BAA2B,EACvC,GAAG,CAAC,EAAE,YAAY,EAClB,cAAc,UAAQ,GACrB,OAAO,CAAC,qBAAqB,CAAC,CAyChC;AAqDD;;;GAGG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,6BAA6B,GACrC,aAAa,EAAE,CAyVjB"}
@@ -90,6 +90,8 @@ export interface CreateSmrtCollectionDataSurfaceOptions {
90
90
  label?: string;
91
91
  description?: string;
92
92
  metadata?: NonNullable<DataSurfaceDefinition['metadata']>;
93
+ /** Host-supplied discovery size hint; never computed by querying. */
94
+ rowCountHint?: DataSurfaceDefinition['rowCountHint'];
93
95
  /** Row identity field. Defaults to `id`. */
94
96
  identityField?: string;
95
97
  /** Extra field ids to exclude beyond the standard field-policy exclusions. */
@@ -124,6 +126,14 @@ export interface CreateSmrtCollectionDataSurfaceOptions {
124
126
  scope?: SmrtCollectionQueryScope | ((context: DataSurfaceExecutionContext) => SmrtCollectionQueryScope | undefined | Promise<SmrtCollectionQueryScope | undefined>);
125
127
  /** Trusted policy override; defaults to the registry-derived schema. */
126
128
  schema?: DataSurfaceSchema;
129
+ /**
130
+ * Enforce field values derived from scanner-declared enums (#4381). By
131
+ * default they are advisory (`valuesEnforced: false`): the ORM does not
132
+ * validate enums on save, so stored rows may hold other values and filters
133
+ * on them keep working. Set `true` once the stored data is known to match.
134
+ * Ignored with a `schema` override, which declares its own `values`.
135
+ */
136
+ enforceDerivedValues?: boolean;
127
137
  }
128
138
  /**
129
139
  * The operators an id (native `UUID` column) field accepts. Ordered and
@@ -170,6 +180,8 @@ export declare function buildDataQuerySchemaForClass(qualifiedName: string, opti
170
180
  defaultSort?: DataQuerySort[];
171
181
  cursorPagination?: boolean;
172
182
  facets?: boolean;
183
+ /** See `CreateSmrtCollectionDataSurfaceOptions.enforceDerivedValues`. */
184
+ enforceDerivedValues?: boolean;
173
185
  }): Promise<DataQuerySchema>;
174
186
  /** Testing seam: drop memoized schemas so a rebuild re-reads the registry. */
175
187
  export declare function clearSmrtCollectionQuerySchemaCache(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"smrt-collection-data-surface.d.ts","sourceRoot":"","sources":["../src/smrt-collection-data-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AAwBH,OAAO,KAAK,EAGV,eAAe,EACf,uBAAuB,EAEvB,eAAe,EAEf,eAAe,EACf,aAAa,EACd,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,qBAAqB,EACrB,2BAA2B,EAC3B,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAE3B,mDAAmD;AACnD,KAAK,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC9C,6EAA6E;AAC7E,KAAK,QAAQ,GAAG,cAAc,EAAE,EAAE,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,WAAW,6BAA6B;IAC5C,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QAC3B,KAAK,CAAC,EAAE,cAAc,GAAG,QAAQ,CAAC;QAClC,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;KAC7B,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;IACvC,KAAK,CAAC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,cAAc,GAAG,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC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,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,WAAW,CAAC,EAAE,aAAa,EAAE,CAAC;IAC9B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,CAAC;CACb,GACL,OAAO,CAAC,eAAe,CAAC,CAwC1B;AAED,8EAA8E;AAC9E,wBAAgB,mCAAmC,IAAI,IAAI,CAE1D;AAuCD,qEAAqE;AACrE,wBAAgB,+BAA+B,CAAC,MAAM,EAAE,eAAe,GAAG,IAAI,CAG7E;AAwjBD;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,UAAU,EAAE,6BAA6B,EACzC,UAAU,EAAE,OAAO,EACnB,OAAO,EAAE;IACP,MAAM,EAAE,eAAe,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,wBAAwB,CAAC;IACjC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GACA,OAAO,CAAC,eAAe,CAAC,CAoR1B;AAED;;;;;;;;;GASG;AACH,wBAAsB,yCAAyC,CAC7D,OAAO,EAAE,sCAAsC,GAC9C,OAAO,CAAC,qBAAqB,CAAC,CAqIhC;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
1
+ {"version":3,"file":"smrt-collection-data-surface.d.ts","sourceRoot":"","sources":["../src/smrt-collection-data-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AA0BH,OAAO,KAAK,EAIV,eAAe,EACf,uBAAuB,EAEvB,eAAe,EAEf,eAAe,EACf,aAAa,EACd,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EACV,qBAAqB,EACrB,2BAA2B,EAC3B,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;A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eAAe,GAAG,IAAI,CAG7E;AAwjBD;;;;;GAKG;AACH,wBAAsB,0BAA0B,CAC9C,UAAU,EAAE,6BAA6B,EACzC,UAAU,EAAE,OAAO,EACnB,OAAO,EAAE;IACP,MAAM,EAAE,eAAe,CAAC;IACxB,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,wBAAwB,CAAC;IACjC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GACA,OAAO,CAAC,eAAe,CAAC,CAoR1B;AAED;;;;;;;;;GASG;AACH,wBAAsB,yCAAyC,CAC7D,OAAO,EAAE,sCAAsC,GAC9C,OAAO,CAAC,qBAAqB,CAAC,CAyIhC;AAED,YAAY,EAAE,gBAAgB,EAAE,CAAC"}
@@ -3,13 +3,15 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-agents",
6
- "packageVersion": "0.57.31",
6
+ "packageVersion": "0.57.33",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "f98630a52b26287c708d4b8abc18d04d2f7635eae67ebe7bb5ba219836133b33",
11
- "packageJson": "dc62d0bcbf9180553a827e2a4b594a09819f6f5c98eef2159aad2ccd255a8abd",
12
- "agents": "23b6d2e4061cad30c3f6d5317046daf127f7576b947f71052656443ca4aa4953"
10
+ "manifest": "d4bed16ce017bf7963d1bdfe4984ba5ba27651f09052568c0c7d61ce8a7e19be",
11
+ "packageJson": "7d595421ec4d04092c64656be4919a66cb05308d83d6c60fbc27aeb5e5bdff3d",
12
+ "agents": "e23151b95c7f51b6b083ed29d88ca2b6b39fec81d31085a6a4feb3067e1e1347",
13
+ "moduleDoc:agents/data-surface-discovery.md": "9db2dd84b076b0a16784e0cef0851042d3634efd046a2178a55afa53870dfa78",
14
+ "moduleDoc:agents/data-surface-denials.md": "543ec991ae6651af4677b7b29762750c75e1c200e32f1a3ce1938f982fd78116"
13
15
  },
14
16
  "exports": [
15
17
  ".",
@@ -45,7 +47,6 @@
45
47
  "@testing-library/svelte": "^5.4.2",
46
48
  "@testing-library/user-event": "^14.6.7",
47
49
  "@types/node": "24.13.6",
48
- "fast-glob": "3.3.3",
49
50
  "svelte-check": "^4.7.6",
50
51
  "svelte": "^5.57.0",
51
52
  "typescript": "6.0.3",
@@ -1855,7 +1856,19 @@
1855
1856
  "polymorphicAssociations": 0,
1856
1857
  "uuidColumns": 18
1857
1858
  },
1858
- "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## 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/shutdown`\n- `execute()` runs the full lifecycle automatically\n- Process signal handling is opt-in via `manageProcessSignals: true` and is intended 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- **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\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## 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.\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()` — generic registry-driven `SmrtObject` collection to `DataSurfaceDefinition` adapter, with field-policy redaction (schema overrides included), class-aware tenant scope, DNF filter/scope lowering, deny-all short-circuit, query-bound opaque cursors, and offset/cursor paging; hydrated row values are serialized to JSON scalars at the adapter boundary — a `Date`/date-only/zoneless-UTC `datetime` becomes an ISO-8601 UTC instant, a `bigint` a safe number, and a non-scalar value on a scalar descriptor its JSON string — so a populated datetime column no longer fails the whole result; callers must keep `maxPageLimit` <= the collection's own row-limit cap (#2905, follow-up #2912, #2933) |\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",
1859
+ "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, and allowed field values |\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/shutdown`\n- `execute()` runs the full lifecycle automatically\n- Process signal handling is opt-in via `manageProcessSignals: true` and is intended 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- **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\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## 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).\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()` — generic registry-driven `SmrtObject` collection to `DataSurfaceDefinition` adapter, with field-policy redaction (schema overrides included), class-aware tenant scope, DNF filter/scope lowering, deny-all short-circuit, query-bound opaque cursors, and offset/cursor paging; hydrated row values are serialized to JSON scalars at the adapter boundary — a `Date`/date-only/zoneless-UTC `datetime` becomes an ISO-8601 UTC instant, a `bigint` a safe number, and a non-scalar value on a scalar descriptor its JSON string — so a populated datetime column no longer fails the whole result; callers must keep `maxPageLimit` <= the collection's own row-limit cap (#2905, follow-up #2912, #2933) |\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",
1860
+ "moduleDocs": [
1861
+ {
1862
+ "path": "agents/data-surface-discovery.md",
1863
+ "module": "data-surface-discovery",
1864
+ "content": "# Data-surface discovery metadata\n\nModule reference for `packages/agents/AGENTS.md`.\n\n## Allowed field values (#4381)\n\nDeclared field `values` (#4381; contract in core\n[data-query.md](../../core/agents/data-query.md)) appear on `data.inspect` and\n`data.discover` field descriptors with an explicit `valuesEnforced` flag; for\nan enforced set an undeclared `eq`/`ne`/`in`/`notIn` value fails as a\n`DataSurfaceRequestError` (`reason` `DATA_QUERY_VALUE_NOT_ALLOWED`) naming the\nallowed values. Enum-derived smrt-collection values are advisory unless the\nhost sets `enforceDerivedValues`.\n\n## Summary discovery and row-count hints (#4329)\n\n`discoverDetail: 'summary'` (#4329; default `'full'`) makes `data.discover`\nreturn only `id`, a cleaned `label`, the description's first non-empty line\nbounded to 160 chars, and `rowCountHint`, with a discover tool description\npointing to `data.inspect`. Without a `rowCountHint`, full discovery and\n`data.inspect` are byte-identical to before; a valid hint is added to both.\nThe catalog/RBAC gates, including identity-field denial, run the same in both\nmodes; query is unaffected. Summary mode assumes the persona may call\n`data.inspect`: a host granting discover and query without inspect keeps full.\n`DataSurfaceDefinition.rowCountHint` is host-supplied and never queried:\n`normalizeDataSurfaceRowCountHint()` accepts a non-negative safe integer or a\ntrimmed label of at most 32 chars with something visible and no Cc/Cf/Zl/Zp\ncharacters, and omits anything else. Every reader of the surface sees the\nsame hint, so it must be a coarse static label, never a tenant- or\nprincipal-specific count; the description's first line is model-facing and\nmust carry no secrets or instructions.\n"
1865
+ },
1866
+ {
1867
+ "path": "agents/data-surface-denials.md",
1868
+ "module": "data-surface-denials",
1869
+ "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"
1870
+ }
1871
+ ],
1859
1872
  "browser": {
1860
1873
  "status": "server-only",
1861
1874
  "issues": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-agents",
3
- "version": "0.57.31",
3
+ "version": "0.57.33",
4
4
  "smrtJsdoc": "strict",
5
5
  "type": "module",
6
6
  "smrtRawPrimitives": "strict",
@@ -46,7 +46,8 @@
46
46
  "files": [
47
47
  "dist",
48
48
  "CLAUDE.md",
49
- "AGENTS.md"
49
+ "AGENTS.md",
50
+ "agents"
50
51
  ],
51
52
  "peerDependencies": {
52
53
  "svelte": "^5.57.0"
@@ -60,21 +61,21 @@
60
61
  "@happyvertical/ai": "^0.108.0",
61
62
  "@happyvertical/files": "^0.108.0",
62
63
  "@happyvertical/logger": "^0.108.0",
63
- "@happyvertical/smrt-config": "0.57.31",
64
- "@happyvertical/smrt-core": "0.57.31",
65
- "@happyvertical/smrt-jobs": "0.57.31",
66
- "@happyvertical/smrt-playbooks": "0.57.31",
67
- "@happyvertical/smrt-reports": "0.57.31",
68
- "@happyvertical/smrt-secrets": "0.57.31",
69
- "@happyvertical/smrt-tenancy": "0.57.31",
70
- "@happyvertical/smrt-types": "0.57.31",
71
- "@happyvertical/smrt-ui": "0.57.31",
72
- "@happyvertical/smrt-users": "0.57.31",
64
+ "@happyvertical/smrt-config": "0.57.33",
65
+ "@happyvertical/smrt-core": "0.57.33",
66
+ "@happyvertical/smrt-jobs": "0.57.33",
67
+ "@happyvertical/smrt-playbooks": "0.57.33",
68
+ "@happyvertical/smrt-reports": "0.57.33",
69
+ "@happyvertical/smrt-secrets": "0.57.33",
70
+ "@happyvertical/smrt-tenancy": "0.57.33",
71
+ "@happyvertical/smrt-types": "0.57.33",
72
+ "@happyvertical/smrt-ui": "0.57.33",
73
+ "@happyvertical/smrt-users": "0.57.33",
73
74
  "@happyvertical/sql": "^0.108.0",
74
75
  "@happyvertical/utils": "^0.108.0"
75
76
  },
76
77
  "devDependencies": {
77
- "@happyvertical/smrt-vitest": "0.57.31",
78
+ "@happyvertical/smrt-vitest": "0.57.33",
78
79
  "@happyvertical/sql": "^0.108.0",
79
80
  "@sentry/node": "^10.75.0",
80
81
  "@sveltejs/package": "^2.5.8",
@@ -82,7 +83,6 @@
82
83
  "@testing-library/svelte": "^5.4.2",
83
84
  "@testing-library/user-event": "^14.6.7",
84
85
  "@types/node": "24.13.6",
85
- "fast-glob": "3.3.3",
86
86
  "svelte-check": "^4.7.6",
87
87
  "svelte": "^5.57.1",
88
88
  "typescript": "6.0.3",