@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,9 @@
|
|
|
1
|
+
import type express from "express";
|
|
2
|
+
import type { GptRouteOptions } from "../types";
|
|
3
|
+
/**
|
|
4
|
+
* Host callbacks give up after this long unless `uiBlocks.actionTimeoutMs` sets another cap.
|
|
5
|
+
* @internal Test seam. Production reads it only inside this module.
|
|
6
|
+
*/
|
|
7
|
+
export declare const HOST_ACTION_TIMEOUT_MS = 10000;
|
|
8
|
+
/** Owner callback route. Mounted only when `uiBlocks` is on, under `/gpt` with the other chat routes. */
|
|
9
|
+
export declare const addGptActionRoutes: (router: express.Router, options: GptRouteOptions) => void;
|
|
@@ -0,0 +1,212 @@
|
|
|
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.addGptActionRoutes = exports.HOST_ACTION_TIMEOUT_MS = void 0;
|
|
7
|
+
const api_1 = require("@terreno/api");
|
|
8
|
+
const blocks_1 = require("@terreno/blocks");
|
|
9
|
+
const luxon_1 = require("luxon");
|
|
10
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
11
|
+
const aiRequest_1 = require("../models/aiRequest");
|
|
12
|
+
const gptHistory_1 = require("../models/gptHistory");
|
|
13
|
+
/**
|
|
14
|
+
* Host callbacks give up after this long unless `uiBlocks.actionTimeoutMs` sets another cap.
|
|
15
|
+
* @internal Test seam. Production reads it only inside this module.
|
|
16
|
+
*/
|
|
17
|
+
exports.HOST_ACTION_TIMEOUT_MS = 10_000;
|
|
18
|
+
const requestUserId = (req) => req.user?._id;
|
|
19
|
+
const requiredString = (value) => typeof value === "string" && value.length > 0;
|
|
20
|
+
const payloadFields = (issues) => {
|
|
21
|
+
const fields = {};
|
|
22
|
+
for (const issue of issues) {
|
|
23
|
+
const path = issue.path.map(String).join(".") || "payload";
|
|
24
|
+
fields[path] = issue.message;
|
|
25
|
+
}
|
|
26
|
+
return fields;
|
|
27
|
+
};
|
|
28
|
+
const withTimeout = async (work, timeoutMs) => {
|
|
29
|
+
let timer;
|
|
30
|
+
try {
|
|
31
|
+
return await Promise.race([
|
|
32
|
+
work,
|
|
33
|
+
new Promise((_resolve, reject) => {
|
|
34
|
+
timer = setTimeout(() => {
|
|
35
|
+
reject(new api_1.APIError({ status: 504, title: "Action timed out" }));
|
|
36
|
+
}, timeoutMs);
|
|
37
|
+
}),
|
|
38
|
+
]);
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
if (timer !== undefined) {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const assertReturnedBlocks = (blocks) => {
|
|
47
|
+
let validated;
|
|
48
|
+
try {
|
|
49
|
+
validated = (0, blocks_1.validateBlocks)(blocks);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw new api_1.APIError({
|
|
53
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
54
|
+
status: 500,
|
|
55
|
+
title: "Action returned an invalid document",
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
if (!validated.ok) {
|
|
59
|
+
throw new api_1.APIError({
|
|
60
|
+
meta: {
|
|
61
|
+
fields: Object.fromEntries(validated.errors.map((error) => [error.path, `${error.code} ${error.message}`])),
|
|
62
|
+
},
|
|
63
|
+
status: 500,
|
|
64
|
+
title: "Action returned an invalid document",
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const logAction = async ({ error, prompt, response, responseTime, userId, }) => {
|
|
69
|
+
try {
|
|
70
|
+
await aiRequest_1.AIRequest.logRequest({
|
|
71
|
+
aiModel: "host-action",
|
|
72
|
+
error,
|
|
73
|
+
prompt,
|
|
74
|
+
requestType: "ui_action",
|
|
75
|
+
response,
|
|
76
|
+
responseTime,
|
|
77
|
+
userId,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (logError) {
|
|
81
|
+
api_1.logger.warn("Failed to log ui_action", {
|
|
82
|
+
error: logError instanceof Error ? logError.message : String(logError),
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/** Owner callback route. Mounted only when `uiBlocks` is on, under `/gpt` with the other chat routes. */
|
|
87
|
+
const addGptActionRoutes = (router, options) => {
|
|
88
|
+
const uiBlocks = options.uiBlocks === true || !options.uiBlocks ? {} : options.uiBlocks;
|
|
89
|
+
const timeoutMs = uiBlocks.actionTimeoutMs ?? exports.HOST_ACTION_TIMEOUT_MS;
|
|
90
|
+
router.post("/gpt/actions", [
|
|
91
|
+
(0, api_1.authenticateMiddleware)(),
|
|
92
|
+
(0, api_1.createOpenApiBuilder)(options.openApiOptions ?? {})
|
|
93
|
+
.withTags(["gpt"])
|
|
94
|
+
.withSummary("Run a host callback from a block button")
|
|
95
|
+
.withRequestBody({
|
|
96
|
+
blockId: { type: "string" },
|
|
97
|
+
elementId: { type: "string" },
|
|
98
|
+
historyId: { type: "string" },
|
|
99
|
+
messageId: { type: "string" },
|
|
100
|
+
name: { type: "string" },
|
|
101
|
+
payload: { type: "object" },
|
|
102
|
+
})
|
|
103
|
+
.withResponse(200, {
|
|
104
|
+
blocks: { type: "object" },
|
|
105
|
+
replace: { type: "string" },
|
|
106
|
+
text: { type: "string" },
|
|
107
|
+
})
|
|
108
|
+
.build(),
|
|
109
|
+
], (0, api_1.asyncHandler)(async (req, res) => {
|
|
110
|
+
const body = (req.body ?? {});
|
|
111
|
+
const { blockId, elementId, historyId, messageId, name, payload } = body;
|
|
112
|
+
if (!requiredString(historyId) ||
|
|
113
|
+
!requiredString(messageId) ||
|
|
114
|
+
!requiredString(blockId) ||
|
|
115
|
+
!requiredString(elementId) ||
|
|
116
|
+
!requiredString(name)) {
|
|
117
|
+
throw new api_1.APIError({
|
|
118
|
+
status: 400,
|
|
119
|
+
title: "historyId, messageId, blockId, elementId, and name are required",
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (!mongoose_1.default.Types.ObjectId.isValid(historyId)) {
|
|
123
|
+
throw new api_1.APIError({ status: 400, title: "historyId is not valid" });
|
|
124
|
+
}
|
|
125
|
+
const userId = requestUserId(req);
|
|
126
|
+
const history = await gptHistory_1.GptHistory.findOneOrNone({ _id: historyId, deleted: false });
|
|
127
|
+
if (!history) {
|
|
128
|
+
throw new api_1.APIError({ status: 404, title: "History not found" });
|
|
129
|
+
}
|
|
130
|
+
if (history.userId.toString() !== userId?.toString()) {
|
|
131
|
+
throw new api_1.APIError({ status: 403, title: "Not authorized to access this history" });
|
|
132
|
+
}
|
|
133
|
+
const action = uiBlocks.hostActions?.[name];
|
|
134
|
+
if (!action?.handler) {
|
|
135
|
+
throw new api_1.APIError({ status: 404, title: "Unknown action" });
|
|
136
|
+
}
|
|
137
|
+
let parsedPayload = payload ?? {};
|
|
138
|
+
if (action.payload) {
|
|
139
|
+
const parsed = action.payload.safeParse(parsedPayload);
|
|
140
|
+
if (!parsed.success) {
|
|
141
|
+
throw new api_1.APIError({
|
|
142
|
+
meta: { fields: payloadFields(parsed.error.issues) },
|
|
143
|
+
status: 400,
|
|
144
|
+
title: "Invalid payload",
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
parsedPayload = parsed.data;
|
|
148
|
+
}
|
|
149
|
+
const started = luxon_1.DateTime.now();
|
|
150
|
+
const prompt = JSON.stringify({ blockId, elementId, historyId, messageId, name });
|
|
151
|
+
let result;
|
|
152
|
+
try {
|
|
153
|
+
result = await withTimeout(Promise.resolve(action.handler({
|
|
154
|
+
blockId,
|
|
155
|
+
elementId,
|
|
156
|
+
history,
|
|
157
|
+
messageId,
|
|
158
|
+
payload: parsedPayload,
|
|
159
|
+
user: { _id: userId },
|
|
160
|
+
})), timeoutMs);
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
164
|
+
await logAction({
|
|
165
|
+
error: message,
|
|
166
|
+
prompt,
|
|
167
|
+
responseTime: luxon_1.DateTime.now().toMillis() - started.toMillis(),
|
|
168
|
+
userId,
|
|
169
|
+
});
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
if (result?.replace !== undefined &&
|
|
173
|
+
result.replace !== "block" &&
|
|
174
|
+
result.replace !== "message") {
|
|
175
|
+
await logAction({
|
|
176
|
+
error: "Action returned an unknown replace value",
|
|
177
|
+
prompt,
|
|
178
|
+
responseTime: luxon_1.DateTime.now().toMillis() - started.toMillis(),
|
|
179
|
+
userId,
|
|
180
|
+
});
|
|
181
|
+
throw new api_1.APIError({ status: 500, title: "Action returned an unknown replace value" });
|
|
182
|
+
}
|
|
183
|
+
if (result?.blocks !== undefined) {
|
|
184
|
+
try {
|
|
185
|
+
assertReturnedBlocks(result.blocks);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
189
|
+
await logAction({
|
|
190
|
+
error: message,
|
|
191
|
+
prompt,
|
|
192
|
+
responseTime: luxon_1.DateTime.now().toMillis() - started.toMillis(),
|
|
193
|
+
userId,
|
|
194
|
+
});
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const data = {
|
|
199
|
+
...(result?.blocks !== undefined ? { blocks: result.blocks } : {}),
|
|
200
|
+
...(result?.replace !== undefined ? { replace: result.replace } : {}),
|
|
201
|
+
...(result?.text !== undefined ? { text: result.text } : {}),
|
|
202
|
+
};
|
|
203
|
+
await logAction({
|
|
204
|
+
prompt,
|
|
205
|
+
response: JSON.stringify(data),
|
|
206
|
+
responseTime: luxon_1.DateTime.now().toMillis() - started.toMillis(),
|
|
207
|
+
userId,
|
|
208
|
+
});
|
|
209
|
+
return res.json({ data });
|
|
210
|
+
}));
|
|
211
|
+
};
|
|
212
|
+
exports.addGptActionRoutes = addGptActionRoutes;
|
|
@@ -0,0 +1,94 @@
|
|
|
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.addGptDatasetRoutes = void 0;
|
|
7
|
+
const api_1 = require("@terreno/api");
|
|
8
|
+
const blocks_1 = require("@terreno/blocks");
|
|
9
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
10
|
+
const aiDataset_1 = require("../models/aiDataset");
|
|
11
|
+
const aiDatasets_1 = require("../service/aiDatasets");
|
|
12
|
+
const DEFAULT_LIMIT = 500;
|
|
13
|
+
const MAX_LIMIT = 1000;
|
|
14
|
+
const requestUserId = (req) => req.user?._id;
|
|
15
|
+
const queryValue = (value) => {
|
|
16
|
+
if (value === undefined) {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
if (typeof value !== "string") {
|
|
20
|
+
throw new api_1.APIError({ status: 400, title: "Query parameters must be single values" });
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
const parsePositiveInt = (value, name, max) => {
|
|
25
|
+
if (!/^[1-9]\d*$/.test(value)) {
|
|
26
|
+
throw new api_1.APIError({ status: 400, title: `${name} must be a positive integer` });
|
|
27
|
+
}
|
|
28
|
+
const parsed = Number(value);
|
|
29
|
+
if (parsed > max) {
|
|
30
|
+
throw new api_1.APIError({ status: 400, title: `${name} must be at most ${max}` });
|
|
31
|
+
}
|
|
32
|
+
return parsed;
|
|
33
|
+
};
|
|
34
|
+
const parseGrain = (value) => {
|
|
35
|
+
if (value === undefined) {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
if (!blocks_1.DATASET_GRAINS.includes(value)) {
|
|
39
|
+
throw new api_1.APIError({ status: 400, title: "grain must be hour, day, week, or month" });
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
};
|
|
43
|
+
/** Owner read of a stored dataset. Mounted only when `uiBlocks` is on. */
|
|
44
|
+
const addGptDatasetRoutes = (router, options) => {
|
|
45
|
+
router.get("/gpt/datasets/:id", [
|
|
46
|
+
(0, api_1.authenticateMiddleware)(),
|
|
47
|
+
(0, api_1.createOpenApiBuilder)(options.openApiOptions ?? {})
|
|
48
|
+
.withTags(["gpt"])
|
|
49
|
+
.withSummary("Read a stored chart dataset")
|
|
50
|
+
.withPathParameter("id", { type: "string" })
|
|
51
|
+
.withQueryParameter("grain", { enum: [...blocks_1.DATASET_GRAINS], type: "string" }, { required: false })
|
|
52
|
+
.withQueryParameter("limit", { type: "number" }, { required: false })
|
|
53
|
+
.withQueryParameter("page", { type: "number" }, { required: false })
|
|
54
|
+
.withResponse(200, {
|
|
55
|
+
columns: { items: { type: "object" }, type: "array" },
|
|
56
|
+
more: { type: "boolean" },
|
|
57
|
+
page: { type: "number" },
|
|
58
|
+
rowCount: { type: "number" },
|
|
59
|
+
rows: { items: { type: "array" }, type: "array" },
|
|
60
|
+
})
|
|
61
|
+
.build(),
|
|
62
|
+
], (0, api_1.asyncHandler)(async (req, res) => {
|
|
63
|
+
const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
|
|
64
|
+
if (!id || !mongoose_1.default.Types.ObjectId.isValid(id)) {
|
|
65
|
+
throw new api_1.APIError({ status: 400, title: "Dataset id is not valid" });
|
|
66
|
+
}
|
|
67
|
+
const userId = requestUserId(req);
|
|
68
|
+
// Another user's dataset is "not found", so ids cannot be probed.
|
|
69
|
+
const dataset = await aiDataset_1.AIDataset.findOneOrNone({
|
|
70
|
+
_id: id,
|
|
71
|
+
deleted: false,
|
|
72
|
+
userId,
|
|
73
|
+
});
|
|
74
|
+
if (!dataset) {
|
|
75
|
+
throw new api_1.APIError({ status: 404, title: "Dataset not found" });
|
|
76
|
+
}
|
|
77
|
+
const grain = parseGrain(queryValue(req.query.grain));
|
|
78
|
+
const limitText = queryValue(req.query.limit);
|
|
79
|
+
const pageText = queryValue(req.query.page);
|
|
80
|
+
const limit = limitText === undefined ? DEFAULT_LIMIT : parsePositiveInt(limitText, "limit", MAX_LIMIT);
|
|
81
|
+
const page = pageText === undefined ? undefined : parsePositiveInt(pageText, "page", 10_000);
|
|
82
|
+
const read = (0, aiDatasets_1.readDatasetRows)(dataset, { grain, limit, page });
|
|
83
|
+
return res.json({
|
|
84
|
+
data: {
|
|
85
|
+
columns: dataset.columns,
|
|
86
|
+
more: read.more,
|
|
87
|
+
page: read.page,
|
|
88
|
+
rowCount: read.rowCount,
|
|
89
|
+
rows: read.rows,
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
}));
|
|
93
|
+
};
|
|
94
|
+
exports.addGptDatasetRoutes = addGptDatasetRoutes;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type ModelRouterOptions } from "@terreno/api";
|
|
2
2
|
import type express from "express";
|
|
3
3
|
import type { GptHistoryDocument, GptHistoryRouteOptions } from "../types";
|
|
4
|
-
|
|
4
|
+
type HistoryRouterOptions = Partial<ModelRouterOptions<GptHistoryDocument>>;
|
|
5
|
+
export declare const addGptHistoryRoutes: (router: express.Router, options?: HistoryRouterOptions & GptHistoryRouteOptions) => void;
|
|
6
|
+
export {};
|
|
@@ -2,10 +2,182 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.addGptHistoryRoutes = void 0;
|
|
4
4
|
const api_1 = require("@terreno/api");
|
|
5
|
+
const blocks_1 = require("@terreno/blocks");
|
|
6
|
+
const luxon_1 = require("luxon");
|
|
5
7
|
const gptHistory_1 = require("../models/gptHistory");
|
|
8
|
+
const asks_1 = require("../service/asks");
|
|
9
|
+
const chatTurn_1 = require("../service/chatTurn");
|
|
10
|
+
/**
|
|
11
|
+
* Only the chat turn writes `pendingAsk`: it holds messages replayed verbatim to the model, so a
|
|
12
|
+
* client must not be able to plant or edit one, including through dotted paths.
|
|
13
|
+
*/
|
|
14
|
+
const withoutPendingAsk = (body) => Object.fromEntries(Object.entries(body ?? {}).filter(([key]) => key !== "pendingAsk" && !key.startsWith("pendingAsk.")));
|
|
15
|
+
/** Generated SDKs leave `readOnly` properties out of request types, so clients never send it. */
|
|
16
|
+
const READ_ONLY_PENDING_ASK = {
|
|
17
|
+
requestBody: {
|
|
18
|
+
content: { "application/json": { schema: { properties: { pendingAsk: { readOnly: true } } } } },
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
const isFragment = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
+
/** Server-only fields of `pendingAsk`: the paused turn's messages, replayed only to the model. */
|
|
23
|
+
const SERVER_ONLY_PENDING_ASK_FIELDS = ["promptIndex", "responseMessages"];
|
|
24
|
+
const withoutServerOnlyFields = (pendingAsk) => Object.fromEntries(Object.entries(pendingAsk).filter(([key]) => !SERVER_ONLY_PENDING_ASK_FIELDS.includes(key)));
|
|
25
|
+
/** A serialized history as clients receive it: its pending ask without the server-only fields. */
|
|
26
|
+
const withClientPendingAsk = (history) => {
|
|
27
|
+
if (!isFragment(history) || !isFragment(history.pendingAsk)) {
|
|
28
|
+
return history;
|
|
29
|
+
}
|
|
30
|
+
return { ...history, pendingAsk: withoutServerOnlyFields(history.pendingAsk) };
|
|
31
|
+
};
|
|
32
|
+
/** The model's `pendingAsk` schema without the server-only fields, for the OpenAPI spec. */
|
|
33
|
+
const clientPendingAskSchema = () => {
|
|
34
|
+
const { properties } = (0, api_1.getOpenApiSpecForModel)(gptHistory_1.GptHistory);
|
|
35
|
+
const schema = isFragment(properties.pendingAsk) ? properties.pendingAsk : {};
|
|
36
|
+
const { properties: fields, required, ...rest } = schema;
|
|
37
|
+
return {
|
|
38
|
+
...rest,
|
|
39
|
+
...(isFragment(fields) ? { properties: withoutServerOnlyFields(fields) } : {}),
|
|
40
|
+
...(Array.isArray(required)
|
|
41
|
+
? { required: required.filter((field) => !SERVER_ONLY_PENDING_ASK_FIELDS.includes(field)) }
|
|
42
|
+
: {}),
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
const mergeFragments = (base, extra = {}) => {
|
|
46
|
+
const merged = { ...base };
|
|
47
|
+
for (const [key, value] of Object.entries(extra)) {
|
|
48
|
+
const current = merged[key];
|
|
49
|
+
merged[key] = isFragment(current) && isFragment(value) ? mergeFragments(current, value) : value;
|
|
50
|
+
}
|
|
51
|
+
return merged;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* preCreate sets `userId` to the caller, so a client such as a watch creates a history with `{}`
|
|
55
|
+
* even when the host validates request bodies against the model. A host's `validation: false`
|
|
56
|
+
* stays off.
|
|
57
|
+
*/
|
|
58
|
+
const withCallerUserId = (validation) => {
|
|
59
|
+
if (validation === false) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
const hostValidation = typeof validation === "object" ? validation : {};
|
|
63
|
+
return {
|
|
64
|
+
...hostValidation,
|
|
65
|
+
excludeFromCreate: [...(hostValidation.excludeFromCreate ?? []), "userId"],
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
const userIdOf = (req) => req.user?._id;
|
|
69
|
+
/** The caller's pending asks, newest first, without the stored messages of the paused turns. */
|
|
70
|
+
const listPendingAsks = async (req) => {
|
|
71
|
+
const userId = userIdOf(req);
|
|
72
|
+
if (!userId) {
|
|
73
|
+
throw new api_1.APIError({ status: 401, title: "Authentication required" });
|
|
74
|
+
}
|
|
75
|
+
const histories = await gptHistory_1.GptHistory.find({ pendingAsk: { $ne: null }, userId })
|
|
76
|
+
.select({
|
|
77
|
+
"pendingAsk.created": 1,
|
|
78
|
+
"pendingAsk.kind": 1,
|
|
79
|
+
"pendingAsk.simple": 1,
|
|
80
|
+
"pendingAsk.toolCallId": 1,
|
|
81
|
+
title: 1,
|
|
82
|
+
})
|
|
83
|
+
.sort({ "pendingAsk.created": -1 })
|
|
84
|
+
.lean();
|
|
85
|
+
return histories.flatMap(({ _id, pendingAsk, title }) => pendingAsk
|
|
86
|
+
? [
|
|
87
|
+
{
|
|
88
|
+
created: luxon_1.DateTime.fromJSDate(pendingAsk.created).toUTC().toISO() ?? "",
|
|
89
|
+
historyId: _id.toString(),
|
|
90
|
+
kind: pendingAsk.kind,
|
|
91
|
+
simple: pendingAsk.simple,
|
|
92
|
+
...(title ? { title } : {}),
|
|
93
|
+
toolCallId: pendingAsk.toolCallId,
|
|
94
|
+
},
|
|
95
|
+
]
|
|
96
|
+
: []);
|
|
97
|
+
};
|
|
98
|
+
/**
|
|
99
|
+
* Runs one turn of the history. A `buttonId` sends the answer stored on that button of the
|
|
100
|
+
* pending ask's simple card, so a small client never builds an answer itself.
|
|
101
|
+
*/
|
|
102
|
+
const runHeadlessTurn = async ({ body, chat, history, req, }) => {
|
|
103
|
+
// Admins pass IsOwner, but a turn speaks as the conversation's owner.
|
|
104
|
+
if (history.userId.toString() !== userIdOf(req)?.toString()) {
|
|
105
|
+
throw new api_1.APIError({ status: 403, title: "Not authorized to access this history" });
|
|
106
|
+
}
|
|
107
|
+
const { askResponse, buttonId, prompt, surface, toolCallId } = body;
|
|
108
|
+
const historyId = history._id.toString();
|
|
109
|
+
if (buttonId === undefined || toolCallId === undefined) {
|
|
110
|
+
return (0, chatTurn_1.runBufferedChatTurn)({
|
|
111
|
+
body: { askResponse, historyId, prompt, surface },
|
|
112
|
+
options: chat,
|
|
113
|
+
req,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const { pendingAsk } = history;
|
|
117
|
+
if (pendingAsk?.toolCallId !== toolCallId) {
|
|
118
|
+
throw (0, chatTurn_1.staleAskError)(toolCallId);
|
|
119
|
+
}
|
|
120
|
+
const { errors, response } = (0, blocks_1.resolveButtonAnswer)({ buttonId, card: pendingAsk.simple });
|
|
121
|
+
if (!response) {
|
|
122
|
+
throw new api_1.APIError({
|
|
123
|
+
code: "UNKNOWN_BUTTON",
|
|
124
|
+
detail: "The button is not on the pending ask's simple card. See fields.",
|
|
125
|
+
meta: { fields: errors },
|
|
126
|
+
status: 400,
|
|
127
|
+
title: "Unknown buttonId",
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return (0, chatTurn_1.runBufferedChatTurn)({
|
|
131
|
+
body: { askResponse: { ...response, toolCallId }, historyId, surface },
|
|
132
|
+
options: chat,
|
|
133
|
+
req,
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
/** The headless actions, next to any actions the host adds to `/gpt/histories`. */
|
|
137
|
+
const headlessActions = ({ chat, routerOptions, }) => ({
|
|
138
|
+
collectionActions: {
|
|
139
|
+
...routerOptions.collectionActions,
|
|
140
|
+
pendingAsks: {
|
|
141
|
+
description: "The asks the caller's conversations are waiting on, newest first, each with its simple card. Answer one with POST /gpt/histories/{id}/turn.",
|
|
142
|
+
handler: ({ req }) => listPendingAsks(req),
|
|
143
|
+
method: "GET",
|
|
144
|
+
permissions: [api_1.Permissions.IsAuthenticated],
|
|
145
|
+
response: blocks_1.pendingAskListSchema,
|
|
146
|
+
summary: "List the caller's pending asks",
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
instanceActions: {
|
|
150
|
+
...routerOptions.instanceActions,
|
|
151
|
+
turn: {
|
|
152
|
+
body: blocks_1.turnRequestSchema,
|
|
153
|
+
description: "Runs one chat turn to completion and returns the reply as JSON, for clients that do not read server-sent events. The turn finishes and is saved even if the client disconnects.",
|
|
154
|
+
handler: ({ body, doc, req }) => runHeadlessTurn({ body: body, chat, history: doc, req }),
|
|
155
|
+
method: "POST",
|
|
156
|
+
permissions: [api_1.Permissions.IsOwner],
|
|
157
|
+
response: blocks_1.turnResultSchema,
|
|
158
|
+
summary: "Run a chat turn and return the reply as JSON",
|
|
159
|
+
},
|
|
160
|
+
},
|
|
161
|
+
});
|
|
6
162
|
const addGptHistoryRoutes = (router, options) => {
|
|
163
|
+
const { chat, openApiOptions, ...routerOptions } = options ?? {};
|
|
164
|
+
const headlessChat = (0, asks_1.resolveAskKinds)(chat?.asks).length > 0 ? chat : undefined;
|
|
165
|
+
if (headlessChat) {
|
|
166
|
+
(0, asks_1.assertNoReservedToolNames)(headlessChat.tools);
|
|
167
|
+
}
|
|
7
168
|
router.use("/gpt/histories", (0, api_1.modelRouter)(gptHistory_1.GptHistory, {
|
|
8
|
-
...
|
|
169
|
+
...openApiOptions,
|
|
170
|
+
...routerOptions,
|
|
171
|
+
...(headlessChat ? headlessActions({ chat: headlessChat, routerOptions }) : {}),
|
|
172
|
+
openApiExtraModelProperties: {
|
|
173
|
+
...routerOptions.openApiExtraModelProperties,
|
|
174
|
+
pendingAsk: clientPendingAskSchema(),
|
|
175
|
+
},
|
|
176
|
+
openApiOverwrite: {
|
|
177
|
+
...routerOptions.openApiOverwrite,
|
|
178
|
+
create: mergeFragments(READ_ONLY_PENDING_ASK, routerOptions.openApiOverwrite?.create),
|
|
179
|
+
update: mergeFragments(READ_ONLY_PENDING_ASK, routerOptions.openApiOverwrite?.update),
|
|
180
|
+
},
|
|
9
181
|
permissions: {
|
|
10
182
|
create: [api_1.Permissions.IsAuthenticated],
|
|
11
183
|
delete: [api_1.Permissions.IsOwner],
|
|
@@ -15,13 +187,27 @@ const addGptHistoryRoutes = (router, options) => {
|
|
|
15
187
|
},
|
|
16
188
|
preCreate: (body, req) => {
|
|
17
189
|
return {
|
|
18
|
-
...body,
|
|
190
|
+
...withoutPendingAsk(body),
|
|
19
191
|
userId: req.user?._id,
|
|
20
192
|
};
|
|
21
193
|
},
|
|
194
|
+
preUpdate: (body, req) => {
|
|
195
|
+
const update = withoutPendingAsk(body);
|
|
196
|
+
return routerOptions.preUpdate
|
|
197
|
+
? routerOptions.preUpdate(update, req)
|
|
198
|
+
: update;
|
|
199
|
+
},
|
|
22
200
|
queryFields: ["userId", "projectId"],
|
|
23
201
|
queryFilter: (user) => ({ userId: user?.id }),
|
|
202
|
+
responseHandler: async (value, method, req, handlerOptions) => {
|
|
203
|
+
const hostHandler = routerOptions.responseHandler ?? api_1.defaultResponseHandler;
|
|
204
|
+
const serialized = await hostHandler(value, method, req, handlerOptions);
|
|
205
|
+
return (Array.isArray(serialized)
|
|
206
|
+
? serialized.map(withClientPendingAsk)
|
|
207
|
+
: withClientPendingAsk(serialized));
|
|
208
|
+
},
|
|
24
209
|
sort: "-updated",
|
|
210
|
+
validation: withCallerUserId(routerOptions.validation),
|
|
25
211
|
}));
|
|
26
212
|
};
|
|
27
213
|
exports.addGptHistoryRoutes = addGptHistoryRoutes;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { type DATASET_GRAINS, type DatasetColumn } from "@terreno/blocks";
|
|
2
|
+
import type mongoose from "mongoose";
|
|
3
|
+
import type { AIDatasetCell, AIDatasetDocument } from "../types";
|
|
4
|
+
export type DatasetGrain = (typeof DATASET_GRAINS)[number];
|
|
5
|
+
/** Handle returned by `registerAiDataset` for the tool result the model sees. */
|
|
6
|
+
export interface RegisteredDataset {
|
|
7
|
+
columns: DatasetColumn[];
|
|
8
|
+
datasetId: string;
|
|
9
|
+
preview: AIDatasetCell[][];
|
|
10
|
+
rowCount: number;
|
|
11
|
+
stats: Record<string, {
|
|
12
|
+
max: number;
|
|
13
|
+
min: number;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
16
|
+
/** Row cap and retention used by `registerAiDataset`. Called from `addGptRoutes` when `uiBlocks` is on. */
|
|
17
|
+
export declare const configureAiDatasets: (options?: {
|
|
18
|
+
datasetMaxRows?: number;
|
|
19
|
+
datasetTtlDays?: number;
|
|
20
|
+
}) => void;
|
|
21
|
+
/**
|
|
22
|
+
* Stores rows for a `ref` dataset. Only server tools call this. The model receives
|
|
23
|
+
* `datasetId`, not a way to create one.
|
|
24
|
+
*/
|
|
25
|
+
export declare const registerAiDataset: ({ columns, historyId, rows, userId, }: {
|
|
26
|
+
columns: DatasetColumn[];
|
|
27
|
+
historyId: mongoose.Types.ObjectId | string;
|
|
28
|
+
rows: AIDatasetCell[][];
|
|
29
|
+
userId: mongoose.Types.ObjectId | string;
|
|
30
|
+
}) => Promise<RegisteredDataset>;
|
|
31
|
+
/**
|
|
32
|
+
* Sums number columns into one row per date bucket. The first date column is the bucket.
|
|
33
|
+
* @internal Test seam. Dataset reads call this before the response is built.
|
|
34
|
+
*/
|
|
35
|
+
export declare const bucketByGrain: (columns: DatasetColumn[], rows: AIDatasetCell[][], grain: DatasetGrain) => AIDatasetCell[][];
|
|
36
|
+
/**
|
|
37
|
+
* Largest-triangle-three-buckets downsample. Keeps the first and last points and at most
|
|
38
|
+
* `threshold` points total.
|
|
39
|
+
* @internal Test seam. Row downsampling uses `lttbIndexes` in this module.
|
|
40
|
+
*/
|
|
41
|
+
export declare const lttb: (points: {
|
|
42
|
+
x: number;
|
|
43
|
+
y: number;
|
|
44
|
+
}[], threshold: number) => {
|
|
45
|
+
x: number;
|
|
46
|
+
y: number;
|
|
47
|
+
}[];
|
|
48
|
+
export declare const readDatasetRows: (dataset: AIDatasetDocument, options: {
|
|
49
|
+
grain?: DatasetGrain;
|
|
50
|
+
limit: number;
|
|
51
|
+
page?: number;
|
|
52
|
+
}) => {
|
|
53
|
+
more: boolean;
|
|
54
|
+
page: number;
|
|
55
|
+
rowCount: number;
|
|
56
|
+
rows: AIDatasetCell[][];
|
|
57
|
+
};
|