opencode-devin 0.2.1 → 0.2.2

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.
@@ -8,33 +8,111 @@
8
8
  *
9
9
  * Originally ported from ai-sdk-devin / pi-devin-auth (MIT).
10
10
  */
11
- import { streamChatEvents } from "./chat.js";
11
+ import { streamChatEvents, } from "./chat.js";
12
12
  import { getCachedCatalog, ModelNotAvailableError, } from "./catalog.js";
13
- import { splitEffortSuffix, toEffortLevel, withEffortSuffix } from "./effort.js";
13
+ import { defaultMember, splitEffortSuffix, toEffortLevel, withEffortSuffix } from "./effort.js";
14
14
  import { DEFAULT_API_SERVER } from "../constants.js";
15
15
  /**
16
- * Resolve the actual model UID to send upstream, applying an optional
17
- * reasoning-effort override from providerOptions: swap an existing effort
18
- * suffix, or append one when the catalog lists that variant.
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.
19
22
  *
20
23
  * Exported for tests: this is what the catalog lookup exists for, so it needs
21
24
  * to stay covered independently of the network.
22
25
  */
23
26
  export function resolveEffortUid(modelId, catalog, requestedEffort) {
24
27
  const effort = toEffortLevel(requestedEffort);
25
- if (!effort)
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))
26
40
  return modelId;
27
- const split = splitEffortSuffix(modelId);
28
- if (split.effortLevel)
29
- return withEffortSuffix(split.baseModelUid, effort);
30
- if (catalog?.some((entry) => entry.baseModelUid === modelId && entry.effortLevel === effort)) {
31
- return withEffortSuffix(modelId, effort);
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;
32
65
  }
33
- return modelId;
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}.` });
34
70
  }
35
- // --- Prompt conversion: LanguageModelV3Prompt → ChatHistoryItem[] ---
36
- function convertPrompt(prompt) {
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) {
37
114
  const items = [];
115
+ const warnings = [];
38
116
  for (const message of prompt) {
39
117
  if (message.role === "system") {
40
118
  items.push({ role: "system", content: message.content });
@@ -42,13 +120,10 @@ function convertPrompt(prompt) {
42
120
  else if (message.role === "user") {
43
121
  const parts = [];
44
122
  for (const part of message.content) {
45
- if (part.type === "text") {
123
+ if (part.type === "text")
46
124
  parts.push({ type: "text", text: part.text });
47
- }
48
- else if (part.type === "file" && part.mediaType.startsWith("image/") && typeof part.data !== "object") {
49
- const data = typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64");
50
- parts.push({ type: "image", mimeType: part.mediaType, base64Data: data });
51
- }
125
+ else if (part.type === "file")
126
+ pushFile(parts, warnings, part);
52
127
  }
53
128
  items.push({ role: "user", content: parts });
54
129
  }
@@ -72,14 +147,48 @@ function convertPrompt(prompt) {
72
147
  else if (message.role === "tool") {
73
148
  for (const part of message.content) {
74
149
  if (part.type === "tool-result") {
75
- const output = typeof part.output === "string" ? part.output : JSON.stringify(part.output);
76
- items.push({ role: "tool", content: output, tool_call_id: part.toolCallId });
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
+ });
77
157
  }
78
158
  }
79
159
  }
80
160
  }
81
- return items;
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
+ };
82
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;
83
192
  function convertTools(tools) {
84
193
  if (!tools || tools.length === 0)
85
194
  return undefined;
@@ -112,7 +221,7 @@ const TICK = Symbol("coalesce-tick");
112
221
  * Exported for tests: the Cascade event -> AI SDK stream translation is pure,
113
222
  * and interleaved parallel tool calls are the case most likely to regress.
114
223
  */
115
- export async function* convertStreamEvents(events, generateId) {
224
+ export async function* convertStreamEvents(events, generateId, warnings = []) {
116
225
  let textId = "";
117
226
  let reasoningId = "";
118
227
  let textOpen = false;
@@ -129,6 +238,7 @@ export async function* convertStreamEvents(events, generateId) {
129
238
  const openTools = new Map();
130
239
  // Deltas that carry no id belong to the most recently opened call.
131
240
  let lastToolId = "";
241
+ let madeToolCalls = false;
132
242
  const pendingDeltas = () => {
133
243
  const parts = [];
134
244
  if (textBuf) {
@@ -155,9 +265,11 @@ export async function* convertStreamEvents(events, generateId) {
155
265
  };
156
266
  // The protocol has no end-of-tool-call marker, so a call cannot be completed
157
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`.
158
269
  const completedToolCalls = () => {
159
270
  const parts = [];
160
271
  for (const [id, tool] of openTools) {
272
+ parts.push({ type: "tool-input-end", id });
161
273
  parts.push({ type: "tool-call", toolCallId: id, toolName: tool.name, input: tool.args });
162
274
  }
163
275
  openTools.clear();
@@ -230,20 +342,27 @@ export async function* convertStreamEvents(events, generateId) {
230
342
  parts.push(...pendingDeltas());
231
343
  parts.push(...closeBlocks());
232
344
  const id = event.id || generateId();
233
- const open = openTools.get(id);
234
- if (open)
235
- open.name = event.name;
236
- else
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)) {
237
348
  openTools.set(id, { name: event.name, args: "" });
349
+ madeToolCalls = true;
350
+ parts.push({ type: "tool-input-start", id, toolName: event.name });
351
+ }
238
352
  lastToolId = id;
