Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/sdk-task-intent-revisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions scripts/verify/stages/task-intent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
133 changes: 133 additions & 0 deletions scripts/verify/task-intent-readonly-tools.mjs
Original file line number Diff line number Diff line change
@@ -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 });
}
}
8 changes: 7 additions & 1 deletion src/core/loop/agent-loop-context-prep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -135,7 +136,12 @@ export function buildProviderToolDeclarations(
return {
name: tool.name,
description: toolDescriptionForModel(tool, lean),
parameters: compactSchemaNode(pruned) as Record<string, unknown>,
// 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<string, unknown>),
};
});
}
Expand Down
12 changes: 6 additions & 6 deletions src/core/session/task-intent-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' } },
},
Expand Down Expand Up @@ -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: {
Expand All @@ -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'],
Expand Down
10 changes: 5 additions & 5 deletions src/core/session/task-intent-turn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
]
: []),
]
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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.`,
};
}
}
Expand Down
Loading