@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.
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-path-routes-manifest.json +5 -5
- package/.next/standalone/.next/build-manifest.json +2 -2
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/react-loadable-manifest.json +2 -2
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +2 -2
- package/.next/standalone/.next/server/app/_not-found.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/chats/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/lookup/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/pair/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/bridges/[id]/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/credentials/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/credentials/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/credentials/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/dashboard/pricing-task/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/delegations/codex/[job_id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/reindex/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/documents/sources/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/documents/sources/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/events/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extension/agents/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extension/fill/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extension/refine/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extension/turn/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/config/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/extensions/tools/[name]/secrets/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/health/probes/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/health/probes/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/integrations/[name]/test/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/callback/route.js +22 -1
- package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/start/route.js +22 -1
- package/.next/standalone/.next/server/app/api/v1/integrations/gmail/oauth/status/route.js +22 -1
- package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/callback/route.js +19 -2
- package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/start/route.js +19 -2
- package/.next/standalone/.next/server/app/api/v1/integrations/outlook/oauth/status/route.js +19 -2
- package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js +12 -2
- package/.next/standalone/.next/server/app/api/v1/packages/defaults/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/packages/install/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/install/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/packages/install/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/enabled/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/[name]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/packages/manifests/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js +12 -2
- package/.next/standalone/.next/server/app/api/v1/packages/reload/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/packages/route.js +12 -2
- package/.next/standalone/.next/server/app/api/v1/packages/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/approve/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/pending-actions/[id]/deny/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/pending-actions/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/scheduled-tasks/[id]/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/system/restart/route.js +7 -0
- package/.next/standalone/.next/server/app/api/v1/system/restart/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +52 -45
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/tools/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/tools/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/update/apply/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/watchers/[id]/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/v1/watchers/route.js +8 -1
- package/.next/standalone/.next/server/app/api/v1/watchers/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page.js +73385 -73375
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +5 -5
- package/.next/standalone/.next/server/chunks/1433.js +1 -1
- package/.next/standalone/.next/server/chunks/210.js +6 -6
- package/.next/standalone/.next/server/chunks/3524.js +31 -15
- package/.next/standalone/.next/server/chunks/3566.js +1 -1
- package/.next/standalone/.next/server/chunks/4189.js +1 -1
- package/.next/standalone/.next/server/chunks/{9590.js → 423.js} +10 -3
- package/.next/standalone/.next/server/chunks/4596.js +5 -2
- package/.next/standalone/.next/server/chunks/46.js +7 -0
- package/.next/standalone/.next/server/chunks/540.js +29 -5
- package/.next/standalone/.next/server/chunks/5585.js +41 -3
- package/.next/standalone/.next/server/chunks/5908.js +10 -10
- package/.next/standalone/.next/server/chunks/{3399.js → 6058.js} +485 -3
- package/.next/standalone/.next/server/chunks/{9164.js → 6190.js} +13828 -13581
- package/.next/standalone/.next/server/chunks/{1388.js → 8842.js} +5961 -5793
- package/.next/standalone/.next/server/chunks/9032.js +5 -5
- package/.next/standalone/.next/server/chunks/{7547.js → 9217.js} +485 -3
- package/.next/standalone/.next/server/instrumentation.js +7 -0
- package/.next/standalone/.next/server/middleware-build-manifest.js +2 -2
- package/.next/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
- package/.next/standalone/.next/server/middleware.js +7 -0
- package/.next/standalone/.next/server/pages/404.html +2 -2
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/preview-props.json +3 -3
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/static/chunks/app/{page-2ef8d75d40eb4311.js → page-4112e14360a9909e.js} +1291 -1281
- package/.next/standalone/.next/static/css/{c160ea862133acd2.css → 5b30046ba49144c5.css} +2 -2
- package/.next/standalone/docs/adoption/changesets.json +151 -0
- package/.next/standalone/package.json +2 -1
- package/CHANGELOG.md +46 -0
- package/browser-extension/background.js +5 -539
- package/browser-extension/lib/form-editing.mjs +541 -0
- package/components/chat/MessageBubble.tsx +4 -736
- package/components/chat/MessageContent.tsx +749 -0
- package/components/dashboard/DashboardPanel.test.tsx +34 -0
- package/components/dashboard/DashboardPanel.tsx +1 -1
- package/components/layout/MenuPanel.tsx +1 -1
- package/components/ui/BootScreen.test.tsx +1 -0
- package/components/ui/BootScreen.tsx +1 -0
- package/components/ui/ServerStatus.test.tsx +50 -0
- package/components/ui/ServerStatus.tsx +10 -8
- package/hooks/useSSE.test.ts +46 -0
- package/lib/agents/llm.ts +1 -1
- package/lib/agents/output-validator/validator.test.ts +4 -0
- package/lib/agents/output-validator/validator.ts +1 -1
- package/lib/agents/prompt-registry.test.ts +11 -0
- package/lib/agents/prompt-registry.ts +13 -0
- package/lib/agents/retry-prompts.ts +17 -0
- package/lib/agents/run-retry.ts +671 -0
- package/lib/agents/run-thread.retry.test.ts +176 -2
- package/lib/agents/run-thread.test.ts +6 -6
- package/lib/agents/run-thread.ts +9 -717
- package/lib/agents/stream-collector.test.ts +28 -4
- package/lib/agents/stream-collector.ts +5 -28
- package/lib/agents/tool-outcomes.ts +61 -0
- package/lib/documents/remote/confluence.test.ts +65 -0
- package/lib/documents/remote/confluence.ts +35 -9
- package/lib/documents/remote/jira.ts +1 -1
- package/lib/health/probes.test.ts +32 -0
- package/lib/health/probes.ts +29 -14
- package/lib/integrations/atlassian/manifest.ts +5 -3
- package/lib/integrations/github/manifest.ts +7 -4
- package/lib/integrations/gmail-oauth.ts +16 -1
- package/lib/integrations/microsoft-oauth.ts +17 -2
- package/lib/integrations/outlook/manifest.ts +10 -8
- package/lib/stores/integrations.ts +1 -0
- package/lib/tools/communications/calendar-aliases.test.ts +77 -1
- package/lib/tools/communications/gmail.test.ts +13 -0
- package/lib/tools/communications/ms-graph.test.ts +26 -3
- package/lib/tools/communications/ms-graph.ts +9 -11
- package/lib/tools/communications/outlook-calendar.ts +94 -17
- package/lib/tools/packages/default-packages/atlassian.ts +8 -2
- package/package.json +2 -1
- package/scripts/standalone-footprint.mjs +1 -1
- /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{544OFJV-q0RC6Gjgje4LT → VZXMorlOmSmi3dUr7K5UX}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
import { isWriteToolNameSegment, STALL_NOW_ACTION_VERBS, STALL_TAIL_PHRASES } from "@/lib/agents/action-vocabulary";
|
|
2
|
+
import { getConfig } from "@/lib/env/config";
|
|
3
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
|
+
import type { StreamChunk } from "@/lib/agents/base";
|
|
5
|
+
import { registeredCapability } from "@/lib/tools/runtime/registry";
|
|
6
|
+
import { getThread } from "@/lib/stores/threads";
|
|
7
|
+
import { getAgentConfig, parseCitationStrictness } from "@/lib/stores/agent-configs";
|
|
8
|
+
import { validateAssistantOutput } from "@/lib/agents/output-validator";
|
|
9
|
+
import { buildWorkflowStepRetryNudge, collectWorkflowContractFailures, planWorkflowStepRetries, WORKFLOW_TURN_AUTO_RETRY_LIMIT, workflowProgressArgs, type WorkflowProgressObservation } from "@/lib/agents/workflow-step-retry";
|
|
10
|
+
import { type ThreadRunRequest } from "@/lib/agents/prepare";
|
|
11
|
+
import { classifyStall, resolveDetector, type StallVerdict } from "@/lib/agents/hallucination-classifier";
|
|
12
|
+
import { nextPolicyForRetry } from "@/lib/agents/model-router";
|
|
13
|
+
import { buildCombinedManifest, classifyCitations } from "@/lib/agents/citation-checker";
|
|
14
|
+
import type { PreparedThreadRun } from "@/lib/agents/run-thread";
|
|
15
|
+
import { ToolOutcomes, unwrapInvokedToolName } from "./tool-outcomes";
|
|
16
|
+
import { buildFabricationNudge, buildCitationRetryNudge } from "./retry-prompts";
|
|
17
|
+
export { buildFabricationNudge } from "./retry-prompts";
|
|
18
|
+
export { unwrapInvokedToolName } from "./tool-outcomes";
|
|
19
|
+
|
|
20
|
+
type PrepareRetry = (request: ThreadRunRequest) => Promise<Pick<PreparedThreadRun, "stream">>;
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
export function transientRetryDelayMs(attempt: number): number {
|
|
24
|
+
const clamped = Math.max(1, attempt);
|
|
25
|
+
return Math.min(8_000, 500 * (2 ** (clamped - 1)));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
export const MAX_RATE_LIMIT_RETRY_AFTER_MS = 60_000;
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
export function rateLimitRetryDelayMs(attempt: number, retryAfterMs = 0): number {
|
|
33
|
+
return Math.max(transientRetryDelayMs(attempt), Math.max(0, retryAfterMs));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
export function shouldRetryTransientError(code: string | null | undefined, message: string | null | undefined): boolean {
|
|
38
|
+
const normalized = (code ?? "").trim().toLowerCase();
|
|
39
|
+
if (normalized === "rate_limited" || normalized === "empty_response" || normalized === "stream_error" || normalized === "agent_error") {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
if (normalized === "aborted" || normalized === "auth_failed" || normalized === "context_length_exceeded" || normalized === "recursion_limit" || normalized === "no_model") {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
const text = (message ?? "").toLowerCase();
|
|
46
|
+
return /429|retry after|timed out|timeout|socket|eai_again|econnreset|fetch failed|temporar/i.test(text);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
export async function* transientRetryStream(
|
|
51
|
+
inner: AsyncIterable<StreamChunk>,
|
|
52
|
+
originalReq: ThreadRunRequest,
|
|
53
|
+
retriesLeft: number,
|
|
54
|
+
prepareRetry: PrepareRetry,
|
|
55
|
+
): AsyncGenerator<StreamChunk> {
|
|
56
|
+
if (retriesLeft <= 0) {
|
|
57
|
+
yield* inner;
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let sawVisibleOutput = false;
|
|
62
|
+
let errorChunk: StreamChunk | null = null;
|
|
63
|
+
let doneChunk: StreamChunk | null = null;
|
|
64
|
+
|
|
65
|
+
for await (const chunk of inner) {
|
|
66
|
+
if (chunk.type === "text_delta" || chunk.type === "thinking_delta" || chunk.type === "tool_call" || chunk.type === "tool_result") {
|
|
67
|
+
sawVisibleOutput = true;
|
|
68
|
+
yield chunk;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (chunk.type === "done") {
|
|
72
|
+
doneChunk = chunk;
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
if (chunk.type === "error") {
|
|
76
|
+
errorChunk = chunk;
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
yield chunk;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (doneChunk) {
|
|
83
|
+
yield doneChunk;
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!errorChunk) return;
|
|
87
|
+
|
|
88
|
+
const data = errorChunk.data as { code?: unknown; message?: unknown; retry_after_ms?: unknown } | undefined;
|
|
89
|
+
const code = typeof data?.code === "string" ? data.code : "";
|
|
90
|
+
const message = typeof data?.message === "string" ? data.message : "";
|
|
91
|
+
const retryAfterMs = typeof data?.retry_after_ms === "number" && Number.isFinite(data.retry_after_ms)
|
|
92
|
+
? Math.max(0, data.retry_after_ms) : 0;
|
|
93
|
+
if (code === "rate_limited" && retryAfterMs > MAX_RATE_LIMIT_RETRY_AFTER_MS) {
|
|
94
|
+
yield errorChunk;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (sawVisibleOutput || !shouldRetryTransientError(code, message)) {
|
|
98
|
+
yield errorChunk;
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const attempt = Math.max(1, getConfig().maxTransientRetries - retriesLeft + 1);
|
|
103
|
+
const backoffMs = code === "rate_limited"
|
|
104
|
+
? rateLimitRetryDelayMs(attempt, retryAfterMs)
|
|
105
|
+
: transientRetryDelayMs(attempt);
|
|
106
|
+
const nextPolicy = nextPolicyForRetry(originalReq._router_policy_override ?? getConfig().modelRouterPolicy);
|
|
107
|
+
console.warn(`[transient-retry] attempt=${attempt} thread=${originalReq.thread_id} code=${code || "unknown"} backoff_ms=${backoffMs} policy=${nextPolicy}`);
|
|
108
|
+
try {
|
|
109
|
+
await delay(backoffMs, undefined, { signal: originalReq.signal });
|
|
110
|
+
originalReq.signal?.throwIfAborted();
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (!originalReq.signal?.aborted) throw error;
|
|
113
|
+
yield { type: "error", data: { code: "aborted", message: "Run stopped during retry backoff." } };
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const retry = await prepareRetry({
|
|
118
|
+
...originalReq,
|
|
119
|
+
_transient_retries_left: retriesLeft - 1,
|
|
120
|
+
_skip_persist_message: true,
|
|
121
|
+
_retry_count: (originalReq._retry_count ?? 0) + 1,
|
|
122
|
+
_router_policy_override: originalReq._pinned_model_config_name ? (originalReq._router_policy_override ?? null) : nextPolicy,
|
|
123
|
+
}).catch(() => null);
|
|
124
|
+
if (!retry) {
|
|
125
|
+
yield errorChunk;
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
yield* retry.stream;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
// Wraps the raw agent stream with stall-retry logic. Chunks pass through
|
|
133
|
+
// LIVE to the consumer (so the chat UI sees deltas as they arrive); we only
|
|
134
|
+
// hold the terminal `done` chunk so we can decide whether to retry. If the
|
|
135
|
+
// completed turn produced no tool calls AND the assistant text matches a
|
|
136
|
+
// "one moment"-style stall pattern, we inject a forceful nudge as a
|
|
137
|
+
// synthetic user message and forward the retry stream's chunks too. The
|
|
138
|
+
// stalled prose stays visible (already streamed) and a "↻" separator marks
|
|
139
|
+
// the boundary; the consumer's text/tool accumulator naturally captures
|
|
140
|
+
// both halves into a single combined assistant message.
|
|
141
|
+
export async function* stallRetryStream(
|
|
142
|
+
inner: AsyncIterable<StreamChunk>,
|
|
143
|
+
originalReq: ThreadRunRequest,
|
|
144
|
+
allowedTools: readonly string[],
|
|
145
|
+
retriesLeft: number,
|
|
146
|
+
attemptAbort: AbortController,
|
|
147
|
+
prepareRetry: PrepareRetry,
|
|
148
|
+
): AsyncGenerator<StreamChunk> {
|
|
149
|
+
let textBuf = "";
|
|
150
|
+
const toolNames: string[] = [];
|
|
151
|
+
const toolResultSummaries: string[] = [];
|
|
152
|
+
// Track (name, args) signatures within the turn so we can detect a
|
|
153
|
+
// ReAct loop where the model spins on the same tool call. Counts
|
|
154
|
+
// increment only on tool_call chunks; tool_result echoes are ignored.
|
|
155
|
+
const signatureCounts = new Map<string, number>();
|
|
156
|
+
const toolOutcomes = new ToolOutcomes();
|
|
157
|
+
// workflow_progress calls (direct or proxied) awaiting their result, so the
|
|
158
|
+
// step contract can be checked from observed tool output at turn end.
|
|
159
|
+
const pendingWorkflowArgs = new Map<string, Record<string, unknown>>();
|
|
160
|
+
const workflowObservations: WorkflowProgressObservation[] = [];
|
|
161
|
+
let loopedToolName: string | null = null;
|
|
162
|
+
let doneChunk: StreamChunk | null = null;
|
|
163
|
+
|
|
164
|
+
for await (const chunk of inner) {
|
|
165
|
+
toolOutcomes.observe(chunk);
|
|
166
|
+
if (chunk.type === "text_delta") {
|
|
167
|
+
const d = (chunk.data as { delta?: unknown } | undefined)?.delta;
|
|
168
|
+
if (typeof d === "string") textBuf += d;
|
|
169
|
+
yield chunk;
|
|
170
|
+
} else if (chunk.type === "tool_call") {
|
|
171
|
+
const data = chunk.data as { id?: unknown; name?: unknown; arguments?: unknown } | undefined;
|
|
172
|
+
const rawName = typeof data?.name === "string" ? data.name : "";
|
|
173
|
+
const args = data?.arguments && typeof data.arguments === "object"
|
|
174
|
+
? (data.arguments as Record<string, unknown>)
|
|
175
|
+
: {};
|
|
176
|
+
const name = unwrapInvokedToolName(rawName, args);
|
|
177
|
+
if (name) {
|
|
178
|
+
toolNames.push(name);
|
|
179
|
+
if (typeof data?.id === "string") {
|
|
180
|
+
const workflowArgs = workflowProgressArgs(rawName, args);
|
|
181
|
+
if (workflowArgs) pendingWorkflowArgs.set(data.id, workflowArgs);
|
|
182
|
+
}
|
|
183
|
+
const sig = toolCallSignature(rawName, args);
|
|
184
|
+
const count = (signatureCounts.get(sig) ?? 0) + 1;
|
|
185
|
+
signatureCounts.set(sig, count);
|
|
186
|
+
if (count >= TOOL_LOOP_THRESHOLD && loopedToolName === null) {
|
|
187
|
+
loopedToolName = name;
|
|
188
|
+
// Leave a fingerprint so future loop incidents can be traced
|
|
189
|
+
// to a specific provider/model — most often a sign the
|
|
190
|
+
// aggregator's tool-use fidelity is poor (model narrates
|
|
191
|
+
// "writing now" without emitting the corresponding tool_use
|
|
192
|
+
// block).
|
|
193
|
+
console.warn(
|
|
194
|
+
`[stall-retry] tool-loop detected: tool=${name} repeats=${count} thread=${originalReq.thread_id}`,
|
|
195
|
+
);
|
|
196
|
+
if (retriesLeft > 0) {
|
|
197
|
+
yield chunk;
|
|
198
|
+
break;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
yield chunk;
|
|
203
|
+
} else if (chunk.type === "tool_result") {
|
|
204
|
+
const data = chunk.data as { id?: unknown; name?: unknown; result?: unknown } | undefined;
|
|
205
|
+
const name = typeof data?.name === "string" ? data.name : "tool";
|
|
206
|
+
if (typeof data?.id === "string" && pendingWorkflowArgs.has(data.id)) {
|
|
207
|
+
workflowObservations.push({ args: pendingWorkflowArgs.get(data.id), result: data.result });
|
|
208
|
+
pendingWorkflowArgs.delete(data.id);
|
|
209
|
+
}
|
|
210
|
+
const summary = summarizeRetryValue(data?.result).trim();
|
|
211
|
+
if (summary) {
|
|
212
|
+
const clipped = summary.length > 240 ? `${summary.slice(0, 237)}...` : summary;
|
|
213
|
+
toolResultSummaries.push(`${name}: ${clipped}`);
|
|
214
|
+
}
|
|
215
|
+
yield chunk;
|
|
216
|
+
} else if (chunk.type === "done") {
|
|
217
|
+
// Hold the terminal marker — if we retry, the retry's `done` closes
|
|
218
|
+
// the turn instead.
|
|
219
|
+
doneChunk = chunk;
|
|
220
|
+
break;
|
|
221
|
+
} else if (chunk.type === "error") {
|
|
222
|
+
yield chunk;
|
|
223
|
+
return;
|
|
224
|
+
} else {
|
|
225
|
+
yield chunk;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const succeededToolNames = toolOutcomes.successfulNames();
|
|
230
|
+
|
|
231
|
+
const trimmedText = textBuf.trim();
|
|
232
|
+
const isStallProse = trimmedText.length > 0 && looksLikeStall(trimmedText);
|
|
233
|
+
// The original stall path: model produced narration but called nothing.
|
|
234
|
+
const zeroToolStall = toolNames.length === 0 && isStallProse;
|
|
235
|
+
// The "promised next-step" path: model DID call read-only tools, ended
|
|
236
|
+
// the turn with stall prose ("Writing it now", "Saving the file now"),
|
|
237
|
+
// and never invoked a write-like tool. Real failure from the wild — the
|
|
238
|
+
// read+narrate+stop loop slipped past the zero-tool gate. Uses
|
|
239
|
+
// succeededToolNames — a write attempt that was rejected/errored (most
|
|
240
|
+
// commonly a proxied invoke_tool call) must still count as "no write
|
|
241
|
+
// tool ran", or a genuinely stalled turn is silently waved through.
|
|
242
|
+
const promisedWriteStall =
|
|
243
|
+
!zeroToolStall &&
|
|
244
|
+
isStallProse &&
|
|
245
|
+
toolNames.length > 0 &&
|
|
246
|
+
!succeededToolNames.some(isWriteLikeToolName);
|
|
247
|
+
const regexStalled = zeroToolStall || promisedWriteStall;
|
|
248
|
+
const looped = loopedToolName !== null;
|
|
249
|
+
|
|
250
|
+
// Anti-hallucination detector — picks ONE method per turn (regex or
|
|
251
|
+
// model), based on the resolved per-agent (or global env) settings.
|
|
252
|
+
// The classifier and the regex never run together; the model is more
|
|
253
|
+
// accurate but adds latency + cost, the regex is fast but brittle.
|
|
254
|
+
const agentCfg = getAgentConfig(originalReq.thread_id ? (getThread(originalReq.thread_id)?.agent_id ?? "") : "");
|
|
255
|
+
const detector = resolveDetector(agentCfg);
|
|
256
|
+
// Strict citation mode forces the stall classifier to model-based:
|
|
257
|
+
// strict turns are higher-stakes, so the more accurate (but more
|
|
258
|
+
// expensive) LLM judge is worth the extra round-trip. Falls back to
|
|
259
|
+
// regex automatically if the agent has no checker model configured.
|
|
260
|
+
const strictness = agentCfg ? parseCitationStrictness(agentCfg.citation_strictness) : null;
|
|
261
|
+
if (strictness === "strict" && detector.modelConfigName) {
|
|
262
|
+
detector.mode = "model";
|
|
263
|
+
}
|
|
264
|
+
let classifierVerdict: StallVerdict | null = null;
|
|
265
|
+
if (retriesLeft > 0 && !looped && detector.mode === "model") {
|
|
266
|
+
classifierVerdict = await classifyStall(textBuf, succeededToolNames, detector.modelConfigName, originalReq.signal)
|
|
267
|
+
.catch(() => null);
|
|
268
|
+
if (!classifierVerdict) {
|
|
269
|
+
// Classifier unavailable / errored / aborted — fall back to regex
|
|
270
|
+
// for THIS turn so the agent isn't left ungovernable.
|
|
271
|
+
console.warn(
|
|
272
|
+
`[anti-hallucination] classifier unavailable, falling back to regex for thread ${originalReq.thread_id} (model=${detector.modelConfigName || "<unset>"})`,
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const classifierStalled = classifierVerdict?.stalled ?? false;
|
|
277
|
+
const classifierReason = classifierVerdict?.reason ?? "";
|
|
278
|
+
|
|
279
|
+
// Effective stall verdict per the resolved mode:
|
|
280
|
+
// off → no stall detection (whatever the regex thought, ignore)
|
|
281
|
+
// regex → regex verdict
|
|
282
|
+
// model → classifier verdict if we got one, else regex fallback
|
|
283
|
+
let stalled = false;
|
|
284
|
+
if (detector.mode === "regex") {
|
|
285
|
+
stalled = regexStalled;
|
|
286
|
+
} else if (detector.mode === "model") {
|
|
287
|
+
stalled = classifierVerdict?.stalled ?? regexStalled;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Fabrication check (ADR-0037): only run when no other path claimed
|
|
291
|
+
// this turn. hasWriteEvidence must reflect a CONFIRMED write, not merely
|
|
292
|
+
// an attempted one — see succeededToolNames above.
|
|
293
|
+
const fabrication = !stalled && !looped
|
|
294
|
+
? validateAssistantOutput(textBuf, toolNames, allowedTools, succeededToolNames.filter(isWriteLikeToolName))
|
|
295
|
+
: ({ ok: true } as const);
|
|
296
|
+
|
|
297
|
+
// Strict-mode citation audit. Runs ONLY at `citation_strictness === 'strict'`
|
|
298
|
+
// when no earlier gate already claimed the turn — that's when we want to
|
|
299
|
+
// catch hallucinated/uncited high-impact claims and force a correction
|
|
300
|
+
// round. Standard / informational defer to the post-persist fire-and-
|
|
301
|
+
// forget checker (no nudge, just surfacing). The audit is synchronous so
|
|
302
|
+
// it adds one checker round-trip to strict turns; the cost is the price
|
|
303
|
+
// of the stronger guarantee.
|
|
304
|
+
let uncitedHighClaims: ReadonlyArray<{ text: string; reason: string; marker: number | null }> = [];
|
|
305
|
+
if (
|
|
306
|
+
!stalled && !looped && fabrication.ok
|
|
307
|
+
&& agentCfg
|
|
308
|
+
&& parseCitationStrictness(agentCfg.citation_strictness) === "strict"
|
|
309
|
+
&& retriesLeft > 0
|
|
310
|
+
&& textBuf.trim().length > 0
|
|
311
|
+
) {
|
|
312
|
+
const checkerModel = (agentCfg.anti_hallucination_model_config ?? "").trim();
|
|
313
|
+
if (checkerModel) {
|
|
314
|
+
// The audit grades against THIS turn's sources. We don't accumulate
|
|
315
|
+
// tool-result payloads in this scope (only names + signatures for
|
|
316
|
+
// loop detection), so the audit can only see what landed in the
|
|
317
|
+
// text — pass an empty events array and let `classifyCitations`
|
|
318
|
+
// judge purely on the markers/links in the prose. The post-persist
|
|
319
|
+
// checker (which runs against the persisted manifest) catches
|
|
320
|
+
// anything this scope misses.
|
|
321
|
+
const auditManifest = buildCombinedManifest([], originalReq.thread_id, {
|
|
322
|
+
tools: Math.max(0, getConfig().citationManifestMax - 10),
|
|
323
|
+
delegates: 10,
|
|
324
|
+
});
|
|
325
|
+
try {
|
|
326
|
+
const verdict = await classifyCitations(textBuf, auditManifest, checkerModel, originalReq.signal);
|
|
327
|
+
if (verdict) {
|
|
328
|
+
uncitedHighClaims = verdict.claims
|
|
329
|
+
.filter((c) => c.impact === "high" && !c.verified)
|
|
330
|
+
.map((c) => ({ text: c.text, reason: c.reason, marker: c.marker }));
|
|
331
|
+
}
|
|
332
|
+
} catch { /* audit failed — fall through, no retry */ }
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const citationFail = uncitedHighClaims.length > 0;
|
|
336
|
+
|
|
337
|
+
if (!stalled && !looped && fabrication.ok && !citationFail) {
|
|
338
|
+
if (workflowObservations.length > 0) {
|
|
339
|
+
yield* workflowStepRetryStream(workflowObservations, originalReq, retriesLeft, attemptAbort, doneChunk, textBuf, toolNames, toolResultSummaries, prepareRetry);
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (doneChunk) yield doneChunk;
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const writeLikeTools = [...new Set(toolOutcomes.possiblyChangedNames().filter(isWriteLikeToolName))];
|
|
347
|
+
if (writeLikeTools.length > 0) {
|
|
348
|
+
yield {
|
|
349
|
+
type: "text_delta",
|
|
350
|
+
data: {
|
|
351
|
+
delta:
|
|
352
|
+
`\n\n*⚠️ Retry guard skipped automatic retry because state-changing tools were attempted this turn: ${writeLikeTools.slice(0, 6).join(", ")}. Their effects may be incomplete or unverified. Review the result before continuing to avoid duplicate side effects.*`,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
if (doneChunk) yield doneChunk;
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
if (retriesLeft <= 0) {
|
|
360
|
+
yield {
|
|
361
|
+
type: "text_delta",
|
|
362
|
+
data: {
|
|
363
|
+
delta: "\n\n*⚠️ Automatic quality retry is disabled for this usage strategy. Review the result before continuing.*",
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
if (doneChunk) yield doneChunk;
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A stall/loop retry continues a legitimate partial answer, so the prior
|
|
371
|
+
// prose stays visible with a "↻" separator. A fabrication/citation retry
|
|
372
|
+
// (ADR-0037) is different: the COMPLETED reply itself is what's wrong, so
|
|
373
|
+
// the correct move is to discard it, not append a correction after it —
|
|
374
|
+
// otherwise the user (and the persisted message) ends up with both the
|
|
375
|
+
// flagged reply and its replacement (issue #576). `reset_text` tells the
|
|
376
|
+
// client buffer and the persistence collector to drop what they've
|
|
377
|
+
// accumulated for this turn; only the retry's own chunks land after it.
|
|
378
|
+
const isReplaceRetry = !stalled && !looped;
|
|
379
|
+
if (!isReplaceRetry) {
|
|
380
|
+
// Visible separator between the stalled prose and the retry
|
|
381
|
+
// continuation, so the user can see something is being re-attempted.
|
|
382
|
+
yield { type: "text_delta", data: { delta: "\n\n↻ " } };
|
|
383
|
+
} else {
|
|
384
|
+
yield { type: "status", data: { phase: "validating", label: "Checking answer..." } };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Inject a forceful nudge as a synthetic user message so the model sees
|
|
388
|
+
// its own flagged reply + an instruction to continue. Each failure mode
|
|
389
|
+
// gets its own reason-aware nudge.
|
|
390
|
+
let nudge: string;
|
|
391
|
+
if (looped) {
|
|
392
|
+
nudge = `↻ 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.`;
|
|
393
|
+
} else if (stalled && promisedWriteStall) {
|
|
394
|
+
nudge = `↻ 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.`;
|
|
395
|
+
} else if (stalled && zeroToolStall) {
|
|
396
|
+
nudge = "↻ 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.";
|
|
397
|
+
} else if (stalled && classifierStalled) {
|
|
398
|
+
nudge = `↻ 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.`;
|
|
399
|
+
} else if (citationFail) {
|
|
400
|
+
nudge = buildCitationRetryNudge(uncitedHighClaims);
|
|
401
|
+
} else {
|
|
402
|
+
nudge = buildFabricationNudge("reason" in fabrication ? fabrication.reason : "");
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const retryContext = buildRetryContextSummary(isReplaceRetry ? "" : textBuf, toolNames, toolResultSummaries);
|
|
406
|
+
const draftContext = isReplaceRetry ? `Original answer to revise (verify its action claims):\n${textBuf}` : "";
|
|
407
|
+
const nudgeWithContext = [nudge, draftContext, retryContext].filter(Boolean).join("\n\n");
|
|
408
|
+
|
|
409
|
+
// Cancel this attempt's own provider call before starting the retry — the
|
|
410
|
+
// consumer loop above already stopped reading (via `break` on tool-loop
|
|
411
|
+
// detection, or naturally via `doneChunk`), but that alone never aborted
|
|
412
|
+
// the underlying HTTP request. Without this, an abandoned attempt can keep
|
|
413
|
+
// running a tool call in the background while the retry starts a second,
|
|
414
|
+
// unrelated one.
|
|
415
|
+
if (originalReq.signal?.aborted) {
|
|
416
|
+
yield { type: "error", data: { code: "aborted", message: "Run stopped before automatic correction." } };
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
attemptAbort.abort("stall_retry");
|
|
420
|
+
|
|
421
|
+
const retry = await prepareRetry({
|
|
422
|
+
...originalReq,
|
|
423
|
+
message: nudgeWithContext,
|
|
424
|
+
attachments: undefined,
|
|
425
|
+
_stall_retries_left: retriesLeft - 1,
|
|
426
|
+
_retry_count: (originalReq._retry_count ?? 0) + 1,
|
|
427
|
+
// The nudge is in-memory only — never write it to `messages`. What ends
|
|
428
|
+
// up persisted at end-of-turn via `persistAssistantMessage` is: for a
|
|
429
|
+
// stall/loop retry, the flagged prose + "↻" + the retry (a genuine
|
|
430
|
+
// continuation); a successful fabrication/citation retry atomically
|
|
431
|
+
// replaces the draft with the complete corrected answer.
|
|
432
|
+
// Without these flags the nudge becomes a permanent user-role row the
|
|
433
|
+
// LLM mistakes for user input on every future turn.
|
|
434
|
+
_skip_persist_message: true,
|
|
435
|
+
_history_append_message: nudgeWithContext,
|
|
436
|
+
});
|
|
437
|
+
if (!isReplaceRetry) {
|
|
438
|
+
yield* retry.stream;
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
let retryTextBuf = "";
|
|
442
|
+
for await (const chunk of retry.stream) {
|
|
443
|
+
if (chunk.type === "text_delta") {
|
|
444
|
+
const d = (chunk.data as { delta?: unknown } | undefined)?.delta;
|
|
445
|
+
if (typeof d === "string") retryTextBuf += d;
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (chunk.type === "reset_text") {
|
|
449
|
+
retryTextBuf = "";
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (chunk.type === "done" && !chunk.data.aborted && !originalReq.signal?.aborted) {
|
|
453
|
+
if (!retryTextBuf.trim()) {
|
|
454
|
+
yield { type: "error", data: { code: "correction_failed", message: "Automatic correction returned no answer. The original draft is unchanged and may contain unverified claims." } };
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
yield { type: "reset_text", data: {} };
|
|
458
|
+
yield { type: "text_delta", data: { delta: retryTextBuf } };
|
|
459
|
+
}
|
|
460
|
+
yield chunk;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
// Workflow step contract auto-retry. Runs only after every other quality
|
|
466
|
+
// gate passed, and has its own per-step budget (WORKFLOW_STEP_MAX_ATTEMPTS)
|
|
467
|
+
// so a stall retry earlier in the turn never starves it. The retry is an
|
|
468
|
+
// append-mode continuation: the turn's work stays visible, followed by the
|
|
469
|
+
// model redoing only the failed steps.
|
|
470
|
+
export async function* workflowStepRetryStream(
|
|
471
|
+
observations: readonly WorkflowProgressObservation[],
|
|
472
|
+
originalReq: ThreadRunRequest,
|
|
473
|
+
stallRetriesLeft: number,
|
|
474
|
+
attemptAbort: AbortController,
|
|
475
|
+
doneChunk: StreamChunk | null,
|
|
476
|
+
textBuf: string,
|
|
477
|
+
toolNames: readonly string[],
|
|
478
|
+
toolResultSummaries: readonly string[],
|
|
479
|
+
prepareRetry: PrepareRetry,
|
|
480
|
+
): AsyncGenerator<StreamChunk> {
|
|
481
|
+
const spent = originalReq._workflow_step_retries ?? {};
|
|
482
|
+
const failures = collectWorkflowContractFailures(observations);
|
|
483
|
+
const { retry, exhausted } = planWorkflowStepRetries(failures, spent);
|
|
484
|
+
const spentTotal = Object.values(spent).reduce((sum, n) => sum + n, 0);
|
|
485
|
+
|
|
486
|
+
if (retry.length === 0 || spentTotal >= WORKFLOW_TURN_AUTO_RETRY_LIMIT) {
|
|
487
|
+
const unresolved = [...exhausted, ...retry];
|
|
488
|
+
if (unresolved.length > 0) {
|
|
489
|
+
console.warn(
|
|
490
|
+
`[workflow-retry] contract still failing after auto-retry: ${unresolved.map((f) => f.key).join(", ")} thread=${originalReq.thread_id}`,
|
|
491
|
+
);
|
|
492
|
+
yield {
|
|
493
|
+
type: "text_delta",
|
|
494
|
+
data: {
|
|
495
|
+
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.*`,
|
|
496
|
+
},
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
if (doneChunk) yield doneChunk;
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
console.warn(
|
|
504
|
+
`[workflow-retry] retrying ${retry.map((f) => `${f.key}#${f.attempt}`).join(", ")} thread=${originalReq.thread_id}`,
|
|
505
|
+
);
|
|
506
|
+
yield { type: "text_delta", data: { delta: "\n\n↻ " } };
|
|
507
|
+
const nudge = buildWorkflowStepRetryNudge(retry);
|
|
508
|
+
const retryContext = buildRetryContextSummary(textBuf, [...toolNames], [...toolResultSummaries]);
|
|
509
|
+
const nudgeWithContext = retryContext ? `${nudge}\n\n${retryContext}` : nudge;
|
|
510
|
+
const nextSpent: Record<string, number> = { ...spent };
|
|
511
|
+
for (const failure of retry) nextSpent[failure.key] = (nextSpent[failure.key] ?? 0) + 1;
|
|
512
|
+
|
|
513
|
+
if (originalReq.signal?.aborted) {
|
|
514
|
+
yield { type: "error", data: { code: "aborted", message: "Run stopped before workflow retry." } };
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
attemptAbort.abort("workflow_step_retry");
|
|
518
|
+
const next = await prepareRetry({
|
|
519
|
+
...originalReq,
|
|
520
|
+
message: nudgeWithContext,
|
|
521
|
+
attachments: undefined,
|
|
522
|
+
_stall_retries_left: stallRetriesLeft,
|
|
523
|
+
_workflow_step_retries: nextSpent,
|
|
524
|
+
_retry_count: (originalReq._retry_count ?? 0) + 1,
|
|
525
|
+
_skip_persist_message: true,
|
|
526
|
+
_history_append_message: nudgeWithContext,
|
|
527
|
+
});
|
|
528
|
+
for await (const chunk of next.stream) yield chunk;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
const TOOL_LOOP_THRESHOLD = 3;
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
// A "write-like" tool, by name, is one whose path segments contain a CRUD
|
|
536
|
+
// verb. Per-segment match so e.g. `dataset_search` doesn't qualify on
|
|
537
|
+
// `set`. Used to flag the "called read-only tools then promised a write"
|
|
538
|
+
// stall pattern.
|
|
539
|
+
export function isWriteLikeToolName(name: string): boolean {
|
|
540
|
+
if (!name) return false;
|
|
541
|
+
// Built-ins declare their safety class at registration (ADR-0038), so trust
|
|
542
|
+
// that over re-deriving it from the name — `propose_config_change` queues a
|
|
543
|
+
// pending action but has no CRUD verb in it. MCP/external tools aren't in
|
|
544
|
+
// the registry and still fall back to the verb scan.
|
|
545
|
+
const capability = registeredCapability(name);
|
|
546
|
+
if (capability) return capability !== "read";
|
|
547
|
+
const segments = name.toLowerCase().split(/[._\-/]+/).filter(Boolean);
|
|
548
|
+
return segments.some(isWriteToolNameSegment);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
// Stable signature of a tool call so repeated identical calls collapse to
|
|
553
|
+
// the same key. JSON.stringify with sorted keys is good enough — the
|
|
554
|
+
// argument shapes that matter here are small JSON objects, not graphs.
|
|
555
|
+
export function toolCallSignature(name: string, args: Record<string, unknown>): string {
|
|
556
|
+
try {
|
|
557
|
+
const sortedKeys = Object.keys(args).sort();
|
|
558
|
+
const stable: Record<string, unknown> = {};
|
|
559
|
+
for (const k of sortedKeys) stable[k] = args[k];
|
|
560
|
+
return `${name}::${JSON.stringify(stable)}`;
|
|
561
|
+
} catch {
|
|
562
|
+
return `${name}::<unserializable>`;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
function summarizeRetryValue(value: unknown): string {
|
|
568
|
+
if (typeof value === "string") return value.trim();
|
|
569
|
+
if (typeof value === "number" || typeof value === "boolean" || value === null) return String(value);
|
|
570
|
+
try {
|
|
571
|
+
return JSON.stringify(value);
|
|
572
|
+
} catch {
|
|
573
|
+
return Object.prototype.toString.call(value);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
// A short clip reads to the model as "a snippet of what I said" rather than
|
|
579
|
+
// "the whole thing I said" — which pushed it to re-emit the full prior reply
|
|
580
|
+
// on retry instead of trusting that the recap already covers it (issue
|
|
581
|
+
// #577). 2000 chars covers the overwhelming majority of turns in full while
|
|
582
|
+
// still bounding the nudge's own token cost.
|
|
583
|
+
const RETRY_CONTEXT_CLIP_CHARS = 2000;
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
export function buildRetryContextSummary(
|
|
587
|
+
text: string,
|
|
588
|
+
toolNames: readonly string[],
|
|
589
|
+
toolResults: readonly string[] = [],
|
|
590
|
+
): string {
|
|
591
|
+
const parts: string[] = [];
|
|
592
|
+
const trimmedText = text.trim();
|
|
593
|
+
if (trimmedText) {
|
|
594
|
+
const clipped = trimmedText.length > RETRY_CONTEXT_CLIP_CHARS
|
|
595
|
+
? `${trimmedText.slice(0, RETRY_CONTEXT_CLIP_CHARS - 3)}...`
|
|
596
|
+
: trimmedText;
|
|
597
|
+
parts.push(`Already said this turn: ${clipped}`);
|
|
598
|
+
}
|
|
599
|
+
const uniqueTools = [...new Set(toolNames.filter(Boolean))];
|
|
600
|
+
if (uniqueTools.length > 0) {
|
|
601
|
+
parts.push(`Tools already used this turn: ${uniqueTools.slice(0, 8).join(", ")}`);
|
|
602
|
+
}
|
|
603
|
+
if (toolResults.length > 0) {
|
|
604
|
+
parts.push(`Tool results already seen this turn:\n${toolResults.slice(0, 5).map((line, index) => ` ${index + 1}. ${line}`).join("\n")}`);
|
|
605
|
+
}
|
|
606
|
+
return parts.join("\n");
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
// Word-multiset containment: what fraction of `retry`'s tokens also appear
|
|
611
|
+
// in `original`. Order-insensitive and duplicate-aware (each token in
|
|
612
|
+
// `original` can only satisfy one token in `retry`), so a retry that mostly
|
|
613
|
+
// repeats the flagged reply verbatim — the failure mode issue #577
|
|
614
|
+
// describes — scores high regardless of minor rewording. Used only for
|
|
615
|
+
// telemetry: it flags regurgitation, it doesn't gate or alter rendering.
|
|
616
|
+
export function retryTextOverlapRatio(original: string, retry: string): number {
|
|
617
|
+
const tokenize = (s: string) => s.toLowerCase().match(/[a-z0-9']+/g) ?? [];
|
|
618
|
+
const retryTokens = tokenize(retry);
|
|
619
|
+
if (retryTokens.length === 0) return 0;
|
|
620
|
+
const originalCounts = new Map<string, number>();
|
|
621
|
+
for (const t of tokenize(original)) originalCounts.set(t, (originalCounts.get(t) ?? 0) + 1);
|
|
622
|
+
let shared = 0;
|
|
623
|
+
for (const t of retryTokens) {
|
|
624
|
+
const remaining = originalCounts.get(t) ?? 0;
|
|
625
|
+
if (remaining > 0) {
|
|
626
|
+
shared += 1;
|
|
627
|
+
originalCounts.set(t, remaining - 1);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
return shared / retryTokens.length;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
const STALL_PHRASE_GROUP = STALL_TAIL_PHRASES.join("|").replace(/ /g, "\\s+");
|
|
635
|
+
|
|
636
|
+
const STALL_NOW_VERB_GROUP = STALL_NOW_ACTION_VERBS.join("|");
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
const STALL_PATTERNS: RegExp[] = [
|
|
640
|
+
new RegExp(`\\b(?:${STALL_PHRASE_GROUP})\\b`, "i"),
|
|
641
|
+
/\bgive me (a|just a) (moment|sec(?:ond)?|minute)\b/i,
|
|
642
|
+
/\blet me (try|do (?:that|this|it))\b/i,
|
|
643
|
+
/\bi['’]?ll (check|verify|continue|proceed|look|try|do (?:that|this|it)|keep going|get (?:on|right) (?:on|to))/i,
|
|
644
|
+
/\b(continuing|proceeding|working on it|moving on)\b.*[!.]?\s*$/i,
|
|
645
|
+
// Aspirational future-action family: "Writing X now", "Saving the file
|
|
646
|
+
// now", "Creating the report now". Catches the read-only-tools +
|
|
647
|
+
// narrate-the-write + end-of-turn loop where the model promises a
|
|
648
|
+
// write but never invokes the corresponding tool.
|
|
649
|
+
new RegExp(`\\b(?:${STALL_NOW_VERB_GROUP})\\b[^.!?]*\\bnow\\b[!.]?\\s*$`, "i"),
|
|
650
|
+
// Broader promise-shape: any "I'll <verb>" or "I will <verb>" followed
|
|
651
|
+
// by "now" anywhere in the trailing clause. Catches "I will read it
|
|
652
|
+
// now to understand the plan" / "I'll add the note now" — variants the
|
|
653
|
+
// narrow aspirational-verb list above misses because the verb is in
|
|
654
|
+
// bare infinitive form and `now` is mid-sentence rather than at the
|
|
655
|
+
// end.
|
|
656
|
+
/\b(?:i['’]?ll|i\s+will)\s+\w+\b[^.!?]*\bnow\b/i,
|
|
657
|
+
// Present-continuous version: "I'm reading … now to figure out …" /
|
|
658
|
+
// "I am updating the dashboard now to reflect …". Same idea, but the
|
|
659
|
+
// model is narrating in progress rather than promising in future.
|
|
660
|
+
// Same failure mode in practice — followed by no actual write call.
|
|
661
|
+
/\b(?:i['’]?m|i\s+am)\s+\w+ing\b[^.!?]*\bnow\b/i,
|
|
662
|
+
];
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
export function looksLikeStall(text: string): boolean {
|
|
666
|
+
// Inspect the last paragraph / sentence — earlier acknowledgment
|
|
667
|
+
// language is fine when followed by real work. The stall signal is when
|
|
668
|
+
// the message ends on a promise.
|
|
669
|
+
const tail = text.split(/\n{2,}|(?<=[.!?])\s+/).filter(Boolean).slice(-2).join(" ");
|
|
670
|
+
return STALL_PATTERNS.some((re) => re.test(tail));
|
|
671
|
+
}
|