Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(scheduler): swap out a running background model call for interactive work
LeoXingcb4c8b670628
diff --git a/apps/computer/AGENTS.md b/apps/computer/AGENTS.mdindex 1a8e4313..d4a115c7 100644--- a/apps/computer/AGENTS.md+++ b/apps/computer/AGENTS.md@@ -80,10 +80,11 @@change therefore needs no version bump to reach Computers.- Bump `apps/computer/package.json` only when raising the versionfloor or when the Agent Service must tell a release that decodes a new- optional `runner.welcome` field from one that rejects it (the Daemon decodes- frames strictly). The package version is the source for the bundled CLI and- Go Daemon `ReleaseVersion`; it is used for display, the floor, and those- welcome fields, never to trigger or order upgrades.+ optional `runner.welcome` field or a new Agent frame from one that rejects+ it (the Daemon decodes frames strictly and closes the connection on an+ unknown one). The package version is the source for the bundled CLI and Go+ Daemon `ReleaseVersion`; it is used for display, the floor, and those+ fields and frames, never to trigger or order upgrades.- A Daemon can outlive its Agent Service release: a desktop upgrade replacesthe Daemon while the installed services keep running until the ownerupdates them. A Daemon-to-Agent frame family added within protocol 2 isdiff --git a/apps/computer/local-daemon/internal/daemon/connection.go b/apps/computer/local-daemon/internal/daemon/connection.goindex b3cf9245..9a196b84 100644--- a/apps/computer/local-daemon/internal/daemon/connection.go+++ b/apps/computer/local-daemon/internal/daemon/connection.go@@ -191,6 +191,13 @@ func (d *Daemon) handleConnectionCommand(ctx, connectionCtx context.Context, strif err := d.handleModelInvoke(connectionCtx, stream, command); err != nil {return err}+ case protocol.CommandModelInvokeCancel:+ if !d.welcomeSeen || command.ConnectionEpoch != d.connectionEpoch {+ return errors.New("Model invocation cancel uses a stale connection epoch")+ }+ if err := d.cancelModelInvoke(command); err != nil {+ return err+ }case protocol.CommandOperationStart:if !d.welcomeSeen {return errors.New("operation uses a stale connection epoch")diff --git a/apps/computer/local-daemon/internal/daemon/model_invoke.go b/apps/computer/local-daemon/internal/daemon/model_invoke.goindex 03174cdc..aa2ed0bc 100644--- a/apps/computer/local-daemon/internal/daemon/model_invoke.go+++ b/apps/computer/local-daemon/internal/daemon/model_invoke.go@@ -157,6 +157,29 @@ func (d *Daemon) runModelInvoke(ctx context.Context, stream transport.Stream, co}}+// cancelModelInvoke cancels one in-flight model call; its canceled receipt+// follows unless it finished first. A call that is not running is already+// answered, so the cancel does nothing.+func (d *Daemon) cancelModelInvoke(command protocol.Command) error {+ var cancel wire.ModelInvokeCancel+ if err := json.Unmarshal(command.Payload, &cancel); err != nil {+ return fmt.Errorf("decode model invocation cancel: %w", err)+ }+ if cancel.InvokeID == "" {+ return errors.New("model invocation cancel is incomplete")+ }+ d.modelInvokeMu.Lock()+ defer d.modelInvokeMu.Unlock()+ entry := d.modelInvokes[cancel.InvokeID]+ if entry == nil {+ slog.Info("runner.model.invoke", "phase", "cancel_ignored", "invoke_id", cancel.InvokeID, "cancellation_source", cancel.Reason)+ return nil+ }+ entry.cancel()+ slog.Info("runner.model.invoke", "phase", "cancel_requested", "invoke_id", entry.id, "cancellation_source", cancel.Reason)+ return nil+}+// cancelModelInvokes cancels every in-flight model call; each still sends its// canceled receipt if the connection is open.func (d *Daemon) cancelModelInvokes(source string) {diff --git a/apps/computer/local-daemon/internal/daemon/model_invoke_test.go b/apps/computer/local-daemon/internal/daemon/model_invoke_test.goindex 77829fe4..bb2ee45a 100644--- a/apps/computer/local-daemon/internal/daemon/model_invoke_test.go+++ b/apps/computer/local-daemon/internal/daemon/model_invoke_test.go@@ -178,6 +178,37 @@ func TestModelInvokeIsCanceledByDisconnectAndDrain(t *testing.T) {}}+func TestModelInvokeCancelStopsOnlyThatCall(t *testing.T) {+ invoker := newFakeModelInvoker()+ d, stream := modelInvokeFixture(t, invoker)+ for _, id := range []string{"invoke-keep", "invoke-yield"} {+ if err := d.handleModelInvoke(context.Background(), stream, modelInvokeCommand(id, nil)); err != nil {+ t.Fatal(err)+ }+ <-invoker.started+ }+ cancel := func(id string) protocol.Command {+ return protocol.Command{+ Type: protocol.CommandModelInvokeCancel, CommandID: "cancel-" + id, RunnerID: "computer-1", ConnectionEpoch: 1,+ Payload: mustJSON(map[string]any{"invoke_id": id, "reason": "scheduler_yield"}),+ }+ }+ if err := d.cancelModelInvoke(cancel("invoke-yield")); err != nil {+ t.Fatal(err)+ }+ if payload := waitForModelInvoked(t, stream, "invoke-yield"); payload["outcome"] != "canceled" {+ t.Fatalf("payload = %v", payload)+ }+ // A cancel that arrives after its call was answered does nothing.+ if err := d.cancelModelInvoke(cancel("invoke-yield")); err != nil {+ t.Fatal(err)+ }+ close(invoker.release)+ if payload := waitForModelInvoked(t, stream, "invoke-keep"); payload["outcome"] != "completed" {+ t.Fatalf("payload = %v", payload)+ }+}+func TestModelInvokeRefusesWithoutRunningTheCall(t *testing.T) {for name, test := range map[string]struct {setup func(*Daemon)diff --git a/apps/computer/local-daemon/internal/linger/transport/gateway.go b/apps/computer/local-daemon/internal/linger/transport/gateway.goindex 2795ec30..3eede2e4 100644--- a/apps/computer/local-daemon/internal/linger/transport/gateway.go+++ b/apps/computer/local-daemon/internal/linger/transport/gateway.go@@ -150,6 +150,7 @@ var agentShapes = map[string]func() wire.Shape{"OperationStart": func() wire.Shape { return &wire.OperationStart{} },"OperationInput": func() wire.Shape { return &wire.OperationInput{} },"OperationCancel": func() wire.Shape { return &wire.OperationCancel{} },+ "ModelInvokeCancel": func() wire.Shape { return &wire.ModelInvokeCancel{} },"OperationAck": func() wire.Shape { return &wire.OperationAck{} },"ComputerToolCall": func() wire.Shape { return &wire.ComputerToolCall{} },}@@ -266,7 +267,8 @@ func decodeGatewayCommand(encoded []byte) (protocol.Command, error) {return protocol.Command{}, fmt.Errorf("encode Agent Runner lifecycle payload: %w", err)}case protocol.CommandProviderPrepare,- protocol.CommandSessionCompact, protocol.CommandModelInvoke, protocol.CommandComputerToolCall,+ protocol.CommandSessionCompact, protocol.CommandModelInvoke, protocol.CommandModelInvokeCancel,+ protocol.CommandComputerToolCall,protocol.CommandDebugInspect, protocol.CommandAgentCLICredentialPut,protocol.CommandCapabilitySkillsScan, protocol.CommandCapabilityBrowserConnect,protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels:diff --git a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.goindex 068c9c3a..46027fc9 100644--- a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go+++ b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go@@ -120,7 +120,8 @@ func TestRunnerWireContractFixtures(t *testing.T) {protocol.CommandDebugInspect, protocol.CommandCapabilitySkillsScan, protocol.CommandCapabilityBrowserConnect,protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels, protocol.CommandOperationPrepare, protocol.CommandOperationStart, protocol.CommandOperationInput,protocol.CommandOperationCancel, protocol.CommandOperationAck, protocol.CommandProviderPrepare,- protocol.CommandSessionCompact, protocol.CommandModelInvoke, protocol.CommandComputerToolCall} {+ protocol.CommandSessionCompact, protocol.CommandModelInvoke, protocol.CommandModelInvokeCancel,+ protocol.CommandComputerToolCall} {if !seen[kind] {t.Errorf("Agent fixture missing %s", kind)}@@ -348,6 +349,34 @@ func TestGatewayModelInvocationKeepsIdentityAndRawRequest(t *testing.T) {}}+func TestGatewayModelInvocationCancelNamesTheCall(t *testing.T) {+ const valid = `{"type":"cancel","target":"model_invoke","command_id":"command-2","invoke_id":"invoke-1","protocol_version":"2","runner_id":"computer-1","connection_epoch":3,"reason":"scheduler_yield"}`+ command, err := decodeGatewayCommand([]byte(valid))+ if err != nil {+ t.Fatal(err)+ }+ var cancel struct {+ InvokeID string `json:"invoke_id"`+ Reason string `json:"reason"`+ }+ if err := json.Unmarshal(command.Payload, &cancel); err != nil {+ t.Fatal(err)+ }+ if command.Type != protocol.CommandModelInvokeCancel || command.ConnectionEpoch != 3 ||+ cancel.InvokeID != "invoke-1" || cancel.Reason != "scheduler_yield" {+ t.Fatalf("command = %+v cancel = %+v", command, cancel)+ }+ for _, change := range [][2]string{+ {`"invoke_id":"invoke-1",`, ""},+ {`"connection_epoch":3,`, ""},+ } {+ frame := strings.Replace(valid, change[0], change[1], 1)+ if _, err := decodeGatewayCommand([]byte(frame)); err == nil {+ t.Fatalf("accepted %s", frame)+ }+ }+}+func TestGatewaySessionCompactionKeepsIdentityAndRawRequest(t *testing.T) {const valid = `{"type":"execute","kind":"session_compact","command_id":"command-1","compact_id":"compact-1","protocol_version":"2","runner_id":"computer-1","connection_epoch":3,"agent_id":"agent-1","runtime_type":"claude","execution_context_key":"meta:agent-1","instructions":"Keep open questions."}`command, err := decodeGatewayCommand([]byte(valid))diff --git a/apps/computer/local-daemon/internal/protocol/types.go b/apps/computer/local-daemon/internal/protocol/types.goindex 3dbbf564..02de2ef1 100644--- a/apps/computer/local-daemon/internal/protocol/types.go+++ b/apps/computer/local-daemon/internal/protocol/types.go@@ -131,6 +131,7 @@ const (CommandOperationPrepare = wire.TypePrepare + ":" + wire.TargetOperationCommandProviderPrepare = wire.TypePrepare + ":" + wire.TargetProviderCommandOperationCancel = wire.TypeCancel + ":" + wire.TargetOperation+ CommandModelInvokeCancel = wire.TypeCancel + ":" + wire.TargetModelInvokeCommandOperationStart = wire.TypeOperationStartCommandOperationInput = wire.TypeOperationInputCommandOperationAck = wire.TypeOperationAckdiff --git a/apps/computer/package.json b/apps/computer/package.jsonindex 55d4271c..71e6e78e 100644--- a/apps/computer/package.json+++ b/apps/computer/package.json@@ -1,6 +1,6 @@{"name": "@linger/computer",- "version": "0.52.0",+ "version": "0.53.0","description": "Local Computer: resident Daemon, control CLI, and Runner Gateway transport.","private": true,"type": "module",diff --git a/apps/computer/tests/runner-wire-contract.test.ts b/apps/computer/tests/runner-wire-contract.test.tsindex 0a3566b3..291ef747 100644--- a/apps/computer/tests/runner-wire-contract.test.ts+++ b/apps/computer/tests/runner-wire-contract.test.ts@@ -211,6 +211,16 @@ const agentFrames = [workspace_files: [{ path: "raw/notes.md", content_base64: "bm90ZXM=" }],timeout_ms: 4 * 60 * 60_000,},+ {+ type: "cancel",+ target: "model_invoke",+ protocol_version: "2",+ command_id: "invoke-cancel-1",+ invoke_id: "invoke-1",+ runner_id: assignment.runner_id,+ connection_epoch: 1,+ reason: "scheduler_yield",+ },...[{kind: "run.start",diff --git a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts b/apps/node-services/src/agent/executor/http/agent-manager-http-server.tsindex c764bac7..739cdfa1 100644--- a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts+++ b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts@@ -732,6 +732,8 @@ const modelCallFailures: Record<output_limited: [502, "model_call_failed"],invalid_output: [502, "model_output_invalid"],invalid_request: [400, "invalid_model_call"],+ // A yielded attempt runs again, so a caller never receives it.+ yielded: [502, "model_call_failed"],failed: [502, "model_call_failed"],};diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts b/apps/node-services/src/agent/runner-gateway/local-computer-management.tsindex f0e10434..57b8b8ea 100644--- a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts+++ b/apps/node-services/src/agent/runner-gateway/local-computer-management.ts@@ -29,6 +29,9 @@ export const FIRST_PROTOCOL_2_COMPUTER_VERSION = "0.43.0";// older Computer rejects the unknown key and would never reach its// `target_release`, so it is welcomed without the field.export const FIRST_SERVICE_FEATURES_COMPUTER_VERSION = "0.52.0";+// The first release that decodes a cancel for one model_invoke. An older+// Computer closes the connection on it, so its calls are never swapped out.+export const FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION = "0.53.0";const COMPUTER_RELEASE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;diff --git a/apps/node-services/src/agent/runner-gateway/runner-connections.ts b/apps/node-services/src/agent/runner-gateway/runner-connections.tsindex ea951344..14ff367a 100644--- a/apps/node-services/src/agent/runner-gateway/runner-connections.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-connections.ts@@ -24,6 +24,7 @@ import {LocalComputerPlacementError,LocalRuntimeAdmissionUnavailableError,MINIMUM_CURRENT_COMPUTER_VERSION,+ FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION,FIRST_SERVICE_FEATURES_COMPUTER_VERSION,type LocalPlacementRequirement,type LocalReasoningEffort,@@ -783,6 +784,22 @@ export class RunnerConnections {);}+ /** Whether the Computer on this connection can stop one model invocation. */+ supportsModelInvokeCancel(+ runnerId: string,+ connectionEpoch: number,+ ): boolean {+ const connection = this.#connections.get(runnerId);+ return (+ isServingConnection(connection) &&+ connection.connectionEpoch === connectionEpoch &&+ isComputerVersionAtLeast(+ connection.hello.daemon_version,+ FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION,+ )+ );+ }+/** Whether the Computer can run a model invocation on this Runtime now. */supportsModelInvoke(runnerId: string,diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.tsindex c8bea5cd..d50771cf 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts@@ -180,7 +180,11 @@ export class RunnerGatewaythis.runtimeModels(endpoint.computerId, endpoint.runtimeType),),Date.now,- (endpoint, priority) => this.#operations.yieldFor(endpoint, priority),+ // A background model call is below every Run, so it is swapped out first.+ (endpoint, priority) => {+ if (!this.#modelInvocation.yieldCall(endpoint, priority))+ this.#operations.yieldFor(endpoint, priority);+ },);this.#computerTools = new RunnerComputerTools(context, owners);this.#localModels = new RunnerLocalModels(context, owners);diff --git a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.tsindex 564968f9..e2d63f58 100644--- a/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-model-invocation.ts@@ -1,4 +1,8 @@-import type { ModelLease } from "../../model-tasks.js";+import {+ isModelCallKind,+ modelCallPolicies,+ type ModelLease,+} from "../../model-tasks.js";import type {ModelInvoke,ModelInvoked,@@ -10,7 +14,7 @@ import {} from "@linger/wire-contracts/runner-gateway/validator";import { LocalComputerOfflineError } from "./local-computer-management.js";import type { ModelSignal } from "./adaptive-limit.js";-import type { ModelWork } from "./model-queue.js";+import type { ModelEndpoint, ModelWork } from "./model-queue.js";import type {RunnerGatewayContext,RunnerGatewayControllers,@@ -71,11 +75,28 @@ export class RunnerModelInvokeUnavailableError extends RunnerGatewayError {}}+/**+ * A background call swapped out for interactive work. The Computer stopped it+ * and freed its place; the same attempt runs again once admitted.+ */+export class RunnerModelInvokeYieldedError extends RunnerGatewayError {+ constructor() {+ super("The model invocation yielded its place to interactive work");+ this.name = "RunnerModelInvokeYieldedError";+ }+}+interface InFlightCall {readonly runnerId: string;+ readonly connectionEpoch: number;readonly runtimeType: ModelInvoke["runtime_type"];+ readonly priority: number;+ /** Background work nobody waits on, which may be swapped out. */+ readonly yieldable: boolean;readonly lease: Pick<ModelLease, "release">;readonly timer: NodeJS.Timeout;+ /** A cancel to swap it out was sent; its reply frees the place. */+ yielding: boolean;waiter?: {readonly signal: AbortSignal;readonly onAbort: () => void;@@ -167,6 +188,48 @@ export class RunnerModelInvocation {this.#finish(envelope.invoke_id, { outcome });}+ /**+ * Swaps out the lowest-priority background call below priority on endpoint:+ * the Computer stops it, and its reply frees the place for the waiting work.+ * One at a time. Returns whether a swap is under way.+ */+ yieldCall(endpoint: ModelEndpoint, priority: number): boolean {+ const calls = [...this.#inFlight].filter(+ ([, call]) =>+ call.runnerId === endpoint.computerId &&+ call.runtimeType === endpoint.runtimeType,+ );+ if (calls.some(([, call]) => call.yielding)) return true;+ const connections = this.owners.connections();+ const lowest = calls+ .filter(+ ([, call]) =>+ call.yieldable &&+ call.priority > priority &&+ connections.supportsModelInvokeCancel(+ call.runnerId,+ call.connectionEpoch,+ ),+ )+ .sort(([, a], [, b]) => b.priority - a.priority)[0];+ if (!lowest) return false;+ const [invokeId, call] = lowest;+ call.yielding = true;+ const command = parseAgentToDaemonEnvelope({+ type: "cancel",+ target: "model_invoke",+ protocol_version: RUNNER_GATEWAY_PROTOCOL_VERSION,+ command_id: this.context.createId(),+ invoke_id: invokeId,+ runner_id: call.runnerId,+ connection_epoch: call.connectionEpoch,+ reason: "scheduler_yield",+ });+ // A lost connection stops every call on it and rejects its waiters.+ connections.sendToCurrentRunner(command).catch(() => undefined);+ return true;+ }+rejectWaitersForComputer(runnerId: string): void {for (const [invokeId, call] of this.#inFlight) {if (call.runnerId !== runnerId) continue;@@ -259,15 +322,26 @@ export class RunnerModelInvocation {call.waiter = undefined;reject(signal.reason ?? new Error("Model invocation was abandoned"));};+ const { kind, priority } = request.queue;this.#inFlight.set(command.invoke_id, {runnerId: command.runner_id,+ connectionEpoch: command.connection_epoch,runtimeType: command.runtime_type,+ priority,+ yieldable:+ isModelCallKind(kind) && !modelCallPolicies[kind].interactive,lease,timer,+ yielding: false,waiter: { signal, onAbort, resolve, reject },});signal.addEventListener("abort", onAbort, { once: true });if (signal.aborted) onAbort();+ // Interactive work may have queued while this call was being admitted.+ this.owners.queue().recheckInteractiveWait({+ computerId: command.runner_id,+ runtimeType: command.runtime_type,+ });});}@@ -302,7 +376,14 @@ export class RunnerModelInvocation {const waiter = call.waiter;if (!waiter) return;waiter.signal.removeEventListener("abort", waiter.onAbort);- if ("outcome" in result) waiter.resolve(result.outcome);+ // A call that finished before its cancel arrived keeps its answer.+ if (+ call.yielding &&+ "outcome" in result &&+ result.outcome.outcome === "canceled"+ )+ waiter.reject(new RunnerModelInvokeYieldedError());+ else if ("outcome" in result) waiter.resolve(result.outcome);else waiter.reject(result.error);}}diff --git a/apps/node-services/src/agent/runner-gateway/runtime-model-gateway.ts b/apps/node-services/src/agent/runner-gateway/runtime-model-gateway.tsindex cdbddd6a..3b5002c7 100644--- a/apps/node-services/src/agent/runner-gateway/runtime-model-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runtime-model-gateway.ts@@ -4,7 +4,10 @@ import {type RuntimeModelGateway,} from "../../runtime-model-call.js";import { LocalComputerOfflineError } from "./local-computer-management.js";-import { RunnerModelInvokeUnavailableError } from "./runner-model-invocation.js";+import {+ RunnerModelInvokeUnavailableError,+ RunnerModelInvokeYieldedError,+} from "./runner-model-invocation.js";/** The Runner Gateway's model invocation with its failures as ModelCallError,* so the host-level model call never depends on agent role modules. */@@ -46,6 +49,8 @@ function modelCallFailure(error: unknown): unknown {return new ModelCallError("runtime_unavailable", error.message, {cause: error,});+ if (error instanceof RunnerModelInvokeYieldedError)+ return new ModelCallError("yielded", error.message, { cause: error });if (error instanceof RangeError)return new ModelCallError("invalid_request", error.message, {cause: error,diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.tsindex e0f7f859..e4864986 100644--- a/apps/node-services/src/runtime-model-call.ts+++ b/apps/node-services/src/runtime-model-call.ts@@ -231,6 +231,9 @@ export type ModelCallErrorKind =/** Background work still queued or running when the caller stopped* waiting; the same request later joins it or receives its result. */| "pending"+ /** Swapped out for interactive work; the attempt runs again once admitted+ * and does not count as one. */+ | "yielded"| "failed";/** Shared by every offline ModelCallError, so a failure that only survives as@@ -770,6 +773,7 @@ async function invokeAttempt(| undefined;let lease: ModelLease | undefined;let stopBudget: (() => void) | undefined;+ let yielded = false;const timeoutMs = call.timeoutMs ?? policy.timeoutMs;try {if (entry.chain) lease = await entry.chain.acquire(call.key, signal);@@ -808,11 +812,12 @@ async function invokeAttempt(signal,});} catch (error) {+ yielded = error instanceof ModelCallError && error.kind === "yielded";callLog?.finished({kind: call.kind,key: call.key,attempt,- outcome: signal.aborted ? "abandoned" : "failed",+ outcome: signal.aborted ? "abandoned" : yielded ? "yielded" : "failed",durationMs: state.now() - startedAt,error: error instanceof Error ? error.message : String(error),});@@ -829,7 +834,9 @@ async function invokeAttempt(} finally {stopBudget?.();lease?.release({- outcome: outcome?.outcome ?? (signal.aborted ? "aborted" : "failed"),+ outcome:+ outcome?.outcome ??+ (signal.aborted ? "aborted" : yielded ? "yielded" : "failed"),...(outcome?.usage === undefined ? {} : { usage: outcome.usage }),});}@@ -935,6 +942,8 @@ async function executeCall(} catch (error) {if (signal.aborted) throw signal.reason;if (!(error instanceof ModelCallError)) throw error;+ // It queues again at once behind the work it yielded to.+ if (error.kind === "yielded") continue;if (!retryableKinds.has(error.kind) || attempt >= attempts) throw error;attempt += 1;await sleep(RETRY_DELAY_MS, signal);diff --git a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.tsindex 3ec7b77a..8c72d7ae 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-model-invocation-public.test.ts@@ -1,5 +1,6 @@import type {ModelInvoke,+ ModelInvokeCancel,ModelInvoked,OperationStart,RunnerHello,@@ -14,6 +15,7 @@ import type {RunnerModelInvokeRequest,} from "../../../src/agent/runner-gateway/runner-gateway.js";import { RunnerModelInvokeUnavailableError } from "../../../src/agent/runner-gateway/runner-gateway.js";+import { RunnerModelInvokeYieldedError } from "../../../src/agent/runner-gateway/runner-model-invocation.js";import {modelCallPolicies,type ModelCallKind,@@ -70,10 +72,16 @@ const sentInvocations = (peer: RecordingPeer): ModelInvoke[] =>envelope.type === "execute" && envelope.kind === "model_invoke",);+const sentCancels = (peer: RecordingPeer): ModelInvokeCancel[] =>+ peer.sent.filter(+ (envelope): envelope is ModelInvokeCancel =>+ envelope.type === "cancel" && envelope.target === "model_invoke",+ );+const invoked = (connection: RunnerGatewayConnection,command: Pick<ModelInvoke, "command_id" | "invoke_id">,- outcome: "completed" | "unavailable" = "completed",+ outcome: "completed" | "unavailable" | "canceled" = "completed",usage?: ModelInvoked["usage"],) =>connection.receive({@@ -215,8 +223,81 @@ describe("RunnerGateway model invocation", () => {}});- it("keeps recording work queued at hard one while a background call owns the endpoint", async () => {+ it("swaps out a background call holding the only place so recording work starts", async () => {+ const { gateway, peer, connection } = await connect();+ try {+ const memory = gateway.invokeModel(+ "runner-local",+ request({ input: "memory" }),+ );+ memory.catch(() => undefined);+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));+ const background = sentInvocations(peer)[0]!;+ const notes = gateway.invokeModel(+ "runner-local",+ request({ input: "notes", queue: queued("meeting_notes") }),+ );+ const ask = gateway.invokeModel(+ "runner-local",+ request({ input: "voice", queue: queued("voice_ask") }),+ );+ await vi.waitFor(() =>+ expect(sentCancels(peer)).toEqual([+ expect.objectContaining({+ invoke_id: background.invoke_id,+ connection_epoch: background.connection_epoch,+ reason: "scheduler_yield",+ }),+ ]),+ );+ // The place frees once the Computer answers that the call stopped.+ expect(sentInvocations(peer)).toHaveLength(1);+ await invoked(connection, background, "canceled");+ await expect(memory).rejects.toBeInstanceOf(+ RunnerModelInvokeYieldedError,+ );+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));+ expect(sentInvocations(peer)[1]!.input).toBe("notes");+ await invoked(connection, sentInvocations(peer)[1]!);+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(3));+ expect(sentInvocations(peer)[2]!.input).toBe("voice");+ await invoked(connection, sentInvocations(peer)[2]!);+ await Promise.all([notes, ask]);+ // Recording work never swaps out other recording work.+ expect(sentCancels(peer)).toHaveLength(1);+ } finally {+ connection.disconnect();+ }+ });++ it("keeps the answer of a background call that finished before its cancel", async () => {const { gateway, peer, connection } = await connect();+ try {+ const memory = gateway.invokeModel(+ "runner-local",+ request({ input: "memory" }),+ );+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));+ const notes = gateway.invokeModel(+ "runner-local",+ request({ input: "notes", queue: queued("meeting_notes") }),+ );+ await vi.waitFor(() => expect(sentCancels(peer)).toHaveLength(1));+ await invoked(connection, sentInvocations(peer)[0]!);+ await expect(memory).resolves.toMatchObject({ outcome: "completed" });+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));+ await invoked(connection, sentInvocations(peer)[1]!);+ await notes;+ } finally {+ connection.disconnect();+ }+ });++ it("keeps recording work queued behind a background call a Computer before 0.53.0 cannot stop", async () => {+ const { gateway, peer, connection } = await connect({+ ...invokingHello(),+ daemon_version: "0.52.0",+ });try {const memory = gateway.invokeModel("runner-local",@@ -240,6 +321,7 @@ describe("RunnerGateway model invocation", () => {expect(sentInvocations(peer)[2]!.input).toBe("voice");await invoked(connection, sentInvocations(peer)[2]!);await Promise.all([memory, notes, ask]);+ expect(sentCancels(peer)).toEqual([]);} finally {connection.disconnect();}@@ -422,6 +504,62 @@ describe("RunnerGateway model invocation", () => {},);+ it("runs a swapped-out Wiki step again without spending one of its attempts", async () => {+ const { gateway, peer, connection } = await connect();+ const model = createRuntimeModelCall({+ gateway: runtimeModelGateway(gateway),+ placements: async () => [],+ });+ const target = sessionTarget();+ const wiki = model.chain(+ {+ kind: "wiki",+ key: "wiki:yield",+ placement: {+ tenantId: target.tenantId,+ ownerActorId: target.ownerActorId,+ agentId: target.agentId,+ computerId: target.runnerId,+ runtimeType: "codex",+ },+ },+ async (chain) =>+ (await chain.text({ step: "write", input: "page" })).output,+ );+ try {+ // More swaps than the kind's attempts: a swap is not a failed attempt.+ const swaps = modelCallPolicies.wiki.attempts + 1;+ for (let swap = 0; swap < swaps; swap += 1) {+ await vi.waitFor(() =>+ expect(sentInvocations(peer)).toHaveLength(2 * swap + 1),+ );+ const step = sentInvocations(peer)[2 * swap]!;+ expect(step.input).toBe("page");+ const ask = gateway.invokeModel(+ "runner-local",+ request({ input: `ask ${swap}`, queue: queued("voice_ask") }),+ );+ await vi.waitFor(() =>+ expect(sentCancels(peer)).toHaveLength(swap + 1),+ );+ await invoked(connection, step, "canceled");+ await vi.waitFor(() =>+ expect(sentInvocations(peer)).toHaveLength(2 * swap + 2),+ );+ await invoked(connection, sentInvocations(peer)[2 * swap + 1]!);+ await ask;+ }+ await vi.waitFor(() =>+ expect(sentInvocations(peer)).toHaveLength(2 * swaps + 1),+ );+ await invoked(connection, sentInvocations(peer)[2 * swaps]!);+ await expect(wiki).resolves.toBe('{"summary":"ok"}');+ } finally {+ model.close();+ connection.disconnect();+ }+ });+it("holds the chain's place for a sent step after the caller stops waiting", async () => {const { gateway, peer, connection } = await connect();try {diff --git a/contracts/generated/go/runnergateway/wire.gen.go b/contracts/generated/go/runnergateway/wire.gen.goindex 603a5657..cce88750 100644--- a/contracts/generated/go/runnergateway/wire.gen.go+++ b/contracts/generated/go/runnergateway/wire.gen.go@@ -60,6 +60,7 @@ const (TargetProvider = "provider"KindSessionCompact = "session_compact"KindModelInvoke = "model_invoke"+ TargetModelInvoke = "model_invoke"KindComputerTool = "computer_tool"StateReady = "ready"StateRemoved = "removed"@@ -100,6 +101,7 @@ var AgentToDaemonMessages = []Message{{Name: "OperationStart", Type: "operation.start", Match: nil},{Name: "OperationInput", Type: "operation.input", Match: nil},{Name: "OperationCancel", Type: "cancel", Match: map[string]string{"target": "operation"}},+ {Name: "ModelInvokeCancel", Type: "cancel", Match: map[string]string{"target": "model_invoke"}},{Name: "OperationAck", Type: "operation.ack", Match: nil},{Name: "ComputerToolCall", Type: "execute", Match: map[string]string{"kind": "computer_tool"}},}@@ -2080,6 +2082,28 @@ func (OperationCancel) RequiredFields() []string {return []string{"protocol_version", "host_access", "execution_context_key", "runtime_instance_id", "context_view_ref", "tenant_id", "registration_id", "assignment_revision", "runner_id", "agent_id", "operation_id", "connection_epoch", "runner_revision", "generation", "execution_lease_id", "workspace_grant_id", "runtime_type", "type", "command_id", "reason", "target"}}+// ModelInvokeCancel mirrors the ModelInvokeCancel schema shape.+type ModelInvokeCancel struct {+ Type string `json:"type"`+ Target string `json:"target"`+ CommandID string `json:"command_id"`+ InvokeID string `json:"invoke_id"`+ ProtocolVersion string `json:"protocol_version"`+ RunnerID string `json:"runner_id"`+ ConnectionEpoch uint64 `json:"connection_epoch"`+ Reason string `json:"reason"`+}++// FixedFields lists the keys whose value the schema fixes for a ModelInvokeCancel.+func (ModelInvokeCancel) FixedFields() map[string]string {+ return map[string]string{"type": "cancel", "target": "model_invoke", "protocol_version": "2"}+}++// RequiredFields lists the keys a ModelInvokeCancel must carry.+func (ModelInvokeCancel) RequiredFields() []string {+ return []string{"type", "target", "command_id", "invoke_id", "protocol_version", "runner_id", "connection_epoch", "reason"}+}+// OperationAck mirrors the OperationAck schema shape.type OperationAck struct {ProtocolVersion string `json:"protocol_version"`diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.tsindex 5687ba3d..d3d2b8cc 100644--- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts+++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts@@ -69,6 +69,9 @@ export const runnerGatewayEnvelopeSchema = {{$ref: "#/$defs/OperationCancel",},+ {+ $ref: "#/$defs/ModelInvokeCancel",+ },{$ref: "#/$defs/OperationAck",},@@ -3946,6 +3949,48 @@ export const runnerGatewayEnvelopeSchema = {],unevaluatedProperties: false,},+ ModelInvokeCancel: {+ description:+ "Stops one model_invoke the Daemon is running. Its executed model_invoke follows as usual, canceled unless the call finished first; a cancel for a call that is not running does nothing. The Agent Service sends it only to a Computer release that decodes it.",+ type: "object",+ additionalProperties: false,+ required: [+ "type",+ "target",+ "command_id",+ "invoke_id",+ "protocol_version",+ "runner_id",+ "connection_epoch",+ "reason",+ ],+ properties: {+ type: {+ const: "cancel",+ },+ target: {+ const: "model_invoke",+ },+ command_id: {+ $ref: "#/$defs/Id",+ },+ invoke_id: {+ $ref: "#/$defs/Id",+ },+ protocol_version: {+ $ref: "#/$defs/ProtocolVersion",+ },+ runner_id: {+ $ref: "#/$defs/Id",+ },+ connection_epoch: {+ $ref: "#/$defs/PositiveInteger",+ },+ reason: {+ enum: ["scheduler_yield"],+ },+ },+ },OperationAck: {type: "object",allOf: [diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.tsindex 5946b51b..f8c2fb49 100644--- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts+++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts@@ -22,6 +22,7 @@ export type AgentToDaemonEnvelope =| OperationStart| OperationInput| OperationCancel+ | ModelInvokeCancel| OperationAck| ComputerToolCall;export type ProtocolVersion = "2";@@ -1055,6 +1056,19 @@ export interface LocalRunResources {*/mcp_servers: LocalMcpRelayDescriptor[];}+/**+ * Stops one model_invoke the Daemon is running. Its executed model_invoke follows as usual, canceled unless the call finished first; a cancel for a call that is not running does nothing. The Agent Service sends it only to a Computer release that decodes it.+ */+export interface ModelInvokeCancel {+ type: "cancel";+ target: "model_invoke";+ command_id: Id;+ invoke_id: Id;+ protocol_version: ProtocolVersion;+ runner_id: Id;+ connection_epoch: PositiveInteger;+ reason: "scheduler_yield";+}export interface ComputerToolCall {type: "execute";protocol_version: ProtocolVersion;diff --git a/contracts/runner-gateway/asyncapi.yaml b/contracts/runner-gateway/asyncapi.yamlindex c42ef72e..49787ebd 100644--- a/contracts/runner-gateway/asyncapi.yaml+++ b/contracts/runner-gateway/asyncapi.yaml@@ -19,7 +19,7 @@ info:operation reconciliation; runner.welcome alone is not readiness.Messages come in coarse families distinguished by one field: prepare andprepared (target operation or provider), cancel (target operation or- provider), execute and executed (kind session_compact, model_invoke,+ model_invoke), execute and executed (kind session_compact, model_invoke,computer_tool, skills_scan, browser_connect, computer_permission,local_models, debug_history orcli_credential), agent_runner.state (state ready, removed or failed) and@@ -46,6 +46,9 @@ info:decides when a call is sent; the Daemon runs every call it receives. Itsoptional session_key lets a Daemon answer the structured Codex calls ofone session in one resident thread; the result is the same either way.+ cancel with target model_invoke stops one running call so the scheduler+ can swap it out; the call's executed model_invoke still follows. The+ service sends it only to a Computer release that decodes it.execute with kindcomputer_tool runs native browser actions and retained Task output reads.TeamHub resolves the owner, Agent and Task scope; the Computer checks itsdiff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.jsonindex d724a7f3..59dfdbac 100644--- a/contracts/runner-gateway/envelope.schema.json+++ b/contracts/runner-gateway/envelope.schema.json@@ -68,6 +68,9 @@{"$ref": "#/$defs/OperationCancel"},+ {+ "$ref": "#/$defs/ModelInvokeCancel"+ },{"$ref": "#/$defs/OperationAck"},@@ -3901,6 +3904,47 @@],"unevaluatedProperties": false},+ "ModelInvokeCancel": {+ "description": "Stops one model_invoke the Daemon is running. Its executed model_invoke follows as usual, canceled unless the call finished first; a cancel for a call that is not running does nothing. The Agent Service sends it only to a Computer release that decodes it.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "type",+ "target",+ "command_id",+ "invoke_id",+ "protocol_version",+ "runner_id",+ "connection_epoch",+ "reason"+ ],+ "properties": {+ "type": {+ "const": "cancel"+ },+ "target": {+ "const": "model_invoke"+ },+ "command_id": {+ "$ref": "#/$defs/Id"+ },+ "invoke_id": {+ "$ref": "#/$defs/Id"+ },+ "protocol_version": {+ "$ref": "#/$defs/ProtocolVersion"+ },+ "runner_id": {+ "$ref": "#/$defs/Id"+ },+ "connection_epoch": {+ "$ref": "#/$defs/PositiveInteger"+ },+ "reason": {+ "enum": ["scheduler_yield"]+ }+ }+ },"OperationAck": {"type": "object","allOf": [diff --git a/docs/model-scheduling.md b/docs/model-scheduling.mdindex 0d33f2ee..776d295b 100644--- a/docs/model-scheduling.md+++ b/docs/model-scheduling.md@@ -39,31 +39,37 @@ for an interactive Run when that capacity exceeds one.| Compaction | An idle conversation's session compaction. New work for that conversation cancels it. || Background | Agent memory, user memory, profile, insights and wiki refresh, in descending priority. |-When work at chat priority or above is first in line and cannot start, it asks-the lowest-priority running Run below it on that endpoint or Computer to yield,-one Run at a time and at any limit. A recording question can swap out a chat,-and a chat can swap out a Task or a routine. A Run can yield once the Runtime-has a resumable native session. On Codex, the Run must also have produced-model output, its thinking included, or a tool event so that its original-input is in its history. A pending tool approval or human interaction is-answered before yielding. The waiting work starts after the Computer confirms-cleanup. A Run that finishes on its own while it is asked to yield completes-normally.+When work at chat priority or above is first in line and cannot start, it+swaps out the lowest-priority work below it on that endpoint, one unit at a+time and at any limit. A background model call goes first: the Computer stops+the call, the waiting work starts once the Computer confirms the stop, and+the call queues again at its priority to run the same attempt later, without+counting it as a failed try. A Computer before release 0.53.0 cannot stop one+call, so there the waiting work waits for it. Otherwise the work asks the+lowest-priority running Run below it on that endpoint or Computer to yield. A+recording question can swap out a chat, and a chat can swap out a Task or a+routine. A Run can yield once the Runtime has a resumable native session. On+Codex, the Run must also have produced model output, its thinking included,+or a tool event so that its original input is in its history. A pending tool+approval or human interaction is answered before yielding. The waiting work+starts after the Computer confirms cleanup. A Run that finishes on its own+while it is asked to yield completes normally.The yielded Run keeps its ID, running status and claim while it waits, andcontinues in the same session when admitted again. A user stop still ends it.If a yielded Run's cleanup cannot be confirmed, the Computer refuses furtherwork on that Runtime until it restarts. Other stops only report the unknown-cleanup. A model attempt already sent and a compaction are never interrupted,-so waiting work may still wait for one of them.+cleanup. A recording question, its notes, an approval and a compaction are+never interrupted, so waiting work may still wait for one of them.Each running Operation holds one place across its tool calls. Inputs mergedinto a queued Run take the highest priority among them. Eligible work at the same prioritystarts in arrival order.Wiki and Memory chains keep their steps in order on one endpoint. Each model-attempt releases its place when the Runtime answers. A waiting chat can start-before the next step, retry or correction, even at a hard limit of one. The-chain then continues with the results of its completed steps.+attempt releases its place when the Runtime answers or the step is swapped+out. A waiting chat can start before the next step, retry or correction, even+at a hard limit of one. The chain then continues with the results of its+completed steps.Time limits count running time. A model call's timeout starts when theRuntime starts the attempt, so waiting for a place, also while other work was