Turn services + agent DI: chat-handler becomes the composition root (stage 4)
The chat turn is now composed, not implemented, by chat-handler.ts:
- src/server/turn-service.ts: one named, error-contained seam per turn
responsibility — buildTeacherContext (W8 read channel), persistTurn
(canonical state write), spawnTurnJobs (async protocol kick-off),
foldTurnIntoGraph (session→graph consolidation; the extraction-pipeline
stage swaps this body behind the same seam). Each takes its deps
explicitly; failures log one [chat <id>] line and never touch the
response.
- chat-handler.ts wires: storage ports (stores), the job runner, the
teacher tools (ctx = chatId + injected ChatStore), and the services.
It no longer contains any logic beyond request validation.
Agent layer now receives dependencies instead of importing them — a new
lint zone enforces it (src/agent never imports src/server or src/store;
verified to fire both ways):
- runner.ts: createJobRunner({ chatStore, jobStore }) factory returning
the spawn hook + the three job runners; the model-override test seam
stays module-level. Bodies otherwise verbatim.
- plan tools: persist through the ctx-injected ChatStore
(TeacherToolContext = { chatId, chatStore }).
- teacher-agent's dependency-free default registry is now the true
client-side set: questionTools + jobTools (jobTools was ctx-parameter-
shaped but never used its ctx — now honestly context-free). Production
always passes createTeacherTools({ chatId, chatStore }); tests that
drive a bare mock model get the client-side set unchanged.
Zero behavior change: tsc clean, 190/190 tests, eslint clean, production
build clean. Tests inject the same fs ports the chat-handler does.
This commit is contained in:
+217
-197
@@ -1,22 +1,22 @@
|
||||
import { isToolUIPart, type LanguageModel, type UIMessage } from "ai";
|
||||
import type { DemoResult, DemoToolInput, JobKind, ResearchResult, ResearchToolInput, VisualResult, VisualToolInput } from "../../core/contracts.ts";
|
||||
import { JOB_TOOLS } from "../../core/pending.ts";
|
||||
import { chatStore } from "../../store/chats.ts";
|
||||
import { jobStore } from "../../store/jobs.ts";
|
||||
import type { ChatStore, JobStore } from "../../core/ports.ts";
|
||||
import { runDemoBuilder } from "./demo-builder.ts";
|
||||
import { createResearcherAgent } from "./researcher.ts";
|
||||
import { runVisualMaker } from "./visual-maker.ts";
|
||||
|
||||
/**
|
||||
* The background job runner + the chat-handler spawn hook (contracts.ts
|
||||
* "THE ASYNC PROTOCOL").
|
||||
* The background job runner (contracts.ts "THE ASYNC PROTOCOL"), created via
|
||||
* createJobRunner({ chatStore, jobStore }) — the composition root (chat-handler)
|
||||
* injects the storage ports; this module never imports an adapter.
|
||||
*
|
||||
* spawnPendingJobs — called from onFinish AFTER saveMessages: finds
|
||||
* spawnPendingJobs — called from the turn service AFTER persist: finds
|
||||
* input-available JOB_TOOLS parts in the last assistant message with no
|
||||
* existing job and fires the kind's runner WITHOUT awaiting (the HTTP
|
||||
* response is long gone). Kind dispatch (research/demo/visual) is a
|
||||
* self-contained map here, so chat-handler needs no changes for new
|
||||
* job kinds — anything listed in JOB_TOOLS routes automatically.
|
||||
* self-contained map here, so no caller changes for new job kinds —
|
||||
* anything listed in JOB_TOOLS routes automatically.
|
||||
*
|
||||
* runResearchJob / runDemoJob / runVisualJob — run the sub-agent loop in
|
||||
* the background, updating the job's activity line on every iteration,
|
||||
@@ -40,186 +40,236 @@ export const researchModelOverride: { current?: LanguageModel } = {};
|
||||
export const demoModelOverride: { current?: LanguageModel } = {};
|
||||
export const visualModelOverride: { current?: LanguageModel } = {};
|
||||
|
||||
export interface JobRunnerDeps {
|
||||
chatStore: ChatStore;
|
||||
jobStore: JobStore;
|
||||
}
|
||||
|
||||
export interface RunResearchJobOptions {
|
||||
model?: LanguageModel;
|
||||
}
|
||||
|
||||
/** The kind→runner map: everything in JOB_TOOLS routes through here. */
|
||||
const KIND_RUNNERS: Record<JobKind, (jobId: string) => Promise<void>> = {
|
||||
research: (jobId) => runResearchJob(jobId, { model: researchModelOverride.current }),
|
||||
demo: (jobId) => runDemoJob(jobId, { model: demoModelOverride.current }),
|
||||
visual: (jobId) => runVisualJob(jobId, { model: visualModelOverride.current }),
|
||||
};
|
||||
|
||||
export function spawnPendingJobs(chatId: string, messages: UIMessage[]): void {
|
||||
const last = [...messages].reverse().find((m) => m.role === "assistant");
|
||||
if (!last) return;
|
||||
for (const part of last.parts) {
|
||||
if (!isToolUIPart(part) || part.state !== "input-available") continue;
|
||||
const tool = part.type.slice("tool-".length);
|
||||
if (!(JOB_TOOLS as readonly string[]).includes(tool)) continue;
|
||||
const runner = KIND_RUNNERS[tool as JobKind];
|
||||
if (!runner) continue;
|
||||
if (jobStore.findJobByToolCallId(chatId, part.toolCallId)) continue; // already has a job
|
||||
const job = jobStore.createJob({ kind: tool as JobKind, chatId, toolCallId: part.toolCallId });
|
||||
void runner(job.id).catch((err) => {
|
||||
console.error(`[job ${job.id}] ${tool} runner crashed:`, err);
|
||||
jobStore.updateJob(job.id, { status: "error", error: String(err), activity: "failed" });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function runResearchJob(jobId: string, opts: RunResearchJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as ResearchToolInput | undefined;
|
||||
const question = typeof input?.question === "string" && input.question.trim() ? input.question : "(no question)";
|
||||
const context = typeof input?.context === "string" && input.context.trim() ? input.context : undefined;
|
||||
|
||||
const prompt = [
|
||||
`Research question: ${question}`,
|
||||
context ? `Context (what this is needed for): ${context}` : null,
|
||||
"Produce your final brief in the required format.",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
const fetchedUrls: string[] = [];
|
||||
const agent = createResearcherAgent(opts.model);
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "researching" });
|
||||
const result = await agent.generate({
|
||||
prompt,
|
||||
onToolExecutionStart: ({ toolCall }) => {
|
||||
const input = toolCall.input as { query?: string; url?: string } | undefined;
|
||||
if (toolCall.toolName === "web_fetch" && typeof input?.url === "string") {
|
||||
fetchedUrls.push(input.url);
|
||||
}
|
||||
jobStore.updateJob(jobId, { activity: activityLine(toolCall.toolName, input) });
|
||||
},
|
||||
});
|
||||
|
||||
const brief = result.text.trim();
|
||||
if (!brief) throw new Error("the researcher produced no text");
|
||||
const research: ResearchResult = { brief, sources: parseSources(brief, fetchedUrls) };
|
||||
|
||||
fulfillPart(job.chatId, job.toolCallId, research);
|
||||
jobStore.updateJob(jobId, { status: "done", result: research }); // activity line kept: the last tool call is the record
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
fulfillPart(job.chatId, job.toolCallId, { brief: `Research failed: ${reason}`, sources: [] });
|
||||
jobStore.updateJob(jobId, { status: "error", activity: "failed", error: reason });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── demo + visual job wrappers ───────────────────────────────────────────
|
||||
|
||||
export interface RunDemoJobOptions {
|
||||
model?: LanguageModel;
|
||||
}
|
||||
|
||||
/** Failure shape (W6 brief): html === "" with "FAILED: …" notes. */
|
||||
function isDemoFailure(result: DemoResult): boolean {
|
||||
return typeof result.html !== "string" || result.html.length === 0;
|
||||
}
|
||||
|
||||
function isVisualFailure(result: VisualResult): boolean {
|
||||
return typeof result.svg !== "string" || result.svg.length === 0;
|
||||
}
|
||||
|
||||
export async function runDemoJob(jobId: string, opts: RunDemoJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as DemoToolInput | undefined;
|
||||
const title = typeof input?.title === "string" && input.title.trim() ? input.title : "Interactive demo";
|
||||
const brief = typeof input?.brief === "string" ? input.brief : "";
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "building demo" });
|
||||
const result = await runDemoBuilder(
|
||||
{ title, brief },
|
||||
{
|
||||
model: opts.model,
|
||||
onActivity: (line) => jobStore.updateJob(jobId, { activity: line }),
|
||||
},
|
||||
);
|
||||
fulfillPart(job.chatId, job.toolCallId, result);
|
||||
if (isDemoFailure(result)) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: result.notes ?? "demo build failed", activity: "failed" });
|
||||
} else {
|
||||
jobStore.updateJob(jobId, { status: "done", result });
|
||||
}
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
const failure: DemoResult = { title, html: "", tested: true, notes: `FAILED: ${reason}` };
|
||||
fulfillPart(job.chatId, job.toolCallId, failure);
|
||||
jobStore.updateJob(jobId, { status: "error", error: reason, activity: "failed" });
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunVisualJobOptions {
|
||||
model?: LanguageModel;
|
||||
}
|
||||
|
||||
export async function runVisualJob(jobId: string, opts: RunVisualJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
export interface JobRunner {
|
||||
spawnPendingJobs(chatId: string, messages: UIMessage[]): void;
|
||||
runResearchJob(jobId: string, opts?: RunResearchJobOptions): Promise<void>;
|
||||
runDemoJob(jobId: string, opts?: RunDemoJobOptions): Promise<void>;
|
||||
runVisualJob(jobId: string, opts?: RunVisualJobOptions): Promise<void>;
|
||||
}
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
export function createJobRunner(deps: JobRunnerDeps): JobRunner {
|
||||
const { chatStore, jobStore } = deps;
|
||||
|
||||
/** The kind→runner map: everything in JOB_TOOLS routes through here. */
|
||||
const KIND_RUNNERS: Record<JobKind, (jobId: string) => Promise<void>> = {
|
||||
research: (jobId) => runResearchJob(jobId, { model: researchModelOverride.current }),
|
||||
demo: (jobId) => runDemoJob(jobId, { model: demoModelOverride.current }),
|
||||
visual: (jobId) => runVisualJob(jobId, { model: visualModelOverride.current }),
|
||||
};
|
||||
|
||||
function spawnPendingJobs(chatId: string, messages: UIMessage[]): void {
|
||||
const last = [...messages].reverse().find((m) => m.role === "assistant");
|
||||
if (!last) return;
|
||||
for (const part of last.parts) {
|
||||
if (!isToolUIPart(part) || part.state !== "input-available") continue;
|
||||
const tool = part.type.slice("tool-".length);
|
||||
if (!(JOB_TOOLS as readonly string[]).includes(tool)) continue;
|
||||
const runner = KIND_RUNNERS[tool as JobKind];
|
||||
if (!runner) continue;
|
||||
if (jobStore.findJobByToolCallId(chatId, part.toolCallId)) continue; // already has a job
|
||||
const job = jobStore.createJob({ kind: tool as JobKind, chatId, toolCallId: part.toolCallId });
|
||||
void runner(job.id).catch((err) => {
|
||||
console.error(`[job ${job.id}] ${tool} runner crashed:`, err);
|
||||
jobStore.updateJob(job.id, { status: "error", error: String(err), activity: "failed" });
|
||||
});
|
||||
}
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as VisualToolInput | undefined;
|
||||
const brief = typeof input?.brief === "string" ? input.brief : "";
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "drawing figure" });
|
||||
const result = await runVisualMaker(
|
||||
{ brief },
|
||||
{
|
||||
model: opts.model,
|
||||
onActivity: (line) => jobStore.updateJob(jobId, { activity: line }),
|
||||
},
|
||||
async function runResearchJob(jobId: string, opts: RunResearchJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as ResearchToolInput | undefined;
|
||||
const question = typeof input?.question === "string" && input.question.trim() ? input.question : "(no question)";
|
||||
const context = typeof input?.context === "string" && input.context.trim() ? input.context : undefined;
|
||||
|
||||
const prompt = [
|
||||
`Research question: ${question}`,
|
||||
context ? `Context (what this is needed for): ${context}` : null,
|
||||
"Produce your final brief in the required format.",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
const fetchedUrls: string[] = [];
|
||||
const agent = createResearcherAgent(opts.model);
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "researching" });
|
||||
const result = await agent.generate({
|
||||
prompt,
|
||||
onToolExecutionStart: ({ toolCall }) => {
|
||||
const input = toolCall.input as { query?: string; url?: string } | undefined;
|
||||
if (toolCall.toolName === "web_fetch" && typeof input?.url === "string") {
|
||||
fetchedUrls.push(input.url);
|
||||
}
|
||||
jobStore.updateJob(jobId, { activity: activityLine(toolCall.toolName, input) });
|
||||
},
|
||||
});
|
||||
|
||||
const brief = result.text.trim();
|
||||
if (!brief) throw new Error("the researcher produced no text");
|
||||
const research: ResearchResult = { brief, sources: parseSources(brief, fetchedUrls) };
|
||||
|
||||
fulfillPart(job.chatId, job.toolCallId, research);
|
||||
jobStore.updateJob(jobId, { status: "done", result: research }); // activity line kept: the last tool call is the record
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
fulfillPart(job.chatId, job.toolCallId, { brief: `Research failed: ${reason}`, sources: [] });
|
||||
jobStore.updateJob(jobId, { status: "error", activity: "failed", error: reason });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── demo + visual job wrappers ───────────────────────────────────────────
|
||||
|
||||
/** Failure shape (W6 brief): html === "" with "FAILED: …" notes. */
|
||||
function isDemoFailure(result: DemoResult): boolean {
|
||||
return typeof result.html !== "string" || result.html.length === 0;
|
||||
}
|
||||
|
||||
function isVisualFailure(result: VisualResult): boolean {
|
||||
return typeof result.svg !== "string" || result.svg.length === 0;
|
||||
}
|
||||
|
||||
async function runDemoJob(jobId: string, opts: RunDemoJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as DemoToolInput | undefined;
|
||||
const title = typeof input?.title === "string" && input.title.trim() ? input.title : "Interactive demo";
|
||||
const brief = typeof input?.brief === "string" ? input.brief : "";
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "building demo" });
|
||||
const result = await runDemoBuilder(
|
||||
{ title, brief },
|
||||
{
|
||||
model: opts.model,
|
||||
onActivity: (line) => jobStore.updateJob(jobId, { activity: line }),
|
||||
},
|
||||
);
|
||||
fulfillPart(job.chatId, job.toolCallId, result);
|
||||
if (isDemoFailure(result)) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: result.notes ?? "demo build failed", activity: "failed" });
|
||||
} else {
|
||||
jobStore.updateJob(jobId, { status: "done", result });
|
||||
}
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
const failure: DemoResult = { title, html: "", tested: true, notes: `FAILED: ${reason}` };
|
||||
fulfillPart(job.chatId, job.toolCallId, failure);
|
||||
jobStore.updateJob(jobId, { status: "error", error: reason, activity: "failed" });
|
||||
}
|
||||
}
|
||||
|
||||
async function runVisualJob(jobId: string, opts: RunVisualJobOptions = {}): Promise<void> {
|
||||
const job = jobStore.getJob(jobId);
|
||||
if (!job || job.status !== "running") return;
|
||||
|
||||
const chat = chatStore.getChat(job.chatId);
|
||||
if (!chat) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: `Chat not found: ${job.chatId}`, activity: "failed" });
|
||||
return;
|
||||
}
|
||||
const input = findToolPart(chat.messages, job.toolCallId)?.input as VisualToolInput | undefined;
|
||||
const brief = typeof input?.brief === "string" ? input.brief : "";
|
||||
|
||||
try {
|
||||
jobStore.updateJob(jobId, { activity: "drawing figure" });
|
||||
const result = await runVisualMaker(
|
||||
{ brief },
|
||||
{
|
||||
model: opts.model,
|
||||
onActivity: (line) => jobStore.updateJob(jobId, { activity: line }),
|
||||
},
|
||||
);
|
||||
fulfillPart(job.chatId, job.toolCallId, result);
|
||||
if (isVisualFailure(result)) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: result.notes ?? "visual build failed", activity: "failed" });
|
||||
} else {
|
||||
jobStore.updateJob(jobId, { status: "done", result });
|
||||
}
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
const failure: VisualResult = { svg: "", notes: `FAILED: ${reason}` };
|
||||
fulfillPart(job.chatId, job.toolCallId, failure);
|
||||
jobStore.updateJob(jobId, { status: "error", error: reason, activity: "failed" });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
function findToolPart(messages: UIMessage[], toolCallId: string) {
|
||||
for (const m of messages) {
|
||||
for (const part of m.parts) {
|
||||
if (isToolUIPart(part) && part.toolCallId === toolCallId) return part;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite the tool part in the LATEST chat record to output-available.
|
||||
* Synchronous read-modify-write (no awaits) — atomic within the event loop.
|
||||
*/
|
||||
function fulfillPart(chatId: string, toolCallId: string, output: ResearchResult | DemoResult | VisualResult): void {
|
||||
const chat = chatStore.getChat(chatId);
|
||||
if (!chat) return;
|
||||
let found = false;
|
||||
const messages = chat.messages.map((m) =>
|
||||
m.role !== "assistant"
|
||||
? m
|
||||
: {
|
||||
...m,
|
||||
parts: m.parts.map((part) => {
|
||||
if (isToolUIPart(part) && part.toolCallId === toolCallId && part.state === "input-available") {
|
||||
found = true;
|
||||
return { ...part, state: "output-available" as const, output };
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
},
|
||||
);
|
||||
fulfillPart(job.chatId, job.toolCallId, result);
|
||||
if (isVisualFailure(result)) {
|
||||
jobStore.updateJob(jobId, { status: "error", error: result.notes ?? "visual build failed", activity: "failed" });
|
||||
} else {
|
||||
jobStore.updateJob(jobId, { status: "done", result });
|
||||
}
|
||||
} catch (err) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
const failure: VisualResult = { svg: "", notes: `FAILED: ${reason}` };
|
||||
fulfillPart(job.chatId, job.toolCallId, failure);
|
||||
jobStore.updateJob(jobId, { status: "error", error: reason, activity: "failed" });
|
||||
}
|
||||
}
|
||||
|
||||
// ─── helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
function findToolPart(messages: UIMessage[], toolCallId: string) {
|
||||
for (const m of messages) {
|
||||
for (const part of m.parts) {
|
||||
if (isToolUIPart(part) && part.toolCallId === toolCallId) return part;
|
||||
if (!found) return;
|
||||
try {
|
||||
chatStore.saveMessages(chatId, messages);
|
||||
} catch (err) {
|
||||
console.error(`[chat ${chatId}] fulfilling job part ${toolCallId} failed:`, err);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
|
||||
return { spawnPendingJobs, runResearchJob, runDemoJob, runVisualJob };
|
||||
}
|
||||
|
||||
// ─── module-level pure helpers ──────────────────────────────────────────────
|
||||
|
||||
/** The activity line shown in the UI: `web_search: "query"` / `web_fetch: host`. */
|
||||
function activityLine(toolName: string, input: { query?: string; url?: string } | undefined): string {
|
||||
if (toolName === "web_search") return `web_search: "${input?.query ?? ""}"`;
|
||||
@@ -236,36 +286,6 @@ function hostOf(url: string | undefined): string {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite the tool part in the LATEST chat record to output-available.
|
||||
* Synchronous read-modify-write (no awaits) — atomic within the event loop.
|
||||
*/
|
||||
function fulfillPart(chatId: string, toolCallId: string, output: ResearchResult | DemoResult | VisualResult): void {
|
||||
const chat = chatStore.getChat(chatId);
|
||||
if (!chat) return;
|
||||
let found = false;
|
||||
const messages = chat.messages.map((m) =>
|
||||
m.role !== "assistant"
|
||||
? m
|
||||
: {
|
||||
...m,
|
||||
parts: m.parts.map((part) => {
|
||||
if (isToolUIPart(part) && part.toolCallId === toolCallId && part.state === "input-available") {
|
||||
found = true;
|
||||
return { ...part, state: "output-available" as const, output };
|
||||
}
|
||||
return part;
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!found) return;
|
||||
try {
|
||||
chatStore.saveMessages(chatId, messages);
|
||||
} catch (err) {
|
||||
console.error(`[chat ${chatId}] fulfilling job part ${toolCallId} failed:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
/** Sources for the result: markdown links cited in the brief, else fetched URLs. */
|
||||
function parseSources(brief: string, fetchedUrls: string[]): ResearchResult["sources"] {
|
||||
const sources: ResearchResult["sources"] = [];
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as path from "node:path";
|
||||
import { ToolLoopAgent, stepCountIs, type LanguageModel, type ToolSet } from "ai";
|
||||
import { openrouter } from "@openrouter/ai-sdk-provider";
|
||||
import { PATHS } from "../../config.ts";
|
||||
import { createTeacherTools } from "./tools.ts";
|
||||
import { createTeacherTools, jobTools, questionTools } from "./tools.ts";
|
||||
|
||||
/**
|
||||
* The teacher agent. Everything pi used to provide (agent loop, tool calling,
|
||||
@@ -62,10 +62,11 @@ export function createTeacherAgent(model?: LanguageModel, tools?: ToolSet, graph
|
||||
reasoning: { enabled: true, effort: "medium" },
|
||||
}),
|
||||
instructions: withGraphContext(graphContext),
|
||||
// Tools are per-request (plan tools close over chatId); chat-handler
|
||||
// passes createTeacherTools({ chatId }). Tests pass a mock model and get
|
||||
// the default question-only set.
|
||||
tools: tools ?? createTeacherTools({ chatId: "" }),
|
||||
// Tools are per-request (plan tools close over the injected ctx);
|
||||
// chat-handler passes createTeacherTools({ chatId, chatStore }). The
|
||||
// dependency-free default is the question-only set (client-side tools,
|
||||
// no storage needed) — used when tests pass a bare mock model.
|
||||
tools: tools ?? { ...questionTools, ...jobTools() },
|
||||
// Question and job tools are client-side — a call ends the server turn
|
||||
// automatically. stepCountIs is just the safety net.
|
||||
stopWhen: stepCountIs(20),
|
||||
|
||||
+11
-3
@@ -1,6 +1,9 @@
|
||||
import { tool, type ToolSet } from "ai";
|
||||
import { askInputSchema, quizInputSchema } from "../core/question-core.ts";
|
||||
import type { ChatStore } from "../core/ports.ts";
|
||||
import { jobTools } from "./tools/jobs.ts";
|
||||
|
||||
export { jobTools };
|
||||
import { planTools } from "./tools/plan.ts";
|
||||
|
||||
/**
|
||||
@@ -43,16 +46,21 @@ export const questionTools = {
|
||||
|
||||
export interface TeacherToolContext {
|
||||
chatId: string;
|
||||
/** The storage port plan tools persist through — the composition root
|
||||
* (chat-handler) injects the wired adapter; the agent layer never
|
||||
* imports one. */
|
||||
chatStore: ChatStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-request tool registry. Plan tools close over chatId for persistence;
|
||||
* question and job tools are context-free.
|
||||
* Per-request tool registry. Plan tools close over the ctx (chatId + the
|
||||
* injected ChatStore) for persistence; question and job tools are
|
||||
* context-free.
|
||||
*/
|
||||
export function createTeacherTools(ctx: TeacherToolContext): ToolSet {
|
||||
return {
|
||||
...questionTools,
|
||||
...planTools(ctx),
|
||||
...jobTools(ctx),
|
||||
...jobTools(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { tool, type ToolSet } from "ai";
|
||||
import { z } from "zod";
|
||||
import type { TeacherToolContext } from "../tools.ts";
|
||||
|
||||
/**
|
||||
* Async sub-agent job tools (W2: research; W6 adds demo + visual).
|
||||
@@ -72,10 +71,10 @@ export const visualTool = tool({
|
||||
|
||||
/**
|
||||
* Per-request job tool registry. Context-free (the runner resolves
|
||||
* everything from the chat record by toolCallId) — the ctx parameter keeps
|
||||
* the createTeacherTools factory shape stable.
|
||||
* everything from the chat record by toolCallId). Takes no dependencies —
|
||||
* part of the dependency-free default registry in teacher-agent.ts.
|
||||
*/
|
||||
export function jobTools(ctx: TeacherToolContext): ToolSet {
|
||||
export function jobTools(): ToolSet {
|
||||
return {
|
||||
research: researchTool,
|
||||
demo: demoTool,
|
||||
|
||||
+11
-11
@@ -13,7 +13,6 @@ import {
|
||||
setCurrent,
|
||||
updateNode,
|
||||
} from "../../core/plan-tree.ts";
|
||||
import { chatStore } from "../../store/chats.ts";
|
||||
import type { TeacherToolContext } from "../tools.ts";
|
||||
|
||||
/**
|
||||
@@ -49,9 +48,10 @@ const edgeSchema = z.object({
|
||||
* empty) tree, so the model can see what it's working with and fix the call.
|
||||
*/
|
||||
async function runPlanOp(
|
||||
chatId: string,
|
||||
ctx: TeacherToolContext,
|
||||
op: (tree: PlanTree) => PlanTree,
|
||||
): Promise<PlanToolResult> {
|
||||
const { chatId, chatStore } = ctx;
|
||||
const record = chatStore.getChat(chatId);
|
||||
if (!record) return { ok: false, error: `Chat not found: ${chatId}`, tree: emptyTree() };
|
||||
const current = record.tree ?? emptyTree();
|
||||
@@ -81,7 +81,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
.describe("Initial `requires` edges between the nodes. Edge direction: from = prerequisite, to = dependent."),
|
||||
}),
|
||||
execute: async ({ nodes, edges }): Promise<PlanToolResult> => {
|
||||
const record = chatStore.getChat(ctx.chatId);
|
||||
const record = ctx.chatStore.getChat(ctx.chatId);
|
||||
if (!record) return { ok: false, error: `Chat not found: ${ctx.chatId}`, tree: emptyTree() };
|
||||
const existing = record.tree;
|
||||
if (existing && existing.nodes.length > 0) {
|
||||
@@ -91,7 +91,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
tree: existing,
|
||||
};
|
||||
}
|
||||
return runPlanOp(ctx.chatId, () => createTree(nodes, edges ?? []));
|
||||
return runPlanOp(ctx, () => createTree(nodes, edges ?? []));
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -109,7 +109,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
.describe("Ids of prerequisite nodes — each gets a `requires` edge pointing to this node. All must already exist."),
|
||||
}),
|
||||
execute: async ({ id, title, summary, parents }): Promise<PlanToolResult> =>
|
||||
runPlanOp(ctx.chatId, (tree) => addNode(tree, { id, title, ...(summary !== undefined ? { summary } : {}) }, parents)),
|
||||
runPlanOp(ctx, (tree) => addNode(tree, { id, title, ...(summary !== undefined ? { summary } : {}) }, parents)),
|
||||
}),
|
||||
|
||||
plan_update_node: tool({
|
||||
@@ -125,7 +125,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
message: "Pass at least one of `title` or `summary` — an update with neither changes nothing.",
|
||||
}),
|
||||
execute: async ({ id, title, summary }): Promise<PlanToolResult> =>
|
||||
runPlanOp(ctx.chatId, (tree) => updateNode(tree, id, { ...(title !== undefined ? { title } : {}), ...(summary !== undefined ? { summary } : {}) })),
|
||||
runPlanOp(ctx, (tree) => updateNode(tree, id, { ...(title !== undefined ? { title } : {}), ...(summary !== undefined ? { summary } : {}) })),
|
||||
}),
|
||||
|
||||
plan_remove_node: tool({
|
||||
@@ -133,7 +133,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
"Remove a node from the plan tree — prune what proves unnecessary. Cascades: every edge touching the node (both directions), its current " +
|
||||
"status, and its done status are removed with it.",
|
||||
inputSchema: z.object({ id: nodeId }),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx.chatId, (tree) => removeNode(tree, id)),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => removeNode(tree, id)),
|
||||
}),
|
||||
|
||||
plan_add_edge: tool({
|
||||
@@ -144,7 +144,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
from: nodeId.describe("Prerequisite node id (must be understood before `to`)."),
|
||||
to: nodeId.describe("Dependent node id (requires `from`)."),
|
||||
}),
|
||||
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx.chatId, (tree) => addEdge(tree, from, to)),
|
||||
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => addEdge(tree, from, to)),
|
||||
}),
|
||||
|
||||
plan_remove_edge: tool({
|
||||
@@ -154,7 +154,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
from: nodeId.describe("Prerequisite end of the edge to remove."),
|
||||
to: nodeId.describe("Dependent end of the edge to remove."),
|
||||
}),
|
||||
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx.chatId, (tree) => removeEdge(tree, from, to)),
|
||||
execute: async ({ from, to }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => removeEdge(tree, from, to)),
|
||||
}),
|
||||
|
||||
plan_set_current: tool({
|
||||
@@ -162,7 +162,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
"Set the CURRENT node — where the lesson is right now. Call it the moment you START teaching a node, so the learner sees their position " +
|
||||
"on the map. The node must exist. This marks position only; it does not mark anything done.",
|
||||
inputSchema: z.object({ id: nodeId.describe("The node you are starting to teach now.") }),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx.chatId, (tree) => setCurrent(tree, id)),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => setCurrent(tree, id)),
|
||||
}),
|
||||
|
||||
plan_mark_done: tool({
|
||||
@@ -170,7 +170,7 @@ export function planTools(ctx: TeacherToolContext): ToolSet {
|
||||
"Mark a node DONE — and only when the learner has DEMONSTRATED it (a correct check), not when you finished explaining it. " +
|
||||
"The node must exist. Idempotent.",
|
||||
inputSchema: z.object({ id: nodeId.describe("The node the learner just demonstrated.") }),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx.chatId, (tree) => markDone(tree, id)),
|
||||
execute: async ({ id }): Promise<PlanToolResult> => runPlanOp(ctx, (tree) => markDone(tree, id)),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user