@superblocksteam/vite-plugin-file-sync 2.0.172-next.0 → 2.0.173-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/ai-service/agent/middleware.d.ts.map +1 -1
  2. package/dist/ai-service/agent/middleware.js +45 -0
  3. package/dist/ai-service/agent/middleware.js.map +1 -1
  4. package/dist/ai-service/agent/prompts/build-base-system-prompt.d.ts.map +1 -1
  5. package/dist/ai-service/agent/prompts/build-base-system-prompt.js +2 -0
  6. package/dist/ai-service/agent/prompts/build-base-system-prompt.js.map +1 -1
  7. package/dist/ai-service/agent/prompts/build-security-scan-prompt.d.ts.map +1 -1
  8. package/dist/ai-service/agent/prompts/build-security-scan-prompt.js +106 -11
  9. package/dist/ai-service/agent/prompts/build-security-scan-prompt.js.map +1 -1
  10. package/dist/ai-service/agent/tool-permission-delivery-metrics.d.ts +1 -1
  11. package/dist/ai-service/agent/tool-permission-delivery-metrics.d.ts.map +1 -1
  12. package/dist/ai-service/agent/tool-permission-delivery-metrics.js +1 -1
  13. package/dist/ai-service/agent/tool-permission-delivery-metrics.js.map +1 -1
  14. package/dist/ai-service/agent/tool-permission-delivery.d.ts +2 -0
  15. package/dist/ai-service/agent/tool-permission-delivery.d.ts.map +1 -1
  16. package/dist/ai-service/agent/tool-permission-delivery.js +7 -0
  17. package/dist/ai-service/agent/tool-permission-delivery.js.map +1 -1
  18. package/dist/ai-service/agent/tools/apis/get-api-docs.d.ts +1 -1
  19. package/dist/ai-service/agent/tools/apis/test-api.d.ts +2 -2
  20. package/dist/ai-service/agent/tools/apis/test-api.d.ts.map +1 -1
  21. package/dist/ai-service/agent/tools/apis/test-api.js +6 -5
  22. package/dist/ai-service/agent/tools/apis/test-api.js.map +1 -1
  23. package/dist/ai-service/agent/tools/apis/write-api.d.ts +1 -1
  24. package/dist/ai-service/agent/tools/build-copy-directory.d.ts +2 -2
  25. package/dist/ai-service/agent/tools/build-copy-file.d.ts +1 -1
  26. package/dist/ai-service/agent/tools/build-copy-utils.d.ts +8 -8
  27. package/dist/ai-service/agent/tools/build-delete-file.d.ts +1 -1
  28. package/dist/ai-service/agent/tools/build-manage-checklist.d.ts +3 -3
  29. package/dist/ai-service/agent/tools/build-manage-packages.d.ts +1 -1
  30. package/dist/ai-service/agent/tools/databases/dev-database-tasks.d.ts +8 -8
  31. package/dist/ai-service/agent/tools/get-logs.d.ts +3 -3
  32. package/dist/ai-service/agent/tools/get-security-findings.d.ts +1 -1
  33. package/dist/ai-service/agent/tools/integrations/execute-request.d.ts +10 -10
  34. package/dist/ai-service/agent/tools/report-security-findings.d.ts +18 -18
  35. package/dist/ai-service/agent/tools/report-security-findings.d.ts.map +1 -1
  36. package/dist/ai-service/agent/tools/report-security-findings.js +6 -4
  37. package/dist/ai-service/agent/tools/report-security-findings.js.map +1 -1
  38. package/dist/ai-service/agent/tools2/tools/bash.d.ts +1 -1
  39. package/dist/ai-service/agent/tools2/tools/git.d.ts +2 -2
  40. package/dist/ai-service/agent/tools2/tools/grep-metadata.d.ts +1 -1
  41. package/dist/ai-service/agent/tools2/tools/grep.d.ts +1 -1
  42. package/dist/ai-service/agent/tools2/tools/list-attachments.d.ts +1 -1
  43. package/dist/ai-service/agent/utils.d.ts.map +1 -1
  44. package/dist/ai-service/agent/utils.js +12 -8
  45. package/dist/ai-service/agent/utils.js.map +1 -1
  46. package/dist/ai-service/app-interface/shell.d.ts +1 -0
  47. package/dist/ai-service/app-interface/shell.d.ts.map +1 -1
  48. package/dist/ai-service/app-interface/shell.js +53 -22
  49. package/dist/ai-service/app-interface/shell.js.map +1 -1
  50. package/dist/ai-service/checklist/remediation-findings-client.d.ts +1 -1
  51. package/dist/ai-service/index.d.ts +6 -0
  52. package/dist/ai-service/index.d.ts.map +1 -1
  53. package/dist/ai-service/index.js +131 -57
  54. package/dist/ai-service/index.js.map +1 -1
  55. package/dist/ai-service/judge/tools/playwright-action.d.ts +1 -1
  56. package/dist/ai-service/judge/tools/submit-feedback.d.ts +1 -1
  57. package/dist/ai-service/llm/context-v2/storage/event-types.d.ts +12 -12
  58. package/dist/ai-service/llm/error.d.ts.map +1 -1
  59. package/dist/ai-service/llm/error.js +17 -3
  60. package/dist/ai-service/llm/error.js.map +1 -1
  61. package/dist/ai-service/llm/stream/observers/llmobs.d.ts.map +1 -1
  62. package/dist/ai-service/llm/stream/observers/llmobs.js +5 -2
  63. package/dist/ai-service/llm/stream/observers/llmobs.js.map +1 -1
  64. package/dist/ai-service/llmobs/otel-exporter.d.ts.map +1 -1
  65. package/dist/ai-service/llmobs/otel-exporter.js +4 -0
  66. package/dist/ai-service/llmobs/otel-exporter.js.map +1 -1
  67. package/dist/ai-service/policy-agent-metrics.d.ts +1 -1
  68. package/dist/ai-service/policy-agent-metrics.d.ts.map +1 -1
  69. package/dist/ai-service/policy-agent-metrics.js +1 -0
  70. package/dist/ai-service/policy-agent-metrics.js.map +1 -1
  71. package/dist/ai-service/policy-gate-error.d.ts.map +1 -1
  72. package/dist/ai-service/policy-gate-error.js +34 -3
  73. package/dist/ai-service/policy-gate-error.js.map +1 -1
  74. package/dist/ai-service/state-machine/handlers/llm-generating.d.ts.map +1 -1
  75. package/dist/ai-service/state-machine/handlers/llm-generating.js +20 -1
  76. package/dist/ai-service/state-machine/handlers/llm-generating.js.map +1 -1
  77. package/dist/ai-service/state-machine/helpers/peer.d.ts.map +1 -1
  78. package/dist/ai-service/state-machine/helpers/peer.js +5 -4
  79. package/dist/ai-service/state-machine/helpers/peer.js.map +1 -1
  80. package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.d.ts.map +1 -1
  81. package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.js +1 -0
  82. package/dist/ai-service/state-machine/helpers/policy-gate-usage-metrics.js.map +1 -1
  83. package/dist/ai-service/state-machine/helpers/prompt-request-metrics.d.ts +1 -1
  84. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts +2 -0
  85. package/dist/ai-service/state-machine/helpers/stable-peer.d.ts.map +1 -1
  86. package/dist/ai-service/state-machine/helpers/stable-peer.js +29 -4
  87. package/dist/ai-service/state-machine/helpers/stable-peer.js.map +1 -1
  88. package/dist/ai-service/util/rpc-timeout.d.ts +2 -0
  89. package/dist/ai-service/util/rpc-timeout.d.ts.map +1 -1
  90. package/dist/ai-service/util/rpc-timeout.js +2 -0
  91. package/dist/ai-service/util/rpc-timeout.js.map +1 -1
  92. package/dist/ai-service/util/stop-condition.d.ts +8 -0
  93. package/dist/ai-service/util/stop-condition.d.ts.map +1 -1
  94. package/dist/ai-service/util/stop-condition.js +15 -0
  95. package/dist/ai-service/util/stop-condition.js.map +1 -1
  96. package/dist/extract-api-integrations.d.ts +4 -0
  97. package/dist/extract-api-integrations.d.ts.map +1 -1
  98. package/dist/extract-api-integrations.js +21 -7
  99. package/dist/extract-api-integrations.js.map +1 -1
  100. package/dist/migration-templates/app-fullstack/package.json +1 -1
  101. package/dist/sync-service/download.d.ts +22 -0
  102. package/dist/sync-service/download.d.ts.map +1 -1
  103. package/dist/sync-service/download.js +154 -1
  104. package/dist/sync-service/download.js.map +1 -1
  105. package/dist/sync-service/draft-helpers.d.ts +14 -3
  106. package/dist/sync-service/draft-helpers.d.ts.map +1 -1
  107. package/dist/sync-service/draft-helpers.js +61 -72
  108. package/dist/sync-service/draft-helpers.js.map +1 -1
  109. package/dist/sync-service/draft-state-report-metrics.d.ts +3 -0
  110. package/dist/sync-service/draft-state-report-metrics.d.ts.map +1 -1
  111. package/dist/sync-service/draft-state-report-metrics.js +9 -0
  112. package/dist/sync-service/draft-state-report-metrics.js.map +1 -1
  113. package/dist/sync-service/index.d.ts +5 -0
  114. package/dist/sync-service/index.d.ts.map +1 -1
  115. package/dist/sync-service/index.js +45 -2
  116. package/dist/sync-service/index.js.map +1 -1
  117. package/package.json +9 -9
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { context as otelContext, metrics, propagation, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
5
- import { hasToolCall, stepCountIs, } from "ai";
5
+ import { stepCountIs, } from "ai";
6
6
  import { z } from "zod";
7
7
  import { AiGenerationState, AiMode, resolveAttachmentFileName, } from "@superblocksteam/library-shared/types";
8
8
  import { isToolPermissionClarification } from "@superblocksteam/library-shared/types/tool-permission-response";
@@ -17,7 +17,7 @@ import { OperationQueue } from "../util/operation-queue.js";
17
17
  import { composeSecurityAgentPrompt, } from "./agent/prompts/build-security-scan-prompt.js";
18
18
  import { getToolCallArguments, getToolErrorCode, getToolErrorMessage, getToolOutput, } from "./agent/tool-message-utils.js";
19
19
  import { recordToolPermissionDeliveryOutcome } from "./agent/tool-permission-delivery-metrics.js";
20
- import { createExpiredPermissionPromptDeliveryError, flushPendingToolPermissionPrompt, inFlightToolPermissionReplay, } from "./agent/tool-permission-delivery.js";
20
+ import { createExpiredPermissionPromptDeliveryError, flushPendingToolPermissionPrompt, inFlightToolPermissionReplay, setToolPermissionAckListener, } from "./agent/tool-permission-delivery.js";
21
21
  import { recordToolPermissionLateOutcome } from "./agent/tool-permission-outcome-metrics.js";
22
22
  import { buildSecurityScanTools, isBackgroundTaskFrameworkEnabled, } from "./agent/tools.js";
23
23
  import { hasPendingEscalations, flushPendingEscalations, } from "./agent/tools/apis/api-validation-orchestrator.js";
@@ -122,7 +122,8 @@ import { TemplateRenderer } from "./template-renderer.js";
122
122
  import { describeMigrationInferenceJwt, isUsableMigrationInferenceJwt, } from "./util/inference-jwt.js";
123
123
  import { buildModelConfigAttributes, processLLMConfig, processOneShotLLMConfig, } from "./util/llm-config-utils.js";
124
124
  import { parseJwt } from "./util/parse-jwt.js";
125
- import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS } from "./util/rpc-timeout.js";
125
+ import { PERMISSION_PROMPT_DELIVERY_TIMEOUT_MS, PERMISSION_PROMPT_RESPONSE_TIMEOUT_MS, } from "./util/rpc-timeout.js";
126
+ import { hasValidToolCall } from "./util/stop-condition.js";
126
127
  import { getToolCallSignature } from "./util/tool-signature.js";
