Wave A: pi-native tool layer — delete LhTool/toPiTool, TypeBox everywhere, terminate on questions
- src/agent/lh-tool.ts deleted: the zod-wrapped LhTool + toPiTool bridge (z.toJSONSchema per call, clientQuestion flag, hand-rolled result mapping) is gone. Tools are pi-agent-core native AgentTools now. - New src/agent/tool-execute.ts owns what the wrapper added: the abort guard (runWithAbortGuard: run signal + 30s per-call timeout + 250ms grace, 'Operation aborted' / timeout wording preserved), ToolInputError (the retryable '- problem at path' format), result mapping (string verbatim / object JSON / image parts, details rides the record's tool part output), and questionResult() — placeholder + terminate:true (owner Option A: belt of terminate + slim makeQuestionStopper with the clean-question rule; maxTurns deleted from the teaching turn entirely per owner). - All 11 tool files + tools.ts registries converted to TypeBox parameters (typebox@1.3.7, pinned to pi-agent-core's copy). zod refinements (quizInputProblems, askOptionProblems, live-nodeId) moved from schemas into execute — the model sees the same retryable error shape. - question-core + contracts/probe TypeBox-authored (single source shared with the UI); tool-parts parse seam runs the boundary's full chain (Convert → Check → Clean → refinement), fixing the live-smoke lockout: pi's boundary Value.Converts correctAnswer: 17 → '17' but the record keeps raw args, so a parse without Convert rejected a posed quiz (invisible pending question, turn ended). Pinned with the real smoke emission shape. - Subagents converted: demo-builder/researcher AgentTool-native, visual-maker/pdf-reader declaration-only pi-ai Tools with local execute fns, extraction submit schemas re-authored in TypeBox (owner option 2: zod defaults → Type.Optional + fill at the submit seam). - Accepted delta, flagged: TypeBox-native schemas skip pi's JSON-Schema primitive coercion fast path... (boundary still Value.Converts), and prober-quiz unknown keys ride through (Value.Clean strips at display). - Tests: 988 passing (was 967 at the recon baseline); tool-abort and read-tool rewritten against the native seams; question-core/question- tools/tool-parts/demos/web-search/graph-tools/plan-tree/probe-done/ tool-toggles converted to Value.Check/execute pins. Live smoke (PORT=3004, real model): native ls turn streams end-to-end; a real quiz pose (first attempt missing correctAnswer → tool-input-error → model retry → posed) terminates the turn cleanly and persists pending.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { z } from "zod";
|
||||
import { Type } from "typebox";
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import type { Usage } from "@earendil-works/pi-ai";
|
||||
import { lhTool, toPiTools, type LhTool } from "../lh-tool.ts";
|
||||
import { serverExecute } from "../tool-execute.ts";
|
||||
import type { PiEngine } from "../models.ts";
|
||||
import { runSubagent } from "./pi-run.ts";
|
||||
import type { DemoResult } from "../../core/contracts.ts";
|
||||
@@ -77,39 +78,48 @@ interface BuilderState {
|
||||
lastResult: DemoRunResult | null;
|
||||
}
|
||||
|
||||
const writeDemoInput = Type.Object({
|
||||
html: Type.String({ description: "The complete HTML document: <!doctype html>…</html>, all JS inline." }),
|
||||
});
|
||||
|
||||
const runDemoInput = Type.Object({
|
||||
probe: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
"Optional JS expression evaluated in the page after settling, e.g. \"document.querySelectorAll('input').length\".",
|
||||
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export function createDemoBuilderTools(
|
||||
state: BuilderState,
|
||||
headless: HeadlessApi,
|
||||
onActivity?: (line: string) => void,
|
||||
): Record<string, LhTool<any, any>> {
|
||||
): Record<string, AgentTool<any>> {
|
||||
return {
|
||||
write_demo: lhTool({
|
||||
write_demo: {
|
||||
name: "write_demo",
|
||||
label: "write_demo",
|
||||
description:
|
||||
"Write the complete self-contained HTML document for the demo (overwrites any previous version). " +
|
||||
"Always follow with run_demo to test it headlessly.",
|
||||
schema: z.object({
|
||||
html: z.string().describe("The complete HTML document: <!doctype html>…</html>, all JS inline."),
|
||||
}),
|
||||
execute: async ({ html }) => {
|
||||
parameters: writeDemoInput,
|
||||
execute: serverExecute("write_demo", writeDemoInput, async ({ html }) => {
|
||||
if (!html || html.trim().length === 0) return "ERROR: empty document — write the full HTML.";
|
||||
state.html = html;
|
||||
onActivity?.(`write_demo: ${(html.length / 1024).toFixed(1)} KB`);
|
||||
return `Saved (${html.length} bytes). Now call run_demo to test it — never deliver untested.`;
|
||||
},
|
||||
}),
|
||||
run_demo: lhTool({
|
||||
}),
|
||||
},
|
||||
run_demo: {
|
||||
name: "run_demo",
|
||||
label: "run_demo",
|
||||
description:
|
||||
"Headlessly execute the current demo in Chrome and report console errors, uncaught errors, and failed requests. " +
|
||||
"Optionally pass a probe expression to assert on page state.",
|
||||
schema: z.object({
|
||||
probe: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Optional JS expression evaluated in the page after settling, e.g. \"document.querySelectorAll('input').length\"."),
|
||||
}),
|
||||
execute: async ({ probe }) => {
|
||||
parameters: runDemoInput,
|
||||
execute: serverExecute("run_demo", runDemoInput, async ({ probe }) => {
|
||||
if (!state.html) return "ERROR: nothing to run — call write_demo first.";
|
||||
const reason = headless.unavailableReason();
|
||||
if (reason) return `HEADLESS UNAVAILABLE: ${reason}`;
|
||||
@@ -127,8 +137,8 @@ export function createDemoBuilderTools(
|
||||
result.ok ? "run_demo: clean" : `run_demo: ${summarizeCounts(result)}`,
|
||||
);
|
||||
return formatRunResult(result);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,7 +200,7 @@ export async function runDemoBuilder(input: DemoBuilderInput, opts: DemoBuilderO
|
||||
|
||||
let finalText = "";
|
||||
try {
|
||||
const result = await runSubagent(toPiTools(createDemoBuilderTools(state, headless, opts.onActivity)), {
|
||||
const result = await runSubagent(Object.values(createDemoBuilderTools(state, headless, opts.onActivity)), {
|
||||
role: "demoBuilder",
|
||||
engine: opts.engine,
|
||||
systemPrompt: INSTRUCTIONS,
|
||||
|
||||
+184
-109
@@ -1,8 +1,9 @@
|
||||
import * as crypto from "node:crypto";
|
||||
import type { UIMessage } from "ai";
|
||||
import type { Usage } from "@earendil-works/pi-ai";
|
||||
import { z } from "zod";
|
||||
import { lhTool, toPiTools } from "../lh-tool.ts";
|
||||
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import { Type, type Static, type TSchema } from "typebox";
|
||||
import { toToolResult } from "../tool-execute.ts";
|
||||
import type { ModelRole } from "../../../config.ts";
|
||||
import {
|
||||
FACTORY_SETTINGS,
|
||||
@@ -45,7 +46,7 @@ import { batchRuns, batchTag, coverageOf, messageViewLines } from "../../core/co
|
||||
* The LLM stages supply only the judgment calls; the deterministic rebuild
|
||||
* in the merger owns everything that must never be mis-copied (event kinds,
|
||||
* timestamps, refs, provenance points). Both agents are single-tool-call
|
||||
* workers: their whole deliverable is one zod-validated submit call — a
|
||||
* workers: their whole deliverable is one TypeBox-validated submit call — a
|
||||
* ToolLoopAgent purely so the model can retry a schema-invalid call.
|
||||
*
|
||||
* Created via createExtractionPipeline(deps) — the composition root
|
||||
@@ -101,75 +102,170 @@ export function transcriptView(record: ChatRecord): string {
|
||||
|
||||
// ─── the extractor ──────────────────────────────────────────────────────────
|
||||
|
||||
const evidence = z
|
||||
.array(z.string())
|
||||
.min(1)
|
||||
.describe("Verbatim quotes from the transcript that back this. The auditor will check every quote.");
|
||||
const evidenceSchema = Type.Array(Type.String(), {
|
||||
minItems: 1,
|
||||
description: "Verbatim quotes from the transcript that back this. The auditor will check every quote.",
|
||||
});
|
||||
|
||||
const messagesField = z
|
||||
.array(z.string())
|
||||
.describe("The message ids (from the [id] tags in the transcript) where this came up — provenance.");
|
||||
const messagesSchema = Type.Array(Type.String(), {
|
||||
description: "The message ids (from the [id] tags in the transcript) where this came up — provenance.",
|
||||
});
|
||||
|
||||
const propositionSchema = z.object({
|
||||
id: z.string().describe("Local id: \"p1\", \"p2\", … — referenced by edges and attribution."),
|
||||
name: z
|
||||
.string()
|
||||
.describe(
|
||||
"A very short label for the proposition — a few words, a compact handle like a glossary headword " +
|
||||
'(\'Will to power\', \'Divine command theory\'). Not a sentence, needn\'t be unique or ' +
|
||||
"self-contained: the statement carries the precision. This becomes the node's label in the graph.",
|
||||
),
|
||||
statement: z
|
||||
.string()
|
||||
.describe(
|
||||
"The proposition as one reasoning step — a TRUE, self-contained, world-facing statement. " +
|
||||
"Never reference the learner, the teacher, or the session: not \"the learner understands X\" but " +
|
||||
'"X". A misconception is stated as the TRUE correction ("Nietzsche did not endorse ' +
|
||||
'might-makes-right social Darwinism") — the wrongness lives in the quiz outcomes, never here.',
|
||||
),
|
||||
aliases: z.array(z.string()).describe("Verbatim phrasings this session used for the same proposition, if any."),
|
||||
messages: messagesField,
|
||||
evidence,
|
||||
understanding: z
|
||||
.enum(["solid", "shaky", "accepted", "resisted", "not yet engaged"])
|
||||
.optional()
|
||||
.describe(
|
||||
"ONE word — the learner's grasp of this proposition in THIS session, from the fixed scale " +
|
||||
const understandingSchema = Type.Optional(
|
||||
Type.Union(
|
||||
[
|
||||
Type.Literal("solid"),
|
||||
Type.Literal("shaky"),
|
||||
Type.Literal("accepted"),
|
||||
Type.Literal("resisted"),
|
||||
Type.Literal("not yet engaged"),
|
||||
],
|
||||
{
|
||||
description:
|
||||
"ONE word — the learner's grasp of this proposition in THIS session, from the fixed scale " +
|
||||
'"solid" | "shaky" | "accepted" | "resisted" | "not yet engaged". Nothing else: no numbers, ' +
|
||||
"no justification, no explanation.",
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const propositionProps = {
|
||||
id: Type.String({ description: 'Local id: "p1", "p2", … — referenced by edges and attribution.' }),
|
||||
name: Type.String({
|
||||
description:
|
||||
"A very short label for the proposition — a few words, a compact handle like a glossary headword " +
|
||||
"('Will to power', 'Divine command theory'). Not a sentence, needn't be unique or " +
|
||||
"self-contained: the statement carries the precision. This becomes the node's label in the graph.",
|
||||
}),
|
||||
statement: Type.String({
|
||||
description:
|
||||
"The proposition as one reasoning step — a TRUE, self-contained, world-facing statement. " +
|
||||
'Never reference the learner, the teacher, or the session: not "the learner understands X" but ' +
|
||||
'"X". A misconception is stated as the TRUE correction ("Nietzsche did not endorse ' +
|
||||
'might-makes-right social Darwinism") — the wrongness lives in the quiz outcomes, never here.',
|
||||
}),
|
||||
aliases: Type.Array(Type.String(), {
|
||||
description: "Verbatim phrasings this session used for the same proposition, if any.",
|
||||
}),
|
||||
messages: messagesSchema,
|
||||
evidence: evidenceSchema,
|
||||
understanding: understandingSchema,
|
||||
};
|
||||
|
||||
const edgeSchema = Type.Object({
|
||||
from: Type.String({ description: "Proposition id that is followed / supported." }),
|
||||
to: Type.String({ description: "Proposition id that follows / is supported by `from`." }),
|
||||
type: Type.Union([Type.Literal("follows"), Type.Literal("supports")], {
|
||||
description: '"follows" = to is derivable from from; "supports" = from grounds to without entailing it.',
|
||||
}),
|
||||
messages: messagesSchema,
|
||||
evidence: evidenceSchema,
|
||||
});
|
||||
|
||||
// Weak-model tolerance (owner, 2026-09-25): the old zod `.default([])` /
|
||||
// `.default({ quiz: {} })` on required-but-empty fields becomes Type.Optional
|
||||
// here + a ??-fill at the submit seam (fillFindings/fillAudit below) — same
|
||||
// contract on the wire (omission tolerated, empty never means "invalid"),
|
||||
// no zod left in the agent band.
|
||||
const findingsProps = {
|
||||
propositions: Type.Array(Type.Object(propositionProps), {
|
||||
description: "Every distinct proposition the session touched — true statements, misconception-free.",
|
||||
}),
|
||||
edges: Type.Optional(
|
||||
Type.Array(edgeSchema, {
|
||||
description:
|
||||
"Relations between propositions: follows (derivable) / supports (grounds without entailing). Pass [] when there are none — never omit the field.",
|
||||
}),
|
||||
),
|
||||
attribution: Type.Optional(
|
||||
Type.Object(
|
||||
{
|
||||
quiz: Type.Record(Type.String(), Type.Union([Type.String(), Type.Null()]), {
|
||||
description:
|
||||
"toolCallId of EVERY quiz line → the proposition id it was really testing. Attribute RETROACTIVELY — the whole transcript is visible; map each quiz to the proposition it tests (often articulated elsewhere in the session). null when genuinely unattributable.",
|
||||
}),
|
||||
},
|
||||
{
|
||||
description:
|
||||
"Quiz attribution — your only event judgment. Pass { quiz: {} } when the session has no quiz lines — never omit the field.",
|
||||
},
|
||||
),
|
||||
});
|
||||
),
|
||||
};
|
||||
|
||||
const edgeSchema = z.object({
|
||||
from: z.string().describe("Proposition id that is followed / supported."),
|
||||
to: z.string().describe("Proposition id that follows / is supported by `from`."),
|
||||
type: z
|
||||
.enum(["follows", "supports"])
|
||||
.describe('"follows" = to is derivable from from; "supports" = from grounds to without entailing it.'),
|
||||
messages: messagesField,
|
||||
evidence,
|
||||
});
|
||||
const findingsSchema = Type.Object(findingsProps);
|
||||
|
||||
const findingsSchema = z.object({
|
||||
propositions: z
|
||||
.array(propositionSchema)
|
||||
.describe("Every distinct proposition the session touched — true statements, misconception-free."),
|
||||
edges: z
|
||||
.array(edgeSchema)
|
||||
.describe("Relations between propositions: follows (derivable) / supports (grounds without entailing). Pass [] when there are none — never omit the field.")
|
||||
.default([]), // weak models omit required-but-empty arrays; omission means "none"
|
||||
const auditProps = {
|
||||
...findingsProps,
|
||||
propositions: Type.Array(
|
||||
Type.Object({
|
||||
...propositionProps,
|
||||
linkTo: Type.Optional(
|
||||
Type.String({
|
||||
description:
|
||||
"The id of the EXISTING graph node this proposition IS — your identity verdict. Absent = create a new node. When unsure, omit: duplicates over wrong merges.",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{
|
||||
description: "Every distinct proposition the session touched — true statements, misconception-free.",
|
||||
},
|
||||
),
|
||||
dropped: Type.Optional(
|
||||
Type.Array(
|
||||
Type.Object({
|
||||
ref: Type.String({
|
||||
description: 'Proposition id, "from→to" for an edge, or attribution toolCallId.',
|
||||
}),
|
||||
reason: Type.String(),
|
||||
}),
|
||||
{
|
||||
description:
|
||||
"Everything you dropped, with the reason — the audit trail. Pass [] when you dropped nothing — never omit the field.",
|
||||
},
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
attribution: z
|
||||
.object({
|
||||
quiz: z
|
||||
.record(z.string(), z.string().nullable())
|
||||
.describe(
|
||||
"toolCallId of EVERY quiz line → the proposition id it was really testing. Attribute RETROACTIVELY — the whole transcript is visible; map each quiz to the proposition it tests (often articulated elsewhere in the session). null when genuinely unattributable.",
|
||||
),
|
||||
})
|
||||
.describe("Quiz attribution — your only event judgment. Pass { quiz: {} } when the session has no quiz lines — never omit the field.")
|
||||
.default({ quiz: {} }), // weak models omit empty objects too
|
||||
});
|
||||
const auditSchema = Type.Object(auditProps);
|
||||
|
||||
// The notes front door's shapes: everything session findings have, minus
|
||||
// quiz attribution — raw notes have no quiz tool parts, so there is
|
||||
// nothing to attribute (and no event to build: outcomes inside the text
|
||||
// surface only through understanding observations, user-decided).
|
||||
const { attribution: _omitted, ...notesFindingsProps } = findingsProps;
|
||||
const notesFindingsSchema = Type.Object(notesFindingsProps);
|
||||
const { attribution: _omitted2, ...notesAuditProps } = auditProps;
|
||||
const notesAuditSchema = Type.Object(notesAuditProps);
|
||||
type NotesFindings = Omit<SessionFindings, "attribution">;
|
||||
type NotesAuditResult = Omit<AuditResult, "attribution">;
|
||||
|
||||
// ── the weak-model ??-fills (the old zod defaults, applied at submit) ──
|
||||
|
||||
function fillFindings(raw: Static<typeof findingsSchema>): SessionFindings {
|
||||
return {
|
||||
propositions: raw.propositions,
|
||||
edges: raw.edges ?? [],
|
||||
attribution: raw.attribution ?? { quiz: {} },
|
||||
};
|
||||
}
|
||||
|
||||
function fillNotesFindings(raw: Static<typeof notesFindingsSchema>): NotesFindings {
|
||||
return { propositions: raw.propositions, edges: raw.edges ?? [] };
|
||||
}
|
||||
|
||||
function fillAudit(raw: Static<typeof auditSchema>): AuditResult {
|
||||
return {
|
||||
propositions: raw.propositions,
|
||||
edges: raw.edges ?? [],
|
||||
attribution: raw.attribution ?? { quiz: {} },
|
||||
dropped: raw.dropped ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
function fillNotesAudit(raw: Static<typeof notesAuditSchema>): NotesAuditResult {
|
||||
return { propositions: raw.propositions, edges: raw.edges ?? [], dropped: raw.dropped ?? [] };
|
||||
}
|
||||
|
||||
const NOTES_EXTRACTOR_INSTRUCTIONS = `You are the extraction specialist in a learning application. You read ONE source —
|
||||
the user's own NOTES, in an ARBITRARY format (personal notes, an exported conversation, a document — anything) — and
|
||||
@@ -260,15 +356,19 @@ are no quizzes. NEVER omit a field because it is empty.
|
||||
Your entire deliverable is ONE submit_findings call.`;
|
||||
|
||||
/** One single-submit agent run — the shared shape of EVERY LLM stage
|
||||
* here (session + notes): the whole deliverable is ONE zod-validated
|
||||
* here (session + notes): the whole deliverable is ONE TypeBox-validated
|
||||
* submit call (a pi agent purely so the model can retry a schema-invalid
|
||||
* call). The submitted value is captured from the execute seam, which
|
||||
* only fires on a schema-valid call. */
|
||||
* only fires on a schema-valid call — the ??-fill (the old zod defaults)
|
||||
* applies at the capture. */
|
||||
async function runSubmitAgent<T>(opts: {
|
||||
role: ModelRole;
|
||||
toolName: string;
|
||||
toolDescription: string;
|
||||
schema: z.ZodType<T>;
|
||||
parameters: TSchema;
|
||||
/** Weak-model tolerance: the old zod `.default()`s, applied to the
|
||||
* schema-valid raw input at the submit seam. */
|
||||
fill: (input: any) => T;
|
||||
systemPrompt: string;
|
||||
prompt: string;
|
||||
engine: PiEngine | undefined;
|
||||
@@ -278,17 +378,18 @@ async function runSubmitAgent<T>(opts: {
|
||||
}): Promise<T> {
|
||||
let submitted: T | undefined;
|
||||
const result = await runSubagent(
|
||||
toPiTools({
|
||||
[opts.toolName]: lhTool({
|
||||
[
|
||||
{
|
||||
name: opts.toolName,
|
||||
label: opts.toolName,
|
||||
description: opts.toolDescription,
|
||||
schema: opts.schema,
|
||||
execute: async (findings) => {
|
||||
submitted = findings;
|
||||
return findings;
|
||||
parameters: opts.parameters,
|
||||
execute: async (_toolCallId, input) => {
|
||||
submitted = opts.fill(input);
|
||||
return toToolResult(submitted);
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} satisfies AgentTool<any>,
|
||||
],
|
||||
{
|
||||
role: opts.role,
|
||||
engine: opts.engine,
|
||||
@@ -326,7 +427,8 @@ function runExtractor(
|
||||
role: "extractor",
|
||||
toolName: "submit_findings",
|
||||
toolDescription: "Submit the session findings.",
|
||||
schema: findingsSchema,
|
||||
parameters: findingsSchema,
|
||||
fill: fillFindings,
|
||||
systemPrompt: EXTRACTOR_INSTRUCTIONS,
|
||||
prompt,
|
||||
engine,
|
||||
@@ -348,7 +450,8 @@ function runNotesExtractor(
|
||||
role: "extractor",
|
||||
toolName: "submit_findings",
|
||||
toolDescription: "Submit the notes findings.",
|
||||
schema: notesFindingsSchema,
|
||||
parameters: notesFindingsSchema,
|
||||
fill: fillNotesFindings,
|
||||
systemPrompt: NOTES_EXTRACTOR_INSTRUCTIONS,
|
||||
prompt,
|
||||
engine,
|
||||
@@ -360,36 +463,6 @@ function runNotesExtractor(
|
||||
|
||||
// ─── the auditor ───────────────────────────────────────────────────────────
|
||||
|
||||
const auditSchema = findingsSchema.extend({
|
||||
propositions: z.array(
|
||||
propositionSchema.extend({
|
||||
linkTo: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
"The id of the EXISTING graph node this proposition IS — your identity verdict. Absent = create a new node. When unsure, omit: duplicates over wrong merges.",
|
||||
),
|
||||
}),
|
||||
),
|
||||
dropped: z
|
||||
.array(
|
||||
z.object({
|
||||
ref: z.string().describe("Proposition id, \"from→to\" for an edge, or attribution toolCallId."),
|
||||
reason: z.string(),
|
||||
}),
|
||||
)
|
||||
.describe("Everything you dropped, with the reason — the audit trail. Pass [] when you dropped nothing — never omit the field.")
|
||||
.default([]), // same weak-model tolerance as findings.edges
|
||||
});
|
||||
|
||||
// The notes front door's shapes: everything session findings have, minus
|
||||
// quiz attribution — raw notes have no quiz tool parts, so there is
|
||||
// nothing to attribute (and no event to build: outcomes inside the text
|
||||
// surface only through understanding observations, user-decided).
|
||||
const notesFindingsSchema = findingsSchema.omit({ attribution: true });
|
||||
const notesAuditSchema = auditSchema.omit({ attribution: true });
|
||||
type NotesFindings = Omit<SessionFindings, "attribution">;
|
||||
type NotesAuditResult = Omit<AuditResult, "attribution">;
|
||||
|
||||
const AUDITOR_INSTRUCTIONS = `You are the audit stage of a learning application's extraction pipeline. You receive
|
||||
ONE source — a session transcript, or the author's personal notes in an ARBITRARY format (the notes front door) — a
|
||||
@@ -453,7 +526,8 @@ function runAuditor(
|
||||
role: "auditor",
|
||||
toolName: "submit_review",
|
||||
toolDescription: "Submit the verified findings subset (with identity verdicts) + the dropped list.",
|
||||
schema: auditSchema,
|
||||
parameters: auditSchema,
|
||||
fill: fillAudit,
|
||||
systemPrompt: AUDITOR_INSTRUCTIONS,
|
||||
prompt,
|
||||
engine,
|
||||
@@ -475,7 +549,8 @@ function runNotesAuditor(
|
||||
role: "auditor",
|
||||
toolName: "submit_review",
|
||||
toolDescription: "Submit the verified findings subset (with identity verdicts) + the dropped list.",
|
||||
schema: notesAuditSchema,
|
||||
parameters: notesAuditSchema,
|
||||
fill: fillNotesAudit,
|
||||
systemPrompt: AUDITOR_INSTRUCTIONS,
|
||||
prompt,
|
||||
engine,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { AssistantMessage, Message, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
|
||||
import { z } from "zod";
|
||||
import { lhTool, piToolDeclarations, type LhTool } from "../lh-tool.ts";
|
||||
import type { AssistantMessage, Message, ToolResultMessage, Usage, Tool } from "@earendil-works/pi-ai";
|
||||
import { Type } from "typebox";
|
||||
import { piEngineFor, type PiEngine, type ThinkingLevel } from "../models.ts";
|
||||
import type { PdfResult, PdfToolInput } from "../../core/contracts.ts";
|
||||
import { getHeadless, type HeadlessApi } from "./headless.ts";
|
||||
@@ -70,79 +69,75 @@ export interface PdfReaderOptions {
|
||||
|
||||
export interface PdfReaderInput extends PdfToolInput {}
|
||||
|
||||
export function createPdfTools(
|
||||
pdfPath: string,
|
||||
): {
|
||||
pdf_info: LhTool<any, any>;
|
||||
pdf_extract: LhTool<any, any>;
|
||||
pdf_render: LhTool<any, any>;
|
||||
pdf_search: LhTool<any, any>;
|
||||
} {
|
||||
/** The wire declarations (pi-ai Tool, TypeBox parameters). This loop owns
|
||||
* execution itself — pdf_info/pdf_extract run via the plain pdfInfoText/
|
||||
* pdfExtractText bodies below, pdf_search/pdf_render dispatch inline in
|
||||
* the loop (search hits must join the citation set; renders feed the
|
||||
* image-in-the-loop message) — so the declarations carry no execute.
|
||||
* dpi/context_lines/literal carry the old zod `.default()`s as schema
|
||||
* descriptions + loop-side ??-fills (the loop reads them via numOr). */
|
||||
export function createPdfTools(_pdfPath: string): Record<string, Tool> {
|
||||
return {
|
||||
pdf_info: lhTool({
|
||||
pdf_info: {
|
||||
name: "pdf_info",
|
||||
description: "Metadata + per-page triage signals for the PDF (page count, text length, image count, math density). ALWAYS call this first.",
|
||||
schema: z.object({}),
|
||||
execute: async () => {
|
||||
const info = await pdfInfo(pdfPath);
|
||||
const lines = [
|
||||
`File: ${info.path}`,
|
||||
`Pages: ${info.page_count} (mean text length/page: ${info.mean_text_length})`,
|
||||
...info.pages.map(
|
||||
(p) =>
|
||||
`p${p.page}: len=${p.text_length} img=${p.image_count} math=${p.math_density.toFixed(2)}`,
|
||||
),
|
||||
];
|
||||
return lines.join("\n");
|
||||
},
|
||||
}),
|
||||
pdf_extract: lhTool({
|
||||
parameters: Type.Object({}),
|
||||
},
|
||||
pdf_extract: {
|
||||
name: "pdf_extract",
|
||||
description: "Extract text from pages (spec: 'all', '1-5', '1,3,7', '3'). Use pdf_info first; narrow the spec for big documents.",
|
||||
schema: z.object({ pages: z.string().describe("Page spec, e.g. 'all', '1-5', '1,3,7'") }),
|
||||
execute: async ({ pages }) => {
|
||||
const text = await pdfExtract(pdfPath, pages);
|
||||
if (text.length > EXTRACT_CAP) {
|
||||
return `${text.slice(0, EXTRACT_CAP)}\n\n[Output truncated at ${EXTRACT_CAP} chars — narrow the page spec and extract in smaller batches.]`;
|
||||
}
|
||||
return text;
|
||||
},
|
||||
}),
|
||||
pdf_render: lhTool({
|
||||
parameters: Type.Object({
|
||||
pages: Type.String({ description: "Page spec, e.g. 'all', '1-5', '1,3,7'" }),
|
||||
}),
|
||||
},
|
||||
pdf_render: {
|
||||
name: "pdf_render",
|
||||
description:
|
||||
"Render pages to images and show them to you for visual reading (equations, diagrams, layout). DPI: 100 text, 150 default, 200 dense small print. Max 6 pages per call.",
|
||||
schema: z.object({
|
||||
pages: z.string().describe("Page spec, e.g. '1-3' or '2,5,8'"),
|
||||
dpi: z.number().int().min(72).max(300).default(150).describe("Render DPI (100 text / 150 default / 200 dense)"),
|
||||
parameters: Type.Object({
|
||||
pages: Type.String({ description: "Page spec, e.g. '1-3' or '2,5,8'" }),
|
||||
dpi: Type.Optional(
|
||||
Type.Integer({ minimum: 72, maximum: 300, description: "Render DPI (100 text / 150 default / 200 dense)" }),
|
||||
),
|
||||
}),
|
||||
execute: async () => {
|
||||
// Actual rendering happens OUTSIDE execute — the loop appends the
|
||||
// images as a user message after the tool results (the
|
||||
// image-in-the-loop idiom). execute returns the plan the loop uses.
|
||||
return "render requested";
|
||||
},
|
||||
}),
|
||||
pdf_search: lhTool({
|
||||
},
|
||||
pdf_search: {
|
||||
name: "pdf_search",
|
||||
description: "Search the PDF's text by keyword or regex (case-insensitive); returns hits with context lines. Use for long documents before reading anything at length.",
|
||||
schema: z.object({
|
||||
query: z.string().describe("Keyword or regex"),
|
||||
context_lines: z.number().int().min(0).max(8).default(3).describe("Context lines around each hit"),
|
||||
literal: z.boolean().default(false).describe("true = treat the query literally (no regex)"),
|
||||
parameters: Type.Object({
|
||||
query: Type.String({ description: "Keyword or regex" }),
|
||||
context_lines: Type.Optional(
|
||||
Type.Integer({ minimum: 0, maximum: 8, description: "Context lines around each hit (default 3)" }),
|
||||
),
|
||||
literal: Type.Optional(Type.Boolean({ description: "true = treat the query literally (no regex; default false)" })),
|
||||
}),
|
||||
execute: async ({ query, context_lines, literal }) => {
|
||||
const { hits } = await pdfSearch(pdfPath, query, { contextLines: context_lines, literal });
|
||||
if (hits.length === 0) return "No hits.";
|
||||
const cap = hits.slice(0, 40);
|
||||
const body = cap.map((h: PdfSearchHit) => `=== Page ${h.page}, line ${h.line} ===\n${h.context}`).join("\n");
|
||||
const more = hits.length > cap.length ? `\n\n[${hits.length - cap.length} more hits — narrow the query.]` : "";
|
||||
return body + more;
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** pdf_info's body (the loop's dispatch target): the triage readout. */
|
||||
async function pdfInfoText(pdfPath: string): Promise<string> {
|
||||
const info = await pdfInfo(pdfPath);
|
||||
const lines = [
|
||||
`File: ${info.path}`,
|
||||
`Pages: ${info.page_count} (mean text length/page: ${info.mean_text_length})`,
|
||||
...info.pages.map(
|
||||
(p) =>
|
||||
`p${p.page}: len=${p.text_length} img=${p.image_count} math=${p.math_density.toFixed(2)}`,
|
||||
),
|
||||
];
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/** pdf_extract's body: capped text extraction with the narrow-the-spec notice. */
|
||||
async function pdfExtractText(pdfPath: string, pages: string): Promise<string> {
|
||||
const text = await pdfExtract(pdfPath, pages);
|
||||
if (text.length > EXTRACT_CAP) {
|
||||
return `${text.slice(0, EXTRACT_CAP)}\n\n[Output truncated at ${EXTRACT_CAP} chars — narrow the page spec and extract in smaller batches.]`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function toolText(toolCallId: string, toolName: string, value: string): ToolResultMessage {
|
||||
return {
|
||||
role: "toolResult",
|
||||
@@ -179,7 +174,7 @@ export async function runPdfReaderAgent(
|
||||
// doctrine degrades to extract+search (render calls return an error note).
|
||||
|
||||
const tools = createPdfTools(pdfPath);
|
||||
const toolDeclarations = piToolDeclarations(tools);
|
||||
const toolDeclarations = Object.values(tools);
|
||||
const engine = opts.engine ?? piEngineFor("pdfReader");
|
||||
// BYOK (owner, 2026-09-22): the level rides the injected engine — no
|
||||
// factory pin to consult (engine.level is the resolved/clamped value).
|
||||
@@ -242,12 +237,12 @@ export async function runPdfReaderAgent(
|
||||
try {
|
||||
if (call.name === "pdf_info") {
|
||||
opts.onActivity?.("pdf_info: triaging");
|
||||
const r = await tools.pdf_info.execute!({}, { toolCallId: call.id });
|
||||
const r = await pdfInfoText(pdfPath);
|
||||
toolResults.push(toolText(call.id, call.name, String(r)));
|
||||
} else if (call.name === "pdf_extract") {
|
||||
const spec = String(args.pages ?? "all");
|
||||
opts.onActivity?.(`pdf_extract: ${spec}`);
|
||||
const r = await tools.pdf_extract.execute!({ pages: spec }, { toolCallId: call.id });
|
||||
const r = await pdfExtractText(pdfPath, spec);
|
||||
toolResults.push(toolText(call.id, call.name, String(r)));
|
||||
for (const p of specNumbers(spec, Infinity)) {
|
||||
consulted.add(p);
|
||||
@@ -393,7 +388,7 @@ async function streamOnce(
|
||||
engine: PiEngine,
|
||||
systemPrompt: string,
|
||||
messages: Message[],
|
||||
tools: ReturnType<typeof piToolDeclarations>,
|
||||
tools: Tool[],
|
||||
reasoning: ThinkingLevel | undefined,
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<AssistantMessage> {
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
|
||||
import type { Usage } from "@earendil-works/pi-ai";
|
||||
import { createWebTools } from "../tools/web.ts";
|
||||
import type { SearchProvider } from "../../core/search.ts";
|
||||
import { toPiTools } from "../lh-tool.ts";
|
||||
import type { PiEngine } from "../models.ts";
|
||||
import { runSubagent } from "./pi-run.ts";
|
||||
|
||||
@@ -80,7 +79,7 @@ export interface ResearcherRunOptions {
|
||||
* the loop scripted.
|
||||
*/
|
||||
export async function runResearcherAgent(prompt: string, opts: ResearcherRunOptions = {}): Promise<string> {
|
||||
const { text } = await runSubagent(toPiTools(createWebTools(opts.search ?? (() => null))) as AgentTool<any, any>[], {
|
||||
const { text } = await runSubagent(Object.values(createWebTools(opts.search ?? (() => null))), {
|
||||
role: "researcher",
|
||||
prompt,
|
||||
engine: opts.engine,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { AssistantMessage, Message, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
|
||||
import { z } from "zod";
|
||||
import { lhTool, piToolDeclarations, type LhTool } from "../lh-tool.ts";
|
||||
import type { AssistantMessage, Message, Tool, ToolResultMessage, Usage } from "@earendil-works/pi-ai";
|
||||
import { Type } from "typebox";
|
||||
import { piEngineFor, type PiEngine, type ThinkingLevel } from "../models.ts";
|
||||
import type { VisualResult } from "../../core/contracts.ts";
|
||||
import { getHeadless, type HeadlessApi } from "./headless.ts";
|
||||
@@ -88,29 +87,32 @@ Your FINAL message: 1-2 sentences of notes for the teacher (what the figure show
|
||||
NEVER the SVG source itself. If you genuinely cannot make a correct picture of the brief, say exactly
|
||||
that in your final message and why.`;
|
||||
|
||||
export function createVisualTools(): Record<string, LhTool<any, any>> {
|
||||
/** The wire declarations (pi-ai Tool, TypeBox parameters): this loop owns
|
||||
* execution itself — write/edit dispatch inline below, render feeds the
|
||||
* image-in-the-loop message — so the declarations carry no execute. */
|
||||
export function createVisualTools(): Record<string, Tool> {
|
||||
return {
|
||||
write_svg: lhTool({
|
||||
write_svg: {
|
||||
name: "write_svg",
|
||||
description: "Write the complete SVG source for the figure (overwrites any previous version).",
|
||||
schema: z.object({
|
||||
svg: z.string().describe('Complete <svg xmlns="…">…</svg> markup.'),
|
||||
parameters: Type.Object({
|
||||
svg: Type.String({ description: 'Complete <svg xmlns="…">…</svg> markup.' }),
|
||||
}),
|
||||
}),
|
||||
edit_svg: lhTool({
|
||||
},
|
||||
edit_svg: {
|
||||
name: "edit_svg",
|
||||
description:
|
||||
"Replace one exact spot in the current SVG: old_text must appear EXACTLY ONCE and is replaced by new_text. Call write_svg first. For larger changes, write_svg the whole document.",
|
||||
schema: z.object({
|
||||
old_text: z.string().describe("The exact text to replace — must match exactly once in the current SVG."),
|
||||
new_text: z.string().describe("The replacement text."),
|
||||
parameters: Type.Object({
|
||||
old_text: Type.String({ description: "The exact text to replace — must match exactly once in the current SVG." }),
|
||||
new_text: Type.String({ description: "The replacement text." }),
|
||||
}),
|
||||
}),
|
||||
render_svg: lhTool({
|
||||
},
|
||||
render_svg: {
|
||||
name: "render_svg",
|
||||
description: "Render the current SVG to a PNG and show it to you for inspection. No arguments.",
|
||||
schema: z.object({}),
|
||||
}),
|
||||
parameters: Type.Object({}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -130,7 +132,7 @@ export async function runVisualMaker(input: VisualMakerInput, opts: VisualMakerO
|
||||
}
|
||||
|
||||
const tools = createVisualTools();
|
||||
const toolDeclarations = piToolDeclarations(tools);
|
||||
const toolDeclarations = Object.values(tools);
|
||||
const engine = opts.engine ?? piEngineFor("visualMaker");
|
||||
// BYOK (owner, 2026-09-22): the level rides the injected engine — no
|
||||
// factory pin to consult (engine.level is the resolved/clamped value).
|
||||
@@ -301,7 +303,7 @@ async function streamOnce(
|
||||
engine: PiEngine,
|
||||
systemPrompt: string,
|
||||
messages: Message[],
|
||||
tools: ReturnType<typeof piToolDeclarations>,
|
||||
tools: Tool[],
|
||||
reasoning: ThinkingLevel | undefined,
|
||||
abortSignal?: AbortSignal,
|
||||
): Promise<AssistantMessage> {
|
||||
|
||||
Reference in New Issue
Block a user