src/core/assistant.ts
11 KB - Ver o arquivo original
// The assistant: connects a session (memory of the conversation) to the turn loop (thinking and
// acting). Channels call `reply()` and `answerApproval()`; they never touch the model or the log
// directly.
//
// Lab 02: every message is written to the session log the moment it exists.
// Lab 03: each user message gets a per-turn context block (time, channel).
// Lab 05: tool calls go through the policy; calls that need the owner pause the turn, and
// `answerApproval()` resumes it. Every decision lands in the audit log.
// Lab 08 puts a per-session queue in front of these methods, so two channels writing to the
// same session at once are processed one after the other.
import type { AuditLog } from '../security/audit.ts';
import type { SpendLedger } from '../security/budget.ts';
import type { Policy } from '../security/policy.ts';
import type { ApprovalRequest, Session } from '../sessions/session.ts';
import type { Tool, ToolContext } from '../tools/tool.ts';
import { userContent } from '../context/turn-context.ts';
import type { BetaTextBlockParam, ModelClient } from './model.ts';
import {
runTurn,
type ToolReport,
type TurnInput,
type TurnResult,
type TurnUsage,
} from './turn-loop.ts';
/** Usage of a turn that threw, keyed by the error, from runAndRecord() to guard(). */
const spentByError = new WeakMap<object, TurnUsage>();
export interface AssistantDeps {
model: ModelClient;
system: BetaTextBlockParam[];
tools: readonly Tool[];
toolContext: ToolContext;
maxSteps: number;
/** Which calls run, ask, or never run (lab 05). Without it, every valid call runs. */
policy?: Policy;
/** Where every tool decision is recorded (lab 05). */
audit?: AuditLog;
/** Builds the per-turn context block (lab 03). */
turnContext?: (channel: string) => string;
/** Called when the owner answers "always": persist the policy's overrides. */
saveOverrides?: () => Promise<void>;
/** Records the cost of every turn and enforces the daily cap (lab 12). */
ledger?: SpendLedger;
dailyUsd?: number;
/**
* Treat "ask" as "deny". Sub-agents (lab 10) run inside another turn with nobody to ask, so a
* call that would need approval is refused instead of waiting.
*/
askMeansDeny?: boolean;
}
const BUDGET_TEXT =
'The daily spending limit has been reached, so I am not calling the model again today. ' +
'Raise limits.dailyUsd in the config, or wait until midnight.';
export interface ReplyOptions {
channel: string;
onText?: (delta: string) => void;
onTool?: (event: { name: string; phase: 'start' | 'end'; isError?: boolean }) => void;
signal?: AbortSignal;
}
export interface AssistantResult extends TurnResult {
/** Approval requests created by this turn, with their ids (stop "awaiting_approval"). */
approvals?: ApprovalRequest[];
}
export type AnswerResult =
| { status: 'unknown' }
| { status: 'waiting'; remaining: ApprovalRequest[] }
| { status: 'resumed'; result: AssistantResult };
export class Assistant {
private readonly deps: AssistantDeps;
constructor(deps: AssistantDeps) {
this.deps = deps;
}
/** Handles a new message from the owner. */
async reply(session: Session, text: string, options: ReplyOptions): Promise<AssistantResult> {
const turnId = await session.startTurn(options.channel);
return this.guard(session, turnId, options, async () => {
// A new message while tool calls still wait for approval: the owner moved on. Close the
// waiting calls as denied so the history stays valid, then handle the new message.
await this.supersedePending(session, turnId);
const context = this.deps.turnContext?.(options.channel);
const userMessage = { role: 'user' as const, content: userContent(text, context) };
if (await this.overBudget()) {
// Keep the message (it merges with the next one), but do not call the model.
await session.addMessage(turnId, userMessage);
return this.budgetStop(session, turnId);
}
return this.runAndRecord(session, turnId, options, { userMessage });
});
}
/**
* Records the owner's answer to one approval request. When every request of that turn has an
* answer, the turn resumes: approved calls run, denied calls get an error result.
*/
async answerApproval(
session: Session,
approvalId: string,
decision: 'approved' | 'denied',
options: ReplyOptions & { always?: boolean },
): Promise<AnswerResult> {
const request = session.pendingApprovals().find((r) => r.approvalId === approvalId);
if (!request) return { status: 'unknown' };
await session.resolveApproval(approvalId, decision, options.channel);
if (decision === 'approved' && options.always) await this.rememberAlways(session, request);
const batch = session.approvalsForTurn(request.turnId);
const remaining = batch.filter((r) => r.decision === undefined);
if (remaining.length > 0) return { status: 'waiting', remaining };
const answers = new Map(batch.map((r) => [r.toolUseId, r.decision!] as const));
const turnId = await session.startTurn(options.channel);
if (await this.overBudget()) {
// Close the waiting calls so the history stays valid; nothing runs.
await session.interruptTurn(turnId, 'daily spending limit reached');
return { status: 'resumed', result: this.budgetResult() };
}
const result = await this.guard(session, turnId, options, () =>
this.runAndRecord(session, turnId, options, { approvals: answers }),
);
return { status: 'resumed', result };
}
private async runAndRecord(
session: Session,
turnId: string,
options: ReplyOptions,
start: Pick<TurnInput, 'userMessage' | 'approvals'>,
): Promise<AssistantResult> {
let spent: TurnUsage | undefined;
const record = (usage: TurnUsage) =>
this.deps.ledger?.record(session.key, this.deps.model.model, usage);
let result: TurnResult;
try {
result = await this.runTurnFor(session, turnId, options, start, (usage) => {
spent = { ...usage };
});
} catch (err) {
// The turn failed or was cancelled after some model calls: they still cost money. Record
// them in the ledger now, and hand them to guard() for the turn_interrupted event.
if (spent && spent.modelCalls > 0) {
await record(spent);
spentByError.set(err as object, spent);
}
throw err;
}
let approvals: ApprovalRequest[] | undefined;
if (result.stop === 'awaiting_approval' && result.pending) {
approvals = await session.requestApprovals(turnId, result.pending);
}
await session.completeTurn(turnId, {
stop: result.stop,
model: this.deps.model.model,
usage: result.usage,
});
await record(result.usage);
return { ...result, ...(approvals ? { approvals } : {}) };
}
private runTurnFor(
session: Session,
turnId: string,
options: ReplyOptions,
start: Pick<TurnInput, 'userMessage' | 'approvals'>,
onUsage: (usage: TurnUsage) => void,
): Promise<TurnResult> {
const { policy, audit } = this.deps;
return runTurn({
...this.deps,
...start,
onUsage,
history: session.messages(),
authorize: policy
? (tool, input) => {
const decision = policy.decide(tool.name, tool.argv?.(input));
return this.deps.askMeansDeny && decision.decision === 'ask'
? { decision: 'deny', reason: `${decision.reason}; nobody can approve it here` }
: decision;
}
: undefined,
onText: options.onText,
onTool: options.onTool,
signal: options.signal,
onMessage: (message) => session.addMessage(turnId, message),
onToolReport: audit
? (report: ToolReport) =>
audit.append({
ts: new Date().toISOString(),
session: session.key,
turnId,
tool: report.tool,
summary: report.summary,
decision: report.decision,
reason: report.reason,
outcome: report.outcome,
...(report.ms !== undefined ? { ms: report.ms } : {}),
})
: undefined,
});
}
private async overBudget(): Promise<boolean> {
const { ledger, dailyUsd } = this.deps;
return Boolean(ledger && dailyUsd && (await ledger.exceeded(dailyUsd)));
}
private budgetResult(): AssistantResult {
return {
text: BUDGET_TEXT,
stop: 'budget',
added: [],
usage: {
modelCalls: 0,
inputTokens: 0,
outputTokens: 0,
cacheReadTokens: 0,
cacheWriteTokens: 0,
},
};
}
private async budgetStop(session: Session, turnId: string): Promise<AssistantResult> {
const result = this.budgetResult();
await session.completeTurn(turnId, {
stop: 'budget',
model: this.deps.model.model,
usage: result.usage,
});
return result;
}
private async guard(
session: Session,
turnId: string,
options: ReplyOptions,
work: () => Promise<AssistantResult>,
): Promise<AssistantResult> {
try {
return await work();
} catch (err) {
const signal = options.signal;
const reason = signal?.aborted
? typeof signal.reason === 'string'
? signal.reason
: 'cancelled by the owner'
: (err as Error).message;
const spent = err !== null && typeof err === 'object' ? spentByError.get(err) : undefined;
await session.interruptTurn(
turnId,
reason,
spent ? { model: this.deps.model.model, usage: spent } : undefined,
);
throw err;
}
}
private async supersedePending(session: Session, turnId: string): Promise<void> {
const pending = session.pendingApprovals();
if (pending.length === 0) return;
for (const request of pending) {
await session.resolveApproval(request.approvalId, 'denied', 'system', 'superseded');
}
// Every tool call of the waiting assistant message gets a result, in one message.
const last = session.messages().at(-1);
if (last?.role !== 'assistant' || !Array.isArray(last.content)) return;
const content = last.content.flatMap((block) =>
block.type === 'tool_use'
? [
{
type: 'tool_result' as const,
tool_use_id: block.id,
is_error: true,
content:
'Not run: the owner sent a new message instead of answering the approval request.',
},
]
: [],
);
if (content.length > 0) await session.addMessage(turnId, { role: 'user', content });
}
/** "Always": allow this exact program call from now on (only for program-running tools). */
private async rememberAlways(session: Session, request: ApprovalRequest): Promise<void> {
const { policy, tools, saveOverrides } = this.deps;
const tool = tools.find((t) => t.name === request.tool);
if (!policy || !tool?.argv) return;
const call = findToolUse(session, request.toolUseId);
if (!call) return;
const parsed = tool.input.safeParse(call.input);
if (!parsed.success) return;
policy.addOverride({ tool: tool.name, argv: tool.argv(parsed.data) });
await saveOverrides?.();
}
}
function findToolUse(session: Session, toolUseId: string): { input: unknown } | undefined {
for (const message of session.messages()) {
if (message.role !== 'assistant' || !Array.isArray(message.content)) continue;
for (const block of message.content) {
if (block.type === 'tool_use' && block.id === toolUseId) return block;
}
}
return undefined;
}