botinabox 2.16.15 → 2.16.17

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.
@@ -0,0 +1,389 @@
1
+ // src/connectors/google/oauth.ts
2
+ var _google;
3
+ async function getGoogle() {
4
+ if (!_google) {
5
+ try {
6
+ const mod = await import("googleapis");
7
+ _google = mod.google;
8
+ } catch {
9
+ throw new Error(
10
+ "googleapis is required for Google connectors. Install it: npm install googleapis"
11
+ );
12
+ }
13
+ }
14
+ return _google;
15
+ }
16
+ async function createOAuth2Client(config) {
17
+ const google = await getGoogle();
18
+ return new google.auth.OAuth2(
19
+ config.clientId,
20
+ config.clientSecret,
21
+ config.redirectUri
22
+ );
23
+ }
24
+ function getAuthUrl(client, scopes) {
25
+ return client.generateAuthUrl({
26
+ access_type: "offline",
27
+ prompt: "consent",
28
+ scope: scopes
29
+ });
30
+ }
31
+ async function exchangeCode(client, code) {
32
+ const { tokens } = await client.getToken(code);
33
+ return tokens;
34
+ }
35
+ async function createServiceAccountClient(config, scopes) {
36
+ const google = await getGoogle();
37
+ const auth = new google.auth.GoogleAuth({
38
+ ...config.keyFile ? { keyFile: config.keyFile } : {},
39
+ ...config.credentials ? { credentials: config.credentials } : {},
40
+ scopes,
41
+ clientOptions: { subject: config.subject }
42
+ });
43
+ return auth.getClient();
44
+ }
45
+ async function loadTokens(getter, accountKey) {
46
+ const raw = await getter(`google_tokens:${accountKey}`);
47
+ if (!raw) return null;
48
+ try {
49
+ return JSON.parse(raw);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ async function saveTokens(setter, accountKey, tokens) {
55
+ await setter(`google_tokens:${accountKey}`, JSON.stringify(tokens));
56
+ }
57
+ async function refreshIfNeeded(client, tokens, saver) {
58
+ const buffer = 6e4;
59
+ const isExpired = tokens.expiry_date != null && Date.now() >= tokens.expiry_date - buffer;
60
+ if (!isExpired) return tokens;
61
+ client.setCredentials(tokens);
62
+ const { credentials } = await client.refreshAccessToken();
63
+ const refreshed = {
64
+ access_token: credentials.access_token,
65
+ refresh_token: credentials.refresh_token ?? tokens.refresh_token,
66
+ expiry_date: credentials.expiry_date ?? void 0,
67
+ token_type: credentials.token_type ?? "Bearer"
68
+ };
69
+ if (saver) {
70
+ await saver(refreshed);
71
+ }
72
+ return refreshed;
73
+ }
74
+
75
+ // src/connectors/google/gmail-connector.ts
76
+ var GoogleGmailConnector = class {
77
+ id = "google-gmail";
78
+ meta = {
79
+ displayName: "Google Gmail",
80
+ provider: "google",
81
+ dataType: "email"
82
+ };
83
+ tokenLoader;
84
+ tokenSaver;
85
+ client = null;
86
+ config = null;
87
+ tokens = null;
88
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
89
+ gmail = null;
90
+ constructor(opts = {}) {
91
+ this.tokenLoader = opts.tokenLoader;
92
+ this.tokenSaver = opts.tokenSaver;
93
+ }
94
+ // ── Lifecycle ──────────────────────────────────────────────────
95
+ async connect(config) {
96
+ this.config = config;
97
+ const scopes = config.scopes ?? [
98
+ "https://www.googleapis.com/auth/gmail.readonly"
99
+ ];
100
+ if (config.serviceAccount) {
101
+ this.client = await createServiceAccountClient(config.serviceAccount, scopes);
102
+ } else if (config.oauth) {
103
+ this.client = await createOAuth2Client(config.oauth);
104
+ if (!this.tokenLoader) {
105
+ throw new Error("tokenLoader required for OAuth2 flow");
106
+ }
107
+ this.tokens = await loadTokens(this.tokenLoader, config.account);
108
+ if (!this.tokens) {
109
+ throw new Error(
110
+ `No stored tokens for account ${config.account}. Complete the OAuth flow first.`
111
+ );
112
+ }
113
+ this.tokens = await refreshIfNeeded(
114
+ this.client,
115
+ this.tokens,
116
+ this.tokenSaver ? async (t) => saveTokens(this.tokenSaver, config.account, t) : void 0
117
+ );
118
+ this.client.setCredentials(this.tokens);
119
+ } else {
120
+ throw new Error("Either serviceAccount or oauth config is required");
121
+ }
122
+ const { google } = await import("googleapis");
123
+ this.gmail = google.gmail({ version: "v1", auth: this.client });
124
+ }
125
+ async disconnect() {
126
+ this.client = null;
127
+ this.gmail = null;
128
+ this.tokens = null;
129
+ this.config = null;
130
+ }
131
+ async healthCheck() {
132
+ try {
133
+ this.ensureConnected();
134
+ const res = await this.gmail.users.getProfile({ userId: "me" });
135
+ return { ok: true, account: res.data.emailAddress };
136
+ } catch (err) {
137
+ return { ok: false, error: errorMessage(err) };
138
+ }
139
+ }
140
+ // ── Auth ───────────────────────────────────────────────────────
141
+ async authenticate(codeProvider) {
142
+ if (!this.config) {
143
+ return { success: false, error: "Call connect() first to set config, or pass config and call authenticate() before connect()." };
144
+ }
145
+ try {
146
+ if (!this.config.oauth) {
147
+ return { success: false, error: "OAuth config required for browser-based authenticate(). Use serviceAccount for headless auth." };
148
+ }
149
+ if (!this.tokenSaver) {
150
+ return { success: false, error: "tokenSaver required for authenticate() flow." };
151
+ }
152
+ const client = await createOAuth2Client(this.config.oauth);
153
+ const scopes = this.config.scopes ?? [
154
+ "https://www.googleapis.com/auth/gmail.readonly",
155
+ "https://www.googleapis.com/auth/gmail.send"
156
+ ];
157
+ const authUrl = getAuthUrl(client, scopes);
158
+ const code = await codeProvider(authUrl);
159
+ const tokens = await exchangeCode(client, code);
160
+ await saveTokens(this.tokenSaver, this.config.account, tokens);
161
+ this.tokens = tokens;
162
+ this.client = client;
163
+ this.client.setCredentials(tokens);
164
+ const { google } = await import("googleapis");
165
+ this.gmail = google.gmail({ version: "v1", auth: this.client });
166
+ return { success: true, account: this.config.account };
167
+ } catch (err) {
168
+ return { success: false, error: errorMessage(err) };
169
+ }
170
+ }
171
+ // ── Sync ───────────────────────────────────────────────────────
172
+ async sync(options) {
173
+ this.ensureConnected();
174
+ if (options?.cursor) {
175
+ return this.syncIncremental(options.cursor, options.limit);
176
+ }
177
+ return this.syncFull(options);
178
+ }
179
+ /** Incremental sync using Gmail history API. */
180
+ async syncIncremental(startHistoryId, limit) {
181
+ const records = [];
182
+ const errors = [];
183
+ const seenIds = /* @__PURE__ */ new Set();
184
+ let pageToken;
185
+ let latestHistoryId = startHistoryId;
186
+ do {
187
+ const res = await this.gmail.users.history.list({
188
+ userId: "me",
189
+ startHistoryId,
190
+ historyTypes: ["messageAdded"],
191
+ ...pageToken ? { pageToken } : {}
192
+ });
193
+ latestHistoryId = res.data.historyId ?? latestHistoryId;
194
+ const histories = res.data.history ?? [];
195
+ for (const h of histories) {
196
+ for (const added of h.messagesAdded ?? []) {
197
+ const msgId = added.message?.id;
198
+ if (!msgId || seenIds.has(msgId)) continue;
199
+ seenIds.add(msgId);
200
+ try {
201
+ const record = await this.fetchMessage(msgId);
202
+ records.push(record);
203
+ } catch (err) {
204
+ errors.push({ id: msgId, error: errorMessage(err) });
205
+ }
206
+ if (limit && records.length >= limit) {
207
+ return { records, cursor: latestHistoryId, hasMore: true, errors };
208
+ }
209
+ }
210
+ }
211
+ pageToken = res.data.nextPageToken ?? void 0;
212
+ } while (pageToken);
213
+ return { records, cursor: latestHistoryId, hasMore: false, errors };
214
+ }
215
+ /** Full sync — list messages and fetch each one. */
216
+ async syncFull(options) {
217
+ const records = [];
218
+ const errors = [];
219
+ const maxResults = options?.limit ?? 100;
220
+ let query = "";
221
+ if (options?.since) {
222
+ const epoch = Math.floor(new Date(options.since).getTime() / 1e3);
223
+ query = `after:${epoch}`;
224
+ }
225
+ if (options?.filters?.q) {
226
+ query = query ? `${query} ${options.filters.q}` : String(options.filters.q);
227
+ }
228
+ let pageToken;
229
+ let collected = 0;
230
+ do {
231
+ const res = await this.gmail.users.messages.list({
232
+ userId: "me",
233
+ maxResults: Math.min(maxResults - collected, 100),
234
+ ...query ? { q: query } : {},
235
+ ...pageToken ? { pageToken } : {}
236
+ });
237
+ const messages = res.data.messages ?? [];
238
+ for (const msg of messages) {
239
+ try {
240
+ const record = await this.fetchMessage(msg.id);
241
+ records.push(record);
242
+ } catch (err) {
243
+ errors.push({ id: msg.id, error: errorMessage(err) });
244
+ }
245
+ collected++;
246
+ if (collected >= maxResults) break;
247
+ }
248
+ pageToken = res.data.nextPageToken ?? void 0;
249
+ } while (pageToken && collected < maxResults);
250
+ const profile = await this.gmail.users.getProfile({ userId: "me" });
251
+ const cursor = profile.data.historyId ?? void 0;
252
+ return {
253
+ records,
254
+ cursor,
255
+ hasMore: !!pageToken,
256
+ errors
257
+ };
258
+ }
259
+ // ── Push (send email) ─────────────────────────────────────────
260
+ async push(payload) {
261
+ this.ensureConnected();
262
+ try {
263
+ const toHeader = payload.to.map(formatAddress).join(", ");
264
+ const ccHeader = payload.cc.length ? `Cc: ${payload.cc.map(formatAddress).join(", ")}\r
265
+ ` : "";
266
+ const bccHeader = payload.bcc.length ? `Bcc: ${payload.bcc.map(formatAddress).join(", ")}\r
267
+ ` : "";
268
+ const mime = [
269
+ `To: ${toHeader}\r
270
+ `,
271
+ ccHeader,
272
+ bccHeader,
273
+ `Subject: ${payload.subject}\r
274
+ `,
275
+ `Content-Type: text/plain; charset="UTF-8"\r
276
+ `,
277
+ `\r
278
+ `,
279
+ payload.body ?? ""
280
+ ].join("");
281
+ const encoded = Buffer.from(mime).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
282
+ const res = await this.gmail.users.messages.send({
283
+ userId: "me",
284
+ requestBody: { raw: encoded }
285
+ });
286
+ return { success: true, externalId: res.data.id };
287
+ } catch (err) {
288
+ return { success: false, error: errorMessage(err) };
289
+ }
290
+ }
291
+ // ── Internals ─────────────────────────────────────────────────
292
+ ensureConnected() {
293
+ if (!this.gmail || !this.config) {
294
+ throw new Error("GoogleGmailConnector is not connected. Call connect() first.");
295
+ }
296
+ }
297
+ /** Fetch a single message by ID and parse into an EmailRecord. */
298
+ async fetchMessage(messageId) {
299
+ const res = await this.gmail.users.messages.get({
300
+ userId: "me",
301
+ id: messageId,
302
+ format: "full"
303
+ });
304
+ const msg = res.data;
305
+ const headers = msg.payload?.headers ?? [];
306
+ const getHeader = (name) => headers.find((h) => h.name.toLowerCase() === name.toLowerCase())?.value ?? "";
307
+ return {
308
+ gmailId: msg.id,
309
+ threadId: msg.threadId,
310
+ account: this.config.account,
311
+ subject: getHeader("Subject"),
312
+ from: parseAddress(getHeader("From")),
313
+ to: parseAddressList(getHeader("To")),
314
+ cc: parseAddressList(getHeader("Cc")),
315
+ bcc: parseAddressList(getHeader("Bcc")),
316
+ date: new Date(getHeader("Date")).toISOString(),
317
+ snippet: msg.snippet ?? "",
318
+ body: extractPlainTextBody(msg.payload),
319
+ labels: msg.labelIds ?? [],
320
+ isRead: !(msg.labelIds ?? []).includes("UNREAD")
321
+ };
322
+ }
323
+ };
324
+ function extractPlainTextBody(payload) {
325
+ if (!payload) return void 0;
326
+ if (payload.mimeType === "text/plain" && payload.body?.data) {
327
+ return decodeBase64Url(payload.body.data);
328
+ }
329
+ if (payload.parts) {
330
+ for (const part of payload.parts) {
331
+ if (part.mimeType === "text/plain" && part.body?.data) {
332
+ return decodeBase64Url(part.body.data);
333
+ }
334
+ }
335
+ for (const part of payload.parts) {
336
+ if (part.mimeType?.startsWith("multipart/")) {
337
+ const result = extractPlainTextBody(part);
338
+ if (result) return result;
339
+ }
340
+ }
341
+ }
342
+ return void 0;
343
+ }
344
+ function decodeBase64Url(data) {
345
+ const base64 = data.replace(/-/g, "+").replace(/_/g, "/");
346
+ return Buffer.from(base64, "base64").toString("utf-8");
347
+ }
348
+ function parseAddress(raw) {
349
+ const match = raw.match(/^(.+?)\s*<([^>]+)>$/);
350
+ if (match) {
351
+ return { name: match[1].replace(/^["']|["']$/g, "").trim(), email: match[2] };
352
+ }
353
+ return { email: raw.trim() };
354
+ }
355
+ function parseAddressList(raw) {
356
+ if (!raw.trim()) return [];
357
+ const results = [];
358
+ let current = "";
359
+ let depth = 0;
360
+ for (const ch of raw) {
361
+ if (ch === "<") depth++;
362
+ else if (ch === ">") depth--;
363
+ else if (ch === "," && depth === 0) {
364
+ if (current.trim()) results.push(parseAddress(current.trim()));
365
+ current = "";
366
+ continue;
367
+ }
368
+ current += ch;
369
+ }
370
+ if (current.trim()) results.push(parseAddress(current.trim()));
371
+ return results;
372
+ }
373
+ function formatAddress(addr) {
374
+ return addr.name ? `${addr.name} <${addr.email}>` : addr.email;
375
+ }
376
+ function errorMessage(err) {
377
+ return err instanceof Error ? err.message : String(err);
378
+ }
379
+
380
+ export {
381
+ createOAuth2Client,
382
+ getAuthUrl,
383
+ exchangeCode,
384
+ createServiceAccountClient,
385
+ loadTokens,
386
+ saveTokens,
387
+ refreshIfNeeded,
388
+ GoogleGmailConnector
389
+ };
package/dist/cli.js CHANGED
File without changes
@@ -0,0 +1,79 @@
1
+ /** Connector types — generic external service integrations. */
2
+ interface ConnectorMeta {
3
+ displayName: string;
4
+ /** Provider identifier, e.g. "google", "trello", "jira", "salesforce" */
5
+ provider: string;
6
+ /** Data type this connector handles, e.g. "email", "calendar", "board", "crm" */
7
+ dataType: string;
8
+ }
9
+ interface SyncOptions {
10
+ /** Only sync records after this ISO 8601 timestamp */
11
+ since?: string;
12
+ /** Provider-specific incremental sync token */
13
+ cursor?: string;
14
+ /** Maximum number of records to fetch */
15
+ limit?: number;
16
+ /** Provider-specific query filters */
17
+ filters?: Record<string, unknown>;
18
+ }
19
+ interface SyncResult<T = Record<string, unknown>> {
20
+ /** Typed records produced by the connector — consumer decides where to store */
21
+ records: T[];
22
+ /** Next incremental sync token (persist for future calls) */
23
+ cursor?: string;
24
+ /** Whether more records are available (pagination) */
25
+ hasMore: boolean;
26
+ /** Errors encountered during sync (non-fatal per-record failures) */
27
+ errors: Array<{
28
+ id?: string;
29
+ error: string;
30
+ }>;
31
+ }
32
+ interface PushResult {
33
+ success: boolean;
34
+ externalId?: string;
35
+ error?: string;
36
+ }
37
+ interface AuthResult {
38
+ success: boolean;
39
+ account?: string;
40
+ /** URL the user must visit to authorize (for OAuth flows) */
41
+ authUrl?: string;
42
+ error?: string;
43
+ }
44
+ type ConnectorConfig = Record<string, unknown>;
45
+ /**
46
+ * Generic connector interface for external service integrations.
47
+ *
48
+ * Connectors pull and optionally push data to/from external services
49
+ * (Gmail, Calendar, Trello, Jira, Salesforce, etc.). They produce
50
+ * typed records — the consuming application decides where to store them.
51
+ *
52
+ * @typeParam T - The record type this connector produces/consumes.
53
+ */
54
+ interface Connector<T = Record<string, unknown>> {
55
+ readonly id: string;
56
+ readonly meta: ConnectorMeta;
57
+ connect(config: ConnectorConfig): Promise<void>;
58
+ disconnect(): Promise<void>;
59
+ healthCheck(): Promise<{
60
+ ok: boolean;
61
+ account?: string;
62
+ error?: string;
63
+ }>;
64
+ /** Pull records from external source */
65
+ sync(options?: SyncOptions): Promise<SyncResult<T>>;
66
+ /** Push a record to external source (optional) */
67
+ push?(payload: T): Promise<PushResult>;
68
+ /**
69
+ * Run the authentication/authorization flow for this connector.
70
+ * For OAuth connectors, this generates the auth URL and exchanges the code for tokens.
71
+ *
72
+ * @param codeProvider - called with the auth URL; must return the authorization code.
73
+ * For CLI flows, this prints the URL and reads from stdin.
74
+ * For programmatic flows, the caller handles the redirect.
75
+ */
76
+ authenticate?(codeProvider: (authUrl: string) => Promise<string>): Promise<AuthResult>;
77
+ }
78
+
79
+ export type { AuthResult as A, ConnectorConfig as C, PushResult as P, SyncOptions as S, Connector as a, ConnectorMeta as b, SyncResult as c };
@@ -117,6 +117,27 @@ export interface ChatPipelineV2Config {
117
117
  messageText: string;
118
118
  channel: string;
119
119
  }) => Promise<ContextFile[]> | ContextFile[];
120
+ /**
121
+ * Optional per-turn tool-context resolver. Called once per inbound message
122
+ * with the resolved conversation coordinates (the same shape passed to
123
+ * `resolveContextFiles`). The returned fields are merged into the
124
+ * `ToolContext` handed to every tool handler for that turn — letting an app
125
+ * thread per-turn identity (e.g. which user the primary agent is acting on
126
+ * behalf of) into tool execution, which the static config cannot express.
127
+ *
128
+ * The base `ToolContext` fields (`taskId`, `agentId`, `hooks`, `db`,
129
+ * `resolveFilePath`) are applied first and cannot be overridden by the
130
+ * resolver — returned keys that collide with them are ignored. If the
131
+ * resolver throws, the error propagates to the turn's try/catch and fails
132
+ * loudly; there is no silent fallback.
133
+ */
134
+ resolveToolContext?: (ctx: {
135
+ channelId: string;
136
+ threadId: string;
137
+ userId?: string;
138
+ messageText: string;
139
+ channel: string;
140
+ }) => Promise<Record<string, unknown>> | Record<string, unknown>;
120
141
  }
121
142
  export declare class ChatPipelineV2 {
122
143
  private db;
@@ -0,0 +1,7 @@
1
+ import {
2
+ GoogleGmailConnector
3
+ } from "./chunk-XYF5PSB2.js";
4
+ import "./chunk-3RG5ZIWI.js";
5
+ export {
6
+ GoogleGmailConnector
7
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ enrichVoiceMessage,
3
+ extractVoiceTranscript,
4
+ parseSlackEvent
5
+ } from "./chunk-OEMM2LEA.js";
6
+ import "./chunk-3RG5ZIWI.js";
7
+ export {
8
+ enrichVoiceMessage,
9
+ extractVoiceTranscript,
10
+ parseSlackEvent
11
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ enrichVoiceMessage,
3
+ extractVoiceTranscript,
4
+ parseSlackEvent
5
+ } from "./chunk-NNPCKR6G.js";
6
+ import "./chunk-3RG5ZIWI.js";
7
+ export {
8
+ enrichVoiceMessage,
9
+ extractVoiceTranscript,
10
+ parseSlackEvent
11
+ };
@@ -0,0 +1,11 @@
1
+ import {
2
+ enrichVoiceMessage,
3
+ extractVoiceTranscript,
4
+ parseSlackEvent
5
+ } from "./chunk-QBBROFEL.js";
6
+ import "./chunk-3RG5ZIWI.js";
7
+ export {
8
+ enrichVoiceMessage,
9
+ extractVoiceTranscript,
10
+ parseSlackEvent
11
+ };
package/dist/index.js CHANGED
@@ -2345,13 +2345,24 @@ ${ctx2}`;
2345
2345
 
2346
2346
  ${contextFilesBlock}`;
2347
2347
  }
2348
+ let toolContextExtra = {};
2349
+ if (this.config.resolveToolContext) {
2350
+ toolContextExtra = await this.config.resolveToolContext({
2351
+ channelId,
2352
+ threadId: threadTs,
2353
+ userId: msg.from,
2354
+ messageText: msg.body,
2355
+ channel: this.channel
2356
+ }) ?? {};
2357
+ }
2348
2358
  const { text, tasksDispatched } = await this.think(
2349
2359
  systemPrompt,
2350
2360
  history,
2351
2361
  msg.body,
2352
2362
  threadTs,
2353
2363
  channelId,
2354
- msg.attachmentBlocks
2364
+ msg.attachmentBlocks,
2365
+ toolContextExtra
2355
2366
  );
2356
2367
  await this.hooks.emit("typing.stop", { channel: this.channel, threadId: threadTs });
2357
2368
  if (text) {
@@ -2399,7 +2410,7 @@ ${contextFilesBlock}`;
2399
2410
  /**
2400
2411
  * Primary agent tool loop — adapted from ExecutionEngine pattern.
2401
2412
  */
2402
- async think(systemPrompt, history, currentMessage, threadTs, channelId, attachmentBlocks) {
2413
+ async think(systemPrompt, history, currentMessage, threadTs, channelId, attachmentBlocks, toolContextExtra) {
2403
2414
  const model = this.config.model ?? "claude-sonnet-4-6";
2404
2415
  const maxIterations = this.config.maxIterations ?? DEFAULT_MAX_ITERATIONS;
2405
2416
  const maxTokens = this.config.maxTokens ?? DEFAULT_MAX_TOKENS;
@@ -2432,6 +2443,9 @@ ${contextFilesBlock}`;
2432
2443
  if (handler) {
2433
2444
  try {
2434
2445
  const toolCtx = {
2446
+ // Per-turn extras first; base fields applied last so the
2447
+ // resolver can never override taskId/agentId/hooks/db.
2448
+ ...toolContextExtra,
2435
2449
  taskId: "",
2436
2450
  agentId: "primary",
2437
2451
  hooks: this.hooks,
@@ -0,0 +1,75 @@
1
+ /** LLM provider types — Story 1.5 / 2.1 */
2
+ interface ToolDefinition {
3
+ name: string;
4
+ description: string;
5
+ parameters: Record<string, unknown>;
6
+ }
7
+ interface ChatMessage {
8
+ role: "user" | "assistant" | "system";
9
+ content: string | ContentBlock[];
10
+ }
11
+ type ContentBlock = {
12
+ type: "text";
13
+ text: string;
14
+ } | {
15
+ type: "tool_use";
16
+ id: string;
17
+ name: string;
18
+ input: unknown;
19
+ } | {
20
+ type: "tool_result";
21
+ tool_use_id: string;
22
+ content: string;
23
+ };
24
+ interface ChatParams {
25
+ messages: ChatMessage[];
26
+ system?: string;
27
+ tools?: ToolDefinition[];
28
+ maxTokens?: number;
29
+ temperature?: number;
30
+ model: string;
31
+ abortSignal?: AbortSignal;
32
+ }
33
+ interface TokenUsage {
34
+ inputTokens: number;
35
+ outputTokens: number;
36
+ cacheReadTokens?: number;
37
+ cacheWriteTokens?: number;
38
+ }
39
+ interface ChatResult {
40
+ content: string;
41
+ toolUses?: ToolUse[];
42
+ usage: TokenUsage;
43
+ model: string;
44
+ stopReason: "end_turn" | "tool_use" | "max_tokens" | "stop_sequence";
45
+ }
46
+ interface ToolUse {
47
+ id: string;
48
+ name: string;
49
+ input: unknown;
50
+ }
51
+ interface ModelInfo {
52
+ id: string;
53
+ displayName: string;
54
+ contextWindow: number;
55
+ maxOutputTokens: number;
56
+ capabilities: Array<"chat" | "tools" | "vision" | "streaming">;
57
+ /** Cost in micro-cents per 1M tokens */
58
+ inputCostPerMToken?: number;
59
+ outputCostPerMToken?: number;
60
+ }
61
+ interface ResolvedModel {
62
+ provider: string;
63
+ model: string;
64
+ }
65
+ interface LLMProvider {
66
+ id: string;
67
+ displayName: string;
68
+ models: ModelInfo[];
69
+ chat(params: ChatParams): Promise<ChatResult>;
70
+ chatStream(params: ChatParams): AsyncGenerator<string, ChatResult, unknown>;
71
+ /** Convert ToolDefinition[] to provider-native format */
72
+ serializeTools(tools: ToolDefinition[]): unknown;
73
+ }
74
+
75
+ export type { ChatMessage as C, LLMProvider as L, ModelInfo as M, ResolvedModel as R, TokenUsage as T, ChatParams as a, ChatResult as b, ContentBlock as c, ToolUse as d, ToolDefinition as e };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "botinabox",
3
- "version": "2.16.15",
3
+ "version": "2.16.17",
4
4
  "description": "Bot in a Box — framework for building multi-agent bots",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",