@circuitwall/jarela 2.5.0 → 2.5.2

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 (188) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-path-routes-manifest.json +5 -5
  3. package/.next/standalone/.next/build-manifest.json +2 -2
  4. package/.next/standalone/.next/prerender-manifest.json +3 -3
  5. package/.next/standalone/.next/react-loadable-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  7. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  11. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  12. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  13. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  14. package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
  15. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  16. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  17. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  19. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js +8 -1
  20. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js.nft.json +1 -1
  21. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js +8 -1
  22. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js.nft.json +1 -1
  23. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js +8 -1
  24. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +8 -1
  26. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js +8 -1
  28. package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +7 -0
  30. package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js +7 -0
  32. package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js.nft.json +1 -1
  33. package/.next/standalone/.next/server/app/api/v1/credentials/route.js +7 -0
  34. package/.next/standalone/.next/server/app/api/v1/credentials/route.js.nft.json +1 -1
  35. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js +8 -1
  36. package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js.nft.json +1 -1
  37. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js +7 -0
  38. package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js +7 -0
  40. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js +8 -1
  42. package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js.nft.json +1 -1
  43. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js +8 -1
  44. package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/api/v1/events/route.js +8 -1
  46. package/.next/standalone/.next/server/app/api/v1/events/route.js.nft.json +1 -1
  47. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js +8 -1
  48. package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js +8 -1
  50. package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js.nft.json +1 -1
  51. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js +8 -1
  52. package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js.nft.json +1 -1
  53. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js +8 -1
  54. package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js.nft.json +1 -1
  55. package/.next/standalone/.next/server/app/api/v1/extensions/route.js +8 -1
  56. package/.next/standalone/.next/server/app/api/v1/extensions/route.js.nft.json +1 -1
  57. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js +8 -1
  58. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js +8 -1
  60. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js.nft.json +1 -1
  61. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +8 -1
  62. package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js +7 -0
  64. package/.next/standalone/.next/server/app/api/v1/health/probes/route.js.nft.json +1 -1
  65. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js +7 -0
  66. package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js.nft.json +1 -1
  67. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/callback/route.js +22 -1
  68. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/start/route.js +22 -1
  69. package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/status/route.js +22 -1
  70. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/callback/route.js +19 -2
  71. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/start/route.js +19 -2
  72. package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/status/route.js +19 -2
  73. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js +12 -2
  74. package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js.nft.json +1 -1
  75. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js +7 -0
  76. package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js.nft.json +1 -1
  77. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js +7 -0
  78. package/.next/standalone/.next/server/app/api/v1/packages/install/route.js.nft.json +1 -1
  79. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js +7 -0
  80. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js.nft.json +1 -1
  81. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js +7 -0
  82. package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js.nft.json +1 -1
  83. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js +7 -0
  84. package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js.nft.json +1 -1
  85. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js +12 -2
  86. package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js.nft.json +1 -1
  87. package/.next/standalone/.next/server/app/api/v1/packages/route.js +12 -2
  88. package/.next/standalone/.next/server/app/api/v1/packages/route.js.nft.json +1 -1
  89. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +8 -1
  90. package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.nft.json +1 -1
  91. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +7 -0
  92. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.nft.json +1 -1
  93. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js +7 -0
  94. package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js.nft.json +1 -1
  95. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js +7 -0
  96. package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js.nft.json +1 -1
  97. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js +8 -1
  98. package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js.nft.json +1 -1
  99. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js +7 -0
  100. package/.next/standalone/.next/server/app/api/v1/system/restart/route.js.nft.json +1 -1
  101. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +52 -45
  102. package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.nft.json +1 -1
  103. package/.next/standalone/.next/server/app/api/v1/tools/route.js +8 -1
  104. package/.next/standalone/.next/server/app/api/v1/tools/route.js.nft.json +1 -1
  105. package/.next/standalone/.next/server/app/api/v1/update/apply/route.js.nft.json +1 -1
  106. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js +8 -1
  107. package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js.nft.json +1 -1
  108. package/.next/standalone/.next/server/app/api/v1/watchers/route.js +8 -1
  109. package/.next/standalone/.next/server/app/api/v1/watchers/route.js.nft.json +1 -1
  110. package/.next/standalone/.next/server/app/page.js +73385 -73375
  111. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  112. package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
  113. package/.next/standalone/.next/server/app-paths-manifest.json +5 -5
  114. package/.next/standalone/.next/server/chunks/1433.js +1 -1
  115. package/.next/standalone/.next/server/chunks/210.js +6 -6
  116. package/.next/standalone/.next/server/chunks/3524.js +31 -15
  117. package/.next/standalone/.next/server/chunks/3566.js +1 -1
  118. package/.next/standalone/.next/server/chunks/4189.js +1 -1
  119. package/.next/standalone/.next/server/chunks/{9590.js → 423.js} +10 -3
  120. package/.next/standalone/.next/server/chunks/4596.js +5 -2
  121. package/.next/standalone/.next/server/chunks/46.js +7 -0
  122. package/.next/standalone/.next/server/chunks/540.js +29 -5
  123. package/.next/standalone/.next/server/chunks/5585.js +41 -3
  124. package/.next/standalone/.next/server/chunks/5908.js +10 -10
  125. package/.next/standalone/.next/server/chunks/{3399.js → 6058.js} +485 -3
  126. package/.next/standalone/.next/server/chunks/{9164.js → 6190.js} +13828 -13581
  127. package/.next/standalone/.next/server/chunks/{1388.js → 8842.js} +5961 -5793
  128. package/.next/standalone/.next/server/chunks/9032.js +5 -5
  129. package/.next/standalone/.next/server/chunks/{7547.js → 9217.js} +485 -3
  130. package/.next/standalone/.next/server/instrumentation.js +7 -0
  131. package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
  132. package/.next/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  133. package/.next/standalone/.next/server/middleware.js +7 -0
  134. package/.next/standalone/.next/server/pages/404.html +2 -2
  135. package/.next/standalone/.next/server/pages/500.html +1 -1
  136. package/.next/standalone/.next/server/preview-props.json +3 -3
  137. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  138. package/.next/standalone/.next/static/chunks/app/{page-2ef8d75d40eb4311.js → page-4112e14360a9909e.js} +1291 -1281
  139. package/.next/standalone/.next/static/css/{c160ea862133acd2.css → 5b30046ba49144c5.css} +2 -2
  140. package/.next/standalone/docs/adoption/changesets.json +151 -0
  141. package/.next/standalone/package.json +2 -1
  142. package/CHANGELOG.md +46 -0
  143. package/browser-extension/background.js +5 -539
  144. package/browser-extension/lib/form-editing.mjs +541 -0
  145. package/components/chat/MessageBubble.tsx +4 -736
  146. package/components/chat/MessageContent.tsx +749 -0
  147. package/components/dashboard/DashboardPanel.test.tsx +34 -0
  148. package/components/dashboard/DashboardPanel.tsx +1 -1
  149. package/components/layout/MenuPanel.tsx +1 -1
  150. package/components/ui/BootScreen.test.tsx +1 -0
  151. package/components/ui/BootScreen.tsx +1 -0
  152. package/components/ui/ServerStatus.test.tsx +50 -0
  153. package/components/ui/ServerStatus.tsx +10 -8
  154. package/hooks/useSSE.test.ts +46 -0
  155. package/lib/agents/llm.ts +1 -1
  156. package/lib/agents/output-validator/validator.test.ts +4 -0
  157. package/lib/agents/output-validator/validator.ts +1 -1
  158. package/lib/agents/prompt-registry.test.ts +11 -0
  159. package/lib/agents/prompt-registry.ts +13 -0
  160. package/lib/agents/retry-prompts.ts +17 -0
  161. package/lib/agents/run-retry.ts +671 -0
  162. package/lib/agents/run-thread.retry.test.ts +176 -2
  163. package/lib/agents/run-thread.test.ts +6 -6
  164. package/lib/agents/run-thread.ts +9 -717
  165. package/lib/agents/stream-collector.test.ts +28 -4
  166. package/lib/agents/stream-collector.ts +5 -28
  167. package/lib/agents/tool-outcomes.ts +61 -0
  168. package/lib/documents/remote/confluence.test.ts +65 -0
  169. package/lib/documents/remote/confluence.ts +35 -9
  170. package/lib/documents/remote/jira.ts +1 -1
  171. package/lib/health/probes.test.ts +32 -0
  172. package/lib/health/probes.ts +29 -14
  173. package/lib/integrations/atlassian/manifest.ts +5 -3
  174. package/lib/integrations/github/manifest.ts +7 -4
  175. package/lib/integrations/gmail-oauth.ts +16 -1
  176. package/lib/integrations/microsoft-oauth.ts +17 -2
  177. package/lib/integrations/outlook/manifest.ts +10 -8
  178. package/lib/stores/integrations.ts +1 -0
  179. package/lib/tools/communications/calendar-aliases.test.ts +77 -1
  180. package/lib/tools/communications/gmail.test.ts +13 -0
  181. package/lib/tools/communications/ms-graph.test.ts +26 -3
  182. package/lib/tools/communications/ms-graph.ts +9 -11
  183. package/lib/tools/communications/outlook-calendar.ts +94 -17
  184. package/lib/tools/packages/default-packages/atlassian.ts +8 -2
  185. package/package.json +2 -1
  186. package/scripts/standalone-footprint.mjs +1 -1
  187. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_buildManifest.js +0 -0
  188. /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_ssgManifest.js +0 -0