239
353
  break;
240
354
  }
241
355
  case "tool_call_args": {
242
- const open = openTools.get(event.id ?? lastToolId);
356
+ const id = event.id ?? lastToolId;
357
+ const open = openTools.get(id);
243
358
  // An orphan delta has no call to attach to; dropping it beats inventing
244
359
  // a nameless tool call.
245
- if (open)
360
+ if (open && event.argsDelta) {
246
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
+ }
247
366
  break;
248
367
  }
249
368
  case "finish": {
@@ -253,23 +372,7 @@ export async function* convertStreamEvents(events, generateId) {
253
372
  break;
254
373
  }
255
374
  case "usage": {
256
- usage = {
257
- inputTokens: {
258
- total: event.promptTokens,
259
- noCache: event.promptTokens !== undefined && event.cachedInputTokens !== undefined
260
- ? event.promptTokens - event.cachedInputTokens
261
- : undefined,
262
- cacheRead: event.cachedInputTokens,
263
- cacheWrite: event.cacheCreationInputTokens,
264
- },
265
- outputTokens: {
266
- total: event.completionTokens,
267
- text: event.completionTokens !== undefined && event.reasoningTokens !== undefined
268
- ? event.completionTokens - event.reasoningTokens
269
- : undefined,
270
- reasoning: event.reasoningTokens,
271
- },
272
- };
375
+ usage = toUsage(event);
273
376
  break;
274
377
  }
275
378
  }
