Swap the server engine to pi-ai/pi-agent-core (Band B+C of docs/pi-engine-swap.md)

The Vercel AI SDK survives only as Band D (useChat client + UIMessage
record types); @openrouter/ai-sdk-provider is uninstalled.

- src/agent/models.ts: PiEngine {model, streamFn} via createModels +
  openrouterProvider subpath; thinkingLevelFor maps config effort none->off
- src/agent/lh-tool.ts: neutral LhTool (zod authoring, optional execute,
  clientQuestion flag); toPiTool converts via z.toJSONSchema and re-runs
  zod inside execute so refinements ride the error-result retry path
- src/server/pi/record-adapter.ts: UIMessage records -> pi Messages
  (dangling tool calls get synthesized interrupted results)
- src/server/pi/ui-stream.ts: SSE bridge emitting AI-SDK-shaped chunks so
  the useChat client parses unchanged (continuation id rule, question
  tools never emit output, tool-input-error for bad authoring)
- teacher-agent.ts: stateless per-turn pi Agents; shouldStopAfterTurn
  stops only when every question-tool call resolved cleanly (errors retry)
- chat-handler.ts: buildAgent(outgoing) factory seam (stateless doctrine);
  assertValidUiMessages owns the retired SDK validation gate
- sub-agents via shared runSubagent (pi-run.ts); extraction stages stop
  after a clean submit; visual-maker keeps its hand-rolled loop over
  direct streamSimple calls; aborted model calls bill no usage
- tests: all model seams ported to pi-ai faux provider (scripted
  FauxResponseSteps, agent factories); handleChatRequest second param
  is now an agent factory