@@ -1,4 +1,3 @@
1
- import { isWriteToolNameSegment, STALL_NOW_ACTION_VERBS, STALL_TAIL_PHRASES } from "@/lib/agents/action-vocabulary";
2
1
  import { streamWithConfig } from "@/lib/agents/llm";
3
2
  import { DEFAULT_HOT_TURN_LIMIT } from "@/api/types";
4
3
  import { getConfig } from "@/lib/env/config";
@@ -6,14 +5,13 @@ import { claimSystemSignals, renewSystemSignalLease, releaseSystemSignals, commi
6
5
  import { runtimeInstanceId } from "@/lib/lifecycle/system-signals";
7
6
  import type { StreamChunk, StreamOptions } from "@/lib/agents/base";
8
7
  import type { ContentPart } from "@/lib/tools/runtime/types";
9
- import { registeredCapability } from "@/lib/tools/runtime/registry";
10
8
  import { spillAttachments } from "@/lib/attachments/spill";
11
9
  import { fileReferenceFromContentPart, isFileReferenceMetadata, type AttachmentHandlingMetadata, type FileReferenceMetadata } from "@/lib/attachments/reference";
12
10
  import { autoCompactionKeepLast, compactAgentThread } from "@/lib/agents/thread-compaction";
13
11
  import { kickBoundaryCompaction, kickWarmSummaryRefresh, pendingCompactionBoundarySeq } from "@/lib/agents/warm-summary-background";
14
12
  import { moveThreadContextBoundary } from "@/lib/agents/context-boundary";
15
13
  import { getForegroundTabPresence } from "@/lib/api/foreground-presence";
16
- import { addMessage, capToolEventPayload, countForegroundThreadMessages, getMessagesPage, isValidThreadContextCursor, pruneThreadMessages, getRecentlyUsedToolNames, getRecentMessagesWindow, getThread, getThreadMessageBySeq, mergeMessageMetadata, touchThread, updateMessageContent, type MessageTranscriptStatus, type PersistedToolEvent } from "@/lib/stores/threads";
14
+ import { addMessage, capToolEventPayload, countForegroundThreadMessages, getMessagesPage, isValidThreadContextCursor, pruneThreadMessages, getRecentlyUsedToolNames, getRecentMessagesWindow, getThread, mergeMessageMetadata, touchThread, updateMessageContent, type MessageTranscriptStatus, type PersistedToolEvent } from "@/lib/stores/threads";
17
15
  import { transcriptText } from "@/lib/agents/conversation-summary";
18
16
  import { getMaskRunContext } from "@/lib/redaction/context";
19
17
  import { recordToolUsage } from "@/lib/stores/tool-stats";
@@ -22,53 +20,21 @@ import { startScheduler } from "@/lib/scheduler";
22
20
  import { recall, type RecalledMemory } from "@/lib/embeddings";
23
21
  import { getMemoryPolicy } from "@/lib/stores/app-settings";
24
22
  import { validateAssistantOutput } from "@/lib/agents/output-validator";
25
- import {
26
- buildWorkflowStepRetryNudge,
27
- collectWorkflowContractFailures,
28
- planWorkflowStepRetries,
29
- WORKFLOW_TURN_AUTO_RETRY_LIMIT,
30
- workflowProgressArgs,
31
- type WorkflowProgressObservation,
32
- } from "@/lib/agents/workflow-step-retry";
33
23
  import { getDefaultModelConfig, getModelConfig, getModelParams, isModelConfigEnabled, listEnabledModelConfigs } from "@/lib/stores/model-config";
34
- import {
35
- buildHistoryWindow,
36
- buildSystemPrompt,
37
- buildSurroundingsContext,
38
- buildConversationGapContext,
39
- resolveExperienceMode,
40
- warmSummaryMessageLimit,
41
- type ThreadRunRequest,
42
- } from "@/lib/agents/prepare";
24
+ import { buildHistoryWindow, buildSystemPrompt, buildSurroundingsContext, buildConversationGapContext, resolveExperienceMode, warmSummaryMessageLimit, type ThreadRunRequest } from "@/lib/agents/prepare";
43
25
  import { getLatestMessageUsageForThread, recordMessageUsage } from "@/lib/stores/message-usage";
44
26
  import { getPricingTables, modelRatesFor, estimateProviderCostUsd } from "@/lib/stores/pricing";
45
27
  import { DEFAULT_CONTEXT_WINDOW_TOKENS, estimateTokens } from "@/lib/agents/context-budget";
46
28
  import { getUsageStrategyProfile, resolveOutputTokenCap, resolveUsageStrategy, shouldAutoRecall } from "@/lib/agents/usage-strategy";
47
29
  import { getKnownContextLength } from "@/lib/providers/known-context-windows";
48
30
  import { modelThinksByDefault, thinkingReductionParams } from "@/lib/providers/capabilities";
49
- import { classifyStall, resolveDetector } from "@/lib/agents/hallucination-classifier";
50
- import { nextPolicyForRetry, routeTurnModel, type ModelRouterPolicy, type RouteDecisionMetadata } from "@/lib/agents/model-router";
51
- import {
52
- buildCombinedManifest,
53
- classifyCitations,
54
- extractCitedMarkers,
55
- extractDeclaredReferences,
56
- mergeDeclaredReferences,
57
- type SourceManifestEntry,
58
- } from "@/lib/agents/citation-checker";
31
+ import { routeTurnModel, type RouteDecisionMetadata } from "@/lib/agents/model-router";
32
+ import { buildCombinedManifest, classifyCitations, extractCitedMarkers, extractDeclaredReferences, mergeDeclaredReferences, type SourceManifestEntry } from "@/lib/agents/citation-checker";
59
33
  import { getEffectiveProviderToolLimit } from "@/lib/providers/tool-limit";
60
34
  import { withDbTransaction } from "@/lib/db/transaction";
61
- import {
62
- allowedToolNamesFromPermissionMap,
63
- applyAgentPermissionsToCatalog,
64
- applyProviderToolLimitToCatalog,
65
- applyToolBindBudget,
66
- getAllToolCatalogAsync,
67
- getDefaultAgentToolNames,
68
- isHotLoadTool,
69
- markProxyOnlyTools,
70
- type ToolCatalogEntry,
71
- } from "@/lib/tools";
35
+ import { allowedToolNamesFromPermissionMap, applyAgentPermissionsToCatalog, applyProviderToolLimitToCatalog, applyToolBindBudget, getAllToolCatalogAsync, getDefaultAgentToolNames, isHotLoadTool, markProxyOnlyTools, type ToolCatalogEntry } from "@/lib/tools";
36
+ import { transientRetryStream, stallRetryStream, isWriteLikeToolName, unwrapInvokedToolName, looksLikeStall } from "@/lib/agents/run-retry";
37
+ export { transientRetryDelayMs, MAX_RATE_LIMIT_RETRY_AFTER_MS, rateLimitRetryDelayMs, shouldRetryTransientError, isWriteLikeToolName, unwrapInvokedToolName, toolCallSignature, buildRetryContextSummary, buildFabricationNudge, retryTextOverlapRatio, looksLikeStall } from "@/lib/agents/run-retry";
72
38
 
73
39
  export type { ThreadRunRequest } from "@/lib/agents/prepare";
74
40
 
@@ -371,29 +337,6 @@ export interface ContextUsageSnapshot {
371
337
  function maxStallRetries(): number { return getConfig().maxStallRetries; }
372
338
  function maxTransientRetries(): number { return getConfig().maxTransientRetries; }
373
339
 
374
- export function transientRetryDelayMs(attempt: number): number {
375
- const clamped = Math.max(1, attempt);
376
- return Math.min(8_000, 500 * (2 ** (clamped - 1)));
377
- }
378
-
379
- export const MAX_RATE_LIMIT_RETRY_AFTER_MS = 60_000;
380
-
381
- export function rateLimitRetryDelayMs(attempt: number, retryAfterMs = 0): number {
382
- return Math.max(transientRetryDelayMs(attempt), Math.max(0, retryAfterMs));
383
- }
384
-
385
- export function shouldRetryTransientError(code: string | null | undefined, message: string | null | undefined): boolean {
386
- const normalized = (code ?? "").trim().toLowerCase();
387
- if (normalized === "rate_limited" || normalized === "empty_response" || normalized === "stream_error" || normalized === "agent_error") {
388
- return true;
389
- }
390
- if (normalized === "aborted" || normalized === "auth_failed" || normalized === "context_length_exceeded" || normalized === "recursion_limit" || normalized === "no_model") {
391
- return false;
392
- }
393
- const text = (message ?? "").toLowerCase();
394
- return /429|retry after|timed out|timeout|socket|eai_again|econnreset|fetch failed|temporar/i.test(text);
395
- }
396
-
397
340
  function getLatestRoutingObservation(threadId: string): RouteDecisionMetadata | null {
398
341
  const page = getMessagesPage(threadId, 20);
399
342
  for (let index = page.messages.length - 1; index >= 0; index -= 1) {
@@ -973,7 +916,7 @@ export async function prepareThreadRun(req: ThreadRunRequest): Promise<PreparedT
973
916
  req._transient_retries_left ?? maxTransientRetries(),
974
917
  usageProfile.providerFailureRetries ?? Number.POSITIVE_INFINITY,
975
918
  );
976
- const transientWrapped = transientRetryStream(rawStream, retrySeedReq, transientRetriesLeft);
919
+ const transientWrapped = transientRetryStream(rawStream, retrySeedReq, transientRetriesLeft, prepareThreadRun);
977
920
  const retriesLeft = Math.min(
978
921
  req._stall_retries_left ?? maxStallRetries(),
979
922
  usageProfile.stallRetries ?? Number.POSITIVE_INFINITY,
@@ -988,7 +931,7 @@ export async function prepareThreadRun(req: ThreadRunRequest): Promise<PreparedT
988
931
  // the same with retry continuations. Bypass it entirely for those callers.
989
932
  const stream = req.disable_quality_gates
990
933
  ? transientWrapped
991
- : stallRetryStream(transientWrapped, req, allowedTools, retriesLeft, attemptAbort);
934
+ : stallRetryStream(transientWrapped, req, allowedTools, retriesLeft, attemptAbort, prepareThreadRun);
992
935
  return {
993
936
  signal_delivery: signalDelivery,
994
937
  stream: ownsSignalDelivery ? (async function* () {
@@ -1026,83 +969,6 @@ export async function prepareThreadRun(req: ThreadRunRequest): Promise<PreparedT
1026
969
  };
1027
970
  }
1028
971
 
1029
- async function delay(ms: number): Promise<void> {
1030
- await new Promise<void>((resolve) => setTimeout(resolve, ms));
1031
- }
1032
-
1033
- async function* transientRetryStream(
1034
- inner: AsyncIterable<StreamChunk>,
1035
- originalReq: ThreadRunRequest,
1036
- retriesLeft: number,
1037
- ): AsyncGenerator<StreamChunk> {
1038
- if (retriesLeft <= 0) {
1039
- for await (const chunk of inner) yield chunk;
1040
- return;
1041
- }
1042
-
1043
- let sawVisibleOutput = false;
1044
- let errorChunk: StreamChunk | null = null;
1045
- let doneChunk: StreamChunk | null = null;
1046
-
1047
- for await (const chunk of inner) {
1048
- if (chunk.type === "text_delta" || chunk.type === "thinking_delta" || chunk.type === "tool_call" || chunk.type === "tool_result") {
1049
- sawVisibleOutput = true;
1050
- yield chunk;
1051
- continue;
1052
- }
1053
- if (chunk.type === "done") {
1054
- doneChunk = chunk;
1055
- break;
1056
- }
1057
- if (chunk.type === "error") {
1058
- errorChunk = chunk;
1059
- break;
1060
- }
1061
- yield chunk;
1062
- }
1063
-
1064
- if (doneChunk) {
1065
- yield doneChunk;
1066
- return;
1067
- }
1068
- if (!errorChunk) return;
1069
-
1070
- const data = errorChunk.data as { code?: unknown; message?: unknown; retry_after_ms?: unknown } | undefined;
1071
- const code = typeof data?.code === "string" ? data.code : "";
1072
- const message = typeof data?.message === "string" ? data.message : "";
1073
- const retryAfterMs = typeof data?.retry_after_ms === "number" && Number.isFinite(data.retry_after_ms)
1074
- ? Math.max(0, data.retry_after_ms) : 0;
1075
- if (code === "rate_limited" && retryAfterMs > MAX_RATE_LIMIT_RETRY_AFTER_MS) {
1076
- yield errorChunk;
1077
- return;
1078
- }
1079
- if (sawVisibleOutput || !shouldRetryTransientError(code, message)) {
1080
- yield errorChunk;
1081
- return;
1082
- }
1083
-
1084
- const attempt = Math.max(1, maxTransientRetries() - retriesLeft + 1);
1085
- const backoffMs = code === "rate_limited"
1086
- ? rateLimitRetryDelayMs(attempt, retryAfterMs)
1087
- : transientRetryDelayMs(attempt);
1088
- const nextPolicy = nextPolicyForRetry(originalReq._router_policy_override ?? getConfig().modelRouterPolicy);
1089
- console.warn(`[transient-retry] attempt=${attempt} thread=${originalReq.thread_id} code=${code || "unknown"} backoff_ms=${backoffMs} policy=${nextPolicy}`);
1090
- await delay(backoffMs);
1091
-
1092
- const retry = await prepareThreadRun({
1093
- ...originalReq,
1094
- _transient_retries_left: retriesLeft - 1,
1095
- _skip_persist_message: true,
1096
- _retry_count: (originalReq._retry_count ?? 0) + 1,
1097
- _router_policy_override: originalReq._pinned_model_config_name ? (originalReq._router_policy_override ?? null) : nextPolicy,
1098
- }).catch(() => null);
1099
- if (!retry) {
1100
- yield errorChunk;
1101
- return;
1102
- }
1103
- for await (const chunk of retry.stream) yield chunk;
1104
- }
1105
-
1106
972
  /**
1107
973
  * Build the `--- Available delegates ---` block lines for the system prompt
1108
974
  * when the agent has the `delegate_to_agent` tool allowed and at least one
@@ -1126,429 +992,6 @@ function buildDelegateRoster(
1126
992
  .filter((s): s is string => Boolean(s));
1127
993
  }
1128
994
 
1129
- // Wraps the raw agent stream with stall-retry logic. Chunks pass through
1130
- // LIVE to the consumer (so the chat UI sees deltas as they arrive); we only
1131
- // hold the terminal `done` chunk so we can decide whether to retry. If the
1132
- // completed turn produced no tool calls AND the assistant text matches a
1133
- // "one moment"-style stall pattern, we inject a forceful nudge as a
1134
- // synthetic user message and forward the retry stream's chunks too. The
1135
- // stalled prose stays visible (already streamed) and a "↻" separator marks
1136
- // the boundary; the consumer's text/tool accumulator naturally captures
1137
- // both halves into a single combined assistant message.
1138
- async function* stallRetryStream(
1139
- inner: AsyncIterable<StreamChunk>,
1140
- originalReq: ThreadRunRequest,
1141
- allowedTools: readonly string[],
1142
- retriesLeft: number,
1143
- attemptAbort: AbortController,
1144
- ): AsyncGenerator<StreamChunk> {
1145
- let textBuf = "";
1146
- const toolNames: string[] = [];
1147
- const toolResultSummaries: string[] = [];
1148
- // Track (name, args) signatures within the turn so we can detect a
1149
- // ReAct loop where the model spins on the same tool call. Counts
1150
- // increment only on tool_call chunks; tool_result echoes are ignored.
1151
- const signatureCounts = new Map<string, number>();
1152
- // invoke_tool is `execute`-capability regardless of its target and never
1153
- // throws — a rejected/errored proxied call still comes back as a normal
1154
- // tool_result. Without tracking outcome per call id, a REJECTED proxied
1155
- // write (bad args_json, permission denied, target tool crashed) still
1156
- // satisfies "a write tool ran this turn" below, silently defeating both
1157
- // the fabrication check and the stall/loop auto-retry for exactly the
1158
- // turns where the model's claimed action didn't actually happen.
1159
- const toolCallIds = new Map<string, string>();
1160
- const failedProxyCallIds = new Set<string>();
1161
- // workflow_progress calls (direct or proxied) awaiting their result, so the
1162
- // step contract can be checked from observed tool output at turn end.
1163
- const pendingWorkflowArgs = new Map<string, Record<string, unknown>>();
1164
- const workflowObservations: WorkflowProgressObservation[] = [];
1165
- let loopedToolName: string | null = null;
1166
- let doneChunk: StreamChunk | null = null;
1167
- let sawError = false;
1168
-
1169
- for await (const chunk of inner) {
1170
- if (chunk.type === "text_delta") {
1171
- const d = (chunk.data as { delta?: unknown } | undefined)?.delta;
1172
- if (typeof d === "string") textBuf += d;
1173
- yield chunk;
1174
- } else if (chunk.type === "tool_call") {
1175
- const data = chunk.data as { id?: unknown; name?: unknown; arguments?: unknown } | undefined;
1176
- const rawName = typeof data?.name === "string" ? data.name : "";
1177
- const args = data?.arguments && typeof data.arguments === "object"
1178
- ? (data.arguments as Record<string, unknown>)
1179
- : {};
1180
- const name = unwrapInvokedToolName(rawName, args);
1181
- if (name) {
1182
- toolNames.push(name);
1183
- if (typeof data?.id === "string") {
1184
- toolCallIds.set(data.id, name);
1185
- const workflowArgs = workflowProgressArgs(rawName, args);
1186
- if (workflowArgs) pendingWorkflowArgs.set(data.id, workflowArgs);
1187
- }
1188
- const sig = toolCallSignature(rawName, args);
1189
- const count = (signatureCounts.get(sig) ?? 0) + 1;
1190
- signatureCounts.set(sig, count);
1191
- if (count >= TOOL_LOOP_THRESHOLD && loopedToolName === null) {
1192
- loopedToolName = name;
1193
- // Leave a fingerprint so future loop incidents can be traced
1194
- // to a specific provider/model — most often a sign the
1195
- // aggregator's tool-use fidelity is poor (model narrates
1196
- // "writing now" without emitting the corresponding tool_use
1197
- // block).
1198
- console.warn(
1199
- `[stall-retry] tool-loop detected: tool=${name} repeats=${count} thread=${originalReq.thread_id}`,
1200
- );
1201
- if (retriesLeft > 0) {
1202
- yield chunk;
1203
- break;
1204
- }
1205
- }
1206
- }
1207
- yield chunk;
1208
- } else if (chunk.type === "tool_result") {
1209
- const data = chunk.data as { id?: unknown; name?: unknown; result?: unknown } | undefined;
1210
- const name = typeof data?.name === "string" ? data.name : "tool";
1211
- if (name === "invoke_tool" && typeof data?.id === "string") {
1212
- const payload = data?.result as { ok?: unknown } | null | undefined;
1213
- if (payload && typeof payload === "object" && payload.ok === false) {
1214
- failedProxyCallIds.add(data.id);
1215
- }
1216
- }
1217
- if (typeof data?.id === "string" && pendingWorkflowArgs.has(data.id)) {
1218
- workflowObservations.push({ args: pendingWorkflowArgs.get(data.id), result: data.result });
1219
- pendingWorkflowArgs.delete(data.id);
1220
- }
1221
- const summary = summarizeRetryValue(data?.result).trim();
1222
- if (summary) {
1223
- const clipped = summary.length > 240 ? `${summary.slice(0, 237)}...` : summary;
1224
- toolResultSummaries.push(`${name}: ${clipped}`);
1225
- }
1226
- yield chunk;
1227
- } else if (chunk.type === "done") {
1228
- // Hold the terminal marker — if we retry, the retry's `done` closes
1229
- // the turn instead.
1230
- doneChunk = chunk;
1231
- break;
1232
- } else if (chunk.type === "error") {
1233
- sawError = true;
1234
- yield chunk;
1235
- return;
1236
- } else {
1237
- yield chunk;
1238
- }
1239
- }
1240
-
1241
- // Every call this turn whose outcome is actually known to have succeeded —
1242
- // excludes proxied (invoke_tool) calls confirmed rejected/errored by their
1243
- // tool_result. A direct call with no proxy involved, or a proxied call
1244
- // whose result hasn't arrived, still counts (fail open: absence of
1245
- // evidence of failure is not evidence of failure).
1246
- const succeededToolNames = [...toolCallIds.entries()]
1247
- .filter(([id]) => !failedProxyCallIds.has(id))
1248
- .map(([, name]) => name);
1249
-
1250
- const trimmedText = textBuf.trim();
1251
- const isStallProse = trimmedText.length > 0 && looksLikeStall(trimmedText);
1252
- // The original stall path: model produced narration but called nothing.
1253
- const zeroToolStall = !sawError && toolNames.length === 0 && isStallProse;
1254
- // The "promised next-step" path: model DID call read-only tools, ended
1255
- // the turn with stall prose ("Writing it now", "Saving the file now"),
1256
- // and never invoked a write-like tool. Real failure from the wild — the
1257
- // read+narrate+stop loop slipped past the zero-tool gate. Uses
1258
- // succeededToolNames — a write attempt that was rejected/errored (most
1259
- // commonly a proxied invoke_tool call) must still count as "no write
1260
- // tool ran", or a genuinely stalled turn is silently waved through.
1261
- const promisedWriteStall =
1262
- !sawError &&
1263
- !zeroToolStall &&
1264
- isStallProse &&
1265
- toolNames.length > 0 &&
1266
- !succeededToolNames.some(isWriteLikeToolName);
1267
- const regexStalled = zeroToolStall || promisedWriteStall;
1268
- const looped = !sawError && loopedToolName !== null;
1269
-
1270
- // Anti-hallucination detector — picks ONE method per turn (regex or
1271
- // model), based on the resolved per-agent (or global env) settings.
1272
- // The classifier and the regex never run together; the model is more
1273
- // accurate but adds latency + cost, the regex is fast but brittle.
1274
- const agentCfg = getAgentConfig(originalReq.thread_id ? (getThread(originalReq.thread_id)?.agent_id ?? "") : "");
1275
- const detector = resolveDetector(agentCfg);
1276
- // Strict citation mode forces the stall classifier to model-based:
1277
- // strict turns are higher-stakes, so the more accurate (but more
1278
- // expensive) LLM judge is worth the extra round-trip. Falls back to
1279
- // regex automatically if the agent has no checker model configured.
1280
- const strictness = agentCfg ? parseCitationStrictness(agentCfg.citation_strictness) : null;
1281
- if (strictness === "strict" && detector.modelConfigName) {
1282
- detector.mode = "model";
1283
- }
1284
- let classifierStalled = false;
1285
- let classifierReason = "";
1286
- if (retriesLeft > 0 && !sawError && !looped && detector.mode === "model") {
1287
- const verdict = await classifyStall(textBuf, toolNames, detector.modelConfigName, originalReq.signal)
1288
- .catch(() => null);
1289
- if (verdict) {
1290
- classifierStalled = verdict.stalled;
1291
- classifierReason = verdict.reason;
1292
- } else {
1293
- // Classifier unavailable / errored / aborted — fall back to regex
1294
- // for THIS turn so the agent isn't left ungovernable.
1295
- console.warn(
1296
- `[anti-hallucination] classifier unavailable, falling back to regex for thread ${originalReq.thread_id} (model=${detector.modelConfigName || "<unset>"})`,
1297
- );
1298
- }
1299
- }
1300
-
1301
- // Effective stall verdict per the resolved mode:
1302
- // off → no stall detection (whatever the regex thought, ignore)
1303
- // regex → regex verdict
1304
- // model → classifier verdict if we got one, else regex fallback
1305
- const stalled =
1306
- detector.mode === "off"
1307
- ? false
1308
- : detector.mode === "regex"
1309
- ? regexStalled
1310
- : (classifierStalled || (classifierReason === "" && regexStalled)); // "model" mode
1311
-
1312
- // Fabrication check (ADR-0037): only run when no other path claimed
1313
- // this turn. hasWriteEvidence must reflect a CONFIRMED write, not merely
1314
- // an attempted one — see succeededToolNames above.
1315
- const fabrication = !sawError && !stalled && !looped
1316
- ? validateAssistantOutput(textBuf, toolNames, allowedTools, succeededToolNames.filter(isWriteLikeToolName))
1317
- : ({ ok: true } as const);
1318
-
1319
- // Strict-mode citation audit. Runs ONLY at `citation_strictness === 'strict'`
1320
- // when no earlier gate already claimed the turn — that's when we want to
1321
- // catch hallucinated/uncited high-impact claims and force a correction
1322
- // round. Standard / informational defer to the post-persist fire-and-
1323
- // forget checker (no nudge, just surfacing). The audit is synchronous so
1324
- // it adds one checker round-trip to strict turns; the cost is the price
1325
- // of the stronger guarantee.
1326
- let uncitedHighClaims: ReadonlyArray<{ text: string; reason: string; marker: number | null }> = [];
1327
- if (
1328
- !sawError && !stalled && !looped && fabrication.ok
1329
- && agentCfg
1330
- && parseCitationStrictness(agentCfg.citation_strictness) === "strict"
1331
- && retriesLeft > 0
1332
- && textBuf.trim().length > 0
1333
- ) {
1334
- const checkerModel = (agentCfg.anti_hallucination_model_config ?? "").trim();
1335
- if (checkerModel) {
1336
- // The audit grades against THIS turn's sources. We don't accumulate
1337
- // tool-result payloads in this scope (only names + signatures for
1338
- // loop detection), so the audit can only see what landed in the
1339
- // text — pass an empty events array and let `classifyCitations`
1340
- // judge purely on the markers/links in the prose. The post-persist
1341
- // checker (which runs against the persisted manifest) catches
1342
- // anything this scope misses.
1343
- const auditManifest = buildCombinedManifest([], originalReq.thread_id, {
1344
- tools: Math.max(0, getConfig().citationManifestMax - 10),
1345
- delegates: 10,
1346
- });
1347
- try {
1348
- const verdict = await classifyCitations(textBuf, auditManifest, checkerModel, originalReq.signal);
1349
- if (verdict) {
1350
- uncitedHighClaims = verdict.claims
1351
- .filter((c) => c.impact === "high" && !c.verified)
1352
- .map((c) => ({ text: c.text, reason: c.reason, marker: c.marker }));
1353
- }
1354
- } catch { /* audit failed — fall through, no retry */ }
1355
- }
1356
- }
1357
- const citationFail = uncitedHighClaims.length > 0;
1358
-
1359
- if (!stalled && !looped && fabrication.ok && !citationFail) {
1360
- if (!sawError && workflowObservations.length > 0) {
1361
- yield* workflowStepRetryStream(workflowObservations, originalReq, retriesLeft, attemptAbort, doneChunk, textBuf, toolNames, toolResultSummaries);
1362
- return;
1363
- }
1364
- if (doneChunk) yield doneChunk;
1365
- return;
1366
- }
1367
-
1368
- // succeededToolNames, not toolNames — a rejected/errored proxied write
1369
- // (bad args_json, permission denied, target tool crashed) produced no
1370
- // side effect, so there's nothing a retry could duplicate. Skipping the
1371
- // retry anyway would strand the turn on a write that never happened.
1372
- const writeLikeTools = [...new Set(succeededToolNames.filter(isWriteLikeToolName))];
1373
- if (writeLikeTools.length > 0) {
1374
- yield {
1375
- type: "text_delta",
1376
- data: {
1377
- delta:
1378
- `\n\n*⚠️ Retry guard skipped automatic retry because state-changing tools already ran this turn: ${writeLikeTools.slice(0, 6).join(", ")}. Review the result before continuing to avoid duplicate side effects.*`,
1379
- },
1380
- };
1381
- if (doneChunk) yield doneChunk;
1382
- return;
1383
- }
1384
-
1385
- if (retriesLeft <= 0) {
1386
- yield {
1387
- type: "text_delta",
1388
- data: {
1389
- delta: "\n\n*⚠️ Automatic quality retry is disabled for this usage strategy. Review the result before continuing.*",
1390
- },
1391
- };
1392
- if (doneChunk) yield doneChunk;
1393
- return;
1394
- }
1395
-
1396
- // A stall/loop retry continues a legitimate partial answer, so the prior
1397
- // prose stays visible with a "↻" separator. A fabrication/citation retry
1398
- // (ADR-0037) is different: the COMPLETED reply itself is what's wrong, so
1399
- // the correct move is to discard it, not append a correction after it —
1400
- // otherwise the user (and the persisted message) ends up with both the
1401
- // flagged reply and its replacement (issue #576). `reset_text` tells the
1402
- // client buffer and the persistence collector to drop what they've
1403
- // accumulated for this turn; only the retry's own chunks land after it.
1404
- const isReplaceRetry = !stalled && !looped;
1405
- if (!isReplaceRetry) {
1406
- // Visible separator between the stalled prose and the retry
1407
- // continuation, so the user can see something is being re-attempted.
1408
- yield { type: "text_delta", data: { delta: "\n\n↻ " } };
1409
- }
1410
-
1411
- // Inject a forceful nudge as a synthetic user message so the model sees
1412
- // its own flagged reply + an instruction to continue. Each failure mode
1413
- // gets its own reason-aware nudge.
1414
- const nudge = looped
1415
- ? `↻ Auto-retry: you called \`${loopedToolName}\` ${TOOL_LOOP_THRESHOLD}+ times in this turn with the same arguments without making progress. Either invoke a DIFFERENT tool to advance the task (for example, if you intend to write a file, call \`file_write\` now), or stop and explain what's blocking. Do NOT call \`${loopedToolName}\` again with the same arguments.`
1416
- : promisedWriteStall
1417
- ? `↻ Auto-retry: your reply ended with a 'writing/saving/creating ... now' style statement but you only called read-only tools (${[...new Set(toolNames)].slice(0, 6).join(", ")}) — no write-like tool was invoked. Don't narrate the next step; CALL the actual write tool now (e.g. file_write, file_edit, memory_write). If you cannot, stop and explain why.`
1418
- : zeroToolStall
1419
- ? "↻ Auto-retry: your previous reply ended with a 'one moment' style promise but you didn't call any tool, which ends the turn with nothing happening. Continue the original task NOW by invoking the appropriate tool. Do not acknowledge, do not apologize — just call the tool."
1420
- : classifierStalled
1421
- ? `↻ Auto-retry: the anti-hallucination classifier flagged your reply as a stall (${classifierReason || "promise without a write tool"}). Don't narrate the next step; either CALL the actual tool that fulfils what you promised, or stop and explain why you can't.`
1422
- : citationFail
1423
- ? `↻ Auto-retry: the citation audit flagged ${uncitedHighClaims.length} high-impact claim${uncitedHighClaims.length === 1 ? "" : "s"} without a verified source:\n${uncitedHighClaims.slice(0, 5).map((c, i) => ` ${i + 1}. ${c.text}${c.reason ? ` — ${c.reason}` : ""}`).join("\n")}\n\nThe flagged reply has been discarded — the user will see ONLY what you write next, not the original. Fix each claim in exactly ONE of these three ways:\n (a) cite an existing source from the manifest by appending the marker \`[N]\` to the claim,\n (b) call a tool now (file_read, web_search, fetch_webpage, memory_read, …) to actually ground the claim before stating it,\n (c) rephrase plainly — drop the specific number/fact, or say "I don't have a source for this" — so the claim is no longer load-bearing.\n\nDo NOT restate the rest of the previous reply — it has been discarded and will not be shown again; write only the corrected content. Do NOT invent a marker number that isn't in the manifest.`
1424
- : buildFabricationNudge("reason" in fabrication ? fabrication.reason : "");
1425
-
1426
- const retryContext = buildRetryContextSummary(textBuf, toolNames, toolResultSummaries);
1427
- const nudgeWithContext = retryContext ? `${nudge}\n\n${retryContext}` : nudge;
1428
-
1429
- // Cancel this attempt's own provider call before starting the retry — the
1430
- // consumer loop above already stopped reading (via `break` on tool-loop
1431
- // detection, or naturally via `doneChunk`), but that alone never aborted
1432
- // the underlying HTTP request. Without this, an abandoned attempt can keep
1433
- // running a tool call in the background while the retry starts a second,
1434
- // unrelated one.
1435
- attemptAbort.abort("stall_retry");
1436
-
1437
- const retry = await prepareThreadRun({
1438
- ...originalReq,
1439
- message: nudgeWithContext,
1440
- attachments: undefined,
1441
- _stall_retries_left: retriesLeft - 1,
1442
- _retry_count: (originalReq._retry_count ?? 0) + 1,
1443
- // The nudge is in-memory only — never write it to `messages`. What ends
1444
- // up persisted at end-of-turn via `persistAssistantMessage` is: for a
1445
- // stall/loop retry, the flagged prose + "↻" + the retry (a genuine
1446
- // continuation); for a fabrication/citation retry, the `reset_text`
1447
- // chunk above already cleared the buffer, so it's the retry alone.
1448
- // Without these flags the nudge becomes a permanent user-role row the
1449
- // LLM mistakes for user input on every future turn.
1450
- _skip_persist_message: true,
1451
- _history_append_message: nudgeWithContext,
1452
- });
1453
- if (!isReplaceRetry) {
1454
- for await (const chunk of retry.stream) yield chunk;
1455
- return;
1456
- }
1457
- // Telemetry only (issue #577): a fabrication retry that still mostly
1458
- // repeats the discarded reply's wording didn't fix the underlying
1459
- // regurgitation habit, even though `reset_text` kept the user from
1460
- // seeing two copies. Surfaces as a log line, same as the tool-loop
1461
- // warning above — no gating, no effect on what gets rendered.
1462
- let retryTextBuf = "";
1463
- let resetEmitted = false;
1464
- for await (const chunk of retry.stream) {
1465
- if (chunk.type === "text_delta") {
1466
- const d = (chunk.data as { delta?: unknown } | undefined)?.delta;
1467
- if (typeof d === "string") {
1468
- // A prepared retry can still fail before it produces content. Keep
1469
- // the flagged reply until its replacement has an actual first delta,
1470
- // so an upstream failure does not turn a usable answer into a blank
1471
- // bubble plus an error marker.
1472
- if (!resetEmitted) {
1473
- yield { type: "reset_text", data: {} };
1474
- resetEmitted = true;
1475
- }
1476
- retryTextBuf += d;
1477
- }
1478
- }
1479
- yield chunk;
1480
- }
1481
- if (trimmedText && retryTextBuf.trim()) {
1482
- const overlap = retryTextOverlapRatio(trimmedText, retryTextBuf);
1483
- if (overlap >= 0.85) {
1484
- console.warn(
1485
- `[output-validator] retry_regurgitation ratio=${overlap.toFixed(2)} thread=${originalReq.thread_id}`,
1486
- );
1487
- }
1488
- }
1489
- }
1490
-
1491
- // Workflow step contract auto-retry. Runs only after every other quality
1492
- // gate passed, and has its own per-step budget (WORKFLOW_STEP_MAX_ATTEMPTS)
1493
- // so a stall retry earlier in the turn never starves it. The retry is an
1494
- // append-mode continuation: the turn's work stays visible, followed by the
1495
- // model redoing only the failed steps.
1496
- async function* workflowStepRetryStream(
1497
- observations: readonly WorkflowProgressObservation[],
1498
- originalReq: ThreadRunRequest,
1499
- stallRetriesLeft: number,
1500
- attemptAbort: AbortController,
1501
- doneChunk: StreamChunk | null,
1502
- textBuf: string,
1503
- toolNames: readonly string[],
1504
- toolResultSummaries: readonly string[],
1505
- ): AsyncGenerator<StreamChunk> {
1506
- const spent = originalReq._workflow_step_retries ?? {};
1507
- const failures = collectWorkflowContractFailures(observations);
1508
- const { retry, exhausted } = planWorkflowStepRetries(failures, spent);
1509
- const spentTotal = Object.values(spent).reduce((sum, n) => sum + n, 0);
1510
-
1511
- if (retry.length === 0 || spentTotal >= WORKFLOW_TURN_AUTO_RETRY_LIMIT) {
1512
- const unresolved = [...exhausted, ...retry];
1513
- if (unresolved.length > 0) {
1514
- console.warn(
1515
- `[workflow-retry] contract still failing after auto-retry: ${unresolved.map((f) => f.key).join(", ")} thread=${originalReq.thread_id}`,
1516
- );
1517
- yield {
1518
- type: "text_delta",
1519
- data: {
1520
- delta: `\n\n*⚠️ Workflow step${unresolved.length === 1 ? "" : "s"} still failing the step contract after automatic retries: ${unresolved.slice(0, 4).map((f) => `"${f.label}"`).join(", ")}. Use the step's retry button or review it manually.*`,
1521
- },
1522
- };
1523
- }
1524
- if (doneChunk) yield doneChunk;
1525
- return;
1526
- }
1527
-
1528
- console.warn(
1529
- `[workflow-retry] retrying ${retry.map((f) => `${f.key}#${f.attempt}`).join(", ")} thread=${originalReq.thread_id}`,
1530
- );
1531
- yield { type: "text_delta", data: { delta: "\n\n↻ " } };
1532
- const nudge = buildWorkflowStepRetryNudge(retry);
1533
- const retryContext = buildRetryContextSummary(textBuf, [...toolNames], [...toolResultSummaries]);
1534
- const nudgeWithContext = retryContext ? `${nudge}\n\n${retryContext}` : nudge;
1535
- const nextSpent: Record<string, number> = { ...spent };
1536
- for (const failure of retry) nextSpent[failure.key] = (nextSpent[failure.key] ?? 0) + 1;
1537
-
1538
- attemptAbort.abort("workflow_step_retry");
1539
- const next = await prepareThreadRun({
1540
- ...originalReq,
1541
- message: nudgeWithContext,
1542
- attachments: undefined,
1543
- _stall_retries_left: stallRetriesLeft,
1544
- _workflow_step_retries: nextSpent,
1545
- _retry_count: (originalReq._retry_count ?? 0) + 1,
1546
- _skip_persist_message: true,
1547
- _history_append_message: nudgeWithContext,
1548
- });
1549
- for await (const chunk of next.stream) yield chunk;
1550
- }
1551
-
1552
995
  export interface AssistantUsageSnapshot {
1553
996
  input_tokens: number;
1554
997
  output_tokens: number;
@@ -1958,149 +1401,6 @@ function stripAutoplayHints(text: string): string {
1958
1401
  );
1959
1402
  }
1960
1403
 
1961
- const TOOL_LOOP_THRESHOLD = 3;
1962
-
1963
- // A "write-like" tool, by name, is one whose path segments contain a CRUD
1964
- // verb. Per-segment match so e.g. `dataset_search` doesn't qualify on
1965
- // `set`. Used to flag the "called read-only tools then promised a write"
1966
- // stall pattern.
1967
- export function isWriteLikeToolName(name: string): boolean {
1968
- if (!name) return false;
1969
- // Built-ins declare their safety class at registration (ADR-0038), so trust
1970
- // that over re-deriving it from the name — `propose_config_change` queues a
1971
- // pending action but has no CRUD verb in it. MCP/external tools aren't in
1972
- // the registry and still fall back to the verb scan.
1973
- const capability = registeredCapability(name);
1974
- if (capability) return capability !== "read";
1975
- const segments = name.toLowerCase().split(/[._\-/]+/).filter(Boolean);
1976
- return segments.some(isWriteToolNameSegment);
1977
- }
1978
-
1979
- // `invoke_tool` is a dispatcher: the tool that actually ran is named in its
1980
- // arguments. Reporting the wrapper to the retry heuristics makes every
1981
- // proxied call look read-only and unnamed, so a turn that really did call
1982
- // `memory_write` gets flagged as a stall and re-run from scratch.
1983
- export function unwrapInvokedToolName(name: string, args: Record<string, unknown>): string {
1984
- if (name !== "invoke_tool") return name;
1985
- const target = args.name;
1986
- return typeof target === "string" && target.trim() ? target.trim() : name;
1987
- }
1988
-
1989
- // Stable signature of a tool call so repeated identical calls collapse to
1990
- // the same key. JSON.stringify with sorted keys is good enough — the
1991
- // argument shapes that matter here are small JSON objects, not graphs.
1992
- export function toolCallSignature(name: string, args: Record<string, unknown>): string {
1993
- try {
1994
- const sortedKeys = Object.keys(args).sort();
1995
- const stable: Record<string, unknown> = {};
1996
- for (const k of sortedKeys) stable[k] = args[k];
1997
- return `${name}::${JSON.stringify(stable)}`;
1998
- } catch {
1999
- return `${name}::<unserializable>`;
2000
- }
2001
- }
2002
-
2003
- function summarizeRetryValue(value: unknown): string {
2004
- if (typeof value === "string") return value.trim();
2005
- if (typeof value === "number" || typeof value === "boolean" || value === null) return String(value);
2006
- try {
2007
- return JSON.stringify(value);
2008
- } catch {
2009
- return Object.prototype.toString.call(value);
2010
- }
2011
- }
2012
-
2013
- // A short clip reads to the model as "a snippet of what I said" rather than
2014
- // "the whole thing I said" — which pushed it to re-emit the full prior reply
2015
- // on retry instead of trusting that the recap already covers it (issue
2016
- // #577). 2000 chars covers the overwhelming majority of turns in full while
2017
- // still bounding the nudge's own token cost.
2018
- const RETRY_CONTEXT_CLIP_CHARS = 2000;
2019
-
2020
- export function buildRetryContextSummary(
2021
- text: string,
2022
- toolNames: readonly string[],
2023
- toolResults: readonly string[] = [],
2024
- ): string {
2025
- const parts: string[] = [];
2026
- const trimmedText = text.trim();
2027
- if (trimmedText) {
2028
- const clipped = trimmedText.length > RETRY_CONTEXT_CLIP_CHARS
2029
- ? `${trimmedText.slice(0, RETRY_CONTEXT_CLIP_CHARS - 3)}...`
2030
- : trimmedText;
2031
- parts.push(`Already said this turn: ${clipped}`);
2032
- }
2033
- const uniqueTools = [...new Set(toolNames.filter(Boolean))];
2034
- if (uniqueTools.length > 0) {
2035
- parts.push(`Tools already used this turn: ${uniqueTools.slice(0, 8).join(", ")}`);
2036
- }
2037
- if (toolResults.length > 0) {
2038
- parts.push(`Tool results already seen this turn:\n${toolResults.slice(0, 5).map((line, index) => ` ${index + 1}. ${line}`).join("\n")}`);
2039
- }
2040
- return parts.join("\n");
2041
- }
2042
-
2043
- // The default ADR-0037 fabrication nudge (issue #577). Phrased as a
2044
- // minimal-diff instruction rather than "redo this turn" — "redo" reads to
2045
- // the model as "do the whole thing over", which is exactly the regurgitation
2046
- // this issue reports. Paired with the `reset_text` StreamChunk (issue #576),
2047
- // which discards the flagged reply when the replacement produces its first
2048
- // text delta, so the persisted final reply never contains both versions.
2049
- export function buildFabricationNudge(reason: string): string {
2050
- return `↻ Auto-retry: output validator flagged your reply${reason ? ` — ${reason}` : ""}. The flagged reply has been discarded — the user will see ONLY what you write next, not the original. Do NOT restate, summarize, or repeat any part of the previous answer. Emit ONLY the fix: call the tool that's actually missing, or state the corrected claim in one or two sentences.`;
2051
- }
2052
-
2053
- // Word-multiset containment: what fraction of `retry`'s tokens also appear
2054
- // in `original`. Order-insensitive and duplicate-aware (each token in
2055
- // `original` can only satisfy one token in `retry`), so a retry that mostly
2056
- // repeats the flagged reply verbatim — the failure mode issue #577
2057
- // describes — scores high regardless of minor rewording. Used only for
2058
- // telemetry: it flags regurgitation, it doesn't gate or alter rendering.
2059
- export function retryTextOverlapRatio(original: string, retry: string): number {
2060
- const tokenize = (s: string) => s.toLowerCase().match(/[a-z0-9']+/g) ?? [];
2061
- const retryTokens = tokenize(retry);
2062
- if (retryTokens.length === 0) return 0;
2063
- const originalCounts = new Map<string, number>();
2064
- for (const t of tokenize(original)) originalCounts.set(t, (originalCounts.get(t) ?? 0) + 1);
2065
- let shared = 0;
2066
- for (const t of retryTokens) {
2067
- const remaining = originalCounts.get(t) ?? 0;
2068
- if (remaining > 0) {
2069
- shared += 1;
2070
- originalCounts.set(t, remaining - 1);
2071
- }
2072
- }
2073
- return shared / retryTokens.length;
2074
- }
2075
-
2076
- const STALL_PHRASE_GROUP = STALL_TAIL_PHRASES.join("|").replace(/ /g, "\\s+");
2077
- const STALL_NOW_VERB_GROUP = STALL_NOW_ACTION_VERBS.join("|");
2078
-
2079
- const STALL_PATTERNS: RegExp[] = [
2080
- new RegExp(`\\b(?:${STALL_PHRASE_GROUP})\\b`, "i"),
2081
- /\bgive me (a|just a) (moment|sec(?:ond)?|minute)\b/i,
2082
- /\blet me (try|do (?:that|this|it))\b/i,
2083
- /\bi['’]?ll (check|verify|continue|proceed|look|try|do (?:that|this|it)|keep going|get (?:on|right) (?:on|to))/i,
2084
- /\b(continuing|proceeding|working on it|moving on)\b.*[!.]?\s*$/i,
2085
- // Aspirational future-action family: "Writing X now", "Saving the file
2086
- // now", "Creating the report now". Catches the read-only-tools +
2087
- // narrate-the-write + end-of-turn loop where the model promises a
2088
- // write but never invokes the corresponding tool.
2089
- new RegExp(`\\b(?:${STALL_NOW_VERB_GROUP})\\b[^.!?]*\\bnow\\b[!.]?\\s*$`, "i"),
2090
- // Broader promise-shape: any "I'll <verb>" or "I will <verb>" followed
2091
- // by "now" anywhere in the trailing clause. Catches "I will read it
2092
- // now to understand the plan" / "I'll add the note now" — variants the
2093
- // narrow aspirational-verb list above misses because the verb is in
2094
- // bare infinitive form and `now` is mid-sentence rather than at the
2095
- // end.
2096
- /\b(?:i['’]?ll|i\s+will)\s+\w+\b[^.!?]*\bnow\b/i,
2097
- // Present-continuous version: "I'm reading … now to figure out …" /
2098
- // "I am updating the dashboard now to reflect …". Same idea, but the
2099
- // model is narrating in progress rather than promising in future.
2100
- // Same failure mode in practice — followed by no actual write call.
2101
- /\b(?:i['’]?m|i\s+am)\s+\w+ing\b[^.!?]*\bnow\b/i,
2102
- ];
2103
-
2104
1404
  // Resolve the agent's allowed_tools list from a thread id. Best-effort: empty
2105
1405
  // list if the thread or agent config has gone away (the validator then
2106
1406
  // flags any `(via foo)` citation as unregistered, which is the safe default).
@@ -2111,14 +1411,6 @@ function lookupAllowedToolsForThread(thread_id: string): string[] {
2111
1411
  return withDefaultTools(getAgentTools(agentCfg), getDefaultAgentToolNames());
2112
1412
  }
2113
1413
 
2114
- export function looksLikeStall(text: string): boolean {
2115
- // Inspect the last paragraph / sentence — earlier acknowledgment
2116
- // language is fine when followed by real work. The stall signal is when
2117
- // the message ends on a promise.
2118
- const tail = text.split(/\n{2,}|(?<=[.!?])\s+/).filter(Boolean).slice(-2).join(" ");
2119
- return STALL_PATTERNS.some((re) => re.test(tail));
2120
- }
2121
-
2122
1414
  // Run semantic recall on the user's turn, format the top hits as a system-prompt
2123
1415
  // block. Empty string when no embeddings configured or no good matches.
2124
1416
  async function buildRecallContext(