Skip to content

Commit 1d456de

Browse files
committed
fix: preserve worker sessions across automation owner eviction
1 parent 0f84630 commit 1d456de

14 files changed

Lines changed: 220 additions & 64 deletions

‎CHANGELOG.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@ include the full version, for example `## 0.7.0-beta.1`.
88

99
## Unreleased
1010

11+
### Fixed
12+
13+
- Prevent hourly owner eviction using durable activity on one empty maintenance
14+
session. The previous plugin-list heartbeat did not refresh OpenCode's session
15+
inactivity timer. Keepalive never prompts a model or modifies a work session.
16+
- Bound SDK waits independently of adapters that ignore AbortSignal, allowing
17+
shutdown to release locks without interrupting a healthy worktree session.
18+
A replacement dispatcher reconciles the saved session before publication.
19+
- Wait briefly for a retiring owner's locks, bound RPC disposal, and reject
20+
queued checkpoint writes after shutdown to prevent failed plugin reloads.
21+
1122
## 0.6.3
1223

1324
### Fixed
@@ -51,4 +62,4 @@ include the full version, for example `## 0.7.0-beta.1`.
5162
- Add detailed bot workflow diagrams and a documentation map in `AGENTS.md`.
5263
- Expand bundled bot instructions for planning, delegation, verification, and
5364
handing publication back to the dispatcher.
54-
- Add the README banner showing an OpenCode2 agent executing a task.
65+
- Add the README banner showing an OpenCode2 agent executing a task.

‎docs/advanced.md‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -101,19 +101,23 @@ uncertain network results. Uncertain initial prompt delivery is not automaticall
101101
resent. Issue replies and helper prompts use deterministic IDs for admission retries.
102102
Merge requests pin the verified head SHA and reconcile an already-merged PR.
103103

104-
The shared service can evict an idle owner location even while an agent works in
105-
a different worktree. Scheduler and dispatcher components therefore refresh the
106-
owner every 30 seconds through the public plugin-list API, after confirming the
107-
service PID matches their own process. Transient heartbeat errors are logged and
108-
retried; requests do not overlap. A standalone server without a matching service
109-
registration skips this mechanism. Keep its owner location in use or use the
110-
shared background service for unattended automation.
111-
112-
Cleanup aborts and settles work before releasing ownership. All cleanup steps
113-
are attempted even when RPC disposal fails; locks are not forcibly removed or
114-
stolen from another owner. A held-lock startup error should be investigated via
115-
plugin details and server logs. Back up the queue and worktree before recovery;
116-
do not assume a failed session means its edits were lost.
104+
The shared service evicts owner locations after roughly an hour without durable
105+
session activity, even if plugin RPC or HTTP requests continue. Components use one
106+
deterministically identified, empty maintenance session per owner directory and
107+
rename it at startup and every ten minutes. Creation is idempotent, metadata and
108+
location are checked before renaming, and no model is prompted. Requests have a
109+
15-second deadline, never overlap, and require a matching service PID. Standalone
110+
servers without a matching service registration skip this mechanism; use the
111+
shared service for unattended automation.
112+
113+
SDK adapters may ignore AbortSignal. The plugin therefore bounds its own SDK waits,
114+
preserves healthy worker execution on owner disposal, and settles local state writes
115+
before releasing ownership. A replacement waits up to 15 seconds for the retiring
116+
owner's locks. RPC disposal has a five-second deadline per component; cleanup still
117+
attempts every remaining step. No live lock is forcibly removed. A held-lock startup
118+
error should be investigated via plugin details and server logs. Back up the queue,
119+
worktree, and session database before recovery. Reconcile an already-published PR
120+
and saved session instead of restarting implementation or deleting the worktree.
117121

118122
Only one issue executes at a time. Checks must succeed before publication. Push
119123
uses the exact verified commit without force. Worktrees remain available for

‎docs/architecture.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,14 @@ The primary checkout owns scheduling. Worker worktrees do not start additional
4242
schedulers. A shared Git-directory state folder holds the queue and locks; separate
4343
machines require separate test repositories to avoid duplicate execution.
4444

