opencode-devin 0.2.11 → 2.0.0-beta.0
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 +56 -0
- package/LICENSE +1 -1
- package/README.md +118 -228
- package/SECURITY.md +81 -0
- package/package.json +52 -58
- package/scripts/dump-log.ts +22 -0
- package/scripts/login.ts +46 -0
- package/src/index.ts +5 -0
- package/src/plugin.ts +293 -0
- package/src/provider/auth.ts +339 -0
- package/src/provider/cascade.ts +469 -0
- package/src/provider/index.ts +321 -0
- package/src/provider/log.ts +99 -0
- package/src/provider/package.json +6 -0
- package/src/provider/paths.ts +33 -0
- package/src/provider/proto.ts +197 -0
- package/dist/catalog.d.ts +0 -22
- package/dist/catalog.js +0 -111
- package/dist/constants.d.ts +0 -19
- package/dist/constants.js +0 -19
- package/dist/credentials.d.ts +0 -23
- package/dist/credentials.js +0 -57
- package/dist/index.d.ts +0 -17
- package/dist/index.js +0 -135
- package/dist/protocol/model.d.ts +0 -68
- package/dist/protocol/model.js +0 -738
- package/dist/provider.d.ts +0 -43
- package/dist/provider.js +0 -30
package/dist/protocol/model.js
DELETED
|
@@ -1,738 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* AI SDK `LanguageModelV3` facade over the Cascade chat stream.
|
|
3
|
-
*
|
|
4
|
-
* Models are discovered dynamically from the per-account catalog
|
|
5
|
-
* (GetCascadeModelConfigs). Auth: the long-lived session token
|
|
6
|
-
* (`devin-session-token$<JWT>`) as `apiKey`; a short-lived `user_jwt` is
|
|
7
|
-
* minted automatically per session.
|
|
8
|
-
*
|
|
9
|
-
* Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
|
|
10
|
-
*/
|
|
11
|
-
import { streamChatEvents, } from "devin-core";
|
|
12
|
-
import { getCachedCatalog, ModelNotAvailableError, } from "devin-core";
|
|
13
|
-
import { defaultMember, splitEffortSuffix, toEffortLevel, withEffortSuffix } from "devin-core";
|
|
14
|
-
import { DEFAULT_API_SERVER } from "../constants.js";
|
|
15
|
-
/**
|
|
16
|
-
* Resolve the model UID to send upstream.
|
|
17
|
-
*
|
|
18
|
-
* A model is published once per family, under its UID without the effort, and
|
|
19
|
-
* the effort arrives as `providerOptions.devin.reasoningEffort` from the
|
|
20
|
-
* variant the user picked. Upstream has no effort parameter: each effort is a
|
|
21
|
-
* separate UID, so the choice is made here.
|
|
22
|
-
*
|
|
23
|
-
* Exported for tests: this is what the catalog lookup exists for, so it needs
|
|
24
|
-
* to stay covered independently of the network.
|
|
25
|
-
*/
|
|
26
|
-
export function resolveEffortUid(modelId, catalog, requestedEffort) {
|
|
27
|
-
const effort = toEffortLevel(requestedEffort);
|
|
28
|
-
const self = splitEffortSuffix(modelId);
|
|
29
|
-
const family = catalog?.filter((entry) => (entry.baseModelUid ?? entry.modelUid) === self.baseModelUid) ?? [];
|
|
30
|
-
if (effort) {
|
|
31
|
-
const match = family.find((entry) => entry.effortLevel === effort);
|
|
32
|
-
if (match)
|
|
33
|
-
return match.modelUid;
|
|
34
|
-
// The catalog is not a contract, so an effort it does not list is still
|
|
35
|
-
// tried on a UID that already carries one.
|
|
36
|
-
if (self.effortLevel)
|
|
37
|
-
return withEffortSuffix(modelId, effort);
|
|
38
|
-
}
|
|
39
|
-
if (!catalog || catalog.some((entry) => entry.modelUid === modelId))
|
|
40
|
-
return modelId;
|
|
41
|
-
// A family id that is not itself a UID, e.g. `claude-opus-5-5`.
|
|
42
|
-
return defaultMember(family)?.modelUid ?? modelId;
|
|
43
|
-
}
|
|
44
|
-
/** Base64 payload of a file part, or `undefined` when it is not inline data. */
|
|
45
|
-
function inlineBase64(data) {
|
|
46
|
-
if (data instanceof Uint8Array)
|
|
47
|
-
return Buffer.from(data).toString("base64");
|
|
48
|
-
if (typeof data !== "string")
|
|
49
|
-
return undefined;
|
|
50
|
-
const dataUrl = /^data:[^,]*;base64,(.*)$/s.exec(data);
|
|
51
|
-
if (dataUrl)
|
|
52
|
-
return dataUrl[1];
|
|
53
|
-
return /^[a-z][a-z0-9+.-]*:/i.test(data) ? undefined : data;
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Cascade carries images and nothing else. Anything else is replaced by a
|
|
57
|
-
* note, so the model can say the attachment is missing instead of answering as
|
|
58
|
-
* if it had never been sent, and is reported to the caller as a warning.
|
|
59
|
-
*/
|
|
60
|
-
function pushFile(parts, warnings, file) {
|
|
61
|
-
const base64 = file.mediaType.startsWith("image/") ? inlineBase64(file.data) : undefined;
|
|
62
|
-
if (base64 !== undefined) {
|
|
63
|
-
parts.push({ type: "image", mimeType: file.mediaType, base64Data: base64 });
|
|
64
|
-
return;
|
|
65
|
-
}
|
|
66
|
-
const what = file.filename ? `${file.mediaType} file "${file.filename}"` : `${file.mediaType} file`;
|
|
67
|
-
const why = file.mediaType.startsWith("image/") ? "only inline image data can be sent" : "only images can be sent";
|
|
68
|
-
parts.push({ type: "text", text: `[Attachment omitted: ${what}. The Devin provider could not send it; ${why}.]` });
|
|
69
|
-
warnings.push({ type: "unsupported", feature: `${file.mediaType} file input`, details: `Omitted: ${why}.` });
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Flatten a tool result to what the model should read.
|
|
73
|
-
*
|
|
74
|
-
* The output is a tagged union, not the content itself: serialising it whole
|
|
75
|
-
* sends the model `{"type":"text","value":"line1\\nline2"}` in place of the two
|
|
76
|
-
* lines, which costs tokens on every tool call and is harder to read.
|
|
77
|
-
*/
|
|
78
|
-
function convertToolOutput(output, warnings) {
|
|
79
|
-
const text = (value) => [{ type: "text", text: value }];
|
|
80
|
-
switch (output.type) {
|
|
81
|
-
case "text":
|
|
82
|
-
return { content: text(output.value), isError: false };
|
|
83
|
-
case "json":
|
|
84
|
-
return { content: text(JSON.stringify(output.value)), isError: false };
|
|
85
|
-
case "error-text":
|
|
86
|
-
return { content: text(output.value), isError: true };
|
|
87
|
-
case "error-json":
|
|
88
|
-
return { content: text(JSON.stringify(output.value)), isError: true };
|
|
89
|
-
case "execution-denied":
|
|
90
|
-
return {
|
|
91
|
-
content: text(output.reason ? `Tool execution was denied: ${output.reason}` : "Tool execution was denied."),
|
|
92
|
-
isError: true,
|
|
93
|
-
};
|
|
94
|
-
case "content": {
|
|
95
|
-
const content = [];
|
|
96
|
-
for (const part of output.value) {
|
|
97
|
-
if (part.type === "text")
|
|
98
|
-
content.push({ type: "text", text: part.text });
|
|
99
|
-
else if (part.type === "image-data" || part.type === "file-data")
|
|
100
|
-
pushFile(content, warnings, part);
|
|
101
|
-
else {
|
|
102
|
-
content.push({ type: "text", text: `[Attachment omitted: the Devin provider cannot send a ${part.type} part.]` });
|
|
103
|
-
warnings.push({ type: "unsupported", feature: `${part.type} tool output` });
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
return { content, isError: false };
|
|
107
|
-
}
|
|
108
|
-
default:
|
|
109
|
-
return { content: text(JSON.stringify(output)), isError: false };
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
/** Exported for tests. */
|
|
113
|
-
export function convertPrompt(prompt) {
|
|
114
|
-
const items = [];
|
|
115
|
-
const warnings = [];
|
|
116
|
-
for (const message of prompt) {
|
|
117
|
-
if (message.role === "system") {
|
|
118
|
-
items.push({ role: "system", content: message.content });
|
|
119
|
-
}
|
|
120
|
-
else if (message.role === "user") {
|
|
121
|
-
const parts = [];
|
|
122
|
-
for (const part of message.content) {
|
|
123
|
-
if (part.type === "text")
|
|
124
|
-
parts.push({ type: "text", text: part.text });
|
|
125
|
-
else if (part.type === "file")
|
|
126
|
-
pushFile(parts, warnings, part);
|
|
127
|
-
}
|
|
128
|
-
items.push({ role: "user", content: parts });
|
|
129
|
-
}
|
|
130
|
-
else if (message.role === "assistant") {
|
|
131
|
-
const parts = [];
|
|
132
|
-
const toolCalls = [];
|
|
133
|
-
for (const part of message.content) {
|
|
134
|
-
if (part.type === "text") {
|
|
135
|
-
parts.push({ type: "text", text: part.text });
|
|
136
|
-
}
|
|
137
|
-
else if (part.type === "tool-call") {
|
|
138
|
-
toolCalls?.push({
|
|
139
|
-
id: part.toolCallId,
|
|
140
|
-
name: part.toolName,
|
|
141
|
-
arguments: typeof part.input === "string" ? part.input : JSON.stringify(part.input),
|
|
142
|
-
});
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
items.push({ role: "assistant", content: parts, tool_calls: toolCalls && toolCalls.length > 0 ? toolCalls : undefined });
|
|
146
|
-
}
|
|
147
|
-
else if (message.role === "tool") {
|
|
148
|
-
for (const part of message.content) {
|
|
149
|
-
if (part.type === "tool-result") {
|
|
150
|
-
const { content, isError } = convertToolOutput(part.output, warnings);
|
|
151
|
-
items.push({
|
|
152
|
-
role: "tool",
|
|
153
|
-
content,
|
|
154
|
-
tool_call_id: part.toolCallId,
|
|
155
|
-
...(isError ? { is_error: true } : {}),
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
return { messages: items, warnings };
|
|
162
|
-
}
|
|
163
|
-
/**
|
|
164
|
-
* Cascade reports uncached input, cache reads and cache writes as separate
|
|
165
|
-
* counts: against the live API a repeated 165k-token prompt came back as
|
|
166
|
-
* `input_tokens=4, cached_input_tokens=165031`. The total is their sum, and
|
|
167
|
-
* `promptTokens` is already the uncached share.
|
|
168
|
-
*/
|
|
169
|
-
function toUsage(event) {
|
|
170
|
-
const { promptTokens, cachedInputTokens, cacheCreationInputTokens, completionTokens, reasoningTokens } = event;
|
|
171
|
-
return {
|
|
172
|
-
inputTokens: {
|
|
173
|
-
total: promptTokens === undefined
|
|
174
|
-
? undefined
|
|
175
|
-
: promptTokens + (cachedInputTokens ?? 0) + (cacheCreationInputTokens ?? 0),
|
|
176
|
-
noCache: promptTokens,
|
|
177
|
-
cacheRead: cachedInputTokens,
|
|
178
|
-
cacheWrite: cacheCreationInputTokens,
|
|
179
|
-
},
|
|
180
|
-
outputTokens: {
|
|
181
|
-
total: completionTokens,
|
|
182
|
-
text: completionTokens !== undefined && reasoningTokens !== undefined ? completionTokens - reasoningTokens : undefined,
|
|
183
|
-
reasoning: reasoningTokens,
|
|
184
|
-
},
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Some upstream models end a turn that made tool calls with a plain stop, or
|
|
189
|
-
* with no stop reason at all. The caller has to run the tools either way.
|
|
190
|
-
*/
|
|
191
|
-
const finishReasonFor = (reason, madeToolCalls) => madeToolCalls && reason === "stop" ? "tool_calls" : reason;
|
|
192
|
-
function convertTools(tools) {
|
|
193
|
-
if (!tools || tools.length === 0)
|
|
194
|
-
return undefined;
|
|
195
|
-
const out = [];
|
|
196
|
-
for (const tool of tools) {
|
|
197
|
-
if (tool.type === "function") {
|
|
198
|
-
out.push({ name: tool.name, description: tool.description ?? "", parameters: tool.inputSchema });
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
return out.length > 0 ? out : undefined;
|
|
202
|
-
}
|
|
203
|
-
// --- Stream event conversion ---
|
|
204
|
-
// Text/reasoning coalescing thresholds — reduces stream events from
|
|
205
|
-
// hundreds of 5-byte micro-deltas to a few dozen batched chunks.
|
|
206
|
-
const COALESCE_INTERVAL_MS = 32;
|
|
207
|
-
const COALESCE_MAX_BYTES = 128;
|
|
208
|
-
const FINISH_REASON_MAP = {
|
|
209
|
-
stop: "stop",
|
|
210
|
-
length: "length",
|
|
211
|
-
tool_calls: "tool-calls",
|
|
212
|
-
content_filter: "content-filter",
|
|
213
|
-
};
|
|
214
|
-
const DEFAULT_USAGE = {
|
|
215
|
-
inputTokens: { total: 0, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
|
|
216
|
-
outputTokens: { total: 0, text: undefined, reasoning: undefined },
|
|
217
|
-
};
|
|
218
|
-
/** Sentinel distinguishing a timer wake-up from an upstream event. */
|
|
219
|
-
const TICK = Symbol("coalesce-tick");
|
|
220
|
-
/**
|
|
221
|
-
* Exported for tests: the Cascade event -> AI SDK stream translation is pure,
|
|
222
|
-
* and interleaved parallel tool calls are the case most likely to regress.
|
|
223
|
-
*/
|
|
224
|
-
export async function* convertStreamEvents(events, generateId, warnings = []) {
|
|
225
|
-
let textId = "";
|
|
226
|
-
let reasoningId = "";
|
|
227
|
-
let textOpen = false;
|
|
228
|
-
let reasoningOpen = false;
|
|
229
|
-
let finishReason = "stop";
|
|
230
|
-
let usage;
|
|
231
|
-
let textBuf = "";
|
|
232
|
-
let textLastFlush = 0;
|
|
233
|
-
let reasoningBuf = "";
|
|
234
|
-
let reasoningLastFlush = 0;
|
|
235
|
-
// Cascade interleaves argument deltas across parallel tool calls, so pending
|
|
236
|
-
// arguments are buffered per call id. A single shared buffer would splice two
|
|
237
|
-
// calls' JSON into one unparsable string.
|
|
238
|
-
const openTools = new Map();
|
|
239
|
-
// Deltas that carry no id belong to the most recently opened call.
|
|
240
|
-
let lastToolId = "";
|
|
241
|
-
let madeToolCalls = false;
|
|
242
|
-
const pendingDeltas = () => {
|
|
243
|
-
const parts = [];
|
|
244
|
-
if (textBuf) {
|
|
245
|
-
parts.push({ type: "text-delta", id: textId, delta: textBuf });
|
|
246
|
-
textBuf = "";
|
|
247
|
-
}
|
|
248
|
-
if (reasoningBuf) {
|
|
249
|
-
parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
|
|
250
|
-
reasoningBuf = "";
|
|
251
|
-
}
|
|
252
|
-
return parts;
|
|
253
|
-
};
|
|
254
|
-
const closeBlocks = () => {
|
|
255
|
-
const parts = [];
|
|
256
|
-
if (textOpen) {
|
|
257
|
-
parts.push({ type: "text-end", id: textId });
|
|
258
|
-
textOpen = false;
|
|
259
|
-
}
|
|
260
|
-
if (reasoningOpen) {
|
|
261
|
-
parts.push({ type: "reasoning-end", id: reasoningId });
|
|
262
|
-
reasoningOpen = false;
|
|
263
|
-
}
|
|
264
|
-
return parts;
|
|
265
|
-
};
|
|
266
|
-
// The protocol has no end-of-tool-call marker, so a call cannot be completed
|
|
267
|
-
// until the stream ends. They are emitted in the order they were started.
|
|
268
|
-
// The arguments themselves are streamed as they arrive, see `tool_call_args`.
|
|
269
|
-
const completedToolCalls = () => {
|
|
270
|
-
const parts = [];
|
|
271
|
-
for (const [id, tool] of openTools) {
|
|
272
|
-
parts.push({ type: "tool-input-end", id });
|
|
273
|
-
parts.push({ type: "tool-call", toolCallId: id, toolName: tool.name, input: tool.args });
|
|
274
|
-
}
|
|
275
|
-
openTools.clear();
|
|
276
|
-
return parts;
|
|
277
|
-
};
|
|
278
|
-
/** Flush only the buffers that have been waiting longer than the interval. */
|
|
279
|
-
const staleDeltas = () => {
|
|
280
|
-
const now = Date.now();
|
|
281
|
-
const parts = [];
|
|
282
|
-
if (textBuf && now - textLastFlush >= COALESCE_INTERVAL_MS) {
|
|
283
|
-
parts.push({ type: "text-delta", id: textId, delta: textBuf });
|
|
284
|
-
textBuf = "";
|
|
285
|
-
textLastFlush = now;
|
|
286
|
-
}
|
|
287
|
-
if (reasoningBuf && now - reasoningLastFlush >= COALESCE_INTERVAL_MS) {
|
|
288
|
-
parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
|
|
289
|
-
reasoningBuf = "";
|
|
290
|
-
reasoningLastFlush = now;
|
|
291
|
-
}
|
|
292
|
-
return parts;
|
|
293
|
-
};
|
|
294
|
-
const handleEvent = (event) => {
|
|
295
|
-
const parts = [];
|
|
296
|
-
switch (event.kind) {
|
|
297
|
-
case "text": {
|
|
298
|
-
// Flush the other block before opening this one, so the parts stay in
|
|
299
|
-
// causal order. Without this, text buffered right before the model
|
|
300
|
-
// starts thinking would stay invisible until more text, a tool call, or
|
|
301
|
-
// the end of the stream.
|
|
302
|
-
if (reasoningOpen && reasoningBuf) {
|
|
303
|
-
parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
|
|
304
|
-
reasoningBuf = "";
|
|
305
|
-
reasoningLastFlush = Date.now();
|
|
306
|
-
}
|
|
307
|
-
if (!textOpen) {
|
|
308
|
-
textId = generateId();
|
|
309
|
-
textOpen = true;
|
|
310
|
-
textLastFlush = Date.now();
|
|
311
|
-
parts.push({ type: "text-start", id: textId });
|
|
312
|
-
}
|
|
313
|
-
textBuf += event.text;
|
|
314
|
-
if (textBuf.length >= COALESCE_MAX_BYTES || Date.now() - textLastFlush >= COALESCE_INTERVAL_MS) {
|
|
315
|
-
parts.push({ type: "text-delta", id: textId, delta: textBuf });
|
|
316
|
-
textBuf = "";
|
|
317
|
-
textLastFlush = Date.now();
|
|
318
|
-
}
|
|
319
|
-
break;
|
|
320
|
-
}
|
|
321
|
-
case "reasoning": {
|
|
322
|
-
if (textOpen && textBuf) {
|
|
323
|
-
parts.push({ type: "text-delta", id: textId, delta: textBuf });
|
|
324
|
-
textBuf = "";
|
|
325
|
-
textLastFlush = Date.now();
|
|
326
|
-
}
|
|
327
|
-
if (!reasoningOpen) {
|
|
328
|
-
reasoningId = generateId();
|
|
329
|
-
reasoningOpen = true;
|
|
330
|
-
reasoningLastFlush = Date.now();
|
|
331
|
-
parts.push({ type: "reasoning-start", id: reasoningId });
|
|
332
|
-
}
|
|
333
|
-
reasoningBuf += event.text;
|
|
334
|
-
if (reasoningBuf.length >= COALESCE_MAX_BYTES || Date.now() - reasoningLastFlush >= COALESCE_INTERVAL_MS) {
|
|
335
|
-
parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningBuf });
|
|
336
|
-
reasoningBuf = "";
|
|
337
|
-
reasoningLastFlush = Date.now();
|
|
338
|
-
}
|
|
339
|
-
break;
|
|
340
|
-
}
|
|
341
|
-
case "tool_call_start": {
|
|
342
|
-
parts.push(...pendingDeltas());
|
|
343
|
-
parts.push(...closeBlocks());
|
|
344
|
-
const id = event.id || generateId();
|
|
345
|
-
// A repeated start keeps the first name: the call was already announced
|
|
346
|
-
// under it, and a host rejects a call whose name changes midway.
|
|
347
|
-
if (!openTools.has(id)) {
|
|
348
|
-
openTools.set(id, { name: event.name, args: "" });
|
|
349
|
-
madeToolCalls = true;
|
|
350
|
-
parts.push({ type: "tool-input-start", id, toolName: event.name });
|
|
351
|
-
}
|
|
352
|
-
lastToolId = id;
|
|
353
|
-
break;
|
|
354
|
-
}
|
|
355
|
-
case "tool_call_args": {
|
|
356
|
-
const id = event.id ?? lastToolId;
|
|
357
|
-
const open = openTools.get(id);
|
|
358
|
-
// An orphan delta has no call to attach to; dropping it beats inventing
|
|
359
|
-
// a nameless tool call.
|
|
360
|
-
if (open && event.argsDelta) {
|
|
361
|
-
open.args += event.argsDelta;
|
|
362
|
-
// Streamed so a long call, such as writing a file, shows progress
|
|
363
|
-
// instead of looking stalled until the whole turn has arrived.
|
|
364
|
-
parts.push({ type: "tool-input-delta", id, delta: event.argsDelta });
|
|
365
|
-
}
|
|
366
|
-
break;
|
|
367
|
-
}
|
|
368
|
-
case "finish": {
|
|
369
|
-
parts.push(...pendingDeltas());
|
|
370
|
-
parts.push(...closeBlocks());
|
|
371
|
-
finishReason = event.reason;
|
|
372
|
-
break;
|
|
373
|
-
}
|
|
374
|
-
case "usage": {
|
|
375
|
-
usage = toUsage(event);
|
|
376
|
-
break;
|
|
377
|
-
}
|
|
378
|
-
}
|
|
379
|
-
return parts;
|
|
380
|
-
};
|
|
381
|
-
// The loop is woken by a timer as well as by upstream events, so text that
|
|
382
|
-
// arrives and is then followed by silence is still delivered promptly instead
|
|
383
|
-
// of waiting for the next event or the end of the stream.
|
|
384
|
-
//
|
|
385
|
-
// A single `next()` is kept in flight across iterations: when the timer wins
|
|
386
|
-
// the race the pending read is handed to the next iteration rather than
|
|
387
|
-
// dropped, which is what keeps this from losing events.
|
|
388
|
-
const upstream = events[Symbol.asyncIterator]();
|
|
389
|
-
let inFlight = null;
|
|
390
|
-
const nextEvent = () => (inFlight ??= upstream.next());
|
|
391
|
-
let wake;
|
|
392
|
-
const ticker = setInterval(() => wake?.(), COALESCE_INTERVAL_MS);
|
|
393
|
-
const tick = () => new Promise((resolve) => {
|
|
394
|
-
wake = () => {
|
|
395
|
-
wake = undefined;
|
|
396
|
-
resolve(TICK);
|
|
397
|
-
};
|
|
398
|
-
});
|
|
399
|
-
// With nothing buffered there is nothing to flush, so the timer race — and its
|
|
400
|
-
// allocation — is skipped entirely for the common fast-streaming path.
|
|
401
|
-
const nextStep = () => textBuf || reasoningBuf ? Promise.race([nextEvent(), tick()]) : nextEvent();
|
|
402
|
-
yield { type: "stream-start", warnings };
|
|
403
|
-
try {
|
|
404
|
-
for (;;) {
|
|
405
|
-
const step = await nextStep();
|
|
406
|
-
if (step === TICK) {
|
|
407
|
-
// The upstream read is still in flight; keep it for the next iteration.
|
|
408
|
-
yield* staleDeltas();
|
|
409
|
-
continue;
|
|
410
|
-
}
|
|
411
|
-
// Consume the read. Without clearing it here, the same settled promise
|
|
412
|
-
// would be handed back on the next iteration and the same event replayed
|
|
413
|
-
// forever.
|
|
414
|
-
inFlight = null;
|
|
415
|
-
if (step.done)
|
|
416
|
-
break;
|
|
417
|
-
yield* handleEvent(step.value);
|
|
418
|
-
}
|
|
419
|
-
}
|
|
420
|
-
finally {
|
|
421
|
-
clearInterval(ticker);
|
|
422
|
-
inFlight = null;
|
|
423
|
-
// Let the upstream generator finish so its own cleanup runs.
|
|
424
|
-
void upstream.return?.(undefined);
|
|
425
|
-
}
|
|
426
|
-
// Final flush
|
|
427
|
-
yield* pendingDeltas();
|
|
428
|
-
yield* closeBlocks();
|
|
429
|
-
yield* completedToolCalls();
|
|
430
|
-
finishReason = finishReasonFor(finishReason, madeToolCalls);
|
|
431
|
-
const rawReason = FINISH_REASON_MAP[finishReason] ?? "stop";
|
|
432
|
-
yield {
|
|
433
|
-
type: "finish",
|
|
434
|
-
finishReason: { unified: rawReason, raw: finishReason },
|
|
435
|
-
usage: usage ?? DEFAULT_USAGE,
|
|
436
|
-
};
|
|
437
|
-
}
|
|
438
|
-
/** Exported for tests; mirrors `convertStreamEvents` for the non-streaming path. */
|
|
439
|
-
export async function collectEvents(events) {
|
|
440
|
-
const result = { text: "", reasoning: "", toolCalls: [], finishReason: "stop" };
|
|
441
|
-
// Keyed by call id for the same reason as the streaming path: parallel tool
|
|
442
|
-
// calls interleave their argument deltas.
|
|
443
|
-
const openTools = new Map();
|
|
444
|
-
let lastToolId = "";
|
|
445
|
-
let anonymous = 0;
|
|
446
|
-
const commit = () => {
|
|
447
|
-
for (const tool of openTools.values())
|
|
448
|
-
result.toolCalls.push(tool);
|
|
449
|
-
openTools.clear();
|
|
450
|
-
};
|
|
451
|
-
for await (const event of events) {
|
|
452
|
-
switch (event.kind) {
|
|
453
|
-
case "text":
|
|
454
|
-
result.text += event.text;
|
|
455
|
-
break;
|
|
456
|
-
case "reasoning":
|
|
457
|
-
result.reasoning += event.text;
|
|
458
|
-
break;
|
|
459
|
-
case "tool_call_start": {
|
|
460
|
-
// A start without an id still needs its own buffer, otherwise two
|
|
461
|
-
// anonymous calls would share one.
|
|
462
|
-
const id = event.id ?? `__anonymous_${anonymous++}`;
|
|
463
|
-
const open = openTools.get(id);
|
|
464
|
-
if (open)
|
|
465
|
-
open.name = event.name;
|
|
466
|
-
else
|
|
467
|
-
openTools.set(id, { id: event.id ?? id, name: event.name, args: "" });
|
|
468
|
-
lastToolId = id;
|
|
469
|
-
break;
|
|
470
|
-
}
|
|
471
|
-
case "tool_call_args": {
|
|
472
|
-
const open = openTools.get(event.id ?? lastToolId);
|
|
473
|
-
if (open)
|
|
474
|
-
open.args += event.argsDelta;
|
|
475
|
-
break;
|
|
476
|
-
}
|
|
477
|
-
case "finish":
|
|
478
|
-
result.finishReason = event.reason;
|
|
479
|
-
break;
|
|
480
|
-
case "usage":
|
|
481
|
-
result.usage = toUsage(event);
|
|
482
|
-
break;
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
commit();
|
|
486
|
-
result.finishReason = finishReasonFor(result.finishReason, result.toolCalls.length > 0);
|
|
487
|
-
return result;
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* Refuse a request the catalog says cannot succeed, and warn about one it cannot
|
|
491
|
-
* vouch for.
|
|
492
|
-
*
|
|
493
|
-
* Disabled is a hard stop because the account cannot use it. Absent is only a
|
|
494
|
-
* warning: the catalog is not a contract that it enumerates every uid Cascade
|
|
495
|
-
* accepts, so the upstream response stays the authority.
|
|
496
|
-
*/
|
|
497
|
-
function checkModelUsable(modelId, catalog) {
|
|
498
|
-
if (!catalog)
|
|
499
|
-
return;
|
|
500
|
-
const entry = catalog.entries.find((candidate) => candidate.modelUid === modelId);
|
|
501
|
-
if (!entry) {
|
|
502
|
-
console.warn(`[opencode-devin] model "${modelId}" is not in the Cascade catalog for this account; sending the request anyway`);
|
|
503
|
-
return;
|
|
504
|
-
}
|
|
505
|
-
if (entry.disabled)
|
|
506
|
-
throw new ModelNotAvailableError(modelId, entry.label);
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Whether the catalog vouches for this model.
|
|
510
|
-
*
|
|
511
|
-
* `true` when the account's catalog lists it, `false` when the catalog loaded
|
|
512
|
-
* and does not mention it, `undefined` when no catalog was available at all.
|
|
513
|
-
*/
|
|
514
|
-
function isKnownToCatalog(modelId, catalog) {
|
|
515
|
-
if (!catalog)
|
|
516
|
-
return undefined;
|
|
517
|
-
return catalog.entries.some((entry) => entry.modelUid === modelId);
|
|
518
|
-
}
|
|
519
|
-
/**
|
|
520
|
-
* Stream one request through the devin-engine guarded-retry pipeline.
|
|
521
|
-
*
|
|
522
|
-
* The import is dynamic on purpose: the engine is the compliance layer (the
|
|
523
|
-
* jailbreak), and a user in normal mode should neither load nor execute it —
|
|
524
|
-
* same reason devin-core and devin-engine are separate packages in the first
|
|
525
|
-
* place.
|
|
526
|
-
*/
|
|
527
|
-
async function* streamThroughPipeline(options, wire) {
|
|
528
|
-
const { CascadePipeline } = await import("devin-engine");
|
|
529
|
-
const settings = options.pipeline ?? {};
|
|
530
|
-
const pipeline = new CascadePipeline({
|
|
531
|
-
mode: settings.mode ?? "normal",
|
|
532
|
-
guardChars: settings.guardChars,
|
|
533
|
-
guardFull: settings.guardFull,
|
|
534
|
-
maxRetries: settings.maxRetries,
|
|
535
|
-
retryTemps: settings.retryTemps,
|
|
536
|
-
overrideFile: settings.overrideFile,
|
|
537
|
-
keepClientSystem: settings.keepClientSystem,
|
|
538
|
-
planPreamble: settings.planPreamble,
|
|
539
|
-
maxInputTokens: settings.maxInputTokens,
|
|
540
|
-
pruneKeepTurns: settings.pruneKeepTurns,
|
|
541
|
-
}, options.apiKey, options.apiServerUrl ?? DEFAULT_API_SERVER);
|
|
542
|
-
yield* pipeline.stream({
|
|
543
|
-
modelUid: wire.modelUid,
|
|
544
|
-
messages: wire.messages,
|
|
545
|
-
tools: wire.tools,
|
|
546
|
-
toolChoice: wire.toolChoice,
|
|
547
|
-
maxOutputTokens: wire.maxOutputTokens,
|
|
548
|
-
temperature: wire.temperature,
|
|
549
|
-
topP: wire.topP,
|
|
550
|
-
signal: wire.signal,
|
|
551
|
-
});
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Add the likely cause to a failure for a model the catalog never listed.
|
|
555
|
-
*
|
|
556
|
-
* Refusing such a model up front would be wrong: the catalog is not a contract
|
|
557
|
-
* that it enumerates every uid Cascade accepts, so a false rejection would break
|
|
558
|
-
* a model that does work. Instead the request is allowed to fail the way
|
|
559
|
-
* upstream makes it fail, and the probable reason is attached to that error —
|
|
560
|
-
* otherwise the user has to correlate a log warning with an HTTP failure.
|
|
561
|
-
*/
|
|
562
|
-
function hintUnlistedModel(cause, modelId, known) {
|
|
563
|
-
if (known !== false || !(cause instanceof Error))
|
|
564
|
-
return cause;
|
|
565
|
-
cause.message +=
|
|
566
|
-
` — model "${modelId}" is not listed in your Cognition catalog, which is the most likely reason.` +
|
|
567
|
-
` If it should be available, run /connect to refresh the catalog, or pick a model from /models.`;
|
|
568
|
-
return cause;
|
|
569
|
-
}
|
|
570
|
-
function createLanguageModel(options) {
|
|
571
|
-
const run = async (callOptions, signal) => {
|
|
572
|
-
const catalog = await options.loadCatalog();
|
|
573
|
-
const effortOverride = callOptions.providerOptions?.devin?.reasoningEffort;
|
|
574
|
-
const resolvedModelId = resolveEffortUid(options.modelId, catalog?.enabled, effortOverride);
|
|
575
|
-
// Checked on the UID that is sent: a family id is not a UID of its own.
|
|
576
|
-
checkModelUsable(resolvedModelId, catalog);
|
|
577
|
-
const { messages, warnings } = convertPrompt(callOptions.prompt);
|
|
578
|
-
const wire = {
|
|
579
|
-
modelUid: resolvedModelId,
|
|
580
|
-
messages,
|
|
581
|
-
tools: convertTools(callOptions.tools),
|
|
582
|
-
toolChoice: callOptions.toolChoice,
|
|
583
|
-
maxOutputTokens: callOptions.maxOutputTokens,
|
|
584
|
-
temperature: callOptions.temperature,
|
|
585
|
-
topP: callOptions.topP,
|
|
586
|
-
signal,
|
|
587
|
-
};
|
|
588
|
-
const pipelineMode = options.pipeline?.mode ?? "normal";
|
|
589
|
-
const events = pipelineMode === "uncensored"
|
|
590
|
-
? streamThroughPipeline(options, wire)
|
|
591
|
-
: streamChatEvents({
|
|
592
|
-
apiKey: options.apiKey,
|
|
593
|
-
apiServerUrl: options.apiServerUrl,
|
|
594
|
-
modelUid: wire.modelUid,
|
|
595
|
-
messages: wire.messages,
|
|
596
|
-
tools: wire.tools,
|
|
597
|
-
toolChoice: wire.toolChoice,
|
|
598
|
-
completionOpts: {
|
|
599
|
-
maxOutputTokens: wire.maxOutputTokens,
|
|
600
|
-
temperature: wire.temperature,
|
|
601
|
-
topP: wire.topP,
|
|
602
|
-
topK: callOptions.topK,
|
|
603
|
-
},
|
|
604
|
-
signal,
|
|
605
|
-
});
|
|
606
|
-
return {
|
|
607
|
-
resolvedModelId,
|
|
608
|
-
warnings,
|
|
609
|
-
knownToCatalog: isKnownToCatalog(resolvedModelId, catalog),
|
|
610
|
-
events,
|
|
611
|
-
};
|
|
612
|
-
};
|
|
613
|
-
return {
|
|
614
|
-
specificationVersion: "v3",
|
|
615
|
-
provider: "devin",
|
|
616
|
-
modelId: options.modelId,
|
|
617
|
-
supportedUrls: {},
|
|
618
|
-
async doGenerate(callOptions) {
|
|
619
|
-
const { events, knownToCatalog, warnings } = await run(callOptions, callOptions.abortSignal);
|
|
620
|
-
const collected = await collectEvents(events).catch((cause) => {
|
|
621
|
-
throw hintUnlistedModel(cause, options.modelId, knownToCatalog);
|
|
622
|
-
});
|
|
623
|
-
const content = [];
|
|
624
|
-
if (collected.reasoning)
|
|
625
|
-
content.push({ type: "reasoning", text: collected.reasoning });
|
|
626
|
-
if (collected.text)
|
|
627
|
-
content.push({ type: "text", text: collected.text });
|
|
628
|
-
for (const call of collected.toolCalls) {
|
|
629
|
-
content.push({ type: "tool-call", toolCallId: call.id, toolName: call.name, input: call.args });
|
|
630
|
-
}
|
|
631
|
-
return {
|
|
632
|
-
content,
|
|
633
|
-
finishReason: {
|
|
634
|
-
unified: FINISH_REASON_MAP[collected.finishReason] ?? "stop",
|
|
635
|
-
raw: collected.finishReason,
|
|
636
|
-
},
|
|
637
|
-
usage: collected.usage ?? DEFAULT_USAGE,
|
|
638
|
-
warnings,
|
|
639
|
-
};
|
|
640
|
-
},
|
|
641
|
-
async doStream(callOptions) {
|
|
642
|
-
// Owned so that cancelling the stream can tear the request down; the
|
|
643
|
-
// caller's signal is honoured alongside it.
|
|
644
|
-
const abort = new AbortController();
|
|
645
|
-
const signal = callOptions.abortSignal
|
|
646
|
-
? AbortSignal.any([callOptions.abortSignal, abort.signal])
|
|
647
|
-
: abort.signal;
|
|
648
|
-
const { events, knownToCatalog, warnings } = await run(callOptions, signal);
|
|
649
|
-
const generateId = () => crypto.randomUUID();
|
|
650
|
-
const generator = convertStreamEvents(events, generateId, warnings);
|
|
651
|
-
const modelId = options.modelId;
|
|
652
|
-
let cancelled = false;
|
|
653
|
-
const stream = new ReadableStream({
|
|
654
|
-
async start(controller) {
|
|
655
|
-
try {
|
|
656
|
-
for await (const chunk of generator) {
|
|
657
|
-
if (cancelled)
|
|
658
|
-
break;
|
|
659
|
-
controller.enqueue(chunk);
|
|
660
|
-
}
|
|
661
|
-
if (!cancelled)
|
|
662
|
-
controller.close();
|
|
663
|
-
}
|
|
664
|
-
catch (cause) {
|
|
665
|
-
if (cancelled)
|
|
666
|
-
return;
|
|
667
|
-
controller.enqueue({ type: "error", error: hintUnlistedModel(cause, modelId, knownToCatalog) });
|
|
668
|
-
controller.enqueue({ type: "finish", finishReason: { unified: "error", raw: "error" }, usage: DEFAULT_USAGE });
|
|
669
|
-
controller.close();
|
|
670
|
-
}
|
|
671
|
-
},
|
|
672
|
-
async cancel() {
|
|
673
|
-
cancelled = true;
|
|
674
|
-
// Aborting is what actually releases the connection. `generator.return()`
|
|
675
|
-
// alone is not enough: it is queued behind the in-flight read, so the
|
|
676
|
-
// request would stay open until the idle timeout fired.
|
|
677
|
-
abort.abort(new Error("Stream cancelled by the consumer"));
|
|
678
|
-
await generator.return(undefined).catch(() => { });
|
|
679
|
-
},
|
|
680
|
-
});
|
|
681
|
-
return { stream };
|
|
682
|
-
},
|
|
683
|
-
};
|
|
684
|
-
}
|
|
685
|
-
export function createDevin(options) {
|
|
686
|
-
const apiKey = options.apiKey ?? "";
|
|
687
|
-
let catalog;
|
|
688
|
-
let pending;
|
|
689
|
-
/**
|
|
690
|
-
* Per-account catalog, memoized for the life of the provider.
|
|
691
|
-
*
|
|
692
|
-
* `getCachedCatalog` already dedupes concurrent fetches and caches the result
|
|
693
|
-
* for 10 minutes, so this is normally a cache hit — the plugin's `publish()`
|
|
694
|
-
* warms the same module-level cache before any chat happens. On failure it
|
|
695
|
-
* resolves `undefined`, and the request proceeds uncatalogued rather than being
|
|
696
|
-
* rejected on a guess.
|
|
697
|
-
*/
|
|
698
|
-
const loadCatalog = () => {
|
|
699
|
-
if (!apiKey)
|
|
700
|
-
return Promise.resolve(undefined);
|
|
701
|
-
if (catalog)
|
|
702
|
-
return Promise.resolve(catalog);
|
|
703
|
-
pending ??= getCachedCatalog(apiKey, options.baseURL)
|
|
704
|
-
.then((result) => {
|
|
705
|
-
if (result) {
|
|
706
|
-
const entries = Array.from(result.byUid.values());
|
|
707
|
-
catalog = { entries, enabled: entries.filter((entry) => !entry.disabled) };
|
|
708
|
-
}
|
|
709
|
-
return catalog;
|
|
710
|
-
})
|
|
711
|
-
.finally(() => {
|
|
712
|
-
pending = undefined;
|
|
713
|
-
});
|
|
714
|
-
return pending;
|
|
715
|
-
};
|
|
716
|
-
return {
|
|
717
|
-
languageModel(modelId) {
|
|
718
|
-
return createLanguageModel({
|
|
719
|
-
modelId,
|
|
720
|
-
apiKey,
|
|
721
|
-
apiServerUrl: options.baseURL,
|
|
722
|
-
loadCatalog,
|
|
723
|
-
pipeline: {
|
|
724
|
-
mode: options.mode,
|
|
725
|
-
guardChars: options.guardChars,
|
|
726
|
-
guardFull: options.guardFull,
|
|
727
|
-
maxRetries: options.maxRetries,
|
|
728
|
-
retryTemps: options.retryTemps,
|
|
729
|
-
overrideFile: options.overrideFile,
|
|
730
|
-
keepClientSystem: options.keepClientSystem,
|
|
731
|
-
planPreamble: options.planPreamble,
|
|
732
|
-
maxInputTokens: options.maxInputTokens,
|
|
733
|
-
pruneKeepTurns: options.pruneKeepTurns,
|
|
734
|
-
},
|
|
735
|
-
});
|
|
736
|
-
},
|
|
737
|
-
};
|
|
738
|
-
}
|