Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
38 changes: 37 additions & 1 deletion docs/sdk-task-intent-revisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ 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.

Hosts can set `MossAgentConfig.validateTaskIntentDecision` when a proposed
decision must follow host-specific rules. The synchronous callback receives a
copy of the parsed `TurnDecision` with any runtime-bound fields filled in. Return
without a value to continue to the SDK's commit checks. Throw an error with
model-facing repair guidance to reject the decision and every business call in
the response. The input stays pending, and the existing bounded decision retry
gives the model a chance to submit a corrected declaration. Use a short error
message suitable for the model with sensitive details omitted.

`getTaskIntent` returns the committed state plus the current pending-input barrier. `getTaskIntentReceipt` distinguishes semantic commit from canonical message delivery. Input IDs are session-scoped and must never be reused for different text. After the inbox payload limit, processed inputs retain compact hash/receipt tombstones so retries remain idempotent; these small identity records grow with the session.

With `sessionInboxDir`, input, receipt and the retryable task projection share the existing locked, fsynced inbox journal. A projecting entry blocks actions until recovery completes. Deterministically rejected projections remain failed/pending and may be superseded by a valid new input, including a fresh task binding. Storage errors fail closed.
Expand All @@ -26,6 +35,16 @@ For native tasks, `applyTaskRevision` commits a revision with an idempotent `rev

Host callbacks outside normal tool execution must freeze the binding at callback creation and use `withTaskExecutionGuard(() => agent.assertTaskIntentCurrent(sessionKey, capturedIntent), action)`. Do not reread a new binding when an old callback wakes. Host evidence must also preserve its producing plan identity: stamping an old observation with the current revision does not make it current evidence.

Hosts that provision an isolated workspace can register `hooks.prepareToolBatch`.
The hook receives currently available, schema-checked business calls after the
runtime commits the pending decision. Use `assertCurrent()` before provisioning
and after each asynchronous step. The hook can update the host tool registry and
return a dispatch context with the new workspace. The SDK rechecks the decision,
resolves the updated tools and applies its usual approval and execution guards.
An answer or decision with no business calls skips the hook.

Each active constraint may have an exact author citation in `state.constraintSources`. A host can use that citation to bind an execution allowance to its originating input. `VersionedSessionStore.claimExecutionReceipt(scope, id)` atomically reserves a host action in a durable namespace. Call it when a validated operation is about to cross its dispatch boundary. A reservation only records admission and survives an uncertain or failed dispatch. Confirm the outcome from the transport or tool receipt.

The SDK defaults to the existing path when this option is absent. Studio enables it for ordinary runs, while fixed JSON execution profiles retain their own protocol.

Verification: `npm run verify` includes the `task-intent` stage, which exercises a scripted provider, durable recovery and native task revision/acceptance. These offline probes do not measure model interpretation accuracy or real-device behavior.
Expand All @@ -46,10 +65,27 @@ identity. Close the agent before closing a store owned by the host.
- `/compact` prepares or selects a source-checked checkpoint. It preserves
original source rows. `MossAgent.listContextSources` can inspect them after
a restart. Imported sessions can only retain messages still present on disk.
- Hosts can call `readContextToolEvidence(store.snapshot(sessionKey), query)` to
retrieve a bounded excerpt from an original tool receipt. Resolve the session
and its owner on the host. The query accepts a source ID, a result block
index, an offset and an optional literal match. The result carries the
context revision and original tool call ID. A receipt from an earlier
execution remains historical evidence for that execution.
- Hosts that switch the active workspace within a session can call
`store.enterContextScope(sessionKey, scopeId)` with an identity selected by the
host. Switching starts a new revision and hides the previous workspace's
sources, corrections, claims and checkpoints from the next model request.
The original rows remain in `sourceMessages`. The store rejects scope changes
while an input is still pending. `activeContextScope` returns a scope identity
and revision that a host can include in a context handoff's `scopeCheck` to
reject a transfer captured before either session changed scope.

The request pipeline progressively adjusts the output reservation, shortens old
tool results, prepares checkpoints in the background, reuses compatible
checkpoints, or performs bounded synchronous summarization. Provider-independent
checkpoints, or performs bounded synchronous summarization. It keeps the latest
tool result batch intact when it fits. If that batch still prevents a request,
the projection sends source-linked excerpts with the same tool call IDs. The
original results remain available in the archive. Provider-independent
admission uses a conservative serialized-size estimate. Provider-reported
overflow triggers a bounded retry with a smaller budget. Structured summaries
are historical data, and do not authorize work or commit acceptance.
Expand Down
21 changes: 21 additions & 0 deletions scripts/verify/assistant-live-text.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ const cases = [
'- RDK-X5 状态正常。\n- 第二个条目正常。',
'```text\nname=stream-check\nstatus=ready\n```\n代码说明继续输出。',
'普通路径 https://example.test/docs 之后继续写作。',
'可行,而且板子上已经有路径。要看你想要哪种「YOLO」。\n\n|项|状态|\n|---|:---:|\n|BPU|正常|',
'|项|状态|\n|---|---|\n|password="full credential sample"|已掩码|',
'先看「板端状态」。\n- -----BEGIN PRIVATE KEY-----\nABCdef12345\n-----END PRIVATE KEY-----',
'普通输出路径为 /tmp/stream-check/result.txt。针对 RDK-X5 继续说明。',
'\n\n 原始前导空白用于校验纯脱敏函数的原文一致性。',
'name=stream-check status=ready password="full credential sample"',
Expand Down Expand Up @@ -224,6 +227,24 @@ assert.equal(
);
assert.equal(formatted.flush(), '');

const table = createAssistantTextRedactor();
const tableChunks = [
'结论:可行。要看你想要哪种',
'「YOLO」。\n\n',
'|项|状态|\n',
'|---|:---:|\n',
'|BPU|正常|\n',
'下一步可用静态图。',
];
let liveTable = '';
for (const chunk of tableChunks) {
const delta = table.push(chunk);
assert.ok(delta, `the stream stalled on ${JSON.stringify(chunk)}`);
liveTable += delta;
}
assert.equal(liveTable, tableChunks.join(''));
assert.equal(table.flush(), '');

const normalized = createMossAgentLoopEventAdapter();
normalized.onMiniEvent({ type: 'turn_start', turn: 1 });
assert.deepEqual(normalized.onMiniEvent({ type: 'message_delta', delta: '\n\n ' }), []);
Expand Down
177 changes: 176 additions & 1 deletion scripts/verify/task-intent-revisions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ const { MossAgent } = await import(pathToFileURL(path.join(dist, 'core/agent/mos
const { InMemorySessionStore } = await import(
pathToFileURL(path.join(dist, 'core/session/session.js')).href
);
const { VersionedSessionStore } = await import(
pathToFileURL(path.join(dist, 'core/session/versioned-session-store.js')).href
);
const workspace = await fs.mkdtemp(path.join(os.tmpdir(), 'moss-intent-'));
const agents = [];
const validationStore = new VersionedSessionStore(path.join(workspace, 'validation.sqlite'));

function frame(options) {
const lines = options.systemPrompt.split('\n');
Expand Down Expand Up @@ -106,6 +110,133 @@ function register(agent, name, execute) {
}

try {
const workspaceSteps = [];
const admittedWorkspace = path.join(workspace, 'admitted');
const admitted = createAgent(
(request, count) => {
if (count > 1) return response(text('Workspace verified.'));
return response(declaration(frame(request)), toolCall('workspace_probe'));
},
{
hooks: {
prepareToolBatch: async ({ calls, context, assertCurrent }) => {
assertCurrent();
assert.deepEqual(
calls.map((call) => call.name),
['workspace_probe']
);
assert.equal(admitted.agent.getTaskIntent('workspace-admission').disposition, 'execute');
assert.equal(
admitted.agent.getTaskIntentReceipt('workspace-admission', 'workspace-input').status,
'committed'
);
workspaceSteps.push('admit');
admitted.agent.tools.remove('workspace_probe');
register(admitted.agent, 'workspace_probe', async (_input, ctx) => {
assert.equal(ctx.workspaceDir, admittedWorkspace);
workspaceSteps.push('execute');
return 'Verified the admitted workspace.';
});
return { ...context, workspaceDir: admittedWorkspace };
},
},
}
);
register(admitted.agent, 'workspace_probe', async () => {
workspaceSteps.push('stale tool');
return 'This tool was replaced before dispatch.';
});
await admitted.agent.chat('workspace-admission', 'Verify the project', {
userInput: { id: 'workspace-input' },
taskFlow: false,
});
assert.deepEqual(workspaceSteps, ['admit', 'execute']);
console.log(
'PASS tool batch preparation observes committed intent and replaces dispatch context'
);

const session = 'host-validation';
const hostInputId = 'host-source-input';
const literal = 'uname -m';
const hostInput = `Run this exact command once: ${literal}`;
const repair = 'Quote only the exact command literal';
const validConstraint = `device_command_once:${literal}`;
const proposedQuotes = [];
const dispatched = [];
const validated = createAgent(
(request, count) => {
if (count === 3) return response(text('Checked the requested architecture.'));
if (count === 2) {
assert.match(JSON.stringify(request.messages), new RegExp(repair));
const pending = validated.agent.getTaskIntent(session);
assert.equal(pending.pending, true);
assert.equal(pending.processedSeq, 0);
assert.deepEqual(pending.state.constraints, []);
assert.deepEqual(dispatched, []);
assert.equal(validated.agent.getTaskIntentReceipt(session, hostInputId).status, 'pending');
}
const quote = count === 1 ? hostInput : literal;
return response(
{
type: 'tool_use',
id: `validated-decision-${count}`,
name: 'turn_decision',
input: {
disposition: 'execute',
plan: ['Check architecture'],
changes: [
{
field: 'constraints',
operation: 'add',
value: validConstraint,
messageId: hostInputId,
quote,
},
],
},
},
toolCall('validate_action', `validated-action-${count}`)
);
},
{
sessionStore: validationStore,
validateTaskIntentDecision(decision) {
assert.equal(decision.baseRevision, 0);
assert.equal(decision.inputSeq, 1);
assert.deepEqual(decision.messageIds, [hostInputId]);
const change = decision.changes[0];
proposedQuotes.push(change.quote);
if (change.quote !== literal) throw new Error(repair);
change.value = 'ignored-by-the-runtime';
},
}
);
register(validated.agent, 'validate_action', async (_input, context) => {
const committed = validated.agent.getTaskIntent(session);
assert.equal(committed.pending, false);
assert.equal(committed.processedSeq, 1);
assert.equal(validated.agent.getTaskIntentReceipt(session, hostInputId).status, 'committed');
assert.deepEqual(committed.state.constraints, [validConstraint]);
assert.deepEqual(committed.state.constraintSources[validConstraint], {
messageId: hostInputId,
quote: literal,
});
dispatched.push(context.toolCallId);
return 'Architecture confirmed by the probe.';
});
const validatedResult = await validated.agent.chat(session, hostInput, {
userInput: { id: hostInputId },
taskFlow: false,
maxTurns: 5,
});
assert.deepEqual(proposedQuotes, [hostInput, literal]);
assert.deepEqual(dispatched, ['validated-action-2']);
assert.equal(validated.provider.calls, 3);
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'
);

const starts = [];
const { agent, provider } = createAgent((request, count) => {
const f = frame(request);
Expand Down Expand Up @@ -253,7 +384,16 @@ try {
console.log('PASS input during receipt persistence prevents stale answer publication');

let illegalStarts = 0;
const invalid = createAgent(() => response(toolCall('illegal')));
const invalid = createAgent((request, count) => {
if (count === 2) {
assert.deepEqual(
request.tools.map(({ name }) => name),
['turn_decision']
);
assert.equal(request.toolChoice, 'required');
}
return response(toolCall('illegal'));
});
register(invalid.agent, 'illegal', async () => {
illegalStarts++;
return 'should not execute';
Expand All @@ -268,6 +408,40 @@ try {
assert.equal(held.stopReason, 'task_intent_hold');
console.log('PASS missing declaration blocks all actions with bounded repair');

let recoveredStarts = 0;
const recovered = createAgent((request, count) => {
if (count === 1) return response(toolCall('recovered_action'));
if (count === 2) {
assert.deepEqual(
request.tools.map(({ name }) => name),
['turn_decision']
);
return response(declaration(frame(request), 'execute'));
}
if (count === 3) {
assert(request.tools.some(({ name }) => name === 'recovered_action'));
return response(toolCall('recovered_action'));
}
return response(text('Verified after the decision repair.'));
});
register(recovered.agent, 'recovered_action', async () => {
recoveredStarts++;
return 'verified';
});
await recovered.agent.chat('decision-repair', 'Recover the pending task', {
userInput: { id: 'decision-repair-1' },
taskFlow: false,
maxTurns: 5,
});
assert.equal(recoveredStarts, 1);
assert.equal(
recovered.agent.getTaskIntentReceipt('decision-repair', 'decision-repair-1').status,
'committed'
);
console.log(
'PASS a failed declaration can repair and execute without replaying its original tool call'
);

const raceStarts = [];
let race;
race = createAgent((request, count) => {
Expand Down Expand Up @@ -347,5 +521,6 @@ try {
console.log('PASS restart persistence, receipt dedupe, pending-input barrier');
} finally {
await Promise.allSettled(agents.map((agent) => agent.close()));
validationStore.close();
await fs.rm(workspace, { recursive: true, force: true });
}
43 changes: 43 additions & 0 deletions scripts/verify/task-intent-store.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { VersionedSessionStore } from '../../dist/core/session/versioned-session-store.js';
import { TaskIntentCoordinator } from '../../dist/core/session/task-intent-coordinator.js';
import {
loadSessionInbox,
Expand Down Expand Up @@ -68,6 +69,48 @@ try {
}
console.log('PASS correction during acceptance environment setup prevents process startup');
}
{
const authorizationInbox = path.join(workspace, 'authorization.json');
const authorization = new TaskIntentCoordinator(port(authorizationInbox), workspace);
authorization.admit({ id: 'action-1', text: 'Run exactly uname -a once' });
const authorizationBatch = await authorization.capture();
const change = {
field: 'constraints',
operation: 'add',
value: 'example:uname -a',
messageId: 'action-1',
quote: 'uname -a',
};
await authorization.commit(
authorizationBatch,
proposal(authorizationBatch, 'execute', [change])
);
const recovered = new TaskIntentCoordinator(port(authorizationInbox), workspace);
assert.deepEqual((await recovered.capture()).snapshot.state.constraintSources?.[change.value], {
messageId: 'action-1',
quote: 'uname -a',
});
recovered.admit({ id: 'action-remove', text: 'Remove the uname -a permission' });
const removal = await recovered.capture();
await recovered.commit(
removal,
proposal(removal, 'answer', [{ ...change, operation: 'remove', messageId: 'action-remove' }])
);
assert.equal(
(await recovered.capture()).snapshot.state.constraintSources?.[change.value],
undefined
);
const db = path.join(workspace, 'execution.sqlite');
const firstStore = new VersionedSessionStore(db);
assert.equal(firstStore.claimExecutionReceipt('session', 'action-1'), true);
firstStore.close();
const restartedStore = new VersionedSessionStore(db);
assert.equal(restartedStore.claimExecutionReceipt('session', 'action-1'), false);
assert.equal(restartedStore.claimExecutionReceipt('other-session', 'action-1'), true);
assert.deepEqual((await restartedStore.loadDeliverySnapshot('session')).deliveryIds, []);
restartedStore.close();
console.log('PASS active constraint provenance and durable once-only action admission');
}
const file = path.join(workspace, 'receipt.json');
const a = new TaskIntentCoordinator(port(file), workspace);
const b = new TaskIntentCoordinator(port(file), workspace);
Expand Down
Loading
Loading