@useavalon/caelence-agent 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.
Files changed (161) hide show
  1. package/README.md +201 -0
  2. package/bin/harness.ts +10 -0
  3. package/package.json +75 -0
  4. package/skills/copy-editor/SKILL.md +74 -0
  5. package/skills/copy-editor/references/anti-slop.md +62 -0
  6. package/skills/copy-editor/references/ui-states.md +46 -0
  7. package/skills/copy-editor/scripts/lint-copy.py +78 -0
  8. package/skills/copy-harry-dry/SKILL.md +120 -0
  9. package/skills/copy-rmbc/SKILL.md +97 -0
  10. package/skills/copywriting/SKILL.md +73 -0
  11. package/skills/impeccable/SKILL.md +133 -0
  12. package/skills/impeccable/references/visual-slop.md +36 -0
  13. package/src/cli/main.test.ts +36 -0
  14. package/src/cli/main.ts +384 -0
  15. package/src/cli/media-models.ts +82 -0
  16. package/src/cli/models.ts +43 -0
  17. package/src/cli/openrouter-live.test.ts +35 -0
  18. package/src/cli/openrouter-live.ts +72 -0
  19. package/src/cli/openrouter-modality.test.ts +25 -0
  20. package/src/cli/openrouter-modality.ts +83 -0
  21. package/src/cli/picker.test.ts +53 -0
  22. package/src/cli/picker.ts +48 -0
  23. package/src/cli/plain-text.ts +15 -0
  24. package/src/cli/slash-dispatch.test.ts +213 -0
  25. package/src/cli/slash-dispatch.ts +298 -0
  26. package/src/cli/slash.test.ts +113 -0
  27. package/src/cli/slash.ts +119 -0
  28. package/src/cli/theme.test.ts +10 -0
  29. package/src/cli/theme.ts +44 -0
  30. package/src/cli/tui-layout.test.ts +33 -0
  31. package/src/cli/tui-layout.ts +33 -0
  32. package/src/cli/tui-screen.test.ts +33 -0
  33. package/src/cli/tui-screen.ts +13 -0
  34. package/src/cli/tui.tsx +735 -0
  35. package/src/config.ts +86 -0
  36. package/src/core/approval.test.ts +60 -0
  37. package/src/core/approval.ts +83 -0
  38. package/src/core/auto-router.test.ts +31 -0
  39. package/src/core/auto-router.ts +66 -0
  40. package/src/core/errors.ts +67 -0
  41. package/src/core/events.ts +85 -0
  42. package/src/core/hooks.test.ts +66 -0
  43. package/src/core/hooks.ts +94 -0
  44. package/src/core/ids.ts +6 -0
  45. package/src/core/instructions.test.ts +49 -0
  46. package/src/core/instructions.ts +44 -0
  47. package/src/core/logger.ts +45 -0
  48. package/src/core/mcp.ts +191 -0
  49. package/src/core/mode.test.ts +63 -0
  50. package/src/core/mode.ts +60 -0
  51. package/src/core/run-turn.test.ts +339 -0
  52. package/src/core/run-turn.ts +487 -0
  53. package/src/core/session.test.ts +203 -0
  54. package/src/core/session.ts +349 -0
  55. package/src/core/stdio-mcp.ts +143 -0
  56. package/src/core/strands.ts +262 -0
  57. package/src/core/usage.test.ts +69 -0
  58. package/src/core/usage.ts +171 -0
  59. package/src/desktop/bridge.test.ts +331 -0
  60. package/src/desktop/bridge.ts +729 -0
  61. package/src/desktop/open-local.test.ts +40 -0
  62. package/src/desktop/open-local.ts +52 -0
  63. package/src/desktop/preview-cache.test.ts +36 -0
  64. package/src/desktop/preview-cache.ts +63 -0
  65. package/src/desktop/secrets.test.ts +44 -0
  66. package/src/desktop/secrets.ts +60 -0
  67. package/src/evals/runner.test.ts +43 -0
  68. package/src/evals/runner.ts +225 -0
  69. package/src/index.ts +132 -0
  70. package/src/init.test.ts +54 -0
  71. package/src/init.ts +117 -0
  72. package/src/integrations/catalog-data.json +424 -0
  73. package/src/integrations/catalog.ts +81 -0
  74. package/src/integrations/connect.ts +231 -0
  75. package/src/integrations/integrations.test.ts +329 -0
  76. package/src/integrations/marks/airtable.svg +1 -0
  77. package/src/integrations/marks/algolia-mcp.svg +1 -0
  78. package/src/integrations/marks/canva.jpg +0 -0
  79. package/src/integrations/marks/cloudflare-mcp.svg +1 -0
  80. package/src/integrations/marks/contentful-mcp.svg +1 -0
  81. package/src/integrations/marks/craft.png +0 -0
  82. package/src/integrations/marks/dinero.png +0 -0
  83. package/src/integrations/marks/figma.svg +1 -0
  84. package/src/integrations/marks/gitlab.svg +1 -0
  85. package/src/integrations/marks/google-calendar.svg +1 -0
  86. package/src/integrations/marks/google-docs.svg +1 -0
  87. package/src/integrations/marks/google-drive.svg +1 -0
  88. package/src/integrations/marks/google-gmail.svg +1 -0
  89. package/src/integrations/marks/google-sheets.svg +1 -0
  90. package/src/integrations/marks/google-slides.svg +1 -0
  91. package/src/integrations/marks/granola.png +0 -0
  92. package/src/integrations/marks/jira.svg +1 -0
  93. package/src/integrations/marks/linear.svg +1 -0
  94. package/src/integrations/marks/microsoft-365.svg +7 -0
  95. package/src/integrations/marks/miro.svg +1 -0
  96. package/src/integrations/marks/mixpanel-mcp.svg +1 -0
  97. package/src/integrations/marks/monday.png +0 -0
  98. package/src/integrations/marks/mux-mcp.png +0 -0
  99. package/src/integrations/marks/neon-mcp.svg +1 -0
  100. package/src/integrations/marks/notion.svg +1 -0
  101. package/src/integrations/marks/paddle-mcp.svg +1 -0
  102. package/src/integrations/marks/posthog-mcp.svg +1 -0
  103. package/src/integrations/marks/prismic-mcp.svg +1 -0
  104. package/src/integrations/marks/replicate-mcp.svg +1 -0
  105. package/src/integrations/marks/resend-mcp.svg +1 -0
  106. package/src/integrations/marks/sanity-mcp.svg +1 -0
  107. package/src/integrations/marks/sceneplane.png +0 -0
  108. package/src/integrations/marks/sentry-mcp.svg +1 -0
  109. package/src/integrations/marks/stripe-mcp.svg +1 -0
  110. package/src/integrations/marks/supabase-mcp.svg +1 -0
  111. package/src/integrations/marks/upstash-mcp.svg +1 -0
  112. package/src/integrations/marks/vercel.svg +1 -0
  113. package/src/integrations/marks/webflow.svg +1 -0
  114. package/src/integrations/mcp-oauth.test.ts +39 -0
  115. package/src/integrations/mcp-oauth.ts +330 -0
  116. package/src/integrations/oauth-clients.test.ts +77 -0
  117. package/src/integrations/oauth-clients.ts +127 -0
  118. package/src/integrations/oauth.ts +145 -0
  119. package/src/integrations/remote-mcp.ts +307 -0
  120. package/src/integrations/store.ts +149 -0
  121. package/src/media/openrouter-generate.test.ts +80 -0
  122. package/src/media/openrouter-generate.ts +178 -0
  123. package/src/media/prefs.ts +54 -0
  124. package/src/observability/categories.ts +41 -0
  125. package/src/observability/create.test.ts +56 -0
  126. package/src/observability/create.ts +45 -0
  127. package/src/observability/experiments.ts +113 -0
  128. package/src/observability/fake.ts +191 -0
  129. package/src/observability/index.ts +57 -0
  130. package/src/observability/judges.ts +91 -0
  131. package/src/observability/langfuse.ts +275 -0
  132. package/src/observability/noop.ts +33 -0
  133. package/src/observability/observability.test.ts +113 -0
  134. package/src/observability/prompts.ts +98 -0
  135. package/src/observability/regression-items.ts +158 -0
  136. package/src/observability/sanitize.test.ts +26 -0
  137. package/src/observability/sanitize.ts +57 -0
  138. package/src/observability/types.ts +122 -0
  139. package/src/observability/version.ts +41 -0
  140. package/src/product.ts +2 -0
  141. package/src/runtime.test.ts +98 -0
  142. package/src/runtime.ts +438 -0
  143. package/src/skills/author-skill.ts +49 -0
  144. package/src/skills/create-skill.test.ts +108 -0
  145. package/src/skills/create-skill.ts +70 -0
  146. package/src/skills/loader.test.ts +122 -0
  147. package/src/skills/loader.ts +162 -0
  148. package/src/skills/registry.test.ts +190 -0
  149. package/src/skills/registry.ts +402 -0
  150. package/src/skills/skill-command.ts +53 -0
  151. package/src/skills/user-dir.ts +8 -0
  152. package/src/tools/git.test.ts +71 -0
  153. package/src/tools/git.ts +126 -0
  154. package/src/tools/local.ts +258 -0
  155. package/src/tools/paths.test.ts +24 -0
  156. package/src/tools/paths.ts +39 -0
  157. package/src/tools/read-skill.ts +43 -0
  158. package/src/tools/subagent.test.ts +77 -0
  159. package/src/tools/subagent.ts +74 -0
  160. package/src/tools/todo.test.ts +25 -0
  161. package/src/tools/todo.ts +70 -0
