@meetopenbot/openbot 0.2.6 → 1.0.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/runtime.js CHANGED
@@ -1,518 +1,413 @@
1
- import { generateText } from 'ai';
1
+ import { streamText, stepCountIs } from 'ai';
2
2
  import { eventsToModelMessages } from './history.js';
3
3
  import { buildContext } from './context.js';
4
4
  import { OPENBOT_SYSTEM_PROMPT } from './system-prompt.js';
5
5
  import { isAuthErrorMessage, isCreditsErrorMessage } from '@meetopenbot/plugin-sdk';
6
- import { AUTO_MODEL_ID, isAutoModel, isRetryableModelError, listAutoModelCandidates, } from './auto-model.js';
7
- import { resolveModel } from './model.js';
6
+ import { AUTO_MODEL_ID, isAutoModel, isRetryableModelError, listAutoModelCandidates, missingByokApiKeyMessage, } from './auto-model.js';
7
+ import { includeReasoningInHistory, reasoningForModel, resolveModel } from './model.js';
8
8
  import { fetchModelRegistry, getProviderModelOptions, listApiKeyProviders, PROVIDER_API_KEY_LINKS, } from '@meetopenbot/plugin-sdk';
9
+ import { errorFromStreamPart } from './stream-error.js';
10
+ import { createAgentOutputBuffer, isOutputBoundaryPart } from './output-buffer.js';
9
11
  async function buildSystemPrompt(state, storage) {
10
12
  const context = await buildContext(state, storage);
11
13
  const sections = [OPENBOT_SYSTEM_PROMPT, '', context];
12
- // Hardcoded naming hint logic
13
14
  const threadState = state.threadDetails?.state;
14
15
  if (!threadState?.isSmartNamed) {
15
- sections.push('', '## SYSTEM HINT', 'This thread is unnamed. Please use the `patch_thread_details` tool to set a concise, descriptive, and regular `name` (e.g., "Project Brainstorming" instead of "project-brainstorm") in the thread state and set `isSmartNamed: true` in the same patch. Only do this once.');
16
+ sections.push('', '## SYSTEM HINT', 'This thread is unnamed. Please use the `set_thread_title` tool to set a concise, descriptive title (e.g., "Project Brainstorming" instead of "project-brainstorm"). Only do this once.');
16
17
  }
17
18
  return sections.join('\n');
18
19
  }
