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): admit each sequential model call by priority
LeoXing044a136cb328
diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.tsindex 5c6e0649..c2e7a376 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts@@ -407,8 +407,8 @@ export class RunnerGatewayreturn this.#modelInvocation.invokeModel(computerId, request);}- /** Admits a chain, which then holds its place on the endpoint until it ends. */- acquireModelChain(+ /** Reserves a place for one model call on this endpoint. */+ acquireModelCall(endpoint: ModelEndpoint,work: ModelWork,signal: AbortSignal,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 6394616a..564968f9 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@@ -44,7 +44,7 @@ export interface RunnerModelInvokeRequest {readonly sessionKey?: ModelInvoke["session_key"];readonly timeoutMs: number;readonly maxOutputChars?: ModelInvoke["max_output_chars"];- readonly chainLease?: ModelLease;+ readonly callLease?: 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@@ -116,7 +116,7 @@ export class RunnerModelInvocation {const endpoint = { computerId, runtimeType: request.runtimeType };const { queue } = request;const borrowed =- request.chainLease?.borrow() ??+ request.callLease?.borrow() ??(queue.kind === "approval"? this.owners.operations()@@ -281,8 +281,7 @@ export class RunnerModelInvocation {if (!call) return;this.#inFlight.delete(invokeId);clearTimeout(call.timer);- // Chain steps and approvals hold no lease of their own but still tell- // how fast the endpoint answers.+ // Each Runtime reply supplies a latency sample, including a borrowed approval.const signal ="outcome" in result ? modelSignal(result.outcome) : undefined;if (signal)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 adb0d4d7..cdbddd6a 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@@ -16,9 +16,9 @@ export function runtimeModelGateway(gateway.supportsModelInvoke(computerId, runtimeType),runtimeModels: (computerId, runtimeType) =>gateway.runtimeModels(computerId, runtimeType),- acquireModelChain: async (endpoint, work, signal) => {+ acquireModelCall: async (endpoint, work, signal) => {try {- return await gateway.acquireModelChain(endpoint, work, signal);+ return await gateway.acquireModelCall(endpoint, work, signal);} catch (error) {if (signal.aborted) throw error;throw modelCallFailure(error);diff --git a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts b/apps/node-services/src/llm-wiki/agent-wiki-backend.tsindex 23f985e0..59b4030c 100644--- a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts+++ b/apps/node-services/src/llm-wiki/agent-wiki-backend.ts@@ -243,8 +243,7 @@ export class AgentWikiBackend implements LlmWikiBackend {logGenerationStep("prepare_workspace", startedAt, {context_window: contextWindow,});- // Each routing pack, meeting, page batch and correction is its own- // queued chain, so other model work runs between them.+ // A chain keeps one batch's steps in order while each model attempt queues.const key = `wiki:${request.generationId ?? `manual_${runId.replaceAll("-", "")}`}`;const result = await generation.run((step, body) =>modelCall.chain(@@ -1518,8 +1517,8 @@ ${renderExcerpts(};}- /** Submits one chain per item at once, named by step; the queue decides- * how many run together. The first failure stops the rest. */+ /** Submits one chain per item, named by step. The endpoint schedules their+ * model calls. The first failure stops the rest. */async #each<T>(items: readonly T[],step: (item: T, index: number) => string,diff --git a/apps/node-services/src/memory-agent.ts b/apps/node-services/src/memory-agent.tsindex 3026883a..d51dd07b 100644--- a/apps/node-services/src/memory-agent.ts+++ b/apps/node-services/src/memory-agent.ts@@ -7,6 +7,7 @@ import { isRecord } from "@linger/service-kit";import { packageRoot } from "./paths.js";import {+ ModelCallStartDeadlineError,schemaProblem,type ModelCallEffort,type ModelChain,@@ -245,7 +246,11 @@ export async function runAgentTask(request: {actionsSchema,steps,index,- );+ ).catch((error: unknown) => {+ if (error instanceof ModelCallStartDeadlineError) return undefined;+ throw error;+ });+ if (output === undefined) break;const actions = parseActions(output, task);const calls: string[] = [];const results: AgentObservation[] = [];@@ -371,6 +376,9 @@ async function callStep(: undefined;},timeoutMs: request.task.timeoutMs,+ ...(request.deadline === undefined+ ? {}+ : { startBefore: request.deadline }),...(request.task.maxOutputChars === undefined? {}: { maxOutputChars: request.task.maxOutputChars }),diff --git a/apps/node-services/src/memory/README.md b/apps/node-services/src/memory/README.mdindex 0bbcf3df..6003fcbc 100644--- a/apps/node-services/src/memory/README.md+++ b/apps/node-services/src/memory/README.md@@ -181,8 +181,8 @@ Core configuration:windows of at most 3,000 characters, extracted with `apps/node-services/prompts/memory/facts/fact-extraction.md`(the Hindsight concise prompt) at low reasoning effort. Up to 16 windows form one batch, and each batch runs as oneModelCall chain of kind `memory`, keyed `memory.facts:<sha256 of the batch's sorted window hashes>` so a restart- asks the same key. The chain is queued once and holds its place in the queue; its calls run one at a time, each- corrected within the `memory` kind's attempts. An answer still invalid after them is split into two halves, and windows whose facts drift into another+ asks the same key. Its calls run in order. Each model attempt queues separately, so chat can start before the next+ step, retry or correction. An answer still invalid after them is split into two halves, and windows whose facts drift into anotherlanguage are extracted once more; both are steps of the same chain (`first`, `split-<n>`, `<step>-drift`). Eachsync keeps at most two batches on the queue at once. Backfill write transactions are short and share Memory's connection poolwith recall. Windows are recorded by content hash in `memory_index.session_fact_windows`, so only new or changeddiff --git a/apps/node-services/src/memory/llm.ts b/apps/node-services/src/memory/llm.tsindex cd3b91b4..5ad79de2 100644--- a/apps/node-services/src/memory/llm.ts+++ b/apps/node-services/src/memory/llm.ts@@ -94,9 +94,8 @@ export type MemoryModelChainRunner = <T>() => Promise<T>;/**- * Runs a Memory flow as one ModelCall chain: it is queued once and holds its- * place, and a call that fails past the kind's attempts throws for the flow- * to split or give up.+ * Runs Memory's ordered steps on one endpoint. Each attempt queues separately;+ * the flow can split or give up after a call exhausts its attempts.*/export function runMemoryModelChain<T>(spec: ModelChainSpec,diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.tsindex 47856d72..1264c109 100644--- a/apps/node-services/src/runtime-model-call.ts+++ b/apps/node-services/src/runtime-model-call.ts@@ -132,6 +132,8 @@ export interface WorkspaceModelCallRequest/** One step of a chain; its key is `<chain key>/<step>`. */export interface ModelChainTextRequest extends ModelPrompt {readonly step: string;+ /** A queued attempt may only start before this Unix timestamp in milliseconds. */+ readonly startBefore?: number;}export interface ModelChainCallRequest@@ -156,8 +158,8 @@ export interface ModelChainSpec extends ModelTarget {/*** Calls that each build on the one before, with the flow's own fallback- * logic, queued once as a whole. They run one at a time in the order they- * are made, each retried and corrected within the kind's attempts like a+ * logic. Each attempt queues on the same endpoint, one at a time in the+ * order the calls are made. Each call is retried and corrected like a* lone call; a ModelCallError past them is the flow's to handle.*/export interface ModelChain {@@ -190,7 +192,7 @@ export interface ModelCall {workspace(request: WorkspaceModelCallRequest,): Promise<ModelCallResult<readonly WorkspaceFile[]>>;- /** Runs body as one queued unit on the target's endpoint. */+ /** Runs the chain's ordered steps on the target's endpoint. */chain<T>(spec: ModelChainSpec,body: (chain: ModelChain) => Promise<T>,@@ -295,7 +297,7 @@ export interface RuntimeModelGateway {readonly sessionKey?: string;readonly timeoutMs: number;readonly maxOutputChars?: number;- readonly chainLease?: ModelLease;+ readonly callLease?: ModelLease;readonly queue: ModelQueueWork & { readonly runOperationId?: string };readonly signal: AbortSignal;},@@ -315,7 +317,7 @@ export interface RuntimeModelGateway {computerId: string,runtimeType: LocalRuntimeType,): readonly RuntimeModelInfo[] | undefined;- acquireModelChain(+ acquireModelCall(endpoint: {readonly computerId: string;readonly runtimeType: ModelInvoke["runtime_type"];@@ -389,6 +391,7 @@ interface CallRequest {readonly kind: ModelCallKind;readonly key: string;readonly target: ModelTarget;+ readonly startBefore?: number;readonly mode: "text" | "structured" | "workspace";readonly effort?: ModelCallEffort;readonly instructions?: string;@@ -408,14 +411,22 @@ interface Call extends CallRequest {readonly id: string;}+/** A chain starts its body after admission. Its first attempt takes that+ * place and each later attempt queues for its own. */+interface ChainAdmission {+ readonly runtimeType: ModelInvoke["runtime_type"];+ acquire(key: string, signal: AbortSignal): Promise<ModelLease>;+ releaseUnused(outcome: string): void;+}++/** A queued chain step missed its latest start time. An already sent call can finish. */+export class ModelCallStartDeadlineError extends Error {}+/** One execution of a call, shared by every caller asking the same. */interface Entry {readonly call: Call;- /** A chain's call, which runs in its chain's place. */- readonly chainLease?: ModelLease;+ readonly chain?: ChainAdmission;readonly controller: AbortController;- /** Token usage of each attempt, as the Runtime reported it. */- readonly usage: unknown[];result: Promise<ModelCallAnswer>;waiters: number;}@@ -458,6 +469,8 @@ function callId(call: CallRequest): string {call.input,call.schemaName ?? null,call.outputSchema ?? null,+ call.startBefore ?? null,+ call.sessionKey ?? null,(call.files ?? []).map((file) => [file.path,sha256Hex(file.content_base64),@@ -695,7 +708,9 @@ async function invokeAttempt(const { call } = entry;const signal = entry.controller.signal;const { placement, key } = await resolvePlacement(state, call.target, signal);- const { runtimeType } = resolveTarget(state.options.gateway, placement);+ const runtimeType =+ entry.chain?.runtimeType ??+ resolveTarget(state.options.gateway, placement).runtimeType;const policy = modelCallPolicies[call.kind];const startedAt = state.now();const callLog = state.options.callLog;@@ -707,13 +722,21 @@ async function invokeAttempt(...(call.instructions ? { instructions: call.instructions } : {}),input,});- let outcome: Awaited<ReturnType<RuntimeModelGateway["invokeModel"]>>;+ let outcome:+ | Awaited<ReturnType<RuntimeModelGateway["invokeModel"]>>+ | undefined;+ let lease: ModelLease | undefined;const timeoutMs = call.timeoutMs ?? policy.timeoutMs;const deadline = policy.interactive? AbortSignal.timeout(timeoutMs): undefined;const attemptSignal = deadline ? AbortSignal.any([signal, deadline]) : signal;try {+ if (entry.chain) lease = await entry.chain.acquire(call.key, attemptSignal);+ if (call.startBefore !== undefined && Date.now() >= call.startBefore)+ throw new ModelCallStartDeadlineError(+ "The model step missed its start deadline",+ );outcome = await state.options.gateway.invokeModel(placement.computerId, {tenantId: placement.tenantId,ownerActorId: placement.ownerActorId,@@ -742,7 +765,7 @@ async function invokeAttempt(? { runOperationId: call.runOperationId }: {}),},- chainLease: entry.chainLease,+ ...(lease ? { callLease: lease } : {}),signal: attemptSignal,});} catch (error) {@@ -760,6 +783,7 @@ async function invokeAttempt("timed_out","The model call did not finish in time",);+ if (error instanceof ModelCallStartDeadlineError) throw error;if (error instanceof ModelCallError) {if (error.kind === "computer_offline" && key !== undefined)state.placementCache.delete(key);@@ -768,8 +792,12 @@ async function invokeAttempt(throw new ModelCallError("failed", "Model invocation failed", {cause: error,});+ } finally {+ lease?.release({+ outcome: outcome?.outcome ?? (signal.aborted ? "aborted" : "failed"),+ ...(outcome?.usage === undefined ? {} : { usage: outcome.usage }),+ });}- if (outcome.usage !== undefined) entry.usage.push(outcome.usage);const failure = outcomeFailure(outcome);callLog?.finished({kind: call.kind,@@ -840,7 +868,10 @@ async function executeCall(): Promise<ModelCallAnswer> {const { call } = entry;const cached = state.results.get(call.id);- if (cached) return cached;+ if (cached) {+ entry.chain?.releaseUnused("cached");+ return cached;+ }const signal = entry.controller.signal;const { attempts } = modelCallPolicies[call.kind];let input = call.input;@@ -899,13 +930,12 @@ function settleCall(function startCall(state: ModelCallState,call: Call,- chainLease?: ModelLease,+ chain?: ChainAdmission,): Entry {const entry: Entry = {call,- chainLease,+ chain,controller: new AbortController(),- usage: [],result: Promise.resolve(undefined as never),waiters: 0,};@@ -932,29 +962,23 @@ async function requestCall(state: ModelCallState,call: CallRequest,signal: AbortSignal | undefined,- chainLease?: ModelLease,-): Promise<{- readonly settled: ModelCallAnswer;- readonly usage: readonly unknown[];-}> {+ chain?: ChainAdmission,+): Promise<ModelCallAnswer> {state.stopped.signal.throwIfAborted();signal?.throwIfAborted();const id = callId(call);- const entry =- state.entries.get(id) ?? startCall(state, { ...call, id }, chainLease);+ const existing = state.entries.get(id);+ if (existing) chain?.releaseUnused("joined");+ const entry = existing ?? startCall(state, { ...call, id }, chain);entry.waiters += 1;try {- const settled = await untilAborted(entry.result, [- signal,- state.stopped.signal,- ]);- return { settled, usage: entry.usage };+ return await untilAborted(entry.result, [signal, state.stopped.signal]);} finally {entry.waiters -= 1;if (entry.waiters === 0 &&state.entries.get(id) === entry &&- (entry.chainLease || modelCallPolicies[entry.call.kind].interactive)+ (entry.chain || modelCallPolicies[entry.call.kind].interactive))entry.controller.abort(new ModelCallError("failed", "Nobody waits for the model call"),@@ -967,6 +991,7 @@ function callRequest(ModelPrompt & {readonly kind: ModelCallKind;readonly runOperationId?: string;+ readonly startBefore?: number;},key: string,mode: CallRequest["mode"],@@ -982,6 +1007,9 @@ function callRequest(kind: request.kind,key,target: targetOf(request),+ ...(request.startBefore === undefined+ ? {}+ : { startBefore: request.startBefore }),mode,...(request.effort ? { effort: request.effort } : {}),...(request.instructions ? { instructions: request.instructions } : {}),@@ -1013,15 +1041,15 @@ function structuredCall(request: ModelCallRequest): CallRequest {}const answer = {- structured: ({ settled }: { readonly settled: ModelCallAnswer }) => ({+ structured: (settled: ModelCallAnswer) => ({output: settled.output as Record<string, unknown>,model: settled.model,}),- text: ({ settled }: { readonly settled: ModelCallAnswer }) => ({+ text: (settled: ModelCallAnswer) => ({output: settled.output as string,model: settled.model,}),- workspace: ({ settled }: { readonly settled: ModelCallAnswer }) => ({+ workspace: (settled: ModelCallAnswer) => ({output: decodeFiles(settled.output as readonly ModelInvokeFile[]),model: settled.model,}),@@ -1044,11 +1072,12 @@ async function runModelChain<T>(signal.addEventListener("abort", abort, { once: true });}state.chains.add(controller);- let lease: ModelLease | undefined;+ let initialPlace: ModelLease | undefined;let deadline: NodeJS.Timeout | undefined;- let outcome = "failed";- let calls = 0;- const usage: unknown[] = [];+ const releaseUnused = (outcome: string) => {+ initialPlace?.release({ outcome });+ initialPlace = undefined;+ };try {controller.signal.throwIfAborted();const { placement } = await resolvePlacement(@@ -1058,11 +1087,24 @@ async function runModelChain<T>();const { runtimeType } = resolveTarget(state.options.gateway, placement);const policy = modelCallPolicies[spec.kind];- lease = await state.options.gateway.acquireModelChain(- { computerId: placement.computerId, runtimeType },- { priority: policy.priority, kind: spec.kind, key: spec.key },- controller.signal,- );+ const acquire = (key: string, signal: AbortSignal) =>+ state.options.gateway.acquireModelCall(+ { computerId: placement.computerId, runtimeType },+ { priority: policy.priority, kind: spec.kind, key },+ signal,+ );+ initialPlace = await acquire(spec.key, controller.signal);+ controller.signal.throwIfAborted();+ const admission: ChainAdmission = {+ runtimeType,+ acquire(key, signal) {+ if (!initialPlace) return acquire(key, signal);+ const place = initialPlace;+ initialPlace = undefined;+ return Promise.resolve(place);+ },+ releaseUnused,+ };if (spec.timeoutMs !== undefined)deadline = setTimeout(() =>@@ -1074,29 +1116,24 @@ async function runModelChain<T>(),spec.timeoutMs,);- // Every call runs on the endpoint the chain was admitted to, in its- // place, one at a time in the order the body makes them.const inChain = {kind: spec.kind,placement: { ...placement, runtimeType },};let previous: Promise<unknown> = Promise.resolve();const step = (call: (key: string) => CallRequest, stepName: string) => {- const run = previous.then(async () => {- const settled = await requestCall(+ const run = previous.then(() =>+ requestCall(state,call(`${spec.key}/${stepName}`),controller.signal,- lease,- );- calls += 1;- if (settled.usage.length) usage.push(settled.usage);- return settled;- });+ admission,+ ),+ );previous = run.catch(() => undefined);return run;};- const result = await body({+ return await body({signal: controller.signal,call: async ({ step: name, ...call }) =>answer.structured(@@ -1123,20 +1160,12 @@ async function runModelChain<T>(),),});- outcome = "completed";- return result;- } catch (error) {- if (controller.signal.aborted) outcome = "aborted";- throw error;} finally {clearTimeout(deadline);for (const signal of signals) signal.removeEventListener("abort", abort);state.chains.delete(controller);controller.abort();- lease?.release({- outcome,- usage: { calls, ...(usage.length ? { per_call: usage } : {}) },- });+ releaseUnused("unused");}}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 296fe428..633fb153 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@@ -4,6 +4,8 @@ import type {OperationStart,RunnerHello,} from "@linger/wire-contracts/runner-gateway/types";+import { createRuntimeModelCall } from "../../../src/runtime-model-call.js";+import { runtimeModelGateway } from "../../../src/agent/runner-gateway/runtime-model-gateway.js";import { describe, expect, it, vi } from "vitest";import { LocalComputerOfflineError } from "../../../src/agent/runner-gateway/local-computer-management.js";import type {@@ -22,6 +24,7 @@ import {acceptReadyConnection,hello,RecordingPeer,+ event,settlesWithin,sequenceIds,sessionTarget,@@ -242,11 +245,107 @@ describe("RunnerGateway model invocation", () => {}});+ it.each(["next step", "schema correction"] as const)(+ "at one place a chat runs before the Wiki chain's %s",+ async (next) => {+ 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:interleave",+ placement: {+ tenantId: target.tenantId,+ ownerActorId: target.ownerActorId,+ agentId: target.agentId,+ computerId: target.runnerId,+ runtimeType: "codex",+ },+ },+ async (chain) => {+ if (next === "schema correction") {+ return (+ await chain.call({+ step: "write",+ input: "first",+ schemaName: "page",+ outputSchema: { type: "object", required: ["summary"] },+ })+ ).output;+ }+ const first = await chain.text({ step: "read", input: "first" });+ return (await chain.text({ step: "write", input: first.output }))+ .output;+ },+ );+ try {+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(1));+ const chat = gateway.startOperation({ ...target, runKind: "chat" });+ expect(await settlesWithin(chat, 10)).toBe(false);+ const first = sentInvocations(peer)[0]!;+ await connection.receive({+ type: "executed",+ kind: "model_invoke",+ command_id: first.command_id,+ invoke_id: first.invoke_id,+ runner_id: first.runner_id,+ outcome: "completed",+ text: next === "schema correction" ? "{}" : "first result",+ duration_ms: 900,+ });+ const operation = await chat;+ const start = peer.sent.find(+ (envelope): envelope is OperationStart =>+ envelope.type === "operation.start" &&+ envelope.operation_id === operation.operationId,+ )!;+ expect(start.request.run_context.execution_run_ref).toBe(+ target.request.run_context.execution_run_ref,+ );+ expect(sentInvocations(peer)).toHaveLength(1);+ await connection.receive(+ event(start, 1, {+ type: "operation.accepted",+ command_id: start.command_id,+ runner_pid: 100,+ }),+ );+ await connection.receive(+ event(start, 2, {+ type: "operation.completed",+ result: {+ type: "run",+ final_response: "done",+ session: { thread_id: "thread-chat" },+ },+ }),+ );+ await operation.result;+ await vi.waitFor(() => expect(sentInvocations(peer)).toHaveLength(2));+ const second = sentInvocations(peer)[1]!;+ expect(second.input).toContain(+ next === "schema correction" ? "Required Correction" : "first result",+ );+ await invoked(connection, second);+ await expect(wiki).resolves.toEqual(+ next === "schema correction" ? { summary: "ok" } : '{"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 {const stop = new AbortController();- const chain = await gateway.acquireModelChain(+ const chain = await gateway.acquireModelCall({ computerId: "runner-local", runtimeType: "codex" },queued("wiki"),stop.signal,@@ -254,7 +353,7 @@ describe("RunnerGateway model invocation", () => {const step = gateway.invokeModel("runner-local",request({- chainLease: chain,+ callLease: chain,queue: queued("wiki"),signal: stop.signal,}),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 d2ffa0f8..efd993fd 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@@ -445,7 +445,7 @@ describe("RunnerGateway", () => {};const stop = new AbortController();const wiki = (index: number) =>- gateway.acquireModelChain(+ gateway.acquireModelCall(endpoint,{ kind: "wiki", priority: 70, key: String(index) },stop.signal,@@ -499,7 +499,7 @@ describe("RunnerGateway", () => {});const codex = { computerId: "runner-local", runtimeType: "codex" as const };try {- const wiki = await gateway.acquireModelChain(+ const wiki = await gateway.acquireModelCall(codex,{ priority: 70, kind: "wiki", key: "wiki:test" },new AbortController().signal,@@ -515,7 +515,7 @@ describe("RunnerGateway", () => {expect(peer.sent.some((command) => command.type === "operation.start"),).toBe(false);- const memory = gateway.acquireModelChain(+ const memory = gateway.acquireModelCall(codex,{ priority: 40, kind: "memory", key: "memory:test" },new AbortController().signal,@@ -623,7 +623,7 @@ describe("RunnerGateway", () => {const { gateway, connection, start } = await startRun();try {const waiting = admittedLater(- gateway.acquireModelChain(+ gateway.acquireModelCall(codex,approval,new AbortController().signal,@@ -641,7 +641,7 @@ describe("RunnerGateway", () => {it("halves the limit when the Run fails rate limited", async () => {const { gateway, connection, start } = await startRun();try {- const alongside = gateway.acquireModelChain(+ const alongside = gateway.acquireModelCall(codex,approval,new AbortController().signal,@@ -662,7 +662,7 @@ describe("RunnerGateway", () => {);// Two places would admit it beside the running chain; one does not.const next = admittedLater(- gateway.acquireModelChain(+ gateway.acquireModelCall(codex,approval,new AbortController().signal,diff --git a/apps/node-services/tests/agent/runner-gateway/runner-session-compaction-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-session-compaction-public.test.tsindex 970765b7..ef4a00e3 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-session-compaction-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-session-compaction-public.test.ts@@ -145,12 +145,12 @@ describe("RunnerGateway session compaction", () => {const { gateway, peer, connection } = await connect();const codex = { computerId: "runner-local", runtimeType: "codex" as const };try {- const running = await gateway.acquireModelChain(+ const running = await gateway.acquireModelCall(codex,{ priority: 70, kind: "wiki", key: "wiki:test" },new AbortController().signal,);- const memory = gateway.acquireModelChain(+ const memory = gateway.acquireModelCall(codex,{ priority: 40, kind: "memory", key: "memory:test" },new AbortController().signal,@@ -181,7 +181,7 @@ describe("RunnerGateway session compaction", () => {it("answers no_process when the Computer disconnects while compaction waits", async () => {const { gateway, connection } = await connect();- const running = await gateway.acquireModelChain(+ const running = await gateway.acquireModelCall({ computerId: "runner-local", runtimeType: "codex" },{ priority: 70, kind: "wiki", key: "wiki:test" },new AbortController().signal,diff --git a/apps/node-services/tests/memory-agent.test.ts b/apps/node-services/tests/memory-agent.test.tsindex 45248469..445c0c24 100644--- a/apps/node-services/tests/memory-agent.test.ts+++ b/apps/node-services/tests/memory-agent.test.ts@@ -12,6 +12,7 @@ import {} from "../src/memory-agent.js";import {ModelCallError,+ ModelCallStartDeadlineError,type ModelChain,type ModelChainCallRequest,} from "../src/runtime-model-call.js";@@ -106,6 +107,41 @@ describe("agentInstructions", () => {});describe("runAgentTask", () => {+ it("keeps an accepted proposal when the next step misses admission before the deadline", async () => {+ const deadline = Date.now() + 60_000;+ const call = vi+ .fn<ModelChain["call"]>()+ .mockResolvedValueOnce({+ model: "test",+ output: {+ actions: [+ {+ tool: "propose",+ object: "note",+ target: "n1",+ payload: { text: "saved" },+ },+ ],+ },+ })+ .mockRejectedValueOnce(new ModelCallStartDeadlineError());+ const result = await runAgentTask({+ model: stubChain({ call }),+ task,+ input: "evidence",+ step: "write",+ environment: environment(),+ deadline,+ maxInputTokens: 20_000,+ });+ expect(call.mock.calls.map(([request]) => request.startBefore)).toEqual([+ deadline,+ deadline,+ ]);+ expect(result).toMatchObject({ finished: false, accepted: 1 });+ expect(result.steps).toHaveLength(1);+ });+it("runs reads before proposals, feeds the results back and stops at finish", async () => {const inputs: string[] = [];const steps: string[] = [];diff --git a/apps/node-services/tests/runtime-model-call.test.ts b/apps/node-services/tests/runtime-model-call.test.tsindex 1e623177..ec470320 100644--- a/apps/node-services/tests/runtime-model-call.test.ts+++ b/apps/node-services/tests/runtime-model-call.test.ts@@ -5,6 +5,7 @@ import {createRuntimeModelCall,isComputerOffline,ModelCallError,+ ModelCallStartDeadlineError,type ModelPlacement,type RuntimeModelGateway,type RuntimeModelInfo,@@ -70,7 +71,7 @@ function setup(}),);const supportsModelInvoke = vi.fn(options.ready ?? (() => true));- const acquireModelChain = vi.fn<RuntimeModelGateway["acquireModelChain"]>(+ const acquireModelCall = vi.fn<RuntimeModelGateway["acquireModelCall"]>(async () =>options.lease ?? {release: () => {},@@ -85,7 +86,7 @@ function setup(invokeModel,supportsModelInvoke,runtimeModels: options.runtimeModels ?? (() => []),- acquireModelChain,+ acquireModelCall,},placements,logger,@@ -96,7 +97,7 @@ function setup(modelCall,logger,invokeModel,- acquireModelChain,+ acquireModelCall,supportsModelInvoke,placements,advance: (ms: number) => {@@ -623,16 +624,18 @@ describe("Model chains", () => {borrow: () => ({ release: vi.fn() }),});- it("runs its calls in the one place it was admitted to", async () => {- const chainLease = lease();- const { modelCall, invokeModel, acquireModelChain } = setup({+ it("takes a new place for each call on the same Runtime", async () => {+ const first = lease();+ const second = lease();+ const { modelCall, invokeModel, acquireModelCall } = setup({placements: [alice],- lease: chainLease,+ lease: second,outcomes: [{ ...completed("one"), usage: { input_tokens: 3 } } as Outcome,completed('{"answer":"two"}'),],});+ acquireModelCall.mockResolvedValueOnce(first);const result = await modelCall.chain({ kind: "wiki", key: "wiki:refresh:1", owner },async (task) => [@@ -648,27 +651,144 @@ describe("Model chains", () => {],);expect(result).toEqual(["one", { answer: "two" }]);- expect(acquireModelChain).toHaveBeenCalledTimes(1);- expect(acquireModelChain).toHaveBeenCalledWith(- { computerId: "computer_alice", runtimeType: "codex" },- { priority: 70, kind: "wiki", key: "wiki:refresh:1" },- expect.any(AbortSignal),- );expect(- invokeModel.mock.calls.map(([, request]) => [- request.runtimeType,- request.chainLease,+ acquireModelCall.mock.calls.map(([endpoint, work]) => [+ endpoint.runtimeType,+ work.key,]),).toEqual([- ["codex", chainLease],- ["codex", chainLease],+ ["codex", "wiki:refresh:1"],+ ["codex", "wiki:refresh:1/b"],]);- expect(chainLease.release).toHaveBeenCalledWith({+ expect(+ invokeModel.mock.calls.map(([, request]) => request.callLease),+ ).toEqual([first, second]);+ expect(first.release).toHaveBeenCalledExactlyOnceWith({+ outcome: "completed",+ usage: { input_tokens: 3 },+ });+ expect(second.release).toHaveBeenCalledExactlyOnceWith({outcome: "completed",- usage: { calls: 2, per_call: [[{ input_tokens: 3 }]] },});});+ it("releases a joined chain's unused place and keeps the shared call alive for the other waiter", async () => {+ const first = lease();+ const joined = lease();+ const { modelCall, acquireModelCall, invokeModel } = setup({+ placements: [alice],+ invoke: hanging,+ });+ acquireModelCall.mockResolvedValueOnce(first).mockResolvedValueOnce(joined);+ const left = new AbortController();+ const right = new AbortController();+ const execute = (signal: AbortSignal) =>+ modelCall.chain(+ { kind: "wiki", key: "wiki:duplicate", owner, signal },+ (chain) => chain.text({ step: "a", input: "one" }),+ );+ const a = execute(left.signal);+ const b = execute(right.signal);+ await vi.waitFor(() =>+ expect(joined.release).toHaveBeenCalledExactlyOnceWith({+ outcome: "joined",+ }),+ );+ expect(invokeModel).toHaveBeenCalledTimes(1);+ left.abort(new Error("left"));+ await expect(a).rejects.toThrow("left");+ expect(invokeModel.mock.calls[0]![1].signal.aborted).toBe(false);+ right.abort(new Error("right"));+ await expect(b).rejects.toThrow("right");+ expect(invokeModel.mock.calls[0]![1].signal.aborted).toBe(true);+ });++ it("starts its deadline after initial admission and includes later queue waits", async () => {+ vi.useFakeTimers();+ const firstPlace = deferred<ModelLease>();+ const { modelCall, acquireModelCall, invokeModel } = setup({+ placements: [alice],+ outcomes: [completed("a")],+ });+ acquireModelCall+ .mockReturnValueOnce(firstPlace.promise)+ .mockImplementationOnce(+ (_endpoint, _work, signal) =>+ new Promise((_resolve, reject) =>+ signal.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ }),+ ),+ );+ const chain = modelCall.chain(+ { kind: "wiki", key: "wiki:timeout", owner, timeoutMs: 50 },+ async (model) => {+ await model.text({ step: "first", input: "a" });+ return model.text({ step: "second", input: "b" });+ },+ );+ const result = expect(chain).rejects.toMatchObject({ kind: "timed_out" });+ await vi.advanceTimersByTimeAsync(100);+ expect(invokeModel).not.toHaveBeenCalled();+ firstPlace.resolve(lease());+ await vi.advanceTimersByTimeAsync(49);+ expect(acquireModelCall).toHaveBeenCalledTimes(2);+ expect(invokeModel).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ await result;+ });++ it("skips a step whose latest start passed while waiting for its place", async () => {+ vi.useFakeTimers();+ const { modelCall, invokeModel, acquireModelCall } = setup({+ placements: [alice],+ outcomes: [completed("done")],+ });+ acquireModelCall+ .mockResolvedValueOnce(lease())+ .mockImplementationOnce(async () => {+ vi.setSystemTime(Date.now() + 2_000);+ return lease();+ });+ const result = modelCall.chain(+ { kind: "wiki", key: "wiki:deadline", owner },+ async (chain) => {+ await chain.text({ step: "first", input: "x" });+ return chain.text({+ step: "late",+ input: "y",+ startBefore: Date.now() + 1_000,+ });+ },+ );+ await expect(result).rejects.toBeInstanceOf(ModelCallStartDeadlineError);+ expect(invokeModel).toHaveBeenCalledTimes(1);+ });++ it("keeps its admitted Runtime when availability changes between steps", async () => {+ let codexReady = false;+ const { modelCall, invokeModel, acquireModelCall } = setup({+ placements: [alice],+ ready: (_computer, runtime) =>+ runtime === "codex" ? codexReady : !codexReady,+ outcomes: [completed("a"), completed("b")],+ });+ await modelCall.chain(+ { kind: "wiki", key: "wiki:pinned", owner },+ async (chain) => {+ await chain.text({ step: "first", input: "a" });+ codexReady = true;+ await chain.text({ step: "second", input: "b" });+ },+ );+ expect(+ acquireModelCall.mock.calls.map(([endpoint]) => endpoint.runtimeType),+ ).toEqual(["claude", "claude"]);+ expect(+ invokeModel.mock.calls.map(([, request]) => request.runtimeType),+ ).toEqual(["claude", "claude"]);+ });+it("runs its calls one at a time in the order they are made", async () => {const answers: ((outcome: Outcome) => void)[] = [];const { modelCall, invokeModel } = setup({@@ -795,10 +915,10 @@ describe("Model chains", () => {);});- it("retries a chain's call in its place within the kind's attempts, then hands the failure to the chain", async () => {+ it("queues each retry and hands the final failure to the chain", async () => {vi.useFakeTimers();const timedOut = { outcome: "timed_out", duration_ms: 0 } as const;- const { modelCall, invokeModel } = setup({+ const { modelCall, invokeModel, acquireModelCall } = setup({placements: [alice],outcomes: [timedOut, timedOut, timedOut],});@@ -813,18 +933,19 @@ describe("Model chains", () => {await vi.advanceTimersByTimeAsync(10_000);expect(await kind).toBe("timed_out");expect(invokeModel).toHaveBeenCalledTimes(3);+ expect(acquireModelCall).toHaveBeenCalledTimes(3);expect(invokeModel.mock.calls.every(- ([, request]) => request.chainLease !== undefined,+ ([, request]) => request.callLease !== undefined,),).toBe(true);});it("stops its calls and frees its place when the caller stops it", async () => {- const chainLease = lease();+ const callLease = lease();const { modelCall, invokeModel } = setup({placements: [alice],- lease: chainLease,+ lease: callLease,invoke: hanging,});const stop = new AbortController();@@ -836,7 +957,7 @@ describe("Model chains", () => {stop.abort(new Error("refresh canceled"));await expect(task).rejects.toThrow("refresh canceled");expect(invokeModel.mock.calls[0]![1].signal.aborted).toBe(true);- expect(chainLease.release).toHaveBeenCalledWith(+ expect(callLease.release).toHaveBeenCalledWith(expect.objectContaining({ outcome: "aborted" }),);});@@ -936,7 +1057,7 @@ describe("Runner Gateway model invocation adapter", () => {invokeModel: async () => {throw thrown;},- acquireModelChain: async () => {+ acquireModelCall: async () => {throw thrown;},});diff --git a/docs/model-scheduling.md b/docs/model-scheduling.mdindex 153a1926..aa181c88 100644--- a/docs/model-scheduling.md+++ b/docs/model-scheduling.md@@ -43,8 +43,10 @@ Each Run holds one place across its tool calls. Inputs merged into a queuedRun take the highest priority among them. Eligible work at the same prioritystarts in arrival order.-A wiki refresh is many units, not one: each routing pack, meeting, page batch-and correction queues on its own, so other work can run between them.+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.Every model call is retried and corrected in one place. A timeout, a reply pastits length cap or a runtime failure is tried again after a pause, and an answer