@useavalon/caelence-agent 0.1.0 → 0.1.1-canary.1

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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +129 -137
  3. package/brand/logo/favicon-agent-bg-16.svg +7 -0
  4. package/brand/logo/favicon-agent-bg-32.svg +7 -0
  5. package/brand/previews/desktop-chat.png +0 -0
  6. package/brand/previews/desktop-commands.png +0 -0
  7. package/brand/previews/desktop-integrations.png +0 -0
  8. package/brand/previews/desktop-skills.png +0 -0
  9. package/package.json +5 -3
  10. package/skills/impeccable/LICENSE +13 -0
  11. package/skills/impeccable/NOTICE +14 -0
  12. package/skills/impeccable/SKILL.md +2 -1
  13. package/src/agent-cwd.ts +51 -0
  14. package/src/cli/agent-cwd.test.ts +65 -0
  15. package/src/cli/main.test.ts +5 -0
  16. package/src/cli/main.ts +282 -201
  17. package/src/cli/picker.test.ts +59 -1
  18. package/src/cli/picker.ts +46 -0
  19. package/src/cli/slash-dispatch.test.ts +116 -7
  20. package/src/cli/slash-dispatch.ts +343 -174
  21. package/src/cli/slash.test.ts +25 -2
  22. package/src/cli/slash.ts +37 -8
  23. package/src/cli/theme.test.ts +7 -0
  24. package/src/cli/theme.ts +6 -6
  25. package/src/cli/tui.tsx +385 -217
  26. package/src/config.ts +1 -1
  27. package/src/core/strands.ts +10 -1
  28. package/src/desktop/bridge.test.ts +56 -1
  29. package/src/desktop/bridge.ts +527 -390
  30. package/src/desktop/uploads.test.ts +57 -0
  31. package/src/desktop/uploads.ts +92 -0
  32. package/src/index.ts +26 -2
  33. package/src/init.test.ts +19 -2
  34. package/src/init.ts +25 -17
  35. package/src/integrations/loopback.test.ts +17 -0
  36. package/src/integrations/loopback.ts +91 -0
  37. package/src/observability/prompts.ts +1 -1
  38. package/src/product.ts +3 -1
  39. package/src/runtime.test.ts +24 -0
  40. package/src/runtime.ts +48 -5
  41. package/src/skills/catalog.test.ts +188 -0
  42. package/src/skills/catalog.ts +279 -0
  43. package/src/skills/disabled.test.ts +27 -0
  44. package/src/skills/disabled.ts +59 -0
  45. package/src/skills/loader.test.ts +31 -0
  46. package/src/skills/loader.ts +31 -4
  47. package/src/skills/registry.test.ts +64 -3
  48. package/src/skills/registry.ts +248 -93
  49. package/src/skills/skill-command.ts +2 -0
@@ -8,6 +8,7 @@ import { isHelpAlias } from "../cli/slash.ts";
8
8
  import { applyPickerChoice, isSlashPickerKind, runSlashLine } from "../cli/slash-dispatch.ts";
9
9
  import { resolveOpenRouter } from "../config.ts";
10
10
  import type { ApprovalRequest } from "../core/approval.ts";
11
+ import { errorMessage } from "../core/errors.ts";
11
12
  import type { AgentEvent } from "../core/events.ts";
12
13
  import { tryParseAgentMode } from "../core/mode.ts";
13
14
  import { normalizeSessionTitle, type Session, sessionTranscript } from "../core/session.ts";
@@ -24,9 +25,19 @@ import { transcribeAudio } from "../media/openrouter-generate.ts";
24
25
  import { readMediaPrefs } from "../media/prefs.ts";
25
26
  import { PRODUCT_NAME } from "../product.ts";
26
27
  import { createHarness, type HarnessRuntime } from "../runtime.ts";
28
+ import {
29
+ buildSkillsPage,
30
+ cachedPopularSkills,
31
+ decorateCatalogSkill,
32
+ readPopularSkillsCache,
33
+ refreshPopularSkills,
34
+ withDisabledCatalogSkills,
35
+ } from "../skills/catalog.ts";
36
+ import { searchSkillCatalog } from "../skills/registry.ts";
27
37
  import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
28
38
  import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
29
39
  import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
40
+ import { composeUploadMessage, parseIncomingUploads, saveUploads } from "./uploads.ts";
30
41
 
31
42
  export interface DesktopState {
32
43
  name: string;
@@ -274,416 +285,540 @@ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Pr
274
285
  return { ok: true };
275
286
  };
276
287
 