19
- /**
20
- * Tracks tool-call IDs from one LLM turn until matching `:result` events arrive.
21
- *
22
- * Melony runs yielded `action:*` events depth-first, so parallel tool calls from
23
- * a single `generateText` response execute one-by-one. We must wait for every ID
24
- * in the batch before calling the LLM again — not after the first result.
25
- */
26
- function createToolBatchTracker(state, storage, channelId, threadId) {
27
- const save = async (ids) => {
28
- if (!storage || !channelId || !threadId)
29
- return;
30
- try {
31
- await storage.patchThreadState({
32
- channelId,
33
- threadId,
34
- state: { pendingToolCallIds: ids },
35
- });
36
- }
37
- catch (error) {
38
- console.error('[openbot] Failed to persist pendingToolCallIds:', error);
39
- }
40
- };
41
- return {
42
- async startBatch(toolCallIds) {
43
- state.pendingToolCallIds = [...toolCallIds];
44
- await save(state.pendingToolCallIds);
45
- },
46
- async clear() {
47
- state.pendingToolCallIds = undefined;
48
- await save(undefined);
49
- },
50
- /** Returns true when this result completes the batch (time to call the LLM again). */
51
- async recordResult(toolCallId) {
52
- if (!state.pendingToolCallIds?.includes(toolCallId))
53
- return false;
54
- state.pendingToolCallIds = state.pendingToolCallIds.filter((id) => id !== toolCallId);
55
- const done = state.pendingToolCallIds.length === 0;
56
- if (done) {
57
- state.pendingToolCallIds = undefined;
58
- }
59
- await save(state.pendingToolCallIds);
60
- return done;
61
- },
62
- };
20
+ function toAiTools(tools, args, flushPendingOutput) {
21
+ const mapped = {};
22
+ for (const [name, def] of Object.entries(tools)) {
23
+ if (!def.execute)
24
+ continue;
25
+ mapped[name] = {
26
+ description: def.description,
27
+ inputSchema: def.inputSchema,
28
+ execute: async (input, { toolCallId }) => {
29
+ await flushPendingOutput();
30
+ await args.emit({
31
+ type: `action:${name}`,
32
+ data: input,
33
+ meta: {
34
+ toolCallId,
35
+ agentId: args.context.agentId,
36
+ threadId: args.threadId,
37
+ },
38
+ });
39
+ try {
40
+ const result = await def.execute(input, {
41
+ agentId: args.context.agentId,
42
+ channelId: args.state.channelId,
43
+ threadId: args.threadId,
44
+ runId: args.state.runId,
45
+ toolCallId,
46
+ abortSignal: args.context.abortSignal,
47
+ storage: args.context.storage,
48
+ host: args.context.host,
49
+ publicBaseUrl: args.context.publicBaseUrl,
50
+ config: args.context.config,
51
+ state: args.state,
52
+ emit: args.emit,
53
+ });
54
+ const data = typeof result === 'string'
55
+ ? { success: true, output: result }
56
+ : { success: result.success !== false, ...result };
57
+ await args.emit({
58
+ type: `action:${name}:result`,
59
+ data,
60
+ meta: {
61
+ toolCallId,
62
+ agentId: args.context.agentId,
63
+ threadId: args.threadId,
64
+ },
65
+ });
66
+ return data.output ?? JSON.stringify(data);
67
+ }
68
+ catch (error) {
69
+ const message = error instanceof Error ? error.message : String(error);
70
+ await args.emit({
71
+ type: `action:${name}:result`,
72
+ data: { success: false, error: message, output: message },
73
+ meta: {
74
+ toolCallId,
75
+ agentId: args.context.agentId,
76
+ threadId: args.threadId,
77
+ },
78
+ });
79
+ return message;
80
+ }
81
+ },
82
+ };
83
+ }
84
+ return mapped;
63
85
  }
64
- /**
65
- * OpenBot agent runtime.
66
- *
67
- * - One `generateText` call per `runLLM` (tools have no `execute`; SDK stops at 1 step).
68
- * - Tool calls become `action:*` events; plugins emit `:result` when done.
69
- * - When a full batch of results is in, `runLLM` runs again with updated history.
70
- */
71
- export const openbotRuntime = (options) => (builder) => {
72
- const { model: modelString = AUTO_MODEL_ID, authMode = 'byok', agentId, storage, toolDefinitions = {}, abortSignal, host, } = options;
86
+ export async function* runOpenbotTurn(args, options) {
87
+ const { model: modelString = AUTO_MODEL_ID, authMode = 'byok', storage, toolDefinitions = {}, abortSignal, host, } = options;
73
88
  let configuredModelString = modelString;
74
89
  const isCreditsCloudAgent = (id) => host.isCloudSystemAgent(id ?? '') && authMode === 'credits';
75
- const runLLM = async function* (context, threadId, trigger) {
76
- if (!storage)
77
- return;
78
- if (abortSignal?.aborted)
79
- return;
80
- const toolBatch = createToolBatchTracker(context.state, storage, context.state.channelId, threadId || context.state.threadId);
81
- // Capture parent metadata for event enrichment
82
- const triggerEvent = trigger || context.state.triggerEvent;
83
- const parentAgentId = triggerEvent?.meta?.parentAgentId;
84
- const parentToolCallId = triggerEvent?.meta?.parentToolCallId;
85
- const state = context.state;
86
- state.model = configuredModelString;
87
- const systemPrompt = await buildSystemPrompt(context.state, storage);
88
- const events = await storage.getEvents({
89
- channelId: context.state.channelId,
90
- threadId: context.state.threadId,
91
- });
92
- const messages = eventsToModelMessages(events);
93
- const candidates = isAutoModel(configuredModelString)
94
- ? listAutoModelCandidates({ authMode })
95
- : [configuredModelString];
96
- try {
97
- // Single LLM request tool execution happens externally via action:* handlers.
98
- const generate = async () => {
99
- let lastError;
100
- for (let i = 0; i < candidates.length; i++) {
101
- try {
102
- return await generateText({
103
- model: resolveModel(candidates[i], { authMode }),
104
- system: systemPrompt,
105
- messages,
106
- tools: toolDefinitions,
107
- stopWhen: ({ steps }) => steps.length === 1,
108
- allowSystemInMessages: true,
109
- abortSignal,
110
- });
90
+ if (!storage || abortSignal?.aborted)
91
+ return;
92
+ const state = args.state;
93
+ state.model = configuredModelString;
94
+ const threadId = args.threadId || state.threadId;
95
+ const systemPrompt = await buildSystemPrompt(state, storage);
96
+ const events = await storage.getEvents({
97
+ channelId: state.channelId ?? '',
98
+ threadId,
99
+ });
100
+ const candidates = isAutoModel(configuredModelString)
101
+ ? listAutoModelCandidates({ authMode })
102
+ : [configuredModelString];
103
+ try {
104
+ const missingKey = missingByokApiKeyMessage(configuredModelString, { authMode });
105
+ if (missingKey)
106
+ throw new Error(missingKey);
107
+ let lastError;
108
+ let started = false;
109
+ for (let i = 0; i < candidates.length; i++) {
110
+ const candidate = candidates[i];
111
+ const output = createAgentOutputBuffer({ agentId: state.agentId, threadId });
112
+ const flushPendingOutput = async () => {
113
+ const event = output.take();
114
+ if (event)
115
+ await args.emit(event);
116
+ };
117
+ const tools = toAiTools(toolDefinitions, args, flushPendingOutput);
118
+ try {
119
+ const result = streamText({
120
+ model: resolveModel(candidate, { authMode }),
121
+ system: systemPrompt,
122
+ messages: eventsToModelMessages(events, {
123
+ includeReasoning: includeReasoningInHistory(candidate),
124
+ }),
125
+ tools,
126
+ abortSignal,
127
+ reasoning: reasoningForModel(candidate),
128
+ stopWhen: stepCountIs(20),
129
+ allowSystemInMessages: true,
130
+ });
131
+ for await (const part of result.fullStream) {
132
+ if (abortSignal?.aborted)
133
+ return;
134
+ const streamError = errorFromStreamPart(part);
135
+ if (streamError)
136
+ throw streamError;
137
+ if (part.type === 'text-delta' && part.text) {
138
+ output.addText(part.text);
139
+ yield {
140
+ type: 'agent:output:delta',
141
+ data: { content: part.text },
142
+ meta: { agentId: state.agentId, threadId },
143
+ };
111
144
  }
112
- catch (error) {
113
- lastError = error;
114
- if (abortSignal?.aborted)
115
- throw error;
116
- const errorMessage = error instanceof Error ? error.message : String(error);
117
- if (isCreditsErrorMessage(errorMessage) || isAuthErrorMessage(errorMessage)) {
118
- throw error;
119
- }
120
- if (!isRetryableModelError(error) || i === candidates.length - 1) {
121
- throw error;
122
- }
145
+ if (part.type === 'reasoning-delta' && 'text' in part && part.text) {
146
+ output.addReasoning(part.text);
147
+ yield {
148
+ type: 'agent:output:delta',
149
+ data: { reasoning: part.text },
150
+ meta: { agentId: state.agentId, threadId },
151
+ };
152
+ }
153
+ if (isOutputBoundaryPart(part.type)) {
154
+ const event = output.take();
155
+ if (event)
156
+ yield event;
123
157
  }
124
158
  }
125
- throw lastError ?? new Error('Model request failed.');
126
- };
127
- const result = await generate();
128
- const toolCalls = result.toolCalls ?? [];
129
- // if (result.usage) {
130
- // const usage = result.usage;
131
- // yield {
132
- // type: 'agent:usage',
133
- // data: {
134
- // usage: {
135
- // promptTokens: usage.inputTokens,
136
- // completionTokens: usage.outputTokens,
137
- // totalTokens: usage.totalTokens,
138
- // currentContextTokens: usage.inputTokens,
139
- // contextBudget: getContextBudgetForModel(currentModelString),
140
- // },
141
- // model: currentModelString,
142
- // },
143
- // meta: {
144
- // agentId: context.state.agentId,
145
- // threadId,
146
- // runId: context.state.runId,
147
- // },
148
- // } as OpenBotEvent;
149
- // }
150
- const outputMeta = {
151
- agentId: context.state.agentId,
152
- threadId,
153
- parentAgentId,
154
- parentToolCallId,
155
- };
156
- // Text before actions so history/UI show the model's intent first.
157
- if (result.text) {
158
- yield {
159
- type: 'agent:output',
160
- data: { content: result.text },
161
- meta: outputMeta,
162
- };
163
- }
164
- if (toolCalls.length > 0) {
165
- // when multiple tool calls are made, Melony runtime handles them one by one, thats why we need to start a new batch
166
- await toolBatch.startBatch(toolCalls.map((tc) => tc.toolCallId));
167
- for (const toolCall of toolCalls) {
168
- yield {
169
- type: `action:${toolCall.toolName}`,
170
- data: toolCall.input,
171
- meta: {
172
- toolCallId: toolCall.toolCallId,
173
- ...outputMeta,
174
- },
175
- };
176
- }
177
- }
178
- else {
179
- // clear the tool batch if there are no tool calls
180
- await toolBatch.clear();
159
+ const leftover = output.take();
160
+ if (leftover)
161
+ yield leftover;
162
+ started = true;
163
+ lastError = undefined;
164
+ break;
181
165
  }
182
- }
183
- catch (error) {
184
- // Run was stopped — unwind quietly without surfacing an error.
185
- if (abortSignal?.aborted)
186
- return;
187
- const errorMessage = error instanceof Error ? error.message : String(error);
188
- if (isCreditsCloudAgent(context.state.agentId)) {
189
- if (isCreditsErrorMessage(errorMessage)) {
190
- yield {
191
- type: 'agent:output',
192
- data: {
193
- content: 'Insufficient workspace credits. Add credits in workspace settings or switch this agent to BYOK mode.',
194
- },
195
- meta: { agentId: context.state.agentId, threadId },
196
- };
166
+ catch (error) {
167
+ lastError = error;
168
+ if (abortSignal?.aborted)
197
169
  return;
170
+ const errorMessage = error instanceof Error ? error.message : String(error);
171
+ if (isCreditsErrorMessage(errorMessage) || isAuthErrorMessage(errorMessage)) {
172
+ throw error;
198
173
  }
199
- if (isAuthErrorMessage(errorMessage)) {
200
- yield {
201
- type: 'agent:output',
202
- data: {
203
- content: 'Could not authenticate via OpenBot Credits. Check your workspace credit balance in settings, or switch this agent to BYOK mode.',
204
- },
205
- meta: { agentId: context.state.agentId, threadId },
206
- };
207
- return;
174
+ if (!isRetryableModelError(error) || i === candidates.length - 1) {
175
+ throw error;
208
176
  }
209
177
  }
210
- if (isAuthErrorMessage(errorMessage) && !isCreditsCloudAgent(context.state.agentId)) {
211
- const registry = await fetchModelRegistry();
212
- const providerActions = listApiKeyProviders(registry).map((provider) => ({
213
- id: provider.id,
214
- label: provider.label,
215
- variant: 'primary',
216
- }));
178
+ }
179
+ if (!started && lastError)
180
+ throw lastError;
181
+ }
182
+ catch (error) {
183
+ if (abortSignal?.aborted)
184
+ return;
185
+ const errorMessage = error instanceof Error ? error.message : String(error);
186
+ if (isCreditsCloudAgent(state.agentId)) {
187
+ if (isCreditsErrorMessage(errorMessage)) {
217
188
  yield {
218
- type: 'client:ui:widget',
189
+ type: 'agent:output',
219
190
  data: {
220
- kind: 'choice',
221
- widgetId: `api_provider_selection_${Date.now()}`,
222
- title: `Setup AI Provider`,
223
- description: `Select a provider to continue.`,
224
- actions: providerActions,
225
- metadata: {
226
- type: 'api_provider_selection',
227
- },
191
+ content: 'Insufficient workspace credits. Add credits in workspace settings or switch this agent to BYOK mode.',
228
192
  },
229
- meta: { agentId: context.state.agentId, threadId },
193
+ meta: { agentId: state.agentId, threadId },
230
194
  };
231
195
  return;
232
196
  }
233
- throw error;
234
- }
235
- };
236
- builder.on('agent:invoke', async function* (event, context) {
237
- const routedTo = event.data?.agentId;
238
- if (typeof routedTo === 'string' && routedTo && routedTo !== context.state.agentId) {
239
- return;
240
- }
241
- // Capture user info from meta if available
242
- if (event.meta?.userName) {
243
- context.state.currentUser = {
244
- userName: event.meta.userName,
245
- };
246
- }
247
- const threadId = event.meta?.threadId || context.state.threadId;
248
- // clear the tool batch if the agent is invoked
249
- // this is to prevent the tool batch from being used for a new agent invocation
250
- await createToolBatchTracker(context.state, storage, context.state.channelId, threadId).clear();
251
- yield* runLLM(context, threadId, event);
252
- });
253
- // this is to handle the tool results from the tool calls
254
- // because Melony runtime handles them one by one, thats why we need to record the result
255
- builder.on('*', async function* (event, context) {
256
- if (!event.type.endsWith(':result'))
257
- return;
258
- if (event.meta?.agentId !== context.state.agentId)
259
- return;
260
- const toolCallId = event.meta?.toolCallId;
261
- // record the result of the tool call
262
- if (!toolCallId ||
263
- !(await createToolBatchTracker(context.state, storage, context.state.channelId, event.meta?.threadId || context.state.threadId).recordResult(toolCallId)))
264
- return;
265
- const threadId = event.meta?.threadId || context.state.threadId;
266
- yield* runLLM(context, threadId);
267
- });
268
- builder.on('client:ui:widget:response', async function* (event, context) {
269
- const { metadata, values, actionId } = event.data;
270
- const threadId = event.meta?.threadId || context.state.threadId;
271
- if (isCreditsCloudAgent(context.state.agentId))
272
- return;
273
- if (metadata?.type === 'api_provider_selection') {
274
- const provider = actionId;
275
- const configuredModelId = isAutoModel(configuredModelString)
276
- ? ''
277
- : configuredModelString.split('/').slice(1).join('/');
278
- const registry = await fetchModelRegistry();
279
- const providerData = registry?.providers?.[provider];
280
- const label = providerData?.label || provider;
281
- const link = PROVIDER_API_KEY_LINKS[provider] || '';
282
- const modelOptions = getProviderModelOptions(registry, provider);
283
- yield {
284
- type: 'client:ui:widget',
285
- data: {
286
- widgetId: event.data.widgetId,
287
- kind: 'message',
288
- title: 'Provider Selected',
289
- body: `${label} provider was selected.`,
290
- state: 'submitted',
291
- display: 'collapsed',
292
- disabled: true,
293
- actions: [],
294
- },
295
- meta: { agentId: context.state.agentId, threadId },
296
- };
297
- if (modelOptions && modelOptions.length > 0 && !isAutoModel(configuredModelString)) {
298
- const defaultModelId = modelOptions.find((m) => m.value === configuredModelId)?.value || modelOptions[0].value;
197
+ if (isAuthErrorMessage(errorMessage)) {
299
198
  yield {
300
- type: 'client:ui:widget',
199
+ type: 'agent:output',
301
200
  data: {
302
- kind: 'choice',
303
- widgetId: `api_model_selection_${Date.now()}`,
304
- title: 'Select Model',
305
- description: `Choose a ${label} model.`,
306
- actions: modelOptions.map((option) => ({
307
- id: option.value,
308
- label: option.label,
309
- variant: option.value === defaultModelId ? 'primary' : 'secondary',
310
- })),
311
- metadata: {
312
- type: 'api_model_selection',
313
- provider,
314
- },
201
+ content: 'Could not authenticate via OpenBot Credits. Check your workspace credit balance in settings, or switch this agent to BYOK mode.',
315
202
  },
316
- meta: { agentId: context.state.agentId, threadId },
203
+ meta: { agentId: state.agentId, threadId },
317
204
  };
318
205
  return;
319
206
  }
320
- yield {
321
- type: 'client:ui:widget',
322
- data: {
323
- kind: 'form',
324
- widgetId: `api_key_request_${Date.now()}`,
325
- title: `${label} Setup`,
326
- description: isAutoModel(configuredModelString)
327
- ? `Enter your API key to continue.`
328
- : `Enter your API key and model ID.`,
329
- fields: [
330
- ...(isAutoModel(configuredModelString)
331
- ? []
332
- : [
333
- {
334
- id: 'model',
335
- label: 'Model',
336
- type: 'text',
337
- description: 'Enter the model ID for this provider.',
338
- placeholder: provider === 'openai'
339
- ? 'gpt-4o-mini'
340
- : provider === 'anthropic'
341
- ? 'claude-3-5-sonnet-20241022'
342
- : provider === 'deepseek'
343
- ? 'deepseek-chat'
344
- : 'gemini-2.0-flash',
345
- required: true,
346
- defaultValue: configuredModelId || '',
347
- },
348
- ]),
349
- {
350
- id: 'apiKey',
351
- label: 'API Key',
352
- type: 'password',
353
- description: `Get your key here: [${link}](${link})`,
354
- placeholder: `sk-...`,
355
- required: true,
356
- },
357
- ],
358
- submitLabel: 'Save & Continue',
359
- metadata: {
360
- type: 'api_key_request',
361
- provider,
362
- },
363
- },
364
- meta: { agentId: context.state.agentId, threadId },
365
- };
366
- return;
367
207
  }
368
- if (metadata?.type === 'api_model_selection') {
369
- const provider = String(metadata.provider);
370
- const modelId = String(actionId).trim();
208
+ if (isAuthErrorMessage(errorMessage) && !isCreditsCloudAgent(state.agentId)) {
371
209
  const registry = await fetchModelRegistry();
372
- const providerData = registry?.providers?.[provider];
373
- const label = providerData?.label || provider;
374
- const modelLabel = providerData?.models.find((model) => model.id === modelId)?.label || modelId;
375
- const link = PROVIDER_API_KEY_LINKS[provider] || '';
210
+ const providerActions = listApiKeyProviders(registry).map((provider) => ({
211
+ id: provider.id,
212
+ label: provider.label,
213
+ variant: 'primary',
214
+ }));
376
215
  yield {
377
216
  type: 'client:ui:widget',
378
217
  data: {
379
- widgetId: event.data.widgetId,
380
- kind: 'message',
381
- title: 'Model Selected',
382
- body: `${modelLabel} was selected.`,
383
- state: 'submitted',
384
- display: 'collapsed',
385
- disabled: true,
386
- actions: [],
218
+ kind: 'choice',
219
+ widgetId: `api_provider_selection_${Date.now()}`,
220
+ title: `Setup AI Provider`,
221
+ description: `Select a provider to continue.`,
222
+ actions: providerActions,
223
+ metadata: { type: 'api_provider_selection' },
387
224
  },
388
- meta: { agentId: context.state.agentId, threadId },
225
+ meta: { agentId: state.agentId, threadId },
389
226
  };
227
+ return;
228
+ }
229
+ throw error;
230
+ }
231
+ }
232
+ export async function* handleOpenbotWidgetResponse(args, options) {
233
+ const event = args.event;
234
+ const { metadata, values, actionId } = event.data;
235
+ const threadId = args.threadId;
236
+ const { host, storage } = options;
237
+ let configuredModelString = options.model ?? AUTO_MODEL_ID;
238
+ const state = args.state;
239
+ if (host.isCloudSystemAgent(state.agentId) && options.authMode === 'credits')
240
+ return;
241
+ if (metadata?.type === 'api_provider_selection') {
242
+ const provider = actionId;
243
+ const configuredModelId = isAutoModel(configuredModelString)
244
+ ? ''
245
+ : configuredModelString.split('/').slice(1).join('/');
246
+ const registry = await fetchModelRegistry();
247
+ const providerData = registry?.providers?.[provider];
248
+ const label = providerData?.label || provider;
249
+ const link = PROVIDER_API_KEY_LINKS[provider] || '';
250
+ const modelOptions = getProviderModelOptions(registry, provider);
251
+ yield {
252
+ type: 'client:ui:widget',
253
+ data: {
254
+ widgetId: event.data.widgetId,
255
+ kind: 'message',
256
+ title: 'Provider Selected',
257
+ body: `${label} provider was selected.`,
258
+ state: 'submitted',
259
+ display: 'collapsed',
260
+ disabled: true,
261
+ actions: [],
262
+ },
263
+ meta: { agentId: state.agentId, threadId },
264
+ };
265
+ if (modelOptions && modelOptions.length > 0 && !isAutoModel(configuredModelString)) {
266
+ const defaultModelId = modelOptions.find((m) => m.value === configuredModelId)?.value || modelOptions[0].value;
390
267
  yield {
391
268
  type: 'client:ui:widget',
392
269
  data: {
393
- kind: 'form',
394
- widgetId: `api_key_request_${Date.now()}`,
395
- title: `${label} Setup`,
396
- description: `Enter your API key to continue.`,
397
- fields: [
398
- {
399
- id: 'apiKey',
400
- label: 'API Key',
401
- type: 'password',
402
- description: `Get your key here: [${link}](${link})`,
403
- placeholder: `sk-...`,
404
- required: true,
405
- },
406
- ],
407
- submitLabel: 'Save & Continue',
408
- metadata: {
409
- type: 'api_key_request',
410
- provider,
411
- model: modelId,
412
- },
270
+ kind: 'choice',
271
+ widgetId: `api_model_selection_${Date.now()}`,
272
+ title: 'Select Model',
273
+ description: `Choose a ${label} model.`,
274
+ actions: modelOptions.map((option) => ({
275
+ id: option.value,
276
+ label: option.label,
277
+ variant: option.value === defaultModelId ? 'primary' : 'secondary',
278
+ })),
279
+ metadata: { type: 'api_model_selection', provider },
413
280
  },
414
- meta: { agentId: context.state.agentId, threadId },
415
- };
416
- return;
417
- }
418
- if (metadata?.type !== 'api_key_request')
419
- return;
420
- if (!values?.apiKey)
421
- return;
422
- const provider = String(values.provider || metadata.provider);
423
- const keepAuto = isAutoModel(configuredModelString);
424
- const modelId = String(values.model || metadata.model || '').trim();
425
- if (!keepAuto && !modelId)
426
- return;
427
- const apiKey = String(values.apiKey);
428
- if (provider !== 'openai' &&
429
- provider !== 'anthropic' &&
430
- provider !== 'google' &&
431
- provider !== 'deepseek') {
432
- yield {
433
- type: 'agent:output',
434
- data: { content: `Unsupported provider: ${provider}` },
435
- meta: { agentId: context.state.agentId },
281
+ meta: { agentId: state.agentId, threadId },
436
282
  };
437
283
  return;
438
284
  }
439
- const envVar = provider === 'openai'
440
- ? 'OPENAI_API_KEY'
441
- : provider === 'anthropic'
442
- ? 'ANTHROPIC_API_KEY'
443
- : provider === 'deepseek'
444
- ? 'DEEPSEEK_API_KEY'
445
- : 'GOOGLE_GENERATIVE_AI_API_KEY';
446
- const newModelString = keepAuto ? AUTO_MODEL_ID : `${provider}/${modelId}`;
447
- if (!storage)
448
- return;
449
- try {
450
- await storage.createVariable({ key: envVar, value: apiKey, secret: true });
451
- process.env[envVar] = apiKey;
452
- if (!keepAuto) {
453
- configuredModelString = newModelString;
454
- }
455
- try {
456
- if (!keepAuto) {
457
- host.saveConfig({ model: configuredModelString });
458
- }
459
- const details = await storage.getAgentDetails({ agentId: context.state.agentId });
460
- const updatedPlugins = details.pluginRefs.map((ref) => {
461
- if (ref.id === host.openbotPluginId) {
462
- return {
463
- ...ref,
464
- config: {
465
- ...ref.config,
466
- ...(keepAuto ? {} : { model: configuredModelString }),
467
- ...(host.isCloudSystemAgent(context.state.agentId) ? { authMode: 'byok' } : {}),
285
+ yield {
286
+ type: 'client:ui:widget',
287
+ data: {
288
+ kind: 'form',
289
+ widgetId: `api_key_request_${Date.now()}`,
290
+ title: `${label} Setup`,
291
+ description: isAutoModel(configuredModelString)
292
+ ? `Enter your API key to continue.`
293
+ : `Enter your API key and model ID.`,
294
+ fields: [
295
+ ...(isAutoModel(configuredModelString)
296
+ ? []
297
+ : [
298
+ {
299
+ id: 'model',
300
+ label: 'Model',
301
+ type: 'text',
302
+ required: true,
303
+ defaultValue: configuredModelId || '',
468
304
  },
469
- };
470
- }
471
- return ref;
472
- });
473
- await storage.updateAgent({
474
- agentId: context.state.agentId,
475
- plugins: updatedPlugins,
476
- });
477
- }
478
- catch {
479
- // best-effort: config persistence failure shouldn't block the conversation
480
- }
481
- yield {
482
- type: 'agent:output',
483
- data: {
484
- content: keepAuto
485
- ? `Saved ${provider} API key. Auto will use it when that provider is the cheapest available.`
486
- : `Saved ${provider} API key and set model to \`${newModelString}\`.`,
487
- },
488
- meta: { agentId: context.state.agentId },
489
- };
490
- yield {
491
- type: 'client:ui:widget',
492
- data: {
493
- widgetId: event.data.widgetId,
494
- kind: 'message',
495
- title: 'API Key Saved',
496
- body: keepAuto
497
- ? `Successfully saved ${provider} API key. You can now continue your conversation.`
498
- : `Successfully saved ${provider} API key and selected model \`${newModelString}\`. You can now continue your conversation.`,
499
- state: 'submitted',
500
- display: 'collapsed',
501
- disabled: true,
502
- actions: [],
503
- },
504
- meta: { agentId: context.state.agentId },
505
- };
506
- yield* runLLM(context, threadId);
305
+ ]),
306
+ {
307
+ id: 'apiKey',
308
+ label: 'API Key',
309
+ type: 'password',
310
+ description: `Get your key here: [${link}](${link})`,
311
+ required: true,
312
+ },
313
+ ],
314
+ submitLabel: 'Save & Continue',
315
+ metadata: { type: 'api_key_request', provider },
316
+ },
317
+ meta: { agentId: state.agentId, threadId },
318
+ };
319
+ return;
320
+ }
321
+ if (metadata?.type === 'api_model_selection') {
322
+ const provider = String(metadata.provider);
323
+ const modelId = String(actionId).trim();
324
+ const registry = await fetchModelRegistry();
325
+ const providerData = registry?.providers?.[provider];
326
+ const label = providerData?.label || provider;
327
+ const link = PROVIDER_API_KEY_LINKS[provider] || '';
328
+ yield {
329
+ type: 'client:ui:widget',
330
+ data: {
331
+ widgetId: event.data.widgetId,
332
+ kind: 'message',
333
+ title: 'Model Selected',
334
+ body: `${modelId} was selected.`,
335
+ state: 'submitted',
336
+ display: 'collapsed',
337
+ disabled: true,
338
+ actions: [],
339
+ },
340
+ meta: { agentId: state.agentId, threadId },
341
+ };
342
+ yield {
343
+ type: 'client:ui:widget',
344
+ data: {
345
+ kind: 'form',
346
+ widgetId: `api_key_request_${Date.now()}`,
347
+ title: `${label} Setup`,
348
+ description: `Enter your API key to continue.`,
349
+ fields: [
350
+ {
351
+ id: 'apiKey',
352
+ label: 'API Key',
353
+ type: 'password',
354
+ description: `Get your key here: [${link}](${link})`,
355
+ required: true,
356
+ },
357
+ ],
358
+ submitLabel: 'Save & Continue',
359
+ metadata: { type: 'api_key_request', provider, model: modelId },
360
+ },
361
+ meta: { agentId: state.agentId, threadId },
362
+ };
363
+ return;
364
+ }
365
+ if (metadata?.type !== 'api_key_request' || !values?.apiKey || !storage)
366
+ return;
367
+ const provider = String(values.provider || metadata.provider);
368
+ const keepAuto = isAutoModel(configuredModelString);
369
+ const modelId = String(values.model || metadata.model || '').trim();
370
+ if (!keepAuto && !modelId)
371
+ return;
372
+ const apiKey = String(values.apiKey);
373
+ if (provider !== 'openai' &&
374
+ provider !== 'anthropic' &&
375
+ provider !== 'google' &&
376
+ provider !== 'deepseek') {
377
+ yield {
378
+ type: 'agent:output',
379
+ data: { content: `Unsupported provider: ${provider}` },
380
+ meta: { agentId: state.agentId },
381
+ };
382
+ return;
383
+ }
384
+ const envVar = provider === 'openai'
385
+ ? 'OPENAI_API_KEY'
386
+ : provider === 'anthropic'
387
+ ? 'ANTHROPIC_API_KEY'
388
+ : provider === 'deepseek'
389
+ ? 'DEEPSEEK_API_KEY'
390
+ : 'GOOGLE_GENERATIVE_AI_API_KEY';
391
+ const newModelString = keepAuto ? AUTO_MODEL_ID : `${provider}/${modelId}`;
392
+ await storage.createVariable({ key: envVar, value: apiKey, secret: true });
393
+ process.env[envVar] = apiKey;
394
+ if (!keepAuto) {
395
+ configuredModelString = newModelString;
396
+ try {
397
+ host.saveConfig({ model: configuredModelString });
507
398
  }
508
- catch (error) {
509
- yield {
510
- type: 'agent:output',
511
- data: {
512
- content: `Failed to save API key: ${error instanceof Error ? error.message : 'Unknown error'}`,
513
- },
514
- meta: { agentId: context.state.agentId },
515
- };
399
+ catch {
400
+ /* ignore */
516
401
  }
517
- });
518
- };
402
+ }
403
+ yield {
404
+ type: 'agent:output',
405
+ data: {
406
+ content: keepAuto
407
+ ? `Saved ${provider} API key. Auto will use it when that provider is the cheapest available.`
408
+ : `Saved ${provider} API key and set model to \`${newModelString}\`.`,
409
+ },
410
+ meta: { agentId: state.agentId },
411
+ };
412
+ yield* runOpenbotTurn(args, { ...options, model: configuredModelString });
413
+ }