45-
In the shared background service, each scheduler/dispatcher component sends a
46-
periodic request back to its owner location to prevent idle eviction while work
47-
runs elsewhere. It checks the service PID before touching the location, so a
48-
standalone instance cannot activate another owner in a different service.
49-
Shutdown settles work and attempts all cleanup steps, including lock release,
50-
even if an SDK registration fails to dispose after location eviction.
45+
In the shared background service, each scheduler/dispatcher component renews one
46+
empty maintenance session in the owner location at startup and every ten minutes.
47+
OpenCode counts durable session events as activity; polling plugin APIs alone
48+
does not prevent its hourly inactivity eviction. No model is prompted by keepalive.
49+
The service PID must match the plugin process before any maintenance session is
50+
created. Shutdown releases local SDK waits independently of adapter cancellation,
51+
settles state writes, bounds RPC disposal, and releases locks. A healthy worktree
52+
session continues and the replacement owner reconciles its saved identity.
5153

5254
See [advanced configuration](advanced.md) for retry commands, limits, and RPC
5355
settings, and the [README](../README.md) for installation and user-facing behavior.

‎docs/bot-workflow.md‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,22 @@ flowchart TD
3535
cancel accepted work or active sessions.
3636
- A scan cannot overlap another scan in the same dispatcher. Only one worker
3737
invocation runs at a time; one scheduler job cannot overlap itself.
38-
- Each component refreshes the owner through the matching background service's
39-
plugin-list API every 30 seconds. A PID check prevents activating a second
40-
owner in another service. Requests do not overlap and have a 15-second deadline.
41-
This heartbeat keeps the owner loaded while execution happens in worktrees;
42-
pausing issue scans does not pause it. Standalone servers without a matching
43-
registered service skip the refresh.
38+
- Each component renews one empty owner maintenance session at startup and every
39+
ten minutes. Durable session events refresh OpenCode's inactivity timer; listing
40+
plugins does not. No model is prompted. A PID check prevents touching a different
41+
service. Requests do not overlap and have a 15-second deadline. Pausing issue
42+
scans does not pause keepalive. Standalone servers without a matching registered
43+
service skip it.
4444
- State is schema-validated and saved through a temporary file, file sync, and
4545
rename. A corrupt state file fails to load rather than resetting the queue.
4646
Local locks prevent duplicate owners sharing this state directory; independent
4747
machines do not share ownership.
48-
- Shutdown clears timers, aborts operations, waits for in-flight work, disposes
49-
registrations, and releases locks. Cleanup attempts the remaining steps even
50-
if an earlier step fails, so an evicted RPC registration cannot skip lock
51-
release. Executor shutdown interrupts its task session.
48+
- Shutdown clears timers and aborts local SDK waits even if the adapter ignores
49+
cancellation. It settles local writes, bounds RPC disposal to five seconds per
50+
component, and attempts all cleanup steps before releasing ownership. A replacement
51+
waits up to 15 seconds for locks without removing them. Healthy worktree sessions
52+
continue; the next owner reconciles the saved session before verifying and publishing.
53+
5254

5355
Sources: [index.ts](../src/index.ts), [easy.ts](../src/easy.ts),
5456
[GitHub plugin](../src/plugins/github.ts),

‎docs/runtime.md‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,18 @@ After restarting the service, load the owner project again to resume polling.
4646
No terminal UI is needed to answer in GitHub.
4747

4848
The automation owner must remain loaded while its worktree sessions run. In the
49-
shared background service, the plugin refreshes the owner location every 30
50-
seconds, independently of issue polling and its pause setting. This prevents
51-
idle owner eviction from disconnecting worker hooks and publication. The refresh
52-
only targets a service whose PID matches the plugin process; standalone servers
53-
without a matching registered service do not receive this heartbeat.
49+
shared background service, keepalive runs at startup and every ten minutes,
50+
independently of issue polling and its pause setting. It reuses one empty session
51+
named `Automation owner keepalive` in the primary checkout. The session has no
52+
messages, consumes no model tokens, and is not an issue task. Its durable rename
53+
event refreshes OpenCode's activity timer; requests to list plugins do not.
54+
Keepalive only targets a service whose PID matches the plugin process. Standalone
55+
servers without a matching registered service do not receive this protection.
56+
57+
On owner reload, the dispatcher stops waiting locally and releases its lock without
58+
interrupting a healthy worker. The next owner reconnects to the saved session ID,
59+
checks its outcome, verifies the changes, and resumes publication. Explicit task
60+
cancellation, unanswered questions, and session deadlines still interrupt workers.
5461

