@sema-agent/core
Version:
Stateless, task-oriented AI agent core
214 lines (204 loc) • 13.7 kB
JavaScript
import { Type } from "typebox";
import { delimitUntrusted, inlineUntrusted } from "./untrusted-text.js";
import { foreignLine } from "./protocol-http-auth.js";
import { mountRuleFace, toolFace } from "./tool-catalog-entries.js";
import { errorResult } from "./tools.js";
import { readMember } from "./thrown-value.js";
import { MAX_TOOL_CARD_CHARS, toolCardChars } from "./tool-card-bound.js";
const READ_REASON_MAX = 600;
export const PRESENT_PLAN_TOOL_NAME = "ExitPlanMode";
export const ENTER_PLAN_MODE_TOOL_NAME = "EnterPlanMode";
const ENTER_PLAN_MODE_DESCRIPTION = `Enter PLAN MODE (read-only): stop making changes and switch to exploration/planning. For the rest of this run, every write/edit/mutating tool call ASKS the user first ("Cannot write to <path> while in plan mode."; where nobody can answer, it is refused) while read-only tools (Read, Grep, Glob, etc.) still work. When your plan is ready, call ${PRESENT_PLAN_TOOL_NAME} with it — the run PAUSES for a human to approve it, then continues (read-only lifted) so you can execute.
Use this tool proactively when you're about to start a non-trivial implementation task. If you would use AskUserQuestion to clarify the approach, use EnterPlanMode instead — getting alignment on the plan itself is the point.
## When to Use This Tool
1. Non-trivial implementation work: the change involves real design decisions worth aligning on before code is written
- Example: "Add a delete button to the user profile" — placement, confirmation UX, what the deletion cascades to
- Example: "Update the error handling in the API" — which layers change, error shapes, retry semantics
2. Significant architectural ambiguity: multiple reasonable approaches exist and the choice meaningfully affects the codebase
- Example: "Add caching to the API" — Redis vs in-memory vs file-based
- Example: "Add real-time updates" — WebSockets vs SSE vs polling
3. Unclear requirements: you need to explore and clarify before you can make progress
- Example: "Make the app faster" — need to profile and identify bottlenecks first
4. High-impact or destructive restructuring: the work significantly restructures, migrates, or deletes existing code, and buy-in first reduces risk
- Example: "Redesign the authentication system"
## When NOT to Use This Tool
Skip plan mode only when there is genuinely nothing to align on:
- Trivial fixes (e.g. fixing a typo, removing a stray console.log)
- Pure research/exploration tasks — just read; no plan approval is needed
If unsure whether to use it, err on the side of planning - it's better to get alignment upfront than to redo work.
## Examples
GOOD: "Add user authentication to the app" (genuinely ambiguous: session vs JWT, token storage, middleware). "Add a delete button to the user profile" (small but has real design decisions — align first). "Update the error handling in the API" (touches multiple layers; agree on the shape before rewriting). "Redesign the data pipeline" (major restructuring where the wrong approach wastes significant effort).
BAD: "Fix the typo in the README" (trivial; nothing to align on). "Remove the leftover console.log in utils.js" (trivial cleanup). "How does the caching layer work?" (pure research — read and answer; no plan needed).`;
const ENTER_PLAN_MODE_HEAD = "Entered plan mode (read-only). Every write/edit/mutating tool call now asks the user first for the rest of this run; ";
function enterPlanModeMessage(seat) {
if (seat?.isChildLeg === true)
return `${ENTER_PLAN_MODE_HEAD}research with read-only tools, and answer the request comprehensively — your final answer, carrying the plan, goes back to the caller.`;
const exitMounted = seat === undefined || seat.mountedTools().some((t) => t.name === PRESENT_PLAN_TOOL_NAME || (t.aliases ?? []).includes(PRESENT_PLAN_TOOL_NAME));
return exitMounted
? `${ENTER_PLAN_MODE_HEAD}research with read-only tools, then call ${PRESENT_PLAN_TOOL_NAME} with your plan to get it approved before acting.`
: `${ENTER_PLAN_MODE_HEAD}research with read-only tools, and when you have formed a concrete plan, give it as your final answer and stop.`;
}
export function createEnterPlanModeTool(enterPlanMode, seat) {
return {
name: ENTER_PLAN_MODE_TOOL_NAME,
...toolFace("enter-plan-mode"),
ruleFace: mountRuleFace("enter-plan-mode"),
description: ENTER_PLAN_MODE_DESCRIPTION,
parameters: Type.Object({}),
executionMode: "sequential",
execute: async () => {
await enterPlanMode();
const message = enterPlanModeMessage(seat);
return {
content: message,
details: { type: "enter-plan-mode", message },
};
},
};
}
const PRESENT_PLAN_DESCRIPTION = [
"Present your proposed PLAN for human approval BEFORE taking any action (CC plan-mode parity).",
"Use this when you are in plan mode (read-only research): once you have explored enough and formed a concrete plan,",
"provide the full plan here. The run PAUSES for a human to approve, edit, or reject it.",
"IMPORTANT: only use this when the task requires planning the implementation steps of work that changes things;",
"for research tasks (gathering information, reading files, understanding the codebase) do NOT use this tool.",
"This tool inherently requests approval of your plan — do not separately ask \"Is this plan okay?\".",
"Do NOT attempt edits / writes / mutating commands before the plan is approved — present the plan first.",
"If the plan is approved, the run continues (and any read-only restriction is lifted) so you can execute it;",
"if it is rejected or edited, follow the reviewer's feedback instead of the original plan.",
].join(" ");
const PRESENT_PLAN_FILE_DESCRIPTION = (shown) => `Use this tool when you are in plan mode and have finished writing your plan to the plan file and are ready for user approval.
## How This Tool Works
- You should have already written your plan to the plan file: ${shown}
- This tool does NOT take the plan content as a parameter - it will read the plan from the file you wrote
- This tool simply signals that you're done planning and ready for the user to review and approve; the run PAUSES for a human to approve, edit, or reject it
- The user will see the contents of your plan file when they review it
## When to Use This Tool
IMPORTANT: Only use this tool when the task requires planning the implementation steps of a task that requires writing code. For research tasks where you're gathering information, searching files, reading files or in general trying to understand the codebase - do NOT use this tool.
## Before Using This Tool
Ensure your plan is complete and unambiguous:
- If you have unresolved questions about requirements or approach, resolve them first (in earlier phases)
- Once your plan is finalized, use THIS tool to request approval
**Important:** Do NOT separately ask "Is this plan okay?" or "Should I proceed?" - that's exactly what THIS tool does. ExitPlanMode inherently requests user approval of your plan.`;
function outsidePlanRefusal(seat) {
if (seat?.mode() === "plan")
return undefined;
return errorResult(`You are not in plan mode. ${seat?.enterPlanModeMounted === true ? `To enter plan mode, call the ${ENTER_PLAN_MODE_TOOL_NAME} tool first. ` : ""}If your plan was already approved, continue with implementation.`);
}
const PAUSE_GAP_MAX = 400;
function planCardRefusal(card) {
const chars = toolCardChars(card);
if (chars <= MAX_TOOL_CARD_CHARS)
return undefined;
return errorResult(`The plan was NOT submitted for approval and plan mode was not exited: its approval card is ${chars.toFixed(0)} characters as JSON, over the ${MAX_TOOL_CARD_CHARS.toFixed(0)} that the card can carry. ` +
"A quote, backslash, tab or line break counts as two characters, any other control character as six, and a character outside the Basic Multilingual Plane (most emoji) as two. " +
"Shorten the plan and call ExitPlanMode again.");
}
function createPresentPlanFileTool(requestReview, seat, planFile, notPausing) {
return {
name: PRESENT_PLAN_TOOL_NAME,
...toolFace("exit-plan-mode-file"),
ruleFace: mountRuleFace("exit-plan-mode-file"),
description: PRESENT_PLAN_FILE_DESCRIPTION(planFile.shown),
parameters: Type.Object({}),
execute: async (_args, ctx) => {
const outside = outsidePlanRefusal(seat);
if (outside !== undefined)
return outside;
const read = await planFile.read(ctx?.signal);
if (!read.ok)
return errorResult(`The plan file ${planFile.shown} could not be read (${foreignLine(read.reason, READ_REASON_MAX)}), so plan mode was not exited. Write your plan to this file and call ExitPlanMode again.`);
if (read.text === undefined)
return errorResult(`No plan file found at ${planFile.shown}. Please write your plan to this file before calling ExitPlanMode.`);
const plan = read.text;
const card = exitPlanCard(plan, planFile.path);
const tooLarge = planCardRefusal(card);
if (tooLarge !== undefined)
return tooLarge;
requestReview(reviewRequestFor(ctx, "ExitPlanMode"));
if (notPausing !== undefined)
return notPausing();
return {
content: `Plan presented for human review (from ${planFile.shown}):\n\n${delimitUntrusted("plan", plan)}\n\n` +
"(The run is pausing for approval — you will continue once the plan is approved, edited, or rejected.)",
details: card,
};
},
};
}
export function reviewWithdrawalClause(why) {
return why === "ended_in_error"
? "the call that requested it ended in error (its result failed or was withheld), so no plan card reached a reviewer"
: `the plan card of the call that requested it did not ride that call's tool_end (over the ${MAX_TOOL_CARD_CHARS} characters as JSON a frame carries, or with no plan string), so no plan reached a reviewer`;
}
export function reviewRequestFor(ctx, reason) {
return {
...(reason !== undefined ? { reason } : {}),
...(ctx !== undefined && ctx.reviveClaim === undefined && typeof ctx.toolCallId === "string" && ctx.toolCallId !== "" ? { requestedByCallId: ctx.toolCallId } : {}),
};
}
const EXIT_PLAN_CARD = "exit-plan-mode";
function exitPlanCard(plan, filePath) {
return { type: "exit-plan-mode", plan, isAgent: false, ...(filePath !== undefined ? { filePath } : {}) };
}
export function notePresentedPlan(cell, toolCallId, result, card, isError) {
const shown = shownBy(result, card, isError);
if (shown === undefined)
return;
const settle = (r) => (r.requestedByCallId === toolCallId && r.presented === undefined && r.withdrawn === undefined ? { ...r, ...shown } : r);
if (cell.pending !== undefined)
cell.pending = settle(cell.pending);
if (cell.later !== undefined)
cell.later = cell.later.map(settle);
if (cell.pending?.withdrawn === undefined || cell.later === undefined)
return;
const next = cell.later.findIndex((r) => r.withdrawn === undefined);
if (next < 0)
return;
cell.pending = cell.later[next];
cell.later = cell.later.slice(next + 1);
}
function shownBy(result, card, isError) {
if (isError)
return { withdrawn: "ended_in_error" };
if (readMember(readMember(result, "details"), "type") !== EXIT_PLAN_CARD)
return undefined;
const plan = readMember(card, "type") === EXIT_PLAN_CARD ? readMember(card, "plan") : undefined;
return typeof plan === "string" ? { presented: plan } : { withdrawn: "plan_not_carried" };
}
export function createPresentPlanTool(requestReview, seat, planFile, suspendGap) {
const notPausing = suspendGap === undefined
? undefined
: () => errorResult(`The plan was NOT submitted for approval and the run is not pausing: the per-task execution env ${inlineUntrusted(suspendGap, PAUSE_GAP_MAX)}, so its workspace could not be restored on resume. You remain in plan mode; present the plan to the user in your reply instead.`);
if (planFile !== undefined)
return createPresentPlanFileTool(requestReview, seat, planFile, notPausing);
return {
name: PRESENT_PLAN_TOOL_NAME,
...toolFace("exit-plan-mode"),
ruleFace: mountRuleFace("exit-plan-mode"),
description: PRESENT_PLAN_DESCRIPTION,
parameters: Type.Object({
plan: Type.String({
description: "Your full proposed plan, in markdown. The human reviewer approves / edits / rejects it before you act.",
}),
}),
execute: async (args, ctx) => {
const outside = outsidePlanRefusal(seat);
if (outside !== undefined)
return outside;
const { plan } = args;
const card = exitPlanCard(plan);
const tooLarge = planCardRefusal(card);
if (tooLarge !== undefined)
return tooLarge;
requestReview(reviewRequestFor(ctx, "ExitPlanMode"));
if (notPausing !== undefined)
return notPausing();
return {
content: `Plan presented for human review:\n\n${delimitUntrusted("plan", plan)}\n\n` +
"(The run is pausing for approval — you will continue once the plan is approved, edited, or rejected.)",
details: card,
};
},
};
}