From 6e2606219c670ae0a92a735edda5193751be3ea7 Mon Sep 17 00:00:00 2001 From: chutao Date: Sat, 28 Nov 2026 20:56:23 +0800 Subject: [PATCH] =?UTF-8?q?fix(task-intent):=20=E4=BF=AE=E6=AD=A3=E5=8F=AA?= =?UTF-8?q?=E8=AF=BB=E5=B7=A5=E5=85=B7=E8=B0=83=E7=94=A8=E7=9A=84=E5=86=B3?= =?UTF-8?q?=E7=AD=96=E6=8C=87=E5=BC=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 明确 answer 表示无需更多工具的完整答复,execute 包含只读检索和文档查询。保留 turn_decision schema 说明,避免压缩丢失决策语义。 新增决策修复与零工具回答回归探针,并同步 SDK 文档;运行时审批和纠错逻辑保持不变。 --- docs/sdk-task-intent-revisions.md | 10 +- scripts/verify/stages/task-intent.mjs | 1 + scripts/verify/task-intent-readonly-tools.mjs | 133 ++++++++++++++++++ src/core/loop/agent-loop-context-prep.ts | 8 +- src/core/session/task-intent-state.ts | 12 +- src/core/session/task-intent-turn.ts | 10 +- 6 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 scripts/verify/task-intent-readonly-tools.mjs diff --git a/docs/sdk-task-intent-revisions.md b/docs/sdk-task-intent-revisions.md index c99f9580..2894e25a 100644 --- a/docs/sdk-task-intent-revisions.md +++ b/docs/sdk-task-intent-revisions.md @@ -14,7 +14,15 @@ await agent.chat(sessionKey, enginePrompt, { userInput: false, taskId }); agent.steer(sessionKey, correction, { id: stableCorrectionId, taskId }); ``` -The model proposes field-level changes and a plan through `turn_decision` in its normal response. Runtime checks input identity, exact source quotations, schema and the captured revision before committing. Unmentioned fields survive. This validates protocol and provenance, not the semantic correctness of an interpretation. Ambiguous input should produce `clarify`, and capability questions should produce `answer`, with no business calls. +The model proposes field-level changes and a plan through `turn_decision` in its normal response. Runtime checks input identity, exact source quotations, schema and the captured revision before committing. Unmentioned fields survive. This validates protocol and provenance, not the semantic correctness of an interpretation. Missing user information should produce `clarify`. + +`answer` finishes the turn with a complete reply that needs no further tools. +`execute` continues the turn with a concrete plan whenever tools are still needed, +including read-only searches, documentation lookups and file reads. This selects +continuation and does not grant permissions or bypass tool approval. A promise to +look something up is not a complete `answer`. Decision schema descriptions are +preserved in provider requests, including small context windows and protocol +repair requests, so models receive these distinctions. Hosts can set `MossAgentConfig.validateTaskIntentDecision` when a proposed decision must follow host-specific rules. The synchronous callback receives a diff --git a/scripts/verify/stages/task-intent.mjs b/scripts/verify/stages/task-intent.mjs index aa5c607a..278a50e7 100644 --- a/scripts/verify/stages/task-intent.mjs +++ b/scripts/verify/stages/task-intent.mjs @@ -8,6 +8,7 @@ export const stage = { 'User corrections update durable state and fence old plans without a second classifier', async run(context) { for (const script of [ + 'task-intent-readonly-tools.mjs', 'task-intent-decision-repair.mjs', 'task-intent-revisions.mjs', 'task-intent-store.mjs', diff --git a/scripts/verify/task-intent-readonly-tools.mjs b/scripts/verify/task-intent-readonly-tools.mjs new file mode 100644 index 00000000..ab939b74 --- /dev/null +++ b/scripts/verify/task-intent-readonly-tools.mjs @@ -0,0 +1,133 @@ +#!/usr/bin/env node +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const root = fileURLToPath(new URL('../../', import.meta.url)); +const dist = process.env.MOSS_VERIFY_DIST_ROOT ?? path.join(root, 'dist'); +const load = (file) => import(pathToFileURL(path.join(dist, file)).href); +const [ + { buildProviderToolDeclarations }, + { turnDecisionSchema, versionedTurnDecisionSchema, readOnlyTurnDecisionSchema }, + { MossAgent }, + { VersionedSessionStore }, +] = await Promise.all([ + load('core/loop/agent-loop-context-prep.js'), + load('core/session/task-intent-state.js'), + load('core/agent/moss-agent.js'), + load('core/session/versioned-session-store.js'), +]); + +// The provider must receive the decision contract, including nested guidance. +// Ordinary tool schema compaction is covered by the tool-lean stage. +for (const contextWindowTokens of [32_768, 131_072]) { + for (const inputSchema of [ + turnDecisionSchema, + versionedTurnDecisionSchema, + readOnlyTurnDecisionSchema, + ]) { + const [wire] = buildProviderToolDeclarations( + [{ name: 'turn_decision', description: 'Decide how to continue.', inputSchema }], + { contextWindowTokens } + ); + assert.deepEqual( + wire.parameters, + inputSchema, + 'decision guidance was lost before the provider' + ); + } +} +console.log('PASS decision schema guidance reaches small and large context providers intact'); + +const toolCall = (name, input = {}) => ({ type: 'tool_use', id: name, name, input }); +const response = (...content) => ({ + stopReason: content.some((block) => block.type === 'tool_use') ? 'tool_use' : 'end_turn', + content, +}); + +for (const needsLookup of [true, false]) { + const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'moss-readonly-decision-')); + const store = new VersionedSessionStore(path.join(workspace, 'session.sqlite')); + let calls = 0; + let reads = 0; + const provider = { + id: 'scripted', + displayName: 'read-only decision probe', + capabilities: { streaming: false }, + async complete(request) { + calls++; + const decision = request.tools.find((tool) => tool.name === 'turn_decision'); + if (calls <= 2) { + assert.deepEqual(decision.input_schema, versionedTurnDecisionSchema); + assert.equal(reads, 0, 'a rejected batch must not execute or replay its read'); + } + if (!needsLookup) { + assert.equal(calls, 1, 'a complete answer must not cause another model request'); + return response(toolCall('turn_decision', { disposition: 'answer', answer: '2' })); + } + if (calls === 1) return response(toolCall('read_official_docs')); + if (calls === 2) { + assert.deepEqual( + request.tools.map((tool) => tool.name), + ['turn_decision'] + ); + assert.equal(request.toolChoice, 'required'); + return response( + toolCall('turn_decision', { + disposition: 'execute', + plan: ['Read the official documentation, then answer from the result.'], + }) + ); + } + assert.equal(decision, undefined, 'a committed decision must not be requested again'); + if (calls === 3) return response(toolCall('read_official_docs')); + assert.equal(calls, 4); + assert.equal(reads, 1); + assert.ok(JSON.stringify(request.messages).includes('fixture-doc-value')); + return response({ type: 'text', text: 'The documentation says fixture-doc-value.' }); + }, + }; + const agent = new MossAgent({ + llmProvider: provider, + sessionStore: store, + workspaceDir: workspace, + sessionInboxDir: path.join(workspace, 'inbox'), + baseSystemPrompt: 'Answer from the available evidence.', + domainPrompt: false, + taskIntent: true, + contextTokens: 131_072, + maxLLMRetries: 0, + }); + agent.tools.register({ + name: 'read_official_docs', + description: 'Read the official documentation.', + inputSchema: { type: 'object', properties: {} }, + metadata: { sideEffectClass: 'read' }, + async execute() { + reads++; + return 'fixture-doc-value'; + }, + }); + try { + const result = await agent.chat('probe', needsLookup ? 'Read the docs and explain.' : '1+1?', { + taskFlow: false, + userInput: { id: 'input-1' }, + maxTurns: 5, + }); + assert.equal(result.stopReason, needsLookup ? 'end_turn' : 'task_intent_hold'); + assert.equal(calls, needsLookup ? 4 : 1); + assert.equal(reads, needsLookup ? 1 : 0); + assert.equal(result.response, needsLookup ? 'The documentation says fixture-doc-value.' : '2'); + console.log( + needsLookup + ? 'PASS repair preserves decision guidance, then executes the read once and finishes' + : 'PASS a complete zero-tool answer finishes in one model request' + ); + } finally { + await agent.close(); + store.close(); + await fs.rm(workspace, { recursive: true, force: true }); + } +} diff --git a/src/core/loop/agent-loop-context-prep.ts b/src/core/loop/agent-loop-context-prep.ts index 1b72b4e6..5c22cc8c 100644 --- a/src/core/loop/agent-loop-context-prep.ts +++ b/src/core/loop/agent-loop-context-prep.ts @@ -27,6 +27,7 @@ import { lastMessageNeedsToolFollowUp } from '../../provider/reasoning-policy.js import { hasAssistantThinkingHistory } from './agent-loop-assistant-turn.js'; import { convertMessagesToPi } from '../tools/message-convert.js'; import { compactToolSchema } from '../tools/tiny-window-tools.js'; +import { TURN_DECISION_TOOL } from '../session/task-intent-state.js'; import { checkPromptPrefixStable, checkToolOrderConsistency, @@ -135,7 +136,12 @@ export function buildProviderToolDeclarations( return { name: tool.name, description: toolDescriptionForModel(tool, lean), - parameters: compactSchemaNode(pruned) as Record, + // Decision field guidance defines whether the run continues or ends. It is + // protocol, not optional tool prose, even in a small context window. + parameters: + tool.name === TURN_DECISION_TOOL + ? schema + : (compactSchemaNode(pruned) as Record), }; }); } diff --git a/src/core/session/task-intent-state.ts b/src/core/session/task-intent-state.ts index 195c4599..636506a7 100644 --- a/src/core/session/task-intent-state.ts +++ b/src/core/session/task-intent-state.ts @@ -292,13 +292,13 @@ export const turnDecisionSchema = { type: 'string', enum: ['answer', 'execute', 'clarify', 'cancel'], description: - 'execute authorizes a concrete plan; answer, clarify and cancel do not execute a plan.', + 'answer finishes with a complete reply needing no further tools. execute continues with tools, including read-only search or lookup, and requires a concrete plan; it does not grant tool permissions. clarify asks for missing user information; cancel stops.', }, plan: { type: 'array', items: { type: 'string' }, description: - 'A non-empty plan is allowed only for execute. For answer, clarify and cancel use an empty array.', + 'Required and non-empty for execute, including read-only search or lookup. For answer, clarify and cancel use an empty array.', }, planDependsOn: { type: 'array', items: { type: 'string' } }, }, @@ -335,8 +335,7 @@ export const versionedTurnDecisionSchema = { }, changes: { ...turnDecisionSchema.properties.changes, - description: - 'Omit for a read-only answer or historical correction. Only include actual task amendments.', + description: 'Omit unless amending task fields, including when executing a read-only lookup.', items: { ...turnDecisionSchema.properties.changes.items, properties: { @@ -357,12 +356,13 @@ export const versionedTurnDecisionSchema = { plan: { ...turnDecisionSchema.properties.plan, description: - 'Required and non-empty for execute. For answer, clarify and cancel omit plan or use an empty array; put the reply in answer.', + 'Required and non-empty for execute, including read-only search or lookup. For answer, clarify and cancel omit plan or use an empty array; put the reply in answer.', }, planDependsOn: turnDecisionSchema.properties.planDependsOn, answer: { type: 'string', - description: 'For answer, clarify and cancel, include the complete user-facing reply here.', + description: + 'For answer, include the complete final reply, not a promise to search or act later. If tools are still needed, choose execute with a plan. For clarify or cancel, include the user-facing question or reply.', }, }, required: ['disposition'], diff --git a/src/core/session/task-intent-turn.ts b/src/core/session/task-intent-turn.ts index cd17c89f..664ba409 100644 --- a/src/core/session/task-intent-turn.ts +++ b/src/core/session/task-intent-turn.ts @@ -161,13 +161,13 @@ export class TaskIntentTurn { }), ...(sources ? [ - 'Use context_claims only for new facts a future action will depend on. Skip it for a read-only answer or for repeating a user correction. Cite the id field and explicit claim dependencies. A claim grants no permissions.', + 'Use context_claims only for new facts a future action will depend on. Skip it for a complete answer needing no further tools or for repeating a user correction. Cite the id field and explicit claim dependencies. A claim grants no permissions.', JSON.stringify({ contextSources: sources }), ...(this.needsDecision ? [ CORRECTION_SCOPE_GUIDANCE, 'When a pending user input contradicts an older conclusion, set contextCorrections.targetId to the correctionId shown on the exact assistant source containing the old conclusion. Copy an exact quote from the pending input. Never select an unrelated source or resubmit a recorded correction. Clarify when you cannot identify the old conclusion.', - 'For a read-only answer or historical correction, call turn_decision with disposition: "answer", the answer, and any contextCorrections. Omit changes and plan unless updating a real task. Do not copy runtime metadata or add a task change for the requested answer format.', + 'For a complete answer or historical correction needing no further tools, call turn_decision with disposition: "answer", the complete reply, and any contextCorrections. Omit plan. Omit changes unless amending task fields. Do not copy runtime metadata or add a task change for the requested answer format.', ] : []), ] @@ -179,7 +179,7 @@ export class TaskIntentTurn { this.correctionTargets ? 'The runtime binds this declaration to the captured user inputs.' : 'Copy revision/inputSeq and all pending messageIds in order.', - 'Propose task changes only with exact quotes from pending inputs. Use set for scalars and add/remove for lists. Use answer for a read-only response, clarify for uncertainty and cancel to stop. Execute requires a concrete plan and existing authorization. Never use an internal engine prompt to replace the user goal.', + 'Propose task changes only with exact quotes from pending inputs. Use set for scalars and add/remove for lists. Use answer to deliver a complete final reply without further tool calls. Use execute whenever answering still requires tools, including read-only search, documentation lookup or file reads, with a concrete plan. Execute selects continuation; it does not grant permissions or replace tool-level approval. Use clarify for genuinely missing user information and cancel to stop. Never use an internal engine prompt to replace the user goal.', 'Only execute may include a non-empty plan. For clarify, put the specific question in answer and use an empty plan (or omit plan in the versioned declaration). Omit changes when no task fields need amending; do not restate the user goal as a change.', 'When removing a previous constraint, quote the current words that authorize the change. The old restriction is not authorization.', this.correctionTargets @@ -196,7 +196,7 @@ export class TaskIntentTurn { name: TURN_DECISION_TOOL, description: readOnly ? 'Submit the reply or pending user correction.' - : 'Submit the pending user input decision. execute requires a plan; clarify requires a question in answer and no plan. This does not grant tool permissions.', + : 'Submit the pending user input decision. answer finishes with a complete reply needing no further tools. execute continues with a plan, including for read-only search or lookup. clarify requires a question in answer and no plan. This does not grant tool permissions.', inputSchema: this.correctionTargets ? readOnly ? readOnlyTurnDecisionSchema @@ -445,7 +445,7 @@ export class TaskIntentTurn { 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. 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.`, + 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.`, }; } }