diff --git a/CHANGELOG.md b/CHANGELOG.md index f7007f3..1628548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,21 @@ Harness spec 3.9.0: the model last used in a directory, the two types of schedul one last used in that directory; a scheduled run never changes what the directory remembers. `/schedule` says each schedule's type, and `/schedule new` offers the two by name. +- **Harness spec 3.9.0: interactive-only models** (`harness/interactive.md`). A server may mark a + model `interactive_only` — one its provider sells for a person's own turns and forbids for + automated, batch and scheduled use. Your turns, and the subagents and teams your session + starts, run on it as on any model. What is not your turn does not: the session's **title** + and its **compaction** (asked for or automatic) are asked of the same model under another + provider when the server lists one, else of your global `model` or the server's default when + that is not interactive-only; with none, the title stays the one made from your first prompt, + automatic compaction is skipped and said once, and `/compact` is refused with the reason. + **Scheduled work never runs on one**: a scheduled session opened on such a model, or a + scheduled turn of a session that has come to be on one, is refused before anything is sent + (`data.reason: "interactive_only"`), a scheduled run's subagent on one is not started, and a + schedule that follows the directory skips such a model. `lembas run` with no terminal at all + (a cron job, a pipeline) is refused on one too. `/model` says which models are for + interactive use only. + ### Fixed - **A continuing schedule's run after the service restarted is offered `report_write` again.** diff --git a/schema/connections.schema.json b/schema/connections.schema.json index eafaecc..3a8908d 100644 --- a/schema/connections.schema.json +++ b/schema/connections.schema.json @@ -182,6 +182,10 @@ "description": "The model reads images: @image files, pasted paths and view_image.", "type": "boolean" }, + "interactive_only": { + "description": "The server's word that this model is for a person's own turns only (harness interactive.md): no scheduled work is sent to it, and a session's title and compaction are asked of another model.", + "type": "boolean" + }, "html_pages": { "description": "The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages.", "type": "boolean" diff --git a/src/acp/agent.ts b/src/acp/agent.ts index ff3f4b7..f4ab78d 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -15,7 +15,8 @@ // applies in every mode, as everywhere. import { existsSync, readdirSync, statSync } from "node:fs" import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path" -import { createApp, type App, type SessionContext } from "../app.ts" +import { createApp, InteractiveOnlyError, type App, type SessionContext } from "../app.ts" +import { INTERACTIVE_REASON } from "../provider/interactive.ts" import type { AskReply, Asker, Event } from "../bus/index.ts" import { FileIndex } from "../project/files.ts" import { loadSkills } from "../skill/index.ts" @@ -641,9 +642,10 @@ export class AcpAgent { const effort = effortOf(p?._meta?.effort) try { // A schedule's session uses the directory's model and never becomes it (spec 3.9.0). - session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}), ...(scheduled ? { remember: false as const } : {}) }) + session.app = createApp({ cwd, mode, asker: this.asker(session), modelTitles: false, model, ...(effort !== undefined ? { effort } : {}), ...(scheduled ? { remember: false as const, automated: true as const } : {}) }) } catch (e) { - throw new RpcError(INVALID_PARAMS, (e as Error).message) + // Scheduled work never runs on an interactive-only model (interactive.md §2): the sentence, and why. + throw new RpcError(INVALID_PARAMS, (e as Error).message, e instanceof InteractiveOnlyError ? { reason: INTERACTIVE_REASON } : undefined) } if (served !== undefined) { const why = this.notServed(session.app, model!) @@ -1084,11 +1086,20 @@ export class AcpAgent { // The turn that runs now says whether the session is a scheduled run's (it may wait behind another). if (scheduled) (s.scheduled = scheduled), s.app.forgetful() else delete s.scheduled + // The turn that runs now is the schedule's, or the person's own in the run's chat: scheduled + // work never uses an interactive-only model — refused before anything is sent to it. + const interactiveOnly = s.app.setAutomated(scheduled !== undefined) + if (interactiveOnly) { + s.prompting = false + throw new RpcError(INVALID_PARAMS, interactiveOnly, { reason: INTERACTIVE_REASON }) + } started() try { return await this.runPrepared(s, prepared, turnId) } finally { s.prompting = false + // What comes next is the person's until a prompt says otherwise. + s.app.setAutomated(false) } } return s.turns.run(turnId, (started) => { diff --git a/src/app.ts b/src/app.ts index 1d5c27b..98be20c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -15,7 +15,7 @@ import { loadConfig, type Loaded } from "./config/load.ts" import type { Mode } from "./config/schema.ts" import { DEFAULT_RULES, toRules } from "./permission/evaluate.ts" import { hardlineRules } from "./permission/hardline.ts" -import { clientFor, familyOf, resolveModel } from "./provider/index.ts" +import { clientFor, familyOf, resolveModel, ModelError } from "./provider/index.ts" import { subagentModel, type ModelInfo } from "./team/subagents.ts" import { assembleSystem, instructionFiles, knowledgeScope, modeText } from "./prompt/assemble.ts" import type { Changing } from "./session/prefix.ts" @@ -52,7 +52,12 @@ import { isLevel, levelsFor, readLevel, type Level } from "./provider/effort.ts" import { memberTools as memberToolsOf, readingBashByDefault, Team, TEAM, TEAM_TOOLS, type Capacity, type TeamAgent } from "./team/team.ts" import { whoDecides } from "./team/delegation.ts" import { lastModel, rememberModel, startModel } from "./session/lastmodel.ts" -import { readRaw } from "./config/settings.ts" +import { globalConfigFile, readRaw } from "./config/settings.ts" +import { background, scheduledRefusal, type BackgroundCall, type Listed } from "./provider/interactive.ts" + +/** Scheduled or unattended work was about to use an interactive-only model (harness + * interactive.md §2): the message is the spec's sentence. */ +export class InteractiveOnlyError extends ModelError {} import { TeamRuntime, type MemberHandle } from "./team/runtime.ts" export interface AppOptions { @@ -79,6 +84,9 @@ export interface AppOptions { /** false: this session's model is never made its directory's (harness acp.md, *The model last * used in a directory*): a one-shot run, a session a schedule opened. It still starts on it. */ remember?: false + /** Scheduled work, or a one-shot run with nobody at it (harness interactive.md §2): never on an + * interactive-only model — not at the start, by a switch, or in a subagent. */ + automated?: true } const UNATTENDED: Record = { @@ -119,6 +127,9 @@ export interface App { chooseModel(ref: string): void /** Stop remembering this session's model for its directory (a schedule's session). */ forgetful(): void + /** Whether what runs now is scheduled work (a schedule's turn) or the person's own. On: the + * spec's sentence when the session's model is interactive-only and so may not run it. */ + setAutomated(on: boolean): string | undefined newSession(): void /** Name the open session by hand (a chat renamed in the web UI); no model title follows. */ rename(title: string): void @@ -236,6 +247,8 @@ export function createApp(o: AppOptions): App { const trust = trustOf(project.root) const trusted = trust === "trusted" const loaded = loadConfig({ projectConfigDir: project.dir, trusted }) + // The login's models as the interactive-only rules read them (harness interactive.md). + const listed = (): Listed[] => loaded.refs.map((r) => ({ id: r.ref, ...(loaded.connections[r.connection]?.models[r.id]?.interactive_only === true ? { interactive_only: true } : {}) })) // Which model it starts on (harness acp.md, spec 3.9.0): the one asked for, the project's // setting, the model last used in this directory while the login serves it, the global setting, // the server's default. @@ -245,9 +258,14 @@ export function createApp(o: AppOptions): App { project: projectModel, directory: o.model || projectModel ? undefined : lastModel(o.cwd), global: projectModel ? undefined : loaded.config.model, - served: loaded.refs.map((r) => r.ref), + // Scheduled work skips an interactive-only directory's model as it skips one no longer served. + served: listed().filter((m) => !(o.automated && m.interactive_only)).map((m) => m.id), }) const model = resolveModel(loaded, start.model) + let automated = o.automated === true + /** Why scheduled work may not use `m`, or undefined: it is interactive-only (interactive.md §2). */ + const notAutomated = (m: ResolvedModel): string | undefined => (m.spec.interactive_only === true ? scheduledRefusal(m.ref, [{ id: m.ref, interactive_only: true }]) : undefined) + if (automated && notAutomated(model)) throw new InteractiveOnlyError(notAutomated(model)) // An untrusted project is read-only: plan mode, and its own config is ignored. let mode: Mode = o.mode ?? loaded.config.mode ?? "manual" if (trust === "readonly") mode = "plan" @@ -512,6 +530,9 @@ export function createApp(o: AppOptions): App { if ("refused" in r) throw new ToolError(r.refused) m = wanted && wanted.ref === r.model ? wanted : engine.model } + // A scheduled run's subagents are the same run: none on an interactive-only model. + const scheduledNo = automated ? notAutomated(m) : undefined + if (scheduledNo) throw new ToolError(scheduledNo) // A team's member is not refused for capacity: the team gave it its slot (team.md §8). if (!member) { const running = registry.running(jobsSessionId()).filter((j) => j.kind === "subagent" && j.subagent && !j.team) @@ -713,6 +734,7 @@ export function createApp(o: AppOptions): App { maxSteps: loaded.config.limits?.steps, budget: { wall_seconds: loaded.config.limits?.wall_seconds, output_bytes: loaded.config.limits?.output_bytes, completion_tokens: loaded.config.limits?.completion_tokens }, compaction, + background: (call) => backgroundFor(engine.model, call), perm, toolCtx: { ...baseToolCtx(), jobs: { registry, owner: baseOwner }, team: { get runtime() { return teamRt }, as: TEAM.names.lead } }, system: (m, current, plan, ch) => system(m, current, ch, undefined, undefined, plan), @@ -875,7 +897,12 @@ export function createApp(o: AppOptions): App { named = "model" const first = firstShown || store.firstPrompt(id) const reply = firstReply(engine.messages) - const { client } = small() + // A title is background work: for an interactive-only model it is asked of the twin or a + // default, or not at all — the prompt's line stays (interactive.md §3). + const s = small() + const where = backgroundFor(s.model, "title") + if (where && !("client" in where)) return + const client = where?.client ?? s.client const signal = AbortSignal.timeout(120_000) // Quietly: a title is not worth a warning, and the prompt's line is already there. void modelTitle(client, first, reply, signal) @@ -889,6 +916,23 @@ export function createApp(o: AppOptions): App { const turns = new Turns(engine, snapshots, store) // By provider for an instance's models (`deepseek/deepseek-flash`), src/provider/refs.ts. const modelRefs = () => loaded.refs.map((r) => r.ref) + /** Where a background call that would use `m` goes when `m` is interactive-only (harness + * interactive.md §3): its twin, else the global `model` setting, else the server's default — + * or skipped, or refused in words. Undefined: `m` itself, as ever. */ + function backgroundFor(m: ResolvedModel, call: BackgroundCall): { client: Client; effort: Level; model: ResolvedModel } | { skip: true } | { refused: string } | undefined { + if (m.spec.interactive_only !== true) return undefined + const canonical = (ref: unknown): string | undefined => { + try { + return typeof ref === "string" && ref ? resolveModel(loaded, ref).ref : undefined + } catch { + return undefined + } + } + const r = background({ model: m.ref, models: listed(), defaults: [canonical(readRaw(globalConfigFile()).model), canonical(loaded.connections[m.connectionName]?.webui?.default)], call }) + if (!("model" in r)) return r + const other = resolveModel(loaded, r.model) + return { client: clientFor(other), effort: startEffort(other), model: other } + } // The directory's model (spec 3.9.0): written when a person's turn begins and when the person // changes the model — never for a model borrowed for one prompt, a turn the harness started, // a one-shot run or a schedule's session. @@ -900,6 +944,8 @@ export function createApp(o: AppOptions): App { bus.on((e) => e.type === "prompt" && !e.machine && remember()) const switchModel = (ref: string, how?: "borrowed") => { const m = resolveModel(loaded, ref) + const no = automated ? notAutomated(m) : undefined + if (no) throw new InteractiveOnlyError(no) borrowed = how === "borrowed" engine.setModel(m, clientFor(m), startEffort(m)) } @@ -1017,6 +1063,10 @@ export function createApp(o: AppOptions): App { forgetful() { remembers = false }, + setAutomated(on) { + automated = on + return on ? notAutomated(engine.model) : undefined + }, settings, memory, projectMemory, diff --git a/src/cli.ts b/src/cli.ts index 4ab580c..99c531e 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -341,6 +341,9 @@ async function main() { modelTitles: false, // A one-shot run starts on the directory's model and never becomes it (spec 3.9.0). remember: false, + // With no terminal at all it is a batch job — a cron line, a pipeline — and never runs on an + // interactive-only model (harness interactive.md §2). + ...(!process.stdin.isTTY && !process.stdout.isTTY && !process.stderr.isTTY ? { automated: true as const } : {}), }) if (values.json) renderJson(app.bus) else renderPlain(app.bus, { color: process.stderr.isTTY ?? false, showReasoning: values.reasoning ?? false, icons: app.loaded.config.icons, theme: app.loaded.config.theme }) diff --git a/src/config/schema.ts b/src/config/schema.ts index 9a05e80..5dbb3ac 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -56,6 +56,7 @@ export const ModelSpec = z.strictObject({ effort: z.union([z.enum(EFFORTS), z.literal("off"), z.literal("default")]).optional().describe("The level a conversation starts with, when the model offers it: an effort, `off` (thinking switched off, with thinking_switch) or `default` (nothing sent, for a model that takes no efforts)."), effort_style: z.enum(["top", "kwargs", "both"]).optional().describe("Where the effort goes in a request: top-level, in chat_template_kwargs, or both (the default: llama.cpp drops top-level)."), vision: z.boolean().optional().describe("The model reads images: @image files, pasted paths and view_image."), + interactive_only: z.boolean().optional().describe("The server's word that this model is for a person's own turns only (harness interactive.md): no scheduled work is sent to it, and a session's title and compaction are asked of another model."), html_pages: z.boolean().optional().describe("The server's word that this model can write HTML pages (harness pages.md). Read and kept, never used here: a terminal's model is not offered pages."), tools: z.boolean().optional().describe("false: a model without tool calls — it can only talk."), headers: z.record(z.string(), z.string()).optional().describe("Extra HTTP headers for this model's requests."), diff --git a/src/harness.ts b/src/harness.ts index 0038c94..e180730 100644 --- a/src/harness.ts +++ b/src/harness.ts @@ -127,7 +127,7 @@ export const LOOP: { /** Interactive-only models (spec 3.9.0, harness/interactive.md): the field, the reason of a * refused scheduled request, the two sentences, and what each background call does with * nowhere to go. */ - interactive: { field: string; reason: string; texts: { scheduled: string; compact: string }; background: Record<"title" | "compaction" | "auto_compaction", "skip" | "refuse"> } + interactive: { field: string; reason: string; texts: { scheduled: string; compact: string }; background: Record<"title" | "compaction" | "auto_compaction", string> } /** Background work (spec 2.0.0): the marks every note begins with, and the caps. */ jobs: { marks: { command: string; subagent: string; message: string; to_subagent: string } diff --git a/src/lembas/client.ts b/src/lembas/client.ts index dc41a82..03e23b9 100644 --- a/src/lembas/client.ts +++ b/src/lembas/client.ts @@ -65,6 +65,8 @@ export interface ServedModel { vision?: boolean /** Spec 3.8.0 (harness pages.md): the model can write HTML pages. */ html_pages?: boolean + /** Spec 3.9.0 (harness interactive.md): for a person's own turns only. Sent only when true. */ + interactive_only?: boolean tools?: boolean notes?: string capacity?: { group?: string; single_session?: boolean; parallel?: number } diff --git a/src/lembas/webui.ts b/src/lembas/webui.ts index 9a8dcdf..9e50876 100644 --- a/src/lembas/webui.ts +++ b/src/lembas/webui.ts @@ -101,6 +101,8 @@ export function specFor(m: ServedModel, connection: string): ModelSpec { if (m.vision !== undefined) out.vision = m.vision // Spec 3.8.0 (pages.md): kept as the server says it; nothing here offers pages. if (m.html_pages !== undefined) out.html_pages = m.html_pages === true + // Spec 3.9.0 (interactive.md): the server's word; what is scheduled or background work is decided here. + if (m.interactive_only === true) out.interactive_only = true if (m.tools !== undefined) out.tools = m.tools if (m.notes) out.notes = m.notes.slice(0, 300) if (m.capacity?.single_session) out.single_session = true diff --git a/src/session/engine.ts b/src/session/engine.ts index 33a6a9f..234fa84 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -70,6 +70,10 @@ export interface EngineOptions { /** Take a rule out of the project's config again; whether it was there. */ forgetRule?: (rule: Pick) => boolean compaction?: { autoAt?: number } + /** Where a compaction's summary is asked for when it may not be asked of the session's model + * (harness interactive.md §3): another model's client, skip it, or the refusal's words. + * Undefined, or absent: the session's own model, as ever. */ + background?: (call: "compaction" | "auto_compaction") => { client: Client; effort: Level } | { skip: true } | { refused: string } | undefined /** Starts a subagent for the task tool; absent in a subagent. */ spawn?: ToolContext["spawn"] /** What a message sent mid-turn starts with: the user's words for a session, the main agent's for @@ -547,7 +551,7 @@ export class Engine { this.busy = true this.abort = new AbortController() try { - return await this.summarise(this.abort.signal) + return await this.summarise(this.abort.signal, "compaction") } finally { this.busy = false } @@ -556,11 +560,18 @@ export class Engine { /** The summary, asked for as the next turn of this same conversation (harness context.md §7): * the same system prompt and tools, every message as it is, then tasks/compact.md with an empty * transcript and previous summary. Nothing of it is shown or stored as a turn; a tool call in the reply is not run. */ - private async summarise(signal: AbortSignal): Promise { + private async summarise(signal: AbortSignal, call: "compaction" | "auto_compaction"): Promise { + // An interactive-only model is not asked for background work: the summary is another model's, + // of the same conversation, and comes back into this session (interactive.md §3). + const elsewhere = this.o.background?.(call) + if (elsewhere && "refused" in elsewhere) throw new Error(elsewhere.refused) + if (elsewhere && "skip" in elsewhere) throw new Error("skipped") + const client = elsewhere?.client ?? this.client + const effort = elsewhere?.effort ?? this.effort // No previous summary in the ask: an earlier one is already the conversation's first message. const ask: Message = { role: "user", parts: [{ type: "text", text: compactAsk() }] } let summary = "" - for await (const ev of this.client.stream({ system: this.systemPrompt(), messages: mergeUsers([...this.messages, ask]), tools: this.toolSpecs(), effort: this.effort, signal })) { + for await (const ev of client.stream({ system: this.systemPrompt(), messages: mergeUsers([...this.messages, ask]), tools: this.toolSpecs(), effort, signal })) { if (ev.type === "finish") summary = summaryOf(ev.message.parts) else if (ev.type === "usage") this.recordUsage(ev.usage, "compaction") } @@ -603,6 +614,7 @@ export class Engine { /** Before a step: past compaction.auto_at of the window, compact. Old tool results are never * pruned in place (harness context.md: nothing already sent is rewritten — it would throw the * prompt cache away from that point); compaction is the one deliberate break. */ + private autoSkipSaid = false private async manageContext(signal: AbortSignal): Promise<"stop" | void> { const window = contextWindow(this.model) // Spec 3.4.0 §9: a subagent of the tree does not compact; at pause_at it is paused instead. @@ -630,11 +642,19 @@ export class Engine { } return } + // Nowhere to ask for the summary (an interactive-only model with no twin and no usable + // default): skipped, said once, and the turn goes on (interactive.md §3). + const where = this.o.background?.("auto_compaction") + if (where && !("client" in where)) { + if (!this.autoSkipSaid) this.o.bus.emit({ type: "notice", message: `context at ${Math.round((used / window) * 100)}% of ${window}, and not compacted: this session's model is for interactive use only and there is no other model to ask for the summary — switch model (/model), or start a new session` }) + this.autoSkipSaid = true + return + } this.autoCompactions++ this.o.bus.emit({ type: "notice", level: "info", message: `context at ${Math.round((used / window) * 100)}% of ${window}: compacting the conversation` }) this.progress.set({ phase: "compacting" }) try { - await this.summarise(signal) + await this.summarise(signal, "auto_compaction") // The task is never left to the summary: the prompt that started this turn comes back word // for word (found on a real run, where a small model's summary lost the task entirely). // Its note is not: what it said may be out of date, and the new prompt's first user message diff --git a/src/tui/commands.ts b/src/tui/commands.ts index 71aaddb..9d6956e 100644 --- a/src/tui/commands.ts +++ b/src/tui/commands.ts @@ -234,7 +234,7 @@ export const COMMANDS: Command[] = [ options: refs.map((r) => { const known = c.app.loaded.refs.find((x) => x.ref === r)! const spec = c.app.loaded.connections[known.connection]!.models[known.id]! - const bits = [spec.context ? `${Math.round(spec.context / 1024)}k ctx` : "", spec.vision ? "vision" : "", levelsFor(c.app.engine.model.ref === r ? c.app.engine.model : { ...c.app.engine.model, ref: r, spec }).control === "switch" ? "thinking switch" : spec.efforts?.length ? "effort" : ""].filter(Boolean).join(" · ") + const bits = [spec.context ? `${Math.round(spec.context / 1024)}k ctx` : "", spec.vision ? "vision" : "", levelsFor(c.app.engine.model.ref === r ? c.app.engine.model : { ...c.app.engine.model, ref: r, spec }).control === "switch" ? "thinking switch" : spec.efforts?.length ? "effort" : "", spec.interactive_only ? "interactive use only" : ""].filter(Boolean).join(" · ") return { label: r, value: r, description: bits, current: r === c.app.engine.model.ref } }), onSelect: pick, diff --git a/tests/interactive.test.ts b/tests/interactive.test.ts new file mode 100644 index 0000000..0649261 --- /dev/null +++ b/tests/interactive.test.ts @@ -0,0 +1,228 @@ +// Interactive-only models (harness spec 3.9.0, interactive.md): the field as the server sends it, +// scheduled work that never runs on such a model, and a session's background calls — its title, +// its compaction — asked of another model. A fake LLeMbas is the client; the model is a scripted +// endpoint that records which model each request named. +import { afterEach, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { AcpAgent, type Limits } from "../src/acp/agent.ts" +import { Peer, type Transport } from "../src/acp/rpc.ts" +import { createApp, InteractiveOnlyError } from "../src/app.ts" +import { paths } from "../src/config/paths.ts" +import { LOOP } from "../src/harness.ts" +import { specFor } from "../src/lembas/webui.ts" +import { setTrust } from "../src/project/root.ts" +import { rememberModel, lastModelFile } from "../src/session/lastmodel.ts" +import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts" + +let fake: Fake | undefined +const closing: (() => unknown)[] = [] +afterEach(async () => { + for (const c of closing.splice(0)) await c() + fake?.stop() + rmSync(lastModelFile(), { force: true }) +}) + +/** A plan's model, its pay-as-you-go twin, and one more — or without the twin. */ +function config(url: string, o: { model?: string; twin?: boolean; other?: boolean; extra?: string; window?: number } = {}) { + mkdirSync(paths.config, { recursive: true }) + const models = [`plan/coder: { interactive_only: true${o.window ? `, context: ${o.window}` : ""} }`, "plan/max: { interactive_only: true }", ...(o.twin === false ? [] : ["payg/coder: {}"]), ...(o.other === false ? [] : ["open/flash: {}"])] + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models:\n${models.map((m) => ` ${m}`).join("\n")}\n`, { mode: 0o600 }) + writeFileSync(join(paths.config, "config.yaml"), `model: ${o.model ?? "plan/coder"}\n${o.extra ?? ""}`) +} + +function project(): string { + const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-interactive-"))) + Bun.spawnSync(["git", "init", "-q", dir]) + setTrust(dir, "trusted") + return dir +} + +const asker = { ask: async () => ({ action: "deny" as const }) } as never +function app(cwd: string, extra: Record = {}) { + const a = createApp({ cwd, asker, snapshots: false, ...extra }) + closing.push(() => a.close()) + return a +} +const reply = (text = "ok") => ({ chunks: [delta({ content: text })] }) +const asked = () => fake!.requests.map((r) => r.model as string) +const SENTENCE = (model: string) => LOOP.interactive.texts.scheduled.replace("{{model}}", model) + +test("the field: read from /v1/models only when the server says true", () => { + expect(specFor({ id: "plan/coder", interactive_only: true }, "f").interactive_only).toBe(true) + expect("interactive_only" in specFor({ id: "payg/coder" }, "f")).toBe(false) + expect("interactive_only" in specFor({ id: "payg/coder", interactive_only: false }, "f")).toBe(false) +}) + +test("a person's turn runs on the interactive-only model; its title is asked of the twin", async () => { + fake = fakeProvider([reply("Hello."), reply("A greeting")]) + config(fake.url) + const a = app(project()) + await a.turns.prompt("hello there") + for (let i = 0; i < 100 && fake.requests.length < 2; i++) await Bun.sleep(10) + expect(asked()).toEqual(["plan/coder", "payg/coder"]) +}) + +test("no twin: the title goes to the default that is not interactive-only; with none, it is not asked for at all", async () => { + fake = fakeProvider([reply("Hello."), reply("A greeting")]) + // The session is on plan/max (asked for); the global setting is a model that may take it. + config(fake.url, { model: "open/flash" }) + const a = app(project(), { model: "plan/max" }) + await a.turns.prompt("hello there") + for (let i = 0; i < 100 && fake.requests.length < 2; i++) await Bun.sleep(10) + expect(asked()).toEqual(["plan/max", "open/flash"]) + fake.stop() + + fake = fakeProvider([reply("Hello.")]) + config(fake.url, { twin: false, other: false }) + const root = project() + const b = app(root) + await b.turns.prompt("hello there") + await Bun.sleep(150) + expect(asked()).toEqual(["plan/coder"]) + // The name made from the first prompt stays. + expect(b.store!.session(b.engine.sessionId!)!.title).toBe("hello there") +}) + +test("compaction the person asks for is the twin's work, and the session stays on its model", async () => { + fake = fakeProvider([reply("Hello."), reply("We said hello."), reply("Carrying on.")]) + config(fake.url) + const a = app(project(), { modelTitles: false }) + await a.turns.prompt("hello there") + expect(await a.engine.compact()).toContain("We said hello.") + expect(a.engine.model.ref).toBe("plan/coder") + await a.turns.prompt("and now?") + expect(asked()).toEqual(["plan/coder", "payg/coder", "plan/coder"]) +}) + +test("with nowhere to go, compaction asked for is refused in the spec's words and nothing is sent", async () => { + fake = fakeProvider([reply("Hello.")]) + config(fake.url, { twin: false, other: false }) + const a = app(project(), { modelTitles: false }) + await a.turns.prompt("hello there") + await expect(a.engine.compact()).rejects.toThrow(LOOP.interactive.texts.compact) + expect(asked()).toEqual(["plan/coder"]) + expect(a.engine.messages.length).toBeGreaterThan(1) +}) + +test("automatic compaction with nowhere to go is skipped, said once, and the turn goes on", async () => { + const long = "word ".repeat(2500) + fake = fakeProvider([{ chunks: [delta({ content: long })] }, reply("Second."), reply("Third.")]) + // A window the system prompt alone overflows: every step is past the automatic threshold. + config(fake.url, { twin: false, other: false, window: 2000 }) + const a = app(project(), { modelTitles: false }) + const notices: string[] = [] + a.bus.on((e) => e.type === "notice" && notices.push(e.message)) + await a.turns.prompt("one") + await a.turns.prompt("two") + await a.turns.prompt("three") + expect(asked()).toEqual(["plan/coder", "plan/coder", "plan/coder"]) + expect(notices.filter((n) => n.includes("interactive use only"))).toHaveLength(1) + expect(notices.some((n) => n.includes("compacting the conversation"))).toBe(false) +}) + +test("automatic compaction with a twin is the twin's work", async () => { + fake = fakeProvider([reply("First."), reply("A summary of it."), reply("Second.")]) + config(fake.url, { window: 2000 }) + const a = app(project(), { modelTitles: false }) + await a.turns.prompt("one") + await a.turns.prompt("two") + expect(asked().slice(0, 3)).toEqual(["plan/coder", "payg/coder", "plan/coder"]) + expect(a.engine.model.ref).toBe("plan/coder") +}) + +// ── scheduled work ────────────────────────────────────────────────────────────────────────── + +test("scheduled work never starts on one: asked for, it is refused; remembered for the directory, it is skipped", () => { + fake = fakeProvider([]) + config(fake.url, { model: "open/flash" }) + const root = project() + expect(() => app(root, { model: "plan/coder", automated: true })).toThrow(SENTENCE("plan/coder")) + expect(() => app(root, { model: "plan/coder", automated: true })).toThrow(InteractiveOnlyError) + rememberModel(root, "plan/coder") + expect(app(root, { automated: true }).engine.model.ref).toBe("open/flash") + // A person's session there starts on it. + expect(app(root).engine.model.ref).toBe("plan/coder") + // And scheduled work cannot switch to one. + const a = app(root, { automated: true }) + expect(() => a.switchModel("plan/max")).toThrow(SENTENCE("plan/max")) + expect(a.engine.model.ref).toBe("open/flash") +}) + +function pair(): [Transport, Transport] { + const make = () => ({ msg: (_: string) => {}, end: () => {} }) + const a = make() + const b = make() + const side = (me: typeof a, other: typeof a): Transport => ({ + send: (t) => queueMicrotask(() => other.msg(t)), + onMessage: (fn) => (me.msg = fn), + onClose: (fn) => (me.end = fn), + close: () => (me.end(), other.end()), + }) + return [side(a, b), side(b, a)] +} + +const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true, scheduled: true }) + +async function client(limits: Limits) { + const [ta, tb] = pair() + new AcpAgent(new Peer(ta), limits, "f") + const c = new Peer(tb) + c.on("_lembas/event", () => {}) + c.on("session/update", () => {}) + c.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } })) + await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + return c +} + +const refusal = async (p: Promise) => p.then(() => undefined, (e) => ({ message: (e as Error).message, data: (e as { data?: unknown }).data })) +const scheduled = { schedule_id: "sched1", run_id: "run7", title: "Check" } +const say = (sessionId: string, text: string, lembas: Record = {}) => ({ sessionId, prompt: [{ type: "text", text }], _meta: { lembas } }) + +test("a scheduled session on an interactive-only model is refused by the device, with the sentence and the reason; an agent chat on it is not", async () => { + fake = fakeProvider([reply("Hello.")]) + config(fake.url, { model: "open/flash" }) + const root = project() + const c = await client(limitsFor(root)) + const no = await refusal(c.request("session/new", { cwd: root, _meta: { lembas_model: "plan/coder", lembas: { scheduled } } })) + expect(no).toEqual({ message: SENTENCE("plan/coder"), data: { reason: "interactive_only" } }) + expect(fake.requests).toHaveLength(0) + // A person's agent chat on the same model: theirs to use. + const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "plan/coder" } }) + expect(s._meta.lembas.model).toBe("plan/coder") + await c.request("session/prompt", say(s.sessionId, "hello")) + expect(asked()).toEqual(["plan/coder"]) +}) + +test("a continuing schedule whose session has since come to be on one: the scheduled turn is refused before anything is sent, the person's own turn runs", async () => { + fake = fakeProvider([reply("Checked."), reply("It was fine.")]) + config(fake.url, { model: "open/flash" }) + const root = project() + const c = await client(limitsFor(root)) + const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "open/flash", lembas: { scheduled } } }) + await c.request("session/prompt", say(s.sessionId, "check", { scheduled, turnId: "run7" })) + // Between runs the chat's model is changed to the plan's. + await c.request("_lembas/configure", { sessionId: s.sessionId, model: "plan/coder" }) + const no = await refusal(c.request("session/prompt", say(s.sessionId, "check", { scheduled: { ...scheduled, run_id: "run8" }, turnId: "run8" }))) + expect(no).toEqual({ message: SENTENCE("plan/coder"), data: { reason: "interactive_only" } }) + expect(asked()).toEqual(["open/flash"]) + await c.request("session/prompt", say(s.sessionId, "what did you find?")) + expect(asked()).toEqual(["open/flash", "plan/coder"]) +}) + +test("a scheduled run's subagent is not started on one: the call answers the sentence and the run goes on", async () => { + fake = fakeProvider([ + { chunks: [toolCall(0, "t1", "task", JSON.stringify({ agent: "general", description: "look", prompt: "look around", model: "plan/coder" }))] }, + reply("Done without it."), + ]) + config(fake.url, { model: "open/flash" }) + const root = project() + const c = await client(limitsFor(root)) + const s: any = await c.request("session/new", { cwd: root, _meta: { lembas_model: "open/flash", lembas: { scheduled: { ...scheduled, mode: "auto" } } } }) + const r: any = await c.request("session/prompt", say(s.sessionId, "use plan/coder for a subagent and check", { scheduled: { ...scheduled, mode: "auto" }, turnId: "run7" })) + expect(r._meta.lembas.scheduled.status).toBe("ok") + expect(asked()).toEqual(["open/flash", "open/flash"]) + const result = JSON.stringify(fake.requests[1].messages.at(-1)) + expect(result).toContain("for interactive use only") +})