127
128
  export { AiServiceFeatureFlags } from "./features.js";
128
129
  export { getManagedNativeDbGateDenialReason, hasEditLifecycleCapability, isManagedNativeDbAvailableForClark, } from "./managed-native-db-availability.js";
@@ -138,6 +139,7 @@ function streamRetryOptionsFromConfig(retryOptions, streamTimeoutBudgets) {
138
139
  };
139
140
  }
140
141
  export { stripResolvedFromLockfile } from "./app-interface/npm-registry.js";
142
+ export { isPeerUnavailableError } from "./state-machine/helpers/stable-peer.js";
141
143
  export { SnapshotManager } from "./recording/index.js";
142
144
  export { isSdkApiTemplate } from "./sdk-api-templates.js";
143
145
  /**
@@ -452,7 +454,13 @@ const TOOL_MESSAGE_ROLE = "tool";
452
454
  const TOOL_RESULT_CONTENT_TYPE = "tool-result";
453
455
  const TOOL_PERMISSION_CONTEXT_ATTEMPTS = 3;
454
456
  const TOOL_PERMISSION_CONTEXT_RETRY_MS = 200;
457
+ const TOOL_PERMISSION_RESPONSE_RETRY_MS = 10_000;
455
458
  const CLARIFICATION_DENY_REASON = "The user answered with the message that follows instead of approving.";
459
+ // Another approval would wait out the same timeout, and build_finalize still requires the skipped tool, so the turn ends without it.
460
+ const TOOL_PERMISSION_RESPONSE_TIMEOUT_PROMPT = "The user did not answer the permission request in time, so that tool did not run. " +
461
+ "The user did not deny it; they may be away. " +
462
+ "Finish this turn now. Do not call build_finalize or another tool that needs the user's permission. " +
463
+ "Summarize what you completed, and list what still needs the user's approval so they can approve it when they return.";
456
464
  const TOOL_PERMISSION_PLACEHOLDER_USAGE = {
457
465
  inputTokens: 0,
458
466
  outputTokens: 0,
@@ -516,6 +524,7 @@ export class AiService extends TracedEventEmitter {
516
524
  activeGenerationTrace;
517
525
  currentGenerationId;
518
526
  generationStarting = false;
527
+ toolPermissionResponseTimer;
519
528
  /**
520
529
  * The context, and why, that a busy editor disconnect or connection reset
521
530
  * left to be cleared once the turn settles (see `releaseEditorContext`).
@@ -1134,24 +1143,7 @@ export class AiService extends TracedEventEmitter {
1134
1143
  recordingsDir: path.join(config.appRootDirPath, ".superblocks", "recordings"),
1135
1144
  appRootDirPath: config.appRootDirPath,
1136
1145
  });
1137
- this.config.draftInterface
1138
- .hasLocalDraftChanges()
1139
- .then((hasDraft) => {
1140
- if (hasDraft &&
1141
- this.currentGenerationId === undefined &&
1142
- this.clark.state === ClarkStateNames.Idle) {
1143
- this.clark.updateContext({
1144
- hasSuggestions: true,
1145
- });
1146
- const transitionTo = transitionFrom(this.clark);
1147
- void transitionTo({
1148
- type: SERVICE_STARTED_WITH_DRAFT,
1149
- });
1150
- }
1151
- })
1152
- .catch((error) => {
1153
- this.getLogger().error(`[ai-service] Error checking for local draft changes: ${error}`, getErrorMeta(error));
1154
- });
1146
+ void this.awaitUserIfDraftExists();
1155
1147
  const handlerMethods = [
1156
1148
  "handleAiGenerate",
1157
1149
  "handleAiTriggerMigrationTurn",
@@ -1176,8 +1168,30 @@ export class AiService extends TracedEventEmitter {
1176
1168
  // closing is still a backstop for a turn that never reaches a terminal
1177
1169
  // state.
1178
1170
  bindHeadlessTurnLifecycle(this, this.stablePeer, () => this.clark.context.promptId, () => this.clark.context.promptOutcomeDedupeKey);
1171
+ setToolPermissionAckListener(this.clark, (messageId) => this.scheduleToolPermissionResponseExpiry(messageId));
1179
1172
  // TODO apply isocket error handling
1180
1173
  }
1174
+ /** Moves an idle session to AwaitingUser when a draft is on disk. */
1175
+ awaitUserIfDraftExists() {
1176
+ return this.config.draftInterface
1177
+ .hasLocalDraftChanges()
1178
+ .then((hasDraft) => {
1179
+ if (hasDraft &&
1180
+ this.currentGenerationId === undefined &&
1181
+ this.clark.state === ClarkStateNames.Idle) {
1182
+ this.clark.updateContext({
1183
+ hasSuggestions: true,
1184
+ });
1185
+ const transitionTo = transitionFrom(this.clark);
1186
+ void transitionTo({
1187
+ type: SERVICE_STARTED_WITH_DRAFT,
1188
+ });
1189
+ }
1190
+ })
1191
+ .catch((error) => {
1192
+ this.getLogger().error(`[ai-service] Error checking for local draft changes: ${error}`, getErrorMeta(error));
1193
+ });
1194
+ }
1181
1195
  /**
1182
1196
  * Initialize the AI service. Must be called after construction.
1183
1197
  * Sets up storage, cleanup tasks, and starts recording.
@@ -3952,6 +3966,49 @@ export class AiService extends TracedEventEmitter {
3952
3966
  });
3953
3967
  }, expiresInMs);
3954
3968
  }
3969
+ /** Each acknowledgement, including a reconnect re-send, restarts the deadline. It expires only on the editor route and re-arms while a Gateway peer owns the turn. */
3970
+ scheduleToolPermissionResponseExpiry(messageId, delayMs = PERMISSION_PROMPT_RESPONSE_TIMEOUT_MS, retryOnFailure = true) {
3971
+ const pending = this.clark.context.pendingToolPermissionRequest;
3972
+ if (pending?.messageId !== messageId ||
3973
+ pending.delivery.status !== "acked") {
3974
+ return;
3975
+ }
3976
+ clearTimeout(this.toolPermissionResponseTimer);
3977
+ const { generation } = pending.delivery;
3978
+ const isSamePrompt = () => {
3979
+ const current = this.clark.context.pendingToolPermissionRequest;
3980
+ return (current?.messageId === messageId &&
3981
+ current.delivery.status === "acked" &&
3982
+ current.delivery.generation === generation);
3983
+ };
3984
+ this.toolPermissionResponseTimer = setTimeout(() => {
3985
+ void (async () => {
3986
+ if (!(await this.waitUntilToolPermissionContinuationAllowed(messageId))) {
3987
+ return;
3988
+ }
3989
+ await inFlightToolPermissionReplay(this.clark);
3990
+ if (!isSamePrompt()) {
3991
+ return;
3992
+ }
3993
+ // A Gateway caller answers in its own time; keep a deadline for when routing returns to the editor.
3994
+ if (this.stablePeer.routesToTurnPeer) {
3995
+ this.scheduleToolPermissionResponseExpiry(messageId);
3996
+ return;
3997
+ }
3998
+ await this.handleToolPermissionOutcome({
3999
+ kind: "response_timeout",
4000
+ messageId,
4001
+ });
4002
+ recordToolPermissionDeliveryOutcome("response_expired");
4003
+ })().catch((cause) => {
4004
+ this.getLogger().error(`[ai-service] Failed to continue after an unanswered tool permission: messageId=${messageId}, toolName=${pending.toolName}, deliveryGeneration=${generation}, generationId=${this.currentGenerationId}, willRetry=${retryOnFailure}`, getErrorMeta(cause));
4005
+ // A continuation that starts at the same moment makes this one fail with "Service is busy".
4006
+ if (retryOnFailure && isSamePrompt()) {
4007
+ this.scheduleToolPermissionResponseExpiry(messageId, TOOL_PERMISSION_RESPONSE_RETRY_MS, false);
4008
+ }
4009
+ });
4010
+ }, delayMs);
4011
+ }
3955
4012
  /** Wait for a pending permission decision to become a valid continuation. */