5562
If the plugin reports a held lock or a worker reports unavailable automation RPC,
5663
inspect plugin details, logs, and queue state before retrying. Preserve the

‎src/dispatcher.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ export class Dispatcher {
7777
this.signal.throwIfAborted();
7878
let announce = false;
7979
await this.serial.run(async () => {
80+
this.signal.throwIfAborted();
8081
announce = Boolean(patch.sessionReady && !task.sessionReady) || Boolean(patch.status && patch.status !== task.status && ["done", "blocked", "failed", "waiting"].includes(patch.status));
8182
announce ||= patch.pr?.state === "closed" && task.pr?.state !== "closed";
8283
if (patch.sessionID) task.sessionIDs = [...new Set([...task.sessionIDs ?? [], ...[task.previousSessionID, task.sessionID, patch.sessionID].filter((id): id is string => Boolean(id))])];

‎src/executor.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { analysisDecision } from "./analysis.js";
99
import { baseChoice, type BranchInput } from "./branch.js";
1010
import { installWorkerPlugin } from "./worker.js";
1111
import { Blocked, WaitingForAnswer, type Executor, type Task } from "./dispatcher.js";
12+
import { cancellable } from "./lifecycle.js";
1213

1314
export type CommandRunner = (cwd: string, argv: string[]) => Promise<string>;
1415
export function commandRunner(signal: AbortSignal, timeout: number, secretEnv: string): CommandRunner {
@@ -104,6 +105,7 @@ export class GitWorkspace {
104105
export class OpenCodeExecutor implements Executor {
105106
private git: GitWorkspace;
106107
constructor(private ctx: Plugin.Context, private options: GithubOptions, private signal: AbortSignal, private runtimeInstaller = installWorkerPlugin) {
108+
this.ctx = { ...ctx, ...(ctx.session ? { session: cancellable(ctx.session) } : {}), ...(ctx.generate ? { generate: cancellable(ctx.generate) } : {}) };
107109
this.git = new GitWorkspace(options.stateDirectory, commandRunner(signal, options.commandTimeoutSeconds * 1000, options.tokenEnv));
108110
}
109111
async title(task: Task) {
@@ -156,11 +158,9 @@ export class OpenCodeExecutor implements Executor {
156158
return this.runtimeInstaller(directory, this.options, commandRunner(this.signal, this.options.commandTimeoutSeconds * 1000, this.options.tokenEnv));
157159
}
158160
async run(task: Task, checkpoint: (patch: Partial<Task>) => Promise<void>) {
159-
try { await this.runSession(task, checkpoint); }
160-
catch (error) {
161-
if (this.signal.aborted) await this.cancel(task);
162-
throw error;
163-
}
161+
// Owner disposal must not interrupt a healthy worker in another location.
162+
// The replacement owner resumes waiting on the saved session ID.
163+
await this.runSession(task, checkpoint);
164164
}
165165
private async runSession(task: Task, checkpoint: (patch: Partial<Task>) => Promise<void>) {
166166
if (!task.worktree || !task.route) throw new Blocked("Missing execution configuration");

‎src/lifecycle.ts‎

Lines changed: 44 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { OpenCode } from "@opencode/client";
22
import { Service } from "@opencode/client/service";
3+
import { createHash } from "node:crypto";
34

45
// Cleanup must reach the lock release even when an evicted SDK scope can no
56
// longer dispose its RPC registration. Keep the lock until work has settled.
@@ -13,7 +14,10 @@ export async function cleanup(...steps: (() => void | Promise<void>)[]) {
1314

1415
export interface OwnerClient {
1516
health: { get(options: { signal: AbortSignal }): Promise<{ pid: number }> };
16-
plugin: { list(input: { location: { directory: string } }, options: { signal: AbortSignal }): Promise<unknown> };
17+
session: {
18+
create(input: { id: string; title: string; location: { directory: string }; metadata: Record<string, string> }, options: { signal: AbortSignal }): Promise<{ id: string; location: { directory: string }; metadata?: Record<string, unknown> }>;
19+
rename(input: { sessionID: string; title: string }, options: { signal: AbortSignal }): Promise<unknown>;
20+
};
1721
}
1822

1923
export async function touchOwner(directory: string, signal: AbortSignal, connect: () => Promise<OwnerClient | undefined> = async () => {
@@ -25,22 +29,57 @@ export async function touchOwner(directory: string, signal: AbortSignal, connect
2529
// A standalone server must never activate a second owner in a different
2630
// background service. The public request must return to this exact process.
2731
if ((await client.health.get({ signal })).pid !== process.pid) return false;
28-
await client.plugin.list({ location: { directory } }, { signal });
32+
// OpenCode's inactivity sweep observes durable session events, NOT HTTP
33+
// requests or plugin RPC. Reuse one empty maintenance session; never prompt
34+
// a model, touch a user's session, or create a new session on every tick.
35+
const id = `ses_${createHash("sha256").update(`opencode2-automation-owner:${directory}`).digest("hex").slice(0, 32)}`;
36+
const title = "Automation owner keepalive";
37+
const session = await client.session.create({ id, title, location: { directory }, metadata: { automation: "owner-keepalive" } }, { signal });
38+
if (session.location.directory !== directory || session.metadata?.automation !== "owner-keepalive") throw new Error("Automation keepalive session identity mismatch");
39+
// Rename emits Session.Renamed even when the title is unchanged.
40+
await client.session.rename({ sessionID: session.id, title }, { signal });
2941
return true;
3042
}
3143

32-
export function heartbeat(touch: (signal: AbortSignal) => Promise<unknown>, report: (error: unknown) => void, everyMs = 30_000) {
44+
export function heartbeat(touch: (signal: AbortSignal) => Promise<unknown>, report: (error: unknown) => void, everyMs = 10 * 60_000) {
3345
const controller = new AbortController();
3446
let active: Promise<void> | undefined;
35-
const timer = setInterval(() => {
47+
const tick = () => {
3648
if (active || controller.signal.aborted) return;
3749
active = Promise.resolve().then(() => touch(AbortSignal.any([controller.signal, AbortSignal.timeout(15_000)])))
3850
.then(() => {}, error => { if (!controller.signal.aborted) report(error); })
3951
.finally(() => { active = undefined; });
40-
}, everyMs);
52+
};
53+
const timer = setInterval(tick, everyMs);
54+
tick();
4155
return async () => {
4256
clearInterval(timer);
4357
controller.abort();
4458
await active;
4559
};
4660
}
61+
62+
// Some OpenCode Promise plugin adapters ignore the request's AbortSignal.
63+
// Bound our wait independently. Late SDK results are observed but cannot resume
64+
// the retired dispatcher; durable session identity allows the next owner to
65+
// reconcile work that continues in the server.
66+
export function abortable<T>(action: () => Promise<T>, signal?: AbortSignal): Promise<T> {
67+
if (!signal) return action();
68+
return new Promise<T>((resolve, reject) => {
69+
if (signal.aborted) { reject(signal.reason); return; }
70+
const abort = () => reject(signal.reason);
71+
signal.addEventListener("abort", abort, { once: true });
72+
Promise.resolve().then(() => { signal.throwIfAborted(); return action(); })
73+
.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
74+
});
75+
}
76+
77+
export function cancellable<T extends object>(api: T): T {
78+
return new Proxy(api, {
79+
get(target, property, receiver) {
80+
const method: unknown = Reflect.get(target, property, receiver);
81+
if (typeof method !== "function") return method;
82+
return (input: unknown, request?: { signal?: AbortSignal }) => abortable(() => Reflect.apply(method, target, [input, request]), request?.signal);
83+
},
84+
});
85+
}

‎src/plugins/github.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { GithubRpc } from "../rpc.js";
1010
import { acquire, JsonStore, redact } from "../state.js";
1111
import { githubToken } from "../easy.js";
1212
import type { Activity } from "../activity.js";
13-
import { cleanup, heartbeat, touchOwner } from "../lifecycle.js";
13+
import { abortable, cleanup, heartbeat, touchOwner } from "../lifecycle.js";
1414

1515
export default Plugin.define({
1616
id: "automation.github",
@@ -19,7 +19,7 @@ export default Plugin.define({
1919
if (await realpath(ctx.location.directory) !== await realpath(options.ownerDirectory)) return;
2020
const token = await githubToken(options.tokenEnv);
2121
const controller = new AbortController();
22-
const release = await acquire(options.stateDirectory, "github", error => controller.abort(error));
22+
const release = await acquire(options.stateDirectory, "github", error => controller.abort(error), true);
2323
const executor = new OpenCodeExecutor(ctx, options, controller.signal);
2424
let publish: (activity: Activity) => Promise<void> = async () => {};
2525
const dispatcher = new Dispatcher(options, new JsonStore(join(options.stateDirectory, "queue.json"), Queue, () => ({ version: 1, tasks: [] })), new Github(token, controller.signal, fetch, options.signature), executor, controller.signal, [token], Date.now, activity => publish(activity));
@@ -31,7 +31,7 @@ export default Plugin.define({
3131
() => { clearInterval(timer); controller.abort(); },
3232
() => stopHeartbeat?.(),
3333
() => dispatcher.settle(),
34-
() => registration?.dispose(),
34+
() => abortable(async () => { await registration?.dispose(); }, AbortSignal.timeout(5_000)),
3535
() => releaseBridge?.(),
3636
release,
3737
);

‎src/plugins/scheduler.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,20 @@ import { SchedulerOptions } from "../config.js";
55
import { Scheduler, SchedulerState } from "../scheduler.js";
66
import { SchedulerRpc, handlerRpc } from "../rpc.js";
77
import { acquire, JsonStore, redact } from "../state.js";
8-
import { cleanup, heartbeat, touchOwner } from "../lifecycle.js";
8+
import { abortable, cleanup, heartbeat, touchOwner } from "../lifecycle.js";
99

1010
export default Plugin.define({
1111
id: "automation.scheduler",
1212
async setup(ctx) {
1313
const options = SchedulerOptions.parse(ctx.options);
1414
if (await realpath(ctx.location.directory) !== await realpath(options.ownerDirectory)) return;
1515
const controller = new AbortController();
16-
const release = await acquire(options.stateDirectory, "scheduler", error => controller.abort(error));
16+
const release = await acquire(options.stateDirectory, "scheduler", error => controller.abort(error), true);
1717
const scheduler = new Scheduler(options.jobs, new JsonStore(join(options.stateDirectory, "scheduler.json"), SchedulerState, () => []), async job => {
1818
controller.signal.throwIfAborted();
1919
const method = ctx.rpc(handlerRpc(job.rpcID, job.method))[job.method]!;
20-
return method(job.input, { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(120_000)]) });
20+
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(120_000)]);
21+
return abortable(() => method(job.input, { signal }), signal);
2122
});
2223
let registration: { dispose(): Promise<void> } | undefined;
2324
let stopHeartbeat: (() => Promise<void>) | undefined;
@@ -26,7 +27,7 @@ export default Plugin.define({
2627
() => { clearInterval(timer); controller.abort(); },
2728
() => stopHeartbeat?.(),
2829
() => scheduler.settle(),
29-
() => registration?.dispose(),
30+
() => abortable(async () => { await registration?.dispose(); }, AbortSignal.timeout(5_000)),
3031
release,
3132
);
3233
try {

0 commit comments

Comments
 (0)