Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(bots): govern the turn — caps, compaction, real failure classes, outcome gate

Salman Qureshi9b71f235951e
diff --git a/src/bots/bot-manager.test.ts b/src/bots/bot-manager.test.ts
index dd257732..641e1e9c 100644
--- a/src/bots/bot-manager.test.ts
+++ b/src/bots/bot-manager.test.ts
@@ -345,7 +345,7 @@ describe('BotManager queue + turn lifecycle', () => {
await vi.waitFor(() => {
expect(systemPrompt).toContain(store.sandboxDir('pathfinder'));
expect(systemPrompt).toContain('_shared');
- expect(systemPrompt).toContain('even when not explicitly asked');
+ expect(systemPrompt).toContain('DATA other bots consume');
});
});
diff --git a/src/bots/bot-turn.test.ts b/src/bots/bot-turn.test.ts
index 1fd5a9d1..7d8a843a 100644
--- a/src/bots/bot-turn.test.ts
+++ b/src/bots/bot-turn.test.ts
@@ -245,3 +245,177 @@ describe('runBotTurn live thinking events', () => {
expect(secondRound.length).toBeGreaterThan(0);
});
});
+
+// ── ADR-020: governor, compaction, failure classes, outcome gate ──────────
+
+import { compactMessages, computeOutcome, wrapBotTools, isReadOnlyCommand, isTransientFailure, DEFAULT_TURN_LIMITS } from './bot-turn.js';
+
+describe('classifyFailure (ADR-020)', () => {
+ it('treats network cuts and empty streams as transient, unwrapping retry wrappers', () => {
+ expect(classifyFailure(new Error('terminated'))).toBe('provider_timeout');
+ expect(classifyFailure(new Error('The socket connection was closed unexpectedly'))).toBe('provider_timeout');
+ expect(classifyFailure(new Error('Generation was interrupted before completion (no finish signal from provider)'))).toBe('provider_timeout');
+ expect(classifyFailure(new Error('No output generated. Check the stream for errors.'))).toBe('provider_empty');
+ expect(classifyFailure(new Error('Failed after 3 attempts. Last error: Too many requests'))).toBe('provider_rate_limit');
+ expect(classifyFailure(new Error('Failed after 3 attempts. Last error: Internal server error'))).toBe('unknown_error');
+ expect(classifyFailure(new Error('No LLM providers available — configure ANTHROPIC_API_KEY'))).toBe('provider_unavailable');
+ for (const code of ['provider_timeout', 'provider_empty', 'provider_rate_limit']) expect(isTransientFailure(code)).toBe(true);
+ expect(isTransientFailure('provider_unavailable')).toBe(false);
+ });
+
+ it('surfaces the stream error instead of the generic "No output generated"', async () => {
+ mockedStreamText.mockImplementationOnce(() => ({
+ fullStream: (async function* () { yield { type: 'error', error: new Error('invalid_api_key: 401') }; })(),
+ text: Promise.reject(new Error('No output generated. Check the stream for errors.')),
+ finishReason: Promise.reject(new Error('No output generated. Check the stream for errors.')),
+ usage: Promise.resolve({}),
+ }) as any);
+ const out = await runBotTurn(turnInput());
+ expect(out.status).toBe('failed');
+ expect(out.error).toContain('invalid_api_key');
+ expect(out.reasonCode).toBe('provider_auth');
+ });
+});
+
+describe('compactMessages', () => {
+ const toolMsg = (id: string, value: string) => ({ role: 'tool', content: [{ type: 'tool-result', toolCallId: id, toolName: 'read_file', output: { type: 'text', value } }] });
+ it('keeps the newest results (capped) and stubs older ones', () => {
+ const big = 'x'.repeat(30_000);
+ const msgs = [
+ { role: 'user', content: 'go' },
+ toolMsg('a', 'old '.repeat(300)),
+ toolMsg('b', big),
+ toolMsg('c', 'recent'),
+ ];
+ const out: any[] = compactMessages(msgs, { keepRecentToolResults: 2, maxToolResultChars: 1000 });
+ expect(out[0]).toBe(msgs[0]);
+ expect(out[1].content[0].output.value).toContain('more chars trimmed from an earlier step');
+ expect(out[1].content[0].output.value.length).toBeLessThan(600);
+ expect(out[2].content[0].output.value).toContain('[…truncated');
+ expect(out[2].content[0].output.value.length).toBeLessThan(1100);
+ expect(out[3].content[0].output.value).toBe('recent');
+ // Never mutates the originals.
+ expect((msgs[2] as any).content[0].output.value).toBe(big);
+ });
+ it('is a no-op without tool results', () => {
+ const msgs = [{ role: 'user', content: 'hi' }];
+ expect(compactMessages(msgs, DEFAULT_TURN_LIMITS)).toBe(msgs);
+ });
+});
+
+describe('turn governor', () => {
+ it('stops a turn that exceeds the per-turn token cap and reports it as turn_budget, not an escalation', async () => {
+ let rounds = 0;
+ mockedStreamText.mockImplementation((opts: any) => {
+ rounds++;
+ // Each step burns 200k tokens; the cap is 300k.
+ opts.onStepFinish?.({ usage: { inputTokens: 200_000, outputTokens: 10 }, toolCalls: [{ toolName: 'read_file', toolCallId: 't1', input: { path: 'a' } }], toolResults: [{ toolCallId: 't1', output: { type: 'text', value: 'ok' } }] });
+ opts.onStepFinish?.({ usage: { inputTokens: 200_000, outputTokens: 10 }, toolCalls: [], toolResults: [] });
+ const aborted = opts.abortSignal?.aborted;
+ return streamedResult({ text: aborted ? '' : 'still going', finishReason: aborted ? 'other' : 'tool-calls' } as any);
+ });
+ const out = await runBotTurn(turnInput({ trigger: 'cron', manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 2 } } }));
+ expect(out.status).toBe('failed');
+ expect(out.reasonCode).toBe('turn_budget');
+ expect(out.tokensIn).toBeGreaterThanOrEqual(300_000);
+ expect(rounds).toBe(1);
+ expect(out.output).toContain('300k-token cap');
+ });
+
+ it('honours a per-bot maxTokensPerTurn override', async () => {
+ mockedStreamText.mockImplementation((opts: any) => {
+ opts.onStepFinish?.({ usage: { inputTokens: 900, outputTokens: 10 }, toolCalls: [], toolResults: [] });
+ return streamedResult({ text: 'done', finishReason: 'stop' } as any);
+ });
+ const out = await runBotTurn(turnInput({ manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 3, maxTokensPerTurn: 500 } } }));
+ expect(out.reasonCode).toBe('turn_budget');
+ });
+});
+
+describe('outcome gate', () => {
+ const sandbox = { workspace: '/tmp/ws', shared: '/tmp/shared' };
+ it('classifies the trace: notes are none, outside writes and commands are actions, deliveries win', () => {
+ const ok = (name: string, arg?: string, task?: boolean) => ({ name, ok: true, arg, ...(task ? { task } : {}) });
+ expect(computeOutcome({ trace: [ok('read_file', '/x'), ok('write_file', '/tmp/shared/record.md')], deliveries: [], expects: 'work', text: 'Filed the record.', sandbox })).toBe('none');
+ expect(computeOutcome({ trace: [ok('write_file', '/home/u/site/index.html')], deliveries: [], expects: 'work', text: '', sandbox })).toBe('action');
+ expect(computeOutcome({ trace: [ok('run_command', 'ls -la && cmp a b')], deliveries: [], expects: 'work', text: '', sandbox })).toBe('none');
+ expect(computeOutcome({ trace: [ok('run_command', 'npm run build')], deliveries: [], expects: 'work', text: '', sandbox })).toBe('action');
+ expect(computeOutcome({ trace: [{ name: 'run_command', ok: false, arg: 'npm run build' }], deliveries: [], expects: 'work', text: '', sandbox })).toBe('none');
+ expect(computeOutcome({ trace: [ok('bot_send', 'crew-1', true)], deliveries: [], expects: 'work', text: '', sandbox })).toBe('delegated');
+ expect(computeOutcome({ trace: [], deliveries: ['/home/u/Documents/Mercury/Writer/2026-10-10 Piece.md'], expects: 'work', text: '', sandbox })).toBe('deliverable');
+ expect(computeOutcome({ trace: [], deliveries: [], expects: 'message', text: 'Here is my report.', sandbox })).toBe('message');
+ expect(computeOutcome({ trace: [], deliveries: [], expects: 'message', text: ' ', sandbox })).toBe('none');
+ expect(isReadOnlyCommand('cat a | grep b')).toBe(true);
+ expect(isReadOnlyCommand('cat a | tee b')).toBe(false);
+ });
+
+ it('nudges a work run that only wrote notes exactly once, then journals none + the false claim', async () => {
+ const prompts: string[] = [];
+ mockedStreamText.mockImplementation((opts: any) => {
+ prompts.push(opts.messages.at(-1).content);
+ opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'write_file', toolCallId: 'w', input: { path: '/tmp/shared/cycle-record.md', content: 'x' } }], toolResults: [{ toolCallId: 'w', output: { type: 'text', value: 'Wrote file' } }] });
+ return streamedResult({ text: 'Record filed and delivered.', finishReason: 'stop' } as any);
+ });
+ const out = await runBotTurn(turnInput({ trigger: 'cron', manifest: { id: 't', name: 'T', enabled: true, autonomy: { maxSteps: 3 } } }));
+ expect(out.status).toBe('completed');
+ expect(out.outcome).toBe('none');
+ expect(out.outcomeNudged).toBe(true);
+ expect(out.claimedWithoutAction).toBe(true);
+ expect(prompts).toHaveLength(2);
+ expect(prompts[1]).toContain('[outcome check]');
+ expect(out.toolCalls).toBe(2);
+ expect(out.steps).toBe(0); // the mock never fires onStepStart
+ });
+
+ it('does not nudge a check routine or a reply-contract run', async () => {
+ mockedStreamText.mockImplementation(() => streamedResult({ text: 'All quiet.', finishReason: 'stop' } as any));
+ const check = await runBotTurn(turnInput({ trigger: 'cron', expects: 'check' }));
+ expect(check.outcome).toBe('none');
+ expect(check.outcomeNudged).toBe(false);
+ const reply = await runBotTurn(turnInput({ trigger: 'chat' }));
+ expect(reply.outcome).toBe('message');
+ expect(mockedStreamText).toHaveBeenCalledTimes(2);
+ });
+
+ it('a delivery during the turn makes the outcome deliverable with the path recorded', async () => {
+ const deliver = { execute: async () => 'Delivered to /home/u/Documents/Mercury/T/2026-10-10 Piece.md — the owner\'s outputs zone.' } as any;
+ // The tool runs inside the stream (as the SDK would run it), so the
+ // wrapper's capture lands before the turn computes its outcome.
+ mockedStreamText.mockImplementation(((opts: any) => ({
+ fullStream: (async function* () {
+ const r = await opts.tools.bot_deliver.execute({ file: 'x.md' }, {});
+ opts.onStepFinish?.({ usage: { inputTokens: 10, outputTokens: 5 }, toolCalls: [{ toolName: 'bot_deliver', toolCallId: 'd', input: { file: 'x.md' } }], toolResults: [{ toolCallId: 'd', output: { type: 'text', value: r } }] });
+ yield { type: 'text-delta', text: 'Delivered.' };
+ })(),
+ text: Promise.resolve('Delivered.'),
+ finishReason: Promise.resolve('stop'),
+ usage: Promise.resolve({}),
+ })) as any);
+ const out = await runBotTurn(turnInput({ trigger: 'cron', tools: { bot_deliver: deliver } }));
+ expect(out.outcome).toBe('deliverable');
+ expect(out.deliverables).toEqual(['/home/u/Documents/Mercury/T/2026-10-10 Piece.md']);
+ expect(out.claimedWithoutAction).toBe(false);
+ });
+});
+
+describe('shared-folder write budget', () => {
+ const sandbox = { workspace: '/tmp/ws', shared: '/tmp/shared' };
+ const writes: string[] = [];
+ const write = { execute: async (args: any) => { writes.push(args.path); return `Wrote ${args.path}`; } } as any;
+ it('warns past the soft limit and refuses past the hard limit, but never limits the private workspace', async () => {
+ writes.length = 0;
+ const tools = wrapBotTools({ write_file: write }, { sandbox, limits: { ...DEFAULT_TURN_LIMITS, sharedWrites: { softFiles: 1, softBytes: 100, hardFiles: 2, hardBytes: 1000 } }, onDelivered: () => {} });
+ const a = await tools.write_file.execute!({ path: '/tmp/shared/a.md', content: 'x'.repeat(50) }, {} as any);
+ expect(String(a)).toBe('Wrote /tmp/shared/a.md');
+ const b = await tools.write_file.execute!({ path: '/tmp/shared/b.md', content: 'x'.repeat(60) }, {} as any);
+ expect(String(b)).toContain('[Note: this run has written 2 files');
+ const c = await tools.write_file.execute!({ path: '/tmp/shared/c.md', content: 'x' }, {} as any);
+ expect(String(c)).toMatch(/^Error: shared-folder write budget/);
+ expect(writes).toEqual(['/tmp/shared/a.md', '/tmp/shared/b.md']);
+ const p = await tools.write_file.execute!({ path: '/tmp/ws/notes.md', content: 'x'.repeat(5000) }, {} as any);
+ expect(String(p)).toBe('Wrote /tmp/ws/notes.md');
+ // Relative paths resolve against the private workspace, not the shared folder.
+ const r = await tools.write_file.execute!({ path: 'draft.md', content: 'x' }, {} as any);
+ expect(String(r)).toBe('Wrote draft.md');
+ });
+});
diff --git a/src/bots/bot-turn.ts b/src/bots/bot-turn.ts
index c5317650..a3371b0a 100644
--- a/src/bots/bot-turn.ts
+++ b/src/bots/bot-turn.ts
@@ -1,11 +1,13 @@
import { streamText, stepCountIs } from 'ai';
import type { Tool } from 'ai';
+import { isAbsolute, relative, resolve } from 'node:path';
import type { CapabilityRegistry } from '../capabilities/registry.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import type { TokenBudget } from '../utils/tokens.js';
import type { BaseProvider } from '../providers/base.js';
import { classifyStreamCompletion } from '../core/stream-completion.js';
import { stepsExhaustedPrompt } from '../core/completion-verdict.js';
+import { isFailedToolResult } from '../core/execute-guard.js';
import { MAX_AUTOMATIC_CONTINUATIONS } from '../core/execution-limits.js';
import { formatToolStep } from '../utils/tool-label.js';
import { logger } from '../utils/logger.js';
@@ -38,6 +40,41 @@ export type BotActivityEvent = {
textTail?: string;
};
+/**
+ * What a run is expected to leave behind. Computed by the manager from the
+ * trigger and the routine's declaration, never by the model:
+ * - work: a deliverable, an action, or a delegation (cron, self-schedule,
+ * manual runs). A run that only wrote notes is NOT done.
+ * - message: a delegated task whose reply text IS the result (crew → lead).
+ * - check: a monitoring routine that is allowed to find nothing to do.
+ */
+export type BotExpectedOutcome = 'work' | 'message' | 'check';
+
+/** What the tool trace proves the run did — the journal's `outcome`. */
+export type BotOutcome = 'deliverable' | 'action' | 'delegated' | 'message' | 'none';
+
+/** Hard per-turn limits (ADR-020). Overridable per bot via `autonomy`. */
+export interface BotTurnLimits {
+ /** Tokens (in + out) a single turn may spend before it is cut off. */
+ maxTokensPerTurn: number;
+ /** Wall-clock minutes a single turn may run. */
+ maxTurnMinutes: number;
+ /** Tool results kept verbatim in the context window; older ones are stubbed. */
+ keepRecentToolResults: number;
+ /** Any single tool result larger than this is truncated before the model sees it. */
+ maxToolResultChars: number;
+ /** Fleet-shared folder write budget per turn: notes are not work. */
+ sharedWrites: { softFiles: number; softBytes: number; hardFiles: number; hardBytes: number };
+}
+
+export const DEFAULT_TURN_LIMITS: BotTurnLimits = {
+ maxTokensPerTurn: 300_000,
+ maxTurnMinutes: 20,
+ keepRecentToolResults: 8,
+ maxToolResultChars: 24_000,
+ sharedWrites: { softFiles: 2, softBytes: 32 * 1024, hardFiles: 6, hardBytes: 128 * 1024 },
+};
+
export interface BotTurnInput {
manifest: BotManifest;
trigger: BotTrigger;
@@ -51,6 +88,8 @@ export interface BotTurnInput {
pollMail: () => BotTurnMail[];
/** Sandbox areas granted implicitly (rw+x): private workspace + fleet-shared folder. */
sandbox: { workspace: string; shared: string };
+ /** Where finals go (shown to the bot every turn); absent = legacy outputs zone. */
+ deliverablesDir?: string;
/** Skill roster text (native + the bot's own library); empty when none. */
skillsPrompt?: string;
/** Fleet hierarchy context (lead crew roster / crew membership); absent for solos. */
@@ -60,6 +99,9 @@ export interface BotTurnInput {
crew: Array<{ id: string; name: string; description?: string; state: string }>;
maxCrew: number;
};
+ /** Outcome contract for this run (default 'work'). */
+ expects?: BotExpectedOutcome;
+ limits?: Partial<BotTurnLimits>;
capabilities: CapabilityRegistry;
tools: Record<string, Tool>;
userMemory: UserMemoryStore | null;
@@ -70,6 +112,16 @@ export interface BotTurnInput {
onActivity?: (ev: BotActivityEvent) => void;
}
+/** One tool call as the trace saw it: name, whether it worked, where it wrote. */
+export interface BotToolTraceEntry {
+ name: string;
+ ok: boolean;
+ /** `path` / `command` / `target` argument, when the tool has one. */
+ arg?: string;
+ /** bot_send with task: true. */
+ task?: boolean;
+}
+
export interface BotTurnOutput {
status: 'completed' | 'failed' | 'halted' | 'paused';
output: string;
@@ -79,6 +131,20 @@ export interface BotTurnOutput {
toolsUsed: string[];
error?: string;
reasonCode?: string;
+ /** Wall-clock start of the turn itself (the job's createdAt is the enqueue time). */
+ startedAt: number;
+ steps: number;
+ toolCalls: number;
+ /** Largest single-step prompt the provider saw — the context-growth meter. */
+ peakInputTokens: number;
+ outcome: BotOutcome;
+ /** Paths of files delivered via bot_deliver this turn. */
+ deliverables: string[];
+ /** The reply claimed delivery/execution but the trace shows none. */
+ claimedWithoutAction: boolean;
+ /** The no-outcome nudge was issued (once per turn). */
+ outcomeNudged: boolean;
+ trace: BotToolTraceEntry[];
}
const MAX_STEPS_DEFAULT = 25;
@@ -88,15 +154,41 @@ const THINKING_EMIT_INTERVAL_MS = 300;
/** Rolling tail cap per field; surfaces render the tail bottom-anchored. */
const THINKING_TAIL_CHARS = 600;
+/** Steps allowed for the single no-outcome continuation round. */
+const NUDGE_STEPS = 8;
+
+/** File tools whose target path decides sandbox (notes) vs outside (action). */
+const FILE_WRITE_TOOLS: ReadonlySet<string> = new Set(['write_file', 'create_file', 'edit_file', 'delete_file']);
+/** Tools whose success IS an action regardless of arguments. */
+const ACTION_TOOLS: ReadonlySet<string> = new Set([
+ 'git_add', 'git_commit', 'git_push', 'create_pr', 'create_issue', 'github_api', 'use_skill', 'bot_spawn', 'bot_retire',
+]);
+/** run_command heads that only look: not an action. */
+const READ_ONLY_COMMANDS: ReadonlySet<string> = new Set([
+ 'ls', 'cat', 'head', 'tail', 'wc', 'grep', 'rg', 'find', 'stat', 'file', 'du', 'df', 'pwd', 'echo', 'date', 'which',
+ 'cmp', 'diff', 'md5', 'md5sum', 'sha1sum', 'sha256sum', 'shasum', 'test', 'true', 'false', 'printf', 'env', 'uname', 'tree', 'less', 'more',
+]);
+
+const CLAIM_PATTERN = /\b(delivered|filed|shipped|published|executed|committed|pushed|posted|sent|deployed|uploaded)\b/i;
+
/**
* One run of one bot: a fresh-context tool loop over the bot's own provider,
* persona, toolset, memory namespace, and fail-closed permission manager.
* Structurally mirrors SubAgent.run() minus the shared-registry hazards:
* every dependency here is already per-bot.
+ *
+ * Governed (ADR-020): a hard token and wall-clock cap per turn, tool results
+ * compacted as the context grows, a per-turn write budget on the shared
+ * folder, and an OUTCOME verdict computed from the tool trace — a run that
+ * only wrote notes gets one nudge to deliver or admit it, and is journaled
+ * as `none` if it still produced nothing.
*/
export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
- const { manifest, provider, capabilities, tools, tokenBudget, abortSignal } = input;
+ const { manifest, provider, capabilities, tokenBudget } = input;
const maxSteps = manifest.autonomy?.maxSteps ?? MAX_STEPS_DEFAULT;
+ const limits = resolveTurnLimits(manifest, input.limits);
+ const expects: BotExpectedOutcome = input.expects ?? defaultExpectation(input.trigger);
+ const startedAt = Date.now();
const system = buildBotSystemPrompt(input);
const messages: any[] = [];
@@ -113,12 +205,15 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
let tokensIn = 0;
let tokensOut = 0;
+ let peakInputTokens = 0;
let lastResult: any = null;
let stepsRemaining = maxSteps;
let budgetContinuations = 0;
let stepIndex = 0;
- const turnStartedAt = Date.now();
+ let outcomeNudged = false;
const toolsUsed = new Set<string>();
+ const trace: BotToolTraceEntry[] = [];
+ const deliveries: string[] = [];
const onActivity = input.onActivity;
const emit = (ev: { kind: BotActivityEvent['kind']; label: string; detail?: string; stepIndex: number; status?: BotActivityEvent['status']; elapsedMs?: number; reasoningTail?: string; textTail?: string }): void => {
if (!onActivity) return;
@@ -126,7 +221,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
onActivity({
botId: manifest.id,
jobId: input.jobId ?? '',
- elapsedMs: ev.elapsedMs ?? Date.now() - turnStartedAt,
+ elapsedMs: ev.elapsedMs ?? Date.now() - startedAt,
kind: ev.kind,
label: ev.label,
detail: ev.detail,
@@ -138,22 +233,54 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
} catch { /* activity feedback must never break a turn */ }
};
+ // Turn governor: a local abort the caps trip, chained to the caller's
+ // halt signal. The reason tells the two apart in the catch below.
+ const governor = new AbortController();
+ let governorReason: 'turn_budget' | 'turn_time' | null = null;
+ const trip = (reason: 'turn_budget' | 'turn_time'): void => {
+ if (governor.signal.aborted) return;
+ governorReason = reason;
+ governor.abort();
+ };
+ const onHalt = (): void => governor.abort();
+ if (input.abortSignal.aborted) governor.abort();
+ else input.abortSignal.addEventListener('abort', onHalt, { once: true });
+ const deadline = setTimeout(() => trip('turn_time'), limits.maxTurnMinutes * 60_000);
+ deadline.unref?.();
+ const halted = (): boolean => input.abortSignal.aborted;
+
+ const tools = wrapBotTools(input.tools, {
+ sandbox: input.sandbox,
+ limits,
+ onDelivered: (path) => deliveries.push(path),
+ });
+
+ const baseOutput = () => ({
+ tokensIn, tokensOut, toolsUsed: [...toolsUsed], startedAt, steps: stepIndex, toolCalls: trace.length,
+ peakInputTokens, deliverables: [...deliveries], outcomeNudged, trace: [...trace],
+ });
+
try {
emit({ kind: 'turn-start', stepIndex: 0, label: input.prompt ? input.prompt.slice(0, 80) : 'Checking inbox' });
- while (stepsRemaining > 0 && !abortSignal.aborted) {
+ while (stepsRemaining > 0 && !governor.signal.aborted) {
// streamText, not generateText: the deltas are the real-time feedback
// inside the bot's thread (reasoning + reply tails). Same options and
// step-count semantics; the result's final promises preserve the old
// result shape exactly (text/finishReason), so all classification below
// is unchanged.
+ let streamError: unknown = null;
const stream = streamText({
model: provider.getModelInstance(),
system,
messages,
tools,
stopWhen: stepCountIs(stepsRemaining),
- abortSignal,
+ abortSignal: governor.signal,
experimental_include: { requestBody: false },
+ // Context compaction: every step re-sends the whole conversation, so
+ // 25 steps of 60KB tool results is a multi-megatoken prompt. Keep
+ // the newest results verbatim (capped), stub the rest.
+ prepareStep: ({ messages: stepMessages }: any) => ({ messages: compactMessages(stepMessages, limits) }),
experimental_onStepStart: () => {
stepIndex++;
emit({ kind: 'step', stepIndex, label: `step ${stepIndex}` });
@@ -173,18 +300,21 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
elapsedMs: typeof durationMs === 'number' ? durationMs : undefined,
});
},
- onStepFinish: ({ usage, toolCalls }) => {
- if (abortSignal.aborted) return;
+ onStepFinish: ({ usage, toolCalls, toolResults }: any) => {
+ if (governor.signal.aborted) return;
stepsRemaining--;
if (usage) {
tokensIn += usage.inputTokens ?? 0;
tokensOut += usage.outputTokens ?? 0;
+ peakInputTokens = Math.max(peakInputTokens, usage.inputTokens ?? 0);
}
for (const tc of toolCalls ?? []) {
if (tc?.toolName) toolsUsed.add(String(tc.toolName));
+ trace.push(traceEntry(tc, (toolResults ?? []).find((r: any) => r?.toolCallId && r.toolCallId === tc?.toolCallId)));
}
const kIn = Math.round(tokensIn / 100) / 10;
emit({ kind: 'step', stepIndex, label: `step ${stepIndex} · ${kIn}k tok in` });
+ if (tokensIn + tokensOut > limits.maxTokensPerTurn) trip('turn_budget');
},
});
@@ -211,13 +341,24 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
} else if (part.type === 'start-step' && (reasoningTail || textTail)) {
reasoningTail += '\n\n';
textTail += '\n\n';
+ } else if (part.type === 'error') {
+ // The provider's real error. Without this, `stream.text` below
+ // throws the generic "No output generated" and the journal never
+ // learns it was an invalid key or a 429.
+ streamError = (part as any).error ?? streamError;
}
if (Date.now() - lastEmit >= THINKING_EMIT_INTERVAL_MS) flushThinking();
}
flushThinking();
- const [finalText, finishReason] = await Promise.all([stream.text, stream.finishReason]);
- const result = { text: finalText, finishReason };
+ let result: { text: string; finishReason: unknown };
+ try {
+ const [finalText, finishReason] = await Promise.all([stream.text, stream.finishReason]);
+ result = { text: finalText, finishReason };
+ } catch (err) {
+ throw streamError ?? err;
+ }
+ if (streamError && !result.text) throw streamError;
lastResult = result;
const completion = classifyStreamCompletion({
@@ -238,11 +379,11 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
// bounded auto-continuation: refill the budget and resume the SAME
// conversation in-process — the old path requeued the job and rebuilt
// the turn from scratch, discarding every completed step and re-burning
- // the budget redoing the first 25 steps. The per-bot daily token
- // budget remains the runaway guard; past the continuation bound the
- // paused return below still applies.
+ // the budget redoing the first 25 steps. The per-turn token cap is the
+ // runaway guard; past the continuation bound the paused return below
+ // still applies.
if (stepsRemaining <= 0 && (lastResult as any)?.finishReason === 'tool-calls') {
- if (!abortSignal.aborted && budgetContinuations < MAX_AUTOMATIC_CONTINUATIONS) {
+ if (!governor.signal.aborted && budgetContinuations < MAX_AUTOMATIC_CONTINUATIONS) {
budgetContinuations++;
logger.warn(
{ botId: manifest.id, rounds: budgetContinuations, budget: maxSteps },
@@ -257,7 +398,7 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
// Consume newly arrived mailbox messages before finishing, so a
// handoff delivered mid-turn is not lost to the next scheduling gap.
- if (!abortSignal.aborted && stepsRemaining > 0) {
+ if (!governor.signal.aborted && stepsRemaining > 0) {
const fresh = input.pollMail();
if (fresh.length > 0) {
for (const m of fresh) {
@@ -266,11 +407,27 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
continue;
}
}
+
+ // Outcome gate: the trace, not the reply, says whether work happened.
+ // A run expected to produce work that only read and wrote notes gets
+ // exactly one nudge — deliver now, or say plainly that nothing was
+ // done. Bounded like the execute guard; never a loop.
+ if (!governor.signal.aborted && expects === 'work' && !outcomeNudged
+ && computeOutcome({ trace, deliveries, expects, text: result.text, sandbox: input.sandbox }) === 'none') {
+ outcomeNudged = true;
+ emit({ kind: 'step', stepIndex, label: 'no deliverable yet — asking for one' });
+ messages.push({ role: 'user', content: noOutcomePrompt(input) });
+ stepsRemaining = Math.min(maxSteps, NUDGE_STEPS);
+ continue;
+ }
break;
}
- if (abortSignal.aborted) {
- return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
+ if (halted()) {
+ return { status: 'halted', output: 'Turn was halted.', outcome: 'none', claimedWithoutAction: false, ...baseOutput() };
+ }
+ if (governorReason) {
+ return governedFailure(governorReason, lastResult?.text, limits, baseOutput(), input, trace, deliveries, expects, emit, stepIndex);
}
// Step budget exhausted with tool calls still pending — pause, never
@@ -281,14 +438,16 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
return {
status: 'paused',
output: 'Step budget reached before the turn completed — remaining work continues next turn.',
- tokensIn,
- tokensOut,
- toolsUsed: [...toolsUsed],
reasonCode: 'step_budget',
+ outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),
+ claimedWithoutAction: false,
+ ...baseOutput(),
};
}
const output = (lastResult?.text || '').trim() || '(no text response)';
+ const outcome = computeOutcome({ trace, deliveries, expects, text: lastResult?.text ?? '', sandbox: input.sandbox });
+ const claimedWithoutAction = outcome === 'none' && CLAIM_PATTERN.test(output);
tokenBudget.recordUsage({
provider: provider.name,
@@ -299,37 +458,109 @@ export async function runBotTurn(input: BotTurnInput): Promise<BotTurnOutput> {
channelType: 'bot',
});
- emit({ kind: 'turn-end', stepIndex, label: 'completed', status: 'done' });
- return { status: 'completed', output, tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
+ emit({ kind: 'turn-end', stepIndex, label: outcome === 'none' && expects === 'work' ? 'completed — no deliverable' : 'completed', status: 'done' });
+ return { status: 'completed', output, outcome, claimedWithoutAction, ...baseOutput() };
} catch (err: any) {
- if (abortSignal.aborted) {
+ if (halted()) {
emit({ kind: 'turn-end', stepIndex, label: 'halted', status: 'done' });
- return { status: 'halted', output: 'Turn was halted.', tokensIn, tokensOut, toolsUsed: [...toolsUsed] };
+ return { status: 'halted', output: 'Turn was halted.', outcome: 'none', claimedWithoutAction: false, ...baseOutput() };
+ }
+ if (governorReason) {
+ return governedFailure(governorReason, lastResult?.text, limits, baseOutput(), input, trace, deliveries, expects, emit, stepIndex);
}
emit({ kind: 'turn-end', stepIndex, label: `failed: ${String(err?.message ?? err).slice(0, 80)}`, status: 'error' });
return {
status: 'failed',
output: `Turn failed: ${err?.message ?? String(err)}`,
- tokensIn,
- tokensOut,
- toolsUsed: [...toolsUsed],
error: err?.message ?? String(err),
reasonCode: classifyFailure(err),
+ outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),
+ claimedWithoutAction: false,
+ ...baseOutput(),
};
+ } finally {
+ clearTimeout(deadline);
+ input.abortSignal.removeEventListener('abort', onHalt);
}
}
+function governedFailure(
+ reason: 'turn_budget' | 'turn_time',
+ partialText: string | undefined,
+ limits: BotTurnLimits,
+ base: ReturnType<() => Omit<BotTurnOutput, 'status' | 'output' | 'outcome' | 'claimedWithoutAction'>>,
+ input: BotTurnInput,
+ trace: BotToolTraceEntry[],
+ deliveries: string[],
+ expects: BotExpectedOutcome,
+ emit: (ev: { kind: BotActivityEvent['kind']; label: string; stepIndex: number; status?: BotActivityEvent['status'] }) => void,
+ stepIndex: number,
+): BotTurnOutput {
+ const what = reason === 'turn_budget'
+ ? `the ${Math.round(limits.maxTokensPerTurn / 1000)}k-token cap for one turn`
+ : `the ${limits.maxTurnMinutes}-minute cap for one turn`;
+ // Token spend of a cut-off turn is still spend.
+ input.tokenBudget.recordUsage({
+ provider: input.provider.name,
+ model: input.provider.getModel(),
+ inputTokens: base.tokensIn,
+ outputTokens: base.tokensOut,
+ totalTokens: base.tokensIn + base.tokensOut,
+ channelType: 'bot',
+ });
+ emit({ kind: 'turn-end', stepIndex, label: `stopped — ${what}`, status: 'error' });
+ return {
+ status: 'failed',
+ output: `Turn stopped at ${what} (${base.steps} steps, ${base.toolCalls} tool calls).`
+ + (partialText ? `\n\nLast reply before the cut-off:\n${partialText.slice(0, 2000)}` : ''),
+ error: `turn limit: ${reason}`,
+ reasonCode: reason,
+ outcome: computeOutcome({ trace, deliveries, expects, text: '', sandbox: input.sandbox }),
+ claimedWithoutAction: false,
+ ...base,
+ };
+}
+
+/**
+ * The outcome contract when the caller did not set one: a conversation
+ * (chat, a bot's mail, a channel message) is answered by its reply; an
+ * unattended wake (cron, self-schedule, API) must produce work.
+ */
+export function defaultExpectation(trigger: BotTrigger): BotExpectedOutcome {
+ return trigger === 'cron' || trigger === 'api' || trigger === 'cloud' ? 'work' : 'message';
+}
+
+export function resolveTurnLimits(manifest: BotManifest, overrides?: Partial<BotTurnLimits>): BotTurnLimits {
+ const a = manifest.autonomy ?? {};
+ return {
+ ...DEFAULT_TURN_LIMITS,
+ ...(overrides ?? {}),
+ ...(a.maxTokensPerTurn ? { maxTokensPerTurn: a.maxTokensPerTurn } : {}),
+ ...(a.maxTurnMinutes ? { maxTurnMinutes: a.maxTurnMinutes } : {}),
+ sharedWrites: { ...DEFAULT_TURN_LIMITS.sharedWrites, ...(overrides?.sharedWrites ?? {}) },
+ };
+}
+
/** Map a provider/tool error to a typed reason code (retry vs permanent). */
export function classifyFailure(err: any): string {
- const msg = String(err?.message ?? err ?? '').toLowerCase();
+ let msg = String(err?.message ?? err ?? '').toLowerCase();
+ // Retry wrappers ("Failed after 3 attempts. Last error: …") carry the
+ // real cause after the colon — classify that, not the wrapper.
+ const inner = /last error:\s*(.+)$/s.exec(msg);
+ if (inner) msg = inner[1];
if (/rate.?limit|429|too many requests/.test(msg)) return 'provider_rate_limit';
// Network blips ARE transient — ECONNRESET (connection dropped mid-read)
// and friends used to fall through to unknown_error, so a plain
// connection blip went straight to the DLQ with a needs-you flag instead
// of retrying like every other transient failure. "timed out" (with a
- // space) is how several providers phrase a deadline miss — it also used to
- // fall through to unknown_error and land the turn in the DLQ.
- if (/timeout|timed out|etimedout|econnaborted|econnreset|econnrefused|epipe|enotfound|eai_again|getaddrinfo|fetch failed|socket hang up|network/.test(msg)) return 'provider_timeout';
+ // space) is how several providers phrase a deadline miss. "terminated" is
+ // undici's wording for a response body cut mid-stream; "socket connection
+ // was closed" is Node's. Both were 135 DLQ entries in one fleet.
+ if (/timeout|timed out|etimedout|econnaborted|econnreset|econnrefused|epipe|enotfound|eai_again|getaddrinfo|fetch failed|socket|terminated|network|interrupted before completion/.test(msg)) return 'provider_timeout';
+ // The SDK's "No output generated" means the stream ended before any step:
+ // a provider hiccup, not a permanent condition.
+ if (/no output generated/.test(msg)) return 'provider_empty';
+ if (/no llm providers available/.test(msg)) return 'provider_unavailable';
if (/permission denied|blocked command|no permission/.test(msg)) return 'permission_denied';
if (/api key|unauthorized|401|authentication/.test(msg)) return 'provider_auth';
if (/quota|billing|402/.test(msg)) return 'provider_quota';
@@ -339,9 +570,189 @@ export function classifyFailure(err: any): string {
/** Transient failures may retry; permanent ones go straight to the DLQ. */
export function isTransientFailure(reasonCode: string): boolean {
- return reasonCode === 'provider_rate_limit' || reasonCode === 'provider_timeout';
+ return reasonCode === 'provider_rate_limit' || reasonCode === 'provider_timeout' || reasonCode === 'provider_empty';
+}
+
+/**
+ * Turn-limit failures are terminal for the job but are NOT escalations: the
+ * bot was stopped by policy, not by a fault. Settled done, no DLQ, no
+ * "needs you" — the owner is told once (ADR-020).
+ */
+export function isTurnLimitFailure(reasonCode: string | undefined): boolean {
+ return reasonCode === 'turn_budget' || reasonCode === 'turn_time';
+}
+
+// ---- outcome verdict ------------------------------------------------------
+
+function traceEntry(toolCall: any, toolResult: any): BotToolTraceEntry {
+ const name = String(toolCall?.toolName ?? 'tool');
+ const inputArgs = (toolCall?.input ?? {}) as Record<string, unknown>;
+ const text = toolResultText(toolResult?.output);
+ const failedOutput = toolResult?.output?.type === 'error-text' || toolResult?.output?.type === 'error-json';
+ const ok = toolResult !== undefined && !failedOutput && !isFailedToolResult(text);
+ const arg = typeof inputArgs.path === 'string' ? inputArgs.path
+ : typeof inputArgs.command === 'string' ? inputArgs.command
+ : typeof inputArgs.target === 'string' ? inputArgs.target
+ : typeof inputArgs.file === 'string' ? inputArgs.file
+ : undefined;
+ return { name, ok, arg, ...(inputArgs.task === true ? { task: true } : {}) };
+}
+
+function toolResultText(output: any): string {
+ if (!output) return '';
+ if (output.type === 'text' || output.type === 'error-text') return String(output.value ?? '');
+ if (output.type === 'json' || output.type === 'error-json') {
+ try { return JSON.stringify(output.value ?? ''); } catch { return ''; }
+ }
+ if (typeof output === 'string') return output;
+ return '';
+}
+
+function insideAny(target: string, roots: string[]): boolean {
+ const abs = resolve(target.replace(/^~(?=$|\/|\\)/, process.env.HOME ?? ''));
+ return roots.some((root) => {
+ const rel = relative(resolve(root), abs);
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
+ });
+}
+
+export function isReadOnlyCommand(command: string): boolean {
+ const head = command.trim().split(/\s+/)[0]?.replace(/^.*\//, '') ?? '';
+ // A pipeline or chain with any non-read head is not read-only.
+ const heads = command.split(/\s*(?:\|\||&&|;|\|)\s*/).map((seg) => seg.trim().split(/\s+/)[0]?.replace(/^.*\//, '') ?? '');
+ return heads.every((h) => READ_ONLY_COMMANDS.has(h)) && READ_ONLY_COMMANDS.has(head);
+}
+
+/**
+ * What the run did, by evidence. Order matters: a delivery beats everything;
+ * an action outside the sandbox beats a delegation; `message` only counts
+ * when the run's contract is a reply.
+ */
+export function computeOutcome(input: {
+ trace: BotToolTraceEntry[];
+ deliveries: string[];
+ expects: BotExpectedOutcome;
+ text: string;
+ sandbox: { workspace: string; shared: string };
+}): BotOutcome {
+ if (input.deliveries.length > 0) return 'deliverable';
+ const roots = [input.sandbox.workspace, input.sandbox.shared];
+ for (const t of input.trace) {
+ if (!t.ok) continue;
+ if (ACTION_TOOLS.has(t.name)) return 'action';
+ if (FILE_WRITE_TOOLS.has(t.name) && t.arg && !insideAny(t.arg, roots)) return 'action';
+ if (t.name === 'run_command' && t.arg && !isReadOnlyCommand(t.arg)) return 'action';
+ }
+ if (input.trace.some((t) => t.ok && t.name === 'bot_send' && t.task)) return 'delegated';
+ if (input.expects === 'message' && input.text.trim().length > 0) return 'message';
+ return 'none';
+}
+
+function noOutcomePrompt(input: BotTurnInput): string {
+ const where = input.deliverablesDir ? ` into ${input.deliverablesDir}` : '';
+ return `[outcome check] This run has produced no deliverable and taken no action — only reads and notes in your sandbox. `
+ + `Notes are not work. Do ONE of these now, then stop:\n`
+ + `1. If you have a finished result, deliver it with bot_deliver${where} and name the file in your reply.\n`
+ + `2. If the task needs an action (a command, a change outside your sandbox, a delegation), do it.\n`
+ + `3. If there was genuinely nothing to do, reply with one line starting "Nothing to do:" and the reason. Do not write a record about it.`;
+}
+
+// ---- context compaction ---------------------------------------------------
+
+/**
+ * Keep the newest tool results verbatim (each capped), replace older ones
+ * with a short stub. The model can re-run a tool it still needs; it cannot
+ * afford to re-send 60KB of every file it ever read on every step.
+ */
+export function compactMessages(messages: any[], limits: Pick<BotTurnLimits, 'keepRecentToolResults' | 'maxToolResultChars'>): any[] {
+ const resultRefs: Array<{ mi: number; pi: number }> = [];
+ messages.forEach((m, mi) => {
+ if (m?.role !== 'tool' || !Array.isArray(m.content)) return;
+ m.content.forEach((p: any, pi: number) => {
+ if (p?.type === 'tool-result') resultRefs.push({ mi, pi });
+ });
+ });
+ if (resultRefs.length === 0) return messages;
+ const stubBefore = Math.max(0, resultRefs.length - limits.keepRecentToolResults);
+ const out = messages.slice();
+ resultRefs.forEach(({ mi, pi }, idx) => {
+ const part = out[mi].content[pi];
+ const text = toolResultText(part.output);
+ if (part.output?.type === 'content') return; // media parts: leave alone
+ let next: string | null = null;
+ if (idx < stubBefore) {
+ if (text.length > 400) {
+ next = `${text.slice(0, 400)}\n[…${text.length - 400} more chars trimmed from an earlier step — re-run ${part.toolName ?? 'the tool'} if you need it]`;
+ }
+ } else if (text.length > limits.maxToolResultChars) {
+ next = `${text.slice(0, limits.maxToolResultChars)}\n[…truncated ${text.length - limits.maxToolResultChars} chars]`;
+ }
+ if (next === null) return;
+ if (out[mi] === messages[mi]) out[mi] = { ...messages[mi], content: messages[mi].content.slice() };
+ out[mi].content[pi] = { ...part, output: { type: 'text', value: next } };
+ });
+ return out;
+}
+
+// ---- tool wrapping: delivery capture + shared-folder write budget ----------
+
+/**
+ * Wrap the bot's toolset so the turn can see what matters without parsing
+ * replies: deliveries (bot_deliver's destination) and writes into the
+ * fleet-shared folder (budgeted — the shared folder is for data other bots
+ * consume, not for narration; a soft limit warns, a hard limit refuses).
+ */
+export function wrapBotTools(
+ tools: Record<string, Tool>,
+ ctx: { sandbox: { workspace: string; shared: string }; limits: BotTurnLimits; onDelivered: (path: string) => void },
+): Record<string, Tool> {
+ const out: Record<string, Tool> = { ...tools };
+ const shared = { files: new Set<string>(), bytes: 0 };
+ const { sharedWrites } = ctx.limits;
+ type Exec = (args: any, options: any) => Promise<unknown>;
+ const wrap = (name: string, fn: (original: Exec, args: any, options: any) => Promise<unknown>): void => {
+ const original = tools[name];
+ if (!original || typeof original.execute !== 'function') return;
+ const exec = original.execute.bind(original) as Exec;
+ out[name] = { ...original, execute: (args: any, options: any) => fn(exec, args, options) } as Tool;
+ };
+
+ wrap('bot_deliver', async (exec, args, options) => {
+ const result = await exec(args, options);
+ const m = /^Delivered to (.+?) —/.exec(String(result ?? ''));
+ if (m) ctx.onDelivered(m[1]);
+ return result;
+ });
+
+ for (const name of ['write_file', 'create_file', 'edit_file']) {
+ wrap(name, async (exec, args, options) => {
+ const target = typeof args?.path === 'string' ? args.path : '';
+ const inShared = target && insideAny(resolve(ctx.sandbox.workspace, target), [ctx.sandbox.shared]);
+ if (!inShared) return exec(args, options);
+ const bytes = String(args?.content ?? args?.new_string ?? '').length;
+ const nextFiles = shared.files.has(target) ? shared.files.size : shared.files.size + 1;
+ if (nextFiles > sharedWrites.hardFiles || shared.bytes + bytes > sharedWrites.hardBytes) {
+ return `Error: shared-folder write budget for this run is used up (${shared.files.size} files, ${Math.round(shared.bytes / 1024)}KB). `
+ + `_shared is for data other bots consume, not for notes or records. Keep working notes in your private workspace, `
+ + `and deliver finished results with bot_deliver.`;
+ }
+ const result = await exec(args, options);
+ const text = String(result ?? '');
+ if (isFailedToolResult(text)) return result;
+ shared.files.add(target);
+ shared.bytes += bytes;
+ if (shared.files.size > sharedWrites.softFiles || shared.bytes > sharedWrites.softBytes) {
+ return `${text}\n\n[Note: this run has written ${shared.files.size} files / ${Math.round(shared.bytes / 1024)}KB to the shared folder. `
+ + `That is a lot for one run — the shared folder is for data other bots consume. Notes belong in your private workspace; finals go through bot_deliver.]`;
+ }
+ return result;
+ });
+ }
+ return out;
}
+// ---- system prompt --------------------------------------------------------
+
function buildBotSystemPrompt(input: BotTurnInput): string {
const { manifest } = input;
let prompt = `You are "${manifest.name}", a Mercury bot (id: ${manifest.id}).\n`;
@@ -368,14 +779,22 @@ function buildBotSystemPrompt(input: BotTurnInput): string {
prompt += `\n\nOperating rules:
- You run unattended: NEVER ask the user questions or wait for confirmation. If a required input is missing, state the assumption you are proceeding with.
- Actions you lack permission for are denied automatically (fail-closed). Do not attempt workarounds; report what you could not do.
-- Stay in your specialty; say so plainly when a request falls outside it.`;
+- Stay in your specialty; say so plainly when a request falls outside it.
+- Work, don't narrate: a run is judged by what it delivered or changed, not by what it wrote about itself. Do not write records, receipts, logs or status files about your own runs — Mercury keeps the journal. If there is nothing to do, say "Nothing to do:" and the reason, and stop.`;
// Sandbox: the bot's always-granted work areas (rw+x, no permission ask).
prompt += `\n\nSandbox (always granted — read, write, execute; no permission needed):
- Private workspace: ${input.sandbox.workspace} — your scratch area: drafts, intermediate work, compiled artifacts.
-- Fleet-shared folder: ${input.sandbox.shared} — one folder shared with all other bots. Publish reusable data here (clearly named files), even when not explicitly asked — other bots consume it without a handoff.
+- Fleet-shared folder: ${input.sandbox.shared} — one folder shared with all other bots, for DATA other bots consume (a dossier, a dataset, a draft handed to the next stage). Not for notes about your work; writes here are budgeted per run.
Anything outside these two areas and your declared Access grants is denied.`;
+ if (input.deliverablesDir) {
+ prompt += `\n\nDeliverables — where the owner finds your results: ${input.deliverablesDir}
+- When a result is finished, call bot_deliver on the file (give it a human title; mark final: true for the finished piece the owner asked for). Never write there by hand.
+- Intermediate stages (research, drafts, checks) are delivered as work, not finals; the lead delivers the final.
+- Name the delivered file in your reply.`;
+ }
+
const roster = manifest.comms?.canMessage ?? [];
if (roster.length > 0) {
prompt += `\n\nBots you can message via bot_send: ${roster.join(', ')}.`;
@@ -414,4 +833,4 @@ Fleet protocol:
prompt += `\n\nToken budget remaining: ${remaining}`;
return prompt;
-}
\ No newline at end of file
+}
diff --git a/src/bots/types.ts b/src/bots/types.ts
index 794a5627..6312fa3f 100644
--- a/src/bots/types.ts
+++ b/src/bots/types.ts
@@ -52,13 +52,30 @@ export interface BotScheduleConfig {
* is skipped entirely (Hermes' wakeAgent gate pattern).
*/
gateScript?: string;
+ /**
+ * Outcome contract: 'work' (default) — the run must deliver, act or
+ * delegate, and gets one nudge if it only wrote notes; 'check' — a
+ * monitoring routine that may legitimately find nothing to do.
+ */
+ expects?: 'work' | 'check';
+ /**
+ * Minimum minutes between two runs of this routine (default 30). A tick
+ * that arrives sooner, or while the previous run is still queued or
+ * running, is skipped — never stacked.
+ */
+ minIntervalMinutes?: number;
}
export interface BotAutonomyConfig {
maxConcurrent?: number;
maxSteps?: number;
- /** Hard daily token cap. Exceeded → the bot pauses until the next day. */
+ /** Hard daily token cap. Exceeded → the bot pauses until the next day.
+ * Unset = the fleet default (config bots.suggestedDailyTokenBudget). */
dailyTokenBudget?: number;
+ /** Tokens (in + out) one turn may spend before it is cut off (default 300k). */
+ maxTokensPerTurn?: number;
+ /** Wall-clock minutes one turn may run (default 20). */
+ maxTurnMinutes?: number;
}
export interface BotRetentionConfig {
@@ -169,6 +186,20 @@ export interface BotRunRecord {
/** Escalation marker: this run needs the owner (DLQ'd failure / crash).
* The newest row's flag is the durable "needs you" state across restarts. */
needsYou?: boolean;
+ /** Journal v2 (ADR-020). Absent on rows written before it. */
+ /** When the turn itself started; `startedAt` is the enqueue time. */
+ turnStartedAt?: number;
+ steps?: number;
+ toolCalls?: number;
+ /** Largest single-step prompt the provider saw. */
+ peakInputTokens?: number;
+ /** What the tool trace proved: deliverable | action | delegated | message | none. */
+ outcome?: string;
+ deliverables?: string[];
+ /** The reply claimed delivery/execution with no matching tool call. */
+ claimedWithoutAction?: boolean;
+ /** Routine id for cron/self runs (consecutive no-outcome tracking). */
+ routineId?: string;
}
/** Live bot state surfaced by /bots, the status bar, and the API. */