diff --git a/AGENTS.md b/AGENTS.md index dfc78bbcb..96413c3df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -372,6 +372,25 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri so a reload reattaching seconds later does not 409. Both are fed by `resetIdleTimer()`, the single activity choke point for `send()` and every child frame: adding a new call path must route activity through it. +- **Goal mode (`{type:"goal", op}`)** is forwarded to omp verbatim through its + own dispatch case; every op answers `{goal, state}` (`GoalCommandReply`), both + `null` once no goal is set — omp answers that after `drop`. `get_state` carries + the same mode snapshot as its `goal` field (`GoalModeState`: `{enabled, mode, + goal}`, `null` after a drop, absent on an omp that predates goal mode, which is + never invented here). Only the mutating ops (`create`, `pause`, `resume`, + `drop`) may start a child; every other op — `get`, a missing op, a typo or a + non-string op (a bare property lookup would coerce `["create"]`) — is live-only + (`liveOnlyRefusal` in `lib/agent-command.ts`): with no live wrapper it answers + 409 `goal_state_unavailable` instead of resuming a full omp child, and a live + idle child is never replaced for it. + Those same four ops are history mutations for the edit fence + (`isHistoryMutatingCommand` in `lib/hosts/link-protocol.ts`): a `goal` write is + refused while an Edit owns the wrapper, blocks a new Edit while it is in + flight, and is refused by the daemon for a peer while another server holds the + edit lease. `get` stays a read that an Edit does not fence. + `mode` stays `active` for a paused goal too; `enabled` is the field that says + whether it runs. The web composer's `/goal` slash command is a client-side + prompt expansion, not this transport. ### Auto-resume after a restart (`lib/session-resume.ts`) - **v7 hosts:** `lib/hosts/host-resume.ts` records unsettled sessions and launch @@ -411,7 +430,8 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri `omp_version` reports omp found after a hello that said none (the daemon retries the runner fetch and the read, 30 s doubling to 5 min); one link is the automatic notification publisher. Cross-server fences live in the daemon: a history edit takes the acknowledged - `editLease` op before preflight, and a `peer_message_command` marker makes another server's identical echo + `editLease` op before preflight (peer `goal` writes are classified by their + `op`, so `get` is not fenced), and a `peer_message_command` marker makes another server's identical echo ambiguous (`watchReplacement`). An open's preparation lease passes only to the command that asked for it (`withPendingCommand(run, true)`); a command timeout that recycles the child stops the shared process (`destroyAndWait(reason, true)`). diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..9c9c7dd8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -164,6 +164,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **The dictation waveform recovers when the browser suspends its audio.** If the browser suspends or interrupts the meter's audio context mid-recording or during a pause, the recording resumes it, so the bars follow your voice again instead of staying flat while the recording itself works. - **Provider cards no longer look clickable.** Hovering or tapping a provider's non-interactive card no longer accents its border. Configure and Manage keep the neutral secondary-button styling used elsewhere in Settings; the clickable Browse all providers card keeps its hover feedback. - **The retry banner keeps its cancel button on-screen on mobile.** Retry details wrap within the composer, including long provider errors, instead of pushing the Abort retry button past the side of the screen. Long details scroll within a bounded area, and the controls reflow in narrow chat columns. +- **Goal mode is available to native clients.** `goal` RPC commands (`create`, `get`, `pause`, `resume`, `drop`) are forwarded to omp unchanged, and `get_state` carries omp's `goal` snapshot (an absent field stays absent on older omp). Native apps can now start, show and control a running goal; `goal_updated` frames already streamed. Reading goal state (`get`, or any op omp would reject — including a non-string op) requires a live session and answers 409 `goal_state_unavailable` instead of resuming a full omp child just to relay the answer; the mutating ops keep starting an idle session, since that is how a goal is set there. The four mutating ops are fenced like every other history write: they wait while an Edit owns the session and hold a new Edit until they finish. - **Windows host updates allow more time for safety checks.** The process inventory gets up to 20 seconds to start and finish on a busy machine, instead of five. Shared installations and failed or unreadable inventories still block the update before the daemon is stopped. - **Copied uploads start retention at the send time on Windows too.** When a hard link cannot be used or its timestamp cannot be changed, the host writes a fresh exclusive copy instead of inheriting an old staging timestamp. Failed copies remain retryable without replacing unrelated files. - **Windows servers can manage pools of Unix workers.** Pool configuration and clone paths use the worker's path rules, not the web server's OS. Creation journals retain their synced-file, atomic-rename commit on Windows without requiring unsupported directory fsync. diff --git a/lib/agent-command.test.mjs b/lib/agent-command.test.mjs index 0b7bca1f3..1b2e3f324 100644 --- a/lib/agent-command.test.mjs +++ b/lib/agent-command.test.mjs @@ -46,6 +46,10 @@ async function respond(message, link = daemon) { reply = child.setModelFails ? { ok: false, error: "Model not found" } : { ok: true, data: { id: command.modelId, provider: command.provider } }; + } else if (command.type === "goal") { + // omp 18.12.4: `{goal, state}`, both null once no goal is set (after `drop`). + const goal = child.goal ?? null; + reply = { ok: true, data: { goal, state: goal ? { enabled: true, mode: "active", goal } : null } }; } await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ t: "res", id: command.id, ...reply }) }); } @@ -258,6 +262,73 @@ test("asking a side question (btw) without a wrapper starts omp", async (t) => { assert.equal(launches(), 1); }); +// `goal` `get` reads the state a running child holds: inspecting goal mode must +// not resume a full omp child (MCP, LSP) for a saved session. The mutating ops +// keep their start semantics — they are how a client sets a goal on an idle one. +test("goal get without a live wrapper is refused and never starts omp", async (t) => { + useRegistry(t); + const response = await post(SAVED_ID, { type: "goal", op: "get" }); + const text = await response.text(); + assert.equal(response.status, 409, text); + assert.equal(JSON.parse(text).code, "goal_state_unavailable"); + assert.equal(launches(), 0, "no omp child was created"); + assert.equal(globalThis.__ompSessions.size, 0, "no wrapper was registered"); +}); + +test("goal get does not resume a session whose wrapper has exited", async (t) => { + const exited = fake(); + exited.isAlive = () => false; + useRegistry(t, { [SAVED_ID]: exited }); + const response = await post(SAVED_ID, { type: "goal", op: "get" }); + assert.equal(response.status, 409); + assert.equal((await response.json()).code, "goal_state_unavailable"); + assert.equal(launches(), 0, "no replacement omp child was created"); + assert.deepEqual(exited.sent, [], "the exited wrapper received nothing"); +}); + +// omp answers `Unknown goal op: undefined` for a bare `{type:"goal"}` and +// `Unknown goal op: ` for anything it does not know, so a spawn would only +// pay for a full child to relay that rejection. Only the four mutating ops start; +// a non-string op (an array would be coerced by a bare property lookup) never +// does. +for (const body of [ + { type: "goal" }, { type: "goal", op: "bogus" }, { type: "goal", op: "" }, + { type: "goal", op: ["create"] }, { type: "goal", op: 7 }, { type: "goal", op: { op: "create" } }, +]) { + test(`goal with ${JSON.stringify(body.op)} is live-only and never starts omp`, async (t) => { + useRegistry(t); + const response = await post(SAVED_ID, body); + const text = await response.text(); + assert.equal(response.status, 409, text); + assert.equal(JSON.parse(text).code, "goal_state_unavailable"); + assert.equal(launches(), 0, "no omp child was created for an op omp would reject"); + assert.equal(globalThis.__ompSessions.size, 0, "no wrapper was registered"); + }); +} + +test("goal get is answered by a live idle wrapper without replacing it", async (t) => { + const goal = { id: "g1", objective: "ship", status: "active", tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 1 }; + const live = fake({ advisorSpawned: false, send: async () => ({ goal, state: { enabled: true, mode: "active", goal } }) }); + useRegistry(t, { [SAVED_ID]: live }); + const response = await post(SAVED_ID, { type: "goal", op: "get" }, undefined, "?advisor=1"); + assert.deepEqual(await jsonOf(response), { success: true, data: { goal, state: { enabled: true, mode: "active", goal } } }); + assert.deepEqual(live.sent, [{ type: "goal", op: "get" }]); + assert.equal(live.destroyed, 0, "an idle live child is never restarted to read goal state"); + assert.equal(launches(), 0); +}); + +for (const op of ["create", "pause", "resume", "drop"]) { + test(`goal ${op} keeps its start semantics and resumes a saved session`, async (t) => { + useRegistry(t); + child.goal = { id: "g1", objective: "ship", status: "active", tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 1 }; + const response = await post(SAVED_ID, { type: "goal", op, objective: "ship" }); + const text = await response.text(); + assert.equal(response.status, 200, text); + assert.equal(launches(), 1, `goal ${op} starts omp for a saved session`); + assert.deepEqual(stdin.filter((command) => command.type === "goal").map((command) => command.op), [op]); + }); +} + test("an oversized body is 413 request_too_large; a malformed body is 400 invalid_json", async (t) => { useRegistry(t, { s3: fake() }); const big = JSON.stringify({ type: "prompt", message: "a".repeat(MAX_AGENT_COMMAND_REQUEST_BYTES + 1) }); diff --git a/lib/agent-command.ts b/lib/agent-command.ts index 2878d7065..95c5af745 100644 --- a/lib/agent-command.ts +++ b/lib/agent-command.ts @@ -8,6 +8,7 @@ import { runOutboxCommand } from "@/lib/message-outbox"; import { readClientMessageIds } from "@/lib/client-message-ids"; import { reconcileOutboxHandoffs } from "@/lib/outbox-handoff"; import type { MessageOrigin } from "@/lib/message-origin"; +import { GOAL_HISTORY_MUTATING_OPS } from "@/lib/hosts/link-protocol"; // Commands that ride whatever child is alive and never spawn or replace one: // keystroke predictions, and the side-question reads/cancel omp-web sends in @@ -21,6 +22,24 @@ export const NO_SPAWN_REPLIES: Record = { btw_cancel: { cancelled: false }, }; +/** The refusal for a command that may only ride a live child, or undefined when + * the command may start one. `goal` reads the state a running child holds: a + * native client inspecting goal mode must not resume a full omp child (MCP, + * LSP) for it, and a saved session's goal is not read off disk here. Only the + * history-mutating ops (`create`, `pause`, `resume`, `drop`) keep their start + * semantics — they are what a client uses to set a goal on an idle session; + * `get`, a missing op, a typo and a non-string op only read state a live child + * holds, and omp rejects an unknown op (`Unknown goal op: undefined`), so + * spawning a full child just to relay that rejection is not what the caller + * asked for. The `typeof` check is load-bearing: the table lookup coerces its + * key, so `op: ["create"]` would otherwise read as the start op `create`. */ +function liveOnlyRefusal(type: string, command: Record): { error: string; code: string } | undefined { + if (type !== "goal") return undefined; + const op = command.op; + if (typeof op === "string" && Object.hasOwn(GOAL_HISTORY_MUTATING_OPS, op)) return undefined; + return { error: "Goal state requires a running session", code: "goal_state_unavailable" }; +} + /** omp-web's own failures carry a stable code the client can localize; omp's * errors stay opaque English text. */ export function commandErrorResponse(error: unknown): Response { @@ -112,8 +131,9 @@ export async function runAgentCommand(id: string, body: unknown, advisor: boolea let resumeId = id; let resumeHost: AgentSessionWrapper["host"] | undefined; const noSpawn = Object.hasOwn(NO_SPAWN_REPLIES, type); + const liveOnly = liveOnlyRefusal(type, command); if (existing?.isAlive()) { - if (noSpawn || (existing.adopted && !existing.hostOwnedLifecycle) + if (noSpawn || liveOnly || (existing.adopted && !existing.hostOwnedLifecycle) || existing.advisorSpawned === (advisor === true || existing.launchAdvisor === true) || existing.isRunning() || existing.isEditingHistory()) { const result = await send(existing); return Response.json({ success: true, data: result }); @@ -126,6 +146,9 @@ export async function runAgentCommand(id: string, body: unknown, advisor: boolea if (!existing.hostOwnedLifecycle) await existing.destroyAndWait("advisor", true); } if (noSpawn) return Response.json({ success: true, data: NO_SPAWN_REPLIES[type] }); + if (liveOnly) { + return Response.json({ error: liveOnly.error, code: liveOnly.code }, { status: 409 }); + } const resolved = resumeHost ? { host: resumeHost } : await resolveSessionHostOr404(resumeId); if ("response" in resolved) return resolved.response; diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 003735354..8539e09f3 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -5,7 +5,7 @@ import { readSessionHeaderSync } from "../omp/session-files"; import { isValidSessionId } from "../session-file-references-core"; import { isRecord } from "../type-guards"; import type { DaemonLink } from "./daemon-link"; -import { CONFIG_VERSION_RE, CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME, type HelloChannel, type HostUriScheme, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; +import { CONFIG_VERSION_RE, CREATION_ID_RE, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME, isHistoryMutatingCommand, type HelloChannel, type HostUriScheme, type OpenChannelRequest, type OpenChannelResult, type Unsequenced, type UpMessage } from "./link-protocol"; import { CHANNEL_PROTO } from "./omp-socket"; import { idOf, parseWire, PendingRequests, wireEvent, type WireFrame } from "./pending-requests"; import { StreamSnapshot } from "./stream-snapshot"; @@ -457,7 +457,7 @@ export class ChannelTable { if (op !== null) this.deliver(channel, member, { type: "stdout", ch, line: JSON.stringify({ t: "res", id: frame.id, ok: false, code, error }) }, true); }; if (channel.replacing) return refuse("session_restarting", "This session is restarting to apply advisor mode; retry once it is ready"); - if (op !== null && channel.editor !== undefined && channel.editor !== link.id && HISTORY_MUTATING_COMMANDS.has(op)) { + if (op !== null && channel.editor !== undefined && channel.editor !== link.id && isHistoryMutatingCommand(op, frame.args)) { return refuse("session_busy", "Another web app is editing this session's history; retry once it finishes"); } if (op === "branch" || op === "new_session" || op === "switch_session") channel.sessionMovePending = false; diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index dd59a01ac..3bc57f52d 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -73,6 +73,19 @@ export const HISTORY_MUTATING_COMMANDS = new Set([ "set_model", "cycle_model", "set_thinking_level", "cycle_thinking_level", "set_fast_mode", "set_slow_mode", "set_auto_compaction", "set_auto_retry", "abort_retry", ]); +/** `goal` sub-ops that append to or replace the active history; `get` only reads + * the state a live child holds. omp rejects any other op (`Unknown goal op`), so + * a typo never writes and never needs the fence. */ +export const GOAL_HISTORY_MUTATING_OPS: Record = { create: true, pause: true, resume: true, drop: true }; +/** Whether one command frame mutates session history: by type for every + * `HISTORY_MUTATING_COMMANDS` entry, and by its `op` for `goal` (the frame's + * args, or the wrapper's flat command). A non-string op is never a goal write. */ +export function isHistoryMutatingCommand(type: string, args?: unknown): boolean { + if (HISTORY_MUTATING_COMMANDS.has(type)) return true; + if (type !== "goal" || !args || typeof args !== "object" || !("op" in args)) return false; + const op = args.op; + return typeof op === "string" && Object.hasOwn(GOAL_HISTORY_MUTATING_OPS, op); +} /** Commands whose user message a peer's identical echo could be mistaken for. */ export const MESSAGE_COMMANDS = new Set(["prompt", "steer", "follow_up", "followUp", "abort_and_prompt"]); /** Shared-channel marker a daemon puts in the other members' output when one link writes a message command. */ diff --git a/lib/pi-types.ts b/lib/pi-types.ts index 495d116dc..664a754f3 100644 --- a/lib/pi-types.ts +++ b/lib/pi-types.ts @@ -17,6 +17,38 @@ export type UsageLimitState = export type SlowModeScope = "session" | "global"; +/** omp's goal record: the `goal` value of a `goal` command reply and of `state.goal` in `get_state`. */ +export interface GoalInfo { + id: string; + objective: string; + /** `active` or `paused`; a dropped goal is reported as `null` instead of a record. */ + status: string; + tokenBudget?: number; + tokensUsed: number; + timeUsedSeconds: number; + createdAt: number; + updatedAt: number; +} + +/** omp's goal-mode state snapshot: the `state` value of a `goal` command reply, + * and the `goal` field of `get_state`. Not the command reply itself (see + * GoalCommandReply). */ +export interface GoalModeState { + enabled: boolean; + /** omp reports `active` for a running and for a paused goal alike; `enabled` + * is what says whether it runs. */ + mode: string; + goal: GoalInfo | null; +} + +/** Reply to `{type:"goal", op}`: `{goal, state}`, both `null` once no goal is + * set (omp answers that after `drop`). `goal` is the record the op acted on, + * `state` the mode snapshot around it. */ +export interface GoalCommandReply { + goal: GoalInfo | null; + state: GoalModeState | null; +} + export interface ModelLike { id: string; provider: string; @@ -116,6 +148,8 @@ export interface RpcSessionState { usageLimit?: UsageLimitState; /** omp's reported output throughput; null/undefined when not generating. */ tokensPerSecond?: number | null; + /** omp goal mode; absent on older OMP builds (never invented here). */ + goal?: GoalModeState | null; } /** @@ -153,6 +187,8 @@ export interface WebSessionState { autoRetryEnabled?: boolean; tokensPerSecond?: number | null; todoPhases: TodoPhase[]; + /** omp goal mode snapshot; omitted when the child predates the `goal` field. */ + goal?: GoalModeState | null; extensionStatuses: Array<{ key: string; text: string }>; extensionWidgets: Array<{ key: string; lines: string[]; placement: "aboveEditor" | "belowEditor" }>; } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 4c732883f..cbb55836a 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2330,6 +2330,8 @@ test("an edit fences prompts and history changes from every client until its cor { type: "abort_and_prompt", message: "replace" }, { type: "abort" }, { type: "set_session_name", name: "rename" }, { type: "set_model", provider: "x", modelId: "y" }, { type: "remove_queued_message", messageId: "queued" }, + { type: "goal", op: "create", objective: "ship" }, { type: "goal", op: "pause" }, + { type: "goal", op: "resume" }, { type: "goal", op: "drop" }, ]; const sentBefore = session.commands.length; for (const command of fenced) await assert.rejects(session.wrapper.send(command), { code: "session_busy" }); @@ -2338,6 +2340,8 @@ test("an edit fences prompts and history changes from every client until its cor assert.equal(session.commands.length, sentBefore, "no fenced mutation reaches the shared child"); await session.wrapper.send({ type: "get_state" }); await session.wrapper.send({ type: "get_messages" }); + await session.wrapper.send({ type: "goal", op: "get" }); + assert.equal(session.commands.at(-1).type, "goal", "reading goal state is not a history mutation"); await session.wrapper.send({ type: "ui_response", id: 7 }); assert.equal(session.sentFrames.at(-1).id, 7, "navigation hooks may still receive dialog answers"); release(); @@ -2362,6 +2366,20 @@ test("the mutation fence is acquired before the edit's native-state preflight ca assert.equal((await editing).sessionId, state.sessionId); }); +test("a pending goal mutation prevents an edit, and a completed edit admits it again", async (t) => { + const { wrapper, commands } = await editableSession(t); + const originalSend = wrapper.proc.sendCommand; + const { promise: gate, resolve: release } = Promise.withResolvers(); + wrapper.proc.sendCommand = async (command, ...rest) => command.type === "goal" ? gate : originalSend(command, ...rest); + const creating = wrapper.send({ type: "goal", op: "create", objective: "ship" }); + await assert.rejects(wrapper.send({ type: "edit_message", entryId: "u2" }), { code: "session_busy" }); + assert.equal(commands.some((command) => command.type === "edit_message"), false, "the edit never reaches the shared child"); + release({ goal: { id: "g1", objective: "ship" }, state: { enabled: true, mode: "active" } }); + assert.deepEqual(await creating, { goal: { id: "g1", objective: "ship" }, state: { enabled: true, mode: "active" } }); + wrapper.proc.sendCommand = originalSend; + assert.equal((await wrapper.send({ type: "edit_message", entryId: "u2" })).cancelled, false); +}); + test("a pending Fork prevents an edit, while independent Fork retains its native branch contract", async (t) => { const { wrapper, commands } = await editableSession(t); const originalSend = wrapper.proc.sendCommand; @@ -4234,3 +4252,44 @@ test("prepared creation cannot accept a validateCwd fallback while standalone st session = standalone.value.session; assert.equal(session.cwd, "/fallback"); }); + +test("goal commands pass through and their state reaches the web state", async (t) => { + const sent = []; + const active = { + goal: { id: "g1", objective: "ship", status: "active", tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 1 }, + state: { enabled: true, mode: "active", goal: { id: "g1", objective: "ship", status: "active", tokensUsed: 0, timeUsedSeconds: 0, createdAt: 1, updatedAt: 1 } }, + }; + const { wrapper } = snapshotSession(t, async (command) => { + sent.push(command); + // omp 18.12.4: `{goal, state}`, both null once no goal is set (after `drop`). + if (command.type === "goal") return command.op === "drop" ? { goal: null, state: null } : active; + return {}; + }); + assert.deepEqual(await wrapper.send({ type: "goal", op: "create", objective: "ship" }), active); + assert.deepEqual(await wrapper.send({ type: "goal", op: "get" }), active); + assert.deepEqual(await wrapper.send({ type: "goal", op: "drop" }), { goal: null, state: null }); + assert.deepEqual(sent.map((command) => [command.type, command.op]), [["goal", "create"], ["goal", "get"], ["goal", "drop"]]); + assert.equal(sent[0].objective, "ship", "the frame reaches omp verbatim"); +}); + +test("get_state carries the goal snapshot and never invents one", async (t) => { + const goal = { id: "g1", objective: "ship", status: "active", tokensUsed: 1, timeUsedSeconds: 2, createdAt: 3, updatedAt: 4 }; + const state = (patch = {}) => ({ + sessionId: "goal-state", sessionFile: "/nonexistent/goal-state.jsonl", + isStreaming: false, isCompacting: false, steeringMode: "all", followUpMode: "all", + interruptMode: "immediate", autoCompactionEnabled: false, messageCount: 0, + queuedMessageCount: 0, todoPhases: [], systemPrompt: ["p"], + goal: { enabled: true, mode: "active", goal }, + ...patch, + }); + const withGoal = snapshotSession(t, async (command) => (command.type === "get_state" ? state() : {}), SnapshotWrapper, "goal-shape"); + const full = await withGoal.wrapper.send({ type: "get_state" }); + // The field is omp's GoalModeState snapshot (`{enabled, mode, goal}`), not the + // `{goal, state}` command reply. + assert.deepEqual(full.goal, { enabled: true, mode: "active", goal }); + const dropped = snapshotSession(t, async (command) => (command.type === "get_state" ? state({ goal: null }) : {}), SnapshotWrapper, "goal-dropped"); + assert.equal((await dropped.wrapper.send({ type: "get_state" })).goal, null, "a dropped goal stays null"); + const withoutGoal = snapshotSession(t, async (command) => (command.type === "get_state" ? state({ goal: undefined }) : {}), SnapshotWrapper, "no-goal"); + const slim = await withoutGoal.wrapper.send({ type: "get_state" }); + assert.equal("goal" in slim, false, "a child that reports no goal gets none invented"); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index fcff6ac53..d8ddfa2b2 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -33,6 +33,7 @@ import { publishNotification } from "./notification-hub"; import { eventWithToolResultImageUrls } from "./media-cache"; import type { BashResultInfo, + GoalCommandReply, OmpModel, RpcAvailableSlashCommand, RpcSessionState, @@ -42,7 +43,7 @@ import type { import type { AgentConfirmPayload, AgentMessage, CrossSessionHostToolCall, CrossSessionHostToolEvent, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus, type SpawnRequest, type SpawnResult } from "./hosts/host"; import { freezeHostLinks, getHost, hostOwnsLifecycle, isNotifier, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; -import { CREATION_ID_RE, HISTORY_MUTATING_COMMANDS, HostOpError, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME } from "./hosts/link-protocol"; +import { CREATION_ID_RE, HostOpError, PEER_MESSAGE_FRAME, PEER_PROMPT_OUTCOME_FRAME, isHistoryMutatingCommand } from "./hosts/link-protocol"; import { LOCAL_HOST_ID } from "./hosts/registry"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; @@ -182,6 +183,9 @@ const PASSTHROUGH_COMMANDS = new Set([ "btw_cancel", "get_btw_history", "get_client_message_status", + // Goal mode (`{type:"goal", op}`) has the same shape as omp's RPC frame and + // is the only way native clients reach it; every op answers `{goal, state}`. + "goal", ]); // Outlasts omp's cold prediction-daemon start (up to 3 × 30s start rounds plus a @@ -2215,6 +2219,8 @@ export class AgentSessionWrapper { slowModeScope: state.slowModeScope, usageLimit: state.usageLimit, todoPhases: state.todoPhases ?? [], + // Never invent a goal shape for a child that does not report one. + ...(state.goal !== undefined ? { goal: state.goal } : {}), extensionStatuses: Array.from(this.extensionStatuses, ([key, text]) => ({ key, text })), extensionWidgets: Array.from(this.extensionWidgets.values()), }; @@ -2593,7 +2599,7 @@ export class AgentSessionWrapper { if (typeof command.type === "string" && command.type.startsWith("abort")) { console.info("[omp-web] cancellation-command", JSON.stringify({ sessionId: this._sessionId, type: command.type, at: new Date().toISOString() })); } - const mutatesHistory = HISTORY_MUTATING_COMMANDS.has(command.type as string); + const mutatesHistory = isHistoryMutatingCommand(command.type as string, command); if (mutatesHistory && this.historyEditInFlight) { throw new WebRpcError("Wait for the history edit to finish", "session_busy"); } @@ -3011,6 +3017,16 @@ export class AgentSessionWrapper { return null; } + // Goal mode: `{type:"goal", op}` is omp's own RPC frame, forwarded + // verbatim. Every op answers `{goal, state}` — `goal` the record the op + // acted on, `state` the mode snapshot around it, both `null` once no goal + // is set (omp answers that after `drop`). Typed here because this is the + // only place omp-web sees the reply shape. + case "goal": { + const reply: GoalCommandReply = await this.sendNativeMessageCommand(command as { type: string }, undefined, command); + return reply; + } + default: { if (PASSTHROUGH_COMMANDS.has(type)) { if (type === "abort_and_prompt") {