@archships/dim-agent-sdk 0.0.3 → 0.0.4

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 (105) hide show
  1. package/README.md +15 -2
  2. package/dist/dim-agent-sdk/src/agent-core/agent-types.d.ts +1 -1
  3. package/dist/dim-agent-sdk/src/agent-core/{Agent.d.ts → agent.d.ts} +2 -2
  4. package/dist/dim-agent-sdk/src/agent-core/index.d.ts +10 -10
  5. package/dist/dim-agent-sdk/src/agent-core/{LoopRunner.d.ts → loop-runner.d.ts} +5 -5
  6. package/dist/dim-agent-sdk/src/agent-core/notifications.d.ts +1 -1
  7. package/dist/dim-agent-sdk/src/agent-core/session-state.d.ts +1 -1
  8. package/dist/dim-agent-sdk/src/agent-core/{Session.d.ts → session.d.ts} +2 -2
  9. package/dist/dim-agent-sdk/src/agent-core/{ToolExecutor.d.ts → tool-executor.d.ts} +2 -2
  10. package/dist/dim-agent-sdk/src/context/{AutoContextManager.d.ts → auto-context-manager.d.ts} +1 -1
  11. package/dist/dim-agent-sdk/src/context/index.d.ts +2 -2
  12. package/dist/dim-agent-sdk/src/index.d.ts +6 -5
  13. package/dist/dim-agent-sdk/src/persistence/index.d.ts +5 -5
  14. package/dist/dim-agent-sdk/src/plugin-host/index.d.ts +2 -2
  15. package/dist/dim-agent-sdk/src/plugin-host/{PluginHost.d.ts → plugin-host.d.ts} +4 -4
  16. package/dist/dim-agent-sdk/src/providers/aihubmix/adapter.d.ts +17 -0
  17. package/dist/dim-agent-sdk/src/providers/aihubmix/driver.d.ts +3 -0
  18. package/dist/dim-agent-sdk/src/providers/aihubmix/index.d.ts +2 -0
  19. package/dist/dim-agent-sdk/src/providers/aihubmix-responses/adapter.d.ts +17 -0
  20. package/dist/dim-agent-sdk/src/providers/aihubmix-responses/driver.d.ts +12 -0
  21. package/dist/dim-agent-sdk/src/providers/aihubmix-responses/index.d.ts +2 -0
  22. package/dist/dim-agent-sdk/src/providers/aihubmix-responses/state.d.ts +7 -0
  23. package/dist/dim-agent-sdk/src/providers/anthropic/adapter.d.ts +15 -4
  24. package/dist/dim-agent-sdk/src/providers/anthropic/driver.d.ts +3 -0
  25. package/dist/dim-agent-sdk/src/providers/anthropic/index.d.ts +2 -0
  26. package/dist/dim-agent-sdk/src/providers/anthropic/state.d.ts +6 -0
  27. package/dist/dim-agent-sdk/src/providers/core/create-provider-factory.d.ts +39 -0
  28. package/dist/dim-agent-sdk/src/providers/core/index.d.ts +2 -0
  29. package/dist/dim-agent-sdk/src/providers/deepseek/adapter.d.ts +11 -0
  30. package/dist/dim-agent-sdk/src/providers/deepseek/driver.d.ts +3 -0
  31. package/dist/dim-agent-sdk/src/providers/deepseek/index.d.ts +2 -0
  32. package/dist/dim-agent-sdk/src/providers/gemini/adapter.d.ts +3 -4
  33. package/dist/dim-agent-sdk/src/providers/gemini/driver.d.ts +3 -0
  34. package/dist/dim-agent-sdk/src/providers/gemini/index.d.ts +2 -0
  35. package/dist/dim-agent-sdk/src/providers/gemini/state.d.ts +5 -0
  36. package/dist/dim-agent-sdk/src/providers/index.d.ts +22 -8
  37. package/dist/dim-agent-sdk/src/providers/moonshotai/adapter.d.ts +11 -0
  38. package/dist/dim-agent-sdk/src/providers/moonshotai/driver.d.ts +3 -0
  39. package/dist/dim-agent-sdk/src/providers/moonshotai/index.d.ts +2 -0
  40. package/dist/dim-agent-sdk/src/providers/openai/adapter.d.ts +3 -4
  41. package/dist/dim-agent-sdk/src/providers/openai/driver.d.ts +3 -0
  42. package/dist/dim-agent-sdk/src/providers/openai/index.d.ts +2 -0
  43. package/dist/dim-agent-sdk/src/providers/openai-responses/adapter.d.ts +3 -4
  44. package/dist/dim-agent-sdk/src/providers/openai-responses/driver.d.ts +3 -0
  45. package/dist/dim-agent-sdk/src/providers/openai-responses/index.d.ts +2 -0
  46. package/dist/dim-agent-sdk/src/providers/openai-responses/state.d.ts +7 -0
  47. package/dist/dim-agent-sdk/src/providers/shared/ai-sdk-driver.d.ts +7 -0
  48. package/dist/dim-agent-sdk/src/providers/shared/auth-warning.d.ts +6 -0
  49. package/dist/dim-agent-sdk/src/providers/shared/fetch.d.ts +8 -0
  50. package/dist/dim-agent-sdk/src/providers/shared/http-error.d.ts +10 -0
  51. package/dist/dim-agent-sdk/src/providers/shared/prompt.d.ts +14 -0
  52. package/dist/dim-agent-sdk/src/providers/shared/reasoning.d.ts +30 -7
  53. package/dist/dim-agent-sdk/src/providers/shared/responses-state.d.ts +11 -0
  54. package/dist/dim-agent-sdk/src/providers/shared/usage.d.ts +4 -2
  55. package/dist/dim-agent-sdk/src/providers/xai/adapter.d.ts +11 -0
  56. package/dist/dim-agent-sdk/src/providers/xai/driver.d.ts +3 -0
  57. package/dist/dim-agent-sdk/src/providers/xai/index.d.ts +2 -0
  58. package/dist/dim-agent-sdk/src/providers/xai-responses/adapter.d.ts +11 -0
  59. package/dist/dim-agent-sdk/src/providers/xai-responses/driver.d.ts +3 -0
  60. package/dist/dim-agent-sdk/src/providers/xai-responses/index.d.ts +2 -0
  61. package/dist/dim-agent-sdk/src/providers/xai-responses/state.d.ts +7 -0
  62. package/dist/dim-agent-sdk/src/providers/zenmux/adapter.d.ts +13 -0
  63. package/dist/dim-agent-sdk/src/providers/zenmux/driver.d.ts +3 -0
  64. package/dist/dim-agent-sdk/src/providers/zenmux/index.d.ts +2 -0
  65. package/dist/dim-agent-sdk/src/services/index.d.ts +6 -6
  66. package/dist/dim-agent-sdk/src/tools/builtins/{EditTool.d.ts → edit-tool.d.ts} +1 -1
  67. package/dist/dim-agent-sdk/src/tools/builtins/{ExecTool.d.ts → exec-tool.d.ts} +1 -1
  68. package/dist/dim-agent-sdk/src/tools/builtins/index.d.ts +4 -4
  69. package/dist/dim-agent-sdk/src/tools/builtins/{ReadTool.d.ts → read-tool.d.ts} +1 -1
  70. package/dist/dim-agent-sdk/src/tools/builtins/{WriteTool.d.ts → write-tool.d.ts} +1 -1
  71. package/dist/dim-agent-sdk/src/tools/index.d.ts +2 -2
  72. package/dist/{index.js → src/index.js} +4124 -3645
  73. package/dist/src/providers/aihubmix/index.js +636 -0
  74. package/dist/src/providers/aihubmix-responses/index.js +759 -0
  75. package/dist/src/providers/anthropic/index.js +743 -0
  76. package/dist/src/providers/core/index.js +92 -0
  77. package/dist/src/providers/deepseek/index.js +639 -0
  78. package/dist/src/providers/gemini/index.js +756 -0
  79. package/dist/src/providers/moonshotai/index.js +639 -0
  80. package/dist/src/providers/openai/index.js +499 -0
  81. package/dist/src/providers/openai-responses/index.js +727 -0
  82. package/dist/src/providers/xai/index.js +639 -0
  83. package/dist/src/providers/xai-responses/index.js +728 -0
  84. package/dist/src/providers/zenmux/index.js +642 -0
  85. package/package.json +74 -5
  86. package/dist/dim-agent-sdk/src/providers/anthropic/mapper.d.ts +0 -28
  87. package/dist/dim-agent-sdk/src/providers/gemini/mapper.d.ts +0 -30
  88. package/dist/dim-agent-sdk/src/providers/openai/mapper.d.ts +0 -15
  89. package/dist/dim-agent-sdk/src/providers/openai-responses/mapper.d.ts +0 -40
  90. /package/dist/dim-agent-sdk/src/agent-core/{createModel.d.ts → create-model.d.ts} +0 -0
  91. /package/dist/dim-agent-sdk/src/agent-core/{MessageFactory.d.ts → message-factory.d.ts} +0 -0
  92. /package/dist/dim-agent-sdk/src/agent-core/{ModelTurnCollector.d.ts → model-turn-collector.d.ts} +0 -0
  93. /package/dist/dim-agent-sdk/src/agent-core/{TerminationPolicy.d.ts → termination-policy.d.ts} +0 -0
  94. /package/dist/dim-agent-sdk/src/persistence/{FileStateStore.d.ts → file-state-store.d.ts} +0 -0
  95. /package/dist/dim-agent-sdk/src/persistence/{InMemoryStateStore.d.ts → in-memory-state-store.d.ts} +0 -0
  96. /package/dist/dim-agent-sdk/src/persistence/{SnapshotCodec.d.ts → snapshot-codec.d.ts} +0 -0
  97. /package/dist/dim-agent-sdk/src/plugin-host/{HookPipeline.d.ts → hook-pipeline.d.ts} +0 -0
  98. /package/dist/dim-agent-sdk/src/services/{ExecGateway.d.ts → exec-gateway.d.ts} +0 -0
  99. /package/dist/dim-agent-sdk/src/services/{FileSystemGateway.d.ts → file-system-gateway.d.ts} +0 -0
  100. /package/dist/dim-agent-sdk/src/services/{GitGateway.d.ts → git-gateway.d.ts} +0 -0
  101. /package/dist/dim-agent-sdk/src/services/{ModelGateway.d.ts → model-gateway.d.ts} +0 -0
  102. /package/dist/dim-agent-sdk/src/services/{NetworkGateway.d.ts → network-gateway.d.ts} +0 -0
  103. /package/dist/dim-agent-sdk/src/services/{PermissionGateway.d.ts → permission-gateway.d.ts} +0 -0
  104. /package/dist/dim-agent-sdk/src/tools/{BaseTool.d.ts → base-tool.d.ts} +0 -0
  105. /package/dist/dim-agent-sdk/src/tools/{ToolRegistry.d.ts → tool-registry.d.ts} +0 -0
