@xiaoso/dsh-tool-plus 0.1.16 → 0.1.17-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.
Files changed (109) hide show
  1. package/lib/{abort-DZ54CaKU.mjs → abort-BTblp0Rt.mjs} +2 -2
  2. package/lib/{alibaba-coding-plan-DODpkcqi.mjs → alibaba-coding-plan-t3R4YKCB.mjs} +3 -3
  3. package/lib/{alibaba-token-plan-C6lpKCda.mjs → alibaba-token-plan-CO4djG1y.mjs} +4 -4
  4. package/lib/{alibaba-token-plan-CHGyWOfX.mjs → alibaba-token-plan-CUjYJX0-.mjs} +1 -1
  5. package/lib/{anthropic-Dv_GGX6g.mjs → anthropic-nf7w6so1.mjs} +48 -21
  6. package/lib/{api-key-validation-MnMf_ihX.mjs → api-key-validation-C_tZ7Y9a.mjs} +2 -2
  7. package/lib/behavior-BwvTUtag.mjs +111 -0
  8. package/lib/{browser-render-BZXt548F.mjs → browser-render-BQaEVK_n.mjs} +4 -4
  9. package/lib/{reference-CtvM4zLU.mjs → bundled-references-CrQ4dQcT.mjs} +57 -4
  10. package/lib/cascade-BWjRTD1q.mjs +30265 -0
  11. package/lib/{cline-pass-BT9CBEOj.mjs → cline-pass-Bjm-O8GG.mjs} +2 -2
  12. package/lib/cloudflare-CKXRJ0l9.mjs +37 -0
  13. package/lib/{cloudflare-ai-gateway-DReN6ohJ.mjs → cloudflare-ai-gateway-BpnBSjwV.mjs} +8 -4
  14. package/lib/cloudflare-workers-ai-odj9XswL.mjs +32 -0
  15. package/lib/collapse-_nkb2dn7.mjs +1945 -0
  16. package/lib/{coreweave-C82HrLpb.mjs → coreweave-CGDZOD8-.mjs} +1 -1
  17. package/lib/{coreweave-C68UgRQO.mjs → coreweave-DwffcgW5.mjs} +4 -4
  18. package/lib/cursor-BgOuV7Qf.mjs +794 -0
  19. package/lib/{cursor-_gHHq-Dq.mjs → cursor-CF1iHHbv.mjs} +68 -19
  20. package/lib/{cursor-proto-Cr_WEMuv.mjs → cursor-proto-BuNTjX3L.mjs} +823 -23
  21. package/lib/{devin-QpfTSl9H.mjs → devin-7OEeEb80.mjs} +112 -31
  22. package/lib/{devin-proto-DYhp4Ty6.mjs → devin-proto-C-QreeAv.mjs} +71 -5
  23. package/lib/{dom-DG3sPESc.mjs → dom-BmbZv4v9.mjs} +598 -182
  24. package/lib/{error-O63pC8zg.mjs → error-8LVo7tug.mjs} +725 -104
  25. package/lib/factory-droid-ChhmsGWb.mjs +71 -0
  26. package/lib/{fs-promises-shim-B2YFWkcd.mjs → fs-promises-shim-CANAxFWh.mjs} +10 -1
  27. package/lib/{github-copilot-BMEcw8N1.mjs → github-copilot-QwevdT30.mjs} +4 -4
  28. package/lib/{github-copilot-headers-DnjGEbko.mjs → github-copilot-headers-CAUZ0rUD.mjs} +138 -26
  29. package/lib/{gitlab-duo-DnHqJjFY.mjs → gitlab-duo-DigV7k_o.mjs} +2 -2
  30. package/lib/{google-antigravity-B1mSckrK.mjs → google-antigravity-D-oe0r8A.mjs} +6 -7
  31. package/lib/{google-gemini-cli-DJwThCCn.mjs → google-gemini-cli-CQBHgGJT.mjs} +5 -6
  32. package/lib/{google-oauth-shared-BctLpVUN.mjs → google-oauth-shared-CvgVIUwJ.mjs} +2 -2
  33. package/lib/google-validation-CdvRj4ec.mjs +126 -0
  34. package/lib/id-EJwVLDHE.mjs +2548 -0
  35. package/lib/index.mjs +248 -258
  36. package/lib/{kilo-BEgEwMJQ.mjs → kilo-5r6OffCa.mjs} +2 -2
  37. package/lib/{kimi-T9NldEIJ.mjs → kimi-DOOtbXmm.mjs} +9 -10
  38. package/lib/{launch-BIWNyrBB.mjs → launch-DkAjib7h.mjs} +1 -1
  39. package/lib/{markit-Dvp2JPdT.mjs → markit-CCcyeAds.mjs} +359 -140
  40. package/lib/{models-DnXMYGcJ.mjs → models-DCpDT_im.mjs} +199203 -112275
  41. package/lib/{muse-code-CNvqqAp6.mjs → muse-code-CYf8zj_B.mjs} +5 -5
  42. package/lib/{openai-codex-D5-CyTxa.mjs → openai-codex-Cj-TvSFh.mjs} +13 -10
  43. package/lib/{perplexity-A2PEoGaC.mjs → perplexity-Dh_Qgsmx.mjs} +68 -25
  44. package/lib/{pkce-BYjmugmw.mjs → pkce-DO-jBJLV.mjs} +1 -1
  45. package/lib/pricing-DusBEhwm.mjs +593 -0
  46. package/lib/{readability-uGhqb4GC.mjs → readability-XHK0o3bv.mjs} +287 -27
  47. package/lib/{scrapers-C1ujjV8k.mjs → scrapers-B6PADOVm.mjs} +13 -13
  48. package/lib/slugify-ynYWBIA5.mjs +11 -0
  49. package/lib/snowflake-B_jap6lz.mjs +666 -0
  50. package/lib/snowflake-Cu1ZyOp6.mjs +151 -0
  51. package/lib/{src-AELUUb5U.mjs → src-BhinCSpi.mjs} +1172 -458
  52. package/lib/{stream-AVOoe5Hj.mjs → stream-D2ivg3GH.mjs} +3740 -5311
  53. package/lib/{turndown-D6fof1OX.mjs → turndown-Vya8SavL.mjs} +82 -30
  54. package/lib/types/tools/hashline/native/index.d.ts +2 -2
  55. package/lib/types/tools/hashline/native/policy.d.ts +19 -21
  56. package/lib/types/tools/omp/session/agent-storage.d.ts +3 -3
  57. package/lib/types/tools/shared/bun-named-shim.d.ts +5 -0
  58. package/lib/{types-BLrLohwK.mjs → types-tH1v9uRm.mjs} +2 -2
  59. package/lib/{utils-cZX3f_Ls.mjs → utils-C_Ncya1r.mjs} +1737 -509
  60. package/lib/utils-D2tK38xq.mjs +34006 -0
  61. package/lib/{utils-I4I8azHN.mjs → utils-DrDwmNtu.mjs} +8 -3
  62. package/lib/{xai-oauth-CbeldUSV.mjs → xai-oauth-DLLzX6my.mjs} +4 -4
  63. package/lib/{xiaomi-Dl3VSs04.mjs → xiaomi-CqK-KivK.mjs} +2 -2
  64. package/lib/{zai-FyjGSypr.mjs → zai-DoJ2xPIH.mjs} +2 -2
  65. package/lib/{zip-DRrycScC.mjs → zip-DG1mUV6X.mjs} +1 -1
  66. package/package.json +8 -8
  67. package/lib/amazon-bedrock-Dx0rr9dY.mjs +0 -996
  68. package/lib/anthropic-ClCw0PV_.mjs +0 -3624
  69. package/lib/anthropic-wire-lbGAFzYb.mjs +0 -927
  70. package/lib/azure-openai-responses-WE_bgFWp.mjs +0 -285
  71. package/lib/bundled-references-DY3EJxZV.mjs +0 -56
  72. package/lib/cloudflare-ai-gateway-CrMa97Ap.mjs +0 -44
  73. package/lib/collapse-CkMNRNr7.mjs +0 -2304
  74. package/lib/cursor-C6jaIJDg.mjs +0 -283
  75. package/lib/cursor-D-XZYDf_.mjs +0 -4544
  76. package/lib/deterministic-id-CUEIMSqR.mjs +0 -17
  77. package/lib/devin-ExGIghmx.mjs +0 -69
  78. package/lib/devin-u0ljw5P6.mjs +0 -628
  79. package/lib/effort-BdtQMN-_.mjs +0 -23
  80. package/lib/event-stream-BKEtb45Y.mjs +0 -167
  81. package/lib/gemini-headers-Co9cVvex.mjs +0 -54
  82. package/lib/google-auth-qAN-6DMW.mjs +0 -232
  83. package/lib/google-gemini-cli-B2Aw1S5w.mjs +0 -844
  84. package/lib/google-lTxuq28n.mjs +0 -38
  85. package/lib/google-shared-Y01j9xOr.mjs +0 -856
  86. package/lib/google-validation-BEkNs-Bx.mjs +0 -18
  87. package/lib/google-vertex-DcM-FRC5.mjs +0 -99
  88. package/lib/hosts-00rjRzUD.mjs +0 -203
  89. package/lib/id-AL5obQzR.mjs +0 -71
  90. package/lib/idle-iterator-D0ZXEcUq.mjs +0 -366
  91. package/lib/ollama-6R0oXZks.mjs +0 -574
  92. package/lib/openai-codex-responses-C8bnBWOe.mjs +0 -3232
  93. package/lib/openai-completions-DNr3mUsn.mjs +0 -1430
  94. package/lib/openai-configuration-update-xMYUjaK_.mjs +0 -150
  95. package/lib/openai-reasoning-fallback-Ju-5pSR8.mjs +0 -380
  96. package/lib/openai-responses-CjpafAEr.mjs +0 -861
  97. package/lib/protobuf-BMgDYu_U.mjs +0 -717
  98. package/lib/provider-response-SqKSkkUc.mjs +0 -22
  99. package/lib/proxy-DxvCQOCA.mjs +0 -230
  100. package/lib/request-debug-BwPOqN_j.mjs +0 -183
  101. package/lib/sanitize-text-BCf5KmCf.mjs +0 -33
  102. package/lib/sse-debug-B-tkLCPW.mjs +0 -11
  103. package/lib/stream-markup-healing-CN3RsqG9.mjs +0 -267
  104. package/lib/strict-tool-validation-CBTz1dAA.mjs +0 -105
  105. package/lib/taxonomy-DSIM99rS.mjs +0 -15392
  106. package/lib/thinking-ngMwf_1Y.mjs +0 -336
  107. package/lib/type-guards-CttAANEx.mjs +0 -11
  108. package/lib/utils-CE3DSebh.mjs +0 -11763
  109. package/lib/vision-guard-BCpXWUj3.mjs +0 -77
