@mupt-ai/dari-gateway 0.0.0-stage → 0.2.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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +135 -2
  3. package/dari-gateway.example.yaml +28 -0
  4. package/package.json +42 -4
  5. package/src/bun.ts +4 -0
  6. package/src/context/eval_catalog.ts +11 -0
  7. package/src/context/interaction_fingerprint.ts +691 -0
  8. package/src/context/interaction_fingerprint_format.ts +189 -0
  9. package/src/context/interaction_lease_depth.ts +150 -0
  10. package/src/context/lease_history.ts +200 -0
  11. package/src/context/pricing.ts +30 -0
  12. package/src/context/provider_prompt_accounting.ts +241 -0
  13. package/src/context/routing_context.ts +337 -0
  14. package/src/http/auth.ts +43 -0
  15. package/src/http/errors.ts +114 -0
  16. package/src/http/handler.ts +110 -0
  17. package/src/http/http2_server.ts +122 -0
  18. package/src/http/serve.ts +119 -0
  19. package/src/index.ts +22 -0
  20. package/src/ingress/anthropic_messages.ts +162 -0
  21. package/src/ingress/anthropic_models.ts +28 -0
  22. package/src/ingress/chat_completions.ts +49 -0
  23. package/src/ingress/claude_code/request_context.ts +36 -0
  24. package/src/ingress/codex.ts +81 -0
  25. package/src/ingress/codex_models.ts +113 -0
  26. package/src/ingress/json.ts +113 -0
  27. package/src/ingress/models.ts +55 -0
  28. package/src/interaction/capabilities.ts +30 -0
  29. package/src/interaction/image.ts +12 -0
  30. package/src/interaction/portable_reasoning_state.ts +25 -0
  31. package/src/interaction/provider_continuation_state.ts +36 -0
  32. package/src/interaction/tool_identity.ts +65 -0
  33. package/src/interaction/types.ts +282 -0
  34. package/src/models/context_limits.ts +8 -0
  35. package/src/models/execution_provider.ts +22 -0
  36. package/src/models/gateways.ts +73 -0
  37. package/src/models/ids.ts +26 -0
  38. package/src/models/provider_defaults.ts +47 -0
  39. package/src/models/runtime_overrides.ts +221 -0
  40. package/src/observability/errors.ts +25 -0
  41. package/src/platform/platform.ts +204 -0
  42. package/src/platform/routing_contract.ts +6 -0
  43. package/src/protocol/input/anthropic_messages.ts +531 -0
  44. package/src/protocol/input/chat_completions.ts +255 -0
  45. package/src/protocol/input/chat_completions_validation.ts +293 -0
  46. package/src/protocol/input/openai_responses.ts +749 -0
  47. package/src/protocol/input/router_model.ts +53 -0
  48. package/src/protocol/output/anthropic_messages.ts +32 -0
  49. package/src/protocol/output/anthropic_messages_output.ts +129 -0
  50. package/src/protocol/output/anthropic_messages_stream.ts +281 -0
  51. package/src/protocol/output/chat_completions.ts +451 -0
  52. package/src/protocol/output/chat_reasoning_detail.ts +19 -0
  53. package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
  54. package/src/protocol/output/openai_responses.ts +30 -0
  55. package/src/protocol/output/openai_responses_output.ts +159 -0
  56. package/src/protocol/output/openai_responses_stream.ts +631 -0
  57. package/src/protocol/output/sse_stream.ts +102 -0
  58. package/src/providers/anthropic_safeguards.ts +115 -0
  59. package/src/providers/aws_assume_role.ts +147 -0
  60. package/src/providers/cancel_estimate.ts +140 -0
  61. package/src/providers/execution.ts +800 -0
  62. package/src/providers/model_capabilities.ts +50 -0
  63. package/src/providers/pi.ts +499 -0
  64. package/src/providers/pi_context.ts +466 -0
  65. package/src/providers/pi_options.ts +416 -0
  66. package/src/providers/pi_output.ts +500 -0
  67. package/src/providers/provider_attempt_runner.ts +153 -0
  68. package/src/providers/provider_call.ts +433 -0
  69. package/src/providers/provider_reported_cost.ts +138 -0
  70. package/src/providers/reasoning.ts +59 -0
  71. package/src/providers/response_capture.ts +65 -0
  72. package/src/providers/stream_finalization.ts +264 -0
  73. package/src/providers/subscription_limits.ts +208 -0
  74. package/src/providers/subscription_usage.ts +99 -0
  75. package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
  76. package/src/runtime/customer_disconnect.ts +66 -0
  77. package/src/runtime/explicit_model.ts +86 -0
  78. package/src/runtime/harness_identity/conversation.ts +87 -0
  79. package/src/runtime/harness_identity/extract.ts +323 -0
  80. package/src/runtime/harness_identity/index.ts +14 -0
  81. package/src/runtime/prepare_routed_completion.ts +224 -0
  82. package/src/runtime/provider_stream_lifecycle.ts +105 -0
  83. package/src/runtime/provider_stream_outcome.ts +83 -0
  84. package/src/runtime/request_tags.ts +34 -0
  85. package/src/runtime/routed_completion.ts +102 -0
  86. package/src/runtime/routed_protocol.ts +33 -0
  87. package/src/runtime/routed_runtime.ts +722 -0
  88. package/src/runtime/routing_lease.ts +273 -0
  89. package/src/runtime/runtime_reporter.ts +115 -0
  90. package/src/self_host/config.ts +173 -0
  91. package/src/self_host/main.ts +104 -0
  92. package/src/self_host/platform.ts +63 -0
  93. package/src/self_host/prefix_store.ts +315 -0
  94. package/src/self_host/resolve.ts +240 -0
  95. package/src/self_host/subscriptions/access.ts +43 -0
  96. package/src/self_host/subscriptions/http.ts +204 -0
  97. package/src/self_host/subscriptions/index.ts +43 -0
  98. package/src/self_host/subscriptions/oauth.ts +395 -0
  99. package/src/self_host/subscriptions/store.ts +339 -0
  100. package/src/strategies/auto_routing_selector.ts +72 -0
  101. package/src/strategies/eval_relevance.ts +57 -0
  102. package/src/strategies/fallback_decision.ts +30 -0
  103. package/src/strategies/priority_selector.ts +40 -0
  104. package/src/strategies/route_decision.ts +106 -0
  105. package/src/strategies/routing.ts +455 -0
  106. package/src/strategies/selector_projection.ts +207 -0
  107. package/src/telemetry/background.ts +40 -0
  108. package/src/telemetry/benchmark_replay.ts +160 -0
  109. package/src/telemetry/billing_finalization.ts +167 -0
  110. package/src/telemetry/ingest_values.ts +15 -0
  111. package/src/telemetry/model_cost.ts +14 -0
  112. package/src/telemetry/prefix_state.ts +183 -0
  113. package/src/telemetry/report.ts +832 -0
  114. package/src/telemetry/requests/interaction_observability.ts +258 -0
  115. package/src/telemetry/requests/retained_interaction_request.ts +20 -0
  116. package/src/telemetry/scrub.ts +38 -0
  117. package/src/telemetry/skills/claude/catalog.ts +119 -0
  118. package/src/telemetry/skills/claude/file_reads.ts +153 -0
  119. package/src/telemetry/skills/claude/observations.ts +450 -0
  120. package/src/telemetry/skills/codex/catalog.ts +171 -0
  121. package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
  122. package/src/telemetry/skills/codex/explicit.ts +116 -0
  123. package/src/telemetry/skills/codex/file_reads.ts +51 -0
  124. package/src/telemetry/skills/codex/identity.ts +21 -0
  125. package/src/telemetry/skills/observations.ts +94 -0
  126. package/src/telemetry/skills/paths.ts +82 -0
  127. package/src/telemetry/skills/pi.ts +276 -0
  128. package/src/telemetry/skills/shell_file_reads.ts +267 -0
  129. package/src/telemetry/skills/shell_words.ts +202 -0
  130. package/src/telemetry/tools/input.ts +16 -0
  131. package/src/telemetry/tools/observations.ts +349 -0
  132. package/src/telemetry/usage.ts +173 -0
  133. package/src/types.ts +150 -0
