@terreno/ai 57.9.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/README.md +1 -0
- package/bunfig.toml +1 -1
- package/dist/aiApp.d.ts +8 -2
- package/dist/aiApp.js +12 -6
- 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 +73 -0
- 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 +18 -7
- package/dist/routes/gpt.js +79 -689
- 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 +426 -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/fillActionIds.d.ts +6 -0
- package/dist/service/fillActionIds.js +79 -0
- 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/types/harness.d.ts +934 -0
- package/dist/types/harness.js +133 -0
- package/dist/types/index.d.ts +192 -14
- 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 +19 -6
- 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.ts +2 -1
- package/src/models/gptHistory.test.ts +156 -0
- package/src/models/gptHistory.ts +89 -1
- 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 +63 -9
- package/src/routes/files.ts +21 -7
- package/src/routes/gpt.test.ts +3279 -0
- package/src/routes/gpt.ts +91 -816
- 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 +222 -2
- package/src/service/aiDatasets.test.ts +123 -0
- package/src/service/aiDatasets.ts +316 -0
- package/src/service/aiService.test.ts +593 -0
- package/src/service/aiService.ts +568 -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/fillActionIds.test.ts +65 -0
- package/src/service/fillActionIds.ts +98 -0
- 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/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 +209 -13
- package/src/types/observability.ts +344 -0
- package/src/types/sanitize-html.d.ts +25 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.assertValidBasePath = exports.addHarnessApprovalRoutes = void 0;
|
|
4
|
+
const api_1 = require("@terreno/api");
|
|
5
|
+
const harness_1 = require("../../types/harness");
|
|
6
|
+
const errors_1 = require("../errors");
|
|
7
|
+
const harnessApproval_1 = require("../models/harnessApproval");
|
|
8
|
+
const approveBody = api_1.z
|
|
9
|
+
.object({ reason: api_1.z.string().trim().min(1).optional() })
|
|
10
|
+
.strict()
|
|
11
|
+
.describe("Optional reason recorded with the approval");
|
|
12
|
+
const rejectBody = api_1.z
|
|
13
|
+
.object({ reason: api_1.z.string().trim().min(1) })
|
|
14
|
+
.strict()
|
|
15
|
+
.describe("Why the approval is rejected; required");
|
|
16
|
+
/**
|
|
17
|
+
* Mount `/harness/approvals` on `router`: list and read the approvals the caller may
|
|
18
|
+
* decide, and `approve` / `reject` instance actions. Approvers come from `harness`'s
|
|
19
|
+
* registry at request time.
|
|
20
|
+
*/
|
|
21
|
+
const addHarnessApprovalRoutes = (router, { basePath, harness, openApi }) => {
|
|
22
|
+
const model = (0, harnessApproval_1.registerHarnessApproval)();
|
|
23
|
+
// Without a document (the pre-check) defer to the document check, like IsOwner.
|
|
24
|
+
const canApprove = (method, user, approval) => approval ? harness.mayApprove({ approval, method, user }) : true;
|
|
25
|
+
const decide = (approved) => async ({ body, doc, user, }) => {
|
|
26
|
+
// HarnessApprovalConflictError is already a 409 APIError.
|
|
27
|
+
return harness.decideApproval(doc._id, {
|
|
28
|
+
approved,
|
|
29
|
+
// Validated by the action's zod body schema.
|
|
30
|
+
reason: body?.reason,
|
|
31
|
+
userId: user?.id,
|
|
32
|
+
});
|
|
33
|
+
};
|
|
34
|
+
router.use(`${basePath}/approvals`, (0, api_1.modelRouter)(model, {
|
|
35
|
+
...(openApi
|
|
36
|
+
? { openApi: openApi }
|
|
37
|
+
: {}),
|
|
38
|
+
instanceActions: {
|
|
39
|
+
approve: {
|
|
40
|
+
body: approveBody,
|
|
41
|
+
description: "Approve a pending approval; wakes the task waiting on it.",
|
|
42
|
+
handler: decide(true),
|
|
43
|
+
method: "POST",
|
|
44
|
+
permissions: [api_1.Permissions.IsAuthenticated, canApprove],
|
|
45
|
+
summary: "Approve a harness approval",
|
|
46
|
+
tag: "harness",
|
|
47
|
+
},
|
|
48
|
+
reject: {
|
|
49
|
+
body: rejectBody,
|
|
50
|
+
description: "Reject a pending approval with a reason; wakes the task waiting on it.",
|
|
51
|
+
handler: decide(false),
|
|
52
|
+
method: "POST",
|
|
53
|
+
permissions: [api_1.Permissions.IsAuthenticated, canApprove],
|
|
54
|
+
summary: "Reject a harness approval",
|
|
55
|
+
tag: "harness",
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
permissions: {
|
|
59
|
+
create: [],
|
|
60
|
+
delete: [],
|
|
61
|
+
list: [api_1.Permissions.IsAuthenticated],
|
|
62
|
+
read: [api_1.Permissions.IsAuthenticated, canApprove],
|
|
63
|
+
update: [],
|
|
64
|
+
},
|
|
65
|
+
queryFields: ["rootTaskId", "taskId"],
|
|
66
|
+
// Approvers are code, so the inbox is filtered in memory; pagination runs after it.
|
|
67
|
+
queryFilter: async (user) => {
|
|
68
|
+
if (!user) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const approvable = await harness.approvableApprovals({ user });
|
|
72
|
+
if (approvable.length === 0) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
_id: { $in: approvable.map((approval) => approval._id) },
|
|
77
|
+
status: harness_1.HARNESS_APPROVAL_STATUSES.pending,
|
|
78
|
+
};
|
|
79
|
+
},
|
|
80
|
+
sort: "created _id",
|
|
81
|
+
}));
|
|
82
|
+
};
|
|
83
|
+
exports.addHarnessApprovalRoutes = addHarnessApprovalRoutes;
|
|
84
|
+
const assertValidBasePath = (basePath) => {
|
|
85
|
+
if (!basePath.startsWith("/") || basePath.endsWith("/")) {
|
|
86
|
+
throw (0, errors_1.harnessError)({
|
|
87
|
+
detail: `HarnessApp basePath must start with "/" and not end with "/": "${basePath}"`,
|
|
88
|
+
kind: "configInvalid",
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return basePath;
|
|
92
|
+
};
|
|
93
|
+
exports.assertValidBasePath = assertValidBasePath;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import type { Harness } from "../harness";
|
|
3
|
+
/**
|
|
4
|
+
* Mount `{basePath}/conversations`: read (owner or admin), list your own, and the
|
|
5
|
+
* `submit` instance action (owner only: messages are sent as the conversation's user).
|
|
6
|
+
*/
|
|
7
|
+
export declare const addHarnessConversationRoutes: (router: express.Application, { basePath, harness, openApi }: {
|
|
8
|
+
basePath: string;
|
|
9
|
+
harness: Harness;
|
|
10
|
+
openApi?: unknown;
|
|
11
|
+
}) => void;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.addHarnessConversationRoutes = void 0;
|
|
4
|
+
const api_1 = require("@terreno/api");
|
|
5
|
+
const harness_1 = require("../../types/harness");
|
|
6
|
+
const harnessConversation_1 = require("../models/harnessConversation");
|
|
7
|
+
const events_1 = require("./events");
|
|
8
|
+
const submitBody = api_1.z
|
|
9
|
+
.object({
|
|
10
|
+
content: api_1.z.string().trim().min(1),
|
|
11
|
+
requestId: api_1.z.string().trim().min(1),
|
|
12
|
+
whenBusy: api_1.z
|
|
13
|
+
.enum([harness_1.HARNESS_WHEN_BUSY.queue, harness_1.HARNESS_WHEN_BUSY.steer])
|
|
14
|
+
.default(harness_1.HARNESS_WHEN_BUSY.queue),
|
|
15
|
+
})
|
|
16
|
+
.strict()
|
|
17
|
+
.describe("A user message. requestId makes the submit idempotent; whenBusy (default queue) says what happens while a turn runs");
|
|
18
|
+
// Without a document (the pre-check) defer to the document check, like IsOwner.
|
|
19
|
+
const ownerOrAdmin = (_method, user, conversation) => (conversation ? (0, events_1.isOwnerOrAdmin)(user, conversation) : true);
|
|
20
|
+
const ownerOnly = (_method, user, conversation) => {
|
|
21
|
+
if (!conversation) {
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
24
|
+
return Boolean(user && conversation.userId && String(conversation.userId) === String(user.id ?? user._id));
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Mount `{basePath}/conversations`: read (owner or admin), list your own, and the
|
|
28
|
+
* `submit` instance action (owner only: messages are sent as the conversation's user).
|
|
29
|
+
*/
|
|
30
|
+
const addHarnessConversationRoutes = (router, { basePath, harness, openApi }) => {
|
|
31
|
+
const model = (0, harnessConversation_1.registerHarnessConversation)();
|
|
32
|
+
const submit = async ({ body, doc, }) => {
|
|
33
|
+
// Validated by the action's zod body schema.
|
|
34
|
+
const { content, requestId, whenBusy } = body;
|
|
35
|
+
// HarnessConversationOwnedError is already a 409 APIError.
|
|
36
|
+
const conversation = await harness.conversation(doc._id);
|
|
37
|
+
return conversation.send({ content, requestId, whenBusy });
|
|
38
|
+
};
|
|
39
|
+
router.use(`${basePath}/conversations`, (0, api_1.modelRouter)(model, {
|
|
40
|
+
...(openApi
|
|
41
|
+
? { openApi: openApi }
|
|
42
|
+
: {}),
|
|
43
|
+
instanceActions: {
|
|
44
|
+
submit: {
|
|
45
|
+
body: submitBody,
|
|
46
|
+
description: "Send a user message. Idle: starts a turn. Busy: queue runs it as a later turn; steer adds it to the active turn's next model request. Idempotent on requestId.",
|
|
47
|
+
handler: submit,
|
|
48
|
+
method: "POST",
|
|
49
|
+
permissions: [api_1.Permissions.IsAuthenticated, ownerOnly],
|
|
50
|
+
summary: "Submit a message to a harness conversation",
|
|
51
|
+
tag: "harness",
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
permissions: {
|
|
55
|
+
create: [],
|
|
56
|
+
delete: [],
|
|
57
|
+
list: [api_1.Permissions.IsAuthenticated],
|
|
58
|
+
read: [api_1.Permissions.IsAuthenticated, ownerOrAdmin],
|
|
59
|
+
update: [],
|
|
60
|
+
},
|
|
61
|
+
// Lists are always the caller's own conversations, admins included.
|
|
62
|
+
queryFilter: (user) => (user ? { userId: user.id ?? user._id } : null),
|
|
63
|
+
sort: "-created",
|
|
64
|
+
}));
|
|
65
|
+
};
|
|
66
|
+
exports.addHarnessConversationRoutes = addHarnessConversationRoutes;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type User } from "@terreno/api";
|
|
2
|
+
import type express from "express";
|
|
3
|
+
import { type DurationLike } from "luxon";
|
|
4
|
+
import mongoose from "mongoose";
|
|
5
|
+
import type { HarnessEventHub } from "../eventHub";
|
|
6
|
+
/** Whether `user` owns a record (its `userId`) or is an admin. */
|
|
7
|
+
export declare const isOwnerOrAdmin: (user: User | undefined, record: {
|
|
8
|
+
userId?: mongoose.Types.ObjectId | string | null;
|
|
9
|
+
}) => boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Mount the SSE routes `GET {basePath}/conversations/:id/events` and
|
|
12
|
+
* `GET {basePath}/tasks/:id/events`. SSE is the listed exception to modelRouter actions:
|
|
13
|
+
* the response is a long-lived stream, not a JSON document.
|
|
14
|
+
*/
|
|
15
|
+
export declare const addHarnessEventRoutes: (router: express.Application, { basePath, heartbeatInterval, hub, }: {
|
|
16
|
+
basePath: string;
|
|
17
|
+
heartbeatInterval?: DurationLike;
|
|
18
|
+
hub: HarnessEventHub;
|
|
19
|
+
}) => void;
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.addHarnessEventRoutes = exports.isOwnerOrAdmin = void 0;
|
|
7
|
+
const api_1 = require("@terreno/api");
|
|
8
|
+
const luxon_1 = require("luxon");
|
|
9
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
10
|
+
const errors_1 = require("../errors");
|
|
11
|
+
const events_1 = require("../events");
|
|
12
|
+
const harnessConversation_1 = require("../models/harnessConversation");
|
|
13
|
+
const harnessEvent_1 = require("../models/harnessEvent");
|
|
14
|
+
const harnessTask_1 = require("../models/harnessTask");
|
|
15
|
+
/** Events read per replay query. */
|
|
16
|
+
const REPLAY_PAGE_SIZE = 500;
|
|
17
|
+
/** Whether `user` owns a record (its `userId`) or is an admin. */
|
|
18
|
+
const isOwnerOrAdmin = (user, record) => Boolean(user?.admin) ||
|
|
19
|
+
(Boolean(user && record.userId) && String(record.userId) === String(user?.id ?? user?._id));
|
|
20
|
+
exports.isOwnerOrAdmin = isOwnerOrAdmin;
|
|
21
|
+
/**
|
|
22
|
+
* The last event the client has: the `Last-Event-ID` header a reconnecting `EventSource`
|
|
23
|
+
* sends, else the `after` query parameter, else 0 (from the start).
|
|
24
|
+
*/
|
|
25
|
+
const resumeAfter = (req) => {
|
|
26
|
+
const header = req.get("Last-Event-ID");
|
|
27
|
+
const raw = header !== undefined && header !== "" ? header : req.query.after;
|
|
28
|
+
if (raw === undefined || raw === "") {
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
if (typeof raw !== "string" || !/^\d+$/.test(raw)) {
|
|
32
|
+
throw new api_1.APIError({
|
|
33
|
+
detail: "Last-Event-ID and after must be a non-negative integer event seq",
|
|
34
|
+
status: 400,
|
|
35
|
+
title: "Invalid event id",
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return Number(raw);
|
|
39
|
+
};
|
|
40
|
+
const sseFrame = (event) => `id: ${event.seq}\nevent: ${event.type}\ndata: ${JSON.stringify((0, events_1.eventBody)(event))}\n\n`;
|
|
41
|
+
/**
|
|
42
|
+
* Track the client connection from the first middleware on, so a client that leaves
|
|
43
|
+
* during auth or the lookups (before any stream resource exists) is still noticed.
|
|
44
|
+
*/
|
|
45
|
+
const trackConnection = (req, res, next) => {
|
|
46
|
+
let isClosed = Boolean(req.socket?.destroyed);
|
|
47
|
+
const cleanups = [];
|
|
48
|
+
res.on("close", () => {
|
|
49
|
+
isClosed = true;
|
|
50
|
+
for (const cleanup of cleanups.splice(0)) {
|
|
51
|
+
cleanup();
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
const connection = {
|
|
55
|
+
get isClosed() {
|
|
56
|
+
return isClosed;
|
|
57
|
+
},
|
|
58
|
+
onClose: (cleanup) => {
|
|
59
|
+
if (isClosed) {
|
|
60
|
+
cleanup();
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
cleanups.push(cleanup);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
res.locals.harnessConnection = connection;
|
|
67
|
+
next();
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Serve one SSE stream: subscribe to the shared tail, replay stored events after the
|
|
71
|
+
* client's last one, then send what the tail delivered and keeps delivering. Registering
|
|
72
|
+
* before the replay query means every event is in the replay, the tail, or both; frames
|
|
73
|
+
* are deduplicated by `seq`, so the client receives each event once, in order.
|
|
74
|
+
*/
|
|
75
|
+
const serveEvents = async ({ after, filter, heartbeat, hub, req, res, scope, }) => {
|
|
76
|
+
const connection = res.locals.harnessConnection;
|
|
77
|
+
if (connection.isClosed) {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
const model = (0, harnessEvent_1.registerHarnessEvent)();
|
|
81
|
+
let lastSeq = after;
|
|
82
|
+
let isReplaying = true;
|
|
83
|
+
let isStreaming = false;
|
|
84
|
+
let isFailed = false;
|
|
85
|
+
const buffered = [];
|
|
86
|
+
const send = (event) => {
|
|
87
|
+
if (connection.isClosed || res.writableEnded || event.seq <= lastSeq) {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
lastSeq = event.seq;
|
|
91
|
+
res.write(sseFrame(event));
|
|
92
|
+
};
|
|
93
|
+
// Ends the stream; the client reconnects with Last-Event-ID and resumes where it stopped.
|
|
94
|
+
const end = (failure) => {
|
|
95
|
+
api_1.logger.warn(`Harness event stream ${failure.stage} failed; closing: ${String(failure.error)}`);
|
|
96
|
+
isFailed = true;
|
|
97
|
+
if (isStreaming && !res.writableEnded) {
|
|
98
|
+
res.end();
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
const unsubscribe = await hub.subscribe({
|
|
102
|
+
...scope,
|
|
103
|
+
// During the replay, tail events wait in `buffered`.
|
|
104
|
+
deliver: (event) => (isReplaying ? buffered.push(event) : send(event)),
|
|
105
|
+
fail: (error) => end({ error, stage: "tail" }),
|
|
106
|
+
});
|
|
107
|
+
connection.onClose(unsubscribe);
|
|
108
|
+
if (connection.isClosed) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
req.socket.setTimeout(0);
|
|
112
|
+
res.status(200);
|
|
113
|
+
res.set({
|
|
114
|
+
"Cache-Control": "no-cache, no-transform",
|
|
115
|
+
Connection: "keep-alive",
|
|
116
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
117
|
+
"X-Accel-Buffering": "no",
|
|
118
|
+
});
|
|
119
|
+
res.flushHeaders();
|
|
120
|
+
isStreaming = true;
|
|
121
|
+
if (isFailed) {
|
|
122
|
+
res.end();
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
// An ended response (a failed tail) may outlive its timer until the socket closes.
|
|
126
|
+
const timer = setInterval(() => {
|
|
127
|
+
if (!res.writableEnded) {
|
|
128
|
+
res.write(": heartbeat\n\n");
|
|
129
|
+
}
|
|
130
|
+
}, heartbeat.toMillis());
|
|
131
|
+
connection.onClose(() => clearInterval(timer));
|
|
132
|
+
try {
|
|
133
|
+
let page;
|
|
134
|
+
do {
|
|
135
|
+
page = await model
|
|
136
|
+
.find({ ...filter, seq: { $gt: lastSeq } })
|
|
137
|
+
.sort({ seq: 1 })
|
|
138
|
+
.limit(REPLAY_PAGE_SIZE)
|
|
139
|
+
.lean();
|
|
140
|
+
page.forEach(send);
|
|
141
|
+
} while (page.length === REPLAY_PAGE_SIZE && !connection.isClosed);
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
end({ error, stage: "replay" });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
isReplaying = false;
|
|
148
|
+
buffered.sort((left, right) => left.seq - right.seq);
|
|
149
|
+
buffered.splice(0).forEach(send);
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* Mount the SSE routes `GET {basePath}/conversations/:id/events` and
|
|
153
|
+
* `GET {basePath}/tasks/:id/events`. SSE is the listed exception to modelRouter actions:
|
|
154
|
+
* the response is a long-lived stream, not a JSON document.
|
|
155
|
+
*/
|
|
156
|
+
const addHarnessEventRoutes = (router, { basePath, heartbeatInterval, hub, }) => {
|
|
157
|
+
const heartbeat = luxon_1.Duration.fromDurationLike(heartbeatInterval ?? { seconds: 15 });
|
|
158
|
+
if (heartbeat.toMillis() <= 0) {
|
|
159
|
+
throw (0, errors_1.harnessError)({
|
|
160
|
+
detail: "HarnessApp heartbeatInterval must be positive",
|
|
161
|
+
kind: "configInvalid",
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
const loadOr404 = async (find, id, label) => {
|
|
165
|
+
const found = id && mongoose_1.default.isValidObjectId(id) ? await find(id) : null;
|
|
166
|
+
if (!found) {
|
|
167
|
+
throw new api_1.NotFoundError(`${label} not found`);
|
|
168
|
+
}
|
|
169
|
+
return found;
|
|
170
|
+
};
|
|
171
|
+
const assertCanRead = (req, record) => {
|
|
172
|
+
if (!(0, exports.isOwnerOrAdmin)(req.user, record)) {
|
|
173
|
+
throw new api_1.ForbiddenError("Only the owner or an admin may read this event stream");
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
router.get(`${basePath}/conversations/:id/events`, [
|
|
177
|
+
trackConnection,
|
|
178
|
+
(0, api_1.authenticateMiddleware)(),
|
|
179
|
+
(0, api_1.asyncHandler)(async (req, res) => {
|
|
180
|
+
const conversation = await loadOr404((id) => (0, harnessConversation_1.registerHarnessConversation)().findOneOrNone({ _id: id }), req.params.id, "Conversation");
|
|
181
|
+
assertCanRead(req, conversation);
|
|
182
|
+
const after = resumeAfter(req);
|
|
183
|
+
await serveEvents({
|
|
184
|
+
after,
|
|
185
|
+
filter: { streamId: conversation._id },
|
|
186
|
+
heartbeat,
|
|
187
|
+
hub,
|
|
188
|
+
req,
|
|
189
|
+
res,
|
|
190
|
+
scope: { streamId: String(conversation._id) },
|
|
191
|
+
});
|
|
192
|
+
}),
|
|
193
|
+
]);
|
|
194
|
+
router.get(`${basePath}/tasks/:id/events`, [
|
|
195
|
+
trackConnection,
|
|
196
|
+
(0, api_1.authenticateMiddleware)(),
|
|
197
|
+
(0, api_1.asyncHandler)(async (req, res) => {
|
|
198
|
+
const task = await loadOr404((id) => (0, harnessTask_1.registerHarnessTask)().findOneOrNone({ _id: id }), req.params.id, "Task");
|
|
199
|
+
assertCanRead(req, task);
|
|
200
|
+
const after = resumeAfter(req);
|
|
201
|
+
// The tree's stream, narrowed to this task and the tasks below it.
|
|
202
|
+
const { streamId } = (0, events_1.taskStreamOf)(task);
|
|
203
|
+
await serveEvents({
|
|
204
|
+
after,
|
|
205
|
+
filter: { streamId, taskPath: task._id },
|
|
206
|
+
heartbeat,
|
|
207
|
+
hub,
|
|
208
|
+
req,
|
|
209
|
+
res,
|
|
210
|
+
scope: { streamId: String(streamId), taskId: String(task._id) },
|
|
211
|
+
});
|
|
212
|
+
}),
|
|
213
|
+
]);
|
|
214
|
+
};
|
|
215
|
+
exports.addHarnessEventRoutes = addHarnessEventRoutes;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import type { Harness } from "../harness";
|
|
3
|
+
/**
|
|
4
|
+
* Mount `{basePath}/tasks`: read (owner or admin), plus the `abort` (owner or admin) and
|
|
5
|
+
* `resolveInterrupted` (admin) instance actions. Tasks are not listed or edited over HTTP.
|
|
6
|
+
*/
|
|
7
|
+
export declare const addHarnessTaskRoutes: (router: express.Application, { basePath, harness, openApi }: {
|
|
8
|
+
basePath: string;
|
|
9
|
+
harness: Harness;
|
|
10
|
+
openApi?: unknown;
|
|
11
|
+
}) => void;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.addHarnessTaskRoutes = void 0;
|
|
4
|
+
const api_1 = require("@terreno/api");
|
|
5
|
+
const harness_1 = require("../../types/harness");
|
|
6
|
+
const commit_1 = require("../commit");
|
|
7
|
+
const errors_1 = require("../errors");
|
|
8
|
+
const harnessTask_1 = require("../models/harnessTask");
|
|
9
|
+
const events_1 = require("./events");
|
|
10
|
+
const abortBody = api_1.z
|
|
11
|
+
.object({ reason: api_1.z.string().trim().min(1) })
|
|
12
|
+
.strict()
|
|
13
|
+
.describe("Why the task is aborted; required and audited");
|
|
14
|
+
const resolveBody = api_1.z
|
|
15
|
+
.object({
|
|
16
|
+
action: api_1.z.enum([
|
|
17
|
+
harness_1.HARNESS_RESOLVE_ACTIONS.abort,
|
|
18
|
+
harness_1.HARNESS_RESOLVE_ACTIONS.complete,
|
|
19
|
+
harness_1.HARNESS_RESOLVE_ACTIONS.retry,
|
|
20
|
+
]),
|
|
21
|
+
reason: api_1.z.string().trim().min(1),
|
|
22
|
+
result: api_1.z.unknown().optional(),
|
|
23
|
+
})
|
|
24
|
+
.strict()
|
|
25
|
+
.describe("What to do with an interrupted task, why, and (for complete) its result");
|
|
26
|
+
// Without a document (the pre-check) defer to the document check, like IsOwner.
|
|
27
|
+
const ownerOrAdmin = (_method, user, task) => task ? (0, events_1.isOwnerOrAdmin)(user, task) : true;
|
|
28
|
+
// Checked against the document so a non-admin gets 403, not the pre-document 405.
|
|
29
|
+
const adminOnly = (_method, user, task) => task ? Boolean(user?.admin) : true;
|
|
30
|
+
const isCommitConflict = (error) => error instanceof commit_1.HarnessCommitConflictError;
|
|
31
|
+
/**
|
|
32
|
+
* Mount `{basePath}/tasks`: read (owner or admin), plus the `abort` (owner or admin) and
|
|
33
|
+
* `resolveInterrupted` (admin) instance actions. Tasks are not listed or edited over HTTP.
|
|
34
|
+
*/
|
|
35
|
+
const addHarnessTaskRoutes = (router, { basePath, harness, openApi }) => {
|
|
36
|
+
const model = (0, harnessTask_1.registerHarnessTask)();
|
|
37
|
+
const abort = async ({ body, doc, user, }) => {
|
|
38
|
+
const { reason } = body;
|
|
39
|
+
try {
|
|
40
|
+
return await harness.abort(doc._id, { reason, userId: user?.id });
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
// The harness throws coded APIErrors itself; only a lost race (the task finished on
|
|
44
|
+
// its own between the check and the abort) needs restating as "already ended".
|
|
45
|
+
const current = await model.findOneOrNone({ _id: doc._id });
|
|
46
|
+
if (!isCommitConflict(error) || !current || !harness_1.HARNESS_TERMINAL_STATUSES.has(current.status)) {
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
throw (0, errors_1.harnessError)({
|
|
50
|
+
cause: error,
|
|
51
|
+
detail: `Task ${String(doc._id)} is already ${current.status}`,
|
|
52
|
+
kind: "taskTerminal",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const resolveInterrupted = async ({ body, doc, user, }) => {
|
|
57
|
+
const { action, reason, result } = body;
|
|
58
|
+
try {
|
|
59
|
+
return await harness.resolveInterrupted(doc._id, { action, reason, result, userId: user?.id });
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// The harness throws coded APIErrors itself; only a lost race (another resolution won)
|
|
63
|
+
// needs restating as "not interrupted".
|
|
64
|
+
const current = await model.findOneOrNone({ _id: doc._id });
|
|
65
|
+
if (!isCommitConflict(error) ||
|
|
66
|
+
!current ||
|
|
67
|
+
current.status === harness_1.HARNESS_TASK_STATUSES.interrupted) {
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
throw (0, errors_1.harnessError)({
|
|
71
|
+
cause: error,
|
|
72
|
+
detail: `Task ${String(doc._id)} is ${current.status}, not interrupted`,
|
|
73
|
+
kind: "taskNotInterrupted",
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
router.use(`${basePath}/tasks`, (0, api_1.modelRouter)(model, {
|
|
78
|
+
...(openApi ? { openApi: openApi } : {}),
|
|
79
|
+
instanceActions: {
|
|
80
|
+
abort: {
|
|
81
|
+
body: abortBody,
|
|
82
|
+
description: "Abort the task and every task it owns, deepest first; each runs its abort handler.",
|
|
83
|
+
handler: abort,
|
|
84
|
+
method: "POST",
|
|
85
|
+
permissions: [api_1.Permissions.IsAuthenticated, ownerOrAdmin],
|
|
86
|
+
summary: "Abort a harness task",
|
|
87
|
+
tag: "harness",
|
|
88
|
+
},
|
|
89
|
+
resolveInterrupted: {
|
|
90
|
+
body: resolveBody,
|
|
91
|
+
description: "Decide an interrupted task: retry its phase, abort it, or complete it with a result.",
|
|
92
|
+
handler: resolveInterrupted,
|
|
93
|
+
method: "POST",
|
|
94
|
+
permissions: [api_1.Permissions.IsAuthenticated, adminOnly],
|
|
95
|
+
summary: "Resolve an interrupted harness task",
|
|
96
|
+
tag: "harness",
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
permissions: {
|
|
100
|
+
create: [],
|
|
101
|
+
delete: [],
|
|
102
|
+
list: [],
|
|
103
|
+
read: [api_1.Permissions.IsAuthenticated, ownerOrAdmin],
|
|
104
|
+
update: [],
|
|
105
|
+
},
|
|
106
|
+
}));
|
|
107
|
+
};
|
|
108
|
+
exports.addHarnessTaskRoutes = addHarnessTaskRoutes;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type DurationLike } from "luxon";
|
|
2
|
+
import type { HarnessRunner, HarnessRunnerContext } from "../../types/harness";
|
|
3
|
+
export interface InProcessRunnerOptions {
|
|
4
|
+
/** How often the runner renews its owner lease and its running task's lease. */
|
|
5
|
+
heartbeatInterval?: DurationLike;
|
|
6
|
+
/** How long the owner lease and each task lease live without a heartbeat. */
|
|
7
|
+
leaseDuration?: DurationLike;
|
|
8
|
+
/** Runner instance id written into leases. Defaults to `hostname:pid:uuid`. */
|
|
9
|
+
ownerId?: string;
|
|
10
|
+
/** How long an idle owner sleeps before polling for runnable tasks again. */
|
|
11
|
+
pollInterval?: DurationLike;
|
|
12
|
+
}
|
|
13
|
+
/** `owner` drains tasks; `standby` waits for the owner lease; `stopped` does neither. */
|
|
14
|
+
export declare const IN_PROCESS_RUNNER_ROLES: {
|
|
15
|
+
readonly owner: "owner";
|
|
16
|
+
readonly standby: "standby";
|
|
17
|
+
readonly stopped: "stopped";
|
|
18
|
+
};
|
|
19
|
+
export type InProcessRunnerRole = (typeof IN_PROCESS_RUNNER_ROLES)[keyof typeof IN_PROCESS_RUNNER_ROLES];
|
|
20
|
+
/**
|
|
21
|
+
* Executes runnable tasks inside this process, one at a time, until each is terminal.
|
|
22
|
+
* Only the process holding the singleton `HarnessOwner` lease drains; every other
|
|
23
|
+
* process stays on standby and takes over once that lease expires. On becoming owner,
|
|
24
|
+
* and on every heartbeat while owner, it recovers tasks whose lease expired.
|
|
25
|
+
*/
|
|
26
|
+
export declare class InProcessRunner implements HarnessRunner {
|
|
27
|
+
private context;
|
|
28
|
+
private heartbeatInFlight;
|
|
29
|
+
private heartbeatTimer;
|
|
30
|
+
private hasPendingWake;
|
|
31
|
+
private isHeartbeatStopped;
|
|
32
|
+
private isStopping;
|
|
33
|
+
private readonly lease;
|
|
34
|
+
private loop;
|
|
35
|
+
private readonly pollIntervalMs;
|
|
36
|
+
private currentRole;
|
|
37
|
+
private wakeSleeper;
|
|
38
|
+
constructor(options?: InProcessRunnerOptions);
|
|
39
|
+
/** Whether this runner currently drains tasks, waits for the lease, or is stopped. */
|
|
40
|
+
get role(): InProcessRunnerRole;
|
|
41
|
+
/** Id written into every lease this runner holds. */
|
|
42
|
+
get ownerId(): string;
|
|
43
|
+
start(context: HarnessRunnerContext): Promise<void>;
|
|
44
|
+
/** Stop claiming new work, wait for the task in flight, then release the owner lease. */
|
|
45
|
+
stop(): Promise<void>;
|
|
46
|
+
/** Skip the rest of the idle sleep, e.g. right after a task is created. */
|
|
47
|
+
wake(): void;
|
|
48
|
+
private drain;
|
|
49
|
+
/** Become owner when the lease is free or expired, then recover abandoned tasks. */
|
|
50
|
+
private tryTakeOwnership;
|
|
51
|
+
/** Run one claimed task; returns true when nothing was runnable. */
|
|
52
|
+
private runNext;
|
|
53
|
+
private scheduleHeartbeat;
|
|
54
|
+
/** Renew the owner lease and sweep for expired task leases; demote on a lost lease. */
|
|
55
|
+
private heartbeat;
|
|
56
|
+
private sleep;
|
|
57
|
+
}
|