@@ -0,0 +1,729 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mediaModelLabel } from "../cli/media-models.ts";
3
+ import { HARNESS_MODELS, modelPickerItems } from "../cli/models.ts";
4
+ import { cachedLiveTargetNames, loadLiveTargetNames } from "../cli/openrouter-live.ts";
5
+ import { cachedModalityModels } from "../cli/openrouter-modality.ts";
6
+ import { sessionPickerItems } from "../cli/picker.ts";
7
+ import { isHelpAlias } from "../cli/slash.ts";
8
+ import { applyPickerChoice, isSlashPickerKind, runSlashLine } from "../cli/slash-dispatch.ts";
9
+ import { resolveOpenRouter } from "../config.ts";
10
+ import type { ApprovalRequest } from "../core/approval.ts";
11
+ import type { AgentEvent } from "../core/events.ts";
12
+ import { tryParseAgentMode } from "../core/mode.ts";
13
+ import { normalizeSessionTitle, type Session, sessionTranscript } from "../core/session.ts";
14
+ import { formatUsage } from "../core/usage.ts";
15
+ import {
16
+ connectMcp,
17
+ type OAuthCallback,
18
+ oauthResultPage,
19
+ openSystemBrowser,
20
+ } from "../integrations/connect.ts";
21
+ import { readProviderOAuth, writeProviderOAuth } from "../integrations/oauth-clients.ts";
22
+ import { listPublicIntegrations, removeConnection } from "../integrations/store.ts";
23
+ import { transcribeAudio } from "../media/openrouter-generate.ts";
24
+ import { readMediaPrefs } from "../media/prefs.ts";
25
+ import { PRODUCT_NAME } from "../product.ts";
26
+ import { createHarness, type HarnessRuntime } from "../runtime.ts";
27
+ import { openResolvedPath, resolveLocalPath } from "./open-local.ts";
28
+ import { readPreviewCache, writePreviewCache } from "./preview-cache.ts";
29
+ import { applyStoredOpenRouterKey, maskSecret, writeOpenRouterKey } from "./secrets.ts";
30
+
31
+ export interface DesktopState {
32
+ name: string;
33
+ cwd: string;
34
+ mode: string;
35
+ modelId: string;
36
+ modelLabel: string;
37
+ modelTarget?: string;
38
+ imageModelId: string;
39
+ imageModelLabel: string;
40
+ videoModelId: string;
41
+ videoModelLabel: string;
42
+ transcribeModelId: string;
43
+ transcribeModelLabel: string;
44
+ sessionId?: string;
45
+ title: string;
46
+ spend?: string;
47
+ skills: Array<{ name: string; source: string }>;
48
+ busy: boolean;
49
+ hasApiKey: boolean;
50
+ }
51
+
52
+ export interface BridgeReady {
53
+ url: string;
54
+ token: string;
55
+ port: number;
56
+ }
57
+
58
+ export interface StartDesktopBridgeOptions {
59
+ cwd: string;
60
+ host?: string;
61
+ port?: number;
62
+ token?: string;
63
+ harness?: HarnessRuntime;
64
+ openUrl?: (url: string) => void;
65
+ openPath?: (path: string, reveal: boolean) => void;
66
+ }
67
+
68
+ const CORS_HEADERS = {
69
+ "access-control-allow-origin": "*",
70
+ "access-control-allow-headers": "authorization, content-type",
71
+ "access-control-allow-methods": "GET, POST, OPTIONS",
72
+ };
73
+
74
+ function modelLabel(id: string): string {
75
+ return HARNESS_MODELS.find((model) => model.id === id)?.label ?? id;
76
+ }
77
+
78
+ function settingsPayload(harness: HarnessRuntime) {
79
+ const google = readProviderOAuth("google");
80
+ const microsoft = readProviderOAuth("microsoft");
81
+ return {
82
+ hasApiKey: harness.hasApiKey,
83
+ apiKeyHint: harness.hasApiKey ? maskSecret(process.env.OPENROUTER_API_KEY ?? "") : "",
84
+ mode: harness.mode,
85
+ modelId: harness.modelId,
86
+ modelLabel: modelLabel(harness.modelId),
87
+ hasGoogleOAuth: Boolean(google?.clientId),
88
+ googleOAuthHint: google?.clientId ? maskSecret(google.clientId) : "",
89
+ hasMicrosoftOAuth: Boolean(microsoft?.clientId),
90
+ microsoftOAuthHint: microsoft?.clientId ? maskSecret(microsoft.clientId) : "",
91
+ };
92
+ }
93
+
94
+ function saveProviderOAuth(body: Record<string, unknown>, kind: "google" | "microsoft"): void {
95
+ const idKey = kind === "google" ? "googleClientId" : "microsoftClientId";
96
+ const secretKey = kind === "google" ? "googleClientSecret" : "microsoftClientSecret";
97
+ const clientId = typeof body[idKey] === "string" ? body[idKey].trim() : "";
98
+ const clientSecret = typeof body[secretKey] === "string" ? body[secretKey].trim() : "";
99
+ if (!clientId && !clientSecret) return;
100
+ writeProviderOAuth(kind, {
101
+ ...(clientId ? { clientId } : {}),
102
+ ...(clientSecret ? { clientSecret } : {}),
103
+ });
104
+ }
105
+
106
+ function chatMessages(session: Session | undefined) {
107
+ return session ? sessionTranscript(session) : [];
108
+ }
109
+
110
+ function json(data: unknown, status = 200, extra?: HeadersInit): Response {
111
+ return new Response(JSON.stringify(data), {
112
+ status,
113
+ headers: {
114
+ "content-type": "application/json",
115
+ ...CORS_HEADERS,
116
+ ...extra,
117
+ },
118
+ });
119
+ }
120
+
121
+ function readToken(req: Request): string | undefined {
122
+ const header = req.headers.get("authorization");
123
+ if (header?.startsWith("Bearer ")) return header.slice("Bearer ".length).trim();
124
+ return new URL(req.url).searchParams.get("token") ?? undefined;
125
+ }
126
+
127
+ function parseHttpUrl(raw: string): URL | null {
128
+ try {
129
+ const parsed = new URL(raw.trim());
130
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
131
+ return parsed;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+
137
+ function publicHttpHref(raw: string): string | null {
138
+ const href = raw.trim();
139
+ const parsed = parseHttpUrl(href);
140
+ if (!parsed) return null;
141
+ const host = parsed.hostname.toLowerCase();
142
+ if (
143
+ host === "localhost" ||
144
+ host === "127.0.0.1" ||
145
+ host === "[::1]" ||
146
+ host === "::1" ||
147
+ host.endsWith(".local")
148
+ ) {
149
+ return null;
150
+ }
151
+ return href;
152
+ }
153
+
154
+ async function fetchPreview(href: string): Promise<Response> {
155
+ const cached = readPreviewCache(href);
156
+ if (cached) return previewBytes(cached.type, cached.bytes);
157
+
158
+ const remote = await fetch(href, {
159
+ headers: {
160
+ Accept: "image/avif,image/webp,image/png,image/jpeg,image/gif,image/*,*/*;q=0.8",
161
+ Referer: "https://www.canva.com/",
162
+ "User-Agent":
163
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.6 Safari/605.1.15",
164
+ },
165
+ redirect: "follow",
166
+ signal: AbortSignal.timeout(15_000),
167
+ });
168
+ if (!remote.ok) {
169
+ const fallback = readPreviewCache(href);
170
+ if (fallback) return previewBytes(fallback.type, fallback.bytes);
171
+ return json({ error: `Preview fetch failed (${remote.status}).` }, 502);
172
+ }
173
+ const type =
174
+ (remote.headers.get("content-type") ?? "application/octet-stream").split(";")[0]?.trim() ??
175
+ "application/octet-stream";
176
+ if (!type.startsWith("image/") && type !== "application/pdf") {
177
+ const fallback = readPreviewCache(href);
178
+ if (fallback) return previewBytes(fallback.type, fallback.bytes);
179
+ return json({ error: "Preview is not an image." }, 502);
180
+ }
181
+ const buffer = await remote.arrayBuffer();
182
+ if (buffer.byteLength > 8 * 1024 * 1024) {
183
+ return json({ error: "Preview is larger than 8 MB." }, 413);
184
+ }
185
+ const bytes = new Uint8Array(buffer);
186
+ writePreviewCache(href, type, bytes);
187
+ return previewBytes(type, bytes);
188
+ }
189
+
190
+ function previewBytes(type: string, bytes: Uint8Array): Response {
191
+ return new Response(Buffer.from(bytes), {
192
+ status: 200,
193
+ headers: {
194
+ "content-type": type,
195
+ "cache-control": "private, max-age=3600",
196
+ ...CORS_HEADERS,
197
+ },
198
+ });
199
+ }
200
+
201
+ async function readJson(req: Request): Promise<Record<string, unknown>> {
202
+ const text = await req.text();
203
+ if (!text.trim()) return {};
204
+ const parsed = JSON.parse(text) as unknown;
205
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
206
+ }
207
+
208
+ function snapshot(harness: HarnessRuntime, busy: boolean, title: string): DesktopState {
209
+ const live = cachedLiveTargetNames();
210
+ const target = live.get(harness.modelId);
211
+ const prefs = readMediaPrefs();
212
+ return {
213
+ name: harness.config.name,
214
+ cwd: harness.cwd,
215
+ mode: harness.mode,
216
+ modelId: harness.modelId,
217
+ modelLabel: modelLabel(harness.modelId),
218
+ ...(target && target.toLowerCase() !== modelLabel(harness.modelId).toLowerCase()
219
+ ? { modelTarget: target }
220
+ : {}),
221
+ imageModelId: prefs.imageModel,
222
+ imageModelLabel: mediaModelLabel(cachedModalityModels("image"), prefs.imageModel),
223
+ videoModelId: prefs.videoModel,
224
+ videoModelLabel: mediaModelLabel(cachedModalityModels("video"), prefs.videoModel),
225
+ transcribeModelId: prefs.transcribeModel,
226
+ transcribeModelLabel: mediaModelLabel(
227
+ cachedModalityModels("transcription"),
228
+ prefs.transcribeModel,
229
+ ),
230
+ sessionId: harness.activeSessionId,
231
+ title,
232
+ spend: harness.spend ? formatUsage(harness.spend) : undefined,
233
+ skills: harness.skills.map((skill) => ({ name: skill.name, source: skill.source })),
234
+ busy,
235
+ hasApiKey: harness.hasApiKey,
236
+ };
237
+ }
238
+
239
+ export async function startDesktopBridge(options: StartDesktopBridgeOptions): Promise<{
240
+ ready: BridgeReady;
241
+ stop: () => Promise<void>;
242
+ }> {
243
+ const host = options.host ?? "127.0.0.1";
244
+ const token = options.token ?? randomBytes(24).toString("hex");
245
+ const openUrl = options.openUrl ?? openSystemBrowser;
246
+ if (!options.harness) applyStoredOpenRouterKey();
247
+ const harness = options.harness ?? (await createHarness({ cwd: options.cwd }));
248
+ const openPath =
249
+ options.openPath ??
250
+ ((path: string, reveal: boolean) => {
251
+ const resolved = resolveLocalPath(path, harness.cwd);
252
+ if (!resolved) throw new Error("File is missing.");
253
+ openResolvedPath(resolved, reveal);
254
+ });
255
+ const ownsHarness = !options.harness;
256
+ let title = "New chat";
257
+ let busy = false;
258
+ let abort: AbortController | undefined;
259
+ const pending = new Map<string, (ok: boolean) => void>();
260
+ const oauthWaiters = new Map<string, (result: OAuthCallback) => void>();
261
+
262
+ const refreshLiveNames = (): void => {
263
+ if (!harness.hasApiKey) return;
264
+ void loadLiveTargetNames(resolveOpenRouter(harness.config));
265
+ };
266
+ refreshLiveNames();
267
+
268
+ const applySession = async (id: string): Promise<{ ok: boolean; error?: string }> => {
269
+ const session = await harness.store.get(id);
270
+ if (!session) return { ok: false, error: `No session ${id}` };
271
+ harness.setSession(session.id);
272
+ if (session.model) harness.setModel(session.model);
273
+ title = session.title.trim() || "New chat";
274
+ return { ok: true };
275
+ };
276
+
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.",
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
+ if (readToken(req) !== token) {
323
+ return json({ error: `Unauthorized. Restart ${PRODUCT_NAME}.` }, 401);
324
+ }
325
+
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
+ }
341
+
342
+ if (req.method === "GET" && path === "/integrations") {
343
+ return json({ items: listPublicIntegrations() });
344
+ }
345
+
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
+ }
373
+
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
+ }
382
+
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
+ }
390
+
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
+ }
405
+
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
+ }
416
+
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
+ }
426
+
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
+ }
450
+
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
+ }
474
+
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
+ }
479
+
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
+ }
525
+
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
+ }
533
+
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
+ }
541
+
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
+ }
555
+
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
+ }
578
+
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
+ }
591
+
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
+ }
598
+
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() {
674
+ 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
+ }
685
+
686
+ return json({ error: "Not found." }, 404);
687
+ },
688
+ });
689
+
690
+ const port = server.port;
691
+ if (port === undefined) {
692
+ server.stop(true);
693
+ throw new Error(`${PRODUCT_NAME} did not bind a local port.`);
694
+ }
695
+ const ready: BridgeReady = {
696
+ url: `http://${host}:${port}`,
697
+ token,
698
+ port,
699
+ };
700
+
701
+ return {
702
+ ready,
703
+ stop: async () => {
704
+ abort?.abort();
705
+ for (const resolve of pending.values()) resolve(false);
706
+ pending.clear();
707
+ for (const resolve of oauthWaiters.values()) resolve({ error: "cancelled" });
708
+ oauthWaiters.clear();
709
+ server.stop(true);
710
+ if (ownsHarness) {
711
+ harness.close();
712
+ await harness.observability.shutdown();
713
+ }
714
+ },
715
+ };
716
+ }
717
+
718
+ export async function main(): Promise<void> {
719
+ const cwd = process.env.HARNESS_CWD?.trim() || process.cwd();
720
+ const { ready } = await startDesktopBridge({ cwd });
721
+ process.stdout.write(`HARNESS_READY=${JSON.stringify(ready)}\n`);
722
+ }
723
+
724
+ if (import.meta.main) {
725
+ main().catch((err) => {
726
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
727
+ process.exit(1);
728
+ });
729
+ }