Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)`).
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
71 changes: 71 additions & 0 deletions lib/agent-command.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) });
}
Expand Down Expand Up @@ -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: <typo>` 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) });
Expand Down
25 changes: 24 additions & 1 deletion lib/agent-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -21,6 +22,24 @@ export const NO_SPAWN_REPLIES: Record<string, unknown> = {
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<string, unknown>): { 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 {
Expand Down Expand Up @@ -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 });
Expand All @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions lib/hosts/daemon-channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions lib/hosts/link-protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, true> = { 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. */
Expand Down
36 changes: 36 additions & 0 deletions lib/pi-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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" }>;
}
Expand Down
Loading
Loading