@@ -296,7 +399,7 @@ export async function* convertStreamEvents(events, generateId) {
296
399
  // With nothing buffered there is nothing to flush, so the timer race — and its
297
400
  // allocation — is skipped entirely for the common fast-streaming path.
298
401
  const nextStep = () => textBuf || reasoningBuf ? Promise.race([nextEvent(), tick()]) : nextEvent();
299
- yield { type: "stream-start", warnings: [] };
402
+ yield { type: "stream-start", warnings };
300
403
  try {
301
404
  for (;;) {
302
405
  const step = await nextStep();
@@ -324,6 +427,7 @@ export async function* convertStreamEvents(events, generateId) {
324
427
  yield* pendingDeltas();
325
428
  yield* closeBlocks();
326
429
  yield* completedToolCalls();
430
+ finishReason = finishReasonFor(finishReason, madeToolCalls);
327
431
  const rawReason = FINISH_REASON_MAP[finishReason] ?? "stop";
328
432
  yield {
329
433
  type: "finish",
@@ -374,19 +478,12 @@ export async function collectEvents(events) {
374
478
  result.finishReason = event.reason;
375
479
  break;
376
480
  case "usage":
377
- result.usage = {
378
- inputTokens: {
379
- total: event.promptTokens,
380
- noCache: undefined,
381
- cacheRead: event.cachedInputTokens,
382
- cacheWrite: event.cacheCreationInputTokens,
383
- },
384
- outputTokens: { total: event.completionTokens, text: undefined, reasoning: event.reasoningTokens },
385
- };
481
+ result.usage = toUsage(event);
386
482
  break;
387
483
  }
388
484
  }
389
485
  commit();
486
+ result.finishReason = finishReasonFor(result.finishReason, result.toolCalls.length > 0);
390
487
  return result;
391
488
  }
392
489
  /**
@@ -439,18 +536,22 @@ function hintUnlistedModel(cause, modelId, known) {
439
536
  function createLanguageModel(options) {
440
537
  const run = async (callOptions, signal) => {
441
538
  const catalog = await options.loadCatalog();
442
- checkModelUsable(options.modelId, catalog);
443
539
  const effortOverride = callOptions.providerOptions?.devin?.reasoningEffort;
444
540
  const resolvedModelId = resolveEffortUid(options.modelId, catalog?.enabled, effortOverride);
541
+ // Checked on the UID that is sent: a family id is not a UID of its own.
542
+ checkModelUsable(resolvedModelId, catalog);
543
+ const { messages, warnings } = convertPrompt(callOptions.prompt);
445
544
  return {
446
545
  resolvedModelId,
447
- knownToCatalog: isKnownToCatalog(options.modelId, catalog),
546
+ warnings,
547
+ knownToCatalog: isKnownToCatalog(resolvedModelId, catalog),
448
548
  events: streamChatEvents({
449
549
  apiKey: options.apiKey,
450
550
  apiServerUrl: options.apiServerUrl,
451
551
  modelUid: resolvedModelId,
452
- messages: convertPrompt(callOptions.prompt),
552
+ messages,
453
553
  tools: convertTools(callOptions.tools),
554
+ toolChoice: callOptions.toolChoice,
454
555
  completionOpts: {
455
556
  maxOutputTokens: callOptions.maxOutputTokens,
456
557
  temperature: callOptions.temperature,
@@ -467,7 +568,7 @@ function createLanguageModel(options) {
467
568
  modelId: options.modelId,
468
569
  supportedUrls: {},
469
570
  async doGenerate(callOptions) {
470
- const { events, knownToCatalog } = await run(callOptions, callOptions.abortSignal);
571
+ const { events, knownToCatalog, warnings } = await run(callOptions, callOptions.abortSignal);
471
572
  const collected = await collectEvents(events).catch((cause) => {
472
573
  throw hintUnlistedModel(cause, options.modelId, knownToCatalog);
473
574
  });
@@ -486,7 +587,7 @@ function createLanguageModel(options) {
486
587
  raw: collected.finishReason,
487
588
  },
488
589
  usage: collected.usage ?? DEFAULT_USAGE,
489
- warnings: [],
590
+ warnings,
490
591
  };
491
592
  },
492
593
  async doStream(callOptions) {
@@ -496,9 +597,9 @@ function createLanguageModel(options) {
496
597
  const signal = callOptions.abortSignal
497
598
  ? AbortSignal.any([callOptions.abortSignal, abort.signal])
498
599
  : abort.signal;
499
- const { events, knownToCatalog } = await run(callOptions, signal);
600
+ const { events, knownToCatalog, warnings } = await run(callOptions, signal);
500
601
  const generateId = () => crypto.randomUUID();
501
- const generator = convertStreamEvents(events, generateId);
602
+ const generator = convertStreamEvents(events, generateId, warnings);
502
603
  const modelId = options.modelId;
503
604
  let cancelled = false;
504
605
  const stream = new ReadableStream({
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "opencode-devin",
4
- "version": "0.2.1",
4
+ "version": "0.2.2",
5
5
  "description": "OpenCode v2 plugin: connect your Devin subscription to opencode with native /connect login and devin/* models",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -50,7 +50,7 @@
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/bun": "1.4.4",
53
- "protobufjs": "^8.8.1",
53
+ "protobufjs": "8.8.1",
54
54
  "typescript": "7.0.2"
55
55
  }
56
56
  }