@bubx/cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2197 @@
1
+ #!/usr/bin/env node
2
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
3
+ var __typeError = (msg) => {
4
+ throw TypeError(msg);
5
+ };
6
+ var __using = (stack, value, async) => {
7
+ if (value != null) {
8
+ if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
9
+ var dispose, inner;
10
+ if (async) dispose = value[__knownSymbol("asyncDispose")];
11
+ if (dispose === void 0) {
12
+ dispose = value[__knownSymbol("dispose")];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") __typeError("Object not disposable");
16
+ if (inner) dispose = function() {
17
+ try {
18
+ inner.call(this);
19
+ } catch (e) {
20
+ return Promise.reject(e);
21
+ }
22
+ };
23
+ stack.push([async, dispose, value]);
24
+ } else if (async) {
25
+ stack.push([async]);
26
+ }
27
+ return value;
28
+ };
29
+ var __callDispose = (stack, error, hasError) => {
30
+ var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
31
+ return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
32
+ };
33
+ var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
34
+ var next = (it) => {
35
+ while (it = stack.pop()) {
36
+ try {
37
+ var result = it[1] && it[1].call(it[2]);
38
+ if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
39
+ } catch (e) {
40
+ fail(e);
41
+ }
42
+ }
43
+ if (hasError) throw error;
44
+ };
45
+ return next();
46
+ };
47
+
48
+ // ../bot-server/src/main.ts
49
+ import { once } from "node:events";
50
+ import { resolve as resolve2 } from "node:path";
51
+
52
+ // ../bot-server/src/control-plane.ts
53
+ var ControlPlaneError = class extends Error {
54
+ constructor(status, code, retryAfterSeconds) {
55
+ super(`Bot Server API request failed: ${code} (HTTP ${status})`);
56
+ this.status = status;
57
+ this.code = code;
58
+ this.retryAfterSeconds = retryAfterSeconds;
59
+ }
60
+ status;
61
+ code;
62
+ retryAfterSeconds;
63
+ };
64
+ function createControlPlane(origin, key) {
65
+ async function request(path, method, body, signal) {
66
+ const timeout = AbortSignal.timeout(1e4);
67
+ const response = await fetch(new URL(path, origin), {
68
+ method,
69
+ headers: {
70
+ accept: "application/json",
71
+ authorization: `Bearer ${key}`,
72
+ ...body === void 0 ? {} : { "content-type": "application/json" }
73
+ },
74
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
75
+ redirect: "error",
76
+ signal: signal ? AbortSignal.any([timeout, signal]) : timeout
77
+ });
78
+ if (!response.ok) {
79
+ const error = await response.json().catch(() => void 0);
80
+ const retry = Number(response.headers.get("retry-after") ?? 0);
81
+ throw new ControlPlaneError(
82
+ response.status,
83
+ error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "REQUEST_FAILED",
84
+ Number.isFinite(retry) ? Math.max(0, retry) : 0
85
+ );
86
+ }
87
+ return await response.json();
88
+ }
89
+ return {
90
+ issueTicket(botId, signal) {
91
+ return request(
92
+ "/api/v2/relay/tickets",
93
+ "POST",
94
+ { botId },
95
+ signal
96
+ );
97
+ },
98
+ async publishCatalog(botId, catalog, ownerPermissions) {
99
+ const path = `/api/bots/${encodeURIComponent(botId)}/catalog`;
100
+ const { revision: revision2 } = await request(path, "GET");
101
+ if (!Number.isSafeInteger(revision2) || revision2 < 0)
102
+ throw new Error("The API returned an invalid catalog revision.");
103
+ await request(path, "PUT", {
104
+ expectedCatalogRevision: revision2,
105
+ catalog,
106
+ ownerPermissions
107
+ });
108
+ }
109
+ };
110
+ }
111
+
112
+ // ../bot-server/src/server.ts
113
+ import { createHash as createHash2 } from "node:crypto";
114
+ import { mkdirSync, realpathSync, statSync } from "node:fs";
115
+ import { rm as rm2 } from "node:fs/promises";
116
+ import { join as join4 } from "node:path";
117
+ import { DatabaseSync } from "node:sqlite";
118
+ import { setTimeout as delay } from "node:timers/promises";
119
+
120
+ // ../../packages/agent-adapters/agy/dist/local.js
121
+ import { execFile } from "node:child_process";
122
+ import { promisify } from "node:util";
123
+ var run = promisify(execFile);
124
+ var environmentKeys = [
125
+ "HOME",
126
+ "PATH",
127
+ "USER",
128
+ "TMPDIR",
129
+ "XDG_CONFIG_HOME",
130
+ "XDG_DATA_HOME",
131
+ "LANG",
132
+ "HTTPS_PROXY",
133
+ "HTTP_PROXY",
134
+ "ALL_PROXY",
135
+ "NO_PROXY",
136
+ "https_proxy",
137
+ "http_proxy",
138
+ "all_proxy",
139
+ "no_proxy",
140
+ "SSL_CERT_FILE",
141
+ "SSL_CERT_DIR"
142
+ ];
143
+ function agyEnvironment() {
144
+ return Object.fromEntries(environmentKeys.map((key) => [key, process.env[key]]));
145
+ }
146
+
147
+ // ../../packages/agent-adapters/agy/dist/text.js
148
+ import { spawn } from "node:child_process";
149
+ var timeoutMs = 9e4;
150
+ var maximumOutputBytes = 1048576;
151
+ async function runAgyText({ workingDirectory, text, signal, config, onEvent }) {
152
+ if (signal.aborted)
153
+ throw new Error("The Antigravity request was cancelled.");
154
+ const permission = config?.permission ?? "read-only";
155
+ if (permission !== "read-only" && permission !== "full-access")
156
+ throw new Error("Antigravity does not support this permission mode.");
157
+ const stopped = new AbortController();
158
+ const timeout = AbortSignal.timeout(timeoutMs);
159
+ const processSignal = AbortSignal.any([signal, timeout, stopped.signal]);
160
+ const settings = permission === "read-only" ? {
161
+ toolPermission: "request-review",
162
+ allowNonWorkspaceAccess: false,
163
+ permissions: {
164
+ allow: [],
165
+ ask: [],
166
+ deny: [
167
+ "write_file(*)",
168
+ "command(*)",
169
+ "unsandboxed(*)",
170
+ "mcp(*)",
171
+ "read_url(*)",
172
+ "execute_url(*)"
173
+ ]
174
+ }
175
+ } : { enableTerminalSandbox: false, allowNonWorkspaceAccess: true };
176
+ const executionArgs = permission === "full-access" ? ["--dangerously-skip-permissions"] : [];
177
+ if (config) {
178
+ executionArgs.push(`--model=${config.model}`);
179
+ if (config.reasoningEffort !== "default")
180
+ executionArgs.push(`--effort=${config.reasoningEffort}`);
181
+ }
182
+ return new Promise((resolve3, reject) => {
183
+ const child = spawn("agy", [
184
+ "--input-format",
185
+ "stream-json",
186
+ "--output-format",
187
+ "stream-json",
188
+ "--disable-slash-commands",
189
+ "--print-timeout",
190
+ "90s",
191
+ "--mode",
192
+ "accept-edits",
193
+ "--settings",
194
+ JSON.stringify(settings),
195
+ ...executionArgs
196
+ ], {
197
+ cwd: workingDirectory,
198
+ env: agyEnvironment(),
199
+ stdio: ["pipe", "pipe", "ignore"],
200
+ signal: processSignal,
201
+ // AGY handles SIGINT by cancelling its independently grouped tools.
202
+ killSignal: "SIGINT"
203
+ });
204
+ let bytes = 0;
205
+ let buffer = "";
206
+ let answer = "";
207
+ let completed = false;
208
+ let failure;
209
+ function fail(message) {
210
+ if (failure)
211
+ return;
212
+ failure = message;
213
+ stopped.abort();
214
+ }
215
+ function readEvent(line) {
216
+ if (!line.trim() || failure)
217
+ return;
218
+ try {
219
+ const event = JSON.parse(line);
220
+ switch (event.event) {
221
+ case "init":
222
+ case "step_update":
223
+ break;
224
+ case "result": {
225
+ const result = event.result;
226
+ if (result?.status !== "SUCCESS" || typeof result.response !== "string" || result.finished_reason) {
227
+ fail("Antigravity could not complete the request.");
228
+ return;
229
+ }
230
+ answer = result.response;
231
+ completed = true;
232
+ break;
233
+ }
234
+ default:
235
+ throw new Error();
236
+ }
237
+ onEvent?.({ type: event.event });
238
+ } catch {
239
+ fail("Antigravity returned an invalid text event.");
240
+ }
241
+ }
242
+ child.stdout.setEncoding("utf8");
243
+ child.stdout.on("data", (chunk) => {
244
+ if (failure)
245
+ return;
246
+ bytes += Buffer.byteLength(chunk);
247
+ if (bytes > maximumOutputBytes) {
248
+ fail("Antigravity returned too much data.");
249
+ return;
250
+ }
251
+ const lines = (buffer + chunk).split("\n");
252
+ buffer = lines.pop() ?? "";
253
+ for (const line of lines)
254
+ readEvent(line);
255
+ });
256
+ child.once("error", () => {
257
+ failure ??= "Could not start the local Antigravity CLI.";
258
+ });
259
+ child.stdin.on("error", () => {
260
+ failure ??= "Could not submit the prompt to Antigravity.";
261
+ });
262
+ child.once("close", (code) => {
263
+ readEvent(buffer);
264
+ if (signal.aborted)
265
+ reject(new Error("The Antigravity request was cancelled."));
266
+ else if (timeout.aborted)
267
+ reject(new Error("The Antigravity request timed out."));
268
+ else if (failure)
269
+ reject(new Error(failure));
270
+ else if (code !== 0 || !completed || !answer.trim())
271
+ reject(new Error("Antigravity did not return a complete text reply."));
272
+ else
273
+ resolve3(answer);
274
+ });
275
+ child.stdin.end(JSON.stringify({ event: "user", message: { content: text } }) + "\n");
276
+ });
277
+ }
278
+
279
+ // ../../packages/agent-adapters/agy/dist/index.js
280
+ var agyDescriptor = {
281
+ id: "agy",
282
+ name: "Antigravity",
283
+ integrationStatus: "ready",
284
+ capabilities: {
285
+ textStreaming: "unsupported",
286
+ toolEvents: "unsupported",
287
+ approvals: "unsupported",
288
+ cancellation: process.platform === "win32" ? "unverified" : "supported",
289
+ sessionResume: "unsupported"
290
+ }
291
+ };
292
+
293
+ // ../../packages/agent-adapters/codex/dist/local.js
294
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
295
+ import { promisify as promisify2 } from "node:util";
296
+ var run2 = promisify2(execFile2);
297
+ var environmentKeys2 = [
298
+ "HOME",
299
+ "PATH",
300
+ "USER",
301
+ "TMPDIR",
302
+ "CODEX_HOME",
303
+ "XDG_CONFIG_HOME",
304
+ "XDG_DATA_HOME",
305
+ "LANG",
306
+ "HTTPS_PROXY",
307
+ "HTTP_PROXY",
308
+ "ALL_PROXY",
309
+ "NO_PROXY",
310
+ "https_proxy",
311
+ "http_proxy",
312
+ "all_proxy",
313
+ "no_proxy",
314
+ "SSL_CERT_FILE",
315
+ "SSL_CERT_DIR"
316
+ ];
317
+ function codexEnvironment() {
318
+ return Object.fromEntries(environmentKeys2.map((key) => [key, process.env[key]]));
319
+ }
320
+
321
+ // ../../packages/agent-adapters/codex/dist/text.js
322
+ import { spawn as spawn3 } from "node:child_process";
323
+ var timeoutMs2 = 9e4;
324
+ var maximumOutputBytes2 = 1048576;
325
+ async function runCodexText({ workingDirectory, text, imagePaths, signal, config, onEvent }) {
326
+ if (signal.aborted)
327
+ throw new Error("The Codex request was cancelled.");
328
+ const stopped = new AbortController();
329
+ const timeout = AbortSignal.timeout(timeoutMs2);
330
+ const processSignal = AbortSignal.any([signal, timeout, stopped.signal]);
331
+ const permission = config?.permission ?? "read-only";
332
+ const sandbox = permission === "full-access" ? "danger-full-access" : permission;
333
+ const executionArgs = config ? [
334
+ `--model=${config.model}`,
335
+ "-c",
336
+ `model_reasoning_effort=${JSON.stringify(config.reasoningEffort)}`
337
+ ] : [
338
+ "--disable",
339
+ "shell_tool",
340
+ "--disable",
341
+ "unified_exec",
342
+ "--disable",
343
+ "multi_agent",
344
+ "--disable",
345
+ "multi_agent_v2"
346
+ ];
347
+ if (permission === "workspace-write")
348
+ executionArgs.push("-c", "sandbox_workspace_write.network_access=false");
349
+ return new Promise((resolve3, reject) => {
350
+ const ownProcessGroup = process.platform !== "win32";
351
+ const child = spawn3("codex", [
352
+ "--ask-for-approval",
353
+ "never",
354
+ "exec",
355
+ "--json",
356
+ "--color",
357
+ "never",
358
+ "--ephemeral",
359
+ "--ignore-user-config",
360
+ "--skip-git-repo-check",
361
+ "--sandbox",
362
+ sandbox,
363
+ ...executionArgs,
364
+ ...imagePaths?.map((path) => `--image=${path}`) ?? [],
365
+ "--disable",
366
+ "apps",
367
+ "-c",
368
+ "mcp_servers={}",
369
+ "-c",
370
+ 'web_search="disabled"',
371
+ "-"
372
+ ], {
373
+ cwd: workingDirectory,
374
+ env: codexEnvironment(),
375
+ stdio: ["pipe", "pipe", "ignore"],
376
+ detached: ownProcessGroup,
377
+ signal: processSignal,
378
+ killSignal: "SIGINT"
379
+ });
380
+ function forceStop() {
381
+ if (ownProcessGroup && child.pid !== void 0) {
382
+ try {
383
+ process.kill(-child.pid, "SIGKILL");
384
+ return;
385
+ } catch {
386
+ }
387
+ }
388
+ child.kill("SIGKILL");
389
+ }
390
+ let forceStopTimer;
391
+ function scheduleForceStop() {
392
+ forceStopTimer = setTimeout(forceStop, 2e3).unref();
393
+ }
394
+ processSignal.addEventListener("abort", scheduleForceStop, { once: true });
395
+ let bytes = 0;
396
+ let buffer = "";
397
+ let answer = "";
398
+ let completed = false;
399
+ let failure;
400
+ function fail(message) {
401
+ if (failure)
402
+ return;
403
+ failure = message;
404
+ stopped.abort();
405
+ }
406
+ function readEvent(line) {
407
+ if (!line.trim() || failure)
408
+ return;
409
+ try {
410
+ const event = JSON.parse(line);
411
+ switch (event.type) {
412
+ case "thread.started":
413
+ case "turn.started":
414
+ break;
415
+ case "item.started":
416
+ case "item.updated":
417
+ case "item.completed": {
418
+ const item = event.item;
419
+ if (typeof item?.type !== "string" || !config && item.type !== "agent_message" && item.type !== "reasoning") {
420
+ fail("Codex emitted an unsupported action.");
421
+ return;
422
+ }
423
+ if (event.type === "item.completed" && item.type === "agent_message") {
424
+ if (typeof item.text !== "string")
425
+ throw new Error();
426
+ answer = item.text;
427
+ }
428
+ break;
429
+ }
430
+ case "turn.completed":
431
+ completed = true;
432
+ break;
433
+ case "turn.failed":
434
+ case "error":
435
+ fail("Codex could not complete the request.");
436
+ return;
437
+ default:
438
+ throw new Error();
439
+ }
440
+ onEvent?.({ type: event.type });
441
+ } catch {
442
+ fail("Codex returned an invalid text event.");
443
+ }
444
+ }
445
+ child.stdout.setEncoding("utf8");
446
+ child.stdout.on("data", (chunk) => {
447
+ if (failure)
448
+ return;
449
+ bytes += Buffer.byteLength(chunk);
450
+ if (bytes > maximumOutputBytes2) {
451
+ fail("Codex returned too much data.");
452
+ return;
453
+ }
454
+ const lines = (buffer + chunk).split("\n");
455
+ buffer = lines.pop() ?? "";
456
+ for (const line of lines)
457
+ readEvent(line);
458
+ });
459
+ child.once("error", () => {
460
+ failure ??= "Could not start the local Codex CLI.";
461
+ });
462
+ child.stdin.on("error", () => {
463
+ failure ??= "Could not submit the prompt to Codex.";
464
+ });
465
+ child.once("close", (code) => {
466
+ readEvent(buffer);
467
+ processSignal.removeEventListener("abort", scheduleForceStop);
468
+ clearTimeout(forceStopTimer);
469
+ if (processSignal.aborted && ownProcessGroup)
470
+ forceStop();
471
+ if (signal.aborted)
472
+ reject(new Error("The Codex request was cancelled."));
473
+ else if (timeout.aborted)
474
+ reject(new Error("The Codex request timed out."));
475
+ else if (failure)
476
+ reject(new Error(failure));
477
+ else if (code !== 0 || !completed || !answer.trim()) {
478
+ reject(new Error("Codex did not return a complete text reply."));
479
+ } else
480
+ resolve3(answer);
481
+ });
482
+ child.stdin.end(text);
483
+ });
484
+ }
485
+
486
+ // ../bot-server/src/server.ts
487
+ import { newWebSocketRpcSession, RpcTarget } from "capnweb";
488
+
489
+ // ../../packages/relay-sdk/dist/protocol/index.js
490
+ import { z as z3 } from "zod";
491
+
492
+ // ../../packages/relay-sdk/dist/protocol/chat-attachments.js
493
+ import { z } from "zod";
494
+ var MAX_CHAT_ATTACHMENTS = 5;
495
+ var MAX_CHAT_ATTACHMENT_BYTES = 10 * 1024 * 1024;
496
+ var CHAT_ATTACHMENT_CHUNK_BYTES = 24 * 1024;
497
+ var attachmentId = z.uuid();
498
+ var fileOffset = z.int().min(0).max(MAX_CHAT_ATTACHMENT_BYTES);
499
+ var chatAttachmentDescriptor = z.strictObject({
500
+ attachmentId,
501
+ name: z.string().min(1).max(150).refine((name) => name !== "." && name !== ".." && !/[/\\\p{Cc}]/u.test(name)),
502
+ mediaType: z.string().max(100).regex(/^[\w.!#$&^+-]+\/[\w.!#$&^+-]+$/u),
503
+ sizeBytes: fileOffset
504
+ });
505
+ var attachmentUploadInput = chatAttachmentDescriptor.extend({
506
+ sessionId: z.string().min(1).max(128),
507
+ offset: fileOffset,
508
+ data: z.base64().max(CHAT_ATTACHMENT_CHUNK_BYTES / 3 * 4)
509
+ }).refine((input2) => input2.offset <= input2.sizeBytes);
510
+ var attachmentUploadResult = z.strictObject({
511
+ attachmentId,
512
+ nextOffset: fileOffset
513
+ });
514
+ var chatAttachmentIds = z.array(attachmentId).max(MAX_CHAT_ATTACHMENTS).refine((ids) => ids.length === new Set(ids).size);
515
+
516
+ // ../../packages/relay-sdk/dist/protocol/workspace-files.js
517
+ import { z as z2 } from "zod";
518
+ var WORKSPACE_FILES_PAGE_SIZE = 32;
519
+ var WORKSPACE_FILE_CHUNK_BYTES = 24 * 1024;
520
+ function isEntryName(value) {
521
+ return value.length > 0 && value.length <= 255 && value !== "." && value !== ".." && !value.includes("/") && !value.includes("\0");
522
+ }
523
+ var entryName = z2.string().refine(isEntryName);
524
+ var listCursor = z2.string().min(1).max(257);
525
+ var sortedListCursor = listCursor.refine((value) => (value.startsWith("d:") || value.startsWith("f:")) && isEntryName(value.slice(2)));
526
+ var relativePath = z2.string().max(4096).refine((value) => value.split("/").every(isEntryName));
527
+ var workspaceId = z2.string().min(1).max(128);
528
+ var offset = z2.int().nonnegative();
529
+ var revision = z2.string().min(1).max(128);
530
+ var workspaceFilesListInput = z2.strictObject({
531
+ workspaceId,
532
+ directory: z2.union([z2.literal(""), relativePath]).optional(),
533
+ cursor: sortedListCursor.optional()
534
+ });
535
+ var workspaceFilesReadInput = z2.strictObject({
536
+ workspaceId,
537
+ path: relativePath,
538
+ offset,
539
+ revision: revision.optional()
540
+ }).refine((input2) => input2.offset === 0 || input2.revision !== void 0);
541
+ var workspaceFileEntry = z2.strictObject({
542
+ name: entryName,
543
+ kind: z2.enum(["directory", "file"])
544
+ });
545
+ var workspaceFilesListResult = z2.strictObject({
546
+ entries: z2.array(workspaceFileEntry).max(WORKSPACE_FILES_PAGE_SIZE),
547
+ nextCursor: listCursor.optional()
548
+ });
549
+ var workspaceFilesReadResult = z2.strictObject({
550
+ path: relativePath,
551
+ offset,
552
+ data: z2.base64().max(WORKSPACE_FILE_CHUNK_BYTES / 3 * 4),
553
+ eof: z2.boolean(),
554
+ revision,
555
+ sizeBytes: z2.int().nonnegative()
556
+ });
557
+
558
+ // ../../packages/relay-sdk/dist/protocol/index.js
559
+ var RELAY_PROTOCOL_VERSION = "0.1-draft";
560
+ var identifier = z3.string().min(1).max(128).refine((value) => value === value.trim(), {
561
+ message: "Identifiers must not have leading or trailing whitespace"
562
+ });
563
+ var envelopeFields = {
564
+ version: z3.literal(RELAY_PROTOCOL_VERSION),
565
+ messageId: identifier,
566
+ botId: identifier,
567
+ sessionId: identifier.optional(),
568
+ sentAt: z3.iso.datetime({ offset: true })
569
+ };
570
+ var requestSchema = z3.strictObject({
571
+ ...envelopeFields,
572
+ type: z3.literal("request"),
573
+ requestId: identifier,
574
+ method: identifier,
575
+ payload: z3.json()
576
+ });
577
+ var eventSchema = z3.strictObject({
578
+ ...envelopeFields,
579
+ type: z3.literal("event"),
580
+ requestId: identifier.optional(),
581
+ seq: z3.int().nonnegative().optional(),
582
+ event: identifier,
583
+ payload: z3.json()
584
+ });
585
+ var ackSchema = z3.strictObject({
586
+ ...envelopeFields,
587
+ type: z3.literal("ack"),
588
+ requestId: identifier.optional(),
589
+ ackMessageId: identifier,
590
+ status: z3.literal("received")
591
+ });
592
+ var relayEnvelopeSchema = z3.discriminatedUnion("type", [
593
+ requestSchema,
594
+ eventSchema,
595
+ ackSchema
596
+ ]);
597
+ var version = z3.literal(RELAY_PROTOCOL_VERSION);
598
+ var routeRevision = z3.int().positive();
599
+ var role = z3.enum(["CLI", "CLIENT"]);
600
+ var botFields = { version, botId: identifier };
601
+ var relayAuthFrameSchema = z3.strictObject({
602
+ type: z3.literal("auth"),
603
+ version,
604
+ ticket: z3.string().min(32).max(512)
605
+ });
606
+ var relayAuthOkFrameSchema = z3.strictObject({
607
+ ...botFields,
608
+ type: z3.literal("auth.ok"),
609
+ role,
610
+ connectionId: identifier,
611
+ routeRevision
612
+ });
613
+ var relayAuthErrorFrameSchema = z3.strictObject({
614
+ type: z3.literal("auth.error"),
615
+ version,
616
+ code: z3.enum([
617
+ "TICKET_INVALID",
618
+ "ACCESS_DENIED",
619
+ "STALE_ROUTE",
620
+ "SERVICE_UNAVAILABLE"
621
+ ])
622
+ });
623
+ var permissionScope = (limit) => z3.array(z3.string().min(1).max(128)).max(limit).refine((items) => new Set(items).size === items.length);
624
+ var relayPrincipalSchema = z3.strictObject({
625
+ role,
626
+ botId: identifier,
627
+ userId: identifier,
628
+ deviceId: identifier,
629
+ relayNodeId: identifier,
630
+ routeRevision,
631
+ permissions: z3.strictObject({
632
+ agentIds: permissionScope(32),
633
+ workspaceIds: permissionScope(64),
634
+ toolIds: permissionScope(128),
635
+ canApprove: z3.boolean()
636
+ })
637
+ });
638
+ var principalIdentity = relayPrincipalSchema.pick({
639
+ userId: true,
640
+ deviceId: true
641
+ });
642
+ var targetedEventSchema = eventSchema.extend({
643
+ target: principalIdentity.extend({ connectionId: identifier })
644
+ });
645
+ var routedRequestSchema = requestSchema.extend({
646
+ actor: principalIdentity.extend({
647
+ permissions: relayPrincipalSchema.shape.permissions
648
+ }),
649
+ originConnectionId: identifier,
650
+ routeRevision
651
+ });
652
+ var presenceSchema = z3.strictObject({
653
+ ...botFields,
654
+ type: z3.literal("relay.presence"),
655
+ payload: z3.strictObject({
656
+ state: z3.enum(["CLI_ONLINE", "CLI_OFFLINE"]),
657
+ routeRevision
658
+ })
659
+ });
660
+ var rejectSchema = z3.strictObject({
661
+ ...botFields,
662
+ type: z3.literal("relay.reject"),
663
+ payload: z3.strictObject({
664
+ messageId: identifier,
665
+ code: z3.enum([
666
+ "CLI_OFFLINE",
667
+ "STALE_ROUTE",
668
+ "RATE_LIMITED",
669
+ "BACKPRESSURE"
670
+ ])
671
+ })
672
+ });
673
+ var relayOutgoingMessageSchema = z3.discriminatedUnion("type", [
674
+ requestSchema,
675
+ targetedEventSchema,
676
+ ackSchema
677
+ ]);
678
+ var relayIncomingMessageSchema = z3.discriminatedUnion("type", [
679
+ routedRequestSchema,
680
+ eventSchema,
681
+ ackSchema,
682
+ presenceSchema,
683
+ rejectSchema
684
+ ]);
685
+
686
+ // ../bot-server/src/agent-text.ts
687
+ var BotRequestError = class extends Error {
688
+ constructor(code, message) {
689
+ super(message);
690
+ this.code = code;
691
+ }
692
+ code;
693
+ };
694
+ function identifier2(input2) {
695
+ return typeof input2 === "string" && input2.length > 0 && input2.length <= 128 && input2 === input2.trim();
696
+ }
697
+ function logItem(session, itemId, role2, text, attachments) {
698
+ const truncated = text.length > 500;
699
+ session.items.push({
700
+ itemId,
701
+ role: role2,
702
+ excerpt: text.slice(0, 500),
703
+ truncated,
704
+ ...attachments?.length ? { attachments } : {}
705
+ });
706
+ if (session.items.length > 10) {
707
+ session.items.shift();
708
+ session.historyTruncated = true;
709
+ }
710
+ if (truncated) session.historyTruncated = true;
711
+ }
712
+ function createAgentTextRuntime({
713
+ botId,
714
+ ownerId,
715
+ workspace,
716
+ store,
717
+ digest,
718
+ attachments: uploads,
719
+ agentId,
720
+ agentName,
721
+ runText,
722
+ config,
723
+ onTrace,
724
+ waitUntil
725
+ }) {
726
+ const sessions = /* @__PURE__ */ new Map();
727
+ const admissions = /* @__PURE__ */ new Map();
728
+ const lifetime = new AbortController();
729
+ let activeTurn;
730
+ const loaded = store.load();
731
+ const turns = new Map(loaded.turns.map((turn) => [turn.turnId, turn]));
732
+ for (const saved of loaded.sessions) {
733
+ const turn = saved.currentTurn && turns.get(saved.currentTurn.turnId);
734
+ const session = {
735
+ ...saved,
736
+ subscriptions: /* @__PURE__ */ new Map(),
737
+ ...turn ? { currentTurn: turn } : {}
738
+ };
739
+ sessions.set(saved.summary.sessionId, session);
740
+ if (turn && ["ACCEPTED", "RUNNING", "CANCEL_REQUESTED"].includes(turn.state)) {
741
+ turn.state = "RECOVERY_REQUIRED";
742
+ session.seq++;
743
+ persist(session);
744
+ }
745
+ }
746
+ for (const request of loaded.requests) {
747
+ const key = admissionKey(request.userId, request.requestId);
748
+ if (request.method === "session.create") {
749
+ const session = sessions.get(request.resultRef);
750
+ if (session)
751
+ admissions.set(key, {
752
+ kind: request.method,
753
+ digest: request.payloadHash,
754
+ session
755
+ });
756
+ } else {
757
+ const turn = turns.get(request.resultRef);
758
+ if (turn)
759
+ admissions.set(key, {
760
+ kind: request.method,
761
+ digest: request.payloadHash,
762
+ turn
763
+ });
764
+ }
765
+ }
766
+ function admissionKey(userId, requestId) {
767
+ return JSON.stringify([userId, requestId]);
768
+ }
769
+ function success(value) {
770
+ return { ok: true, value };
771
+ }
772
+ function persist(session, request) {
773
+ const { summary, ownerUserId, seq, items, historyTruncated, currentTurn } = session;
774
+ store.save(
775
+ {
776
+ summary,
777
+ ownerUserId,
778
+ seq,
779
+ items,
780
+ historyTruncated,
781
+ ...currentTurn ? { currentTurn } : {}
782
+ },
783
+ request
784
+ );
785
+ }
786
+ function publish(session, turn, event, payload) {
787
+ const seq = ++session.seq;
788
+ persist(session);
789
+ const frame2 = {
790
+ event,
791
+ payload,
792
+ seq,
793
+ requestId: turn.startRequestId,
794
+ sessionId: turn.sessionId
795
+ };
796
+ for (const { emit } of session.subscriptions.values()) {
797
+ void Promise.resolve().then(() => emit(frame2)).catch(() => {
798
+ });
799
+ }
800
+ onTrace?.(event, {
801
+ requestId: turn.startRequestId,
802
+ sessionId: turn.sessionId,
803
+ seq,
804
+ state: turn.state
805
+ });
806
+ }
807
+ function setState(session, turn, state) {
808
+ turn.state = state;
809
+ session.summary.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
810
+ publish(session, turn, "turn.state", { ...turn });
811
+ }
812
+ async function executeTurn(session, { turn, controller }, text, attachments) {
813
+ const signal = AbortSignal.any([lifetime.signal, controller.signal]);
814
+ let answer;
815
+ try {
816
+ signal.throwIfAborted();
817
+ setState(session, turn, "RUNNING");
818
+ onTrace?.(`${agentId}.exec`, {
819
+ requestId: turn.startRequestId,
820
+ turnId: turn.turnId,
821
+ ...config?.model ? { model: config.model } : {},
822
+ ...config?.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {},
823
+ ...config?.permission ? { permission: config.permission } : {}
824
+ });
825
+ answer = await runText({
826
+ text,
827
+ attachments,
828
+ signal,
829
+ onEvent: ({ type }) => {
830
+ onTrace?.(`${agentId}.event`, {
831
+ requestId: turn.startRequestId,
832
+ type
833
+ });
834
+ }
835
+ });
836
+ } catch {
837
+ } finally {
838
+ activeTurn = void 0;
839
+ }
840
+ if (lifetime.signal.aborted) return;
841
+ if (controller.signal.aborted) {
842
+ setState(session, turn, "CANCELLED");
843
+ return;
844
+ }
845
+ if (answer === void 0) {
846
+ turn.error = {
847
+ code: `${agentId.toUpperCase()}_EXEC_FAILED`,
848
+ message: `${agentName} \u6267\u884C\u5931\u8D25\u3002`
849
+ };
850
+ setState(session, turn, "FAILED");
851
+ return;
852
+ }
853
+ const itemId = crypto.randomUUID();
854
+ logItem(session, itemId, "ASSISTANT", answer);
855
+ for (let offset2 = 0; offset2 < answer.length; offset2 += 4096) {
856
+ publish(session, turn, "text.delta", {
857
+ turnId: turn.turnId,
858
+ itemId,
859
+ text: answer.slice(offset2, offset2 + 4096)
860
+ });
861
+ }
862
+ setState(session, turn, "SUCCEEDED");
863
+ }
864
+ function sessionFor(userId, input2, envelopeId) {
865
+ if (!identifier2(input2) || envelopeId !== void 0 && envelopeId !== input2)
866
+ throw new BotRequestError("INVALID_INPUT", "\u4F1A\u8BDD\u6807\u8BC6\u65E0\u6548\u3002");
867
+ const session = sessions.get(input2);
868
+ if (!session || session.ownerUserId !== userId)
869
+ throw new BotRequestError("SESSION_NOT_FOUND", "\u627E\u4E0D\u5230\u8BE5\u4F1A\u8BDD\u3002");
870
+ return session;
871
+ }
872
+ function readAdmission(userId, requestId, kind, digest2) {
873
+ const prior = admissions.get(admissionKey(userId, requestId));
874
+ if (!prior) return;
875
+ if (prior.kind !== kind || prior.digest !== digest2)
876
+ throw new BotRequestError(
877
+ "REQUEST_ID_CONFLICT",
878
+ "\u6B64\u8BF7\u6C42\u6807\u8BC6\u5DF2\u7528\u4E8E\u5176\u4ED6\u64CD\u4F5C\u3002"
879
+ );
880
+ return prior;
881
+ }
882
+ function requireSubscription(session, grant) {
883
+ if (session.subscriptions.get(grant.deviceId)?.connectionId !== grant.connectionId)
884
+ throw new BotRequestError("SESSION_NOT_SUBSCRIBED", "\u8BF7\u5148\u540C\u6B65\u6B64\u4F1A\u8BDD\u3002");
885
+ }
886
+ async function handle(grant, message, onEvent) {
887
+ if (lifetime.signal.aborted)
888
+ return {
889
+ ok: false,
890
+ error: { code: "SERVICE_UNAVAILABLE", message: "Bot Server \u5DF2\u505C\u6B62\u3002" }
891
+ };
892
+ const { userId, permissions } = grant;
893
+ const { method, requestId, payload } = message;
894
+ onTrace?.("rpc.received", { method, requestId });
895
+ try {
896
+ if (grant.botId !== botId || grant.ownerId !== ownerId || userId !== ownerId || !permissions.agentIds.includes(agentId) || !permissions.workspaceIds.includes(workspace.id))
897
+ throw new BotRequestError(
898
+ "FORBIDDEN",
899
+ `\u5F53\u524D\u8EAB\u4EFD\u6CA1\u6709\u6743\u9650\u4F7F\u7528 ${agentName}\u3002`
900
+ );
901
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
902
+ throw new BotRequestError("INVALID_INPUT", "\u8BF7\u6C42\u5185\u5BB9\u65E0\u6548\u3002");
903
+ switch (method) {
904
+ case "session.list": {
905
+ if (payload.createRequestId !== void 0) {
906
+ if (!identifier2(payload.createRequestId))
907
+ throw new BotRequestError("INVALID_INPUT", "\u521B\u5EFA\u8BF7\u6C42\u6807\u8BC6\u65E0\u6548\u3002");
908
+ const existing = admissions.get(
909
+ admissionKey(userId, payload.createRequestId)
910
+ );
911
+ return success({
912
+ items: existing?.kind === "session.create" ? [existing.session.summary] : []
913
+ });
914
+ }
915
+ const limit = payload.limit ?? 20;
916
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > 20)
917
+ throw new BotRequestError("INVALID_INPUT", "\u5217\u8868\u6570\u91CF\u65E0\u6548\u3002");
918
+ const ordered = [...sessions.values()].filter((session) => session.ownerUserId === userId).map(({ summary }) => summary).sort(
919
+ (a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.sessionId.localeCompare(b.sessionId)
920
+ );
921
+ const cursor = payload.cursor;
922
+ const start2 = cursor === void 0 ? 0 : ordered.findIndex(({ sessionId }) => sessionId === cursor) + 1;
923
+ if (cursor !== void 0 && start2 === 0)
924
+ throw new BotRequestError("INVALID_INPUT", "\u4F1A\u8BDD\u5217\u8868\u6E38\u6807\u65E0\u6548\u3002");
925
+ const items = ordered.slice(start2, start2 + limit);
926
+ const nextCursor = start2 + limit < ordered.length ? items.at(-1)?.sessionId : void 0;
927
+ return success({
928
+ items,
929
+ ...nextCursor ? { nextCursor } : {}
930
+ });
931
+ }
932
+ case "session.create": {
933
+ if (payload.agentId !== agentId || payload.workspaceId !== workspace.id)
934
+ throw new BotRequestError("FORBIDDEN", "\u8BE5 Agent \u6216\u5DE5\u4F5C\u533A\u4E0D\u53EF\u7528\u3002");
935
+ const title = payload.title ?? `${agentName} \u4F1A\u8BDD`;
936
+ if (typeof title !== "string" || !title.trim() || title.length > 100)
937
+ throw new BotRequestError("INVALID_INPUT", "\u4F1A\u8BDD\u540D\u79F0\u65E0\u6548\u3002");
938
+ const payloadHash = await digest(JSON.stringify([title]));
939
+ const prior = readAdmission(userId, requestId, method, payloadHash);
940
+ if (prior?.kind === "session.create")
941
+ return success(prior.session.summary);
942
+ const summary = {
943
+ sessionId: crypto.randomUUID(),
944
+ agentId,
945
+ workspaceId: workspace.id,
946
+ title,
947
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
948
+ };
949
+ const session = {
950
+ summary,
951
+ ownerUserId: userId,
952
+ seq: 0,
953
+ items: [],
954
+ historyTruncated: false,
955
+ subscriptions: /* @__PURE__ */ new Map()
956
+ };
957
+ persist(session, {
958
+ userId,
959
+ requestId,
960
+ method,
961
+ payloadHash,
962
+ resultRef: summary.sessionId
963
+ });
964
+ sessions.set(summary.sessionId, session);
965
+ admissions.set(admissionKey(userId, requestId), {
966
+ kind: method,
967
+ digest: payloadHash,
968
+ session
969
+ });
970
+ return success(summary);
971
+ }
972
+ case "session.resume": {
973
+ const session = sessionFor(
974
+ userId,
975
+ payload.sessionId,
976
+ message.sessionId
977
+ );
978
+ return success(session.summary);
979
+ }
980
+ case "session.subscribe": {
981
+ const session = sessionFor(
982
+ userId,
983
+ payload.sessionId,
984
+ message.sessionId
985
+ );
986
+ const highWaterSeq = session.seq;
987
+ const snapshot = {
988
+ event: "session.snapshot",
989
+ payload: {
990
+ session: session.summary,
991
+ recentItems: session.items,
992
+ historyTruncated: session.historyTruncated,
993
+ ...session.currentTurn ? { currentTurn: session.currentTurn } : {}
994
+ },
995
+ sessionId: session.summary.sessionId,
996
+ seq: highWaterSeq
997
+ };
998
+ for (const candidate of sessions.values())
999
+ candidate.subscriptions.delete(grant.deviceId);
1000
+ session.subscriptions.set(grant.deviceId, {
1001
+ connectionId: grant.connectionId,
1002
+ emit: onEvent
1003
+ });
1004
+ await onEvent(snapshot);
1005
+ return success({ mode: "SNAPSHOT", highWaterSeq });
1006
+ }
1007
+ case "attachment.upload": {
1008
+ const input2 = attachmentUploadInput.safeParse(payload);
1009
+ if (!input2.success)
1010
+ throw new BotRequestError("INVALID_INPUT", "\u9644\u4EF6\u6570\u636E\u65E0\u6548\u3002");
1011
+ if (!uploads?.supports(input2.data.mediaType))
1012
+ throw new BotRequestError(
1013
+ "ATTACHMENT_UNSUPPORTED",
1014
+ "\u5F53\u524D Bot \u670D\u52A1\u672A\u542F\u7528\u6B64\u9644\u4EF6\u7C7B\u578B\u3002"
1015
+ );
1016
+ const session = sessionFor(
1017
+ userId,
1018
+ input2.data.sessionId,
1019
+ message.sessionId
1020
+ );
1021
+ requireSubscription(session, grant);
1022
+ return success(uploads.upload(input2.data));
1023
+ }
1024
+ case "turn.start": {
1025
+ void Promise.resolve().then(
1026
+ () => onEvent({
1027
+ event: "request.received",
1028
+ payload: null,
1029
+ requestId
1030
+ })
1031
+ ).catch(() => {
1032
+ });
1033
+ const session = sessionFor(
1034
+ userId,
1035
+ payload.sessionId,
1036
+ message.sessionId
1037
+ );
1038
+ const text = payload.text;
1039
+ const attachmentIds = chatAttachmentIds.safeParse(
1040
+ payload.attachmentIds === void 0 ? [] : payload.attachmentIds
1041
+ );
1042
+ if (!attachmentIds.success)
1043
+ throw new BotRequestError("INVALID_INPUT", "\u9644\u4EF6\u5217\u8868\u65E0\u6548\u3002");
1044
+ if (typeof text !== "string" || text.length > 1e4 || !text.trim() && !attachmentIds.data.length)
1045
+ throw new BotRequestError(
1046
+ "INVALID_INPUT",
1047
+ "\u8BF7\u9644\u52A0\u6587\u4EF6\u6216\u8F93\u5165 1\u201310000 \u4E2A\u5B57\u7B26\u3002"
1048
+ );
1049
+ const payloadHash = await digest(
1050
+ JSON.stringify([
1051
+ session.summary.sessionId,
1052
+ text,
1053
+ ...attachmentIds.data
1054
+ ])
1055
+ );
1056
+ const prior = readAdmission(userId, requestId, method, payloadHash);
1057
+ if (prior?.kind === "turn.start") return success(prior.turn);
1058
+ if (activeTurn)
1059
+ throw new BotRequestError(
1060
+ "TURN_BUSY",
1061
+ `${agentName} \u6B63\u5728\u5904\u7406\u53E6\u4E00\u6761\u6D88\u606F\u3002`
1062
+ );
1063
+ requireSubscription(session, grant);
1064
+ if (!uploads && attachmentIds.data.length)
1065
+ throw new BotRequestError(
1066
+ "ATTACHMENT_UNSUPPORTED",
1067
+ "\u5F53\u524D Bot Server \u4E0D\u652F\u6301\u9644\u4EF6\u3002"
1068
+ );
1069
+ const attachments = uploads?.take(session.summary.sessionId, attachmentIds.data) ?? [];
1070
+ const turn = {
1071
+ startRequestId: requestId,
1072
+ sessionId: session.summary.sessionId,
1073
+ turnId: crypto.randomUUID(),
1074
+ state: "ACCEPTED"
1075
+ };
1076
+ const job = { turn, controller: new AbortController() };
1077
+ const updated = {
1078
+ ...session,
1079
+ items: [...session.items],
1080
+ currentTurn: turn
1081
+ };
1082
+ logItem(
1083
+ updated,
1084
+ requestId,
1085
+ "USER",
1086
+ text,
1087
+ attachments.map(({ descriptor }) => descriptor)
1088
+ );
1089
+ persist(updated, {
1090
+ userId,
1091
+ requestId,
1092
+ method,
1093
+ payloadHash,
1094
+ resultRef: turn.turnId
1095
+ });
1096
+ Object.assign(session, updated);
1097
+ activeTurn = job;
1098
+ admissions.set(admissionKey(userId, requestId), {
1099
+ kind: method,
1100
+ digest: payloadHash,
1101
+ turn
1102
+ });
1103
+ const receipt = { ...turn };
1104
+ job.finished = Promise.resolve().then(() => executeTurn(session, job, text, attachments)).catch(() => {
1105
+ turn.state = "RECOVERY_REQUIRED";
1106
+ onTrace?.("turn.recovery.required", {
1107
+ requestId,
1108
+ turnId: turn.turnId
1109
+ });
1110
+ });
1111
+ waitUntil?.(job.finished);
1112
+ return success(receipt);
1113
+ }
1114
+ case "turn.cancel":
1115
+ case "turn.status": {
1116
+ const { startRequestId } = payload;
1117
+ if (!identifier2(startRequestId))
1118
+ throw new BotRequestError("INVALID_INPUT", "\u6267\u884C\u8BF7\u6C42\u6807\u8BC6\u65E0\u6548\u3002");
1119
+ const prior = admissions.get(admissionKey(userId, startRequestId));
1120
+ const turn = prior?.kind === "turn.start" ? prior.turn : void 0;
1121
+ if (turn && method === "turn.cancel") {
1122
+ const session = sessionFor(
1123
+ userId,
1124
+ turn.sessionId,
1125
+ message.sessionId
1126
+ );
1127
+ if (activeTurn?.turn === turn && (turn.state === "ACCEPTED" || turn.state === "RUNNING")) {
1128
+ setState(session, turn, "CANCEL_REQUESTED");
1129
+ activeTurn.controller.abort();
1130
+ }
1131
+ }
1132
+ return success(
1133
+ turn ? { ...turn } : { startRequestId, state: "UNKNOWN" }
1134
+ );
1135
+ }
1136
+ default:
1137
+ throw new BotRequestError(
1138
+ "NOT_IMPLEMENTED",
1139
+ `\u5F53\u524D Bot Server \u4EC5\u652F\u6301 ${agentName} \u6587\u672C\u95EE\u7B54\u3002`
1140
+ );
1141
+ }
1142
+ } catch (error) {
1143
+ if (!(error instanceof BotRequestError)) throw error;
1144
+ onTrace?.("rpc.rejected", { method, requestId, code: error.code });
1145
+ return { ok: false, error: { code: error.code, message: error.message } };
1146
+ }
1147
+ }
1148
+ return {
1149
+ openSession(grant) {
1150
+ let closed = false;
1151
+ return {
1152
+ call(request, onEvent) {
1153
+ if (closed)
1154
+ return Promise.resolve({
1155
+ ok: false,
1156
+ error: {
1157
+ code: "SERVICE_UNAVAILABLE",
1158
+ message: "Bot Server \u4F1A\u8BDD\u5DF2\u5173\u95ED\u3002"
1159
+ }
1160
+ });
1161
+ return handle(grant, request, onEvent);
1162
+ },
1163
+ close() {
1164
+ closed = true;
1165
+ for (const session of sessions.values()) {
1166
+ if (session.subscriptions.get(grant.deviceId)?.connectionId === grant.connectionId)
1167
+ session.subscriptions.delete(grant.deviceId);
1168
+ }
1169
+ }
1170
+ };
1171
+ },
1172
+ dispose() {
1173
+ lifetime.abort();
1174
+ activeTurn?.controller.abort();
1175
+ uploads?.dispose();
1176
+ for (const session of sessions.values()) session.subscriptions.clear();
1177
+ return activeTurn?.finished;
1178
+ }
1179
+ };
1180
+ }
1181
+
1182
+ // ../bot-server/src/chat-attachments.ts
1183
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
1184
+ import { basename, extname, join } from "node:path";
1185
+ var uploadIdleMs = 10 * 6e4;
1186
+ var maximumStagedBytes = MAX_CHAT_ATTACHMENTS * MAX_CHAT_ATTACHMENT_BYTES;
1187
+ var maximumStagedFiles = MAX_CHAT_ATTACHMENTS * 20;
1188
+ var imageExtensions = /* @__PURE__ */ new Map([
1189
+ ["image/jpeg", ".jpg"],
1190
+ ["image/png", ".png"],
1191
+ ["image/webp", ".webp"],
1192
+ ["image/gif", ".gif"]
1193
+ ]);
1194
+ function isInlineChatImage(mediaType) {
1195
+ return imageExtensions.has(mediaType);
1196
+ }
1197
+ function createChatAttachmentStore() {
1198
+ const files = /* @__PURE__ */ new Map();
1199
+ let stagedBytes = 0;
1200
+ function deleteFile(key) {
1201
+ const file = files.get(key);
1202
+ if (!file) return;
1203
+ files.delete(key);
1204
+ stagedBytes -= file.bytes.length;
1205
+ }
1206
+ function prune() {
1207
+ const now = Date.now();
1208
+ for (const [key, file] of files) {
1209
+ if (file.expiresAt <= now) deleteFile(key);
1210
+ }
1211
+ }
1212
+ const timer = setInterval(prune, 6e4).unref();
1213
+ return {
1214
+ upload(input2) {
1215
+ const {
1216
+ sessionId,
1217
+ attachmentId: attachmentId2,
1218
+ name,
1219
+ mediaType,
1220
+ sizeBytes,
1221
+ offset: offset2,
1222
+ data
1223
+ } = input2;
1224
+ const bytes = Buffer.from(data, "base64");
1225
+ const nextOffset = offset2 + bytes.length;
1226
+ if (nextOffset > sizeBytes || bytes.length > CHAT_ATTACHMENT_CHUNK_BYTES || bytes.length === 0 && sizeBytes !== 0)
1227
+ throw new BotRequestError("INVALID_INPUT", "\u9644\u4EF6\u5206\u7247\u65E0\u6548\u3002");
1228
+ prune();
1229
+ const key = `${sessionId}/${attachmentId2}`;
1230
+ let file = files.get(key);
1231
+ if (!file) {
1232
+ if (offset2 !== 0)
1233
+ throw new BotRequestError(
1234
+ "ATTACHMENT_NOT_FOUND",
1235
+ "\u9644\u4EF6\u5C1A\u672A\u5F00\u59CB\u4E0A\u4F20\u3002"
1236
+ );
1237
+ if (stagedBytes + sizeBytes > maximumStagedBytes || files.size >= maximumStagedFiles)
1238
+ throw new BotRequestError(
1239
+ "CAPACITY_REACHED",
1240
+ "\u672C\u673A\u5F85\u53D1\u9001\u7684\u9644\u4EF6\u5DF2\u6EE1\u3002"
1241
+ );
1242
+ file = {
1243
+ descriptor: { attachmentId: attachmentId2, name, mediaType, sizeBytes },
1244
+ bytes: Buffer.alloc(sizeBytes),
1245
+ nextOffset: 0,
1246
+ expiresAt: Date.now() + uploadIdleMs
1247
+ };
1248
+ files.set(key, file);
1249
+ stagedBytes += sizeBytes;
1250
+ }
1251
+ const descriptor = file.descriptor;
1252
+ if (descriptor.name !== name || descriptor.mediaType !== mediaType || descriptor.sizeBytes !== sizeBytes)
1253
+ throw new BotRequestError("ATTACHMENT_CONFLICT", "\u9644\u4EF6\u4FE1\u606F\u5DF2\u53D8\u5316\u3002");
1254
+ if (offset2 === file.nextOffset) {
1255
+ bytes.copy(file.bytes, offset2);
1256
+ file.nextOffset = nextOffset;
1257
+ } else if (nextOffset > file.nextOffset || !file.bytes.subarray(offset2, nextOffset).equals(bytes)) {
1258
+ throw new BotRequestError(
1259
+ "ATTACHMENT_CONFLICT",
1260
+ "\u9644\u4EF6\u5206\u7247\u4F4D\u7F6E\u6216\u5185\u5BB9\u4E0D\u7B26\u3002"
1261
+ );
1262
+ }
1263
+ file.expiresAt = Date.now() + uploadIdleMs;
1264
+ return { attachmentId: attachmentId2, nextOffset };
1265
+ },
1266
+ take(sessionId, attachmentIds) {
1267
+ prune();
1268
+ const keys = attachmentIds.map((id) => `${sessionId}/${id}`);
1269
+ const attachments = keys.map((key) => {
1270
+ const file = files.get(key);
1271
+ if (!file || file.nextOffset !== file.descriptor.sizeBytes)
1272
+ throw new BotRequestError(
1273
+ "ATTACHMENT_INCOMPLETE",
1274
+ "\u9644\u4EF6\u5C1A\u672A\u5B8C\u6574\u4E0A\u4F20\u3002"
1275
+ );
1276
+ return file;
1277
+ });
1278
+ for (const key of keys) deleteFile(key);
1279
+ return attachments;
1280
+ },
1281
+ dispose() {
1282
+ clearInterval(timer);
1283
+ files.clear();
1284
+ stagedBytes = 0;
1285
+ }
1286
+ };
1287
+ }
1288
+ async function prepareChatAttachments(workspace, staged, signal) {
1289
+ const directory = await mkdtemp(join(workspace, ".bubai-input-"));
1290
+ const files = [];
1291
+ const imagePaths = [];
1292
+ try {
1293
+ for (const { descriptor, bytes } of staged) {
1294
+ signal.throwIfAborted();
1295
+ const { name, mediaType } = descriptor;
1296
+ const imageExtension = imageExtensions.get(mediaType);
1297
+ const extension = extname(name);
1298
+ const filename = `${files.length + 1}${imageExtension ?? (/^\.[a-z0-9]{1,12}$/i.test(extension) ? extension : "")}`;
1299
+ await writeFile(join(directory, filename), bytes, {
1300
+ mode: 384,
1301
+ flag: "wx",
1302
+ signal
1303
+ });
1304
+ const path = join(basename(directory), filename);
1305
+ files.push({ name, path, mediaType });
1306
+ if (imageExtension) imagePaths.push(path);
1307
+ }
1308
+ return {
1309
+ imagePaths,
1310
+ prompt: `User attachments, with paths relative to the working directory:
1311
+ ${JSON.stringify(files)}`,
1312
+ directory
1313
+ };
1314
+ } catch (error) {
1315
+ await rm(directory, { recursive: true, force: true }).catch(
1316
+ () => void 0
1317
+ );
1318
+ throw error;
1319
+ } finally {
1320
+ staged.length = 0;
1321
+ }
1322
+ }
1323
+
1324
+ // ../bot-server/src/ipc.ts
1325
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
1326
+ import {
1327
+ chmodSync,
1328
+ existsSync,
1329
+ lstatSync,
1330
+ readFileSync,
1331
+ unlinkSync,
1332
+ writeFileSync
1333
+ } from "node:fs";
1334
+ import { createConnection, createServer } from "node:net";
1335
+ import { join as join2 } from "node:path";
1336
+ var frameLimit = 4096;
1337
+ function verifyPrivateDirectory(directory) {
1338
+ const stats = lstatSync(directory);
1339
+ if (!stats.isDirectory() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0)
1340
+ throw new Error(
1341
+ "Bot Server state must be in a private directory owned by the current user."
1342
+ );
1343
+ }
1344
+ function credentialPath(directory) {
1345
+ return join2(directory, "bot-server-ipc.secret");
1346
+ }
1347
+ function socketPath(directory) {
1348
+ const path = join2(directory, "daemon.sock");
1349
+ if (Buffer.byteLength(path) > 100) {
1350
+ throw new Error(
1351
+ "The Bubai state directory is too long for the daemon socket."
1352
+ );
1353
+ }
1354
+ return path;
1355
+ }
1356
+ function verifiedEndpoint(directory, path) {
1357
+ verifyPrivateDirectory(directory);
1358
+ const stats = lstatSync(path);
1359
+ if (!stats.isSocket() || stats.uid !== process.getuid?.() || (stats.mode & 63) !== 0) {
1360
+ throw new Error(
1361
+ "The Bubai daemon socket has invalid ownership or permissions."
1362
+ );
1363
+ }
1364
+ }
1365
+ function proof(secret, nonce, method) {
1366
+ return createHmac("sha256", secret).update(nonce).update(":").update(method).digest("hex");
1367
+ }
1368
+ function frame(socket) {
1369
+ return new Promise((resolve3, reject) => {
1370
+ let body = "";
1371
+ function cleanup() {
1372
+ socket.off("data", onData);
1373
+ socket.off("end", onEnd);
1374
+ socket.off("error", onError);
1375
+ socket.off("timeout", onTimeout);
1376
+ }
1377
+ function fail(error) {
1378
+ cleanup();
1379
+ reject(error);
1380
+ }
1381
+ function onEnd() {
1382
+ fail(new Error("The daemon connection ended early."));
1383
+ }
1384
+ function onError(error) {
1385
+ fail(error);
1386
+ }
1387
+ function onTimeout() {
1388
+ fail(new Error("The daemon did not respond in time."));
1389
+ }
1390
+ function onData(chunk) {
1391
+ body += chunk;
1392
+ if (Buffer.byteLength(body) > frameLimit) {
1393
+ fail(new Error("The daemon IPC frame exceeds its limit."));
1394
+ } else if (body.endsWith("\n")) {
1395
+ cleanup();
1396
+ try {
1397
+ resolve3(JSON.parse(body));
1398
+ } catch {
1399
+ reject(new Error("The daemon IPC frame is invalid."));
1400
+ }
1401
+ }
1402
+ }
1403
+ socket.on("data", onData);
1404
+ socket.once("end", onEnd);
1405
+ socket.once("error", onError);
1406
+ socket.once("timeout", onTimeout);
1407
+ });
1408
+ }
1409
+ function record(value) {
1410
+ return typeof value === "object" && value !== null;
1411
+ }
1412
+ async function openDaemonSocket(directory, handler) {
1413
+ const path = socketPath(directory);
1414
+ verifyPrivateDirectory(directory);
1415
+ if (existsSync(path)) {
1416
+ verifiedEndpoint(directory, path);
1417
+ unlinkSync(path);
1418
+ }
1419
+ const key = credentialPath(directory);
1420
+ const secret = randomBytes(32).toString("base64url");
1421
+ if (existsSync(key)) unlinkSync(key);
1422
+ writeFileSync(key, secret, { mode: 384, flag: "wx" });
1423
+ const server = createServer((socket) => {
1424
+ socket.setEncoding("utf8").setTimeout(15e3);
1425
+ socket.on("error", () => {
1426
+ });
1427
+ void (async () => {
1428
+ const nonce = randomBytes(32).toString("hex");
1429
+ const request = frame(socket);
1430
+ socket.write(JSON.stringify({ nonce }) + "\n");
1431
+ const payload = await request;
1432
+ if (!record(payload) || typeof payload.method !== "string" || !Object.hasOwn(handler, payload.method) || typeof payload.proof !== "string" || !/^[a-f0-9]{64}$/.test(payload.proof) || !timingSafeEqual(
1433
+ Buffer.from(payload.proof, "hex"),
1434
+ Buffer.from(proof(secret, nonce, payload.method), "hex")
1435
+ )) {
1436
+ throw new Error("Daemon IPC authentication failed.");
1437
+ }
1438
+ const value = await handler[payload.method]();
1439
+ socket.end(JSON.stringify({ ok: true, value }) + "\n");
1440
+ })().catch((error) => {
1441
+ socket.end(
1442
+ JSON.stringify({
1443
+ ok: false,
1444
+ error: error instanceof Error ? error.message : "The daemon command failed."
1445
+ }) + "\n"
1446
+ );
1447
+ });
1448
+ });
1449
+ try {
1450
+ await new Promise((resolve3, reject) => {
1451
+ server.once("error", reject);
1452
+ server.listen(path, () => {
1453
+ server.off("error", reject);
1454
+ resolve3();
1455
+ });
1456
+ });
1457
+ chmodSync(path, 384);
1458
+ } catch (error) {
1459
+ server.close();
1460
+ unlinkSync(key);
1461
+ throw error;
1462
+ }
1463
+ return async () => {
1464
+ await new Promise((resolve3) => server.close(() => resolve3()));
1465
+ unlinkSync(key);
1466
+ };
1467
+ }
1468
+
1469
+ // ../bot-server/src/storage.ts
1470
+ function createBotRuntimeStore(botId, db) {
1471
+ db.run(`
1472
+ CREATE TABLE IF NOT EXISTS BotSession (
1473
+ id TEXT PRIMARY KEY,
1474
+ botId TEXT NOT NULL,
1475
+ ownerUserId TEXT NOT NULL,
1476
+ agentId TEXT NOT NULL,
1477
+ workspaceId TEXT NOT NULL,
1478
+ title TEXT NOT NULL,
1479
+ snapshot TEXT NOT NULL,
1480
+ seq INTEGER NOT NULL,
1481
+ updatedAt TEXT NOT NULL
1482
+ )
1483
+ `);
1484
+ db.run(`
1485
+ CREATE INDEX IF NOT EXISTS bot_session_owner
1486
+ ON BotSession (botId, ownerUserId, updatedAt)
1487
+ `);
1488
+ db.run(`
1489
+ CREATE TABLE IF NOT EXISTS BotTurn (
1490
+ id TEXT PRIMARY KEY,
1491
+ sessionId TEXT NOT NULL REFERENCES BotSession(id),
1492
+ startRequestId TEXT NOT NULL,
1493
+ state TEXT NOT NULL,
1494
+ snapshot TEXT NOT NULL,
1495
+ UNIQUE (sessionId, startRequestId)
1496
+ )
1497
+ `);
1498
+ db.run(`
1499
+ CREATE TABLE IF NOT EXISTS BotRequest (
1500
+ botId TEXT NOT NULL,
1501
+ userId TEXT NOT NULL,
1502
+ requestId TEXT NOT NULL,
1503
+ method TEXT NOT NULL,
1504
+ payloadHash TEXT NOT NULL,
1505
+ resultRef TEXT NOT NULL,
1506
+ createdAt TEXT NOT NULL,
1507
+ PRIMARY KEY (botId, userId, requestId)
1508
+ )
1509
+ `);
1510
+ return {
1511
+ load() {
1512
+ const sessions = db.read("SELECT snapshot FROM BotSession WHERE botId = ?", botId).map(({ snapshot }) => JSON.parse(String(snapshot)));
1513
+ const turns = db.read(
1514
+ "SELECT t.snapshot FROM BotTurn t JOIN BotSession s ON s.id = t.sessionId WHERE s.botId = ?",
1515
+ botId
1516
+ ).map(({ snapshot }) => JSON.parse(String(snapshot)));
1517
+ const requests = db.read(
1518
+ "SELECT userId, requestId, method, payloadHash, resultRef FROM BotRequest WHERE botId = ?",
1519
+ botId
1520
+ );
1521
+ return { sessions, turns, requests };
1522
+ },
1523
+ save(session, request) {
1524
+ const { sessionId, agentId, workspaceId: workspaceId2, title, updatedAt } = session.summary;
1525
+ db.transaction(() => {
1526
+ db.run(
1527
+ `
1528
+ INSERT INTO BotSession (id, botId, ownerUserId, agentId, workspaceId, title, snapshot, seq, updatedAt)
1529
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
1530
+ ON CONFLICT(id) DO UPDATE SET snapshot = excluded.snapshot, seq = excluded.seq, updatedAt = excluded.updatedAt
1531
+ `,
1532
+ sessionId,
1533
+ botId,
1534
+ session.ownerUserId,
1535
+ agentId,
1536
+ workspaceId2,
1537
+ title,
1538
+ JSON.stringify(session),
1539
+ session.seq,
1540
+ updatedAt
1541
+ );
1542
+ if (session.currentTurn) {
1543
+ const turn = session.currentTurn;
1544
+ db.run(
1545
+ `
1546
+ INSERT INTO BotTurn (id, sessionId, startRequestId, state, snapshot) VALUES (?, ?, ?, ?, ?)
1547
+ ON CONFLICT(id) DO UPDATE SET state = excluded.state, snapshot = excluded.snapshot
1548
+ `,
1549
+ turn.turnId,
1550
+ sessionId,
1551
+ turn.startRequestId,
1552
+ turn.state,
1553
+ JSON.stringify(turn)
1554
+ );
1555
+ }
1556
+ if (request) {
1557
+ db.run(
1558
+ `
1559
+ INSERT INTO BotRequest (botId, userId, requestId, method, payloadHash, resultRef, createdAt)
1560
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1561
+ `,
1562
+ botId,
1563
+ request.userId,
1564
+ request.requestId,
1565
+ request.method,
1566
+ request.payloadHash,
1567
+ request.resultRef,
1568
+ (/* @__PURE__ */ new Date()).toISOString()
1569
+ );
1570
+ }
1571
+ });
1572
+ }
1573
+ };
1574
+ }
1575
+
1576
+ // ../bot-server/src/workspace-files.ts
1577
+ import { createHash } from "node:crypto";
1578
+ import { constants } from "node:fs";
1579
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
1580
+ import { isAbsolute, join as join3, relative, resolve, sep } from "node:path";
1581
+ var fileNames = new Intl.Collator("zh-CN", {
1582
+ numeric: true,
1583
+ sensitivity: "base"
1584
+ });
1585
+ var WorkspaceError = class extends Error {
1586
+ constructor(code, message) {
1587
+ super(message);
1588
+ this.code = code;
1589
+ }
1590
+ code;
1591
+ };
1592
+ function forbidden() {
1593
+ return new WorkspaceError("FORBIDDEN", "\u65E0\u6743\u8BBF\u95EE\u6B64\u5DE5\u4F5C\u76EE\u5F55\u6216\u6587\u4EF6\u3002");
1594
+ }
1595
+ function changed() {
1596
+ return new WorkspaceError("FILE_CHANGED", "\u76EE\u5F55\u6216\u6587\u4EF6\u5DF2\u66F4\u6539\uFF0C\u8BF7\u5237\u65B0\u540E\u91CD\u8BD5\u3002");
1597
+ }
1598
+ async function workspacePath(root, path) {
1599
+ if (await realpath(root) !== root) throw forbidden();
1600
+ const canonical = await realpath(resolve(root, path));
1601
+ const child = relative(root, canonical);
1602
+ if (child === ".." || child.startsWith(`..${sep}`) || isAbsolute(child))
1603
+ throw forbidden();
1604
+ return canonical;
1605
+ }
1606
+ async function verifyPath(root, path, canonical, opened) {
1607
+ if (await workspacePath(root, path) !== canonical) throw changed();
1608
+ const current = await lstat(canonical, { bigint: true });
1609
+ if (current.dev !== opened.dev || current.ino !== opened.ino) throw changed();
1610
+ }
1611
+ async function entryKind(root, path) {
1612
+ try {
1613
+ const entry = await lstat(await workspacePath(root, path));
1614
+ if (entry.isDirectory()) return "directory";
1615
+ if (entry.isFile()) return "file";
1616
+ } catch (error) {
1617
+ const code = error.code;
1618
+ if (!["FORBIDDEN", "ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM"].includes(
1619
+ code ?? ""
1620
+ ))
1621
+ throw error;
1622
+ }
1623
+ }
1624
+ function compareEntries(left, right) {
1625
+ if (left.kind !== right.kind) return left.kind === "directory" ? -1 : 1;
1626
+ return fileNames.compare(left.name, right.name) || (left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
1627
+ }
1628
+ async function listFiles(root, directory, cursor) {
1629
+ const canonical = await workspacePath(root, directory);
1630
+ const before = await lstat(canonical, { bigint: true });
1631
+ if (!before.isDirectory())
1632
+ throw new WorkspaceError("FILE_UNAVAILABLE", "\u6240\u9009\u9879\u76EE\u4E0D\u662F\u76EE\u5F55\u3002");
1633
+ const children = await readdir(canonical, { withFileTypes: true });
1634
+ const after = cursor ? {
1635
+ name: cursor.slice(2),
1636
+ kind: cursor.startsWith("d:") ? "directory" : "file"
1637
+ } : void 0;
1638
+ const remaining = [];
1639
+ for (const child of children) {
1640
+ const kind = child.isDirectory() ? "directory" : child.isFile() ? "file" : child.isSymbolicLink() ? await entryKind(root, join3(directory, child.name)) : void 0;
1641
+ if (!kind) continue;
1642
+ const entry = { name: child.name, kind };
1643
+ if (!after || compareEntries(entry, after) > 0) remaining.push(entry);
1644
+ }
1645
+ const entries = remaining.sort(compareEntries).slice(0, WORKSPACE_FILES_PAGE_SIZE);
1646
+ const last = entries.at(-1);
1647
+ await verifyPath(root, directory, canonical, before);
1648
+ return {
1649
+ entries,
1650
+ ...remaining.length > entries.length && last ? { nextCursor: `${last.kind === "directory" ? "d:" : "f:"}${last.name}` } : {}
1651
+ };
1652
+ }
1653
+ function fileRevision(stats) {
1654
+ return createHash("sha256").update(
1655
+ `${stats.dev}:${stats.ino}:${stats.size}:${stats.mtimeNs}:${stats.ctimeNs}`
1656
+ ).digest("hex");
1657
+ }
1658
+ async function readFileChunk(root, path, offset2, expectedRevision) {
1659
+ const canonical = await workspacePath(root, path);
1660
+ if (!(await lstat(canonical)).isFile())
1661
+ throw new WorkspaceError("FILE_UNAVAILABLE", "\u53EA\u80FD\u4E0B\u8F7D\u666E\u901A\u6587\u4EF6\u3002");
1662
+ const file = await open(
1663
+ canonical,
1664
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
1665
+ );
1666
+ try {
1667
+ const before = await file.stat({ bigint: true });
1668
+ if (!before.isFile())
1669
+ throw new WorkspaceError("FILE_UNAVAILABLE", "\u53EA\u80FD\u4E0B\u8F7D\u666E\u901A\u6587\u4EF6\u3002");
1670
+ await verifyPath(root, path, canonical, before);
1671
+ const revision2 = fileRevision(before);
1672
+ if (expectedRevision !== void 0 && expectedRevision !== revision2)
1673
+ throw changed();
1674
+ const sizeBytes = Number(before.size);
1675
+ if (!Number.isSafeInteger(sizeBytes) || offset2 > sizeBytes)
1676
+ throw new WorkspaceError("INVALID_INPUT", "\u6587\u4EF6\u5927\u5C0F\u6216\u8BFB\u53D6\u4F4D\u7F6E\u65E0\u6548\u3002");
1677
+ const buffer = Buffer.alloc(
1678
+ Math.min(WORKSPACE_FILE_CHUNK_BYTES, sizeBytes - offset2)
1679
+ );
1680
+ const { bytesRead } = buffer.length ? await file.read(buffer, 0, buffer.length, offset2) : { bytesRead: 0 };
1681
+ await verifyPath(root, path, canonical, before);
1682
+ if (buffer.length && bytesRead === 0 || fileRevision(await file.stat({ bigint: true })) !== revision2)
1683
+ throw changed();
1684
+ return {
1685
+ path,
1686
+ offset: offset2,
1687
+ data: buffer.toString("base64", 0, bytesRead),
1688
+ eof: offset2 + bytesRead === sizeBytes,
1689
+ revision: revision2,
1690
+ sizeBytes
1691
+ };
1692
+ } finally {
1693
+ await file.close();
1694
+ }
1695
+ }
1696
+ function workspaceError(error) {
1697
+ if (error instanceof WorkspaceError) return error;
1698
+ const code = error.code;
1699
+ if (code === "ENOENT" || code === "ENOTDIR")
1700
+ return new WorkspaceError("FILE_NOT_FOUND", "\u627E\u4E0D\u5230\u8BE5\u76EE\u5F55\u6216\u6587\u4EF6\u3002");
1701
+ return new WorkspaceError("FILE_UNAVAILABLE", "\u65E0\u6CD5\u8BFB\u53D6\u8BE5\u76EE\u5F55\u6216\u6587\u4EF6\u3002");
1702
+ }
1703
+ async function handleWorkspaceFiles(grant, request, bot, workspace) {
1704
+ try {
1705
+ if (grant.botId !== bot.id || grant.userId !== bot.ownerId)
1706
+ throw forbidden();
1707
+ if (!workspace)
1708
+ throw new WorkspaceError(
1709
+ "WORKSPACE_UNAVAILABLE",
1710
+ "Bot \u5C1A\u672A\u914D\u7F6E\u5DE5\u4F5C\u76EE\u5F55\u3002"
1711
+ );
1712
+ if (!grant.permissions.workspaceIds.includes(workspace.id))
1713
+ throw forbidden();
1714
+ if (request.method === "workspace.files.list") {
1715
+ const input3 = workspaceFilesListInput.safeParse(request.payload);
1716
+ if (!input3.success)
1717
+ throw new WorkspaceError("INVALID_INPUT", "\u76EE\u5F55\u8BF7\u6C42\u65E0\u6548\u3002");
1718
+ if (input3.data.workspaceId !== workspace.id) throw forbidden();
1719
+ return {
1720
+ ok: true,
1721
+ value: await listFiles(
1722
+ workspace.path,
1723
+ input3.data.directory ?? "",
1724
+ input3.data.cursor
1725
+ )
1726
+ };
1727
+ }
1728
+ const input2 = workspaceFilesReadInput.safeParse(request.payload);
1729
+ if (!input2.success)
1730
+ throw new WorkspaceError("INVALID_INPUT", "\u6587\u4EF6\u8BF7\u6C42\u65E0\u6548\u3002");
1731
+ const { workspaceId: workspaceId2, path, offset: offset2, revision: revision2 } = input2.data;
1732
+ if (workspaceId2 !== workspace.id) throw forbidden();
1733
+ return {
1734
+ ok: true,
1735
+ value: await readFileChunk(workspace.path, path, offset2, revision2)
1736
+ };
1737
+ } catch (cause) {
1738
+ const { code, message } = workspaceError(cause);
1739
+ return { ok: false, error: { code, message } };
1740
+ }
1741
+ }
1742
+
1743
+ // ../bot-server/src/server.ts
1744
+ var SessionTarget = class extends RpcTarget {
1745
+ #subscription;
1746
+ #closed = false;
1747
+ #run;
1748
+ #detach;
1749
+ constructor(run3, detach) {
1750
+ super();
1751
+ this.#run = run3;
1752
+ this.#detach = detach;
1753
+ }
1754
+ call(request, onEvent) {
1755
+ if (this.#closed)
1756
+ return Promise.resolve({
1757
+ ok: false,
1758
+ error: {
1759
+ code: "SERVICE_UNAVAILABLE",
1760
+ message: "Bot Server \u4F1A\u8BDD\u5DF2\u5173\u95ED\u3002"
1761
+ }
1762
+ });
1763
+ if (request.method !== "session.subscribe")
1764
+ return this.#run(request, onEvent);
1765
+ this.#subscription ??= onEvent.dup();
1766
+ return this.#run(request, this.#subscription);
1767
+ }
1768
+ close() {
1769
+ if (this.#closed) return;
1770
+ this.#closed = true;
1771
+ this.#detach();
1772
+ this.#subscription?.[Symbol.dispose]();
1773
+ this.#subscription = void 0;
1774
+ }
1775
+ [Symbol.dispose]() {
1776
+ this.close();
1777
+ }
1778
+ };
1779
+ var PeerTarget = class extends RpcTarget {
1780
+ #session;
1781
+ constructor(session) {
1782
+ super();
1783
+ this.#session = session;
1784
+ }
1785
+ openSession(grant) {
1786
+ return this.#session(grant);
1787
+ }
1788
+ };
1789
+ function relayEndpoint(input2) {
1790
+ const url = new URL(input2);
1791
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
1792
+ if (url.protocol !== "wss:" && (url.protocol !== "ws:" || !local) || url.username || url.password || url.search || url.hash || url.pathname !== "/v2/relay")
1793
+ throw new Error("The API returned an invalid Bot Server relay endpoint.");
1794
+ return url;
1795
+ }
1796
+ function lockState(directory) {
1797
+ mkdirSync(directory, { recursive: true, mode: 448 });
1798
+ verifyPrivateDirectory(directory);
1799
+ const db = new DatabaseSync(join4(directory, "daemon-lock.sqlite"));
1800
+ try {
1801
+ db.exec("BEGIN EXCLUSIVE");
1802
+ } catch (cause) {
1803
+ db.close();
1804
+ throw new Error("Another Bot Server already holds this state directory.", {
1805
+ cause
1806
+ });
1807
+ }
1808
+ return () => db.close();
1809
+ }
1810
+ async function runBotServer(config, ready) {
1811
+ const release = lockState(config.directory);
1812
+ try {
1813
+ await start(config, ready);
1814
+ } finally {
1815
+ release();
1816
+ }
1817
+ }
1818
+ async function start(config, ready) {
1819
+ const { botId, ownerId, execution } = config;
1820
+ const origin = new URL(config.apiOrigin);
1821
+ if (!["http:", "https:"].includes(origin.protocol) || origin.username || origin.password || origin.pathname !== "/" || origin.search || origin.hash)
1822
+ throw new Error("Bot Server requires an HTTP or HTTPS API origin.");
1823
+ const key = config.key;
1824
+ if (!botId || !ownerId || !/^[a-zA-Z0-9_-]{32,512}$/.test(key))
1825
+ throw new Error("Bot Server ID, owner and API credential are required.");
1826
+ const workspace = config.workspace ? { ...config.workspace, path: realpathSync(config.workspace.path) } : void 0;
1827
+ if (workspace && !statSync(workspace.path).isDirectory())
1828
+ throw new Error("The Bot Server workspace must be a directory.");
1829
+ const agentEnabled = execution !== void 0 || process.env.BUBAI_CODEX_TEXT_ONLY === "1";
1830
+ const activeWorkspace = agentEnabled ? workspace : void 0;
1831
+ if (agentEnabled && !activeWorkspace)
1832
+ throw new Error("Configure a workspace before enabling Agent execution.");
1833
+ const agentId = execution?.adapter ?? "codex";
1834
+ const agentName = agentId === "agy" ? "agy" : "Codex";
1835
+ const trace = process.env.BUBAI_AGENT_TRACE === "1" || process.env.BUBAI_CODEX_TRACE === "1" ? (action, info) => {
1836
+ console.error(
1837
+ `[${agentId}-trace] ${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), action, ...info })}`
1838
+ );
1839
+ } : void 0;
1840
+ const api = createControlPlane(origin.href, key);
1841
+ const catalog = {
1842
+ agents: [
1843
+ {
1844
+ id: "codex",
1845
+ label: "Codex",
1846
+ supported: !!activeWorkspace && agentId === "codex"
1847
+ },
1848
+ {
1849
+ id: "agy",
1850
+ label: "agy",
1851
+ supported: !!activeWorkspace && agentId === "agy"
1852
+ },
1853
+ { id: "claude", label: "Claude", supported: false }
1854
+ ],
1855
+ workspaces: workspace ? [{ id: workspace.id, label: workspace.label, supported: true }] : [],
1856
+ tools: []
1857
+ };
1858
+ await api.publishCatalog(
1859
+ botId,
1860
+ catalog,
1861
+ activeWorkspace ? {
1862
+ ...config.ownerPermissions,
1863
+ agentIds: [agentId],
1864
+ workspaceIds: [activeWorkspace.id]
1865
+ } : config.ownerPermissions
1866
+ );
1867
+ const db = new DatabaseSync(join4(config.directory, "bot-server.sqlite"));
1868
+ try {
1869
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 3000;");
1870
+ const store = createBotRuntimeStore(botId, {
1871
+ run: (sql, ...params) => {
1872
+ db.prepare(sql).run(...params);
1873
+ },
1874
+ read: (sql, ...params) => db.prepare(sql).all(...params),
1875
+ transaction(action) {
1876
+ db.exec("BEGIN IMMEDIATE");
1877
+ try {
1878
+ action();
1879
+ db.exec("COMMIT");
1880
+ } catch (error) {
1881
+ db.exec("ROLLBACK");
1882
+ throw error;
1883
+ }
1884
+ }
1885
+ });
1886
+ const agent = activeWorkspace && createAgentTextRuntime({
1887
+ botId,
1888
+ ownerId,
1889
+ workspace: activeWorkspace,
1890
+ agentId,
1891
+ agentName,
1892
+ store,
1893
+ digest: (canonical) => createHash2("sha256").update(canonical).digest("hex"),
1894
+ attachments: {
1895
+ ...createChatAttachmentStore(),
1896
+ supports: (mediaType) => execution !== void 0 || isInlineChatImage(mediaType)
1897
+ },
1898
+ ...execution ? { config: execution } : {},
1899
+ ...trace ? { onTrace: trace } : {},
1900
+ async runText({ text, attachments, signal, onEvent }) {
1901
+ const input2 = attachments.length ? await prepareChatAttachments(
1902
+ activeWorkspace.path,
1903
+ attachments,
1904
+ signal
1905
+ ) : void 0;
1906
+ try {
1907
+ signal.throwIfAborted();
1908
+ const options = {
1909
+ workingDirectory: activeWorkspace.path,
1910
+ text: input2 ? `${text.trim() ? text : "\u8BF7\u67E5\u9605\u9644\u5E26\u7684\u6587\u4EF6\u3002"}
1911
+
1912
+ ${input2.prompt}` : text,
1913
+ ...input2?.imagePaths.length ? { imagePaths: input2.imagePaths } : {},
1914
+ signal,
1915
+ ...onEvent ? { onEvent } : {}
1916
+ };
1917
+ return execution?.adapter === "agy" ? await runAgyText({ ...options, config: execution }) : await runCodexText({
1918
+ ...options,
1919
+ ...execution ? { config: execution } : {}
1920
+ });
1921
+ } finally {
1922
+ if (input2)
1923
+ await rm2(input2.directory, { recursive: true, force: true }).catch(
1924
+ () => {
1925
+ trace?.("attachment.cleanup.failed");
1926
+ }
1927
+ );
1928
+ }
1929
+ }
1930
+ });
1931
+ try {
1932
+ const peer = new PeerTarget((grant) => {
1933
+ const session = agent ? agent.openSession(grant) : void 0;
1934
+ return new SessionTarget(
1935
+ (request, onEvent) => {
1936
+ if (grant.botId !== botId || grant.ownerId !== ownerId) {
1937
+ return Promise.resolve({
1938
+ ok: false,
1939
+ error: { code: "FORBIDDEN", message: "Bot Server \u6388\u6743\u65E0\u6548\u3002" }
1940
+ });
1941
+ }
1942
+ if (request.method === "workspace.files.list" || request.method === "workspace.files.read")
1943
+ return handleWorkspaceFiles(
1944
+ grant,
1945
+ request,
1946
+ { id: botId, ownerId },
1947
+ workspace
1948
+ );
1949
+ if (request.method === "capabilities.get") {
1950
+ return Promise.resolve({
1951
+ ok: true,
1952
+ value: {
1953
+ agents: catalog.agents.filter(
1954
+ ({ id }) => grant.permissions.agentIds.includes(id)
1955
+ ),
1956
+ workspaces: catalog.workspaces.filter(
1957
+ ({ id }) => grant.permissions.workspaceIds.includes(id)
1958
+ ),
1959
+ tools: catalog.tools
1960
+ }
1961
+ });
1962
+ }
1963
+ return session?.call(request, onEvent) ?? Promise.resolve({
1964
+ ok: false,
1965
+ error: {
1966
+ code: "NOT_IMPLEMENTED",
1967
+ message: "\u6B64 Bot Server \u672A\u914D\u7F6E Agent\u3002"
1968
+ }
1969
+ });
1970
+ },
1971
+ () => session?.close()
1972
+ );
1973
+ });
1974
+ await serve(
1975
+ config,
1976
+ api,
1977
+ peer,
1978
+ ready,
1979
+ activeWorkspace ? agentId : void 0,
1980
+ trace
1981
+ );
1982
+ } finally {
1983
+ if (agent) await agent.dispose();
1984
+ }
1985
+ } finally {
1986
+ db.close();
1987
+ }
1988
+ }
1989
+ async function serve(config, api, peer, ready, adapter, trace) {
1990
+ const controller = new AbortController();
1991
+ const status = {
1992
+ pid: process.pid,
1993
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1994
+ botId: config.botId,
1995
+ ...adapter ? { adapter } : {},
1996
+ state: "CONNECTING",
1997
+ localReady: true
1998
+ };
1999
+ const stop = () => controller.abort();
2000
+ const closeSocket = await openDaemonSocket(config.directory, {
2001
+ status: () => status,
2002
+ stop() {
2003
+ setImmediate(stop);
2004
+ return { stopping: true };
2005
+ }
2006
+ });
2007
+ process.once("SIGINT", stop);
2008
+ process.once("SIGTERM", stop);
2009
+ let first = true;
2010
+ let retry = 2e3;
2011
+ try {
2012
+ if (!config.requireOnline) ready({ ...status });
2013
+ while (!controller.signal.aborted) {
2014
+ try {
2015
+ var _stack = [];
2016
+ try {
2017
+ status.state = "CONNECTING";
2018
+ const ticket = await api.issueTicket(config.botId, controller.signal);
2019
+ if (!Number.isFinite(Date.parse(ticket.expiresAt)) || Date.parse(ticket.expiresAt) <= Date.now())
2020
+ throw new Error("The API returned an expired Bot Server ticket.");
2021
+ const endpoint = relayEndpoint(ticket.relayUrl);
2022
+ const connection = __using(_stack, await connect(
2023
+ endpoint,
2024
+ ticket.ticket,
2025
+ config.botId,
2026
+ peer,
2027
+ controller.signal
2028
+ ), true);
2029
+ retry = 2e3;
2030
+ status.state = "ONLINE";
2031
+ trace?.("bot-server.relay.auth.ok", { botId: config.botId });
2032
+ if (config.requireOnline && first) ready({ ...status });
2033
+ await connection.disconnected;
2034
+ } catch (_) {
2035
+ var _error = _, _hasError = true;
2036
+ } finally {
2037
+ var _promise = __callDispose(_stack, _error, _hasError);
2038
+ _promise && await _promise;
2039
+ }
2040
+ } catch (error) {
2041
+ if (controller.signal.aborted) break;
2042
+ if (first && config.requireOnline) throw error;
2043
+ if (error instanceof ControlPlaneError) {
2044
+ if ([401, 403, 404].includes(error.status)) {
2045
+ status.state = "OFFLINE";
2046
+ await delay(2 ** 31 - 1, void 0, {
2047
+ signal: controller.signal
2048
+ }).catch(() => void 0);
2049
+ break;
2050
+ }
2051
+ retry = Math.max(retry, error.retryAfterSeconds * 1e3);
2052
+ }
2053
+ }
2054
+ first = false;
2055
+ if (controller.signal.aborted) break;
2056
+ status.state = "OFFLINE";
2057
+ await delay(retry, void 0, { signal: controller.signal }).catch(
2058
+ () => void 0
2059
+ );
2060
+ retry = Math.min(retry * 2, 3e4);
2061
+ }
2062
+ } finally {
2063
+ status.state = "DRAINING";
2064
+ process.off("SIGINT", stop);
2065
+ process.off("SIGTERM", stop);
2066
+ await closeSocket();
2067
+ }
2068
+ }
2069
+ async function connect(url, ticket, botId, peer, signal) {
2070
+ signal.throwIfAborted();
2071
+ const socket = new WebSocket(url.href);
2072
+ const root = newWebSocketRpcSession(socket, peer);
2073
+ let settle;
2074
+ const disconnected = new Promise((resolve3) => {
2075
+ settle = resolve3;
2076
+ });
2077
+ root.onRpcBroken(settle);
2078
+ socket.addEventListener("close", settle, { once: true });
2079
+ const stop = () => {
2080
+ socket.close();
2081
+ settle();
2082
+ };
2083
+ signal.addEventListener("abort", stop, { once: true });
2084
+ const dispose = () => {
2085
+ signal.removeEventListener("abort", stop);
2086
+ root[Symbol.dispose]();
2087
+ stop();
2088
+ };
2089
+ let timeout;
2090
+ try {
2091
+ const admission = await Promise.race([
2092
+ root.connect(ticket),
2093
+ disconnected.then(() => {
2094
+ throw new Error("Bot Server disconnected during admission.");
2095
+ }),
2096
+ new Promise((_, reject) => {
2097
+ timeout = setTimeout(
2098
+ () => reject(new Error("Bot Server relay admission timed out.")),
2099
+ 1e4
2100
+ );
2101
+ })
2102
+ ]);
2103
+ if (admission.kind !== "peer" || admission.botId !== botId)
2104
+ throw new Error(
2105
+ admission.kind === "error" ? admission.code : "Relay returned an invalid Bot Server identity."
2106
+ );
2107
+ return { disconnected, [Symbol.asyncDispose]: async () => dispose() };
2108
+ } catch (error) {
2109
+ dispose();
2110
+ throw error;
2111
+ } finally {
2112
+ clearTimeout(timeout);
2113
+ }
2114
+ }
2115
+
2116
+ // ../bot-server/src/main.ts
2117
+ async function input() {
2118
+ if (process.send) {
2119
+ const [message] = await Promise.race([
2120
+ once(process, "message"),
2121
+ once(process, "disconnect").then(() => {
2122
+ throw new Error(
2123
+ "The launcher disconnected before configuring Bot Server."
2124
+ );
2125
+ })
2126
+ ]);
2127
+ if (!message || typeof message !== "object")
2128
+ throw new Error("Bot Server configuration is invalid.");
2129
+ return message;
2130
+ }
2131
+ const {
2132
+ BUBAI_BOT_API_URL: apiOrigin,
2133
+ BUBAI_BOT_ID: botId,
2134
+ BUBAI_BOT_OWNER_ID: ownerId,
2135
+ BUBAI_BOT_KEY: key,
2136
+ BUBAI_BOT_STATE_DIR: directory,
2137
+ BUBAI_BOT_WORKSPACE: workspacePath2,
2138
+ BUBAI_BOT_WORKSPACE_ID: workspaceId2,
2139
+ BUBAI_BOT_EXECUTION: executionJSON
2140
+ } = process.env;
2141
+ if (!apiOrigin || !botId || !ownerId || !key || !directory)
2142
+ throw new Error(
2143
+ "Set BUBAI_BOT_API_URL, BUBAI_BOT_ID, BUBAI_BOT_OWNER_ID, BUBAI_BOT_KEY and BUBAI_BOT_STATE_DIR."
2144
+ );
2145
+ if (Boolean(workspacePath2) !== Boolean(workspaceId2))
2146
+ throw new Error(
2147
+ "Set both BUBAI_BOT_WORKSPACE and BUBAI_BOT_WORKSPACE_ID for a local workspace."
2148
+ );
2149
+ const execution = executionJSON ? JSON.parse(executionJSON) : void 0;
2150
+ if (execution && !["codex", "agy"].includes(execution.adapter))
2151
+ throw new Error("Bot Server execution must configure Codex or agy.");
2152
+ return {
2153
+ apiOrigin,
2154
+ botId,
2155
+ ownerId,
2156
+ key,
2157
+ directory: resolve2(directory),
2158
+ ...workspacePath2 && workspaceId2 ? {
2159
+ workspace: {
2160
+ id: workspaceId2,
2161
+ label: "Workspace",
2162
+ path: resolve2(workspacePath2)
2163
+ }
2164
+ } : {},
2165
+ ...execution ? { execution } : {},
2166
+ ownerPermissions: {
2167
+ workspaceIds: workspaceId2 ? [workspaceId2] : [],
2168
+ agentIds: execution ? [execution.adapter] : [],
2169
+ toolIds: [],
2170
+ canApprove: false
2171
+ }
2172
+ };
2173
+ }
2174
+ function report(message) {
2175
+ if (process.connected) {
2176
+ process.send?.(message, () => {
2177
+ if (process.connected) process.disconnect?.();
2178
+ });
2179
+ } else {
2180
+ console.log(JSON.stringify(message));
2181
+ }
2182
+ }
2183
+ try {
2184
+ await runBotServer(await input(), (value) => report({ ok: true, value }));
2185
+ } catch (error) {
2186
+ const message = error instanceof Error ? error.message : "Bot Server could not start.";
2187
+ if (process.connected) {
2188
+ report({
2189
+ ok: false,
2190
+ error: message,
2191
+ ...error instanceof ControlPlaneError ? { status: error.status, code: error.code } : {}
2192
+ });
2193
+ } else {
2194
+ console.error(message);
2195
+ }
2196
+ process.exitCode = 1;
2197
+ }