opencode-devin 2.0.0-beta.1 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/package.json +2 -1
- package/src/provider/cascade.ts +41 -18
- package/src/provider/index.ts +248 -38
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,92 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [2.0.1] — patch
|
|
4
|
+
|
|
5
|
+
AI-SDK v3 conformance hardening, image (`file`) parts, and a fix for tool
|
|
6
|
+
calls failing with `Schema validation failed`.
|
|
7
|
+
|
|
8
|
+
### Fixed
|
|
9
|
+
|
|
10
|
+
- **Full AI-SDK v3 conformance.** Verified assignable to `LanguageModelV3`
|
|
11
|
+
(`@ai-sdk/provider`) under `tsc --strict`.
|
|
12
|
+
- **Finish reason.** v3 unified = `stop|length|content-filter|tool-calls|
|
|
13
|
+
error|other`. Was emitting `content_filter`/`tool_calls`. Now mapped;
|
|
14
|
+
`raw` keeps the original. `raw` always present.
|
|
15
|
+
- **`doGenerate`.** Was `finishReason: string`. Now `{unified, raw}`.
|
|
16
|
+
Was dropping tool-calls + reasoning and rebuilding usage wrong. Now full
|
|
17
|
+
`LanguageModelV3GenerateResult`: `content` = reasoning? + text? +
|
|
18
|
+
tool-calls, `usage` = `LanguageModelV3Usage`, no `warnings` requirement.
|
|
19
|
+
- **Reasoning.** `reasoning-start` once, `reasoning-delta`*, then
|
|
20
|
+
`reasoning-end`, closed before any other block; no repeated starts.
|
|
21
|
+
- **Block ordering.** `reasoning-end` emitted before `text-start`/
|
|
22
|
+
`tool-input-start`; `text-end`; then `tool-input-end`+`tool-call`.
|
|
23
|
+
- **`topP`/`topK`.** passed through to Cascade `top_p`/`top_k`.
|
|
24
|
+
- **`abortSignal`.** propagated to `fetch` + streaming; abort → `error`
|
|
25
|
+
`AbortError` part.
|
|
26
|
+
- **`headers`.** merged into request (auth/protocol keys not overridable).
|
|
27
|
+
- **`toolChoice`.** `none`→no tools; `{type:'tool',toolName}`→only that
|
|
28
|
+
tool; `auto`→all; `required`→tools sent (can't force server choice).
|
|
29
|
+
- **`stopSequences`.** client-side truncation with holdback (streaming
|
|
30
|
+
split-safe), finish `stop`.
|
|
31
|
+
- **Tool results full.** v3 `LanguageModelV3ToolResultOutput`:
|
|
32
|
+
`text/json/error-text/error-json/execution-denied/content`, string,
|
|
33
|
+
`output.value`; `is_error` (Cascade field 9) on `role:'tool'`;
|
|
34
|
+
`LanguageModelV3ToolApprovalResponsePart`; `providerOptions`.
|
|
35
|
+
- **`LanguageModelV3ProviderTool`** filtered (can't execute server-side).
|
|
36
|
+
- **`LanguageModelV3FilePart` images.** image `file` parts → Cascade
|
|
37
|
+
`field 10 images`. **Wire format recovered from live `chisel` (Devin
|
|
38
|
+
CLI 3000.15.14) traffic via mitmproxy** (no proto/shipped schema):
|
|
39
|
+
repeated `ImageData { 1 base64_data, 2 mime_type }`. `data` =
|
|
40
|
+
`Uint8Array`|base64|`data:`URL→base64; `mediaType` `image/*`.
|
|
41
|
+
Non-image `file` parts → text note. http(s) URLs not pre-downloaded
|
|
42
|
+
(`supportedUrls={}`) → noted, not inlined. Works on user + tool.
|
|
43
|
+
|
|
44
|
+
### Known server-side limits (Cascade wire not verifiable here)
|
|
45
|
+
|
|
46
|
+
Not faked; ignored safely: `seed`, `presencePenalty`, `frequencyPenalty`
|
|
47
|
+
(no Cascade field), `stopSequences` server-side (done client-side),
|
|
48
|
+
`toolChoice` forcing (`required`/`tool` sent as tools; server picks),
|
|
49
|
+
**non-image `LanguageModelV3FilePart`** (audio/video/docs — Cascade image
|
|
50
|
+
wire is `image/*` only here), http(s) `file.data` URLs,
|
|
51
|
+
`LanguageModelV3ReasoningPart` input (not re-sent), `source`/`file`/
|
|
52
|
+
`approval-request` outputs, `providerExecuted`, `dynamic`, `includeRawChunks`,
|
|
53
|
+
`providerOptions` beyond `devin.*`. `tsc --strict` type-compat still passes.
|
|
54
|
+
- **AI-SDK v3 tool streaming order.** `Tool input delta before start`. The
|
|
55
|
+
stream emitted `tool-input-delta` without `tool-input-start`, never emitted
|
|
56
|
+
`tool-input-end`/`tool-call`, and dropped `toolName`. Now per tool call:
|
|
57
|
+
`tool-input-start` (first, with toolName) → `tool-input-delta`* →
|
|
58
|
+
`tool-input-end` → `tool-call` (`toolCallId`, `toolName`, `input` as the
|
|
59
|
+
stringified JSON args — `{}` when empty). Cascade `argsDelta` accumulated
|
|
60
|
+
per id.
|
|
61
|
+
- **`tool-call.input` must be a string.** v3 `LanguageModelV3ToolCall.input`
|
|
62
|
+
is *stringified* JSON; we were sending a parsed object. opencode parses it
|
|
63
|
+
as a string, and its failure path put the object in
|
|
64
|
+
`InvalidProviderOutput.body` (typed `string | undefined`) → the whole turn
|
|
65
|
+
died with `Error: Schema validation failed` right after the tool call, so
|
|
66
|
+
**every tool call broke**. Now the accumulated args are passed through as
|
|
67
|
+
the raw JSON string. Also fixed `doGenerate` content (`input` typed
|
|
68
|
+
`string`), and the stream is now typed
|
|
69
|
+
`AsyncGenerator<LanguageModelV3StreamPart>` (plus `doGenerate` →
|
|
70
|
+
`LanguageModelV3GenerateResult`) so `tsc` catches any future shape
|
|
71
|
+
regression instead of it reaching the user as `Schema validation failed`.
|
|
72
|
+
`usage.outputTokens.text` is now reported too.
|
|
73
|
+
- **Tool-result orphan `invalid_argument`.** `toCascadeMessages` mishandled
|
|
74
|
+
AI-SDK v3 `role:'tool'` messages (content `tool-result` parts): it emitted
|
|
75
|
+
an extra `role:'tool'` **without `toolCallId`** plus an empty parent, and
|
|
76
|
+
could leave tool results orphaned → Cascade `invalid_argument`
|
|
77
|
+
("There is an issue with this request, please try a different model.").
|
|
78
|
+
Now: one `role:'tool'` per result, `toolCallId` from part or message
|
|
79
|
+
(`toolCallId`/`tool_call_id`), `tool-result.output` → string
|
|
80
|
+
(`output.value` unwrapped), no empty extra message, `role:'tool'`-inside-
|
|
81
|
+
other hoisted. Tool-call id/name fallbacks.
|
|
82
|
+
|
|
83
|
+
## [2.0.0] — stable
|
|
84
|
+
|
|
85
|
+
Stable promotion of the `2.0.0-beta.x` line. Same code as `2.0.0-beta.1`
|
|
86
|
+
plus nothing else; `latest` dist-tag points here on npm. `2.0.0` is a
|
|
87
|
+
**breaking major** vs `0.2.x` (see `2.0.0-beta.0` below). Uncensored mode
|
|
88
|
+
and local-`file:///` docs from `2.0.0-beta.1` are included.
|
|
89
|
+
|
|
3
90
|
## [2.0.0-beta.1] — beta
|
|
4
91
|
|
|
5
92
|
### Added
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-devin",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "Devin (Cognition) provider for opencode — clean-room Cascade client, PKCE login, full model catalog",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
"@opencode/plugin": "2.4.2"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
+
"@ai-sdk/provider": "3.0.8",
|
|
49
50
|
"@types/bun": "1.4.5",
|
|
50
51
|
"typescript": "7.0.2"
|
|
51
52
|
}
|
package/src/provider/cascade.ts
CHANGED
|
@@ -79,23 +79,30 @@ async function* readFrames(stream: ReadableStream<Uint8Array>): AsyncGenerator<R
|
|
|
79
79
|
} finally { reader.releaseLock(); }
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
async function post(
|
|
82
|
+
async function post(
|
|
83
|
+
host: string, path: string, body: Uint8Array, jwt: string, stream: boolean,
|
|
84
|
+
signal?: AbortSignal, extraHeaders?: Record<string, string>,
|
|
85
|
+
) {
|
|
83
86
|
// user_jwt travels inside proto Metadata field 21 — no Authorization header.
|
|
87
|
+
const base: Record<string, string> = stream
|
|
88
|
+
? {
|
|
89
|
+
"content-type": "application/connect+proto",
|
|
90
|
+
"connect-protocol-version": "1",
|
|
91
|
+
"connect-content-encoding": "gzip",
|
|
92
|
+
"connect-accept-encoding": "gzip",
|
|
93
|
+
}
|
|
94
|
+
: {
|
|
95
|
+
"content-type": "application/proto",
|
|
96
|
+
"connect-protocol-version": "1",
|
|
97
|
+
authorization: `Bearer ${jwt}`,
|
|
98
|
+
};
|
|
99
|
+
// caller headers merged first; protocol/auth keys can't be overridden
|
|
100
|
+
const headers = { ...(extraHeaders ?? {}), ...base };
|
|
84
101
|
const res = await fetch(`${host}${RPC_BASE}/${path}`, {
|
|
85
102
|
method: "POST",
|
|
86
|
-
headers
|
|
87
|
-
? {
|
|
88
|
-
"content-type": "application/connect+proto",
|
|
89
|
-
"connect-protocol-version": "1",
|
|
90
|
-
"connect-content-encoding": "gzip",
|
|
91
|
-
"connect-accept-encoding": "gzip",
|
|
92
|
-
}
|
|
93
|
-
: {
|
|
94
|
-
"content-type": "application/proto",
|
|
95
|
-
"connect-protocol-version": "1",
|
|
96
|
-
authorization: `Bearer ${jwt}`,
|
|
97
|
-
},
|
|
103
|
+
headers,
|
|
98
104
|
body: stream ? frame(body, true) : body,
|
|
105
|
+
signal,
|
|
99
106
|
});
|
|
100
107
|
if (!res.ok) {
|
|
101
108
|
const text = await res.text().catch(() => "");
|
|
@@ -239,6 +246,10 @@ export interface ChatMessage {
|
|
|
239
246
|
content: string;
|
|
240
247
|
toolCallId?: string;
|
|
241
248
|
toolCalls?: { id: string; name: string; args: string }[];
|
|
249
|
+
/** mark tool result as error (Cascade prompt field 9). */
|
|
250
|
+
isError?: boolean;
|
|
251
|
+
/** images for Cascade field-10 `images`: base64_data + mime_type. */
|
|
252
|
+
images?: { base64: string; mimeType: string }[];
|
|
242
253
|
}
|
|
243
254
|
|
|
244
255
|
export interface ChatRequest {
|
|
@@ -248,7 +259,13 @@ export interface ChatRequest {
|
|
|
248
259
|
tools?: { name: string; description: string; parameters: string }[]; // JSON schema as string
|
|
249
260
|
maxTokens?: number;
|
|
250
261
|
temperature?: number;
|
|
262
|
+
topP?: number;
|
|
263
|
+
topK?: number;
|
|
251
264
|
cascadeId?: string;
|
|
265
|
+
/** AbortSignal — propagated to fetch + stream reading. */
|
|
266
|
+
signal?: AbortSignal;
|
|
267
|
+
/** Extra request headers (merged; auth/content-type not overridable). */
|
|
268
|
+
headers?: Record<string, string>;
|
|
252
269
|
/** Prepend the uncensored preamble ahead of the system block. */
|
|
253
270
|
uncensored?: boolean;
|
|
254
271
|
}
|
|
@@ -326,6 +343,12 @@ function encodeChatPrompt(msg: ChatMessage, system?: string): Uint8Array {
|
|
|
326
343
|
fVarint(5, 1),
|
|
327
344
|
];
|
|
328
345
|
if (msg.toolCallId) parts.push(fString(7, msg.toolCallId));
|
|
346
|
+
if (msg.isError) parts.push(fVarint(9, 1));
|
|
347
|
+
// field 10 `images` (verified vs chisel live traffic): repeated msg
|
|
348
|
+
// ImageData { 1 base64_data, 2 mime_type }
|
|
349
|
+
for (const img of msg.images ?? []) {
|
|
350
|
+
parts.push(fMessage(10, concatProto([fString(1, img.base64), fString(2, img.mimeType)])));
|
|
351
|
+
}
|
|
329
352
|
for (const tc of msg.toolCalls ?? []) parts.push(fMessage(6, encodeToolCallProto(tc)));
|
|
330
353
|
return concatProto(parts);
|
|
331
354
|
}
|
|
@@ -333,7 +356,7 @@ function encodeChatPrompt(msg: ChatMessage, system?: string): Uint8Array {
|
|
|
333
356
|
// CompletionConfiguration (field 8):
|
|
334
357
|
// 1 num_completions | 2 max_tokens | 3 max_newlines | 5 temperature(float64)
|
|
335
358
|
// 6 first_temperature | 7 top_k | 8 top_p(float64) | 11 fim_eot_prob_threshold
|
|
336
|
-
function encodeCompletionConfiguration(opts: { maxTokens?: number; temperature?: number }): Uint8Array {
|
|
359
|
+
function encodeCompletionConfiguration(opts: { maxTokens?: number; temperature?: number; topP?: number; topK?: number }): Uint8Array {
|
|
337
360
|
const f64 = (field: number, v: number): Uint8Array => {
|
|
338
361
|
const b = new Uint8Array(8);
|
|
339
362
|
new DataView(b.buffer).setFloat64(0, v, true);
|
|
@@ -345,8 +368,8 @@ function encodeCompletionConfiguration(opts: { maxTokens?: number; temperature?:
|
|
|
345
368
|
fVarint(3, 128_000),
|
|
346
369
|
f64(5, opts.temperature ?? 0.7),
|
|
347
370
|
f64(6, 0.95),
|
|
348
|
-
fVarint(7, 50),
|
|
349
|
-
f64(8, 1.0),
|
|
371
|
+
fVarint(7, opts.topK ?? 50),
|
|
372
|
+
f64(8, opts.topP ?? 1.0),
|
|
350
373
|
f64(11, 1.0),
|
|
351
374
|
]);
|
|
352
375
|
}
|
|
@@ -425,13 +448,13 @@ export async function* streamChat(
|
|
|
425
448
|
tools: req.tools?.length ?? 0, host: cascadeHost, cascadeId: req.cascadeId,
|
|
426
449
|
});
|
|
427
450
|
|
|
428
|
-
let res = await post(cascadeHost, "GetChatMessage", body, jwt, true).catch(async (e) => {
|
|
451
|
+
let res = await post(cascadeHost, "GetChatMessage", body, jwt, true, req.signal, req.headers).catch(async (e) => {
|
|
429
452
|
if (e.status === 401) { // expired jwt — re-mint and retry once
|
|
430
453
|
log.warn("chat.401_remint", { modelUid: req.modelUid });
|
|
431
454
|
creds.invalidate();
|
|
432
455
|
({ jwt, cascadeHost } = await creds.jwt());
|
|
433
456
|
body = encodeChatRequest(req, creds, jwt);
|
|
434
|
-
return post(cascadeHost, "GetChatMessage", body, jwt, true);
|
|
457
|
+
return post(cascadeHost, "GetChatMessage", body, jwt, true, req.signal, req.headers);
|
|
435
458
|
}
|
|
436
459
|
log.error("chat.post_fail", { modelUid: req.modelUid, err: scrubSecrets(String(e)) });
|
|
437
460
|
throw e;
|
package/src/provider/index.ts
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
import { DevinCredentials } from "./auth.js";
|
|
9
9
|
import { streamChat, fetchCatalog, type ChatMessage, type UsageBlock } from "./cascade.js";
|
|
10
10
|
import { log } from "./log.js";
|
|
11
|
+
import type {
|
|
12
|
+
LanguageModelV3StreamPart,
|
|
13
|
+
LanguageModelV3GenerateResult,
|
|
14
|
+
} from "@ai-sdk/provider";
|
|
11
15
|
|
|
12
16
|
export { fetchCatalog };
|
|
13
17
|
|
|
@@ -24,6 +28,11 @@ interface ProviderSettings {
|
|
|
24
28
|
sessionToken?: string; // devin-session-token$<jwt> — full credential
|
|
25
29
|
}
|
|
26
30
|
|
|
31
|
+
/** AI-SDK v3 unified finish reason. */
|
|
32
|
+
export type V3UnifiedFinish =
|
|
33
|
+
| "stop" | "length" | "content-filter" | "tool-calls" | "error" | "other";
|
|
34
|
+
export type V3FinishReason = { unified: V3UnifiedFinish; raw: string | undefined };
|
|
35
|
+
|
|
27
36
|
export function createDevinProvider(options: ProviderSettings = {}) {
|
|
28
37
|
const token = options.sessionToken ?? options.apiKey ?? process.env.DEVIN_API_KEY ?? "";
|
|
29
38
|
const creds = new DevinCredentials(token);
|
|
@@ -50,6 +59,56 @@ export function model(modelID: string, settings: ProviderSettings = {}) {
|
|
|
50
59
|
*/
|
|
51
60
|
const EFFORT_LEVELS = ["none","minimal","low","medium","high","xhigh","max"] as const;
|
|
52
61
|
|
|
62
|
+
/** v3 LanguageModelV3FilePart → Cascade ImageData {base64, mimeType}.
|
|
63
|
+
* `data` = Uint8Array | base64-string | data:URL. Non-image media returns
|
|
64
|
+
* undefined (Cascade image wire is image-only here); http(s) URLs can't be
|
|
65
|
+
* inlined without fetch (supportedUrls={} so opencode pre-downloads). */
|
|
66
|
+
function toCascadeImage(p: any): { base64: string; mimeType: string } | undefined {
|
|
67
|
+
const mediaType: string = p.mediaType ?? p.mimeType ?? "application/octet-stream";
|
|
68
|
+
if (!/^image\//i.test(mediaType)) return undefined;
|
|
69
|
+
let data = p.data ?? p.content ?? p.value;
|
|
70
|
+
let base64: string | undefined;
|
|
71
|
+
if (data instanceof Uint8Array) base64 = Buffer.from(data).toString("base64");
|
|
72
|
+
else if (typeof data === "string") {
|
|
73
|
+
if (data.startsWith("data:")) {
|
|
74
|
+
const comma = data.indexOf(",");
|
|
75
|
+
const meta = data.slice(5, comma);
|
|
76
|
+
const payload = comma >= 0 ? data.slice(comma + 1) : "";
|
|
77
|
+
base64 = meta.includes(";base64") ? payload : Buffer.from(decodeURIComponent(payload)).toString("base64");
|
|
78
|
+
const mt = meta.split(";")[0]; return { base64, mimeType: mt || mediaType };
|
|
79
|
+
}
|
|
80
|
+
if (/^https?:\/\//i.test(data)) return undefined; // URL not pre-downloaded
|
|
81
|
+
base64 = data; // assume already base64
|
|
82
|
+
}
|
|
83
|
+
if (!base64) return undefined;
|
|
84
|
+
return { base64, mimeType: mediaType };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** tool-result output → plain string for the `tool` prompt (field 3).
|
|
88
|
+
* Full v3 LanguageModelV3ToolResultOutput coverage:
|
|
89
|
+
* text→value, json→JSON, error-text→value, error-json→JSON,
|
|
90
|
+
* execution-denied→reason/note, content→flatten parts (text/image),
|
|
91
|
+
* string passthrough. */
|
|
92
|
+
function outputText(o: any): string {
|
|
93
|
+
if (o == null) return "";
|
|
94
|
+
if (typeof o === "string") return o;
|
|
95
|
+
if (Array.isArray(o)) return o.map(outputText).join("\n");
|
|
96
|
+
const t = o.type;
|
|
97
|
+
if (t === "execution-denied") return `[execution denied${o.reason ? `: ${o.reason}` : ""}]`;
|
|
98
|
+
if (t === "content") return (o.value ?? []).map((p: any) =>
|
|
99
|
+
p?.type === "text" ? p.text : p?.type === "image" ? "[image]" : outputText(p)).join("\n");
|
|
100
|
+
if (t === "image" || t === "image-data") return "[image]";
|
|
101
|
+
if (t === "file" || t === "file-data" || t === "media") return `[file${o.mediaType ? ` ${o.mediaType}` : ""}]`;
|
|
102
|
+
if (o.value !== undefined) return typeof o.value === "string" ? o.value : JSON.stringify(o.value);
|
|
103
|
+
return JSON.stringify(o);
|
|
104
|
+
}
|
|
105
|
+
/** Is this tool-result output an error variant? (v3 error-text/error-json/denied) */
|
|
106
|
+
function outputIsError(o: any): boolean {
|
|
107
|
+
if (o == null) return false;
|
|
108
|
+
const t = o.type;
|
|
109
|
+
return t === "error-text" || t === "error-json" || t === "execution-denied";
|
|
110
|
+
}
|
|
111
|
+
|
|
53
112
|
function effortIndex(segs: string[]): number {
|
|
54
113
|
for (let i = segs.length - 1; i > 0; i--) {
|
|
55
114
|
if ((EFFORT_LEVELS as readonly string[]).includes(segs[i])) return i;
|
|
@@ -107,6 +166,7 @@ export class CascadeLanguageModel {
|
|
|
107
166
|
) {}
|
|
108
167
|
|
|
109
168
|
private toCascadeMessages(prompt: unknown[]): { system?: string; messages: ChatMessage[] } {
|
|
169
|
+
// tool-result output → plain string for the `tool` prompt (field 3).
|
|
110
170
|
let system: string | undefined;
|
|
111
171
|
const messages: ChatMessage[] = [];
|
|
112
172
|
for (const m of prompt as any[]) {
|
|
@@ -118,70 +178,143 @@ export class CascadeLanguageModel {
|
|
|
118
178
|
system = (system ? system + "\n\n" : "") + text;
|
|
119
179
|
continue;
|
|
120
180
|
}
|
|
121
|
-
|
|
122
|
-
|
|
181
|
+
// AI-SDK v3 `tool` message: content is tool-result part(s) (or raw
|
|
182
|
+
// string). Emit ONE role:"tool" per result WITH toolCallId matching a
|
|
183
|
+
// preceding assistant tool-call — an orphan tool msg = server
|
|
184
|
+
// invalid_argument. Never push an extra empty parent.
|
|
185
|
+
if (m.role === "tool") {
|
|
186
|
+
const contentArr = Array.isArray(m.content) ? m.content : [];
|
|
187
|
+
const results = contentArr.filter((p: any) => p?.type === "tool-result");
|
|
188
|
+
if (results.length === 0) {
|
|
189
|
+
messages.push({
|
|
190
|
+
role: "tool",
|
|
191
|
+
toolCallId: m.toolCallId ?? m.tool_call_id,
|
|
192
|
+
content: typeof m.content === "string" ? m.content : outputText(m.content ?? ""),
|
|
193
|
+
isError: !!m.isError,
|
|
194
|
+
});
|
|
195
|
+
} else {
|
|
196
|
+
for (const p of results) {
|
|
197
|
+
messages.push({
|
|
198
|
+
role: "tool",
|
|
199
|
+
toolCallId: p.toolCallId ?? p.tool_call_id ?? m.toolCallId ?? m.tool_call_id,
|
|
200
|
+
content: outputText(p.output ?? p.result ?? p.content ?? ""),
|
|
201
|
+
isError: outputIsError(p.output ?? p.result),
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// v3 tool-approval-response parts — recorded as tool results.
|
|
206
|
+
for (const p of contentArr.filter((x: any) => x?.type === "tool-approval-response")) {
|
|
207
|
+
messages.push({
|
|
208
|
+
role: "tool",
|
|
209
|
+
toolCallId: p.toolCallId ?? p.approvalId,
|
|
210
|
+
content: p.approved ? "[approved]" : `[denied${p.reason ? `: ${p.reason}` : ""}]`,
|
|
211
|
+
isError: p.approved !== true,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
const role = m.role === "assistant" ? "assistant" : "user";
|
|
123
217
|
const parts: string[] = [];
|
|
124
218
|
const toolCalls: { id: string; name: string; args: string }[] = [];
|
|
219
|
+
const images: { base64: string; mimeType: string }[] = [];
|
|
125
220
|
if (typeof m.content === "string") parts.push(m.content);
|
|
126
221
|
const contentArr = Array.isArray(m.content) ? m.content : [];
|
|
127
222
|
for (const p of contentArr) {
|
|
128
|
-
if (p.type === "text") parts.push(p.text);
|
|
223
|
+
if (p.type === "text") parts.push(p.text ?? "");
|
|
224
|
+
// v3 LanguageModelV3FilePart — image/data → Cascade field-10 images.
|
|
225
|
+
// (assistant role accepted by server; works on user + tool too.)
|
|
226
|
+
else if (p.type === "file") {
|
|
227
|
+
const img = toCascadeImage(p);
|
|
228
|
+
if (img) images.push(img);
|
|
229
|
+
else if (typeof p.filename === "string" || p.mediaType) {
|
|
230
|
+
parts.push(`[file${p.filename ? ` ${p.filename}` : p.mediaType ? ` ${p.mediaType}` : ""}]`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
129
233
|
else if (p.type === "tool-call") {
|
|
130
|
-
toolCalls.push({
|
|
234
|
+
toolCalls.push({
|
|
235
|
+
id: p.toolCallId ?? p.tool_call_id ?? crypto.randomUUID(),
|
|
236
|
+
name: p.toolName ?? p.tool_name ?? p.name,
|
|
237
|
+
args: typeof p.args === "string" ? p.args : JSON.stringify(p.input ?? p.args ?? {}),
|
|
238
|
+
});
|
|
131
239
|
} else if (p.type === "tool-result") {
|
|
132
|
-
// tool
|
|
240
|
+
// tool-result nested inside another message — hoist to role:"tool".
|
|
133
241
|
messages.push({
|
|
134
242
|
role: "tool",
|
|
135
|
-
toolCallId: p.toolCallId,
|
|
136
|
-
content:
|
|
243
|
+
toolCallId: p.toolCallId ?? p.tool_call_id,
|
|
244
|
+
content: outputText(p.output ?? p.result ?? p.content ?? ""),
|
|
245
|
+
isError: outputIsError(p.output ?? p.result),
|
|
137
246
|
});
|
|
138
|
-
continue;
|
|
139
247
|
}
|
|
140
248
|
}
|
|
141
|
-
messages.push({
|
|
249
|
+
messages.push({
|
|
250
|
+
role,
|
|
251
|
+
content: parts.join(""),
|
|
252
|
+
toolCalls: toolCalls.length ? toolCalls : undefined,
|
|
253
|
+
images: images.length ? images : undefined,
|
|
254
|
+
});
|
|
142
255
|
}
|
|
143
256
|
return { system, messages };
|
|
144
257
|
}
|
|
145
258
|
|
|
146
|
-
async doGenerate(options: any) {
|
|
259
|
+
async doGenerate(options: any): Promise<LanguageModelV3GenerateResult> {
|
|
260
|
+
// Non-streaming: accumulate full v3 content + reuse streamParts' finish.
|
|
147
261
|
let text = "";
|
|
148
|
-
let
|
|
149
|
-
|
|
262
|
+
let reasoning = "";
|
|
263
|
+
// v3 LanguageModelV3ToolCall.input is a *stringified* JSON object.
|
|
264
|
+
const toolCalls: { type: "tool-call"; toolCallId: string; toolName: string; input: string }[] = [];
|
|
265
|
+
let finishReason: V3FinishReason = { unified: "stop", raw: undefined };
|
|
266
|
+
let usage: any;
|
|
150
267
|
for await (const part of this.streamParts(options)) {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
output: part.usage?.outputTokens?.total,
|
|
157
|
-
};
|
|
268
|
+
switch (part.type) {
|
|
269
|
+
case "text-delta": text += part.delta; break;
|
|
270
|
+
case "reasoning-delta": reasoning += part.delta; break;
|
|
271
|
+
case "tool-call": toolCalls.push({ type: "tool-call", toolCallId: part.toolCallId, toolName: part.toolName, input: part.input }); break;
|
|
272
|
+
case "finish": finishReason = part.finishReason; usage = part.usage; break;
|
|
158
273
|
}
|
|
159
274
|
}
|
|
275
|
+
const content: any[] = [];
|
|
276
|
+
if (reasoning) content.push({ type: "reasoning", text: reasoning });
|
|
277
|
+
if (text) content.push({ type: "text", text });
|
|
278
|
+
content.push(...toolCalls);
|
|
160
279
|
return {
|
|
161
|
-
content
|
|
280
|
+
content,
|
|
162
281
|
finishReason,
|
|
163
|
-
usage: {
|
|
164
|
-
inputTokens: { total:
|
|
165
|
-
outputTokens: { total:
|
|
282
|
+
usage: usage ?? {
|
|
283
|
+
inputTokens: { total: 0, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
|
|
284
|
+
outputTokens: { total: 0, reasoning: undefined },
|
|
166
285
|
},
|
|
167
286
|
warnings: [],
|
|
168
287
|
};
|
|
169
288
|
}
|
|
170
289
|
|
|
171
|
-
private async *streamParts(options: any): AsyncGenerator<
|
|
290
|
+
private async *streamParts(options: any): AsyncGenerator<LanguageModelV3StreamPart> {
|
|
172
291
|
log.debug("model.doStream", {
|
|
173
292
|
modelId: this.modelId, optKeys: Object.keys(options),
|
|
174
293
|
providerOptionKeys: Object.keys(options.providerOptions ?? {}),
|
|
175
294
|
ctorEffort: this.effort ?? null,
|
|
176
295
|
});
|
|
177
296
|
const { system, messages } = this.toCascadeMessages(options.prompt ?? []);
|
|
178
|
-
|
|
297
|
+
// v3 toolChoice: 'none'→no tools; {type:'tool',toolName}→only that tool;
|
|
298
|
+
// 'auto'/'required'→all tools (can't force server-side choice; see docs).
|
|
299
|
+
// provider-defined tools (LanguageModelV3ProviderTool) can't execute
|
|
300
|
+
// server-side → only type:'function' tools are passed.
|
|
301
|
+
const toolChoice = options.toolChoice;
|
|
302
|
+
let tools = (options.tools ?? [])
|
|
179
303
|
.filter((t: any) => t.type === "function")
|
|
180
304
|
.map((t: any) => ({
|
|
181
305
|
name: t.name,
|
|
182
306
|
description: t.description ?? "",
|
|
183
307
|
parameters: JSON.stringify(t.inputSchema ?? {}),
|
|
184
308
|
}));
|
|
309
|
+
if (toolChoice?.type === "none") tools = [];
|
|
310
|
+
else if (toolChoice?.type === "tool" && toolChoice.toolName) {
|
|
311
|
+
tools = tools.filter((t: any) => t.name === toolChoice.toolName);
|
|
312
|
+
}
|
|
313
|
+
// v3 stopSequences — applied client-side to generated text (Cascade has no
|
|
314
|
+
// server stop-list field we can verify).
|
|
315
|
+
const stopSequences: string[] = Array.isArray(options.stopSequences)
|
|
316
|
+
? options.stopSequences.filter((s: any) => typeof s === "string" && s.length > 0)
|
|
317
|
+
: [];
|
|
185
318
|
|
|
186
319
|
// Effort resolution order: providerOptions (opencode sets
|
|
187
320
|
// devin.reasoningEffort from the #variant) then constructor effort.
|
|
@@ -250,7 +383,11 @@ export class CascadeLanguageModel {
|
|
|
250
383
|
tools: tools.length ? tools : undefined,
|
|
251
384
|
temperature: options.temperature,
|
|
252
385
|
maxTokens: options.maxOutputTokens,
|
|
386
|
+
topP: options.topP,
|
|
387
|
+
topK: options.topK,
|
|
253
388
|
uncensored,
|
|
389
|
+
signal: options.abortSignal,
|
|
390
|
+
headers: options.headers,
|
|
254
391
|
},
|
|
255
392
|
this.creds,
|
|
256
393
|
);
|
|
@@ -271,11 +408,23 @@ export class CascadeLanguageModel {
|
|
|
271
408
|
cacheRead: u.cachedInput,
|
|
272
409
|
cacheWrite: u.cacheCreation,
|
|
273
410
|
},
|
|
274
|
-
outputTokens: {
|
|
411
|
+
outputTokens: {
|
|
412
|
+
total: u.output ?? 0,
|
|
413
|
+
text: Math.max(0, (u.output ?? 0) - (u.reasoning ?? 0)),
|
|
414
|
+
reasoning: u.reasoning,
|
|
415
|
+
},
|
|
275
416
|
});
|
|
417
|
+
// Cascade reason → AI-SDK v3 `unified`:
|
|
418
|
+
// stop→stop, length→length, tool_calls→tool-calls,
|
|
419
|
+
// content_filter→content-filter, error→error, else→other. raw keeps raw.
|
|
420
|
+
const V3_FINISH: Record<string, V3UnifiedFinish> = {
|
|
421
|
+
stop: "stop", length: "length", "tool-calls": "tool-calls", "tool_calls": "tool-calls",
|
|
422
|
+
"content-filter": "content-filter", "content_filter": "content-filter",
|
|
423
|
+
error: "error", other: "other",
|
|
424
|
+
};
|
|
276
425
|
const mkFinish = (reason: string, u: Usage) => ({
|
|
277
|
-
type: "finish",
|
|
278
|
-
finishReason: { unified: reason, raw: reason },
|
|
426
|
+
type: "finish" as const,
|
|
427
|
+
finishReason: { unified: V3_FINISH[reason] ?? "other", raw: reason } satisfies V3FinishReason,
|
|
279
428
|
usage: mkUsage(u),
|
|
280
429
|
});
|
|
281
430
|
|
|
@@ -283,26 +432,73 @@ export class CascadeLanguageModel {
|
|
|
283
432
|
let finishReason = "stop";
|
|
284
433
|
let reported: Usage = {};
|
|
285
434
|
let producedChars = 0;
|
|
435
|
+
// AI-SDK v3 tool streaming order per tool call:
|
|
436
|
+
// tool-input-start → tool-input-delta* → tool-input-end → tool-call
|
|
437
|
+
// Cascade `tool_call` frames carry id + name + argsDelta; track pending
|
|
438
|
+
// calls, emit start first, accumulate args, close at stream end.
|
|
439
|
+
const pendingTools = new Map<string, { id: string; name: string; args: string }>();
|
|
440
|
+
let reasoningStarted = false;
|
|
441
|
+
// close reasoning block once, BEFORE starting any other block
|
|
442
|
+
const closeReasoning = function* (): Generator<any> {
|
|
443
|
+
if (reasoningStarted) { reasoningStarted = false; yield { type: "reasoning-end", id: "r1" }; }
|
|
444
|
+
};
|
|
445
|
+
// client-side stopSequences with holdback so a seq split across chunks
|
|
446
|
+
// still matches; output before it is emitted, seq + after are dropped.
|
|
447
|
+
const stopMaxLen = stopSequences.reduce((mx, s) => Math.max(mx, s.length), 0);
|
|
448
|
+
let stopHit = false;
|
|
449
|
+
let stopBuf = "";
|
|
450
|
+
const emitText = function* (s: string): Generator<any> {
|
|
451
|
+
if (!s) return;
|
|
452
|
+
if (!textId) { textId = "t1"; yield { type: "text-start", id: textId }; }
|
|
453
|
+
yield { type: "text-delta", id: textId, delta: s };
|
|
454
|
+
};
|
|
286
455
|
for await (const d of stream) {
|
|
456
|
+
if (stopHit && d.type !== "usage" && d.type !== "finish") continue;
|
|
287
457
|
switch (d.type) {
|
|
288
458
|
case "thinking":
|
|
289
459
|
producedChars += d.text.length;
|
|
290
|
-
|
|
460
|
+
// v3: ONE reasoning-start per id; closed with reasoning-end.
|
|
461
|
+
if (!reasoningStarted) { reasoningStarted = true; yield { type: "reasoning-start", id: "r1" }; }
|
|
291
462
|
yield { type: "reasoning-delta", id: "r1", delta: d.text };
|
|
292
463
|
break;
|
|
293
|
-
case "text":
|
|
464
|
+
case "text": {
|
|
294
465
|
producedChars += d.text.length;
|
|
295
|
-
if (!textId)
|
|
296
|
-
|
|
466
|
+
if (!textId) yield* closeReasoning();
|
|
467
|
+
if (stopSequences.length === 0) { yield* emitText(d.text); break; }
|
|
468
|
+
stopBuf += d.text;
|
|
469
|
+
// earliest stop match in buffer
|
|
470
|
+
let earliest = -1;
|
|
471
|
+
for (const s of stopSequences) {
|
|
472
|
+
const i = stopBuf.indexOf(s);
|
|
473
|
+
if (i >= 0 && (earliest < 0 || i < earliest)) earliest = i;
|
|
474
|
+
}
|
|
475
|
+
if (earliest >= 0) {
|
|
476
|
+
yield* emitText(stopBuf.slice(0, earliest));
|
|
477
|
+
stopHit = true; stopBuf = "";
|
|
478
|
+
break;
|
|
479
|
+
}
|
|
480
|
+
const keep = stopMaxLen > 0 ? stopMaxLen - 1 : 0;
|
|
481
|
+
const safeLen = Math.max(0, stopBuf.length - keep);
|
|
482
|
+
yield* emitText(stopBuf.slice(0, safeLen));
|
|
483
|
+
stopBuf = stopBuf.slice(safeLen);
|
|
297
484
|
break;
|
|
298
|
-
|
|
485
|
+
}
|
|
486
|
+
case "tool_call": {
|
|
299
487
|
producedChars += (d.argsDelta ?? "").length;
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
delta
|
|
304
|
-
|
|
488
|
+
const cur = pendingTools.get(d.id) ?? { id: d.id, name: "", args: "" };
|
|
489
|
+
if (d.name) cur.name = d.name;
|
|
490
|
+
if (!pendingTools.has(d.id)) {
|
|
491
|
+
// start BEFORE any delta — v3 requires it; close reasoning first
|
|
492
|
+
yield* closeReasoning();
|
|
493
|
+
yield { type: "tool-input-start", id: d.id, toolName: cur.name };
|
|
494
|
+
}
|
|
495
|
+
if (d.argsDelta) {
|
|
496
|
+
cur.args += d.argsDelta;
|
|
497
|
+
yield { type: "tool-input-delta", id: d.id, delta: d.argsDelta };
|
|
498
|
+
}
|
|
499
|
+
pendingTools.set(d.id, cur);
|
|
305
500
|
break;
|
|
501
|
+
}
|
|
306
502
|
case "finish":
|
|
307
503
|
finishReason = d.reason;
|
|
308
504
|
break;
|
|
@@ -314,7 +510,21 @@ export class CascadeLanguageModel {
|
|
|
314
510
|
break;
|
|
315
511
|
}
|
|
316
512
|
}
|
|
513
|
+
// flush any held-back text not part of a stop sequence
|
|
514
|
+
if (!stopHit && stopBuf) yield* emitText(stopBuf);
|
|
515
|
+
if (stopHit) finishReason = "stop";
|
|
317
516
|
if (textId) yield { type: "text-end", id: textId };
|
|
517
|
+
yield* closeReasoning();
|
|
518
|
+
// Close every started tool call in arrival order.
|
|
519
|
+
for (const t of pendingTools.values()) {
|
|
520
|
+
yield { type: "tool-input-end", id: t.id };
|
|
521
|
+
yield {
|
|
522
|
+
type: "tool-call",
|
|
523
|
+
toolCallId: t.id,
|
|
524
|
+
toolName: t.name,
|
|
525
|
+
input: t.args.trim() || "{}",
|
|
526
|
+
};
|
|
527
|
+
}
|
|
318
528
|
const usage: Usage = {
|
|
319
529
|
...reported,
|
|
320
530
|
input: reported.input ?? estimateTokens(promptChars),
|