fix(opencode): resume the OpenCode session on follow-ups instead of starting an empty one (#3617)
Co-authored-by: codex <[email protected]>
This commit is contained in:
1 parent
b6d9ce325c
commit
f4da4f3b40
2 files changed
+601
-23
No files matched your search
@@ -5,8 +5,10 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
@@ -31,6 +33,8 @@ import {
|
||||
} from "../opencodeRuntime.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
isOpenCodeNotFound,
|
||||
isSameOpenCodeDirectory,
|
||||
makeOpenCodeAdapter,
|
||||
mergeOpenCodeAssistantText,
|
||||
} from "./OpenCodeAdapter.ts";
|
||||
@@ -64,6 +68,12 @@ const runtimeMock = {
|
||||
closeError: null as Error | null,
|
||||
messages: [] as MessageEntry[],
|
||||
subscribedEvents: [] as unknown[],
|
||||
sessionGetIds: [] as string[],
|
||||
missingSessionIds: new Set<string>(),
|
||||
transientErrorSessionIds: new Set<string>(),
|
||||
sessionDirectoryById: new Map<string, string>(),
|
||||
sessionUpdateCalls: [] as Array<{ sessionID: string; permission: unknown }>,
|
||||
forkCalls: [] as Array<{ sessionID: string; directory?: string }>,
|
||||
},
|
||||
reset() {
|
||||
this.state.startCalls.length = 0;
|
||||
@@ -78,6 +88,12 @@ const runtimeMock = {
|
||||
this.state.closeError = null;
|
||||
this.state.messages = [];
|
||||
this.state.subscribedEvents = [];
|
||||
this.state.sessionGetIds.length = 0;
|
||||
this.state.missingSessionIds.clear();
|
||||
this.state.transientErrorSessionIds.clear();
|
||||
this.state.sessionDirectoryById.clear();
|
||||
this.state.sessionUpdateCalls.length = 0;
|
||||
this.state.forkCalls.length = 0;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -102,10 +118,8 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
connectToOpenCodeServer: ({ serverUrl }) =>
|
||||
Effect.gen(function* () {
|
||||
const url = serverUrl ?? "http://127.0.0.1:4301";
|
||||
// Unconditionally register a scope finalizer for test observability —
|
||||
// preserves the `closeCalls` / `closeError` probes that the existing
|
||||
// suites rely on. Production code never attaches a finalizer to an
|
||||
// external server (it simply returns `Effect.succeed(...)`).
|
||||
// Always register a finalizer so the closeCalls/closeError probes fire;
|
||||
// production attaches none for external servers.
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.sync(() => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
@@ -132,6 +146,34 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = {
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
},
|
||||
get: async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.sessionGetIds.push(sessionID);
|
||||
// The real client is `throwOnError: true`: non-2xx rejects rather
|
||||
// than resolving, so missing → 404 throw, transient → 500 throw.
|
||||
if (runtimeMock.state.transientErrorSessionIds.has(sessionID)) {
|
||||
throw new Error("opencode server error", { cause: { status: 500 } });
|
||||
}
|
||||
if (runtimeMock.state.missingSessionIds.has(sessionID)) {
|
||||
throw new Error(`Session not found: ${sessionID}`, {
|
||||
cause: { status: 404, body: { name: "NotFoundError" } },
|
||||
});
|
||||
}
|
||||
const directory = runtimeMock.state.sessionDirectoryById.get(sessionID);
|
||||
return { data: { id: sessionID, ...(directory ? { directory } : {}) } };
|
||||
},
|
||||
update: async ({ sessionID, permission }: { sessionID: string; permission: unknown }) => {
|
||||
runtimeMock.state.sessionUpdateCalls.push({ sessionID, permission });
|
||||
return { data: { id: sessionID } };
|
||||
},
|
||||
fork: async ({ sessionID, directory }: { sessionID: string; directory?: string }) => {
|
||||
// Fork clones history into a new session bound to the directory.
|
||||
const forkedId = `${sessionID}_fork`;
|
||||
runtimeMock.state.forkCalls.push({ sessionID, ...(directory ? { directory } : {}) });
|
||||
if (directory) {
|
||||
runtimeMock.state.sessionDirectoryById.set(forkedId, directory);
|
||||
}
|
||||
return { data: { id: forkedId, ...(directory ? { directory } : {}) } };
|
||||
},
|
||||
abort: async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
},
|
||||
@@ -251,6 +293,256 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a durable resume cursor for a freshly created session", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-cursor");
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
// Without a persisted cursor, a session is created and its id is
|
||||
// surfaced as a resume cursor so the upper layer can persist it.
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []);
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "http://127.0.0.1:9999/session",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("resumes the persisted OpenCode session instead of creating a new one", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-resume");
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" },
|
||||
});
|
||||
|
||||
// The adapter validates the persisted id with session.get and re-adopts
|
||||
// it — no new session is minted (issue #3604).
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_persisted"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "ses_persisted",
|
||||
});
|
||||
// Resume re-asserts the permission ruleset for the current runtimeMode.
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_persisted");
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("sends follow-up turns to the resumed session id", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-resume-turn");
|
||||
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_persisted" },
|
||||
});
|
||||
|
||||
const result = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "continue where we left off",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"anthropic/sonnet",
|
||||
),
|
||||
});
|
||||
|
||||
// The prompt targets the resumed id, and the turn re-surfaces the cursor.
|
||||
NodeAssert.deepEqual(
|
||||
(runtimeMock.state.promptCalls[0] as { sessionID: string }).sessionID,
|
||||
"ses_persisted",
|
||||
);
|
||||
NodeAssert.deepEqual(result.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "ses_persisted",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to a fresh session when the persisted session is gone", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-stale");
|
||||
runtimeMock.state.missingSessionIds.add("ses_stale");
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_stale" },
|
||||
});
|
||||
|
||||
// get probed the stale id, found nothing, then created a new session and
|
||||
// emitted a fresh cursor rather than wedging the thread.
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_stale"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "http://127.0.0.1:9999/session",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores a malformed or wrong-version resume cursor", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-badcursor");
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 99, sessionId: "ses_persisted" },
|
||||
});
|
||||
|
||||
// A foreign/stale-shaped cursor is treated as "no resume": never probed,
|
||||
// a fresh session is created.
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, []);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "http://127.0.0.1:9999/session",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a non-not-found resume probe error instead of silently starting fresh", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-transient");
|
||||
// session.get returns a 500 (not a 404) for this id.
|
||||
runtimeMock.state.transientErrorSessionIds.add("ses_transient");
|
||||
|
||||
const exit = yield* Effect.exit(
|
||||
adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_transient" },
|
||||
}),
|
||||
);
|
||||
|
||||
// A transient/transport/auth failure must propagate — NOT be masked as a
|
||||
// brand-new empty session (the #3604 class of silent context loss).
|
||||
NodeAssert.equal(Exit.isFailure(exit), true);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_transient"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("re-applies the current runtimeMode permissions when resuming", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-perms");
|
||||
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
// A different runtimeMode than the original create — resume must not
|
||||
// leave the upstream session on stale permissions.
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_perms" },
|
||||
});
|
||||
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_perms"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_perms");
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.permission != null, true);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"forks the resumed session into the requested directory instead of losing context",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-cwd");
|
||||
// The persisted session still exists but was created in another working dir
|
||||
// (e.g. the thread moved from the project root into a git worktree).
|
||||
runtimeMock.state.sessionDirectoryById.set("ses_otherdir", "/some/other/worktree");
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_otherdir" },
|
||||
});
|
||||
|
||||
// A cwd change must not mint an empty session: the adapter forks the
|
||||
// persisted session into the requested cwd, carrying history forward.
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_otherdir"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
|
||||
NodeAssert.equal(runtimeMock.state.forkCalls.length, 1);
|
||||
NodeAssert.equal(runtimeMock.state.forkCalls[0]?.sessionID, "ses_otherdir");
|
||||
NodeAssert.equal(typeof runtimeMock.state.forkCalls[0]?.directory, "string");
|
||||
// Permission ruleset re-asserted on the fork for the current runtimeMode.
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls.length, 1);
|
||||
NodeAssert.equal(runtimeMock.state.sessionUpdateCalls[0]?.sessionID, "ses_otherdir_fork");
|
||||
// Durable cursor now points at the history-complete fork in the new directory.
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "ses_otherdir_fork",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reuses the resumed session when the stored directory differs only lexically", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-opencode-samedir");
|
||||
// Same working tree, different spelling (trailing slash) — must reuse,
|
||||
// not fork.
|
||||
runtimeMock.state.sessionDirectoryById.set("ses_samedir", `${process.cwd()}/`);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
resumeCursor: { schemaVersion: 1, sessionId: "ses_samedir" },
|
||||
});
|
||||
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionGetIds, ["ses_samedir"]);
|
||||
NodeAssert.deepEqual(runtimeMock.state.sessionCreateUrls, []);
|
||||
NodeAssert.deepEqual(runtimeMock.state.forkCalls, []);
|
||||
NodeAssert.deepEqual(session.resumeCursor, {
|
||||
schemaVersion: 1,
|
||||
sessionId: "ses_samedir",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails sendTurn for missing sessions through the typed error channel", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
@@ -673,6 +965,88 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("classifies a confirmed not-found across the shapes the SDK/runtime can produce", () =>
|
||||
Effect.sync(() => {
|
||||
// The real production shape: runOpenCodeSdk wraps the thrown Error
|
||||
// (cause = { body, status }) under OpenCodeRuntimeError.
|
||||
const wrappedError = new Error("Session not found: ses_x", {
|
||||
cause: { body: { name: "NotFoundError" }, status: 404 },
|
||||
});
|
||||
NodeAssert.equal(
|
||||
isOpenCodeNotFound({
|
||||
_tag: "OpenCodeRuntimeError",
|
||||
operation: "session.get",
|
||||
detail: "Session not found: ses_x",
|
||||
cause: wrappedError,
|
||||
}),
|
||||
true,
|
||||
);
|
||||
|
||||
// 404 expressed only via response.status (the bot's flagged shape).
|
||||
NodeAssert.equal(isOpenCodeNotFound({ cause: { response: { status: 404 } } }), true);
|
||||
// 404 via a bare numeric status / statusCode.
|
||||
NodeAssert.equal(isOpenCodeNotFound(new Error("x", { cause: { status: 404 } })), true);
|
||||
NodeAssert.equal(isOpenCodeNotFound({ statusCode: 404 }), true);
|
||||
// OpenCode NotFoundError body name with no status.
|
||||
NodeAssert.equal(isOpenCodeNotFound({ body: { name: "NotFoundError" } }), true);
|
||||
|
||||
// NOT a miss: only structured signals count, never free text. A non-404
|
||||
// error whose message/detail merely contains "not found" must propagate,
|
||||
// not be misread as a missing session and silently start fresh.
|
||||
NodeAssert.equal(
|
||||
isOpenCodeNotFound(new Error("upstream provider not found", { cause: { status: 500 } })),
|
||||
false,
|
||||
);
|
||||
NodeAssert.equal(isOpenCodeNotFound({ detail: "status=500 body={...not found...}" }), false);
|
||||
// An explicit non-404 status seals its subtree: a 500 whose serialized
|
||||
// body echoes a NotFoundError name — or that is itself named
|
||||
// *NotFound* — is a real failure, never a miss.
|
||||
NodeAssert.equal(isOpenCodeNotFound({ status: 500, body: { name: "NotFoundError" } }), false);
|
||||
NodeAssert.equal(isOpenCodeNotFound({ name: "UpstreamNotFoundError", status: 500 }), false);
|
||||
// A "NotFound"-flavored name that isn't OpenCode's exact `NotFoundError`
|
||||
// is not a confirmed miss even without a sealing status.
|
||||
NodeAssert.equal(isOpenCodeNotFound({ name: "UpstreamNotFoundError" }), false);
|
||||
NodeAssert.equal(isOpenCodeNotFound({ cause: { name: "ProviderNotFoundError" } }), false);
|
||||
NodeAssert.equal(
|
||||
isOpenCodeNotFound(
|
||||
new Error("x", { cause: { status: 502, body: { name: "NotFoundError" } } }),
|
||||
),
|
||||
false,
|
||||
);
|
||||
// Other transient/auth/network failures must propagate too.
|
||||
NodeAssert.equal(isOpenCodeNotFound(new Error("boom", { cause: { status: 500 } })), false);
|
||||
NodeAssert.equal(isOpenCodeNotFound({ cause: { response: { status: 401 } } }), false);
|
||||
NodeAssert.equal(isOpenCodeNotFound(new Error("network error (no response)")), false);
|
||||
NodeAssert.equal(isOpenCodeNotFound(undefined), false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("treats lexically or physically identical directories as the same", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sameDirectory = (left: string, right: string) =>
|
||||
isSameOpenCodeDirectory(fileSystem, path, left, right);
|
||||
|
||||
// Lexical-only differences (trailing slash, dot segments) short-circuit
|
||||
// without touching the filesystem — the paths need not exist.
|
||||
NodeAssert.equal(yield* sameDirectory("/repo/project/", "/repo/project"), true);
|
||||
NodeAssert.equal(yield* sameDirectory("/repo/nested/../project", "/repo/project"), true);
|
||||
// Nonexistent paths degrade to the lexical comparison instead of failing.
|
||||
NodeAssert.equal(yield* sameDirectory("/repo/project", "/repo/other"), false);
|
||||
|
||||
// A symlinked cwd (the macOS `/tmp` → `/private/tmp` shape) resolves to
|
||||
// the directory it points at, so the two spellings compare equal.
|
||||
const base = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-opencode-dir-" });
|
||||
const real = path.join(base, "real");
|
||||
const link = path.join(base, "link");
|
||||
yield* fileSystem.makeDirectory(real);
|
||||
yield* fileSystem.symlink(real, link);
|
||||
NodeAssert.equal(yield* sameDirectory(link, real), true);
|
||||
NodeAssert.equal(yield* sameDirectory(link, path.join(base, "other")), false);
|
||||
}).pipe(Effect.scoped),
|
||||
);
|
||||
|
||||
it.effect("appends raw assistant text deltas and reconciles part update snapshots", () =>
|
||||
Effect.sync(() => {
|
||||
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
|
||||
|
||||
@@ -17,6 +17,8 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Scope from "effect/Scope";
|
||||
@@ -53,6 +55,114 @@ import * as Option from "effect/Option";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("opencode");
|
||||
|
||||
/**
|
||||
* Version tag stamped into the OpenCode resume cursor. Bump if the cursor
|
||||
* shape changes so stale-shaped cursors written by older builds are ignored
|
||||
* rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION).
|
||||
*/
|
||||
const OPENCODE_RESUME_VERSION = 1 as const;
|
||||
|
||||
/**
|
||||
* Decode a persisted resume cursor into the upstream `ses_…` id. Anything
|
||||
* that isn't a current-version cursor with a non-empty id means "no resume"
|
||||
* rather than an error. Re-adopting the session id IS the resume mechanism —
|
||||
* OpenCode scopes a conversation's history by session id.
|
||||
*/
|
||||
function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined {
|
||||
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
||||
return undefined;
|
||||
}
|
||||
const record = raw as Record<string, unknown>;
|
||||
if (record.schemaVersion !== OPENCODE_RESUME_VERSION) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof record.sessionId !== "string" || record.sessionId.trim().length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return { sessionId: record.sessionId.trim() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an error definitively reports a missing session. Only a confirmed
|
||||
* miss may silently start a fresh session; any other failure (the SDK client
|
||||
* is `throwOnError: true`, so `session.get` rejects on every non-2xx) must
|
||||
* propagate, or a transient blip resets a live thread to an empty one — the
|
||||
* #3604 silent context loss. Decides on structured signals only, never free
|
||||
* text: a numeric 404 or the exact `NotFoundError` name, found via a bounded walk
|
||||
* over `cause`/`body`/`error`/`data`. An explicit non-404 status seals its
|
||||
* subtree so a wrapped "NotFound" name can't reclassify a real failure.
|
||||
* Exported for unit testing.
|
||||
*/
|
||||
export function isOpenCodeNotFound(cause: unknown): boolean {
|
||||
const seen = new Set<unknown>();
|
||||
const queue: Array<unknown> = [cause];
|
||||
for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) {
|
||||
const node = queue.shift();
|
||||
if (node === null || typeof node !== "object" || seen.has(node)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(node);
|
||||
const record = node as Record<string, unknown>;
|
||||
|
||||
const response = record.response;
|
||||
const statuses = [
|
||||
record.status,
|
||||
record.statusCode,
|
||||
response !== null && typeof response === "object"
|
||||
? (response as { readonly status?: unknown }).status
|
||||
: undefined,
|
||||
].filter((status): status is number => typeof status === "number");
|
||||
if (statuses.includes(404)) {
|
||||
return true;
|
||||
}
|
||||
if (statuses.length > 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = record.name;
|
||||
if (typeof name === "string" && name.toLowerCase() === "notfounderror") {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (const key of ["cause", "body", "error", "data"] as const) {
|
||||
if (record[key] !== undefined) {
|
||||
queue.push(record[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two directory spellings name the same location. Raw string
|
||||
* equality misreads a trailing slash, `.`/`..` segment, or symlinked cwd
|
||||
* (macOS `/tmp` → `/private/tmp`) as a cwd change, needlessly forking the
|
||||
* session on every resume. Lexically equal paths short-circuit; otherwise
|
||||
* both sides go through `realPath`, each falling back to its lexical form
|
||||
* on failure (deleted directory, external-server path) — so the probe can
|
||||
* only widen matches, never split them. Takes the services as arguments so
|
||||
* adapter methods stay service-free. Exported for unit testing.
|
||||
*/
|
||||
export function isSameOpenCodeDirectory(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: Path.Path,
|
||||
left: string,
|
||||
right: string,
|
||||
): Effect.Effect<boolean> {
|
||||
const lexicalLeft = path.resolve(left);
|
||||
const lexicalRight = path.resolve(right);
|
||||
if (lexicalLeft === lexicalRight) {
|
||||
return Effect.succeed(true);
|
||||
}
|
||||
const canonicalize = (lexical: string) =>
|
||||
fileSystem.realPath(lexical).pipe(Effect.orElseSucceed(() => lexical));
|
||||
return Effect.zipWith(
|
||||
canonicalize(lexicalLeft),
|
||||
canonicalize(lexicalRight),
|
||||
(canonicalLeft, canonicalRight) => canonicalLeft === canonicalRight,
|
||||
);
|
||||
}
|
||||
|
||||
interface OpenCodeTurnSnapshot {
|
||||
readonly id: TurnId;
|
||||
readonly items: Array<unknown>;
|
||||
@@ -459,6 +569,10 @@ export function makeOpenCodeAdapter(
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const openCodeRuntime = yield* OpenCodeRuntime;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sameDirectory = (left: string, right: string) =>
|
||||
isSameOpenCodeDirectory(fileSystem, path, left, right);
|
||||
const nativeEventLogger =
|
||||
options?.nativeEventLogger ??
|
||||
(options?.nativeEventLogPath !== undefined
|
||||
@@ -1076,6 +1190,7 @@ export function makeOpenCodeAdapter(
|
||||
const serverUrl = openCodeSettings.serverUrl;
|
||||
const serverPassword = openCodeSettings.serverPassword;
|
||||
const directory = input.cwd ?? serverConfig.cwd;
|
||||
const resumeSessionId = parseOpenCodeResume(input.resumeCursor)?.sessionId;
|
||||
const existing = sessions.get(input.threadId);
|
||||
if (existing) {
|
||||
yield* stopOpenCodeContext(existing);
|
||||
@@ -1115,22 +1230,96 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
);
|
||||
}
|
||||
const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
|
||||
client.session.create({
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
if (!openCodeSession.data) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "session.create",
|
||||
detail: "OpenCode session.create returned no session payload.",
|
||||
});
|
||||
}
|
||||
// Resume: re-adopt the session named by the durable cursor —
|
||||
// OpenCode scopes history by session id. The probe recovers only
|
||||
// a confirmed not-found (start fresh); transport/auth/server
|
||||
// errors propagate instead of masking as a new empty session.
|
||||
const resolved = yield* Effect.gen(function* () {
|
||||
const adopted = resumeSessionId
|
||||
? yield* runOpenCodeSdk("session.get", () =>
|
||||
client.session.get({ sessionID: resumeSessionId }),
|
||||
).pipe(
|
||||
Effect.map((response) => response.data),
|
||||
Effect.catchIf(
|
||||
(cause) => isOpenCodeNotFound(cause),
|
||||
() => Effect.void,
|
||||
),
|
||||
)
|
||||
: undefined;
|
||||
|
||||
// Reuse in place only when the session still matches the
|
||||
// requested cwd; on a cwd change it is forked below instead.
|
||||
const reusable =
|
||||
adopted &&
|
||||
(!adopted.directory || (yield* sameDirectory(adopted.directory, directory)))
|
||||
? adopted
|
||||
: undefined;
|
||||
|
||||
if (reusable) {
|
||||
// Resume skips `session.create`, so re-assert the ruleset —
|
||||
// a runtime-mode change would otherwise leave the session on
|
||||
// its original permissions.
|
||||
yield* runOpenCodeSdk("session.update", () =>
|
||||
client.session.update({
|
||||
sessionID: reusable.id,
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
return { openCodeSession: reusable, created: false };
|
||||
}
|
||||
|
||||
// The session lives under a different cwd (e.g. the thread
|
||||
// moved into a git worktree). Fork it into the requested
|
||||
// directory instead of minting an empty one — the fork carries
|
||||
// the full history, so the follow-up keeps its context (#3604).
|
||||
if (adopted) {
|
||||
yield* Effect.logInfo(
|
||||
`OpenCode session '${adopted.id}' was created under a different working directory; forking into '${directory}' to preserve conversation history.`,
|
||||
);
|
||||
const forkedSession = yield* runOpenCodeSdk("session.fork", () =>
|
||||
client.session.fork({ sessionID: adopted.id, directory }),
|
||||
);
|
||||
const forked = forkedSession.data;
|
||||
if (!forked) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "session.fork",
|
||||
detail: "OpenCode session.fork returned no session payload.",
|
||||
});
|
||||
}
|
||||
yield* runOpenCodeSdk("session.update", () =>
|
||||
client.session.update({
|
||||
sessionID: forked.id,
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
return { openCodeSession: forked, created: true };
|
||||
}
|
||||
|
||||
if (resumeSessionId) {
|
||||
yield* Effect.logWarning(
|
||||
`OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`,
|
||||
);
|
||||
}
|
||||
const createdSession = yield* runOpenCodeSdk("session.create", () =>
|
||||
client.session.create({
|
||||
permission: buildOpenCodePermissionRules(input.runtimeMode),
|
||||
}),
|
||||
);
|
||||
if (!createdSession.data) {
|
||||
return yield* new OpenCodeRuntimeError({
|
||||
operation: "session.create",
|
||||
detail: "OpenCode session.create returned no session payload.",
|
||||
});
|
||||
}
|
||||
return { openCodeSession: createdSession.data, created: true };
|
||||
});
|
||||
|
||||
return {
|
||||
sessionScope,
|
||||
server,
|
||||
client,
|
||||
openCodeSession: openCodeSession.data,
|
||||
openCodeSession: resolved.openCodeSession,
|
||||
created: resolved.created,
|
||||
};
|
||||
}).pipe(Effect.provideService(Scope.Scope, sessionScope)),
|
||||
);
|
||||
@@ -1145,13 +1334,16 @@ export function makeOpenCodeAdapter(
|
||||
// and already inserted a session while we were awaiting async work.
|
||||
const raceWinner = sessions.get(input.threadId);
|
||||
if (raceWinner) {
|
||||
// Another call won the race – clean up the session we just created
|
||||
// (including the remote SDK session) and return the existing one.
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
started.client.session.abort({
|
||||
sessionID: started.openCodeSession.id,
|
||||
}),
|
||||
).pipe(Effect.ignore);
|
||||
// Another call won the race — clean up. Only abort the remote
|
||||
// session if we created it here; a resumed one is shared upstream
|
||||
// state the winner is now using.
|
||||
if (started.created) {
|
||||
yield* runOpenCodeSdk("session.abort", () =>
|
||||
started.client.session.abort({
|
||||
sessionID: started.openCodeSession.id,
|
||||
}),
|
||||
).pipe(Effect.ignore);
|
||||
}
|
||||
yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);
|
||||
return raceWinner.session;
|
||||
}
|
||||
@@ -1165,6 +1357,13 @@ export function makeOpenCodeAdapter(
|
||||
cwd: directory,
|
||||
...(input.modelSelection ? { model: input.modelSelection.model } : {}),
|
||||
threadId: input.threadId,
|
||||
// ProviderService persists this cursor and feeds it back into
|
||||
// `startSession` after the in-memory session is lost (reaper /
|
||||
// restart), so follow-ups continue the same conversation (#3604).
|
||||
resumeCursor: {
|
||||
schemaVersion: OPENCODE_RESUME_VERSION,
|
||||
sessionId: started.openCodeSession.id,
|
||||
},
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
@@ -1330,6 +1529,11 @@ export function makeOpenCodeAdapter(
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
// Re-surface the durable cursor on every turn so the persisted binding
|
||||
// is refreshed alongside last-seen/runtime state (mirrors Grok/Codex).
|
||||
...(context.session.resumeCursor !== undefined
|
||||
? { resumeCursor: context.session.resumeCursor }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user