Files
learnharness/src/agent/tools/probe.ts
T
amosblomqvist 7ab47d4fcb Wave B: the native message record — input events, projection, adapter death
The chat record is now pi-native agent history (LhMessage[]), the AI SDK's
UIMessage transcript contract is gone from the server, and every client turn
arrives as ONE explicit input event.

Core (new):
- src/core/native-messages.ts — the LhMessage taxonomy (user/assistant/
  toolResult + lhMarker customs: verdict, probe-handoff, subagent-steer,
  subagent-abort, plan-block), constructors, and toLlmMessages — the single
  model-facing seam (convertToLlm): strips ids, flattens markers to user
  text, drops UI-only plan-blocks, synthesizes INTERRUPTED results for
  dangling aborted calls, never throws.
- src/core/projection.ts — projectNative: the one-way native → UIMessage
  projection (consecutive assistant+toolResult runs group into one
  assistant view message; toolResults attach backward by toolCallId;
  markers project to data parts; plan-blocks splice after the last
  successful plan_init). Every existing consumer reads through it.
- src/core/input-events.ts — the ChatInput union (text/answer/verdict/
  continue), parseChatInput validation, and inputAppends (answer targets
  the dangling question call or 400s; verdict = optional note user
  message + native verdict marker).

Server:
- chat-handler.ts — the turn root takes {chatId, input}; write-ahead
  persists input appends + claimed steers before the turn; claimSteers
  coalesces the whole queue with the handler's steerDelivered filter as
  the dedupe seam; teacher-vs-prober branch on hasProbeDone.
- turn-service.ts — persistTurn stamps ids, drops clean question
  placeholder toolResults (the record ends at the unanswered call),
  emits plan-block markers idempotently (plan-blocks.ts rewrite), and
  persists abort partials.
- ui-stream.ts — PiTurnSpec takes the native base; the wire dialect is
  unchanged. jobs.ts steers are native markers (steer_<jobId> dedup ids);
  waitForIdle reads danglingQuestionOf. teacher-agent.ts wires
  convertToLlm: toLlmMessages. record-adapter.ts DELETED wholesale.
- GET /api/chats/[id] serves messages: projectNative(record.messages).

Client:
- chat-transport.ts — the 409 retry is IDENTITY (re-POST the same event
  body after the turn settles — the event was never persisted
  pre-acceptance; the merge logic is gone). The transport consumes the
  stashed input event via prepareSendMessagesRequest and throws loudly on
  a missing stash.
- chat.tsx — every send call site stashes exactly one ChatInput event
  (text, answer, verdict, continue) before invoking the SDK send.

Tests: full native migration (chat-flow rewritten to input events and
native record pins; jobs/extraction/demos/graph/usage/plan-blocks/
probe-done/reattach-transport converted; record-adapter.test.ts deleted;
chat-transport tests pin the identity retry). 982/982, typecheck, lint,
build all green.
2026-09-26 00:37:46 +03:00

89 lines
4.3 KiB
TypeScript

import type { AgentTool } from "@earendil-works/pi-agent-core";
import { serverExecute } from "../tool-execute.ts";
import { probeDoneInputSchema, type ProbeDoneResult } from "../../core/contracts.ts";
import { danglingQuestionOf, hasProbeDone, type LhMessage } from "../../core/native-messages.ts";
import type { ChatStore } from "../../core/ports.ts";
import { buildProbeHandoffSteer, type SteerMessage } from "../../core/contracts.ts";
/** What the probe_done tool closes over. */
export interface ProbeDoneContext {
chatId: string;
/** The storage port (open-question + already-concluded checks). */
chatStore: ChatStore;
/** Queue the handoff steer (the wake pipeline — src/server/jobs.ts).
* Injected so this module never imports the server seam. */
deliver: (steer: SteerMessage) => void;
}
/** Does the transcript already carry a concluded probe (any state)?
* Wave B: the native scan (any probe_done tool call, any state) — same
* semantics the UIMessage part scan had. */
function probeConcluded(messages: readonly LhMessage[]): boolean {
return hasProbeDone(messages);
}
/**
* probe_done — the probe→planning seam (docs/probe-teach-split.md §2).
*
* SERVER-SIDE. The prober concludes the probe by authoring the learner
* assessment (the tool INPUT — it streams to the learner live and is
* durable in the transcript as the tool part itself). Three outcomes:
*
* ok:false + error — a question is still open ("resolve it first"), or
* the probe is already concluded. The refusal returns to the prober as
* a tool result; it fixes course and retries (the return-to-agent
* doctrine, same as nodeId validation).
* ok:true — the assessment is recorded, and the HANDOFF is queued: a
* steer through the wake pipeline that fires the teacher's first turn
* (plan authoring) the moment the prober's turn ends. Auto-wake is the
* user-decided trigger — the learner experiences assessment → plan as
* one continuous flow.
*
* 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): Record<string, AgentTool<any>> {
return {
probe_done: {
name: "probe_done",
label: "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 " +
"ceiling where it runs out), and his learning goal is concrete. The input IS the learner assessment — " +
"one strand per dependency the lesson will rest on, with your read of where his edge sits on it " +
"(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.",
// The core-owned schema (contracts/probe.ts) — the SAME schema the UI
// parse seam (tool-parts.ts) runs, so boundary-valid ⇔ consumer-parseable.
parameters: probeDoneInputSchema,
execute: serverExecute("probe_done", probeDoneInputSchema, async (input): Promise<ProbeDoneResult> => {
const record = ctx.chatStore.getChat(ctx.chatId);
if (!record) return { ok: false, error: `Chat not found: ${ctx.chatId}` };
if (danglingQuestionOf(record.messages) !== null) {
return {
ok: false,
error:
"A question is still open — resolve it (or let him answer) before concluding the probe. " +
"probe_done only fires with no question outstanding.",
};
}
if (probeConcluded(record.messages)) {
return { ok: false, error: "The probe is already concluded — probe_done fires exactly once." };
}
try {
ctx.deliver(buildProbeHandoffSteer(ctx.chatId));
} catch (err) {
console.error(`[chat ${ctx.chatId}] probe handoff queueing failed:`, err);
// The handoff is recoverable-by-design (the next client message
// constructs the teacher off the transcript seam) — record the
// assessment anyway; the wake is an optimization, not a gate.
}
return { ok: true, assessment: input.assessment };
}),
},
};
}