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): reserve interactive capacity and rank queued runs
LeoXing25ec9fb24166
diff --git a/apps/node-services/src/agent/executor/activation.ts b/apps/node-services/src/agent/executor/activation.tsindex ddae5e9f..c9fd2e1e 100644--- a/apps/node-services/src/agent/executor/activation.ts+++ b/apps/node-services/src/agent/executor/activation.ts@@ -1276,7 +1276,7 @@ class SynchronizedContextProvider implements AgentProvider {readonly #runGuards = new WeakMap<AgentRun, InterruptibleRun>();#steerTail: Promise<void> = Promise.resolve();- readonly acquireRunCapacity?: (signal: AbortSignal) => Promise<() => void>;+ readonly acquireRunCapacity?: AgentProvider["acquireRunCapacity"];constructor(provider: AgentProvider,diff --git a/apps/node-services/src/agent/executor/context-runtime-state.ts b/apps/node-services/src/agent/executor/context-runtime-state.tsindex d2bc840c..c124535e 100644--- a/apps/node-services/src/agent/executor/context-runtime-state.ts+++ b/apps/node-services/src/agent/executor/context-runtime-state.ts@@ -1,3 +1,5 @@+import { queuedMetaRunKind } from "./run-kind.js";+import type { RunKind } from "../../model-tasks.js";import { logAgentEvent } from "../observability/agent-log.js";import { acceptedNotificationInput } from "../prompt/accepted-notification.js";import {@@ -144,6 +146,7 @@ export interface ContextRuntimeStatePort {runId: string,outcome: "applied" | "uncertain",): RuntimeStateAwaitable<void>;+ queuedMetaKind?(signal: AbortSignal): Promise<RunKind>;hasQueuedRuns(): boolean;hasPendingWork(): boolean;/** Inputs accepted by this process that are not yet claimed or settled. */@@ -338,6 +341,7 @@ class TeamHubContextRuntimeState implements ContextRuntimeStatePort {// Resources the Runtime loaded for its next turn; they reach TeamHub with// the next Session checkpoint instead of a write of their own.#pendingResources: ExecutionResources | undefined;+ #queuedKind?: RunKind;#hasQueuedRuns = false;#hasPendingWork = false;#messageSteers: readonly MessageSteer[] = [];@@ -722,6 +726,12 @@ class TeamHubContextRuntimeState implements ContextRuntimeStatePort {await this.#refreshWorkState();}+ async queuedMetaKind(signal: AbortSignal): Promise<RunKind> {+ if (this.#queuedKind) return this.#queuedKind;+ const state = await this.#client.getWorkState(this.#contextKey, signal);+ return queuedMetaRunKind(state.next_run_origins ?? []);+ }+hasQueuedRuns(): boolean {return this.#hasQueuedRuns;}@@ -879,6 +889,9 @@ class TeamHubContextRuntimeState implements ContextRuntimeStatePort {// Queued work committed while this read was in flight stays visible; a// stale positive only costs one empty claim, which refreshes again.const queuedMeanwhile = mark !== this.#queuedWorkMark;+ this.#queuedKind = queuedMeanwhile+ ? undefined+ : queuedMetaRunKind(state.next_run_origins ?? []);this.#hasQueuedRuns = state.has_queued_runs || queuedMeanwhile;this.#hasPendingWork = state.has_pending_work || queuedMeanwhile;const steers = (state.message_steers ?? []).flatMap((input) =>@@ -919,6 +932,7 @@ class TeamHubContextRuntimeState implements ContextRuntimeStatePort {}#recordQueuedWork(): void {+ this.#queuedKind = undefined;this.#queuedWorkMark += 1;this.#hasQueuedRuns = true;this.#hasPendingWork = true;diff --git a/apps/node-services/src/agent/executor/provider.ts b/apps/node-services/src/agent/executor/provider.tsindex 9552f8cc..f31fcdf5 100644--- a/apps/node-services/src/agent/executor/provider.ts+++ b/apps/node-services/src/agent/executor/provider.ts@@ -1,4 +1,4 @@-import type { RunKind } from "../../model-tasks.js";+import type { RunKind, CapacityPriority } from "../../model-tasks.js";import type { RuntimeHistoryOptions, RuntimeHistoryPage } from "./history.js";export interface McpServerResource {@@ -342,7 +342,10 @@ export interface ProviderSessionOptions extends SessionSpec {export interface AgentProvider {/** Reserve execution capacity before claiming a durable Run. Always release. */- acquireRunCapacity?(signal: AbortSignal): Promise<() => void>;+ acquireRunCapacity?(+ signal: AbortSignal,+ priority?: CapacityPriority,+ ): Promise<() => void>;createSession(options: ProviderSessionOptions): Promise<RuntimeSession>;diff --git a/apps/node-services/src/agent/executor/run-kind.ts b/apps/node-services/src/agent/executor/run-kind.tsindex 44cc60d0..5c29e785 100644--- a/apps/node-services/src/agent/executor/run-kind.ts+++ b/apps/node-services/src/agent/executor/run-kind.ts@@ -1,27 +1,16 @@import { isRecord } from "@linger/service-kit";-import type { RunKind } from "../../model-tasks.js";+import { runPriorities, type RunKind } from "../../model-tasks.js";import type { ExecutionContextRef } from "./context-ref.js";+import type { RuntimeStateSchemas } from "./teamhub-runtime-state-client.js";import type { Message } from "./types.js";/** The fields of one queued Inbox Message that say what it is. */interface QueuedMessageOrigin {- readonly authorType?: "agent" | "user";+ readonly authorType?: string;readonly messageKind?: string;- readonly firedRoutine?: true;+ readonly firedRoutine?: boolean;}-/** Most likely waited on first. */-const byWaiting: readonly RunKind[] = [- "chat",- "document",- "agent_message",- "task_callback",- "task",- "follow_up",- "routine",- "proactive",-];-function messageRunKind(origin: QueuedMessageOrigin): RunKind {if (origin.messageKind === "agent_runtime")return origin.firedRoutine ? "routine" : "proactive";@@ -46,20 +35,36 @@ function inputRunKinds(message: Message): readonly RunKind[] {: ["chat"];}-/**- * What queued a Run, for its log; every Run has the same model queue- * priority. A Run that merges inputs of several kinds takes the one someone- * is most likely waiting on.- */+/** Classifies the compact TeamHub projection with the same policy used after claim. */+export function queuedMetaRunKind(+ origins: readonly RuntimeStateSchemas["AgentRunInputOrigin"][],+): RunKind {+ return highestKind(+ origins.map((origin) => {+ if (!origin.notification) return "follow_up";+ if (origin.task_inbox) return "task_callback";+ return messageRunKind({+ authorType: origin.author_type,+ messageKind: origin.message_kind,+ firedRoutine: origin.fired_routine,+ });+ }),+ );+}++function highestKind(kinds: readonly RunKind[]): RunKind {+ return kinds.length+ ? kinds.reduce((best, kind) =>+ runPriorities[kind] < runPriorities[best] ? kind : best,+ )+ : "follow_up";+}+export function runKind(ref: ExecutionContextRef | undefined,messages: readonly Message[],): RunKind {if (ref?.kind === "document") return "document";if (ref?.kind === "alter_ego") return "task";- return messages- .flatMap(inputRunKinds)- .reduce((best, kind) =>- byWaiting.indexOf(kind) < byWaiting.indexOf(best) ? kind : best,- );+ return highestKind(messages.flatMap(inputRunKinds));}diff --git a/apps/node-services/src/agent/executor/run-loop.ts b/apps/node-services/src/agent/executor/run-loop.tsindex 96f7902c..d3a29cbf 100644--- a/apps/node-services/src/agent/executor/run-loop.ts+++ b/apps/node-services/src/agent/executor/run-loop.ts@@ -41,6 +41,7 @@ import {renderInterruptedRunReminder,renderRuntimeContinuationReminder,} from "../prompt/inbox-notification.js";+import { runPriorities, COMPACTION_PRIORITY } from "../../model-tasks.js";import { runKind } from "./run-kind.js";/** The Run's own agent in `agent.model_request`; a sub-agent logs its id. */@@ -324,6 +325,7 @@ export class RunLoop {* happen; their next attempt is not a resumption. */readonly #unstartedRequeues = new Set<string>();#terminalRecoveryStop = new AbortController();+ #priorityWait?: AbortController;#capacityWait = new AbortController();#retiredPreparationFailure: { readonly error: unknown } | undefined;// Native session compaction; no Run is claimed until it settles.@@ -423,7 +425,10 @@ export class RunLoop {// returns before claiming anything.await this.#executionPromise?.catch(() => undefined);if (controller.signal.aborted) return { status: "input_arrived" };- releaseCapacity = await this.#provider.acquireRunCapacity?.(signal);+ releaseCapacity = await this.#provider.acquireRunCapacity?.(+ signal,+ COMPACTION_PRIORITY,+ );const result = await this.#provider.compactSession(this.#runtimeSession, {...(options.instructions ? { instructions: options.instructions } : {}),signal,@@ -517,6 +522,7 @@ export class RunLoop {notifyWorkAvailable(options: { readonly workStateAlreadyFresh?: boolean } = {},): void {+ this.#priorityWait?.abort();if (!options.workStateAlreadyFresh) this.#workStateRefreshRequested = true;this.#maintenance?.abort();this.#cancelLoopRetry();@@ -540,8 +546,10 @@ export class RunLoop {active.controller.abort(new LocalRunCancellationRequestedError());}}- if (status === "canceled" && !this.#state.hasQueuedRuns())- this.#capacityWait.abort();+ if (status === "canceled") {+ if (this.#state.hasQueuedRuns()) this.#priorityWait?.abort();+ else this.#capacityWait.abort();+ }this.#notifyActivityChanged();return status;}@@ -697,6 +705,7 @@ export class RunLoop {}async #runLoop(): Promise<void> {+ let queuedAt: number | undefined;while (!this.#drainRequested) {if (this.#workStateRefreshRequested) {this.#workStateRefreshRequested = false;@@ -724,9 +733,32 @@ export class RunLoop {!this.#retiredPreparationFailure &&this.#provider.acquireRunCapacity) {- releaseCapacity = await this.#provider.acquireRunCapacity(+ const refresh = new AbortController();+ this.#priorityWait = refresh;+ const signal = AbortSignal.any([this.#capacityWait.signal,- );+ refresh.signal,+ ]);+ try {+ queuedAt ??= performance.now();+ releaseCapacity = await this.#provider.acquireRunCapacity(signal, {+ queuedAt,+ resolve: async () => {+ const kind = this.#executionContextRef?.kind;+ if (kind === "document") return runPriorities.document;+ if (kind === "alter_ego") return runPriorities.task;+ const metaKind = await this.#state.queuedMetaKind?.(signal);+ return runPriorities[metaKind ?? "follow_up"];+ },+ });+ queuedAt = undefined;+ } catch (error) {+ if (refresh.signal.aborted && !this.#capacityWait.signal.aborted)+ continue;+ throw error;+ } finally {+ this.#priorityWait = undefined;+ }}} catch (error) {if (diff --git a/apps/node-services/src/agent/runner-gateway/model-queue.ts b/apps/node-services/src/agent/runner-gateway/model-queue.tsindex a74e2fed..69b9b175 100644--- a/apps/node-services/src/agent/runner-gateway/model-queue.ts+++ b/apps/node-services/src/agent/runner-gateway/model-queue.ts@@ -1,4 +1,8 @@-import { COMPACTION_PRIORITY } from "../../model-tasks.js";+import {+ admissionLimit,+ type ModelLease,+ type ModelLeaseResult,+} from "../../model-tasks.js";import { logAgentEvent } from "../observability/agent-log.js";import {AdaptiveLimit,@@ -19,23 +23,12 @@ export interface ModelEndpoint {export interface ModelWork {/** Lowest first; see model-tasks. */readonly priority: number;- /** What the work is: a call kind, a Run kind or compaction. Only logged. */+ /** A call kind, a Run kind or compaction. */readonly kind: string;/** Names the work in the log. */readonly key: string;}-export interface ModelLeaseResult {- readonly outcome: string;- /** Token usage as the Runtime reported it; only logged. */- readonly usage?: unknown;-}--export interface ModelLease {- /** Frees the place; later calls do nothing. */- release(result: ModelLeaseResult): void;-}-/** A Runtime whose every model is on the signed-in account. */const SUBSCRIPTION_CONCURRENCY: ConcurrencyRange = { initial: 10, max: 10 };/** A Runtime that reaches its models through an API link, or whose models@@ -57,14 +50,8 @@ export function endpointConcurrency(: API_CONCURRENCY;}-/** Work after compaction; it never takes an endpoint's last place. */-function isBackground(priority: number): boolean {- return priority > COMPACTION_PRIORITY;-}-interface Waiter {readonly priority: number;- readonly background: boolean;readonly seq: number;readonly signal: AbortSignal;readonly admit: () => void;@@ -76,17 +63,15 @@ interface EndpointState {readonly key: string;readonly endpoint: ModelEndpoint;active: number;- /** Running background units, also counted in active. */- background: number;readonly waiting: Waiter[];}/*** Admits model work per endpoint. A Run's Operation, a one-shot call, a- * chain and a compaction are each one unit. Units start lowest priority- * first, in arrival order within one priority, while the endpoint runs fewer- * than its limit; a running unit is never interrupted. Background work- * leaves the last place to Runs and compaction once the limit is above one.+ * chain and a compaction are each one unit. Smaller priority numbers start+ * first, in arrival order within a priority. Running units finish. When the+ * limit exceeds one, chat, voice asks and standalone approvals may fill the+ * last place.* The limit adapts to what finished requests report. Admission only; it* never picks, orders or retries a Run.*/@@ -163,7 +148,6 @@ export class ModelQueue {};const waiter: Waiter = {priority: work.priority,- background: isBackground(work.priority),seq: this.#seq++,signal,admit: () => {@@ -177,7 +161,7 @@ export class ModelQueue {signal.addEventListener("abort", onAbort, { once: true });this.#drain(state);});- return this.#lease(state, work, queuedAt, isBackground(work.priority));+ return this.#lease(state, work, queuedAt);}/** The Computer is gone; work waiting for it fails with error. */@@ -196,7 +180,7 @@ export class ModelQueue {const key = endpointKey(endpoint);let state = this.#endpoints.get(key);if (!state) {- state = { key, endpoint, active: 0, background: 0, waiting: [] };+ state = { key, endpoint, active: 0, waiting: [] };this.#endpoints.set(key, state);}return state;@@ -218,32 +202,44 @@ export class ModelQueue {}/** Admission already counted the unit as active. */- #lease(- state: EndpointState,- work: ModelWork,- queuedAt: number,- background: boolean,- ): ModelLease {+ #lease(state: EndpointState, work: ModelWork, queuedAt: number): ModelLease {const startedAt = Date.now();- let released = false;+ let result: ModelLeaseResult | undefined;+ let borrowers = 0;+ const finish = () => {+ if (!result || borrowers > 0) return;+ state.active -= 1;+ logAgentEvent("info", "model_queue.finished", {+ kind: work.kind,+ key: work.key.slice(0, 200),+ computer_id: state.endpoint.computerId,+ runtime_type: state.endpoint.runtimeType,+ outcome: result.outcome,+ queued_ms: startedAt - queuedAt,+ run_ms: Date.now() - startedAt,+ limit: this.#limits.get(state.key)?.value,+ ...(result.usage === undefined ? {} : { usage: result.usage }),+ });+ this.#drain(state);+ };return {- release: (result) => {- if (released) return;- released = true;- state.active -= 1;- if (background) state.background -= 1;- logAgentEvent("info", "model_queue.finished", {- kind: work.kind,- key: work.key.slice(0, 200),- computer_id: state.endpoint.computerId,- runtime_type: state.endpoint.runtimeType,- outcome: result.outcome,- queued_ms: startedAt - queuedAt,- run_ms: Date.now() - startedAt,- limit: this.#limits.get(state.key)?.value,- ...(result.usage === undefined ? {} : { usage: result.usage }),- });- this.#drain(state);+ borrow() {+ if (result) throw new Error("The model lease was released");+ borrowers++;+ let held = true;+ return {+ release() {+ if (!held) return;+ held = false;+ borrowers--;+ finish();+ },+ };+ },+ release(outcome) {+ if (result) return;+ result = outcome;+ finish();},};}@@ -253,12 +249,8 @@ export class ModelQueue {const limit = this.#limit(state.key, state.endpoint).value;while (state.active < limit && state.waiting.length > 0) {const next = state.waiting[0]!;- // Sorted foreground first, so every waiter after this one is- // background too.- if (next.background && limit > 1 && state.background >= limit - 1) break;- // Counted now, so the next waiter sees the place taken.+ if (state.active >= admissionLimit(limit, next.priority)) break;state.active += 1;- if (next.background) state.background += 1;state.waiting.shift();next.admit();}diff --git a/apps/node-services/src/agent/runner-gateway/remote-codex-provider.ts b/apps/node-services/src/agent/runner-gateway/remote-codex-provider.tsindex f65802d2..64bc67f7 100644--- a/apps/node-services/src/agent/runner-gateway/remote-codex-provider.ts+++ b/apps/node-services/src/agent/runner-gateway/remote-codex-provider.ts@@ -1,3 +1,4 @@+import { runPriorities, type CapacityPriority } from "../../model-tasks.js";import { displayText } from "@linger/service-kit";import {OPERATION_OUTCOME_UNKNOWN,@@ -156,11 +157,14 @@ export class RemoteRuntimeProvider implements AgentProvider {#capacityPermit?: RunnerCapacityPermit;readonly #closed = new AbortController();- async acquireRunCapacity(signal: AbortSignal): Promise<() => void> {+ async acquireRunCapacity(+ signal: AbortSignal,+ priority?: CapacityPriority,+ ): Promise<() => void> {let permit: RunnerCapacityPermit | undefined;try {permit = await this.#dispatcher.acquireOperationCapacity?.(- this.#target,+ { ...this.#target, priority },AbortSignal.any([signal, this.#closed.signal]),);} catch (error) {@@ -689,7 +693,10 @@ export class RemoteRuntimeProvider implements AgentProvider {}const permit =this.#capacityPermit ??- (await this.#dispatcher.acquireOperationCapacity?.(this.#target, signal));+ (await this.#dispatcher.acquireOperationCapacity?.(+ { ...this.#target, priority: runPriorities[runKind ?? "chat"] },+ signal,+ ));try {const operation = await this.#dispatcher.startOperation({...this.#target,diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.tsindex a2d47b43..5c6e0649 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts@@ -1,3 +1,4 @@+import type { ModelLease } from "../../model-tasks.js";import {RunnerComputerTools,type ComputerToolRequest,@@ -77,7 +78,6 @@ import {endpointConcurrency,ModelQueue,type ModelEndpoint,- type ModelLease,type ModelWork,} from "./model-queue.js";import {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 e98b915b..6394616a 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,3 +1,4 @@+import type { ModelLease } from "../../model-tasks.js";import type {ModelInvoke,ModelInvoked,@@ -9,7 +10,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 { ModelLease, ModelWork } from "./model-queue.js";+import type { ModelWork } from "./model-queue.js";import type {RunnerGatewayContext,RunnerGatewayControllers,@@ -43,9 +44,8 @@ export interface RunnerModelInvokeRequest {readonly sessionKey?: ModelInvoke["session_key"];readonly timeoutMs: number;readonly maxOutputChars?: ModelInvoke["max_output_chars"];- /** The call's place in its endpoint's queue; absent, it runs at once: a- * chain's call runs in its chain's place, and some kinds never queue. */- readonly queue?: ModelWork & {+ readonly chainLease?: ModelLease;+ readonly queue: ModelWork & {/** The Run Operation an approval reviews. While that Operation holds its* place on the same endpoint, the approval runs in it: the Run waits for* the verdict, so queuing behind it would never end. */@@ -74,7 +74,7 @@ export class RunnerModelInvokeUnavailableError extends RunnerGatewayError {interface InFlightCall {readonly runnerId: string;readonly runtimeType: ModelInvoke["runtime_type"];- readonly lease?: ModelLease;+ readonly lease: Pick<ModelLease, "release">;readonly timer: NodeJS.Timeout;waiter?: {readonly signal: AbortSignal;@@ -115,13 +115,19 @@ export class RunnerModelInvocation {this.#assertAvailable(computerId, request.runtimeType);const endpoint = { computerId, runtimeType: request.runtimeType };const { queue } = request;+ const borrowed =+ request.chainLease?.borrow() ??+ (queue.kind === "approval"+ ? this.owners+ .operations()+ .borrowModelPlace(queue.runOperationId, endpoint)+ : undefined);const lease =- !queue ||- this.owners.operations().holdsModelPlace(queue.runOperationId, endpoint)- ? undefined- : await this.owners.queue().acquire(endpoint, queue, request.signal);+ borrowed ??+ (await this.owners.queue().acquire(endpoint, queue, request.signal));let sent = false;try {+ request.signal.throwIfAborted();const connections = this.owners.connections();const connection = connections.getConnection(computerId);this.#assertAvailable(computerId, request.runtimeType);@@ -142,7 +148,7 @@ export class RunnerModelInvocation {}return await outcome;} finally {- if (!sent) lease?.release({ outcome: "not_sent" });+ if (!sent) lease.release({ outcome: "not_sent" });}}@@ -233,7 +239,7 @@ export class RunnerModelInvocation {#wait(command: ModelInvoke,request: RunnerModelInvokeRequest,- lease: ModelLease | undefined,+ lease: Pick<ModelLease, "release">,): Promise<RunnerModelInvokeOutcome> {return new Promise<RunnerModelInvokeOutcome>((resolve, reject) => {const { signal } = request;@@ -256,7 +262,7 @@ export class RunnerModelInvocation {this.#inFlight.set(command.invoke_id, {runnerId: command.runner_id,runtimeType: command.runtime_type,- ...(lease ? { lease } : {}),+ lease,timer,waiter: { signal, onAbort, resolve, reject },});@@ -286,7 +292,7 @@ export class RunnerModelInvocation {{ computerId: call.runnerId, runtimeType: call.runtimeType },signal,);- call.lease?.release(+ call.lease.release("outcome" in result? {outcome: result.outcome.outcome,diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.tsindex 8f9bec92..9c06e54f 100644--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts@@ -1,4 +1,4 @@-import type { RunKind } from "../../model-tasks.js";+import type { RunKind, CapacityPriority } from "../../model-tasks.js";import { EventEmitter, once } from "node:events";import { isDeepStrictEqual } from "node:util";@@ -39,7 +39,7 @@ import {interface RunnerOperationTargetBase {/** The Agent Service epoch whose Run this Operation executes. */readonly executionEpoch?: string;- /** What queued the Run; only logged. Absent, chat. */+ /** What queued the Run. Absent, chat. */readonly runKind?: RunKind;/** Stops the Run waiting for its turn in the model queue. */readonly signal?: AbortSignal;@@ -78,9 +78,10 @@ export interface RunnerOperation {export type RunnerCapacityTarget = Pick<RunnerOperationTarget,"runnerId" | "tenantId" | "agentId" | "executionContextKey"->;+> & { readonly priority?: CapacityPriority };export interface RunnerCapacityPermit {+ readonly reservedForChat?: boolean;readonly id: string;release(): void;}diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.tsindex 10f74581..fe85db7d 100644--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts@@ -1,3 +1,4 @@+import type { ModelLease } from "../../model-tasks.js";import type {DaemonToAgentEnvelope,OperationPrepare,@@ -6,13 +7,13 @@ import type {} from "@linger/wire-contracts/runner-gateway/types";import { isRecord } from "@linger/service-kit";import { isDeepStrictEqual } from "node:util";-import { RUN_PRIORITY } from "../../model-tasks.js";+import { admissionLimit, runPriorities, softLimit } from "../../model-tasks.js";import { logAgentEvent } from "../observability/agent-log.js";import {LocalComputerOfflineError,resolveOperationModel,} from "./local-computer-management.js";-import type { ModelEndpoint, ModelLease } from "./model-queue.js";+import type { ModelEndpoint } from "./model-queue.js";import { isServingConnection } from "./runner-connections.js";import type {CapacitySignal,@@ -104,7 +105,9 @@ export class RunnerOperations {}>();- readonly #capacityWaiters = new Set<RunnerCapacityTarget>();+ readonly #capacityWaiters = new Set<+ RunnerCapacityTarget & { rank?: number; queuedAt: number }+ >();#capacitySignal = capacitySignal();@@ -127,7 +130,13 @@ export class RunnerOperations {target: RunnerCapacityTarget,signal: AbortSignal,): Promise<RunnerCapacityPermit> {- const waiter = { ...target };+ const source = target.priority ?? runPriorities.chat;+ const waiter = {+ ...target,+ queuedAt:+ typeof source === "number" ? performance.now() : source.queuedAt,+ rank: typeof source === "number" ? source : undefined,+ };this.#capacityWaiters.add(waiter);try {for (;;) {@@ -165,23 +174,37 @@ export class RunnerOperations {candidate.tenantId === other.tenantId &&candidate.executionContextKey === other.executionContextKey,);- const busy = isBusy(target);- // FIFO among runnable waiters; a busy Context never blocks an unrelated one.- const earlierConflict = [...this.#capacityWaiters]- .slice(0, [...this.#capacityWaiters].indexOf(waiter))- .some(- (other) => other.runnerId === target.runnerId && !isBusy(other),- );+ const hard = connection.hello.capacity;+ const soft = hard === undefined ? Infinity : softLimit(hard);+ const peers = [...this.#capacityWaiters].filter(+ (other) => other.runnerId === target.runnerId && !isBusy(other),+ );+ if (+ hard !== undefined &&+ waiter.rank === undefined &&+ typeof source !== "number" &&+ (occupied.length >= soft || peers.length > 1)+ ) {+ waiter.rank = await source.resolve();+ this.wakeCapacityWaiters();+ continue;+ }+ const rank = waiter.rank ?? runPriorities.chat;+ // An unresolved contender may be interactive. Its lookup wakes every waiter.+ const first = peers.sort(+ (a, b) =>+ (a.rank ?? runPriorities.chat) - (b.rank ?? runPriorities.chat) ||+ a.queuedAt - b.queuedAt,+ )[0];if (- !busy &&- !earlierConflict &&- (connection.hello.capacity === undefined ||- active.length + reservations.length < connection.hello.capacity)+ first === waiter &&+ (hard === undefined || occupied.length < admissionLimit(hard, rank))) {const id = this.context.createId();this.#capacityReservations.set(id, { target, connection });return {id,+ reservedForChat: occupied.length >= soft && hard !== 1,release: () => {if (this.#capacityReservations.delete(id))this.wakeCapacityWaiters();@@ -201,12 +224,17 @@ export class RunnerOperations {target: RunnerOperationTarget,): Promise<RunnerOperation> {// Readiness is checked once, after any capacity wait.- const permit =- target.capacityPermit ??- (await this.acquireOperationCapacity(- target,- new AbortController().signal,- ));+ const priority = runPriorities[target.runKind ?? "chat"];+ let permit = target.capacityPermit;+ // The durable claim may select a different Run than the scheduling hint.+ if (permit?.reservedForChat && priority > runPriorities.chat) {+ permit.release();+ permit = undefined;+ }+ permit ??= await this.acquireOperationCapacity(+ { ...target, priority },+ target.signal ?? new AbortController().signal,+ );try {// The whole Run is one unit of its endpoint's model queue. It waits// holding its capacity, and readiness is checked after both waits.@@ -216,7 +244,7 @@ export class RunnerOperations {runtimeType: target.request.runtime.type,},{- priority: RUN_PRIORITY,+ priority,kind: target.runKind ?? "chat",key: target.request.run_context.execution_run_ref,},@@ -248,18 +276,16 @@ export class RunnerOperations {}}- /** Whether this Run Operation holds its model place on endpoint, which an- * approval of its actions borrows. */- holdsModelPlace(- operationId: string | undefined,- endpoint: ModelEndpoint,- ): boolean {- if (!operationId || !this.#leases.has(operationId)) return false;+ /** Pins the reviewed Operation's place until its approval has settled. */+ borrowModelPlace(operationId: string | undefined, endpoint: ModelEndpoint) {+ if (!operationId) return undefined;const operation = this.#operations.get(operationId);- return (+ if (operation?.start.runner_id === endpoint.computerId &&operation.start.runtime_type === endpoint.runtimeType- );+ )+ return this.#leases.get(operationId)?.borrow();+ return undefined;}/**diff --git a/apps/node-services/src/agent/runner-gateway/runner-session-compaction.ts b/apps/node-services/src/agent/runner-gateway/runner-session-compaction.tsindex 4bf92ff2..ebc2a625 100644--- a/apps/node-services/src/agent/runner-gateway/runner-session-compaction.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-session-compaction.ts@@ -1,3 +1,4 @@+import type { ModelLease } from "../../model-tasks.js";import type {SessionCompact,SessionCompacted,@@ -8,7 +9,6 @@ import {} from "@linger/wire-contracts/runner-gateway/validator";import { COMPACTION_PRIORITY } from "../../model-tasks.js";import { LocalComputerOfflineError } from "./local-computer-management.js";-import type { ModelLease } from "./model-queue.js";import type {RunnerGatewayContext,RunnerGatewayControllers,diff --git a/apps/node-services/src/model-tasks.ts b/apps/node-services/src/model-tasks.tsindex 60843944..cb2b0c71 100644--- a/apps/node-services/src/model-tasks.ts+++ b/apps/node-services/src/model-tasks.ts@@ -16,7 +16,7 @@ const modelCallKinds = [] as const;export type ModelCallKind = (typeof modelCallKinds)[number];-/** What queued a Run; only logged. */+/** What queued a Run. */export type RunKind =| "chat"| "agent_message"@@ -27,15 +27,51 @@ export type RunKind =| "follow_up"| "document";-/** Queue priorities, lowest first: an approval, then every Run alike, then- * compaction, then the background kinds. */-export const RUN_PRIORITY = 10;+/** Smaller priorities go first; chat and its dependencies may use the last place. */+export const runPriorities: Readonly<Record<RunKind, number>> = {+ chat: 10,+ task: 12,+ task_callback: 12,+ document: 12,+ agent_message: 12,+ routine: 15,+ proactive: 15,+ follow_up: 15,+};+export interface ModelLeaseResult {+ readonly outcome: string;+ /** Token usage as the Runtime reported it; only logged. */+ readonly usage?: unknown;+}++export interface ModelLease {+ /** A sent approval or chain step keeps the place until its Runtime reply. */+ borrow(): Pick<ModelLease, "release">;+ /** Frees the place once all borrowers finish. Later calls do nothing. */+ release(result: ModelLeaseResult): void;+}++/** A bounded Computer resolves an unknown Meta priority only when work contends. */+export type CapacityPriority =+ | number+ | {+ /** Monotonic arrival time retained across priority refreshes for this wait. */+ readonly queuedAt: number;+ resolve(): Promise<number>;+ };+export const COMPACTION_PRIORITY = 20;+export function softLimit(hard: number): number {+ return Math.max(1, hard - 1);+}++export function admissionLimit(hard: number, priority: number): number {+ return priority <= runPriorities.chat ? hard : softLimit(hard);+}+export interface ModelCallPolicy {- /** Whether the call waits its turn on its endpoint's queue. */- readonly queued: boolean;- /** Queued work starts lowest priority first, in arrival order within one. */+ /** Smaller numbers start first, in arrival order within one priority. */readonly priority: number;/** Someone waits on the answer: the call stops once nobody waits, and* over HTTP it never answers pending. */@@ -51,59 +87,48 @@ export const modelCallPolicies: Readonly<Record<ModelCallKind, ModelCallPolicy>> = {approval: {- queued: true,priority: 0,interactive: true,attempts: 1,timeoutMs: 15_000,},voice_ask: {- queued: false,- priority: 0,+ priority: runPriorities.chat,interactive: true,attempts: 1,timeoutMs: 45_000,},- // Quick notes right after a recording ends: the completion message waits- // on them, so they never queue, answer only when done, and get one short- // attempt.meeting_notes: {- queued: false,- priority: 0,+ priority: runPriorities.task,interactive: true,attempts: 1,timeoutMs: 20_000,},agent_memory: {- queued: true,priority: 30,interactive: false,attempts: 2,timeoutMs: 10 * 60_000,},memory: {- queued: true,priority: 40,interactive: false,attempts: 3,timeoutMs: 10 * 60_000,},profile: {- queued: true,priority: 50,interactive: false,attempts: 2,timeoutMs: 2 * 60_000,},insight: {- queued: true,priority: 60,interactive: false,attempts: 2,timeoutMs: 2 * 60_000,},wiki: {- queued: true,priority: 70,interactive: false,attempts: 2,diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.tsindex 6f269590..47856d72 100644--- a/apps/node-services/src/runtime-model-call.ts+++ b/apps/node-services/src/runtime-model-call.ts@@ -1,3 +1,4 @@+import type { ModelLease } from "./model-tasks.js";import { Ajv, type ValidateFunction } from "ajv";import { isRecord, sleep } from "@linger/service-kit";import { sha256Hex, type JsonLogger } from "@linger/service-kit/node";@@ -259,11 +260,6 @@ export function isComputerOffline(error: unknown): boolean {error.message.startsWith(COMPUTER_OFFLINE_MESSAGE);}-/** A queue place a chain holds on its endpoint until release. */-export interface ModelChainLease {- release(result: { readonly outcome: string; readonly usage?: unknown }): void;-}-/** A place in one endpoint's queue. */export interface ModelQueueWork {readonly priority: number;@@ -299,9 +295,8 @@ export interface RuntimeModelGateway {readonly sessionKey?: string;readonly timeoutMs: number;readonly maxOutputChars?: number;- /** Absent, the call runs at once: a chain's call runs in its chain's- * place, and some kinds never queue. */- readonly queue?: ModelQueueWork & { readonly runOperationId?: string };+ readonly chainLease?: ModelLease;+ readonly queue: ModelQueueWork & { readonly runOperationId?: string };readonly signal: AbortSignal;},): Promise<@@ -327,7 +322,7 @@ export interface RuntimeModelGateway {},work: ModelQueueWork,signal: AbortSignal,- ): Promise<ModelChainLease>;+ ): Promise<ModelLease>;}/** Placements of active Another Me Agents; with an owner, only that owner's. */@@ -417,7 +412,7 @@ interface Call extends CallRequest {interface Entry {readonly call: Call;/** A chain's call, which runs in its chain's place. */- readonly admitted: boolean;+ readonly chainLease?: ModelLease;readonly controller: AbortController;/** Token usage of each attempt, as the Runtime reported it. */readonly usage: unknown[];@@ -713,6 +708,11 @@ async function invokeAttempt(input,});let outcome: Awaited<ReturnType<RuntimeModelGateway["invokeModel"]>>;+ const timeoutMs = call.timeoutMs ?? policy.timeoutMs;+ const deadline = policy.interactive+ ? AbortSignal.timeout(timeoutMs)+ : undefined;+ const attemptSignal = deadline ? AbortSignal.any([signal, deadline]) : signal;try {outcome = await state.options.gateway.invokeModel(placement.computerId, {tenantId: placement.tenantId,@@ -730,23 +730,20 @@ async function invokeAttempt(...(call.sessionKey? { sessionKey: attemptSession(call.sessionKey, attempt) }: {}),- timeoutMs: call.timeoutMs ?? policy.timeoutMs,+ timeoutMs,...(call.maxOutputChars === undefined? {}: { maxOutputChars: call.maxOutputChars }),- ...(policy.queued && !entry.admitted- ? {- queue: {- priority: policy.priority,- kind: call.kind,- key: call.key,- ...(call.runOperationId- ? { runOperationId: call.runOperationId }- : {}),- },- }- : {}),- signal,+ queue: {+ priority: policy.priority,+ kind: call.kind,+ key: call.key,+ ...(call.kind === "approval" && call.runOperationId+ ? { runOperationId: call.runOperationId }+ : {}),+ },+ chainLease: entry.chainLease,+ signal: attemptSignal,});} catch (error) {callLog?.finished({@@ -758,6 +755,11 @@ async function invokeAttempt(error: error instanceof Error ? error.message : String(error),});if (signal.aborted) throw signal.reason;+ if (deadline?.aborted)+ throw new ModelCallError(+ "timed_out",+ "The model call did not finish in time",+ );if (error instanceof ModelCallError) {if (error.kind === "computer_offline" && key !== undefined)state.placementCache.delete(key);@@ -897,11 +899,11 @@ function settleCall(function startCall(state: ModelCallState,call: Call,- admitted: boolean,+ chainLease?: ModelLease,): Entry {const entry: Entry = {call,- admitted,+ chainLease,controller: new AbortController(),usage: [],result: Promise.resolve(undefined as never),@@ -930,7 +932,7 @@ async function requestCall(state: ModelCallState,call: CallRequest,signal: AbortSignal | undefined,- admitted = false,+ chainLease?: ModelLease,): Promise<{readonly settled: ModelCallAnswer;readonly usage: readonly unknown[];@@ -939,7 +941,7 @@ async function requestCall(signal?.throwIfAborted();const id = callId(call);const entry =- state.entries.get(id) ?? startCall(state, { ...call, id }, admitted);+ state.entries.get(id) ?? startCall(state, { ...call, id }, chainLease);entry.waiters += 1;try {const settled = await untilAborted(entry.result, [@@ -952,7 +954,7 @@ async function requestCall(if (entry.waiters === 0 &&state.entries.get(id) === entry &&- (entry.admitted || modelCallPolicies[entry.call.kind].interactive)+ (entry.chainLease || modelCallPolicies[entry.call.kind].interactive))entry.controller.abort(new ModelCallError("failed", "Nobody waits for the model call"),@@ -1042,7 +1044,7 @@ async function runModelChain<T>(signal.addEventListener("abort", abort, { once: true });}state.chains.add(controller);- let lease: ModelChainLease | undefined;+ let lease: ModelLease | undefined;let deadline: NodeJS.Timeout | undefined;let outcome = "failed";let calls = 0;@@ -1056,12 +1058,11 @@ async function runModelChain<T>();const { runtimeType } = resolveTarget(state.options.gateway, placement);const policy = modelCallPolicies[spec.kind];- if (policy.queued)- lease = await state.options.gateway.acquireModelChain(- { computerId: placement.computerId, runtimeType },- { priority: policy.priority, kind: spec.kind, key: spec.key },- controller.signal,- );+ lease = await state.options.gateway.acquireModelChain(+ { computerId: placement.computerId, runtimeType },+ { priority: policy.priority, kind: spec.kind, key: spec.key },+ controller.signal,+ );if (spec.timeoutMs !== undefined)deadline = setTimeout(() =>@@ -1086,7 +1087,7 @@ async function runModelChain<T>(state,call(`${spec.key}/${stepName}`),controller.signal,- true,+ lease,);calls += 1;if (settled.usage.length) usage.push(settled.usage);diff --git a/apps/node-services/tests/agent/executor/context-runtime-state.test.ts b/apps/node-services/tests/agent/executor/context-runtime-state.test.tsindex f45fb149..d36e3782 100644--- a/apps/node-services/tests/agent/executor/context-runtime-state.test.ts+++ b/apps/node-services/tests/agent/executor/context-runtime-state.test.ts@@ -434,6 +434,49 @@ describe("TeamHub Context Runtime state", () => {await state.close();});+ it("refreshes the queued Meta priority when a chat merges into a waiting routine", async () => {+ const routine = {+ notification: true,+ task_inbox: false,+ message_kind: "agent_runtime",+ author_type: "agent",+ fired_routine: true,+ };+ const origins = [routine];+ const getWorkState = vi.fn(async () => ({+ has_queued_runs: true,+ has_pending_work: true,+ next_run_origins: origins,+ }));+ const client = createTeamHubRuntimeStateClientFake({+ getWorkState,+ getContext: async () => context("suspended"),+ getSession: async () => ({ available: false }),+ });+ const state = await createTeamHubContextRuntimeState({+ client,+ ref: { kind: "meta", agentId: "agent-reviewer", roomId: "room-1" },+ configurationRevision: "1",+ providerKind: "codex",+ });+ const signal = new AbortController().signal;+ try {+ expect(await state.queuedMetaKind!(signal)).toBe("routine");+ expect(getWorkState).toHaveBeenCalledTimes(1);+ origins.push({+ ...routine,+ author_type: "user",+ message_kind: "conversation",+ fired_routine: false,+ });+ state.noteQueuedRun!();+ expect(await state.queuedMetaKind!(signal)).toBe("chat");+ expect(getWorkState).toHaveBeenCalledTimes(2);+ } finally {+ await state.close();+ }+ });+it("keeps a hinted queued Run while an older work-state read is in flight", async () => {let finishRead!: (value: {has_pending_work: boolean;diff --git a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts b/apps/node-services/tests/agent/runner-gateway/model-queue.test.tsindex b698bbc1..f1746242 100644--- a/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/model-queue.test.ts@@ -3,13 +3,13 @@ import {endpointConcurrency,ModelQueue,type ModelEndpoint,- type ModelLease,} from "../../../src/agent/runner-gateway/model-queue.js";import {COMPACTION_PRIORITY,modelCallPolicies,- RUN_PRIORITY,+ runPriorities,type ModelCallKind,+ type ModelLease,} from "../../../src/model-tasks.js";const codex: ModelEndpoint = {@@ -27,7 +27,11 @@ const call = (kind: ModelCallKind, key: string = kind) => ({kind,key,});-const run = (key = "run") => ({ priority: RUN_PRIORITY, kind: "chat", key });+const run = (key = "run") => ({+ priority: runPriorities.chat,+ kind: "chat",+ key,+});const compaction = {priority: COMPACTION_PRIORITY,kind: "compaction",@@ -170,6 +174,42 @@ describe("ModelQueue limit", () => {expect(await single.acquire(claude, call("wiki"), signal)).toBeDefined();});+ it("admits only interactive work above soft, including when chat occupies an ordinary place", async () => {+ const queue = new ModelQueue(() => fixed(3));+ const routine = await queue.acquire(+ codex,+ { kind: "routine", priority: runPriorities.routine, key: "r" },+ signal,+ );+ const chat = await queue.acquire(codex, run(), signal);+ const notes = track(queue.acquire(codex, call("meeting_notes"), signal));+ const doc = track(+ queue.acquire(+ codex,+ { kind: "document", priority: runPriorities.document, key: "d" },+ signal,+ ),+ );+ const ask = await queue.acquire(codex, call("voice_ask"), signal);+ const next = track(queue.acquire(codex, run(), signal));+ await flush();+ expect([notes.value, doc.value, next.value]).toEqual([+ undefined,+ undefined,+ undefined,+ ]);+ ask.release(done);+ await flush();+ expect(next.value).toBeDefined();+ chat.release(done);+ await flush();+ expect(notes.value).toBeUndefined();+ routine.release(done);+ await flush();+ expect(notes.value).toBeDefined();+ expect(doc.value).toBeUndefined();+ });+it("tries one more unit while work waits and requests stay as fast", async () => {const queue = new ModelQueue(() => ({ initial: 1, max: 3 }));await queue.acquire(codex, run("a"), 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 0ff03eed..296fe428 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@@ -22,6 +22,7 @@ import {acceptReadyConnection,hello,RecordingPeer,+ settlesWithin,sequenceIds,sessionTarget,} from "./runner-gateway-fixtures.js";@@ -211,23 +212,68 @@ describe("RunnerGateway model invocation", () => {}});- it("starts a call that never queues while queued work fills the endpoint", async () => {+ it("keeps voice queued at hard one while a background call owns the endpoint", async () => {const { gateway, peer, connection } = await connect();try {- const background = gateway.invokeModel(+ 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") }),+ );const ask = gateway.invokeModel("runner-local",- request({ input: "voice", queue: undefined }),+ request({ input: "voice", queue: queued("voice_ask") }),);+ expect(sentInvocations(peer)).toHaveLength(1);+ await invoked(connection, sentInvocations(peer)[0]!);await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));expect(sentInvocations(peer)[1]!.input).toBe("voice");- for (const command of sentInvocations(peer))- await invoked(connection, command);- await Promise.all([background, ask]);+ await invoked(connection, sentInvocations(peer)[1]!);+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(3));+ expect(sentInvocations(peer)[2]!.input).toBe("notes");+ await invoked(connection, sentInvocations(peer)[2]!);+ await Promise.all([memory, notes, ask]);+ } finally {+ 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 {+ const stop = new AbortController();+ const chain = await gateway.acquireModelChain(+ { computerId: "runner-local", runtimeType: "codex" },+ queued("wiki"),+ stop.signal,+ );+ const step = gateway.invokeModel(+ "runner-local",+ request({+ chainLease: chain,+ queue: queued("wiki"),+ signal: stop.signal,+ }),+ );+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));+ const observed = expect(step).rejects.toThrow("caller left");+ stop.abort(new Error("caller left"));+ await observed;+ chain.release({ outcome: "aborted" });+ const ask = gateway.invokeModel(+ "runner-local",+ request({ queue: queued("voice_ask") }),+ );+ expect(await settlesWithin(ask, 10)).toBe(false);+ expect(sentInvocations(peer)).toHaveLength(1);+ await invoked(connection, sentInvocations(peer)[0]!);+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));+ await invoked(connection, sentInvocations(peer)[1]!);+ await ask;} finally {connection.disconnect();}diff --git a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.tsindex 3270752d..d2ffa0f8 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts@@ -1,3 +1,4 @@+import { runPriorities } from "../../../src/model-tasks.js";import { describe, expect, it, vi } from "vitest";import type {AgentToDaemonEnvelope,@@ -203,6 +204,98 @@ describe("RunnerGateway", () => {next.release();});+ it.each([1, 2])(+ "prioritizes chat with a Computer capacity of %i",+ async (hard) => {+ const gateway = createTestRunnerGateway({ createId: sequenceIds() });+ const connection = await gateway.acceptConnection(+ authenticatedPrincipal(),+ hello([], hard),+ new RecordingPeer(),+ );+ const signal = new AbortController().signal;+ const acquire = (+ executionContextKey: string,+ priority: () => Promise<number>,+ ) =>+ gateway.acquireOperationCapacity(+ {+ ...runTarget(),+ executionContextKey,+ priority: { queuedAt: performance.now(), resolve: priority },+ },+ signal,+ );+ try {+ const classify = vi.fn(async () => runPriorities.routine);+ const first = await acquire("routine", classify);+ expect(classify).not.toHaveBeenCalled();+ const order: string[] = [];+ const doc = acquire(+ "document",+ async () => runPriorities.document,+ ).then((p) => {+ order.push("document");+ return p;+ });+ const chat = acquire(+ "interactive",+ async () => runPriorities.chat,+ ).then((p) => {+ order.push("chat");+ return p;+ });+ if (hard === 1) {+ expect(await settlesWithin(chat, 15)).toBe(false);+ first.release();+ }+ const interactive = await chat;+ expect(order).toEqual(["chat"]);+ interactive.release();+ first.release();+ (await doc).release();+ expect(order).toEqual(["chat", "document"]);+ } finally {+ connection.disconnect();+ }+ },+ );++ it("keeps the FIFO position of a waiting Run when its priority is refreshed", async () => {+ const gateway = createTestRunnerGateway({ createId: sequenceIds() });+ const connection = await gateway.acceptConnection(+ authenticatedPrincipal(),+ hello([], 1),+ new RecordingPeer(),+ );+ const stop = new AbortController();+ const refreshed = new AbortController();+ const acquire = (key: string, queuedAt: number, signal: AbortSignal) =>+ gateway.acquireOperationCapacity(+ {+ ...runTarget(),+ executionContextKey: key,+ priority: { queuedAt, resolve: async () => runPriorities.routine },+ },+ signal,+ );+ try {+ const active = await acquire("active", 0, stop.signal);+ const old = acquire("first", 1, refreshed.signal);+ const second = acquire("second", 2, stop.signal);+ const canceled = expect(old).rejects.toThrow();+ refreshed.abort();+ await canceled;+ const first = acquire("first", 1, stop.signal);+ active.release();+ (await first).release();+ (await second).release();+ } finally {+ stop.abort();+ connection.disconnect();+ }+ });+it("rejects a capacity reservation for an offline Computer instead of waiting", async () => {const gateway = createTestRunnerGateway({ createId: sequenceIds() });await expect(@@ -339,6 +432,61 @@ describe("RunnerGateway", () => {).resolves.toHaveLength(3);});+ it("starts a late chat when ordinary work has filled both soft limits", async () => {+ const gateway = createTestRunnerGateway({ createId: sequenceIds() });+ const peer = new RecordingPeer();+ const connection = await acceptReadyConnection(gateway, peer, {+ ...hello([], 2),+ runtime_diagnostics: runtimeDiagnostics({ link: "subscription" }),+ });+ const endpoint = {+ computerId: "runner-local",+ runtimeType: "codex" as const,+ };+ const stop = new AbortController();+ const wiki = (index: number) =>+ gateway.acquireModelChain(+ endpoint,+ { kind: "wiki", priority: 70, key: String(index) },+ stop.signal,+ );+ // Eight wiki chains and one routine occupy all nine ordinary endpoint places.+ const chains = await Promise.all(+ Array.from({ length: 8 }, (_, i) => wiki(i)),+ );+ const start = (runKind: "routine" | "document" | "chat") =>+ gateway.startOperation({+ ...sessionTarget(),+ ...readyContextScope(runKind),+ runKind,+ signal: stop.signal,+ });+ try {+ const routine = await start("routine");+ const document = start("document");+ const waitingWiki = wiki(8);+ const chat = await start("chat");+ expect(+ peer.sent+ .filter((command) => command.type === "operation.start")+ .map((command) => command.execution_context_key),+ ).toEqual(["context-routine", "context-chat"]);+ expect(await settlesWithin(waitingWiki, 10)).toBe(false);+ const canceled = Promise.all([+ expect(document).rejects.toThrow(),+ expect(waitingWiki).rejects.toThrow(),+ ]);+ stop.abort();+ await canceled;+ void routine.result.catch(() => undefined);+ void chat.result.catch(() => undefined);+ } finally {+ stop.abort();+ for (const chain of chains) chain.release({ outcome: "completed" });+ connection.disconnect();+ }+ });+it("queues a Run's whole Operation as one unit of its endpoint", async () => {const gateway = createTestRunnerGateway({heartbeatIntervalMs: 60_000,diff --git a/apps/node-services/tests/runtime-model-call.test.ts b/apps/node-services/tests/runtime-model-call.test.tsindex 56e83dff..1e623177 100644--- a/apps/node-services/tests/runtime-model-call.test.ts+++ b/apps/node-services/tests/runtime-model-call.test.ts@@ -1,3 +1,4 @@+import type { ModelLease } from "../src/model-tasks.js";import { afterEach, describe, expect, it, vi } from "vitest";import {COMPUTER_OFFLINE_MESSAGE,@@ -5,7 +6,6 @@ import {isComputerOffline,ModelCallError,type ModelPlacement,- type ModelChainLease,type RuntimeModelGateway,type RuntimeModelInfo,} from "../src/runtime-model-call.js";@@ -55,7 +55,7 @@ function setup(outcomes?: (Outcome | Error)[];/** Answers every invocation instead of the outcome list. */invoke?: Invoke;- lease?: ModelChainLease;+ lease?: ModelLease;callLog?: ModelCallLog;runtimeModels?: RuntimeModelGateway["runtimeModels"];} = {},@@ -71,7 +71,11 @@ function setup();const supportsModelInvoke = vi.fn(options.ready ?? (() => true));const acquireModelChain = vi.fn<RuntimeModelGateway["acquireModelChain"]>(- async () => options.lease ?? { release: () => {} },+ async () =>+ options.lease ?? {+ release: () => {},+ borrow: () => ({ release: () => {} }),+ },);const placements = vi.fn(async () => options.placements ?? [alice, bob]);let time = 0;@@ -156,14 +160,32 @@ describe("Runtime model call", () => {},}),);- // A voice ask never queues.+ // Voice uses the interactive reserve.await modelCall.text({kind: "voice_ask",key: "ask",owner: { tenantId: "tenant_1", ownerActorId: "bob" },input: "What did they say?",});- expect(invokeModel.mock.lastCall![1]).not.toHaveProperty("queue");+ expect(invokeModel.mock.lastCall![1].queue).toEqual({+ kind: "voice_ask",+ key: "ask",+ priority: 10,+ });+ });++ it("expires interactive work while waiting for model admission", async () => {+ const { modelCall, invokeModel } = setup({ invoke: hanging });+ await expect(+ modelCall.text({+ kind: "meeting_notes",+ key: "recording",+ owner: { tenantId: "tenant_1", ownerActorId: "alice" },+ input: "Notes",+ timeoutMs: 25,+ }),+ ).rejects.toMatchObject({ kind: "timed_out" });+ expect(invokeModel.mock.lastCall![1].signal.aborted).toBe(true);});it("runs a workspace call on a named Another Me and returns its files", async () => {@@ -596,7 +618,10 @@ describe("Model call executions", () => {describe("Model chains", () => {afterEach(() => vi.useRealTimers());const owner = { tenantId: "tenant_1", ownerActorId: "alice" };- const lease = () => ({ release: vi.fn() });+ const lease = () => ({+ release: vi.fn(),+ borrow: () => ({ release: vi.fn() }),+ });it("runs its calls in the one place it was admitted to", async () => {const chainLease = lease();@@ -632,11 +657,11 @@ describe("Model chains", () => {expect(invokeModel.mock.calls.map(([, request]) => [request.runtimeType,- request.queue,+ request.chainLease,]),).toEqual([- ["codex", undefined],- ["codex", undefined],+ ["codex", chainLease],+ ["codex", chainLease],]);expect(chainLease.release).toHaveBeenCalledWith({outcome: "completed",@@ -790,7 +815,7 @@ describe("Model chains", () => {expect(invokeModel).toHaveBeenCalledTimes(3);expect(invokeModel.mock.calls.every(- ([, request]) => request.queue === undefined,+ ([, request]) => request.chainLease !== undefined,),).toBe(true);});diff --git a/apps/teamhub/internal/agentruntimestate/steer.go b/apps/teamhub/internal/agentruntimestate/steer.goindex 5d22c4eb..2572f9b0 100644--- a/apps/teamhub/internal/agentruntimestate/steer.go+++ b/apps/teamhub/internal/agentruntimestate/steer.go@@ -229,14 +229,15 @@ func (s *Service) RedeliverUnconfirmedRunInputs(ctx context.Context, runID strin})}-func (s *Service) ContextHasQueuedRuns(ctx context.Context, contextKey string) (bool, error) {+// NextRunInputOrigins reads scheduling metadata without claiming the next Run.+func (s *Service) NextRunInputOrigins(ctx context.Context, contextKey string) ([]store.NextAgentRunInputOriginsRow, error) {if s == nil || s.pool == nil {- return false, ErrInvalid+ return nil, ErrInvalid}if _, err := DecodeContextKey(contextKey); err != nil {- return false, ErrInvalid+ return nil, ErrInvalid}- return store.New(s.pool).AgentRuntimeContextHasQueuedRun(ctx, contextKey)+ return store.New(s.pool).NextAgentRunInputOrigins(ctx, contextKey)}func enqueueSteerRows(diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go b/apps/teamhub/internal/app/contract_server_agent_runtime_state.goindex ae600ea2..edcb5837 100644--- a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go+++ b/apps/teamhub/internal/app/contract_server_agent_runtime_state.go@@ -415,7 +415,7 @@ func (a *App) getAgentRuntimeWorkState(c *gin.Context) {if a.writeAgentRuntimeStateError(c, "get Runtime pending work", err) {return}- queued, err := a.agentRuntimeState.ContextHasQueuedRuns(c.Request.Context(), params.ContextKey)+ rows, err := a.agentRuntimeState.NextRunInputOrigins(c.Request.Context(), params.ContextKey)if a.writeAgentRuntimeStateError(c, "get Runtime queued Runs", err) {return}@@ -427,8 +427,15 @@ func (a *App) getAgentRuntimeWorkState(c *gin.Context) {if a.writeAgentRuntimeStateProjectionError(c, "project Runtime Message steers", err) {return}+ origins := make([]teamhubinternal.AgentRunInputOrigin, 0, len(rows))+ for _, row := range rows {+ origins = append(origins, teamhubinternal.AgentRunInputOrigin{+ Notification: row.Notification, TaskInbox: row.TaskInbox, AuthorType: row.AuthorType,+ MessageKind: row.MessageKind, FiredRoutine: row.FiredRoutine,+ })+ }c.JSON(http.StatusOK, teamhubinternal.AgentRuntimeWorkState{- HasPendingWork: pending, HasQueuedRuns: queued, MessageSteers: &messageSteers,+ HasPendingWork: pending, HasQueuedRuns: len(origins) > 0, NextRunOrigins: &origins, MessageSteers: &messageSteers,})}diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.goindex fd814c2d..d34935d7 100644--- a/apps/teamhub/internal/store/agent_runtime_state.sql.go+++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go@@ -111,21 +111,6 @@ func (q *Queries) AgentRuntimeContextHasPendingWork(ctx context.Context, contextreturn column_1, err}-const agentRuntimeContextHasQueuedRun = `-- name: AgentRuntimeContextHasQueuedRun :one-SELECT EXISTS(- SELECT 1 FROM agent_local_runs run- WHERE run.context_key=$1::text AND run.status='queued'- AND agent_document_run_claimable(run.run_id,run.context_key)-)::boolean-`--func (q *Queries) AgentRuntimeContextHasQueuedRun(ctx context.Context, contextKey string) (bool, error) {- row := q.db.QueryRow(ctx, agentRuntimeContextHasQueuedRun, contextKey)- var column_1 bool- err := row.Scan(&column_1)- return column_1, err-}-const agentRuntimeDatabaseNow = `-- name: AgentRuntimeDatabaseNow :oneSELECT clock_timestamp()::timestamptz`@@ -3557,6 +3542,59 @@ func (q *Queries) NextAgentLocalRunSteerOrdinal(ctx context.Context, runID strinreturn column_1, err}+const nextAgentRunInputOrigins = `-- name: NextAgentRunInputOrigins :many+WITH next_run AS (+ SELECT run.run_id FROM agent_local_runs run+ WHERE run.context_key=$1::text AND run.status='queued'+ AND agent_document_run_claimable(run.run_id,run.context_key)+ ORDER BY run.created_at, run.run_id LIMIT 1+)+SELECT DISTINCT (input.payload ? 'acceptedNotification')::boolean AS notification,+ coalesce(input.payload->'acceptedNotification'->>'inboxId' LIKE 'taskmeta:%', false)::boolean AS task_inbox,+ coalesce(msg.value->>'authorType', '')::text AS author_type,+ coalesce(msg.value->>'messageKind', '')::text AS message_kind,+ coalesce(msg.value->>'firedRoutine' = 'true', false)::boolean AS fired_routine+FROM next_run+JOIN agent_local_run_inputs relation ON relation.run_id=next_run.run_id AND relation.relation='initial'+JOIN agent_runtime_inputs input ON input.context_key=relation.context_key AND input.input_id=relation.input_id+LEFT JOIN LATERAL jsonb_array_elements(input.payload->'acceptedNotification'->'messages') AS msg(value) ON true+`++type NextAgentRunInputOriginsRow struct {+ Notification bool `json:"notification"`+ TaskInbox bool `json:"task_inbox"`+ AuthorType string `json:"author_type"`+ MessageKind string `json:"message_kind"`+ FiredRoutine bool `json:"fired_routine"`+}++// Match claim order without locking the Run or returning message bodies.+func (q *Queries) NextAgentRunInputOrigins(ctx context.Context, contextKey string) ([]NextAgentRunInputOriginsRow, error) {+ rows, err := q.db.Query(ctx, nextAgentRunInputOrigins, contextKey)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []NextAgentRunInputOriginsRow{}+ for rows.Next() {+ var i NextAgentRunInputOriginsRow+ if err := rows.Scan(+ &i.Notification,+ &i.TaskInbox,+ &i.AuthorType,+ &i.MessageKind,+ &i.FiredRoutine,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const observeAgentRuntimeLocalComputer = `-- name: ObserveAgentRuntimeLocalComputer :oneUPDATE local_computersSET display_name=$1::text,diff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sqlindex 87fe86f5..773127b6 100644--- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql+++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql@@ -673,12 +673,23 @@ SELECT * FROM agent_local_runsWHERE context_key=sqlc.arg(context_key)::text AND status='running'LIMIT 1;--- name: AgentRuntimeContextHasQueuedRun :one-SELECT EXISTS(- SELECT 1 FROM agent_local_runs run+-- name: NextAgentRunInputOrigins :many+-- Match claim order without locking the Run or returning message bodies.+WITH next_run AS (+ SELECT run.run_id FROM agent_local_runs runWHERE run.context_key=sqlc.arg(context_key)::text AND run.status='queued'AND agent_document_run_claimable(run.run_id,run.context_key)-)::boolean;+ ORDER BY run.created_at, run.run_id LIMIT 1+)+SELECT DISTINCT (input.payload ? 'acceptedNotification')::boolean AS notification,+ coalesce(input.payload->'acceptedNotification'->>'inboxId' LIKE 'taskmeta:%', false)::boolean AS task_inbox,+ coalesce(msg.value->>'authorType', '')::text AS author_type,+ coalesce(msg.value->>'messageKind', '')::text AS message_kind,+ coalesce(msg.value->>'firedRoutine' = 'true', false)::boolean AS fired_routine+FROM next_run+JOIN agent_local_run_inputs relation ON relation.run_id=next_run.run_id AND relation.relation='initial'+JOIN agent_runtime_inputs input ON input.context_key=relation.context_key AND input.input_id=relation.input_id+LEFT JOIN LATERAL jsonb_array_elements(input.payload->'acceptedNotification'->'messages') AS msg(value) ON true;-- name: ClaimAgentLocalRun :oneUPDATE agent_local_runsdiff --git a/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go b/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.goindex 246e5cef..f44f8bc5 100644--- a/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go+++ b/apps/teamhub/internal/voicecaptureqa/voicecaptureqa.go@@ -178,8 +178,7 @@ type modelAnswerer struct {}// NewAnswerer answers through a foreground Agent Service model call on the-// owner's Agent Runtime, which starts at once; timeout bounds its single-// Runtime attempt.+// owner's Agent Runtime. The timeout covers queueing and the model attempt.func NewAnswerer(models *roomagent.ModelCallClient, timeout time.Duration) Answerer {return &modelAnswerer{models: models, timeout: timeout}}diff --git a/apps/teamhub/internal/voicequicknotes/voicequicknotes.go b/apps/teamhub/internal/voicequicknotes/voicequicknotes.goindex bef87daf..3a75850c 100644--- a/apps/teamhub/internal/voicequicknotes/voicequicknotes.go+++ b/apps/teamhub/internal/voicequicknotes/voicequicknotes.go@@ -51,8 +51,7 @@ type Writer interface {type modelWriter struct{ models *roomagent.ModelCallClient }-// NewWriter writes on the owner's Agent Runtime with a call that never-// queues.+// NewWriter writes on the owner's Agent Runtime at task priority.func NewWriter(models *roomagent.ModelCallClient) Writer { return modelWriter{models: models} }func (w modelWriter) Write(ctx context.Context, owner roomagent.ModelCallOwner, captureID, transcript string) (Notes, error) {diff --git a/apps/teamhub/tests/integration/agent_run_wake_test.go b/apps/teamhub/tests/integration/agent_run_wake_test.goindex 91d915ec..4990d956 100644--- a/apps/teamhub/tests/integration/agent_run_wake_test.go+++ b/apps/teamhub/tests/integration/agent_run_wake_test.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5""github.com/simplexai-labs/linger/apps/teamhub/internal/config""github.com/simplexai-labs/linger/apps/teamhub/internal/realtime"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store")// Database commits own wake visibility. A Message transaction queues its Run@@ -123,6 +124,19 @@ func TestAgentRunWakesFollowCommitsAndReconnect(t *testing.T) {if err := tx.Commit(t.Context()); err != nil {t.Fatal(err)}+ origins, err := store.New(env.pool).NextAgentRunInputOrigins(t.Context(), metaContextKey)+ if err != nil {+ t.Fatal(err)+ }+ sawChat := false+ for _, origin := range origins {+ if origin.Notification && !origin.TaskInbox && origin.AuthorType == "user" {+ sawChat = true+ }+ }+ if !sawChat {+ t.Fatalf("oldest queued Run lost the chat origin: %+v", origins)+ }// The Room Message queues a Run; the Task callback joins it or steers it.ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)defer cancel()diff --git a/apps/teamhub/tests/integration/room_document_agent_input_test.go b/apps/teamhub/tests/integration/room_document_agent_input_test.goindex 9b2dfbdb..b23d8f25 100644--- a/apps/teamhub/tests/integration/room_document_agent_input_test.go+++ b/apps/teamhub/tests/integration/room_document_agent_input_test.go@@ -120,10 +120,7 @@ func TestStandaloneDocumentCommentMentionStartsRun(t *testing.T) {t.Fatalf("saved standalone %s mention has no Run: %v", action, err)}queries := store.New(env.pool)- ready, err := queries.AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil || ready {- t.Fatalf("pending anchor ready=%t err=%v", ready, err)- }+ assertDocumentRunClaimable(t, queries, contextKey, false)attachDocumentAgentThread(t, env, alice, doc.ID, thread.ID, suffix)if scenario == "edit_existing_mention" {// The contract invalidates queued input when its source comment changes.@@ -140,10 +137,7 @@ func TestStandaloneDocumentCommentMentionStartsRun(t *testing.T) {return}waitForDocumentCommentRunQueued(t, env, runID, "active")- ready, err = queries.AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil || !ready {- t.Fatalf("attached standalone mention ready=%t err=%v", ready, err)- }+ assertDocumentRunClaimable(t, queries, contextKey, true)status, _, body = agentWorkItemRequest(t, env, http.MethodPost,"/internal/agents/"+acmeOfficialAgentManagementID+"/mcp-context/actions/resolve", teamHubInternalToken, "",map[string]any{"context": map[string]any{"kind": "document", "document_id": doc.ID}})@@ -233,13 +227,7 @@ func TestHumanDocumentCommentAgentMentionCreatesOneDocumentContextAcrossRooms(t}queries := store.New(env.pool)- dispatchable, err := queries.AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil {- t.Fatal(err)- }- if dispatchable {- t.Fatal("pending Comment anchor made its Local Run dispatchable")- }+ assertDocumentRunClaimable(t, queries, contextKey, false)if _, err := queries.ClaimAgentLocalRun(t.Context(), store.ClaimAgentLocalRunParams{Epoch: "document-epoch", ClaimID: "blocked-document-claim-" + suffix, ClaimConfigurationRevision: 1,RunID: localRunID, ContextKey: contextKey,@@ -258,10 +246,7 @@ func TestHumanDocumentCommentAgentMentionCreatesOneDocumentContextAcrossRooms(tcurrentSeq, currentHash := attachDocumentAgentThread(t, env, alice, document.ID, thread.ID, suffix)waitForDocumentCommentRunQueued(t, env, localRunID, "active")- dispatchable, err = queries.AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil || !dispatchable {- t.Fatalf("attached Comment Local Run dispatchable=%t err=%v", dispatchable, err)- }+ assertDocumentRunClaimable(t, queries, contextKey, true)status, _, body = agentWorkItemRequest(t, env, http.MethodPost,"/internal/agents/"+acmeOfficialAgentManagementID+"/mcp-context/actions/resolve",@@ -505,13 +490,7 @@ func TestResolvedDocumentCommentMentionNeverDispatchesAgent(t *testing.T) {waitForDocumentCommentRunFailed(t, env, runID)contextKey := documentCommentRunContextKey(t, env, runID)- dispatchable, err := store.New(env.pool).AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil {- t.Fatal(err)- }- if dispatchable {- t.Fatal("resolved Comment Thread made its Document Local Run dispatchable")- }+ assertDocumentRunClaimable(t, store.New(env.pool), contextKey, false)}func TestResolvedActiveDocumentCommentMentionFailsQueuedRun(t *testing.T) {@@ -557,13 +536,7 @@ func TestResolvedActiveDocumentCommentMentionFailsQueuedRun(t *testing.T) {waitForDocumentCommentRunFailed(t, env, runID)contextKey := documentCommentRunContextKey(t, env, runID)- dispatchable, err := store.New(env.pool).AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil {- t.Fatal(err)- }- if dispatchable {- t.Fatal("resolved active Comment Thread kept its Document Local Run dispatchable")- }+ assertDocumentRunClaimable(t, store.New(env.pool), contextKey, false)}func TestExpiredQueuedDocumentCommentRunFails(t *testing.T) {@@ -788,10 +761,7 @@ func TestRoomDocumentCommentMentionDispatchesAgentWithoutGrant(t *testing.T) {}attachDocumentAgentThread(t, env, alice, document.ID, thread.ID, "mention-attach-"+suffix)waitForDocumentCommentRunQueued(t, env, localRunID, "active")- dispatchable, err := store.New(env.pool).AgentRuntimeContextHasQueuedRun(t.Context(), contextKey)- if err != nil || !dispatchable {- t.Fatalf("mention Local Run dispatchable=%t err=%v", dispatchable, err)- }+ assertDocumentRunClaimable(t, store.New(env.pool), contextKey, true)var stateRevision int64if err := env.pool.QueryRow(t.Context(), `SELECT state_revision FROM agent_execution_contexts WHERE context_key=$1`, contextKey).Scan(&stateRevision); err != nil {@@ -1051,3 +1021,14 @@ func waitForDocumentCommentRunState(t *testing.T, env *testEnv, runID, wantRunSttime.Sleep(20 * time.Millisecond)}}++func assertDocumentRunClaimable(t *testing.T, queries *store.Queries, contextKey string, want bool) {+ t.Helper()+ origins, err := queries.NextAgentRunInputOrigins(t.Context(), contextKey)+ if err != nil {+ t.Fatal(err)+ }+ if got := len(origins) > 0; got != want {+ t.Fatalf("Document Run in %s claimable=%t, want %t", contextKey, got, want)+ }+}diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.goindex 2e3941eb..57cc494b 100644--- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go+++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go@@ -2043,7 +2043,7 @@ type MemoryRebuildStatusPhase string// ModelCallEffort Reasoning effort for the Runtime's default model; omitted, low.type ModelCallEffort string-// ModelCallKind What the call is for. It sets the call's place in the queue of the Runtime it runs on, where an approval goes first and Runs come next; voice_ask and meeting_notes never queue. approval, voice_ask and meeting_notes have someone waiting, so they stop once the request is gone and never answer pending.+// ModelCallKind An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.type ModelCallKind string// ModelCallRequest defines model for ModelCallRequest.@@ -2060,7 +2060,7 @@ type ModelCallRequest struct {// Key Names the work, for example profile:<generation_id>. A request with the same key and the same content joins the running execution or receives its cached result; the same key with other content is a new request.Key string `json:"key"`- // Kind What the call is for. It sets the call's place in the queue of the Runtime it runs on, where an approval goes first and Runs come next; voice_ask and meeting_notes never queue. approval, voice_ask and meeting_notes have someone waiting, so they stop once the request is gone and never answer pending.+ // Kind An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.Kind ModelCallKind `json:"kind"`// Output Asks for one JSON object; omitted, the answer is text.diff --git a/contracts/generated/go/teamhubinternal/openapi.gen.go b/contracts/generated/go/teamhubinternal/openapi.gen.goindex 39d6348d..297d3ea0 100644--- a/contracts/generated/go/teamhubinternal/openapi.gen.go+++ b/contracts/generated/go/teamhubinternal/openapi.gen.go@@ -2248,6 +2248,15 @@ type AgentRepresentedHumanRef struct {Memory *UserMemoryRevision `json:"memory,omitempty"`}+// AgentRunInputOrigin defines model for AgentRunInputOrigin.+type AgentRunInputOrigin struct {+ AuthorType string `json:"author_type"`+ FiredRoutine bool `json:"fired_routine"`+ MessageKind string `json:"message_kind"`+ Notification bool `json:"notification"`+ TaskInbox bool `json:"task_inbox"`+}+// AgentRuntimeAcceptedContextState The Context state the accepting transaction committed. The Agent Service applies it to its Context record instead of reading the Context again.type AgentRuntimeAcceptedContextState struct {NextInputSequence AgentRuntimeInt64 `json:"next_input_sequence"`@@ -2640,6 +2649,9 @@ type AgentRuntimeWorkState struct {// MessageSteers Present on the work-state read. Steers a Message transaction queued for this Context that the Agent Service has not settled, in input order: a targeted Message for the running Run that reads its Inbox, or a native question's answer assigned to the Run that asked it.MessageSteers *[]StoredAgentRuntimeInput `json:"message_steers,omitempty"`++ // NextRunOrigins Distinct scheduling metadata of the oldest claimable Run's initial inputs.+ NextRunOrigins *[]AgentRunInputOrigin `json:"next_run_origins,omitempty"`}// AgentRuntimeWorkingStatusChangedEvent defines model for AgentRuntimeWorkingStatusChangedEvent.diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.tsindex 33159fd4..70b620b1 100644--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts@@ -672,7 +672,7 @@ export interface components {*/ModelCallEffort: "low" | "medium" | "high";/**- * @description What the call is for. It sets the call's place in the queue of the Runtime it runs on, where an approval goes first and Runs come next; voice_ask and meeting_notes never queue. approval, voice_ask and meeting_notes have someone waiting, so they stop once the request is gone and never answer pending.+ * @description An approval borrows its Run's place on the same endpoint or queues first. Voice questions share chat priority and can use the reserved place. Meeting notes share task priority. All three calls stop waiting when their caller leaves and return a result or an error within their deadline.* @enum {string}*/ModelCallKind:diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.tsindex fc68a481..4d147fc9 100644--- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts@@ -2243,9 +2243,18 @@ export interface components {ClearAgentRuntimeSessionResult: {cleared: boolean;};+ AgentRunInputOrigin: {+ notification: boolean;+ task_inbox: boolean;+ author_type: string;+ message_kind: string;+ fired_routine: boolean;+ };AgentRuntimeWorkState: {has_queued_runs: boolean;has_pending_work: boolean;+ /** @description Distinct scheduling metadata of the oldest claimable Run's initial inputs. */+ next_run_origins?: components["schemas"]["AgentRunInputOrigin"][];/** @description Present on the work-state read. Steers a Message transaction queued for this Context that the Agent Service has not settled, in input order: a targeted Message for the running Run that reads its Inbox, or a native question's answer assigned to the Run that asked it. */message_steers?: components["schemas"]["StoredAgentRuntimeInput"][];};diff --git a/contracts/openapi/components/agent-runtime-state.yaml b/contracts/openapi/components/agent-runtime-state.yamlindex addc51ef..d35bb967 100644--- a/contracts/openapi/components/agent-runtime-state.yaml+++ b/contracts/openapi/components/agent-runtime-state.yaml@@ -971,6 +971,11 @@ components:type: booleanhas_pending_work:type: boolean+ next_run_origins:+ type: array+ description: Distinct scheduling metadata of the oldest claimable Run's initial inputs.+ items:+ $ref: "#/components/schemas/AgentRunInputOrigin"message_steers:type: arraymaxItems: 1024@@ -981,6 +986,17 @@ components:or a native question's answer assigned to the Run that asked it.items:$ref: "#/components/schemas/StoredAgentRuntimeInput"+ AgentRunInputOrigin:+ type: object+ additionalProperties: false+ required:+ [notification, task_inbox, author_type, message_kind, fired_routine]+ properties:+ notification: { type: boolean }+ task_inbox: { type: boolean }+ author_type: { type: string }+ message_kind: { type: string }+ fired_routine: { type: boolean }AgentRuntimeWaitingContexts:type: objectadditionalProperties: falsediff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yamlindex aaf8aa68..6e9466e4 100644--- a/contracts/openapi/node-services-internal/openapi.yaml+++ b/contracts/openapi/node-services-internal/openapi.yaml@@ -1423,10 +1423,10 @@ components:- ModelCallKindProfile- ModelCallKindInsightdescription: >-- What the call is for. It sets the call's place in the queue of the- Runtime it runs on, where an approval goes first and Runs come next;- voice_ask and meeting_notes never queue. approval, voice_ask and meeting_notes have someone waiting,- so they stop once the request is gone and never answer pending.+ An approval borrows its Run's place on the same endpoint or queues first.+ Voice questions share chat priority and can use the reserved place.+ Meeting notes share task priority. All three calls stop waiting when+ their caller leaves and return a result or an error within their deadline.ModelCallErrorCode:type: stringdescription: Stable error codes of POST /v1/model-calls.diff --git a/docs/model-scheduling.md b/docs/model-scheduling.mdindex d282eacb..153a1926 100644--- a/docs/model-scheduling.md+++ b/docs/model-scheduling.md@@ -22,18 +22,26 @@ minutes; if that retry is too slow as well, the wait doubles, up to half anhour. What it learns lasts until the service restarts or the runtime's modelschange.-Background work never takes the last place once there is more than one, so a-chat does not wait behind a wiki refresh.--| Work, highest priority first | Unit |-| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |-| Tool approval | One review. It runs in the place of the run it reviews, since that run waits for the verdict. |-| Agent run | A whole run, tool calls and waits for you included. Chats, tasks, routines and proactive runs share one priority. |-| Compaction | Shortening the context of a conversation that is not running. New work for that conversation cancels it. |-| Background | Agent memory, your memory, profile, insights, wiki refresh, in that order. A flow whose calls build on each other is one unit. |--Questions in a recording's Ask tab never queue. Within one priority, work-starts in the order it was asked.+The current adaptive limit is the hard limit. Ordinary work can start while+the total running count is below the soft limit, `max(1, hard - 1)`. Chat,+recording questions and standalone approvals can use the last place. At a+hard limit of one, the current unit finishes before the next starts. When+the limit drops, running units finish and new work respects the lower limit.+A Computer with an explicit Operation capacity also reserves its last place+for an interactive Run when that capacity exceeds one.++| Work in priority order | Unit |+| ---------------------------- | --------------------------------------------------------------------------------------------------- |+| Tool approval | The review borrows the reviewed Run's place on the same endpoint. A standalone review queues first. |+| Chat and recording questions | A chat Run or a question in a recording's Ask tab. |+| Tasks and documents | Tasks, task callbacks, agent messages, document Runs and recording notes share one priority. |+| Scheduled and proactive work | Routines, proactive Runs and automatic follow-ups share one priority. |+| 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. |++Each Run holds one place across its tool calls. Inputs merged into a queued+Run take the highest priority among them. Eligible work at the same priority+starts in arrival order.A wiki refresh is many units, not one: each routing pack, meeting, page batchand correction queues on its own, so other work can run between them.