3956
4013
  async waitUntilToolPermissionContinuationAllowed(messageId) {
3957
4014
  const TOOL_PERMISSION_CONTINUATION_POLL_MS = 250;
@@ -4127,7 +4184,9 @@ export class AiService extends TracedEventEmitter {
4127
4184
  // Clear the pending request and notify UI
4128
4185
  clearPendingToolPermissionRequest(this.clark, request.kind === "delivery_error"
4129
4186
  ? "tool-permission-delivery-expired"
4130
- : "tool-permission-response");
4187
+ : request.kind === "response_timeout"
4188
+ ? "tool-permission-response-expired"
4189
+ : "tool-permission-response");
4131
4190
  const toolCallId = pendingRequest.messageId;
4132
4191
  const toolName = pendingRequest.toolName;
4133
4192
  const rawInput = pendingRequest.rawInput;
@@ -4187,10 +4246,14 @@ export class AiService extends TracedEventEmitter {
4187
4246
  else {
4188
4247
  // A clarification reaches Clark as the user's next message, where the
4189
4248
  // prompt safety checks see it. Repeating it here would leak it past them.
4190
- const denyReason = isClarification
4191
- ? CLARIFICATION_DENY_REASON
4192
- : request.denyMessage || "User denied permission for this tool call";
4193
- if (toolName === "testApi") {
4249
+ const toolError = request.kind === "response_timeout"
4250
+ ? `The user did not answer the permission request within ${PERMISSION_PROMPT_RESPONSE_TIMEOUT_MS / 60_000} minutes, so the tool did not run.`
4251
+ : `Permission denied: ${isClarification
4252
+ ? CLARIFICATION_DENY_REASON
4253
+ : request.denyMessage ||
4254
+ "User denied permission for this tool call"}`;
4255
+ // No answer is not a denial, so the API stays untested and build_finalize keeps requiring it.
4256
+ if (toolName === "testApi" && request.kind !== "response_timeout") {
4194
4257
  const apiName = rawInput?.apiName;
4195
4258
  if (apiName) {
4196
4259
  await applyTestApiDenialSideEffects({
@@ -4204,9 +4267,9 @@ export class AiService extends TracedEventEmitter {
4204
4267
  }
4205
4268
  }
4206
4269
  outcome = {
4207
- toolResultMessage: toolErrorResult(toolCallId, toolName, `Permission denied: ${denyReason}`),
4270
+ toolResultMessage: toolErrorResult(toolCallId, toolName, toolError),
4208
4271
  };
4209
- logger.info(`[ai-service] Tool ${toolName} permission denied, error injected into context`);
4272
+ logger.info(`[ai-service] Tool ${toolName} permission denied, error injected into context`, { outcomeKind: request.kind });
4210
4273
  }
4211
4274
  // The tool or its denial has already taken effect, so the outcome is
4212
4275
  // recorded even when a cancel or a newer prompt superseded this response.
@@ -4268,9 +4331,11 @@ export class AiService extends TracedEventEmitter {
4268
4331
  const continueRequest = {
4269
4332
  prompt: approved || request.kind === "delivery_error"
4270
4333
  ? ``
4271
- : isClarification && request.denyMessage
4272
- ? request.denyMessage.trim()
4273
- : this.buildDenialContinuationPrompt(toolName, rawInput),
4334
+ : request.kind === "response_timeout"
4335
+ ? TOOL_PERMISSION_RESPONSE_TIMEOUT_PROMPT
4336
+ : isClarification && request.denyMessage
4337
+ ? request.denyMessage.trim()
4338
+ : this.buildDenialContinuationPrompt(toolName, rawInput),
4274
4339
  promptContext: {
4275
4340
  entities: [],
4276
4341
  integrations: [],
@@ -4286,7 +4351,9 @@ export class AiService extends TracedEventEmitter {
4286
4351
  approved,
4287
4352
  outcome: request.kind === "delivery_error"
4288
4353
  ? "delivery_expired"
4289
- : "user_response",
4354
+ : request.kind === "response_timeout"
4355
+ ? "response_expired"
4356
+ : "user_response",
4290
4357
  alwaysAllowPermissions: request.kind === "response"
4291
4358
  ? request.alwaysAllowPermissions
4292
4359
  : undefined,
@@ -5287,6 +5354,7 @@ export class AiService extends TracedEventEmitter {
5287
5354
  ? this.appShell.appRootDirPath
5288
5355
  : undefined;
5289
5356
  let scanResult;
5357
+ let lastReportCall;
5290
5358
  let metricsRecorded = false;
5291
5359
  const totalToolCalls = () => Object.values(toolCallCounts).reduce((sum, count) => sum + count, 0);
5292
5360
  const recordExecutionMetrics = (outcome) => {
@@ -5370,23 +5438,20 @@ export class AiService extends TracedEventEmitter {
5370
5438
  name: i.name,
5371
5439
  pluginType: i.plugin?.id ?? "unknown",
5372
5440
  }));
5373
- let scanScopeJson = request.scanScopeJson;
5374
- if (scanScopeJson?.unifiedDiff) {
5375
- try {
5376
- const scanResult = await scanContentForSecrets(scanScopeJson.unifiedDiff, { consumer: "policy_gate" });
5377
- if (scanResult.success && scanResult.hasSecrets) {
5378
- scanScopeJson = {
5379
- ...scanScopeJson,
5380
- unifiedDiff: new SecretRedactor(scanResult.findings).redact(scanScopeJson.unifiedDiff),
5381
- };
5382
- }
5383
- }
5384
- catch {
5385
- logger.warn("[secret-scan] Secret scan threw on policy gate diff; using the original diff");
5441
+ const scanScopeJson = request.scanScopeJson;
5442
+ const appContext = { integrations };
5443
+ let systemPrompt = composeSecurityAgentPrompt(appContext, request.adminPrompt, scanScopeJson);
5444
+ try {
5445
+ const scanResult = await scanContentForSecrets(systemPrompt, {
5446
+ consumer: "policy_gate",
5447
+ });
5448
+ if (scanResult.success && scanResult.hasSecrets) {
5449
+ systemPrompt = new SecretRedactor(scanResult.findings).redact(systemPrompt);
5386
5450
  }
5387
5451
  }
5388
- const appContext = { integrations };
5389
- const systemPrompt = composeSecurityAgentPrompt(appContext, request.adminPrompt, scanScopeJson);
5452
+ catch {
5453
+ logger.warn("[secret-scan] Secret scan threw on policy gate text; using the original text");
5454
+ }
5390
5455
  promptHash = createHash("sha256").update(systemPrompt).digest("hex");
5391
5456
  const scanContext = {};
5392
5457
  const { headers, interleavedThinking, maxOutputTokens: configuredMaxOutputTokens, providerOptions, thinkingBudgetTokens, thinkingEnabled, } = processLLMConfig(llmConfig);
@@ -5462,7 +5527,7 @@ export class AiService extends TracedEventEmitter {
5462
5527
  },
5463
5528
  tools,
5464
5529
  stopWhen: [
5465
- hasToolCall("reportReviewRun"),
5530
+ hasValidToolCall("reportReviewRun", 5),
5466
5531
  stepCountIs(POLICY_GATE_MAX_STEPS),
5467
5532
  ],
5468
5533
  user: {
@@ -5598,16 +5663,25 @@ export class AiService extends TracedEventEmitter {
5598
5663
  part.toolName === "reportReviewRun") {
5599
5664
  const input = part.input ??
5600
5665
  part.args;
5601
- const parsedInput = securityScanResultSchema.safeParse(input);
5602
- if (!parsedInput.success) {
5603
- logger.error("[ai-service] Invalid policy gate reportReviewRun input", {
5604
- ...policyRunLogContext,
5605
- ...getErrorMeta(parsedInput.error),
5606
- });
5607
- failPolicyGateExecution("Invalid policy gate reportReviewRun input", "invalid_report");
5608
- }
5609
- scanResult = parsedInput.data;
5666
+ lastReportCall = {
5667
+ input,
5668
+ invalid: part.invalid === true,
5669
+ };
5670
+ }
5671
+ }
5672
+ if (lastReportCall) {
5673
+ const parsedInput = securityScanResultSchema.safeParse(lastReportCall.input);
5674
+ if (lastReportCall.invalid || !parsedInput.success) {
5675
+ const reportError = parsedInput.success
5676
+ ? new Error("reportReviewRun call was invalid")
5677
+ : parsedInput.error;
5678
+ logger.error("[ai-service] Invalid policy gate reportReviewRun input", {
5679
+ ...policyRunLogContext,
5680
+ ...getErrorMeta(reportError),
5681
+ });
5682
+ failPolicyGateExecution("Invalid policy gate reportReviewRun input", "invalid_report");
5610
5683
  }
5684
+ scanResult = parsedInput.data;
5611
5685
  }
5612
5686
  }
5613
5687
  catch (error) {