@openrouter/sdk 1.5.56 → 1.5.58
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.
- package/esm/lib/config.d.ts +2 -2
- package/esm/lib/config.js +2 -2
- package/esm/models/additionaltoolsitem.d.ts +5 -4
- package/esm/models/additionaltoolsitem.js +3 -0
- package/esm/models/alignmentresponsesrejected.d.ts +4 -1
- package/esm/models/alignmentresponsesrejected.js +6 -0
- package/esm/models/byokproviderslug.d.ts +1 -0
- package/esm/models/byokproviderslug.js +1 -0
- package/esm/models/createworkspacerequest.d.ts +1 -0
- package/esm/models/createworkspacerequest.js +1 -0
- package/esm/models/decisionschoicequestion.d.ts +4 -4
- package/esm/models/decisionschoicequestion.js +1 -5
- package/esm/models/decisionsnoulquestion.d.ts +12 -12
- package/esm/models/decisionsnoulquestion.js +3 -7
- package/esm/models/decisionsresponse.d.ts +12 -0
- package/esm/models/decisionsresponse.js +5 -0
- package/esm/models/decisionsscorequestion.d.ts +4 -4
- package/esm/models/decisionsscorequestion.js +1 -5
- package/esm/models/imagegenerationproviderpreferences.d.ts +6 -0
- package/esm/models/imagegenerationproviderpreferences.js +1 -0
- package/esm/models/imagegenerationrequest.d.ts +1 -1
- package/esm/models/index.d.ts +6 -0
- package/esm/models/index.js +6 -0
- package/esm/models/mcpapprovalrequestitem.d.ts +7 -0
- package/esm/models/mcpapprovalrequestitem.js +19 -1
- package/esm/models/mcpcallitem.d.ts +17 -1
- package/esm/models/mcpcallitem.js +18 -0
- package/esm/models/mcpservertool.d.ts +78 -69
- package/esm/models/mcpservertool.js +135 -105
- package/esm/models/mcpservertoolopenrouter.d.ts +28 -0
- package/esm/models/mcpservertoolopenrouter.js +20 -0
- package/esm/models/mcpservertoolparameters.d.ts +152 -0
- package/esm/models/mcpservertoolparameters.js +134 -0
- package/esm/models/openairesponsestoolchoiceunion.d.ts +3 -2
- package/esm/models/openairesponsestoolchoiceunion.js +3 -0
- package/esm/models/operations/listbyokkeys.d.ts +1 -0
- package/esm/models/operations/listbyokkeys.js +1 -0
- package/esm/models/outputitemmcpapprovalrequest.d.ts +14 -0
- package/esm/models/outputitemmcpapprovalrequest.js +23 -0
- package/esm/models/outputitemmcpcall.d.ts +74 -0
- package/esm/models/outputitemmcpcall.js +94 -0
- package/esm/models/outputitemmcplisttools.d.ts +25 -0
- package/esm/models/outputitemmcplisttools.js +37 -0
- package/esm/models/outputitems.d.ts +3 -0
- package/esm/models/outputitems.js +2 -0
- package/esm/models/providername.d.ts +1 -0
- package/esm/models/providername.js +1 -0
- package/esm/models/provideroptions.d.ts +6 -0
- package/esm/models/provideroptions.js +1 -0
- package/esm/models/providerresponse.d.ts +1 -0
- package/esm/models/providerresponse.js +1 -0
- package/esm/models/responsesrequest.d.ts +9 -0
- package/esm/models/responsesrequest.js +3 -0
- package/esm/models/toolchoicemcp.d.ts +33 -0
- package/esm/models/toolchoicemcp.js +42 -0
- package/esm/models/toolsearchoutputitem.d.ts +5 -4
- package/esm/models/toolsearchoutputitem.js +3 -0
- package/esm/models/updateworkspacerequest.d.ts +1 -0
- package/esm/models/updateworkspacerequest.js +1 -0
- package/esm/models/videogenerationrequest.d.ts +6 -0
- package/esm/models/videogenerationrequest.js +1 -0
- package/esm/sdk/sdk.d.ts +0 -9
- package/esm/sdk/sdk.js +1 -7
- package/jsr.json +1 -1
- package/package.json +8 -8
- package/esm/funcs/call-model.d.ts +0 -67
- package/esm/funcs/call-model.js +0 -98
- package/esm/lib/anthropic-compat.d.ts +0 -51
- package/esm/lib/anthropic-compat.js +0 -222
- package/esm/lib/async-params.d.ts +0 -107
- package/esm/lib/async-params.js +0 -88
- package/esm/lib/chat-compat.d.ts +0 -47
- package/esm/lib/chat-compat.js +0 -111
- package/esm/lib/claude-constants.d.ts +0 -22
- package/esm/lib/claude-constants.js +0 -20
- package/esm/lib/claude-type-guards.d.ts +0 -10
- package/esm/lib/claude-type-guards.js +0 -70
- package/esm/lib/conversation-state.d.ts +0 -63
- package/esm/lib/conversation-state.js +0 -210
- package/esm/lib/model-result.d.ts +0 -373
- package/esm/lib/model-result.js +0 -1414
- package/esm/lib/next-turn-params.d.ts +0 -30
- package/esm/lib/next-turn-params.js +0 -135
- package/esm/lib/reusable-stream.d.ts +0 -39
- package/esm/lib/reusable-stream.js +0 -192
- package/esm/lib/stop-conditions.d.ts +0 -80
- package/esm/lib/stop-conditions.js +0 -104
- package/esm/lib/stream-transformers.d.ts +0 -118
- package/esm/lib/stream-transformers.js +0 -852
- package/esm/lib/stream-type-guards.d.ts +0 -49
- package/esm/lib/stream-type-guards.js +0 -85
- package/esm/lib/tool-context.d.ts +0 -68
- package/esm/lib/tool-context.js +0 -175
- package/esm/lib/tool-event-broadcaster.d.ts +0 -44
- package/esm/lib/tool-event-broadcaster.js +0 -146
- package/esm/lib/tool-executor.d.ts +0 -74
- package/esm/lib/tool-executor.js +0 -267
- package/esm/lib/tool-orchestrator.d.ts +0 -52
- package/esm/lib/tool-orchestrator.js +0 -180
- package/esm/lib/tool-types.d.ts +0 -573
- package/esm/lib/tool-types.js +0 -80
- package/esm/lib/tool.d.ts +0 -108
- package/esm/lib/tool.js +0 -74
- package/esm/lib/turn-context.d.ts +0 -52
- package/esm/lib/turn-context.js +0 -59
package/esm/lib/chat-compat.js
DELETED
|
@@ -1,111 +0,0 @@
|
|
|
1
|
-
import { EasyInputMessageRoleUser, EasyInputMessageRoleSystem, EasyInputMessageRoleAssistant, EasyInputMessageRoleDeveloper, } from "../models/easyinputmessage.js";
|
|
2
|
-
import { extractMessageFromResponse } from "./stream-transformers.js";
|
|
3
|
-
/**
|
|
4
|
-
* Type guard for ChatToolMessage
|
|
5
|
-
*/
|
|
6
|
-
function isToolResponseMessage(msg) {
|
|
7
|
-
return msg.role === "tool";
|
|
8
|
-
}
|
|
9
|
-
/**
|
|
10
|
-
* Type guard for ChatAssistantMessage
|
|
11
|
-
*/
|
|
12
|
-
function isAssistantMessage(msg) {
|
|
13
|
-
return msg.role === "assistant";
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* Maps chat role strings to OpenResponses role types
|
|
17
|
-
*/
|
|
18
|
-
function mapChatRole(role) {
|
|
19
|
-
switch (role) {
|
|
20
|
-
case "user":
|
|
21
|
-
return EasyInputMessageRoleUser.User;
|
|
22
|
-
case "system":
|
|
23
|
-
return EasyInputMessageRoleSystem.System;
|
|
24
|
-
case "assistant":
|
|
25
|
-
return EasyInputMessageRoleAssistant.Assistant;
|
|
26
|
-
case "developer":
|
|
27
|
-
return EasyInputMessageRoleDeveloper.Developer;
|
|
28
|
-
default: {
|
|
29
|
-
const exhaustiveCheck = role;
|
|
30
|
-
throw new Error(`Unhandled role type: ${exhaustiveCheck}`);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Convert message content to a string representation.
|
|
36
|
-
* Handles string, null, undefined, and object content types.
|
|
37
|
-
*/
|
|
38
|
-
function contentToString(content) {
|
|
39
|
-
if (typeof content === "string") {
|
|
40
|
-
return content;
|
|
41
|
-
}
|
|
42
|
-
if (content === null || content === undefined) {
|
|
43
|
-
return "";
|
|
44
|
-
}
|
|
45
|
-
return JSON.stringify(content);
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Convert OpenAI chat-style messages to OpenResponses input format.
|
|
49
|
-
*
|
|
50
|
-
* This function transforms Message[] (OpenAI chat format) to OpenResponsesInput
|
|
51
|
-
* format that can be passed directly to callModel().
|
|
52
|
-
*
|
|
53
|
-
* @example
|
|
54
|
-
* ```typescript
|
|
55
|
-
* import { fromChatMessages } from '@openrouter/sdk';
|
|
56
|
-
*
|
|
57
|
-
* const chatMessages = [
|
|
58
|
-
* { role: "system", content: "You are a helpful assistant." },
|
|
59
|
-
* { role: "user", content: "Hello!" },
|
|
60
|
-
* ];
|
|
61
|
-
*
|
|
62
|
-
* const response = openrouter.callModel({
|
|
63
|
-
* model: "openai/gpt-4",
|
|
64
|
-
* input: fromChatMessages(chatMessages),
|
|
65
|
-
* });
|
|
66
|
-
* ```
|
|
67
|
-
*/
|
|
68
|
-
export function fromChatMessages(messages) {
|
|
69
|
-
return messages.map((msg) => {
|
|
70
|
-
if (isToolResponseMessage(msg)) {
|
|
71
|
-
return {
|
|
72
|
-
type: "function_call_output",
|
|
73
|
-
callId: msg.toolCallId,
|
|
74
|
-
output: contentToString(msg.content),
|
|
75
|
-
};
|
|
76
|
-
}
|
|
77
|
-
if (isAssistantMessage(msg)) {
|
|
78
|
-
return {
|
|
79
|
-
role: mapChatRole("assistant"),
|
|
80
|
-
content: contentToString(msg.content),
|
|
81
|
-
};
|
|
82
|
-
}
|
|
83
|
-
// System, user, developer messages
|
|
84
|
-
return {
|
|
85
|
-
role: mapChatRole(msg.role),
|
|
86
|
-
content: contentToString(msg.content),
|
|
87
|
-
};
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Convert an OpenResponses response to OpenAI chat message format.
|
|
92
|
-
*
|
|
93
|
-
* This function transforms OpenResponsesResult to ChatAssistantMessage
|
|
94
|
-
* (OpenAI chat format) for compatibility with code expecting chat responses.
|
|
95
|
-
*
|
|
96
|
-
* @example
|
|
97
|
-
* ```typescript
|
|
98
|
-
* import { toChatMessage } from '@openrouter/sdk';
|
|
99
|
-
*
|
|
100
|
-
* const response = await openrouter.callModel({
|
|
101
|
-
* model: "openai/gpt-4",
|
|
102
|
-
* input: "Hello!",
|
|
103
|
-
* });
|
|
104
|
-
*
|
|
105
|
-
* const openResponsesResult = await response.getResponse();
|
|
106
|
-
* const chatMessage = toChatMessage(openResponsesResult);
|
|
107
|
-
* // chatMessage is now { role: "assistant", content: "..." }
|
|
108
|
-
* ```
|
|
109
|
-
*/
|
|
110
|
-
export const toChatMessage = extractMessageFromResponse;
|
|
111
|
-
//# sourceMappingURL=chat-compat.js.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude-specific content block types
|
|
3
|
-
* Used for detecting Claude message format
|
|
4
|
-
*/
|
|
5
|
-
export declare const ClaudeContentBlockType: {
|
|
6
|
-
readonly Text: "text";
|
|
7
|
-
readonly Image: "image";
|
|
8
|
-
readonly ToolUse: "tool_use";
|
|
9
|
-
readonly ToolResult: "tool_result";
|
|
10
|
-
};
|
|
11
|
-
export type ClaudeContentBlockType = (typeof ClaudeContentBlockType)[keyof typeof ClaudeContentBlockType];
|
|
12
|
-
/**
|
|
13
|
-
* Message roles that are NOT supported in Claude format
|
|
14
|
-
* Used for distinguishing Claude vs OpenAI format
|
|
15
|
-
*/
|
|
16
|
-
export declare const NonClaudeMessageRole: {
|
|
17
|
-
readonly System: "system";
|
|
18
|
-
readonly Developer: "developer";
|
|
19
|
-
readonly Tool: "tool";
|
|
20
|
-
};
|
|
21
|
-
export type NonClaudeMessageRole = (typeof NonClaudeMessageRole)[keyof typeof NonClaudeMessageRole];
|
|
22
|
-
//# sourceMappingURL=claude-constants.d.ts.map
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Claude-specific content block types
|
|
3
|
-
* Used for detecting Claude message format
|
|
4
|
-
*/
|
|
5
|
-
export const ClaudeContentBlockType = {
|
|
6
|
-
Text: "text",
|
|
7
|
-
Image: "image",
|
|
8
|
-
ToolUse: "tool_use",
|
|
9
|
-
ToolResult: "tool_result",
|
|
10
|
-
};
|
|
11
|
-
/**
|
|
12
|
-
* Message roles that are NOT supported in Claude format
|
|
13
|
-
* Used for distinguishing Claude vs OpenAI format
|
|
14
|
-
*/
|
|
15
|
-
export const NonClaudeMessageRole = {
|
|
16
|
-
System: "system",
|
|
17
|
-
Developer: "developer",
|
|
18
|
-
Tool: "tool",
|
|
19
|
-
};
|
|
20
|
-
//# sourceMappingURL=claude-constants.js.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { ClaudeMessageParam } from "../models/claude-message.js";
|
|
2
|
-
/**
|
|
3
|
-
* Check if input is in Claude message format
|
|
4
|
-
* Uses structural analysis to detect Claude-specific patterns
|
|
5
|
-
*
|
|
6
|
-
* @param input - Input to check
|
|
7
|
-
* @returns True if input appears to be Claude format
|
|
8
|
-
*/
|
|
9
|
-
export declare function isClaudeStyleMessages(input: unknown): input is ClaudeMessageParam[];
|
|
10
|
-
//# sourceMappingURL=claude-type-guards.d.ts.map
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
import { ClaudeContentBlockType, NonClaudeMessageRole, } from "./claude-constants.js";
|
|
2
|
-
function isRecord(value) {
|
|
3
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4
|
-
}
|
|
5
|
-
function isNonClaudeRole(role) {
|
|
6
|
-
return (role === NonClaudeMessageRole.System ||
|
|
7
|
-
role === NonClaudeMessageRole.Developer ||
|
|
8
|
-
role === NonClaudeMessageRole.Tool);
|
|
9
|
-
}
|
|
10
|
-
function isClaudeToolResultBlock(block) {
|
|
11
|
-
if (!isRecord(block))
|
|
12
|
-
return false;
|
|
13
|
-
return block["type"] === ClaudeContentBlockType.ToolResult;
|
|
14
|
-
}
|
|
15
|
-
function isClaudeImageBlockWithSource(block) {
|
|
16
|
-
if (!isRecord(block))
|
|
17
|
-
return false;
|
|
18
|
-
return (block["type"] === ClaudeContentBlockType.Image &&
|
|
19
|
-
"source" in block &&
|
|
20
|
-
isRecord(block["source"]));
|
|
21
|
-
}
|
|
22
|
-
function isClaudeToolUseBlockWithId(block) {
|
|
23
|
-
if (!isRecord(block))
|
|
24
|
-
return false;
|
|
25
|
-
return (block["type"] === ClaudeContentBlockType.ToolUse &&
|
|
26
|
-
"id" in block &&
|
|
27
|
-
typeof block["id"] === "string");
|
|
28
|
-
}
|
|
29
|
-
function hasClaudeSpecificBlocks(content) {
|
|
30
|
-
for (const block of content) {
|
|
31
|
-
if (isClaudeToolResultBlock(block))
|
|
32
|
-
return true;
|
|
33
|
-
if (isClaudeImageBlockWithSource(block))
|
|
34
|
-
return true;
|
|
35
|
-
if (isClaudeToolUseBlockWithId(block))
|
|
36
|
-
return true;
|
|
37
|
-
}
|
|
38
|
-
return false;
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Check if input is in Claude message format
|
|
42
|
-
* Uses structural analysis to detect Claude-specific patterns
|
|
43
|
-
*
|
|
44
|
-
* @param input - Input to check
|
|
45
|
-
* @returns True if input appears to be Claude format
|
|
46
|
-
*/
|
|
47
|
-
export function isClaudeStyleMessages(input) {
|
|
48
|
-
if (!Array.isArray(input) || input.length === 0) {
|
|
49
|
-
return false;
|
|
50
|
-
}
|
|
51
|
-
for (const msg of input) {
|
|
52
|
-
if (!isRecord(msg))
|
|
53
|
-
continue;
|
|
54
|
-
if (!("role" in msg))
|
|
55
|
-
continue;
|
|
56
|
-
if ("type" in msg)
|
|
57
|
-
continue; // Claude messages don't have top-level "type"
|
|
58
|
-
// If we find a non-Claude role, it's not Claude format
|
|
59
|
-
if (isNonClaudeRole(msg["role"])) {
|
|
60
|
-
return false;
|
|
61
|
-
}
|
|
62
|
-
// If we find Claude-specific content blocks, it's Claude format
|
|
63
|
-
const content = msg["content"];
|
|
64
|
-
if (Array.isArray(content) && hasClaudeSpecificBlocks(content)) {
|
|
65
|
-
return true;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return false;
|
|
69
|
-
}
|
|
70
|
-
//# sourceMappingURL=claude-type-guards.js.map
|
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import type { FunctionCallOutputItem } from '../models/functioncalloutputitem.js';
|
|
2
|
-
import type { InputsUnion, InputsUnion1 } from '../models/inputsunion.js';
|
|
3
|
-
import type { OpenResponsesResult } from '../models/openresponsesresult.js';
|
|
4
|
-
import type { ConversationState, ParsedToolCall, Tool, TurnContext, UnsentToolResult } from './tool-types.js';
|
|
5
|
-
/**
|
|
6
|
-
* Generate a unique ID for a conversation
|
|
7
|
-
* Uses crypto.randomUUID if available, falls back to timestamp + random
|
|
8
|
-
*/
|
|
9
|
-
export declare function generateConversationId(): string;
|
|
10
|
-
/**
|
|
11
|
-
* Create an initial conversation state
|
|
12
|
-
* @param id - Optional custom ID, generates one if not provided
|
|
13
|
-
*/
|
|
14
|
-
export declare function createInitialState<TTools extends readonly Tool[] = readonly Tool[]>(id?: string): ConversationState<TTools>;
|
|
15
|
-
/**
|
|
16
|
-
* Update a conversation state with new values
|
|
17
|
-
* Automatically updates the updatedAt timestamp
|
|
18
|
-
*/
|
|
19
|
-
export declare function updateState<TTools extends readonly Tool[] = readonly Tool[]>(state: ConversationState<TTools>, updates: Partial<Omit<ConversationState<TTools>, 'id' | 'createdAt' | 'updatedAt'>>): ConversationState<TTools>;
|
|
20
|
-
/**
|
|
21
|
-
* Append new items to the message history
|
|
22
|
-
*/
|
|
23
|
-
export declare function appendToMessages(current: InputsUnion, newItems: InputsUnion1[]): InputsUnion;
|
|
24
|
-
/**
|
|
25
|
-
* Check if a tool call requires approval
|
|
26
|
-
* @param toolCall - The tool call to check
|
|
27
|
-
* @param tools - Available tools
|
|
28
|
-
* @param context - Turn context for the approval check
|
|
29
|
-
* @param callLevelCheck - Optional call-level approval function (overrides tool-level), can be async
|
|
30
|
-
*/
|
|
31
|
-
export declare function toolRequiresApproval<TTools extends readonly Tool[]>(toolCall: ParsedToolCall<TTools[number]>, tools: TTools, context: TurnContext, callLevelCheck?: (toolCall: ParsedToolCall<TTools[number]>, context: TurnContext) => boolean | Promise<boolean>): Promise<boolean>;
|
|
32
|
-
/**
|
|
33
|
-
* Partition tool calls into those requiring approval and those that can auto-execute
|
|
34
|
-
* @param toolCalls - Tool calls to partition
|
|
35
|
-
* @param tools - Available tools
|
|
36
|
-
* @param context - Turn context for the approval check
|
|
37
|
-
* @param callLevelCheck - Optional call-level approval function (overrides tool-level), can be async
|
|
38
|
-
*/
|
|
39
|
-
export declare function partitionToolCalls<TTools extends readonly Tool[]>(toolCalls: ParsedToolCall<TTools[number]>[], tools: TTools, context: TurnContext, callLevelCheck?: (toolCall: ParsedToolCall<TTools[number]>, context: TurnContext) => boolean | Promise<boolean>): Promise<{
|
|
40
|
-
requiresApproval: ParsedToolCall<TTools[number]>[];
|
|
41
|
-
autoExecute: ParsedToolCall<TTools[number]>[];
|
|
42
|
-
}>;
|
|
43
|
-
/**
|
|
44
|
-
* Create an unsent tool result from a successful execution
|
|
45
|
-
*/
|
|
46
|
-
export declare function createUnsentResult<TTools extends readonly Tool[] = readonly Tool[]>(callId: string, name: string, output: unknown): UnsentToolResult<TTools>;
|
|
47
|
-
/**
|
|
48
|
-
* Create an unsent tool result from a rejection
|
|
49
|
-
*/
|
|
50
|
-
export declare function createRejectedResult<TTools extends readonly Tool[] = readonly Tool[]>(callId: string, name: string, reason?: string): UnsentToolResult<TTools>;
|
|
51
|
-
/**
|
|
52
|
-
* Convert unsent tool results to API format for sending to the model
|
|
53
|
-
*/
|
|
54
|
-
export declare function unsentResultsToAPIFormat(results: UnsentToolResult[]): FunctionCallOutputItem[];
|
|
55
|
-
/**
|
|
56
|
-
* Extract text content from a response
|
|
57
|
-
*/
|
|
58
|
-
export declare function extractTextFromResponse(response: OpenResponsesResult): string;
|
|
59
|
-
/**
|
|
60
|
-
* Extract tool calls from a response
|
|
61
|
-
*/
|
|
62
|
-
export declare function extractToolCallsFromResponse<TTools extends readonly Tool[]>(response: OpenResponsesResult): ParsedToolCall<TTools[number]>[];
|
|
63
|
-
//# sourceMappingURL=conversation-state.d.ts.map
|
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
import { normalizeInputToArray } from './turn-context.js';
|
|
2
|
-
/**
|
|
3
|
-
* Type guard to verify an object is a valid UnsentToolResult
|
|
4
|
-
*/
|
|
5
|
-
function isValidUnsentToolResult(obj) {
|
|
6
|
-
if (typeof obj !== 'object' || obj === null)
|
|
7
|
-
return false;
|
|
8
|
-
return ('callId' in obj &&
|
|
9
|
-
typeof obj.callId === 'string' &&
|
|
10
|
-
'name' in obj &&
|
|
11
|
-
typeof obj.name === 'string' &&
|
|
12
|
-
'output' in obj);
|
|
13
|
-
}
|
|
14
|
-
/**
|
|
15
|
-
* Type guard to verify an object is a valid ParsedToolCall
|
|
16
|
-
*/
|
|
17
|
-
function isValidParsedToolCall(obj) {
|
|
18
|
-
if (typeof obj !== 'object' || obj === null)
|
|
19
|
-
return false;
|
|
20
|
-
return ('id' in obj &&
|
|
21
|
-
typeof obj.id === 'string' &&
|
|
22
|
-
'name' in obj &&
|
|
23
|
-
typeof obj.name === 'string' &&
|
|
24
|
-
'arguments' in obj);
|
|
25
|
-
}
|
|
26
|
-
/**
|
|
27
|
-
* Generate a unique ID for a conversation
|
|
28
|
-
* Uses crypto.randomUUID if available, falls back to timestamp + random
|
|
29
|
-
*/
|
|
30
|
-
export function generateConversationId() {
|
|
31
|
-
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
|
32
|
-
return `conv_${crypto.randomUUID()}`;
|
|
33
|
-
}
|
|
34
|
-
// Fallback for environments without crypto.randomUUID
|
|
35
|
-
return `conv_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Create an initial conversation state
|
|
39
|
-
* @param id - Optional custom ID, generates one if not provided
|
|
40
|
-
*/
|
|
41
|
-
export function createInitialState(id) {
|
|
42
|
-
const now = Date.now();
|
|
43
|
-
return {
|
|
44
|
-
id: id ?? generateConversationId(),
|
|
45
|
-
messages: [],
|
|
46
|
-
status: 'in_progress',
|
|
47
|
-
createdAt: now,
|
|
48
|
-
updatedAt: now,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Update a conversation state with new values
|
|
53
|
-
* Automatically updates the updatedAt timestamp
|
|
54
|
-
*/
|
|
55
|
-
export function updateState(state, updates) {
|
|
56
|
-
return {
|
|
57
|
-
...state,
|
|
58
|
-
...updates,
|
|
59
|
-
updatedAt: Date.now(),
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
/**
|
|
63
|
-
* Append new items to the message history
|
|
64
|
-
*/
|
|
65
|
-
export function appendToMessages(current, newItems) {
|
|
66
|
-
const currentArray = normalizeInputToArray(current);
|
|
67
|
-
return [...currentArray, ...newItems];
|
|
68
|
-
}
|
|
69
|
-
/**
|
|
70
|
-
* Check if a tool call requires approval
|
|
71
|
-
* @param toolCall - The tool call to check
|
|
72
|
-
* @param tools - Available tools
|
|
73
|
-
* @param context - Turn context for the approval check
|
|
74
|
-
* @param callLevelCheck - Optional call-level approval function (overrides tool-level), can be async
|
|
75
|
-
*/
|
|
76
|
-
export async function toolRequiresApproval(toolCall, tools, context, callLevelCheck) {
|
|
77
|
-
// Call-level check takes precedence
|
|
78
|
-
if (callLevelCheck) {
|
|
79
|
-
return callLevelCheck(toolCall, context);
|
|
80
|
-
}
|
|
81
|
-
// Fall back to tool-level setting
|
|
82
|
-
const tool = tools.find(t => t.function.name === toolCall.name);
|
|
83
|
-
if (!tool)
|
|
84
|
-
return false;
|
|
85
|
-
const requireApproval = tool.function.requireApproval;
|
|
86
|
-
// If it's a function, call it with the tool's arguments and context
|
|
87
|
-
if (typeof requireApproval === 'function') {
|
|
88
|
-
return requireApproval(toolCall.arguments, context);
|
|
89
|
-
}
|
|
90
|
-
// Otherwise treat as boolean
|
|
91
|
-
return requireApproval ?? false;
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Partition tool calls into those requiring approval and those that can auto-execute
|
|
95
|
-
* @param toolCalls - Tool calls to partition
|
|
96
|
-
* @param tools - Available tools
|
|
97
|
-
* @param context - Turn context for the approval check
|
|
98
|
-
* @param callLevelCheck - Optional call-level approval function (overrides tool-level), can be async
|
|
99
|
-
*/
|
|
100
|
-
export async function partitionToolCalls(toolCalls, tools, context, callLevelCheck) {
|
|
101
|
-
const requiresApproval = [];
|
|
102
|
-
const autoExecute = [];
|
|
103
|
-
for (const tc of toolCalls) {
|
|
104
|
-
if (await toolRequiresApproval(tc, tools, context, callLevelCheck)) {
|
|
105
|
-
requiresApproval.push(tc);
|
|
106
|
-
}
|
|
107
|
-
else {
|
|
108
|
-
autoExecute.push(tc);
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return { requiresApproval, autoExecute };
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* Create an unsent tool result from a successful execution
|
|
115
|
-
*/
|
|
116
|
-
export function createUnsentResult(callId, name, output) {
|
|
117
|
-
const result = { callId, name, output };
|
|
118
|
-
if (!isValidUnsentToolResult(result)) {
|
|
119
|
-
throw new Error('Invalid UnsentToolResult structure');
|
|
120
|
-
}
|
|
121
|
-
return result;
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Create an unsent tool result from a rejection
|
|
125
|
-
*/
|
|
126
|
-
export function createRejectedResult(callId, name, reason) {
|
|
127
|
-
const result = {
|
|
128
|
-
callId,
|
|
129
|
-
name,
|
|
130
|
-
output: null,
|
|
131
|
-
error: reason ?? 'Tool call rejected by user',
|
|
132
|
-
};
|
|
133
|
-
if (!isValidUnsentToolResult(result)) {
|
|
134
|
-
throw new Error('Invalid UnsentToolResult structure');
|
|
135
|
-
}
|
|
136
|
-
return result;
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Convert unsent tool results to API format for sending to the model
|
|
140
|
-
*/
|
|
141
|
-
export function unsentResultsToAPIFormat(results) {
|
|
142
|
-
return results.map(r => ({
|
|
143
|
-
type: 'function_call_output',
|
|
144
|
-
id: `output_${r.callId}`,
|
|
145
|
-
callId: r.callId,
|
|
146
|
-
output: r.error
|
|
147
|
-
? JSON.stringify({ error: r.error })
|
|
148
|
-
: JSON.stringify(r.output),
|
|
149
|
-
}));
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Extract text content from a response
|
|
153
|
-
*/
|
|
154
|
-
export function extractTextFromResponse(response) {
|
|
155
|
-
if (!response.output) {
|
|
156
|
-
return '';
|
|
157
|
-
}
|
|
158
|
-
const outputs = Array.isArray(response.output) ? response.output : [response.output];
|
|
159
|
-
const textParts = [];
|
|
160
|
-
for (const item of outputs) {
|
|
161
|
-
if (item.type === 'message' && 'content' in item && item.content) {
|
|
162
|
-
for (const content of item.content) {
|
|
163
|
-
if (content.type === 'output_text' && 'text' in content && content.text) {
|
|
164
|
-
textParts.push(content.text);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return textParts.join('');
|
|
170
|
-
}
|
|
171
|
-
/**
|
|
172
|
-
* Extract tool calls from a response
|
|
173
|
-
*/
|
|
174
|
-
export function extractToolCallsFromResponse(response) {
|
|
175
|
-
if (!response.output) {
|
|
176
|
-
return [];
|
|
177
|
-
}
|
|
178
|
-
const outputs = Array.isArray(response.output) ? response.output : [response.output];
|
|
179
|
-
const toolCalls = [];
|
|
180
|
-
for (const item of outputs) {
|
|
181
|
-
if (item.type !== 'function_call' || !('arguments' in item)) {
|
|
182
|
-
continue;
|
|
183
|
-
}
|
|
184
|
-
let parsedArguments;
|
|
185
|
-
if (typeof item.arguments === 'string') {
|
|
186
|
-
try {
|
|
187
|
-
parsedArguments = JSON.parse(item.arguments);
|
|
188
|
-
}
|
|
189
|
-
catch (error) {
|
|
190
|
-
// Log warning and skip malformed tool call, similar to stream-transformers.ts
|
|
191
|
-
console.warn(`Failed to parse arguments for tool call "${'name' in item ? item.name : 'unknown'}": ${error instanceof Error ? error.message : String(error)}`);
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
else {
|
|
196
|
-
parsedArguments = item.arguments;
|
|
197
|
-
}
|
|
198
|
-
const toolCall = {
|
|
199
|
-
id: ('callId' in item ? item.callId : undefined) ?? item.id ?? '',
|
|
200
|
-
name: ('name' in item ? item.name : undefined) ?? '',
|
|
201
|
-
arguments: parsedArguments,
|
|
202
|
-
};
|
|
203
|
-
if (!isValidParsedToolCall(toolCall)) {
|
|
204
|
-
throw new Error(`Invalid tool call structure for tool: ${toolCall.name}`);
|
|
205
|
-
}
|
|
206
|
-
toolCalls.push(toolCall);
|
|
207
|
-
}
|
|
208
|
-
return toolCalls;
|
|
209
|
-
}
|
|
210
|
-
//# sourceMappingURL=conversation-state.js.map
|