Skip to content
Closed
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
159 changes: 97 additions & 62 deletions src/core/minions/handlers/subagent-oneshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,74 @@ async function loadOneshotLedger(engine: BrainEngine, jobId: number): Promise<Le
);
}

async function oneshotChatCall(args: OneshotArgs, budgetMs: number, messages: Parameters<typeof gatewayChat>[0]['messages']): Promise<ChatResult | OneshotOutcome> {
const { engine, ctx, model } = args;
const chat = args._chat ?? gatewayChat;
const lease = await acquireLease(engine, args.leaseKey, ctx.id, args.maxConcurrent, {
ttlMs: Math.max(args.leaseTtlMs, budgetMs + 30_000),
});
if (!lease.acquired) {
// A full bucket is a scheduling condition, not a model failure — throw
// RateLeaseUnavailableError so the worker / inline drain requeue the job
// WITHOUT burning an attempt (never fall back: the fallback would hit
// the same full bucket sixteen times over).
throw new RateLeaseUnavailableError(args.leaseKey, lease.activeCount, lease.maxConcurrent);
}
const budgetAbort = AbortSignal.timeout(budgetMs);
const callSignal = ctx.signal ? AbortSignal.any([ctx.signal, budgetAbort]) : budgetAbort;

let chatResult: ChatResult;
const t0 = Date.now();
logSubagentHeartbeat({ job_id: ctx.id, event: 'llm_call_started', turn_idx: 0, mode: 'oneshot' });
try {
chatResult = await chat({
model,
system: ONESHOT_SYSTEM,
messages,
maxTokens: args.maxOutputTokens,
abortSignal: callSignal,
timeoutMs: budgetMs,
// cacheSystem marks the system block as a cache breakpoint. Note:
// ONESHOT_SYSTEM alone is under Anthropic's ~1024-token cache minimum,
// so cross-job prefix hits only materialize on providers/models with a
// lower floor — harmless no-op otherwise.
cacheSystem: true,
});
} catch (err) {
if (budgetAbort.aborted && !(ctx.signal?.aborted) && isAbortShaped(err)) {
// The oneshot sub-budget expired — the agentic fallback still has the
// rest of the job budget (OV-9). Never charge a slow single call
// against the whole job.
logSubagentHeartbeat({ job_id: ctx.id, event: 'oneshot_timeout', turn_idx: 0, ms_elapsed: Date.now() - t0 });
return { kind: 'fallback', reason: 'oneshot_timeout' };
}
// Same terminal classification as the gateway-loop path's
// runLoopConvertingLeaseLoss (subagent.ts): `chat()` here is the SAME
// gateway.chat() entrypoint, so a 400 "prompt is too long" arrives
// normalizeAIError()-wrapped the same way — isPromptTooLongError() walks
// the `.cause` chain to still match the SDK's inner shape. Without this,
// a prompt-too-long condition on the oneshot dispatch path retries like
// any other transient failure up to max_stalled, recreating the same
// dream-cycle queue-clog class the legacy and gateway-loop paths already
// fast-fail on.
// Single walk: extractPromptTooLongDetail is non-null exactly when
// isPromptTooLongError matches (both wrap the same matcher).
const detail = extractPromptTooLongDetail(err);
if (detail !== null) {
throw new UnrecoverableError(`prompt_too_long: ${detail}`);
}
// Job-level abort or transport error: the job machinery owns these — a
// provider outage would break the fallback identically (don't double-pay).
throw err;
} finally {
await releaseLease(engine, lease.leaseId!).catch(() => { /* best-effort */ });
}

return chatResult;
}

