src/agents/subagent.ts
4 KB - 元のファイルを表示
// Sub-agents (lab 10): delegate a focused task to a helper with its own context.
//
// Why: reading ten files to answer one question fills the main conversation with text it will
// never need again, and every later request pays for it. A sub-agent does the reading in its own
// session ("steward:sub:<id>") and hands back only a short report, which becomes one tool result
// in the main conversation.
//
// The helper is deliberately weaker and narrower than Steward:
// - a cheaper model (model.subagent, Haiku by default) at low effort,
// - read-only tools: no writes, no programs, no memory, no spawning more helpers,
// - a task budget the model paces itself against, plus a hard step limit,
// - "ask" means "deny": it runs inside another turn, so nobody is there to approve anything.
// Everything it does is still checked by the policy and written to the audit log.
import { randomBytes } from 'node:crypto';
import { z } from 'zod';
import { Assistant } from '../core/assistant.ts';
import type { BetaTextBlockParam, ModelClient } from '../core/model.ts';
import type { AuditLog } from '../security/audit.ts';
import type { SpendLedger } from '../security/budget.ts';
import type { Policy } from '../security/policy.ts';
import type { SessionStore } from '../sessions/session-store.ts';
import { defineTool, limitOutput, type Tool, type ToolContext } from '../tools/tool.ts';
/** Tools a sub-agent may use. Everything else is withheld, not just denied. */
export const SUBAGENT_TOOLS = [
'current_time',
'days_until',
'list_files',
'read_file',
'search_files',
];
export interface SubagentDeps {
model: ModelClient;
system: BetaTextBlockParam[];
/** The main tool list; the read-only subset is taken from it. */
tools: readonly Tool[];
toolContext: ToolContext;
sessions: SessionStore;
policy?: Policy;
audit?: AuditLog;
ledger?: SpendLedger;
dailyUsd?: number;
maxSteps: number;
maxResultChars: number;
}
export function spawnAgentTool(deps: SubagentDeps): Tool {
const helper = new Assistant({
model: deps.model,
system: deps.system,
tools: deps.tools.filter((t) => SUBAGENT_TOOLS.includes(t.name)),
toolContext: deps.toolContext,
maxSteps: deps.maxSteps,
askMeansDeny: true,
...(deps.policy ? { policy: deps.policy } : {}),
...(deps.audit ? { audit: deps.audit } : {}),
...(deps.ledger ? { ledger: deps.ledger } : {}),
...(deps.dailyUsd !== undefined ? { dailyUsd: deps.dailyUsd } : {}),
});
return defineTool({
name: 'spawn_agent',
description:
'Hands a focused, read-only research task to a helper with its own context, for example ' +
'"Turn notes/exam-guide.md into a checklist of topics". The helper can list, read, and ' +
'search workspace files, and returns a short report with file:line references. Use it ' +
'when a task needs a lot of reading; several helpers can run at once.',
input: z.object({
task: z.string().min(10).max(2000).describe('What the helper should do and return'),
}),
summarize: ({ task }) => `spawn_agent "${task.slice(0, 80)}"`,
run: async ({ task }, context) => {
const id = `${new Date().toISOString().slice(0, 10)}-${randomBytes(3).toString('hex')}`;
const key = `steward:sub:${id}`;
const { session } = await deps.sessions.open(key);
const result = await helper.reply(session, task, {
channel: 'subagent',
...(context.signal ? { signal: context.signal } : {}),
});
const usage = result.usage;
const header =
`Helper report (session ${key}; ${usage.modelCalls} model call(s), ` +
`${usage.inputTokens + usage.cacheReadTokens + usage.cacheWriteTokens} input and ` +
`${usage.outputTokens} output tokens; stop: ${result.stop}).`;
const body = result.text.trim() || 'The helper returned no text.';
return `${header}\n\n${limitOutput(body, deps.maxResultChars)}`;
},
});
}