@@ -3,20 +3,32 @@ import type {
33 OcxAssistantContentPart ,
44 OcxAssistantMessage ,
55 OcxParsedRequest ,
6+ OcxToolChoice ,
67 OcxUsage ,
78} from "../../types" ;
9+ import { isAllowedToolChoice } from "../../types" ;
810
11+ // User-intent gates. These classify what the USER asked for, not whether the model executed —
12+ // keep them. `ACTIONABLE_REQUEST_RE` decides whether the turn is an execution request at all;
13+ // `PLAN_ONLY_REQUEST_RE` honors an explicit "just give me a plan / don't call tools" request.
914const ACTIONABLE_REQUEST_RE = / (?: \b (?: a d d | c h a n g e | c h e c k | c o n t i n u e | c r e a t e | d e b u g | d e l e t e | d e p l o y | e d i t | e x e c u t e | f i x | i m p l e m e n t | i n s p e c t | k e e p g o i n g | m o d i f y | p a t c h | p r o c e e d | r e f a c t o r | r e m o v e | r e v i e w | r u n | t e s t | u p d a t e | w r i t e ) \b | 继 续 | 接 着 | 往 下 | 升 级 | 修 改 | 改 (?: 一 下 | 下 ) ? | 修 复 | 实 现 | 添 加 | 新 增 | 删 除 | 重 构 | 更 新 | 运 行 | 执 行 | 检 查 | 查 看 | 排 查 | 调 试 | 创 建 | 写 入 | 提 交 | 推 送 | 部 署 | 看 下 | 改 成 | 修 一 下 ) / iu;
1015const PLAN_ONLY_REQUEST_RE = / (?: 只 (?: 给 | 要 | 需 ) (?: 我 ) ? (?: 一 个 | 个 | 一 下 ) ? (?: 计 划 | 方 案 ) | 先 (?: 给 | 说 ) (?: 我 ) ? (?: 一 个 | 个 | 一 下 ) ? (?: 计 划 | 方 案 ) | 暂 时 不 要 (?: 调 用 | 使 用 ) 工 具 | 不 要 调 用 工 具 | 不 用 执 行 | 只 回 复 (?: 计 划 | 方 案 ) | \b (?: j u s t g i v e | p r o v i d e ) \s + (?: m e \s + ) ? (?: a \s + ) ? p l a n \b | \b (?: d o n o t | d o n ' t ) \s + (?: u s e | c a l l ) \s + t o o l s ? \b ) / iu;
11- const PLAN_INTENT_RE = / (?: \b (?: i (?: ' | ’ ) m g o i n g t o | i w i l l | i (?: ' | ’ ) l l | l e t m e | n e x t i ) \b | 我 (?: 先 | 会 | 将 | 接 下 来 ) | 让 我 (?: 用 | 先 | 再 | 去 | 来 ) | 我 得 (?: 用 | 先 | 再 | 去 | 查 | 读 | 连 接 ) | 我 (?: 需 要 | 打 算 | 准 备 ) (?: 用 | 先 | 再 | 去 | 查 | 读 | 连 接 ) | 下 一 步 ) / iu ;
12- const PLAN_OR_COMPLETION_RE = / (?: \b (?: i (?: ' | ’ ) m g o i n g t o | i w i l l | i (?: ' | ’ ) l l | l e t m e | n e x t i | i (?: ' | ’ ) v e (?: a l r e a d y ) ? (?: a d d e d | a p p l i e d | c h a n g e d | c o m p l e t e d | f i x e d | i m p l e m e n t e d | m o d i f i e d | u p d a t e d ) ) \b | \b (?: d o n e | c o m p l e t e d | f i x e d | i m p l e m e n t e d | u p d a t e d | a p p l i e d ) \b | 我 (?: 先 | 会 | 将 | 接 下 来 ) | 让 我 (?: 用 | 先 | 再 | 去 | 来 ) | 我 得 (?: 用 | 先 | 再 | 去 | 查 | 读 | 连 接 ) | 我 (?: 需 要 | 打 算 | 准 备 ) (?: 用 | 先 | 再 | 去 | 查 | 读 | 连 接 ) | 下 一 步 | 已 (?: 经 ) ? (?: 修 改 | 修 复 | 完 成 | 应 用 | 更 新 | 实 现 | 处 理 ) | 完 成 了 | 已 经 好 了 ) / iu ;
16+ // Waiting-for-user is a SAFE PASS heuristic (not a reliable classifier): if the model appears to
17+ // be asking the user something, never auto-continue.
1318const WAITING_FOR_USER_RE = / (?: [ ? ? ] \s * $ | 需 要 我 | 请 (?: 确 认 | 选 择 | 提 供 ) | 是 否 | 要 不 要 | 可 以 吗 | \b (?: d o y o u w a n t | s h o u l d i | w h i c h f i l e | p l e a s e c o n f i r m | p l e a s e p r o v i d e ) \b ) / iu;
1419const EXPLICIT_CONTINUE_RE = / ^ (?: 继 续 | 接 着 | 往 下 | g o o n | c o n t i n u e | p r o c e e d | k e e p g o i n g ) \s * [ . ! 。 ! ] ? $ / iu;
15- const MAX_ANNOUNCEMENT_CHARS = 280 ;
1620
21+ // Length is a precision/recall knob, NOT proof of a substantive answer. A short correct final
22+ // answer ("已修复 README") can fall under it; a long plan can exceed it. We use a conservative
23+ // base and widen it only when the current task segment already shows real tool activity.
24+ const MAX_AUTO_CONTINUATION_TEXT_CHARS = 200 ;
25+ const MAX_AUTO_CONTINUATION_TEXT_CHARS_WITH_ACTIVITY = 280 ;
26+
27+ // Neutral nudge: on misfire the model may actually have produced a correct short final answer, so
28+ // do NOT assert "you only described a plan". Ask for execution OR an explicit blocker/no-op reason.
1729export const TERMINAL_GUARD_NUDGE =
18- "你刚才只描述了计划,没有执行任何工具。不要再次解释计划,现在立即调用必要工具执行用户任务。 " +
19- "只有工具返回后才总结;如果确实无法执行,请明确说明阻塞原因 。" ;
30+ "本回合没有调用任何工具。如果用户任务需要执行,请立即调用必要工具; " +
31+ "如果无需执行或确实无法执行,请明确说明无需执行的原因或具体阻塞点。不要只重复计划 。" ;
2032
2133export type TerminalGuardDecision = "pass" | "continue" | "ambiguous" ;
2234
@@ -46,6 +58,11 @@ function latestUserText(parsed: OcxParsedRequest): string {
4658 return "" ;
4759}
4860
61+ // Structural "task is in-progress" signal, scoped to the CURRENT task segment only: scan back from
62+ // the latest user message to the previous user message. Tool activity in an OLDER, unrelated
63+ // segment must not count as the current task still executing (avoids cross-task bleed). This is a
64+ // confidence/threshold enhancer, NEVER a hard gate — a first-turn actionable request has no prior
65+ // activity yet must still be eligible to auto-continue.
4966function recentTurnHasToolActivity ( parsed : OcxParsedRequest ) : boolean {
5067 let latestUserIndex = - 1 ;
5168 for ( let i = parsed . context . messages . length - 1 ; i >= 0 ; i -= 1 ) {
@@ -55,26 +72,49 @@ function recentTurnHasToolActivity(parsed: OcxParsedRequest): boolean {
5572 }
5673 }
5774 if ( latestUserIndex < 0 ) return false ;
58- let lastAssistant : OcxAssistantMessage | undefined ;
59- for ( let i = latestUserIndex - 1 ; i >= 0 ; i -= 1 ) {
75+ for ( let i = latestUserIndex - 1 ; i >= 0 && parsed . context . messages [ i ] ?. role !== "user" ; i -= 1 ) {
6076 const message = parsed . context . messages [ i ] ;
61- if ( message . role === "assistant" ) {
62- lastAssistant = message ;
77+ // An orphan toolResult (no matching assistant toolCall) still evidences execution in this
78+ // segment, so count it — but only within the current segment because of the loop bound.
79+ if ( message . role === "toolResult" ) return true ;
80+ if ( message . role === "assistant" && message . content . some ( part => part . type === "toolCall" ) ) return true ;
81+ }
82+ return false ;
83+ }
84+
85+ // STRUCTURAL high-confidence signal: the request forced a tool call (toolChoice `required`, a
86+ // specific `{ name }`, or `{ mode: "required" }`) but the turn produced none. That is a protocol
87+ // mismatch, independent of any language, so it can trigger a continuation on its own.
88+ function toolChoiceRequiresTool ( choice : OcxToolChoice | undefined ) : boolean {
89+ if ( choice === "required" ) return true ;
90+ if ( typeof choice === "object" && choice !== null ) {
91+ if ( isAllowedToolChoice ( choice ) ) return choice . mode === "required" ;
92+ if ( "name" in choice ) return true ;
93+ }
94+ return false ;
95+ }
96+
97+ // STRUCTURAL signal that the model itself labeled this output a final answer (Responses phase).
98+ // When present it is authoritative — never auto-continue over a declared final answer.
99+ function turnIsFinalAnswer ( events : readonly AdapterEvent [ ] ) : boolean {
100+ return events . some ( event => event . type === "text_delta" && event . phase === "final_answer" ) ;
101+ }
102+
103+ // The Anthropic adapter normally does not attach a phase to fresh output events. When a client
104+ // explicitly says "continue", a persisted prior assistant phase is therefore the only structural
105+ // evidence that the preceding task was already handed back as a final answer.
106+ function priorAssistantIsFinalAnswer ( parsed : OcxParsedRequest ) : boolean {
107+ let latestUserIndex = - 1 ;
108+ for ( let i = parsed . context . messages . length - 1 ; i >= 0 ; i -= 1 ) {
109+ if ( parsed . context . messages [ i ] ?. role === "user" ) {
110+ latestUserIndex = i ;
63111 break ;
64112 }
65113 }
66- if ( lastAssistant ?. role === "assistant" ) {
67- const hasToolCall = lastAssistant . content . some ( part => part . type === "toolCall" ) ;
68- const text = lastAssistant . content
69- . filter ( part => part . type === "text" )
70- . map ( part => part . text )
71- . join ( "" ) ;
72- if ( ! hasToolCall && PLAN_INTENT_RE . test ( text ) ) return false ;
73- }
74- for ( let i = latestUserIndex - 1 ; i >= 0 && parsed . context . messages [ i ] ?. role !== "user" ; i -= 1 ) {
114+ if ( latestUserIndex < 0 ) return false ;
115+ for ( let i = latestUserIndex - 1 ; i >= 0 ; i -= 1 ) {
75116 const message = parsed . context . messages [ i ] ;
76- if ( message . role === "toolResult" ) return true ;
77- if ( message . role === "assistant" && message . content . some ( part => part . type === "toolCall" ) ) return true ;
117+ if ( message . role === "assistant" ) return message . phase === "final_answer" ;
78118 }
79119 return false ;
80120}
@@ -86,35 +126,72 @@ function assistantText(events: readonly AdapterEvent[]): string {
86126 . join ( "" ) ;
87127}
88128
129+ // Structure-first terminal analysis. We deliberately do NOT parse the assistant's wording to guess
130+ // whether it "only described a plan" — that heuristic was language-fragile and mixed up "about to do" with
131+ // "already done". Instead we combine reliable structural facts (tool calls this turn, tool
132+ // availability, toolChoice, final-answer phase, current-segment activity) with two USER-INTENT
133+ // gates and one length knob. This lowers the frequency of premature `end_turn` stops; it cannot
134+ // guarantee elimination because the stop decision ultimately lives in the model.
89135export function analyzeTerminalTurn ( parsed : OcxParsedRequest , events : readonly AdapterEvent [ ] ) : TerminalTurnAnalysis {
90136 const userText = latestUserText ( parsed ) ;
91137 const text = assistantText ( events ) ;
138+ const trimmedLength = text . trim ( ) . length ;
92139 const hasToolCall = events . some ( event => event . type === "tool_call_start" ) ;
140+ const explicitContinue = EXPLICIT_CONTINUE_RE . test ( userText ) ;
141+ const base = { assistantText : text , userText, hasToolCall } as const ;
142+
143+ // A real tool call happened this turn → this is a normal in-progress terminal.
93144 if ( hasToolCall ) {
94- return { decision : "pass" , reason : "normal" , assistantText : text , userText , hasToolCall } ;
145+ return { decision : "pass" , reason : "normal" , ... base } ;
95146 }
96- if ( ! parsed . context . tools || parsed . context . tools . length === 0 || parsed . options . toolChoice === "none" ) {
97- return { decision : "pass" , reason : "no_tools" , assistantText : text , userText, hasToolCall } ;
147+
148+ // Nothing to continue toward when tools are unavailable or explicitly disabled.
149+ const toolChoice = parsed . options . toolChoice ;
150+ const hasTools = ! ! parsed . context . tools && parsed . context . tools . length > 0 ;
151+ if ( ! hasTools || toolChoice === "none" ) {
152+ return { decision : "pass" , reason : "no_tools" , ...base } ;
98153 }
99- if ( ! ACTIONABLE_REQUEST_RE . test ( userText ) ) {
100- return { decision : "pass" , reason : "no_actionable_request" , assistantText : text , userText, hasToolCall } ;
154+
155+ // The model itself declared a final answer → authoritative, never auto-continue.
156+ if ( turnIsFinalAnswer ( events ) || ( explicitContinue && priorAssistantIsFinalAnswer ( parsed ) ) ) {
157+ return { decision : "pass" , reason : "substantive_answer" , ...base } ;
101158 }
102- if ( PLAN_ONLY_REQUEST_RE . test ( userText ) ) {
103- return { decision : "pass" , reason : "no_actionable_request" , assistantText : text , userText, hasToolCall } ;
159+
160+ // Appears to be asking the user something → safe pass (heuristic, not a classifier).
161+ if ( WAITING_FOR_USER_RE . test ( text ) ) {
162+ return { decision : "pass" , reason : "waiting_for_user" , ...base } ;
104163 }
105- if ( EXPLICIT_CONTINUE_RE . test ( userText ) && recentTurnHasToolActivity ( parsed ) ) {
106- return { decision : "pass" , reason : "recent_tool_activity" , assistantText : text , userText, hasToolCall } ;
164+
165+ // The user's explicit plan-only/no-tools instruction takes precedence over a conflicting tool
166+ // choice in the request body — do not manufacture execution the user explicitly declined.
167+ if ( PLAN_ONLY_REQUEST_RE . test ( userText ) ) {
168+ return { decision : "pass" , reason : "no_actionable_request" , ...base } ;
107169 }
108- if ( WAITING_FOR_USER_RE . test ( text ) ) {
109- return { decision : "pass" , reason : "waiting_for_user" , assistantText : text , userText, hasToolCall } ;
170+
171+ // High-confidence structural trigger: a forced tool call produced no tool. Language-independent.
172+ if ( toolChoiceRequiresTool ( toolChoice ) ) {
173+ return { decision : "continue" , reason : "suspicious_no_tool" , ...base } ;
110174 }
111- if ( text . trim ( ) . length > MAX_ANNOUNCEMENT_CHARS ) {
112- return { decision : "pass" , reason : "substantive_answer" , assistantText : text , userText, hasToolCall } ;
175+
176+ // For ordinary `auto` tool selection we require a user-intent signal that this turn was an
177+ // execution request at all (otherwise every tool-enabled Q&A would be eligible), and honor an
178+ // explicit "just give me a plan / don't call tools" request.
179+ if ( ! ACTIONABLE_REQUEST_RE . test ( userText ) ) {
180+ return { decision : "pass" , reason : "no_actionable_request" , ...base } ;
113181 }
114- if ( ! PLAN_OR_COMPLETION_RE . test ( text ) ) {
115- return { decision : "ambiguous" , reason : "no_execution_claim" , assistantText : text , userText, hasToolCall } ;
182+
183+ // Length is a precision/recall knob, not proof. Widen it only when the current task segment
184+ // already shows real tool activity (higher prior that a longer message is still mid-task).
185+ const lengthCap = recentTurnHasToolActivity ( parsed )
186+ ? MAX_AUTO_CONTINUATION_TEXT_CHARS_WITH_ACTIVITY
187+ : MAX_AUTO_CONTINUATION_TEXT_CHARS ;
188+ if ( trimmedLength > lengthCap ) {
189+ return { decision : "pass" , reason : "substantive_answer" , ...base } ;
116190 }
117- return { decision : "continue" , reason : "suspicious_no_tool" , assistantText : text , userText, hasToolCall } ;
191+
192+ // Actionable request, tools available, not forced, not waiting on the user, no declared final
193+ // answer, and a short output: a suspicious early stop → auto-continue once (bounded upstream).
194+ return { decision : "continue" , reason : "suspicious_no_tool" , ...base } ;
118195}
119196
120197function assistantMessageFromEvents ( events : readonly AdapterEvent [ ] ) : OcxAssistantMessage | undefined {
@@ -198,7 +275,11 @@ export async function* guardTerminalEventStream(options: GuardedEventStreamOptio
198275 const analysis = options . adapterName === "anthropic"
199276 ? analyzeTerminalTurn ( parsed , seen )
200277 : { decision : "pass" as const } ;
201- const normalStop = event . stopReason !== "max_tokens" && event . stopReason !== "content_filter" ;
278+ // Only a normal `end_turn` is eligible for auto-continuation. Other terminal reasons
279+ // (`max_tokens`, `content_filter`, `stop_sequence`, and even an explicit `tool_use` stop)
280+ // must never be re-asked. `undefined` is tolerated because several adapters omit the field
281+ // on a clean stop and the tests exercise that shape.
282+ const normalStop = event . stopReason === undefined || event . stopReason === "end_turn" ;
202283 if ( normalStop && analysis . decision === "continue" && continuations < maxContinuations ) {
203284 accumulatedUsage = mergeUsage ( accumulatedUsage , event . usage ) ;
204285 continuations += 1 ;
0 commit comments