Skip to content

Commit d50965c

Browse files
committed
fix(agents): talk to opencode over the v1 session endpoints
opencode 1.18.x serve drops provider auth (auth.json keys) from LLM requests made on behalf of sessions created through the v2 API (/api/session/*): the turn 401s at the provider, the assistant message lands with finish:"error", and no error event reaches the event stream, so SDK clients stall until timeout (anomalyco/opencode#47888, reported here as Waishnav#302). The v1 endpoints (/session/*) do not have this problem: the same serve instance, providers, and auth complete turns normally. Switch the opencode runtime to the v1 client while keeping the shared server launcher. Design notes: - create session via POST /session?directory=<root> - send prompt via POST /session/{id}/message with parts + agent + inline model (model refs use modelID; variant/effort supported) - v1 prompt blocks until the turn completes and returns the assistant message envelope with a durable assistant id; the wait loop now gates on that id appearing with a terminal finish state, so resumed sessions never mistake an earlier turn for the current one - response extraction prefers the prompt envelope text (the definitive current-turn result) and falls back to id-scoped history lookup - effort-only overrides resolve the session's current model via GET /session/{id} and apply the effort as a variant, restoring behavior lost in the initial migration - v1 GET /session/{id}/message returns chronological order (oldest first, verified against 1.18.29) - no reversal needed - health probe uses the cheap session list (v1 has no /health) - permission config trimmed to the fields the v1 agent schema accepts (edit/bash/webfetch/external_directory)
1 parent c34de7e commit d50965c

2 files changed

Lines changed: 271 additions & 279 deletions

File tree

‎src/local-agent-opencode.test.ts‎

Lines changed: 122 additions & 143 deletions
Original file line numberDiff line numberDiff line change
@@ -12,41 +12,43 @@ import { LocalAgentRuntimePool } from "./local-agent-runtime-pool.js";
1212
let sessionNumber = 0;
1313
const createInputs: unknown[] = [];
1414
const promptInputs: unknown[] = [];
15-
const switchInputs: unknown[] = [];
16-
const agentInputs: unknown[] = [];
15+
const getInputs: string[] = [];
1716
let healthAvailable = true;
17+
// Chronological in-memory history per session, mirroring the real v1
18+
// endpoint ordering (user, assistant, user, assistant...).
19+
const sessionHistories = new Map<string, unknown[]>();
1820
const client = {
19-
v2: {
20-
session: {
21+
session: {
22+
async list() {
23+
if (!healthAvailable) throw new Error("server unavailable");
24+
return { data: [] };
25+
},
2126
async create(input: unknown) {
2227
createInputs.push(input);
2328
sessionNumber += 1;
24-
return { data: { data: { id: `session_${sessionNumber}` } } };
29+
return { data: { id: `session_${sessionNumber}` } };
30+
},
31+
async get(input: unknown) {
32+
const sessionId = (input as { path: { id: string } }).path.id;
33+
getInputs.push(sessionId);
34+
return { data: { id: sessionId, modelID: "glm-5.2", providerID: "zhipuai-coding-plan" } };
2535
},
2636
async prompt(input: unknown) {
2737
promptInputs.push(input);
28-
return input;
29-
},
30-
async wait() {},
31-
async messages(input: unknown) {
32-
const sessionId = (input as { sessionID: string }).sessionID;
33-
return {
34-
data: { data: [{
35-
info: { role: "assistant" },
36-
parts: [{ type: "text", text: `response:${sessionId}` }],
37-
}] },
38+
const sessionId = (input as { path: { id: string } }).path.id;
39+
const assistantMessage = {
40+
info: { role: "assistant", id: `assistant_${sessionId}_${sessionHistories.get(sessionId)?.length ?? 0}`, finish: "stop", time: { created: 1, completed: 2 } },
41+
parts: [{ type: "text", text: `response:${sessionId}` }],
3842
};
43+
const history = sessionHistories.get(sessionId) ?? [];
44+
history.push({ info: { role: "user", id: `user_${history.length}` } }, assistantMessage);
45+
sessionHistories.set(sessionId, history);
46+
return { data: assistantMessage };
3947
},
40-
async get() {
41-
return { data: { data: { model: { providerID: "anthropic", id: "sonnet" } } } };
42-
},
43-
async switchAgent(input: unknown) { agentInputs.push(input); },
44-
async switchModel(input: unknown) { switchInputs.push(input); },
48+
async messages(input: unknown) {
49+
const sessionId = (input as { path: { id: string } }).path.id;
50+
return { data: sessionHistories.get(sessionId) ?? [] };
4551
},
46-
health: { async get() {
47-
if (!healthAvailable) throw new Error("server unavailable");
48-
return { data: { healthy: true } };
49-
} },
5052
},
5153
} as unknown as OpencodeClientLike;
5254
let factoryCalls = 0;
@@ -91,17 +93,21 @@ assert.equal(firstRecord.providerSessionId, "session_1");
9193
assert.equal(secondRecord.providerSessionId, "session_2");
9294
assert.equal(secondRecord.finalResponse, "response:session_2");
9395
assert.deepEqual(createInputs[0], {
94-
location: { directory: "/tmp/project" },
95-
agent: "devspace_allowed",
96-
model: { providerID: "anthropic", id: "sonnet", variant: "high" },
96+
query: { directory: "/tmp/project" },
97+
throwOnError: true,
9798
});
9899
assert.deepEqual(promptInputs[0], {
99-
sessionID: "session_1",
100-
prompt: { text: "first" },
100+
path: { id: "session_1" },
101+
body: {
102+
parts: [{ type: "text", text: "first" }],
103+
agent: "devspace_allowed",
104+
model: { providerID: "anthropic", modelID: "sonnet", variant: "high" },
105+
},
106+
throwOnError: true,
101107
});
102108

103109
let callbackSessionId: string | undefined;
104-
await pool.run(driver, {
110+
const effortResume = await pool.run(driver, {
105111
agentId: "agt_one",
106112
provider: "opencode",
107113
workspaceRoot: "/tmp/project",
@@ -114,55 +120,49 @@ await pool.run(driver, {
114120
onSessionId: (id) => { callbackSessionId = id; },
115121
});
116122
assert.equal(callbackSessionId, firstRecord.providerSessionId);
117-
assert.deepEqual(switchInputs[0], {
118-
sessionID: "session_1",
119-
model: { providerID: "anthropic", id: "sonnet", variant: "low" },
123+
assert.deepEqual(getInputs, ["session_1"], "effort-only resume resolves the current session model");
124+
assert.deepEqual(promptInputs.at(-1), {
125+
path: { id: "session_1" },
126+
body: {
127+
parts: [{ type: "text", text: "effort override" }],
128+
agent: "devspace_allowed",
129+
model: { providerID: "zhipuai-coding-plan", modelID: "glm-5.2", variant: "low" },
130+
},
131+
throwOnError: true,
120132
});
121-
assert.deepEqual(agentInputs[0], { sessionID: "session_1", agent: "devspace_allowed" });
133+
if (effortResume.isErr()) throw effortResume.error;
134+
assert.equal(effortResume.value.finalResponse, "response:session_1", "resumed turn returns the new turn's response");
122135

123-
let readinessActiveCalls = 0;
124-
let readinessWaitCalls = 0;
136+
let readinessMessageCalls = 0;
125137
const readinessRaceClient = {
126-
v2: {
127-
session: {
128-
async create() {
129-
return { data: { data: { id: "session_readiness" } } };
130-
},
131-
async switchAgent() {},
132-
async prompt() {
133-
return { data: { data: { id: "prompt_readiness" } } };
134-
},
135-
async wait() {
136-
readinessWaitCalls += 1;
137-
throw new Error("Session wait is not available yet");
138-
},
139-
async active() {
140-
readinessActiveCalls += 1;
141-
return {
142-
data: {
143-
data: readinessActiveCalls < 3
144-
? { session_readiness: { type: "running" } }
145-
: {},
138+
session: {
139+
async list() { return { data: [] }; },
140+
async create() {
141+
return { data: { id: "session_readiness" } };
142+
},
143+
async prompt() {
144+
return {
145+
data: {
146+
info: { role: "assistant", id: "assistant_readiness", finish: "stop" },
147+
parts: [],
148+
},
149+
};
150+
},
151+
async messages() {
152+
readinessMessageCalls += 1;
153+
// The first polls observe the turn's assistant message not yet durable;
154+
// later ones see it, mimicking a blocking prompt whose response lands
155+
// in history shortly after it returns.
156+
const data = readinessMessageCalls >= 3
157+
? [
158+
{
159+
info: { role: "assistant", id: "assistant_readiness", finish: "stop", time: { created: 1, completed: 2 } },
160+
parts: [{ type: "text", id: "part_readiness", text: "ready response" }],
146161
},
147-
};
148-
},
149-
async messages() {
150-
const data = readinessActiveCalls >= 3
151-
? [
152-
{ type: "user", id: "prompt_readiness" },
153-
{
154-
type: "assistant",
155-
id: "assistant_readiness",
156-
time: { created: 1, completed: 2 },
157-
finish: "stop",
158-
content: [{ type: "text", id: "part_readiness", text: "ready response" }],
159-
},
160-
]
161-
: [{ type: "user", id: "prompt_readiness" }];
162-
return { data: { data } };
163-
},
162+
]
163+
: [];
164+
return { data };
164165
},
165-
health: { async get() { return { data: { healthy: true } }; } },
166166
},
167167
} as unknown as OpencodeClientLike;
168168
const readinessPool = new LocalAgentRuntimePool();
@@ -179,54 +179,41 @@ assert.equal(readinessResult.isOk(), true, "OpenCode should wait for the active
179179
if (readinessResult.isOk()) {
180180
assert.equal(readinessResult.value.finalResponse, "ready response");
181181
}
182-
assert.equal(readinessWaitCalls, 0, "OpenCode should not rely on the unavailable wait endpoint");
183182
await readinessPool.close();
184183

185-
const longSessionRequests: Array<{ cursor?: string; order?: string }> = [];
184+
const longSessionRequests: Array<{ limit?: number }> = [];
186185
const longSessionClient = {
187-
v2: {
188-
session: {
189-
async create() {
190-
return { data: { data: { id: "session_long" } } };
191-
},
192-
async switchAgent() {},
193-
async prompt() {
194-
return { data: { data: { id: "prompt_long" } } };
195-
},
196-
async active() {
197-
return { data: { data: {} } };
198-
},
199-
async messages(input: unknown) {
200-
const request = input as { cursor?: string; order?: string };
201-
longSessionRequests.push({ cursor: request.cursor, order: request.order });
202-
if (!request.cursor) {
203-
return {
204-
data: {
205-
data: Array.from({ length: 100 }, (_, index) => ({
206-
type: "assistant",
207-
id: `old-assistant-${index}`,
208-
finish: "stop",
209-
content: [{ type: "text", text: `old response ${index}` }],
210-
})),
211-
cursor: { next: "long-session-next" },
212-
},
213-
};
214-
}
215-
return {
216-
data: {
217-
data: [
218-
{ type: "user", id: "prompt_long" },
219-
{
220-
type: "assistant",
221-
id: "assistant_long",
222-
finish: "stop",
223-
content: [{ type: "text", text: "long response" }],
224-
},
225-
],
226-
cursor: {},
186+
session: {
187+
async list() { return { data: [] }; },
188+
async create() {
189+
return { data: { id: "session_long" } };
190+
},
191+
async prompt() {
192+
return {
193+
data: {
194+
info: { role: "assistant", id: "assistant_long", finish: "stop" },
195+
parts: [{ type: "text", text: "long response" }],
196+
},
197+
};
198+
},
199+
async messages(input: unknown) {
200+
const request = (input as { query?: { limit?: number } }).query ?? {};
201+
longSessionRequests.push({ limit: request.limit });
202+
// v1 returns the full chronological history (oldest first). The mock
203+
// includes the current turn's assistant at the end and does not
204+
// artificially truncate (real servers honor a generous limit).
205+
return {
206+
data: [
207+
...Array.from({ length: 100 }, (_, index) => ({
208+
info: { role: "assistant", id: `old-assistant-${index}`, finish: "stop" },
209+
parts: [{ type: "text", text: `old response ${index}` }],
210+
})),
211+
{
212+
info: { role: "assistant", id: "assistant_long", finish: "stop" },
213+
parts: [{ type: "text", text: "long response" }],
227214
},
228-
};
229-
},
215+
],
216+
};
230217
},
231218
},
232219
} as unknown as OpencodeClientLike;
@@ -240,53 +227,45 @@ const longSessionResult = await longSessionPool.run(longSessionDriver, {
240227
provider: "opencode",
241228
workspaceRoot: "/tmp/project",
242229
}, { prompt: "long session", workspaceRoot: "/tmp/project" });
243-
assert.equal(longSessionResult.isOk(), true, "OpenCode should find completions past the first message page");
230+
assert.equal(longSessionResult.isOk(), true, "OpenCode should return the newest turn's response from a long history");
244231
if (longSessionResult.isOk()) {
245232
assert.equal(longSessionResult.value.finalResponse, "long response");
246233
}
247-
assert.ok(
248-
longSessionRequests.some((request) => request.cursor === "long-session-next"),
249-
"OpenCode should follow the continuation cursor",
250-
);
251234
await longSessionPool.close();
252235

253236
assert.equal(opencodeAgentFor("read_only"), "devspace_read_only");
254237
assert.equal(opencodeAgentFor("full_access"), "devspace_full_access");
255238
assert.deepEqual(opencodePermissionFor("allowed"), {
256-
read: "allow",
257239
edit: "allow",
258-
glob: "allow",
259-
grep: "allow",
260-
list: "allow",
261240
bash: "allow",
262-
task: "deny",
241+
webfetch: "allow",
263242
external_directory: "deny",
264243
});
265244
const readOnlyPermissions = opencodePermissionFor("read_only");
266245
assert.equal(typeof readOnlyPermissions === "object" ? readOnlyPermissions.bash : undefined, "deny");
267246
for (const writeMode of ["read_only", "allowed", "full_access"] as const) {
268247
const config = opencodeAgentConfig(writeMode);
269248
assert.equal(config.mode, "primary");
270-
assert.equal(typeof config.permission === "object" ? config.permission.task : undefined, "deny");
271249
}
272250

273251
let promptFailureCount = 0;
274252
const applicationErrorClient = {
275-
v2: {
276-
session: {
277-
async create() { return { data: { data: { id: "session_app_error" } } }; },
278-
async switchAgent() {},
279-
async prompt() {
280-
promptFailureCount += 1;
281-
if (promptFailureCount === 1) throw new Error("server rejected invalid input");
282-
return {};
283-
},
284-
async wait() {},
285-
async messages() {
286-
return { data: { data: [{ info: { role: "assistant" }, parts: [{ type: "text", text: "ok" }] }] } };
287-
},
253+
session: {
254+
async list() { return { data: [] }; },
255+
async create() { return { data: { id: "session_app_error" } }; },
256+
async prompt() {
257+
promptFailureCount += 1;
258+
if (promptFailureCount === 1) throw new Error("server rejected invalid input");
259+
return {
260+
data: {
261+
info: { role: "assistant", id: "assistant_app_error", finish: "stop" },
262+
parts: [{ type: "text", text: "ok" }],
263+
},
264+
};
265+
},
266+
async messages() {
267+
return { data: [{ info: { role: "assistant", id: "assistant_app_error", finish: "stop" }, parts: [{ type: "text", text: "ok" }] }] };
288268
},
289-
health: { async get() { return { data: { healthy: true } }; } },
290269
},
291270
} as unknown as OpencodeClientLike;
292271
const applicationErrorPool = new LocalAgentRuntimePool();

0 commit comments

Comments
 (0)