Gates: tsc, lint, build, 305/305. Live GLM smoke (disposable driver,
deleted): prober streaming + persistence, question seam, turn-2
continuation same message id, per-turn real token usage - ALL PASS.
Data wiped at the pivot (chats/graph/jobs, .gitkeeps kept).
This commit is contained in:
amosblomqvist
2026-09-12 02:34:18 +03:00
parent 377d4b6548
commit 2d717fd932
27 changed files with 3557 additions and 769 deletions
+11 -8
View File
@@ -1,5 +1,5 @@
import { tool, type ToolSet } from "ai";
import { z } from "zod";
import { lhTool, type LhTool } from "../lh-tool.ts";
import type { JobRecord } from "../../core/contracts.ts";
import type { JobStore } from "../../core/ports.ts";
@@ -103,21 +103,24 @@ const VISUAL_DESCRIPTION =
* context (chatId + jobStore + the spawn seam), so concurrent chats never
* share state. chat-handler wires it each turn; tests wire their own.
*/
export function jobTools(ctx: JobToolContext): ToolSet {
export function jobTools(ctx: JobToolContext): Record<string, LhTool<any, any>> {
return {
research: tool({
research: lhTool({
name: "research",
description: RESEARCH_DESCRIPTION,
inputSchema: researchInputSchema,
schema: researchInputSchema,
execute: async (input, { toolCallId }) => dispatch(ctx, "research", toolCallId, RESEARCH_ACK, input),
}),
demo: tool({
demo: lhTool({
name: "demo",
description: DEMO_DESCRIPTION,
inputSchema: demoInputSchema,
schema: demoInputSchema,
execute: async (input, { toolCallId }) => dispatch(ctx, "demo", toolCallId, DEMO_ACK, input),
}),
visual: tool({
visual: lhTool({
name: "visual",
description: VISUAL_DESCRIPTION,
inputSchema: visualInputSchema,
schema: visualInputSchema,
execute: async (input, { toolCallId }) => dispatch(ctx, "visual", toolCallId, VISUAL_ACK, input),
}),
};
+5 -4
View File
@@ -1,5 +1,5 @@
import { tool, type ToolSet } from "ai";
import { z } from "zod";
import { lhTool, type LhTool } from "../lh-tool.ts";
import type { PlanToolResult, PlanTree } from "../../core/contracts.ts";
import type { ChatStore } from "../../core/ports.ts";
import { createTree, emptyTree, PlanTreeError } from "../../core/plan-tree.ts";
@@ -37,16 +37,17 @@ export interface PlanToolContext {
* latest state straight from the transcript's tool outputs (the plan
* window and the plan blocks).
*/
export function planTools(ctx: PlanToolContext): ToolSet {
export function planTools(ctx: PlanToolContext): Record<string, LhTool<any, any>> {
return {
plan_init: tool({
plan_init: lhTool({
name: "plan_init",
description:
"Write or REWRITE this session's plan map — the dependency graph the learner follows live in the plan window. " +
"Call once right after the probe concludes, to present the map; re-call whenever the map is wrong (the new block replaces the old tree). " +
"A mermaid graph block (any direction): one node per line (`slug[Short Title]` — slugs are permanent lowercase ids: a-z, 0-9, hyphens/underscores), " +
"`-->` edges meaning 'from must be understood before to' (chains fine). 5–15 nodes: a map, not a syllabus — one reasoning step per node, compress. " +
"Every check you fire names the node it assesses via `nodeId`; where the lesson stands derives from those tags.",
inputSchema: z.object({
schema: z.object({
mermaid: z
.string()
.min(1)
+5 -4
View File
@@ -1,5 +1,5 @@
import { tool, type ToolSet } from "ai";
import { z } from "zod";
import { lhTool, type LhTool } from "../lh-tool.ts";
import type { ProbeDoneInput, ProbeDoneResult } from "../../core/contracts.ts";
import type { UIMessage } from "ai";
import { findPendingToolCall } from "../../core/pending.ts";
@@ -44,9 +44,10 @@ function probeConcluded(messages: UIMessage[]): boolean {
* The first probe_done in the transcript is also the construction seam:
* from that message on, every request builds the TEACHER agent.
*/
export function probeDoneTool(ctx: ProbeDoneContext): ToolSet {
export function probeDoneTool(ctx: ProbeDoneContext): Record<string, LhTool<any, any>> {
return {
probe_done: tool({
probe_done: lhTool({
name: "probe_done",
description:
"Conclude the probing phase and hand off to the teaching phase. Call this ONCE, when the probe is " +
"complete: every strand the lesson depends on is bracketed (a floor he reliably gets right AND a " +
@@ -55,7 +56,7 @@ export function probeDoneTool(ctx: ProbeDoneContext): ToolSet {
"(floor, ceiling, misconceptions, what to build from). It streams to the learner live and becomes " +
"the handoff artifact the teacher plans from. Refused while a question is still open, and after " +
"the probe is already concluded. After it succeeds, say your closing sentence and end your turn.",
inputSchema: z.object({
schema: z.object({
assessment: z
.object({
strands: z
+7 -5
View File
@@ -1,5 +1,5 @@
import { tool } from "ai";
import { z } from "zod";
import { lhTool } from "../lh-tool.ts";
import { Readability } from "@mozilla/readability";
import { parseHTML } from "linkedom";
import TurndownService from "turndown";
@@ -137,11 +137,12 @@ async function fetchAndExtract(url: string): Promise<string> {
// ── tool registry ────────────────────────────────────────────────────────────
export const webTools = {
web_search: tool({
web_search: lhTool({
name: "web_search",
description:
"Search the web via Google Custom Search. One search per call — use one call per search angle. " +
"Returns an array of results with title, url, and snippet.",
inputSchema: z.object({
schema: z.object({
query: z.string().describe("The search query (a normal search string, phrases included)"),
count: z.number().int().min(1).max(10).optional().describe("Number of results (default 5, max 10)"),
}),
@@ -161,11 +162,12 @@ export const webTools = {
},
}),
web_fetch: tool({
web_fetch: lhTool({
name: "web_fetch",
description:
"Fetch a web page and extract its readable content as markdown (Readability). " +
"Handles HTML pages and plain text; JS-rendered pages fall back to a reader service.",
inputSchema: z.object({
schema: z.object({
url: z.string().describe("The URL to fetch"),
}),
execute: async ({ url }): Promise<string> => {