export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutcome> {
const { engine, ctx, data, model, putPageTool } = args;
const chat = args._chat ?? gatewayChat;
const submitted = snapshotFromJob(ctx.data);
const checkCurrentWrite = async (slug?: string): Promise<void> => {
if (!submitted) return;
Expand Down Expand Up @@ -420,66 +485,10 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc
// the call (AbortSignal.timeout below), so ttl = budget + slack. With the
// bare 120s default TTL a 300s call's lease would be pruned mid-flight and
// the next acquirer would over-admit past maxConcurrent.
const lease = await acquireLease(engine, args.leaseKey, ctx.id, args.maxConcurrent, {
ttlMs: Math.max(args.leaseTtlMs, budgetMs + 30_000),
});
if (!lease.acquired) {
// A full bucket is a scheduling condition, not a model failure — throw
// RateLeaseUnavailableError so the worker / inline drain requeue the job
// WITHOUT burning an attempt (never fall back: the fallback would hit
// the same full bucket sixteen times over).
throw new RateLeaseUnavailableError(args.leaseKey, lease.activeCount, lease.maxConcurrent);
}
const budgetAbort = AbortSignal.timeout(budgetMs);
const callSignal = ctx.signal ? AbortSignal.any([ctx.signal, budgetAbort]) : budgetAbort;

let chatResult: ChatResult;
const t0 = Date.now();
logSubagentHeartbeat({ job_id: ctx.id, event: 'llm_call_started', turn_idx: 0, mode: 'oneshot' });
try {
chatResult = await chat({
model,
system: ONESHOT_SYSTEM,
messages: [{ role: 'user', content: data.prompt }],
maxTokens: args.maxOutputTokens,
abortSignal: callSignal,
timeoutMs: budgetMs,
// cacheSystem marks the system block as a cache breakpoint. Note:
// ONESHOT_SYSTEM alone is under Anthropic's ~1024-token cache minimum,
// so cross-job prefix hits only materialize on providers/models with a
// lower floor — harmless no-op otherwise.
cacheSystem: true,
});
} catch (err) {
if (budgetAbort.aborted && !(ctx.signal?.aborted) && isAbortShaped(err)) {
// The oneshot sub-budget expired — the agentic fallback still has the
// rest of the job budget (OV-9). Never charge a slow single call
// against the whole job.
logSubagentHeartbeat({ job_id: ctx.id, event: 'oneshot_timeout', turn_idx: 0, ms_elapsed: Date.now() - t0 });
return { kind: 'fallback', reason: 'oneshot_timeout' };
}
// Same terminal classification as the gateway-loop path's
// runLoopConvertingLeaseLoss (subagent.ts): `chat()` here is the SAME
// gateway.chat() entrypoint, so a 400 "prompt is too long" arrives
// normalizeAIError()-wrapped the same way — isPromptTooLongError() walks
// the `.cause` chain to still match the SDK's inner shape. Without this,
// a prompt-too-long condition on the oneshot dispatch path retries like
// any other transient failure up to max_stalled, recreating the same
// dream-cycle queue-clog class the legacy and gateway-loop paths already
// fast-fail on.
// Single walk: extractPromptTooLongDetail is non-null exactly when
// isPromptTooLongError matches (both wrap the same matcher).
const detail = extractPromptTooLongDetail(err);
if (detail !== null) {
throw new UnrecoverableError(`prompt_too_long: ${detail}`);
}
// Job-level abort or transport error: the job machinery owns these — a
// provider outage would break the fallback identically (don't double-pay).
throw err;
} finally {
await releaseLease(engine, lease.leaseId!).catch(() => { /* best-effort */ });
}

const callOnce = (messages: Parameters<typeof gatewayChat>[0]['messages']) => oneshotChatCall(args, budgetMs, messages);
const first = await callOnce([{ role: 'user', content: data.prompt }]);
if ('kind' in first) return first;
let chatResult: ChatResult = first;
await ctx.updateTokens({
input: chatResult.usage.input_tokens,
output: chatResult.usage.output_tokens,
Expand All @@ -502,7 +511,33 @@ export async function runSubagentOneshot(args: OneshotArgs): Promise<OneshotOutc
return fb('refusal');
}

const parsed = parseOneshotResponse(chatResult.text ?? '');
let parsed = parseOneshotResponse(chatResult.text ?? '');
if (!parsed && chatResult.usage.output_tokens < args.maxOutputTokens && (chatResult.text ?? '').trim() !== '') {
// A model that decided "nothing to write" often answers in prose instead of
// the skip JSON. One bounded re-ask holds it to the contract so the skip is
// banked (no re-synthesis next cycle) instead of dead-lettering.
const second = await callOnce([
{ role: 'user', content: data.prompt },
{ role: 'assistant', content: chatResult.text ?? '' },
{ role: 'user', content: 'Your reply was not the required JSON object. Respond again with ONLY the JSON object from the system contract (use {"pages": [], "skipped": true, "skip_reason": "<one line>"} if nothing meets the bar).' },
]);
if ('kind' in second) return second;
await ctx.updateTokens({ input: second.usage.input_tokens, output: second.usage.output_tokens, cache_read: second.usage.cache_read_tokens });
// The re-ask's usage is already on the job (updateTokens above); the
// fallback rollup keeps reporting the original attempt, and a parsed
// re-ask adds its own usage to the result.
const secondParsed = second.stopReason === 'length' || second.stopReason === 'refusal' || second.stopReason === 'content_filter'
? null
: parseOneshotResponse(second.text ?? '');
if (secondParsed) {
parsed = secondParsed;
chatResult = second;
tokens.in += second.usage.input_tokens;
tokens.out += second.usage.output_tokens;
tokens.cache_read += second.usage.cache_read_tokens;
tokens.cache_create += second.usage.cache_creation_tokens;
}
}
if (!parsed) {
// Some providers normalize an output-cap stop to end/other. Usage at the
// requested ceiling is the provider-neutral truncation signal (same
Expand Down
80 changes: 80 additions & 0 deletions test/minions/subagent-oneshot-prose-skip.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* #9648 — a oneshot child that answers a skip as prose (not the skip JSON) is
* re-asked once for the JSON contract, so the skip is banked instead of
* falling through to an agentic loop that dead-letters under require_writes.
*/
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { MinionQueue } from '../../src/core/minions/queue.ts';
import { buildBrainTools } from '../../src/core/minions/tools/brain-allowlist.ts';
import type { MinionJobContext, SubagentHandlerData } from '../../src/core/minions/types.ts';
import type { GBrainConfig } from '../../src/core/config.ts';
import { runSubagentOneshot, type OneshotArgs } from '../../src/core/minions/handlers/subagent-oneshot.ts';

let engine: PGLiteEngine;
let queue: MinionQueue;
let schemaVersion: string;

beforeAll(async () => {
engine = new PGLiteEngine();
await engine.connect({ database_url: '' });
await engine.initSchema();
schemaVersion = (await engine.getConfig('version')) ?? '7';
queue = new MinionQueue(engine);
}, 60_000);

afterAll(async () => {
await engine.disconnect();
});

beforeEach(async () => {
await resetPgliteState(engine);
await engine.setConfig('version', schemaVersion);
});

const DATA: SubagentHandlerData = {
prompt: 'CONTEXT ... TRANSCRIPT ...',
allowed_slug_prefixes: ['wiki/personal/reflections/*'],
oneshot_slug_suffix: 'abc123',
mode: 'oneshot',
require_writes: true,
};

const PROSE = "I'm not writing any pages for this transcript. It contains only one idle notification.";
const SKIP_JSON = '{"pages": [], "skipped": true, "skip_reason": "routine idle notification"}';

describe('oneshot prose skip (#9648)', () => {
test('prose skip is re-asked once and banked as a skip, not a fallback', async () => {
const job = await queue.add('subagent', DATA as unknown as Record<string, unknown>, {}, { allowProtectedSubmit: true });
const ac = new AbortController();
const ctx = {
id: job.id, name: job.name, data: DATA as unknown as Record<string, unknown>, attempts_made: 0,
idempotency_key: null, signal: ac.signal, deadlineAtMs: null, shutdownSignal: new AbortController().signal,
async updateProgress() {}, async updateTokens() {}, async log() {}, async isActive() { return true; }, async readInbox() { return []; },
} as MinionJobContext;
const tools = buildBrainTools({
subagentId: ctx.id, engine, config: { engine: 'pglite' } as unknown as GBrainConfig,
allowedSlugPrefixes: DATA.allowed_slug_prefixes, sourceId: DATA.source_id, deferEmbeds: true,
});
let calls = 0;
const chat = (async () => {
calls++;
const text = calls === 1 ? PROSE : SKIP_JSON;
return {
text, blocks: [{ type: 'text', text }], stopReason: 'end',
usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic',
};
}) as OneshotArgs['_chat'];
const out = await runSubagentOneshot({
engine, ctx, data: DATA, model: 'anthropic:claude-sonnet-4-6', maxOutputTokens: 8192,
putPageTool: tools.find(t => t.name === 'brain_put_page'),
leaseKey: 'anthropic:messages', maxConcurrent: 32, leaseTtlMs: 120_000, _chat: chat,
});
expect(out.kind).toBe('done');
const rows = await engine.executeRaw<{ tool_name: string }>(
`SELECT tool_name FROM subagent_tool_executions WHERE job_id = $1`, [ctx.id]);
expect(rows.map(r => r.tool_name)).toContain('oneshot_skip');
});
});
Loading