@clearideas/agent-runtime-model-ai-sdk 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import type { JsonObject, ToolCall } from "@clearideas/agent-runtime-contracts";
2
2
  import type { ModelAdapter, ModelRequest, ModelResult } from "@clearideas/agent-runtime-core/ports";
3
- import { type LanguageModel, type ModelMessage as AiSdkModelMessage, type ToolSet } from "ai";
3
+ import { type LanguageModel, type ModelMessage as AiSdkModelMessage, type SystemModelMessage, type ToolSet } from "ai";
4
4
  export type ModelResolver = (model: string) => LanguageModel;
5
5
  export type ProviderModelFactory = (modelId: string) => LanguageModel;
6
6
  export interface ProviderRegistryOptions {
@@ -15,7 +15,7 @@ export declare const parseModelKey: (value: string, defaultProvider?: string) =>
15
15
  export declare const createProviderRegistryModelResolver: (providers: Readonly<Record<string, ProviderModelFactory>>, options?: ProviderRegistryOptions) => ModelResolver;
16
16
  export interface AiSdkCallOptions {
17
17
  model: LanguageModel;
18
- system?: string;
18
+ system?: string | SystemModelMessage | SystemModelMessage[];
19
19
  messages: AiSdkModelMessage[];
20
20
  tools?: ToolSet;
21
21
  output?: unknown;
@@ -40,6 +40,7 @@ export interface AiSdkToolCall {
40
40
  toolCallId: string;
41
41
  toolName: string;
42
42
  input: unknown;
43
+ providerExecuted?: boolean;
43
44
  }
44
45
  export interface AiSdkGenerateResult {
45
46
  text: string;
@@ -48,6 +49,7 @@ export interface AiSdkGenerateResult {
48
49
  finishReason?: string;
49
50
  totalUsage?: AiSdkUsage;
50
51
  providerMetadata?: unknown;
52
+ responseMessages?: readonly AiSdkModelMessage[];
51
53
  output?: unknown;
52
54
  }
53
55
  export interface AiSdkStreamPart {
@@ -67,6 +69,7 @@ export interface AiSdkStreamPart {
67
69
  export interface AiSdkStreamResult {
68
70
  fullStream: AsyncIterable<AiSdkStreamPart>;
69
71
  output?: PromiseLike<unknown> | unknown;
72
+ responseMessages?: PromiseLike<readonly AiSdkModelMessage[]> | readonly AiSdkModelMessage[];
70
73
  }
71
74
  export type GenerateTextFunction = (options: AiSdkCallOptions) => Promise<AiSdkGenerateResult>;
72
75
  export type StreamTextFunction = (options: AiSdkCallOptions) => AiSdkStreamResult;
@@ -30,6 +30,16 @@ const defaultStreamText = (options) => {
30
30
  const result = streamText(options);
31
31
  return result;
32
32
  };
33
+ const combinedProviderOptions = (message) => {
34
+ const combined = {};
35
+ for (const part of message.content) {
36
+ if (part.providerOptions)
37
+ Object.assign(combined, part.providerOptions);
38
+ }
39
+ if (message.providerOptions)
40
+ Object.assign(combined, message.providerOptions);
41
+ return Object.keys(combined).length > 0 ? combined : undefined;
42
+ };
33
43
  /**
34
44
  * Keeps AI SDK provider and message types behind the neutral ModelAdapter port.
35
45
  * Tool definitions are advertised without execute functions; Agent Runtime owns
@@ -83,6 +93,9 @@ export class AiSdkModelAdapter {
83
93
  toolCallId: part.toolCallId,
84
94
  toolName: part.toolName,
85
95
  input: part.input,
96
+ ...(typeof part.providerExecuted === "boolean"
97
+ ? { providerExecuted: part.providerExecuted }
98
+ : {}),
86
99
  });
87
100
  toolCalls.push(call);
88
101
  yield { type: "tool-call", call };
@@ -114,6 +127,9 @@ export class AiSdkModelAdapter {
114
127
  }
115
128
  }
116
129
  const structuredOutput = request.outputSchema == null ? undefined : await result.output;
130
+ const responseMessages = result.responseMessages == null
131
+ ? undefined
132
+ : await result.responseMessages;
117
133
  const completed = this.#buildModelResult({
118
134
  request,
119
135
  text,
@@ -123,15 +139,30 @@ export class AiSdkModelAdapter {
123
139
  usage,
124
140
  providerMetadata,
125
141
  structuredOutput,
142
+ responseMessages,
126
143
  });
127
144
  yield { type: "completed", result: completed };
128
145
  }
129
146
  #toCallOptions(request) {
130
- const system = request.messages
147
+ const systemMessages = request.messages
131
148
  .filter((message) => message.role === "system")
132
- .map((message) => partsAsText(message.content))
133
- .filter(Boolean)
134
- .join("\n\n");
149
+ .map((message) => {
150
+ const providerOptions = combinedProviderOptions(message);
151
+ return {
152
+ role: "system",
153
+ content: partsAsText(message.content),
154
+ ...(providerOptions
155
+ ? { providerOptions: providerOptions }
156
+ : {}),
157
+ };
158
+ })
159
+ .filter((message) => message.content.length > 0);
160
+ const hasSystemProviderOptions = systemMessages.some((message) => message.providerOptions != null);
161
+ const system = systemMessages.length === 0
162
+ ? undefined
163
+ : hasSystemProviderOptions
164
+ ? systemMessages
165
+ : systemMessages.map((message) => message.content).join("\n\n");
135
166
  const options = {
136
167
  model: this.#resolveModel(request.model),
137
168
  ...(system ? { system } : {}),
@@ -168,6 +199,7 @@ export class AiSdkModelAdapter {
168
199
  finishReason: result.finishReason,
169
200
  usage: result.totalUsage,
170
201
  providerMetadata: result.providerMetadata,
202
+ responseMessages: result.responseMessages,
171
203
  structuredOutput: request.outputSchema == null ? undefined : result.output,
172
204
  });
173
205
  }
@@ -180,22 +212,32 @@ export class AiSdkModelAdapter {
180
212
  content.push({ type: "text", text: input.text });
181
213
  }
182
214
  content.push(...input.toolCalls.map((call) => ({ type: "tool-call", call })));
183
- const transcriptItem = {
184
- id: this.#generateTranscriptId(),
185
- type: "message",
186
- role: "assistant",
187
- content,
188
- createdAt: this.#now().toISOString(),
189
- model: input.request.model,
190
- };
215
+ const transcript = input.responseMessages == null || input.responseMessages.length === 0
216
+ ? [
217
+ {
218
+ id: this.#generateTranscriptId(),
219
+ type: "message",
220
+ role: "assistant",
221
+ content,
222
+ createdAt: this.#now().toISOString(),
223
+ model: input.request.model,
224
+ },
225
+ ]
226
+ : input.responseMessages.flatMap((message) => {
227
+ const item = fromAiSdkResponseMessage(message, this.#generateTranscriptId(), this.#now().toISOString(), input.request.model);
228
+ return item == null ? [] : [item];
229
+ });
191
230
  const mappedUsage = toModelUsage(input.usage);
192
- if (mappedUsage != null)
193
- transcriptItem.usage = mappedUsage;
231
+ const usageItem = [...transcript]
232
+ .reverse()
233
+ .find((item) => item.role === "assistant");
234
+ if (mappedUsage != null && usageItem != null)
235
+ usageItem.usage = mappedUsage;
194
236
  const modelResult = {
195
237
  output: input.structuredOutput === undefined
196
238
  ? input.text
197
239
  : toJsonValue(input.structuredOutput),
198
- transcript: [transcriptItem],
240
+ transcript,
199
241
  toolCalls: input.toolCalls,
200
242
  };
201
243
  if (input.finishReason != null) {
@@ -221,46 +263,112 @@ function toAiSdkTools(tools) {
221
263
  }),
222
264
  ]));
223
265
  }
224
- function toAiSdkMessage(message) {
225
- if (message.role === "tool") {
226
- const content = [];
227
- for (const part of message.content) {
228
- if (part.type !== "tool-result")
229
- continue;
230
- const output = part.result.error == null
231
- ? { type: "json", value: part.result.output ?? null }
266
+ const contentProviderOptions = (part) => part.providerOptions
267
+ ? { providerOptions: part.providerOptions }
268
+ : {};
269
+ const messageProviderOptions = (message) => message.providerOptions
270
+ ? { providerOptions: message.providerOptions }
271
+ : {};
272
+ const mediaSource = (part) => {
273
+ if (part.data != null)
274
+ return part.data;
275
+ const uri = part.url ?? part.artifact?.uri;
276
+ if (uri != null)
277
+ return new URL(uri);
278
+ throw new Error(`${part.type} content requires resolvable data or a URL`);
279
+ };
280
+ const mediaType = (part) => {
281
+ const value = part.mediaType ?? part.artifact?.mediaType;
282
+ if (value == null) {
283
+ throw new Error(`${part.type} content requires a media type`);
284
+ }
285
+ return value;
286
+ };
287
+ const toAiSdkToolResultPart = (part) => {
288
+ const result = part.result;
289
+ let output;
290
+ if (result.artifacts != null && result.artifacts.length > 0) {
291
+ const value = [];
292
+ if (result.output !== undefined) {
293
+ value.push({
294
+ type: "text",
295
+ text: typeof result.output === "string"
296
+ ? result.output
297
+ : JSON.stringify(result.output),
298
+ });
299
+ }
300
+ for (const artifact of result.artifacts) {
301
+ if (artifact.uri == null) {
302
+ throw new Error(`Historical tool artifact ${artifact.id} requires a URI`);
303
+ }
304
+ value.push({
305
+ type: "file",
306
+ data: new URL(artifact.uri),
307
+ mediaType: artifact.mediaType,
308
+ filename: artifact.name,
309
+ });
310
+ }
311
+ output = { type: "content", value };
312
+ }
313
+ else {
314
+ output =
315
+ result.error == null
316
+ ? { type: "json", value: result.output ?? null }
232
317
  : {
233
318
  type: "json",
234
319
  value: {
235
320
  error: {
236
- code: part.result.error.code,
237
- message: part.result.error.message,
321
+ code: result.error.code,
322
+ message: result.error.message,
238
323
  },
239
324
  },
240
325
  };
241
- content.push({
242
- type: "tool-result",
243
- toolCallId: part.result.callId,
244
- toolName: part.result.name,
245
- output,
246
- });
247
- }
248
- return { role: "tool", content };
326
+ }
327
+ return {
328
+ type: "tool-result",
329
+ toolCallId: result.callId,
330
+ toolName: result.name,
331
+ output,
332
+ ...contentProviderOptions(part),
333
+ };
334
+ };
335
+ function toAiSdkMessage(message) {
336
+ if (message.role === "system") {
337
+ throw new Error("System messages must be mapped as model instructions");
338
+ }
339
+ if (message.role === "tool") {
340
+ const content = message.content.map((part) => {
341
+ if (part.type !== "tool-result") {
342
+ throw new Error(`Tool messages cannot contain ${part.type} content`);
343
+ }
344
+ return toAiSdkToolResultPart(part);
345
+ });
346
+ return { role: "tool", content, ...messageProviderOptions(message) };
249
347
  }
250
348
  if (message.role === "assistant") {
251
349
  const content = [];
252
350
  for (const part of message.content) {
253
351
  switch (part.type) {
254
352
  case "text":
255
- content.push({ type: "text", text: part.text });
353
+ content.push({
354
+ type: "text",
355
+ text: part.text,
356
+ ...contentProviderOptions(part),
357
+ });
256
358
  break;
257
359
  case "reasoning":
258
- if (part.text != null) {
259
- content.push({ type: "reasoning", text: part.text });
260
- }
360
+ content.push({
361
+ type: "reasoning",
362
+ text: part.text ?? "",
363
+ ...contentProviderOptions(part),
364
+ });
261
365
  break;
262
366
  case "json":
263
- content.push({ type: "text", text: JSON.stringify(part.value) });
367
+ content.push({
368
+ type: "text",
369
+ text: JSON.stringify(part.value),
370
+ ...contentProviderOptions(part),
371
+ });
264
372
  break;
265
373
  case "tool-call":
266
374
  content.push({
@@ -268,45 +376,233 @@ function toAiSdkMessage(message) {
268
376
  toolCallId: part.call.id,
269
377
  toolName: part.call.name,
270
378
  input: part.call.input,
379
+ ...(part.call.providerExecuted != null
380
+ ? { providerExecuted: part.call.providerExecuted }
381
+ : {}),
382
+ ...contentProviderOptions(part),
271
383
  });
272
384
  break;
273
- default:
385
+ case "tool-result":
386
+ content.push(toAiSdkToolResultPart(part));
387
+ break;
388
+ case "image":
389
+ case "file":
390
+ content.push({
391
+ type: "file",
392
+ data: mediaSource(part),
393
+ mediaType: mediaType(part),
394
+ ...(part.type === "file" && (part.name ?? part.artifact?.name)
395
+ ? { filename: (part.name ?? part.artifact?.name) }
396
+ : {}),
397
+ ...contentProviderOptions(part),
398
+ });
274
399
  break;
400
+ default:
401
+ throw new Error(`Unsupported assistant content`);
275
402
  }
276
403
  }
277
- return { role: "assistant", content };
404
+ return {
405
+ role: "assistant",
406
+ content,
407
+ ...messageProviderOptions(message),
408
+ };
278
409
  }
279
410
  const content = [];
280
411
  for (const part of message.content) {
281
412
  switch (part.type) {
282
413
  case "text":
283
- content.push({ type: "text", text: part.text });
414
+ content.push({
415
+ type: "text",
416
+ text: part.text,
417
+ ...contentProviderOptions(part),
418
+ });
284
419
  break;
285
420
  case "json":
286
- content.push({ type: "text", text: JSON.stringify(part.value) });
421
+ content.push({
422
+ type: "text",
423
+ text: JSON.stringify(part.value),
424
+ ...contentProviderOptions(part),
425
+ });
287
426
  break;
288
- case "image": {
289
- const url = part.url ?? part.artifact?.uri;
290
- if (url != null)
291
- content.push({ type: "image", image: new URL(url) });
427
+ case "image":
428
+ content.push({
429
+ type: "image",
430
+ image: mediaSource(part),
431
+ ...((part.mediaType ?? part.artifact?.mediaType)
432
+ ? { mediaType: (part.mediaType ?? part.artifact?.mediaType) }
433
+ : {}),
434
+ ...contentProviderOptions(part),
435
+ });
292
436
  break;
293
- }
294
- case "file": {
295
- const uri = part.artifact.uri;
296
- if (uri != null) {
297
- content.push({
298
- type: "file",
299
- data: new URL(uri),
300
- mediaType: part.artifact.mediaType,
301
- });
302
- }
437
+ case "file":
438
+ content.push({
439
+ type: "file",
440
+ data: mediaSource(part),
441
+ mediaType: mediaType(part),
442
+ ...((part.name ?? part.artifact?.name)
443
+ ? { filename: (part.name ?? part.artifact?.name) }
444
+ : {}),
445
+ ...contentProviderOptions(part),
446
+ });
303
447
  break;
304
- }
305
448
  default:
306
- break;
449
+ throw new Error(`User messages cannot contain ${part.type} content`);
307
450
  }
308
451
  }
309
- return { role: "user", content };
452
+ return { role: "user", content, ...messageProviderOptions(message) };
453
+ }
454
+ const fromAiSdkProviderOptions = (value) => toJsonObject(value);
455
+ const fromAiSdkPartOptions = (part) => part.providerOptions == null
456
+ ? {}
457
+ : {
458
+ providerOptions: fromAiSdkProviderOptions(part.providerOptions) ?? {
459
+ value: toJsonValue(part.providerOptions),
460
+ },
461
+ };
462
+ const bytesAsBase64 = (bytes) => {
463
+ let binary = "";
464
+ const chunkSize = 32_768;
465
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
466
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
467
+ }
468
+ return btoa(binary);
469
+ };
470
+ const fromAiSdkFile = (part) => {
471
+ const data = part.data;
472
+ const source = data instanceof URL
473
+ ? { url: data.href }
474
+ : typeof data === "string"
475
+ ? { data }
476
+ : data instanceof Uint8Array
477
+ ? { data: bytesAsBase64(data) }
478
+ : typeof data === "object" &&
479
+ data != null &&
480
+ "type" in data &&
481
+ data.type === "url" &&
482
+ "url" in data
483
+ ? {
484
+ url: data.url instanceof URL ? data.url.href : String(data.url),
485
+ }
486
+ : (() => {
487
+ throw new Error("AI SDK returned file content that cannot be durably replayed");
488
+ })();
489
+ const mediaType = typeof part.mediaType === "string" ? part.mediaType : undefined;
490
+ if (mediaType == null) {
491
+ throw new Error("AI SDK returned file content without a media type");
492
+ }
493
+ return {
494
+ type: "file",
495
+ ...source,
496
+ mediaType,
497
+ ...(typeof part.filename === "string" ? { name: part.filename } : {}),
498
+ ...fromAiSdkPartOptions(part),
499
+ };
500
+ };
501
+ const fromAiSdkToolOutput = (output) => {
502
+ if (typeof output !== "object" || output == null) {
503
+ return { output: toJsonValue(output) };
504
+ }
505
+ const record = output;
506
+ switch (record.type) {
507
+ case "text":
508
+ case "json":
509
+ return { output: toJsonValue(record.value) };
510
+ case "error-text":
511
+ case "error-json":
512
+ return {
513
+ error: {
514
+ code: "tool_error",
515
+ message: typeof record.value === "string"
516
+ ? record.value
517
+ : JSON.stringify(record.value),
518
+ },
519
+ };
520
+ case "execution-denied":
521
+ return {
522
+ error: {
523
+ code: "tool_execution_denied",
524
+ message: typeof record.reason === "string"
525
+ ? record.reason
526
+ : "Tool execution was denied.",
527
+ },
528
+ };
529
+ default:
530
+ return { output: toJsonValue(output) };
531
+ }
532
+ };
533
+ const fromAiSdkToolResult = (part) => {
534
+ if (typeof part.toolCallId !== "string" ||
535
+ typeof part.toolName !== "string") {
536
+ throw new Error("AI SDK returned an invalid tool result");
537
+ }
538
+ return {
539
+ type: "tool-result",
540
+ result: {
541
+ callId: part.toolCallId,
542
+ name: part.toolName,
543
+ ...fromAiSdkToolOutput(part.output),
544
+ },
545
+ ...fromAiSdkPartOptions(part),
546
+ };
547
+ };
548
+ function fromAiSdkResponseMessage(message, id, createdAt, model) {
549
+ if (message.role !== "assistant" && message.role !== "tool")
550
+ return undefined;
551
+ const rawContent = typeof message.content === "string"
552
+ ? [{ type: "text", text: message.content }]
553
+ : message.content;
554
+ const content = rawContent.map((rawPart) => {
555
+ const part = rawPart;
556
+ switch (part.type) {
557
+ case "text":
558
+ return {
559
+ type: "text",
560
+ text: typeof part.text === "string" ? part.text : "",
561
+ ...fromAiSdkPartOptions(part),
562
+ };
563
+ case "reasoning":
564
+ return {
565
+ type: "reasoning",
566
+ ...(typeof part.text === "string" ? { text: part.text } : {}),
567
+ ...fromAiSdkPartOptions(part),
568
+ };
569
+ case "tool-call":
570
+ if (typeof part.toolCallId !== "string" ||
571
+ typeof part.toolName !== "string") {
572
+ throw new Error("AI SDK returned an invalid tool call");
573
+ }
574
+ return {
575
+ type: "tool-call",
576
+ call: {
577
+ id: part.toolCallId,
578
+ name: part.toolName,
579
+ input: toJsonObject(part.input) ?? {
580
+ value: toJsonValue(part.input),
581
+ },
582
+ ...(typeof part.providerExecuted === "boolean"
583
+ ? { providerExecuted: part.providerExecuted }
584
+ : {}),
585
+ },
586
+ ...fromAiSdkPartOptions(part),
587
+ };
588
+ case "tool-result":
589
+ return fromAiSdkToolResult(part);
590
+ case "file":
591
+ return fromAiSdkFile(part);
592
+ default:
593
+ throw new Error(`AI SDK returned unsupported replay content: ${String(part.type)}`);
594
+ }
595
+ });
596
+ const providerOptions = fromAiSdkProviderOptions(message.providerOptions);
597
+ return {
598
+ id,
599
+ type: message.role === "tool" ? "tool-result" : "message",
600
+ role: message.role,
601
+ content,
602
+ createdAt,
603
+ model,
604
+ ...(providerOptions ? { providerOptions } : {}),
605
+ };
310
606
  }
311
607
  function partsAsText(parts) {
312
608
  return parts
@@ -327,6 +623,9 @@ function toToolCall(call) {
327
623
  id: call.toolCallId,
328
624
  name: call.toolName,
329
625
  input: toJsonObject(call.input) ?? { value: toJsonValue(call.input) },
626
+ ...(call.providerExecuted != null
627
+ ? { providerExecuted: call.providerExecuted }
628
+ : {}),
330
629
  };
331
630
  }
332
631
  function toModelUsage(usage) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clearideas/agent-runtime-model-ai-sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "AI SDK model adapter for the vendor-neutral Clear Ideas Agent Runtime.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Clear Ideas Incorporated",
@@ -36,9 +36,9 @@
36
36
  "postpack": "node ../../scripts/cleanup-package-license.mjs"
37
37
  },
38
38
  "dependencies": {
39
- "@clearideas/agent-runtime-contracts": "0.2.0",
40
- "@clearideas/agent-runtime-core": "0.2.0",
41
- "ai": "^7.0.41"
39
+ "@clearideas/agent-runtime-contracts": "0.3.1",
40
+ "@clearideas/agent-runtime-core": "0.3.1",
41
+ "ai": "^7.0.47"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^7.0.2",