@happyvertical/smrt-jobs 0.61.6 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +11 -29
- package/README.md +140 -2
- package/agents/forge-projections.md +30 -0
- package/agents/job-claims.md +82 -0
- package/agents/job-handlers.md +115 -0
- package/agents/provider-loading.md +19 -0
- package/agents/scheduling.md +206 -0
- package/agents/worker-liveness.md +3 -0
- package/dist/chunks/{runner-CB6-XwRQ.js → runner-ComDONr7.js} +862 -485
- package/dist/chunks/runner-ComDONr7.js.map +1 -0
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +53 -2
- package/dist/index.js.map +1 -1
- package/dist/job-claim.d.ts +61 -0
- package/dist/job-claim.d.ts.map +1 -0
- package/dist/job-handlers.d.ts +127 -0
- package/dist/job-handlers.d.ts.map +1 -0
- package/dist/logger-extension.d.ts +5 -0
- package/dist/logger-extension.d.ts.map +1 -1
- package/dist/manifest.json +39 -1
- package/dist/runner.d.ts +67 -0
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +2 -2
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-event.d.ts +21 -1
- package/dist/smrt-job-event.d.ts.map +1 -1
- package/dist/smrt-job.d.ts +37 -4
- package/dist/smrt-job.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +58 -6
- package/dist/smrt-knowledge.okf.md +16 -4
- package/dist/terminal-outcome.d.ts +5 -2
- package/dist/terminal-outcome.d.ts.map +1 -1
- package/dist/worker-liveness.d.ts +9 -0
- package/dist/worker-liveness.d.ts.map +1 -1
- package/package.json +9 -8
- package/dist/chunks/runner-CB6-XwRQ.js.map +0 -1
|
@@ -8,7 +8,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
8
8
|
import { EventEmitter } from "node:events";
|
|
9
9
|
import { Worker } from "node:worker_threads";
|
|
10
10
|
//#region src/__smrt-register__.ts
|
|
11
|
-
ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-jobs","packageVersion":"0.61.6","objects":{"@happyvertical/smrt-jobs:SmrtJobEvent":{"name":"smrtjobevent","className":"SmrtJobEvent","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobEvent","collection":"smrtjobevents","filePath":"src/smrt-job-event.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"jobId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","constraint","related"],"required":true,"requiredFor":"identity","constraint":false},"required":true,"related":"SmrtJob"},"type":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"log"},"required":true,"default":"log"},"level":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"info"},"required":true,"default":"info","enum":["debug","info","warn","error"]},"stage":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"progress":{"type":"integer","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"message":{"type":"text","_meta":{"__statedOptions":["default"],"default":""},"required":false,"default":""},"data":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"createdAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true}},"methods":{"toCursor":{"name":"toCursor","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_job_events","api":false,"cli":{"include":["list","get"],"http":false,"skipApiCheck":true},"mcp":false,"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"SmrtJobEvent","collectionExportName":"SmrtJobEventCollection","validationRules":[{"field":"jobId","rule":"required","fieldType":"foreignKey"},{"field":"type","rule":"required","fieldType":"text"},{"field":"level","rule":"required","fieldType":"text"},{"field":"createdAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"_smrt_job_events","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_events\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"job_id\\" UUID NOT NULL,\\n \\"type\\" TEXT NOT NULL DEFAULT 'log',\\n \\"level\\" TEXT NOT NULL DEFAULT 'info',\\n \\"stage\\" TEXT,\\n \\"progress\\" INTEGER,\\n \\"message\\" TEXT DEFAULT '',\\n \\"data\\" JSON\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"job_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false},"type":{"type":"TEXT","notNull":true,"unique":false,"default":"log"},"level":{"type":"TEXT","notNull":true,"unique":false,"default":"info"},"stage":{"type":"TEXT","notNull":false,"unique":false},"progress":{"type":"INTEGER","notNull":false,"unique":false},"message":{"type":"TEXT","notNull":false,"unique":false,"default":""},"data":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_events_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_job_events_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_job_events_job_id_idx","columns":["job_id"]}],"version":"8645e1da"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeDelivery":{"name":"forgedelivery","className":"ForgeDelivery","qualifiedName":"@happyvertical/smrt-jobs:ForgeDelivery","collection":"forgedeliveries","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"provider":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"deliveryId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"installationKey":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"repositoryKey":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"eventName":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"payload":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"pending"},"required":true,"default":"pending","enum":["pending","leased","retry","completed","dead_letter"]},"attempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0},"maxAttempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":5},"required":true,"default":5},"receivedAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"nextAttemptAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"leaseOwner":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseToken":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseExpiresAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"lastError":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"completedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"replayCount":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0}},"methods":{},"decoratorConfig":{"tableName":"_smrt_forge_deliveries","conflictColumns":["tenant_id","provider","delivery_id"],"api":false,"cli":false,"mcp":false,"indexes":[{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","nextAttemptAt"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","leaseExpiresAt"]}],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ForgeDelivery","collectionExportName":"ForgeDeliveryCollection","validationRules":[{"field":"provider","rule":"required","fieldType":"text"},{"field":"deliveryId","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"attempts","rule":"required","fieldType":"integer"},{"field":"maxAttempts","rule":"required","fieldType":"integer"},{"field":"receivedAt","rule":"required","fieldType":"datetime"},{"field":"nextAttemptAt","rule":"required","fieldType":"datetime"},{"field":"replayCount","rule":"required","fieldType":"integer"}],"schema":{"tableName":"_smrt_forge_deliveries","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_deliveries\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT NOT NULL,\\n \\"delivery_id\\" TEXT NOT NULL,\\n \\"installation_key\\" TEXT,\\n \\"repository_key\\" TEXT,\\n \\"event_name\\" TEXT,\\n \\"payload\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 5,\\n \\"received_at\\" TIMESTAMP NOT NULL,\\n \\"next_attempt_at\\" TIMESTAMP NOT NULL,\\n \\"lease_owner\\" TEXT,\\n \\"lease_token\\" TEXT,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"completed_at\\" TIMESTAMP,\\n \\"replay_count\\" INTEGER NOT NULL DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":true,"unique":false},"installation_key":{"type":"TEXT","notNull":false,"unique":false},"repository_key":{"type":"TEXT","notNull":false,"unique":false},"event_name":{"type":"TEXT","notNull":false,"unique":false},"payload":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":5},"received_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"next_attempt_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"lease_owner":{"type":"TEXT","notNull":false,"unique":false},"lease_token":{"type":"TEXT","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"replay_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0}},"indexes":[{"name":"_smrt_forge_deliveries_tenant_id_provider_idx","columns":["tenant_id","provider","delivery_id"],"unique":true},{"name":"_smrt_forge_deliveries_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","next_attempt_at"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","lease_expires_at"]},{"name":"_smrt_forge_deliveries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"870ae64b"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint":{"name":"forgeprojectioncheckpoint","className":"ForgeProjectionCheckpoint","qualifiedName":"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint","collection":"forgeprojectioncheckpoints","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"projection":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"subjectKey":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"observationVersion":{"type":"integer","_meta":{"__statedOptions":["required"],"required":true},"required":true},"deliveryId":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"observedAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true}},"methods":{},"decoratorConfig":{"tableName":"_smrt_forge_projection_checkpoints","conflictColumns":["tenant_id","projection","subject_key"],"api":false,"cli":false,"mcp":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ForgeProjectionCheckpoint","collectionExportName":"ForgeProjectionCheckpointCollection","validationRules":[{"field":"projection","rule":"required","fieldType":"text"},{"field":"subjectKey","rule":"required","fieldType":"text"},{"field":"observationVersion","rule":"required","fieldType":"integer"},{"field":"observedAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"_smrt_forge_projection_checkpoints","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_projection_checkpoints\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"projection\\" TEXT NOT NULL,\\n \\"subject_key\\" TEXT NOT NULL,\\n \\"observation_version\\" INTEGER NOT NULL,\\n \\"delivery_id\\" TEXT,\\n \\"observed_at\\" TIMESTAMP NOT NULL\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"projection":{"type":"TEXT","notNull":true,"unique":false},"subject_key":{"type":"TEXT","notNull":true,"unique":false},"observation_version":{"type":"INTEGER","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":false,"unique":false},"observed_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"_smrt_forge_projection_checkpoints_tenant_id_projection_idx","columns":["tenant_id","projection","subject_key"],"unique":true},{"name":"_smrt_forge_projection_checkpoints_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_projection_checkpoints_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4493e9ae"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeDeliveryCollection":{"name":"forgedeliverycollection","className":"ForgeDeliveryCollection","qualifiedName":"@happyvertical/smrt-jobs:ForgeDeliveryCollection","collection":"forgedeliveries","description":"Durable provider delivery inbox.","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"accept":{"name":"accept","async":true,"parameters":[{"name":"input","type":"AcceptForgeDeliveryInput","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<AcceptedForgeDelivery>","isStatic":false,"isPublic":true},"claimReady":{"name":"claimReady","async":true,"parameters":[{"name":"options","type":"ClaimForgeDeliveryOptions","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<ForgeDelivery | null>","isStatic":false,"isPublic":true},"replay":{"name":"replay","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":false,"cli":false,"mcp":false,"tableName":"_smrt_forge_deliveries"},"extends":"SmrtCollection","extendsTypeArg":"ForgeDelivery","exportName":"ForgeDeliveryCollection","collectionExportName":"ForgeDeliveryCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:ForgeDelivery","schema":{"tableName":"_smrt_forge_deliveries","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_deliveries\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT NOT NULL,\\n \\"delivery_id\\" TEXT NOT NULL,\\n \\"installation_key\\" TEXT,\\n \\"repository_key\\" TEXT,\\n \\"event_name\\" TEXT,\\n \\"payload\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 5,\\n \\"received_at\\" TIMESTAMP NOT NULL,\\n \\"next_attempt_at\\" TIMESTAMP NOT NULL,\\n \\"lease_owner\\" TEXT,\\n \\"lease_token\\" TEXT,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"completed_at\\" TIMESTAMP,\\n \\"replay_count\\" INTEGER NOT NULL DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":true,"unique":false},"installation_key":{"type":"TEXT","notNull":false,"unique":false},"repository_key":{"type":"TEXT","notNull":false,"unique":false},"event_name":{"type":"TEXT","notNull":false,"unique":false},"payload":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":5},"received_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"next_attempt_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"lease_owner":{"type":"TEXT","notNull":false,"unique":false},"lease_token":{"type":"TEXT","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"replay_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0}},"indexes":[{"name":"_smrt_forge_deliveries_tenant_id_provider_idx","columns":["tenant_id","provider","delivery_id"],"unique":true},{"name":"_smrt_forge_deliveries_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","next_attempt_at"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","lease_expires_at"]},{"name":"_smrt_forge_deliveries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"870ae64b"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobDedupeSlot":{"name":"smrtjobdedupeslot","className":"SmrtJobDedupeSlot","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobDedupeSlot","collection":"smrtjobdedupeslots","description":"Store-owned serialization row for a tenant-partitioned job deduplication key.","filePath":"src/smrt-job-dedupe-slot.ts","packageName":"@happyvertical/smrt-jobs","fields":{"slotKey":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","unique"],"required":true,"requiredFor":"idempotency","unique":true},"required":true},"jobId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"methods":{},"decoratorConfig":{"tableName":"_smrt_job_dedupe_slots","api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"SmrtJobDedupeSlot","collectionExportName":"SmrtJobDedupeSlotCollection","validationRules":[{"field":"slotKey","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_job_dedupe_slots","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_dedupe_slots\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"slot_key\\" TEXT NOT NULL UNIQUE,\\n \\"job_id\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"slot_key":{"type":"TEXT","notNull":true,"unique":true},"job_id":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_dedupe_slots_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"_smrt_job_dedupe_slots_created_at_idx","columns":["created_at"]}],"version":"f876c2d7"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection":{"name":"smrtjobdedupeslotcollection","className":"SmrtJobDedupeSlotCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection","collection":"smrtjobdedupeslots","description":"Internal collection for provisioning the registered store-owned model.","filePath":"src/smrt-job-dedupe-slot.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_job_dedupe_slots","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"SmrtJobDedupeSlot","exportName":"SmrtJobDedupeSlotCollection","collectionExportName":"SmrtJobDedupeSlotCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJobDedupeSlot","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_job_dedupe_slots","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_dedupe_slots\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"slot_key\\" TEXT NOT NULL UNIQUE,\\n \\"job_id\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"slot_key":{"type":"TEXT","notNull":true,"unique":true},"job_id":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_dedupe_slots_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"_smrt_job_dedupe_slots_created_at_idx","columns":["created_at"]}],"version":"f876c2d7"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobEventCollection":{"name":"smrtjobeventcollection","className":"SmrtJobEventCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobEventCollection","collection":"smrtjobevents","filePath":"src/smrt-job-event.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"initialize":{"name":"initialize","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"append":{"name":"append","async":true,"parameters":[{"name":"input","type":"SmrtJobEventData","optional":false}],"returnType":"Promise<SmrtJobEvent>","isStatic":false,"isPublic":true},"listByJob":{"name":"listByJob","async":true,"parameters":[{"name":"jobId","type":"string","optional":false},{"name":"options","type":"ListJobEventsOptions","optional":true}],"returnType":"Promise<SmrtJobEvent[]>","isStatic":false,"isPublic":true},"listSinceCursor":{"name":"listSinceCursor","async":true,"parameters":[{"name":"options","type":"any","optional":true,"typeUnresolved":true}],"returnType":"Promise<SmrtJobEvent[]>","isStatic":false,"isPublic":true},"latestProgressByJobIds":{"name":"latestProgressByJobIds","async":true,"parameters":[{"name":"jobIds","type":"string[]","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string | null"]}],"returnType":"Promise<Map<string, SmrtJobEvent>>","isStatic":false,"isPublic":true},"listTerminalOutcomes":{"name":"listTerminalOutcomes","async":true,"parameters":[{"name":"options","type":"ListTerminalOutcomesOptions","optional":false}],"returnType":"Promise<SmrtJobTerminalOutcomePage>","isStatic":false,"isPublic":true},"cleanup":{"name":"cleanup","async":true,"parameters":[{"name":"options","type":"object","optional":false,"memberTypes":["Date","boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_job_events","api":false,"mcp":false,"cli":{"include":["list","get"],"skipApiCheck":true}},"extends":"SmrtCollection","extendsTypeArg":"SmrtJobEvent","exportName":"SmrtJobEventCollection","collectionExportName":"SmrtJobEventCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJobEvent","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_job_events","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_events\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"job_id\\" UUID NOT NULL,\\n \\"type\\" TEXT NOT NULL DEFAULT 'log',\\n \\"level\\" TEXT NOT NULL DEFAULT 'info',\\n \\"stage\\" TEXT,\\n \\"progress\\" INTEGER,\\n \\"message\\" TEXT DEFAULT '',\\n \\"data\\" JSON\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"job_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false},"type":{"type":"TEXT","notNull":true,"unique":false,"default":"log"},"level":{"type":"TEXT","notNull":true,"unique":false,"default":"info"},"stage":{"type":"TEXT","notNull":false,"unique":false},"progress":{"type":"INTEGER","notNull":false,"unique":false},"message":{"type":"TEXT","notNull":false,"unique":false,"default":""},"data":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_events_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_job_events_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_job_events_job_id_idx","columns":["job_id"]}],"version":"8645e1da"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJob":{"name":"smrtjob","className":"SmrtJob","qualifiedName":"@happyvertical/smrt-jobs:SmrtJob","collection":"smrtjobs","description":"Persistent job record stored in the _smrt_jobs system table.","filePath":"src/smrt-job.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"dedupeKey":{"type":"text","_meta":{"__statedOptions":["nullable","indexed","required"],"nullable":true,"indexed":true,"required":false},"required":false},"queue":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"default"},"required":true,"default":"default"},"objectType":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"objectId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"method":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"args":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"runAt":{"type":"datetime","_meta":{"__statedOptions":["required","indexed"],"required":true,"indexed":true},"required":true},"priority":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":50},"required":true,"default":50},"status":{"type":"text","_meta":{"__statedOptions":["required","default","indexed","enum"],"required":true,"default":"pending","indexed":true},"required":true,"default":"pending","enum":["pending","ready","running","completed","failed","cancelled"]},"attempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0},"maxAttempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":3},"required":true,"default":3},"timeout":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":300000},"required":true,"default":300000},"timeoutBehavior":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"fail"},"required":true,"default":"fail","enum":["fail","kill","warn"]},"startedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"completedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"lastError":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"resultPointer":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskId":{"type":"text","_meta":{"__statedOptions":["nullable","unique","required"],"nullable":true,"unique":true,"required":false},"required":false},"taskOwnerId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskResult":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskInputRequests":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskInputResponses":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"retryStrategy":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"workerId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"workerHeartbeat":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"methods":{"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"retry":{"name":"retry","async":true,"parameters":[{"name":"options","type":"Pick<EnqueueJobOptions, 'transaction'>","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"cancel":{"name":"cancel","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getDescription":{"name":"getDescription","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_jobs","api":false,"cli":{"include":["list","get","retry","cancel"],"skipApiCheck":true,"http":false},"mcp":false,"indexes":[{"name":"_smrt_jobs_status_run_at_idx","columns":["status","runAt"]},{"name":"_smrt_jobs_ready_idx","columns":["status","runAt"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"}],"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"SmrtJob","collectionExportName":"SmrtJobCollection","validationRules":[{"field":"queue","rule":"required","fieldType":"text"},{"field":"objectType","rule":"required","fieldType":"text"},{"field":"method","rule":"required","fieldType":"text"},{"field":"runAt","rule":"required","fieldType":"datetime"},{"field":"priority","rule":"required","fieldType":"integer"},{"field":"status","rule":"required","fieldType":"text"},{"field":"attempts","rule":"required","fieldType":"integer"},{"field":"maxAttempts","rule":"required","fieldType":"integer"},{"field":"timeout","rule":"required","fieldType":"integer"},{"field":"timeoutBehavior","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_jobs","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_jobs\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"dedupe_key\\" TEXT,\\n \\"queue\\" TEXT NOT NULL DEFAULT 'default',\\n \\"object_type\\" TEXT NOT NULL,\\n \\"object_id\\" TEXT,\\n \\"method\\" TEXT NOT NULL,\\n \\"args\\" JSON,\\n \\"run_at\\" TIMESTAMP NOT NULL,\\n \\"priority\\" INTEGER NOT NULL DEFAULT 50,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 3,\\n \\"timeout\\" INTEGER NOT NULL DEFAULT 300000,\\n \\"timeout_behavior\\" TEXT NOT NULL DEFAULT 'fail',\\n \\"started_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"result_pointer\\" TEXT,\\n \\"task_id\\" TEXT UNIQUE,\\n \\"task_owner_id\\" TEXT,\\n \\"task_result\\" JSON,\\n \\"task_input_requests\\" JSON,\\n \\"task_input_responses\\" JSON,\\n \\"retry_strategy\\" JSON,\\n \\"worker_id\\" TEXT,\\n \\"worker_heartbeat\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"dedupe_key":{"type":"TEXT","notNull":false,"unique":false},"queue":{"type":"TEXT","notNull":true,"unique":false,"default":"default"},"object_type":{"type":"TEXT","notNull":true,"unique":false},"object_id":{"type":"TEXT","notNull":false,"unique":false},"method":{"type":"TEXT","notNull":true,"unique":false},"args":{"type":"JSON","notNull":false,"unique":false},"run_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"priority":{"type":"INTEGER","notNull":true,"unique":false,"default":50},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":3},"timeout":{"type":"INTEGER","notNull":true,"unique":false,"default":300000},"timeout_behavior":{"type":"TEXT","notNull":true,"unique":false,"default":"fail"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"result_pointer":{"type":"TEXT","notNull":false,"unique":false},"task_id":{"type":"TEXT","notNull":false,"unique":true},"task_owner_id":{"type":"TEXT","notNull":false,"unique":false},"task_result":{"type":"JSON","notNull":false,"unique":false},"task_input_requests":{"type":"JSON","notNull":false,"unique":false},"task_input_responses":{"type":"JSON","notNull":false,"unique":false},"retry_strategy":{"type":"JSON","notNull":false,"unique":false},"worker_id":{"type":"TEXT","notNull":false,"unique":false},"worker_heartbeat":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_jobs_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_jobs_dedupe_key_idx","columns":["dedupe_key"]},{"name":"_smrt_jobs_run_at_idx","columns":["run_at"]},{"name":"_smrt_jobs_status_idx","columns":["status"]},{"name":"_smrt_jobs_status_run_at_idx","columns":["status","run_at"]},{"name":"_smrt_jobs_ready_idx","columns":["status","run_at"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"},{"name":"_smrt_jobs_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4cc5c3e5"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobCollection":{"name":"smrtjobcollection","className":"SmrtJobCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobCollection","collection":"smrtjobs","description":"Collection for managing SmrtJob objects","filePath":"src/smrt-job.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"initialize":{"name":"initialize","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"listByStatus":{"name":"listByStatus","async":true,"parameters":[{"name":"status","type":"JobStatus | JobStatus[]","optional":false,"unionBranches":[{"type":"JobStatus"},{"type":"JobStatus[]"}]},{"name":"options","type":"object","optional":true,"memberTypes":["number","string"]}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"listReady":{"name":"listReady","async":true,"parameters":[{"name":"options","type":"ListReadyOptions","optional":true}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"claimReady":{"name":"claimReady","async":true,"parameters":[{"name":"options","type":"ClaimReadyOptions","optional":false}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"countInFlightForTenant":{"name":"countInFlightForTenant","async":true,"parameters":[{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"enqueueJob":{"name":"enqueueJob","async":true,"parameters":[{"name":"data","type":"SmrtJobData","optional":false},{"name":"options","type":"EnqueueJobOptions","optional":true}],"returnType":"Promise<SmrtJob>","isStatic":false,"isPublic":true},"stats":{"name":"stats","async":true,"parameters":[{"name":"queue","type":"string","optional":true}],"returnType":"Promise<object>","isStatic":false,"isPublic":true},"cleanup":{"name":"cleanup","async":true,"parameters":[{"name":"options","type":"object","optional":false,"memberTypes":["Date","number","boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_jobs","api":false,"mcp":false,"cli":{"include":["list","get"],"skipApiCheck":true}},"extends":"SmrtCollection","extendsTypeArg":"SmrtJob","exportName":"SmrtJobCollection","collectionExportName":"SmrtJobCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJob","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_jobs","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_jobs\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"dedupe_key\\" TEXT,\\n \\"queue\\" TEXT NOT NULL DEFAULT 'default',\\n \\"object_type\\" TEXT NOT NULL,\\n \\"object_id\\" TEXT,\\n \\"method\\" TEXT NOT NULL,\\n \\"args\\" JSON,\\n \\"run_at\\" TIMESTAMP NOT NULL,\\n \\"priority\\" INTEGER NOT NULL DEFAULT 50,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 3,\\n \\"timeout\\" INTEGER NOT NULL DEFAULT 300000,\\n \\"timeout_behavior\\" TEXT NOT NULL DEFAULT 'fail',\\n \\"started_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"result_pointer\\" TEXT,\\n \\"task_id\\" TEXT UNIQUE,\\n \\"task_owner_id\\" TEXT,\\n \\"task_result\\" JSON,\\n \\"task_input_requests\\" JSON,\\n \\"task_input_responses\\" JSON,\\n \\"retry_strategy\\" JSON,\\n \\"worker_id\\" TEXT,\\n \\"worker_heartbeat\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"dedupe_key":{"type":"TEXT","notNull":false,"unique":false},"queue":{"type":"TEXT","notNull":true,"unique":false,"default":"default"},"object_type":{"type":"TEXT","notNull":true,"unique":false},"object_id":{"type":"TEXT","notNull":false,"unique":false},"method":{"type":"TEXT","notNull":true,"unique":false},"args":{"type":"JSON","notNull":false,"unique":false},"run_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"priority":{"type":"INTEGER","notNull":true,"unique":false,"default":50},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":3},"timeout":{"type":"INTEGER","notNull":true,"unique":false,"default":300000},"timeout_behavior":{"type":"TEXT","notNull":true,"unique":false,"default":"fail"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"result_pointer":{"type":"TEXT","notNull":false,"unique":false},"task_id":{"type":"TEXT","notNull":false,"unique":true},"task_owner_id":{"type":"TEXT","notNull":false,"unique":false},"task_result":{"type":"JSON","notNull":false,"unique":false},"task_input_requests":{"type":"JSON","notNull":false,"unique":false},"task_input_responses":{"type":"JSON","notNull":false,"unique":false},"retry_strategy":{"type":"JSON","notNull":false,"unique":false},"worker_id":{"type":"TEXT","notNull":false,"unique":false},"worker_heartbeat":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_jobs_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_jobs_dedupe_key_idx","columns":["dedupe_key"]},{"name":"_smrt_jobs_run_at_idx","columns":["run_at"]},{"name":"_smrt_jobs_status_idx","columns":["status"]},{"name":"_smrt_jobs_status_run_at_idx","columns":["status","run_at"]},{"name":"_smrt_jobs_ready_idx","columns":["status","run_at"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"},{"name":"_smrt_jobs_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4cc5c3e5"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtWorker":{"name":"smrtworker","className":"SmrtWorker","qualifiedName":"@happyvertical/smrt-jobs:SmrtWorker","collection":"smrtworkers","description":"Liveness record for a single TaskRunner / ScheduleRunner incarnation, stored in the _smrt_workers system table.","filePath":"src/smrt-worker.ts","packageName":"@happyvertical/smrt-jobs","fields":{"workerId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"pid":{"type":"integer","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"hostname":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"startedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"heartbeatAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseExpiresAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"queues":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"status":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"running"},"required":true,"default":"running"}},"methods":{},"decoratorConfig":{"tableName":"_smrt_workers","conflictColumns":["worker_id"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"SmrtWorker","collectionExportName":"SmrtWorkerCollection","validationRules":[{"field":"workerId","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_workers","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_workers\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"worker_id\\" TEXT NOT NULL,\\n \\"pid\\" INTEGER,\\n \\"hostname\\" TEXT,\\n \\"started_at\\" TIMESTAMP,\\n \\"heartbeat_at\\" TIMESTAMP,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"queues\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'running'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"worker_id":{"type":"TEXT","notNull":true,"unique":false},"pid":{"type":"INTEGER","notNull":false,"unique":false},"hostname":{"type":"TEXT","notNull":false,"unique":false},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"heartbeat_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"queues":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"running"}},"indexes":[{"name":"_smrt_workers_worker_id_idx","columns":["worker_id"],"unique":true},{"name":"_smrt_workers_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_workers_created_at_idx","columns":["created_at"]}],"version":"2cdf9341"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtWorkerCollection":{"name":"smrtworkercollection","className":"SmrtWorkerCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtWorkerCollection","collection":"smrtworkers","description":"Collection for managing _smrt_workers liveness rows.","filePath":"src/smrt-worker.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"assertReady":{"name":"assertReady","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"tableReady":{"name":"tableReady","async":true,"parameters":[],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"registerWorker":{"name":"registerWorker","async":true,"parameters":[{"name":"input","type":"RegisterWorkerInput","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"renewLease":{"name":"renewLease","async":true,"parameters":[{"name":"workerKey","type":"string","optional":false},{"name":"leaseTtlMs","type":"number","optional":false},{"name":"queues","type":"string[] | null","optional":true,"unionBranches":[{"type":"string[]"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"expireWorker":{"name":"expireWorker","async":true,"parameters":[{"name":"workerKey","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"freshLeaseWorkerKeys":{"name":"freshLeaseWorkerKeys","async":true,"parameters":[],"returnType":"Promise<Set<string>>","isStatic":false,"isPublic":true},"liveWorkerKeysForQueue":{"name":"liveWorkerKeysForQueue","async":true,"parameters":[{"name":"queue","type":"string","optional":false}],"returnType":"Promise<Set<string>>","isStatic":false,"isPublic":true},"pruneExpired":{"name":"pruneExpired","async":true,"parameters":[{"name":"graceMs","type":"number","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_workers","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"SmrtWorker","exportName":"SmrtWorkerCollection","collectionExportName":"SmrtWorkerCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtWorker","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_workers","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_workers\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"worker_id\\" TEXT NOT NULL,\\n \\"pid\\" INTEGER,\\n \\"hostname\\" TEXT,\\n \\"started_at\\" TIMESTAMP,\\n \\"heartbeat_at\\" TIMESTAMP,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"queues\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'running'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"worker_id":{"type":"TEXT","notNull":true,"unique":false},"pid":{"type":"INTEGER","notNull":false,"unique":false},"hostname":{"type":"TEXT","notNull":false,"unique":false},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"heartbeat_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"queues":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"running"}},"indexes":[{"name":"_smrt_workers_worker_id_idx","columns":["worker_id"],"unique":true},{"name":"_smrt_workers_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_workers_created_at_idx","columns":["created_at"]}],"version":"2cdf9341"},"importPath":"@happyvertical/smrt-jobs"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3615","#3624","#3627"],"reason":"worker_threads runner (the edge commerce inherits), node:events/crypto, bull/bullmq/cloud-tasks SDK graph","via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
|
|
11
|
+
ObjectRegistry.registerPackageManifest(JSON.parse(`{"version":"1.0.0","timestamp":0,"packageName":"@happyvertical/smrt-jobs","packageVersion":"0.62.0","objects":{"@happyvertical/smrt-jobs:SmrtJobEvent":{"name":"smrtjobevent","className":"SmrtJobEvent","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobEvent","collection":"smrtjobevents","filePath":"src/smrt-job-event.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"jobId":{"type":"foreignKey","_meta":{"__statedOptions":["required","requiredFor","constraint","related"],"required":true,"requiredFor":"identity","constraint":false},"required":true,"related":"SmrtJob"},"type":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"log"},"required":true,"default":"log"},"level":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"info"},"required":true,"default":"info","enum":["debug","info","warn","error"]},"stage":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"progress":{"type":"integer","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"message":{"type":"text","_meta":{"__statedOptions":["default"],"default":""},"required":false,"default":""},"data":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"createdAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true}},"methods":{"toCursor":{"name":"toCursor","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_job_events","api":false,"cli":{"include":["list","get"],"http":false,"skipApiCheck":true},"mcp":false,"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"SmrtJobEvent","collectionExportName":"SmrtJobEventCollection","validationRules":[{"field":"jobId","rule":"required","fieldType":"foreignKey"},{"field":"type","rule":"required","fieldType":"text"},{"field":"level","rule":"required","fieldType":"text"},{"field":"createdAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"_smrt_job_events","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_events\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"job_id\\" UUID NOT NULL,\\n \\"type\\" TEXT NOT NULL DEFAULT 'log',\\n \\"level\\" TEXT NOT NULL DEFAULT 'info',\\n \\"stage\\" TEXT,\\n \\"progress\\" INTEGER,\\n \\"message\\" TEXT DEFAULT '',\\n \\"data\\" JSON\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"job_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false},"type":{"type":"TEXT","notNull":true,"unique":false,"default":"log"},"level":{"type":"TEXT","notNull":true,"unique":false,"default":"info"},"stage":{"type":"TEXT","notNull":false,"unique":false},"progress":{"type":"INTEGER","notNull":false,"unique":false},"message":{"type":"TEXT","notNull":false,"unique":false,"default":""},"data":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_events_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_job_events_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_job_events_job_id_idx","columns":["job_id"]}],"version":"8645e1da"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeDelivery":{"name":"forgedelivery","className":"ForgeDelivery","qualifiedName":"@happyvertical/smrt-jobs:ForgeDelivery","collection":"forgedeliveries","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"provider":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"deliveryId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"installationKey":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"repositoryKey":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"eventName":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"payload":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"status":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"pending"},"required":true,"default":"pending","enum":["pending","leased","retry","completed","dead_letter"]},"attempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0},"maxAttempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":5},"required":true,"default":5},"receivedAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"nextAttemptAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true},"leaseOwner":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseToken":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseExpiresAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"lastError":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"completedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"replayCount":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0}},"methods":{},"decoratorConfig":{"tableName":"_smrt_forge_deliveries","conflictColumns":["tenant_id","provider","delivery_id"],"api":false,"cli":false,"mcp":false,"indexes":[{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","nextAttemptAt"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","leaseExpiresAt"]}],"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ForgeDelivery","collectionExportName":"ForgeDeliveryCollection","validationRules":[{"field":"provider","rule":"required","fieldType":"text"},{"field":"deliveryId","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"},{"field":"attempts","rule":"required","fieldType":"integer"},{"field":"maxAttempts","rule":"required","fieldType":"integer"},{"field":"receivedAt","rule":"required","fieldType":"datetime"},{"field":"nextAttemptAt","rule":"required","fieldType":"datetime"},{"field":"replayCount","rule":"required","fieldType":"integer"}],"schema":{"tableName":"_smrt_forge_deliveries","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_deliveries\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT NOT NULL,\\n \\"delivery_id\\" TEXT NOT NULL,\\n \\"installation_key\\" TEXT,\\n \\"repository_key\\" TEXT,\\n \\"event_name\\" TEXT,\\n \\"payload\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 5,\\n \\"received_at\\" TIMESTAMP NOT NULL,\\n \\"next_attempt_at\\" TIMESTAMP NOT NULL,\\n \\"lease_owner\\" TEXT,\\n \\"lease_token\\" TEXT,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"completed_at\\" TIMESTAMP,\\n \\"replay_count\\" INTEGER NOT NULL DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":true,"unique":false},"installation_key":{"type":"TEXT","notNull":false,"unique":false},"repository_key":{"type":"TEXT","notNull":false,"unique":false},"event_name":{"type":"TEXT","notNull":false,"unique":false},"payload":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":5},"received_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"next_attempt_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"lease_owner":{"type":"TEXT","notNull":false,"unique":false},"lease_token":{"type":"TEXT","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"replay_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0}},"indexes":[{"name":"_smrt_forge_deliveries_tenant_id_provider_idx","columns":["tenant_id","provider","delivery_id"],"unique":true},{"name":"_smrt_forge_deliveries_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","next_attempt_at"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","lease_expires_at"]},{"name":"_smrt_forge_deliveries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"870ae64b"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint":{"name":"forgeprojectioncheckpoint","className":"ForgeProjectionCheckpoint","qualifiedName":"@happyvertical/smrt-jobs:ForgeProjectionCheckpoint","collection":"forgeprojectioncheckpoints","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":true,"autoPopulate":true,"nullable":false,"mode":"required","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","requiredFor","__tenancy"],"sqlType":"UUID","requiredFor":"tenant-scope"},"required":true},"projection":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"subjectKey":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"observationVersion":{"type":"integer","_meta":{"__statedOptions":["required"],"required":true},"required":true},"deliveryId":{"type":"text","_meta":{"__statedOptions":[]},"required":false},"observedAt":{"type":"datetime","_meta":{"__statedOptions":["required"],"required":true},"required":true}},"methods":{},"decoratorConfig":{"tableName":"_smrt_forge_projection_checkpoints","conflictColumns":["tenant_id","projection","subject_key"],"api":false,"cli":false,"mcp":false,"tenantScoped":{"mode":"required"}},"extends":"SmrtObject","exportName":"ForgeProjectionCheckpoint","collectionExportName":"ForgeProjectionCheckpointCollection","validationRules":[{"field":"projection","rule":"required","fieldType":"text"},{"field":"subjectKey","rule":"required","fieldType":"text"},{"field":"observationVersion","rule":"required","fieldType":"integer"},{"field":"observedAt","rule":"required","fieldType":"datetime"}],"schema":{"tableName":"_smrt_forge_projection_checkpoints","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_projection_checkpoints\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"projection\\" TEXT NOT NULL,\\n \\"subject_key\\" TEXT NOT NULL,\\n \\"observation_version\\" INTEGER NOT NULL,\\n \\"delivery_id\\" TEXT,\\n \\"observed_at\\" TIMESTAMP NOT NULL\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"projection":{"type":"TEXT","notNull":true,"unique":false},"subject_key":{"type":"TEXT","notNull":true,"unique":false},"observation_version":{"type":"INTEGER","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":false,"unique":false},"observed_at":{"type":"TIMESTAMP","notNull":true,"unique":false}},"indexes":[{"name":"_smrt_forge_projection_checkpoints_tenant_id_projection_idx","columns":["tenant_id","projection","subject_key"],"unique":true},{"name":"_smrt_forge_projection_checkpoints_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_projection_checkpoints_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4493e9ae"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:ForgeDeliveryCollection":{"name":"forgedeliverycollection","className":"ForgeDeliveryCollection","qualifiedName":"@happyvertical/smrt-jobs:ForgeDeliveryCollection","collection":"forgedeliveries","description":"Durable provider delivery inbox.","filePath":"src/forge-projection.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"accept":{"name":"accept","async":true,"parameters":[{"name":"input","type":"AcceptForgeDeliveryInput","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<AcceptedForgeDelivery>","isStatic":false,"isPublic":true},"claimReady":{"name":"claimReady","async":true,"parameters":[{"name":"options","type":"ClaimForgeDeliveryOptions","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<ForgeDelivery | null>","isStatic":false,"isPublic":true},"replay":{"name":"replay","async":true,"parameters":[{"name":"id","type":"string","optional":false},{"name":"audit","type":"ForgeProjectionAuditHook","optional":true,"resolvedType":"Function"}],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true}},"decoratorConfig":{"api":false,"cli":false,"mcp":false,"tableName":"_smrt_forge_deliveries"},"extends":"SmrtCollection","extendsTypeArg":"ForgeDelivery","exportName":"ForgeDeliveryCollection","collectionExportName":"ForgeDeliveryCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:ForgeDelivery","schema":{"tableName":"_smrt_forge_deliveries","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_forge_deliveries\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID NOT NULL,\\n \\"provider\\" TEXT NOT NULL,\\n \\"delivery_id\\" TEXT NOT NULL,\\n \\"installation_key\\" TEXT,\\n \\"repository_key\\" TEXT,\\n \\"event_name\\" TEXT,\\n \\"payload\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 5,\\n \\"received_at\\" TIMESTAMP NOT NULL,\\n \\"next_attempt_at\\" TIMESTAMP NOT NULL,\\n \\"lease_owner\\" TEXT,\\n \\"lease_token\\" TEXT,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"completed_at\\" TIMESTAMP,\\n \\"replay_count\\" INTEGER NOT NULL DEFAULT 0\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":true,"unique":false},"provider":{"type":"TEXT","notNull":true,"unique":false},"delivery_id":{"type":"TEXT","notNull":true,"unique":false},"installation_key":{"type":"TEXT","notNull":false,"unique":false},"repository_key":{"type":"TEXT","notNull":false,"unique":false},"event_name":{"type":"TEXT","notNull":false,"unique":false},"payload":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":5},"received_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"next_attempt_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"lease_owner":{"type":"TEXT","notNull":false,"unique":false},"lease_token":{"type":"TEXT","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"replay_count":{"type":"INTEGER","notNull":true,"unique":false,"default":0}},"indexes":[{"name":"_smrt_forge_deliveries_tenant_id_provider_idx","columns":["tenant_id","provider","delivery_id"],"unique":true},{"name":"_smrt_forge_deliveries_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_forge_deliveries_status_next_attempt_at_idx","columns":["status","next_attempt_at"]},{"name":"_smrt_forge_deliveries_status_lease_expires_at_idx","columns":["status","lease_expires_at"]},{"name":"_smrt_forge_deliveries_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"870ae64b"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobDedupeSlot":{"name":"smrtjobdedupeslot","className":"SmrtJobDedupeSlot","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobDedupeSlot","collection":"smrtjobdedupeslots","description":"Store-owned serialization row for a tenant-partitioned job deduplication key.","filePath":"src/smrt-job-dedupe-slot.ts","packageName":"@happyvertical/smrt-jobs","fields":{"slotKey":{"type":"text","_meta":{"__statedOptions":["required","requiredFor","unique"],"required":true,"requiredFor":"idempotency","unique":true},"required":true},"jobId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"methods":{},"decoratorConfig":{"tableName":"_smrt_job_dedupe_slots","api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"SmrtJobDedupeSlot","collectionExportName":"SmrtJobDedupeSlotCollection","validationRules":[{"field":"slotKey","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_job_dedupe_slots","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_dedupe_slots\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"slot_key\\" TEXT NOT NULL UNIQUE,\\n \\"job_id\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"slot_key":{"type":"TEXT","notNull":true,"unique":true},"job_id":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_dedupe_slots_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"_smrt_job_dedupe_slots_created_at_idx","columns":["created_at"]}],"version":"f876c2d7"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection":{"name":"smrtjobdedupeslotcollection","className":"SmrtJobDedupeSlotCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection","collection":"smrtjobdedupeslots","description":"Internal collection for provisioning the registered store-owned model.","filePath":"src/smrt-job-dedupe-slot.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{},"decoratorConfig":{"tableName":"_smrt_job_dedupe_slots","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"SmrtJobDedupeSlot","exportName":"SmrtJobDedupeSlotCollection","collectionExportName":"SmrtJobDedupeSlotCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJobDedupeSlot","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_job_dedupe_slots","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_dedupe_slots\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"slot_key\\" TEXT NOT NULL UNIQUE,\\n \\"job_id\\" TEXT\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"slot_key":{"type":"TEXT","notNull":true,"unique":true},"job_id":{"type":"TEXT","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_dedupe_slots_slug_context_idx","columns":["slug","context"],"unique":true},{"name":"_smrt_job_dedupe_slots_created_at_idx","columns":["created_at"]}],"version":"f876c2d7"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobEventCollection":{"name":"smrtjobeventcollection","className":"SmrtJobEventCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobEventCollection","collection":"smrtjobevents","filePath":"src/smrt-job-event.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"initialize":{"name":"initialize","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"append":{"name":"append","async":true,"parameters":[{"name":"input","type":"SmrtJobEventData","optional":false}],"returnType":"Promise<SmrtJobEvent>","isStatic":false,"isPublic":true},"listByJob":{"name":"listByJob","async":true,"parameters":[{"name":"jobId","type":"string","optional":false},{"name":"options","type":"ListJobEventsOptions","optional":true}],"returnType":"Promise<SmrtJobEvent[]>","isStatic":false,"isPublic":true},"listSinceCursor":{"name":"listSinceCursor","async":true,"parameters":[{"name":"options","type":"any","optional":true,"typeUnresolved":true}],"returnType":"Promise<SmrtJobEvent[]>","isStatic":false,"isPublic":true},"latestProgressByJobIds":{"name":"latestProgressByJobIds","async":true,"parameters":[{"name":"jobIds","type":"string[]","optional":false},{"name":"options","type":"object","optional":true,"memberTypes":["string | null"]}],"returnType":"Promise<Map<string, SmrtJobEvent>>","isStatic":false,"isPublic":true},"listTerminalOutcomes":{"name":"listTerminalOutcomes","async":true,"parameters":[{"name":"options","type":"ListTerminalOutcomesOptions","optional":false}],"returnType":"Promise<SmrtJobTerminalOutcomePage>","isStatic":false,"isPublic":true},"getTerminalOutcome":{"name":"getTerminalOutcome","async":true,"parameters":[{"name":"jobId","type":"string","optional":false},{"name":"options","type":"GetTerminalOutcomeOptions","optional":false}],"returnType":"Promise<SmrtJobTerminalOutcome | null>","isStatic":false,"isPublic":true},"cleanup":{"name":"cleanup","async":true,"parameters":[{"name":"options","type":"object","optional":false,"memberTypes":["Date","boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_job_events","api":false,"mcp":false,"cli":{"include":["list","get"],"skipApiCheck":true}},"extends":"SmrtCollection","extendsTypeArg":"SmrtJobEvent","exportName":"SmrtJobEventCollection","collectionExportName":"SmrtJobEventCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJobEvent","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_job_events","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_job_events\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"job_id\\" UUID NOT NULL,\\n \\"type\\" TEXT NOT NULL DEFAULT 'log',\\n \\"level\\" TEXT NOT NULL DEFAULT 'info',\\n \\"stage\\" TEXT,\\n \\"progress\\" INTEGER,\\n \\"message\\" TEXT DEFAULT '',\\n \\"data\\" JSON\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"job_id":{"type":"UUID","referenceKind":"foreignKey","notNull":true,"unique":false},"type":{"type":"TEXT","notNull":true,"unique":false,"default":"log"},"level":{"type":"TEXT","notNull":true,"unique":false,"default":"info"},"stage":{"type":"TEXT","notNull":false,"unique":false},"progress":{"type":"INTEGER","notNull":false,"unique":false},"message":{"type":"TEXT","notNull":false,"unique":false,"default":""},"data":{"type":"JSON","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_job_events_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_job_events_tenant_id_created_at_idx","columns":["tenant_id","created_at"]},{"name":"_smrt_job_events_job_id_idx","columns":["job_id"]}],"version":"8645e1da"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJob":{"name":"smrtjob","className":"SmrtJob","qualifiedName":"@happyvertical/smrt-jobs:SmrtJob","collection":"smrtjobs","description":"Persistent job record stored in the _smrt_jobs system table.","filePath":"src/smrt-job.ts","packageName":"@happyvertical/smrt-jobs","fields":{"tenantId":{"type":"text","_meta":{"__tenancy":{"isTenantIdField":true,"autoFilter":true,"required":false,"autoPopulate":true,"nullable":true,"mode":"optional","field":"tenantId","allowSuperAdminBypass":false},"__statedOptions":["sqlType","nullable","__tenancy","required"],"sqlType":"UUID","nullable":true,"required":false},"required":false},"dedupeKey":{"type":"text","_meta":{"__statedOptions":["nullable","indexed","required"],"nullable":true,"indexed":true,"required":false},"required":false},"queue":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"default"},"required":true,"default":"default"},"objectType":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"objectId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"method":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"args":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"runAt":{"type":"datetime","_meta":{"__statedOptions":["required","indexed"],"required":true,"indexed":true},"required":true},"priority":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":50},"required":true,"default":50},"status":{"type":"text","_meta":{"__statedOptions":["required","default","indexed","enum"],"required":true,"default":"pending","indexed":true},"required":true,"default":"pending","enum":["pending","ready","running","completed","failed","cancelled"]},"attempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":0},"required":true,"default":0},"maxAttempts":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":3},"required":true,"default":3},"timeout":{"type":"integer","_meta":{"__statedOptions":["required","default"],"required":true,"default":300000},"required":true,"default":300000},"timeoutBehavior":{"type":"text","_meta":{"__statedOptions":["required","default","enum"],"required":true,"default":"fail"},"required":true,"default":"fail","enum":["fail","kill","warn"]},"startedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"completedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"lastError":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"resultPointer":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskId":{"type":"text","_meta":{"__statedOptions":["nullable","unique","required"],"nullable":true,"unique":true,"required":false},"required":false},"taskOwnerId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskResult":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskInputRequests":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"taskInputResponses":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"retryStrategy":{"type":"json","_meta":{"__statedOptions":[]},"required":false},"workerId":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"workerHeartbeat":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false}},"methods":{"save":{"name":"save","async":true,"parameters":[{"name":"options","type":"SmrtSaveOptions","optional":true}],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"retry":{"name":"retry","async":true,"parameters":[{"name":"options","type":"Pick<EnqueueJobOptions, 'transaction'>","optional":true}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"cancel":{"name":"cancel","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"getDescription":{"name":"getDescription","async":false,"parameters":[],"returnType":"string","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_jobs","api":false,"cli":{"include":["list","get","retry","cancel"],"skipApiCheck":true,"http":false},"mcp":false,"indexes":[{"name":"_smrt_jobs_status_run_at_idx","columns":["status","runAt"]},{"name":"_smrt_jobs_ready_idx","columns":["status","runAt"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"}],"tenantScoped":{"mode":"optional"},"conflictColumns":["tenant_id","slug","context"]},"extends":"SmrtObject","exportName":"SmrtJob","collectionExportName":"SmrtJobCollection","validationRules":[{"field":"queue","rule":"required","fieldType":"text"},{"field":"objectType","rule":"required","fieldType":"text"},{"field":"method","rule":"required","fieldType":"text"},{"field":"runAt","rule":"required","fieldType":"datetime"},{"field":"priority","rule":"required","fieldType":"integer"},{"field":"status","rule":"required","fieldType":"text"},{"field":"attempts","rule":"required","fieldType":"integer"},{"field":"maxAttempts","rule":"required","fieldType":"integer"},{"field":"timeout","rule":"required","fieldType":"integer"},{"field":"timeoutBehavior","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_jobs","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_jobs\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"dedupe_key\\" TEXT,\\n \\"queue\\" TEXT NOT NULL DEFAULT 'default',\\n \\"object_type\\" TEXT NOT NULL,\\n \\"object_id\\" TEXT,\\n \\"method\\" TEXT NOT NULL,\\n \\"args\\" JSON,\\n \\"run_at\\" TIMESTAMP NOT NULL,\\n \\"priority\\" INTEGER NOT NULL DEFAULT 50,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 3,\\n \\"timeout\\" INTEGER NOT NULL DEFAULT 300000,\\n \\"timeout_behavior\\" TEXT NOT NULL DEFAULT 'fail',\\n \\"started_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"result_pointer\\" TEXT,\\n \\"task_id\\" TEXT UNIQUE,\\n \\"task_owner_id\\" TEXT,\\n \\"task_result\\" JSON,\\n \\"task_input_requests\\" JSON,\\n \\"task_input_responses\\" JSON,\\n \\"retry_strategy\\" JSON,\\n \\"worker_id\\" TEXT,\\n \\"worker_heartbeat\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"dedupe_key":{"type":"TEXT","notNull":false,"unique":false},"queue":{"type":"TEXT","notNull":true,"unique":false,"default":"default"},"object_type":{"type":"TEXT","notNull":true,"unique":false},"object_id":{"type":"TEXT","notNull":false,"unique":false},"method":{"type":"TEXT","notNull":true,"unique":false},"args":{"type":"JSON","notNull":false,"unique":false},"run_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"priority":{"type":"INTEGER","notNull":true,"unique":false,"default":50},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":3},"timeout":{"type":"INTEGER","notNull":true,"unique":false,"default":300000},"timeout_behavior":{"type":"TEXT","notNull":true,"unique":false,"default":"fail"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"result_pointer":{"type":"TEXT","notNull":false,"unique":false},"task_id":{"type":"TEXT","notNull":false,"unique":true},"task_owner_id":{"type":"TEXT","notNull":false,"unique":false},"task_result":{"type":"JSON","notNull":false,"unique":false},"task_input_requests":{"type":"JSON","notNull":false,"unique":false},"task_input_responses":{"type":"JSON","notNull":false,"unique":false},"retry_strategy":{"type":"JSON","notNull":false,"unique":false},"worker_id":{"type":"TEXT","notNull":false,"unique":false},"worker_heartbeat":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_jobs_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_jobs_dedupe_key_idx","columns":["dedupe_key"]},{"name":"_smrt_jobs_run_at_idx","columns":["run_at"]},{"name":"_smrt_jobs_status_idx","columns":["status"]},{"name":"_smrt_jobs_status_run_at_idx","columns":["status","run_at"]},{"name":"_smrt_jobs_ready_idx","columns":["status","run_at"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"},{"name":"_smrt_jobs_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4cc5c3e5"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtJobCollection":{"name":"smrtjobcollection","className":"SmrtJobCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtJobCollection","collection":"smrtjobs","description":"Collection for managing SmrtJob objects","filePath":"src/smrt-job.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"initialize":{"name":"initialize","async":true,"parameters":[],"returnType":"Promise<this>","isStatic":false,"isPublic":true},"listByStatus":{"name":"listByStatus","async":true,"parameters":[{"name":"status","type":"JobStatus | JobStatus[]","optional":false,"unionBranches":[{"type":"JobStatus"},{"type":"JobStatus[]"}]},{"name":"options","type":"object","optional":true,"memberTypes":["number","string"]}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"listReady":{"name":"listReady","async":true,"parameters":[{"name":"options","type":"ListReadyOptions","optional":true}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"claimReady":{"name":"claimReady","async":true,"parameters":[{"name":"options","type":"ClaimReadyOptions","optional":false}],"returnType":"Promise<SmrtJob[]>","isStatic":false,"isPublic":true},"countInFlightForTenant":{"name":"countInFlightForTenant","async":true,"parameters":[{"name":"tenantId","type":"string | null","optional":false,"unionBranches":[{"type":"string"},{"type":"null"}]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true},"enqueueJob":{"name":"enqueueJob","async":true,"parameters":[{"name":"data","type":"SmrtJobData","optional":false},{"name":"options","type":"EnqueueJobOptions","optional":true}],"returnType":"Promise<SmrtJob>","isStatic":false,"isPublic":true},"enqueueHandlerJob":{"name":"enqueueHandlerJob","async":true,"parameters":[{"name":"data","type":"HandlerJobData","optional":false},{"name":"options","type":"EnqueueJobOptions","optional":true}],"returnType":"Promise<SmrtJob>","isStatic":false,"isPublic":true},"stats":{"name":"stats","async":true,"parameters":[{"name":"queue","type":"string","optional":true}],"returnType":"Promise<object>","isStatic":false,"isPublic":true},"cleanup":{"name":"cleanup","async":true,"parameters":[{"name":"options","type":"object","optional":false,"memberTypes":["Date","number","boolean"]}],"returnType":"Promise<number>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_jobs","api":false,"mcp":false,"cli":{"include":["list","get"],"skipApiCheck":true}},"extends":"SmrtCollection","extendsTypeArg":"SmrtJob","exportName":"SmrtJobCollection","collectionExportName":"SmrtJobCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtJob","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_jobs","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_jobs\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"tenant_id\\" UUID,\\n \\"dedupe_key\\" TEXT,\\n \\"queue\\" TEXT NOT NULL DEFAULT 'default',\\n \\"object_type\\" TEXT NOT NULL,\\n \\"object_id\\" TEXT,\\n \\"method\\" TEXT NOT NULL,\\n \\"args\\" JSON,\\n \\"run_at\\" TIMESTAMP NOT NULL,\\n \\"priority\\" INTEGER NOT NULL DEFAULT 50,\\n \\"status\\" TEXT NOT NULL DEFAULT 'pending',\\n \\"attempts\\" INTEGER NOT NULL DEFAULT 0,\\n \\"max_attempts\\" INTEGER NOT NULL DEFAULT 3,\\n \\"timeout\\" INTEGER NOT NULL DEFAULT 300000,\\n \\"timeout_behavior\\" TEXT NOT NULL DEFAULT 'fail',\\n \\"started_at\\" TIMESTAMP,\\n \\"completed_at\\" TIMESTAMP,\\n \\"last_error\\" TEXT,\\n \\"result_pointer\\" TEXT,\\n \\"task_id\\" TEXT UNIQUE,\\n \\"task_owner_id\\" TEXT,\\n \\"task_result\\" JSON,\\n \\"task_input_requests\\" JSON,\\n \\"task_input_responses\\" JSON,\\n \\"retry_strategy\\" JSON,\\n \\"worker_id\\" TEXT,\\n \\"worker_heartbeat\\" TIMESTAMP\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"tenant_id":{"type":"UUID","referenceKind":"tenantId","notNull":false,"unique":false},"dedupe_key":{"type":"TEXT","notNull":false,"unique":false},"queue":{"type":"TEXT","notNull":true,"unique":false,"default":"default"},"object_type":{"type":"TEXT","notNull":true,"unique":false},"object_id":{"type":"TEXT","notNull":false,"unique":false},"method":{"type":"TEXT","notNull":true,"unique":false},"args":{"type":"JSON","notNull":false,"unique":false},"run_at":{"type":"TIMESTAMP","notNull":true,"unique":false},"priority":{"type":"INTEGER","notNull":true,"unique":false,"default":50},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"pending"},"attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":0},"max_attempts":{"type":"INTEGER","notNull":true,"unique":false,"default":3},"timeout":{"type":"INTEGER","notNull":true,"unique":false,"default":300000},"timeout_behavior":{"type":"TEXT","notNull":true,"unique":false,"default":"fail"},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"completed_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"last_error":{"type":"TEXT","notNull":false,"unique":false},"result_pointer":{"type":"TEXT","notNull":false,"unique":false},"task_id":{"type":"TEXT","notNull":false,"unique":true},"task_owner_id":{"type":"TEXT","notNull":false,"unique":false},"task_result":{"type":"JSON","notNull":false,"unique":false},"task_input_requests":{"type":"JSON","notNull":false,"unique":false},"task_input_responses":{"type":"JSON","notNull":false,"unique":false},"retry_strategy":{"type":"JSON","notNull":false,"unique":false},"worker_id":{"type":"TEXT","notNull":false,"unique":false},"worker_heartbeat":{"type":"TIMESTAMP","notNull":false,"unique":false}},"indexes":[{"name":"_smrt_jobs_slug_context_idx","columns":["tenant_id","slug","context"],"unique":true,"nullsNotDistinct":true},{"name":"_smrt_jobs_dedupe_key_idx","columns":["dedupe_key"]},{"name":"_smrt_jobs_run_at_idx","columns":["run_at"]},{"name":"_smrt_jobs_status_idx","columns":["status"]},{"name":"_smrt_jobs_status_run_at_idx","columns":["status","run_at"]},{"name":"_smrt_jobs_ready_idx","columns":["status","run_at"],"where":"status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"},{"name":"_smrt_jobs_tenant_id_created_at_idx","columns":["tenant_id","created_at"]}],"version":"4cc5c3e5"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtWorker":{"name":"smrtworker","className":"SmrtWorker","qualifiedName":"@happyvertical/smrt-jobs:SmrtWorker","collection":"smrtworkers","description":"Liveness record for a single TaskRunner / ScheduleRunner incarnation, stored in the _smrt_workers system table.","filePath":"src/smrt-worker.ts","packageName":"@happyvertical/smrt-jobs","fields":{"workerId":{"type":"text","_meta":{"__statedOptions":["required","requiredFor"],"required":true,"requiredFor":"identity"},"required":true},"pid":{"type":"integer","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"hostname":{"type":"text","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"startedAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"heartbeatAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"leaseExpiresAt":{"type":"datetime","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"queues":{"type":"json","_meta":{"__statedOptions":["nullable","required"],"nullable":true,"required":false},"required":false},"status":{"type":"text","_meta":{"__statedOptions":["required","default"],"required":true,"default":"running"},"required":true,"default":"running"}},"methods":{},"decoratorConfig":{"tableName":"_smrt_workers","conflictColumns":["worker_id"],"api":false,"cli":false,"mcp":false},"extends":"SmrtObject","exportName":"SmrtWorker","collectionExportName":"SmrtWorkerCollection","validationRules":[{"field":"workerId","rule":"required","fieldType":"text"},{"field":"status","rule":"required","fieldType":"text"}],"schema":{"tableName":"_smrt_workers","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_workers\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"worker_id\\" TEXT NOT NULL,\\n \\"pid\\" INTEGER,\\n \\"hostname\\" TEXT,\\n \\"started_at\\" TIMESTAMP,\\n \\"heartbeat_at\\" TIMESTAMP,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"queues\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'running'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"worker_id":{"type":"TEXT","notNull":true,"unique":false},"pid":{"type":"INTEGER","notNull":false,"unique":false},"hostname":{"type":"TEXT","notNull":false,"unique":false},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"heartbeat_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"queues":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"running"}},"indexes":[{"name":"_smrt_workers_worker_id_idx","columns":["worker_id"],"unique":true},{"name":"_smrt_workers_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_workers_created_at_idx","columns":["created_at"]}],"version":"2cdf9341"},"importPath":"@happyvertical/smrt-jobs"},"@happyvertical/smrt-jobs:SmrtWorkerCollection":{"name":"smrtworkercollection","className":"SmrtWorkerCollection","qualifiedName":"@happyvertical/smrt-jobs:SmrtWorkerCollection","collection":"smrtworkers","description":"Collection for managing _smrt_workers liveness rows.","filePath":"src/smrt-worker.ts","packageName":"@happyvertical/smrt-jobs","fields":{},"methods":{"assertReady":{"name":"assertReady","async":true,"parameters":[],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"tableReady":{"name":"tableReady","async":true,"parameters":[],"returnType":"Promise<boolean>","isStatic":false,"isPublic":true},"registerWorker":{"name":"registerWorker","async":true,"parameters":[{"name":"input","type":"RegisterWorkerInput","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"renewLease":{"name":"renewLease","async":true,"parameters":[{"name":"workerKey","type":"string","optional":false},{"name":"leaseTtlMs","type":"number","optional":false},{"name":"queues","type":"string[] | null","optional":true,"unionBranches":[{"type":"string[]"},{"type":"null"}]}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"expireWorker":{"name":"expireWorker","async":true,"parameters":[{"name":"workerKey","type":"string","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true},"freshLeaseWorkerKeys":{"name":"freshLeaseWorkerKeys","async":true,"parameters":[],"returnType":"Promise<Set<string>>","isStatic":false,"isPublic":true},"liveWorkerKeysForQueue":{"name":"liveWorkerKeysForQueue","async":true,"parameters":[{"name":"queue","type":"string","optional":false}],"returnType":"Promise<Set<string>>","isStatic":false,"isPublic":true},"pruneExpired":{"name":"pruneExpired","async":true,"parameters":[{"name":"graceMs","type":"number","optional":false}],"returnType":"Promise<void>","isStatic":false,"isPublic":true}},"decoratorConfig":{"tableName":"_smrt_workers","api":false,"mcp":false,"cli":false},"extends":"SmrtCollection","extendsTypeArg":"SmrtWorker","exportName":"SmrtWorkerCollection","collectionExportName":"SmrtWorkerCollectionCollection","collectionOf":"@happyvertical/smrt-jobs:SmrtWorker","inheritedExposure":["api","mcp","cli"],"schema":{"tableName":"_smrt_workers","ddl":"CREATE TABLE IF NOT EXISTS \\"_smrt_workers\\" (\\n \\"_sync_origin_device_id\\" TEXT,\\n \\"_sync_revision\\" INTEGER,\\n \\"id\\" UUID PRIMARY KEY NOT NULL,\\n \\"slug\\" TEXT NOT NULL,\\n \\"context\\" TEXT NOT NULL DEFAULT '',\\n \\"created_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"updated_at\\" TIMESTAMP NOT NULL DEFAULT current_timestamp,\\n \\"worker_id\\" TEXT NOT NULL,\\n \\"pid\\" INTEGER,\\n \\"hostname\\" TEXT,\\n \\"started_at\\" TIMESTAMP,\\n \\"heartbeat_at\\" TIMESTAMP,\\n \\"lease_expires_at\\" TIMESTAMP,\\n \\"queues\\" JSON,\\n \\"status\\" TEXT NOT NULL DEFAULT 'running'\\n);","columns":{"_sync_origin_device_id":{"type":"TEXT"},"_sync_revision":{"type":"INTEGER"},"id":{"type":"UUID","primaryKey":true,"referenceKind":"id","notNull":true},"slug":{"type":"TEXT","notNull":true},"context":{"type":"TEXT","notNull":true,"default":""},"created_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"updated_at":{"type":"TIMESTAMP","notNull":true,"default":"current_timestamp"},"worker_id":{"type":"TEXT","notNull":true,"unique":false},"pid":{"type":"INTEGER","notNull":false,"unique":false},"hostname":{"type":"TEXT","notNull":false,"unique":false},"started_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"heartbeat_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"lease_expires_at":{"type":"TIMESTAMP","notNull":false,"unique":false},"queues":{"type":"JSON","notNull":false,"unique":false},"status":{"type":"TEXT","notNull":true,"unique":false,"default":"running"}},"indexes":[{"name":"_smrt_workers_worker_id_idx","columns":["worker_id"],"unique":true},{"name":"_smrt_workers_slug_context_idx","columns":["slug","context"]},{"name":"_smrt_workers_created_at_idx","columns":["created_at"]}],"version":"2cdf9341"},"importPath":"@happyvertical/smrt-jobs"}},"moduleType":"smrt","smrtDependencies":["@happyvertical/smrt-core","@happyvertical/smrt-tenancy"],"browser":{"status":"server-only","issues":["#3615","#3624","#3627"],"reason":"worker_threads runner (the edge commerce inherits), node:events/crypto, bull/bullmq/cloud-tasks SDK graph","via":["@happyvertical/smrt-tenancy"]},"stampsConstructors":true}`));
|
|
12
12
|
//#endregion
|
|
13
13
|
//#region src/background-policy.ts
|
|
14
14
|
var MAX_JOB_RETRIES = 25;
|
|
@@ -59,6 +59,122 @@ function isBackgroundEligibleMethod(ctor, method) {
|
|
|
59
59
|
return allow.has(method);
|
|
60
60
|
}
|
|
61
61
|
//#endregion
|
|
62
|
+
//#region src/job-handlers.ts
|
|
63
|
+
var JOB_HANDLER_TARGET_PREFIX = "handler:";
|
|
64
|
+
var JOB_HANDLER_METHOD = "handle";
|
|
65
|
+
var MAX_JOB_HANDLERS = 256;
|
|
66
|
+
var MAX_HANDLER_NAME_LENGTH = 200;
|
|
67
|
+
var HANDLER_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*:[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)*$/;
|
|
68
|
+
var JobHandlerNameError = class extends TypeError {
|
|
69
|
+
constructor(handler) {
|
|
70
|
+
super(`Invalid job handler name ${JSON.stringify(handler)}: expected "<package>:<name>", e.g. "@happyvertical/smrt-workflows:workflow-run"`);
|
|
71
|
+
this.handler = handler;
|
|
72
|
+
this.name = "JobHandlerNameError";
|
|
73
|
+
}
|
|
74
|
+
handler;
|
|
75
|
+
};
|
|
76
|
+
var JobHandlerAlreadyRegisteredError = class extends Error {
|
|
77
|
+
constructor(handler) {
|
|
78
|
+
super(`Job handler already registered: ${handler}`);
|
|
79
|
+
this.handler = handler;
|
|
80
|
+
this.name = "JobHandlerAlreadyRegisteredError";
|
|
81
|
+
}
|
|
82
|
+
handler;
|
|
83
|
+
};
|
|
84
|
+
var JobHandlerLimitError = class extends RangeError {
|
|
85
|
+
constructor(handler) {
|
|
86
|
+
super(`Cannot register job handler ${handler}: a process may register at most 256 job handlers`);
|
|
87
|
+
this.handler = handler;
|
|
88
|
+
this.name = "JobHandlerLimitError";
|
|
89
|
+
}
|
|
90
|
+
handler;
|
|
91
|
+
};
|
|
92
|
+
var JobHandlerRegistrationClosedError = class extends Error {
|
|
93
|
+
constructor(handler) {
|
|
94
|
+
super(`Cannot change job handler ${handler} while a TaskRunner is running; register handlers before runner.start()`);
|
|
95
|
+
this.handler = handler;
|
|
96
|
+
this.name = "JobHandlerRegistrationClosedError";
|
|
97
|
+
}
|
|
98
|
+
handler;
|
|
99
|
+
};
|
|
100
|
+
var JobHandlerUnregisteredError = class extends Error {
|
|
101
|
+
constructor(handler) {
|
|
102
|
+
super(`Job handler not registered: ${handler}`);
|
|
103
|
+
this.handler = handler;
|
|
104
|
+
this.name = "JobHandlerUnregisteredError";
|
|
105
|
+
}
|
|
106
|
+
handler;
|
|
107
|
+
/** Read by the runner's retry hints: never retried. */
|
|
108
|
+
retryable = false;
|
|
109
|
+
};
|
|
110
|
+
var JobHandlerTargetError = class extends Error {
|
|
111
|
+
/** Read by the runner's retry hints: never retried. */
|
|
112
|
+
retryable = false;
|
|
113
|
+
constructor(message) {
|
|
114
|
+
super(message);
|
|
115
|
+
this.name = "JobHandlerTargetError";
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
var REGISTRY_KEY = "__smrtJobHandlers";
|
|
119
|
+
function registry() {
|
|
120
|
+
const g = globalThis;
|
|
121
|
+
let state = g[REGISTRY_KEY];
|
|
122
|
+
if (!state) {
|
|
123
|
+
state = {
|
|
124
|
+
handlers: /* @__PURE__ */ new Map(),
|
|
125
|
+
sealedBy: /* @__PURE__ */ new Set()
|
|
126
|
+
};
|
|
127
|
+
g[REGISTRY_KEY] = state;
|
|
128
|
+
}
|
|
129
|
+
return state;
|
|
130
|
+
}
|
|
131
|
+
function isJobHandlerName(name) {
|
|
132
|
+
return typeof name === "string" && name.length <= MAX_HANDLER_NAME_LENGTH && HANDLER_NAME_PATTERN.test(name);
|
|
133
|
+
}
|
|
134
|
+
function assertJobHandlerName(name) {
|
|
135
|
+
if (!isJobHandlerName(name)) throw new JobHandlerNameError(name);
|
|
136
|
+
}
|
|
137
|
+
function assertRegistrationOpen(name) {
|
|
138
|
+
if (registry().sealedBy.size > 0) throw new JobHandlerRegistrationClosedError(name);
|
|
139
|
+
}
|
|
140
|
+
function registerJobHandler(name, handler) {
|
|
141
|
+
assertJobHandlerName(name);
|
|
142
|
+
if (typeof handler !== "function") throw new TypeError(`Job handler ${name} must be a function`);
|
|
143
|
+
assertRegistrationOpen(name);
|
|
144
|
+
const { handlers } = registry();
|
|
145
|
+
if (handlers.has(name)) throw new JobHandlerAlreadyRegisteredError(name);
|
|
146
|
+
if (handlers.size >= 256) throw new JobHandlerLimitError(name);
|
|
147
|
+
handlers.set(name, handler);
|
|
148
|
+
}
|
|
149
|
+
function unregisterJobHandler(name) {
|
|
150
|
+
assertRegistrationOpen(name);
|
|
151
|
+
return registry().handlers.delete(name);
|
|
152
|
+
}
|
|
153
|
+
function listJobHandlers() {
|
|
154
|
+
return [...registry().handlers.keys()].sort();
|
|
155
|
+
}
|
|
156
|
+
function jobHandlerTarget(name) {
|
|
157
|
+
assertJobHandlerName(name);
|
|
158
|
+
return {
|
|
159
|
+
objectType: `${JOB_HANDLER_TARGET_PREFIX}${name}`,
|
|
160
|
+
method: JOB_HANDLER_METHOD
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function isJobHandlerTarget(objectType) {
|
|
164
|
+
return typeof objectType === "string" && objectType.startsWith("handler:");
|
|
165
|
+
}
|
|
166
|
+
function jobHandlerName(objectType) {
|
|
167
|
+
return isJobHandlerTarget(objectType) ? objectType.slice(8) : null;
|
|
168
|
+
}
|
|
169
|
+
function sealJobHandlerRegistry(workerKey) {
|
|
170
|
+
const state = registry();
|
|
171
|
+
state.sealedBy.add(workerKey);
|
|
172
|
+
return new Map(state.handlers);
|
|
173
|
+
}
|
|
174
|
+
function releaseJobHandlerRegistry(workerKey) {
|
|
175
|
+
registry().sealedBy.delete(workerKey);
|
|
176
|
+
}
|
|
177
|
+
//#endregion
|
|
62
178
|
//#region src/smrt-job-dedupe-slot.ts
|
|
63
179
|
var __defProp$3 = Object.defineProperty;
|
|
64
180
|
var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
|
|
@@ -100,6 +216,117 @@ var SmrtJobDedupeSlotCollection = class extends SmrtCollection {
|
|
|
100
216
|
static _itemClass = SmrtJobDedupeSlot;
|
|
101
217
|
};
|
|
102
218
|
//#endregion
|
|
219
|
+
//#region src/worker-liveness.ts
|
|
220
|
+
var LIVE_WORKERS_KEY = "__smrtLiveWorkers";
|
|
221
|
+
function liveWorkers() {
|
|
222
|
+
const g = globalThis;
|
|
223
|
+
let set = g[LIVE_WORKERS_KEY];
|
|
224
|
+
if (!set) {
|
|
225
|
+
set = /* @__PURE__ */ new Set();
|
|
226
|
+
g[LIVE_WORKERS_KEY] = set;
|
|
227
|
+
}
|
|
228
|
+
return set;
|
|
229
|
+
}
|
|
230
|
+
function registerLiveWorker(workerKey) {
|
|
231
|
+
liveWorkers().add(workerKey);
|
|
232
|
+
}
|
|
233
|
+
function unregisterLiveWorker(workerKey) {
|
|
234
|
+
liveWorkers().delete(workerKey);
|
|
235
|
+
}
|
|
236
|
+
function isLiveWorker(workerKey) {
|
|
237
|
+
return liveWorkers().has(workerKey);
|
|
238
|
+
}
|
|
239
|
+
function isWorkerAlive(workerKey, freshLeaseKeys) {
|
|
240
|
+
if (!workerKey) return false;
|
|
241
|
+
return isLiveWorker(workerKey) || freshLeaseKeys.has(workerKey);
|
|
242
|
+
}
|
|
243
|
+
function createWorkerKey(baseId) {
|
|
244
|
+
return `${baseId}~${createId().slice(0, 8)}`;
|
|
245
|
+
}
|
|
246
|
+
function resolveUrl(db) {
|
|
247
|
+
const withConfig = db;
|
|
248
|
+
return db.url || withConfig.config?.url || "";
|
|
249
|
+
}
|
|
250
|
+
async function tuneSqliteForConcurrency(db) {
|
|
251
|
+
try {
|
|
252
|
+
await setBusyTimeoutIfUnset(db, SQLITE_BUSY_TIMEOUT_MS);
|
|
253
|
+
await db.query("PRAGMA journal_mode = WAL");
|
|
254
|
+
} catch {}
|
|
255
|
+
}
|
|
256
|
+
var enabledPgliteClients = /* @__PURE__ */ new WeakSet();
|
|
257
|
+
function enablePgliteJobs(db) {
|
|
258
|
+
const client = db.client;
|
|
259
|
+
if (!client || typeof client.dumpDataDir !== "function") throw new Error("enablePgliteJobs requires an SDK PGlite client");
|
|
260
|
+
enabledPgliteClients.add(client);
|
|
261
|
+
}
|
|
262
|
+
function isPglite(db) {
|
|
263
|
+
return !!db.client && enabledPgliteClients.has(db.client);
|
|
264
|
+
}
|
|
265
|
+
function resolveEngine(db) {
|
|
266
|
+
if (isPglite(db)) return "postgres";
|
|
267
|
+
const withConfig = db;
|
|
268
|
+
const type = withConfig.type || withConfig.config?.type;
|
|
269
|
+
return detectEngine(resolveUrl(db), type);
|
|
270
|
+
}
|
|
271
|
+
function isInMemory(db) {
|
|
272
|
+
const url = resolveUrl(db).toLowerCase();
|
|
273
|
+
return url === ":memory:" || url.includes("mode=memory") || url.includes("file::memory:");
|
|
274
|
+
}
|
|
275
|
+
function planLivenessConnection(db, platform = process.platform) {
|
|
276
|
+
if (isPglite(db)) return {
|
|
277
|
+
kind: "none",
|
|
278
|
+
degraded: false,
|
|
279
|
+
reason: "a PGlite instance cannot be reached by a second connection"
|
|
280
|
+
};
|
|
281
|
+
const engine = resolveEngine(db);
|
|
282
|
+
if (engine === "postgres") return {
|
|
283
|
+
kind: "url",
|
|
284
|
+
url: resolveUrl(db),
|
|
285
|
+
type: engine
|
|
286
|
+
};
|
|
287
|
+
if (engine !== "sqlite") return {
|
|
288
|
+
kind: "none",
|
|
289
|
+
degraded: false,
|
|
290
|
+
reason: `the ${engine} engine has one owner per database`
|
|
291
|
+
};
|
|
292
|
+
if (isInMemory(db)) return {
|
|
293
|
+
kind: "none",
|
|
294
|
+
degraded: false,
|
|
295
|
+
reason: "an in-memory SQLite database cannot be reached by a second connection"
|
|
296
|
+
};
|
|
297
|
+
const dbEngine = db.engine;
|
|
298
|
+
if (dbEngine !== "node-sqlite" && dbEngine !== "libsql") return {
|
|
299
|
+
kind: "none",
|
|
300
|
+
degraded: true,
|
|
301
|
+
reason: "the connection does not report which SQLite engine it uses, so a second connection may use a different engine on the same file"
|
|
302
|
+
};
|
|
303
|
+
if (typeof db.reopenOptions !== "function") return {
|
|
304
|
+
kind: "none",
|
|
305
|
+
degraded: true,
|
|
306
|
+
reason: "the connection cannot give options to reopen the same database"
|
|
307
|
+
};
|
|
308
|
+
let reopen;
|
|
309
|
+
try {
|
|
310
|
+
reopen = db.reopenOptions();
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return {
|
|
313
|
+
kind: "none",
|
|
314
|
+
degraded: true,
|
|
315
|
+
reason: `the connection cannot be reopened on the same engine (${error instanceof Error ? error.message : String(error)})`
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
if (platform === "win32" && dbEngine === "node-sqlite" && reopen.secureFile) return {
|
|
319
|
+
kind: "none",
|
|
320
|
+
degraded: true,
|
|
321
|
+
reason: "on Windows the secure SQLite custody verifier cannot be handed to a worker thread"
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
kind: "reopen",
|
|
325
|
+
engine: dbEngine,
|
|
326
|
+
reopen
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
//#endregion
|
|
103
330
|
//#region src/smrt-job-event.ts
|
|
104
331
|
var __defProp$2 = Object.defineProperty;
|
|
105
332
|
var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
|
|
@@ -217,7 +444,7 @@ function normalizeCursorDate(value) {
|
|
|
217
444
|
}
|
|
218
445
|
function databaseEngine(db) {
|
|
219
446
|
const configured = db;
|
|
220
|
-
const engine =
|
|
447
|
+
const engine = resolveEngine(db);
|
|
221
448
|
const clientName = configured.client?.constructor?.name?.toLowerCase() ?? "";
|
|
222
449
|
if (engine === "sqlite" && (clientName.includes("duckdb") || configured.client?.connection !== void 0)) return "duckdb";
|
|
223
450
|
return engine;
|
|
@@ -362,6 +589,26 @@ var SmrtJobEventCollection = class extends SmrtCollection {
|
|
|
362
589
|
nextCursor: (stoppedAtLimit || candidateBoundReached) && scanned ? scanned.toCursor() : null
|
|
363
590
|
};
|
|
364
591
|
}
|
|
592
|
+
/**
|
|
593
|
+
* Read one job's newest matching authoritative outcome, independently of the
|
|
594
|
+
* tenant-wide feed's 1,000-candidate limit. Retention still applies.
|
|
595
|
+
* @param jobId - Authorized job identity; the caller owns resource authorization.
|
|
596
|
+
* @param options - Explicit tenant and optional current completion identity.
|
|
597
|
+
* @returns A safe outcome or null; never raw errors, arguments or results.
|
|
598
|
+
*/
|
|
599
|
+
async getTerminalOutcome(jobId, options) {
|
|
600
|
+
if (!Object.hasOwn(options, "tenantId") || options.tenantId === void 0) throw new Error("Terminal outcome queries require tenantId or tenantId: null");
|
|
601
|
+
const where = ["job_id = ?", "stage IN ('completed', 'failed', 'cancelled', 'stale-recovery')"];
|
|
602
|
+
const params = [jobId];
|
|
603
|
+
this.addTenantPredicate(where, params, options);
|
|
604
|
+
const events = await this.query(`SELECT ${JOB_EVENT_STORAGE_COLUMNS} FROM _smrt_job_events
|
|
605
|
+
WHERE ${where.join(" AND ")} ORDER BY ${this.createdAtComparableExpression()} DESC, id DESC`, params, { allowRawOnTenantScoped: true });
|
|
606
|
+
for (const event of events) {
|
|
607
|
+
const outcome = terminalOutcome(event);
|
|
608
|
+
if (outcome && (options.attempts === void 0 || options.attempts === outcome.attempts) && (options.completedAt === void 0 || options.completedAt === outcome.completedAt)) return outcome;
|
|
609
|
+
}
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
365
612
|
addTenantPredicate(where, params, options) {
|
|
366
613
|
if (options.tenantId === null) {
|
|
367
614
|
where.push("tenant_id IS NULL");
|
|
@@ -446,7 +693,7 @@ function terminalOutcome(event) {
|
|
|
446
693
|
};
|
|
447
694
|
}
|
|
448
695
|
function isFailureKind(value) {
|
|
449
|
-
return value === "execution" || value === "timeout" || value === "stale-recovery";
|
|
696
|
+
return value === "execution" || value === "timeout" || value === "stale-recovery" || value === "handler-unregistered" || value === "handler-unclaimed";
|
|
450
697
|
}
|
|
451
698
|
function isTerminalStatus(value) {
|
|
452
699
|
return value === "completed" || value === "failed" || value === "cancelled";
|
|
@@ -504,10 +751,23 @@ async function transitionTerminalJob(db, options) {
|
|
|
504
751
|
where.push("worker_id = ?");
|
|
505
752
|
whereValues.push(options.expectedWorkerId);
|
|
506
753
|
}
|
|
754
|
+
if (options.expectedWorkerId !== void 0 && options.job.startedAt !== void 0) {
|
|
755
|
+
where.push("attempts = ?");
|
|
756
|
+
whereValues.push(options.job.attempts);
|
|
757
|
+
if (options.job.startedAt === null) where.push("started_at IS NULL");
|
|
758
|
+
else if (options.job.startedAt !== void 0) {
|
|
759
|
+
where.push("started_at = ?");
|
|
760
|
+
whereValues.push(options.job.startedAt);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
507
763
|
if (options.expectedTaskId !== void 0) {
|
|
508
764
|
where.push("task_id = ?");
|
|
509
765
|
whereValues.push(options.expectedTaskId);
|
|
510
766
|
}
|
|
767
|
+
if (options.expectedRunAtAtOrBefore !== void 0) {
|
|
768
|
+
where.push("run_at <= ?");
|
|
769
|
+
whereValues.push(options.expectedRunAtAtOrBefore);
|
|
770
|
+
}
|
|
511
771
|
const updated = await tx.query(`UPDATE _smrt_jobs
|
|
512
772
|
SET ${assignments.map(([column]) => `${column} = ?`).join(", ")}
|
|
513
773
|
WHERE ${where.join(" AND ")}
|
|
@@ -561,7 +821,7 @@ async function transitionTerminalJob(db, options) {
|
|
|
561
821
|
await event.loadDataFromDb(persisted);
|
|
562
822
|
return event;
|
|
563
823
|
}
|
|
564
|
-
function terminalSnapshot(job) {
|
|
824
|
+
function terminalSnapshot(job, fenceDispatch = false) {
|
|
565
825
|
if (!job.id) return null;
|
|
566
826
|
return {
|
|
567
827
|
id: job.id,
|
|
@@ -569,7 +829,8 @@ function terminalSnapshot(job) {
|
|
|
569
829
|
queue: job.queue,
|
|
570
830
|
objectType: job.objectType,
|
|
571
831
|
method: job.method,
|
|
572
|
-
attempts: job.attempts
|
|
832
|
+
attempts: job.attempts,
|
|
833
|
+
...fenceDispatch && job.startedAt !== void 0 ? { startedAt: job.startedAt?.toISOString() ?? null } : {}
|
|
573
834
|
};
|
|
574
835
|
}
|
|
575
836
|
//#endregion
|
|
@@ -684,11 +945,13 @@ var SmrtJob = class extends SmrtObject {
|
|
|
684
945
|
if (slotKey && typeof slotJobId === "string" && slotJobId !== current.id) {
|
|
685
946
|
if ((await tx.query("SELECT id FROM _smrt_jobs WHERE id = ? AND status IN ('pending', 'running')", slotJobId)).rows.length) throw new Error("Another job already reserves this dedupeKey");
|
|
686
947
|
}
|
|
948
|
+
const retriedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
687
949
|
const retried = await tx.query(`UPDATE _smrt_jobs SET status = 'pending', attempts = 0, last_error = NULL,
|
|
688
950
|
started_at = NULL, completed_at = NULL, worker_id = NULL, worker_heartbeat = NULL,
|
|
951
|
+
run_at = CASE WHEN ${HANDLER_TARGET_SQL} AND run_at < ? THEN ? ELSE run_at END,
|
|
689
952
|
updated_at = ? WHERE id = ? AND ${tenantPredicate}
|
|
690
953
|
AND status IN ('pending', 'failed', 'cancelled')
|
|
691
|
-
RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`,
|
|
954
|
+
RETURNING ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}`, retriedAt, retriedAt, retriedAt, current.id, ...tenantValues);
|
|
692
955
|
if (retried.rows.length !== 1) throw new Error("Job status changed before retry");
|
|
693
956
|
if (slotKey) await tx.query("UPDATE _smrt_job_dedupe_slots SET job_id = ? WHERE slot_key = ?", current.id, slotKey);
|
|
694
957
|
if (schedule) await tx.query(`UPDATE _smrt_agent_schedules SET running_count = ? WHERE id = ? AND ${tenantPredicate}`, occupied + 1, schedule.id, ...tenantValues);
|
|
@@ -868,6 +1131,36 @@ SmrtJob = __decorateClass$1([smrt({
|
|
|
868
1131
|
where: "status = 'pending' AND (task_input_requests IS NULL OR task_input_responses IS NOT NULL)"
|
|
869
1132
|
}]
|
|
870
1133
|
}), TenantScoped({ mode: "optional" })], SmrtJob);
|
|
1134
|
+
var HANDLER_RESERVED_ARG_KEYS = [
|
|
1135
|
+
"_mcpTask",
|
|
1136
|
+
"_agentConfig",
|
|
1137
|
+
"_scheduleId",
|
|
1138
|
+
"_scheduledFor",
|
|
1139
|
+
"_scheduleAdmission"
|
|
1140
|
+
];
|
|
1141
|
+
function assertHandlerJobData(data) {
|
|
1142
|
+
assertJobHandlerName(jobHandlerName(data.objectType));
|
|
1143
|
+
if (data.method !== "handle") throw new TypeError(`A handler job's method must be '${JOB_HANDLER_METHOD}'`);
|
|
1144
|
+
if (data.objectId != null) throw new TypeError("A handler job cannot have an objectId");
|
|
1145
|
+
if (data.taskId != null || data.taskOwnerId != null || data.taskResult != null || data.taskInputRequests != null || data.taskInputResponses != null) throw new TypeError("A handler job cannot be an MCP task");
|
|
1146
|
+
const args = data.args ?? {};
|
|
1147
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) throw new TypeError("A handler job payload must be a JSON object");
|
|
1148
|
+
for (const key of HANDLER_RESERVED_ARG_KEYS) if (Object.hasOwn(args, key)) throw new TypeError(`A handler job payload cannot set reserved ${key}`);
|
|
1149
|
+
}
|
|
1150
|
+
var fencedClaimTimes = /* @__PURE__ */ new WeakMap();
|
|
1151
|
+
var HANDLER_TARGET_SQL = `substr(object_type, 1, ${JOB_HANDLER_TARGET_PREFIX.length}) = '${JOB_HANDLER_TARGET_PREFIX}'`;
|
|
1152
|
+
function handlerClaimFilter(handlerNames) {
|
|
1153
|
+
if (handlerNames.length > 256) throw new RangeError(`claimReady accepts at most 256 handler names`);
|
|
1154
|
+
const notHandler = `NOT (${HANDLER_TARGET_SQL})`;
|
|
1155
|
+
if (handlerNames.length === 0) return {
|
|
1156
|
+
sql: notHandler,
|
|
1157
|
+
params: []
|
|
1158
|
+
};
|
|
1159
|
+
return {
|
|
1160
|
+
sql: `(${notHandler} OR object_type IN (${handlerNames.map(() => "?").join(", ")}))`,
|
|
1161
|
+
params: handlerNames.map((name) => jobHandlerTarget(name).objectType)
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
871
1164
|
var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
872
1165
|
static _itemClass = SmrtJob;
|
|
873
1166
|
async initialize() {
|
|
@@ -927,7 +1220,19 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
927
1220
|
async claimReady(options) {
|
|
928
1221
|
const limit = options.limit ?? 100;
|
|
929
1222
|
if (limit <= 0) return [];
|
|
930
|
-
const
|
|
1223
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
1224
|
+
const nowIso = now.toISOString();
|
|
1225
|
+
let startedAt = nowIso;
|
|
1226
|
+
if (options.claimFencing) {
|
|
1227
|
+
let clock = fencedClaimTimes.get(this.db);
|
|
1228
|
+
if (!clock) {
|
|
1229
|
+
clock = /* @__PURE__ */ new Map();
|
|
1230
|
+
fencedClaimTimes.set(this.db, clock);
|
|
1231
|
+
}
|
|
1232
|
+
const stamp = Math.max(now.getTime(), (clock.get(options.workerId) ?? -Infinity) + 1);
|
|
1233
|
+
startedAt = new Date(stamp).toISOString();
|
|
1234
|
+
clock.set(options.workerId, stamp);
|
|
1235
|
+
}
|
|
931
1236
|
const whereConditions = [
|
|
932
1237
|
"status = 'pending'",
|
|
933
1238
|
"run_at <= ?",
|
|
@@ -939,6 +1244,11 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
939
1244
|
whereConditions.push(`queue IN (${placeholders})`);
|
|
940
1245
|
whereParams.push(...options.queues);
|
|
941
1246
|
}
|
|
1247
|
+
if (options.handlerNames !== void 0) {
|
|
1248
|
+
const filter = handlerClaimFilter(options.handlerNames);
|
|
1249
|
+
whereConditions.push(filter.sql);
|
|
1250
|
+
whereParams.push(...filter.params);
|
|
1251
|
+
}
|
|
942
1252
|
const scope = jobTenantScope(options.tenantIds);
|
|
943
1253
|
whereParams.push(...scope.params);
|
|
944
1254
|
const isPostgres = getDatabaseEngine(this.db) === "postgres";
|
|
@@ -959,7 +1269,7 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
959
1269
|
const setParams = [
|
|
960
1270
|
options.workerId,
|
|
961
1271
|
nowIso,
|
|
962
|
-
|
|
1272
|
+
startedAt,
|
|
963
1273
|
nowIso
|
|
964
1274
|
];
|
|
965
1275
|
return (isPostgres ? await this.query(`WITH claim_candidates AS MATERIALIZED (${candidateSelect})
|
|
@@ -1032,6 +1342,7 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
1032
1342
|
*/
|
|
1033
1343
|
async enqueueJob(data, options = {}) {
|
|
1034
1344
|
const cap = options.tenantJobCap ?? 1e4;
|
|
1345
|
+
if (isJobHandlerTarget(data.objectType)) assertHandlerJobData(data);
|
|
1035
1346
|
const explicitTenant = typeof data.tenantId === "string" && data.tenantId.length > 0 ? data.tenantId : data.tenantId === null ? null : void 0;
|
|
1036
1347
|
const effectiveTenant = explicitTenant !== void 0 ? explicitTenant : getTenantId() ?? null;
|
|
1037
1348
|
if (data.dedupeKey != null) {
|
|
@@ -1089,6 +1400,23 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
1089
1400
|
tenantId: effectiveTenant
|
|
1090
1401
|
}, cap);
|
|
1091
1402
|
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Enqueue a job for a registered named handler (#5005). The handler need
|
|
1405
|
+
* not be registered in this process: producers and runners are usually
|
|
1406
|
+
* different processes. Only runners that registered the handler claim the
|
|
1407
|
+
* job; one still `pending` past the runners' `handlerUnclaimedDeadlineMs`
|
|
1408
|
+
* is failed `handler-unclaimed`. Guards, dedupe and tenancy are those of
|
|
1409
|
+
* {@link enqueueJob}.
|
|
1410
|
+
*/
|
|
1411
|
+
async enqueueHandlerJob(data, options = {}) {
|
|
1412
|
+
const { handler, payload, ...rest } = data;
|
|
1413
|
+
return this.enqueueJob({
|
|
1414
|
+
...rest,
|
|
1415
|
+
...jobHandlerTarget(handler),
|
|
1416
|
+
objectId: null,
|
|
1417
|
+
args: payload ?? {}
|
|
1418
|
+
}, options);
|
|
1419
|
+
}
|
|
1092
1420
|
/** Persist once, without a second save racing a consumer's first claim. */
|
|
1093
1421
|
async createQueuedJob(data, cap) {
|
|
1094
1422
|
const effectiveTenant = data.tenantId;
|
|
@@ -1156,8 +1484,7 @@ var SmrtJobCollection = class SmrtJobCollection extends SmrtCollection {
|
|
|
1156
1484
|
}
|
|
1157
1485
|
};
|
|
1158
1486
|
function getDatabaseEngine(db) {
|
|
1159
|
-
|
|
1160
|
-
return detectEngine(db.url || dbWithConfig.config?.url || "", dbWithConfig.type || dbWithConfig.config?.type);
|
|
1487
|
+
return resolveEngine(db);
|
|
1161
1488
|
}
|
|
1162
1489
|
function compareClaimOrder(left, right) {
|
|
1163
1490
|
const priority = right.priority - left.priority;
|
|
@@ -1384,378 +1711,31 @@ function redactErrorForPersistence(error) {
|
|
|
1384
1711
|
return redactErrorMessage(String(error));
|
|
1385
1712
|
}
|
|
1386
1713
|
//#endregion
|
|
1387
|
-
//#region src/
|
|
1388
|
-
var
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
queue: this.jobContext.queue,
|
|
1402
|
-
objectType: this.jobContext.objectType,
|
|
1403
|
-
method: this.jobContext.method
|
|
1404
|
-
}
|
|
1405
|
-
};
|
|
1406
|
-
}
|
|
1407
|
-
debug(message, data) {
|
|
1408
|
-
this.baseLogger.debug(message, this.addContext(data));
|
|
1409
|
-
}
|
|
1410
|
-
info(message, data) {
|
|
1411
|
-
this.baseLogger.info(message, this.addContext(data));
|
|
1412
|
-
}
|
|
1413
|
-
warn(message, data) {
|
|
1414
|
-
this.baseLogger.warn(message, this.addContext(data));
|
|
1415
|
-
}
|
|
1416
|
-
error(message, data) {
|
|
1417
|
-
this.baseLogger.error(message, this.addContext(data));
|
|
1418
|
-
}
|
|
1419
|
-
};
|
|
1420
|
-
//#endregion
|
|
1421
|
-
//#region src/mcp-task.ts
|
|
1422
|
-
var MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
|
|
1423
|
-
var McpTaskSuspendedError = class extends Error {};
|
|
1424
|
-
function createMcpTaskResult(result) {
|
|
1425
|
-
const publicResult = toPublicTaskData(result) ?? null;
|
|
1426
|
-
return {
|
|
1427
|
-
content: [{
|
|
1428
|
-
type: "text",
|
|
1429
|
-
text: JSON.stringify(publicResult)
|
|
1430
|
-
}],
|
|
1431
|
-
structuredContent: { data: publicResult }
|
|
1432
|
-
};
|
|
1433
|
-
}
|
|
1434
|
-
var McpTaskNotFoundError = class extends Error {
|
|
1435
|
-
constructor(taskId) {
|
|
1436
|
-
super(`MCP task not found: ${taskId}`);
|
|
1437
|
-
this.name = "McpTaskNotFoundError";
|
|
1438
|
-
}
|
|
1714
|
+
//#region src/smrt-worker.ts
|
|
1715
|
+
var __defProp = Object.defineProperty;
|
|
1716
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
1717
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
1718
|
+
enumerable: true,
|
|
1719
|
+
configurable: true,
|
|
1720
|
+
writable: true,
|
|
1721
|
+
value
|
|
1722
|
+
}) : obj[key] = value;
|
|
1723
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
1724
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
1725
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
1726
|
+
if (kind && result) __defProp(target, key, result);
|
|
1727
|
+
return result;
|
|
1439
1728
|
};
|
|
1440
|
-
var
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
this.requireAuthorization = options.requireAuthorization ?? false;
|
|
1451
|
-
this.tenantId = options.tenantId ?? null;
|
|
1452
|
-
this.pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
1453
|
-
this.ttlMs = options.ttlMs ?? 864e5;
|
|
1454
|
-
}
|
|
1455
|
-
collection;
|
|
1456
|
-
ownerId;
|
|
1457
|
-
requireAuthorization;
|
|
1458
|
-
tenantId;
|
|
1459
|
-
pollIntervalMs;
|
|
1460
|
-
ttlMs;
|
|
1461
|
-
static async create(db, options = {}) {
|
|
1462
|
-
const collection = await SmrtJobCollection.create({ db });
|
|
1463
|
-
return new McpTaskStore(collection, options);
|
|
1464
|
-
}
|
|
1465
|
-
/** Create one pending job and return its immediately-pollable task projection. */
|
|
1466
|
-
async createTask(input) {
|
|
1467
|
-
if ((input.tenantId ?? null) !== this.tenantId) throw new Error("MCP task tenant does not match active tenant");
|
|
1468
|
-
if (this.requireAuthorization && !this.ownerId) throw new Error("Authorized tasks require an owner");
|
|
1469
|
-
const continuation = input.continuation ? Object.freeze(validateContinuation(input.continuation)) : void 0;
|
|
1470
|
-
if (continuation) {
|
|
1471
|
-
if (!this.ownerId) throw new Error("Durable continuation requires an owner");
|
|
1472
|
-
}
|
|
1473
|
-
const taskId = createId();
|
|
1474
|
-
const pollIntervalMs = input.pollIntervalMs ?? this.pollIntervalMs;
|
|
1475
|
-
const ttlMs = input.ttlMs ?? this.ttlMs;
|
|
1476
|
-
const args = {
|
|
1477
|
-
_mcpTask: {
|
|
1478
|
-
invocationArgs: input.invocationArgs,
|
|
1479
|
-
...this.requireAuthorization ? { authorizationRequired: true } : {},
|
|
1480
|
-
...continuation ? { continuation } : {},
|
|
1481
|
-
pollIntervalMs,
|
|
1482
|
-
ttlMs
|
|
1483
|
-
},
|
|
1484
|
-
...input.agentConfig ? { _agentConfig: input.agentConfig } : {}
|
|
1485
|
-
};
|
|
1486
|
-
return taskFromJob(await this.collection.enqueueJob({
|
|
1487
|
-
tenantId: input.tenantId ?? null,
|
|
1488
|
-
queue: "mcp-tasks",
|
|
1489
|
-
objectType: input.objectType,
|
|
1490
|
-
objectId: input.objectId,
|
|
1491
|
-
method: input.method,
|
|
1492
|
-
args,
|
|
1493
|
-
timeout: input.timeout,
|
|
1494
|
-
...continuation || this.requireAuthorization ? { maxAttempts: 1 } : {},
|
|
1495
|
-
taskId,
|
|
1496
|
-
taskOwnerId: this.ownerId,
|
|
1497
|
-
taskInputRequests: null,
|
|
1498
|
-
taskInputResponses: null
|
|
1499
|
-
}), {
|
|
1500
|
-
pollIntervalMs,
|
|
1501
|
-
ttlMs
|
|
1502
|
-
});
|
|
1503
|
-
}
|
|
1504
|
-
/**
|
|
1505
|
-
* Read a waiting task's application input descriptor for an explicitly declared
|
|
1506
|
-
* workflow tool or authenticated form. This is not an MCP protocol extension.
|
|
1507
|
-
*/
|
|
1508
|
-
async getContinuation(taskId) {
|
|
1509
|
-
const job = await this.findTaskJob(taskId);
|
|
1510
|
-
const binding = getMcpTaskMarker(job)?.continuation;
|
|
1511
|
-
if (!binding || job.status !== "pending" || job.taskInputResponses !== null) return null;
|
|
1512
|
-
const inputRequests = asRecord(job.taskInputRequests);
|
|
1513
|
-
if (!Object.keys(inputRequests).length) return null;
|
|
1514
|
-
return {
|
|
1515
|
-
binding,
|
|
1516
|
-
inputRequests
|
|
1517
|
-
};
|
|
1518
|
-
}
|
|
1519
|
-
/** Get a task only when it belongs to this store's principal. */
|
|
1520
|
-
async getTask(taskId) {
|
|
1521
|
-
const job = await this.findTaskJob(taskId);
|
|
1522
|
-
return taskFromJob(job, getMcpTaskMarker(job) ?? {
|
|
1523
|
-
pollIntervalMs: this.pollIntervalMs,
|
|
1524
|
-
ttlMs: this.ttlMs
|
|
1525
|
-
});
|
|
1526
|
-
}
|
|
1527
|
-
/**
|
|
1528
|
-
* Persist only values requested by an outstanding `requestInput()` call.
|
|
1529
|
-
* Unknown and already-consumed keys are intentionally ignored per SEP-2663.
|
|
1530
|
-
*/
|
|
1531
|
-
async updateTask(taskId, inputResponses) {
|
|
1532
|
-
const job = await this.findTaskJob(taskId);
|
|
1533
|
-
const requested = asRecord(job.taskInputRequests);
|
|
1534
|
-
if (getMcpTaskMarker(job)?.continuation) {
|
|
1535
|
-
if (!Object.keys(requested).length || !Object.keys(requested).every((key) => Object.hasOwn(inputResponses, key))) return;
|
|
1536
|
-
const selected = Object.fromEntries(Object.keys(requested).map((key) => [key, inputResponses[key]]));
|
|
1537
|
-
await this.collection.query(`UPDATE _smrt_jobs SET task_input_responses = ?, updated_at = ?
|
|
1538
|
-
WHERE id = ? AND task_id = ? AND status = 'pending'
|
|
1539
|
-
AND task_input_responses IS NULL`, [
|
|
1540
|
-
encodeContinuationJson(selected),
|
|
1541
|
-
(/* @__PURE__ */ new Date()).toISOString(),
|
|
1542
|
-
job.id,
|
|
1543
|
-
taskId
|
|
1544
|
-
], { allowRawOnTenantScoped: true });
|
|
1545
|
-
return;
|
|
1546
|
-
}
|
|
1547
|
-
if (Object.keys(requested).length === 0) return;
|
|
1548
|
-
const accepted = { ...asRecord(job.taskInputResponses) };
|
|
1549
|
-
for (const key of Object.keys(requested)) if (Object.hasOwn(inputResponses, key)) accepted[key] = inputResponses[key];
|
|
1550
|
-
await this.collection.query(`UPDATE _smrt_jobs
|
|
1551
|
-
SET task_input_responses = ?, updated_at = ?
|
|
1552
|
-
WHERE id = ? AND task_id = ?`, [
|
|
1553
|
-
JSON.stringify(accepted),
|
|
1554
|
-
(/* @__PURE__ */ new Date()).toISOString(),
|
|
1555
|
-
job.id,
|
|
1556
|
-
taskId
|
|
1557
|
-
], { allowRawOnTenantScoped: true });
|
|
1558
|
-
}
|
|
1559
|
-
/**
|
|
1560
|
-
* Cooperatively cancel the backing job. A completion race cannot resurrect
|
|
1561
|
-
* it because TaskRunner terminal writes require `status = 'running'`.
|
|
1562
|
-
*/
|
|
1563
|
-
async cancelTask(taskId) {
|
|
1564
|
-
const job = await this.findTaskJob(taskId);
|
|
1565
|
-
if (job.status === "completed" || job.status === "failed" || job.status === "cancelled") return;
|
|
1566
|
-
const snapshot = terminalSnapshot(job);
|
|
1567
|
-
if (!snapshot) throw new McpTaskNotFoundError(taskId);
|
|
1568
|
-
await transitionTerminalJob(this.collection.db, {
|
|
1569
|
-
job: snapshot,
|
|
1570
|
-
status: "cancelled",
|
|
1571
|
-
completedAt: /* @__PURE__ */ new Date(),
|
|
1572
|
-
expectedStatuses: ["pending", "running"],
|
|
1573
|
-
expectedTaskId: taskId
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
async findTaskJob(taskId) {
|
|
1577
|
-
const ownerPredicate = this.ownerId === null ? "task_owner_id IS NULL" : "task_owner_id = ?";
|
|
1578
|
-
const params = this.ownerId === null ? [taskId] : [taskId, this.ownerId];
|
|
1579
|
-
const tenantPredicate = this.tenantId === null ? "tenant_id IS NULL" : "tenant_id = ?";
|
|
1580
|
-
if (this.tenantId !== null) params.push(this.tenantId);
|
|
1581
|
-
const job = (await this.collection.query(`SELECT * FROM _smrt_jobs WHERE task_id = ? AND ${ownerPredicate} AND ${tenantPredicate} LIMIT 1`, params, { allowRawOnTenantScoped: true }))[0];
|
|
1582
|
-
if (!job) throw new McpTaskNotFoundError(taskId);
|
|
1583
|
-
return job;
|
|
1584
|
-
}
|
|
1585
|
-
};
|
|
1586
|
-
function getMcpTaskMarker(job) {
|
|
1587
|
-
const marker = asRecord(asRecord(job.args)._mcpTask);
|
|
1588
|
-
if (!Array.isArray(marker.invocationArgs)) return null;
|
|
1589
|
-
return {
|
|
1590
|
-
invocationArgs: marker.invocationArgs,
|
|
1591
|
-
...marker.authorizationRequired === true ? { authorizationRequired: true } : {},
|
|
1592
|
-
...marker.continuation ? { continuation: validateContinuation(marker.continuation) } : {},
|
|
1593
|
-
pollIntervalMs: asPositiveInt(marker.pollIntervalMs, 250),
|
|
1594
|
-
ttlMs: asPositiveInt(marker.ttlMs, 864e5)
|
|
1595
|
-
};
|
|
1596
|
-
}
|
|
1597
|
-
async function requestMcpTaskContinuation(db, job, binding, inputRequest) {
|
|
1598
|
-
validateContinuation(binding);
|
|
1599
|
-
const expected = getMcpTaskMarker(job)?.continuation;
|
|
1600
|
-
if (!expected || expected.recordId !== binding.recordId || expected.revision !== binding.revision || expected.inputKey !== binding.inputKey) throw new Error("MCP continuation binding mismatch");
|
|
1601
|
-
const found = await db.query(`SELECT task_input_responses FROM _smrt_jobs
|
|
1602
|
-
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, job.id, job.taskId, job.workerId);
|
|
1603
|
-
if (found.rows.length !== 1) throw new McpTaskCancelledError(job.taskId ?? "");
|
|
1604
|
-
const answers = asRecord(parseJson(found.rows[0].task_input_responses));
|
|
1605
|
-
if (Object.hasOwn(answers, binding.inputKey)) return answers[binding.inputKey];
|
|
1606
|
-
if ((await db.query(`UPDATE _smrt_jobs SET status = 'pending', worker_id = NULL,
|
|
1607
|
-
worker_heartbeat = NULL, task_input_requests = ?, updated_at = ?
|
|
1608
|
-
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'
|
|
1609
|
-
RETURNING id`, encodeContinuationJson({ [binding.inputKey]: inputRequest }), (/* @__PURE__ */ new Date()).toISOString(), job.id, job.taskId, job.workerId)).rows.length !== 1) throw new McpTaskCancelledError(job.taskId ?? "");
|
|
1610
|
-
throw new McpTaskSuspendedError("MCP task awaits durable input");
|
|
1611
|
-
}
|
|
1612
|
-
function encodeContinuationJson(value) {
|
|
1613
|
-
try {
|
|
1614
|
-
const json = JSON.stringify(value, (_key, item) => {
|
|
1615
|
-
if (item === void 0 || typeof item === "function" || typeof item === "symbol" || typeof item === "bigint" || typeof item === "number" && !Number.isFinite(item)) throw new Error("Invalid JSON");
|
|
1616
|
-
return item;
|
|
1617
|
-
});
|
|
1618
|
-
if (!json || new TextEncoder().encode(json).byteLength > 65536) throw new Error("Oversized JSON");
|
|
1619
|
-
return json;
|
|
1620
|
-
} catch {
|
|
1621
|
-
throw new Error("MCP continuation input must be JSON within 65536 bytes");
|
|
1622
|
-
}
|
|
1623
|
-
}
|
|
1624
|
-
function validateContinuation(value) {
|
|
1625
|
-
const source = asRecord(value);
|
|
1626
|
-
const record = {
|
|
1627
|
-
recordId: source.recordId,
|
|
1628
|
-
revision: source.revision,
|
|
1629
|
-
inputKey: source.inputKey
|
|
1630
|
-
};
|
|
1631
|
-
for (const key of [
|
|
1632
|
-
"recordId",
|
|
1633
|
-
"revision",
|
|
1634
|
-
"inputKey"
|
|
1635
|
-
]) if (typeof record[key] !== "string" || !record[key] || record[key].length > 256) throw new Error("Invalid MCP continuation binding");
|
|
1636
|
-
return {
|
|
1637
|
-
recordId: record.recordId,
|
|
1638
|
-
revision: record.revision,
|
|
1639
|
-
inputKey: record.inputKey
|
|
1640
|
-
};
|
|
1641
|
-
}
|
|
1642
|
-
async function requestMcpTaskInput(db, job, inputRequests) {
|
|
1643
|
-
const jobId = job.id;
|
|
1644
|
-
const taskId = job.taskId;
|
|
1645
|
-
if (!jobId || !taskId || !job.workerId) throw new Error("Task input is only available while an MCP task job is running");
|
|
1646
|
-
if (Object.keys(inputRequests).length === 0) return {};
|
|
1647
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1648
|
-
await db.query(`UPDATE _smrt_jobs
|
|
1649
|
-
SET task_input_requests = ?, task_input_responses = NULL, updated_at = ?
|
|
1650
|
-
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, JSON.stringify(inputRequests), now, jobId, taskId, job.workerId);
|
|
1651
|
-
while (true) {
|
|
1652
|
-
const row = (await db.query(`SELECT status, task_input_responses FROM _smrt_jobs WHERE id = ? AND task_id = ?`, jobId, taskId)).rows[0];
|
|
1653
|
-
if (!row || row.status === "cancelled") throw new McpTaskCancelledError(taskId);
|
|
1654
|
-
if (row.status !== "running") throw new Error(`MCP task is no longer running: ${taskId}`);
|
|
1655
|
-
const responses = asRecord(parseJson(row.task_input_responses));
|
|
1656
|
-
if (Object.keys(inputRequests).every((key) => Object.hasOwn(responses, key))) {
|
|
1657
|
-
const selected = Object.fromEntries(Object.keys(inputRequests).map((key) => [key, responses[key]]));
|
|
1658
|
-
await db.query(`UPDATE _smrt_jobs
|
|
1659
|
-
SET task_input_requests = NULL, updated_at = ?
|
|
1660
|
-
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, (/* @__PURE__ */ new Date()).toISOString(), jobId, taskId, job.workerId);
|
|
1661
|
-
return selected;
|
|
1662
|
-
}
|
|
1663
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1664
|
-
}
|
|
1665
|
-
}
|
|
1666
|
-
function taskFromJob(job, marker) {
|
|
1667
|
-
const status = taskStatusFromJob(job);
|
|
1668
|
-
const createdAt = toIso(job.created_at) ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1669
|
-
const lastUpdatedAt = toIso(job.updated_at) ?? createdAt;
|
|
1670
|
-
const task = {
|
|
1671
|
-
taskId: job.taskId ?? "",
|
|
1672
|
-
status,
|
|
1673
|
-
createdAt,
|
|
1674
|
-
lastUpdatedAt,
|
|
1675
|
-
ttlMs: marker.ttlMs,
|
|
1676
|
-
pollIntervalMs: marker.pollIntervalMs
|
|
1677
|
-
};
|
|
1678
|
-
if (status === "input_required") task.statusMessage = "Waiting for required input";
|
|
1679
|
-
if (status === "cancelled") task.statusMessage = "Task cancelled";
|
|
1680
|
-
if (status === "failed") {
|
|
1681
|
-
task.statusMessage = job.lastError ?? "Task failed";
|
|
1682
|
-
task.error = {
|
|
1683
|
-
code: -32603,
|
|
1684
|
-
message: task.statusMessage
|
|
1685
|
-
};
|
|
1686
|
-
}
|
|
1687
|
-
if (status === "completed" && job.taskResult) task.result = job.taskResult;
|
|
1688
|
-
return task;
|
|
1689
|
-
}
|
|
1690
|
-
function taskStatusFromJob(job) {
|
|
1691
|
-
if (job.status === "completed") return "completed";
|
|
1692
|
-
if (job.status === "cancelled") return "cancelled";
|
|
1693
|
-
if (job.status === "failed") return "failed";
|
|
1694
|
-
if (Object.keys(asRecord(job.taskInputRequests)).length > 0 && !(getMcpTaskMarker(job)?.continuation && job.taskInputResponses !== null)) return "input_required";
|
|
1695
|
-
return "working";
|
|
1696
|
-
}
|
|
1697
|
-
function asRecord(value) {
|
|
1698
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
|
|
1699
|
-
return value;
|
|
1700
|
-
}
|
|
1701
|
-
function parseJson(value) {
|
|
1702
|
-
if (typeof value !== "string") return value;
|
|
1703
|
-
try {
|
|
1704
|
-
return JSON.parse(value);
|
|
1705
|
-
} catch {
|
|
1706
|
-
return {};
|
|
1707
|
-
}
|
|
1708
|
-
}
|
|
1709
|
-
function asPositiveInt(value, fallback) {
|
|
1710
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
1711
|
-
}
|
|
1712
|
-
function toIso(value) {
|
|
1713
|
-
if (value instanceof Date) return value.toISOString();
|
|
1714
|
-
if (typeof value === "string") return value;
|
|
1715
|
-
}
|
|
1716
|
-
function toPublicTaskData(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
1717
|
-
if (value === null || typeof value !== "object") return value;
|
|
1718
|
-
const publicSource = value;
|
|
1719
|
-
if (typeof publicSource.toPublicJSON === "function") return publicSource.toPublicJSON({});
|
|
1720
|
-
if (Array.isArray(value)) {
|
|
1721
|
-
if (seen.has(value)) return "[Circular]";
|
|
1722
|
-
seen.add(value);
|
|
1723
|
-
return value.map((entry) => toPublicTaskData(entry, seen));
|
|
1724
|
-
}
|
|
1725
|
-
const prototype = Object.getPrototypeOf(value);
|
|
1726
|
-
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
1727
|
-
if (seen.has(value)) return "[Circular]";
|
|
1728
|
-
seen.add(value);
|
|
1729
|
-
const out = {};
|
|
1730
|
-
for (const [key, nested] of Object.entries(value)) out[key] = toPublicTaskData(nested, seen);
|
|
1731
|
-
return out;
|
|
1732
|
-
}
|
|
1733
|
-
//#endregion
|
|
1734
|
-
//#region src/smrt-worker.ts
|
|
1735
|
-
var __defProp = Object.defineProperty;
|
|
1736
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
1737
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
|
|
1738
|
-
enumerable: true,
|
|
1739
|
-
configurable: true,
|
|
1740
|
-
writable: true,
|
|
1741
|
-
value
|
|
1742
|
-
}) : obj[key] = value;
|
|
1743
|
-
var __decorateClass = (decorators, target, key, kind) => {
|
|
1744
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
1745
|
-
for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
1746
|
-
if (kind && result) __defProp(target, key, result);
|
|
1747
|
-
return result;
|
|
1748
|
-
};
|
|
1749
|
-
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1750
|
-
var SmrtWorker = class extends SmrtObject {
|
|
1751
|
-
workerId = "";
|
|
1752
|
-
pid = null;
|
|
1753
|
-
hostname = null;
|
|
1754
|
-
startedAt = null;
|
|
1755
|
-
heartbeatAt = null;
|
|
1756
|
-
leaseExpiresAt = null;
|
|
1757
|
-
queues = null;
|
|
1758
|
-
status = "running";
|
|
1729
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
1730
|
+
var SmrtWorker = class extends SmrtObject {
|
|
1731
|
+
workerId = "";
|
|
1732
|
+
pid = null;
|
|
1733
|
+
hostname = null;
|
|
1734
|
+
startedAt = null;
|
|
1735
|
+
heartbeatAt = null;
|
|
1736
|
+
leaseExpiresAt = null;
|
|
1737
|
+
queues = null;
|
|
1738
|
+
status = "running";
|
|
1759
1739
|
};
|
|
1760
1740
|
__publicField(SmrtWorker, "__smrtPackage__", "@happyvertical/smrt-jobs");
|
|
1761
1741
|
__decorateClass([field({
|
|
@@ -1905,113 +1885,365 @@ var SmrtWorkerCollection = class extends SmrtCollection {
|
|
|
1905
1885
|
}
|
|
1906
1886
|
};
|
|
1907
1887
|
//#endregion
|
|
1908
|
-
//#region src/
|
|
1909
|
-
var
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1888
|
+
//#region src/logger-extension.ts
|
|
1889
|
+
var JobContextLogger = class {
|
|
1890
|
+
constructor(baseLogger, jobContext) {
|
|
1891
|
+
this.baseLogger = baseLogger;
|
|
1892
|
+
this.jobContext = jobContext;
|
|
1893
|
+
}
|
|
1894
|
+
baseLogger;
|
|
1895
|
+
jobContext;
|
|
1896
|
+
addContext(data) {
|
|
1897
|
+
return {
|
|
1898
|
+
...data,
|
|
1899
|
+
_job: {
|
|
1900
|
+
id: this.jobContext.jobId,
|
|
1901
|
+
attempt: this.jobContext.attempt,
|
|
1902
|
+
queue: this.jobContext.queue,
|
|
1903
|
+
objectType: this.jobContext.objectType,
|
|
1904
|
+
method: this.jobContext.method
|
|
1905
|
+
}
|
|
1906
|
+
};
|
|
1907
|
+
}
|
|
1908
|
+
debug(message, data) {
|
|
1909
|
+
this.baseLogger.debug(message, this.addContext(data));
|
|
1910
|
+
}
|
|
1911
|
+
info(message, data) {
|
|
1912
|
+
this.baseLogger.info(message, this.addContext(data));
|
|
1913
|
+
}
|
|
1914
|
+
warn(message, data) {
|
|
1915
|
+
this.baseLogger.warn(message, this.addContext(data));
|
|
1916
|
+
}
|
|
1917
|
+
error(message, data) {
|
|
1918
|
+
this.baseLogger.error(message, this.addContext(data));
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
//#endregion
|
|
1922
|
+
//#region src/mcp-task.ts
|
|
1923
|
+
var MCP_TASKS_EXTENSION = "io.modelcontextprotocol/tasks";
|
|
1924
|
+
var McpTaskSuspendedError = class extends Error {};
|
|
1925
|
+
function createMcpTaskResult(result) {
|
|
1926
|
+
const publicResult = toPublicTaskData(result) ?? null;
|
|
1927
|
+
return {
|
|
1928
|
+
content: [{
|
|
1929
|
+
type: "text",
|
|
1930
|
+
text: JSON.stringify(publicResult)
|
|
1931
|
+
}],
|
|
1932
|
+
structuredContent: { data: publicResult }
|
|
1933
|
+
};
|
|
1934
|
+
}
|
|
1935
|
+
var McpTaskNotFoundError = class extends Error {
|
|
1936
|
+
constructor(taskId) {
|
|
1937
|
+
super(`MCP task not found: ${taskId}`);
|
|
1938
|
+
this.name = "McpTaskNotFoundError";
|
|
1939
|
+
}
|
|
1940
|
+
};
|
|
1941
|
+
var McpTaskCancelledError = class extends Error {
|
|
1942
|
+
constructor(taskId) {
|
|
1943
|
+
super(`MCP task was cancelled: ${taskId}`);
|
|
1944
|
+
this.name = "McpTaskCancelledError";
|
|
1945
|
+
}
|
|
1946
|
+
};
|
|
1947
|
+
var McpTaskStore = class McpTaskStore {
|
|
1948
|
+
constructor(collection, options) {
|
|
1949
|
+
this.collection = collection;
|
|
1950
|
+
this.ownerId = options.ownerId ?? null;
|
|
1951
|
+
this.requireAuthorization = options.requireAuthorization ?? false;
|
|
1952
|
+
this.tenantId = options.tenantId ?? null;
|
|
1953
|
+
this.pollIntervalMs = options.pollIntervalMs ?? 250;
|
|
1954
|
+
this.ttlMs = options.ttlMs ?? 864e5;
|
|
1955
|
+
}
|
|
1956
|
+
collection;
|
|
1957
|
+
ownerId;
|
|
1958
|
+
requireAuthorization;
|
|
1959
|
+
tenantId;
|
|
1960
|
+
pollIntervalMs;
|
|
1961
|
+
ttlMs;
|
|
1962
|
+
static async create(db, options = {}) {
|
|
1963
|
+
const collection = await SmrtJobCollection.create({ db });
|
|
1964
|
+
return new McpTaskStore(collection, options);
|
|
1965
|
+
}
|
|
1966
|
+
/** Create one pending job and return its immediately-pollable task projection. */
|
|
1967
|
+
async createTask(input) {
|
|
1968
|
+
if ((input.tenantId ?? null) !== this.tenantId) throw new Error("MCP task tenant does not match active tenant");
|
|
1969
|
+
if (this.requireAuthorization && !this.ownerId) throw new Error("Authorized tasks require an owner");
|
|
1970
|
+
const continuation = input.continuation ? Object.freeze(validateContinuation(input.continuation)) : void 0;
|
|
1971
|
+
if (continuation) {
|
|
1972
|
+
if (!this.ownerId) throw new Error("Durable continuation requires an owner");
|
|
1973
|
+
}
|
|
1974
|
+
const taskId = createId();
|
|
1975
|
+
const pollIntervalMs = input.pollIntervalMs ?? this.pollIntervalMs;
|
|
1976
|
+
const ttlMs = input.ttlMs ?? this.ttlMs;
|
|
1977
|
+
const args = {
|
|
1978
|
+
_mcpTask: {
|
|
1979
|
+
invocationArgs: input.invocationArgs,
|
|
1980
|
+
...this.requireAuthorization ? { authorizationRequired: true } : {},
|
|
1981
|
+
...continuation ? { continuation } : {},
|
|
1982
|
+
pollIntervalMs,
|
|
1983
|
+
ttlMs
|
|
1984
|
+
},
|
|
1985
|
+
...input.agentConfig ? { _agentConfig: input.agentConfig } : {}
|
|
1986
|
+
};
|
|
1987
|
+
return taskFromJob(await this.collection.enqueueJob({
|
|
1988
|
+
tenantId: input.tenantId ?? null,
|
|
1989
|
+
queue: "mcp-tasks",
|
|
1990
|
+
objectType: input.objectType,
|
|
1991
|
+
objectId: input.objectId,
|
|
1992
|
+
method: input.method,
|
|
1993
|
+
args,
|
|
1994
|
+
timeout: input.timeout,
|
|
1995
|
+
...continuation || this.requireAuthorization ? { maxAttempts: 1 } : {},
|
|
1996
|
+
taskId,
|
|
1997
|
+
taskOwnerId: this.ownerId,
|
|
1998
|
+
taskInputRequests: null,
|
|
1999
|
+
taskInputResponses: null
|
|
2000
|
+
}), {
|
|
2001
|
+
pollIntervalMs,
|
|
2002
|
+
ttlMs
|
|
2003
|
+
});
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Read a waiting task's application input descriptor for an explicitly declared
|
|
2007
|
+
* workflow tool or authenticated form. This is not an MCP protocol extension.
|
|
2008
|
+
*/
|
|
2009
|
+
async getContinuation(taskId) {
|
|
2010
|
+
const job = await this.findTaskJob(taskId);
|
|
2011
|
+
const binding = getMcpTaskMarker(job)?.continuation;
|
|
2012
|
+
if (!binding || job.status !== "pending" || job.taskInputResponses !== null) return null;
|
|
2013
|
+
const inputRequests = asRecord(job.taskInputRequests);
|
|
2014
|
+
if (!Object.keys(inputRequests).length) return null;
|
|
2015
|
+
return {
|
|
2016
|
+
binding,
|
|
2017
|
+
inputRequests
|
|
2018
|
+
};
|
|
2019
|
+
}
|
|
2020
|
+
/** Get a task only when it belongs to this store's principal. */
|
|
2021
|
+
async getTask(taskId) {
|
|
2022
|
+
const job = await this.findTaskJob(taskId);
|
|
2023
|
+
return taskFromJob(job, getMcpTaskMarker(job) ?? {
|
|
2024
|
+
pollIntervalMs: this.pollIntervalMs,
|
|
2025
|
+
ttlMs: this.ttlMs
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Persist only values requested by an outstanding `requestInput()` call.
|
|
2030
|
+
* Unknown and already-consumed keys are intentionally ignored per SEP-2663.
|
|
2031
|
+
*/
|
|
2032
|
+
async updateTask(taskId, inputResponses) {
|
|
2033
|
+
const job = await this.findTaskJob(taskId);
|
|
2034
|
+
const requested = asRecord(job.taskInputRequests);
|
|
2035
|
+
if (getMcpTaskMarker(job)?.continuation) {
|
|
2036
|
+
if (!Object.keys(requested).length || !Object.keys(requested).every((key) => Object.hasOwn(inputResponses, key))) return;
|
|
2037
|
+
const selected = Object.fromEntries(Object.keys(requested).map((key) => [key, inputResponses[key]]));
|
|
2038
|
+
await this.collection.query(`UPDATE _smrt_jobs SET task_input_responses = ?, updated_at = ?
|
|
2039
|
+
WHERE id = ? AND task_id = ? AND status = 'pending'
|
|
2040
|
+
AND task_input_responses IS NULL`, [
|
|
2041
|
+
encodeContinuationJson(selected),
|
|
2042
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
2043
|
+
job.id,
|
|
2044
|
+
taskId
|
|
2045
|
+
], { allowRawOnTenantScoped: true });
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
if (Object.keys(requested).length === 0) return;
|
|
2049
|
+
const accepted = { ...asRecord(job.taskInputResponses) };
|
|
2050
|
+
for (const key of Object.keys(requested)) if (Object.hasOwn(inputResponses, key)) accepted[key] = inputResponses[key];
|
|
2051
|
+
await this.collection.query(`UPDATE _smrt_jobs
|
|
2052
|
+
SET task_input_responses = ?, updated_at = ?
|
|
2053
|
+
WHERE id = ? AND task_id = ?`, [
|
|
2054
|
+
JSON.stringify(accepted),
|
|
2055
|
+
(/* @__PURE__ */ new Date()).toISOString(),
|
|
2056
|
+
job.id,
|
|
2057
|
+
taskId
|
|
2058
|
+
], { allowRawOnTenantScoped: true });
|
|
2059
|
+
}
|
|
2060
|
+
/**
|
|
2061
|
+
* Cooperatively cancel the backing job. A completion race cannot resurrect
|
|
2062
|
+
* it because TaskRunner terminal writes require `status = 'running'`.
|
|
2063
|
+
*/
|
|
2064
|
+
async cancelTask(taskId) {
|
|
2065
|
+
const job = await this.findTaskJob(taskId);
|
|
2066
|
+
if (job.status === "completed" || job.status === "failed" || job.status === "cancelled") return;
|
|
2067
|
+
const snapshot = terminalSnapshot(job);
|
|
2068
|
+
if (!snapshot) throw new McpTaskNotFoundError(taskId);
|
|
2069
|
+
await transitionTerminalJob(this.collection.db, {
|
|
2070
|
+
job: snapshot,
|
|
2071
|
+
status: "cancelled",
|
|
2072
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
2073
|
+
expectedStatuses: ["pending", "running"],
|
|
2074
|
+
expectedTaskId: taskId
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
async findTaskJob(taskId) {
|
|
2078
|
+
const ownerPredicate = this.ownerId === null ? "task_owner_id IS NULL" : "task_owner_id = ?";
|
|
2079
|
+
const params = this.ownerId === null ? [taskId] : [taskId, this.ownerId];
|
|
2080
|
+
const tenantPredicate = this.tenantId === null ? "tenant_id IS NULL" : "tenant_id = ?";
|
|
2081
|
+
if (this.tenantId !== null) params.push(this.tenantId);
|
|
2082
|
+
const job = (await this.collection.query(`SELECT * FROM _smrt_jobs WHERE task_id = ? AND ${ownerPredicate} AND ${tenantPredicate} LIMIT 1`, params, { allowRawOnTenantScoped: true }))[0];
|
|
2083
|
+
if (!job) throw new McpTaskNotFoundError(taskId);
|
|
2084
|
+
return job;
|
|
2085
|
+
}
|
|
2086
|
+
};
|
|
2087
|
+
function getMcpTaskMarker(job) {
|
|
2088
|
+
const marker = asRecord(asRecord(job.args)._mcpTask);
|
|
2089
|
+
if (!Array.isArray(marker.invocationArgs)) return null;
|
|
2090
|
+
return {
|
|
2091
|
+
invocationArgs: marker.invocationArgs,
|
|
2092
|
+
...marker.authorizationRequired === true ? { authorizationRequired: true } : {},
|
|
2093
|
+
...marker.continuation ? { continuation: validateContinuation(marker.continuation) } : {},
|
|
2094
|
+
pollIntervalMs: asPositiveInt(marker.pollIntervalMs, 250),
|
|
2095
|
+
ttlMs: asPositiveInt(marker.ttlMs, 864e5)
|
|
2096
|
+
};
|
|
2097
|
+
}
|
|
2098
|
+
async function requestMcpTaskContinuation(db, job, binding, inputRequest) {
|
|
2099
|
+
validateContinuation(binding);
|
|
2100
|
+
const expected = getMcpTaskMarker(job)?.continuation;
|
|
2101
|
+
if (!expected || expected.recordId !== binding.recordId || expected.revision !== binding.revision || expected.inputKey !== binding.inputKey) throw new Error("MCP continuation binding mismatch");
|
|
2102
|
+
const found = await db.query(`SELECT task_input_responses FROM _smrt_jobs
|
|
2103
|
+
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, job.id, job.taskId, job.workerId);
|
|
2104
|
+
if (found.rows.length !== 1) throw new McpTaskCancelledError(job.taskId ?? "");
|
|
2105
|
+
const answers = asRecord(parseJson(found.rows[0].task_input_responses));
|
|
2106
|
+
if (Object.hasOwn(answers, binding.inputKey)) return answers[binding.inputKey];
|
|
2107
|
+
if ((await db.query(`UPDATE _smrt_jobs SET status = 'pending', worker_id = NULL,
|
|
2108
|
+
worker_heartbeat = NULL, task_input_requests = ?, updated_at = ?
|
|
2109
|
+
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'
|
|
2110
|
+
RETURNING id`, encodeContinuationJson({ [binding.inputKey]: inputRequest }), (/* @__PURE__ */ new Date()).toISOString(), job.id, job.taskId, job.workerId)).rows.length !== 1) throw new McpTaskCancelledError(job.taskId ?? "");
|
|
2111
|
+
throw new McpTaskSuspendedError("MCP task awaits durable input");
|
|
1915
2112
|
}
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
function
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
2113
|
+
function encodeContinuationJson(value) {
|
|
2114
|
+
try {
|
|
2115
|
+
const json = JSON.stringify(value, (_key, item) => {
|
|
2116
|
+
if (item === void 0 || typeof item === "function" || typeof item === "symbol" || typeof item === "bigint" || typeof item === "number" && !Number.isFinite(item)) throw new Error("Invalid JSON");
|
|
2117
|
+
return item;
|
|
2118
|
+
});
|
|
2119
|
+
if (!json || new TextEncoder().encode(json).byteLength > 65536) throw new Error("Oversized JSON");
|
|
2120
|
+
return json;
|
|
2121
|
+
} catch {
|
|
2122
|
+
throw new Error("MCP continuation input must be JSON within 65536 bytes");
|
|
1925
2123
|
}
|
|
1926
|
-
return set;
|
|
1927
|
-
}
|
|
1928
|
-
function registerLiveWorker(workerKey) {
|
|
1929
|
-
liveWorkers().add(workerKey);
|
|
1930
2124
|
}
|
|
1931
|
-
function
|
|
1932
|
-
|
|
2125
|
+
function validateContinuation(value) {
|
|
2126
|
+
const source = asRecord(value);
|
|
2127
|
+
const record = {
|
|
2128
|
+
recordId: source.recordId,
|
|
2129
|
+
revision: source.revision,
|
|
2130
|
+
inputKey: source.inputKey
|
|
2131
|
+
};
|
|
2132
|
+
for (const key of [
|
|
2133
|
+
"recordId",
|
|
2134
|
+
"revision",
|
|
2135
|
+
"inputKey"
|
|
2136
|
+
]) if (typeof record[key] !== "string" || !record[key] || record[key].length > 256) throw new Error("Invalid MCP continuation binding");
|
|
2137
|
+
return {
|
|
2138
|
+
recordId: record.recordId,
|
|
2139
|
+
revision: record.revision,
|
|
2140
|
+
inputKey: record.inputKey
|
|
2141
|
+
};
|
|
1933
2142
|
}
|
|
1934
|
-
function
|
|
1935
|
-
|
|
2143
|
+
async function requestMcpTaskInput(db, job, inputRequests) {
|
|
2144
|
+
const jobId = job.id;
|
|
2145
|
+
const taskId = job.taskId;
|
|
2146
|
+
if (!jobId || !taskId || !job.workerId) throw new Error("Task input is only available while an MCP task job is running");
|
|
2147
|
+
if (Object.keys(inputRequests).length === 0) return {};
|
|
2148
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2149
|
+
await db.query(`UPDATE _smrt_jobs
|
|
2150
|
+
SET task_input_requests = ?, task_input_responses = NULL, updated_at = ?
|
|
2151
|
+
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, JSON.stringify(inputRequests), now, jobId, taskId, job.workerId);
|
|
2152
|
+
while (true) {
|
|
2153
|
+
const row = (await db.query(`SELECT status, task_input_responses FROM _smrt_jobs WHERE id = ? AND task_id = ?`, jobId, taskId)).rows[0];
|
|
2154
|
+
if (!row || row.status === "cancelled") throw new McpTaskCancelledError(taskId);
|
|
2155
|
+
if (row.status !== "running") throw new Error(`MCP task is no longer running: ${taskId}`);
|
|
2156
|
+
const responses = asRecord(parseJson(row.task_input_responses));
|
|
2157
|
+
if (Object.keys(inputRequests).every((key) => Object.hasOwn(responses, key))) {
|
|
2158
|
+
const selected = Object.fromEntries(Object.keys(inputRequests).map((key) => [key, responses[key]]));
|
|
2159
|
+
await db.query(`UPDATE _smrt_jobs
|
|
2160
|
+
SET task_input_requests = NULL, updated_at = ?
|
|
2161
|
+
WHERE id = ? AND task_id = ? AND worker_id = ? AND status = 'running'`, (/* @__PURE__ */ new Date()).toISOString(), jobId, taskId, job.workerId);
|
|
2162
|
+
return selected;
|
|
2163
|
+
}
|
|
2164
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
2165
|
+
}
|
|
1936
2166
|
}
|
|
1937
|
-
function
|
|
1938
|
-
|
|
1939
|
-
|
|
2167
|
+
function taskFromJob(job, marker) {
|
|
2168
|
+
const status = taskStatusFromJob(job);
|
|
2169
|
+
const createdAt = toIso(job.created_at) ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
2170
|
+
const lastUpdatedAt = toIso(job.updated_at) ?? createdAt;
|
|
2171
|
+
const task = {
|
|
2172
|
+
taskId: job.taskId ?? "",
|
|
2173
|
+
status,
|
|
2174
|
+
createdAt,
|
|
2175
|
+
lastUpdatedAt,
|
|
2176
|
+
ttlMs: marker.ttlMs,
|
|
2177
|
+
pollIntervalMs: marker.pollIntervalMs
|
|
2178
|
+
};
|
|
2179
|
+
if (status === "input_required") task.statusMessage = "Waiting for required input";
|
|
2180
|
+
if (status === "cancelled") task.statusMessage = "Task cancelled";
|
|
2181
|
+
if (status === "failed") {
|
|
2182
|
+
task.statusMessage = job.lastError ?? "Task failed";
|
|
2183
|
+
task.error = {
|
|
2184
|
+
code: -32603,
|
|
2185
|
+
message: task.statusMessage
|
|
2186
|
+
};
|
|
2187
|
+
}
|
|
2188
|
+
if (status === "completed" && job.taskResult) task.result = job.taskResult;
|
|
2189
|
+
return task;
|
|
1940
2190
|
}
|
|
1941
|
-
function
|
|
1942
|
-
|
|
2191
|
+
function taskStatusFromJob(job) {
|
|
2192
|
+
if (job.status === "completed") return "completed";
|
|
2193
|
+
if (job.status === "cancelled") return "cancelled";
|
|
2194
|
+
if (job.status === "failed") return "failed";
|
|
2195
|
+
if (Object.keys(asRecord(job.taskInputRequests)).length > 0 && !(getMcpTaskMarker(job)?.continuation && job.taskInputResponses !== null)) return "input_required";
|
|
2196
|
+
return "working";
|
|
1943
2197
|
}
|
|
1944
|
-
function
|
|
1945
|
-
|
|
1946
|
-
return
|
|
2198
|
+
function asRecord(value) {
|
|
2199
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return {};
|
|
2200
|
+
return value;
|
|
1947
2201
|
}
|
|
1948
|
-
|
|
2202
|
+
function parseJson(value) {
|
|
2203
|
+
if (typeof value !== "string") return value;
|
|
1949
2204
|
try {
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
2205
|
+
return JSON.parse(value);
|
|
2206
|
+
} catch {
|
|
2207
|
+
return {};
|
|
2208
|
+
}
|
|
1953
2209
|
}
|
|
1954
|
-
function
|
|
1955
|
-
|
|
1956
|
-
const type = withConfig.type || withConfig.config?.type;
|
|
1957
|
-
return detectEngine(resolveUrl(db), type);
|
|
2210
|
+
function asPositiveInt(value, fallback) {
|
|
2211
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
|
|
1958
2212
|
}
|
|
1959
|
-
function
|
|
1960
|
-
|
|
1961
|
-
|
|
2213
|
+
function toIso(value) {
|
|
2214
|
+
if (value instanceof Date) return value.toISOString();
|
|
2215
|
+
if (typeof value === "string") return value;
|
|
1962
2216
|
}
|
|
1963
|
-
function
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
kind: "none",
|
|
1972
|
-
degraded: false,
|
|
1973
|
-
reason: `the ${engine} engine has one owner per database`
|
|
1974
|
-
};
|
|
1975
|
-
if (isInMemory(db)) return {
|
|
1976
|
-
kind: "none",
|
|
1977
|
-
degraded: false,
|
|
1978
|
-
reason: "an in-memory SQLite database cannot be reached by a second connection"
|
|
1979
|
-
};
|
|
1980
|
-
const dbEngine = db.engine;
|
|
1981
|
-
if (dbEngine !== "node-sqlite" && dbEngine !== "libsql") return {
|
|
1982
|
-
kind: "none",
|
|
1983
|
-
degraded: true,
|
|
1984
|
-
reason: "the connection does not report which SQLite engine it uses, so a second connection may use a different engine on the same file"
|
|
1985
|
-
};
|
|
1986
|
-
if (typeof db.reopenOptions !== "function") return {
|
|
1987
|
-
kind: "none",
|
|
1988
|
-
degraded: true,
|
|
1989
|
-
reason: "the connection cannot give options to reopen the same database"
|
|
1990
|
-
};
|
|
1991
|
-
let reopen;
|
|
1992
|
-
try {
|
|
1993
|
-
reopen = db.reopenOptions();
|
|
1994
|
-
} catch (error) {
|
|
1995
|
-
return {
|
|
1996
|
-
kind: "none",
|
|
1997
|
-
degraded: true,
|
|
1998
|
-
reason: `the connection cannot be reopened on the same engine (${error instanceof Error ? error.message : String(error)})`
|
|
1999
|
-
};
|
|
2217
|
+
function toPublicTaskData(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
2218
|
+
if (value === null || typeof value !== "object") return value;
|
|
2219
|
+
const publicSource = value;
|
|
2220
|
+
if (typeof publicSource.toPublicJSON === "function") return publicSource.toPublicJSON({});
|
|
2221
|
+
if (Array.isArray(value)) {
|
|
2222
|
+
if (seen.has(value)) return "[Circular]";
|
|
2223
|
+
seen.add(value);
|
|
2224
|
+
return value.map((entry) => toPublicTaskData(entry, seen));
|
|
2000
2225
|
}
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
};
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2226
|
+
const prototype = Object.getPrototypeOf(value);
|
|
2227
|
+
if (prototype !== Object.prototype && prototype !== null) return value;
|
|
2228
|
+
if (seen.has(value)) return "[Circular]";
|
|
2229
|
+
seen.add(value);
|
|
2230
|
+
const out = {};
|
|
2231
|
+
for (const [key, nested] of Object.entries(value)) out[key] = toPublicTaskData(nested, seen);
|
|
2232
|
+
return out;
|
|
2233
|
+
}
|
|
2234
|
+
//#endregion
|
|
2235
|
+
//#region src/stale-recovery.ts
|
|
2236
|
+
var DEFAULT_TASK_HEARTBEAT_INTERVAL_MS = 3e4;
|
|
2237
|
+
var DEFAULT_LEASE_TICK_MS = 1e4;
|
|
2238
|
+
var DEFAULT_LEASE_TTL_MS = 3e4;
|
|
2239
|
+
var LEASE_TTL_GRACE_MULTIPLIER = 3;
|
|
2240
|
+
function getEffectiveLeaseTtlMs(leaseTtlMs, leaseTickMs) {
|
|
2241
|
+
return Math.max(leaseTtlMs, leaseTickMs * LEASE_TTL_GRACE_MULTIPLIER);
|
|
2011
2242
|
}
|
|
2012
2243
|
//#endregion
|
|
2013
2244
|
//#region src/runner.ts
|
|
2014
2245
|
var runnerExecutionContextIdentities = /* @__PURE__ */ new WeakSet();
|
|
2246
|
+
var runnerJobClaims = /* @__PURE__ */ new WeakMap();
|
|
2015
2247
|
var runnerExecutionContexts = new AsyncLocalStorage();
|
|
2016
2248
|
function isRunnerExecutionContext(value) {
|
|
2017
2249
|
return typeof value === "object" && value !== null && runnerExecutionContextIdentities.has(value);
|
|
@@ -2019,6 +2251,11 @@ function isRunnerExecutionContext(value) {
|
|
|
2019
2251
|
function getActiveJobExecutionContext() {
|
|
2020
2252
|
return runnerExecutionContexts.getStore();
|
|
2021
2253
|
}
|
|
2254
|
+
function getJobClaim(context) {
|
|
2255
|
+
const claim = isRunnerExecutionContext(context) ? runnerJobClaims.get(context) : void 0;
|
|
2256
|
+
if (!claim) throw new Error("Job claim requires TaskRunner context with claimFencing: true");
|
|
2257
|
+
return claim;
|
|
2258
|
+
}
|
|
2022
2259
|
function errorText(error) {
|
|
2023
2260
|
return error instanceof Error ? error.message : String(error);
|
|
2024
2261
|
}
|
|
@@ -2034,6 +2271,10 @@ async function retireLivenessWorker(worker, exited) {
|
|
|
2034
2271
|
if (!exitedInTime) await worker.terminate().catch(() => {});
|
|
2035
2272
|
}
|
|
2036
2273
|
var DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER = 20;
|
|
2274
|
+
var DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS = 1440 * 60 * 1e3;
|
|
2275
|
+
var HANDLER_UNCLAIMED_SWEEP_LIMIT = 100;
|
|
2276
|
+
var MAX_HANDLER_UNCLAIMED_DEADLINE_MS = 10 * 365 * 24 * 60 * 60 * 1e3;
|
|
2277
|
+
var HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS = 900 * 1e3;
|
|
2037
2278
|
var SURPLUS_RELEASE_CHUNK = 500;
|
|
2038
2279
|
var MAX_RETRY_AFTER_MS = 1440 * 60 * 1e3;
|
|
2039
2280
|
function errorRetryHints(error) {
|
|
@@ -2062,6 +2303,7 @@ var JobCancelledError = class extends Error {
|
|
|
2062
2303
|
};
|
|
2063
2304
|
var DEFAULT_CONFIG = {
|
|
2064
2305
|
id: "",
|
|
2306
|
+
claimFencing: false,
|
|
2065
2307
|
authorizeMcpTask: async () => false,
|
|
2066
2308
|
concurrency: 5,
|
|
2067
2309
|
queues: ["default"],
|
|
@@ -2073,7 +2315,8 @@ var DEFAULT_CONFIG = {
|
|
|
2073
2315
|
staleJobThresholdMs: 9e4,
|
|
2074
2316
|
leaseTtlMs: DEFAULT_LEASE_TTL_MS,
|
|
2075
2317
|
leaseTickMs: DEFAULT_LEASE_TICK_MS,
|
|
2076
|
-
retention: {}
|
|
2318
|
+
retention: {},
|
|
2319
|
+
handlerUnclaimedDeadlineMs: DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS
|
|
2077
2320
|
};
|
|
2078
2321
|
var UnpersistedJobWriteError = class extends Error {
|
|
2079
2322
|
constructor(writeError) {
|
|
@@ -2102,6 +2345,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2102
2345
|
workerCollection = null;
|
|
2103
2346
|
workersTableVerified = false;
|
|
2104
2347
|
lastRecoverySweepAt = 0;
|
|
2348
|
+
lastUnclaimedSweepAt = 0;
|
|
2105
2349
|
running = false;
|
|
2106
2350
|
activeJobs = /* @__PURE__ */ new Map();
|
|
2107
2351
|
/**
|
|
@@ -2130,6 +2374,13 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2130
2374
|
livenessWorkerExited = null;
|
|
2131
2375
|
shutdownPromise = null;
|
|
2132
2376
|
db = null;
|
|
2377
|
+
/**
|
|
2378
|
+
* Handlers this runner dispatches to, snapshotted when it starts (#5005).
|
|
2379
|
+
* Registration is closed while it runs, so the snapshot is the registry.
|
|
2380
|
+
*/
|
|
2381
|
+
jobHandlers = /* @__PURE__ */ new Map();
|
|
2382
|
+
/** The snapshot's names: the only handler jobs this runner claims. */
|
|
2383
|
+
handlerNames = [];
|
|
2133
2384
|
logger = createLogger(true);
|
|
2134
2385
|
constructor(config = {}) {
|
|
2135
2386
|
super();
|
|
@@ -2145,6 +2396,8 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2145
2396
|
}
|
|
2146
2397
|
this.id = this.config.id;
|
|
2147
2398
|
this.workerKey = createWorkerKey(this.id);
|
|
2399
|
+
const deadline = this.config.handlerUnclaimedDeadlineMs;
|
|
2400
|
+
if (!Number.isFinite(deadline) || deadline < 1 || deadline > MAX_HANDLER_UNCLAIMED_DEADLINE_MS) throw new RangeError(`handlerUnclaimedDeadlineMs must be between 1 and ${MAX_HANDLER_UNCLAIMED_DEADLINE_MS} milliseconds`);
|
|
2148
2401
|
for (const [name, value] of [["pollInterval", this.config.pollInterval], ["idlePollInterval", config.idlePollInterval ?? this.config.pollInterval]]) if (!Number.isFinite(value) || value < 1 || value > 2147483647) throw new RangeError(`${name} must be between 1 and 2147483647 milliseconds`);
|
|
2149
2402
|
this.maxIdlePollIntervalMs = Math.min(2147483647, Math.max(this.config.pollInterval, config.idlePollInterval ?? this.config.pollInterval * DEFAULT_IDLE_POLL_INTERVAL_MULTIPLIER));
|
|
2150
2403
|
this.idlePollDelayMs = this.config.pollInterval;
|
|
@@ -2178,6 +2431,8 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2178
2431
|
queues: this.config.queues
|
|
2179
2432
|
});
|
|
2180
2433
|
registerLiveWorker(this.workerKey);
|
|
2434
|
+
this.jobHandlers = sealJobHandlerRegistry(this.workerKey);
|
|
2435
|
+
this.handlerNames = [...this.jobHandlers.keys()];
|
|
2181
2436
|
this.running = true;
|
|
2182
2437
|
const plan = planLivenessConnection(this.db);
|
|
2183
2438
|
if (plan.kind === "none") {
|
|
@@ -2229,6 +2484,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2229
2484
|
this.leaseTimer = null;
|
|
2230
2485
|
}
|
|
2231
2486
|
unregisterLiveWorker(this.workerKey);
|
|
2487
|
+
releaseJobHandlerRegistry(this.workerKey);
|
|
2232
2488
|
if (this.activeJobs.size === 0 && !this.pollPromise) try {
|
|
2233
2489
|
await this.workerCollection?.expireWorker(this.workerKey);
|
|
2234
2490
|
} catch {}
|
|
@@ -2292,12 +2548,16 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2292
2548
|
if (generation !== this.pollGeneration) return false;
|
|
2293
2549
|
await this.retryUnreleasedSurplus();
|
|
2294
2550
|
if (generation !== this.pollGeneration) return false;
|
|
2551
|
+
await this.sweepUnclaimedHandlerJobs();
|
|
2552
|
+
if (generation !== this.pollGeneration) return false;
|
|
2295
2553
|
const available = this.config.concurrency - this.activeJobs.size;
|
|
2296
2554
|
if (available <= 0) return true;
|
|
2297
2555
|
const claimed = await this.collection.claimReady({
|
|
2556
|
+
claimFencing: this.config.claimFencing,
|
|
2298
2557
|
workerId: this.workerKey,
|
|
2299
2558
|
queues: this.config.queues,
|
|
2300
2559
|
tenantIds: this.config.tenantIds,
|
|
2560
|
+
handlerNames: this.handlerNames,
|
|
2301
2561
|
limit: available
|
|
2302
2562
|
});
|
|
2303
2563
|
const jobs = claimed.slice(0, available);
|
|
@@ -2393,7 +2653,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2393
2653
|
timeoutHandle = handle;
|
|
2394
2654
|
});
|
|
2395
2655
|
const completedAt = /* @__PURE__ */ new Date();
|
|
2396
|
-
const snapshot = terminalSnapshot(job);
|
|
2656
|
+
const snapshot = terminalSnapshot(job, this.config.claimFencing);
|
|
2397
2657
|
let event = null;
|
|
2398
2658
|
try {
|
|
2399
2659
|
event = snapshot ? await transitionTerminalJob(this.db, {
|
|
@@ -2546,15 +2806,16 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2546
2806
|
* job out from under a finishing handler (a genuine zombie), the handler's
|
|
2547
2807
|
* outcome is dropped rather than resurrecting the row.
|
|
2548
2808
|
*/
|
|
2549
|
-
async writeOwnedJob(jobId, assignments) {
|
|
2809
|
+
async writeOwnedJob(jobId, assignments, dispatch) {
|
|
2550
2810
|
if (!this.db) return false;
|
|
2551
2811
|
const columns = Object.keys(assignments);
|
|
2552
2812
|
const setSql = columns.map((column) => `${column} = ?`).join(", ");
|
|
2553
2813
|
const values = columns.map((column) => assignments[column]);
|
|
2814
|
+
const fenced = this.config.claimFencing && dispatch;
|
|
2554
2815
|
return ((await this.db.query(`UPDATE _smrt_jobs
|
|
2555
2816
|
SET ${setSql}
|
|
2556
|
-
WHERE id = ? AND worker_id = ? AND status = 'running'
|
|
2557
|
-
RETURNING id`, ...values, jobId, this.workerKey)).rows?.length ?? 0) > 0;
|
|
2817
|
+
WHERE id = ? AND worker_id = ? AND status = 'running'${fenced ? " AND attempts = ? AND started_at = ?" : ""}
|
|
2818
|
+
RETURNING id`, ...values, jobId, this.workerKey, ...fenced ? [dispatch.attempts, dispatch.startedAt?.toISOString() ?? null] : [])).rows?.length ?? 0) > 0;
|
|
2558
2819
|
}
|
|
2559
2820
|
/**
|
|
2560
2821
|
* Execute a job by invoking the method on the SmrtObject
|
|
@@ -2562,6 +2823,8 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2562
2823
|
async executeJob(job) {
|
|
2563
2824
|
const runJob = async () => {
|
|
2564
2825
|
await this.assertMcpTaskAuthority(job);
|
|
2826
|
+
const handlerName = jobHandlerName(job.objectType);
|
|
2827
|
+
if (handlerName !== null) return this.executeHandlerJob(job, handlerName);
|
|
2565
2828
|
const registeredClass = ObjectRegistry.getClass(job.objectType);
|
|
2566
2829
|
if (!registeredClass) throw new Error(`Unknown object type: ${job.objectType}`);
|
|
2567
2830
|
const ObjectClass = registeredClass.constructor;
|
|
@@ -2629,6 +2892,31 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2629
2892
|
return runJob();
|
|
2630
2893
|
}
|
|
2631
2894
|
/**
|
|
2895
|
+
* Run a job that targets a registered named handler (#5005). Called inside
|
|
2896
|
+
* `executeJob`'s tenant context, after the same MCP authority check as a
|
|
2897
|
+
* model job; timeout, cancellation, claim fencing and terminal writes are
|
|
2898
|
+
* the shared model-job paths.
|
|
2899
|
+
*/
|
|
2900
|
+
async executeHandlerJob(job, name) {
|
|
2901
|
+
if (job.method !== "handle" || job.objectId != null) throw new JobHandlerTargetError(`Handler job ${job.objectType} must have method '${JOB_HANDLER_METHOD}' and no objectId`);
|
|
2902
|
+
if (getMcpTaskMarker(job) || job.taskId != null || job.taskOwnerId != null) throw new JobHandlerTargetError(`Handler job ${job.objectType} cannot be an MCP task`);
|
|
2903
|
+
const handler = this.jobHandlers.get(name);
|
|
2904
|
+
if (!handler) throw new JobHandlerUnregisteredError(name);
|
|
2905
|
+
const jobId = job.id;
|
|
2906
|
+
if (!jobId) throw new Error("Job has no ID");
|
|
2907
|
+
const { _agentConfig: _, _scheduleId: __, _mcpTask: ___, ...payload } = job.args ?? {};
|
|
2908
|
+
const contextLogger = new JobContextLogger(createLogger(true), {
|
|
2909
|
+
jobId,
|
|
2910
|
+
attempt: job.attempts,
|
|
2911
|
+
queue: job.queue,
|
|
2912
|
+
objectType: job.objectType,
|
|
2913
|
+
method: job.method
|
|
2914
|
+
});
|
|
2915
|
+
contextLogger.info(`Starting job: ${job.getDescription()}`);
|
|
2916
|
+
const executionContext = this.createExecutionContext(job, contextLogger, name);
|
|
2917
|
+
return { result: await runnerExecutionContexts.run(executionContext, async () => await handler(payload, executionContext)) };
|
|
2918
|
+
}
|
|
2919
|
+
/**
|
|
2632
2920
|
* Handle job execution error
|
|
2633
2921
|
*/
|
|
2634
2922
|
async handleJobError(job, error) {
|
|
@@ -2650,7 +2938,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2650
2938
|
worker_id: null,
|
|
2651
2939
|
worker_heartbeat: null,
|
|
2652
2940
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
2653
|
-
}))) return;
|
|
2941
|
+
}, job))) return;
|
|
2654
2942
|
job.status = "pending";
|
|
2655
2943
|
job.lastError = safeMessage;
|
|
2656
2944
|
job.runAt = nextRunAt;
|
|
@@ -2669,7 +2957,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2669
2957
|
this.emit("job:retrying", job, error, delay);
|
|
2670
2958
|
} else {
|
|
2671
2959
|
const completedAt = /* @__PURE__ */ new Date();
|
|
2672
|
-
const snapshot = terminalSnapshot(job);
|
|
2960
|
+
const snapshot = terminalSnapshot(job, this.config.claimFencing);
|
|
2673
2961
|
const event = snapshot ? await this.persistJobWrite(() => transitionTerminalJob(this.db, {
|
|
2674
2962
|
job: snapshot,
|
|
2675
2963
|
status: "failed",
|
|
@@ -2677,7 +2965,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2677
2965
|
expectedStatuses: ["running"],
|
|
2678
2966
|
expectedWorkerId: this.workerKey,
|
|
2679
2967
|
lastError: safeMessage,
|
|
2680
|
-
failureKind: isTimeout ? "timeout" : "execution"
|
|
2968
|
+
failureKind: isTimeout ? "timeout" : error instanceof JobHandlerUnregisteredError ? "handler-unregistered" : "execution"
|
|
2681
2969
|
})) : null;
|
|
2682
2970
|
if (!event) return;
|
|
2683
2971
|
job.status = "failed";
|
|
@@ -2706,7 +2994,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2706
2994
|
if (!authorized) throw new Error("MCP task authorization denied");
|
|
2707
2995
|
if ((await this.db?.query(`SELECT id FROM _smrt_jobs WHERE id = ? AND worker_id = ? AND status = 'running'`, job.id, job.workerId))?.rows.length !== 1) throw new Error("MCP task is no longer active");
|
|
2708
2996
|
}
|
|
2709
|
-
createExecutionContext(job, contextLogger) {
|
|
2997
|
+
createExecutionContext(job, contextLogger, handler) {
|
|
2710
2998
|
const context = {
|
|
2711
2999
|
job: {
|
|
2712
3000
|
jobId: job.id ?? "",
|
|
@@ -2714,7 +3002,8 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2714
3002
|
attempt: job.attempts,
|
|
2715
3003
|
queue: job.queue,
|
|
2716
3004
|
objectType: job.objectType,
|
|
2717
|
-
method: job.method
|
|
3005
|
+
method: job.method,
|
|
3006
|
+
...handler === void 0 ? {} : { handler }
|
|
2718
3007
|
},
|
|
2719
3008
|
logger: contextLogger,
|
|
2720
3009
|
signal: (job.id ? this.jobAborts.get(job.id)?.signal : void 0) ?? new AbortController().signal,
|
|
@@ -2757,6 +3046,16 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2757
3046
|
} } : {}
|
|
2758
3047
|
};
|
|
2759
3048
|
runnerExecutionContextIdentities.add(context);
|
|
3049
|
+
if (this.config.claimFencing) runnerJobClaims.set(context, Object.freeze({
|
|
3050
|
+
jobId: job.id ?? "",
|
|
3051
|
+
workerId: this.workerKey,
|
|
3052
|
+
attempt: job.attempts,
|
|
3053
|
+
startedAt: job.startedAt?.toISOString() ?? "",
|
|
3054
|
+
tenantId: job.tenantId ?? null,
|
|
3055
|
+
objectType: job.objectType,
|
|
3056
|
+
objectId: job.objectId ?? null,
|
|
3057
|
+
method: job.method
|
|
3058
|
+
}));
|
|
2760
3059
|
return context;
|
|
2761
3060
|
}
|
|
2762
3061
|
async appendJobEvent(job, input) {
|
|
@@ -2853,7 +3152,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2853
3152
|
const recoveredAt = /* @__PURE__ */ new Date();
|
|
2854
3153
|
const errorMessage = "Recovered orphaned running job: its owning worker is no longer alive (no fresh liveness lease in _smrt_workers and not running in this process).";
|
|
2855
3154
|
for (const job of orphans) {
|
|
2856
|
-
const snapshot = terminalSnapshot(job);
|
|
3155
|
+
const snapshot = terminalSnapshot(job, this.config.claimFencing);
|
|
2857
3156
|
if (!snapshot) continue;
|
|
2858
3157
|
const lastError = (job.id ? this.unsettledJobs.get(job.id) : void 0) ?? errorMessage;
|
|
2859
3158
|
let event;
|
|
@@ -2864,7 +3163,7 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2864
3163
|
completedAt: recoveredAt,
|
|
2865
3164
|
expectedStatuses: ["running"],
|
|
2866
3165
|
expectedWorkerId: job.workerId ?? null,
|
|
2867
|
-
clearWorker:
|
|
3166
|
+
clearWorker: !this.config.claimFencing,
|
|
2868
3167
|
lastError,
|
|
2869
3168
|
failureKind: "stale-recovery"
|
|
2870
3169
|
});
|
|
@@ -2888,6 +3187,84 @@ var TaskRunner = class extends EventEmitter {
|
|
|
2888
3187
|
}
|
|
2889
3188
|
}
|
|
2890
3189
|
/**
|
|
3190
|
+
* Fail named handler jobs left `pending` past their `run_at` by more than
|
|
3191
|
+
* `handlerUnclaimedDeadlineMs` (#5005), failure kind `handler-unclaimed`.
|
|
3192
|
+
*
|
|
3193
|
+
* Claims skip handler jobs a runner has not registered, so a job no runner
|
|
3194
|
+
* serves would wait forever. Every runner runs this sweep from its poll over
|
|
3195
|
+
* its own queues and tenant scope, at most once per 1% of the deadline
|
|
3196
|
+
* (between one lease tick and 15 min) and
|
|
3197
|
+
* {@link HANDLER_UNCLAIMED_SWEEP_LIMIT} rows at a time. It leaves out the
|
|
3198
|
+
* handlers this runner registered: it can claim those itself, so an
|
|
3199
|
+
* overdue backlog it serves (a saturated queue, a fleet back after a long
|
|
3200
|
+
* outage) is run, not failed. The deadline is measured from `run_at`.
|
|
3201
|
+
* Residual: while every runner serving a handler is down past the deadline,
|
|
3202
|
+
* a runner without it in the same queue still fails its jobs. Races are harmless:
|
|
3203
|
+
* each row is failed by one conditional transition (`pending` and still
|
|
3204
|
+
* past the deadline), so a concurrent sweeper, a claim or a requeue wins
|
|
3205
|
+
* and this one writes nothing. Model jobs are never swept. A failed sweep is
|
|
3206
|
+
* a `runner:error` and never stops the poll from claiming.
|
|
3207
|
+
*/
|
|
3208
|
+
async sweepUnclaimedHandlerJobs() {
|
|
3209
|
+
if (!this.db || !this.collection) return;
|
|
3210
|
+
const now = Date.now();
|
|
3211
|
+
const deadlineMs = this.config.handlerUnclaimedDeadlineMs;
|
|
3212
|
+
const interval = Math.max(this.config.leaseTickMs, Math.min(HANDLER_UNCLAIMED_SWEEP_MAX_INTERVAL_MS, deadlineMs / 100));
|
|
3213
|
+
if (now - this.lastUnclaimedSweepAt < interval) return;
|
|
3214
|
+
this.lastUnclaimedSweepAt = now;
|
|
3215
|
+
const cutoff = new Date(now - deadlineMs).toISOString();
|
|
3216
|
+
const scope = jobTenantScope(this.config.tenantIds);
|
|
3217
|
+
const queuePredicate = this.config.queues.length ? ` AND queue IN (${this.config.queues.map(() => "?").join(", ")})` : "";
|
|
3218
|
+
const served = this.handlerNames.map((name) => jobHandlerTarget(name).objectType);
|
|
3219
|
+
const servedPredicate = served.length ? ` AND object_type NOT IN (${served.map(() => "?").join(", ")})` : "";
|
|
3220
|
+
let unclaimed;
|
|
3221
|
+
try {
|
|
3222
|
+
unclaimed = await this.collection.query(`SELECT ${SMRT_JOB_PORTABLE_SELECT_COLUMNS}
|
|
3223
|
+
FROM _smrt_jobs
|
|
3224
|
+
WHERE status = 'pending' AND run_at <= ? AND ${HANDLER_TARGET_SQL}${scope.sql}${queuePredicate}${servedPredicate}
|
|
3225
|
+
ORDER BY run_at ASC, id ASC
|
|
3226
|
+
LIMIT ?`, [
|
|
3227
|
+
cutoff,
|
|
3228
|
+
...scope.params,
|
|
3229
|
+
...this.config.queues,
|
|
3230
|
+
...served,
|
|
3231
|
+
100
|
|
3232
|
+
], { allowRawOnTenantScoped: true });
|
|
3233
|
+
} catch (error) {
|
|
3234
|
+
this.emit("runner:error", error);
|
|
3235
|
+
return;
|
|
3236
|
+
}
|
|
3237
|
+
if (unclaimed.length >= 100) this.lastUnclaimedSweepAt = 0;
|
|
3238
|
+
const sweptAt = /* @__PURE__ */ new Date();
|
|
3239
|
+
for (const job of unclaimed) {
|
|
3240
|
+
const snapshot = terminalSnapshot(job);
|
|
3241
|
+
if (!snapshot) continue;
|
|
3242
|
+
const lastError = `Job handler not claimed: no runner registered for ${jobHandlerName(job.objectType)} claimed this job within ${deadlineMs} ms of its run_at.`;
|
|
3243
|
+
let event;
|
|
3244
|
+
try {
|
|
3245
|
+
event = await transitionTerminalJob(this.db, {
|
|
3246
|
+
job: snapshot,
|
|
3247
|
+
status: "failed",
|
|
3248
|
+
completedAt: sweptAt,
|
|
3249
|
+
expectedStatuses: ["pending"],
|
|
3250
|
+
expectedRunAtAtOrBefore: cutoff,
|
|
3251
|
+
clearWorker: true,
|
|
3252
|
+
lastError,
|
|
3253
|
+
failureKind: "handler-unclaimed"
|
|
3254
|
+
});
|
|
3255
|
+
} catch (error) {
|
|
3256
|
+
this.emit("runner:error", error);
|
|
3257
|
+
continue;
|
|
3258
|
+
}
|
|
3259
|
+
if (!event) continue;
|
|
3260
|
+
job.status = "failed";
|
|
3261
|
+
job.completedAt = sweptAt;
|
|
3262
|
+
job.lastError = lastError;
|
|
3263
|
+
this.emitPersistedJobEvent(job, event);
|
|
3264
|
+
this.emit("job:unclaimed", job, new Error(lastError));
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
2891
3268
|
* Renew this worker's liveness lease.
|
|
2892
3269
|
*
|
|
2893
3270
|
* In Stage 1 this runs on the main event loop, so it provides cross-process
|
|
@@ -3067,6 +3444,6 @@ function createTaskRunner(config) {
|
|
|
3067
3444
|
return new TaskRunner(config);
|
|
3068
3445
|
}
|
|
3069
3446
|
//#endregion
|
|
3070
|
-
export {
|
|
3447
|
+
export { assertJobHandlerName as $, registerJobRetentionTasks as A, isWorkerAlive as B, SmrtWorkerCollection as C, DEFAULT_RETENTION_SWEEP_INTERVAL_MS as D, DEFAULT_JOB_RETENTION as E, countScheduleJobs as F, JOB_HANDLER_TARGET_PREFIX as G, unregisterLiveWorker as H, SmrtJobEvent as I, JobHandlerNameError as J, JobHandlerAlreadyRegisteredError as K, SmrtJobEventCollection as L, unregisterJobRetentionTasks as M, SmrtJob as N, JOBS_RETENTION_TASK as O, SmrtJobCollection as P, MAX_JOB_HANDLERS as Q, createWorkerKey as R, SmrtWorker as S, redactErrorMessage as T, SmrtJobDedupeSlot as U, registerLiveWorker as V, JOB_HANDLER_METHOD as W, JobHandlerTargetError as X, JobHandlerRegistrationClosedError as Y, JobHandlerUnregisteredError as Z, getMcpTaskMarker as _, TaskRunner as a, registerJobHandler as at, taskFromJob as b, getJobClaim as c, MAX_JOB_RETRIES as ct, MCP_TASKS_EXTENSION as d, backgroundEligible as dt, isJobHandlerName as et, McpTaskCancelledError as f, clampRetries as ft, createMcpTaskResult as g, McpTaskSuspendedError as h, markBackgroundEligible as ht, JobTimeoutError as i, listJobHandlers as it, startRetentionSweeper as j, JOB_EVENTS_RETENTION_TASK as k, isRunnerExecutionContext as l, TenantJobCapExceededError as lt, McpTaskStore as m, isBackgroundEligibleMethod as mt, HANDLER_UNCLAIMED_SWEEP_LIMIT as n, jobHandlerName as nt, createTaskRunner as o, unregisterJobHandler as ot, McpTaskNotFoundError as p, getBackgroundEligibleMethods as pt, JobHandlerLimitError as q, JobCancelledError as r, jobHandlerTarget as rt, getActiveJobExecutionContext as s, DEFAULT_TENANT_JOB_CAP as st, DEFAULT_HANDLER_UNCLAIMED_DEADLINE_MS as t, isJobHandlerTarget as tt, DEFAULT_TASK_HEARTBEAT_INTERVAL_MS as u, assertWithinTenantCreationCap as ut, requestMcpTaskContinuation as v, redactErrorForPersistence as w, JobContextLogger as x, requestMcpTaskInput as y, enablePgliteJobs as z };
|
|
3071
3448
|
|
|
3072
|
-
//# sourceMappingURL=runner-
|
|
3449
|
+
//# sourceMappingURL=runner-ComDONr7.js.map
|