Repository navigation
Expand file tree
/
Copy pathopenbot.ts
More file actions
343 lines (320 loc) · 10.3 KB
/
Copy pathopenbot.ts
File metadata and controls
343 lines (320 loc) · 10.3 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
import { z } from "zod";
/** Verified against OpenBot a96d88c6 and its public CopilotKit runtime 1.70.1. */
export const OPENBOT_CONTRACT_REF = "a96d88c6fb75385842529d7db7d463f4a8c4a86e";
/**
* Inject an authenticated, per-person transport from the host application.
* Paths are relative to the OpenBot deployment. The transport owns its session;
* this adapter never accepts a shared administrator token or calls global fetch.
*/
export interface OpenBotTransport {
runtimeUrl: string;
request(path: string, init?: RequestInit): Promise<Response>;
}
export type OpenBotErrorCode =
| "disabled"
| "not_configured"
| "invalid_input"
| "invalid_response"
| "authentication_required"
| "refused"
| "http_error"
| "unavailable"
| "cancelled";
export class OpenBotError extends Error {
constructor(
readonly code: OpenBotErrorCode,
message: string,
readonly status?: number,
readonly rule?: string,
/** An action may have happened. Reconcile before offering another attempt. */
readonly outcomeUnknown = false,
) {
super(message);
this.name = "OpenBotError";
}
}
const nonempty = z.string().min(1);
const capabilitiesSchema = z.object({
mode: z.literal("intelligence"),
durableHistory: z.boolean(),
generativeUi: z.boolean(),
});
const userSchema = z.object({ user: z.object({ id: nonempty }) });
const computerStatusSchema = z.object({
botId: nonempty,
state: z.enum(["absent", "starting", "ready", "unreachable"]),
reason: z.string().optional(),
});
const controlSchema = z.object({
holder: z.enum(["bot", "human"]),
since: nonempty,
requested: z.boolean(),
reason: z.string().optional(),
requestedAt: z.string().optional(),
secretWanted: z.string().optional(),
});
const snapshotSchema = z.object({
snapshotId: z.number().int().nonnegative(),
url: nonempty,
title: z.string(),
truncated: z.boolean(),
elements: z.array(
z.object({
ref: nonempty,
role: z.string(),
name: z.string(),
value: z.string().optional(),
type: z.string().optional(),
disabled: z.boolean().optional(),
checked: z.boolean().optional(),
}),
),
});
const navigationSchema = z.object({
url: nonempty,
title: z.string(),
text: z.string(),
truncated: z.boolean(),
elapsedMs: z.number().nonnegative(),
});
const channelSchema = z.object({
channel: z.object({ id: nonempty, threadId: nonempty, agentIds: z.array(nonempty).min(1) }),
});
const errorSchema = z.object({ error: z.string().optional(), rule: z.string().optional() });
export type OpenBotComputerStatus = z.infer<typeof computerStatusSchema>;
export type OpenBotControl = z.infer<typeof controlSchema>;
export type OpenBotSnapshot = z.infer<typeof snapshotSchema>;
export type OpenBotNavigation = z.infer<typeof navigationSchema>;
export type OpenBotProbe =
| { state: "disabled" | "not_configured" | "authentication_required" }
| { state: "unavailable"; reason: string }
| ({ state: "authenticated"; userId: string } & z.infer<typeof capabilitiesSchema>);
/**
* Future integration seam; constructing it does not connect to OpenBot.
* The caller must enforce OpenMuse proposals before dispatching external writes.
* OpenBot's own policy/audit gateway remains authoritative for every request.
*/
export class OpenBotAdapter {
readonly unsupportedCapabilities = Object.freeze([
"gmail",
"calendar",
"pdf",
"approval_persistence",
] as const);
constructor(
private readonly options: {
enabled?: boolean;
agentId?: string;
transport?: OpenBotTransport;
} = {},
) {}
/** Configure a compatible public CopilotKit client. This is NOT an AG-UI SSE URL. */
runtime() {
const transport = this.requireTransport();
if (!this.options.agentId?.trim()) {
throw new OpenBotError(
"not_configured",
"Choose an OpenBot agent before configuring its runtime.",
);
}
const runtimeUrl = httpUrl(transport.runtimeUrl);
return {
runtimeUrl,
agentId: identifier(this.options.agentId),
mode: "intelligence" as const,
credentials: "include" as const,
};
}
/** Authenticated API reachability, not evidence that a model can complete a run. */
async probe(signal?: AbortSignal): Promise<OpenBotProbe> {
if (this.options.enabled !== true) return { state: "disabled" };
if (!this.options.transport) return { state: "not_configured" };
try {
const { user } = await this.json("/api/me", userSchema, { signal });
const capabilities = await this.json("/api/capabilities", capabilitiesSchema, { signal });
return { state: "authenticated", userId: user.id, ...capabilities };
} catch (error) {
if (!(error instanceof OpenBotError)) throw error;
if (error.code === "authentication_required") return { state: "authentication_required" };
return { state: "unavailable", reason: error.message };
}
}
async createConversation(agentId: string, signal?: AbortSignal) {
const id = identifier(agentId);
const { channel } = await this.json(
"/api/channels",
channelSchema,
{
method: "POST",
body: JSON.stringify({ agentIds: [id] }),
signal,
},
true,
);
if (channel.agentIds.length !== 1 || channel.agentIds[0] !== id) {
throw new OpenBotError(
"invalid_response",
"OpenBot returned a channel for a different agent.",
undefined,
undefined,
true,
);
}
return { channelId: channel.id, threadId: channel.threadId, agentIds: channel.agentIds };
}
async computerStatus(botId: string, signal?: AbortSignal): Promise<OpenBotComputerStatus> {
const result = await this.json(computerPath(botId, "status"), computerStatusSchema, { signal });
if (result.botId !== botId.trim()) {
throw new OpenBotError("invalid_response", "OpenBot returned another Bot's computer status.");
}
return result;
}
snapshot(botId: string, signal?: AbortSignal): Promise<OpenBotSnapshot> {
return this.json(computerPath(botId, "snapshot"), snapshotSchema, { method: "POST", signal });
}
async navigate(
botId: string,
input: { url: string; toolCallId?: string },
signal?: AbortSignal,
): Promise<OpenBotNavigation> {
const url = httpUrl(input.url);
return this.json(
computerPath(botId, "navigate"),
navigationSchema,
{
method: "POST",
body: JSON.stringify({
url,
...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
}),
signal,
},
true,
);
}
computerControl(botId: string, signal?: AbortSignal): Promise<OpenBotControl> {
return this.json(computerPath(botId, "control"), controlSchema, { signal });
}
requestControl(botId: string, reason: string, signal?: AbortSignal): Promise<OpenBotControl> {
return this.json(
computerPath(botId, "control/request"),
controlSchema,
{
method: "POST",
body: JSON.stringify({ reason }),
signal,
},
true,
);
}
takeControl(botId: string, signal?: AbortSignal): Promise<OpenBotControl> {
return this.json(
computerPath(botId, "control/take"),
controlSchema,
{ method: "POST", signal },
true,
);
}
releaseControl(botId: string, signal?: AbortSignal): Promise<OpenBotControl> {
return this.json(
computerPath(botId, "control/release"),
controlSchema,
{ method: "POST", signal },
true,
);
}
private requireTransport(): OpenBotTransport {
if (this.options.enabled !== true)
throw new OpenBotError("disabled", "OpenBot integration is disabled.");
if (!this.options.transport)
throw new OpenBotError(
"not_configured",
"An authenticated OpenBot transport has not been configured.",
);
return this.options.transport;
}
private async json<T>(
path: string,
schema: z.ZodType<T>,
init: RequestInit = {},
mutates = false,
): Promise<T> {
const transport = this.requireTransport();
if (init.signal?.aborted)
throw new OpenBotError("cancelled", "OpenBot request cancelled before dispatch.");
let response: Response;
try {
response = await transport.request(path, {
...init,
method: init.method ?? "GET",
credentials: "include",
redirect: "error",
headers: {
Accept: "application/json",
...(init.body ? { "Content-Type": "application/json" } : {}),
},
});
} catch {
throw new OpenBotError(
init.signal?.aborted ? "cancelled" : "unavailable",
"OpenBot did not return a response.",
undefined,
undefined,
mutates,
);
}
const body: unknown = await response.json().catch(() => undefined);
if (!response.ok) {
const detail = errorSchema.safeParse(body);
const code =
response.status === 401
? "authentication_required"
: response.status === 403
? "refused"
: "http_error";
throw new OpenBotError(
code,
detail.success && detail.data.error
? detail.data.error.slice(0, 1000)
: `OpenBot request failed (${response.status}).`,
response.status,
detail.success ? detail.data.rule : undefined,
mutates && (response.status >= 500 || response.status === 408),
);
}
const parsed = schema.safeParse(body);
if (!parsed.success)
throw new OpenBotError(
"invalid_response",
"OpenBot returned an incompatible response.",
response.status,
undefined,
mutates,
);
return parsed.data;
}
}
function identifier(value: string): string {
const id = value.trim();
if (!id || id === "." || id === "..")
throw new OpenBotError("invalid_input", "An OpenBot ID is required.");
return id;
}
function computerPath(botId: string, operation: string): string {
return `/api/computers/${encodeURIComponent(identifier(botId))}/${operation}`;
}
function httpUrl(value: string): string {
let url: URL;
try {
url = new URL(value);
} catch {
throw new OpenBotError("invalid_input", "A valid HTTP(S) URL is required.");
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
throw new OpenBotError(
"invalid_input",
"A valid HTTP(S) URL without embedded credentials is required.",
);
}
return url.toString();
}