277
- const server = Bun.serve({
278
- hostname: host,
279
- port: options.port ?? 0,
280
- idleTimeout: 0,
281
- async fetch(req) {
282
- if (req.method === "OPTIONS") {
283
- return new Response(null, { status: 204, headers: CORS_HEADERS });
284
- }
285
- const url = new URL(req.url);
286
- const path = url.pathname;
287
-
288
- if (req.method === "GET" && path === "/oauth/callback") {
289
- const state = url.searchParams.get("state")?.trim() ?? "";
290
- const code = url.searchParams.get("code")?.trim() ?? "";
291
- const error = url.searchParams.get("error")?.trim() ?? "";
292
- const resolve = oauthWaiters.get(state);
293
- if (!resolve) {
294
- return new Response(
295
- oauthResultPage(
296
- false,
297
- "This sign-in is no longer waiting. Close this tab and try Connect again.",
298
- ),
299
- {
300
- status: 400,
301
- headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
302
- },
303
- );
304
- }
305
- oauthWaiters.delete(state);
306
- resolve({ code: code || undefined, error: error || undefined });
307
- const ok = Boolean(code) && !error;
308
- return new Response(
309
- oauthResultPage(
310
- ok,
311
- ok
312
- ? "You can close this tab and return to Caelence agent."
313
- : "Close this tab and try Connect again.",
288
+ const handleOAuthCallback = async (_req: Request, url: URL): Promise<Response> => {
289
+ const state = url.searchParams.get("state")?.trim() ?? "";
290
+ const code = url.searchParams.get("code")?.trim() ?? "";
291
+ const error = url.searchParams.get("error")?.trim() ?? "";
292
+ const resolve = oauthWaiters.get(state);
293
+ if (!resolve) {
294
+ return new Response(
295
+ oauthResultPage(
296
+ false,
297
+ "This sign-in is no longer waiting. Close this tab and try Connect again.",
298
+ ),
299
+ {
300
+ status: 400,
301
+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
302
+ },
303
+ );
304
+ }
305
+ oauthWaiters.delete(state);
306
+ resolve({ code: code || undefined, error: error || undefined });
307
+ const ok = Boolean(code) && !error;
308
+ return new Response(
309
+ oauthResultPage(
310
+ ok,
311
+ ok
312
+ ? "You can close this tab and return to Caelence agent."
313
+ : "Close this tab and try Connect again.",
314
+ ),
315
+ {
316
+ status: ok ? 200 : 400,
317
+ headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
318
+ },
319
+ );
320
+ };
321
+
322
+ const route_get_health = async (_req: Request, _url: URL): Promise<Response> => {
323
+ return json({ ok: true });
324
+ };
325
+
326
+ const route_get_state = async (_req: Request, _url: URL): Promise<Response> => {
327
+ return json(snapshot(harness, busy, title));
328
+ };
329
+
330
+ const route_get_sessions = async (_req: Request, _url: URL): Promise<Response> => {
331
+ return json({ items: sessionPickerItems(await harness.store.list()) });
332
+ };
333
+
334
+ const route_get_models = async (_req: Request, _url: URL): Promise<Response> => {
335
+ return json({ items: modelPickerItems(harness.modelId, cachedLiveTargetNames()) });
336
+ };
337
+
338
+ const route_get_settings = async (_req: Request, _url: URL): Promise<Response> => {
339
+ return json(settingsPayload(harness));
340
+ };
341
+
342
+ const route_get_integrations = async (_req: Request, _url: URL): Promise<Response> => {
343
+ return json({ items: listPublicIntegrations() });
344
+ };
345
+
346
+ const route_post_integrations_connect = async (req: Request, url: URL): Promise<Response> => {
347
+ const body = await readJson(req);
348
+ const connectorId = typeof body.connectorId === "string" ? body.connectorId.trim() : "";
349
+ if (!connectorId) return json({ error: "connectorId is required." }, 400);
350
+ const redirectUri = `http://127.0.0.1:${url.port}/oauth/callback`;
351
+ try {
352
+ await connectMcp({
353
+ connectorId,
354
+ redirectUri,
355
+ waitForCallback: (state) =>
356
+ new Promise<OAuthCallback>((resolve, reject) => {
357
+ const timer = setTimeout(() => {
358
+ oauthWaiters.delete(state);
359
+ reject(new Error("Sign-in timed out. Try Connect again."));
360
+ }, 180_000);
361
+ oauthWaiters.set(state, (result) => {
362
+ clearTimeout(timer);
363
+ resolve(result);
364
+ });
365
+ }),
366
+ });
367
+ await harness.reloadIntegrations();
368
+ return json({ ok: true, items: listPublicIntegrations() });
369
+ } catch (err) {
370
+ return json({ error: errorMessage(err) }, 400);
371
+ }
372
+ };
373
+
374
+ const route_post_integrations_disconnect = async (req: Request, _url: URL): Promise<Response> => {
375
+ const body = await readJson(req);
376
+ const connectorId = typeof body.connectorId === "string" ? body.connectorId.trim() : "";
377
+ if (!connectorId) return json({ error: "connectorId is required." }, 400);
378
+ removeConnection(connectorId);
379
+ await harness.reloadIntegrations();
380
+ return json({ ok: true, items: listPublicIntegrations() });
381
+ };
382
+
383
+ const skillsPage = (popular = cachedPopularSkills()) =>
384
+ buildSkillsPage(
385
+ withDisabledCatalogSkills(harness.skills, harness.disabledSkills()),
386
+ popular,
387
+ harness.disabledSkills(),
388
+ );
389
+
390
+ const route_get_skills = async (_req: Request, _url: URL): Promise<Response> => {
391
+ return json(skillsPage());
392
+ };
393
+
394
+ const route_get_skills_popular = async (_req: Request, _url: URL): Promise<Response> => {
395
+ const cached = readPopularSkillsCache();
396
+ if (!cached.stale) {
397
+ return json({ popular: skillsPage(cached.hits).popular });
398
+ }
399
+ const popular = await refreshPopularSkills();
400
+ return json({ popular: skillsPage(popular).popular });
401
+ };
402
+
403
+ const route_get_skills_search = async (_req: Request, url: URL): Promise<Response> => {
404
+ const q = (url.searchParams.get("q") ?? "").trim();
405
+ if (q.length < 2) return json({ items: [] });
406
+ try {
407
+ const hits = await searchSkillCatalog(q);
408
+ return json({
409
+ items: hits.map((hit) =>
410
+ decorateCatalogSkill(
411
+ hit,
412
+ withDisabledCatalogSkills(harness.skills, harness.disabledSkills()),
413
+ harness.disabledSkills(),
314
414
  ),
315
- {
316
- status: ok ? 200 : 400,
317
- headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" },
318
- },
319
- );
320
- }
415
+ ),
416
+ });
417
+ } catch (err) {
418
+ return json({ error: errorMessage(err) }, 502);
419
+ }
420
+ };
321
421
 
322
- if (readToken(req) !== token) {
323
- return json({ error: `Unauthorized. Restart ${PRODUCT_NAME}.` }, 401);
324
- }
422
+ const route_post_skills_add = async (req: Request, _url: URL): Promise<Response> => {
423
+ const body = await readJson(req);
424
+ const id = typeof body.id === "string" ? body.id.trim() : "";
425
+ if (!id) return json({ error: "id is required." }, 400);
426
+ const name = id.split("@").pop()?.trim() ?? id;
427
+ if (harness.disabledSkills().some((entry) => entry === name.toLowerCase())) {
428
+ harness.enableSkill(name);
429
+ return json({ ok: true, ...skillsPage() });
430
+ }
431
+ const loaded =
432
+ harness.skills.find((skill) => skill.catalogRef === id) ??
433
+ harness.skills.find(
434
+ (skill) => skill.source !== "user" && skill.name.toLowerCase() === name.toLowerCase(),
435
+ );
436
+ if (loaded && loaded.source !== "user") {
437
+ return json({ error: `${loaded.name} is already in the project.` }, 400);
438
+ }
439
+ if (!loaded || loaded.catalogRef !== id) {
440
+ const result = await harness.addSkill(id);
441
+ if ("error" in result) return json({ error: result.error }, 400);
442
+ }
443
+ return json({ ok: true, ...skillsPage() });
444
+ };
325
445
 
326
- if (req.method === "GET" && path === "/health") {
327
- return json({ ok: true });
328
- }
329
- if (req.method === "GET" && path === "/state") {
330
- return json(snapshot(harness, busy, title));
331
- }
332
- if (req.method === "GET" && path === "/sessions") {
333
- return json({ items: sessionPickerItems(await harness.store.list()) });
334
- }
335
- if (req.method === "GET" && path === "/models") {
336
- return json({ items: modelPickerItems(harness.modelId, cachedLiveTargetNames()) });
337
- }
338
- if (req.method === "GET" && path === "/settings") {
339
- return json(settingsPayload(harness));
340
- }
446
+ const route_post_skills_remove = async (req: Request, _url: URL): Promise<Response> => {
447
+ const body = await readJson(req);
448
+ const id = typeof body.id === "string" ? body.id.trim() : "";
449
+ const name =
450
+ (typeof body.name === "string" ? body.name.trim() : "") || id.split("@").pop()?.trim() || "";
451
+ if (!name) return json({ error: "name is required." }, 400);
452
+ const result = harness.removeSkill(name);
453
+ if (!result.ok) return json({ error: result.error ?? "Could not remove." }, 400);
454
+ return json({ ok: true, ...skillsPage() });
455
+ };
341
456
 
342
- if (req.method === "GET" && path === "/integrations") {
343
- return json({ items: listPublicIntegrations() });
344
- }
457
+ const route_post_open = async (req: Request, _url: URL): Promise<Response> => {
458
+ const body = await readJson(req);
459
+ const parsed = parseHttpUrl(typeof body.url === "string" ? body.url : "");
460
+ if (!parsed) return json({ error: "Only http and https links can open." }, 400);
461
+ openUrl(parsed.toString());
462
+ return json({ ok: true });
463
+ };
345
464
 
346
- if (req.method === "POST" && path === "/integrations/connect") {
347
- const body = await readJson(req);
348
- const connectorId = typeof body.connectorId === "string" ? body.connectorId.trim() : "";
349
- if (!connectorId) return json({ error: "connectorId is required." }, 400);
350
- const redirectUri = `http://127.0.0.1:${url.port}/oauth/callback`;
351
- try {
352
- await connectMcp({
353
- connectorId,
354
- redirectUri,
355
- waitForCallback: (state) =>
356
- new Promise<OAuthCallback>((resolve, reject) => {
357
- const timer = setTimeout(() => {
358
- oauthWaiters.delete(state);
359
- reject(new Error("Sign-in timed out. Try Connect again."));
360
- }, 180_000);
361
- oauthWaiters.set(state, (result) => {
362
- clearTimeout(timer);
363
- resolve(result);
364
- });
365
- }),
366
- });
367
- await harness.reloadIntegrations();
368
- return json({ ok: true, items: listPublicIntegrations() });
369
- } catch (err) {
370
- return json({ error: err instanceof Error ? err.message : String(err) }, 400);
371
- }
372
- }
465
+ const route_post_open_path = async (req: Request, _url: URL): Promise<Response> => {
466
+ const body = await readJson(req);
467
+ const filePath = typeof body.path === "string" ? body.path.trim() : "";
468
+ if (!filePath) return json({ error: "Path is missing." }, 400);
469
+ try {
470
+ openPath(filePath, body.reveal === true);
471
+ return json({ ok: true });
472
+ } catch (err) {
473
+ return json({ error: errorMessage(err) || "Could not open the file." }, 400);
474
+ }
475
+ };
373
476
 
374
- if (req.method === "POST" && path === "/integrations/disconnect") {
375
- const body = await readJson(req);
376
- const connectorId = typeof body.connectorId === "string" ? body.connectorId.trim() : "";
377
- if (!connectorId) return json({ error: "connectorId is required." }, 400);
378
- removeConnection(connectorId);
379
- await harness.reloadIntegrations();
380
- return json({ ok: true, items: listPublicIntegrations() });
381
- }
477
+ const route_post_embed = async (req: Request, _url: URL): Promise<Response> => {
478
+ const body = await readJson(req);
479
+ const href = publicHttpHref(typeof body.url === "string" ? body.url : "");
480
+ if (!href) return json({ error: "Only public http and https URLs can embed." }, 400);
481
+ try {
482
+ return await fetchPreview(href);
483
+ } catch (err) {
484
+ return json({ error: errorMessage(err) || "Preview fetch failed." }, 502);
485
+ }
486
+ };
382
487
 
383
- if (req.method === "POST" && path === "/open") {
384
- const body = await readJson(req);
385
- const parsed = parseHttpUrl(typeof body.url === "string" ? body.url : "");
386
- if (!parsed) return json({ error: "Only http and https links can open." }, 400);
387
- openUrl(parsed.toString());
388
- return json({ ok: true });
389
- }
488
+ const route_get_embed = async (_req: Request, url: URL): Promise<Response> => {
489
+ const href = publicHttpHref(url.searchParams.get("url") ?? "");
490
+ if (!href) return json({ error: "Only public http and https URLs can embed." }, 400);
491
+ try {
492
+ return await fetchPreview(href);
493
+ } catch (err) {
494
+ return json({ error: errorMessage(err) || "Preview fetch failed." }, 502);
495
+ }
496
+ };
390
497
 
391
- if (req.method === "POST" && path === "/open-path") {
392
- const body = await readJson(req);
393
- const filePath = typeof body.path === "string" ? body.path.trim() : "";
394
- if (!filePath) return json({ error: "Path is missing." }, 400);
395
- try {
396
- openPath(filePath, body.reveal === true);
397
- return json({ ok: true });
398
- } catch (err) {
399
- return json(
400
- { error: err instanceof Error ? err.message : "Could not open the file." },
401
- 400,
402
- );
403
- }
404
- }
498
+ const route_post_transcribe = async (req: Request, _url: URL): Promise<Response> => {
499
+ if (!harness.hasApiKey) {
500
+ return json({ error: "OpenRouter API key is missing. Add it in Settings." }, 400);
501
+ }
502
+ const body = await readJson(req);
503
+ const data = typeof body.data === "string" ? body.data : "";
504
+ const format = typeof body.format === "string" ? body.format.trim() : "webm";
505
+ if (!data) return json({ error: "Recording is empty." }, 400);
506
+ if (data.length > 25_000_000) return json({ error: "Recording is too large." }, 413);
507
+ try {
508
+ const or = resolveOpenRouter(harness.config);
509
+ const text = await transcribeAudio({
510
+ data,
511
+ format: format || "webm",
512
+ model: readMediaPrefs().transcribeModel,
513
+ apiKey: or.apiKey,
514
+ baseUrl: or.baseUrl,
515
+ });
516
+ return json({ text });
517
+ } catch (err) {
518
+ return json({ error: errorMessage(err) || "Transcription failed." }, 502);
519
+ }
520
+ };
405
521
 
406
- if (req.method === "POST" && path === "/embed") {
407
- const body = await readJson(req);
408
- const href = publicHttpHref(typeof body.url === "string" ? body.url : "");
409
- if (!href) return json({ error: "Only public http and https URLs can embed." }, 400);
410
- try {
411
- return await fetchPreview(href);
412
- } catch (err) {
413
- return json({ error: err instanceof Error ? err.message : "Preview fetch failed." }, 502);
414
- }
415
- }
522
+ const route_post_settings = async (req: Request, _url: URL): Promise<Response> => {
523
+ const body = await readJson(req);
524
+ if (typeof body.apiKey === "string") {
525
+ writeOpenRouterKey(body.apiKey);
526
+ harness.setApiKey(body.apiKey);
527
+ refreshLiveNames();
528
+ }
529
+ if (typeof body.mode === "string") {
530
+ const next = tryParseAgentMode(body.mode);
531
+ if (!next) return json({ error: "Mode is ask, plan, or agent." }, 400);
532
+ harness.setMode(next);
533
+ }
534
+ if (typeof body.modelId === "string" && body.modelId.trim()) {
535
+ harness.setModel(body.modelId.trim());
536
+ }
537
+ saveProviderOAuth(body, "google");
538
+ saveProviderOAuth(body, "microsoft");
539
+ return json({
540
+ ok: true,
541
+ ...settingsPayload(harness),
542
+ state: snapshot(harness, busy, title),
543
+ });
544
+ };
416
545
 
417
- if (req.method === "GET" && path === "/embed") {
418
- const href = publicHttpHref(url.searchParams.get("url") ?? "");
419
- if (!href) return json({ error: "Only public http and https URLs can embed." }, 400);
420
- try {
421
- return await fetchPreview(href);
422
- } catch (err) {
423
- return json({ error: err instanceof Error ? err.message : "Preview fetch failed." }, 502);
424
- }
425
- }
546
+ const route_get_slash = async (_req: Request, url: URL): Promise<Response> => {
547
+ const { filterSlashCommands } = await import("../cli/slash.ts");
548
+ return json({ items: filterSlashCommands(url.searchParams.get("q") ?? "/") });
549
+ };
426
550
 
427
- if (req.method === "POST" && path === "/transcribe") {
428
- if (!harness.hasApiKey) {
429
- return json({ error: "OpenRouter API key is missing. Add it in Settings." }, 400);
430
- }
431
- const body = await readJson(req);
432
- const data = typeof body.data === "string" ? body.data : "";
433
- const format = typeof body.format === "string" ? body.format.trim() : "webm";
434
- if (!data) return json({ error: "Recording is empty." }, 400);
435
- if (data.length > 25_000_000) return json({ error: "Recording is too large." }, 413);
436
- try {
437
- const or = resolveOpenRouter(harness.config);
438
- const text = await transcribeAudio({
439
- data,
440
- format: format || "webm",
441
- model: readMediaPrefs().transcribeModel,
442
- apiKey: or.apiKey,
443
- baseUrl: or.baseUrl,
444
- });
445
- return json({ text });
446
- } catch (err) {
447
- return json({ error: err instanceof Error ? err.message : "Transcription failed." }, 502);
448
- }
449
- }
551
+ const route_post_session = async (req: Request, _url: URL): Promise<Response> => {
552
+ const body = await readJson(req);
553
+ if (body.clear === true) {
554
+ harness.setSession(undefined);
555
+ title = "New chat";
556
+ return json({ ok: true, state: snapshot(harness, busy, title) });
557
+ }
558
+ const id = typeof body.id === "string" ? body.id.trim() : "";
559
+ if (typeof body.title === "string") return renameSessionHttp(id, body.title);
560
+ if (body.delete === true) return deleteSessionHttp(id);
561
+ const result = await applySession(id);
562
+ if (!result.ok) return json({ error: result.error }, 404);
563
+ const session = await harness.store.get(id);
564
+ return json({
565
+ ok: true,
566
+ state: snapshot(harness, busy, title),
567
+ messages: chatMessages(session),
568
+ });
569
+ };
450
570
 
451
- if (req.method === "POST" && path === "/settings") {
452
- const body = await readJson(req);
453
- if (typeof body.apiKey === "string") {
454
- writeOpenRouterKey(body.apiKey);
455
- harness.setApiKey(body.apiKey);
456
- refreshLiveNames();
457
- }
458
- if (typeof body.mode === "string") {
459
- const next = tryParseAgentMode(body.mode);
460
- if (!next) return json({ error: "Mode is ask, plan, or agent." }, 400);
461
- harness.setMode(next);
462
- }
463
- if (typeof body.modelId === "string" && body.modelId.trim()) {
464
- harness.setModel(body.modelId.trim());
465
- }
466
- saveProviderOAuth(body, "google");
467
- saveProviderOAuth(body, "microsoft");
468
- return json({
469
- ok: true,
470
- ...settingsPayload(harness),
471
- state: snapshot(harness, busy, title),
472
- });
473
- }
571
+ const renameSessionHttp = async (id: string, rawTitle: string): Promise<Response> => {
572
+ if (!id) return json({ error: "Session id is required." }, 400);
573
+ const nextTitle = normalizeSessionTitle(rawTitle);
574
+ if (!nextTitle) return json({ error: "Title is empty." }, 400);
575
+ const session = await harness.store.get(id);
576
+ if (!session) return json({ error: `No session ${id}` }, 404);
577
+ const next = await harness.store.setTitle(session, nextTitle);
578
+ if (harness.activeSessionId === id) title = next.title;
579
+ return json({ ok: true, title: next.title, state: snapshot(harness, busy, title) });
580
+ };
474
581
 
475
- if (req.method === "GET" && path === "/slash") {
476
- const { filterSlashCommands } = await import("../cli/slash.ts");
477
- return json({ items: filterSlashCommands(url.searchParams.get("q") ?? "/") });
478
- }
582
+ const deleteSessionHttp = async (id: string): Promise<Response> => {
583
+ if (!id) return json({ error: "Session id is required." }, 400);
584
+ if (busy && harness.activeSessionId === id) {
585
+ return json({ error: "A turn is already running." }, 409);
586
+ }
587
+ const wasActive = harness.activeSessionId === id;
588
+ const removed = await harness.store.remove(id);
589
+ if (!removed) return json({ error: `No session ${id}` }, 404);
590
+ if (wasActive) {
591
+ harness.setSession(undefined);
592
+ title = "New chat";
593
+ }
594
+ return json({
595
+ ok: true,
596
+ cleared: wasActive,
597
+ state: snapshot(harness, busy, title),
598
+ });
599
+ };
479
600
 
480
- if (req.method === "POST" && path === "/session") {
481
- const body = await readJson(req);
482
- if (body.clear === true) {
483
- harness.setSession(undefined);
484
- title = "New chat";
485
- return json({ ok: true, state: snapshot(harness, busy, title) });
486
- }
487
- const id = typeof body.id === "string" ? body.id.trim() : "";
488
- if (typeof body.title === "string") {
489
- if (!id) return json({ error: "Session id is required." }, 400);
490
- const nextTitle = normalizeSessionTitle(body.title);
491
- if (!nextTitle) return json({ error: "Title is empty." }, 400);
492
- const session = await harness.store.get(id);
493
- if (!session) return json({ error: `No session ${id}` }, 404);
494
- const next = await harness.store.setTitle(session, nextTitle);
495
- if (harness.activeSessionId === id) title = next.title;
496
- return json({ ok: true, title: next.title, state: snapshot(harness, busy, title) });
497
- }
498
- if (body.delete === true) {
499
- if (!id) return json({ error: "Session id is required." }, 400);
500
- if (busy && harness.activeSessionId === id) {
501
- return json({ error: "A turn is already running." }, 409);
502
- }
503
- const wasActive = harness.activeSessionId === id;
504
- const removed = await harness.store.remove(id);
505
- if (!removed) return json({ error: `No session ${id}` }, 404);
506
- if (wasActive) {
507
- harness.setSession(undefined);
508
- title = "New chat";
509
- }
510
- return json({
511
- ok: true,
512
- cleared: wasActive,
513
- state: snapshot(harness, busy, title),
514
- });
515
- }
516
- const result = await applySession(id);
517
- if (!result.ok) return json({ error: result.error }, 404);
518
- const session = await harness.store.get(id);
519
- return json({
520
- ok: true,
521
- state: snapshot(harness, busy, title),
522
- messages: chatMessages(session),
523
- });
524
- }
601
+ const route_post_model = async (req: Request, _url: URL): Promise<Response> => {
602
+ const body = await readJson(req);
603
+ const id = typeof body.id === "string" ? body.id.trim() : "";
604
+ if (!id) return json({ error: "Model id is required." }, 400);
605
+ harness.setModel(id);
606
+ return json({ ok: true, state: snapshot(harness, busy, title) });
607
+ };
525
608
 
526
- if (req.method === "POST" && path === "/model") {
527
- const body = await readJson(req);
528
- const id = typeof body.id === "string" ? body.id.trim() : "";
529
- if (!id) return json({ error: "Model id is required." }, 400);
530
- harness.setModel(id);
531
- return json({ ok: true, state: snapshot(harness, busy, title) });
532
- }
609
+ const route_post_mode = async (req: Request, _url: URL): Promise<Response> => {
610
+ const body = await readJson(req);
611
+ const next = tryParseAgentMode(typeof body.mode === "string" ? body.mode : undefined);
612
+ if (!next) return json({ error: "Mode is ask, plan, or agent." }, 400);
613
+ harness.setMode(next);
614
+ return json({ ok: true, state: snapshot(harness, busy, title) });
615
+ };
533
616
 
534
- if (req.method === "POST" && path === "/mode") {
535
- const body = await readJson(req);
536
- const next = tryParseAgentMode(typeof body.mode === "string" ? body.mode : undefined);
537
- if (!next) return json({ error: "Mode is ask, plan, or agent." }, 400);
538
- harness.setMode(next);
539
- return json({ ok: true, state: snapshot(harness, busy, title) });
540
- }
617
+ const route_post_slash = async (req: Request, _url: URL): Promise<Response> => {
618
+ const body = await readJson(req);
619
+ const raw = typeof body.raw === "string" ? body.raw : "";
620
+ if (!raw.trim()) return json({ error: "Command is empty." }, 400);
621
+ const outcome = await runSlashLine(harness, raw);
622
+ if (outcome.kind === "clear") title = "New chat";
623
+ if (outcome.kind === "session") {
624
+ harness.setSession(outcome.session.id);
625
+ if (outcome.session.model) harness.setModel(outcome.session.model);
626
+ title = outcome.session.title.trim() || "New chat";
627
+ }
628
+ return json({ outcome, state: snapshot(harness, busy, title) });
629
+ };
541
630
 
542
- if (req.method === "POST" && path === "/slash") {
543
- const body = await readJson(req);
544
- const raw = typeof body.raw === "string" ? body.raw : "";
545
- if (!raw.trim()) return json({ error: "Command is empty." }, 400);
546
- const outcome = await runSlashLine(harness, raw);
547
- if (outcome.kind === "clear") title = "New chat";
548
- if (outcome.kind === "session") {
549
- harness.setSession(outcome.session.id);
550
- if (outcome.session.model) harness.setModel(outcome.session.model);
551
- title = outcome.session.title.trim() || "New chat";
552
- }
553
- return json({ outcome, state: snapshot(harness, busy, title) });
554
- }
631
+ const route_post_picker = async (req: Request, _url: URL): Promise<Response> => {
632
+ const body = await readJson(req);
633
+ const picker = isSlashPickerKind(body.picker) ? body.picker : undefined;
634
+ const id = typeof body.id === "string" ? body.id : "";
635
+ if (!picker || !id) return json({ error: "Picker choice is incomplete." }, 400);
636
+ const result = await applyPickerChoice(harness, picker, id);
637
+ if (result.kind === "session-id") {
638
+ const applied = await applySession(result.id);
639
+ if (!applied.ok) return json({ error: applied.error }, 404);
640
+ const session = await harness.store.get(result.id);
641
+ return json({
642
+ ok: true,
643
+ state: snapshot(harness, busy, title),
644
+ messages: chatMessages(session),
645
+ });
646
+ }
647
+ return json({
648
+ ok: true,
649
+ state: snapshot(harness, busy, title),
650
+ ...(result.kind === "text" ? { text: result.text } : {}),
651
+ });
652
+ };
555
653
 
556
- if (req.method === "POST" && path === "/picker") {
557
- const body = await readJson(req);
558
- const picker = isSlashPickerKind(body.picker) ? body.picker : undefined;
559
- const id = typeof body.id === "string" ? body.id : "";
560
- if (!picker || !id) return json({ error: "Picker choice is incomplete." }, 400);
561
- const result = applyPickerChoice(harness, picker, id);
562
- if (result.kind === "session-id") {
563
- const applied = await applySession(result.id);
564
- if (!applied.ok) return json({ error: applied.error }, 404);
565
- const session = await harness.store.get(result.id);
566
- return json({
567
- ok: true,
568
- state: snapshot(harness, busy, title),
569
- messages: chatMessages(session),
570
- });
571
- }
572
- return json({
573
- ok: true,
574
- state: snapshot(harness, busy, title),
575
- ...(result.kind === "text" ? { text: result.text } : {}),
576
- });
577
- }
654
+ const route_post_approve = async (req: Request, _url: URL): Promise<Response> => {
655
+ const body = await readJson(req);
656
+ const callId = typeof body.callId === "string" ? body.callId : "";
657
+ const decision = body.decision;
658
+ const resolve = pending.get(callId);
659
+ if (!resolve) return json({ error: "No approval is waiting." }, 404);
660
+ if (decision === "always")
661
+ harness.allowRiskyAlways(typeof body.toolName === "string" ? body.toolName : "exec");
662
+ pending.delete(callId);
663
+ resolve(decision === "yes" || decision === "always");
664
+ return json({ ok: true });
665
+ };
578
666
 
579
- if (req.method === "POST" && path === "/approve") {
580
- const body = await readJson(req);
581
- const callId = typeof body.callId === "string" ? body.callId : "";
582
- const decision = body.decision;
583
- const resolve = pending.get(callId);
584
- if (!resolve) return json({ error: "No approval is waiting." }, 404);
585
- if (decision === "always")
586
- harness.allowRiskyAlways(typeof body.toolName === "string" ? body.toolName : "exec");
587
- pending.delete(callId);
588
- resolve(decision === "yes" || decision === "always");
589
- return json({ ok: true });
590
- }
667
+ const route_post_abort = async (_req: Request, _url: URL): Promise<Response> => {
668
+ abort?.abort();
669
+ for (const resolve of pending.values()) resolve(false);
670
+ pending.clear();
671
+ return json({ ok: true });
672
+ };
591
673
 
592
- if (req.method === "POST" && path === "/abort") {
593
- abort?.abort();
594
- for (const resolve of pending.values()) resolve(false);
595
- pending.clear();
596
- return json({ ok: true });
597
- }
674
+ const route_post_turn = async (req: Request, _url: URL): Promise<Response> => {
675
+ if (busy) return json({ error: "A turn is already running." }, 409);
676
+ const body = await readJson(req);
677
+ const incoming = typeof body.message === "string" ? body.message : "";
678
+ const editUserTurn = parseEditUserTurn(body.editUserTurn);
679
+ const uploads =
680
+ editUserTurn === undefined && !incoming.trim().startsWith("/")
681
+ ? saveUploads(harness.cwd, parseIncomingUploads(body.attachments))
682
+ : [];
683
+ const message = composeUploadMessage(incoming, uploads);
684
+ if (!message.trim()) return json({ error: "Message is empty." }, 400);
685
+ if (editUserTurn === undefined && isHelpAlias(incoming)) {
686
+ const outcome = await runSlashLine(harness, "/help");
687
+ return json({ outcome, state: snapshot(harness, busy, title) });
688
+ }
689
+ if (editUserTurn === undefined && incoming.trim().startsWith("/")) {
690
+ return runSlashTurn(incoming);
691
+ }
692
+ return startTurnStream(message, editUserTurn);
693
+ };
598
694
 
599
- if (req.method === "POST" && path === "/turn") {
600
- if (busy) return json({ error: "A turn is already running." }, 409);
601
- const body = await readJson(req);
602
- const message = typeof body.message === "string" ? body.message : "";
603
- if (!message.trim()) return json({ error: "Message is empty." }, 400);
604
- const editUserTurn =
605
- typeof body.editUserTurn === "number" &&
606
- Number.isInteger(body.editUserTurn) &&
607
- body.editUserTurn >= 0
608
- ? body.editUserTurn
609
- : undefined;
610
- if (editUserTurn === undefined && isHelpAlias(message)) {
611
- const outcome = await runSlashLine(harness, "/help");
612
- return json({ outcome, state: snapshot(harness, busy, title) });
613
- }
614
- if (editUserTurn === undefined && message.trim().startsWith("/")) {
615
- const outcome = await runSlashLine(harness, message);
616
- if (outcome.kind === "clear") title = "New chat";
617
- if (outcome.kind === "session") {
618
- harness.setSession(outcome.session.id);
619
- if (outcome.session.model) harness.setModel(outcome.session.model);
620
- title = outcome.session.title.trim() || "New chat";
621
- }
622
- return json({ outcome, state: snapshot(harness, busy, title) });
623
- }
624
-
625
- busy = true;
626
- abort = new AbortController();
627
- const encoder = new TextEncoder();
628
- const stream = new ReadableStream<Uint8Array>({
629
- start(controller) {
630
- let heartbeat: ReturnType<typeof setInterval> | undefined;
631
- const send = (event: AgentEvent) => {
632
- if (event.kind === "session_meta") title = event.title;
633
- try {
634
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
635
- } catch {
636
- abort?.abort();
637
- }
638
- };
639
- heartbeat = setInterval(() => {
640
- try {
641
- controller.enqueue(encoder.encode(": \n\n"));
642
- } catch {
643
- if (heartbeat) clearInterval(heartbeat);
644
- }
645
- }, 4_000);
646
- void harness
647
- .runTurn(message, send, {
648
- signal: abort?.signal,
649
- approvalAsk: (req: ApprovalRequest) =>
650
- new Promise<boolean>((resolve) => {
651
- pending.set(req.callId, resolve);
652
- }),
653
- ...(editUserTurn !== undefined ? { editUserTurn } : {}),
654
- })
655
- .catch((err) => {
656
- send({
657
- kind: "error",
658
- message: err instanceof Error ? err.message : String(err),
659
- });
660
- })
661
- .finally(() => {
662
- if (heartbeat) clearInterval(heartbeat);
663
- busy = false;
664
- abort = undefined;
665
- pending.clear();
666
- try {
667
- controller.close();
668
- } catch {
669
- // already cancelled by the client
670
- }
671
- });
672
- },
673
- cancel() {
695
+ const parseEditUserTurn = (value: unknown): number | undefined => {
696
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) return undefined;
697
+ return value;
698
+ };
699
+
700
+ const runSlashTurn = async (incoming: string): Promise<Response> => {
701
+ const outcome = await runSlashLine(harness, incoming);
702
+ if (outcome.kind === "clear") title = "New chat";
703
+ if (outcome.kind === "session") {
704
+ harness.setSession(outcome.session.id);
705
+ if (outcome.session.model) harness.setModel(outcome.session.model);
706
+ title = outcome.session.title.trim() || "New chat";
707
+ }
708
+ return json({ outcome, state: snapshot(harness, busy, title) });
709
+ };
710
+
711
+ const startTurnStream = (message: string, editUserTurn?: number): Response => {
712
+ busy = true;
713
+ abort = new AbortController();
714
+ const encoder = new TextEncoder();
715
+ const stream = new ReadableStream<Uint8Array>({
716
+ start(controller) {
717
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
718
+ const send = (event: AgentEvent) => {
719
+ if (event.kind === "session_meta") title = event.title;
720
+ try {
721
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
722
+ } catch {
674
723
  abort?.abort();
675
- },
676
- });
677
- return new Response(stream, {
678
- headers: {
679
- "content-type": "text/event-stream",
680
- "cache-control": "no-cache",
681
- ...CORS_HEADERS,
682
- },
683
- });
684
- }
724
+ }
725
+ };
726
+ heartbeat = setInterval(() => {
727
+ try {
728
+ controller.enqueue(encoder.encode(": \n\n"));
729
+ } catch {
730
+ if (heartbeat) clearInterval(heartbeat);
731
+ }
732
+ }, 4_000);
733
+ void harness
734
+ .runTurn(message, send, {
735
+ signal: abort?.signal,
736
+ approvalAsk: (req: ApprovalRequest) =>
737
+ new Promise<boolean>((resolve) => {
738
+ pending.set(req.callId, resolve);
739
+ }),
740
+ ...(editUserTurn !== undefined ? { editUserTurn } : {}),
741
+ })
742
+ .catch((err) => {
743
+ send({
744
+ kind: "error",
745
+ message: errorMessage(err),
746
+ });
747
+ })
748
+ .finally(() => {
749
+ if (heartbeat) clearInterval(heartbeat);
750
+ busy = false;
751
+ abort = undefined;
752
+ pending.clear();
753
+ try {
754
+ controller.close();
755
+ } catch {
756
+ // already cancelled by the client
757
+ }
758
+ });
759
+ },
760
+ cancel() {
761
+ abort?.abort();
762
+ },
763
+ });
764
+ return new Response(stream, {
765
+ headers: {
766
+ "content-type": "text/event-stream",
767
+ "cache-control": "no-cache",
768
+ ...CORS_HEADERS,
769
+ },
770
+ });
771
+ };
772
+
773
+ const bridgeRoutes: Record<string, (req: Request, url: URL) => Promise<Response>> = {
774
+ "GET /health": route_get_health,
775
+ "GET /state": route_get_state,
776
+ "GET /sessions": route_get_sessions,
777
+ "GET /models": route_get_models,
778
+ "GET /settings": route_get_settings,
779
+ "GET /integrations": route_get_integrations,
780
+ "POST /integrations/connect": route_post_integrations_connect,
781
+ "POST /integrations/disconnect": route_post_integrations_disconnect,
782
+ "GET /skills": route_get_skills,
783
+ "GET /skills/popular": route_get_skills_popular,
784
+ "GET /skills/search": route_get_skills_search,
785
+ "POST /skills/add": route_post_skills_add,
786
+ "POST /skills/remove": route_post_skills_remove,
787
+ "POST /open": route_post_open,
788
+ "POST /open-path": route_post_open_path,
789
+ "POST /embed": route_post_embed,
790
+ "GET /embed": route_get_embed,
791
+ "POST /transcribe": route_post_transcribe,
792
+ "POST /settings": route_post_settings,
793
+ "GET /slash": route_get_slash,
794
+ "POST /session": route_post_session,
795
+ "POST /model": route_post_model,
796
+ "POST /mode": route_post_mode,
797
+ "POST /slash": route_post_slash,
798
+ "POST /picker": route_post_picker,
799
+ "POST /approve": route_post_approve,
800
+ "POST /abort": route_post_abort,
801
+ "POST /turn": route_post_turn,
802
+ };
685
803
 
686
- return json({ error: "Not found." }, 404);
804
+ const server = Bun.serve({
805
+ hostname: host,
806
+ port: options.port ?? 0,
807
+ idleTimeout: 0,
808
+ async fetch(req) {
809
+ if (req.method === "OPTIONS") {
810
+ return new Response(null, { status: 204, headers: CORS_HEADERS });
811
+ }
812
+ const url = new URL(req.url);
813
+ if (req.method === "GET" && url.pathname === "/oauth/callback") {
814
+ return handleOAuthCallback(req, url);
815
+ }
816
+ if (readToken(req) !== token) {
817
+ return json({ error: `Unauthorized. Restart ${PRODUCT_NAME}.` }, 401);
818
+ }
819
+ const matched = bridgeRoutes[`${req.method} ${url.pathname}`];
820
+ if (!matched) return json({ error: "Not found." }, 404);
821
+ return matched(req, url);
687
822
  },
688
823
  });
689
824
 
@@ -722,8 +857,10 @@ export async function main(): Promise<void> {
722
857
  }
723
858
 
724
859
  if (import.meta.main) {
725
- main().catch((err) => {
726
- process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
860
+ try {
861
+ await main();
862
+ } catch (err) {
863
+ process.stderr.write(`${errorMessage(err)}\n`);
727
864
  process.exit(1);
728
- });
865
+ }
729
866
  }