@terreno/ai 57.8.0 → 57.10.1
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/.cursorrules +2 -2
- package/README.md +2 -1
- package/bunfig.toml +1 -1
- package/dist/aiApp.d.ts +16 -5
- package/dist/aiApp.js +17 -7
- package/dist/harness/adminScreens.d.ts +6 -0
- package/dist/harness/adminScreens.js +11 -0
- package/dist/harness/agentLoop.d.ts +61 -0
- package/dist/harness/agentLoop.js +798 -0
- package/dist/harness/agentTaskNames.d.ts +4 -0
- package/dist/harness/agentTaskNames.js +7 -0
- package/dist/harness/approvalPolicy.d.ts +3 -0
- package/dist/harness/approvalPolicy.js +23 -0
- package/dist/harness/approvals.d.ts +101 -0
- package/dist/harness/approvals.js +468 -0
- package/dist/harness/commit.d.ts +238 -0
- package/dist/harness/commit.js +678 -0
- package/dist/harness/conversation.d.ts +75 -0
- package/dist/harness/conversation.js +397 -0
- package/dist/harness/defineAgent.d.ts +9 -0
- package/dist/harness/defineAgent.js +65 -0
- package/dist/harness/defineTask.d.ts +11 -0
- package/dist/harness/defineTask.js +59 -0
- package/dist/harness/defineTool.d.ts +7 -0
- package/dist/harness/defineTool.js +36 -0
- package/dist/harness/definitionError.d.ts +8 -0
- package/dist/harness/definitionError.js +15 -0
- package/dist/harness/errors.d.ts +127 -0
- package/dist/harness/errors.js +101 -0
- package/dist/harness/eventHub.d.ts +45 -0
- package/dist/harness/eventHub.js +135 -0
- package/dist/harness/events.d.ts +95 -0
- package/dist/harness/events.js +267 -0
- package/dist/harness/executionEnv.d.ts +31 -0
- package/dist/harness/executionEnv.js +2 -0
- package/dist/harness/extensions.d.ts +82 -0
- package/dist/harness/extensions.js +274 -0
- package/dist/harness/harness.d.ts +163 -0
- package/dist/harness/harness.js +520 -0
- package/dist/harness/harnessApp.d.ts +44 -0
- package/dist/harness/harnessApp.js +62 -0
- package/dist/harness/internalRuntime.d.ts +16 -0
- package/dist/harness/internalRuntime.js +18 -0
- package/dist/harness/leases.d.ts +35 -0
- package/dist/harness/leases.js +86 -0
- package/dist/harness/memo.d.ts +24 -0
- package/dist/harness/memo.js +78 -0
- package/dist/harness/modelCall.d.ts +45 -0
- package/dist/harness/modelCall.js +147 -0
- package/dist/harness/models/harnessApproval.d.ts +2 -0
- package/dist/harness/models/harnessApproval.js +100 -0
- package/dist/harness/models/harnessConversation.d.ts +2 -0
- package/dist/harness/models/harnessConversation.js +117 -0
- package/dist/harness/models/harnessEvent.d.ts +3 -0
- package/dist/harness/models/harnessEvent.js +73 -0
- package/dist/harness/models/harnessInboxEvent.d.ts +2 -0
- package/dist/harness/models/harnessInboxEvent.js +58 -0
- package/dist/harness/models/harnessMemo.d.ts +2 -0
- package/dist/harness/models/harnessMemo.js +42 -0
- package/dist/harness/models/harnessMessage.d.ts +2 -0
- package/dist/harness/models/harnessMessage.js +73 -0
- package/dist/harness/models/harnessOwner.d.ts +2 -0
- package/dist/harness/models/harnessOwner.js +36 -0
- package/dist/harness/models/harnessTask.d.ts +2 -0
- package/dist/harness/models/harnessTask.js +186 -0
- package/dist/harness/ownership.d.ts +89 -0
- package/dist/harness/ownership.js +438 -0
- package/dist/harness/registry.d.ts +29 -0
- package/dist/harness/registry.js +93 -0
- package/dist/harness/retryBackoff.d.ts +31 -0
- package/dist/harness/retryBackoff.js +50 -0
- package/dist/harness/routes/approvals.d.ts +13 -0
- package/dist/harness/routes/approvals.js +93 -0
- package/dist/harness/routes/conversations.d.ts +11 -0
- package/dist/harness/routes/conversations.js +66 -0
- package/dist/harness/routes/events.d.ts +19 -0
- package/dist/harness/routes/events.js +215 -0
- package/dist/harness/routes/tasks.d.ts +11 -0
- package/dist/harness/routes/tasks.js +108 -0
- package/dist/harness/runners/inProcessRunner.d.ts +57 -0
- package/dist/harness/runners/inProcessRunner.js +196 -0
- package/dist/harness/runtime.d.ts +34 -0
- package/dist/harness/runtime.js +551 -0
- package/dist/harness/subagent.d.ts +53 -0
- package/dist/harness/subagent.js +134 -0
- package/dist/harness/suspend.d.ts +8 -0
- package/dist/harness/suspend.js +16 -0
- package/dist/harness/transaction.d.ts +3 -0
- package/dist/harness/transaction.js +22 -0
- package/dist/harness/waits.d.ts +100 -0
- package/dist/harness/waits.js +214 -0
- package/dist/index.d.ts +19 -1
- package/dist/index.js +45 -2
- package/dist/models/aiDataset.d.ts +2 -0
- package/dist/models/aiDataset.js +67 -0
- package/dist/models/aiRequest.js +1 -1
- package/dist/models/gptHistory.js +88 -2
- package/dist/observability/adminScreens.d.ts +5 -0
- package/dist/observability/adminScreens.js +32 -0
- package/dist/observability/compileTemplate.d.ts +1 -0
- package/dist/observability/compileTemplate.js +13 -0
- package/dist/observability/datasetImport.d.ts +11 -0
- package/dist/observability/datasetImport.js +185 -0
- package/dist/observability/evaluate.d.ts +31 -0
- package/dist/observability/evaluate.js +200 -0
- package/dist/observability/evaluatorTemplates.d.ts +17 -0
- package/dist/observability/evaluatorTemplates.js +111 -0
- package/dist/observability/jsonPath.d.ts +2 -0
- package/dist/observability/jsonPath.js +57 -0
- package/dist/observability/local/datasetStore.d.ts +87 -0
- package/dist/observability/local/datasetStore.js +326 -0
- package/dist/observability/local/evaluatorStore.d.ts +44 -0
- package/dist/observability/local/evaluatorStore.js +182 -0
- package/dist/observability/local/experimentRunner.d.ts +96 -0
- package/dist/observability/local/experimentRunner.js +419 -0
- package/dist/observability/local/localPlugin.d.ts +22 -0
- package/dist/observability/local/localPlugin.js +76 -0
- package/dist/observability/local/models/obsDataset.d.ts +2 -0
- package/dist/observability/local/models/obsDataset.js +37 -0
- package/dist/observability/local/models/obsDatasetItem.d.ts +2 -0
- package/dist/observability/local/models/obsDatasetItem.js +76 -0
- package/dist/observability/local/models/obsEvaluator.d.ts +2 -0
- package/dist/observability/local/models/obsEvaluator.js +98 -0
- package/dist/observability/local/models/obsExperiment.d.ts +2 -0
- package/dist/observability/local/models/obsExperiment.js +87 -0
- package/dist/observability/local/models/obsExperimentItem.d.ts +2 -0
- package/dist/observability/local/models/obsExperimentItem.js +45 -0
- package/dist/observability/local/models/obsPrompt.d.ts +2 -0
- package/dist/observability/local/models/obsPrompt.js +42 -0
- package/dist/observability/local/models/obsPromptLabel.d.ts +2 -0
- package/dist/observability/local/models/obsPromptLabel.js +39 -0
- package/dist/observability/local/models/obsPromptVersion.d.ts +2 -0
- package/dist/observability/local/models/obsPromptVersion.js +96 -0
- package/dist/observability/local/models/obsReviewItem.d.ts +2 -0
- package/dist/observability/local/models/obsReviewItem.js +75 -0
- package/dist/observability/local/models/obsScore.d.ts +2 -0
- package/dist/observability/local/models/obsScore.js +58 -0
- package/dist/observability/local/models/obsSpan.d.ts +2 -0
- package/dist/observability/local/models/obsSpan.js +64 -0
- package/dist/observability/local/models/obsTrace.d.ts +2 -0
- package/dist/observability/local/models/obsTrace.js +93 -0
- package/dist/observability/local/promptStore.d.ts +180 -0
- package/dist/observability/local/promptStore.js +444 -0
- package/dist/observability/local/reviewStore.d.ts +50 -0
- package/dist/observability/local/reviewStore.js +203 -0
- package/dist/observability/local/traceStore.d.ts +103 -0
- package/dist/observability/local/traceStore.js +325 -0
- package/dist/observability/observabilityApp.d.ts +24 -0
- package/dist/observability/observabilityApp.js +157 -0
- package/dist/observability/observabilityAppRegistry.d.ts +14 -0
- package/dist/observability/observabilityAppRegistry.js +16 -0
- package/dist/observability/permissions.d.ts +7 -0
- package/dist/observability/permissions.js +60 -0
- package/dist/observability/reviewPanels.d.ts +18 -0
- package/dist/observability/reviewPanels.js +46 -0
- package/dist/observability/routes/datasets.d.ts +7 -0
- package/dist/observability/routes/datasets.js +149 -0
- package/dist/observability/routes/evaluators.d.ts +7 -0
- package/dist/observability/routes/evaluators.js +123 -0
- package/dist/observability/routes/experiments.d.ts +7 -0
- package/dist/observability/routes/experiments.js +95 -0
- package/dist/observability/routes/observabilityRouteAccess.d.ts +13 -0
- package/dist/observability/routes/observabilityRouteAccess.js +67 -0
- package/dist/observability/routes/prompts.d.ts +12 -0
- package/dist/observability/routes/prompts.js +172 -0
- package/dist/observability/routes/requestAiService.d.ts +13 -0
- package/dist/observability/routes/requestAiService.js +21 -0
- package/dist/observability/routes/review.d.ts +7 -0
- package/dist/observability/routes/review.js +79 -0
- package/dist/observability/routes/status.d.ts +5 -0
- package/dist/observability/routes/status.js +31 -0
- package/dist/observability/routes/testMultiStage.d.ts +9 -0
- package/dist/observability/routes/testMultiStage.js +67 -0
- package/dist/observability/routes/traces.d.ts +7 -0
- package/dist/observability/routes/traces.js +129 -0
- package/dist/observability/schemaValidation.d.ts +5 -0
- package/dist/observability/schemaValidation.js +26 -0
- package/dist/observability/sopThresholds.d.ts +2 -0
- package/dist/observability/sopThresholds.js +21 -0
- package/dist/observability/status.d.ts +23 -0
- package/dist/observability/status.js +34 -0
- package/dist/observability/testMultiStageSchemas.d.ts +10 -0
- package/dist/observability/testMultiStageSchemas.js +79 -0
- package/dist/observability/testMultiStageWorkflow.d.ts +20 -0
- package/dist/observability/testMultiStageWorkflow.js +218 -0
- package/dist/observability/types.d.ts +159 -0
- package/dist/observability/types.js +67 -0
- package/dist/routes/files.js +20 -7
- package/dist/routes/gpt.js +179 -488
- package/dist/routes/gptActions.d.ts +9 -0
- package/dist/routes/gptActions.js +212 -0
- package/dist/routes/gptDatasets.d.ts +5 -0
- package/dist/routes/gptDatasets.js +94 -0
- package/dist/routes/gptHistories.d.ts +3 -1
- package/dist/routes/gptHistories.js +188 -2
- package/dist/service/aiDatasets.d.ts +57 -0
- package/dist/service/aiDatasets.js +253 -0
- package/dist/service/aiService.d.ts +50 -1
- package/dist/service/aiService.js +431 -77
- package/dist/service/askFiles.d.ts +49 -0
- package/dist/service/askFiles.js +162 -0
- package/dist/service/asks.d.ts +76 -0
- package/dist/service/asks.js +284 -0
- package/dist/service/chatTurn.d.ts +128 -0
- package/dist/service/chatTurn.js +1674 -0
- package/dist/service/fileStorage.d.ts +4 -0
- package/dist/service/fileStorage.js +7 -2
- package/dist/service/fileUploadsGate.d.ts +8 -0
- package/dist/service/fileUploadsGate.js +18 -0
- package/dist/service/fillActionIds.d.ts +6 -0
- package/dist/service/fillActionIds.js +79 -0
- package/dist/service/gemini.d.ts +3 -3
- package/dist/service/gemini.js +3 -3
- package/dist/service/jsonFenceModel.d.ts +7 -0
- package/dist/service/jsonFenceModel.js +45 -0
- package/dist/service/prompts.d.ts +52 -0
- package/dist/service/prompts.js +96 -1
- package/dist/service/sanitizeHtml.d.ts +11 -0
- package/dist/service/sanitizeHtml.js +108 -0
- package/dist/service/vertex.d.ts +6 -6
- package/dist/service/vertex.js +5 -5
- package/dist/types/harness.d.ts +934 -0
- package/dist/types/harness.js +133 -0
- package/dist/types/index.d.ts +219 -13
- package/dist/types/index.js +2 -0
- package/dist/types/observability.d.ts +288 -0
- package/dist/types/observability.js +2 -0
- package/package.json +17 -5
- package/src/aiApp.test.ts +207 -1
- package/src/aiApp.ts +31 -8
- package/src/harness/adminScreens.test.ts +34 -0
- package/src/harness/adminScreens.ts +11 -0
- package/src/harness/agentLoop.test.ts +1034 -0
- package/src/harness/agentLoop.ts +1082 -0
- package/src/harness/agentRecovery.test.ts +380 -0
- package/src/harness/agentTaskNames.ts +4 -0
- package/src/harness/approvalPolicy.ts +28 -0
- package/src/harness/approvals.test.ts +1094 -0
- package/src/harness/approvals.ts +644 -0
- package/src/harness/commit.ts +1049 -0
- package/src/harness/conversation.ts +503 -0
- package/src/harness/defineAgent.test.ts +92 -0
- package/src/harness/defineAgent.ts +82 -0
- package/src/harness/defineTask.test.ts +59 -0
- package/src/harness/defineTask.ts +76 -0
- package/src/harness/defineTool.ts +45 -0
- package/src/harness/definitionError.ts +13 -0
- package/src/harness/errors.test.ts +90 -0
- package/src/harness/errors.ts +119 -0
- package/src/harness/eventHub.test.ts +124 -0
- package/src/harness/eventHub.ts +159 -0
- package/src/harness/events.test.ts +757 -0
- package/src/harness/events.ts +384 -0
- package/src/harness/executionEnv.ts +34 -0
- package/src/harness/extensions.test.ts +1218 -0
- package/src/harness/extensions.ts +382 -0
- package/src/harness/harness.test.ts +693 -0
- package/src/harness/harness.ts +767 -0
- package/src/harness/harnessApp.ts +76 -0
- package/src/harness/internalRuntime.ts +44 -0
- package/src/harness/leases.ts +132 -0
- package/src/harness/memo.ts +107 -0
- package/src/harness/modelCall.test.ts +134 -0
- package/src/harness/modelCall.ts +200 -0
- package/src/harness/models/harnessApproval.ts +109 -0
- package/src/harness/models/harnessConversation.ts +142 -0
- package/src/harness/models/harnessEvent.ts +92 -0
- package/src/harness/models/harnessInboxEvent.ts +73 -0
- package/src/harness/models/harnessMemo.ts +43 -0
- package/src/harness/models/harnessMessage.ts +85 -0
- package/src/harness/models/harnessModels.test.ts +60 -0
- package/src/harness/models/harnessOwner.ts +40 -0
- package/src/harness/models/harnessTask.ts +201 -0
- package/src/harness/ownership.test.ts +1087 -0
- package/src/harness/ownership.ts +618 -0
- package/src/harness/recovery.test.ts +912 -0
- package/src/harness/registry.ts +124 -0
- package/src/harness/retries.test.ts +292 -0
- package/src/harness/retryBackoff.test.ts +100 -0
- package/src/harness/retryBackoff.ts +77 -0
- package/src/harness/routes/approvals.ts +123 -0
- package/src/harness/routes/conversations.test.ts +518 -0
- package/src/harness/routes/conversations.ts +102 -0
- package/src/harness/routes/events.ts +280 -0
- package/src/harness/routes/tasks.test.ts +198 -0
- package/src/harness/routes/tasks.ts +146 -0
- package/src/harness/runners/inProcessRunner.test.ts +402 -0
- package/src/harness/runners/inProcessRunner.ts +220 -0
- package/src/harness/runtime.ts +714 -0
- package/src/harness/subagent.test.ts +696 -0
- package/src/harness/subagent.ts +192 -0
- package/src/harness/suspend.ts +13 -0
- package/src/harness/transaction.ts +17 -0
- package/src/harness/versioning.test.ts +288 -0
- package/src/harness/waits.test.ts +693 -0
- package/src/harness/waits.ts +356 -0
- package/src/index.test.ts +13 -0
- package/src/index.ts +70 -0
- package/src/isolated/adminScreensConfig.isolated.ts +143 -0
- package/src/models/aiDataset.test.ts +34 -0
- package/src/models/aiDataset.ts +78 -0
- package/src/models/aiRequest.test.ts +2 -2
- package/src/models/aiRequest.ts +2 -1
- package/src/models/gptHistory.test.ts +156 -0
- package/src/models/gptHistory.ts +106 -4
- package/src/observability/adminScreens.test.ts +71 -0
- package/src/observability/adminScreens.ts +42 -0
- package/src/observability/compileTemplate.test.ts +14 -0
- package/src/observability/compileTemplate.ts +10 -0
- package/src/observability/datasetImport.test.ts +95 -0
- package/src/observability/datasetImport.ts +220 -0
- package/src/observability/evaluate.test.ts +549 -0
- package/src/observability/evaluate.ts +254 -0
- package/src/observability/evaluatorTemplates.ts +124 -0
- package/src/observability/jsonPath.test.ts +52 -0
- package/src/observability/jsonPath.ts +60 -0
- package/src/observability/local/datasetStore.test.ts +230 -0
- package/src/observability/local/datasetStore.ts +452 -0
- package/src/observability/local/evaluatorStore.test.ts +138 -0
- package/src/observability/local/evaluatorStore.ts +224 -0
- package/src/observability/local/experimentRunner.test.ts +489 -0
- package/src/observability/local/experimentRunner.ts +548 -0
- package/src/observability/local/localPlugin.ts +88 -0
- package/src/observability/local/models/obsDataset.ts +38 -0
- package/src/observability/local/models/obsDatasetItem.ts +80 -0
- package/src/observability/local/models/obsEvaluator.ts +102 -0
- package/src/observability/local/models/obsExperiment.ts +91 -0
- package/src/observability/local/models/obsExperimentItem.ts +52 -0
- package/src/observability/local/models/obsPrompt.ts +43 -0
- package/src/observability/local/models/obsPromptLabel.ts +43 -0
- package/src/observability/local/models/obsPromptVersion.ts +107 -0
- package/src/observability/local/models/obsReviewItem.ts +79 -0
- package/src/observability/local/models/obsScore.ts +59 -0
- package/src/observability/local/models/obsSpan.ts +65 -0
- package/src/observability/local/models/obsTrace.ts +94 -0
- package/src/observability/local/obsModels.test.ts +119 -0
- package/src/observability/local/promptStore.test.ts +351 -0
- package/src/observability/local/promptStore.ts +665 -0
- package/src/observability/local/reviewStore.test.ts +164 -0
- package/src/observability/local/reviewStore.ts +264 -0
- package/src/observability/local/traceStore.test.ts +264 -0
- package/src/observability/local/traceStore.ts +440 -0
- package/src/observability/observabilityApp.test.ts +92 -0
- package/src/observability/observabilityApp.ts +185 -0
- package/src/observability/observabilityAppRegistry.test.ts +30 -0
- package/src/observability/observabilityAppRegistry.ts +35 -0
- package/src/observability/permissions.test.ts +96 -0
- package/src/observability/permissions.ts +78 -0
- package/src/observability/reviewPanels.test.ts +35 -0
- package/src/observability/reviewPanels.ts +64 -0
- package/src/observability/routes/datasets.test.ts +176 -0
- package/src/observability/routes/datasets.ts +252 -0
- package/src/observability/routes/evaluators.test.ts +119 -0
- package/src/observability/routes/evaluators.ts +207 -0
- package/src/observability/routes/experiments.test.ts +282 -0
- package/src/observability/routes/experiments.ts +152 -0
- package/src/observability/routes/observabilityRbac.test.ts +767 -0
- package/src/observability/routes/observabilityRouteAccess.ts +106 -0
- package/src/observability/routes/prompts.test.ts +320 -0
- package/src/observability/routes/prompts.ts +263 -0
- package/src/observability/routes/requestAiService.ts +36 -0
- package/src/observability/routes/review.test.ts +120 -0
- package/src/observability/routes/review.ts +125 -0
- package/src/observability/routes/status.test.ts +116 -0
- package/src/observability/routes/status.ts +47 -0
- package/src/observability/routes/testMultiStage.test.ts +214 -0
- package/src/observability/routes/testMultiStage.ts +96 -0
- package/src/observability/routes/traces.test.ts +167 -0
- package/src/observability/routes/traces.ts +172 -0
- package/src/observability/schemaValidation.ts +29 -0
- package/src/observability/sopThresholds.ts +20 -0
- package/src/observability/status.test.ts +38 -0
- package/src/observability/status.ts +56 -0
- package/src/observability/testMultiStageSchemas.ts +95 -0
- package/src/observability/testMultiStageWorkflow.test.ts +114 -0
- package/src/observability/testMultiStageWorkflow.ts +307 -0
- package/src/observability/types.ts +262 -0
- package/src/routes/files.test.ts +84 -9
- package/src/routes/files.ts +23 -7
- package/src/routes/gpt.test.ts +3279 -0
- package/src/routes/gpt.ts +214 -552
- package/src/routes/gptActions.test.ts +241 -0
- package/src/routes/gptActions.ts +255 -0
- package/src/routes/gptApprovals.test.ts +762 -0
- package/src/routes/gptDatasets.test.ts +86 -0
- package/src/routes/gptDatasets.ts +104 -0
- package/src/routes/gptFiles.test.ts +589 -0
- package/src/routes/gptHistories.test.ts +933 -0
- package/src/routes/gptHistories.ts +266 -5
- package/src/routes/routes.test.ts +676 -5
- package/src/service/aiDatasets.test.ts +123 -0
- package/src/service/aiDatasets.ts +316 -0
- package/src/service/aiService.test.ts +614 -0
- package/src/service/aiService.ts +575 -111
- package/src/service/askFiles.test.ts +96 -0
- package/src/service/askFiles.ts +222 -0
- package/src/service/asks.test.ts +946 -0
- package/src/service/asks.ts +423 -0
- package/src/service/chatTurn.ts +2287 -0
- package/src/service/fileStorage.test.ts +11 -0
- package/src/service/fileStorage.ts +10 -2
- package/src/service/fileUploadsGate.ts +23 -0
- package/src/service/fillActionIds.test.ts +65 -0
- package/src/service/fillActionIds.ts +98 -0
- package/src/service/gemini.test.ts +16 -10
- package/src/service/gemini.ts +3 -3
- package/src/service/jsonFenceModel.test.ts +47 -0
- package/src/service/jsonFenceModel.ts +53 -0
- package/src/service/prompts.test.ts +21 -0
- package/src/service/prompts.ts +147 -0
- package/src/service/sanitizeHtml.test.ts +61 -0
- package/src/service/sanitizeHtml.ts +109 -0
- package/src/service/vertex.test.ts +49 -49
- package/src/service/vertex.ts +7 -8
- package/src/tests/bunSetup.test.ts +7 -4
- package/src/tests/bunSetup.ts +7 -7
- package/src/tests/chatHarness.ts +478 -0
- package/src/tests/generateStream.ts +49 -0
- package/src/tests/harnessErrors.ts +22 -0
- package/src/tests/harnessStreaming.ts +227 -0
- package/src/tests/helpers.ts +9 -2
- package/src/types/harness.ts +1095 -0
- package/src/types/index.ts +237 -12
- package/src/types/observability.ts +344 -0
- package/src/types/sanitize-html.d.ts +25 -0
|
@@ -0,0 +1,644 @@
|
|
|
1
|
+
import {
|
|
2
|
+
APIError,
|
|
3
|
+
checkPermissions,
|
|
4
|
+
logger,
|
|
5
|
+
Permissions,
|
|
6
|
+
type RESTMethod,
|
|
7
|
+
type User,
|
|
8
|
+
} from "@terreno/api";
|
|
9
|
+
import {DateTime, type Duration, type DurationLike} from "luxon";
|
|
10
|
+
import mongoose, {type ClientSession} from "mongoose";
|
|
11
|
+
|
|
12
|
+
import type {
|
|
13
|
+
AnyHarnessToolDefinition,
|
|
14
|
+
HarnessApprovalDocument,
|
|
15
|
+
HarnessApprovalOptions,
|
|
16
|
+
HarnessApprovalResult,
|
|
17
|
+
HarnessApprover,
|
|
18
|
+
HarnessDecideApprovalOptions,
|
|
19
|
+
HarnessExtensionDefinition,
|
|
20
|
+
HarnessTaskDefinition,
|
|
21
|
+
HarnessTaskDocument,
|
|
22
|
+
} from "../types/harness";
|
|
23
|
+
import {
|
|
24
|
+
HARNESS_APPROVAL_STATUSES,
|
|
25
|
+
HARNESS_EVENT_TYPES,
|
|
26
|
+
HARNESS_TERMINAL_STATUSES,
|
|
27
|
+
HARNESS_WAIT_KINDS,
|
|
28
|
+
} from "../types/harness";
|
|
29
|
+
import type {HarnessModels} from "./commit";
|
|
30
|
+
import {taskDefinitionKey} from "./defineTask";
|
|
31
|
+
import {HarnessDefinitionError} from "./definitionError";
|
|
32
|
+
import {errorMessage, HARNESS_ERRORS, harnessError} from "./errors";
|
|
33
|
+
import {appendTaskEvents} from "./events";
|
|
34
|
+
import {defineExtension, hook} from "./extensions";
|
|
35
|
+
import {registerHarnessTask} from "./models/harnessTask";
|
|
36
|
+
import {inTransaction} from "./transaction";
|
|
37
|
+
import {
|
|
38
|
+
appendInboxEvent,
|
|
39
|
+
HarnessWaitRaceError,
|
|
40
|
+
parseWaitDuration,
|
|
41
|
+
type WaitCallPlan,
|
|
42
|
+
} from "./waits";
|
|
43
|
+
|
|
44
|
+
/** Event names `harness.sendEvent` refuses: the harness sends these itself. */
|
|
45
|
+
export const HARNESS_RESERVED_EVENT_PREFIX = "terreno.";
|
|
46
|
+
|
|
47
|
+
/** Prefix of the inbox event a decision sends: `terreno.approval:<key>:<step>:<n>`. */
|
|
48
|
+
const APPROVAL_EVENT_PREFIX = `${HARNESS_RESERVED_EVENT_PREFIX}approval`;
|
|
49
|
+
|
|
50
|
+
/** Who may decide an approval whose definition or extension declares no policy for its key. */
|
|
51
|
+
export const HARNESS_DEFAULT_APPROVERS: ReadonlyArray<HarnessApprover> = Object.freeze([
|
|
52
|
+
Permissions.IsAdmin as HarnessApprover,
|
|
53
|
+
]);
|
|
54
|
+
|
|
55
|
+
/** The approval can no longer be decided: already decided, expired, or its task ended. */
|
|
56
|
+
export class HarnessApprovalConflictError extends APIError {
|
|
57
|
+
constructor(detail: string) {
|
|
58
|
+
super({...HARNESS_ERRORS.approvalNotPending, detail});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const toObjectId = (
|
|
63
|
+
id: mongoose.Types.ObjectId | string | undefined
|
|
64
|
+
): mongoose.Types.ObjectId | undefined => {
|
|
65
|
+
if (id === undefined) {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
return typeof id === "string" ? new mongoose.Types.ObjectId(id) : id;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Check `rt.approval(key, options)` arguments; returns the parsed timeout. Misuse throws
|
|
73
|
+
* `HarnessDefinitionError` (fails the task, no retry).
|
|
74
|
+
*/
|
|
75
|
+
export const parseApprovalRequest = ({
|
|
76
|
+
key,
|
|
77
|
+
label,
|
|
78
|
+
options,
|
|
79
|
+
}: {
|
|
80
|
+
key: string;
|
|
81
|
+
label: string;
|
|
82
|
+
options: HarnessApprovalOptions;
|
|
83
|
+
}): Duration | undefined => {
|
|
84
|
+
if (typeof key !== "string" || !key.trim()) {
|
|
85
|
+
throw new HarnessDefinitionError(`${label}: rt.approval requires a key`);
|
|
86
|
+
}
|
|
87
|
+
if (typeof options?.title !== "string" || !options.title.trim()) {
|
|
88
|
+
throw new HarnessDefinitionError(`${label}: rt.approval("${key}") requires a title`);
|
|
89
|
+
}
|
|
90
|
+
if (options.summary !== undefined && typeof options.summary !== "string") {
|
|
91
|
+
throw new HarnessDefinitionError(`${label}: rt.approval("${key}") summary must be a string`);
|
|
92
|
+
}
|
|
93
|
+
if ("approvers" in (options as object)) {
|
|
94
|
+
throw new HarnessDefinitionError(
|
|
95
|
+
`${label}: rt.approval("${key}") does not take approvers; declare them in defineTask({approvals: {"${key}": {approvers}}}) so every process can resolve them`
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
if (options.notify !== undefined && typeof options.notify !== "function") {
|
|
99
|
+
throw new HarnessDefinitionError(`${label}: rt.approval("${key}") notify must be a function`);
|
|
100
|
+
}
|
|
101
|
+
if (options.timeout === undefined) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
const timeout = parseWaitDuration(options.timeout, `${label}: rt.approval("${key}") timeout`);
|
|
105
|
+
if (timeout.toMillis() <= 0) {
|
|
106
|
+
throw new HarnessDefinitionError(`${label}: rt.approval("${key}") timeout must be positive`);
|
|
107
|
+
}
|
|
108
|
+
return timeout;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
type ApprovalDecision = "approved" | "expired" | "rejected";
|
|
112
|
+
|
|
113
|
+
/** The `approval:<key>` CHAIN span recording a decision or an expiry. */
|
|
114
|
+
const createApprovalSpan = async ({
|
|
115
|
+
approval,
|
|
116
|
+
decidedBy,
|
|
117
|
+
decision,
|
|
118
|
+
endedAt,
|
|
119
|
+
models,
|
|
120
|
+
reason,
|
|
121
|
+
session,
|
|
122
|
+
task,
|
|
123
|
+
traceStartedAt,
|
|
124
|
+
}: {
|
|
125
|
+
approval: HarnessApprovalDocument;
|
|
126
|
+
decidedBy?: string;
|
|
127
|
+
decision: ApprovalDecision;
|
|
128
|
+
endedAt: DateTime;
|
|
129
|
+
models: HarnessModels;
|
|
130
|
+
reason?: string;
|
|
131
|
+
session: ClientSession;
|
|
132
|
+
task: HarnessTaskDocument;
|
|
133
|
+
traceStartedAt: DateTime;
|
|
134
|
+
}): Promise<void> => {
|
|
135
|
+
const startedAt = DateTime.fromJSDate(approval.created);
|
|
136
|
+
await models.span.create(
|
|
137
|
+
[
|
|
138
|
+
{
|
|
139
|
+
durationMs: endedAt.diff(startedAt).toMillis(),
|
|
140
|
+
endedAt: endedAt.toJSDate(),
|
|
141
|
+
input: {
|
|
142
|
+
approvalId: String(approval._id),
|
|
143
|
+
definitionKey: approval.definitionKey,
|
|
144
|
+
title: approval.title,
|
|
145
|
+
},
|
|
146
|
+
kind: "CHAIN",
|
|
147
|
+
name: `approval:${approval.key}`,
|
|
148
|
+
output: {
|
|
149
|
+
decision,
|
|
150
|
+
...(decidedBy === undefined ? {} : {decidedBy}),
|
|
151
|
+
...(reason === undefined ? {} : {reason}),
|
|
152
|
+
},
|
|
153
|
+
parentSpanId: task.rootSpanId,
|
|
154
|
+
startedAt: startedAt.toJSDate(),
|
|
155
|
+
startOffsetMs: startedAt.diff(traceStartedAt).toMillis(),
|
|
156
|
+
status: "ok",
|
|
157
|
+
traceId: task.traceId,
|
|
158
|
+
},
|
|
159
|
+
],
|
|
160
|
+
{session}
|
|
161
|
+
);
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
/** What `rt.approval` returns for a settled approval. */
|
|
165
|
+
const approvalResult = (approval: HarnessApprovalDocument): HarnessApprovalResult => {
|
|
166
|
+
const approvalId = String(approval._id);
|
|
167
|
+
if (approval.status === HARNESS_APPROVAL_STATUSES.expired) {
|
|
168
|
+
return {approvalId, approved: false, expired: true};
|
|
169
|
+
}
|
|
170
|
+
if (approval.status === HARNESS_APPROVAL_STATUSES.pending) {
|
|
171
|
+
// Only a decision may wake an approval wait; a hand-sent event must not approve.
|
|
172
|
+
throw harnessError({
|
|
173
|
+
detail: `Approval ${approvalId} received its event without a recorded decision`,
|
|
174
|
+
kind: "internal",
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const result: HarnessApprovalResult = {
|
|
178
|
+
approvalId,
|
|
179
|
+
approved: approval.status === HARNESS_APPROVAL_STATUSES.approved,
|
|
180
|
+
};
|
|
181
|
+
const decidedAt = approval.decidedAt ? DateTime.fromJSDate(approval.decidedAt).toISO() : null;
|
|
182
|
+
if (decidedAt) {
|
|
183
|
+
result.decidedAt = decidedAt;
|
|
184
|
+
}
|
|
185
|
+
if (approval.decidedBy) {
|
|
186
|
+
result.decidedBy = String(approval.decidedBy);
|
|
187
|
+
}
|
|
188
|
+
if (approval.reason !== undefined) {
|
|
189
|
+
result.reason = approval.reason;
|
|
190
|
+
}
|
|
191
|
+
return result;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/** One `rt.approval` call as a wait, plus how to read its result once it resolves. */
|
|
195
|
+
export interface ApprovalWaitPlan extends WaitCallPlan {
|
|
196
|
+
result: () => Promise<HarnessApprovalResult>;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Build the wait behind one `rt.approval` call. Parking upserts the `HarnessApproval`
|
|
201
|
+
* (unique per task and call key) in the waiting commit, so a re-run of the phase visit
|
|
202
|
+
* finds the same approval. A decision sends the approval's own event; a timeout marks
|
|
203
|
+
* it `expired` and writes its span in the timeout's transaction.
|
|
204
|
+
*/
|
|
205
|
+
/** What `approval.*` events carry: enough to render the request and its decision. */
|
|
206
|
+
const approvalEventPayload = (approval: HarnessApprovalDocument): Record<string, unknown> => ({
|
|
207
|
+
approvalId: String(approval._id),
|
|
208
|
+
decidedAt: approval.decidedAt?.toISOString(),
|
|
209
|
+
decidedBy: approval.decidedBy ? String(approval.decidedBy) : undefined,
|
|
210
|
+
expiresAt: approval.expiresAt?.toISOString(),
|
|
211
|
+
key: approval.key,
|
|
212
|
+
reason: approval.reason,
|
|
213
|
+
status: approval.status,
|
|
214
|
+
summary: approval.summary,
|
|
215
|
+
taskId: String(approval.taskId),
|
|
216
|
+
title: approval.title,
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
export const approvalWaitPlan = ({
|
|
220
|
+
callKey,
|
|
221
|
+
extension,
|
|
222
|
+
key,
|
|
223
|
+
models,
|
|
224
|
+
options,
|
|
225
|
+
task,
|
|
226
|
+
timeout,
|
|
227
|
+
}: {
|
|
228
|
+
callKey: string;
|
|
229
|
+
extension?: string;
|
|
230
|
+
key: string;
|
|
231
|
+
models: HarnessModels;
|
|
232
|
+
options: HarnessApprovalOptions;
|
|
233
|
+
task: HarnessTaskDocument;
|
|
234
|
+
timeout?: Duration;
|
|
235
|
+
}): ApprovalWaitPlan => {
|
|
236
|
+
const filter = {callKey, taskId: task._id};
|
|
237
|
+
let isInserted = false;
|
|
238
|
+
return {
|
|
239
|
+
afterPark: async () => {
|
|
240
|
+
if (!isInserted || !options.notify) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
await options.notify(await models.approval.findExactlyOne(filter));
|
|
245
|
+
} catch (error: unknown) {
|
|
246
|
+
logger.error(
|
|
247
|
+
`Harness approval "${key}" of task ${task._id}: notify failed: ${errorMessage(error)}`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
onPark: async ({session, task: parked}) => {
|
|
252
|
+
const now = DateTime.now().toJSDate();
|
|
253
|
+
const written = await models.approval.updateOne(
|
|
254
|
+
filter,
|
|
255
|
+
{
|
|
256
|
+
// createdUpdatedPlugin's updateOne hook sets `updated`.
|
|
257
|
+
$setOnInsert: {
|
|
258
|
+
callKey,
|
|
259
|
+
created: now,
|
|
260
|
+
definitionKey: `${taskDefinitionKey(task)}:${key}`,
|
|
261
|
+
event: `${APPROVAL_EVENT_PREFIX}:${key}:${callKey}`,
|
|
262
|
+
expiresAt: parked.waits?.[callKey]?.timeoutAt,
|
|
263
|
+
...(extension === undefined ? {} : {extension}),
|
|
264
|
+
key,
|
|
265
|
+
payload: options.payload,
|
|
266
|
+
rootTaskId: task.rootTaskId,
|
|
267
|
+
status: HARNESS_APPROVAL_STATUSES.pending,
|
|
268
|
+
...(options.summary === undefined ? {} : {summary: options.summary}),
|
|
269
|
+
taskId: task._id,
|
|
270
|
+
title: options.title,
|
|
271
|
+
traceId: task.traceId,
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
{session, upsert: true}
|
|
275
|
+
);
|
|
276
|
+
isInserted = written.upsertedCount > 0;
|
|
277
|
+
if (isInserted) {
|
|
278
|
+
const [approval] = await models.approval.find(filter, null, {session});
|
|
279
|
+
await appendTaskEvents({
|
|
280
|
+
events: [
|
|
281
|
+
{
|
|
282
|
+
payload: approval ? approvalEventPayload(approval) : {key},
|
|
283
|
+
type: HARNESS_EVENT_TYPES.approvalRequested,
|
|
284
|
+
},
|
|
285
|
+
],
|
|
286
|
+
models,
|
|
287
|
+
session,
|
|
288
|
+
task,
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
request: {
|
|
293
|
+
duration: timeout,
|
|
294
|
+
event: `${APPROVAL_EVENT_PREFIX}:${key}:${callKey}`,
|
|
295
|
+
kind: HARNESS_WAIT_KINDS.event,
|
|
296
|
+
timeoutWrites: async ({session, task: current, traceStartedAt}) => {
|
|
297
|
+
const expired = await models.approval.findOneAndUpdate(
|
|
298
|
+
{...filter, status: HARNESS_APPROVAL_STATUSES.pending},
|
|
299
|
+
{
|
|
300
|
+
$set: {
|
|
301
|
+
status: HARNESS_APPROVAL_STATUSES.expired,
|
|
302
|
+
updated: DateTime.now().toJSDate(),
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
{returnDocument: "after", session}
|
|
306
|
+
);
|
|
307
|
+
if (!expired) {
|
|
308
|
+
// A decision committed first; its event is in the inbox.
|
|
309
|
+
throw new HarnessWaitRaceError();
|
|
310
|
+
}
|
|
311
|
+
await appendTaskEvents({
|
|
312
|
+
events: [
|
|
313
|
+
{payload: approvalEventPayload(expired), type: HARNESS_EVENT_TYPES.approvalDecided},
|
|
314
|
+
],
|
|
315
|
+
models,
|
|
316
|
+
session,
|
|
317
|
+
task: current,
|
|
318
|
+
});
|
|
319
|
+
await createApprovalSpan({
|
|
320
|
+
approval: expired,
|
|
321
|
+
decision: "expired",
|
|
322
|
+
endedAt: DateTime.now(),
|
|
323
|
+
models,
|
|
324
|
+
session,
|
|
325
|
+
task: current,
|
|
326
|
+
traceStartedAt,
|
|
327
|
+
});
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
result: async () => approvalResult(await models.approval.findExactlyOne(filter)),
|
|
331
|
+
};
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
/** Where approvers are looked up: the registry of the process serving the request. */
|
|
335
|
+
export interface ApprovalRegistry {
|
|
336
|
+
definitions: Map<string, HarnessTaskDefinition>;
|
|
337
|
+
extensions: Map<string, HarnessExtensionDefinition>;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* The approvers of `approval`, from the extension that requested it or else its task
|
|
342
|
+
* definition (`name@version`). A registered owner without a policy for the key gets
|
|
343
|
+
* `HARNESS_DEFAULT_APPROVERS`; an owner this registry lacks gets `undefined` (nobody).
|
|
344
|
+
*/
|
|
345
|
+
const resolveApprovers = ({
|
|
346
|
+
approval,
|
|
347
|
+
registry,
|
|
348
|
+
}: {
|
|
349
|
+
approval: HarnessApprovalDocument;
|
|
350
|
+
registry: ApprovalRegistry;
|
|
351
|
+
}): ReadonlyArray<HarnessApprover> | undefined => {
|
|
352
|
+
if (approval.extension !== undefined) {
|
|
353
|
+
const extension = registry.extensions.get(approval.extension);
|
|
354
|
+
if (!extension) {
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
return extension.approvals[approval.key]?.approvers ?? HARNESS_DEFAULT_APPROVERS;
|
|
358
|
+
}
|
|
359
|
+
const suffix = `:${approval.key}`;
|
|
360
|
+
if (!approval.definitionKey.endsWith(suffix)) {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
const definition = registry.definitions.get(approval.definitionKey.slice(0, -suffix.length));
|
|
364
|
+
if (!definition) {
|
|
365
|
+
return undefined;
|
|
366
|
+
}
|
|
367
|
+
return definition.approvals?.[approval.key]?.approvers ?? HARNESS_DEFAULT_APPROVERS;
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Whether `user` passes every approver of `approval` (AND, like modelRouter). Fails
|
|
372
|
+
* closed: no approvers resolved, an empty list, or an approver that throws all deny.
|
|
373
|
+
*/
|
|
374
|
+
export const userMayApprove = async ({
|
|
375
|
+
approval,
|
|
376
|
+
method,
|
|
377
|
+
registry,
|
|
378
|
+
user,
|
|
379
|
+
}: {
|
|
380
|
+
approval: HarnessApprovalDocument;
|
|
381
|
+
method: RESTMethod;
|
|
382
|
+
registry: ApprovalRegistry;
|
|
383
|
+
user?: User;
|
|
384
|
+
}): Promise<boolean> => {
|
|
385
|
+
const approvers = resolveApprovers({approval, registry});
|
|
386
|
+
if (!approvers || approvers.length === 0) {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
return await checkPermissions(method, [...approvers], user, approval);
|
|
391
|
+
} catch (error: unknown) {
|
|
392
|
+
logger.warn(
|
|
393
|
+
`Harness approval ${approval._id}: an approver threw; denying: ${errorMessage(error)}`
|
|
394
|
+
);
|
|
395
|
+
return false;
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const isOpenFilter = (now: Date): Record<string, unknown> => ({
|
|
400
|
+
$or: [{expiresAt: {$exists: false}}, {expiresAt: null}, {expiresAt: {$gt: now}}],
|
|
401
|
+
status: HARNESS_APPROVAL_STATUSES.pending,
|
|
402
|
+
});
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Pending, unexpired approvals of live tasks that `user` may approve, oldest first. Every
|
|
406
|
+
* open approval is checked in memory (open sets are small) with `method: "update"`, the
|
|
407
|
+
* method approve / reject use, so the inbox never lists what the caller cannot decide.
|
|
408
|
+
*/
|
|
409
|
+
export const listApprovableApprovals = async ({
|
|
410
|
+
models,
|
|
411
|
+
registry,
|
|
412
|
+
user,
|
|
413
|
+
}: {
|
|
414
|
+
models: HarnessModels;
|
|
415
|
+
registry: ApprovalRegistry;
|
|
416
|
+
user?: User;
|
|
417
|
+
}): Promise<HarnessApprovalDocument[]> => {
|
|
418
|
+
const open = await models.approval
|
|
419
|
+
.find(isOpenFilter(DateTime.now().toJSDate()))
|
|
420
|
+
.sort({_id: 1, created: 1});
|
|
421
|
+
if (open.length === 0) {
|
|
422
|
+
return [];
|
|
423
|
+
}
|
|
424
|
+
const liveTasks = await models.task
|
|
425
|
+
.find(
|
|
426
|
+
{
|
|
427
|
+
_id: {$in: [...new Set(open.map((approval) => String(approval.taskId)))]},
|
|
428
|
+
status: {$nin: [...HARNESS_TERMINAL_STATUSES]},
|
|
429
|
+
},
|
|
430
|
+
{_id: 1}
|
|
431
|
+
)
|
|
432
|
+
.lean();
|
|
433
|
+
const live = new Set(liveTasks.map((task) => String(task._id)));
|
|
434
|
+
const approvable: HarnessApprovalDocument[] = [];
|
|
435
|
+
for (const approval of open) {
|
|
436
|
+
if (!live.has(String(approval.taskId))) {
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (await userMayApprove({approval, method: "update", registry, user})) {
|
|
440
|
+
approvable.push(approval);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
return approvable;
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Decide a pending approval: in one transaction, set its status, `decidedBy`, `decidedAt`,
|
|
448
|
+
* and `reason`, send its event to the waiting task (waking it), and write the
|
|
449
|
+
* `approval:<key>` span. Throws `HarnessApprovalConflictError` when it is no longer
|
|
450
|
+
* pending, has expired, or its task ended. Does not check approvers.
|
|
451
|
+
*/
|
|
452
|
+
export const decideApprovalRecords = async ({
|
|
453
|
+
approvalId,
|
|
454
|
+
models,
|
|
455
|
+
options,
|
|
456
|
+
}: {
|
|
457
|
+
approvalId: mongoose.Types.ObjectId | string;
|
|
458
|
+
models: HarnessModels;
|
|
459
|
+
options: HarnessDecideApprovalOptions;
|
|
460
|
+
}): Promise<{approval: HarnessApprovalDocument; isWoken: boolean}> => {
|
|
461
|
+
const approval = await models.approval.findExactlyOne({_id: approvalId});
|
|
462
|
+
const now = DateTime.now();
|
|
463
|
+
const notDecidable = (why: string): HarnessApprovalConflictError =>
|
|
464
|
+
new HarnessApprovalConflictError(`Approval ${approvalId} ${why}`);
|
|
465
|
+
if (approval.status !== HARNESS_APPROVAL_STATUSES.pending) {
|
|
466
|
+
throw notDecidable(`is already ${approval.status}`);
|
|
467
|
+
}
|
|
468
|
+
if (approval.expiresAt && DateTime.fromJSDate(approval.expiresAt) <= now) {
|
|
469
|
+
throw notDecidable("has expired");
|
|
470
|
+
}
|
|
471
|
+
const task = await models.task.findExactlyOne({_id: approval.taskId});
|
|
472
|
+
if (HARNESS_TERMINAL_STATUSES.has(task.status)) {
|
|
473
|
+
throw notDecidable(`belongs to a task that is already ${task.status}`);
|
|
474
|
+
}
|
|
475
|
+
const trace = await models.trace.findExactlyOne({_id: task.traceId});
|
|
476
|
+
const status = options.approved
|
|
477
|
+
? HARNESS_APPROVAL_STATUSES.approved
|
|
478
|
+
: HARNESS_APPROVAL_STATUSES.rejected;
|
|
479
|
+
const decidedBy = toObjectId(options.userId);
|
|
480
|
+
const reason = options.reason?.trim() ? options.reason.trim() : undefined;
|
|
481
|
+
|
|
482
|
+
try {
|
|
483
|
+
return await inTransaction(async (session) => {
|
|
484
|
+
const decided = await models.approval.findOneAndUpdate(
|
|
485
|
+
{_id: approval._id, ...isOpenFilter(now.toJSDate())},
|
|
486
|
+
{
|
|
487
|
+
$set: {
|
|
488
|
+
decidedAt: now.toJSDate(),
|
|
489
|
+
status,
|
|
490
|
+
updated: now.toJSDate(),
|
|
491
|
+
...(decidedBy ? {decidedBy} : {}),
|
|
492
|
+
...(reason === undefined ? {} : {reason}),
|
|
493
|
+
},
|
|
494
|
+
},
|
|
495
|
+
{returnDocument: "after", session}
|
|
496
|
+
);
|
|
497
|
+
if (!decided) {
|
|
498
|
+
throw notDecidable("is no longer pending");
|
|
499
|
+
}
|
|
500
|
+
await appendTaskEvents({
|
|
501
|
+
events: [
|
|
502
|
+
{payload: approvalEventPayload(decided), type: HARNESS_EVENT_TYPES.approvalDecided},
|
|
503
|
+
],
|
|
504
|
+
models,
|
|
505
|
+
session,
|
|
506
|
+
task,
|
|
507
|
+
});
|
|
508
|
+
const sent = await appendInboxEvent({
|
|
509
|
+
event: approval.event,
|
|
510
|
+
models,
|
|
511
|
+
payload: {
|
|
512
|
+
approvalId: String(approval._id),
|
|
513
|
+
approved: options.approved,
|
|
514
|
+
decidedAt: now.toISO(),
|
|
515
|
+
...(decidedBy ? {decidedBy: String(decidedBy)} : {}),
|
|
516
|
+
...(reason === undefined ? {} : {reason}),
|
|
517
|
+
},
|
|
518
|
+
session,
|
|
519
|
+
taskId: task._id,
|
|
520
|
+
});
|
|
521
|
+
await createApprovalSpan({
|
|
522
|
+
approval: decided,
|
|
523
|
+
decidedBy: decidedBy ? String(decidedBy) : undefined,
|
|
524
|
+
decision: status,
|
|
525
|
+
endedAt: now,
|
|
526
|
+
models,
|
|
527
|
+
reason,
|
|
528
|
+
session,
|
|
529
|
+
task,
|
|
530
|
+
traceStartedAt: DateTime.fromJSDate(trace.startedAt),
|
|
531
|
+
});
|
|
532
|
+
return {approval: decided, isWoken: sent.isWoken};
|
|
533
|
+
});
|
|
534
|
+
} catch (error: unknown) {
|
|
535
|
+
if (error instanceof HarnessApprovalConflictError) {
|
|
536
|
+
throw error;
|
|
537
|
+
}
|
|
538
|
+
// The task finished between the check above and the transaction.
|
|
539
|
+
const current = await models.task.findExactlyOne({_id: task._id});
|
|
540
|
+
if (HARNESS_TERMINAL_STATUSES.has(current.status)) {
|
|
541
|
+
throw notDecidable(`belongs to a task that is already ${current.status}`);
|
|
542
|
+
}
|
|
543
|
+
throw error;
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
/** The input of the task that requested `approval`, for approver checks that need it. */
|
|
548
|
+
export const approvalTaskInput = async <In = unknown>(
|
|
549
|
+
approval: Pick<HarnessApprovalDocument, "taskId">
|
|
550
|
+
): Promise<In> => {
|
|
551
|
+
const task = await registerHarnessTask().findExactlyOne({_id: approval.taskId});
|
|
552
|
+
return task.input as In;
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
/** A gate's stored decision for one tool call, kept in the turn's memo. */
|
|
556
|
+
interface GateDecision {
|
|
557
|
+
approved: boolean;
|
|
558
|
+
decidedBy?: string;
|
|
559
|
+
expired?: boolean;
|
|
560
|
+
reason?: string;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
export interface ApprovalGateOptions {
|
|
564
|
+
/** Who may approve calls of these tools. Default `[Permissions.IsAdmin]`. */
|
|
565
|
+
approvers?: ReadonlyArray<HarnessApprover>;
|
|
566
|
+
/** Extension name; default `approvalGate:<tool names, comma-separated>`. */
|
|
567
|
+
name?: string;
|
|
568
|
+
/** Called once per approval after it is stored (see `rt.approval`). */
|
|
569
|
+
notify?: HarnessApprovalOptions["notify"];
|
|
570
|
+
/** Expire the approval (blocking the call) when nobody decides within this long. */
|
|
571
|
+
timeout?: DurationLike;
|
|
572
|
+
/** Approval title; default `Run tool "<name>"`. */
|
|
573
|
+
title?: string | ((call: {args: unknown; toolName: string}) => string);
|
|
574
|
+
/** Tools (or tool names) that need an approval before each call. */
|
|
575
|
+
tools: ReadonlyArray<AnyHarnessToolDefinition | string>;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* An extension whose `beforeTool` hook requires a human approval before each call of the
|
|
580
|
+
* named tools. The approval's key is the tool name and its payload `{toolName, toolCallId,
|
|
581
|
+
* args}`. The decision is memoized by `toolCallId` in the turn, so it survives restarts and
|
|
582
|
+
* re-runs of the call. A rejection or expiry blocks the call; the reason reaches the model.
|
|
583
|
+
*/
|
|
584
|
+
export const approvalGate = (options: ApprovalGateOptions): HarnessExtensionDefinition => {
|
|
585
|
+
if (!Array.isArray(options?.tools) || options.tools.length === 0) {
|
|
586
|
+
throw new HarnessDefinitionError("approvalGate: tools must list at least one tool");
|
|
587
|
+
}
|
|
588
|
+
const toolNames = options.tools.map((tool) => (typeof tool === "string" ? tool : tool?.name));
|
|
589
|
+
if (toolNames.some((name) => typeof name !== "string" || !name.trim())) {
|
|
590
|
+
throw new HarnessDefinitionError(
|
|
591
|
+
"approvalGate: every tool must be a defineTool tool or a tool name"
|
|
592
|
+
);
|
|
593
|
+
}
|
|
594
|
+
const gated = new Set(toolNames);
|
|
595
|
+
const name = options.name ?? `approvalGate:${toolNames.join(",")}`;
|
|
596
|
+
const approvers = options.approvers ?? HARNESS_DEFAULT_APPROVERS;
|
|
597
|
+
if (options.title !== undefined && !["function", "string"].includes(typeof options.title)) {
|
|
598
|
+
throw new HarnessDefinitionError(`approvalGate(${name}): title must be a string or a function`);
|
|
599
|
+
}
|
|
600
|
+
if (options.timeout !== undefined) {
|
|
601
|
+
parseWaitDuration(options.timeout, `approvalGate(${name}): timeout`);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
return defineExtension({
|
|
605
|
+
approvals: Object.fromEntries([...gated].map((toolName) => [toolName, {approvers}])),
|
|
606
|
+
hooks: [
|
|
607
|
+
hook("beforeTool", async (call, api) => {
|
|
608
|
+
if (!gated.has(call.toolName)) {
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
const memoKey = `approvalGate:${name}:${call.toolCallId}`;
|
|
612
|
+
let decision = await api.memo<GateDecision>(memoKey);
|
|
613
|
+
if (!decision) {
|
|
614
|
+
const title =
|
|
615
|
+
typeof options.title === "function"
|
|
616
|
+
? options.title({args: call.args, toolName: call.toolName})
|
|
617
|
+
: (options.title ?? `Run tool "${call.toolName}"`);
|
|
618
|
+
const result = await api.approval(call.toolName, {
|
|
619
|
+
notify: options.notify,
|
|
620
|
+
payload: {args: call.args, toolCallId: call.toolCallId, toolName: call.toolName},
|
|
621
|
+
timeout: options.timeout,
|
|
622
|
+
title,
|
|
623
|
+
});
|
|
624
|
+
decision = await api.memo<GateDecision>(memoKey, {
|
|
625
|
+
approved: result.approved,
|
|
626
|
+
...(result.decidedBy === undefined ? {} : {decidedBy: result.decidedBy}),
|
|
627
|
+
...(result.expired ? {expired: true} : {}),
|
|
628
|
+
...(result.reason === undefined ? {} : {reason: result.reason}),
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
if (decision.approved) {
|
|
632
|
+
return undefined;
|
|
633
|
+
}
|
|
634
|
+
if (decision.expired) {
|
|
635
|
+
return {block: `Approval to run "${call.toolName}" expired before anyone decided`};
|
|
636
|
+
}
|
|
637
|
+
return {
|
|
638
|
+
block: `Approval to run "${call.toolName}" was rejected: ${decision.reason ?? "no reason given"}`,
|
|
639
|
+
};
|
|
640
|
+
}),
|
|
641
|
+
],
|
|
642
|
+
name,
|
|
643
|
+
});
|
|
644
|
+
};
|