@@ -0,0 +1,756 @@
1
+ // src/providers/core/create-provider-factory.ts
2
+ function createProviderFactory(definition) {
3
+ return function createConfiguredAdapter(options) {
4
+ const provider = options.provider ?? definition.defaultProvider;
5
+ const defaultModel = {
6
+ provider,
7
+ modelId: options.defaultModel
8
+ };
9
+ return {
10
+ provider,
11
+ defaultModel,
12
+ async* stream(request) {
13
+ const requestId = request.requestId ?? crypto.randomUUID();
14
+ const model = request.model ?? defaultModel;
15
+ yield { type: "response_start", requestId, model };
16
+ const context = {
17
+ options,
18
+ provider,
19
+ defaultModel,
20
+ request: {
21
+ ...request,
22
+ model
23
+ }
24
+ };
25
+ let result;
26
+ try {
27
+ result = await definition.driver.generate(context);
28
+ } catch (error) {
29
+ const payload = definition.driver.normalizeError ? await definition.driver.normalizeError(error, context) : createFallbackErrorPayload(provider, error);
30
+ yield {
31
+ type: "error",
32
+ requestId,
33
+ error: payload,
34
+ terminal: true
35
+ };
36
+ return;
37
+ }
38
+ for (const segment of result.content) {
39
+ if (segment.type === "text") {
40
+ if (segment.text.length > 0)
41
+ yield { type: "text_delta", requestId, delta: segment.text };
42
+ continue;
43
+ }
44
+ if (segment.type === "thinking") {
45
+ if (segment.text.length > 0)
46
+ yield { type: "thinking_delta", requestId, delta: segment.text };
47
+ continue;
48
+ }
49
+ yield {
50
+ type: "tool_call_start",
51
+ requestId,
52
+ callId: segment.callId,
53
+ toolName: segment.toolName
54
+ };
55
+ yield {
56
+ type: "tool_call_args_delta",
57
+ requestId,
58
+ callId: segment.callId,
59
+ delta: segment.argsText
60
+ };
61
+ yield {
62
+ type: "tool_call_end",
63
+ requestId,
64
+ callId: segment.callId
65
+ };
66
+ }
67
+ yield {
68
+ type: "response_end",
69
+ requestId,
70
+ stopReason: result.stopReason,
71
+ usage: result.usage,
72
+ assistantMetadata: result.assistantMetadata
73
+ };
74
+ }
75
+ };
76
+ };
77
+ }
78
+ function createFallbackErrorPayload(provider, error) {
79
+ if (error instanceof Error) {
80
+ return {
81
+ code: `${provider}_request_error`,
82
+ message: error.message
83
+ };
84
+ }
85
+ return {
86
+ code: `${provider}_request_error`,
87
+ message: String(error)
88
+ };
89
+ }
90
+
91
+ // src/providers/gemini/driver.ts
92
+ import { APICallError } from "@ai-sdk/provider";
93
+ import { createGoogleGenerativeAI } from "@ai-sdk/google";
94
+
95
+ // src/providers/shared/usage.ts
96
+ function normalizeLanguageModelUsage(raw) {
97
+ if (!raw)
98
+ return;
99
+ const promptTokens = raw.inputTokens.total ?? 0;
100
+ const completionTokens = raw.outputTokens.total ?? 0;
101
+ const totalTokens = promptTokens + completionTokens;
102
+ if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0)
103
+ return;
104
+ return {
105
+ promptTokens,
106
+ completionTokens,
107
+ totalTokens
108
+ };
109
+ }
110
+ function mapLanguageModelFinishReason(reason) {
111
+ const raw = reason.raw?.toLowerCase();
112
+ if (raw === "cancelled" || raw === "canceled")
113
+ return "cancelled";
114
+ switch (reason.unified) {
115
+ case "tool-calls":
116
+ return "tool_call";
117
+ case "length":
118
+ return "length";
119
+ case "content-filter":
120
+ case "error":
121
+ return "error";
122
+ case "other":
123
+ return raw === "cancelled" || raw === "canceled" ? "cancelled" : "final";
124
+ case "stop":
125
+ default:
126
+ return "final";
127
+ }
128
+ }
129
+
130
+ // src/providers/shared/ai-sdk-driver.ts
131
+ async function generateWithAiSdk(input) {
132
+ const result = await input.model.doGenerate(input.callOptions);
133
+ const content = [];
134
+ for (const part of result.content) {
135
+ if (part.type === "text") {
136
+ if (part.text.length > 0)
137
+ content.push({ type: "text", text: part.text });
138
+ continue;
139
+ }
140
+ if (part.type === "reasoning") {
141
+ if (part.text.length > 0)
142
+ content.push({ type: "thinking", text: part.text });
143
+ continue;
144
+ }
145
+ if (part.type === "tool-call") {
146
+ content.push({
147
+ type: "tool_call",
148
+ callId: part.toolCallId,
149
+ toolName: part.toolName,
150
+ argsText: part.input
151
+ });
152
+ }
153
+ }
154
+ return {
155
+ content,
156
+ stopReason: mapLanguageModelFinishReason(result.finishReason),
157
+ usage: normalizeLanguageModelUsage(result.usage),
158
+ assistantMetadata: input.createAssistantMetadata?.(result)
159
+ };
160
+ }
161
+
162
+ // src/providers/shared/auth-warning.ts
163
+ var warnedProviders = new Set;
164
+ function warnIfPlaceholderApiKey(input) {
165
+ if (!input.shouldWarn)
166
+ return;
167
+ if (false)
168
+ ;
169
+ if (warnedProviders.has(input.provider))
170
+ return;
171
+ warnedProviders.add(input.provider);
172
+ const suffix = input.hint ? ` ${input.hint}` : "";
173
+ console.warn(`[dim-agent-sdk] ${input.provider} is using a placeholder API key because no apiKey or provider-native auth configuration was provided. ` + `If you rely on external authentication, ensure your custom fetch or provider-native headers add real credentials before the request is sent upstream.${suffix}`);
174
+ }
175
+
176
+ // src/providers/shared/fetch.ts
177
+ function createProviderFetch(input) {
178
+ const fetchImpl = input.fetch ?? globalThis.fetch;
179
+ if (!input.stripWhen || !input.stripHeaders || input.stripHeaders.length === 0)
180
+ return fetchImpl;
181
+ const headersToStrip = new Set(input.stripHeaders.map((header) => header.toLowerCase()));
182
+ const wrappedFetch = Object.assign((resource, init) => {
183
+ if (typeof resource === "string" || resource instanceof URL) {
184
+ const headers = new Headers(init?.headers);
185
+ for (const header of headersToStrip)
186
+ headers.delete(header);
187
+ return fetchImpl(resource, { ...init, headers });
188
+ }
189
+ const request = new Request(resource, init);
190
+ for (const header of headersToStrip)
191
+ request.headers.delete(header);
192
+ return fetchImpl(request);
193
+ }, {
194
+ preconnect: typeof fetchImpl.preconnect === "function" ? fetchImpl.preconnect.bind(fetchImpl) : (_url, _options) => {}
195
+ });
196
+ return wrappedFetch;
197
+ }
198
+ function hasHeader(headers, target) {
199
+ if (!headers)
200
+ return false;
201
+ const normalized = target.toLowerCase();
202
+ return Object.keys(headers).some((key) => key.toLowerCase() === normalized);
203
+ }
204
+
205
+ // src/providers/shared/http-error.ts
206
+ import { STATUS_CODES } from "node:http";
207
+ var MAX_TEXT_CHARS = 4000;
208
+ var MAX_JSON_DEPTH = 4;
209
+ var MAX_JSON_ARRAY_ITEMS = 20;
210
+ var MAX_JSON_OBJECT_KEYS = 40;
211
+ var TRUNCATED_SUFFIX = "...[truncated]";
212
+ function createApiCallErrorPayload(input) {
213
+ const responseBody = input.error.responseBody ? parseErrorBody(input.error.responseBody) : limitJsonValue(input.error.data);
214
+ return {
215
+ code: input.code,
216
+ message: `${input.provider} request failed${input.error.statusCode ? ` with status ${input.error.statusCode}` : ""}`,
217
+ status: input.error.statusCode,
218
+ retryable: input.error.isRetryable,
219
+ details: {
220
+ provider: input.provider,
221
+ endpoint: input.error.url,
222
+ ...input.error.statusCode ? { statusText: STATUS_CODES[input.error.statusCode] ?? undefined } : {},
223
+ ...responseBody === undefined ? {} : { responseBody }
224
+ }
225
+ };
226
+ }
227
+ function createRequestErrorPayload(input) {
228
+ if (input.error instanceof Error) {
229
+ return {
230
+ code: input.code,
231
+ message: input.error.message
232
+ };
233
+ }
234
+ return {
235
+ code: input.code,
236
+ message: String(input.error)
237
+ };
238
+ }
239
+ function parseErrorBody(value) {
240
+ const normalized = value.trim();
241
+ if (!normalized)
242
+ return;
243
+ try {
244
+ return limitJsonValue(JSON.parse(normalized));
245
+ } catch {
246
+ return truncateText(normalized);
247
+ }
248
+ }
249
+ function limitJsonValue(value, depth = 0) {
250
+ if (value === undefined)
251
+ return;
252
+ if (value === null || typeof value === "boolean" || typeof value === "number")
253
+ return value;
254
+ if (typeof value === "string")
255
+ return truncateText(value);
256
+ if (Array.isArray(value))
257
+ return value.slice(0, MAX_JSON_ARRAY_ITEMS).map((item) => limitJsonValue(item, depth + 1));
258
+ if (typeof value === "object") {
259
+ if (depth >= MAX_JSON_DEPTH)
260
+ return truncateText(JSON.stringify(value));
261
+ const limited = {};
262
+ for (const [key, child] of Object.entries(value).slice(0, MAX_JSON_OBJECT_KEYS))
263
+ limited[key] = limitJsonValue(child, depth + 1);
264
+ return limited;
265
+ }
266
+ return truncateText(String(value));
267
+ }
268
+ function truncateText(value) {
269
+ if (value.length <= MAX_TEXT_CHARS)
270
+ return value;
271
+ return `${value.slice(0, MAX_TEXT_CHARS)}${TRUNCATED_SUFFIX}`;
272
+ }
273
+
274
+ // src/utils/guards.ts
275
+ function isRecord(value) {
276
+ return typeof value === "object" && value !== null && !Array.isArray(value);
277
+ }
278
+ function isStringArray(value) {
279
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
280
+ }
281
+
282
+ // src/contracts/content-normalize.ts
283
+ function isTextContent(value) {
284
+ return isRecord(value) && value.type === "text" && typeof value.text === "string" && (value.annotations === undefined || isRecord(value.annotations)) && (value._meta === undefined || isRecord(value._meta));
285
+ }
286
+ function isImageContent(value) {
287
+ return isRecord(value) && value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string" && (value.annotations === undefined || isRecord(value.annotations)) && (value._meta === undefined || isRecord(value._meta));
288
+ }
289
+ function isContentBlock(value) {
290
+ return isTextContent(value) || isImageContent(value);
291
+ }
292
+ function normalizeContent(input) {
293
+ if (typeof input === "string") {
294
+ return [{ type: "text", text: input }];
295
+ }
296
+ if (Array.isArray(input)) {
297
+ const blocks = input.filter((item) => item != null);
298
+ if (!blocks.every(isContentBlock))
299
+ throw new TypeError("Content array must contain only text or image blocks");
300
+ return blocks.map((block) => ({ ...block }));
301
+ }
302
+ if (!isContentBlock(input))
303
+ throw new TypeError("Content must be a string, content block, or content block array");
304
+ return [{ ...input }];
305
+ }
306
+ function contentToText(content) {
307
+ return content.filter((block) => block.type === "text").map((block) => block.text).join("");
308
+ }
309
+
310
+ // src/utils/json.ts
311
+ function isJsonSafeValue(value) {
312
+ if (value === null)
313
+ return true;
314
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
315
+ return true;
316
+ if (Array.isArray(value))
317
+ return value.every(isJsonSafeValue);
318
+ if (isRecord(value))
319
+ return Object.values(value).every(isJsonSafeValue);
320
+ return false;
321
+ }
322
+ function assertJsonSafeObject(value, label) {
323
+ if (!isRecord(value) || !isJsonSafeValue(value))
324
+ throw new TypeError(`${label} must be a JSON-safe object`);
325
+ }
326
+ function parseJsonObject(value, label) {
327
+ let parsed;
328
+ try {
329
+ parsed = JSON.parse(value);
330
+ } catch (error) {
331
+ const message = error instanceof Error ? error.message : String(error);
332
+ throw new Error(`${label} must be valid JSON: ${message}`);
333
+ }
334
+ if (!isRecord(parsed))
335
+ throw new Error(`${label} must decode to a JSON object`);
336
+ return parsed;
337
+ }
338
+
339
+ // src/providers/shared/prompt.ts
340
+ function mapToolDefinitionsToLanguageModelTools(tools) {
341
+ if (!tools || tools.length === 0)
342
+ return;
343
+ return tools.map((tool) => ({
344
+ type: "function",
345
+ name: tool.name,
346
+ description: tool.description,
347
+ inputSchema: tool.inputSchema
348
+ }));
349
+ }
350
+ function messagesToLanguageModelPrompt(messages, options = {}) {
351
+ const prompt = [];
352
+ const systemContent = messages.filter((message) => message.role === "system").map((message) => contentToText(message.content)).filter(Boolean).join(`
353
+
354
+ `);
355
+ if (systemContent)
356
+ prompt.push({ role: "system", content: systemContent });
357
+ for (const message of messages) {
358
+ if (message.role === "system")
359
+ continue;
360
+ if (message.role === "tool") {
361
+ prompt.push(toolMessageToPrompt(message));
362
+ continue;
363
+ }
364
+ if (message.role === "assistant") {
365
+ const content = [
366
+ ...options.assistantPrefixParts?.(message) ?? [],
367
+ ...contentBlocksToPromptParts(message.content),
368
+ ...toolCallsToPromptParts(message.toolCalls)
369
+ ];
370
+ if (content.length > 0)
371
+ prompt.push({ role: "assistant", content });
372
+ continue;
373
+ }
374
+ prompt.push({
375
+ role: "user",
376
+ content: contentBlocksToPromptParts(message.content)
377
+ });
378
+ }
379
+ return prompt;
380
+ }
381
+ function contentBlocksToPromptParts(content) {
382
+ return content.map((block) => {
383
+ if (block.type === "text")
384
+ return { type: "text", text: block.text };
385
+ return {
386
+ type: "file",
387
+ data: block.data,
388
+ mediaType: block.mimeType
389
+ };
390
+ });
391
+ }
392
+ function toolCallsToPromptParts(toolCalls) {
393
+ if (!toolCalls || toolCalls.length === 0)
394
+ return [];
395
+ return toolCalls.map((toolCall) => ({
396
+ type: "tool-call",
397
+ toolCallId: toolCall.id,
398
+ toolName: toolCall.function.name,
399
+ input: toolCall.function.arguments
400
+ }));
401
+ }
402
+ function toolMessageToPrompt(message) {
403
+ return {
404
+ role: "tool",
405
+ content: [{
406
+ type: "tool-result",
407
+ toolCallId: message.toolCallId,
408
+ toolName: message.toolName,
409
+ output: toolMessageToOutput(message)
410
+ }]
411
+ };
412
+ }
413
+ function toolMessageToOutput(message) {
414
+ if (message.structuredContent) {
415
+ assertJsonSafeObject(message.structuredContent, "Tool structuredContent");
416
+ return {
417
+ type: "json",
418
+ value: message.structuredContent
419
+ };
420
+ }
421
+ const text = contentToText(message.content);
422
+ if (message.isError === true) {
423
+ return {
424
+ type: "json",
425
+ value: {
426
+ content: text,
427
+ isError: true
428
+ }
429
+ };
430
+ }
431
+ return {
432
+ type: "text",
433
+ value: text
434
+ };
435
+ }
436
+
437
+ // src/providers/shared/reasoning.ts
438
+ function isRecord2(value) {
439
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
440
+ }
441
+ var LOW_HIGH_REASONING_EFFORT_MAP = {
442
+ none: "low",
443
+ minimal: "low",
444
+ low: "low",
445
+ medium: "high",
446
+ high: "high",
447
+ xhigh: "high"
448
+ };
449
+ var LOW_MEDIUM_HIGH_REASONING_EFFORT_MAP = {
450
+ none: "low",
451
+ minimal: "low",
452
+ low: "low",
453
+ medium: "medium",
454
+ high: "high",
455
+ xhigh: "high"
456
+ };
457
+ function normalizeReasoningConfig(reasoning) {
458
+ if (!isRecord2(reasoning))
459
+ return;
460
+ if (reasoning.enabled === false)
461
+ return;
462
+ return reasoning;
463
+ }
464
+ function resolveReasoningBudget(reasoning, fallback = 1024) {
465
+ const normalized = normalizeReasoningConfig(reasoning);
466
+ if (!normalized)
467
+ return;
468
+ for (const key of ["budgetTokens", "budget_tokens", "thinkingBudget"]) {
469
+ const value = normalized[key];
470
+ if (typeof value === "number" && Number.isFinite(value) && value > 0)
471
+ return Math.floor(value);
472
+ }
473
+ return fallback;
474
+ }
475
+ function resolveReasoningEffort(reasoning, allowedValues) {
476
+ const normalized = normalizeReasoningConfig(reasoning);
477
+ if (!normalized)
478
+ return;
479
+ const rawEffort = normalized.reasoningEffort ?? normalized.effort;
480
+ if (typeof rawEffort !== "string" || rawEffort.length === 0)
481
+ return;
482
+ if (!allowedValues || allowedValues.includes(rawEffort))
483
+ return rawEffort;
484
+ return;
485
+ }
486
+ function resolveLowHighReasoningEffort(reasoning) {
487
+ const normalized = normalizeReasoningConfig(reasoning);
488
+ if (!normalized)
489
+ return;
490
+ const rawEffort = normalized.reasoningEffort ?? normalized.effort;
491
+ return typeof rawEffort === "string" ? LOW_HIGH_REASONING_EFFORT_MAP[rawEffort] : undefined;
492
+ }
493
+ function resolveLowMediumHighReasoningEffort(reasoning) {
494
+ const normalized = normalizeReasoningConfig(reasoning);
495
+ if (!normalized)
496
+ return;
497
+ const rawEffort = normalized.reasoningEffort ?? normalized.effort;
498
+ return typeof rawEffort === "string" ? LOW_MEDIUM_HIGH_REASONING_EFFORT_MAP[rawEffort] : undefined;
499
+ }
500
+ function buildOpenAIResponsesProviderOptions(reasoning) {
501
+ const normalized = normalizeReasoningConfig(reasoning);
502
+ if (!normalized)
503
+ return;
504
+ const next = {};
505
+ for (const [key, value] of Object.entries(normalized)) {
506
+ if (key === "enabled" || key === "budgetTokens" || key === "budget_tokens" || key === "thinkingBudget" || key === "includeThoughts")
507
+ continue;
508
+ if (key === "effort") {
509
+ next.reasoningEffort = value;
510
+ continue;
511
+ }
512
+ if (key === "summary") {
513
+ next.reasoningSummary = value;
514
+ continue;
515
+ }
516
+ next[key] = value;
517
+ }
518
+ if (next.reasoningSummary === undefined)
519
+ next.reasoningSummary = "auto";
520
+ return next;
521
+ }
522
+ function buildOpenAIResponsesRequestReasoning(reasoning) {
523
+ const options = buildOpenAIResponsesProviderOptions(reasoning);
524
+ if (!options)
525
+ return;
526
+ const next = {};
527
+ if (typeof options.reasoningEffort === "string")
528
+ next.effort = options.reasoningEffort;
529
+ if (typeof options.reasoningSummary === "string")
530
+ next.summary = options.reasoningSummary;
531
+ return next.effort || next.summary ? next : undefined;
532
+ }
533
+ function buildReasoningEffortProviderOptions(reasoning, allowedValues) {
534
+ const reasoningEffort = resolveReasoningEffort(reasoning, allowedValues);
535
+ return reasoningEffort ? { reasoningEffort } : undefined;
536
+ }
537
+ function buildAnthropicThinkingProviderOptions(reasoning) {
538
+ const budget = resolveReasoningBudget(reasoning);
539
+ if (!budget)
540
+ return { thinking: undefined, sendReasoning: undefined };
541
+ return {
542
+ thinking: {
543
+ type: "enabled",
544
+ budgetTokens: budget
545
+ },
546
+ sendReasoning: true
547
+ };
548
+ }
549
+ function buildGeminiThinkingProviderOptions(reasoning) {
550
+ const normalized = normalizeReasoningConfig(reasoning);
551
+ if (!normalized)
552
+ return;
553
+ return {
554
+ thinkingConfig: {
555
+ thinkingBudget: resolveReasoningBudget(normalized) ?? 1024,
556
+ includeThoughts: normalized.includeThoughts !== false
557
+ }
558
+ };
559
+ }
560
+ function buildMoonshotThinkingProviderOptions(reasoning) {
561
+ const budget = resolveReasoningBudget(reasoning);
562
+ if (!budget)
563
+ return;
564
+ return {
565
+ thinking: {
566
+ type: "enabled",
567
+ budgetTokens: budget
568
+ }
569
+ };
570
+ }
571
+ function buildDeepSeekThinkingProviderOptions(reasoning) {
572
+ return normalizeReasoningConfig(reasoning) ? { thinking: { type: "enabled" } } : undefined;
573
+ }
574
+
575
+ // src/providers/shared/provider-state.ts
576
+ var PROVIDER_STATE_METADATA_KEY = "_dimProviderState";
577
+ function attachProviderState(metadata, provider, state) {
578
+ if (!state || Object.keys(state).length === 0)
579
+ return metadata;
580
+ const nextMetadata = metadata ? structuredClone(metadata) : {};
581
+ const currentBag = isRecord3(nextMetadata[PROVIDER_STATE_METADATA_KEY]) ? nextMetadata[PROVIDER_STATE_METADATA_KEY] : {};
582
+ nextMetadata[PROVIDER_STATE_METADATA_KEY] = {
583
+ ...currentBag,
584
+ [provider]: structuredClone(state)
585
+ };
586
+ return nextMetadata;
587
+ }
588
+ function readProviderState(message, provider) {
589
+ if (message.role !== "assistant" || !isRecord3(message.metadata))
590
+ return;
591
+ const bag = message.metadata[PROVIDER_STATE_METADATA_KEY];
592
+ if (!isRecord3(bag))
593
+ return;
594
+ const state = bag[provider];
595
+ return isRecord3(state) ? structuredClone(state) : undefined;
596
+ }
597
+ function isRecord3(value) {
598
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
599
+ }
600
+
601
+ // src/providers/gemini/state.ts
602
+ var GEMINI_STATE_KEY = "gemini";
603
+ function geminiAssistantPrefixParts(message) {
604
+ const state = readProviderState(message, GEMINI_STATE_KEY);
605
+ const rawParts = state?.parts;
606
+ if (!Array.isArray(rawParts))
607
+ return [];
608
+ const parts = [];
609
+ for (const rawPart of rawParts) {
610
+ if (!isRecord(rawPart))
611
+ continue;
612
+ const thoughtSignature = typeof rawPart.thoughtSignature === "string" ? rawPart.thoughtSignature : undefined;
613
+ if (isRecord(rawPart.functionCall) && typeof rawPart.functionCall.name === "string") {
614
+ parts.push({
615
+ type: "tool-call",
616
+ toolCallId: crypto.randomUUID(),
617
+ toolName: rawPart.functionCall.name,
618
+ input: isRecord(rawPart.functionCall.args) ? rawPart.functionCall.args : {},
619
+ ...thoughtSignature ? {
620
+ providerOptions: {
621
+ google: {
622
+ thoughtSignature
623
+ }
624
+ }
625
+ } : {}
626
+ });
627
+ continue;
628
+ }
629
+ if (typeof rawPart.text === "string") {
630
+ parts.push({
631
+ type: rawPart.thought === true ? "reasoning" : "text",
632
+ text: rawPart.text,
633
+ ...thoughtSignature ? {
634
+ providerOptions: {
635
+ google: {
636
+ thoughtSignature
637
+ }
638
+ }
639
+ } : {}
640
+ });
641
+ }
642
+ }
643
+ return parts;
644
+ }
645
+ function createGeminiAssistantMetadata(result) {
646
+ const parts = result.content.flatMap((part) => {
647
+ const metadata = part.providerMetadata?.google;
648
+ const thoughtSignature = isRecord(metadata) && typeof metadata.thoughtSignature === "string" ? metadata.thoughtSignature : undefined;
649
+ if (!thoughtSignature && part.type !== "reasoning")
650
+ return [];
651
+ if (part.type === "reasoning") {
652
+ return [{
653
+ text: part.text,
654
+ thought: true,
655
+ thoughtSignature
656
+ }];
657
+ }
658
+ if (part.type === "tool-call") {
659
+ return [{
660
+ functionCall: {
661
+ name: part.toolName,
662
+ args: parseToolArguments(part.input)
663
+ },
664
+ thoughtSignature
665
+ }];
666
+ }
667
+ if (part.type === "text") {
668
+ return [{
669
+ text: part.text,
670
+ thoughtSignature
671
+ }];
672
+ }
673
+ return [];
674
+ });
675
+ if (parts.length === 0)
676
+ return;
677
+ return attachProviderState(undefined, GEMINI_STATE_KEY, { parts });
678
+ }
679
+ function parseToolArguments(input) {
680
+ try {
681
+ const parsed = JSON.parse(input);
682
+ return isRecord(parsed) ? parsed : {};
683
+ } catch {
684
+ return {};
685
+ }
686
+ }
687
+
688
+ // src/providers/gemini/driver.ts
689
+ var DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
690
+ var PLACEHOLDER_API_KEY = "dim-placeholder-key";
691
+ var geminiDriver = {
692
+ async generate(context) {
693
+ const model = createProvider(context.options)(context.request.model.modelId);
694
+ const googleProviderOptions = buildGeminiThinkingProviderOptions(context.request.reasoning);
695
+ const callOptions = {
696
+ prompt: messagesToLanguageModelPrompt(context.request.messages, {
697
+ assistantPrefixParts: geminiAssistantPrefixParts
698
+ }),
699
+ tools: mapToolDefinitionsToLanguageModelTools(context.request.tools),
700
+ maxOutputTokens: context.request.maxOutputTokens,
701
+ temperature: context.request.temperature,
702
+ topP: context.request.topP,
703
+ stopSequences: context.request.stop,
704
+ abortSignal: context.request.signal,
705
+ ...googleProviderOptions ? { providerOptions: { google: googleProviderOptions } } : {}
706
+ };
707
+ return generateWithAiSdk({
708
+ model,
709
+ callOptions,
710
+ createAssistantMetadata: createGeminiAssistantMetadata
711
+ });
712
+ },
713
+ normalizeError(error) {
714
+ if (APICallError.isInstance(error)) {
715
+ return createApiCallErrorPayload({
716
+ code: "gemini_http_error",
717
+ provider: "Gemini",
718
+ error
719
+ });
720
+ }
721
+ return createRequestErrorPayload({
722
+ code: "gemini_request_error",
723
+ error
724
+ });
725
+ }
726
+ };
727
+ function createProvider(options) {
728
+ const stripApiKey = !options.apiKey && !hasHeader(options.headers, "x-goog-api-key");
729
+ warnIfPlaceholderApiKey({
730
+ provider: "Gemini",
731
+ shouldWarn: stripApiKey
732
+ });
733
+ return createGoogleGenerativeAI({
734
+ apiKey: options.apiKey ?? PLACEHOLDER_API_KEY,
735
+ baseURL: normalizeBaseUrl(options.baseUrl),
736
+ headers: options.headers,
737
+ fetch: createProviderFetch({
738
+ fetch: options.fetch,
739
+ stripHeaders: ["x-goog-api-key"],
740
+ stripWhen: stripApiKey
741
+ })
742
+ });
743
+ }
744
+ function normalizeBaseUrl(baseUrl) {
745
+ const normalized = (baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
746
+ return normalized.endsWith("/v1beta") ? normalized : `${normalized}/v1beta`;
747
+ }
748
+
749
+ // src/providers/gemini/adapter.ts
750
+ var createGeminiAdapter = createProviderFactory({
751
+ defaultProvider: "gemini",
752
+ driver: geminiDriver
753
+ });
754
+ export {
755
+ createGeminiAdapter
756
+ };