@yourgpt/copilot-sdk 2.1.3 → 2.1.5-alpha.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.
- package/dist/MessageTree-CoIt_4nB.d.cts +161 -0
- package/dist/MessageTree-CzaN9Eul.d.ts +161 -0
- package/dist/{ThreadManager-Dkp_eLty.d.ts → ThreadManager-BEAECB7Y.d.ts} +1 -1
- package/dist/{ThreadManager-LfFRhr4e.d.cts → ThreadManager-Cw5fwyCN.d.cts} +1 -1
- package/dist/{chunk-POZNNKNJ.cjs → chunk-246B6X5D.cjs} +8 -2
- package/dist/chunk-246B6X5D.cjs.map +1 -0
- package/dist/{chunk-QLH6TSCC.js → chunk-4QXY2PBG.js} +8 -2
- package/dist/chunk-4QXY2PBG.js.map +1 -0
- package/dist/{chunk-DMBFN7KO.js → chunk-6BMQZIS3.js} +3105 -355
- package/dist/chunk-6BMQZIS3.js.map +1 -0
- package/dist/{chunk-R6LKHKAI.cjs → chunk-76RE7AJE.cjs} +3277 -509
- package/dist/chunk-76RE7AJE.cjs.map +1 -0
- package/dist/chunk-BJYA5NDL.cjs +96 -0
- package/dist/chunk-BJYA5NDL.cjs.map +1 -0
- package/dist/{chunk-LZMBBGWH.js → chunk-ENFWM3EY.js} +4 -4
- package/dist/{chunk-LZMBBGWH.js.map → chunk-ENFWM3EY.js.map} +1 -1
- package/dist/{chunk-WQSK3Z4K.cjs → chunk-I3SQUNTT.cjs} +81 -31
- package/dist/chunk-I3SQUNTT.cjs.map +1 -0
- package/dist/{chunk-WAPGTQDR.cjs → chunk-JKGFQUHJ.cjs} +10 -10
- package/dist/{chunk-WAPGTQDR.cjs.map → chunk-JKGFQUHJ.cjs.map} +1 -1
- package/dist/{chunk-XGITAEXU.js → chunk-LLM7AHMO.js} +2 -2
- package/dist/{chunk-XGITAEXU.js.map → chunk-LLM7AHMO.js.map} +1 -1
- package/dist/{chunk-ASV6JLYG.cjs → chunk-NUXLAZOE.cjs} +2 -2
- package/dist/{chunk-ASV6JLYG.cjs.map → chunk-NUXLAZOE.cjs.map} +1 -1
- package/dist/{chunk-VFV5FVVI.js → chunk-UXJ6LIZB.js} +61 -13
- package/dist/chunk-UXJ6LIZB.js.map +1 -0
- package/dist/chunk-VNLLW3ZI.js +94 -0
- package/dist/chunk-VNLLW3ZI.js.map +1 -0
- package/dist/core/index.cjs +99 -91
- package/dist/core/index.d.cts +21 -10
- package/dist/core/index.d.ts +21 -10
- package/dist/core/index.js +5 -5
- package/dist/{index-BHkRA0mM.d.cts → index-CiExk87c.d.cts} +1 -1
- package/dist/{index-tB0qI8my.d.ts → index-Dwrcf-CP.d.ts} +1 -1
- package/dist/mcp/index.d.cts +3 -3
- package/dist/mcp/index.d.ts +3 -3
- package/dist/react/index.cjs +113 -52
- package/dist/react/index.d.cts +703 -90
- package/dist/react/index.d.ts +703 -90
- package/dist/react/index.js +7 -6
- package/dist/server/index.cjs +339 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +171 -0
- package/dist/server/index.d.ts +171 -0
- package/dist/server/index.js +332 -0
- package/dist/server/index.js.map +1 -0
- package/dist/tools/anthropic/index.cjs +3 -3
- package/dist/tools/anthropic/index.d.cts +1 -1
- package/dist/tools/anthropic/index.d.ts +1 -1
- package/dist/tools/anthropic/index.js +3 -3
- package/dist/tools/brave/index.cjs +6 -6
- package/dist/tools/brave/index.d.cts +1 -1
- package/dist/tools/brave/index.d.ts +1 -1
- package/dist/tools/brave/index.js +3 -3
- package/dist/tools/exa/index.cjs +6 -6
- package/dist/tools/exa/index.d.cts +1 -1
- package/dist/tools/exa/index.d.ts +1 -1
- package/dist/tools/exa/index.js +3 -3
- package/dist/tools/google/index.cjs +6 -6
- package/dist/tools/google/index.d.cts +1 -1
- package/dist/tools/google/index.d.ts +1 -1
- package/dist/tools/google/index.js +3 -3
- package/dist/tools/openai/index.cjs +6 -6
- package/dist/tools/openai/index.d.cts +1 -1
- package/dist/tools/openai/index.d.ts +1 -1
- package/dist/tools/openai/index.js +3 -3
- package/dist/tools/searxng/index.cjs +6 -6
- package/dist/tools/searxng/index.d.cts +1 -1
- package/dist/tools/searxng/index.d.ts +1 -1
- package/dist/tools/searxng/index.js +3 -3
- package/dist/tools/serper/index.cjs +6 -6
- package/dist/tools/serper/index.d.cts +1 -1
- package/dist/tools/serper/index.d.ts +1 -1
- package/dist/tools/serper/index.js +3 -3
- package/dist/tools/tavily/index.cjs +6 -6
- package/dist/tools/tavily/index.d.cts +1 -1
- package/dist/tools/tavily/index.d.ts +1 -1
- package/dist/tools/tavily/index.js +3 -3
- package/dist/tools/web-search/index.cjs +7 -7
- package/dist/tools/web-search/index.d.cts +2 -2
- package/dist/tools/web-search/index.d.ts +2 -2
- package/dist/tools/web-search/index.js +4 -4
- package/dist/{tools-coIcskZ4.d.ts → tools-DHZhF5km.d.cts} +161 -1
- package/dist/{tools-coIcskZ4.d.cts → tools-DHZhF5km.d.ts} +161 -1
- package/dist/{types-rjaSVmEF.d.ts → types-BTyJu0WD.d.ts} +1 -1
- package/dist/types-BckL3hiw.d.cts +93 -0
- package/dist/types-BckL3hiw.d.ts +93 -0
- package/dist/{types-C8t4Ut8f.d.cts → types-BdX7uPj0.d.cts} +1 -1
- package/dist/{types-DG2ya08y.d.ts → types-BeFBBZ5i.d.cts} +64 -1
- package/dist/{types-DG2ya08y.d.cts → types-BeFBBZ5i.d.ts} +64 -1
- package/dist/ui/index.cjs +468 -163
- package/dist/ui/index.cjs.map +1 -1
- package/dist/ui/index.d.cts +81 -4
- package/dist/ui/index.d.ts +81 -4
- package/dist/ui/index.js +416 -112
- package/dist/ui/index.js.map +1 -1
- package/package.json +6 -1
- package/dist/chunk-DMBFN7KO.js.map +0 -1
- package/dist/chunk-POZNNKNJ.cjs.map +0 -1
- package/dist/chunk-QLH6TSCC.js.map +0 -1
- package/dist/chunk-R6LKHKAI.cjs.map +0 -1
- package/dist/chunk-VFV5FVVI.js.map +0 -1
- package/dist/chunk-WQSK3Z4K.cjs.map +0 -1
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { M as MessageAttachment, T as ToolCall, S as Source } from './types-BeFBBZ5i.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Message Types
|
|
5
|
+
*
|
|
6
|
+
* Pure type definitions for chat messages.
|
|
7
|
+
* No logic, no side effects - just types.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Chat message roles
|
|
12
|
+
*/
|
|
13
|
+
type MessageRole = "user" | "assistant" | "system" | "tool";
|
|
14
|
+
/**
|
|
15
|
+
* UIMessage - The source of truth for UI state
|
|
16
|
+
*
|
|
17
|
+
* Inspired by Vercel AI SDK's UIMessage pattern.
|
|
18
|
+
* This is what your UI renders and what gets persisted.
|
|
19
|
+
*/
|
|
20
|
+
interface UIMessage {
|
|
21
|
+
/** Unique message ID */
|
|
22
|
+
id: string;
|
|
23
|
+
/** Message role */
|
|
24
|
+
role: MessageRole;
|
|
25
|
+
/** Message content */
|
|
26
|
+
content: string;
|
|
27
|
+
/** Thinking/reasoning content (for extended thinking models) */
|
|
28
|
+
thinking?: string;
|
|
29
|
+
/** Message attachments (images, PDFs, etc) */
|
|
30
|
+
attachments?: MessageAttachment[];
|
|
31
|
+
/** Tool calls made by assistant */
|
|
32
|
+
toolCalls?: ToolCall[];
|
|
33
|
+
/** Tool call ID (for tool result messages) */
|
|
34
|
+
toolCallId?: string;
|
|
35
|
+
/** Sources from knowledge base */
|
|
36
|
+
sources?: Source[];
|
|
37
|
+
/** Creation timestamp */
|
|
38
|
+
createdAt: Date;
|
|
39
|
+
/** Additional metadata */
|
|
40
|
+
metadata?: Record<string, unknown>;
|
|
41
|
+
/**
|
|
42
|
+
* Parent message ID for branching support.
|
|
43
|
+
* - null = root message (no parent)
|
|
44
|
+
* - undefined = legacy linear message (no branch awareness)
|
|
45
|
+
* - string = ID of parent message
|
|
46
|
+
*/
|
|
47
|
+
parentId?: string | null;
|
|
48
|
+
/** Direct children IDs for O(1) sibling lookup */
|
|
49
|
+
childrenIds?: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* MessageTree — Bidirectional flat-map message tree for conversation branching.
|
|
54
|
+
*
|
|
55
|
+
* Industry-standard data structure used by ChatGPT, Claude.ai, and Gemini:
|
|
56
|
+
* - parentId + childrenIds[] for O(1) navigation
|
|
57
|
+
* - activeChildMap tracks the active path through the tree
|
|
58
|
+
*
|
|
59
|
+
* Zero React dependency — pure TypeScript, works in any environment.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Branch navigation info for the UI navigator (← N/M →)
|
|
64
|
+
*/
|
|
65
|
+
interface BranchInfo {
|
|
66
|
+
/** 0-based index of this message among its siblings */
|
|
67
|
+
siblingIndex: number;
|
|
68
|
+
/** Total number of sibling variants at this fork */
|
|
69
|
+
totalSiblings: number;
|
|
70
|
+
/** Ordered IDs of all siblings (oldest-first) */
|
|
71
|
+
siblingIds: string[];
|
|
72
|
+
hasPrevious: boolean;
|
|
73
|
+
hasNext: boolean;
|
|
74
|
+
}
|
|
75
|
+
declare class MessageTree<T extends UIMessage = UIMessage> {
|
|
76
|
+
/** All messages by ID */
|
|
77
|
+
private nodeMap;
|
|
78
|
+
/** parentKey → ordered list of child IDs (insertion order = oldest-first) */
|
|
79
|
+
private childrenOf;
|
|
80
|
+
/** parentKey → currently-active child ID */
|
|
81
|
+
private activeChildMap;
|
|
82
|
+
/** Current leaf message ID (tip of the active path) */
|
|
83
|
+
private _currentLeafId;
|
|
84
|
+
/** Cached visible messages — invalidated on every mutation */
|
|
85
|
+
private _visibleCache;
|
|
86
|
+
/** Sentinel key used for root-level messages (parentId === null) */
|
|
87
|
+
static readonly ROOT_KEY = "__root__";
|
|
88
|
+
constructor(messages?: T[]);
|
|
89
|
+
/**
|
|
90
|
+
* Convert a legacy flat array (no parentId) to a tree-linked array.
|
|
91
|
+
*
|
|
92
|
+
* Rules:
|
|
93
|
+
* - Tool messages get parentId = the owning assistant message's id
|
|
94
|
+
* (matched via toolCallId → toolCall.id).
|
|
95
|
+
* - All other messages get parentId of the previous non-tool message
|
|
96
|
+
* (or null for the first message).
|
|
97
|
+
*
|
|
98
|
+
* Returns a new array with parentId/childrenIds filled in.
|
|
99
|
+
* Does NOT mutate the original messages.
|
|
100
|
+
*/
|
|
101
|
+
static fromFlatArray<T extends UIMessage>(messages: T[]): T[];
|
|
102
|
+
/**
|
|
103
|
+
* Returns the visible path (root → current leaf) — what the UI renders
|
|
104
|
+
* and what gets sent to the API.
|
|
105
|
+
*
|
|
106
|
+
* Backward-compat: if NO message has parentId set (all undefined),
|
|
107
|
+
* falls back to insertion order (legacy linear mode).
|
|
108
|
+
*/
|
|
109
|
+
getVisibleMessages(): T[];
|
|
110
|
+
private _invalidateCache;
|
|
111
|
+
/**
|
|
112
|
+
* Returns ALL messages across every branch (for persistence / ThreadManager).
|
|
113
|
+
*/
|
|
114
|
+
getAllMessages(): T[];
|
|
115
|
+
/**
|
|
116
|
+
* Branch navigation info for the UI navigator.
|
|
117
|
+
* Returns null if the message has no siblings (only child).
|
|
118
|
+
*/
|
|
119
|
+
getBranchInfo(messageId: string): BranchInfo | null;
|
|
120
|
+
get currentLeafId(): string | null;
|
|
121
|
+
get hasBranches(): boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Insert a new message.
|
|
124
|
+
* - Updates childrenOf and nodeMap.
|
|
125
|
+
* - New branch becomes active (activeChildMap updated).
|
|
126
|
+
* - Updates current leaf.
|
|
127
|
+
*/
|
|
128
|
+
addMessage(message: T): T;
|
|
129
|
+
/**
|
|
130
|
+
* Navigate: make messageId the active child at its parent fork,
|
|
131
|
+
* then walk to its leaf and update currentLeafId.
|
|
132
|
+
*/
|
|
133
|
+
switchBranch(messageId: string): void;
|
|
134
|
+
/**
|
|
135
|
+
* Update message content in-place (streaming updates).
|
|
136
|
+
* No tree structure change.
|
|
137
|
+
*/
|
|
138
|
+
updateMessage(id: string, updater: (msg: T) => T): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Set current leaf explicitly.
|
|
141
|
+
* Used by regenerate() to rewind the active path before pushing a new message.
|
|
142
|
+
*/
|
|
143
|
+
setCurrentLeaf(leafId: string | null): void;
|
|
144
|
+
/**
|
|
145
|
+
* Rebuild entire tree from a message array.
|
|
146
|
+
* Used by setMessages().
|
|
147
|
+
*/
|
|
148
|
+
reset(messages: T[]): void;
|
|
149
|
+
private _buildFromMessages;
|
|
150
|
+
private _parentKey;
|
|
151
|
+
/**
|
|
152
|
+
* Walk forward from a message along active children to find the leaf.
|
|
153
|
+
*/
|
|
154
|
+
private _walkToLeaf;
|
|
155
|
+
/**
|
|
156
|
+
* Walk the active path from root to the current leaf.
|
|
157
|
+
*/
|
|
158
|
+
private _getActivePath;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { type BranchInfo as B, MessageTree as M, type UIMessage as U };
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { M as MessageAttachment, T as ToolCall, S as Source } from './types-BeFBBZ5i.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Message Types
|
|
5
|
+
*
|
|
6
|
+
* Pure type definitions for chat messages.
|
|
7
|
+
* No logic, no side effects - just types.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Chat message roles
|
|
12
|
+
*/
|
|
13
|
+
type MessageRole = "user" | "assistant" | "system" | "tool";
|
|
14
|
+
/**
|
|
15
|
+
* UIMessage - The source of truth for UI state
|
|
16
|
+
*
|
|
17
|
+
* Inspired by Vercel AI SDK's UIMessage pattern.
|
|
18
|
+
* This is what your UI renders and what gets persisted.
|
|
19
|
+
*/
|
|
20
|
+
interface UIMessage {
|
|
21
|
+
/** Unique message ID */
|
|
22
|
+
id: string;
|
|
23
|
+
/** Message role */
|
|
24
|
+
role: MessageRole;
|
|
25
|
+
/** Message content */
|
|
26
|
+
content: string;
|
|
27
|
+
/** Thinking/reasoning content (for extended thinking models) */
|
|
28
|
+
thinking?: string;
|
|
29
|
+
/** Message attachments (images, PDFs, etc) */
|
|
30
|
+
attachments?: MessageAttachment[];
|
|
31
|
+
/** Tool calls made by assistant */
|
|
32
|
+
toolCalls?: ToolCall[];
|
|
33
|
+
/** Tool call ID (for tool result messages) */
|
|
34
|
+
toolCallId?: string;
|
|
35
|
+
/** Sources from knowledge base */
|
|
36
|
+
sources?: Source[];
|
|
37
|
+
/** Creation timestamp */
|
|
38
|
+
createdAt: Date;
|
|
39
|
+
/** Additional metadata */
|
|
40
|
+
metadata?: Record<string, unknown>;
|
|
41
|
+
/**
|
|
42
|
+
* Parent message ID for branching support.
|
|
43
|
+
* - null = root message (no parent)
|
|
44
|
+
* - undefined = legacy linear message (no branch awareness)
|
|
45
|
+
* - string = ID of parent message
|
|
46
|
+
*/
|
|
47
|
+
parentId?: string | null;
|
|
48
|
+
/** Direct children IDs for O(1) sibling lookup */
|
|
49
|
+
childrenIds?: string[];
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* MessageTree — Bidirectional flat-map message tree for conversation branching.
|
|
54
|
+
*
|
|
55
|
+
* Industry-standard data structure used by ChatGPT, Claude.ai, and Gemini:
|
|
56
|
+
* - parentId + childrenIds[] for O(1) navigation
|
|
57
|
+
* - activeChildMap tracks the active path through the tree
|
|
58
|
+
*
|
|
59
|
+
* Zero React dependency — pure TypeScript, works in any environment.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Branch navigation info for the UI navigator (← N/M →)
|
|
64
|
+
*/
|
|
65
|
+
interface BranchInfo {
|
|
66
|
+
/** 0-based index of this message among its siblings */
|
|
67
|
+
siblingIndex: number;
|
|
68
|
+
/** Total number of sibling variants at this fork */
|
|
69
|
+
totalSiblings: number;
|
|
70
|
+
/** Ordered IDs of all siblings (oldest-first) */
|
|
71
|
+
siblingIds: string[];
|
|
72
|
+
hasPrevious: boolean;
|
|
73
|
+
hasNext: boolean;
|
|
74
|
+
}
|
|
75
|
+
declare class MessageTree<T extends UIMessage = UIMessage> {
|
|
76
|
+
/** All messages by ID */
|
|
77
|
+
private nodeMap;
|
|
78
|
+
/** parentKey → ordered list of child IDs (insertion order = oldest-first) */
|
|
79
|
+
private childrenOf;
|
|
80
|
+
/** parentKey → currently-active child ID */
|
|
81
|
+
private activeChildMap;
|
|
82
|
+
/** Current leaf message ID (tip of the active path) */
|
|
83
|
+
private _currentLeafId;
|
|
84
|
+
/** Cached visible messages — invalidated on every mutation */
|
|
85
|
+
private _visibleCache;
|
|
86
|
+
/** Sentinel key used for root-level messages (parentId === null) */
|
|
87
|
+
static readonly ROOT_KEY = "__root__";
|
|
88
|
+
constructor(messages?: T[]);
|
|
89
|
+
/**
|
|
90
|
+
* Convert a legacy flat array (no parentId) to a tree-linked array.
|
|
91
|
+
*
|
|
92
|
+
* Rules:
|
|
93
|
+
* - Tool messages get parentId = the owning assistant message's id
|
|
94
|
+
* (matched via toolCallId → toolCall.id).
|
|
95
|
+
* - All other messages get parentId of the previous non-tool message
|
|
96
|
+
* (or null for the first message).
|
|
97
|
+
*
|
|
98
|
+
* Returns a new array with parentId/childrenIds filled in.
|
|
99
|
+
* Does NOT mutate the original messages.
|
|
100
|
+
*/
|
|
101
|
+
static fromFlatArray<T extends UIMessage>(messages: T[]): T[];
|
|
102
|
+
/**
|
|
103
|
+
* Returns the visible path (root → current leaf) — what the UI renders
|
|
104
|
+
* and what gets sent to the API.
|
|
105
|
+
*
|
|
106
|
+
* Backward-compat: if NO message has parentId set (all undefined),
|
|
107
|
+
* falls back to insertion order (legacy linear mode).
|
|
108
|
+
*/
|
|
109
|
+
getVisibleMessages(): T[];
|
|
110
|
+
private _invalidateCache;
|
|
111
|
+
/**
|
|
112
|
+
* Returns ALL messages across every branch (for persistence / ThreadManager).
|
|
113
|
+
*/
|
|
114
|
+
getAllMessages(): T[];
|
|
115
|
+
/**
|
|
116
|
+
* Branch navigation info for the UI navigator.
|
|
117
|
+
* Returns null if the message has no siblings (only child).
|
|
118
|
+
*/
|
|
119
|
+
getBranchInfo(messageId: string): BranchInfo | null;
|
|
120
|
+
get currentLeafId(): string | null;
|
|
121
|
+
get hasBranches(): boolean;
|
|
122
|
+
/**
|
|
123
|
+
* Insert a new message.
|
|
124
|
+
* - Updates childrenOf and nodeMap.
|
|
125
|
+
* - New branch becomes active (activeChildMap updated).
|
|
126
|
+
* - Updates current leaf.
|
|
127
|
+
*/
|
|
128
|
+
addMessage(message: T): T;
|
|
129
|
+
/**
|
|
130
|
+
* Navigate: make messageId the active child at its parent fork,
|
|
131
|
+
* then walk to its leaf and update currentLeafId.
|
|
132
|
+
*/
|
|
133
|
+
switchBranch(messageId: string): void;
|
|
134
|
+
/**
|
|
135
|
+
* Update message content in-place (streaming updates).
|
|
136
|
+
* No tree structure change.
|
|
137
|
+
*/
|
|
138
|
+
updateMessage(id: string, updater: (msg: T) => T): boolean;
|
|
139
|
+
/**
|
|
140
|
+
* Set current leaf explicitly.
|
|
141
|
+
* Used by regenerate() to rewind the active path before pushing a new message.
|
|
142
|
+
*/
|
|
143
|
+
setCurrentLeaf(leafId: string | null): void;
|
|
144
|
+
/**
|
|
145
|
+
* Rebuild entire tree from a message array.
|
|
146
|
+
* Used by setMessages().
|
|
147
|
+
*/
|
|
148
|
+
reset(messages: T[]): void;
|
|
149
|
+
private _buildFromMessages;
|
|
150
|
+
private _parentKey;
|
|
151
|
+
/**
|
|
152
|
+
* Walk forward from a message along active children to find the leaf.
|
|
153
|
+
*/
|
|
154
|
+
private _walkToLeaf;
|
|
155
|
+
/**
|
|
156
|
+
* Walk the active path from root to the current leaf.
|
|
157
|
+
*/
|
|
158
|
+
private _getActivePath;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export { type BranchInfo as B, MessageTree as M, type UIMessage as U };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as Thread, b as ThreadData, c as ThreadStorageAdapter, A as AsyncThreadStorageAdapter, d as Message } from './types-BeFBBZ5i.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Tool types for App Context Awareness
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as Thread, b as ThreadData, c as ThreadStorageAdapter, A as AsyncThreadStorageAdapter, d as Message } from './types-BeFBBZ5i.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Tool types for App Context Awareness
|
|
@@ -5,6 +5,12 @@ function tool(config) {
|
|
|
5
5
|
return {
|
|
6
6
|
description: config.description,
|
|
7
7
|
location: config.location ?? "client",
|
|
8
|
+
category: config.category,
|
|
9
|
+
group: config.group,
|
|
10
|
+
deferLoading: config.deferLoading,
|
|
11
|
+
profiles: config.profiles,
|
|
12
|
+
searchKeywords: config.searchKeywords,
|
|
13
|
+
resultConfig: config.resultConfig,
|
|
8
14
|
// Display configuration
|
|
9
15
|
title: config.title,
|
|
10
16
|
executingTitle: config.executingTitle,
|
|
@@ -70,5 +76,5 @@ exports.success = success;
|
|
|
70
76
|
exports.tool = tool;
|
|
71
77
|
exports.toolToAnthropicFormat = toolToAnthropicFormat;
|
|
72
78
|
exports.toolToOpenAIFormat = toolToOpenAIFormat;
|
|
73
|
-
//# sourceMappingURL=chunk-
|
|
74
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
//# sourceMappingURL=chunk-246B6X5D.cjs.map
|
|
80
|
+
//# sourceMappingURL=chunk-246B6X5D.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types/tools.ts"],"names":["tool"],"mappings":";;;AAw8BO,SAAS,KACd,MAAA,EACuC;AACvC,EAAA,OAAO;AAAA,IACL,aAAa,MAAA,CAAO,WAAA;AAAA,IACpB,QAAA,EAAU,OAAO,QAAA,IAAY,QAAA;AAAA,IAC7B,UAAU,MAAA,CAAO,QAAA;AAAA,IACjB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,UAAU,MAAA,CAAO,QAAA;AAAA,IACjB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,cAAc,MAAA,CAAO,YAAA;AAAA;AAAA,IAErB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,gBAAgB,MAAA,CAAO,cAAA;AAAA;AAAA,IAEvB,WAAA,EAAa,OAAO,WAAA,IAAe;AAAA,MACjC,IAAA,EAAM,QAAA;AAAA,MACN,YAAY,EAAC;AAAA,MACb,UAAU;AAAC,KACb;AAAA,IACA,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,iBAAiB,MAAA,CAAO,eAAA;AAAA,IACxB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,WAAW,MAAA,CAAO;AAAA,GACpB;AACF;AASO,SAAS,mBAAmBA,KAAAA,EAA8B;AAC/D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAAA,MACR,MAAMA,KAAAA,CAAK,IAAA;AAAA,MACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,MAClB,YAAYA,KAAAA,CAAK;AAAA;AACnB,GACF;AACF;AAKO,SAAS,sBAAsBA,KAAAA,EAA8B;AAClE,EAAA,OAAO;AAAA,IACL,MAAMA,KAAAA,CAAK,IAAA;AAAA,IACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,IAClB,cAAcA,KAAAA,CAAK;AAAA,GACrB;AACF;AAKO,SAAS,gBAAA,CACd,YACA,QAAA,EACmB;AACnB,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAAA,IAChC,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,OAAO,QAAA,CAAS;AAAA,GAClB;AACF;AAKO,SAAS,OAAA,CACd,MACA,OAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,IAAA;AAAA,IACT,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAKO,SAAS,QAAQ,KAAA,EAA6B;AACnD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-246B6X5D.cjs","sourcesContent":["/**\n * Tool-related types for the agentic loop\n */\n\nimport type { ActionRenderProps } from \"./actions\";\n\n// ============================================\n// Provider Types\n// ============================================\n\n/**\n * Supported AI providers for tool calling\n */\nexport type AIProvider =\n | \"anthropic\"\n | \"openai\"\n | \"xai\"\n | \"grok\"\n | \"gemini\"\n | \"groq\"\n | \"ollama\";\n\n/**\n * Where the tool executes\n */\nexport type ToolLocation = \"server\" | \"client\";\n\n/**\n * Source/origin of the tool\n * - \"mcp\": Tool from an MCP (Model Context Protocol) server\n * - \"native\": Built-in SDK tool\n * - \"custom\": User-defined tool\n */\nexport type ToolSource = \"mcp\" | \"native\" | \"custom\";\n\n// ============================================\n// Tool Definition Types\n// ============================================\n\n/**\n * JSON Schema property definition\n */\nexport interface JSONSchemaProperty {\n type:\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"integer\"\n | \"null\";\n description?: string;\n enum?: (string | number | boolean)[];\n items?: JSONSchemaProperty;\n properties?: Record<string, JSONSchemaProperty>;\n required?: string[];\n default?: unknown;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\n/**\n * JSON Schema for tool input\n */\nexport interface ToolInputSchema {\n type: \"object\";\n properties: Record<string, JSONSchemaProperty>;\n required?: string[];\n additionalProperties?: boolean;\n}\n\n/**\n * Tool execution context\n *\n * Provides runtime information to tool handlers including cancellation signals,\n * request metadata, and custom context data.\n */\nexport interface ToolContext {\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Thread ID if using threads */\n threadId?: string;\n /** Custom context data passed from runtime config */\n data?: Record<string, unknown>;\n\n // ============================================\n // Rich Context (Vercel AI SDK pattern)\n // ============================================\n\n /**\n * Unique ID for this specific tool call.\n * Useful for logging, tracing, and correlating tool executions.\n */\n toolCallId?: string;\n\n /**\n * Request headers (for auth in server tools).\n * Contains headers from the original HTTP request.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * const token = context?.headers?.authorization;\n * if (!token) return failure('Authentication required');\n * // ...\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * Full request metadata for server-side tools.\n * Provides access to HTTP method, URL, and headers.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * console.log(`Tool called from: ${context?.request?.url}`);\n * // Forward auth to internal service\n * const authHeader = context?.request?.headers?.authorization;\n * }\n * ```\n */\n request?: {\n /** HTTP method (GET, POST, etc.) */\n method?: string;\n /** Request URL path */\n url?: string;\n /** Request headers */\n headers?: Record<string, string>;\n };\n\n /**\n * Data passed from user's approval action.\n * Only present when tool has `needsApproval: true` and user approved with extra data.\n *\n * @example\n * ```typescript\n * // In render function:\n * approval.onApprove({ supervisor: selectedSupervisor });\n *\n * // In handler:\n * handler: async (params, context) => {\n * const supervisor = context?.approvalData?.supervisor;\n * await assignToSupervisor(params.ticketId, supervisor);\n * }\n * ```\n */\n approvalData?: Record<string, unknown>;\n}\n\n// ============================================\n// AI Response Control Types\n// ============================================\n\n/**\n * AI response behavior for tool results.\n *\n * Controls what the AI sees after a tool executes and renders UI.\n *\n * - `'none'`: AI generates minimal response, UI component handles display\n * - `'brief'`: AI gets summary context (via aiContext), gives brief acknowledgment\n * - `'full'`: AI receives full data and responds accordingly (default)\n */\nexport type AIResponseMode = \"none\" | \"brief\" | \"full\";\n\n/**\n * Multimodal content for AI to analyze\n */\nexport type AIContent =\n | { type: \"image\"; data: string; mediaType: string }\n | { type: \"text\"; text: string };\n\n/**\n * How large tool results should be trimmed before they are sent back to the AI.\n */\nexport type ToolTruncationStrategy = \"head\" | \"head-tail\" | \"smart\";\n\n/**\n * Truncation controls for tool results.\n */\nexport interface ToolResultTruncationConfig {\n enabled?: boolean;\n maxContextShare?: number;\n hardMaxChars?: number;\n minKeepChars?: number;\n strategy?: ToolTruncationStrategy;\n preserveErrors?: boolean;\n}\n\n/**\n * Global or per-tool controls for how tool results are represented in prompts.\n */\nexport interface ToolResultConfig {\n truncation?: ToolResultTruncationConfig;\n}\n\n/**\n * Named tool profile for selective loading.\n */\nexport interface ToolProfile {\n name: string;\n description?: string;\n include?: string[];\n exclude?: string[];\n}\n\n/**\n * Tool profile configuration.\n */\nexport interface ToolProfileConfig {\n enabled?: boolean;\n defaultProfile?: string;\n profiles?: Record<string, ToolProfile>;\n /** When false, active profiles exclude tools that do not declare profile membership. */\n includeUnprofiled?: boolean;\n dynamicSelection?: {\n enabled?: boolean;\n maxTools?: number;\n };\n}\n\n/**\n * History compaction behavior for long-running sessions.\n */\nexport interface ContextHistoryConfig {\n maxMessages?: number;\n maxTokens?: number;\n maxContextShare?: number;\n pruneStrategy?: \"oldest\" | \"least-relevant\" | \"summarize\";\n}\n\n/**\n * Optional summarization controls used during history compaction.\n */\nexport interface ContextSummarizationConfig {\n enabled?: boolean;\n triggerAt?: number;\n chunkSize?: number;\n preserveRecent?: number;\n fallbackBehavior?: \"truncate\" | \"statistical\" | \"error\";\n}\n\n/**\n * Token estimation controls.\n */\nexport interface TokenEstimationConfig {\n safetyMargin?: number;\n charsPerToken?: number;\n}\n\n/**\n * Conversation context management.\n */\nexport interface ContextManagementConfig {\n enabled?: boolean;\n history?: ContextHistoryConfig;\n summarization?: ContextSummarizationConfig;\n tokenEstimation?: TokenEstimationConfig;\n}\n\n/**\n * One budget bucket in the prompt context.\n */\nexport interface ContextUsagePart {\n tokens: number;\n percent: number;\n}\n\n/**\n * Prompt context usage snapshot.\n */\nexport interface ContextUsage {\n total: ContextUsagePart;\n breakdown: {\n systemPrompt: ContextUsagePart;\n history: ContextUsagePart;\n toolResults: ContextUsagePart;\n tools: ContextUsagePart;\n };\n budget: {\n available: number;\n remaining: number;\n };\n warnings: string[];\n}\n\n/**\n * Real-time context budget configuration.\n */\nexport interface ContextBudgetConfig {\n enabled?: boolean;\n budget?: {\n contextWindowTokens?: number;\n inputHeadroomRatio?: number;\n systemPromptShare?: number;\n historyShare?: number;\n toolResultsShare?: number;\n toolDefinitionsShare?: number;\n };\n enforcement?: {\n mode?: \"warn\" | \"truncate\" | \"error\";\n onBudgetExceeded?: (info: ContextUsage) => void;\n };\n monitoring?: {\n enabled?: boolean;\n onUsageUpdate?: (usage: ContextUsage) => void;\n };\n}\n\n/**\n * Framework-agnostic optimization controls for tool-heavy chat sessions.\n */\nexport interface ToolOptimizationConfig {\n toolProfiles?: ToolProfileConfig;\n toolResultConfig?: ToolResultConfig;\n contextManagement?: ContextManagementConfig;\n contextBudget?: ContextBudgetConfig;\n}\n\n/**\n * Tool response format\n */\nexport interface ToolResponse<T = unknown> {\n /** Whether the tool succeeded */\n success: boolean;\n /** Human-readable message */\n message?: string;\n /** Error message if failed */\n error?: string;\n /** Result data */\n data?: T;\n\n // ============================================\n // AI Response Control (result-level overrides)\n // ============================================\n\n /**\n * Override AI context for this specific result.\n * Takes precedence over tool-level aiContext config.\n * If set, this message is sent to AI instead of full result data.\n *\n * @example\n * ```typescript\n * return {\n * success: true,\n * data: sensitiveData,\n * _aiContext: '[Data retrieved - contains sensitive info, displayed to user]'\n * };\n * ```\n */\n _aiContext?: string;\n\n /**\n * Override AI response mode for this specific result.\n * Takes precedence over tool-level aiResponseMode config.\n */\n _aiResponseMode?: AIResponseMode;\n\n /**\n * Content for AI to analyze (images, documents, etc.).\n * When present, these are included as multimodal content for AI analysis.\n *\n * @example\n * ```typescript\n * // Screenshot for AI to analyze\n * return {\n * success: true,\n * message: 'Screenshot captured',\n * _aiContent: [{ type: 'image', data: base64, mediaType: 'image/png' }]\n * };\n * ```\n */\n _aiContent?: AIContent[];\n\n /**\n * MCP-UI resources for rendering interactive UI components.\n * These are extracted from MCP tool results and rendered as iframes.\n * Not sent to the AI - purely for UI rendering.\n *\n * @example\n * ```typescript\n * // MCP tool returning UI\n * return {\n * success: true,\n * message: 'Product displayed',\n * _uiResources: [{\n * uri: 'ui://shop/product/123',\n * mimeType: 'text/html',\n * content: '<div class=\"product\">...</div>',\n * metadata: { height: '300px' }\n * }]\n * };\n * ```\n */\n _uiResources?: Array<{\n uri: string;\n mimeType:\n | \"text/html\"\n | \"text/uri-list\"\n | \"application/vnd.mcp-ui.remote-dom\";\n content?: string;\n blob?: string;\n metadata?: {\n title?: string;\n width?: string;\n height?: string;\n sandbox?: string[];\n className?: string;\n };\n }>;\n}\n\n/**\n * Approval callbacks passed to render when tool requires user action.\n * Only present when status is \"approval-required\".\n */\nexport interface ToolApprovalCallbacks {\n /**\n * Approve execution and optionally pass extra data to the handler.\n * The extraData is available in handler via `context.approvalData`.\n *\n * @example\n * ```tsx\n * // Simple approval\n * approval.onApprove();\n *\n * // Approval with data (e.g., user selection)\n * approval.onApprove({ supervisor: { name: \"John\", role: \"Manager\" } });\n * ```\n */\n onApprove: (extraData?: Record<string, unknown>) => void;\n\n /**\n * Reject the tool execution with optional reason.\n * This stops the tool from executing and returns an error to AI.\n */\n onReject: (reason?: string) => void;\n\n /** Custom message from tool's approvalMessage config */\n message?: string;\n}\n\n/**\n * Props passed to tool render function.\n *\n * The render function is called for every status change, enabling\n * full lifecycle rendering similar to Vercel AI SDK.\n *\n * @example\n * ```tsx\n * render: ({ status, args, approval, result }) => {\n * if (status === \"approval-required\" && approval) {\n * return <ApprovalCard onConfirm={() => approval.onApprove()} />;\n * }\n * if (status === \"executing\") {\n * return <LoadingSkeleton />;\n * }\n * if (status === \"completed\") {\n * return <ResultCard data={result.data} />;\n * }\n * return null;\n * }\n * ```\n */\nexport interface ToolRenderProps<TParams = Record<string, unknown>> {\n /**\n * Current execution status:\n * - `pending`: Tool call received, waiting to start\n * - `approval-required`: Waiting for user approval (when needsApproval is set)\n * - `executing`: Handler is running\n * - `completed`: Handler finished successfully\n * - `error`: Handler failed\n */\n status: \"pending\" | \"approval-required\" | \"executing\" | \"completed\" | \"error\";\n\n /** Arguments passed to the tool */\n args: TParams;\n\n /** Result if completed */\n result?: ToolResponse;\n\n /** Error if failed */\n error?: string;\n\n /** Tool call ID */\n toolCallId: string;\n\n /** Tool name */\n toolName: string;\n\n /**\n * Approval callbacks - only present when status is \"approval-required\".\n * Use these to create custom approval UIs that can pass extra data to the handler.\n */\n approval?: ToolApprovalCallbacks;\n}\n\n/**\n * Tool definition with JSON Schema\n */\nexport interface ToolDefinition<TParams = Record<string, unknown>> {\n /** Unique tool name */\n name: string;\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (server or client) */\n location: ToolLocation;\n /**\n * Source/origin of the tool.\n * Used to distinguish MCP tools from native/custom tools for UI rendering.\n * @default \"custom\"\n */\n source?: ToolSource;\n /** Optional category for search, filtering, and budgets */\n category?: string;\n /** Optional group for profile-based tool selection */\n group?: string;\n /** Deferred tools are discoverable but need not be sent on every request */\n deferLoading?: boolean;\n /** Profile memberships for selective tool loading */\n profiles?: string[];\n /** Extra keywords for dynamic tool selection */\n searchKeywords?: string[];\n /** Per-tool prompt/result shaping controls */\n resultConfig?: ToolResultConfig;\n\n // ============================================\n // Display Configuration\n // ============================================\n\n /**\n * Human-readable title for UI display.\n * Can be a static string or a function that generates title from args.\n *\n * @example\n * ```typescript\n * title: \"Get order details\"\n * // or dynamic:\n * title: (args) => `Order #${args.orderId}`\n * ```\n */\n title?: string | ((args: TParams) => string);\n\n /**\n * Title shown while executing (present tense with \"...\").\n * If not provided, uses `title` with \"...\" appended.\n *\n * @example\n * ```typescript\n * executingTitle: (args) => `Fetching order #${args.orderId}...`\n * ```\n */\n executingTitle?: string | ((args: TParams) => string);\n\n /**\n * Title shown after completion.\n * If not provided, defaults to `title`.\n *\n * @example\n * ```typescript\n * completedTitle: (args) => `Retrieved order #${args.orderId}`\n * ```\n */\n completedTitle?: string | ((args: TParams) => string);\n /** JSON Schema for input parameters */\n inputSchema: ToolInputSchema;\n /** Handler function (optional for client tools registered on server) */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available (for conditional registration) */\n available?: boolean;\n\n /**\n * Hide this tool's execution from the chat UI.\n * When true, tool calls and results won't be displayed to the user,\n * but the tool will still execute normally.\n * @default false\n */\n hidden?: boolean;\n\n /**\n * Require user approval before execution.\n * Can be:\n * - `true`: Always require approval\n * - `false` or `undefined`: No approval needed (default)\n * - `(params) => boolean`: Conditional approval based on input\n *\n * Similar to Vercel AI SDK v6's needsApproval pattern.\n */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n\n /**\n * Custom message shown in the approval UI.\n * Can be a string or a function that generates a message from params.\n * If not provided, a default message with the tool name is shown.\n */\n approvalMessage?: string | ((params: TParams) => string);\n\n // ============================================\n // AI Response Control\n // ============================================\n\n /**\n * How the AI should respond when this tool's result is rendered as UI.\n *\n * - `'none'`: AI generates minimal response (\"[Result displayed to user]\").\n * Use for tools where UI component fully handles the display (stats cards, etc.)\n *\n * - `'brief'`: AI receives summary context (from aiContext) and gives brief acknowledgment.\n * Use for charts/visualizations where AI should acknowledge but not repeat data.\n *\n * - `'full'`: AI receives complete data and responds accordingly (default).\n * Use for tools where AI should analyze and elaborate on results.\n *\n * @default 'full'\n *\n * @example\n * ```typescript\n * // Chart tool - AI acknowledges without repeating data\n * const chartTool: ToolDefinition = {\n * name: 'get_chart',\n * aiResponseMode: 'brief',\n * aiContext: (result) => `[Chart displayed: ${result.data.title}]`,\n * handler: async () => ({ success: true, data: chartData })\n * };\n * ```\n */\n aiResponseMode?: AIResponseMode;\n\n /**\n * Context/summary sent to AI instead of (or along with) full result.\n *\n * Used when:\n * - `aiResponseMode: 'brief'` - This becomes the only thing AI sees\n * - `aiResponseMode: 'full'` - This is prepended to full data for context\n *\n * Can be:\n * - `string`: Static message (e.g., \"[Weather data displayed]\")\n * - `function`: Dynamic based on result (e.g., (result) => `[Chart: ${result.data.title}]`)\n *\n * @example\n * ```typescript\n * // Static context\n * aiContext: '[Analytics chart displayed to user]'\n *\n * // Dynamic context based on result\n * aiContext: (result, args) => {\n * const { title, currentValue } = result.data;\n * return `[Chart displayed: ${title}, showing ${currentValue}]`;\n * }\n * ```\n */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n// ============================================\n// Unified Tool Call Types (Provider-Agnostic)\n// ============================================\n\n/**\n * Unified tool call format (internal representation)\n */\nexport interface UnifiedToolCall {\n /** Unique tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool input arguments */\n input: Record<string, unknown>;\n}\n\n/**\n * Unified tool result format\n */\nexport interface UnifiedToolResult {\n /** Tool call ID this result is for */\n toolCallId: string;\n /** Serialized result content (JSON string) */\n content: string;\n /** Whether the tool succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n// ============================================\n// Tool Execution Types\n// ============================================\n\n/**\n * Tool execution status\n */\nexport type ToolExecutionStatus =\n | \"pending\"\n | \"executing\"\n | \"completed\"\n | \"error\";\n\n/**\n * Tool approval status (for human-in-the-loop)\n *\n * Similar to Vercel AI SDK v6's tool approval pattern.\n */\nexport type ToolApprovalStatus =\n | \"none\" // No approval needed (default)\n | \"required\" // Waiting for user decision\n | \"approved\" // User approved, execution can proceed\n | \"rejected\"; // User rejected, execution skipped\n\n// ============================================\n// Permission Persistence Types\n// ============================================\n\n/**\n * Permission level for tool execution\n *\n * Controls whether approval is needed and how the choice is remembered:\n * - \"ask\" - Always prompt user (default)\n * - \"allow_always\" - Auto-approve, persisted to storage\n * - \"deny_always\" - Auto-reject, persisted to storage\n * - \"session\" - Auto-approve for current session only\n */\nexport type PermissionLevel =\n | \"ask\"\n | \"allow_always\"\n | \"deny_always\"\n | \"session\";\n\n/**\n * Stored tool permission record\n */\nexport interface ToolPermission {\n /** Tool name (unique identifier) */\n toolName: string;\n /** Permission level */\n level: PermissionLevel;\n /** When permission was set */\n createdAt: number;\n /** Last time this permission was used */\n lastUsedAt?: number;\n}\n\n/**\n * Permission storage configuration\n */\nexport interface PermissionStorageConfig {\n /**\n * Storage type:\n * - \"localStorage\" - Persists across browser sessions\n * - \"sessionStorage\" - Clears when tab closes\n * - \"memory\" - In-memory only (for SSR or testing)\n */\n type: \"localStorage\" | \"sessionStorage\" | \"memory\";\n /** Storage key prefix (default: \"yourgpt-permissions\") */\n keyPrefix?: string;\n}\n\n/**\n * Permission storage adapter interface (for custom implementations)\n */\nexport interface PermissionStorageAdapter {\n /** Get permission for a tool */\n get(toolName: string): Promise<ToolPermission | null>;\n /** Set permission for a tool */\n set(permission: ToolPermission): Promise<void>;\n /** Remove permission for a tool */\n remove(toolName: string): Promise<void>;\n /** Get all permissions */\n getAll(): Promise<ToolPermission[]>;\n /** Clear all permissions */\n clear(): Promise<void>;\n}\n\n/**\n * Tool execution record (for UI tracking)\n */\nexport interface ToolExecution {\n /** Tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Execution status */\n status: ToolExecutionStatus;\n /** Result if completed */\n result?: ToolResponse;\n /** Error message if failed */\n error?: string;\n /** Timestamp when execution started */\n timestamp: number;\n /** Duration in ms (set when completed) */\n duration?: number;\n\n // Approval fields (for needsApproval tools)\n\n /** Approval status for this execution */\n approvalStatus: ToolApprovalStatus;\n /** Message shown in approval UI (from tool's approvalMessage) */\n approvalMessage?: string;\n /** Timestamp when user responded to approval request */\n approvalTimestamp?: number;\n\n /**\n * Whether this tool execution should be hidden from the UI.\n * Server-side tools can set this to hide internal operations from users.\n */\n hidden?: boolean;\n}\n\n// ============================================\n// Agent Loop Types\n// ============================================\n\n/**\n * Agentic loop configuration\n */\nexport interface AgentLoopConfig {\n /** Maximum iterations before stopping (default: 20) */\n maxIterations?: number;\n /** Enable debug logging */\n debug?: boolean;\n /** Whether to enable the agentic loop (default: true) */\n enabled?: boolean;\n /** Optional prompt/tool optimization controls */\n optimization?: ToolOptimizationConfig;\n}\n\n/**\n * Agent loop state (for tracking)\n */\nexport interface AgentLoopState {\n /** Current iteration number */\n iteration: number;\n /** Maximum iterations allowed */\n maxIterations: number;\n /** Whether the loop is currently running */\n running: boolean;\n /** Whether max iterations was reached */\n maxIterationsReached: boolean;\n /** Whether the loop was aborted */\n aborted: boolean;\n}\n\n// ============================================\n// ToolSet Type (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * A tool definition without the name (name is derived from the key in ToolSet)\n */\nexport type ToolSetEntry<TParams = Record<string, unknown>> = Omit<\n ToolDefinition<TParams>,\n \"name\"\n>;\n\n/**\n * A set of tools, keyed by tool name\n *\n * The key becomes the tool name, so tool definitions don't need a name property.\n * Use with the `tool()` helper for clean syntax.\n *\n * @example\n * ```typescript\n * const myTools: ToolSet = {\n * capture_screenshot: tool({\n * description: 'Capture screenshot',\n * handler: async () => ({ success: true }),\n * }),\n * get_weather: tool({\n * description: 'Get weather',\n * inputSchema: { type: 'object', properties: { city: { type: 'string' } } },\n * handler: async ({ city }) => ({ success: true, data: { temp: 72 } }),\n * }),\n * };\n * ```\n */\nexport type ToolSet = Record<string, ToolSetEntry>;\n\n// ============================================\n// Tool Helper Function (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * Configuration for creating a tool\n */\nexport interface ToolConfig<TParams = Record<string, unknown>> {\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (default: 'client') */\n location?: ToolLocation;\n /** Optional category for search, filtering, and budgets */\n category?: string;\n /** Optional group for profile-based tool selection */\n group?: string;\n /** Deferred tools are discoverable but omitted from the default prompt */\n deferLoading?: boolean;\n /** Profile memberships for selective tool loading */\n profiles?: string[];\n /** Extra keywords for dynamic tool selection */\n searchKeywords?: string[];\n /** Per-tool prompt/result shaping controls */\n resultConfig?: ToolResultConfig;\n\n // Display Configuration\n /** Human-readable title for UI display */\n title?: string | ((args: TParams) => string);\n /** Title shown while executing */\n executingTitle?: string | ((args: TParams) => string);\n /** Title shown after completion */\n completedTitle?: string | ((args: TParams) => string);\n\n /** JSON Schema for input parameters */\n inputSchema?: ToolInputSchema;\n /** Handler function */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available */\n available?: boolean;\n /** Hide this tool from chat UI display */\n hidden?: boolean;\n /** Require user approval before execution */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n /** Custom message shown in the approval UI */\n approvalMessage?: string | ((params: TParams) => string);\n /** AI response mode for this tool (default: 'full') */\n aiResponseMode?: AIResponseMode;\n /** Context/summary sent to AI instead of full result */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n/**\n * Create a tool definition (similar to Vercel AI SDK's tool())\n *\n * @example\n * ```typescript\n * const weatherTool = tool({\n * description: 'Get weather for a location',\n * inputSchema: {\n * type: 'object',\n * properties: {\n * location: { type: 'string', description: 'City name' },\n * },\n * required: ['location'],\n * },\n * handler: async ({ location }) => {\n * const weather = await fetchWeather(location);\n * return success(weather);\n * },\n * });\n * ```\n */\nexport function tool<TParams = Record<string, unknown>>(\n config: ToolConfig<TParams>,\n): Omit<ToolDefinition<TParams>, \"name\"> {\n return {\n description: config.description,\n location: config.location ?? \"client\",\n category: config.category,\n group: config.group,\n deferLoading: config.deferLoading,\n profiles: config.profiles,\n searchKeywords: config.searchKeywords,\n resultConfig: config.resultConfig,\n // Display configuration\n title: config.title,\n executingTitle: config.executingTitle,\n completedTitle: config.completedTitle,\n // Schema and handlers\n inputSchema: config.inputSchema ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n handler: config.handler,\n render: config.render,\n available: config.available,\n hidden: config.hidden,\n needsApproval: config.needsApproval,\n approvalMessage: config.approvalMessage,\n aiResponseMode: config.aiResponseMode,\n aiContext: config.aiContext,\n };\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Convert ToolDefinition to OpenAI tool format\n */\nexport function toolToOpenAIFormat(tool: ToolDefinition): object {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Convert ToolDefinition to Anthropic tool format\n */\nexport function toolToAnthropicFormat(tool: ToolDefinition): object {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n };\n}\n\n/**\n * Create a tool result response\n */\nexport function createToolResult(\n toolCallId: string,\n response: ToolResponse,\n): UnifiedToolResult {\n return {\n toolCallId,\n content: JSON.stringify(response),\n success: response.success,\n error: response.error,\n };\n}\n\n/**\n * Create a successful tool response\n */\nexport function success<T = unknown>(\n data?: T,\n message?: string,\n): ToolResponse<T> {\n return {\n success: true,\n data,\n message,\n };\n}\n\n/**\n * Create a failed tool response\n */\nexport function failure(error: string): ToolResponse {\n return {\n success: false,\n error,\n };\n}\n"]}
|
|
@@ -3,6 +3,12 @@ function tool(config) {
|
|
|
3
3
|
return {
|
|
4
4
|
description: config.description,
|
|
5
5
|
location: config.location ?? "client",
|
|
6
|
+
category: config.category,
|
|
7
|
+
group: config.group,
|
|
8
|
+
deferLoading: config.deferLoading,
|
|
9
|
+
profiles: config.profiles,
|
|
10
|
+
searchKeywords: config.searchKeywords,
|
|
11
|
+
resultConfig: config.resultConfig,
|
|
6
12
|
// Display configuration
|
|
7
13
|
title: config.title,
|
|
8
14
|
executingTitle: config.executingTitle,
|
|
@@ -63,5 +69,5 @@ function failure(error) {
|
|
|
63
69
|
}
|
|
64
70
|
|
|
65
71
|
export { createToolResult, failure, success, tool, toolToAnthropicFormat, toolToOpenAIFormat };
|
|
66
|
-
//# sourceMappingURL=chunk-
|
|
67
|
-
//# sourceMappingURL=chunk-
|
|
72
|
+
//# sourceMappingURL=chunk-4QXY2PBG.js.map
|
|
73
|
+
//# sourceMappingURL=chunk-4QXY2PBG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types/tools.ts"],"names":["tool"],"mappings":";AAw8BO,SAAS,KACd,MAAA,EACuC;AACvC,EAAA,OAAO;AAAA,IACL,aAAa,MAAA,CAAO,WAAA;AAAA,IACpB,QAAA,EAAU,OAAO,QAAA,IAAY,QAAA;AAAA,IAC7B,UAAU,MAAA,CAAO,QAAA;AAAA,IACjB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,cAAc,MAAA,CAAO,YAAA;AAAA,IACrB,UAAU,MAAA,CAAO,QAAA;AAAA,IACjB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,cAAc,MAAA,CAAO,YAAA;AAAA;AAAA,IAErB,OAAO,MAAA,CAAO,KAAA;AAAA,IACd,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,gBAAgB,MAAA,CAAO,cAAA;AAAA;AAAA,IAEvB,WAAA,EAAa,OAAO,WAAA,IAAe;AAAA,MACjC,IAAA,EAAM,QAAA;AAAA,MACN,YAAY,EAAC;AAAA,MACb,UAAU;AAAC,KACb;AAAA,IACA,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,QAAQ,MAAA,CAAO,MAAA;AAAA,IACf,eAAe,MAAA,CAAO,aAAA;AAAA,IACtB,iBAAiB,MAAA,CAAO,eAAA;AAAA,IACxB,gBAAgB,MAAA,CAAO,cAAA;AAAA,IACvB,WAAW,MAAA,CAAO;AAAA,GACpB;AACF;AASO,SAAS,mBAAmBA,KAAAA,EAA8B;AAC/D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,UAAA;AAAA,IACN,QAAA,EAAU;AAAA,MACR,MAAMA,KAAAA,CAAK,IAAA;AAAA,MACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,MAClB,YAAYA,KAAAA,CAAK;AAAA;AACnB,GACF;AACF;AAKO,SAAS,sBAAsBA,KAAAA,EAA8B;AAClE,EAAA,OAAO;AAAA,IACL,MAAMA,KAAAA,CAAK,IAAA;AAAA,IACX,aAAaA,KAAAA,CAAK,WAAA;AAAA,IAClB,cAAcA,KAAAA,CAAK;AAAA,GACrB;AACF;AAKO,SAAS,gBAAA,CACd,YACA,QAAA,EACmB;AACnB,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,OAAA,EAAS,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAA;AAAA,IAChC,SAAS,QAAA,CAAS,OAAA;AAAA,IAClB,OAAO,QAAA,CAAS;AAAA,GAClB;AACF;AAKO,SAAS,OAAA,CACd,MACA,OAAA,EACiB;AACjB,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,IAAA;AAAA,IACT,IAAA;AAAA,IACA;AAAA,GACF;AACF;AAKO,SAAS,QAAQ,KAAA,EAA6B;AACnD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT;AAAA,GACF;AACF","file":"chunk-4QXY2PBG.js","sourcesContent":["/**\n * Tool-related types for the agentic loop\n */\n\nimport type { ActionRenderProps } from \"./actions\";\n\n// ============================================\n// Provider Types\n// ============================================\n\n/**\n * Supported AI providers for tool calling\n */\nexport type AIProvider =\n | \"anthropic\"\n | \"openai\"\n | \"xai\"\n | \"grok\"\n | \"gemini\"\n | \"groq\"\n | \"ollama\";\n\n/**\n * Where the tool executes\n */\nexport type ToolLocation = \"server\" | \"client\";\n\n/**\n * Source/origin of the tool\n * - \"mcp\": Tool from an MCP (Model Context Protocol) server\n * - \"native\": Built-in SDK tool\n * - \"custom\": User-defined tool\n */\nexport type ToolSource = \"mcp\" | \"native\" | \"custom\";\n\n// ============================================\n// Tool Definition Types\n// ============================================\n\n/**\n * JSON Schema property definition\n */\nexport interface JSONSchemaProperty {\n type:\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"object\"\n | \"array\"\n | \"integer\"\n | \"null\";\n description?: string;\n enum?: (string | number | boolean)[];\n items?: JSONSchemaProperty;\n properties?: Record<string, JSONSchemaProperty>;\n required?: string[];\n default?: unknown;\n minLength?: number;\n maxLength?: number;\n minimum?: number;\n maximum?: number;\n pattern?: string;\n}\n\n/**\n * JSON Schema for tool input\n */\nexport interface ToolInputSchema {\n type: \"object\";\n properties: Record<string, JSONSchemaProperty>;\n required?: string[];\n additionalProperties?: boolean;\n}\n\n/**\n * Tool execution context\n *\n * Provides runtime information to tool handlers including cancellation signals,\n * request metadata, and custom context data.\n */\nexport interface ToolContext {\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n /** Thread ID if using threads */\n threadId?: string;\n /** Custom context data passed from runtime config */\n data?: Record<string, unknown>;\n\n // ============================================\n // Rich Context (Vercel AI SDK pattern)\n // ============================================\n\n /**\n * Unique ID for this specific tool call.\n * Useful for logging, tracing, and correlating tool executions.\n */\n toolCallId?: string;\n\n /**\n * Request headers (for auth in server tools).\n * Contains headers from the original HTTP request.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * const token = context?.headers?.authorization;\n * if (!token) return failure('Authentication required');\n * // ...\n * }\n * ```\n */\n headers?: Record<string, string>;\n\n /**\n * Full request metadata for server-side tools.\n * Provides access to HTTP method, URL, and headers.\n *\n * @example\n * ```typescript\n * handler: async (params, context) => {\n * console.log(`Tool called from: ${context?.request?.url}`);\n * // Forward auth to internal service\n * const authHeader = context?.request?.headers?.authorization;\n * }\n * ```\n */\n request?: {\n /** HTTP method (GET, POST, etc.) */\n method?: string;\n /** Request URL path */\n url?: string;\n /** Request headers */\n headers?: Record<string, string>;\n };\n\n /**\n * Data passed from user's approval action.\n * Only present when tool has `needsApproval: true` and user approved with extra data.\n *\n * @example\n * ```typescript\n * // In render function:\n * approval.onApprove({ supervisor: selectedSupervisor });\n *\n * // In handler:\n * handler: async (params, context) => {\n * const supervisor = context?.approvalData?.supervisor;\n * await assignToSupervisor(params.ticketId, supervisor);\n * }\n * ```\n */\n approvalData?: Record<string, unknown>;\n}\n\n// ============================================\n// AI Response Control Types\n// ============================================\n\n/**\n * AI response behavior for tool results.\n *\n * Controls what the AI sees after a tool executes and renders UI.\n *\n * - `'none'`: AI generates minimal response, UI component handles display\n * - `'brief'`: AI gets summary context (via aiContext), gives brief acknowledgment\n * - `'full'`: AI receives full data and responds accordingly (default)\n */\nexport type AIResponseMode = \"none\" | \"brief\" | \"full\";\n\n/**\n * Multimodal content for AI to analyze\n */\nexport type AIContent =\n | { type: \"image\"; data: string; mediaType: string }\n | { type: \"text\"; text: string };\n\n/**\n * How large tool results should be trimmed before they are sent back to the AI.\n */\nexport type ToolTruncationStrategy = \"head\" | \"head-tail\" | \"smart\";\n\n/**\n * Truncation controls for tool results.\n */\nexport interface ToolResultTruncationConfig {\n enabled?: boolean;\n maxContextShare?: number;\n hardMaxChars?: number;\n minKeepChars?: number;\n strategy?: ToolTruncationStrategy;\n preserveErrors?: boolean;\n}\n\n/**\n * Global or per-tool controls for how tool results are represented in prompts.\n */\nexport interface ToolResultConfig {\n truncation?: ToolResultTruncationConfig;\n}\n\n/**\n * Named tool profile for selective loading.\n */\nexport interface ToolProfile {\n name: string;\n description?: string;\n include?: string[];\n exclude?: string[];\n}\n\n/**\n * Tool profile configuration.\n */\nexport interface ToolProfileConfig {\n enabled?: boolean;\n defaultProfile?: string;\n profiles?: Record<string, ToolProfile>;\n /** When false, active profiles exclude tools that do not declare profile membership. */\n includeUnprofiled?: boolean;\n dynamicSelection?: {\n enabled?: boolean;\n maxTools?: number;\n };\n}\n\n/**\n * History compaction behavior for long-running sessions.\n */\nexport interface ContextHistoryConfig {\n maxMessages?: number;\n maxTokens?: number;\n maxContextShare?: number;\n pruneStrategy?: \"oldest\" | \"least-relevant\" | \"summarize\";\n}\n\n/**\n * Optional summarization controls used during history compaction.\n */\nexport interface ContextSummarizationConfig {\n enabled?: boolean;\n triggerAt?: number;\n chunkSize?: number;\n preserveRecent?: number;\n fallbackBehavior?: \"truncate\" | \"statistical\" | \"error\";\n}\n\n/**\n * Token estimation controls.\n */\nexport interface TokenEstimationConfig {\n safetyMargin?: number;\n charsPerToken?: number;\n}\n\n/**\n * Conversation context management.\n */\nexport interface ContextManagementConfig {\n enabled?: boolean;\n history?: ContextHistoryConfig;\n summarization?: ContextSummarizationConfig;\n tokenEstimation?: TokenEstimationConfig;\n}\n\n/**\n * One budget bucket in the prompt context.\n */\nexport interface ContextUsagePart {\n tokens: number;\n percent: number;\n}\n\n/**\n * Prompt context usage snapshot.\n */\nexport interface ContextUsage {\n total: ContextUsagePart;\n breakdown: {\n systemPrompt: ContextUsagePart;\n history: ContextUsagePart;\n toolResults: ContextUsagePart;\n tools: ContextUsagePart;\n };\n budget: {\n available: number;\n remaining: number;\n };\n warnings: string[];\n}\n\n/**\n * Real-time context budget configuration.\n */\nexport interface ContextBudgetConfig {\n enabled?: boolean;\n budget?: {\n contextWindowTokens?: number;\n inputHeadroomRatio?: number;\n systemPromptShare?: number;\n historyShare?: number;\n toolResultsShare?: number;\n toolDefinitionsShare?: number;\n };\n enforcement?: {\n mode?: \"warn\" | \"truncate\" | \"error\";\n onBudgetExceeded?: (info: ContextUsage) => void;\n };\n monitoring?: {\n enabled?: boolean;\n onUsageUpdate?: (usage: ContextUsage) => void;\n };\n}\n\n/**\n * Framework-agnostic optimization controls for tool-heavy chat sessions.\n */\nexport interface ToolOptimizationConfig {\n toolProfiles?: ToolProfileConfig;\n toolResultConfig?: ToolResultConfig;\n contextManagement?: ContextManagementConfig;\n contextBudget?: ContextBudgetConfig;\n}\n\n/**\n * Tool response format\n */\nexport interface ToolResponse<T = unknown> {\n /** Whether the tool succeeded */\n success: boolean;\n /** Human-readable message */\n message?: string;\n /** Error message if failed */\n error?: string;\n /** Result data */\n data?: T;\n\n // ============================================\n // AI Response Control (result-level overrides)\n // ============================================\n\n /**\n * Override AI context for this specific result.\n * Takes precedence over tool-level aiContext config.\n * If set, this message is sent to AI instead of full result data.\n *\n * @example\n * ```typescript\n * return {\n * success: true,\n * data: sensitiveData,\n * _aiContext: '[Data retrieved - contains sensitive info, displayed to user]'\n * };\n * ```\n */\n _aiContext?: string;\n\n /**\n * Override AI response mode for this specific result.\n * Takes precedence over tool-level aiResponseMode config.\n */\n _aiResponseMode?: AIResponseMode;\n\n /**\n * Content for AI to analyze (images, documents, etc.).\n * When present, these are included as multimodal content for AI analysis.\n *\n * @example\n * ```typescript\n * // Screenshot for AI to analyze\n * return {\n * success: true,\n * message: 'Screenshot captured',\n * _aiContent: [{ type: 'image', data: base64, mediaType: 'image/png' }]\n * };\n * ```\n */\n _aiContent?: AIContent[];\n\n /**\n * MCP-UI resources for rendering interactive UI components.\n * These are extracted from MCP tool results and rendered as iframes.\n * Not sent to the AI - purely for UI rendering.\n *\n * @example\n * ```typescript\n * // MCP tool returning UI\n * return {\n * success: true,\n * message: 'Product displayed',\n * _uiResources: [{\n * uri: 'ui://shop/product/123',\n * mimeType: 'text/html',\n * content: '<div class=\"product\">...</div>',\n * metadata: { height: '300px' }\n * }]\n * };\n * ```\n */\n _uiResources?: Array<{\n uri: string;\n mimeType:\n | \"text/html\"\n | \"text/uri-list\"\n | \"application/vnd.mcp-ui.remote-dom\";\n content?: string;\n blob?: string;\n metadata?: {\n title?: string;\n width?: string;\n height?: string;\n sandbox?: string[];\n className?: string;\n };\n }>;\n}\n\n/**\n * Approval callbacks passed to render when tool requires user action.\n * Only present when status is \"approval-required\".\n */\nexport interface ToolApprovalCallbacks {\n /**\n * Approve execution and optionally pass extra data to the handler.\n * The extraData is available in handler via `context.approvalData`.\n *\n * @example\n * ```tsx\n * // Simple approval\n * approval.onApprove();\n *\n * // Approval with data (e.g., user selection)\n * approval.onApprove({ supervisor: { name: \"John\", role: \"Manager\" } });\n * ```\n */\n onApprove: (extraData?: Record<string, unknown>) => void;\n\n /**\n * Reject the tool execution with optional reason.\n * This stops the tool from executing and returns an error to AI.\n */\n onReject: (reason?: string) => void;\n\n /** Custom message from tool's approvalMessage config */\n message?: string;\n}\n\n/**\n * Props passed to tool render function.\n *\n * The render function is called for every status change, enabling\n * full lifecycle rendering similar to Vercel AI SDK.\n *\n * @example\n * ```tsx\n * render: ({ status, args, approval, result }) => {\n * if (status === \"approval-required\" && approval) {\n * return <ApprovalCard onConfirm={() => approval.onApprove()} />;\n * }\n * if (status === \"executing\") {\n * return <LoadingSkeleton />;\n * }\n * if (status === \"completed\") {\n * return <ResultCard data={result.data} />;\n * }\n * return null;\n * }\n * ```\n */\nexport interface ToolRenderProps<TParams = Record<string, unknown>> {\n /**\n * Current execution status:\n * - `pending`: Tool call received, waiting to start\n * - `approval-required`: Waiting for user approval (when needsApproval is set)\n * - `executing`: Handler is running\n * - `completed`: Handler finished successfully\n * - `error`: Handler failed\n */\n status: \"pending\" | \"approval-required\" | \"executing\" | \"completed\" | \"error\";\n\n /** Arguments passed to the tool */\n args: TParams;\n\n /** Result if completed */\n result?: ToolResponse;\n\n /** Error if failed */\n error?: string;\n\n /** Tool call ID */\n toolCallId: string;\n\n /** Tool name */\n toolName: string;\n\n /**\n * Approval callbacks - only present when status is \"approval-required\".\n * Use these to create custom approval UIs that can pass extra data to the handler.\n */\n approval?: ToolApprovalCallbacks;\n}\n\n/**\n * Tool definition with JSON Schema\n */\nexport interface ToolDefinition<TParams = Record<string, unknown>> {\n /** Unique tool name */\n name: string;\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (server or client) */\n location: ToolLocation;\n /**\n * Source/origin of the tool.\n * Used to distinguish MCP tools from native/custom tools for UI rendering.\n * @default \"custom\"\n */\n source?: ToolSource;\n /** Optional category for search, filtering, and budgets */\n category?: string;\n /** Optional group for profile-based tool selection */\n group?: string;\n /** Deferred tools are discoverable but need not be sent on every request */\n deferLoading?: boolean;\n /** Profile memberships for selective tool loading */\n profiles?: string[];\n /** Extra keywords for dynamic tool selection */\n searchKeywords?: string[];\n /** Per-tool prompt/result shaping controls */\n resultConfig?: ToolResultConfig;\n\n // ============================================\n // Display Configuration\n // ============================================\n\n /**\n * Human-readable title for UI display.\n * Can be a static string or a function that generates title from args.\n *\n * @example\n * ```typescript\n * title: \"Get order details\"\n * // or dynamic:\n * title: (args) => `Order #${args.orderId}`\n * ```\n */\n title?: string | ((args: TParams) => string);\n\n /**\n * Title shown while executing (present tense with \"...\").\n * If not provided, uses `title` with \"...\" appended.\n *\n * @example\n * ```typescript\n * executingTitle: (args) => `Fetching order #${args.orderId}...`\n * ```\n */\n executingTitle?: string | ((args: TParams) => string);\n\n /**\n * Title shown after completion.\n * If not provided, defaults to `title`.\n *\n * @example\n * ```typescript\n * completedTitle: (args) => `Retrieved order #${args.orderId}`\n * ```\n */\n completedTitle?: string | ((args: TParams) => string);\n /** JSON Schema for input parameters */\n inputSchema: ToolInputSchema;\n /** Handler function (optional for client tools registered on server) */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available (for conditional registration) */\n available?: boolean;\n\n /**\n * Hide this tool's execution from the chat UI.\n * When true, tool calls and results won't be displayed to the user,\n * but the tool will still execute normally.\n * @default false\n */\n hidden?: boolean;\n\n /**\n * Require user approval before execution.\n * Can be:\n * - `true`: Always require approval\n * - `false` or `undefined`: No approval needed (default)\n * - `(params) => boolean`: Conditional approval based on input\n *\n * Similar to Vercel AI SDK v6's needsApproval pattern.\n */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n\n /**\n * Custom message shown in the approval UI.\n * Can be a string or a function that generates a message from params.\n * If not provided, a default message with the tool name is shown.\n */\n approvalMessage?: string | ((params: TParams) => string);\n\n // ============================================\n // AI Response Control\n // ============================================\n\n /**\n * How the AI should respond when this tool's result is rendered as UI.\n *\n * - `'none'`: AI generates minimal response (\"[Result displayed to user]\").\n * Use for tools where UI component fully handles the display (stats cards, etc.)\n *\n * - `'brief'`: AI receives summary context (from aiContext) and gives brief acknowledgment.\n * Use for charts/visualizations where AI should acknowledge but not repeat data.\n *\n * - `'full'`: AI receives complete data and responds accordingly (default).\n * Use for tools where AI should analyze and elaborate on results.\n *\n * @default 'full'\n *\n * @example\n * ```typescript\n * // Chart tool - AI acknowledges without repeating data\n * const chartTool: ToolDefinition = {\n * name: 'get_chart',\n * aiResponseMode: 'brief',\n * aiContext: (result) => `[Chart displayed: ${result.data.title}]`,\n * handler: async () => ({ success: true, data: chartData })\n * };\n * ```\n */\n aiResponseMode?: AIResponseMode;\n\n /**\n * Context/summary sent to AI instead of (or along with) full result.\n *\n * Used when:\n * - `aiResponseMode: 'brief'` - This becomes the only thing AI sees\n * - `aiResponseMode: 'full'` - This is prepended to full data for context\n *\n * Can be:\n * - `string`: Static message (e.g., \"[Weather data displayed]\")\n * - `function`: Dynamic based on result (e.g., (result) => `[Chart: ${result.data.title}]`)\n *\n * @example\n * ```typescript\n * // Static context\n * aiContext: '[Analytics chart displayed to user]'\n *\n * // Dynamic context based on result\n * aiContext: (result, args) => {\n * const { title, currentValue } = result.data;\n * return `[Chart displayed: ${title}, showing ${currentValue}]`;\n * }\n * ```\n */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n// ============================================\n// Unified Tool Call Types (Provider-Agnostic)\n// ============================================\n\n/**\n * Unified tool call format (internal representation)\n */\nexport interface UnifiedToolCall {\n /** Unique tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool input arguments */\n input: Record<string, unknown>;\n}\n\n/**\n * Unified tool result format\n */\nexport interface UnifiedToolResult {\n /** Tool call ID this result is for */\n toolCallId: string;\n /** Serialized result content (JSON string) */\n content: string;\n /** Whether the tool succeeded */\n success: boolean;\n /** Error message if failed */\n error?: string;\n}\n\n// ============================================\n// Tool Execution Types\n// ============================================\n\n/**\n * Tool execution status\n */\nexport type ToolExecutionStatus =\n | \"pending\"\n | \"executing\"\n | \"completed\"\n | \"error\";\n\n/**\n * Tool approval status (for human-in-the-loop)\n *\n * Similar to Vercel AI SDK v6's tool approval pattern.\n */\nexport type ToolApprovalStatus =\n | \"none\" // No approval needed (default)\n | \"required\" // Waiting for user decision\n | \"approved\" // User approved, execution can proceed\n | \"rejected\"; // User rejected, execution skipped\n\n// ============================================\n// Permission Persistence Types\n// ============================================\n\n/**\n * Permission level for tool execution\n *\n * Controls whether approval is needed and how the choice is remembered:\n * - \"ask\" - Always prompt user (default)\n * - \"allow_always\" - Auto-approve, persisted to storage\n * - \"deny_always\" - Auto-reject, persisted to storage\n * - \"session\" - Auto-approve for current session only\n */\nexport type PermissionLevel =\n | \"ask\"\n | \"allow_always\"\n | \"deny_always\"\n | \"session\";\n\n/**\n * Stored tool permission record\n */\nexport interface ToolPermission {\n /** Tool name (unique identifier) */\n toolName: string;\n /** Permission level */\n level: PermissionLevel;\n /** When permission was set */\n createdAt: number;\n /** Last time this permission was used */\n lastUsedAt?: number;\n}\n\n/**\n * Permission storage configuration\n */\nexport interface PermissionStorageConfig {\n /**\n * Storage type:\n * - \"localStorage\" - Persists across browser sessions\n * - \"sessionStorage\" - Clears when tab closes\n * - \"memory\" - In-memory only (for SSR or testing)\n */\n type: \"localStorage\" | \"sessionStorage\" | \"memory\";\n /** Storage key prefix (default: \"yourgpt-permissions\") */\n keyPrefix?: string;\n}\n\n/**\n * Permission storage adapter interface (for custom implementations)\n */\nexport interface PermissionStorageAdapter {\n /** Get permission for a tool */\n get(toolName: string): Promise<ToolPermission | null>;\n /** Set permission for a tool */\n set(permission: ToolPermission): Promise<void>;\n /** Remove permission for a tool */\n remove(toolName: string): Promise<void>;\n /** Get all permissions */\n getAll(): Promise<ToolPermission[]>;\n /** Clear all permissions */\n clear(): Promise<void>;\n}\n\n/**\n * Tool execution record (for UI tracking)\n */\nexport interface ToolExecution {\n /** Tool call ID */\n id: string;\n /** Tool name */\n name: string;\n /** Tool arguments */\n args: Record<string, unknown>;\n /** Execution status */\n status: ToolExecutionStatus;\n /** Result if completed */\n result?: ToolResponse;\n /** Error message if failed */\n error?: string;\n /** Timestamp when execution started */\n timestamp: number;\n /** Duration in ms (set when completed) */\n duration?: number;\n\n // Approval fields (for needsApproval tools)\n\n /** Approval status for this execution */\n approvalStatus: ToolApprovalStatus;\n /** Message shown in approval UI (from tool's approvalMessage) */\n approvalMessage?: string;\n /** Timestamp when user responded to approval request */\n approvalTimestamp?: number;\n\n /**\n * Whether this tool execution should be hidden from the UI.\n * Server-side tools can set this to hide internal operations from users.\n */\n hidden?: boolean;\n}\n\n// ============================================\n// Agent Loop Types\n// ============================================\n\n/**\n * Agentic loop configuration\n */\nexport interface AgentLoopConfig {\n /** Maximum iterations before stopping (default: 20) */\n maxIterations?: number;\n /** Enable debug logging */\n debug?: boolean;\n /** Whether to enable the agentic loop (default: true) */\n enabled?: boolean;\n /** Optional prompt/tool optimization controls */\n optimization?: ToolOptimizationConfig;\n}\n\n/**\n * Agent loop state (for tracking)\n */\nexport interface AgentLoopState {\n /** Current iteration number */\n iteration: number;\n /** Maximum iterations allowed */\n maxIterations: number;\n /** Whether the loop is currently running */\n running: boolean;\n /** Whether max iterations was reached */\n maxIterationsReached: boolean;\n /** Whether the loop was aborted */\n aborted: boolean;\n}\n\n// ============================================\n// ToolSet Type (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * A tool definition without the name (name is derived from the key in ToolSet)\n */\nexport type ToolSetEntry<TParams = Record<string, unknown>> = Omit<\n ToolDefinition<TParams>,\n \"name\"\n>;\n\n/**\n * A set of tools, keyed by tool name\n *\n * The key becomes the tool name, so tool definitions don't need a name property.\n * Use with the `tool()` helper for clean syntax.\n *\n * @example\n * ```typescript\n * const myTools: ToolSet = {\n * capture_screenshot: tool({\n * description: 'Capture screenshot',\n * handler: async () => ({ success: true }),\n * }),\n * get_weather: tool({\n * description: 'Get weather',\n * inputSchema: { type: 'object', properties: { city: { type: 'string' } } },\n * handler: async ({ city }) => ({ success: true, data: { temp: 72 } }),\n * }),\n * };\n * ```\n */\nexport type ToolSet = Record<string, ToolSetEntry>;\n\n// ============================================\n// Tool Helper Function (Vercel AI SDK pattern)\n// ============================================\n\n/**\n * Configuration for creating a tool\n */\nexport interface ToolConfig<TParams = Record<string, unknown>> {\n /** Tool description for LLM */\n description: string;\n /** Where the tool executes (default: 'client') */\n location?: ToolLocation;\n /** Optional category for search, filtering, and budgets */\n category?: string;\n /** Optional group for profile-based tool selection */\n group?: string;\n /** Deferred tools are discoverable but omitted from the default prompt */\n deferLoading?: boolean;\n /** Profile memberships for selective tool loading */\n profiles?: string[];\n /** Extra keywords for dynamic tool selection */\n searchKeywords?: string[];\n /** Per-tool prompt/result shaping controls */\n resultConfig?: ToolResultConfig;\n\n // Display Configuration\n /** Human-readable title for UI display */\n title?: string | ((args: TParams) => string);\n /** Title shown while executing */\n executingTitle?: string | ((args: TParams) => string);\n /** Title shown after completion */\n completedTitle?: string | ((args: TParams) => string);\n\n /** JSON Schema for input parameters */\n inputSchema?: ToolInputSchema;\n /** Handler function */\n handler?: (\n params: TParams,\n context?: ToolContext,\n ) => Promise<ToolResponse> | ToolResponse;\n /** Optional render function for UI */\n render?: (props: ToolRenderProps<TParams>) => unknown;\n /** Whether the tool is available */\n available?: boolean;\n /** Hide this tool from chat UI display */\n hidden?: boolean;\n /** Require user approval before execution */\n needsApproval?: boolean | ((params: TParams) => boolean | Promise<boolean>);\n /** Custom message shown in the approval UI */\n approvalMessage?: string | ((params: TParams) => string);\n /** AI response mode for this tool (default: 'full') */\n aiResponseMode?: AIResponseMode;\n /** Context/summary sent to AI instead of full result */\n aiContext?:\n | string\n | ((result: ToolResponse, args: Record<string, unknown>) => string);\n}\n\n/**\n * Create a tool definition (similar to Vercel AI SDK's tool())\n *\n * @example\n * ```typescript\n * const weatherTool = tool({\n * description: 'Get weather for a location',\n * inputSchema: {\n * type: 'object',\n * properties: {\n * location: { type: 'string', description: 'City name' },\n * },\n * required: ['location'],\n * },\n * handler: async ({ location }) => {\n * const weather = await fetchWeather(location);\n * return success(weather);\n * },\n * });\n * ```\n */\nexport function tool<TParams = Record<string, unknown>>(\n config: ToolConfig<TParams>,\n): Omit<ToolDefinition<TParams>, \"name\"> {\n return {\n description: config.description,\n location: config.location ?? \"client\",\n category: config.category,\n group: config.group,\n deferLoading: config.deferLoading,\n profiles: config.profiles,\n searchKeywords: config.searchKeywords,\n resultConfig: config.resultConfig,\n // Display configuration\n title: config.title,\n executingTitle: config.executingTitle,\n completedTitle: config.completedTitle,\n // Schema and handlers\n inputSchema: config.inputSchema ?? {\n type: \"object\",\n properties: {},\n required: [],\n },\n handler: config.handler,\n render: config.render,\n available: config.available,\n hidden: config.hidden,\n needsApproval: config.needsApproval,\n approvalMessage: config.approvalMessage,\n aiResponseMode: config.aiResponseMode,\n aiContext: config.aiContext,\n };\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Convert ToolDefinition to OpenAI tool format\n */\nexport function toolToOpenAIFormat(tool: ToolDefinition): object {\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.inputSchema,\n },\n };\n}\n\n/**\n * Convert ToolDefinition to Anthropic tool format\n */\nexport function toolToAnthropicFormat(tool: ToolDefinition): object {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: tool.inputSchema,\n };\n}\n\n/**\n * Create a tool result response\n */\nexport function createToolResult(\n toolCallId: string,\n response: ToolResponse,\n): UnifiedToolResult {\n return {\n toolCallId,\n content: JSON.stringify(response),\n success: response.success,\n error: response.error,\n };\n}\n\n/**\n * Create a successful tool response\n */\nexport function success<T = unknown>(\n data?: T,\n message?: string,\n): ToolResponse<T> {\n return {\n success: true,\n data,\n message,\n };\n}\n\n/**\n * Create a failed tool response\n */\nexport function failure(error: string): ToolResponse {\n return {\n success: false,\n error,\n };\n}\n"]}
|