@superblocksteam/vite-plugin-file-sync 2.0.175-next.0 → 2.0.176
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/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts.map +1 -1
- package/dist/ai-service/agent/prompts/build-base-system-prompt.js +1 -11
- package/dist/ai-service/agent/prompts/build-base-system-prompt.js.map +1 -1
- package/dist/ai-service/agent/tools/apis/get-api-docs.d.ts +3 -3
- package/dist/ai-service/agent/tools/apis/test-api.d.ts +13 -78
- package/dist/ai-service/agent/tools/apis/test-api.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/apis/test-api.js +50 -52
- package/dist/ai-service/agent/tools/apis/test-api.js.map +1 -1
- package/dist/ai-service/agent/tools/build-capture-screenshot.d.ts +3 -11
- package/dist/ai-service/agent/tools/build-capture-screenshot.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/build-capture-screenshot.js +8 -13
- package/dist/ai-service/agent/tools/build-capture-screenshot.js.map +1 -1
- package/dist/ai-service/agent/tools/build-navigate-preview.d.ts +0 -6
- package/dist/ai-service/agent/tools/build-navigate-preview.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/build-navigate-preview.js +4 -5
- package/dist/ai-service/agent/tools/build-navigate-preview.js.map +1 -1
- package/dist/ai-service/agent/tools/databases/destructive-migration-prompt.d.ts +1 -4
- package/dist/ai-service/agent/tools/databases/destructive-migration-prompt.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/databases/destructive-migration-prompt.js +3 -6
- package/dist/ai-service/agent/tools/databases/destructive-migration-prompt.js.map +1 -1
- package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts +4 -11
- package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/databases/dev-database-tasks.js +3 -21
- package/dist/ai-service/agent/tools/databases/dev-database-tasks.js.map +1 -1
- package/dist/ai-service/agent/tools/databases/dev-database-tools.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/databases/dev-database-tools.js +5 -32
- package/dist/ai-service/agent/tools/databases/dev-database-tools.js.map +1 -1
- package/dist/ai-service/agent/tools/get-logs.d.ts +2 -5
- package/dist/ai-service/agent/tools/get-logs.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/get-logs.js +3 -6
- package/dist/ai-service/agent/tools/get-logs.js.map +1 -1
- package/dist/ai-service/agent/tools/get-runtime-errors.d.ts +0 -2
- package/dist/ai-service/agent/tools/get-runtime-errors.d.ts.map +1 -1
- package/dist/ai-service/agent/tools/get-runtime-errors.js +2 -3
- package/dist/ai-service/agent/tools/get-runtime-errors.js.map +1 -1
- package/dist/ai-service/agent/tools/get-security-findings.js +1 -1
- package/dist/ai-service/agent/tools/integrations/execute-request.d.ts +5 -5
- package/dist/ai-service/agent/tools/integrations/metadata.d.ts +1 -1
- package/dist/ai-service/agent/tools/integrations/metadata.js.map +1 -1
- package/dist/ai-service/agent/tools/report-security-findings.d.ts +3 -3
- package/dist/ai-service/agent/tools.d.ts +5 -1
- package/dist/ai-service/agent/tools.d.ts.map +1 -1
- package/dist/ai-service/agent/tools.js +42 -7
- package/dist/ai-service/agent/tools.js.map +1 -1
- package/dist/ai-service/agent/tools2/tools/grep-metadata.d.ts +3 -4
- package/dist/ai-service/agent/tools2/tools/grep-metadata.d.ts.map +1 -1
- package/dist/ai-service/agent/tools2/tools/grep-metadata.js +2 -4
- package/dist/ai-service/agent/tools2/tools/grep-metadata.js.map +1 -1
- package/dist/ai-service/agent/tools2/tools/grep.d.ts.map +1 -1
- package/dist/ai-service/agent/tools2/tools/grep.js +5 -27
- package/dist/ai-service/agent/tools2/tools/grep.js.map +1 -1
- package/dist/ai-service/app-interface/file-system-interface.d.ts +1 -1
- package/dist/ai-service/app-interface/filesystem/handlers/skill-handler.d.ts +1 -2
- package/dist/ai-service/app-interface/filesystem/handlers/skill-handler.d.ts.map +1 -1
- package/dist/ai-service/app-interface/filesystem/handlers/skill-handler.js +2 -9
- package/dist/ai-service/app-interface/filesystem/handlers/skill-handler.js.map +1 -1
- package/dist/ai-service/app-interface/filesystem/virtual-file-system.d.ts +0 -1
- package/dist/ai-service/app-interface/filesystem/virtual-file-system.d.ts.map +1 -1
- package/dist/ai-service/app-interface/filesystem/virtual-file-system.js +1 -1
- package/dist/ai-service/app-interface/filesystem/virtual-file-system.js.map +1 -1
- package/dist/ai-service/app-interface/npm-registry.d.ts +0 -1
- package/dist/ai-service/app-interface/npm-registry.d.ts.map +1 -1
- package/dist/ai-service/app-interface/npm-registry.js +6 -45
- package/dist/ai-service/app-interface/npm-registry.js.map +1 -1
- package/dist/ai-service/app-interface/shell.d.ts +1 -4
- package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
- package/dist/ai-service/app-interface/shell.js +8 -26
- package/dist/ai-service/app-interface/shell.js.map +1 -1
- package/dist/ai-service/chat/chat-session-store.d.ts +1 -10
- package/dist/ai-service/chat/chat-session-store.d.ts.map +1 -1
- package/dist/ai-service/chat/chat-session-store.js +1 -30
- package/dist/ai-service/chat/chat-session-store.js.map +1 -1
- package/dist/ai-service/dev-database-client.d.ts +0 -1
- package/dist/ai-service/dev-database-client.d.ts.map +1 -1
- package/dist/ai-service/dev-database-client.js +0 -1
- package/dist/ai-service/dev-database-client.js.map +1 -1
- package/dist/ai-service/dev-database-file-sync.d.ts +1 -3
- package/dist/ai-service/dev-database-file-sync.d.ts.map +1 -1
- package/dist/ai-service/dev-database-file-sync.js.map +1 -1
- package/dist/ai-service/features.d.ts +8 -15
- package/dist/ai-service/features.d.ts.map +1 -1
- package/dist/ai-service/features.js +8 -15
- package/dist/ai-service/features.js.map +1 -1
- package/dist/ai-service/index.d.ts +19 -34
- package/dist/ai-service/index.d.ts.map +1 -1
- package/dist/ai-service/index.js +738 -474
- package/dist/ai-service/index.js.map +1 -1
- package/dist/ai-service/llm/context-v2/context-metrics.js +2 -2
- package/dist/ai-service/llm/context-v2/manager.d.ts +1 -3
- package/dist/ai-service/llm/context-v2/manager.d.ts.map +1 -1
- package/dist/ai-service/llm/context-v2/manager.js +0 -5
- package/dist/ai-service/llm/context-v2/manager.js.map +1 -1
- package/dist/ai-service/llm/context-v2/types.d.ts +1 -1
- package/dist/ai-service/llm/context-v2/types.d.ts.map +1 -1
- package/dist/ai-service/llm/context-v2/types.js.map +1 -1
- package/dist/ai-service/llm/stream/config.d.ts +1 -1
- package/dist/ai-service/llm/stream/config.d.ts.map +1 -1
- package/dist/ai-service/llm/stream/config.js.map +1 -1
- package/dist/ai-service/llm/stream/errors.d.ts +1 -4
- package/dist/ai-service/llm/stream/errors.d.ts.map +1 -1
- package/dist/ai-service/llm/stream/errors.js +2 -8
- package/dist/ai-service/llm/stream/errors.js.map +1 -1
- package/dist/ai-service/llm/stream/orchestrator.d.ts.map +1 -1
- package/dist/ai-service/llm/stream/orchestrator.js +6 -3
- package/dist/ai-service/llm/stream/orchestrator.js.map +1 -1
- package/dist/ai-service/llmobs/tracer.d.ts.map +1 -1
- package/dist/ai-service/llmobs/tracer.js +21 -4
- package/dist/ai-service/llmobs/tracer.js.map +1 -1
- package/dist/ai-service/managed-native-db-availability.d.ts +1 -1
- package/dist/ai-service/managed-native-db-availability.d.ts.map +1 -1
- package/dist/ai-service/managed-native-db-availability.js +2 -4
- package/dist/ai-service/managed-native-db-availability.js.map +1 -1
- package/dist/ai-service/policy-gate-remediation-usage.d.ts +1 -2
- package/dist/ai-service/policy-gate-remediation-usage.d.ts.map +1 -1
- package/dist/ai-service/policy-gate-remediation-usage.js +1 -2
- package/dist/ai-service/policy-gate-remediation-usage.js.map +1 -1
- package/dist/ai-service/skills/system/materialized.d.ts +1 -3
- package/dist/ai-service/skills/system/materialized.d.ts.map +1 -1
- package/dist/ai-service/skills/system/materialized.js +3 -3
- package/dist/ai-service/skills/system/materialized.js.map +1 -1
- package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
- package/dist/ai-service/state-machine/handlers/llm-generating.js +4 -6
- package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
- package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.d.ts +1 -1
- package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.d.ts.map +1 -1
- package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.js +1 -1
- package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.js.map +1 -1
- package/dist/ai-service/state-machine/helpers/user-response-message.d.ts.map +1 -1
- package/dist/ai-service/state-machine/helpers/user-response-message.js +2 -4
- package/dist/ai-service/state-machine/helpers/user-response-message.js.map +1 -1
- package/dist/ai-service/types.d.ts +0 -3
- package/dist/ai-service/types.d.ts.map +1 -1
- package/dist/ai-service/types.js.map +1 -1
- package/dist/extract-api-integrations.d.ts +91 -52
- package/dist/extract-api-integrations.d.ts.map +1 -1
- package/dist/extract-api-integrations.js +487 -512
- package/dist/extract-api-integrations.js.map +1 -1
- package/dist/file-sync-vite-plugin.d.ts.map +1 -1
- package/dist/file-sync-vite-plugin.js +5 -53
- package/dist/file-sync-vite-plugin.js.map +1 -1
- package/dist/file-system-helpers.d.ts.map +1 -1
- package/dist/file-system-helpers.js +2 -3
- package/dist/file-system-helpers.js.map +1 -1
- package/dist/git-service/index.d.ts +0 -1
- package/dist/git-service/index.d.ts.map +1 -1
- package/dist/git-service/index.js +38 -6
- package/dist/git-service/index.js.map +1 -1
- package/dist/git-service/managed-excludes.d.ts.map +1 -1
- package/dist/git-service/managed-excludes.js +0 -2
- package/dist/git-service/managed-excludes.js.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/injected-index.d.ts +3 -1
- package/dist/injected-index.d.ts.map +1 -1
- package/dist/injected-index.js +8 -3
- package/dist/injected-index.js.map +1 -1
- package/dist/lock-service/index.d.ts +0 -3
- package/dist/lock-service/index.d.ts.map +1 -1
- package/dist/lock-service/index.js +0 -7
- package/dist/lock-service/index.js.map +1 -1
- package/dist/migration/get-fullstack-template-dir.d.ts +5 -2
- package/dist/migration/get-fullstack-template-dir.d.ts.map +1 -1
- package/dist/migration/get-fullstack-template-dir.js +8 -5
- package/dist/migration/get-fullstack-template-dir.js.map +1 -1
- package/dist/migration-templates/app-fullstack/.gitignore +50 -0
- package/dist/plugin-options.d.ts +1 -1
- package/dist/plugin-options.d.ts.map +1 -1
- package/dist/policy-gate-runner.d.ts +7 -32
- package/dist/policy-gate-runner.d.ts.map +1 -1
- package/dist/policy-gate-runner.js +6 -23
- package/dist/policy-gate-runner.js.map +1 -1
- package/dist/socket-manager.d.ts +2 -9
- package/dist/socket-manager.d.ts.map +1 -1
- package/dist/socket-manager.js +19 -160
- package/dist/socket-manager.js.map +1 -1
- package/dist/sync-service/draft-helpers.d.ts +0 -9
- package/dist/sync-service/draft-helpers.d.ts.map +1 -1
- package/dist/sync-service/draft-helpers.js +0 -135
- package/dist/sync-service/draft-helpers.js.map +1 -1
- package/dist/sync-service/index.d.ts +1 -24
- package/dist/sync-service/index.d.ts.map +1 -1
- package/dist/sync-service/index.js +9 -197
- package/dist/sync-service/index.js.map +1 -1
- package/dist/sync-service/list-dir.d.ts +1 -3
- package/dist/sync-service/list-dir.d.ts.map +1 -1
- package/dist/sync-service/list-dir.js +1 -7
- package/dist/sync-service/list-dir.js.map +1 -1
- package/dist/util/log-sanitizer.d.ts +0 -4
- package/dist/util/log-sanitizer.d.ts.map +1 -1
- package/dist/util/log-sanitizer.js +0 -7
- package/dist/util/log-sanitizer.js.map +1 -1
- package/package.json +52 -57
- package/dist/agent-tool-executor/codex-drafts.d.ts +0 -12
- package/dist/agent-tool-executor/codex-drafts.d.ts.map +0 -1
- package/dist/agent-tool-executor/codex-drafts.js +0 -48
- package/dist/agent-tool-executor/codex-drafts.js.map +0 -1
- package/dist/agent-tool-executor/codex-exec-server.d.ts +0 -42
- package/dist/agent-tool-executor/codex-exec-server.d.ts.map +0 -1
- package/dist/agent-tool-executor/codex-exec-server.js +0 -405
- package/dist/agent-tool-executor/codex-exec-server.js.map +0 -1
- package/dist/agent-tool-executor/codex-execution-policy.d.ts +0 -12
- package/dist/agent-tool-executor/codex-execution-policy.d.ts.map +0 -1
- package/dist/agent-tool-executor/codex-execution-policy.js +0 -201
- package/dist/agent-tool-executor/codex-execution-policy.js.map +0 -1
- package/dist/agent-tool-executor/native-dotenv-watch-scope.d.ts +0 -12
- package/dist/agent-tool-executor/native-dotenv-watch-scope.d.ts.map +0 -1
- package/dist/agent-tool-executor/native-dotenv-watch-scope.js +0 -74
- package/dist/agent-tool-executor/native-dotenv-watch-scope.js.map +0 -1
- package/dist/ai-service/agent/security-scan-tools.d.ts +0 -12
- package/dist/ai-service/agent/security-scan-tools.d.ts.map +0 -1
- package/dist/ai-service/agent/security-scan-tools.js +0 -44
- package/dist/ai-service/agent/security-scan-tools.js.map +0 -1
- package/dist/ai-service/builder-conversation.d.ts +0 -70
- package/dist/ai-service/builder-conversation.d.ts.map +0 -1
- package/dist/ai-service/builder-conversation.js +0 -660
- package/dist/ai-service/builder-conversation.js.map +0 -1
- package/dist/ai-service/builder-inference-auth.d.ts +0 -11
- package/dist/ai-service/builder-inference-auth.d.ts.map +0 -1
- package/dist/ai-service/builder-inference-auth.js +0 -48
- package/dist/ai-service/builder-inference-auth.js.map +0 -1
- package/dist/ai-service/builder-runtime.d.ts +0 -181
- package/dist/ai-service/builder-runtime.d.ts.map +0 -1
- package/dist/ai-service/builder-runtime.js +0 -337
- package/dist/ai-service/builder-runtime.js.map +0 -1
- package/dist/ai-service/builder-session-store.d.ts +0 -26
- package/dist/ai-service/builder-session-store.d.ts.map +0 -1
- package/dist/ai-service/builder-session-store.js +0 -66
- package/dist/ai-service/builder-session-store.js.map +0 -1
- package/dist/ai-service/builder-tool-callbacks.d.ts +0 -26
- package/dist/ai-service/builder-tool-callbacks.d.ts.map +0 -1
- package/dist/ai-service/builder-tool-callbacks.js +0 -114
- package/dist/ai-service/builder-tool-callbacks.js.map +0 -1
- package/dist/ai-service/builder-tools.d.ts +0 -46
- package/dist/ai-service/builder-tools.d.ts.map +0 -1
- package/dist/ai-service/builder-tools.js +0 -181
- package/dist/ai-service/builder-tools.js.map +0 -1
- package/dist/ai-service/chat/switch-chat-seed.d.ts +0 -8
- package/dist/ai-service/chat/switch-chat-seed.d.ts.map +0 -1
- package/dist/ai-service/chat/switch-chat-seed.js +0 -47
- package/dist/ai-service/chat/switch-chat-seed.js.map +0 -1
- package/dist/ai-service/llm/request-settings.d.ts +0 -6
- package/dist/ai-service/llm/request-settings.d.ts.map +0 -1
- package/dist/ai-service/llm/request-settings.js +0 -21
- package/dist/ai-service/llm/request-settings.js.map +0 -1
- package/dist/ai-service/native-callback-order.d.ts +0 -7
- package/dist/ai-service/native-callback-order.d.ts.map +0 -1
- package/dist/ai-service/native-callback-order.js +0 -39
- package/dist/ai-service/native-callback-order.js.map +0 -1
- package/dist/ai-service/native-secret-redactor.d.ts +0 -4
- package/dist/ai-service/native-secret-redactor.d.ts.map +0 -1
- package/dist/ai-service/native-secret-redactor.js +0 -34
- package/dist/ai-service/native-secret-redactor.js.map +0 -1
- package/dist/ai-service/policy-gate-review.d.ts +0 -42
- package/dist/ai-service/policy-gate-review.d.ts.map +0 -1
- package/dist/ai-service/policy-gate-review.js +0 -664
- package/dist/ai-service/policy-gate-review.js.map +0 -1
- package/dist/ai-service/skills/system/native.d.ts +0 -7
- package/dist/ai-service/skills/system/native.d.ts.map +0 -1
- package/dist/ai-service/skills/system/native.js +0 -25
- package/dist/ai-service/skills/system/native.js.map +0 -1
- package/dist/ai-service/skills/system/paths.d.ts +0 -2
- package/dist/ai-service/skills/system/paths.d.ts.map +0 -1
- package/dist/ai-service/skills/system/paths.js +0 -2
- package/dist/ai-service/skills/system/paths.js.map +0 -1
- package/dist/git-service/credential-scope.d.ts +0 -16
- package/dist/git-service/credential-scope.d.ts.map +0 -1
- package/dist/git-service/credential-scope.js +0 -91
- package/dist/git-service/credential-scope.js.map +0 -1
- package/dist/review-runner.d.ts +0 -25
- package/dist/review-runner.d.ts.map +0 -1
- package/dist/review-runner.js +0 -196
- package/dist/review-runner.js.map +0 -1
- package/dist/sync-service/draft-mutation.d.ts +0 -11
- package/dist/sync-service/draft-mutation.d.ts.map +0 -1
- package/dist/sync-service/draft-mutation.js +0 -121
- package/dist/sync-service/draft-mutation.js.map +0 -1
- package/dist/sync-service/native-draft-session.d.ts +0 -22
- package/dist/sync-service/native-draft-session.d.ts.map +0 -1
- package/dist/sync-service/native-draft-session.js +0 -229
- package/dist/sync-service/native-draft-session.js.map +0 -1
- package/dist/sync-service/safe-directory-reader.d.ts +0 -24
- package/dist/sync-service/safe-directory-reader.d.ts.map +0 -1
- package/dist/sync-service/safe-directory-reader.js +0 -124
- package/dist/sync-service/safe-directory-reader.js.map +0 -1
|
@@ -1,664 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { stepCountIs } from "ai";
|
|
3
|
-
import { getAiQuotaPaywallReasonFromMessage, POLICY_GATE_MAX_TOTAL_TIME_MS, POLICY_GATE_STREAM_IDLE_TIMEOUT_MS, } from "@superblocksteam/shared";
|
|
4
|
-
import { getErrorMeta } from "../util/logger.js";
|
|
5
|
-
import { composeSecurityAgentPrompt, } from "./agent/prompts/build-security-scan-prompt.js";
|
|
6
|
-
import { buildSecurityScanTools, } from "./agent/security-scan-tools.js";
|
|
7
|
-
import { securityScanResultSchema, } from "./agent/tools/report-security-findings.js";
|
|
8
|
-
import { LLMClient } from "./llm/client.js";
|
|
9
|
-
import { resolveContextOptionsV2 } from "./llm/context-v2/config.js";
|
|
10
|
-
import { createLLMProvider } from "./llm/provider.js";
|
|
11
|
-
import { recordPolicyAgentExecution, } from "./policy-agent-metrics.js";
|
|
12
|
-
import { classifyPolicyGateError } from "./policy-gate-error.js";
|
|
13
|
-
import { policyGateStreamPartToAgentStep } from "./policy-gate-step.js";
|
|
14
|
-
import { scanContentForSecrets } from "./security/secret-scanner-service.js";
|
|
15
|
-
import { SecretRedactor } from "./security/secret-scanner.js";
|
|
16
|
-
import { finalizePolicyGateUsageMetrics, policyGateFailureFromStream, recordPolicyGateAttempt, } from "./state-machine/helpers/policy-gate-usage-metrics.js";
|
|
17
|
-
import { CLARK_USAGE_ORIGIN } from "./state-machine/helpers/prompt-request-metrics.js";
|
|
18
|
-
import { processLLMConfig } from "./util/llm-config-utils.js";
|
|
19
|
-
import { hasValidToolCall } from "./util/stop-condition.js";
|
|
20
|
-
const POLICY_GATE_USAGE_METADATA = {
|
|
21
|
-
origin: CLARK_USAGE_ORIGIN.policy_gate,
|
|
22
|
-
surface: "policy_gate",
|
|
23
|
-
};
|
|
24
|
-
function requireJwt(jwt) {
|
|
25
|
-
if (!jwt) {
|
|
26
|
-
throw new Error("[ai-service] no JWT available for policy gate AI inference");
|
|
27
|
-
}
|
|
28
|
-
return jwt;
|
|
29
|
-
}
|
|
30
|
-
const MAX_POLICY_GATE_STREAM_ERRORS = 5;
|
|
31
|
-
const MAX_POLICY_GATE_STREAM_ERROR_ARRAY_LENGTH = 10;
|
|
32
|
-
const MAX_POLICY_GATE_STREAM_ERROR_FIELD_LENGTH = 500;
|
|
33
|
-
const MAX_POLICY_GATE_STREAM_ERROR_OBJECT_DEPTH = 3;
|
|
34
|
-
const MAX_POLICY_GATE_STREAM_ERROR_OBJECT_KEYS = 20;
|
|
35
|
-
// Ceiling above the historical 30-step cap; 100 is an existing policy-agent
|
|
36
|
-
// histogram bucket. Tighten from production p99 if scans complete far below this.
|
|
37
|
-
const POLICY_GATE_MAX_STEPS = 100;
|
|
38
|
-
// AbortError near the budget is treated as timeout (SDK may abort slightly early).
|
|
39
|
-
const POLICY_GATE_TIMEOUT_CLASSIFICATION_SLACK_MS = 5_000;
|
|
40
|
-
const POLICY_GATE_STREAM_ERROR_REDACTED_VALUE = "[redacted]";
|
|
41
|
-
const POLICY_GATE_STREAM_ERROR_SECRET_KEY_PATTERN = /(access[-_]?key|api[-_]?key|authorization|connection[-_]?string|credential|dsn|password|private[-_]?key|secret|token)/i;
|
|
42
|
-
const POLICY_GATE_STREAM_ERROR_SECRET_VALUE_PATTERN_SOURCES = [
|
|
43
|
-
String.raw `\bbearer\s+[a-z0-9._~+/=-]+`,
|
|
44
|
-
String.raw `\bhttps?:\/\/[^@\s/:]+:[^@\s]+@\S+`,
|
|
45
|
-
String.raw `\b(?:mongodb(?:\+srv)?|mysql|postgres(?:ql)?|snowflake):\/\/\S+`,
|
|
46
|
-
String.raw `\bA[SK]IA[0-9A-Z]{16}\b`,
|
|
47
|
-
String.raw `\bgh[pousr]_[a-z0-9_]{20,}\b`,
|
|
48
|
-
String.raw `\bsk-[a-z0-9_-]{8,}\b`,
|
|
49
|
-
String.raw `\bxox[baprs]-[a-z0-9-]{10,}\b`,
|
|
50
|
-
];
|
|
51
|
-
/**
|
|
52
|
-
* Fails a policy gate stream that goes idle, independent of whatever
|
|
53
|
-
* abort/timeout wiring the stream itself does or doesn't honor. A dropped
|
|
54
|
-
* dev-server connection can stall the stream without ever rejecting it
|
|
55
|
-
* (APPS-5642), which leaves the run "running" forever since nothing throws
|
|
56
|
-
* for the existing catch/classification logic to act on.
|
|
57
|
-
*/
|
|
58
|
-
async function* withPolicyGateIdleTimeout(stream, idleTimeoutMs) {
|
|
59
|
-
const iterator = stream[Symbol.asyncIterator]();
|
|
60
|
-
try {
|
|
61
|
-
while (true) {
|
|
62
|
-
const nextResult = iterator.next();
|
|
63
|
-
// If the idle timeout wins the race below, this promise is abandoned
|
|
64
|
-
// mid-flight; attach a handler now so its eventual settlement (once the
|
|
65
|
-
// dead connection is cleaned up, if ever) never surfaces as an
|
|
66
|
-
// unhandled rejection. Promise.race still gets its own notification
|
|
67
|
-
// from this same promise independently.
|
|
68
|
-
nextResult.catch(() => { });
|
|
69
|
-
let timer;
|
|
70
|
-
const idleTimeout = new Promise((_, reject) => {
|
|
71
|
-
timer = setTimeout(() => {
|
|
72
|
-
reject(Object.assign(new Error("Policy gate stream went idle"), {
|
|
73
|
-
name: "TimeoutError",
|
|
74
|
-
}));
|
|
75
|
-
}, idleTimeoutMs);
|
|
76
|
-
});
|
|
77
|
-
let result;
|
|
78
|
-
try {
|
|
79
|
-
result = await Promise.race([nextResult, idleTimeout]);
|
|
80
|
-
}
|
|
81
|
-
finally {
|
|
82
|
-
clearTimeout(timer);
|
|
83
|
-
}
|
|
84
|
-
if (result.done) {
|
|
85
|
-
return;
|
|
86
|
-
}
|
|
87
|
-
yield result.value;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
finally {
|
|
91
|
-
// Best-effort only: never await this. On the exact connection this
|
|
92
|
-
// wrapper exists to fail past — one that stopped responding without
|
|
93
|
-
// erroring or closing — iterator.return() can hang the same way
|
|
94
|
-
// .next() did, and blocking cleanup on it here would defeat the whole
|
|
95
|
-
// point of a timeout that's supposed to guarantee termination.
|
|
96
|
-
void iterator.return?.()?.catch(() => { });
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
function truncatePolicyGateStreamErrorField(value) {
|
|
100
|
-
if (value.length <= MAX_POLICY_GATE_STREAM_ERROR_FIELD_LENGTH) {
|
|
101
|
-
return value;
|
|
102
|
-
}
|
|
103
|
-
return `${value.slice(0, MAX_POLICY_GATE_STREAM_ERROR_FIELD_LENGTH)}...`;
|
|
104
|
-
}
|
|
105
|
-
function sanitizePolicyGateStreamErrorString(value) {
|
|
106
|
-
const redacted = POLICY_GATE_STREAM_ERROR_SECRET_VALUE_PATTERN_SOURCES.reduce((current, patternSource) => current.replace(new RegExp(patternSource, "gi"), POLICY_GATE_STREAM_ERROR_REDACTED_VALUE), value);
|
|
107
|
-
return truncatePolicyGateStreamErrorField(redacted);
|
|
108
|
-
}
|
|
109
|
-
function isUnhelpfulPolicyGateStreamError(serialized) {
|
|
110
|
-
return (Object.keys(serialized).length === 1 &&
|
|
111
|
-
serialized.message === "[object Object]");
|
|
112
|
-
}
|
|
113
|
-
function serializePolicyGateStreamError(error, streamPart) {
|
|
114
|
-
const attachStreamPartIfUseful = (serialized) => {
|
|
115
|
-
if (isUnhelpfulPolicyGateStreamError(serialized) &&
|
|
116
|
-
streamPart &&
|
|
117
|
-
typeof streamPart === "object") {
|
|
118
|
-
return {
|
|
119
|
-
...serialized,
|
|
120
|
-
streamPart: serializePolicyGateStreamErrorRecord(streamPart, 0),
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
return serialized;
|
|
124
|
-
};
|
|
125
|
-
if (error instanceof Error) {
|
|
126
|
-
const serialized = {
|
|
127
|
-
message: sanitizePolicyGateStreamErrorString(error.message),
|
|
128
|
-
name: error.name,
|
|
129
|
-
};
|
|
130
|
-
const extraFields = serializePolicyGateStreamErrorRecord(error, 0);
|
|
131
|
-
return attachStreamPartIfUseful({
|
|
132
|
-
...extraFields,
|
|
133
|
-
...serialized,
|
|
134
|
-
});
|
|
135
|
-
}
|
|
136
|
-
if (error && typeof error === "object") {
|
|
137
|
-
const serialized = serializePolicyGateStreamErrorRecord(error, 0);
|
|
138
|
-
if (Object.keys(serialized).length > 0) {
|
|
139
|
-
return attachStreamPartIfUseful(serialized);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
return attachStreamPartIfUseful({
|
|
143
|
-
message: truncatePolicyGateStreamErrorField(String(error)),
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
function serializePolicyGateStreamErrorValue(value, depth) {
|
|
147
|
-
if (typeof value === "string") {
|
|
148
|
-
return sanitizePolicyGateStreamErrorString(value);
|
|
149
|
-
}
|
|
150
|
-
if (typeof value === "number" ||
|
|
151
|
-
typeof value === "boolean" ||
|
|
152
|
-
value === null) {
|
|
153
|
-
return value;
|
|
154
|
-
}
|
|
155
|
-
if (value instanceof Error) {
|
|
156
|
-
return {
|
|
157
|
-
...serializePolicyGateStreamErrorRecord(value, depth + 1),
|
|
158
|
-
message: sanitizePolicyGateStreamErrorString(value.message),
|
|
159
|
-
name: value.name,
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
if (Array.isArray(value)) {
|
|
163
|
-
if (depth >= MAX_POLICY_GATE_STREAM_ERROR_OBJECT_DEPTH) {
|
|
164
|
-
return `[array:${value.length}]`;
|
|
165
|
-
}
|
|
166
|
-
return value
|
|
167
|
-
.slice(0, MAX_POLICY_GATE_STREAM_ERROR_ARRAY_LENGTH)
|
|
168
|
-
.map((item) => serializePolicyGateStreamErrorValue(item, depth + 1));
|
|
169
|
-
}
|
|
170
|
-
if (value && typeof value === "object") {
|
|
171
|
-
if (depth >= MAX_POLICY_GATE_STREAM_ERROR_OBJECT_DEPTH) {
|
|
172
|
-
return "[object]";
|
|
173
|
-
}
|
|
174
|
-
return serializePolicyGateStreamErrorRecord(value, depth + 1);
|
|
175
|
-
}
|
|
176
|
-
if (value === undefined) {
|
|
177
|
-
return undefined;
|
|
178
|
-
}
|
|
179
|
-
return sanitizePolicyGateStreamErrorString(String(value));
|
|
180
|
-
}
|
|
181
|
-
function serializePolicyGateStreamErrorRecord(value, depth) {
|
|
182
|
-
const output = {};
|
|
183
|
-
for (const key of Object.keys(value).slice(0, MAX_POLICY_GATE_STREAM_ERROR_OBJECT_KEYS)) {
|
|
184
|
-
if (POLICY_GATE_STREAM_ERROR_SECRET_KEY_PATTERN.test(key)) {
|
|
185
|
-
output[key] = POLICY_GATE_STREAM_ERROR_REDACTED_VALUE;
|
|
186
|
-
continue;
|
|
187
|
-
}
|
|
188
|
-
const fieldValue = value[key];
|
|
189
|
-
const serializedValue = serializePolicyGateStreamErrorValue(fieldValue, depth);
|
|
190
|
-
if (serializedValue !== undefined) {
|
|
191
|
-
output[key] = serializedValue;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
return output;
|
|
195
|
-
}
|
|
196
|
-
export async function runPolicyGateReview(deps, request) {
|
|
197
|
-
const logger = deps.logger;
|
|
198
|
-
logger.info(`[ai-service] Policy gate execution requested for app=${request.applicationId}`);
|
|
199
|
-
const startedAt = Date.now();
|
|
200
|
-
const policyRunLogContext = {
|
|
201
|
-
applicationId: request.applicationId,
|
|
202
|
-
reviewPolicyId: request.reviewPolicyId,
|
|
203
|
-
};
|
|
204
|
-
const toolCallCounts = {};
|
|
205
|
-
const filePathsRead = new Set();
|
|
206
|
-
const filePathsListed = new Set();
|
|
207
|
-
const finishReasons = [];
|
|
208
|
-
const grepPatterns = [];
|
|
209
|
-
const grepMatchCounts = [];
|
|
210
|
-
const grepPatternByToolCallId = new Map();
|
|
211
|
-
const lsPathByToolCallId = new Map();
|
|
212
|
-
const streamErrors = [];
|
|
213
|
-
const streamPartTypeCounts = {};
|
|
214
|
-
let stepCount = 0;
|
|
215
|
-
let textDeltaChars = 0;
|
|
216
|
-
let failureErrorCode;
|
|
217
|
-
let maxOutputTokens;
|
|
218
|
-
let modelName;
|
|
219
|
-
let promptHash;
|
|
220
|
-
let quotaReason;
|
|
221
|
-
// Hoisted so the outer catch can attribute a failed run to the same model as
|
|
222
|
-
// the attempt it belongs to. Usage arrives from the client's usage observer,
|
|
223
|
-
// which also flushes on abort, on error, and for compaction calls.
|
|
224
|
-
let coreModel;
|
|
225
|
-
const llmUsage = [];
|
|
226
|
-
let hadFallback = false;
|
|
227
|
-
let attemptRecorded = false;
|
|
228
|
-
const scanRoot = typeof deps.appShell.appRootDirPath === "string"
|
|
229
|
-
? deps.appShell.appRootDirPath
|
|
230
|
-
: undefined;
|
|
231
|
-
let scanResult;
|
|
232
|
-
let lastReportCall;
|
|
233
|
-
let metricsRecorded = false;
|
|
234
|
-
const totalToolCalls = () => Object.values(toolCallCounts).reduce((sum, count) => sum + count, 0);
|
|
235
|
-
const recordExecutionMetrics = (outcome) => {
|
|
236
|
-
if (metricsRecorded) {
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
metricsRecorded = true;
|
|
240
|
-
recordPolicyAgentExecution({
|
|
241
|
-
durationMs: Date.now() - startedAt,
|
|
242
|
-
llmUsage,
|
|
243
|
-
outcome,
|
|
244
|
-
stepCount,
|
|
245
|
-
toolCallCount: totalToolCalls(),
|
|
246
|
-
});
|
|
247
|
-
};
|
|
248
|
-
const buildRuntimeMetadata = (finalFailureReason) => ({
|
|
249
|
-
diagnosticsVersion: 3,
|
|
250
|
-
diffFiles: request.scanScopeJson?.changedFiles ?? [],
|
|
251
|
-
durationMs: Date.now() - startedAt,
|
|
252
|
-
filePathsListed: Array.from(filePathsListed).slice(0, 100),
|
|
253
|
-
filePathsRead: Array.from(filePathsRead).slice(0, 100),
|
|
254
|
-
finalFailureReason,
|
|
255
|
-
finishReasons,
|
|
256
|
-
grepMatchCounts,
|
|
257
|
-
grepPatterns,
|
|
258
|
-
maxOutputTokens,
|
|
259
|
-
model: modelName,
|
|
260
|
-
promptHash,
|
|
261
|
-
quotaReason,
|
|
262
|
-
reportToolCalled: Boolean(scanResult),
|
|
263
|
-
scanComplete: scanResult?.scanComplete === true,
|
|
264
|
-
scanRoot,
|
|
265
|
-
stepCount,
|
|
266
|
-
streamErrors,
|
|
267
|
-
streamPartTypeCounts,
|
|
268
|
-
textDeltaChars,
|
|
269
|
-
toolCallCounts,
|
|
270
|
-
});
|
|
271
|
-
const failPolicyGateExecution = (message, errorCode) => {
|
|
272
|
-
failureErrorCode = errorCode;
|
|
273
|
-
recordExecutionMetrics(errorCode);
|
|
274
|
-
throw Object.assign(new Error(message), {
|
|
275
|
-
errorCode,
|
|
276
|
-
runtimeMetadataJson: buildRuntimeMetadata(message),
|
|
277
|
-
});
|
|
278
|
-
};
|
|
279
|
-
try {
|
|
280
|
-
try {
|
|
281
|
-
await deps.ensureAiQuotaAvailable(request.jwt);
|
|
282
|
-
}
|
|
283
|
-
catch (error) {
|
|
284
|
-
const message = error instanceof Error ? error.message : "AI quota unavailable";
|
|
285
|
-
const errorCode = classifyPolicyGateError(error);
|
|
286
|
-
if (errorCode === "out_of_credits") {
|
|
287
|
-
quotaReason = getAiQuotaPaywallReasonFromMessage(message);
|
|
288
|
-
}
|
|
289
|
-
failPolicyGateExecution(message, errorCode);
|
|
290
|
-
}
|
|
291
|
-
const requestLlmConfig = request.llmConfig;
|
|
292
|
-
const contextLlmConfig = deps.defaultLlmConfig;
|
|
293
|
-
const llmConfig = requestLlmConfig ?? contextLlmConfig;
|
|
294
|
-
const llmProvider = createLLMProvider(deps.getLLMProviderSettings(llmConfig), () => requireJwt(request.jwt), llmConfig, () => ({
|
|
295
|
-
ai_agent_run_id: request.aiAgentRunId,
|
|
296
|
-
application_id: request.applicationId,
|
|
297
|
-
metadata: POLICY_GATE_USAGE_METADATA,
|
|
298
|
-
session_id: deps.sessionId,
|
|
299
|
-
trigger_type: "policy_gate",
|
|
300
|
-
}));
|
|
301
|
-
const { model, providerConfig } = llmProvider.modelForTask("generateBroadEdit");
|
|
302
|
-
const { model: summarizationModel, providerConfig: summarizationProviderConfig, } = llmProvider.modelForTask("summarizeMessages");
|
|
303
|
-
modelName = typeof model === "string" ? model : model.modelId;
|
|
304
|
-
coreModel = llmConfig?.coreModel;
|
|
305
|
-
// Counted as soon as the model resolves, because everything below is
|
|
306
|
-
// inside this try and so is guaranteed a terminal outcome from the catch.
|
|
307
|
-
// A throw above this line leaves no attempt and records no outcome, which
|
|
308
|
-
// keeps the failure ratio free of outcomes with no denominator.
|
|
309
|
-
recordPolicyGateAttempt({ coreModel });
|
|
310
|
-
attemptRecorded = true;
|
|
311
|
-
const availableIntegrations = await deps.integrationStore.availableIntegrations();
|
|
312
|
-
const integrations = availableIntegrations.map((i) => ({
|
|
313
|
-
name: i.name,
|
|
314
|
-
pluginType: i.plugin?.id ?? "unknown",
|
|
315
|
-
}));
|
|
316
|
-
const scanScopeJson = request.scanScopeJson;
|
|
317
|
-
const appContext = { integrations };
|
|
318
|
-
let systemPrompt = composeSecurityAgentPrompt(appContext, request.adminPrompt, scanScopeJson);
|
|
319
|
-
try {
|
|
320
|
-
const scanResult = await scanContentForSecrets(systemPrompt, {
|
|
321
|
-
consumer: "policy_gate",
|
|
322
|
-
});
|
|
323
|
-
if (scanResult.success && scanResult.hasSecrets) {
|
|
324
|
-
systemPrompt = new SecretRedactor(scanResult.findings).redact(systemPrompt);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
catch {
|
|
328
|
-
logger.warn("[secret-scan] Secret scan threw on policy gate text; using the original text");
|
|
329
|
-
}
|
|
330
|
-
promptHash = createHash("sha256").update(systemPrompt).digest("hex");
|
|
331
|
-
const scanContext = {};
|
|
332
|
-
const { headers, interleavedThinking, maxOutputTokens: configuredMaxOutputTokens, providerOptions, thinkingBudgetTokens, thinkingEnabled, } = processLLMConfig(llmConfig);
|
|
333
|
-
maxOutputTokens = configuredMaxOutputTokens;
|
|
334
|
-
// Scan-owned client: gate JWT, own usage sink, built first so scan tools
|
|
335
|
-
// (webFetch generateObject) use this client instead of Clark's.
|
|
336
|
-
const policyGateLlmClient = new LLMClient({
|
|
337
|
-
appShell: deps.appShell,
|
|
338
|
-
applicationId: request.applicationId,
|
|
339
|
-
contextManagerV2: deps.contextManagerV2,
|
|
340
|
-
getJwt: () => requireJwt(request.jwt),
|
|
341
|
-
onUsageRecorded: (usage) => {
|
|
342
|
-
if (usage.hadProviderFallback === true) {
|
|
343
|
-
hadFallback = true;
|
|
344
|
-
}
|
|
345
|
-
llmUsage.push(...usage.promptCostUsageEntries);
|
|
346
|
-
},
|
|
347
|
-
organizationId: deps.organizationId,
|
|
348
|
-
stepTokenUsageLabels: () => ({
|
|
349
|
-
coreModel,
|
|
350
|
-
mode: "build",
|
|
351
|
-
surface: POLICY_GATE_USAGE_METADATA.surface,
|
|
352
|
-
}),
|
|
353
|
-
retryOptions: deps.retryOptions,
|
|
354
|
-
unifiedProviderEnabled: deps.features.unifiedProviderEnabled ?? false,
|
|
355
|
-
});
|
|
356
|
-
const scanToolsDeps = {
|
|
357
|
-
appShell: deps.appShell,
|
|
358
|
-
features: deps.features,
|
|
359
|
-
integrationStore: deps.integrationStore,
|
|
360
|
-
llmClient: policyGateLlmClient,
|
|
361
|
-
llmProvider: llmProvider,
|
|
362
|
-
logger,
|
|
363
|
-
getPeer: deps.getPeer,
|
|
364
|
-
storeSummary: (toolCallId, summary) => {
|
|
365
|
-
scanContext.current?.storeSummary(toolCallId, summary);
|
|
366
|
-
},
|
|
367
|
-
};
|
|
368
|
-
const tools = await buildSecurityScanTools(scanToolsDeps);
|
|
369
|
-
const timeoutSignal = AbortSignal.timeout(POLICY_GATE_MAX_TOTAL_TIME_MS);
|
|
370
|
-
const result = await policyGateLlmClient.streamText({
|
|
371
|
-
abortSignal: request.abortSignal
|
|
372
|
-
? AbortSignal.any([request.abortSignal, timeoutSignal])
|
|
373
|
-
: timeoutSignal,
|
|
374
|
-
context: {
|
|
375
|
-
contextManagement: {
|
|
376
|
-
summarizationModel,
|
|
377
|
-
summarizationProviderConfig,
|
|
378
|
-
type: "client",
|
|
379
|
-
},
|
|
380
|
-
// Product defaults: caller llmConfig cannot shrink the scan window to 0.
|
|
381
|
-
contextOptionsV2: resolveContextOptionsV2(),
|
|
382
|
-
},
|
|
383
|
-
enableFallback: llmConfig?.unifiedProviderEnabled ?? false,
|
|
384
|
-
fallbackStrategy: llmConfig?.fallbackStrategy,
|
|
385
|
-
headers,
|
|
386
|
-
logging: false,
|
|
387
|
-
// processLLMConfig returns the same MAX_OUTPUT_TOKENS cap Clark uses.
|
|
388
|
-
maxOutputTokens: configuredMaxOutputTokens,
|
|
389
|
-
model,
|
|
390
|
-
onContextReady: (ctx) => {
|
|
391
|
-
scanContext.current = ctx;
|
|
392
|
-
},
|
|
393
|
-
providerConfig,
|
|
394
|
-
providerOptions: {
|
|
395
|
-
...providerOptions,
|
|
396
|
-
...(coreModel ? { unified: { coreModel } } : {}),
|
|
397
|
-
},
|
|
398
|
-
recordObsContent: false,
|
|
399
|
-
system: systemPrompt,
|
|
400
|
-
thinking: {
|
|
401
|
-
budgetTokens: thinkingBudgetTokens,
|
|
402
|
-
enabled: thinkingEnabled,
|
|
403
|
-
interleaved: interleavedThinking,
|
|
404
|
-
},
|
|
405
|
-
tools,
|
|
406
|
-
stopWhen: [
|
|
407
|
-
hasValidToolCall("reportReviewRun", 5),
|
|
408
|
-
stepCountIs(POLICY_GATE_MAX_STEPS),
|
|
409
|
-
],
|
|
410
|
-
user: {
|
|
411
|
-
content: "Begin your security review of this application now.",
|
|
412
|
-
role: "user",
|
|
413
|
-
},
|
|
414
|
-
});
|
|
415
|
-
// Best-effort: surface the agent's latest tool/reasoning step in the editor
|
|
416
|
-
// so a running policy row shows live activity instead of an opaque spinner.
|
|
417
|
-
// Only meaningful when an editor session is connected; never blocks the run.
|
|
418
|
-
const emitAgentStep = (part) => {
|
|
419
|
-
const peer = deps.getConnectedPeer();
|
|
420
|
-
if (!peer) {
|
|
421
|
-
return;
|
|
422
|
-
}
|
|
423
|
-
const step = policyGateStreamPartToAgentStep(part);
|
|
424
|
-
if (!step) {
|
|
425
|
-
return;
|
|
426
|
-
}
|
|
427
|
-
void peer.call
|
|
428
|
-
.aiPushPolicyAgentStep({
|
|
429
|
-
applicationId: request.applicationId,
|
|
430
|
-
policyId: request.reviewPolicyId,
|
|
431
|
-
step,
|
|
432
|
-
})
|
|
433
|
-
.catch((error) => {
|
|
434
|
-
logger.warn("[ai-service] Failed to push policy agent step", getErrorMeta(error));
|
|
435
|
-
});
|
|
436
|
-
};
|
|
437
|
-
try {
|
|
438
|
-
for await (const part of withPolicyGateIdleTimeout(result.fullStream, POLICY_GATE_STREAM_IDLE_TIMEOUT_MS)) {
|
|
439
|
-
emitAgentStep(part);
|
|
440
|
-
const partType = typeof part.type === "string"
|
|
441
|
-
? part.type
|
|
442
|
-
: "unknown";
|
|
443
|
-
streamPartTypeCounts[partType] =
|
|
444
|
-
(streamPartTypeCounts[partType] ?? 0) + 1;
|
|
445
|
-
const textDelta = part.textDelta ??
|
|
446
|
-
part.text ??
|
|
447
|
-
part.delta;
|
|
448
|
-
if (typeof textDelta === "string") {
|
|
449
|
-
textDeltaChars += textDelta.length;
|
|
450
|
-
}
|
|
451
|
-
if (partType === "finish-step") {
|
|
452
|
-
stepCount += 1;
|
|
453
|
-
}
|
|
454
|
-
const finishReason = part.finishReason;
|
|
455
|
-
if (typeof finishReason === "string") {
|
|
456
|
-
finishReasons.push(finishReason);
|
|
457
|
-
}
|
|
458
|
-
if (part.type === "tool-call") {
|
|
459
|
-
toolCallCounts[part.toolName] =
|
|
460
|
-
(toolCallCounts[part.toolName] ?? 0) + 1;
|
|
461
|
-
const input = part.input ??
|
|
462
|
-
part.args;
|
|
463
|
-
if (input && typeof input === "object") {
|
|
464
|
-
const record = input;
|
|
465
|
-
if (part.toolName === "build_readFile" &&
|
|
466
|
-
typeof record.filePath === "string") {
|
|
467
|
-
filePathsRead.add(record.filePath);
|
|
468
|
-
}
|
|
469
|
-
if (part.toolName === "grep" &&
|
|
470
|
-
typeof record.pattern === "string") {
|
|
471
|
-
grepPatterns.push(record.pattern);
|
|
472
|
-
const toolCallId = typeof part.toolCallId ===
|
|
473
|
-
"string"
|
|
474
|
-
? part.toolCallId
|
|
475
|
-
: `grep-${grepPatterns.length}`;
|
|
476
|
-
grepPatternByToolCallId.set(toolCallId, record.pattern);
|
|
477
|
-
}
|
|
478
|
-
if (part.toolName === "ls") {
|
|
479
|
-
const toolCallId = typeof part.toolCallId ===
|
|
480
|
-
"string"
|
|
481
|
-
? part.toolCallId
|
|
482
|
-
: `ls-${lsPathByToolCallId.size + 1}`;
|
|
483
|
-
lsPathByToolCallId.set(toolCallId, typeof record.path === "string" ? record.path : ".");
|
|
484
|
-
}
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
if (part.type === "tool-result") {
|
|
488
|
-
const output = part.output ??
|
|
489
|
-
part.result;
|
|
490
|
-
if (output && typeof output === "object") {
|
|
491
|
-
const record = output;
|
|
492
|
-
if ((part.toolName === "build_listFiles" ||
|
|
493
|
-
part.toolName === "glob") &&
|
|
494
|
-
Array.isArray(record.files)) {
|
|
495
|
-
for (const file of record.files) {
|
|
496
|
-
if (typeof file === "string") {
|
|
497
|
-
filePathsListed.add(file);
|
|
498
|
-
}
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
if (part.toolName === "ls" && typeof record.output === "string") {
|
|
502
|
-
const toolCallId = typeof part.toolCallId ===
|
|
503
|
-
"string"
|
|
504
|
-
? part.toolCallId
|
|
505
|
-
: undefined;
|
|
506
|
-
const dirPath = (toolCallId ? lsPathByToolCallId.get(toolCallId) : undefined) ??
|
|
507
|
-
".";
|
|
508
|
-
for (const line of record.output.split("\n")) {
|
|
509
|
-
const trimmed = line.trim();
|
|
510
|
-
if (!trimmed || trimmed.startsWith("total")) {
|
|
511
|
-
continue;
|
|
512
|
-
}
|
|
513
|
-
const name = trimmed.split(/\s+/).at(-1);
|
|
514
|
-
if (!name) {
|
|
515
|
-
continue;
|
|
516
|
-
}
|
|
517
|
-
filePathsListed.add(dirPath === "."
|
|
518
|
-
? name
|
|
519
|
-
: `${dirPath.replace(/\/$/, "")}/${name}`);
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
if (part.toolName === "grep" &&
|
|
523
|
-
typeof record.matches === "number") {
|
|
524
|
-
const toolCallId = typeof part.toolCallId ===
|
|
525
|
-
"string"
|
|
526
|
-
? part.toolCallId
|
|
527
|
-
: `grep-${grepMatchCounts.length + 1}`;
|
|
528
|
-
grepMatchCounts.push({
|
|
529
|
-
matches: record.matches,
|
|
530
|
-
pattern: grepPatternByToolCallId.get(toolCallId) ??
|
|
531
|
-
grepPatterns[grepPatterns.length - 1] ??
|
|
532
|
-
"",
|
|
533
|
-
});
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
if (part.type === "tool-call" && part.toolName === "reportReviewRun") {
|
|
538
|
-
const input = part.input ??
|
|
539
|
-
part.args;
|
|
540
|
-
lastReportCall = {
|
|
541
|
-
input,
|
|
542
|
-
invalid: part.invalid === true,
|
|
543
|
-
};
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
if (lastReportCall) {
|
|
547
|
-
const parsedInput = securityScanResultSchema.safeParse(lastReportCall.input);
|
|
548
|
-
if (lastReportCall.invalid || !parsedInput.success) {
|
|
549
|
-
const reportError = parsedInput.success
|
|
550
|
-
? new Error("reportReviewRun call was invalid")
|
|
551
|
-
: parsedInput.error;
|
|
552
|
-
logger.error("[ai-service] Invalid policy gate reportReviewRun input", {
|
|
553
|
-
...policyRunLogContext,
|
|
554
|
-
...getErrorMeta(reportError),
|
|
555
|
-
});
|
|
556
|
-
failPolicyGateExecution("Invalid policy gate reportReviewRun input", "invalid_report");
|
|
557
|
-
}
|
|
558
|
-
scanResult = parsedInput.data;
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
catch (error) {
|
|
562
|
-
if (failureErrorCode !== undefined) {
|
|
563
|
-
throw error;
|
|
564
|
-
}
|
|
565
|
-
if (error instanceof Error &&
|
|
566
|
-
(error.name === "AbortError" ||
|
|
567
|
-
error.name === "AbortedError" ||
|
|
568
|
-
error.name === "TimeoutError")) {
|
|
569
|
-
const elapsedMs = Date.now() - startedAt;
|
|
570
|
-
const isBudgetTimeout = error.name === "TimeoutError" ||
|
|
571
|
-
elapsedMs + POLICY_GATE_TIMEOUT_CLASSIFICATION_SLACK_MS >=
|
|
572
|
-
POLICY_GATE_MAX_TOTAL_TIME_MS;
|
|
573
|
-
if (isBudgetTimeout) {
|
|
574
|
-
logger.warn("[ai-service] Policy gate agent timed out", {
|
|
575
|
-
...policyRunLogContext,
|
|
576
|
-
...getErrorMeta(error),
|
|
577
|
-
elapsedMs,
|
|
578
|
-
});
|
|
579
|
-
failPolicyGateExecution("Policy gate agent timed out", "llm_timeout");
|
|
580
|
-
}
|
|
581
|
-
logger.warn("[ai-service] Policy gate agent aborted", {
|
|
582
|
-
...policyRunLogContext,
|
|
583
|
-
...getErrorMeta(error),
|
|
584
|
-
elapsedMs,
|
|
585
|
-
});
|
|
586
|
-
failPolicyGateExecution("Policy gate agent aborted", "aborted");
|
|
587
|
-
}
|
|
588
|
-
const streamError = serializePolicyGateStreamError(error);
|
|
589
|
-
if (streamErrors.length < MAX_POLICY_GATE_STREAM_ERRORS) {
|
|
590
|
-
streamErrors.push(streamError);
|
|
591
|
-
}
|
|
592
|
-
logger.warn("[ai-service] Policy gate stream error", {
|
|
593
|
-
...policyRunLogContext,
|
|
594
|
-
streamError,
|
|
595
|
-
});
|
|
596
|
-
const errorCode = classifyPolicyGateError(error);
|
|
597
|
-
if (errorCode === "out_of_credits") {
|
|
598
|
-
quotaReason =
|
|
599
|
-
error instanceof Error
|
|
600
|
-
? getAiQuotaPaywallReasonFromMessage(error.message)
|
|
601
|
-
: undefined;
|
|
602
|
-
}
|
|
603
|
-
failPolicyGateExecution(error instanceof Error ? error.message : "Policy gate stream failed", errorCode);
|
|
604
|
-
}
|
|
605
|
-
if (!scanResult) {
|
|
606
|
-
logger.warn("[ai-service] Policy gate agent did not call reportReviewRun", policyRunLogContext);
|
|
607
|
-
if (finishReasons.includes("length")) {
|
|
608
|
-
const outputTokens = llmUsage.at(-1)?.outputTokens ?? 0;
|
|
609
|
-
failPolicyGateExecution(`Policy gate agent reached the output token limit of ${maxOutputTokens ?? 0} after producing ${outputTokens} output tokens`, "output_token_limit");
|
|
610
|
-
}
|
|
611
|
-
if (finishReasons.includes("content-filter")) {
|
|
612
|
-
failPolicyGateExecution("Policy gate agent output was refused by the provider content filter", "llm_refusal");
|
|
613
|
-
}
|
|
614
|
-
failPolicyGateExecution("Policy gate agent did not complete a report", "missing_report");
|
|
615
|
-
}
|
|
616
|
-
const completedScanResult = scanResult;
|
|
617
|
-
if (!completedScanResult.scanComplete) {
|
|
618
|
-
logger.warn("[ai-service] Policy gate agent reported an incomplete scan", {
|
|
619
|
-
...policyRunLogContext,
|
|
620
|
-
findingCount: completedScanResult.findings.length,
|
|
621
|
-
scannedFiles: completedScanResult.scannedFiles,
|
|
622
|
-
});
|
|
623
|
-
failPolicyGateExecution("Policy gate agent did not complete a report", "incomplete_report");
|
|
624
|
-
}
|
|
625
|
-
logger.info(`[ai-service] Policy gate execution complete: ${completedScanResult.findings.length} findings`);
|
|
626
|
-
recordExecutionMetrics("success");
|
|
627
|
-
await finalizePolicyGateUsageMetrics({
|
|
628
|
-
aiAgentRunId: request.aiAgentRunId,
|
|
629
|
-
chatSessionStore: deps.chatSessionStore,
|
|
630
|
-
coreModel,
|
|
631
|
-
hadFallback,
|
|
632
|
-
llmUsage,
|
|
633
|
-
logger,
|
|
634
|
-
outcome: "success",
|
|
635
|
-
});
|
|
636
|
-
return {
|
|
637
|
-
...completedScanResult,
|
|
638
|
-
runtimeMetadataJson: buildRuntimeMetadata(),
|
|
639
|
-
};
|
|
640
|
-
}
|
|
641
|
-
catch (error) {
|
|
642
|
-
if (!metricsRecorded) {
|
|
643
|
-
recordExecutionMetrics("error");
|
|
644
|
-
}
|
|
645
|
-
// Only when the attempt was counted, so a failure that happened before
|
|
646
|
-
// the model resolved cannot land as an outcome with no denominator.
|
|
647
|
-
// Failing before the stream exists is still an outcome, just one with no
|
|
648
|
-
// tokens to price.
|
|
649
|
-
if (attemptRecorded) {
|
|
650
|
-
await finalizePolicyGateUsageMetrics({
|
|
651
|
-
aiAgentRunId: request.aiAgentRunId,
|
|
652
|
-
chatSessionStore: deps.chatSessionStore,
|
|
653
|
-
coreModel,
|
|
654
|
-
failure: policyGateFailureFromStream(failureErrorCode, quotaReason),
|
|
655
|
-
hadFallback,
|
|
656
|
-
llmUsage,
|
|
657
|
-
logger,
|
|
658
|
-
outcome: "failure",
|
|
659
|
-
});
|
|
660
|
-
}
|
|
661
|
-
throw error;
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
//# sourceMappingURL=policy-gate-review.js.map
|