@@ -1,628 +0,0 @@
1
- import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
- __installBunShim();
3
- import { C as warn, _ as parseStreamingJson, b as debug, v as parseStreamingJsonThrottled, x as error } from "./src-AELUUb5U.mjs";
4
- import { S as attach, T as create, c as finalize, o as DevinApiError, r as ValidationError, s as ProviderResponseError, v as Flag } from "./error-O63pC8zg.mjs";
5
- import { A as toolWireSchema, _ as isDemotedThinking, h as transformMessages, o as normalizeSystemPrompts } from "./utils-cZX3f_Ls.mjs";
6
- import { t as calculateCost } from "./models-DnXMYGcJ.mjs";
7
- import { t as AssistantMessageEventStream } from "./event-stream-BKEtb45Y.mjs";
8
- import { n as devinCliMetadata, t as DEVIN_DEFAULT_BASE_URL } from "./devin-ExGIghmx.mjs";
9
- import { i as fromBinary, o as toBinary, t as create$1 } from "./protobuf-BMgDYu_U.mjs";
10
- import { _ as ImageDataSchema, a as ChatToolCallSchema, c as CompletionConfigurationSchema, i as ChatMessagePromptSchema, l as GetChatMessageRequestSchema, m as GetUserJwtResponseSchema, n as AssignModelRequestSchema, o as ChatToolChoiceSchema, p as GetUserJwtRequestSchema, r as AssignModelResponseSchema, s as ChatToolDefinitionSchema, t as decodeDevinUnaryMessage, u as GetChatMessageResponseSchema, v as MetadataSchema, y as PromptCacheOptionsSchema } from "./devin-proto-DYhp4Ty6.mjs";
11
- import { t as deterministicUuid } from "./deterministic-id-CUEIMSqR.mjs";
12
- import { gunzipSync, gzipSync } from "node:zlib";
13
- //#region node_modules/.pnpm/@oh-my-pi+pi-ai@18.1.17/node_modules/@oh-my-pi/pi-ai/src/providers/devin.ts
14
- /** Base host for Codeium/Windsurf's Cascade chat API (Connect protocol over HTTP/1.1). */
15
- const DEVIN_API_URL = DEVIN_DEFAULT_BASE_URL;
16
- const CHAT_MESSAGE_PATH = "/exa.api_server_pb.ApiServerService/GetChatMessage";
17
- const DEVIN_ASSIGN_MODEL_PATH = "/exa.api_server_pb.ApiServerService/AssignModel";
18
- const DEVIN_AUTH_PATH = "/exa.auth_pb.AuthService/GetUserJwt";
19
- const DEVIN_DEFAULT_STOP_PATTERNS = [
20
- "<|user|>",
21
- "<|bot|>",
22
- "<|context_request|>",
23
- "<|endoftext|>",
24
- "<|end_of_turn|>"
25
- ];
26
- /** Connect streaming framing: flag byte bit 0x01 = gzip payload, 0x02 = end-of-stream JSON trailers. */
27
- const CONNECT_COMPRESSED_FLAG = 1;
28
- const CONNECT_END_STREAM_FLAG = 2;
29
- /**
30
- * Hard upper bound on a single Connect frame payload. The 4-byte length prefix
31
- * is otherwise attacker-controlled (up to `2**32 - 1`), so a malicious or buggy
32
- * peer could force {@link streamDevin}'s reader to buffer gigabytes via
33
- * `Buffer.concat` before the idle-timeout wrapper aborts. Well above any
34
- * legitimate Cascade response but tight enough that a corrupt length prefix
35
- * fails fast instead of consuming memory.
36
- */
37
- const MAX_CONNECT_FRAME_PAYLOAD = 16777216;
38
- /**
39
- * Recovery heuristic for opaque Devin `invalid_argument` trailers. This is not
40
- * asserted to be the backend's hard limit: small requests can hit the same
41
- * intermittent error, while compactable message history this large is likely
42
- * to benefit from the existing context-overflow maintenance path.
43
- */
44
- const LARGE_HISTORY_RECOVERY_BYTES = 524288;
45
- const streamDevin = (model, context, options) => {
46
- const stream = new AssistantMessageEventStream();
47
- (async () => {
48
- const startTime = performance.now();
49
- let firstTokenTime;
50
- const output = {
51
- role: "assistant",
52
- content: [],
53
- api: "devin-agent",
54
- provider: model.provider,
55
- model: model.id,
56
- usage: {
57
- input: 0,
58
- output: 0,
59
- cacheRead: 0,
60
- cacheWrite: 0,
61
- totalTokens: 0,
62
- cost: {
63
- input: 0,
64
- output: 0,
65
- cacheRead: 0,
66
- cacheWrite: 0,
67
- total: 0
68
- }
69
- },
70
- stopReason: "stop",
71
- timestamp: Date.now()
72
- };
73
- let currentTextBlock = null;
74
- let currentThinkingBlock = null;
75
- const toolBlocks = /* @__PURE__ */ new Map();
76
- const toolPartialJson = /* @__PURE__ */ new Map();
77
- const toolLastParseLen = /* @__PURE__ */ new Map();
78
- let activeToolCallId;
79
- let latestStopReason = 0;
80
- const markFirstToken = () => {
81
- if (firstTokenTime === void 0) firstTokenTime = performance.now();
82
- };
83
- const endTextBlock = () => {
84
- const block = currentTextBlock;
85
- if (!block) return;
86
- currentTextBlock = null;
87
- stream.push({
88
- type: "text_end",
89
- contentIndex: output.content.indexOf(block),
90
- content: block.text,
91
- partial: output
92
- });
93
- };
94
- const endThinkingBlock = () => {
95
- const block = currentThinkingBlock;
96
- if (!block) return;
97
- currentThinkingBlock = null;
98
- stream.push({
99
- type: "thinking_end",
100
- contentIndex: output.content.indexOf(block),
101
- content: block.thinking,
102
- partial: output
103
- });
104
- };
105
- try {
106
- const fetchImpl = options?.fetch ?? fetch;
107
- const baseUrl = (model.baseUrl || DEVIN_API_URL).replace(/\/+$/, "");
108
- const auth = await fetchDevinAuthMetadata(options?.apiKey, baseUrl, fetchImpl, options?.signal);
109
- const chatBaseUrl = auth.baseUrl ?? baseUrl;
110
- const turn = {
111
- apiKey: options?.apiKey,
112
- userJwt: auth.userJwt,
113
- cascadeId: options?.conversationId ?? options?.sessionId ?? crypto.randomUUID(),
114
- messages: transformMessages(context.messages, model)
115
- };
116
- let assignment;
117
- if (model.compat.modelRouter) {
118
- assignment = await assignDevinModel(model, turn, chatBaseUrl, fetchImpl, options?.signal);
119
- output.upstreamModel = assignment.modelUid;
120
- }
121
- const request = buildDevinChatRequest(model, context, options, turn, assignment);
122
- const reqBytes = toBinary(GetChatMessageRequestSchema, request);
123
- const gz = gzipSync(reqBytes);
124
- debug("devin: sending chat request", {
125
- model: model.id,
126
- tools: context.tools?.length ?? 0,
127
- requestBytes: reqBytes.byteLength,
128
- compressedBytes: gz.byteLength
129
- });
130
- const frame = Buffer.alloc(5 + gz.length);
131
- frame[0] = CONNECT_COMPRESSED_FLAG;
132
- frame.writeUInt32BE(gz.length, 1);
133
- frame.set(gz, 5);
134
- const response = await fetchImpl(chatBaseUrl + CHAT_MESSAGE_PATH, {
135
- method: "POST",
136
- headers: {
137
- "content-type": "application/connect+proto",
138
- "connect-protocol-version": "1",
139
- "connect-content-encoding": "gzip",
140
- "accept-encoding": "identity",
141
- "user-agent": "connect-go/1.18.1 (go1.26.3)",
142
- "connect-accept-encoding": "gzip",
143
- ...options?.headers
144
- },
145
- body: frame,
146
- signal: options?.signal
147
- });
148
- if (!response.ok) {
149
- const text = await response.text();
150
- throw new DevinApiError(`Devin API error ${response.status} ${response.statusText}: ${text}`, response.status);
151
- }
152
- if (!response.body) throw new ProviderResponseError("Devin API error: response body is empty", {
153
- provider: model.provider,
154
- kind: "empty-body"
155
- });
156
- const body = response.body;
157
- stream.push({
158
- type: "start",
159
- partial: output
160
- });
161
- const reader = body.getReader();
162
- let pending = Buffer.alloc(0);
163
- for (;;) {
164
- const { done, value } = await reader.read();
165
- if (value && value.length > 0) pending = pending.length === 0 ? Buffer.from(value.buffer, value.byteOffset, value.byteLength) : Buffer.concat([pending, value]);
166
- while (pending.length >= 5) {
167
- const flag = pending[0];
168
- const len = pending.readUInt32BE(1);
169
- if (len > MAX_CONNECT_FRAME_PAYLOAD) throw new ProviderResponseError(`Devin Connect frame length ${len} exceeds ${MAX_CONNECT_FRAME_PAYLOAD}-byte cap`, {
170
- provider: model.provider,
171
- kind: "envelope"
172
- });
173
- if (pending.length < 5 + len) break;
174
- const payload = pending.subarray(5, 5 + len);
175
- pending = pending.subarray(5 + len);
176
- if (flag & CONNECT_END_STREAM_FLAG) {
177
- const trailerError = readConnectTrailerError((flag & CONNECT_COMPRESSED_FLAG ? gunzipSync(payload) : payload).toString("utf8").trim());
178
- if (trailerError) {
179
- warn("devin: stream rejected via Connect trailer", {
180
- model: model.id,
181
- code: trailerError.code,
182
- message: trailerError.message,
183
- ...trailerError.detail ? { detail: trailerError.detail } : {},
184
- rawTrailer: trailerError.raw,
185
- requestBytes: reqBytes.byteLength,
186
- compressedBytes: gz.byteLength,
187
- tools: context.tools?.length ?? 0,
188
- messages: context.messages.length,
189
- hadOutput: firstTokenTime !== void 0
190
- });
191
- const error = new ValidationError(trailerError.formatted);
192
- if (firstTokenTime === void 0 && trailerError.code.toLowerCase() === "invalid_argument" && /\binternal error\b/i.test(trailerError.message)) {
193
- let activeTailCount = 0;
194
- const lastRole = context.messages.at(-1)?.role;
195
- if (lastRole === "user" || lastRole === "developer") {
196
- activeTailCount = 1;
197
- if (lastRole === "developer") for (let i = context.messages.length - 2; i >= 0; i--) {
198
- const role = context.messages[i].role;
199
- if (role !== "user" && role !== "developer") break;
200
- activeTailCount++;
201
- }
202
- }
203
- const shrinkablePrompts = activeTailCount > 0 ? request.chatMessagePrompts.slice(0, -activeTailCount) : request.chatMessagePrompts;
204
- const historyBytes = toBinary(GetChatMessageRequestSchema, create$1(GetChatMessageRequestSchema, { chatMessagePrompts: shrinkablePrompts })).byteLength;
205
- if (historyBytes >= LARGE_HISTORY_RECOVERY_BYTES) {
206
- attach(error, create(Flag.ContextOverflow));
207
- warn("devin: treating large-history invalid_argument as context overflow", {
208
- model: model.id,
209
- historyBytes,
210
- requestBytes: reqBytes.byteLength,
211
- compressedBytes: gz.byteLength
212
- });
213
- }
214
- }
215
- throw error;
216
- }
217
- continue;
218
- }
219
- const raw = flag & CONNECT_COMPRESSED_FLAG ? gunzipSync(payload) : payload;
220
- const msg = fromBinary(GetChatMessageResponseSchema, raw);
221
- if (msg.messageId && !output.responseId) output.responseId = msg.messageId;
222
- if (msg.actualModelUid) output.upstreamModel = msg.actualModelUid;
223
- if (msg.deltaThinking) {
224
- markFirstToken();
225
- const block = currentThinkingBlock ?? {
226
- type: "thinking",
227
- thinking: ""
228
- };
229
- if (currentThinkingBlock !== block) {
230
- output.content.push(block);
231
- currentThinkingBlock = block;
232
- stream.push({
233
- type: "thinking_start",
234
- contentIndex: output.content.length - 1,
235
- partial: output
236
- });
237
- }
238
- block.thinking += msg.deltaThinking;
239
- if (msg.deltaSignature) block.thinkingSignature = msg.deltaSignature;
240
- stream.push({
241
- type: "thinking_delta",
242
- contentIndex: output.content.indexOf(block),
243
- delta: msg.deltaThinking,
244
- partial: output
245
- });
246
- }
247
- if (msg.deltaText) {
248
- markFirstToken();
249
- endThinkingBlock();
250
- const block = currentTextBlock ?? {
251
- type: "text",
252
- text: ""
253
- };
254
- if (currentTextBlock !== block) {
255
- output.content.push(block);
256
- currentTextBlock = block;
257
- stream.push({
258
- type: "text_start",
259
- contentIndex: output.content.length - 1,
260
- partial: output
261
- });
262
- }
263
- block.text += msg.deltaText;
264
- stream.push({
265
- type: "text_delta",
266
- contentIndex: output.content.indexOf(block),
267
- delta: msg.deltaText,
268
- partial: output
269
- });
270
- }
271
- if (msg.deltaToolCalls.length > 0) {
272
- markFirstToken();
273
- endTextBlock();
274
- endThinkingBlock();
275
- for (const tc of msg.deltaToolCalls) {
276
- const toolCallId = tc.id || activeToolCallId;
277
- if (!toolCallId) continue;
278
- let block = toolBlocks.get(toolCallId);
279
- if (!block) {
280
- block = {
281
- type: "toolCall",
282
- id: toolCallId,
283
- name: tc.name,
284
- arguments: {}
285
- };
286
- output.content.push(block);
287
- toolBlocks.set(toolCallId, block);
288
- toolPartialJson.set(toolCallId, "");
289
- stream.push({
290
- type: "toolcall_start",
291
- contentIndex: output.content.length - 1,
292
- partial: output
293
- });
294
- }
295
- if (tc.name) block.name = tc.name;
296
- activeToolCallId = toolCallId;
297
- if (!tc.argumentsJson) continue;
298
- const previousJson = toolPartialJson.get(toolCallId) ?? "";
299
- const accumulated = tc.argumentsJson.startsWith(previousJson) ? tc.argumentsJson : previousJson + tc.argumentsJson;
300
- const delta = accumulated.slice(previousJson.length);
301
- toolPartialJson.set(toolCallId, accumulated);
302
- const throttled = parseStreamingJsonThrottled(accumulated, toolLastParseLen.get(toolCallId) ?? 0);
303
- if (throttled) {
304
- block.arguments = throttled.value;
305
- toolLastParseLen.set(toolCallId, throttled.parsedLen);
306
- }
307
- stream.push({
308
- type: "toolcall_delta",
309
- contentIndex: output.content.indexOf(block),
310
- delta,
311
- partial: output
312
- });
313
- }
314
- }
315
- if (msg.stopReason !== 0) latestStopReason = msg.stopReason;
316
- if (msg.usage) {
317
- output.usage.input = Number(msg.usage.inputTokens);
318
- output.usage.output = Number(msg.usage.outputTokens);
319
- output.usage.cacheRead = Number(msg.usage.cacheReadTokens);
320
- output.usage.cacheWrite = Number(msg.usage.cacheWriteTokens);
321
- output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
322
- }
323
- if (msg.creditCost || msg.committedCreditCost || msg.committedAcuCost) {
324
- output.usage.credits ??= {};
325
- const credits = output.usage.credits;
326
- if (msg.creditCost) credits.cost = msg.creditCost;
327
- if (msg.committedCreditCost) credits.committedCost = msg.committedCreditCost;
328
- if (msg.committedAcuCost) credits.acuCost = msg.committedAcuCost;
329
- }
330
- }
331
- if (done) break;
332
- }
333
- endTextBlock();
334
- endThinkingBlock();
335
- for (const [id, block] of toolBlocks) {
336
- block.arguments = parseStreamingJson(toolPartialJson.get(id));
337
- stream.push({
338
- type: "toolcall_end",
339
- contentIndex: output.content.indexOf(block),
340
- toolCall: block,
341
- partial: output
342
- });
343
- }
344
- const doneReason = toolBlocks.size > 0 ? "toolUse" : latestStopReason === 3 ? "length" : "stop";
345
- output.stopReason = doneReason;
346
- calculateCost(model, output.usage, output.timestamp);
347
- output.duration = performance.now() - startTime;
348
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
349
- stream.push({
350
- type: "done",
351
- reason: doneReason,
352
- message: output
353
- });
354
- stream.end();
355
- } catch (error$1) {
356
- error("devin: stream failed", { error: String(error$1) });
357
- const result = await finalize(error$1, {
358
- api: model.api,
359
- signal: options?.signal
360
- });
361
- output.stopReason = result.stopReason;
362
- output.errorStatus = result.status;
363
- output.errorId = result.id;
364
- output.errorMessage = result.message;
365
- output.duration = performance.now() - startTime;
366
- if (firstTokenTime) output.ttft = firstTokenTime - startTime;
367
- stream.push({
368
- type: "error",
369
- reason: result.stopReason,
370
- error: output
371
- });
372
- stream.end();
373
- }
374
- })();
375
- return stream;
376
- };
377
- async function fetchDevinAuthMetadata(apiKey, baseUrl, fetchImpl, signal) {
378
- const request = create$1(GetUserJwtRequestSchema, { metadata: create$1(MetadataSchema, devinCliMetadata(apiKey)) });
379
- const response = await fetchImpl(`${baseUrl}${DEVIN_AUTH_PATH}`, {
380
- method: "POST",
381
- headers: {
382
- "content-type": "application/proto",
383
- "connect-protocol-version": "1",
384
- accept: "*/*"
385
- },
386
- body: toBinary(GetUserJwtRequestSchema, request),
387
- signal
388
- });
389
- const payload = new Uint8Array(await response.arrayBuffer());
390
- if (!response.ok) throw new DevinApiError(`Devin auth error ${response.status} ${response.statusText}: ${new TextDecoder().decode(payload)}`, response.status);
391
- const decoded = decodeDevinUnaryMessage(GetUserJwtResponseSchema, payload);
392
- if (!decoded?.userJwt) throw new ProviderResponseError("Devin auth error: GetUserJwt returned an empty user JWT", {
393
- provider: "devin",
394
- kind: "runtime"
395
- });
396
- const customBaseUrl = decoded.customApiServerUrl.trim();
397
- return {
398
- userJwt: decoded.userJwt,
399
- ...customBaseUrl ? { baseUrl: customBaseUrl.replace(/\/+$/, "") } : void 0
400
- };
401
- }
402
- /**
403
- * Resolve a server-side router (`adaptive`) into the concrete model uid plus the
404
- * assignment JWT that authorizes it. The router uid is never a legal
405
- * `chatModelUid`, so a failed assignment must fail the turn rather than fall
406
- * back to sending the router id to `GetChatMessage`.
407
- */
408
- async function assignDevinModel(model, turn, baseUrl, fetchImpl, signal) {
409
- const request = create$1(AssignModelRequestSchema, {
410
- metadata: create$1(MetadataSchema, devinCliMetadata(turn.apiKey)),
411
- modelRouterUid: model.requestModelId ?? model.id,
412
- cascadeId: turn.cascadeId,
413
- chatMessagePrompt: buildRouterPrompt(turn.messages)
414
- });
415
- const response = await fetchImpl(`${baseUrl}${DEVIN_ASSIGN_MODEL_PATH}`, {
416
- method: "POST",
417
- headers: {
418
- "content-type": "application/proto",
419
- "connect-protocol-version": "1",
420
- accept: "*/*"
421
- },
422
- body: toBinary(AssignModelRequestSchema, request),
423
- signal
424
- });
425
- const payload = new Uint8Array(await response.arrayBuffer());
426
- if (!response.ok) throw new DevinApiError(`Devin AssignModel error ${response.status} ${response.statusText}: ${new TextDecoder().decode(payload)}`, response.status);
427
- const assignment = decodeDevinUnaryMessage(AssignModelResponseSchema, payload)?.assignment;
428
- if (!assignment?.assignmentJwt || !assignment.modelUid) throw new ProviderResponseError("Devin AssignModel error: response carried no assignment JWT and model uid", {
429
- provider: model.provider,
430
- kind: "runtime"
431
- });
432
- debug("devin: router assigned a model", {
433
- router: model.requestModelId ?? model.id,
434
- assigned: assignment.modelUid
435
- });
436
- return assignment;
437
- }
438
- /**
439
- * The prompt the router scores: the current user/developer turn on its own.
440
- * Native leaves `messageId` empty here — the id for the turn is minted by the
441
- * chat request that follows.
442
- */
443
- function buildRouterPrompt(messages) {
444
- for (let index = messages.length - 1; index >= 0; index--) {
445
- const msg = messages[index];
446
- if (msg.role === "user" || msg.role === "developer") return buildUserPrompt(msg, "");
447
- }
448
- }
449
- /**
450
- * Build a {@link GetChatMessageRequest} for one Cascade turn. Auth rides inside
451
- * `Metadata.apiKey`; the system prompt is the flattened `prompt` string and the
452
- * conversation history maps to `chatMessagePrompts`. `assignment` is present only
453
- * for router models and supplies both the resolved uid and its JWT.
454
- */
455
- function buildDevinChatRequest(model, context, options, turn, assignment) {
456
- const stopPatterns = options?.stopSequences && options.stopSequences.length > 0 ? [...DEVIN_DEFAULT_STOP_PATTERNS, ...options.stopSequences] : DEVIN_DEFAULT_STOP_PATTERNS;
457
- return create$1(GetChatMessageRequestSchema, {
458
- metadata: create$1(MetadataSchema, devinCliMetadata(turn.apiKey, turn.userJwt)),
459
- prompt: normalizeSystemPrompts(context.systemPrompt).join("\n\n"),
460
- chatMessagePrompts: buildChatMessagePrompts(turn.messages, turn.cascadeId, model),
461
- chatModelUid: assignment?.modelUid ?? options?.chatModelUid ?? model.requestModelId ?? model.id,
462
- ...assignment ? { modelAssignmentJwt: assignment.assignmentJwt } : void 0,
463
- requestType: 5,
464
- plannerMode: 1,
465
- toolChoice: create$1(ChatToolChoiceSchema, { choice: {
466
- case: "optionName",
467
- value: "auto"
468
- } }),
469
- systemPromptCacheOptions: create$1(PromptCacheOptionsSchema, { type: 1 }),
470
- disableParallelToolCalls: !model.compat.supportsParallelToolCalls,
471
- cascadeId: turn.cascadeId,
472
- executionId: crypto.randomUUID(),
473
- configuration: create$1(CompletionConfigurationSchema, {
474
- numCompletions: 1n,
475
- maxTokens: BigInt(options?.maxTokens ?? model.maxTokens ?? 64e3),
476
- maxNewlines: 200n,
477
- temperature: options?.temperature ?? .4,
478
- firstTemperature: options?.temperature ?? .4,
479
- topK: 50n,
480
- topP: options?.topP ?? 1,
481
- stopPatterns,
482
- fimEotProbThreshold: 1
483
- }),
484
- tools: (context.tools ?? []).map((tool) => create$1(ChatToolDefinitionSchema, {
485
- name: tool.name,
486
- description: tool.description,
487
- jsonSchemaString: JSON.stringify(toolWireSchema(tool)),
488
- strict: tool.strict ?? false
489
- }))
490
- });
491
- }
492
- /** Flatten one user/developer turn into a Cascade USER prompt with inline images. */
493
- function buildUserPrompt(msg, messageId) {
494
- let prompt = "";
495
- const images = [];
496
- if (typeof msg.content === "string") prompt = msg.content;
497
- else for (const part of msg.content) if (part.type === "text") prompt += part.text;
498
- else if (part.type === "image") images.push(create$1(ImageDataSchema, {
499
- base64Data: part.data,
500
- mimeType: part.mimeType
501
- }));
502
- return create$1(ChatMessagePromptSchema, {
503
- messageId,
504
- source: 1,
505
- prompt,
506
- images
507
- });
508
- }
509
- /** Map omp `Message` history onto Cascade `ChatMessagePrompt`s (USER / SYSTEM / TOOL channels). */
510
- function buildChatMessagePrompts(messages, cascadeId, model) {
511
- const prompts = [];
512
- for (const [index, msg] of messages.entries()) if (msg.role === "user" || msg.role === "developer") prompts.push(buildUserPrompt(msg, deterministicUuid(`${cascadeId}\0${index}\0${msg.role}`)));
513
- else if (msg.role === "assistant") {
514
- const isNativeDevinMessage = msg.api === model.api && msg.provider === model.provider && msg.model === model.id;
515
- let promptText = "";
516
- let thinkingText = "";
517
- let signature = "";
518
- const toolCalls = [];
519
- for (const part of msg.content) if (part.type === "text") promptText += `${part.text}${isDemotedThinking(part) ? "\n" : ""}`;
520
- else if (part.type === "thinking") {
521
- thinkingText += part.thinking;
522
- if (isNativeDevinMessage && !signature && part.thinkingSignature) signature = part.thinkingSignature;
523
- } else if (part.type === "toolCall") toolCalls.push(create$1(ChatToolCallSchema, {
524
- id: part.id,
525
- name: part.name,
526
- argumentsJson: JSON.stringify(part.arguments)
527
- }));
528
- if (!promptText && !thinkingText && !signature && toolCalls.length === 0) continue;
529
- prompts.push(create$1(ChatMessagePromptSchema, {
530
- messageId: isNativeDevinMessage && msg.responseId ? msg.responseId : `bot-${deterministicUuid(`${cascadeId}\0${index}\0assistant`)}`,
531
- source: 2,
532
- prompt: promptText,
533
- thinking: thinkingText,
534
- signature,
535
- signatureType: "",
536
- toolCalls
537
- }));
538
- } else {
539
- let resultText = "";
540
- const images = [];
541
- for (const part of msg.content) if (part.type === "text") resultText += part.text;
542
- else if (part.type === "image") images.push(create$1(ImageDataSchema, {
543
- base64Data: part.data,
544
- mimeType: part.mimeType
545
- }));
546
- prompts.push(create$1(ChatMessagePromptSchema, {
547
- messageId: deterministicUuid(`${cascadeId}\0${index}\0tool\0${msg.toolCallId}`),
548
- source: 4,
549
- toolCallId: msg.toolCallId,
550
- toolResultIsError: msg.isError,
551
- prompt: resultText,
552
- images
553
- }));
554
- }
555
- return prompts;
556
- }
557
- /**
558
- * Parse a Connect end-of-stream JSON trailer and return its structured error
559
- * when it carries `{ error: { code, message } }`, else `null`. The trailer is
560
- * untrusted server output, so the shape is checked with guards rather than asserted.
561
- */
562
- function readConnectTrailerError(text) {
563
- if (text.length === 0) return null;
564
- let parsed;
565
- try {
566
- parsed = JSON.parse(text);
567
- } catch {
568
- return null;
569
- }
570
- if (!parsed || typeof parsed !== "object" || !("error" in parsed)) return null;
571
- const err = parsed.error;
572
- if (!err || typeof err !== "object") return null;
573
- const code = "code" in err && typeof err.code === "string" ? err.code : "";
574
- const message = "message" in err && typeof err.message === "string" ? err.message : "";
575
- if (!code && !message) return null;
576
- const trailer = {
577
- code,
578
- message,
579
- formatted: `Devin stream error${code ? ` ${code}` : ""}: ${message}`,
580
- raw: truncateTrailerEvidence(text)
581
- };
582
- const detail = "details" in err ? summarizeTrailerDetails(err.details) : void 0;
583
- if (detail) {
584
- trailer.detail = detail;
585
- trailer.formatted += ` [details: ${detail}]`;
586
- }
587
- return trailer;
588
- }
589
- /** Upper bound on retained raw-trailer evidence so log entries stay bounded. */
590
- const MAX_TRAILER_EVIDENCE_CHARS = 2e3;
591
- function truncateTrailerEvidence(text) {
592
- return text.length > MAX_TRAILER_EVIDENCE_CHARS ? `${text.slice(0, MAX_TRAILER_EVIDENCE_CHARS)}…` : text;
593
- }
594
- /**
595
- * Summarize Connect error `details` entries (loosely `{ type, value, debug }`
596
- * records). #4218's intermittent `invalid_argument` rejections arrive as
597
- * end-of-stream trailers with no HTTP error body, so any detail payload here
598
- * is the only server-side evidence available; previously it was discarded.
599
- */
600
- function summarizeTrailerDetails(details) {
601
- if (!Array.isArray(details) || details.length === 0) return void 0;
602
- let summary = "";
603
- for (const entry of details) {
604
- if (!entry || typeof entry !== "object") continue;
605
- const record = entry;
606
- const type = typeof record.type === "string" && record.type ? record.type : void 0;
607
- const value = typeof record.value === "string" && record.value ? record.value : void 0;
608
- let debug;
609
- if (record.debug !== void 0) try {
610
- debug = typeof record.debug === "string" ? record.debug : JSON.stringify(record.debug);
611
- } catch {
612
- debug = void 0;
613
- }
614
- const boundedType = type ? truncateTrailerEvidence(type) : void 0;
615
- const evidence = debug ?? value;
616
- const boundedEvidence = evidence ? truncateTrailerEvidence(evidence) : void 0;
617
- let part;
618
- if (boundedType && boundedEvidence) part = `${boundedType}: ${boundedEvidence}`;
619
- else part = boundedType ?? boundedEvidence;
620
- if (!part) continue;
621
- const next = summary ? `${summary}; ${part}` : part;
622
- if (next.length > MAX_TRAILER_EVIDENCE_CHARS) return truncateTrailerEvidence(next);
623
- summary = next;
624
- }
625
- return summary || void 0;
626
- }
627
- //#endregion
628
- export { streamDevin };
@@ -1,23 +0,0 @@
1
- import { installBunShim as __installBunShim } from "./bun-shim.mjs";
2
- __installBunShim();
3
- //#region node_modules/.pnpm/@oh-my-pi+pi-catalog@18.1.17/node_modules/@oh-my-pi/pi-catalog/src/effort.ts
4
- /** User-facing thinking levels, ordered least to most intensive. */
5
- let Effort = /* @__PURE__ */ function(Effort) {
6
- Effort["Minimal"] = "minimal";
7
- Effort["Low"] = "low";
8
- Effort["Medium"] = "medium";
9
- Effort["High"] = "high";
10
- Effort["XHigh"] = "xhigh";
11
- Effort["Max"] = "max";
12
- return Effort;
13
- }({});
14
- const THINKING_EFFORTS = [
15
- "minimal",
16
- "low",
17
- "medium",
18
- "high",
19
- "xhigh",
20
- "max"
21
- ];
22
- //#endregion
23
- export { THINKING_EFFORTS as n, Effort as t };