From 55416a545e8ffecc1e2fd8b49401d84c004ca9bf Mon Sep 17 00:00:00 2001 From: d-robotics Date: Thu, 3 Dec 2026 14:57:43 +0800 Subject: [PATCH 1/3] fix(core): bound task decision repair and report validator feedback --- .../ai/src/llm/llm-provider-stream-adapter.ts | 13 + packages/ai/src/llm/llm-provider.ts | 6 + packages/ai/src/provider/connection-error.ts | 5 +- .../ai/src/provider/multi-provider-router.ts | 5 + packages/ai/src/provider/pi-ai-adapter.ts | 34 ++- .../ai/src/provider/pi-ai-http-transport.ts | 37 ++- packages/core/src/agent/moss-agent.ts | 31 +- packages/core/src/loop/agent-loop-llm-call.ts | 4 +- packages/core/src/loop/agent-loop-response.ts | 37 ++- packages/core/src/loop/agent-loop-types.ts | 1 + packages/core/src/loop/agent-loop.ts | 280 +++++++++++------- .../src/session/task-decision-rejection.ts | 40 +++ .../core/src/session/task-decision-repair.ts | 116 ++++++++ .../src/session/task-intent-coordinator.ts | 28 +- .../core/src/session/task-intent-state.ts | 31 +- packages/core/src/session/task-intent-turn.ts | 133 +++++++-- .../core/src/session/versioned-context.ts | 4 +- packages/core/src/task/task-engine.ts | 2 +- .../verify/task-intent-decision-repair.mjs | 204 ++++++++++++- scripts/verify/task-intent-revisions.mjs | 19 +- .../task-intent-tool-choice-fallback.mjs | 15 +- 21 files changed, 834 insertions(+), 211 deletions(-) create mode 100644 packages/core/src/session/task-decision-rejection.ts create mode 100644 packages/core/src/session/task-decision-repair.ts diff --git a/packages/ai/src/llm/llm-provider-stream-adapter.ts b/packages/ai/src/llm/llm-provider-stream-adapter.ts index 888d55d4..3437c2ef 100644 --- a/packages/ai/src/llm/llm-provider-stream-adapter.ts +++ b/packages/ai/src/llm/llm-provider-stream-adapter.ts @@ -337,6 +337,7 @@ function flushForwardState(stream: AssistantMessageEventStream, state: ForwardSt export interface LlmProviderStreamAdapterOptions { provider: LLMProvider; + decisionRepair?: () => LLMRequestOptions['decisionRepair']; getToolChoice?: (tools: LLMRequestOptions['tools']) => LLMRequestOptions['toolChoice']; preferStructuredOutput?: () => boolean; onProviderEvent?: (event: LLMStreamEvent) => void; @@ -386,6 +387,7 @@ export function createStreamFunctionFromLlmProvider( const piContext = context as PiContext; const tools = mapPiToolsToLlm(piContext.tools); const toolChoice = options.getToolChoice?.(tools); + const repair = options.decisionRepair?.(); const envelopeTool = toolChoice && options.preferStructuredOutput?.() && @@ -410,6 +412,7 @@ export function createStreamFunctionFromLlmProvider( tools, ...(toolChoice ? { toolChoice } : {}), ...(responseFormat ? { responseFormat } : {}), + ...(repair ? { decisionRepair: repair } : {}), maxTokens: streamOptions?.maxTokens, temperature: streamOptions?.temperature, abortSignal: streamOptions?.signal, @@ -417,14 +420,24 @@ export function createStreamFunctionFromLlmProvider( ...(options.extraBody ? { extraBody: options.extraBody } : {}), }; await options.onRequest?.(request); + if (repair) { + request.abortSignal?.throwIfAborted(); + repair.check(); + if (!options.provider.tracksDecisionRepairDispatch) repair.dispatch(false); + } const supportsStreaming = !responseFormat && options.provider.capabilities?.streaming !== false; const providerResponse = supportsStreaming ? await options.provider.stream(request, (event) => { + if (repair && request.abortSignal?.aborted) return; options.onProviderEvent?.(event); forwardProviderEvent(stream, event, forwardState); }) : await options.provider.complete(request); + if (repair) { + request.abortSignal?.throwIfAborted(); + repair.check(); + } const response = envelopeTool ? unwrapToolEnvelope(providerResponse, envelopeTool.name) : providerResponse; diff --git a/packages/ai/src/llm/llm-provider.ts b/packages/ai/src/llm/llm-provider.ts index 6ee672b7..03f9af03 100644 --- a/packages/ai/src/llm/llm-provider.ts +++ b/packages/ai/src/llm/llm-provider.ts @@ -47,6 +47,11 @@ export interface LLMRequestOptions { tools?: LLMToolDeclaration[]; /** Request a tool call on this turn when the provider supports it. */ toolChoice?: 'required'; + /** Internal bounded turn_decision request. Only a tool-choice compatibility fallback is allowed. */ + decisionRepair?: { + check: () => void; + dispatch: (fallback: boolean) => void; + }; /** Constrain the response to one named JSON envelope instead of native tool syntax. */ responseFormat?: { name: string; schema: LLMToolDeclaration['input_schema'] }; maxTokens?: number; @@ -88,6 +93,7 @@ export interface LLMProvider { readonly displayName: string; readonly capabilities?: LLMProviderCapabilities; + readonly tracksDecisionRepairDispatch?: boolean; complete(options: LLMRequestOptions): Promise; diff --git a/packages/ai/src/provider/connection-error.ts b/packages/ai/src/provider/connection-error.ts index fdc0795f..0e670b2c 100644 --- a/packages/ai/src/provider/connection-error.ts +++ b/packages/ai/src/provider/connection-error.ts @@ -121,7 +121,8 @@ function classifyConnectionHint( export async function fetchWithConnectionContext( url: string, - init: RequestInit + init: RequestInit, + beforeDispatch?: () => void ): Promise { try { // O83: SDK/embedder paths too. With a proxy the dispatcher must exist before @@ -129,6 +130,8 @@ export async function fetchWithConnectionContext( // requests and must not delay this one (B64: ~80ms of undici import). if (hasProxyConfigured()) await ensureKeepAliveDispatcherInstalled(); else scheduleKeepAliveDispatcherInstalled(); + init.signal?.throwIfAborted(); + beforeDispatch?.(); return await fetch(url, init); } catch (err) { if (err instanceof Error && err.name === 'AbortError') throw err; diff --git a/packages/ai/src/provider/multi-provider-router.ts b/packages/ai/src/provider/multi-provider-router.ts index 35e1b6f6..b01a9cd5 100644 --- a/packages/ai/src/provider/multi-provider-router.ts +++ b/packages/ai/src/provider/multi-provider-router.ts @@ -102,6 +102,10 @@ export class MultiProviderRouter implements LLMProvider { return true; } + get tracksDecisionRepairDispatch(): boolean { + return this.primary.tracksDecisionRepairDispatch === true; + } + async complete(opts: LLMRequestOptions): Promise { return this.stream(opts, () => {}); } @@ -110,6 +114,7 @@ export class MultiProviderRouter implements LLMProvider { opts: LLMRequestOptions, onEvent: (e: LLMStreamEvent) => void ): Promise { + if (opts.decisionRepair) return this.primary.stream(opts, onEvent); let primaryErr: unknown; try { return await this.primary.stream(opts, onEvent); diff --git a/packages/ai/src/provider/pi-ai-adapter.ts b/packages/ai/src/provider/pi-ai-adapter.ts index eaa5ec5d..b59ebf6e 100644 --- a/packages/ai/src/provider/pi-ai-adapter.ts +++ b/packages/ai/src/provider/pi-ai-adapter.ts @@ -142,11 +142,11 @@ function applyAnthropicSystemPromptPartsToPayload( export { PiAiFirstEventTimeoutError } from './pi-ai-watchdog.js'; export type { PiAiModelInfo, PiAiStreamEvent } from './pi-ai-wire-format.js'; -export type PiAiStreamFunction = ( +export type PiAiStreamFunction = (( model: PiAiModelInfo, context: unknown, options?: Record -) => AsyncIterable; +) => AsyncIterable) & { tracksDecisionRepairDispatch?: true }; /** Signals that a gateway refused the *value* of tool_choice, not the request shape. */ const TOOL_CHOICE_FIELD = /tool[ _-]?choice/i; @@ -198,9 +198,9 @@ function rejectionMessage(err: unknown): string { return parts.join('\n'); } -function isToolChoiceUnsupportedRejection(err: unknown): boolean { +function isToolChoiceUnsupportedRejection(err: unknown, requireTypedStatus = false): boolean { const message = rejectionMessage(err); - const status = statusFromError(err) ?? statusFromText(message); + const status = statusFromError(err) ?? (requireTypedStatus ? undefined : statusFromText(message)); if (status !== 400 && status !== 422) return false; return TOOL_CHOICE_FIELD.test(message) && TOOL_CHOICE_UNSUPPORTED.test(message); } @@ -221,6 +221,7 @@ interface PiAttemptResult { state: PiAttemptState; error: Error | null; timedOut: boolean; + dispatched: boolean; } export interface PiAiLLMProviderConfig { @@ -236,6 +237,7 @@ export interface PiAiLLMProviderConfig { } export class PiAiLLMProvider implements LLMProvider { + readonly tracksDecisionRepairDispatch = true; readonly id: string; readonly displayName: string; readonly capabilities: NonNullable; @@ -460,6 +462,12 @@ export class PiAiLLMProvider implements LLMProvider { ): Promise { const watchdog = startFirstEventWatchdog(options.abortSignal, this.model); const piOptions = this.buildPiOptions(options, watchdog.signal, omitToolChoice); + let dispatched = false; + const dispatch = () => { + watchdog.signal?.throwIfAborted(); + options.decisionRepair?.dispatch(omitToolChoice); + dispatched = true; + }; const trace = process.env.MOSS_TRACE_PI_AI_STREAM === '1' || process.env.MOSS_TRACE_PI_AI_STREAM === 'true'; const state: PiAttemptState = { @@ -473,6 +481,11 @@ export class PiAiLLMProvider implements LLMProvider { }; try { + if (options.decisionRepair && this.streamFn.tracksDecisionRepairDispatch) { + piOptions.onDecisionRepairDispatch = dispatch; + } else if (options.decisionRepair) { + dispatch(); + } for await (const event of this.streamFn(piModel, piContext, piOptions)) { watchdog.onActivity(); if (trace) { @@ -503,12 +516,13 @@ export class PiAiLLMProvider implements LLMProvider { state, error: translated instanceof Error ? translated : new Error(String(translated)), timedOut: translated instanceof PiAiFirstEventTimeoutError, + dispatched, }; } finally { watchdog.dispose(); } - return { state, error: null, timedOut: false }; + return { state, error: null, timedOut: false, dispatched }; } /** @@ -532,7 +546,6 @@ export class PiAiLLMProvider implements LLMProvider { log.warn('provider rejected required tool_choice; retrying once without it', { model: this.model.id, provider: this.model.provider, - error: first.error?.message, }); return this.runAttempt(options, piContext, piModel, true, onEvent); } @@ -549,12 +562,16 @@ export class PiAiLLMProvider implements LLMProvider { // Only the `required` Moss raises for this run's logical request may be // relaxed. A requirement that exists only as an environment default never // reaches options.toolChoice, so it stays a hard requirement. - if (options.toolChoice !== 'required') return false; + if ( + options.toolChoice !== 'required' || + (options.decisionRepair && (!attempt.dispatched || options.responseFormat)) + ) + return false; const { state } = attempt; if (state.delivered || state.content.length > 0 || state.thinkingChunks.length > 0) return false; if (state.reportedUsage) return false; - return isToolChoiceUnsupportedRejection(attempt.error); + return isToolChoiceUnsupportedRejection(attempt.error, Boolean(options.decisionRepair)); } private buildPiContext(options: LLMRequestOptions, convertedMessages: unknown[]): unknown { @@ -631,6 +648,7 @@ export class PiAiLLMProvider implements LLMProvider { } : {}), ...(onPayload ? { onPayload } : {}), + ...(options.decisionRepair ? { decisionRepair: true, maxRetries: 0 } : {}), ...(extraBody ? { extraBody } : {}), }; } diff --git a/packages/ai/src/provider/pi-ai-http-transport.ts b/packages/ai/src/provider/pi-ai-http-transport.ts index 8a92685a..3b7ee827 100644 --- a/packages/ai/src/provider/pi-ai-http-transport.ts +++ b/packages/ai/src/provider/pi-ai-http-transport.ts @@ -41,6 +41,11 @@ export function acceptReportedModelId(value: unknown): string | undefined { return REPORTED_MODEL_ID.test(trimmed) ? trimmed : undefined; } +type HttpStreamOptions = SimpleStreamOptions & { + decisionRepair?: boolean; + onDecisionRepairDispatch?: () => void; +}; + export interface HttpTransportConfig { /** Human-facing provider label used in error messages (e.g. 'Anthropic'). */ providerLabel: string; @@ -556,7 +561,7 @@ async function* streamOpenAiChat( config: HttpTransportConfig, model: PiModel, context: PiContext, - options: SimpleStreamOptions | undefined, + options: HttpStreamOptions | undefined, extraBody: Record | undefined ): AsyncGenerator { const signal = (options?.abortSignal ?? options?.signal) as AbortSignal | undefined; @@ -604,12 +609,16 @@ async function* streamOpenAiChat( delete body.tool_choice; } try { - return await fetchWithConnectionContext(endpoint, { - method: 'POST', - headers, - body: JSON.stringify(body), - signal, - }); + return await fetchWithConnectionContext( + endpoint, + { + method: 'POST', + headers, + body: JSON.stringify(body), + signal, + }, + options?.onDecisionRepairDispatch + ); } catch (err) { enhanceOpenAIFetchError(config, err); } @@ -618,6 +627,7 @@ async function* streamOpenAiChat( let response = await send(stream); let errorText = response.ok ? '' : await response.text(); if ( + !options?.decisionRepair && responseFormat && (response.status === 400 || response.status === 422) && /response[ _]?format|json[ _]?schema|structured output/i.test(errorText) @@ -639,7 +649,7 @@ async function* streamOpenAiChat( if (!res.ok) { const looksLikeStreamReject = res.status === 400 && /stream|stream_options|streaming/i.test(errorText); - if (!looksLikeStreamReject) { + if (options?.decisionRepair || !looksLikeStreamReject) { throw enhanceOpenAIHttpError(config, res.status, errorText); } const buffered = await sendCompatible(false); @@ -903,7 +913,7 @@ async function* streamAnthropicMessages( config: HttpTransportConfig, model: PiModel, context: PiContext, - options: SimpleStreamOptions | undefined + options: HttpStreamOptions | undefined ): AsyncGenerator { const signal = (options?.abortSignal ?? options?.signal) as AbortSignal | undefined; const tools = context.tools ?? []; @@ -938,7 +948,8 @@ async function* streamAnthropicMessages( }, body: JSON.stringify(body), signal, - } + }, + options?.onDecisionRepairDispatch ); if (!res.ok) { @@ -1093,14 +1104,14 @@ async function* streamAnthropicMessages( * permissive gateway convention). */ export function createHttpStreamFunction(config: HttpTransportConfig): PiAiStreamFunction { - return (model, context, options) => { + const stream: PiAiStreamFunction = (model, context, options) => { const extraBody = options && 'extraBody' in options && isRecord(options.extraBody) ? (options.extraBody as Record) : undefined; async function* run(): AsyncGenerator { const piContext = context as PiContext; - const piOptions = options as SimpleStreamOptions | undefined; + const piOptions = options as HttpStreamOptions | undefined; if (model.api === 'anthropic-messages') { yield* streamAnthropicMessages(config, model, piContext, piOptions); } else { @@ -1109,4 +1120,6 @@ export function createHttpStreamFunction(config: HttpTransportConfig): PiAiStrea } return run(); }; + stream.tracksDecisionRepairDispatch = true; + return stream; } diff --git a/packages/core/src/agent/moss-agent.ts b/packages/core/src/agent/moss-agent.ts index 2399dbad..c06f7bdb 100644 --- a/packages/core/src/agent/moss-agent.ts +++ b/packages/core/src/agent/moss-agent.ts @@ -438,6 +438,7 @@ export class MossAgent { instanceId: crypto.randomUUID(), }; private readonly activeRunIds = new Map>(); + private readonly activeIntentTurns = new Map(); private readonly taskIntentTaskIds = new Map(); /** Polling claims an entry only until its canonical append acknowledges it. */ private readonly claimedSteers = new Map>(); @@ -923,21 +924,26 @@ export class MossAgent { private mutateInbox(sessionKey: string, mutate: (inbox: SessionInbox) => T): T { const file = this.inboxFilePath(sessionKey); const store = this.versionedStore; + let result: T; if (store) { - const { inbox, result } = store.updateInbox( + const updated = store.updateInbox( sessionKey, mutate, file ? () => loadSessionInbox(file) : undefined ); - this.rememberInbox(sessionKey, inbox); - return result; + this.rememberInbox(sessionKey, updated.inbox); + result = updated.result; + } else if (file) { + const updated = updateSessionInbox(file, mutate); + this.rememberInbox(sessionKey, updated.inbox); + result = updated.result; + } else { + result = mutate(this.inboxFor(sessionKey)); } - if (file) { - const { inbox, result } = updateSessionInbox(file, mutate); - this.rememberInbox(sessionKey, inbox); - return result; + for (const runId of this.activeRunIds.get(sessionKey) ?? []) { + this.activeIntentTurns.get(runId)?.repair?.checkReplacement(); } - return mutate(this.inboxFor(sessionKey)); + return result; } admit( @@ -2092,6 +2098,7 @@ ${result.stderr ?? ''}`.trim(); const streamFn = createStreamFunctionFromLlmProvider({ provider, + decisionRepair: () => intentTurn?.repair?.forRequest(runId, abortSignal), getToolChoice: (tools) => (readOnlyIntentSurface || intentTurn?.isRepairingDecision) && intentTurn?.needsDecision && @@ -2636,7 +2643,8 @@ ${result.stderr ?? ''}`.trim(); sessionKey, minOutput: outputTokensPinned ? input.output : Math.min(input.output, 1024), policyKey: this.contextPolicyKey(), - signal: abortSignal, + signal: input.repairSignal ?? abortSignal, + skipModelSummary: Boolean(input.repairSignal), summarize: this.buildSummarizeFn( { sessionKey, runId: `${runId}:compact` }, (usage) => versionedStore.recordSummaryUsage(sessionKey, runId, usage) @@ -2645,6 +2653,7 @@ ${result.stderr ?? ''}`.trim(); ? { ephemeral: [{ role: 'user', timestamp: Date.now(), content: extraContext }] } : {}), }); + input.repairSignal?.throwIfAborted(); contextGeneration = projection.revision; preparedProjection = projection; return projection; @@ -2933,6 +2942,9 @@ ${result.stderr ?? ''}`.trim(); observeIntent ); this.noteRunStarted(sessionKey, run.params.runId); + if (run.params.taskIntentTurn) { + this.activeIntentTurns.set(run.params.runId, run.params.taskIntentTurn); + } miniStream = runAgentLoop(run.params); for await (const ev of this.adaptMiniStreamEvents(miniStream, run)) { yield ev; @@ -2948,6 +2960,7 @@ ${result.stderr ?? ''}`.trim(); } } finally { if (run) { + this.activeIntentTurns.delete(run.params.runId); this.noteRunFinished(sessionKey, run.params.runId); this.deferUnconsumedSteers(sessionKey, run.params.runId); } diff --git a/packages/core/src/loop/agent-loop-llm-call.ts b/packages/core/src/loop/agent-loop-llm-call.ts index e44e23bc..215aba0a 100644 --- a/packages/core/src/loop/agent-loop-llm-call.ts +++ b/packages/core/src/loop/agent-loop-llm-call.ts @@ -60,6 +60,7 @@ export interface ExecuteLlmTurnParams { lastMessageNeedsToolFollowUpLlm: (messages: Message[]) => boolean; suppressVisibleDeltas?: boolean; preserveSourceHistory?: boolean; + decisionRepair?: boolean; /** Per-call output cap. Overrides modelDef.maxTokens when recovery escalates. */ maxTokens?: number; } @@ -168,7 +169,7 @@ export async function executeLlmTurn(params: ExecuteLlmTurnParams): Promise 0) { - const results: Message = { - role: 'user', - content: intentResponse.results, - timestamp: Date.now(), - }; - await appendMessage(sessionKey, results); - currentMessages.push(results); - } - state.pendingMessages = [buildCorrectionMessage(intentResponse.retry)]; - state.hasMoreToolCalls = true; + if (intentResponse?.retry || intentResponse?.superseded) { + // The next request carries the current validator result in the runtime prompt. + // Rejected output was never published or executed, so it needs no transcript entry. + const repair = params.taskIntentTurn?.repair; + const exhausted = Boolean(repair?.exhausted); + state.hasMoreToolCalls = !exhausted; pushTurnEnd(); + if (exhausted) { + abortSignal.throwIfAborted(); + repair?.assertCurrent(); + repair?.record(runId, 'rounds_exhausted'); + state.taskIntentHalted = true; + push({ type: 'turn_transition', turn: state.turns, reason: 'task_intent_unresolved' }); + return { control: 'break' }; + } return { control: 'continue' }; } diff --git a/packages/core/src/loop/agent-loop-types.ts b/packages/core/src/loop/agent-loop-types.ts index 761f7c5a..0b25304b 100644 --- a/packages/core/src/loop/agent-loop-types.ts +++ b/packages/core/src/loop/agent-loop-types.ts @@ -136,6 +136,7 @@ export interface AgentLoopExtensions { output: number; measure(messages: Message[], output: number): number; force?: boolean; + repairSignal?: AbortSignal; }) => Promise; assertContextRevision?(revision: number): void; registerToolInvocation?( diff --git a/packages/core/src/loop/agent-loop.ts b/packages/core/src/loop/agent-loop.ts index 62ddb9bc..133c68d2 100644 --- a/packages/core/src/loop/agent-loop.ts +++ b/packages/core/src/loop/agent-loop.ts @@ -51,6 +51,7 @@ import { } from './background-completion.js'; import { isNudgeDisabled } from './nudges/disable.js'; import { resolveModelOutputBudget } from './output-limit.js'; +import { abortable } from '@rdk-moss/foundation/utils/abort-signals.js'; const defaultPendingToolAborts = new PendingToolAbortStore(); export type { @@ -336,6 +337,7 @@ export function runTurnEngine( // sub-agents (host-provided engine), once per run. if ( params.bestOfNFix && + !params.taskIntentTurn?.repair && (params.toolStartGuard?.allowsPriorRecovery() ?? true) && !state.bestOfNEscalated && state.failingVerifyStreak && @@ -366,82 +368,107 @@ export function runTurnEngine( } } - if (getSteeringMessages) { - const steeringMessages = await getSteeringMessages(); - if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); - } - if (maxTurns !== null && state.turns >= maxTurns) { - const needsToolFollow = lastMessageNeedsToolFollowUpLlm(currentMessages); - if (needsToolFollow && state.postLimitToolFollowUpsUsed < toolFollowupBypassCap) { - state.postLimitToolFollowUpsUsed += 1; - } else { + let repair = params.taskIntentTurn?.repair; + const roundsBeforeTurn = repair?.roundCount ?? 0; + let repairSignal = repair && AbortSignal.any([abortSignal, repair.signal]); + let turnStarted = false; + let turnToolCalls: { id: string; name: string; input: Record }[] = []; + let textDraft: ReturnType | undefined; + try { + if (abortSignal.aborted) { + repair?.record(runId, 'cancelled'); stream.push({ type: 'turn_transition', turn: state.turns, - reason: needsToolFollow ? 'tool_followup_cap_reached' : 'max_turns_reached', + reason: 'aborted_by_user', }); break outerLoop; } - } - const budgetBreach = checkRunBudgetBreach({ - budget, - tokensUsed: state.budgetTokensUsed, - toolCalls: state.toolExecutionMetrics.totalToolCalls, - turns: state.turns, - runStartMs, - }); - if (budgetBreach) { - log.warn('run budget exceeded, stopping gracefully', { - reason: budgetBreach, + + if (repair?.superseded) { + repair.record(runId, 'superseded'); + params.taskIntentTurn?.clearRepair(); + repair = undefined; + repairSignal = undefined; + } + if (getSteeringMessages && !repair) { + const steeringMessages = await getSteeringMessages(); + if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); + } + if (maxTurns !== null && state.turns >= maxTurns) { + const needsToolFollow = lastMessageNeedsToolFollowUpLlm(currentMessages); + if ( + !params.taskIntentTurn?.repair && + needsToolFollow && + state.postLimitToolFollowUpsUsed < toolFollowupBypassCap + ) { + state.postLimitToolFollowUpsUsed += 1; + } else { + stream.push({ + type: 'turn_transition', + turn: state.turns, + reason: + needsToolFollow && !params.taskIntentTurn?.repair + ? 'tool_followup_cap_reached' + : 'max_turns_reached', + }); + break outerLoop; + } + } + const budgetBreach = checkRunBudgetBreach({ + budget, tokensUsed: state.budgetTokensUsed, toolCalls: state.toolExecutionMetrics.totalToolCalls, turns: state.turns, + runStartMs, }); - stream.push({ type: 'turn_transition', turn: state.turns, reason: budgetBreach }); - break outerLoop; - } - - if (abortSignal.aborted) { - stream.push({ type: 'turn_transition', turn: state.turns, reason: 'aborted_by_user' }); - break outerLoop; - } + if (budgetBreach) { + log.warn('run budget exceeded, stopping gracefully', { + reason: budgetBreach, + tokensUsed: state.budgetTokensUsed, + toolCalls: state.toolExecutionMetrics.totalToolCalls, + turns: state.turns, + }); + stream.push({ type: 'turn_transition', turn: state.turns, reason: budgetBreach }); + break outerLoop; + } - // Sample after awaited host steering. This request's declarations and - // reminders share one snapshot; tool execution still resolves live. - await params.taskIntentTurn?.prepare(); - const toolsForTurn = [...resolveToolsForRun()]; + // After steering, bind tools and the prompt to the same snapshot. + repair?.assertCurrent(); + await abortable(params.taskIntentTurn?.prepare() ?? Promise.resolve(), repairSignal); + repair?.assertCurrent(); + const toolsForTurn = [...resolveToolsForRun()]; - state.turns++; + state.turns++; + turnStarted = true; - if (state.lastTurnEndMs !== null) { - const silence = Date.now() - state.lastTurnEndMs; - state.interTurnSilenceMs.push(silence); - if (state.interTurnSilenceMs.length > INTER_TURN_SILENCE_WINDOW) { - state.interTurnSilenceMs.shift(); + if (state.lastTurnEndMs !== null) { + const silence = Date.now() - state.lastTurnEndMs; + state.interTurnSilenceMs.push(silence); + if (state.interTurnSilenceMs.length > INTER_TURN_SILENCE_WINDOW) { + state.interTurnSilenceMs.shift(); + } } - } - stream.push({ - type: 'turn_start', - turn: state.turns, - ...(params.harnessAdapterReceipt - ? { harnessAdapter: params.harnessAdapterReceipt } - : {}), - }); + stream.push({ + type: 'turn_start', + turn: state.turns, + ...(params.harnessAdapterReceipt + ? { harnessAdapter: params.harnessAdapterReceipt } + : {}), + }); - if (state.pendingMessages.length > 0) { - for (const msg of state.pendingMessages) { - await appendMessage(sessionKey, msg); - currentMessages.push(msg); + if (state.pendingMessages.length > 0) { + for (const msg of state.pendingMessages) { + await abortable(appendMessage(sessionKey, msg), repairSignal); + currentMessages.push(msg); + } + state.pendingMessages = []; } - state.pendingMessages = []; - } - const maxOut = activeOutputTokens(); - const effectiveContextTokens = getEffectiveContextWindowTokens(contextTokens, maxOut); + const maxOut = activeOutputTokens(); + const effectiveContextTokens = getEffectiveContextWindowTokens(contextTokens, maxOut); - let turnToolCalls: { id: string; name: string; input: Record }[] = []; - let textDraft: ReturnType | undefined; - try { + repair?.assertCurrent(); refreshActiveSystemPrompt(); const wire = params.prepareContextProjection ? prepareProjectionWire({ @@ -454,53 +481,64 @@ export function runTurnEngine( : undefined; const projection = wire && params.prepareContextProjection - ? await params.prepareContextProjection({ - window: Math.floor(contextTokens * Math.pow(0.85, projectionOverflowRetries)), - output: maxOut, - force: projectionOverflowRetries > 0, - measure: (messages) => { - const context = wire(messages); - return estimatePromptUnitsForContextWindow({ - messages, - systemPrompt: context.systemPrompt ?? '', - charsPerTokenUnit: charsPerUnit, - effectiveContextWindowTokens: effectiveContextTokens, - includeThinking: shouldIncludeThinkingInBudget(messages, modelDef), - toolsChars: JSON.stringify(context.tools ?? []).length, - }); - }, - }) + ? await abortable( + params.prepareContextProjection({ + window: Math.floor(contextTokens * Math.pow(0.85, projectionOverflowRetries)), + output: maxOut, + force: projectionOverflowRetries > 0, + repairSignal, + measure: (messages) => { + const context = wire(messages); + return estimatePromptUnitsForContextWindow({ + messages, + systemPrompt: context.systemPrompt ?? '', + charsPerTokenUnit: charsPerUnit, + effectiveContextWindowTokens: effectiveContextTokens, + includeThinking: shouldIncludeThinkingInBudget(messages, modelDef), + toolsChars: JSON.stringify(context.tools ?? []).length, + }); + }, + }), + repairSignal + ) : undefined; + repair?.assertCurrent(); const projectionRevision = projection?.revision; if (projectionRevision !== undefined) params.assertContextRevision?.(projectionRevision); const ctxResult: Awaited> | undefined = projection && wire ? undefined - : await prepareTurnContext({ - state, - currentMessages, - systemPrompt: activeSystemPrompt, - systemPromptParts: activeSystemPromptParts, - effectiveContextTokens, - charsPerUnit, - modelDef, - getToolsForRun: () => toolsForTurn, - sessionKey, - runId, - prepareCompaction, - compactHooks, - persistCurrentMessages, - push: (e) => stream.push(e), - abortSignal, - pruningSettings, - hardCapMessageCount: effectiveCaps.maxMessageCount, - hardCapTotalTokens: effectiveCaps.maxTotalTokens, - previousPrefixSnapshot, - previousToolNames, - prefixDebugEnabled, - maxTurns: maxTurns ?? undefined, - }); + : await abortable( + prepareTurnContext({ + state, + currentMessages, + systemPrompt: activeSystemPrompt, + systemPromptParts: activeSystemPromptParts, + effectiveContextTokens, + charsPerUnit, + modelDef, + getToolsForRun: () => toolsForTurn, + sessionKey, + runId, + prepareCompaction: repair + ? (input) => prepareCompaction({ ...input, skipLlmCompaction: true }) + : prepareCompaction, + compactHooks, + persistCurrentMessages, + push: (e) => stream.push(e), + abortSignal: repairSignal ?? abortSignal, + pruningSettings, + hardCapMessageCount: effectiveCaps.maxMessageCount, + hardCapTotalTokens: effectiveCaps.maxTotalTokens, + previousPrefixSnapshot, + previousToolNames, + prefixDebugEnabled, + maxTurns: maxTurns ?? undefined, + }), + repairSignal + ); + repair?.assertCurrent(); if (ctxResult) { previousPrefixSnapshot = ctxResult.updatedSnapshots.previousPrefixSnapshot; @@ -557,7 +595,8 @@ export function runTurnEngine( reasoning, maxLLMRetries, topP, - abortSignal, + decisionRepair: Boolean(repair), + abortSignal: repairSignal ?? abortSignal, maxTokens: projection?.output ?? activeOutputTokens(), messagesForModel: projection?.messages ?? ctxResult!.messagesForModel, toolsForRun: ctxResult?.toolsForRun ?? toolsForTurn, @@ -583,6 +622,8 @@ export function runTurnEngine( continue; } + repair?.assertCurrent(); + // A completed generation no longer consumes the next generation’s recovery attempt. projectionOverflowRetries = 0; turnToolCalls = llmResult.toolCalls; @@ -679,7 +720,7 @@ export function runTurnEngine( break outerLoop; } - if (getSteeringMessages) { + if (getSteeringMessages && !params.taskIntentTurn?.repair) { const steeringMessages = await getSteeringMessages(); if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); } @@ -700,6 +741,43 @@ export function runTurnEngine( break; } } catch (turnErr) { + const activeRepair = params.taskIntentTurn?.repair; + if (activeRepair) { + if ( + turnStarted && + repair === activeRepair && + activeRepair.roundCount === roundsBeforeTurn + ) { + state.turns--; + } + activeRepair.checkReplacement(); + if (abortSignal.aborted) { + activeRepair.record(runId, 'cancelled'); + stream.push({ + type: 'turn_transition', + turn: state.turns, + reason: 'aborted_by_user', + }); + break outerLoop; + } + if (activeRepair.superseded) { + activeRepair.record(runId, 'superseded'); + params.taskIntentTurn?.clearRepair(); + state.hasMoreToolCalls = true; + continue; + } + if (activeRepair.timedOut) { + activeRepair.record(runId, 'repair_timeout'); + stream.push({ + type: 'turn_transition', + turn: state.turns, + reason: 'task_intent_unresolved', + }); + break outerLoop; + } + activeRepair.record(runId, 'provider_error'); + throw turnErr; + } if ( params.prepareContextProjection && !abortSignal.aborted && @@ -921,6 +999,8 @@ export function runTurnEngine( totalToolCalls: state.toolExecutionMetrics.totalToolCalls, messages: currentMessages, }); + } finally { + params.taskIntentTurn?.clearRepair(); } })().catch((err) => { try { diff --git a/packages/core/src/session/task-decision-rejection.ts b/packages/core/src/session/task-decision-rejection.ts new file mode 100644 index 00000000..2d7ae7dc --- /dev/null +++ b/packages/core/src/session/task-decision-rejection.ts @@ -0,0 +1,40 @@ +const guidance = { + truncated: 'The response was truncated. Submit a shorter, complete turn_decision.', + missing: 'The response omitted turn_decision. Submit exactly one declaration.', + duplicate: 'The response had multiple turn_decision calls. Submit exactly one declaration.', + invalid_field: + 'Correct the indicated declaration fields. Use changes: [] if the user did not amend the task. Cite the exact authorizing quote and its pending messageId when required.', + invalid_plan: + 'Use a non-empty, concrete plan for execute. Omit the plan or use plan: [] for the other dispositions.', + action_conflict: + 'The disposition and tool calls conflict. In this repair submit only the declaration.', + precondition_unmet: + 'A condition required by the host is unmet. Base the new decision on the current task context and verified results.', + unknown: 'Submit a complete declaration matching the schema and the current task.', +} as const; + +export type TaskDecisionRejectionCode = keyof typeof guidance; + +export class TaskDecisionRejection extends Error { + // Detail is assigned only at validator sites. Never pass through exception text from hosts. + constructor( + readonly code: TaskDecisionRejectionCode, + detail?: string + ) { + super([guidance[code], detail].filter(Boolean).join(' ')); + } +} + +export function taskDecisionRepairPrompt( + rejection: TaskDecisionRejection, + replyOnly = false +): string { + return [ + `[Runtime] turn_decision rejected (${rejection.code}). ${rejection.message}`, + 'No business action from the rejected response was executed. Continue the original request under the current declaration schema.', + replyOnly + ? 'Use answer, clarify, or cancel as the schema allows. Do not submit an executable plan.' + : 'If tools are still needed, including read-only file reads, search or lookup, choose execute with a concrete plan. It does not grant permissions. Use answer for a complete direct reply, clarify for genuinely missing user information, or cancel to stop.', + 'Put any requested answer format in the final reply. Submit only one corrected turn_decision now.', + ].join(' '); +} diff --git a/packages/core/src/session/task-decision-repair.ts b/packages/core/src/session/task-decision-repair.ts new file mode 100644 index 00000000..bd273368 --- /dev/null +++ b/packages/core/src/session/task-decision-repair.ts @@ -0,0 +1,116 @@ +import { getRootLogger } from '@rdk-moss/foundation/logger.js'; +import { TaskExecutionSupersededError } from '../task/task-execution-guard.js'; +import type { TaskDecisionRejectionCode } from './task-decision-rejection.js'; + +const log = getRootLogger().child('agent:task-intent-repair'); +const MAX_ROUNDS = 3; +const MAX_REQUESTS = 2 * MAX_ROUNDS; +const WINDOW_MS = 60_000; + +class TaskDecisionRepairTimeout extends Error {} + +export class TaskDecisionRepair { + private readonly deadline = performance.now() + WINDOW_MS; + private readonly controller = new AbortController(); + private readonly timer = setTimeout(() => this.expire(), WINDOW_MS); + private rounds = 0; + private requests = 0; + private closed = false; + + constructor( + readonly inputSeq: number, + private readonly readInputSeq: () => number + ) { + this.timer.unref(); + } + + get signal(): AbortSignal { + return this.controller.signal; + } + + get roundCount(): number { + return this.rounds; + } + + get superseded(): boolean { + return this.readInputSeq() !== this.inputSeq; + } + + get timedOut(): boolean { + return ( + this.signal.reason instanceof TaskDecisionRepairTimeout || performance.now() >= this.deadline + ); + } + + get exhausted(): boolean { + return this.rounds >= MAX_ROUNDS; + } + + assertCurrent(): void { + this.checkReplacement(); + if (this.timedOut) this.expire(); + this.signal.throwIfAborted(); + if (this.closed) throw new Error('Task decision repair is closed'); + } + + checkReplacement(): void { + if (this.superseded) { + this.controller.abort(new TaskExecutionSupersededError('Task decision repair superseded')); + this.dispose(); + } + } + + record( + runId: string, + outcome: + | TaskDecisionRejectionCode + | 'dispatched' + | 'fallback' + | 'repair_timeout' + | 'rounds_exhausted' + | 'superseded' + | 'cancelled' + | 'provider_error' + | 'recovered' + ): void { + log.info('task decision repair', { + runId, + inputSeq: this.inputSeq, + round: this.rounds, + requests: this.requests, + elapsedMs: Math.round(performance.now() - (this.deadline - WINDOW_MS)), + outcome, + }); + } + + forRequest(runId: string, abortSignal: AbortSignal) { + let attempts = 0; + const check = () => { + abortSignal.throwIfAborted(); + this.assertCurrent(); + }; + const dispatch = (fallback: boolean) => { + check(); + if ( + this.requests >= MAX_REQUESTS || + (fallback ? attempts !== 1 : attempts !== 0 || this.exhausted) + ) { + throw new Error('Task decision repair request limit reached'); + } + if (!fallback) this.rounds++; + attempts++; + this.requests++; + this.record(runId, fallback ? 'fallback' : 'dispatched'); + }; + return { check, dispatch }; + } + + dispose(): void { + this.closed = true; + clearTimeout(this.timer); + } + + private expire(): void { + this.controller.abort(new TaskDecisionRepairTimeout('Task decision repair timed out')); + } +} diff --git a/packages/core/src/session/task-intent-coordinator.ts b/packages/core/src/session/task-intent-coordinator.ts index b28419e5..610311ea 100644 --- a/packages/core/src/session/task-intent-coordinator.ts +++ b/packages/core/src/session/task-intent-coordinator.ts @@ -20,6 +20,7 @@ import { applyTaskRevision } from '../task/task-revision.js'; import { appendTaskEvent, getTaskStateSnapshot } from '../task/task-store.js'; import { listTaskRecords } from '../task-runtime/artifacts.js'; import { type SessionInbox, type SessionInboxEntry } from './session-inbox.js'; +import { TaskDecisionRejection } from './task-decision-rejection.js'; import { applyIntentChanges, emptyTaskIntent, readTaskIntent } from './task-intent-state.js'; export interface TaskIntentBatch { @@ -196,13 +197,21 @@ export class TaskIntentCoordinator { return this.context?.hasRecordedCorrection(targetId, text) ?? false; } - async commit(batch: TaskIntentBatch, decision: TurnDecision): Promise { + async commit( + batch: TaskIntentBatch, + decision: TurnDecision, + beforeJournal?: () => void, + afterJournal?: () => void + ): Promise { if ( decision.baseRevision !== batch.snapshot.revision || decision.inputSeq !== batch.snapshot.inputSeq || JSON.stringify(decision.messageIds) !== JSON.stringify(batch.inputs.map((entry) => entry.id)) ) { - throw new Error('turn_decision does not match the captured user input'); + throw new TaskDecisionRejection( + 'invalid_field', + 'turn_decision does not match the captured user input.' + ); } const state = applyIntentChanges(batch.snapshot.state, decision.changes, batch.inputs); if (!state.goal && batch.inputs.length > 0) { @@ -210,14 +219,18 @@ export class TaskIntentCoordinator { state.sources.goal = [{ messageId: batch.inputs[0]!.id, quote: batch.inputs[0]!.prompt }]; } const corrections = decision.contextCorrections ?? []; - if (corrections.length && !this.context) throw new Error('Context corrections are unavailable'); + if (corrections.length && !this.context) + throw new TaskDecisionRejection('invalid_field', 'Context corrections are unavailable.'); for (const correction of corrections) { if ( !batch.inputs.some( (entry) => entry.id === correction.messageId && entry.prompt.includes(correction.quote) ) ) { - throw new Error('Context corrections must cite an exact quote from pending user input'); + throw new TaskDecisionRejection( + 'invalid_field', + 'Context corrections must cite an exact quote from pending user input.' + ); } } const changed = @@ -248,6 +261,7 @@ export class TaskIntentCoordinator { ) { throw new TaskExecutionSupersededError('A newer user input superseded this response'); } + beforeJournal?.(); for (const correction of corrections) { this.context?.correct({ id: `intent:${correction.messageId}:${correction.targetId}`, @@ -256,7 +270,10 @@ export class TaskIntentCoordinator { }); } if (snapshot.planDependsOn!.length && !this.context?.claimsActive(snapshot.planDependsOn!)) { - throw new Error('The new plan depends on an invalidated or unknown claim'); + throw new TaskDecisionRejection( + 'invalid_plan', + 'The new plan depends on an invalidated or unknown claim.' + ); } const last = inbox.toEntries().find((entry) => entry.id === lastId)!; // Publish the recovery journal before any asynchronous task projection. @@ -287,6 +304,7 @@ export class TaskIntentCoordinator { : {}), }); }); + afterJournal?.(); await this.projectOrFail(lastId, decision.messageIds); return snapshot; } diff --git a/packages/core/src/session/task-intent-state.ts b/packages/core/src/session/task-intent-state.ts index 92eb21dd..e3f81e91 100644 --- a/packages/core/src/session/task-intent-state.ts +++ b/packages/core/src/session/task-intent-state.ts @@ -1,3 +1,4 @@ +import { TaskDecisionRejection } from './task-decision-rejection.js'; import type { TaskIntentChange, TaskIntentSnapshot, @@ -121,7 +122,7 @@ export function readTaskIntent(entries: readonly SessionInboxEntry[]): TaskInten function record(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { - throw new Error('turn_decision must be an object'); + throw new TaskDecisionRejection('invalid_field', 'turn_decision must be an object.'); } return value as Record; } @@ -132,7 +133,10 @@ function strings(value: unknown, name: string, limit: number): string[] { value.length > limit || !value.every((item) => typeof item === 'string' && item.trim() && item.length <= 4000) ) { - throw new Error(`Invalid ${name}`); + throw new TaskDecisionRejection( + name === 'messageIds' ? 'invalid_field' : 'invalid_plan', + `Invalid ${name}.` + ); } return value as string[]; } @@ -149,7 +153,10 @@ export function parseTurnDecision(input: unknown): TurnDecision { !Array.isArray(value.changes) || value.changes.length > 64 ) { - throw new Error('Invalid turn_decision revision, sequence, disposition, or changes'); + throw new TaskDecisionRejection( + 'invalid_field', + 'Invalid turn_decision revision, sequence, disposition, or changes.' + ); } const problems: string[] = []; const changes = value.changes.map((raw, index): TaskIntentChange => { @@ -175,7 +182,7 @@ export function parseTurnDecision(input: unknown): TurnDecision { }); const rawCorrections = value.contextCorrections ?? []; if (!Array.isArray(rawCorrections) || rawCorrections.length > 16) - throw new Error('Invalid context corrections'); + throw new TaskDecisionRejection('invalid_field', 'Invalid context corrections.'); const contextCorrections = rawCorrections.map((raw) => { const item = record(raw); if ( @@ -186,23 +193,24 @@ export function parseTurnDecision(input: unknown): TurnDecision { (item[key] as string).length <= 4000 ) ) - throw new Error('Invalid context correction source'); + throw new TaskDecisionRejection('invalid_field', 'Invalid context correction source.'); return { targetId: item.targetId as string, messageId: item.messageId as string, quote: item.quote as string, }; }); + if (problems.length) throw new TaskDecisionRejection('invalid_field', problems.join('. ')); const plan = strings(value.plan, 'plan', 32); if (value.disposition === 'execute' && plan.length === 0) { - problems.push('execute requires a non-empty plan'); + throw new TaskDecisionRejection('invalid_plan', 'execute requires a non-empty plan.'); } if (value.disposition !== 'execute' && plan.length > 0) { - problems.push( - `Only execute may submit an executable plan; for ${value.disposition}, submit plan: [] and put the reply in answer` + throw new TaskDecisionRejection( + 'invalid_plan', + `For ${value.disposition}, put the reply in answer.` ); } - if (problems.length) throw new Error(problems.join('; ')); return { baseRevision: value.baseRevision as number, inputSeq: value.inputSeq as number, @@ -226,7 +234,10 @@ export function applyIntentChanges( for (const change of changes) { const source = inputs.find((entry) => entry.id === change.messageId); if (!source || !source.prompt.includes(change.quote)) { - throw new Error('Task changes must cite an exact quote from a pending user input'); + throw new TaskDecisionRejection( + 'invalid_field', + 'Task changes must cite an exact quote from a pending user input.' + ); } const citation = { messageId: change.messageId, quote: change.quote }; if (change.field === 'constraints') { diff --git a/packages/core/src/session/task-intent-turn.ts b/packages/core/src/session/task-intent-turn.ts index 03f70f3a..9e45adb0 100644 --- a/packages/core/src/session/task-intent-turn.ts +++ b/packages/core/src/session/task-intent-turn.ts @@ -6,7 +6,12 @@ import { } from './context-claim-declaration.js'; import type { TaskIntentSnapshot, TurnDecision } from '@rdk-moss/contracts/task-intent.js'; import type { Tool } from '../tools/tool-types.js'; -import { isTaskExecutionSupersededError } from '../task/task-execution-guard.js'; +import { TaskDecisionRejection, taskDecisionRepairPrompt } from './task-decision-rejection.js'; +import { TaskDecisionRepair } from './task-decision-repair.js'; +import { + TaskExecutionSupersededError, + isTaskExecutionSupersededError, +} from '../task/task-execution-guard.js'; import type { ContentBlock } from '@rdk-moss/contracts/messages.js'; import { type TaskIntentCoordinator, type TaskIntentBatch } from './task-intent-coordinator.js'; import { @@ -24,6 +29,7 @@ type Call = { id: string; name: string; input: Record }; export interface TaskIntentResponse { results: ContentBlock[]; retry?: string; + superseded?: true; hold?: boolean; answer?: string; } @@ -32,8 +38,8 @@ export interface TaskIntentResponse { export class TaskIntentTurn { private batch?: TaskIntentBatch; private binding?: TaskIntentSnapshot; - private attempts = 0; - private attemptSeq = -1; + repair?: TaskDecisionRepair; + private rejection?: TaskDecisionRejection; private readonly correctionAliases = new Map(); private wholeInputCitation?: { messageId: string; quote: string }; @@ -52,12 +58,17 @@ export class TaskIntentTurn { this.binding = this.batch.snapshot; this.correctionAliases.clear(); this.wholeInputCitation = undefined; - if (this.attemptSeq !== this.batch.snapshot.inputSeq) { - this.attemptSeq = this.batch.snapshot.inputSeq; - this.attempts = 0; + if (this.repair && this.repair.inputSeq !== this.batch.snapshot.inputSeq) { + this.clearRepair(); } } + clearRepair(): void { + this.repair?.dispose(); + this.repair = undefined; + this.rejection = undefined; + } + get hasBoundTask(): boolean { return this.batch?.snapshot.taskId !== undefined; } @@ -67,7 +78,7 @@ export class TaskIntentTurn { } get isRepairingDecision(): boolean { - return this.needsDecision && this.attempts > 0; + return this.needsDecision && this.repair !== undefined; } get isAnswerOnly(): boolean { @@ -135,6 +146,13 @@ export class TaskIntentTurn { } prompt(readOnly = false, renderedInputId?: string): string { + const prompt = this.intentPrompt(readOnly, renderedInputId); + return this.rejection + ? `${prompt}\n${taskDecisionRepairPrompt(this.rejection, readOnly && !this.hasBoundTask)}` + : prompt; + } + + private intentPrompt(readOnly: boolean, renderedInputId?: string): string { const batch = this.batch; if (!batch) return ''; if (this.correctionTargets && (this.isAnswerOnly || (readOnly && !this.hasBoundTask))) { @@ -232,7 +250,10 @@ export class TaskIntentTurn { const matches = batch.inputs.filter((entry) => entry.prompt.includes(quote)); const latest = matches.at(-1); if (!latest) { - throw new Error(`${location}.quote must copy exact words from a pending user input`); + throw new TaskDecisionRejection( + 'invalid_field', + `${location}.quote must copy exact words from a pending user input.` + ); } if ( !matches.every( @@ -242,8 +263,9 @@ export class TaskIntentTurn { Boolean(entry.intent?.invalidateTask) === Boolean(latest.intent?.invalidateTask) ) ) { - throw new Error( - `${location}.messageId is required: the quote matches different pending inputs ${JSON.stringify(matches.map(({ id }) => id))}. Choose the authorizing input ID; do not guess.` + throw new TaskDecisionRejection( + 'invalid_field', + `${location}.messageId is required because the quote matches different pending inputs.` ); } return latest.id; @@ -371,8 +393,15 @@ export class TaskIntentTurn { return this.binding ? structuredClone(this.binding) : undefined; } - async process(calls: Call[], interrupted: boolean): Promise { + async process( + calls: Call[], + interrupted: boolean, + abortSignal?: AbortSignal, + runId = 'unbound' + ): Promise { const declarations = calls.filter((call) => call.name === TURN_DECISION_TOOL); + let committing = false; + let journaled = false; try { if (!this.needsDecision) { if (declarations.length > 0) throw new Error('No pending input requires turn_decision'); @@ -380,25 +409,49 @@ export class TaskIntentTurn { const hold = Boolean(this.correctionTargets && this.binding?.disposition !== 'execute'); return { results: this.takeClaims(calls, interrupted, { readOnly: hold }), hold }; } - if (interrupted || declarations.length !== 1) { - throw new Error('One complete turn_decision is required before any action or answer'); + abortSignal?.throwIfAborted(); + this.repair?.assertCurrent(); + if (this.coordinator.read().inputSeq !== this.batch!.snapshot.inputSeq) { + throw new TaskExecutionSupersededError('A newer user input superseded this response'); } + if (interrupted) throw new TaskDecisionRejection('truncated'); + if (declarations.length === 0) throw new TaskDecisionRejection('missing'); + if (declarations.length !== 1) throw new TaskDecisionRejection('duplicate'); const input = declarations[0]!.input; const decision = this.parseDecision(input, this.batch!); if ( - decision.disposition !== 'execute' && - calls.some((call) => ![TURN_DECISION_TOOL, CONTEXT_CLAIMS_TOOL].includes(call.name)) + (this.isRepairingDecision && calls.length !== declarations.length) || + (decision.disposition !== 'execute' && + calls.some((call) => ![TURN_DECISION_TOOL, CONTEXT_CLAIMS_TOOL].includes(call.name))) ) { - throw new Error('answer/clarify/cancel cannot include business tool calls'); + throw new TaskDecisionRejection('action_conflict'); } - const validation: unknown = this.validateDecision?.(structuredClone(decision)); - if (validation !== undefined) { - void Promise.resolve(validation).catch(() => {}); - throw new Error( - 'Host task intent validation must finish synchronously without a return value' - ); + if (this.validateDecision) { + try { + const validation: unknown = this.validateDecision(structuredClone(decision)); + if (validation !== undefined) { + void Promise.resolve(validation).catch(() => {}); + throw new Error('Task intent validation must be synchronous'); + } + } catch { + throw new TaskDecisionRejection('precondition_unmet'); + } } - this.binding = await this.coordinator.commit(this.batch!, decision); + const repair = this.repair; + committing = true; + this.binding = await this.coordinator.commit( + this.batch!, + decision, + () => { + abortSignal?.throwIfAborted(); + repair?.assertCurrent(); + }, + () => { + journaled = true; + repair?.record(runId, 'recovered'); + this.clearRepair(); + } + ); this.assertCurrent(decision.disposition !== 'execute'); this.batch = { ...this.batch!, snapshot: this.binding, inputs: [] }; const hold = decision.disposition !== 'execute'; @@ -434,19 +487,39 @@ export class TaskIntentTurn { }; } catch (error) { const superseded = isTaskExecutionSupersededError(error); - const message = error instanceof Error ? error.message : 'Invalid turn_decision'; + if ( + abortSignal?.aborted || + (!superseded && + (journaled || + this.repair?.signal.aborted || + !this.needsDecision || + (committing && !(error instanceof TaskDecisionRejection)))) + ) + throw error; + + const rejection = + error instanceof TaskDecisionRejection ? error : new TaskDecisionRejection('unknown'); const results: ContentBlock[] = calls.map((call) => ({ type: 'tool_result', tool_use_id: call.id, is_error: true, - content: `Not executed: ${superseded ? 'superseded by user input' : 'task decision not committed'}. ${message}`, + content: superseded + ? 'Task decision superseded by newer input.' + : `Task decision not committed (${rejection.code}).`, })); calls.length = 0; - this.attempts++; - return { - results, - retry: `[Runtime] ${message}. No business action executed. Repair this internally and continue the original user request; do not ask the user to retry or describe this protocol error. Submit one corrected turn_decision. If answering still requires tools, including read-only search or lookup, use execute with a concrete plan; this does not grant tool permissions. Use answer for a complete final reply needing no further tools. For clarify, put a specific question about genuinely missing user information in answer and use plan: []; only execute accepts a non-empty plan. Use an empty changes array unless amending task fields. Each change requires value and an exact author quote; use the authorizing pending messageId when matching inputs differ. Never invent a quote or repeat an obsolete plan.`, - }; + if (superseded) { + this.repair?.record(runId, 'superseded'); + this.clearRepair(); + return { results, superseded: true }; + } + this.repair ??= new TaskDecisionRepair( + this.batch!.snapshot.inputSeq, + () => this.coordinator.read().inputSeq + ); + this.repair.record(runId, rejection.code); + this.rejection = rejection; + return { results, retry: taskDecisionRepairPrompt(rejection) }; } } } diff --git a/packages/core/src/session/versioned-context.ts b/packages/core/src/session/versioned-context.ts index 5bfd3cae..f1e046fe 100644 --- a/packages/core/src/session/versioned-context.ts +++ b/packages/core/src/session/versioned-context.ts @@ -369,6 +369,7 @@ export interface ProjectionInput { summarize: SummarizeFn; signal: AbortSignal; force?: boolean; + skipModelSummary?: boolean; ephemeral?: Message[]; policyKey: string; } @@ -602,6 +603,7 @@ export class VersionedContextPipeline { } } if ( + !input.skipModelSummary && boundary && (!selected.legal || (input.force && (!isCompatible || boundary > candidate.throughOrdinal))) ) { @@ -619,7 +621,7 @@ export class VersionedContextPipeline { if (input.force) throw error; if (!selected.legal) summaryFailure = { error }; } - } else if (boundary && (retired || raw.tokens >= capacity * 0.5)) { + } else if (!input.skipModelSummary && boundary && (retired || raw.tokens >= capacity * 0.5)) { // The current source view already excludes superseded conclusions. A // retired checkpoint can rebuild off the reply path when this view fits. const backgroundKey = JSON.stringify([input.sessionKey, snapshot.revision, policy]); diff --git a/packages/core/src/task/task-engine.ts b/packages/core/src/task/task-engine.ts index ce86284a..ca7f5301 100644 --- a/packages/core/src/task/task-engine.ts +++ b/packages/core/src/task/task-engine.ts @@ -260,7 +260,7 @@ async function runAgentTurn( await deps.runTurn(prompt, phase, { taskId: state.taskId, userGoal, judgeGoal }), deps.runTurn ); - if (stopReason === 'task_intent_hold') { + if (stopReason === 'task_intent_hold' || stopReason === 'task_intent_unresolved') { await pauseForNewInput(deps, state.taskId); return 'hold'; } diff --git a/scripts/verify/task-intent-decision-repair.mjs b/scripts/verify/task-intent-decision-repair.mjs index 7a0ca4eb..a66144f7 100644 --- a/scripts/verify/task-intent-decision-repair.mjs +++ b/scripts/verify/task-intent-decision-repair.mjs @@ -1,6 +1,7 @@ #!/usr/bin/env node import assert from 'node:assert/strict'; import os from 'node:os'; +import { mock } from 'node:test'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { distResolve } from './lib/dist-resolve.mjs'; @@ -30,14 +31,14 @@ const execute = (changes = [goal()]) => ({ plan: ['Inspect the selected device'], }); const call = (input) => [{ id: 'decision', name: 'turn_decision', input }]; -function fixture(entries = [], context) { +function fixture(entries = [], context, validateDecision) { const inbox = SessionInbox.fromEntries(entries); const coordinator = new TaskIntentCoordinator( { read: () => inbox, mutate: (operation) => operation(inbox) }, os.tmpdir(), context ); - const turn = () => new TaskIntentTurn(coordinator, undefined, () => []); + const turn = () => new TaskIntentTurn(coordinator, undefined, () => [], validateDecision); return { inbox, coordinator, turn }; } @@ -116,8 +117,7 @@ turn = ambiguous.turn(); await turn.prepare(); const conflict = await turn.process(call(execute()), false); assert.match(conflict.retry, /messageId/); -assert.match(conflict.retry, /restricted/); -assert.match(conflict.retry, /editing/); +assert.doesNotMatch(conflict.retry, /restricted|editing/); assert.throws(() => ambiguous.coordinator.assertCurrent()); const explicit = await turn.process(call(execute([goal(request, 'editing')])), false); assert.ok(!explicit.retry && !explicit.halt, explicit.retry); @@ -214,3 +214,199 @@ const invented = await turn.process(call(execute([goal('用户没有说过的授 assert.ok(invented.retry); assert.throws(() => forged.coordinator.assertCurrent()); console.log('PASS missing or fabricated author quotes still fail closed'); + +const typed = fixture([], undefined, ({ disposition }) => { + if (disposition === 'answer') throw new Error('HOST_EXCEPTION_SENTINEL'); +}); +typed.coordinator.admit({ id: 'typed', text: 'Read the fixture first.' }); +turn = typed.turn(); +await turn.prepare(); +const verifyRejection = async (code, calls, truncated = false) => { + const result = await turn.process(calls, truncated); + assert.match(result.retry, new RegExp(`rejected \\(${code}\\)`)); + assert.doesNotMatch(result.retry, /HOST_EXCEPTION_SENTINEL|RAW_ARGUMENT_SENTINEL/); + assert.equal(calls.length, 0); + assert.equal(typed.coordinator.receipt('typed').status, 'pending'); + assert.equal(turn.prompt().match(/turn_decision rejected/g).length, 1); + assert.ok(turn.prompt().includes(result.retry)); +}; +await verifyRejection('truncated', [], true); +await verifyRejection('missing', []); +await verifyRejection('duplicate', [...call({}), ...call({})]); +await verifyRejection('invalid_field', call({ disposition: 'RAW_ARGUMENT_SENTINEL' })); +await verifyRejection('invalid_plan', call({ disposition: 'execute' })); +await verifyRejection('action_conflict', [ + ...call({ disposition: 'execute', plan: ['Read the fixture'] }), + { id: 'rogue', name: 'write_file', input: { body: 'RAW_ARGUMENT_SENTINEL' } }, +]); +await verifyRejection('precondition_unmet', call({ disposition: 'answer', answer: 'fabricated' })); +await verifyRejection( + 'unknown', + call( + new Proxy( + {}, + { + get: () => { + throw new Error('RAW_ARGUMENT_SENTINEL'); + }, + } + ) + ) +); +assert.equal((await turn.process(call({ disposition: 'cancel' }), false)).hold, true); +assert.equal(typed.coordinator.read().disposition, 'cancel'); +console.log('PASS safe, current feedback for every rejection and a valid cancel following repair'); + +const { TaskDecisionRepair } = await load('core/session/task-decision-repair.js'); +const { MossAgent } = await load('core/agent/moss-agent.js'); +const { InMemorySessionStore } = await load('core/session/session.js'); +const nextTick = () => new Promise((resolve) => setImmediate(resolve)); +const modelResponse = (...content) => ({ stopReason: 'end_turn', content }); +const pendingDecision = (input, id = 'decision') => + modelResponse({ + type: 'tool_use', + name: 'turn_decision', + id, + input, + }); +const model = (stream) => ({ + id: 'repair-fixture', + displayName: 'repair fixture', + stream, + complete: stream, +}); +const makeAgent = (stream) => + new MossAgent({ + llmProvider: model(stream), + sessionStore: new InMemorySessionStore(), + baseSystemPrompt: 'Use the per-turn decision.', + domainPrompt: false, + taskIntent: true, + verificationGate: false, + }); +const answer = pendingDecision({ disposition: 'answer', answer: 'repaired answer' }); +const hold = () => { + let release; + const result = new Promise((resolve) => { + release = resolve; + }); + return { result, release }; +}; + +{ + let clock = 0; + const now = mock.method(performance, 'now', () => clock); + const repair = new TaskDecisionRepair(1, () => 1); + const request = repair.forRequest('boundary', new AbortController().signal); + try { + clock = 59_999; + request.dispatch(false); + repair.assertCurrent(); + clock = 60_000; + assert.throws(() => request.dispatch(true), /timed out/); + assert.equal(repair.roundCount, 1); + } finally { + repair.dispose(); + now.mock.restore(); + } +} + +{ + const oldLimit = process.env.MOSS_LLM_FIRST_CHUNK_TIMEOUT_MS; + process.env.MOSS_LLM_FIRST_CHUNK_TIMEOUT_MS = '0'; + let clock = 0; + const now = mock.method(performance, 'now', () => clock); + mock.timers.enable({ apis: ['setTimeout'] }); + const entered = hold(); + const inFlight = hold(); + let requests = 0; + let settled = false; + let repairSignal; + const session = 'hung-repair'; + const agent = makeAgent((request) => { + if (++requests === 1) + return Promise.resolve(modelResponse({ type: 'text', text: 'bad declaration' })); + repairSignal = request.abortSignal; + entered.release(); + return inFlight.result; + }); + try { + const result = agent + .chat(session, 'Read the file', { + userInput: { id: 'hung' }, + taskFlow: false, + maxTurns: 8, + }) + .finally(() => { + settled = true; + }); + await entered.result; + clock = 59_999; + mock.timers.tick(59_999); + await nextTick(); + assert.equal(settled, false); + clock = 60_000; + mock.timers.tick(1); + assert.equal((await result).stopReason, 'task_intent_unresolved'); + assert.equal(repairSignal.aborted, true); + inFlight.release(answer); + await nextTick(); + assert.equal(agent.getTaskIntentReceipt(session, 'hung').status, 'pending'); + assert.equal(requests, 2); + } finally { + inFlight.release(answer); + mock.timers.reset(); + now.mock.restore(); + if (oldLimit === undefined) delete process.env.MOSS_LLM_FIRST_CHUNK_TIMEOUT_MS; + else process.env.MOSS_LLM_FIRST_CHUNK_TIMEOUT_MS = oldLimit; + await agent.close(); + } + console.log( + 'PASS 60-second deadline aborts an uncooperative provider and fences its late decision' + ); +} + +for (const cancel of [false, true]) { + const entered = hold(); + const inFlight = hold(); + const caller = new AbortController(); + const session = cancel ? 'user-cancel' : 'replacement'; + const prompts = []; + const agent = makeAgent(async ({ systemPrompt }) => { + prompts.push(systemPrompt); + if (prompts.length === 1) return modelResponse({ type: 'text', text: 'no declaration' }); + if (prompts.length === 2) { + entered.release(); + return inFlight.result; + } + return modelResponse({ type: 'text', text: 'replacement also has no declaration' }); + }); + try { + const result = agent.chat(session, 'Old request', { + userInput: { id: 'old' }, + taskFlow: false, + maxTurns: 3, + abortSignal: caller.signal, + }); + await entered.result; + if (cancel) caller.abort(); + else assert.ok(agent.steer(session, 'New request', { id: 'new' })); + const completed = await result; + inFlight.release(answer); + await nextTick(); + assert.equal(completed.stopReason, cancel ? 'aborted_by_user' : 'max_turns_reached'); + assert.equal(prompts.length, cancel ? 2 : 3); + assert.match(prompts[1], /rejected \(missing\)/); + if (!cancel) { + assert.doesNotMatch(prompts[2], /turn_decision rejected/); + assert.equal(agent.getTaskIntentReceipt(session, 'new').status, 'pending'); + } + assert.equal(agent.getTaskIntentReceipt(session, 'old').status, 'pending'); + } finally { + inFlight.release(answer); + await agent.close(); + } +} +console.log( + 'PASS steering supersedes a hanging repair and user cancellation does not open another request' +); diff --git a/scripts/verify/task-intent-revisions.mjs b/scripts/verify/task-intent-revisions.mjs index 41694a03..71abd489 100644 --- a/scripts/verify/task-intent-revisions.mjs +++ b/scripts/verify/task-intent-revisions.mjs @@ -168,9 +168,14 @@ try { const dispatched = []; const validated = createAgent( (request, count) => { - if (count === 3) return response(text('Checked the requested architecture.')); + if (count === 4) return response(text('Checked the requested architecture.')); + if (count === 3) return response(toolCall('validate_action', 'validated-action-3')); if (count === 2) { - assert.match(JSON.stringify(request.messages), new RegExp(repair)); + assert.match(request.systemPrompt, /precondition_unmet/); + assert.doesNotMatch( + request.systemPrompt + JSON.stringify(request.messages), + new RegExp(repair) + ); const pending = validated.agent.getTaskIntent(session); assert.equal(pending.pending, true); assert.equal(pending.processedSeq, 0); @@ -198,7 +203,7 @@ try { ], }, }, - toolCall('validate_action', `validated-action-${count}`) + ...(count === 1 ? [toolCall('validate_action', 'validated-action-1')] : []) ); }, { @@ -233,8 +238,8 @@ try { maxTurns: 5, }); assert.deepEqual(proposedQuotes, [hostInput, literal]); - assert.deepEqual(dispatched, ['validated-action-2']); - assert.equal(validated.provider.calls, 3); + assert.deepEqual(dispatched, ['validated-action-3']); + assert.equal(validated.provider.calls, 4); assert.equal(validatedResult.response, 'Checked the requested architecture.'); console.log( 'PASS host validation rejects the entire batch before commit and repairs the same pending input' @@ -410,8 +415,8 @@ try { maxTurns: 5, }); assert.equal(illegalStarts, 0); - assert.equal(invalid.provider.calls, 5, 'only the ordinary run budget limits protocol repair'); - assert.equal(held.stopReason, 'budget_turns_reached'); + assert.equal(invalid.provider.calls, 4, 'one original request and exactly three repairs'); + assert.equal(held.stopReason, 'task_intent_unresolved'); assert.doesNotMatch(held.response, /Execution is paused|could not be applied reliably/); console.log('PASS malformed decisions stay internal and respect the ordinary run budget'); diff --git a/scripts/verify/task-intent-tool-choice-fallback.mjs b/scripts/verify/task-intent-tool-choice-fallback.mjs index a28fc388..ad64031e 100644 --- a/scripts/verify/task-intent-tool-choice-fallback.mjs +++ b/scripts/verify/task-intent-tool-choice-fallback.mjs @@ -152,7 +152,7 @@ async function scenario(decide, maxTurns = 6) { const tools = (context.tools ?? []).map((tool) => tool.name); const frame = frameOf(context.systemPrompt); transcript.push({ tools, options: snapshot(options) }); - if (options?.toolChoice === 'required') throw new Error(INCIDENT); + if (options?.toolChoice === 'required') throw rejection(400); if (tools.length === 1 && tools[0] === 'turn_decision') { yield* decide(frame, transcript); return; @@ -317,11 +317,22 @@ async function scenario(decide, maxTurns = 6) { }, 3); assert.equal(run.receipt?.status !== 'committed', true, 'an invalid decision commits nothing'); assert.deepEqual(run.starts, [], 'no business tool ran on an invalid decision'); - assert.equal(run.result.stopReason, 'tool_followup_cap_reached'); + assert.equal(run.result.stopReason, 'max_turns_reached'); assert.deepEqual(run.validations, [], 'the host never validated an illegal decision'); console.log('[tool-choice] ok an invalid 200 after the retry still fails the decision contract'); } +{ + const run = await scenario(async function* () { + yield { type: 'done', reason: 'stop', usage: { input: 30, output: 0 } }; + }, 10); + assert.equal(run.result.stopReason, 'task_intent_unresolved'); + assert.equal(run.transcript.length, 7, 'one initial request plus six physical repairs'); + assert.equal(run.receipt.status, 'pending'); + assert.deepEqual(run.starts, []); + console.log('[tool-choice] ok three logical rounds bound the six physical repair requests'); +} + // ─── B: a gateway that accepts `required` sees exactly one request ─────────── { From d9e24dab8e53ac0d79bd5e508effe9571e425e31 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Thu, 3 Dec 2026 16:45:12 +0800 Subject: [PATCH 2/3] refactor(core): keep repair outcome policy with task decisions Regenerate the measured structure baseline for bounded decision repair using the repository metric tool, as in 3269c947. Import cycles, layer boundaries, loop file count and file-size caps remain at their existing limits. --- packages/core/src/loop/agent-loop.ts | 86 +++++-------------- .../core/src/session/task-decision-repair.ts | 17 ++++ packages/core/src/session/task-intent-turn.ts | 10 +++ scripts/structure-budget.json | 8 +- 4 files changed, 53 insertions(+), 68 deletions(-) diff --git a/packages/core/src/loop/agent-loop.ts b/packages/core/src/loop/agent-loop.ts index 133c68d2..3649bfc4 100644 --- a/packages/core/src/loop/agent-loop.ts +++ b/packages/core/src/loop/agent-loop.ts @@ -302,6 +302,9 @@ export function runTurnEngine( ? state.outputTokenBudget : (maxOutputTokensParam ?? modelDef.maxTokens ?? 8192); + const publishTurnStop = (reason: string) => + stream.push({ type: 'turn_transition', turn: state.turns, reason }); + try { // Grok TaskCompletionReminder parity: ensure lifecycle events queue // model-visible completions for background exec (coding UX). @@ -368,50 +371,30 @@ export function runTurnEngine( } } - let repair = params.taskIntentTurn?.repair; - const roundsBeforeTurn = repair?.roundCount ?? 0; - let repairSignal = repair && AbortSignal.any([abortSignal, repair.signal]); - let turnStarted = false; + const repair = params.taskIntentTurn?.beginRepairTurn(runId, abortSignal); + const repairSignal = repair && AbortSignal.any([abortSignal, repair.signal]); + const roundsBeforeTurn = repair?.roundCount; + const turnsBeforeThis = state.turns; let turnToolCalls: { id: string; name: string; input: Record }[] = []; let textDraft: ReturnType | undefined; try { if (abortSignal.aborted) { - repair?.record(runId, 'cancelled'); - stream.push({ - type: 'turn_transition', - turn: state.turns, - reason: 'aborted_by_user', - }); + repair?.finishFailedTurn(runId, abortSignal); + publishTurnStop('aborted_by_user'); break outerLoop; } - - if (repair?.superseded) { - repair.record(runId, 'superseded'); - params.taskIntentTurn?.clearRepair(); - repair = undefined; - repairSignal = undefined; - } if (getSteeringMessages && !repair) { const steeringMessages = await getSteeringMessages(); if (steeringMessages.length > 0) state.pendingMessages.push(...steeringMessages); } if (maxTurns !== null && state.turns >= maxTurns) { - const needsToolFollow = lastMessageNeedsToolFollowUpLlm(currentMessages); - if ( - !params.taskIntentTurn?.repair && - needsToolFollow && - state.postLimitToolFollowUpsUsed < toolFollowupBypassCap - ) { + const needsToolFollow = !repair && lastMessageNeedsToolFollowUpLlm(currentMessages); + if (needsToolFollow && state.postLimitToolFollowUpsUsed < toolFollowupBypassCap) { state.postLimitToolFollowUpsUsed += 1; } else { - stream.push({ - type: 'turn_transition', - turn: state.turns, - reason: - needsToolFollow && !params.taskIntentTurn?.repair - ? 'tool_followup_cap_reached' - : 'max_turns_reached', - }); + publishTurnStop( + needsToolFollow ? 'tool_followup_cap_reached' : 'max_turns_reached' + ); break outerLoop; } } @@ -429,7 +412,7 @@ export function runTurnEngine( toolCalls: state.toolExecutionMetrics.totalToolCalls, turns: state.turns, }); - stream.push({ type: 'turn_transition', turn: state.turns, reason: budgetBreach }); + publishTurnStop(budgetBreach); break outerLoop; } @@ -440,7 +423,6 @@ export function runTurnEngine( const toolsForTurn = [...resolveToolsForRun()]; state.turns++; - turnStarted = true; if (state.lastTurnEndMs !== null) { const silence = Date.now() - state.lastTurnEndMs; @@ -743,39 +725,19 @@ export function runTurnEngine( } catch (turnErr) { const activeRepair = params.taskIntentTurn?.repair; if (activeRepair) { - if ( - turnStarted && - repair === activeRepair && - activeRepair.roundCount === roundsBeforeTurn - ) { - state.turns--; - } - activeRepair.checkReplacement(); - if (abortSignal.aborted) { - activeRepair.record(runId, 'cancelled'); - stream.push({ - type: 'turn_transition', - turn: state.turns, - reason: 'aborted_by_user', - }); - break outerLoop; + if (repair === activeRepair && activeRepair.roundCount === roundsBeforeTurn) { + state.turns = turnsBeforeThis; } - if (activeRepair.superseded) { - activeRepair.record(runId, 'superseded'); + const stop = activeRepair.finishFailedTurn(runId, abortSignal); + if (stop === 'superseded') { params.taskIntentTurn?.clearRepair(); state.hasMoreToolCalls = true; continue; } - if (activeRepair.timedOut) { - activeRepair.record(runId, 'repair_timeout'); - stream.push({ - type: 'turn_transition', - turn: state.turns, - reason: 'task_intent_unresolved', - }); + if (stop) { + publishTurnStop(stop); break outerLoop; } - activeRepair.record(runId, 'provider_error'); throw turnErr; } if ( @@ -790,11 +752,7 @@ export function runTurnEngine( continue; } if (abortSignal.aborted) { - stream.push({ - type: 'turn_transition', - turn: state.turns, - reason: 'aborted_by_user', - }); + publishTurnStop('aborted_by_user'); throw turnErr; } diff --git a/packages/core/src/session/task-decision-repair.ts b/packages/core/src/session/task-decision-repair.ts index bd273368..58053b69 100644 --- a/packages/core/src/session/task-decision-repair.ts +++ b/packages/core/src/session/task-decision-repair.ts @@ -60,6 +60,23 @@ export class TaskDecisionRepair { } } + finishFailedTurn(runId: string, caller: AbortSignal) { + if (caller.aborted) { + this.record(runId, 'cancelled'); + return 'aborted_by_user'; + } + if (this.superseded) { + this.checkReplacement(); + this.record(runId, 'superseded'); + return 'superseded'; + } + if (this.timedOut) { + this.record(runId, 'repair_timeout'); + return 'task_intent_unresolved'; + } + this.record(runId, 'provider_error'); + } + record( runId: string, outcome: diff --git a/packages/core/src/session/task-intent-turn.ts b/packages/core/src/session/task-intent-turn.ts index 9e45adb0..959746d1 100644 --- a/packages/core/src/session/task-intent-turn.ts +++ b/packages/core/src/session/task-intent-turn.ts @@ -63,6 +63,16 @@ export class TaskIntentTurn { } } + beginRepairTurn(runId: string, caller: AbortSignal): TaskDecisionRepair | undefined { + const repair = this.repair; + if (!caller.aborted && repair?.superseded) { + repair.record(runId, 'superseded'); + this.clearRepair(); + return undefined; + } + return repair; + } + clearRepair(): void { this.repair?.dispose(); this.repair = undefined; diff --git a/scripts/structure-budget.json b/scripts/structure-budget.json index 46bcd38d..6b6bd67b 100644 --- a/scripts/structure-budget.json +++ b/scripts/structure-budget.json @@ -1,8 +1,8 @@ { "note": "Ratchet over src/ and every packages/*/src. Lower a number in the same commit that earns it; never raise one to pass a change. Moving code between roots changes nothing.", - "srcFiles": 619, - "totalLines": 171299, - "importEdges": 2650, + "srcFiles": 621, + "totalLines": 171695, + "importEdges": 2658, "largestFileLines": 5205, "largestFilePath": "src/cli/tui/app.ts", "filesOverLarge": 48, @@ -12,7 +12,7 @@ "cliIntoTui": 0, "sdkIntoCli": 0, "loopFiles": 27, - "loopLines": 6353, + "loopLines": 6389, "loopAreaDeps": 10, "loopForbiddenDeps": 0 } From f0d3d6175be16704e56c4ccb7a8ce1397a92bb85 Mon Sep 17 00:00:00 2001 From: d-robotics Date: Thu, 3 Dec 2026 16:46:59 +0800 Subject: [PATCH 3/3] docs: keep Moss repository instructions within the loader limit --- AGENTS.md | 66 +++++++++++++++++++++++++++---------------------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4c75c3b5..0beccf65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,40 +92,38 @@ Linux 真机,目标是机器人闭环 Goal→…→Deploy→Verify→Repair→ ## 结构导航 -| 想改什么 | 去哪 | -| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Agent loop / 轮次控制 / 截断续写与空响应恢复 | `packages/core/src/loop/` | -| 产品完成门(验收 / 验证 / 计划 / 审查账本 / best-of-n 修复) | `packages/core/src/loop-hooks/`(经 `completionGate` 注入引擎;引擎不得反向依赖,见 `docs/design/2026-12-01-loop-engine-hooks.md`) | -| 运行 loop(SDK 的 `runAgentLoop`、端口绑定、后台完成提醒读取) | `packages/core/src/loop-hooks/run-agent-loop.ts`(引擎入口是 `runTurnEngine`,产品实现只经 `LoopPorts` 传入;见 `docs/design/2026-12-01-loop-engine-hooks.md`) | -| 达标驱动自主执行(/goal 验收门) | `packages/core/src/task/task-engine.ts`、`packages/core/src/task/acceptance-command.ts` | -| MossAgent / 配置 / 事件 | `packages/core/src/agent/` | -| 工具注册与执行管线 | `packages/tools/src/builtin.ts`、`packages/core/src/tools/` | -| 内置工具实现 | `packages/tools/src/*.ts`(`read_pdf` 在 `packages/tools/src/read-pdf.ts`,仅 Node 内置;`diagnostics` 在 `packages/tools/src/diagnostics.ts`) | -| 设备契约 / SSH 连接 / 观测解析 | `packages/contracts/src/device.ts`、`packages/device/src/`、`packages/tools/src/device-tools.ts` | -| 上下文 / 压缩 / token | `packages/context/src/` | -| LLM provider / LLM 端口 | `packages/ai/src/provider/`、`packages/ai/src/llm/`(`@rdk-moss/ai`) | -| CLI / REPL / 命令 | `src/cli/`、`src/cli-main.ts` | -| 不需要 agent 的命令(phase None / ConfigOnly / WorkspaceReady) | `src/cli/command-phase.ts` 的 `runCommandWithoutAgent`;启动时的上下文窗口探测在 `src/cli/context-window-probe.ts` | -| CLI 壳(v0.22 起对齐 Claude Code / codex,动态 import) | `src/cli/tui/`(app.ts 外壳 + transcript.ts 语法投影 + help.ts 键位表);与 CLI 共享的文案和文本工具在 `src/cli/ui-copy.ts`、`ui-text.ts`、`tool-label.ts` | -| MCP 客户端与宿主 API(v0.16 起;宿主 API 经 SDK 根导出) | `packages/core/src/mcp/`、`packages/contracts/src/mcp.ts` | -| 轻量 skills(v0.16 起) | `packages/core/src/skills/` | -| 斜杠命令 | `src/cli/commands/registry.ts` 只做分发;命令按子系统分文件(`session-commands`、`permission-commands` 等),契约在 `command-types.ts` | -| 配置 | `src/cli/config.ts`(`resolveCliConfig`);`config-types`、`config-env`、`config-file`、`config-project-rules`、`config-values`、`config-audit`、`config-notices` | -| `moss config` 子命令 | `src/cli/config-commands.ts`(入口)、`config-set.ts`、`config-help.ts`、`config-init.ts`、`config-serialize.ts` | -| 拆分巨型模块 | `node scripts/split/cli.mjs `,见 `docs/design/2026-12-01-cli-split.md` | -| 设备风险分级 / 信任 / 审批文案 / 宿主审批端口 | `packages/foundation/src/safety/device-risk.ts`、`packages/foundation/src/safety/device-trust.ts`、`src/cli/device-safety-prompt.ts`、`packages/contracts/src/device.ts` | -| Hooks(事件 / 阻塞语义 / Stop 完成门 recipe / 技能自带) | `src/cli/hooks.ts`、`docs/hooks.md`、`docs/hooks/stop-verified-completion.mjs`、`packages/core/src/skills/skill-hooks.ts` | -| 显式记忆写路径(`/remember`) | `src/cli/remember-command.ts`(写 `AGENTS.md`) | -| 设备任务基准 | `bench/device-tasks/`、`scripts/bench-device.mjs`、`scripts/lib/device-bench*.mjs` | -| 审批纯策略(allow/ask/deny,无 TTY/UI 依赖) | `packages/core/src/agent/approval-policy.ts`、`packages/core/src/agent/permission-rules.ts`、`packages/foundation/src/safety/readonly-command.ts` | -| 会话树读模型(消息父子、pathTo、descendantsOf) | `packages/core/src/session/session-tree.ts` | -| 命令要读写会话 | `src/cli/session-store.ts` 的 `createWorkspaceSessionStore`,不要自己 `new JsonlSessionStore`;见 `docs/design/2026-12-01-session-context-map.md` | -| 模型元数据 | `src/cli/model-metadata.ts` 读 `model-catalog-snapshot.ts`(`scripts/generate-model-catalog.mjs` 刷新,`--check` 查过期);见 `docs/design/2026-12-01-model-catalog-snapshot.md` | -| 统一 Task Runtime 协议(状态机/事件/快照) | `packages/contracts/src/task-runtime.ts` | -| 统一 Task Runtime 引擎/存储/裁决/能力发现 | `packages/core/src/task/`(engine、store、verdict、capability、agent-turn) | -| TUI 任务投影层(CLI 壳的读路径) | `packages/core/src/task-runtime/`(artifacts + runtime 视图模型) | -| 契约(prompt、soul、async-task) | `packages/contracts/src/`(`@rdk-moss/contracts`) | -| 错误 / 日志 | `packages/foundation/src/errors.ts`、`packages/foundation/src/logger.ts` | +- **Agent loop / 轮次控制 / 截断续写与空响应恢复**:`packages/core/src/loop/` +- **产品完成门(验收 / 验证 / 计划 / 审查账本 / best-of-n 修复)**:`packages/core/src/loop-hooks/`(经 `completionGate` 注入引擎;引擎不得反向依赖,见 `docs/design/2026-12-01-loop-engine-hooks.md`) +- **运行 loop(SDK 的 `runAgentLoop`、端口绑定、后台完成提醒读取)**:`packages/core/src/loop-hooks/run-agent-loop.ts`(引擎入口是 `runTurnEngine`,产品实现只经 `LoopPorts` 传入;见 `docs/design/2026-12-01-loop-engine-hooks.md`) +- **达标驱动自主执行(/goal 验收门)**:`packages/core/src/task/task-engine.ts`、`packages/core/src/task/acceptance-command.ts` +- **MossAgent / 配置 / 事件**:`packages/core/src/agent/` +- **工具注册与执行管线**:`packages/tools/src/builtin.ts`、`packages/core/src/tools/` +- **内置工具实现**:`packages/tools/src/*.ts`(`read_pdf` 在 `packages/tools/src/read-pdf.ts`,仅 Node 内置;`diagnostics` 在 `packages/tools/src/diagnostics.ts`) +- **设备契约 / SSH 连接 / 观测解析**:`packages/contracts/src/device.ts`、`packages/device/src/`、`packages/tools/src/device-tools.ts` +- **上下文 / 压缩 / token**:`packages/context/src/` +- **LLM provider / LLM 端口**:`packages/ai/src/provider/`、`packages/ai/src/llm/`(`@rdk-moss/ai`) +- **CLI / REPL / 命令**:`src/cli/`、`src/cli-main.ts` +- **不需要 agent 的命令(phase None / ConfigOnly / WorkspaceReady)**:`src/cli/command-phase.ts` 的 `runCommandWithoutAgent`;启动时的上下文窗口探测在 `src/cli/context-window-probe.ts` +- **CLI 壳(v0.22 起对齐 Claude Code / codex,动态 import)**:`src/cli/tui/`(app.ts 外壳 + transcript.ts 语法投影 + help.ts 键位表);与 CLI 共享的文案和文本工具在 `src/cli/ui-copy.ts`、`ui-text.ts`、`tool-label.ts` +- **MCP 客户端与宿主 API(v0.16 起;宿主 API 经 SDK 根导出)**:`packages/core/src/mcp/`、`packages/contracts/src/mcp.ts` +- **轻量 skills(v0.16 起)**:`packages/core/src/skills/` +- **斜杠命令**:`src/cli/commands/registry.ts` 只做分发;命令按子系统分文件(`session-commands`、`permission-commands` 等),契约在 `command-types.ts` +- **配置**:`src/cli/config.ts`(`resolveCliConfig`);`config-types`、`config-env`、`config-file`、`config-project-rules`、`config-values`、`config-audit`、`config-notices` +- **`moss config` 子命令**:`src/cli/config-commands.ts`(入口)、`config-set.ts`、`config-help.ts`、`config-init.ts`、`config-serialize.ts` +- **拆分巨型模块**:`node scripts/split/cli.mjs `,见 `docs/design/2026-12-01-cli-split.md` +- **设备风险分级 / 信任 / 审批文案 / 宿主审批端口**:`packages/foundation/src/safety/device-risk.ts`、`packages/foundation/src/safety/device-trust.ts`、`src/cli/device-safety-prompt.ts`、`packages/contracts/src/device.ts` +- **Hooks(事件 / 阻塞语义 / Stop 完成门 recipe / 技能自带)**:`src/cli/hooks.ts`、`docs/hooks.md`、`docs/hooks/stop-verified-completion.mjs`、`packages/core/src/skills/skill-hooks.ts` +- **显式记忆写路径(`/remember`)**:`src/cli/remember-command.ts`(写 `AGENTS.md`) +- **设备任务基准**:`bench/device-tasks/`、`scripts/bench-device.mjs`、`scripts/lib/device-bench*.mjs` +- **审批纯策略(allow/ask/deny,无 TTY/UI 依赖)**:`packages/core/src/agent/approval-policy.ts`、`packages/core/src/agent/permission-rules.ts`、`packages/foundation/src/safety/readonly-command.ts` +- **会话树读模型(消息父子、pathTo、descendantsOf)**:`packages/core/src/session/session-tree.ts` +- **命令要读写会话**:`src/cli/session-store.ts` 的 `createWorkspaceSessionStore`,不要自己 `new JsonlSessionStore`;见 `docs/design/2026-12-01-session-context-map.md` +- **模型元数据**:`src/cli/model-metadata.ts` 读 `model-catalog-snapshot.ts`(`scripts/generate-model-catalog.mjs` 刷新,`--check` 查过期);见 `docs/design/2026-12-01-model-catalog-snapshot.md` +- **统一 Task Runtime 协议(状态机/事件/快照)**:`packages/contracts/src/task-runtime.ts` +- **统一 Task Runtime 引擎/存储/裁决/能力发现**:`packages/core/src/task/`(engine、store、verdict、capability、agent-turn) +- **TUI 任务投影层(CLI 壳的读路径)**:`packages/core/src/task-runtime/`(artifacts + runtime 视图模型) +- **契约(prompt、soul、async-task)**:`packages/contracts/src/`(`@rdk-moss/contracts`) +- **错误 / 日志**:`packages/foundation/src/errors.ts`、`packages/foundation/src/logger.ts` **分层规则**:依赖只能指向内层(@rdk-moss/contracts → @rdk-moss/foundation → @rdk-moss/ai → @rdk-moss/device/@rdk-moss/context → @rdk-moss/core → @rdk-moss/tools → cli)。ESLint `moss/boundary-*` 规则(`eslint.config.mjs`)强制执行——新增 import 前先看边界规则,不要申请豁免除非是新的合法端口。 `packages/core/src/loop/` 是 turn 引擎:运行时不得 import session / subagent / task / agent / skills / prompts、工具执行器或后台进程注册表,