-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
422 lines (387 loc) · 15.4 KB
/
runtime.ts
File metadata and controls
422 lines (387 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import { query, type Options, type SDKMessage } from '@anthropic-ai/claude-agent-sdk';
import {
agentOutput,
shouldHandleInvoke,
uiWidget,
type AgentInvokeEvent,
type OpenBotState,
type PluginFactory,
type Storage,
} from '@meetopenbot/plugin-sdk';
export interface ClaudeCodeRuntimeOptions {
/** Claude model alias or full id (e.g. `sonnet`, `claude-opus-4-5`). */
model?: string;
/** System prompt prepended to the SDK's default tools/system. */
system?: string;
/** Permission mode forwarded to the Claude Agent SDK. */
permissionMode?: NonNullable<Options['permissionMode']>;
/** Working directory for the SDK subprocess (falls back to channel cwd). */
cwd?: string;
/** Restrict the SDK's built-in tools (Read, Edit, Bash, ...). */
allowedTools?: string[];
/** Storage handle for persisting the resume session id across runs. */
storage?: Storage;
}
interface PersistedClaudeState {
claudeSessionId?: string;
}
const asRecord = (value: unknown): Record<string, unknown> =>
value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: {};
const readPersistedSessionId = (state: OpenBotState): string | undefined => {
const source = state.threadDetails?.state ?? state.channelDetails?.state;
const record = asRecord(source) as PersistedClaudeState;
return typeof record.claudeSessionId === 'string' ? record.claudeSessionId : undefined;
};
const persistSessionId = async (
state: OpenBotState,
storage: Storage | undefined,
sessionId: string,
): Promise<void> => {
if (!storage) return;
const patch = { claudeSessionId: sessionId };
if (state.threadId) {
await storage.patchThreadState({
channelId: state.channelId,
threadId: state.threadId,
state: patch,
});
return;
}
await storage.patchChannelState({ channelId: state.channelId, state: patch });
};
const AUTH_ERROR_PATTERNS = [
'api key',
'apikey',
'anthropic_api_key',
'authentication',
'unauthorized',
'401',
'not logged in',
'login',
'oauth',
];
const isAuthErrorMessage = (message: string): boolean => {
const lower = message.toLowerCase();
return AUTH_ERROR_PATTERNS.some((p) => lower.includes(p));
};
const buildApiKeyWidget = (
agentId: string,
threadId: string | undefined,
reason: string,
) =>
uiWidget({
agentId,
threadId,
widget: {
kind: 'form',
widgetId: `claude_code_api_key_request_${Date.now()}`,
title: 'Anthropic API Key Required',
description:
`Claude Code could not authenticate (${reason}). ` +
'Provide an Anthropic API key to continue. The key is stored as a ' +
'workspace variable on your machine and never leaves your local runtime.',
fields: [
{
id: 'apiKey',
label: 'API Key',
type: 'text',
placeholder: 'sk-ant-...',
required: true,
},
],
submitLabel: 'Save API Key',
metadata: {
type: 'api_key_request',
provider: 'anthropic',
envVar: 'ANTHROPIC_API_KEY',
source: 'claude-code',
},
},
});
const toolCallWidgetId = (toolUseId: string) => `claude_code_tool_${toolUseId}`;
const truncate = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}\n…` : s);
const formatJsonForWidget = (value: unknown, maxLen: number): string => {
try {
return truncate(JSON.stringify(value, null, 2), maxLen);
} catch {
return truncate(String(value), maxLen);
}
};
const formatToolResultPayload = (
content: unknown,
isError?: boolean,
): { body: string; state?: 'error' } => {
let body: string;
if (typeof content === 'string') {
body = truncate(content, 12_000);
} else if (Array.isArray(content)) {
const textParts: string[] = [];
for (const block of content) {
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
const t = (block as { text?: unknown }).text;
if (typeof t === 'string' && t.length > 0) textParts.push(t);
}
}
body =
textParts.length > 0
? truncate(textParts.join('\n'), 12_000)
: formatJsonForWidget(content, 12_000);
} else {
body = formatJsonForWidget(content, 12_000);
}
return isError ? { body, state: 'error' } : { body };
};
type ParsedToolUse = { toolUseId: string; title: string; input: unknown };
const parseToolUseBlock = (block: unknown): ParsedToolUse | null => {
if (!block || typeof block !== 'object' || !('type' in block)) return null;
const type = (block as { type: string }).type;
if (type === 'tool_use') {
const b = block as { id?: unknown; name?: unknown; input?: unknown };
if (typeof b.id !== 'string' || typeof b.name !== 'string') return null;
return { toolUseId: b.id, title: b.name, input: b.input };
}
if (type === 'mcp_tool_use') {
const b = block as { id?: unknown; name?: unknown; server_name?: unknown; input?: unknown };
if (typeof b.id !== 'string' || typeof b.name !== 'string') return null;
const title =
typeof b.server_name === 'string' ? `${b.server_name}: ${b.name}` : b.name;
return { toolUseId: b.id, title, input: b.input };
}
if (type === 'server_tool_use') {
const b = block as { id?: unknown; name?: unknown; input?: unknown };
if (typeof b.id !== 'string' || typeof b.name !== 'string') return null;
return { toolUseId: b.id, title: b.name, input: b.input };
}
return null;
};
type ParsedToolResult = { toolUseId: string; content: unknown; isError?: boolean };
const parseToolResultBlock = (block: unknown): ParsedToolResult | null => {
if (!block || typeof block !== 'object' || !('type' in block)) return null;
const type = (block as { type: string }).type;
if (type === 'tool_result' || type === 'mcp_tool_result') {
const b = block as { tool_use_id?: unknown; content?: unknown; is_error?: boolean };
if (typeof b.tool_use_id !== 'string') return null;
return { toolUseId: b.tool_use_id, content: b.content, isError: b.is_error };
}
return null;
};
/**
* OpenBot plugin that drives an agent backed by `@anthropic-ai/claude-agent-sdk`.
*/
export const claudeCodeRuntime =
(options: ClaudeCodeRuntimeOptions = {}): PluginFactory =>
(builder) => {
const {
model = 'sonnet',
system,
permissionMode = 'default',
cwd,
allowedTools,
storage,
} = options;
builder.on('agent:invoke', async function* (event, context) {
if (!shouldHandleInvoke(event as AgentInvokeEvent, context.state.agentId)) {
return;
}
const userContent =
typeof event.data?.content === 'string' ? event.data.content : '';
if (!userContent) return;
const threadId = event.meta?.threadId || context.state.threadId;
const resumeId = readPersistedSessionId(context.state);
const workingDir = cwd ?? context.state.channelDetails?.cwd;
const sdkOptions: Options = {
model,
permissionMode,
...(system ? { systemPrompt: { type: 'preset', preset: 'claude_code', append: system } } : {}),
...(resumeId ? { resume: resumeId } : {}),
...(workingDir ? { cwd: workingDir } : {}),
...(allowedTools ? { allowedTools } : {}),
};
try {
let lastSessionId: string | undefined = resumeId;
let authWidgetYielded = false;
const emittedToolCallIds = new Set<string>();
const emittedToolResultIds = new Set<string>();
const toolTitleByUseId = new Map<string, { title: string; input: unknown }>();
for await (const message of query({ prompt: userContent, options: sdkOptions })) {
if ('session_id' in message && typeof message.session_id === 'string') {
lastSessionId = message.session_id;
}
if (
!authWidgetYielded &&
message.type === 'assistant' &&
(message.error === 'authentication_failed' ||
message.error === 'oauth_org_not_allowed')
) {
authWidgetYielded = true;
yield buildApiKeyWidget(context.state.agentId, threadId, message.error);
return;
}
if (message.type === 'assistant') {
const content = message.message?.content;
if (Array.isArray(content)) {
const textParts: string[] = [];
for (const block of content) {
const tool = parseToolUseBlock(block);
if (tool) {
if (textParts.length > 0) {
const joined = textParts.join('\n');
textParts.length = 0;
if (joined.length > 0) {
yield agentOutput({
agentId: context.state.agentId,
threadId,
content: joined,
});
}
}
if (!emittedToolCallIds.has(tool.toolUseId)) {
emittedToolCallIds.add(tool.toolUseId);
toolTitleByUseId.set(tool.toolUseId, { title: tool.title, input: tool.input });
yield uiWidget({
agentId: context.state.agentId,
threadId,
widget: {
kind: 'message',
widgetId: toolCallWidgetId(tool.toolUseId),
title: toolTitleByUseId.get(tool.toolUseId)?.title ?? '',
description: JSON.stringify(toolTitleByUseId.get(tool.toolUseId)?.input ?? {}),
body: formatJsonForWidget(tool.input, 8000),
display: 'collapsed',
metadata: {
type: 'claude_tool',
phase: 'call',
toolName: tool.title,
toolUseId: tool.toolUseId,
source: 'claude-code',
},
},
});
}
continue;
}
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
const t = (block as { text?: unknown }).text;
if (typeof t === 'string' && t.length > 0) textParts.push(t);
}
}
if (textParts.length > 0) {
const joined = textParts.join('\n');
if (joined.length > 0) {
yield agentOutput({
agentId: context.state.agentId,
threadId,
content: joined,
});
}
}
}
}
if (message.type === 'user') {
const param = message.message;
if (param.role === 'user' && Array.isArray(param.content)) {
for (const block of param.content) {
const res = parseToolResultBlock(block);
if (!res || emittedToolResultIds.has(res.toolUseId)) continue;
emittedToolResultIds.add(res.toolUseId);
const { body, state } = formatToolResultPayload(res.content, res.isError);
yield uiWidget({
agentId: context.state.agentId,
threadId,
widget: {
kind: 'message',
widgetId: toolCallWidgetId(res.toolUseId),
title: toolTitleByUseId.get(res.toolUseId)?.title ?? '',
description: JSON.stringify(toolTitleByUseId.get(res.toolUseId)?.input ?? {}),
body,
display: "collapsed",
...(state ? { state } : {}),
metadata: {
type: 'claude_tool',
phase: 'result',
toolUseId: res.toolUseId,
source: 'claude-code',
},
},
});
}
}
}
if (message.type === 'result' && message.subtype !== 'success') {
const subtype = (message as { subtype: string }).subtype;
const resultText =
'result' in message && typeof (message as { result?: unknown }).result === 'string'
? (message as { result: string }).result
: '';
if (!authWidgetYielded && (isAuthErrorMessage(subtype) || isAuthErrorMessage(resultText))) {
authWidgetYielded = true;
yield buildApiKeyWidget(context.state.agentId, threadId, subtype);
return;
}
yield agentOutput({
agentId: context.state.agentId,
threadId,
content: `[claude-code] run ended with error: ${subtype}`,
});
}
}
if (lastSessionId && lastSessionId !== resumeId) {
await persistSessionId(context.state, storage, lastSessionId);
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
if (isAuthErrorMessage(errorMessage)) {
yield buildApiKeyWidget(context.state.agentId, threadId, errorMessage);
return;
}
yield agentOutput({
agentId: context.state.agentId,
threadId,
content: `[claude-code] error: ${errorMessage}`,
});
}
});
builder.on('client:ui:widget:response', async function* (event, context) {
const { metadata, values, widgetId } = event.data ?? {};
if (!metadata || metadata.type !== 'api_key_request') return;
if (metadata.source !== 'claude-code') return;
const apiKey = values?.apiKey;
if (typeof apiKey !== 'string' || !apiKey) return;
const envVar = typeof metadata.envVar === 'string' ? metadata.envVar : 'ANTHROPIC_API_KEY';
if (!storage) {
yield agentOutput({
agentId: context.state.agentId,
content: '[claude-code] no storage available; cannot persist API key.',
});
return;
}
try {
await storage.createVariable({ key: envVar, value: apiKey, secret: true });
process.env[envVar] = apiKey;
yield uiWidget({
agentId: context.state.agentId,
widget: {
widgetId: widgetId ?? `claude_code_api_key_saved_${Date.now()}`,
kind: 'message',
title: 'API Key Saved',
body: `Saved ${envVar} as a workspace variable. You can now continue the conversation.`,
state: 'submitted',
actions: [{ id: 'ok', label: 'Got it', variant: 'primary' }],
},
});
yield agentOutput({
agentId: context.state.agentId,
content:
'Saved Anthropic API key to workspace variables. Re-send your last message to retry.',
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
yield agentOutput({
agentId: context.state.agentId,
content: `[claude-code] failed to save API key: ${errorMessage}`,
});
}
});
};