@@ -0,0 +1,466 @@
1
+ import { encodeOpenAIReasoningSignature } from "@mupt-ai/dari-router/protocols";
2
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
3
+
4
+ import { HttpError } from "../http/errors";
5
+ import type {
6
+ InteractionContent,
7
+ InteractionItem,
8
+ InteractionRequest,
9
+ InteractionTool,
10
+ ProviderContinuationState,
11
+ ProviderIdentity,
12
+ } from "../interaction/types";
13
+ import { parseDataImageUrl } from "../interaction/image";
14
+ import { providerToolCallId, toolWireName } from "../interaction/tool_identity";
15
+ import {
16
+ compatibleProviderContinuation,
17
+ sameProviderIdentity,
18
+ } from "../interaction/provider_continuation_state";
19
+ import { isOpenAIResponsesApi } from "./model_capabilities";
20
+
21
+ const UNKNOWN_SOURCE: ProviderIdentity = {
22
+ provider: "dari",
23
+ api: "interaction-history",
24
+ model: "unknown",
25
+ };
26
+
27
+ type PiAssistant = {
28
+ role: "assistant";
29
+ content: Array<Record<string, unknown>>;
30
+ api: string;
31
+ provider: string;
32
+ model: string;
33
+ providerThinkingLevel?: string;
34
+ usage: Record<string, unknown>;
35
+ stopReason: "stop" | "toolUse";
36
+ timestamp: number;
37
+ };
38
+
39
+ export type PiContext = Record<string, unknown> & {
40
+ messages: Array<Record<string, unknown>>;
41
+ systemPrompt?: string;
42
+ tools?: Array<Record<string, unknown>>;
43
+ };
44
+
45
+ export function buildContext(
46
+ request: InteractionRequest,
47
+ target: ProviderIdentity,
48
+ ): PiContext {
49
+ const systemParts: string[] = request.instructions ? [request.instructions] : [];
50
+ const messages: Array<Record<string, unknown>> = [];
51
+ const toolCalls = new Map<string, { id: string; name: string }>();
52
+ const timestamp = Date.now();
53
+ let pending: PiAssistant | null = null;
54
+ let sawConversationItem = false;
55
+
56
+ const flushAssistant = () => {
57
+ if (!pending) return;
58
+ if (pending.content.length === 0) pending.content.push({ type: "text", text: "" });
59
+ pending.stopReason = pending.content.some((part) => part.type === "toolCall") ? "toolUse" : "stop";
60
+ messages.push(pending);
61
+ pending = null;
62
+ };
63
+ const assistantFor = (source: ProviderIdentity): PiAssistant => {
64
+ if (pending && !sameProviderIdentity(pending, source)) flushAssistant();
65
+ pending ??= {
66
+ role: "assistant",
67
+ content: [],
68
+ ...source,
69
+ usage: zeroUsage(),
70
+ stopReason: "stop",
71
+ timestamp,
72
+ };
73
+ return pending;
74
+ };
75
+ const assistantForReasoning = (source: ProviderIdentity): PiAssistant => {
76
+ // Codex can persist a streamed tool call before reasoning recovered from
77
+ // the terminal response. Both items still belong to one assistant turn.
78
+ if (pending && sameProviderIdentity(pending, UNKNOWN_SOURCE)) {
79
+ pending.provider = source.provider;
80
+ pending.api = source.api;
81
+ pending.model = source.model;
82
+ }
83
+ return assistantFor(source);
84
+ };
85
+ for (const [itemIndex, item] of request.items.entries()) {
86
+ if (item.type === "message" && (item.role === "system" || item.role === "developer")) {
87
+ flushAssistant();
88
+ const text = readableContent(item.content);
89
+ if (!text) continue;
90
+ if (!sawConversationItem) {
91
+ // Leading preamble is identical on every request, so folding it into
92
+ // the system prompt keeps the provider payload prefix stable.
93
+ systemParts.push(text);
94
+ continue;
95
+ }
96
+ // Mid-conversation system/developer notes arrive between turns (Claude
97
+ // Code appends a `<total_tokens>` reminder after every tool result).
98
+ // Folding them into the system prompt mutates the front of the provider
99
+ // payload, so prefix-matching prompt caches miss and re-write the whole
100
+ // conversation at cache-write prices. Keep them positional instead.
101
+ appendPositionalNote(messages, text, timestamp);
102
+ continue;
103
+ }
104
+ sawConversationItem = true;
105
+ if (item.type === "message" && item.role === "user") {
106
+ flushAssistant();
107
+ appendUserMessage(messages, userContent(item.content, item.contentShape), timestamp);
108
+ continue;
109
+ }
110
+ if (item.type === "tool_result") {
111
+ flushAssistant();
112
+ const call = toolCalls.get(item.callId);
113
+ messages.push({
114
+ role: "toolResult",
115
+ toolCallId: call?.id ?? item.callId,
116
+ toolName: call?.name ?? item.name ?? "tool",
117
+ content: toolResultContent(item.output, target),
118
+ isError: item.isError ?? false,
119
+ timestamp,
120
+ ...(item.loadedTools?.length ? { addedToolNames: [...item.loadedTools] } : {}),
121
+ });
122
+ continue;
123
+ }
124
+ if (item.type === "reasoning_configuration") {
125
+ if (!isOpenAIResponsesApi(target.api)) {
126
+ throw new HttpError(
127
+ 400,
128
+ "Reasoning configuration updates require a GPT-6 Responses model.",
129
+ "unsupported_reasoning_configuration",
130
+ "input"
131
+ );
132
+ }
133
+ const assistant = assistantFor(target);
134
+ assistant.content.push({
135
+ type: "providerItem",
136
+ item: {
137
+ type: "configuration_update",
138
+ reasoning: { effort: item.effort === "off" ? "none" : item.effort },
139
+ },
140
+ name: "providerItem",
141
+ arguments: {},
142
+ });
143
+ continue;
144
+ }
145
+ if (item.type === "reasoning") {
146
+ const continuation = compatibleProviderContinuation(item.continuation, target);
147
+ if (continuation) {
148
+ const assistant = assistantForReasoning(continuation.source);
149
+ const firstNonReasoning = assistant.content.findIndex((content) => content.type !== "thinking");
150
+ assistant.content.splice(
151
+ firstNonReasoning === -1 ? assistant.content.length : firstNonReasoning,
152
+ 0,
153
+ thinkingContent(item, continuation)
154
+ );
155
+ // Managed-effort Claude models bind each thinking block to the prefix
156
+ // it was generated under, which ended in an effort marker. Pi only
157
+ // re-inserts that marker before turns that carry their level; without
158
+ // it the API silently drops the replayed block.
159
+ if (continuation.kind !== "openai_reasoning" && continuation.effort !== undefined) {
160
+ assistant.providerThinkingLevel = continuation.effort;
161
+ }
162
+ } else {
163
+ const readable = [...item.summary, ...item.content].join("\n");
164
+ if (readable) {
165
+ const assistant = assistantForReasoning(item.source ?? item.continuation?.source ?? UNKNOWN_SOURCE);
166
+ const firstToolCall = assistant.content.findIndex((content) => content.type === "toolCall");
167
+ assistant.content.splice(firstToolCall === -1 ? assistant.content.length : firstToolCall, 0, {
168
+ type: "text",
169
+ text: portableReasoningText(request.items, itemIndex, readable, target),
170
+ });
171
+ }
172
+ }
173
+ continue;
174
+ }
175
+ if (item.type === "tool_call") {
176
+ const assistant = assistantFor(pending ? identityOf(pending) : UNKNOWN_SOURCE);
177
+ const id = providerToolCallId(item.callId, item.id, target.api);
178
+ const name = toolWireName(item.namespace, item.name);
179
+ assistant.content.push({
180
+ type: "toolCall",
181
+ id,
182
+ name,
183
+ arguments: toolArguments(item.kind, item.input),
184
+ });
185
+ toolCalls.set(item.callId, { id, name });
186
+ continue;
187
+ }
188
+ if (item.type === "hosted_tool_call") {
189
+ if (item.tool === "server_tool_use" || item.tool === "tool_search") {
190
+ // Server tool use and tool search results are Anthropic-specific.
191
+ // Handle them before the generic OpenAI Responses branch to avoid
192
+ // emitting Anthropic-shaped payloads as Responses provider items.
193
+ if (target.api === "anthropic-messages") {
194
+ // Round-trip preservation when routing to Anthropic.
195
+ if (item.tool === "server_tool_use") {
196
+ const assistant = assistantFor(item.source ?? target);
197
+ assistant.content.push({
198
+ type: "serverToolCall",
199
+ id: item.serverToolUseId ?? item.id,
200
+ name: item.serverToolName ?? "tool",
201
+ arguments: item.serverToolInput ?? {},
202
+ });
203
+ } else {
204
+ const assistant = assistantFor(item.source ?? target);
205
+ assistant.content.push({
206
+ type: "toolSearchResult",
207
+ toolUseId: item.serverToolUseId ?? item.id,
208
+ content: (item.serverToolResult ?? []).map((ref) => ({
209
+ type: "tool_reference",
210
+ tool_name: ref.toolName,
211
+ })),
212
+ });
213
+ }
214
+ } else {
215
+ // Emit as text for non-Anthropic providers at reduced fidelity.
216
+ // Append to the current assistant turn to avoid splitting it with a
217
+ // fabricated user message.
218
+ const assistant = assistantFor(item.source ?? target);
219
+ assistant.content.push({
220
+ type: "text",
221
+ text: `[Server tool ${item.serverToolName ?? item.tool}: ${JSON.stringify(item.payload)}]`,
222
+ });
223
+ }
224
+ } else if (isOpenAIResponsesApi(target.api)) {
225
+ const assistant = assistantFor(item.source ?? target);
226
+ assistant.content.push({
227
+ type: "providerItem",
228
+ item: item.payload,
229
+ // Pi's generic estimator treats non-text assistant blocks like tool calls.
230
+ // These compatibility fields stay in process; the Responses adapter emits only `item`.
231
+ name: "providerItem",
232
+ arguments: item.payload,
233
+ });
234
+ }
235
+ continue;
236
+ }
237
+ if (item.role === "assistant") {
238
+ const assistant = assistantFor(item.source ?? (pending ? identityOf(pending) : UNKNOWN_SOURCE));
239
+ for (const [contentIndex, content] of item.content.entries()) {
240
+ if (content.type === "text") {
241
+ const signatureId = item.id ?? (item.phase ? `msg_dari_${itemIndex}_${contentIndex}` : undefined);
242
+ assistant.content.push({
243
+ type: "text",
244
+ text: content.text,
245
+ ...(content.annotations?.length ? { annotations: content.annotations } : {}),
246
+ ...(signatureId ? { textSignature: textSignature(signatureId, item.phase) } : {}),
247
+ });
248
+ } else {
249
+ assistant.content.push({ type: "text", text: "(assistant image omitted)" });
250
+ }
251
+ }
252
+ }
253
+ }
254
+ flushAssistant();
255
+
256
+ const context: PiContext = { messages };
257
+ if (systemParts.length > 0) context.systemPrompt = systemParts.join("\n\n");
258
+ const clientTools = request.tools.filter(
259
+ (tool): tool is Exclude<InteractionTool, { kind: "hosted" }> =>
260
+ tool.kind !== "hosted" && (tool.kind !== "server_tool" || target.api === "anthropic-messages")
261
+ );
262
+ if (clientTools.length > 0) context.tools = clientTools.map((tool) => toolToPi(tool, target.api));
263
+ return context;
264
+ }
265
+
266
+ function thinkingContent(
267
+ item: Extract<InteractionItem, { type: "reasoning" }>,
268
+ continuation: ProviderContinuationState
269
+ ): Record<string, unknown> {
270
+ if (continuation.kind === "openai_reasoning") {
271
+ const providerItemId = continuation.providerItemId ?? item.id;
272
+ return {
273
+ type: "thinking",
274
+ thinking: [...item.summary, ...item.content].join("\n"),
275
+ thinkingSignature: encodeOpenAIReasoningSignature({
276
+ ...(providerItemId ? { id: providerItemId } : {}),
277
+ summary: item.summary,
278
+ content: item.content,
279
+ encryptedContent: continuation.encryptedContent,
280
+ }),
281
+ };
282
+ }
283
+ if (continuation.kind === "anthropic_thinking") {
284
+ return {
285
+ type: "thinking",
286
+ thinking: continuation.thinking,
287
+ thinkingSignature: continuation.signature,
288
+ };
289
+ }
290
+ return {
291
+ type: "thinking",
292
+ thinking: "",
293
+ thinkingSignature: continuation.data,
294
+ redacted: true,
295
+ };
296
+ }
297
+
298
+ function userContent(
299
+ content: InteractionContent[],
300
+ shape: "string" | "parts" | "null" | "absent"
301
+ ): string | Array<Record<string, unknown>> {
302
+ if (shape !== "parts") return content.filter((part) => part.type === "text").map((part) => part.text).join("");
303
+ return content.map(contentToPi);
304
+ }
305
+
306
+ function appendPositionalNote(
307
+ messages: Array<Record<string, unknown>>,
308
+ text: string,
309
+ timestamp: number,
310
+ ): void {
311
+ const previous = messages.at(-1);
312
+ if (previous?.role === "toolResult") {
313
+ previous.content = [...contentBlocks(previous.content), { type: "text", text }];
314
+ return;
315
+ }
316
+ appendUserMessage(messages, [{ type: "text", text }], timestamp);
317
+ }
318
+
319
+ function appendUserMessage(
320
+ messages: Array<Record<string, unknown>>,
321
+ content: string | Array<Record<string, unknown>>,
322
+ timestamp: number,
323
+ ): void {
324
+ const previous = messages.at(-1);
325
+ if (previous?.role === "user") {
326
+ previous.content = [...contentBlocks(previous.content), ...contentBlocks(content)];
327
+ return;
328
+ }
329
+ messages.push({ role: "user", content, timestamp });
330
+ }
331
+
332
+ function contentBlocks(content: unknown): Array<Record<string, unknown>> {
333
+ if (typeof content === "string") return [{ type: "text", text: content }];
334
+ return Array.isArray(content) ? content as Array<Record<string, unknown>> : [];
335
+ }
336
+
337
+ function toolResultContent(
338
+ content: string | InteractionContent[] | null,
339
+ target: ProviderIdentity,
340
+ ): Array<Record<string, unknown>> {
341
+ if (content === null) return [];
342
+ if (typeof content === "string") return [{ type: "text", text: content }];
343
+ // Anthropic emits tool_reference parts natively via addedToolNames, so
344
+ // flattening them to synthetic text here would duplicate the names. Other
345
+ // providers have no native tool_reference representation, so keep the text
346
+ // fallback for them.
347
+ const filtered = target.api === "anthropic-messages"
348
+ ? content.filter((part) => part.type !== "tool_reference")
349
+ : content;
350
+ return filtered.map(contentToPi);
351
+ }
352
+
353
+ function contentToPi(content: InteractionContent): Record<string, unknown> {
354
+ if (content.type === "text") return { type: "text", text: content.text };
355
+ if (content.type === "tool_reference") return { type: "text", text: `Referenced tool: ${content.toolName}` };
356
+ const image = parseDataImageUrl(content.url);
357
+ if (!image) {
358
+ throw new HttpError(400, "Only base64 data URLs are supported for routed image input.", "invalid_request_error", "input.image_url");
359
+ }
360
+ return {
361
+ type: "image",
362
+ mimeType: image.mimeType,
363
+ data: image.data,
364
+ ...(content.detail !== undefined ? { detail: content.detail } : {}),
365
+ };
366
+ }
367
+
368
+ function portableReasoningText(
369
+ items: ReadonlyArray<InteractionItem>,
370
+ itemIndex: number,
371
+ readable: string,
372
+ target: ProviderIdentity
373
+ ): string {
374
+ if (target.api !== "openai-completions") return readable;
375
+ for (let index = itemIndex + 1; index < items.length; index += 1) {
376
+ const next = items[index];
377
+ if (next.type === "reasoning" || next.type === "tool_call") continue;
378
+ if (next.type === "message" && next.role === "assistant") {
379
+ return next.content.some((part) => part.type === "text" && part.text.length > 0)
380
+ ? `${readable}\n\n`
381
+ : readable;
382
+ }
383
+ break;
384
+ }
385
+ return readable;
386
+ }
387
+
388
+ function readableContent(content: InteractionContent[]): string {
389
+ return content.map((part) => (part.type === "text" ? part.text : "(image omitted)")).join("\n");
390
+ }
391
+
392
+ function toolToPi(
393
+ tool: Exclude<InteractionTool, { kind: "hosted" }>,
394
+ targetApi: string,
395
+ ): Record<string, unknown> {
396
+ if (tool.kind === "client_tool" && targetApi === "anthropic-messages") {
397
+ return {
398
+ name: tool.name,
399
+ type: tool.type,
400
+ serverTool: true,
401
+ };
402
+ }
403
+ const result: Record<string, unknown> = {
404
+ name: (tool.kind === "server_tool" || tool.kind === "client_tool"
405
+ ? tool.name
406
+ : toolWireName(tool.namespace, tool.name)),
407
+ // Anthropic rejects description on server tool definitions as an extra input.
408
+ ...(tool.kind === "server_tool" ? {} : { description: tool.description ?? "" }),
409
+ };
410
+ if (tool.kind === "function") {
411
+ result.parameters = tool.parameters ?? { type: "object", properties: {} };
412
+ if (tool.deferLoading !== undefined) result.deferLoading = tool.deferLoading;
413
+ } else if (tool.kind === "server_tool") {
414
+ // Server tools are Anthropic-specific; Pi doesn't handle them. We pass
415
+ // the type through so the Pi adapter can preserve it for Anthropic.
416
+ result.type = tool.type;
417
+ // Server tools don't have input_schema; but Pi's convertTools would add one
418
+ // if we set parameters. Mark it to skip the schema.
419
+ result.serverTool = true;
420
+ } else if (tool.kind === "client_tool") {
421
+ result.parameters = { type: "object", properties: {}, additionalProperties: true };
422
+ } else {
423
+ result.parameters = {
424
+ type: "object",
425
+ properties: { input: { type: "string" } },
426
+ required: ["input"],
427
+ additionalProperties: false,
428
+ };
429
+ }
430
+ return result;
431
+ }
432
+
433
+ function toolArguments(kind: "function" | "custom", input: string | Record<string, unknown> | undefined): Record<string, unknown> {
434
+ if (kind === "custom") return { input: typeof input === "string" ? input : "" };
435
+ if (input && typeof input === "object") return input;
436
+ if (typeof input !== "string" || input.trim() === "") return {};
437
+ let parsed: unknown;
438
+ try {
439
+ parsed = JSON.parse(input);
440
+ } catch {
441
+ throw new HttpError(400, "Function tool arguments must contain a JSON object.", "invalid_request_error", "input.arguments");
442
+ }
443
+ if (!isRecord(parsed)) {
444
+ throw new HttpError(400, "Function tool arguments must contain a JSON object.", "invalid_request_error", "input.arguments");
445
+ }
446
+ return parsed;
447
+ }
448
+
449
+ function textSignature(id: string, phase: "commentary" | "final_answer" | undefined): string {
450
+ return JSON.stringify({ v: 1, id, ...(phase ? { phase } : {}) });
451
+ }
452
+
453
+ function identityOf(value: Pick<PiAssistant, "provider" | "api" | "model">): ProviderIdentity {
454
+ return { provider: value.provider, api: value.api, model: value.model };
455
+ }
456
+
457
+ function zeroUsage(): Record<string, unknown> {
458
+ return {
459
+ input: 0,
460
+ output: 0,
461
+ cacheRead: 0,
462
+ cacheWrite: 0,
463
+ totalTokens: 0,
464
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
465
+ };
466
+ }