@happyvertical/smrt-agents 0.57.46 → 0.57.47
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 -21
- package/agents/lazy-config.md +35 -0
- package/dist/agent.d.ts +12 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +15 -3
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +534 -517
- package/dist/smrt-knowledge.json +169 -163
- package/package.json +18 -18
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,14 +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.
|
|
6
|
+
"packageVersion": "0.57.47",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "a455b6a7d8694175b6e9dd3828c0541fb00891bb9cf26455e29ac2de069fba42",
|
|
11
|
+
"packageJson": "5266918c008dfeaa6472c263ec4ac303281d29e6d53e9a1f65ca4009ee3d5561",
|
|
12
|
+
"agents": "5986624bedc258c46270f39f8b3e1c45971218951dedac289ad9fcd70eebee64",
|
|
13
13
|
"moduleDoc:agents/data-surface-discovery.md": "3ea5cfbb629258b19d4bc2c7cba333e7d30a7e149c4e46a78748524d8da17563",
|
|
14
|
+
"moduleDoc:agents/lazy-config.md": "f4bb02ee228e2cf43b4680e71a15732ed2e19eadcc38223be775f3e421fcb05c",
|
|
14
15
|
"moduleDoc:agents/data-surface-denials.md": "543ec991ae6651af4677b7b29762750c75e1c200e32f1a3ce1938f982fd78116"
|
|
15
16
|
},
|
|
16
17
|
"exports": [
|
|
@@ -1160,6 +1161,164 @@
|
|
|
1160
1161
|
"tags": [],
|
|
1161
1162
|
"risks": []
|
|
1162
1163
|
},
|
|
1164
|
+
{
|
|
1165
|
+
"name": "SmrtDataSurfaceActionTask",
|
|
1166
|
+
"qualifiedName": "@happyvertical/smrt-agents:SmrtDataSurfaceActionTask",
|
|
1167
|
+
"collection": "smrtdatasurfaceactiontasks",
|
|
1168
|
+
"tableName": "_smrt_data_surface_action_tasks",
|
|
1169
|
+
"packageName": "@happyvertical/smrt-agents",
|
|
1170
|
+
"extends": "SmrtObject",
|
|
1171
|
+
"fields": [
|
|
1172
|
+
{
|
|
1173
|
+
"name": "tenantId",
|
|
1174
|
+
"type": "text",
|
|
1175
|
+
"required": false,
|
|
1176
|
+
"columnType": "UUID"
|
|
1177
|
+
},
|
|
1178
|
+
{
|
|
1179
|
+
"name": "args",
|
|
1180
|
+
"type": "json",
|
|
1181
|
+
"required": true,
|
|
1182
|
+
"columnType": "JSON"
|
|
1183
|
+
}
|
|
1184
|
+
],
|
|
1185
|
+
"relationships": [],
|
|
1186
|
+
"methods": [
|
|
1187
|
+
"run"
|
|
1188
|
+
],
|
|
1189
|
+
"methodSignatures": [
|
|
1190
|
+
{
|
|
1191
|
+
"name": "run",
|
|
1192
|
+
"async": true,
|
|
1193
|
+
"params": [
|
|
1194
|
+
"args?: DataSurfaceActionJobArgs",
|
|
1195
|
+
"context?: JobExecutionContext"
|
|
1196
|
+
],
|
|
1197
|
+
"returns": "Promise<DataSurfaceActionResult>"
|
|
1198
|
+
}
|
|
1199
|
+
],
|
|
1200
|
+
"tenant": {
|
|
1201
|
+
"scoped": true,
|
|
1202
|
+
"mode": "optional",
|
|
1203
|
+
"field": "tenantId"
|
|
1204
|
+
},
|
|
1205
|
+
"conflictColumns": [
|
|
1206
|
+
"tenant_id",
|
|
1207
|
+
"slug",
|
|
1208
|
+
"context"
|
|
1209
|
+
],
|
|
1210
|
+
"surfaces": [],
|
|
1211
|
+
"withheldSurfaces": [
|
|
1212
|
+
{
|
|
1213
|
+
"kind": "api",
|
|
1214
|
+
"operation": "run",
|
|
1215
|
+
"code": "api-disabled",
|
|
1216
|
+
"reason": "api is disabled",
|
|
1217
|
+
"objectName": "@happyvertical/smrt-agents:SmrtDataSurfaceActionTask"
|
|
1218
|
+
}
|
|
1219
|
+
],
|
|
1220
|
+
"relationshipFeatures": [
|
|
1221
|
+
"uuidColumns"
|
|
1222
|
+
],
|
|
1223
|
+
"tags": [],
|
|
1224
|
+
"risks": []
|
|
1225
|
+
},
|
|
1226
|
+
{
|
|
1227
|
+
"name": "DataSurfaceActionTokenState",
|
|
1228
|
+
"qualifiedName": "@happyvertical/smrt-agents:DataSurfaceActionTokenState",
|
|
1229
|
+
"collection": "datasurfaceactiontokenstates",
|
|
1230
|
+
"tableName": "_smrt_data_surface_action_tokens",
|
|
1231
|
+
"packageName": "@happyvertical/smrt-agents",
|
|
1232
|
+
"extends": "SmrtObject",
|
|
1233
|
+
"fields": [
|
|
1234
|
+
{
|
|
1235
|
+
"name": "tokenHash",
|
|
1236
|
+
"type": "text",
|
|
1237
|
+
"required": true,
|
|
1238
|
+
"columnType": "TEXT"
|
|
1239
|
+
},
|
|
1240
|
+
{
|
|
1241
|
+
"name": "record",
|
|
1242
|
+
"type": "json",
|
|
1243
|
+
"required": true,
|
|
1244
|
+
"columnType": "JSON"
|
|
1245
|
+
},
|
|
1246
|
+
{
|
|
1247
|
+
"name": "consumedBy",
|
|
1248
|
+
"type": "text",
|
|
1249
|
+
"required": false,
|
|
1250
|
+
"columnType": "TEXT"
|
|
1251
|
+
}
|
|
1252
|
+
],
|
|
1253
|
+
"relationships": [],
|
|
1254
|
+
"methods": [],
|
|
1255
|
+
"surfaces": [],
|
|
1256
|
+
"relationshipFeatures": [
|
|
1257
|
+
"uuidColumns"
|
|
1258
|
+
],
|
|
1259
|
+
"tags": [],
|
|
1260
|
+
"risks": []
|
|
1261
|
+
},
|
|
1262
|
+
{
|
|
1263
|
+
"name": "DataSurfaceActionIdempotencyState",
|
|
1264
|
+
"qualifiedName": "@happyvertical/smrt-agents:DataSurfaceActionIdempotencyState",
|
|
1265
|
+
"collection": "datasurfaceactionidempotencystates",
|
|
1266
|
+
"tableName": "_smrt_data_surface_action_idempotency",
|
|
1267
|
+
"packageName": "@happyvertical/smrt-agents",
|
|
1268
|
+
"extends": "SmrtObject",
|
|
1269
|
+
"fields": [
|
|
1270
|
+
{
|
|
1271
|
+
"name": "keyHash",
|
|
1272
|
+
"type": "text",
|
|
1273
|
+
"required": true,
|
|
1274
|
+
"columnType": "TEXT"
|
|
1275
|
+
},
|
|
1276
|
+
{
|
|
1277
|
+
"name": "status",
|
|
1278
|
+
"type": "text",
|
|
1279
|
+
"required": true,
|
|
1280
|
+
"columnType": "TEXT"
|
|
1281
|
+
},
|
|
1282
|
+
{
|
|
1283
|
+
"name": "requestFingerprint",
|
|
1284
|
+
"type": "text",
|
|
1285
|
+
"required": true,
|
|
1286
|
+
"columnType": "TEXT"
|
|
1287
|
+
},
|
|
1288
|
+
{
|
|
1289
|
+
"name": "ownerHash",
|
|
1290
|
+
"type": "text",
|
|
1291
|
+
"required": false,
|
|
1292
|
+
"columnType": "TEXT"
|
|
1293
|
+
},
|
|
1294
|
+
{
|
|
1295
|
+
"name": "reservedAt",
|
|
1296
|
+
"type": "text",
|
|
1297
|
+
"required": false,
|
|
1298
|
+
"columnType": "TEXT"
|
|
1299
|
+
},
|
|
1300
|
+
{
|
|
1301
|
+
"name": "result",
|
|
1302
|
+
"type": "json",
|
|
1303
|
+
"required": false,
|
|
1304
|
+
"columnType": "JSON"
|
|
1305
|
+
},
|
|
1306
|
+
{
|
|
1307
|
+
"name": "recovery",
|
|
1308
|
+
"type": "json",
|
|
1309
|
+
"required": false,
|
|
1310
|
+
"columnType": "JSON"
|
|
1311
|
+
}
|
|
1312
|
+
],
|
|
1313
|
+
"relationships": [],
|
|
1314
|
+
"methods": [],
|
|
1315
|
+
"surfaces": [],
|
|
1316
|
+
"relationshipFeatures": [
|
|
1317
|
+
"uuidColumns"
|
|
1318
|
+
],
|
|
1319
|
+
"tags": [],
|
|
1320
|
+
"risks": []
|
|
1321
|
+
},
|
|
1163
1322
|
{
|
|
1164
1323
|
"name": "TenantAgent",
|
|
1165
1324
|
"qualifiedName": "@happyvertical/smrt-agents:TenantAgent",
|
|
@@ -1403,164 +1562,6 @@
|
|
|
1403
1562
|
],
|
|
1404
1563
|
"tags": [],
|
|
1405
1564
|
"risks": []
|
|
1406
|
-
},
|
|
1407
|
-
{
|
|
1408
|
-
"name": "SmrtDataSurfaceActionTask",
|
|
1409
|
-
"qualifiedName": "@happyvertical/smrt-agents:SmrtDataSurfaceActionTask",
|
|
1410
|
-
"collection": "smrtdatasurfaceactiontasks",
|
|
1411
|
-
"tableName": "_smrt_data_surface_action_tasks",
|
|
1412
|
-
"packageName": "@happyvertical/smrt-agents",
|
|
1413
|
-
"extends": "SmrtObject",
|
|
1414
|
-
"fields": [
|
|
1415
|
-
{
|
|
1416
|
-
"name": "tenantId",
|
|
1417
|
-
"type": "text",
|
|
1418
|
-
"required": false,
|
|
1419
|
-
"columnType": "UUID"
|
|
1420
|
-
},
|
|
1421
|
-
{
|
|
1422
|
-
"name": "args",
|
|
1423
|
-
"type": "json",
|
|
1424
|
-
"required": true,
|
|
1425
|
-
"columnType": "JSON"
|
|
1426
|
-
}
|
|
1427
|
-
],
|
|
1428
|
-
"relationships": [],
|
|
1429
|
-
"methods": [
|
|
1430
|
-
"run"
|
|
1431
|
-
],
|
|
1432
|
-
"methodSignatures": [
|
|
1433
|
-
{
|
|
1434
|
-
"name": "run",
|
|
1435
|
-
"async": true,
|
|
1436
|
-
"params": [
|
|
1437
|
-
"args?: DataSurfaceActionJobArgs",
|
|
1438
|
-
"context?: JobExecutionContext"
|
|
1439
|
-
],
|
|
1440
|
-
"returns": "Promise<DataSurfaceActionResult>"
|
|
1441
|
-
}
|
|
1442
|
-
],
|
|
1443
|
-
"tenant": {
|
|
1444
|
-
"scoped": true,
|
|
1445
|
-
"mode": "optional",
|
|
1446
|
-
"field": "tenantId"
|
|
1447
|
-
},
|
|
1448
|
-
"conflictColumns": [
|
|
1449
|
-
"tenant_id",
|
|
1450
|
-
"slug",
|
|
1451
|
-
"context"
|
|
1452
|
-
],
|
|
1453
|
-
"surfaces": [],
|
|
1454
|
-
"withheldSurfaces": [
|
|
1455
|
-
{
|
|
1456
|
-
"kind": "api",
|
|
1457
|
-
"operation": "run",
|
|
1458
|
-
"code": "api-disabled",
|
|
1459
|
-
"reason": "api is disabled",
|
|
1460
|
-
"objectName": "@happyvertical/smrt-agents:SmrtDataSurfaceActionTask"
|
|
1461
|
-
}
|
|
1462
|
-
],
|
|
1463
|
-
"relationshipFeatures": [
|
|
1464
|
-
"uuidColumns"
|
|
1465
|
-
],
|
|
1466
|
-
"tags": [],
|
|
1467
|
-
"risks": []
|
|
1468
|
-
},
|
|
1469
|
-
{
|
|
1470
|
-
"name": "DataSurfaceActionTokenState",
|
|
1471
|
-
"qualifiedName": "@happyvertical/smrt-agents:DataSurfaceActionTokenState",
|
|
1472
|
-
"collection": "datasurfaceactiontokenstates",
|
|
1473
|
-
"tableName": "_smrt_data_surface_action_tokens",
|
|
1474
|
-
"packageName": "@happyvertical/smrt-agents",
|
|
1475
|
-
"extends": "SmrtObject",
|
|
1476
|
-
"fields": [
|
|
1477
|
-
{
|
|
1478
|
-
"name": "tokenHash",
|
|
1479
|
-
"type": "text",
|
|
1480
|
-
"required": true,
|
|
1481
|
-
"columnType": "TEXT"
|
|
1482
|
-
},
|
|
1483
|
-
{
|
|
1484
|
-
"name": "record",
|
|
1485
|
-
"type": "json",
|
|
1486
|
-
"required": true,
|
|
1487
|
-
"columnType": "JSON"
|
|
1488
|
-
},
|
|
1489
|
-
{
|
|
1490
|
-
"name": "consumedBy",
|
|
1491
|
-
"type": "text",
|
|
1492
|
-
"required": false,
|
|
1493
|
-
"columnType": "TEXT"
|
|
1494
|
-
}
|
|
1495
|
-
],
|
|
1496
|
-
"relationships": [],
|
|
1497
|
-
"methods": [],
|
|
1498
|
-
"surfaces": [],
|
|
1499
|
-
"relationshipFeatures": [
|
|
1500
|
-
"uuidColumns"
|
|
1501
|
-
],
|
|
1502
|
-
"tags": [],
|
|
1503
|
-
"risks": []
|
|
1504
|
-
},
|
|
1505
|
-
{
|
|
1506
|
-
"name": "DataSurfaceActionIdempotencyState",
|
|
1507
|
-
"qualifiedName": "@happyvertical/smrt-agents:DataSurfaceActionIdempotencyState",
|
|
1508
|
-
"collection": "datasurfaceactionidempotencystates",
|
|
1509
|
-
"tableName": "_smrt_data_surface_action_idempotency",
|
|
1510
|
-
"packageName": "@happyvertical/smrt-agents",
|
|
1511
|
-
"extends": "SmrtObject",
|
|
1512
|
-
"fields": [
|
|
1513
|
-
{
|
|
1514
|
-
"name": "keyHash",
|
|
1515
|
-
"type": "text",
|
|
1516
|
-
"required": true,
|
|
1517
|
-
"columnType": "TEXT"
|
|
1518
|
-
},
|
|
1519
|
-
{
|
|
1520
|
-
"name": "status",
|
|
1521
|
-
"type": "text",
|
|
1522
|
-
"required": true,
|
|
1523
|
-
"columnType": "TEXT"
|
|
1524
|
-
},
|
|
1525
|
-
{
|
|
1526
|
-
"name": "requestFingerprint",
|
|
1527
|
-
"type": "text",
|
|
1528
|
-
"required": true,
|
|
1529
|
-
"columnType": "TEXT"
|
|
1530
|
-
},
|
|
1531
|
-
{
|
|
1532
|
-
"name": "ownerHash",
|
|
1533
|
-
"type": "text",
|
|
1534
|
-
"required": false,
|
|
1535
|
-
"columnType": "TEXT"
|
|
1536
|
-
},
|
|
1537
|
-
{
|
|
1538
|
-
"name": "reservedAt",
|
|
1539
|
-
"type": "text",
|
|
1540
|
-
"required": false,
|
|
1541
|
-
"columnType": "TEXT"
|
|
1542
|
-
},
|
|
1543
|
-
{
|
|
1544
|
-
"name": "result",
|
|
1545
|
-
"type": "json",
|
|
1546
|
-
"required": false,
|
|
1547
|
-
"columnType": "JSON"
|
|
1548
|
-
},
|
|
1549
|
-
{
|
|
1550
|
-
"name": "recovery",
|
|
1551
|
-
"type": "json",
|
|
1552
|
-
"required": false,
|
|
1553
|
-
"columnType": "JSON"
|
|
1554
|
-
}
|
|
1555
|
-
],
|
|
1556
|
-
"relationships": [],
|
|
1557
|
-
"methods": [],
|
|
1558
|
-
"surfaces": [],
|
|
1559
|
-
"relationshipFeatures": [
|
|
1560
|
-
"uuidColumns"
|
|
1561
|
-
],
|
|
1562
|
-
"tags": [],
|
|
1563
|
-
"risks": []
|
|
1564
1565
|
}
|
|
1565
1566
|
],
|
|
1566
1567
|
"surfaces": [
|
|
@@ -1856,13 +1857,18 @@
|
|
|
1856
1857
|
"polymorphicAssociations": 0,
|
|
1857
1858
|
"uuidColumns": 18
|
|
1858
1859
|
},
|
|
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, allowed values, `id`/request aliases |\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).\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()` — 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
|
+
"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/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\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()` — 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
1861
|
"moduleDocs": [
|
|
1861
1862
|
{
|
|
1862
1863
|
"path": "agents/data-surface-discovery.md",
|
|
1863
1864
|
"module": "data-surface-discovery",
|
|
1864
1865
|
"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` (repeated as `surfaceId`, the argument name `data.inspect`\nand `data.query` take, #4507), 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\n## Argument names and request aliases (#4507, #4505)\n\n`data.inspect`'s `surfaceId` is described (\"The id data.discover lists for the\nsurface\", `DATA_INSPECT_TOOL_PARAMETERS`) and named in its tool description;\nsummary discovery repeats `id` as `surfaceId`. `placeSurfaceId` takes a lone\ntop-level `id` string as `surfaceId` when no `surfaceId` is given and nothing\nelse sits beside it (inspect: no other key; query: only `request` or its\n`query` wrapper, never the flat form, where `id` may be a field). Every other\n`id` is ignored and the existing `DATA_QUERY_SURFACE_ID_*` errors apply.\n\nInside `request` (or the flat form), `data.query` maps SQL-ish aliases before\nvalidation when the canonical key is absent: `select`→`projection` (array or\ncomma-separated string), `where`→`filter`, `orderBy`→`sort` (`\"field desc\"`\nstrings, comma lists, or a `{ field }` object; direction defaults to `asc`),\nand `limit`/`offset`→`page.limit`/`page.offset` (merged into a `page` that\nlacks them). Mapped values are validated exactly as if written canonically.\nAn alias beside its canonical key stays in place and fails as an unsupported\nkey; the error names the canonical key. Beside `request` at the top level an\nalias is `DATA_QUERY_ARGUMENTS_UNEXPECTED` (\"move limit inside request\"). The\nrequest schema's property descriptions name the aliases.\n"
|
|
1865
1866
|
},
|
|
1867
|
+
{
|
|
1868
|
+
"path": "agents/lazy-config.md",
|
|
1869
|
+
"module": "lazy-config",
|
|
1870
|
+
"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"
|
|
1871
|
+
},
|
|
1866
1872
|
{
|
|
1867
1873
|
"path": "agents/data-surface-denials.md",
|
|
1868
1874
|
"module": "data-surface-denials",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-agents",
|
|
3
|
-
"version": "0.57.
|
|
3
|
+
"version": "0.57.47",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"smrtRawPrimitives": "strict",
|
|
@@ -58,25 +58,25 @@
|
|
|
58
58
|
}
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@happyvertical/ai": "^0.111.
|
|
62
|
-
"@happyvertical/files": "^0.111.
|
|
63
|
-
"@happyvertical/logger": "^0.111.
|
|
64
|
-
"@happyvertical/smrt-config": "0.57.
|
|
65
|
-
"@happyvertical/smrt-core": "0.57.
|
|
66
|
-
"@happyvertical/smrt-jobs": "0.57.
|
|
67
|
-
"@happyvertical/smrt-playbooks": "0.57.
|
|
68
|
-
"@happyvertical/smrt-reports": "0.57.
|
|
69
|
-
"@happyvertical/smrt-secrets": "0.57.
|
|
70
|
-
"@happyvertical/smrt-tenancy": "0.57.
|
|
71
|
-
"@happyvertical/smrt-types": "0.57.
|
|
72
|
-
"@happyvertical/smrt-ui": "0.57.
|
|
73
|
-
"@happyvertical/smrt-users": "0.57.
|
|
74
|
-
"@happyvertical/sql": "^0.111.
|
|
75
|
-
"@happyvertical/utils": "^0.111.
|
|
61
|
+
"@happyvertical/ai": "^0.111.3",
|
|
62
|
+
"@happyvertical/files": "^0.111.3",
|
|
63
|
+
"@happyvertical/logger": "^0.111.3",
|
|
64
|
+
"@happyvertical/smrt-config": "0.57.47",
|
|
65
|
+
"@happyvertical/smrt-core": "0.57.47",
|
|
66
|
+
"@happyvertical/smrt-jobs": "0.57.47",
|
|
67
|
+
"@happyvertical/smrt-playbooks": "0.57.47",
|
|
68
|
+
"@happyvertical/smrt-reports": "0.57.47",
|
|
69
|
+
"@happyvertical/smrt-secrets": "0.57.47",
|
|
70
|
+
"@happyvertical/smrt-tenancy": "0.57.47",
|
|
71
|
+
"@happyvertical/smrt-types": "0.57.47",
|
|
72
|
+
"@happyvertical/smrt-ui": "0.57.47",
|
|
73
|
+
"@happyvertical/smrt-users": "0.57.47",
|
|
74
|
+
"@happyvertical/sql": "^0.111.3",
|
|
75
|
+
"@happyvertical/utils": "^0.111.3"
|
|
76
76
|
},
|
|
77
77
|
"devDependencies": {
|
|
78
|
-
"@happyvertical/smrt-vitest": "0.57.
|
|
79
|
-
"@happyvertical/sql": "^0.111.
|
|
78
|
+
"@happyvertical/smrt-vitest": "0.57.47",
|
|
79
|
+
"@happyvertical/sql": "^0.111.3",
|
|
80
80
|
"@sentry/node": "^10.75.0",
|
|
81
81
|
"@sveltejs/package": "^2.5.8",
|
|
82
82
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|