Skip to content

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): yield delegated tasks and resume the same running claim

LeoXinga26c06da6fbc
diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.go
index 94992aa2..441df6b2 100644
--- a/apps/computer/local-daemon/internal/daemon/daemon.go
+++ b/apps/computer/local-daemon/internal/daemon/daemon.go
@@ -122,8 +122,11 @@ type Daemon struct {
// what an accepted Operation may start with: Registration snapshots, Agent
// Runner commands and Context commands. A start whose revision is unchanged
// after its off-lock MCP preparation needs no second Resolve.
- authorityRevision uint64
- activeOperations map[string]*activeOperation
+ authorityRevision uint64
+ activeOperations map[string]*activeOperation
+ // A yielded Operation whose native cleanup is unknown still occupies this
+ // Computer. Its Runtime refuses new work until the Daemon restarts.
+ uncleanOperations []OperationIdentity
preparationMu sync.Mutex
preparedOperations map[string]*preparedOperation
providerPrepareMu sync.Mutex
diff --git a/apps/computer/local-daemon/internal/daemon/daemon_test.go b/apps/computer/local-daemon/internal/daemon/daemon_test.go
index 3d2d463d..5aeeacc6 100644
--- a/apps/computer/local-daemon/internal/daemon/daemon_test.go
+++ b/apps/computer/local-daemon/internal/daemon/daemon_test.go
@@ -416,6 +416,69 @@ func TestDaemonDoesNotReportCancelledWhenProviderCleanupIsUnconfirmed(t *testing
testDaemonDrainCleanup(t, true)
}
+func TestSchedulerYieldRequiresConfirmedCleanup(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ result provider.Result
+ want string
+ blocked bool
+ }{
+ {"confirmed interrupt", provider.Result{Status: "aborted", CleanupConfirmed: true}, protocol.EventOperationCancelled, false},
+ {"confirmed Pi interrupt", provider.Result{Status: "cancelled", CleanupConfirmed: true}, protocol.EventOperationCancelled, false},
+ {"missing confirmation", provider.Result{Status: "aborted"}, protocol.EventOperationFailed, true},
+ {"unconfirmed interrupt", provider.Result{Status: "failed", CleanupUnconfirmed: true}, protocol.EventOperationFailed, true},
+ {"already finished", provider.Result{Status: "completed", Output: "done"}, protocol.EventOperationCompleted, false},
+ {"failed before interrupt", provider.Result{Status: "failed", CleanupConfirmed: true}, protocol.EventOperationFailed, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ stream := &fakeStream{}
+ d, err := newTestDaemon(t, Options{ComputerID: "computer-1", Capacity: intPointer(1), ControlPlane: fakeControlPlane{stream: stream}, IdentityStore: fakeStore{}, OperationResolver: fakeOperationResolver{}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ d.operationStream = stream
+ start := daemonOperationStart("yield", "agent-1")
+ _, err = d.ledger.Begin(t.Context(), operationIdentity(start))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ d.activeOperations[start.OperationID] = &activeOperation{identity: operationIdentity(start), cancel: cancel}
+ stop := operationCancelCommand(start)
+ stop.Payload = mustJSON(map[string]string{"reason": schedulerYield})
+ if err := d.handleOperationCancel(stop); err != nil {
+ t.Fatal(err)
+ }
+ d.finishOperation(t.Context(), start, provider.OperationSpec{OperationKind: "run.start", Provider: start.RuntimeType}, tc.result)
+ events := stream.snapshotEvents()
+ if len(events) != 1 || events[0].Type != tc.want {
+ t.Fatalf("terminal=%+v, want %s", events, tc.want)
+ }
+ if d.runtimeCleanupUnconfirmed(start.RuntimeType) != tc.blocked {
+ t.Fatal("incorrect Runtime availability")
+ }
+ if !tc.blocked {
+ return
+ }
+ next := daemonOperationStart("late-chat", "agent-2")
+ if err := d.handleOperationStart(t.Context(), stream, next); err != nil {
+ t.Fatal(err)
+ }
+ events = stream.snapshotEvents()
+ if len(events) != 2 || events[1].Type != protocol.EventOperationFailed || !strings.Contains(string(events[1].Payload), cleanupUnconfirmedCode) {
+ t.Fatalf("unconfirmed cleanup admitted chat: %+v", events)
+ }
+ if blocked := d.modelInvokeBlocked(next, modelInvokeRequest{}); blocked.Reason != cleanupUnconfirmedMessage {
+ t.Fatalf("unconfirmed cleanup admitted inference: %+v", blocked)
+ }
+ if count, _ := d.operationOccupancy(operationIdentity(next)); count != 1 {
+ t.Fatalf("Computer occupation=%d", count)
+ }
+ })
+ }
+}
+
func testDaemonDrainCleanup(t *testing.T, cleanupUnconfirmed bool) {
t.Helper()
cancelled := make(chan struct{})
@@ -475,6 +538,9 @@ func testDaemonDrainCleanup(t *testing.T, cleanupUnconfirmed bool) {
if len(events) < 2 || events[len(events)-1].Type != wantTerminal {
t.Fatalf("terminal was not delivered before slot release: %+v", events)
}
+ if d.runtimeCleanupUnconfirmed(start.RuntimeType) {
+ t.Fatal("an ordinary stop with unknown cleanup blocked its Runtime")
+ }
if cleanupUnconfirmed {
var failure struct {
Code string `json:"code"`
diff --git a/apps/computer/local-daemon/internal/daemon/model_invoke.go b/apps/computer/local-daemon/internal/daemon/model_invoke.go
index 517314b2..03174cdc 100644
--- a/apps/computer/local-daemon/internal/daemon/model_invoke.go
+++ b/apps/computer/local-daemon/internal/daemon/model_invoke.go
@@ -98,6 +98,9 @@ func (d *Daemon) modelInvokeBlocked(command protocol.Command, request modelInvok
if stopped {
return provider.ModelInvokeResult{Outcome: provider.ModelInvokeUnavailable, Reason: "Agent Runner is locally stopped"}
}
+ if d.runtimeCleanupUnconfirmed(command.RuntimeType) {
+ return provider.ModelInvokeResult{Outcome: provider.ModelInvokeRuntimeUnavailable, Reason: cleanupUnconfirmedMessage}
+ }
if d.modelInvoker == nil {
return provider.ModelInvokeResult{Outcome: provider.ModelInvokeRuntimeUnavailable, Reason: "Model invocation is unavailable"}
}
diff --git a/apps/computer/local-daemon/internal/daemon/operation_prepare.go b/apps/computer/local-daemon/internal/daemon/operation_prepare.go
index 97731722..f0940cb6 100644
--- a/apps/computer/local-daemon/internal/daemon/operation_prepare.go
+++ b/apps/computer/local-daemon/internal/daemon/operation_prepare.go
@@ -179,7 +179,7 @@ func (d *Daemon) handleOperationPrepare(ctx context.Context, stream transport.St
stopped := d.locallyStopped[command.AgentID]
d.activeMu.Unlock()
activeCount, contextBusy := d.operationOccupancy(identity)
- if stopped || contextBusy || (d.capacity != nil && activeCount >= *d.capacity) {
+ if stopped || contextBusy || d.runtimeCleanupUnconfirmed(command.RuntimeType) || (d.capacity != nil && activeCount >= *d.capacity) {
d.admissionMu.Unlock()
return d.sendOperationPrepared(ctx, stream, command, false, 0, "fallback")
}
diff --git a/apps/computer/local-daemon/internal/daemon/operation_start.go b/apps/computer/local-daemon/internal/daemon/operation_start.go
index d8137e04..b4d1cde8 100644
--- a/apps/computer/local-daemon/internal/daemon/operation_start.go
+++ b/apps/computer/local-daemon/internal/daemon/operation_start.go
@@ -58,6 +58,9 @@ func (d *Daemon) handleOperationStart(ctx context.Context, stream transport.Stre
d.activeMu.Lock()
stopped := d.locallyStopped[command.AgentID]
d.activeMu.Unlock()
+ if d.runtimeCleanupUnconfirmed(command.RuntimeType) {
+ return d.finishFailure(ctx, stream, command, cleanupUnconfirmedCode, cleanupUnconfirmedMessage)
+ }
admittedCount, contextBusy := d.operationOccupancy(identity)
capacityExhausted := d.capacity != nil && admittedCount >= *d.capacity
if stopped {
diff --git a/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go b/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go
index 4bb0c8e9..08a84c09 100644
--- a/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go
+++ b/apps/computer/local-daemon/internal/daemon/operation_start_prepare.go
@@ -109,6 +109,9 @@ func (d *Daemon) startAcceptedOperation(ctx context.Context, command protocol.Co
if err == nil {
err = ctx.Err()
}
+ if err == nil && d.runtimeCleanupUnconfirmed(command.RuntimeType) {
+ err = errors.New(cleanupUnconfirmedMessage)
+ }
if err == nil {
spec.MCPConfig = proxies.Config()
spec.TrustedLocalMCPTools = proxies.LocalToolNames()
@@ -165,6 +168,10 @@ func (d *Daemon) operationOccupancy(identity OperationIdentity) (count int, cont
defer d.activeMu.Unlock()
d.preparationMu.Lock()
defer d.preparationMu.Unlock()
+ for _, pending := range d.uncleanOperations {
+ count++
+ contextBusy = contextBusy || operationContextKey(pending) == operationContextKey(identity)
+ }
for _, active := range d.activeOperations {
if !active.terminalCommitted {
count++
diff --git a/apps/computer/local-daemon/internal/daemon/operations.go b/apps/computer/local-daemon/internal/daemon/operations.go
index 9c5e6d93..498fabab 100644
--- a/apps/computer/local-daemon/internal/daemon/operations.go
+++ b/apps/computer/local-daemon/internal/daemon/operations.go
@@ -27,11 +27,8 @@ func (d *Daemon) awaitOperation(ctx context.Context, command protocol.Command, s
func (d *Daemon) finishOperation(ctx context.Context, command protocol.Command, spec provider.OperationSpec, result provider.Result) {
d.activeMu.Lock()
active := d.activeOperations[command.OperationID]
- reason := ""
- if active != nil {
- reason = active.reason
- }
d.activeMu.Unlock()
+ reason := ""
if active != nil {
active.inputMu.Lock()
active.finishing = true
@@ -58,6 +55,31 @@ func (d *Daemon) finishOperation(ctx context.Context, command protocol.Command,
result.Status, result.Error = "failed", "Local MCP cleanup failed"
result.CleanupUnconfirmed = result.CleanupUnconfirmed || errors.Is(err, mcpproxy.ErrCleanupUnconfirmed)
}
+ d.activeMu.Lock()
+ reason = active.reason
+ d.activeMu.Unlock()
+ }
+ yieldRequested := reason == schedulerYield
+ if yieldRequested {
+ // A natural completion can race the scheduler's cancel. Only an
+ // interrupted turn with confirmed cleanup is safe to continue.
+ if result.Status != "completed" && !result.CleanupConfirmed {
+ result.CleanupUnconfirmed = true
+ }
+ if result.Status != "aborted" && result.Status != "cancelled" {
+ reason = ""
+ }
+ }
+ // Chat starts on this Runtime as soon as a yielded Task reports its
+ // terminal, so a yield whose native turn may still run must hold the
+ // Runtime. Any other stop only reports that its cleanup is unknown.
+ if result.CleanupUnconfirmed && yieldRequested {
+ result.Status = "failed"
+ d.admissionMu.Lock()
+ d.activeMu.Lock()
+ d.uncleanOperations = append(d.uncleanOperations, operationIdentity(command))
+ d.activeMu.Unlock()
+ d.admissionMu.Unlock()
}
terminalType := protocol.EventOperationCompleted
if reason != "" && !result.CleanupUnconfirmed {
@@ -158,9 +180,25 @@ func (d *Daemon) finishAdmissionBusy(ctx context.Context, stream transport.Strea
return stream.Send(ctx, persisted)
}
-// Operation failure codes for a start this Computer refused. The first two
-// tell the Agent Service the Computer cannot run the Agent right now, so the
-// Room can say so instead of a generic failure.
+const (
+ schedulerYield = "scheduler_yield"
+ cleanupUnconfirmedCode = "RUNTIME_CLEANUP_UNCONFIRMED"
+ cleanupUnconfirmedMessage = "Provider cancellation cleanup is unconfirmed"
+)
+
+// A Daemon cannot dispatch new work on a Runtime with a potentially live turn.
+func (d *Daemon) runtimeCleanupUnconfirmed(runtime string) bool {
+ d.activeMu.Lock()
+ defer d.activeMu.Unlock()
+ for _, identity := range d.uncleanOperations {
+ if identity.RuntimeType == runtime {
+ return true
+ }
+ }
+ return false
+}
+
+// Operation failure codes for a start this Computer refused.
const (
operationCodeRunnerStopped = "RUNNER_STOPPED"
operationCodeRuntimeNotEnabled = "RUNTIME_NOT_ENABLED"
@@ -251,7 +289,7 @@ func operationIdentity(command protocol.Command) OperationIdentity {
func terminalPayload(spec provider.OperationSpec, result provider.Result) json.RawMessage {
if result.CleanupUnconfirmed {
- return terminalWithUsage(map[string]any{"code": "RUNTIME_CLEANUP_UNCONFIRMED", "message": "Provider cancellation cleanup is unconfirmed", "retryable": false}, spec, result)
+ return terminalWithUsage(map[string]any{"code": cleanupUnconfirmedCode, "message": cleanupUnconfirmedMessage, "retryable": false}, spec, result)
}
if result.Status != "completed" {
failure := provider.ClassifyExecutionFailure(spec.Provider, spec.CodexVersion, result.Status, result.FailureCode, result.Diagnostics)
diff --git a/apps/computer/local-daemon/internal/daemon/provider_prepare.go b/apps/computer/local-daemon/internal/daemon/provider_prepare.go
index 124e246e..19df77a0 100644
--- a/apps/computer/local-daemon/internal/daemon/provider_prepare.go
+++ b/apps/computer/local-daemon/internal/daemon/provider_prepare.go
@@ -70,6 +70,10 @@ func (d *Daemon) handleProviderPrepare(ctx context.Context, stream transport.Str
d.admissionMu.Unlock()
return d.sendProviderPrepared(ctx, stream, command, request.PrepareID, "not_eligible", "Local Computer Daemon is draining", 0)
}
+ if d.runtimeCleanupUnconfirmed(command.RuntimeType) {
+ d.admissionMu.Unlock()
+ return d.sendProviderPrepared(ctx, stream, command, request.PrepareID, "not_eligible", cleanupUnconfirmedMessage, 0)
+ }
d.activeMu.Lock()
stopped := d.locallyStopped[command.AgentID]
d.activeMu.Unlock()
diff --git a/apps/computer/local-daemon/internal/daemon/session_compact.go b/apps/computer/local-daemon/internal/daemon/session_compact.go
index 432dce41..cd880be9 100644
--- a/apps/computer/local-daemon/internal/daemon/session_compact.go
+++ b/apps/computer/local-daemon/internal/daemon/session_compact.go
@@ -107,6 +107,9 @@ func (d *Daemon) sessionCompactBlocked(command protocol.Command) string {
if d.draining {
return "Local Computer Daemon is draining"
}
+ if d.runtimeCleanupUnconfirmed(command.RuntimeType) {
+ return cleanupUnconfirmedMessage
+ }
key := command.ExecutionContextKey
d.activeMu.Lock()
stopped := d.locallyStopped[command.AgentID]
diff --git a/apps/computer/local-daemon/internal/linger/context/resolver.go b/apps/computer/local-daemon/internal/linger/context/resolver.go
index 974ddec6..98ac9e29 100644
--- a/apps/computer/local-daemon/internal/linger/context/resolver.go
+++ b/apps/computer/local-daemon/internal/linger/context/resolver.go
@@ -129,6 +129,9 @@ func (r ExecutionResolver) Resolve(ctx context.Context, command protocol.Command
if resumeSessionID == "" {
resumeSessionID = request.Session.SessionID
}
+ if request.RunContext.ResumeAfterYield && resumeSessionID == "" {
+ return provider.OperationSpec{}, errors.New("a yielded Run requires its native session identity")
+ }
if command.RuntimeType == "codex" && resumeSessionID == "" && (request.Session.ThreadIDCamel == nil || *request.Session.ThreadIDCamel != "") {
return provider.OperationSpec{}, errors.New("Codex run.start requires a retained session or an explicit first-run marker")
}
@@ -153,6 +156,7 @@ func (r ExecutionResolver) Resolve(ctx context.Context, command protocol.Command
ExecutablePath: installation.ExecutablePath, WorkingDirectory: workingDirectory,
Model: request.Runtime.Model, Prompt: request.Input.Text,
ExecutionRunRef: strings.TrimSpace(request.RunContext.ExecutionRunRef),
+ ResumeAfterYield: request.RunContext.ResumeAfterYield,
HumanInteractions: request.RunContext.HumanInteractions,
PermissionReview: request.RunContext.PermissionReview,
TeamHubCLIBin: r.TeamHubCLIBin,
@@ -227,7 +231,7 @@ func (r ExecutionResolver) Resolve(ctx context.Context, command protocol.Command
spec.ClaudeSkillNames = authorizedClaudeSkillNames(view.View.Mappings)
}
spec.ContextSkillDigest = contextSkillDigest(view.View.Mappings)
- if (command.RuntimeType == "claude" || command.RuntimeType == "pi") && resumeSessionID != "" && !request.Session.materialized() {
+ if (command.RuntimeType == "claude" || command.RuntimeType == "pi") && resumeSessionID != "" && !spec.ResumeAfterYield && !request.Session.materialized() {
spec.CreateProviderSessionID = resumeSessionID
spec.ResumeSessionID = ""
}
@@ -364,6 +368,7 @@ type semanticRequest struct {
} `json:"run_resources,omitempty"`
RunContext struct {
ExecutionRunRef string `json:"execution_run_ref,omitempty"`
+ ResumeAfterYield bool `json:"resume_after_yield,omitempty"`
HumanInteractions bool `json:"human_interactions,omitempty"`
PermissionReview bool `json:"permission_review,omitempty"`
} `json:"run_context,omitempty"`
diff --git a/apps/computer/local-daemon/internal/linger/context/resolver_test.go b/apps/computer/local-daemon/internal/linger/context/resolver_test.go
index 19c6fe85..40367af2 100644
--- a/apps/computer/local-daemon/internal/linger/context/resolver_test.go
+++ b/apps/computer/local-daemon/internal/linger/context/resolver_test.go
@@ -214,23 +214,32 @@ func TestExecutionResolverUsesSessionMarkerState(t *testing.T) {
WorkspaceGrantID: "grant-local", RuntimeType: runtimeType,
ExecutionContextKey: "context-1", ContextViewRef: json.RawMessage(`{"receipt_ref":"receipt-1"}`),
}
- request := func(materialized bool) json.RawMessage {
+ request := func(materialized, resumeAfterYield bool) json.RawMessage {
return json.RawMessage(fmt.Sprintf(`{
"kind":"run.start","runtime":{"type":%q},
"session_options":{"thread_name":"Claude"},
"session":{"provider":%q,"sessionId":"123e4567-e89b-12d3-a456-426614174000","lingerMaterialized":%t},
+ "run_context":{"resume_after_yield":%t},
"input":{"type":"text","text":"Run"},"run_resources":{"mcp_servers":[]}
- }`, runtimeType, runtimeType, materialized))
+ }`, runtimeType, runtimeType, materialized, resumeAfterYield))
}
- first, err := resolver.Resolve(context.Background(), command, request(false))
+ first, err := resolver.Resolve(context.Background(), command, request(false, false))
if err != nil || first.CreateProviderSessionID == "" || first.ResumeSessionID != "" {
t.Fatalf("unmaterialized Runtime spec=%+v err=%v", first, err)
}
- resumed, err := resolver.Resolve(context.Background(), command, request(true))
+ resumed, err := resolver.Resolve(context.Background(), command, request(true, false))
if err != nil || resumed.CreateProviderSessionID != "" || resumed.ResumeSessionID != "123e4567-e89b-12d3-a456-426614174000" {
t.Fatalf("materialized Runtime spec=%+v err=%v", resumed, err)
}
+ yielded, err := resolver.Resolve(t.Context(), command, request(false, true))
+ if err != nil || !yielded.ResumeAfterYield || yielded.CreateProviderSessionID != "" || yielded.ResumeSessionID != resumed.ResumeSessionID {
+ t.Fatalf("yielded first turn must resume its assigned identity: %+v, %v", yielded, err)
+ }
+ _, err = resolver.Resolve(t.Context(), command, json.RawMessage(fmt.Sprintf(`{"kind":"run.start","runtime":{"type":%q},"run_context":{"resume_after_yield":true}}`, runtimeType)))
+ if err == nil {
+ t.Fatal("scheduler continuation accepted an empty session")
+ }
})
}
}
diff --git a/apps/computer/local-daemon/internal/provider/event_projection.go b/apps/computer/local-daemon/internal/provider/event_projection.go
index 3676f352..636ce61a 100644
--- a/apps/computer/local-daemon/internal/provider/event_projection.go
+++ b/apps/computer/local-daemon/internal/provider/event_projection.go
@@ -13,6 +13,7 @@ import (
type eventProjection struct {
operationID string
+ canYield bool
tools map[string]string
// quiet holds tool calls that stay in history without a Room activity.
quiet map[string]bool
@@ -97,6 +98,9 @@ func (projection *eventProjection) projectActivity(message native.Event) []any {
message.ToolName = projection.tools[message.InvocationID]
}
event := normalizeMessage(message, projection.operationID).(map[string]any)
+ if session, ok := event["session"].(map[string]any); ok && projection.canYield {
+ session["canYield"] = true
+ }
if event["type"] == "message.delta" {
remaining := strings.ToValidUTF8(event["delta"].(string), "\ufffd")
events := make([]any, 0)
diff --git a/apps/computer/local-daemon/internal/provider/executor.go b/apps/computer/local-daemon/internal/provider/executor.go
index 63a45e4e..8a4b5610 100644
--- a/apps/computer/local-daemon/internal/provider/executor.go
+++ b/apps/computer/local-daemon/internal/provider/executor.go
@@ -31,6 +31,8 @@ const operationMCPPrepareKind = "internal.mcp.prepare"
const operationProviderPrepareKind = "internal.provider.prepare"
type OperationSpec struct {
+ // A continuation prompt requires the exact native history of the interrupted Task.
+ ResumeAfterYield bool
HumanInteractions bool
// PermissionReview sends the Runtime's own permission prompts to the
// Runtime permission review (Agent Service declares it per Run).
@@ -591,7 +593,7 @@ func (e Executor) Start(ctx context.Context, spec OperationSpec, emit EmitFunc)
}
}
emittedResponseText := false
- projection := eventProjection{operationID: spec.TaskID}
+ projection := eventProjection{operationID: spec.TaskID, canYield: spec.OperationKind == "run.start"}
for {
emittedEvent := false
for message := range session.Events {
@@ -844,6 +846,6 @@ func (spec OperationSpec) ReviewsPermissions() bool {
// startsFreshSession reports whether a Run whose retained native session the
// Runtime refused may continue in a new session instead of failing.
func startsFreshSession(spec OperationSpec, result native.Outcome) bool {
- return spec.OperationKind == "run.start" && spec.ResumeSessionID != "" &&
+ return !spec.ResumeAfterYield && spec.OperationKind == "run.start" && spec.ResumeSessionID != "" &&
result.Status != "completed" && result.FailureCode == "session_not_found"
}
diff --git a/apps/computer/local-daemon/internal/provider/executor_test.go b/apps/computer/local-daemon/internal/provider/executor_test.go
index d5d388ae..443dd607 100644
--- a/apps/computer/local-daemon/internal/provider/executor_test.go
+++ b/apps/computer/local-daemon/internal/provider/executor_test.go
@@ -319,6 +319,11 @@ func TestExecutorDoesNotRepeatFreshSessionFallback(t *testing.T) {
runs: []*native.Run{finishedRun(missing, native.Event{Kind: native.EventText, Body: "partial"})},
starts: 1,
},
+ "yielded session must still exist": {
+ spec: OperationSpec{OperationKind: "run.start", ResumeSessionID: "retained", ResumeAfterYield: true},
+ runs: []*native.Run{finishedRun(missing)},
+ starts: 1,
+ },
"new session": {
spec: OperationSpec{OperationKind: "run.start"},
runs: []*native.Run{finishedRun(missing)},
@@ -349,3 +354,19 @@ func TestExecutorDoesNotRepeatFreshSessionFallback(t *testing.T) {
})
}
}
+
+func TestRunStartedOffersYieldOnlyWithNativeSession(t *testing.T) {
+ for _, tc := range []struct {
+ run bool
+ session string
+ want bool
+ }{{true, "native-session", true}, {true, "", false}, {false, "native-session", false}} {
+ projection := eventProjection{canYield: tc.run}
+ events := projection.project(native.Event{Kind: native.EventStatus, TurnID: "turn", SessionID: tc.session})
+ start := events[0].(map[string]any)
+ session, _ := start["session"].(map[string]any)
+ if (session["canYield"] == true) != tc.want {
+ t.Fatalf("run=%v session=%q: %+v", tc.run, tc.session, start)
+ }
+ }
+}
diff --git a/apps/node-services/src/agent/executor/provider.ts b/apps/node-services/src/agent/executor/provider.ts
index f31fcdf5..dda55649 100644
--- a/apps/node-services/src/agent/executor/provider.ts
+++ b/apps/node-services/src/agent/executor/provider.ts
@@ -130,6 +130,8 @@ export interface ExecutionSpec {
acceptedAtMonotonicMs?: number;
/** What queued the Run, for model scheduling; never sent over the wire. */
runKind?: RunKind;
+ /** Revalidate the live claim after readmission and before resuming its native session. */
+ beforeYieldResume?: () => Promise<void>;
signal?: AbortSignal;
resources?: ProviderResourceBundle;
runContext?: ProviderRunContext;
@@ -266,6 +268,13 @@ export interface RunResult {
finalResponse: string;
}
+/** A delegated Task's native Operation stopped and its session can continue. */
+export class ProviderRunYieldedError extends Error {
+ constructor(readonly session: Record<string, string | boolean>) {
+ super("Task yielded its model slot");
+ }
+}
+
export class ProviderRunCleanupError extends Error {
constructor(options?: ErrorOptions) {
super("Provider cancellation cleanup is unconfirmed", options);
diff --git a/apps/node-services/src/agent/executor/run-loop.ts b/apps/node-services/src/agent/executor/run-loop.ts
index d3a29cbf..cd9284ca 100644
--- a/apps/node-services/src/agent/executor/run-loop.ts
+++ b/apps/node-services/src/agent/executor/run-loop.ts
@@ -10,6 +10,7 @@ import {
type RuntimeSession,
ProviderRunAdmissionUnavailableError,
ProviderRunCleanupError,
+ ProviderRunYieldedError,
ProviderRunInterruptedError,
ProviderRunStartError,
StreamingAgentRunLimitError,
@@ -279,6 +280,7 @@ interface LocalRunExecution {
removeAbortListener: (() => void) | undefined;
upstreamCanceled: boolean;
providerSucceeded: boolean;
+ hasYielded: boolean;
}
export class RunLoop {
@@ -926,6 +928,7 @@ export class RunLoop {
removeAbortListener: undefined,
upstreamCanceled: false,
providerSucceeded: false,
+ hasYielded: false,
};
try {
await this.#runExecution(execution);
@@ -988,10 +991,10 @@ export class RunLoop {
/** Prepares, starts, observes and durably finishes one claimed Run. */
async #runExecution(execution: LocalRunExecution): Promise<void> {
- const { runId, attemptCount, controller } = execution;
+ const { runId, controller } = execution;
controller.signal.throwIfAborted();
if (execution.preparationFailure) throw execution.preparationFailure.error;
- const input = this.#prepareRunInput(execution);
+ let input = this.#prepareRunInput(execution);
try {
await this.#beforeStartRun?.(runId);
} catch (error) {
@@ -1001,7 +1004,49 @@ export class RunLoop {
{ cause: error },
);
}
- controller.signal.throwIfAborted();
+ const replyDelivery = new ReplyDelivery();
+ let resumeStartRetries = 0;
+ for (;;) {
+ controller.signal.throwIfAborted();
+ try {
+ await this.#runSegment(execution, input, replyDelivery);
+ return;
+ } catch (error) {
+ if (
+ execution.hasYielded &&
+ error instanceof ProviderRunStartError &&
+ error.effect === "definitely_not_started" &&
+ !(error instanceof ProviderRunAdmissionUnavailableError) &&
+ ++resumeStartRetries < MAX_LOCAL_RUN_START_ATTEMPTS
+ )
+ continue;
+ if (!(error instanceof ProviderRunYieldedError)) throw error;
+ execution.hasYielded = true;
+ resumeStartRetries = 0;
+ const active = this.#activeExecution;
+ if (active?.runId === runId) {
+ active.acceptingSteers = false;
+ await this.#settleProviderSteers(active);
+ }
+ execution.removeAbortListener?.();
+ await this.#settleRuntimeStatusEvents(execution);
+ controller.signal.throwIfAborted();
+ // The claim stays running while the next Operation waits behind chat.
+ await this.#commitDurably(() =>
+ this.#state.setRuntimeSession(this.#runtimeSession),
+ );
+ input = { type: "text", text: "Continue on this task." };
+ this.#logger.log("info", "local_run.yielded", { runId });
+ }
+ }
+ }
+
+ async #runSegment(
+ execution: LocalRunExecution,
+ input: AgentInput,
+ replyDelivery: ReplyDelivery,
+ ): Promise<void> {
+ const { controller, runId, attemptCount } = execution;
const providerStartAt = performance.now();
const run = await this.#startProviderRun(execution, input);
execution.run = run;
@@ -1009,14 +1054,13 @@ export class RunLoop {
this.#logProviderReady(execution, run, providerStartAt, providerReadyAt);
const active = await this.#activateExecution(execution, run, input);
- execution.runtimeStatus = await this.#openRuntimeStatus(
+ execution.runtimeStatus ??= await this.#openRuntimeStatus(
runId,
execution.provenance,
execution.runContext.executionEpoch,
);
controller.signal.throwIfAborted();
- const replyDelivery = new ReplyDelivery();
execution.runtimeStatusEvents = this.#consumeRuntimeStatusEvents(
runId,
run.events,
@@ -1123,6 +1167,20 @@ export class RunLoop {
runContext: execution.runContext,
acceptedAtMonotonicMs: execution.acceptedAtMonotonicMs,
runKind: execution.kind,
+ ...(execution.hasYielded
+ ? {
+ beforeYieldResume: async () => {
+ const claim = await this.#state.getLocalRun(execution.runId);
+ if (
+ claim?.status !== "running" ||
+ claim.cancellationRequested ||
+ claim.attemptCount !== execution.attemptCount
+ )
+ controller.abort(new LocalRunCancellationRequestedError());
+ controller.signal.throwIfAborted();
+ },
+ }
+ : {}),
});
this.#firstSessionRun = false;
return run;
@@ -1257,10 +1315,12 @@ export class RunLoop {
executionEpoch: execution.runContext.executionEpoch,
acceptingSteers: true,
controller,
- inputs: [input],
+ inputs: this.#activeExecution?.inputs ?? [input],
run,
runId,
- sourceInboxIds: new Set(execution.provenance.sourceInboxIds),
+ sourceInboxIds:
+ this.#activeExecution?.sourceInboxIds ??
+ new Set(execution.provenance.sourceInboxIds),
steerOperations: new Set(),
};
this.#activeExecution = active;
@@ -1372,6 +1432,7 @@ export class RunLoop {
error instanceof ProviderRunStartError &&
!(error instanceof ProviderRunAdmissionUnavailableError) &&
error.effect === "definitely_not_started" &&
+ !execution.hasYielded &&
attemptCount < MAX_LOCAL_RUN_START_ATTEMPTS &&
!controller.signal.aborted
) {
@@ -1710,7 +1771,7 @@ export class RunLoop {
return;
}
- const target = await intent.providerReady;
+ const target = this.#activeExecution ?? (await intent.providerReady);
if (
!target ||
!target.acceptingSteers ||
diff --git a/apps/node-services/src/agent/runner-gateway/model-queue.ts b/apps/node-services/src/agent/runner-gateway/model-queue.ts
index 69b9b175..b6fd1ed7 100644
--- a/apps/node-services/src/agent/runner-gateway/model-queue.ts
+++ b/apps/node-services/src/agent/runner-gateway/model-queue.ts
@@ -1,5 +1,6 @@
import {
admissionLimit,
+ runPriorities,
type ModelLease,
type ModelLeaseResult,
} from "../../model-tasks.js";
@@ -67,9 +68,9 @@ interface EndpointState {
}
/**
- * Admits model work per endpoint. A Run's Operation, a one-shot call, a
- * chain and a compaction are each one unit. Smaller priority numbers start
- * first, in arrival order within a priority. Running units finish. When the
+ * Admits model work per endpoint. A Run Operation, a model attempt and a
+ * compaction each occupy one place. Smaller priority numbers start first,
+ * in arrival order within a priority. 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
@@ -84,6 +85,7 @@ export class ModelQueue {
constructor(
private readonly concurrency: (endpoint: ModelEndpoint) => ConcurrencyRange,
private readonly now: () => number = Date.now,
+ private readonly onInteractiveWait?: (endpoint: ModelEndpoint) => void,
) {}
/** A model request on endpoint finished, whoever holds its place. */
@@ -164,6 +166,19 @@ export class ModelQueue {
return this.#lease(state, work, queuedAt);
}
+ /** A newly resumable Task can yield to chat already waiting on this endpoint. */
+ recheckInteractiveWait(endpoint: ModelEndpoint): void {
+ const state = this.#endpoints.get(endpointKey(endpoint));
+ if (
+ state &&
+ state.active === 1 &&
+ state.waiting.length &&
+ this.#limit(state.key, endpoint).value === 1 &&
+ state.waiting[0]!.priority <= runPriorities.chat
+ )
+ this.onInteractiveWait?.(endpoint);
+ }
+
/** The Computer is gone; work waiting for it fails with error. */
rejectWaiters(computerId: string, error: unknown): void {
for (const state of [...this.#endpoints.values()]) {
@@ -254,6 +269,7 @@ export class ModelQueue {
state.waiting.shift();
next.admit();
}
+ this.recheckInteractiveWait(state.endpoint);
this.#prune(state);
}
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.ts
index 64bc67f7..5445d7f6 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
@@ -28,6 +28,7 @@ import {
RuntimeExecutionError,
StreamingAgentRun,
ProviderRunCleanupError,
+ ProviderRunYieldedError,
ProviderRunInterruptedError,
ProviderRunStartError,
runtimeSessionStartsFresh,
@@ -483,6 +484,7 @@ export class RemoteRuntimeProvider implements AgentProvider {
signal,
spec.runContext.executionEpoch,
spec.runKind,
+ spec.beforeYieldResume,
);
if (spec.runContext.cancellationRequested) {
await this.#cancel(operation, "Durable user cancellation");
@@ -687,6 +689,7 @@ export class RemoteRuntimeProvider implements AgentProvider {
signal: AbortSignal = this.#closed.signal,
executionEpoch?: string,
runKind?: RunnerOperationTarget["runKind"],
+ beforeYieldResume?: () => Promise<void>,
): Promise<RunnerOperation> {
if (this.#closePromise) {
throw new Error("Remote Codex provider is closed");
@@ -702,6 +705,7 @@ export class RemoteRuntimeProvider implements AgentProvider {
...this.#target,
executionEpoch,
...(runKind ? { runKind } : {}),
+ ...(beforeYieldResume ? { beforeYieldResume } : {}),
signal,
contextViewRef: this.#contextRunResources.currentContextViewRef(),
request,
@@ -889,6 +893,7 @@ export class RemoteRuntimeProvider implements AgentProvider {
return {
run_context: {
...toContextRunContext(context),
+ ...(spec.beforeYieldResume ? { resume_after_yield: true } : {}),
...this.#runAuthorization(),
},
run_resources: runResources,
@@ -1044,6 +1049,8 @@ class RemoteAgentRun implements AgentRun {
replaceOpaqueObject(this.#session, runResult.session);
return { finalResponse: runResult.final_response };
} catch (error) {
+ if (error instanceof ProviderRunYieldedError)
+ replaceOpaqueObject(this.#session, error.session);
throw localRunFailure(error, true);
}
}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
index c2e7a376..139a2ef0 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
@@ -174,10 +174,13 @@ export class RunnerGateway
this.#preparation = new RunnerOperationPreparation(context, owners);
this.#compaction = new RunnerSessionCompaction(context, owners);
this.#modelInvocation = new RunnerModelInvocation(context, owners);
- this.#queue = new ModelQueue((endpoint) =>
- endpointConcurrency(
- this.runtimeModels(endpoint.computerId, endpoint.runtimeType),
- ),
+ this.#queue = new ModelQueue(
+ (endpoint) =>
+ endpointConcurrency(
+ this.runtimeModels(endpoint.computerId, endpoint.runtimeType),
+ ),
+ Date.now,
+ (endpoint) => this.#operations.yieldTaskForChat(endpoint),
);
this.#computerTools = new RunnerComputerTools(context, owners);
this.#localModels = new RunnerLocalModels(context, owners);
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
index 9c06e54f..97559f70 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts
@@ -5,6 +5,7 @@ import { isDeepStrictEqual } from "node:util";
import { logAgentEvent } from "../observability/agent-log.js";
import {
RuntimeExecutionError,
+ ProviderRunYieldedError,
runtimeSessionAwaitsFirstRun,
} from "../executor/provider.js";
import type { ProviderSteerAck } from "../executor/provider.js";
@@ -41,6 +42,7 @@ interface RunnerOperationTargetBase {
readonly executionEpoch?: string;
/** What queued the Run. Absent, chat. */
readonly runKind?: RunKind;
+ readonly beforeYieldResume?: () => Promise<void>;
/** Stops the Run waiting for its turn in the model queue. */
readonly signal?: AbortSignal;
readonly tenantId: string;
@@ -247,6 +249,11 @@ export class RunnerOperationState {
#accepted = false;
#terminal = false;
#cancelCommand?: OperationCancel;
+ readonly #delegatedTask: boolean;
+ #yieldSessionId?: string;
+ #yieldRequested = false;
+ #observedNativeWork = false;
+ readonly #interactions = new Set<string>();
#prepareCommand?: OperationPrepare;
#prepareResumeObserved = false;
#currentContextViewRef: ContextViewRef;
@@ -295,6 +302,7 @@ export class RunnerOperationState {
};
}) {
this.#epoch = options.target.executionEpoch;
+ this.#delegatedTask = options.target.runKind === "task";
this.#createId = options.createId;
this.#send = options.send;
this.#cancelTimeoutMs = options.cancelTimeoutMs;
@@ -590,6 +598,34 @@ export class RunnerOperationState {
}
}
+ get resumableTask(): boolean {
+ // Codex announces its thread before the first task input is durably in its history.
+ return (
+ Boolean(this.#yieldSessionId) &&
+ (this.start.runtime_type !== "codex" || this.#observedNativeWork)
+ );
+ }
+
+ /** Only a native terminal can hand a running Task's slot to another caller. */
+ requestYield(): void {
+ if (
+ !this.resumableTask ||
+ this.#terminal ||
+ this.#cancelCommand ||
+ this.#interactions.size ||
+ [...this.#pendingInputs.values()].some((input) => !input.settled)
+ )
+ return;
+ this.#yieldRequested = true;
+ this.#cancelCommand = createCancel(
+ this.start,
+ this.#createId(),
+ "scheduler_yield",
+ );
+ // Reconciliation resends this exact command if the Computer disconnected.
+ void this.#send(this.#cancelCommand).catch(() => undefined);
+ }
+
retainCancellation(reason: string): void {
if (this.#terminal) {
return;
@@ -821,8 +857,33 @@ export class RunnerOperationState {
case "operation.accepted":
break;
case "operation.event":
- if (envelope.event.type === "run.started")
+ if (envelope.event.type === "run.started") {
this.#turnId = envelope.event.turn_id;
+ const threadId = envelope.event.session?.threadId;
+ if (
+ this.#delegatedTask &&
+ envelope.event.session?.canYield === true &&
+ typeof threadId === "string" &&
+ threadId.trim()
+ )
+ this.#yieldSessionId = threadId;
+ }
+ if (
+ this.#delegatedTask &&
+ (envelope.event.type === "tool.called" ||
+ envelope.event.type === "tool.returned" ||
+ envelope.event.type === "model.responded")
+ )
+ this.#observedNativeWork = true;
+ if (
+ this.#delegatedTask &&
+ envelope.event.type === "human_interaction.requested"
+ ) {
+ // A prompt in transit belongs to the retiring Operation and cannot be answered on its successor.
+ if (this.#yieldRequested) break;
+ if (typeof envelope.event.request.request_id === "string")
+ this.#interactions.add(envelope.event.request.request_id);
+ }
await this.#events.push(envelope.event);
break;
case "operation.input_result":
@@ -881,15 +942,24 @@ export class RunnerOperationState {
true,
);
break;
- case "operation.cancelled":
- this.#complete(
- () =>
- this.#outcome.reject(
- new RunnerOperationError("cancelled", envelope.reason, false),
- ),
- true,
- );
+ case "operation.cancelled": {
+ const id = this.#yieldSessionId;
+ const runtime = this.start.runtime_type;
+ const error =
+ this.#yieldRequested && id && envelope.reason === "scheduler_yield"
+ ? new ProviderRunYieldedError(
+ runtime === "codex"
+ ? { threadId: id }
+ : {
+ provider: runtime,
+ sessionId: id,
+ lingerMaterialized: true,
+ },
+ )
+ : new RunnerOperationError("cancelled", envelope.reason, false);
+ this.#complete(() => this.#outcome.reject(error), true);
break;
+ }
default:
assertNever(envelope);
}
@@ -897,7 +967,7 @@ export class RunnerOperationState {
async #input(options: RunnerOperationInput): Promise<ProviderSteerAck> {
const pending = await this.#serialize(async () => {
- if (!this.#accepted || this.#terminal) {
+ if (!this.#accepted || this.#terminal || this.#yieldRequested) {
throw new RunnerOperationInputError(
"No active Runtime run",
"definitely_not_applied",
@@ -948,7 +1018,7 @@ export class RunnerOperationState {
message,
);
} catch {
- if (this.#terminal) return;
+ if (this.#terminal || this.#yieldRequested) return;
this.#complete(() =>
this.#outcome.reject(
new RunnerOperationError("cancelled", message, false),
@@ -974,7 +1044,10 @@ export class RunnerOperationState {
}
pending.settled = true;
try {
- pending.outcome.resolve(outcome());
+ const accepted = outcome();
+ const requestId = pending.command.input.runtime_response?.request_id;
+ if (typeof requestId === "string") this.#interactions.delete(requestId);
+ pending.outcome.resolve(accepted);
} catch (error) {
pending.outcome.reject(error);
}
diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
index fe85db7d..40ff074e 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts
@@ -211,6 +211,14 @@ export class RunnerOperations {
},
};
}
+ if (
+ hard === 1 &&
+ first === waiter &&
+ waiter.rank !== undefined &&
+ rank <= runPriorities.chat &&
+ active.length === 1
+ )
+ active[0]!.requestYield();
await waitForCapacityChange(changed, signal);
}
} finally {
@@ -251,6 +259,8 @@ export class RunnerOperations {
target.signal ?? new AbortController().signal,
);
try {
+ if (target.beforeYieldResume) await target.beforeYieldResume();
+ target.signal?.throwIfAborted();
const reservation = this.#capacityReservations.get(permit.id);
if (
!reservation ||
@@ -276,6 +286,14 @@ export class RunnerOperations {
}
}
+ /** A chat waiting on the model may already hold its Computer permit. */
+ yieldTaskForChat(endpoint: ModelEndpoint): void {
+ for (const operation of this.activeOperations(endpoint.computerId)) {
+ if (operation.start.runtime_type === endpoint.runtimeType)
+ operation.requestYield();
+ }
+ }
+
/** Pins the reviewed Operation's place until its approval has settled. */
borrowModelPlace(operationId: string | undefined, endpoint: ModelEndpoint) {
if (!operationId) return undefined;
@@ -656,6 +674,7 @@ export class RunnerOperations {
);
return;
}
+ const wasResumable = operation.resumableTask;
const acknowledgement = await operation.receive(envelope);
if (
envelope.type === "operation.event" &&
@@ -671,6 +690,14 @@ export class RunnerOperations {
!operation.terminal
)
this.#recordRunOperation(operation);
+ if (
+ !operation.terminal &&
+ operation.resumableTask &&
+ (!wasResumable || envelope.type === "operation.input_result")
+ ) {
+ this.owners.queue().recheckInteractiveWait(operationEndpoint(operation));
+ this.wakeCapacityWaiters();
+ }
if (operation.terminal) this.#retireOperation(operation);
if (acknowledgement)
await this.owners.connections().send(connection, acknowledgement);
diff --git a/apps/node-services/tests/agent/executor/run-loop.test.ts b/apps/node-services/tests/agent/executor/run-loop.test.ts
index 12d15cc5..38efd748 100644
--- a/apps/node-services/tests/agent/executor/run-loop.test.ts
+++ b/apps/node-services/tests/agent/executor/run-loop.test.ts
@@ -11,6 +11,7 @@ import {
type RuntimeSession,
ProviderRunAdmissionUnavailableError,
ProviderRunCleanupError,
+ ProviderRunYieldedError,
ProviderRunInterruptedError,
ProviderRunStartError,
StreamingAgentRunLimitError,
@@ -437,6 +438,82 @@ describe("RunLoop", () => {
});
});
+ it.each([false, true])(
+ "keeps a yielded Task on its running claim (user stops it: %s)",
+ async (stop) => {
+ const harness = createHarness(
+ undefined,
+ undefined,
+ undefined,
+ { threadId: "retained" },
+ {
+ kind: "alter_ego",
+ agentId: "agent",
+ taskId: "task",
+ },
+ );
+ const first = new FakeRun();
+ const resumed = new FakeRun();
+ const admit = deferred<void>();
+ const start = harness.provider.startRun.bind(harness.provider);
+ let resumedSpec: ExecutionSpec | undefined;
+ let failedAdmission = false;
+ vi.spyOn(harness.provider, "startRun").mockImplementation(
+ async (session, input, spec) => {
+ if (spec.beforeYieldResume) {
+ resumedSpec = spec;
+ await admit.promise;
+ await spec.beforeYieldResume();
+ if (!failedAdmission) {
+ failedAdmission = true;
+ throw new ProviderRunStartError(
+ "definitely_not_started",
+ "View changed",
+ );
+ }
+ }
+ return start(session, input, spec);
+ },
+ );
+ harness.provider.runs.push(first, resumed);
+ const finish = vi.spyOn(harness.state, "finishLocalRun");
+ const id = enqueue(harness.state, message("original brief"));
+ harness.execution.start();
+ await vi.waitFor(() => expect(first.waitCalls).toBe(1));
+ first.fail(new ProviderRunYieldedError({ threadId: "retained" }));
+ await vi.waitFor(() => expect(resumedSpec).toBeDefined());
+ expect(harness.state.getLocalRun(id)).toMatchObject({
+ status: "running",
+ attemptCount: 1,
+ });
+ expect(finish).not.toHaveBeenCalled();
+ if (stop) await harness.execution.requestCancellation(id);
+ admit.resolve();
+ if (stop) {
+ await vi.waitFor(() =>
+ expect(harness.state.getLocalRun(id)?.status).toBe("canceled"),
+ );
+ expect(harness.provider.starts).toHaveLength(1);
+ } else {
+ await vi.waitFor(() => expect(resumed.waitCalls).toBe(1));
+ expect(harness.provider.starts[1]).toMatchObject({
+ input: { text: "Continue on this task." },
+ spec: {
+ runContext: { executionRunRef: id, executionAttemptCount: 1 },
+ },
+ session: { threadId: "retained" },
+ });
+ resumed.complete("done");
+ await vi.waitFor(() =>
+ expect(harness.state.getLocalRun(id)?.status).toBe("succeeded"),
+ );
+ }
+ expect(finish).toHaveBeenCalledTimes(1);
+ await harness.execution.drain({ cancelActive: false });
+ harness.state.close();
+ },
+ );
+
it("keeps a wake received before fresh-state startup", async () => {
const harness = createHarness();
const run = new FakeRun();
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.ts
index efd993fd..de105b15 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
@@ -96,6 +96,109 @@ describe("RunnerGateway", () => {
await expect(operation.result).resolves.toMatchObject({ type: "run" });
});
+ it.each([1, null])(
+ "waits for confirmed Task cleanup before starting chat (Computer capacity %s)",
+ async (capacity) => {
+ const gateway = createTestRunnerGateway({
+ createId: sequenceIds(),
+ operationCancelTimeoutMs: 10,
+ });
+ const peer = new RecordingPeer();
+ const connection = await acceptReadyConnection(gateway, peer, {
+ ...hello([], capacity),
+ runtime_diagnostics: runtimeDiagnostics({ link: "api" }),
+ });
+ try {
+ const task = await gateway.startOperation({
+ ...runTarget(),
+ runKind: "task",
+ });
+ const start = peer.sent.find(
+ (command) => command.type === "operation.start",
+ )!;
+ const chat = gateway.startOperation({
+ ...runTarget(),
+ ...readyContextScope("chat"),
+ runKind: "chat",
+ });
+ await connection.receive(
+ event(start, 1, {
+ type: "operation.accepted",
+ command_id: start.command_id,
+ runner_pid: 100,
+ }),
+ );
+ expect(await settlesWithin(chat, 10)).toBe(false);
+ expect(peer.sent.some((command) => command.type === "cancel")).toBe(
+ false,
+ );
+ await connection.receive(
+ event(start, 2, {
+ type: "operation.event",
+ event: {
+ type: "run.started",
+ turn_id: "turn-task",
+ session: { threadId: "task-session", canYield: true },
+ },
+ }),
+ );
+ expect(peer.sent.some((command) => command.type === "cancel")).toBe(
+ false,
+ );
+ await connection.receive(
+ event(start, 3, {
+ type: "operation.event",
+ event: {
+ type: "tool.called",
+ call_id: "read",
+ tool_name: "read",
+ input: {},
+ },
+ }),
+ );
+ await vi.waitFor(() =>
+ expect(
+ peer.sent.filter((command) => command.type === "cancel"),
+ ).toHaveLength(1),
+ );
+ expect(
+ peer.sent.find((command) => command.type === "cancel"),
+ ).toMatchObject({
+ operation_id: start.operation_id,
+ reason: "scheduler_yield",
+ });
+ expect(await settlesWithin(chat, 25)).toBe(false);
+ await connection.receive(
+ event(start, 4, {
+ type: "operation.event",
+ event: {
+ type: "human_interaction.requested",
+ request: { request_id: "late" },
+ },
+ }),
+ );
+ const yielded = expect(task.result).rejects.toMatchObject({
+ session: { threadId: "task-session" },
+ });
+ await connection.receive(
+ event(start, 5, {
+ type: "operation.cancelled",
+ reason: "scheduler_yield",
+ }),
+ );
+ await yielded;
+ const events = [];
+ for await (const item of task.events) events.push(item.type);
+ expect(events).toEqual(["run.started", "tool.called"]);
+ const interactive = await chat;
+ expect(interactive.operationId).not.toBe(start.operation_id);
+ void interactive.result.catch(() => undefined);
+ } finally {
+ connection.disconnect();
+ }
+ },
+ );
+
it("records the Runtime turn a Run's Operation started as soon as it starts", async () => {
const recordRunOperation = vi.fn(async () => {});
const gateway = createTestRunnerGateway({
diff --git a/apps/teamhub/tests/integration/task_delegation_run_operations_test.go b/apps/teamhub/tests/integration/task_delegation_run_operations_test.go
new file mode 100644
index 00000000..b6b2113a
--- /dev/null
+++ b/apps/teamhub/tests/integration/task_delegation_run_operations_test.go
@@ -0,0 +1,126 @@
+package integration_test
+
+import (
+ "encoding/json"
+ "net/http"
+ "slices"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+func TestDelegatedTaskAcrossRunnerOperations(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ for _, action := range []string{"resume", "human stop"} {
+ t.Run(action, func(t *testing.T) {
+ env, alice, issued, roomID := newAgentCLIIdentity(t)
+ task := createDelegatedTask(t, env, issued, "operations", "Draft a report", "Draft a report.", roomID)
+ worker := claimDelegatedTask(t, env, task.TaskID, "worker-operations")
+ attemptID := worker.bundle.Execution.CurrentAttempt.ID
+ service := agentruntimestate.New(env.pool)
+ const epoch = "operations-epoch"
+ startRuntimeEpoch(t, service, epoch)
+ context, err := service.EnsureContext(t.Context(), agentruntimestate.EnsureContextInput{
+ Ref: agentruntimestate.ContextRef{Kind: "alter_ego", AgentID: acmeOfficialAgentManagementID, TaskID: task.TaskID}, TargetResidency: "active",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := context.Context.ContextKey
+ submitted, err := service.SubmitTrustedTurn(t.Context(), agentruntimestate.SubmitTrustedTurnInput{
+ ContextKey: key, Epoch: epoch, Inputs: []agentruntimestate.RuntimeInput{
+ runtimeInput("input-operations", "trusted_turn", "meta:actor_acme_official:"+task.TaskID, "Draft a report."),
+ },
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ runID := submitted.RunID
+ effectID := worker.startTurn(runID)
+ claimed, err := service.ClaimLocalRun(t.Context(), agentruntimestate.ClaimLocalRunInput{ContextKey: key, Epoch: epoch, ClaimID: "claim-operations"})
+ if err != nil || claimed.Run == nil || claimed.Run.RunID != runID || claimed.Run.AttemptCount != 1 {
+ t.Fatalf("claim: %+v %v", claimed, err)
+ }
+
+ recordOperation := func(id string, usage json.RawMessage) {
+ t.Helper()
+ if err := service.RecordRunOperation(t.Context(), agentruntimestate.RecordRunOperationInput{
+ ContextKey: key, Epoch: epoch, RunID: runID, OperationID: id, RuntimeType: "codex", Usage: usage,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ backgroundPath := "/v0/rooms/" + roomID + "/background-tasks"
+ assertStillRunning := func() {
+ t.Helper()
+ status, _, body := env.request(alice, http.MethodGet, backgroundPath, nil, "")
+ var list httpapi.RoomBackgroundTaskList
+ if err := json.Unmarshal(body, &list); err != nil || status != http.StatusOK || len(list.Items) != 1 || list.Items[0].Id != task.TaskID {
+ t.Fatalf("background list: %d %s", status, body)
+ }
+ assertDelegatedTaskState(t, env, task.TaskID, "running", "")
+ if got := countRows(t, env, `SELECT count(*) FROM task_attempts WHERE task_id=$1 AND id=$2 AND status='running'`, task.TaskID, attemptID); got != 1 {
+ t.Fatal("original Task attempt no longer running")
+ }
+ run, err := service.GetLocalRun(t.Context(), key, runID)
+ if err != nil || run.Status != "running" || run.AttemptCount != 1 || len(run.Terminal) != 0 {
+ t.Fatalf("yielded Local Run: %+v %v", run, err)
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM task_meta_callback_messages WHERE task_id=$1`, task.TaskID); got != 0 {
+ t.Fatalf("operation generated %d Meta messages", got)
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM river_job WHERE kind='task_execution.participant_run_finished' AND args->>'task_id'=$1`, task.TaskID); got != 0 {
+ t.Fatalf("operation generated %d participant completion jobs", got)
+ }
+ }
+
+ // A yielded Operation reports its terminal usage while the Agent Service keeps the Run's claim.
+ recordOperation("operation-first", json.RawMessage(`[{"provider":"openai","model":"fixture","input":10,"cache_read":0,"cache_write":0,"output":1}]`))
+ assertStillRunning()
+ if action == "human stop" {
+ status, _, body := env.request(alice, http.MethodPost, backgroundPath+"/"+task.TaskID+"/cancel", nil, "")
+ var canceled httpapi.RoomBackgroundTaskCancelResult
+ if err := json.Unmarshal(body, &canceled); err != nil || status != http.StatusOK || canceled.Status != "canceled" || canceled.TaskId != task.TaskID {
+ t.Fatalf("cancel: %d %s", status, body)
+ }
+ assertDelegatedTaskState(t, env, task.TaskID, "canceled", "stopped")
+ if got := countRows(t, env, `SELECT count(*) FROM task_attempts WHERE task_id=$1 AND id=$2 AND status='stopped'`, task.TaskID, attemptID); got != 1 {
+ t.Fatal("human stop did not stop the original attempt")
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM task_effects WHERE task_id=$1 AND operation='cleanup_runtime' AND payload->>'agent_run_ref'=$2`, task.TaskID, runID); got != 1 {
+ t.Fatalf("human stop queued %d cleanups for the yielded Run", got)
+ }
+ if reports := taskReports(t, env, task.TaskID); len(reports) != 0 {
+ t.Fatalf("human stop produced agent reports: %q", reports)
+ }
+ return
+ }
+
+ recordOperation("operation-resumed", nil)
+ assertStillRunning()
+ operations, err := store.New(env.pool).ListAgentRuntimeNativeOperationIDs(t.Context(), runID)
+ if err != nil || !slices.Equal(operations, []string{"operation-first", "operation-resumed"}) {
+ t.Fatalf("native operations on Run %s: %v %v", runID, operations, err)
+ }
+ if _, err := service.FinishLocalRun(t.Context(), agentruntimestate.FinishLocalRunInput{
+ ContextKey: key, Epoch: epoch, RunID: runID, Terminal: json.RawMessage(`{"type":"succeeded","finalResponse":"The report is ready."}`),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ worker.endTurn(effectID, runID, "succeeded", "")
+ worker.advance()
+ assertDelegatedTaskState(t, env, task.TaskID, "idle", "run_succeeded")
+ if got := countRows(t, env, `SELECT count(*) FROM task_attempts WHERE task_id=$1 AND id=$2 AND status='passed'`, task.TaskID, attemptID); got != 1 {
+ t.Fatal("the original attempt did not pass")
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM task_attempts WHERE task_id=$1`, task.TaskID); got != 1 {
+ t.Fatalf("operations created %d Task attempts", got)
+ }
+ if reports := taskReports(t, env, task.TaskID); len(reports) != 2 || reports[1] != "The report is ready." {
+ t.Fatalf("expected one idle notice and final reply: %q", reports)
+ }
+ })
+ }
+}
diff --git a/contracts/generated/go/runnergateway/wire.gen.go b/contracts/generated/go/runnergateway/wire.gen.go
index 85952282..603a5657 100644
--- a/contracts/generated/go/runnergateway/wire.gen.go
+++ b/contracts/generated/go/runnergateway/wire.gen.go
@@ -1846,6 +1846,7 @@ func (AgentInput) RequiredFields() []string { return []string{"type", "text"} }
type ContextRunContext struct {
HumanInteractions *bool `json:"human_interactions,omitempty"`
PermissionReview *bool `json:"permission_review,omitempty"`
+ ResumeAfterYield *bool `json:"resume_after_yield,omitempty"`
ExecutionRunRef string `json:"execution_run_ref"`
SourceInboxIDs []string `json:"source_inbox_ids"`
}
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
index f817b4cf..5687ba3d 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
@@ -3579,6 +3579,11 @@ export const runnerGatewayEnvelopeSchema = {
description:
"The Daemon sends Runtime permission prompts as human_interaction.requested with kind permission_review; Agent Service answers each with an operation.input runtime_response.",
},
+ resume_after_yield: {
+ type: "boolean",
+ description:
+ "Continue the exact native session of this Run after a confirmed scheduler cancellation.",
+ },
execution_run_ref: {
$ref: "#/$defs/Id",
},
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
index 37997f34..5946b51b 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
@@ -1032,6 +1032,10 @@ export interface ContextRunContext {
* The Daemon sends Runtime permission prompts as human_interaction.requested with kind permission_review; Agent Service answers each with an operation.input runtime_response.
*/
permission_review?: boolean;
+ /**
+ * Continue the exact native session of this Run after a confirmed scheduler cancellation.
+ */
+ resume_after_yield?: boolean;
execution_run_ref: Id;
/**
* @maxItems 1024
diff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.json
index df0363bb..d724a7f3 100644
--- a/contracts/runner-gateway/envelope.schema.json
+++ b/contracts/runner-gateway/envelope.schema.json
@@ -3535,6 +3535,10 @@
"type": "boolean",
"description": "The Daemon sends Runtime permission prompts as human_interaction.requested with kind permission_review; Agent Service answers each with an operation.input runtime_response."
},
+ "resume_after_yield": {
+ "type": "boolean",
+ "description": "Continue the exact native session of this Run after a confirmed scheduler cancellation."
+ },
"execution_run_ref": {
"$ref": "#/$defs/Id"
},
diff --git a/docs/model-scheduling.md b/docs/model-scheduling.md
index aa181c88..7f102724 100644
--- a/docs/model-scheduling.md
+++ b/docs/model-scheduling.md
@@ -3,7 +3,7 @@
A model serves one more request only by slowing the others, and every agent,
approval and background job on a computer shares it. One queue per endpoint,
one runtime on one computer, decides what reaches the model: each unit of work
-waits its turn by priority, and a unit that started is never interrupted.
+waits its turn by priority.
| Endpoint | Starts at | Grows to |
| -------------------------------------------------- | --------- | -------- |
@@ -24,9 +24,8 @@ change.
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.
+recording questions and standalone approvals can use the last place. When
+the limit drops, 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.
@@ -39,8 +38,20 @@ for an interactive Run when that capacity exceeds one.
| Compaction | An idle conversation's session compaction. New work for that conversation cancels it. |
| Background | Agent memory, user memory, profile, insights and wiki refresh, in descending priority. |
-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
+When a delegated Task occupies the only place on its endpoint or Computer,
+a waiting interactive request can ask it to yield once the Runtime has a
+resumable native session. On Codex, the Task must also have reached its first
+model response or tool event so that the original brief is in its history.
+Chat starts after the Computer confirms cleanup.
+The Task keeps its ID, running status and claim while it waits, and continues
+in the same session when admitted again. A user stop still ends the Task.
+A pending tool approval or human interaction is answered before yielding.
+If a yielded Task's cleanup cannot be confirmed, the Computer refuses further
+work on that Runtime until it restarts. Other stops only report the unknown
+cleanup.
+
+Each running Operation 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.
Wiki and Memory chains keep their steps in order on one endpoint. Each model