@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,145 @@
1
+ /** PKCE + authorize URL + token exchange. */
2
+
3
+ export interface OAuthSpec {
4
+ authorizeUrl: string;
5
+ tokenUrl: string;
6
+ tokenAuth?: "body" | "basic" | "none";
7
+ tokenBody?: "form" | "json";
8
+ pkce?: boolean;
9
+ extraAuthParams?: Record<string, string>;
10
+ }
11
+
12
+ export interface OAuthClient {
13
+ clientId: string;
14
+ clientSecret: string;
15
+ }
16
+
17
+ export function usesPkce(spec: OAuthSpec): boolean {
18
+ return spec.pkce !== false;
19
+ }
20
+
21
+ export async function pkcePair(): Promise<{ verifier: string; challenge: string }> {
22
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
23
+ const verifier = b64url(bytes);
24
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
25
+ return { verifier, challenge: b64url(new Uint8Array(digest)) };
26
+ }
27
+
28
+ export function b64url(bytes: Uint8Array): string {
29
+ let bin = "";
30
+ for (const b of bytes) bin += String.fromCharCode(b);
31
+ return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
32
+ }
33
+
34
+ export function buildAuthorizeUrl(input: {
35
+ spec: OAuthSpec;
36
+ clientId: string;
37
+ redirectUri: string;
38
+ state: string;
39
+ scopes: readonly string[];
40
+ challenge: string;
41
+ resource?: string;
42
+ }): string {
43
+ const params = new URLSearchParams({
44
+ response_type: "code",
45
+ client_id: input.clientId,
46
+ redirect_uri: input.redirectUri,
47
+ state: input.state,
48
+ ...(input.spec.extraAuthParams ?? {}),
49
+ });
50
+ if (input.scopes.length > 0) params.set("scope", input.scopes.join(" "));
51
+ if (input.resource) params.set("resource", input.resource);
52
+ if (usesPkce(input.spec)) {
53
+ params.set("code_challenge", input.challenge);
54
+ params.set("code_challenge_method", "S256");
55
+ }
56
+ const join = input.spec.authorizeUrl.includes("?") ? "&" : "?";
57
+ return `${input.spec.authorizeUrl}${join}${params}`;
58
+ }
59
+
60
+ export interface TokenExchangeResult {
61
+ access_token: string;
62
+ refresh_token?: string;
63
+ expires_in?: number;
64
+ token_type?: string;
65
+ scope?: string;
66
+ }
67
+
68
+ export async function exchangeAuthorizationCode(input: {
69
+ spec: OAuthSpec;
70
+ client: OAuthClient;
71
+ code: string;
72
+ redirectUri: string;
73
+ verifier: string;
74
+ resource?: string;
75
+ fetchImpl?: typeof fetch;
76
+ }): Promise<TokenExchangeResult> {
77
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
78
+ const tokenAuth = input.spec.tokenAuth ?? (input.client.clientSecret ? "body" : "none");
79
+ const params: Record<string, string> = {
80
+ grant_type: "authorization_code",
81
+ code: input.code,
82
+ redirect_uri: input.redirectUri,
83
+ };
84
+ if (tokenAuth === "body" || tokenAuth === "none") {
85
+ params.client_id = input.client.clientId;
86
+ if (tokenAuth === "body" && input.client.clientSecret) {
87
+ params.client_secret = input.client.clientSecret;
88
+ }
89
+ }
90
+ if (usesPkce(input.spec)) params.code_verifier = input.verifier;
91
+ if (input.resource) params.resource = input.resource;
92
+
93
+ const headers: Record<string, string> = { Accept: "application/json" };
94
+ if (tokenAuth === "basic") {
95
+ headers.Authorization = `Basic ${btoa(`${input.client.clientId}:${input.client.clientSecret}`)}`;
96
+ }
97
+
98
+ let body: string;
99
+ if (input.spec.tokenBody === "json") {
100
+ headers["Content-Type"] = "application/json";
101
+ body = JSON.stringify(params);
102
+ } else {
103
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
104
+ body = new URLSearchParams(params).toString();
105
+ }
106
+
107
+ const res = await fetchImpl(input.spec.tokenUrl, { method: "POST", headers, body });
108
+ const raw = await res.text();
109
+ if (!res.ok) {
110
+ throw new Error(`Token exchange failed (${res.status})`);
111
+ }
112
+ const parsed = parseTokenResponse(raw);
113
+ if (!parsed.access_token) throw new Error("Provider did not return an access token");
114
+ return parsed;
115
+ }
116
+
117
+ export function parseTokenResponse(raw: string): TokenExchangeResult {
118
+ const trimmed = raw.trim();
119
+ if (trimmed.startsWith("{")) {
120
+ const json = JSON.parse(trimmed) as {
121
+ access_token?: string;
122
+ refresh_token?: string;
123
+ expires_in?: number;
124
+ token_type?: string;
125
+ scope?: string;
126
+ authed_user?: { access_token?: string };
127
+ };
128
+ const access = json.access_token || json.authed_user?.access_token || "";
129
+ return {
130
+ access_token: access,
131
+ refresh_token: json.refresh_token,
132
+ expires_in: json.expires_in,
133
+ token_type: json.token_type,
134
+ scope: json.scope,
135
+ };
136
+ }
137
+ const form = new URLSearchParams(trimmed);
138
+ return {
139
+ access_token: form.get("access_token") ?? "",
140
+ refresh_token: form.get("refresh_token") ?? undefined,
141
+ expires_in: form.get("expires_in") ? Number(form.get("expires_in")) : undefined,
142
+ token_type: form.get("token_type") ?? undefined,
143
+ scope: form.get("scope") ?? undefined,
144
+ };
145
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Remote MCP client (streamable HTTP): initialize, tools/list, tools/call
3
+ * against a hosted vendor MCP with a vaulted bearer token.
4
+ */
5
+
6
+ import {
7
+ errorResult,
8
+ jsonResult,
9
+ type McpToolDefinition,
10
+ type ToolResult,
11
+ textResult,
12
+ } from "../core/mcp.ts";
13
+
14
+ export const MCP_PROTOCOL_VERSION = "2025-06-18";
15
+
16
+ export interface RemoteMcpToolMeta {
17
+ name: string;
18
+ description: string;
19
+ inputSchema: Record<string, unknown>;
20
+ }
21
+
22
+ export interface RemoteMcpClient {
23
+ readonly mcpUrl: string;
24
+ readonly sessionId: string | undefined;
25
+ listTools(): Promise<RemoteMcpToolMeta[]>;
26
+ callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
27
+ }
28
+
29
+ export interface LinkedMcpSource {
30
+ connectorId: string;
31
+ label: string;
32
+ mcpUrl: string;
33
+ accessToken: string;
34
+ }
35
+
36
+ export function namespaceRemoteTool(connectorId: string, remoteName: string): string {
37
+ const prefix = connectorId.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "");
38
+ const tool = remoteName.replace(/[^a-zA-Z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
39
+ return `${prefix}__${tool}`;
40
+ }
41
+
42
+ export async function openRemoteMcp(input: {
43
+ mcpUrl: string;
44
+ accessToken: string;
45
+ clientName?: string;
46
+ fetchImpl?: typeof fetch;
47
+ signal?: AbortSignal;
48
+ }): Promise<RemoteMcpClient> {
49
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
50
+ const mcpUrl = input.mcpUrl.trim();
51
+ if (!mcpUrl) throw new Error("mcpUrl is required");
52
+ const accessToken = input.accessToken.trim();
53
+
54
+ let sessionId: string | undefined;
55
+ let nextId = 1;
56
+
57
+ const rpc = async (
58
+ method: string,
59
+ params?: Record<string, unknown>,
60
+ opts?: { notification?: boolean },
61
+ ): Promise<unknown> => {
62
+ const id = opts?.notification ? undefined : nextId++;
63
+ const body: Record<string, unknown> = {
64
+ jsonrpc: "2.0",
65
+ method,
66
+ ...(params ? { params } : {}),
67
+ };
68
+ if (id !== undefined) body.id = id;
69
+
70
+ const headers: Record<string, string> = {
71
+ Accept: "application/json, text/event-stream",
72
+ "Content-Type": "application/json",
73
+ "MCP-Protocol-Version": MCP_PROTOCOL_VERSION,
74
+ };
75
+ if (accessToken) headers.Authorization = `Bearer ${accessToken}`;
76
+ if (sessionId) headers["Mcp-Session-Id"] = sessionId;
77
+
78
+ const res = await fetchImpl(mcpUrl, {
79
+ method: "POST",
80
+ headers,
81
+ body: JSON.stringify(body),
82
+ signal: input.signal,
83
+ });
84
+
85
+ const returnedSession = res.headers.get("mcp-session-id") ?? res.headers.get("Mcp-Session-Id");
86
+ if (returnedSession?.trim()) sessionId = returnedSession.trim();
87
+
88
+ if (opts?.notification) {
89
+ if (!res.ok && res.status !== 202 && res.status !== 204) {
90
+ throw new Error(`MCP ${method} failed (${res.status})`);
91
+ }
92
+ return undefined;
93
+ }
94
+
95
+ const payload = await readMcpResponse(res);
96
+ if (payload.error) {
97
+ const msg =
98
+ typeof payload.error === "object" &&
99
+ payload.error &&
100
+ "message" in payload.error &&
101
+ typeof (payload.error as { message?: unknown }).message === "string"
102
+ ? (payload.error as { message: string }).message
103
+ : `MCP ${method} error`;
104
+ throw new Error(msg);
105
+ }
106
+ return payload.result;
107
+ };
108
+
109
+ await rpc("initialize", {
110
+ protocolVersion: MCP_PROTOCOL_VERSION,
111
+ capabilities: {},
112
+ clientInfo: { name: input.clientName ?? "caelence-agent", version: "0.1" },
113
+ });
114
+ await rpc("notifications/initialized", {}, { notification: true }).catch(() => undefined);
115
+
116
+ return {
117
+ mcpUrl,
118
+ get sessionId() {
119
+ return sessionId;
120
+ },
121
+ async listTools(): Promise<RemoteMcpToolMeta[]> {
122
+ const result = await rpc("tools/list", {});
123
+ const tools = (result as { tools?: unknown } | null)?.tools;
124
+ if (!Array.isArray(tools)) return [];
125
+ const out: RemoteMcpToolMeta[] = [];
126
+ for (const raw of tools) {
127
+ if (!raw || typeof raw !== "object") continue;
128
+ const t = raw as Record<string, unknown>;
129
+ const name = typeof t.name === "string" ? t.name.trim() : "";
130
+ if (!name) continue;
131
+ const description =
132
+ typeof t.description === "string" && t.description.trim()
133
+ ? t.description.trim()
134
+ : `Remote tool ${name}`;
135
+ const inputSchema =
136
+ t.inputSchema && typeof t.inputSchema === "object" && !Array.isArray(t.inputSchema)
137
+ ? (t.inputSchema as Record<string, unknown>)
138
+ : { type: "object", properties: {} };
139
+ out.push({ name, description, inputSchema });
140
+ }
141
+ return out;
142
+ },
143
+ async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {
144
+ try {
145
+ const result = await rpc("tools/call", { name, arguments: args });
146
+ return mapCallToolResult(result);
147
+ } catch (err) {
148
+ return errorResult(err instanceof Error ? err.message : String(err));
149
+ }
150
+ },
151
+ };
152
+ }
153
+
154
+ export async function buildRemoteMcpTools(input: {
155
+ sources: readonly LinkedMcpSource[];
156
+ fetchImpl?: typeof fetch;
157
+ signal?: AbortSignal;
158
+ timeoutMs?: number;
159
+ onWarn?: (message: string, data?: Record<string, unknown>) => void;
160
+ }): Promise<McpToolDefinition[]> {
161
+ const timeoutMs = input.timeoutMs ?? 8_000;
162
+ const out: McpToolDefinition[] = [];
163
+
164
+ await Promise.all(
165
+ input.sources.map(async (source) => {
166
+ try {
167
+ const tools = await withTimeout(
168
+ (signal) =>
169
+ loadSourceTools({
170
+ source,
171
+ fetchImpl: input.fetchImpl,
172
+ signal,
173
+ }),
174
+ timeoutMs,
175
+ input.signal,
176
+ );
177
+ out.push(...tools);
178
+ } catch (err) {
179
+ input.onWarn?.("remote MCP tools unavailable", {
180
+ connectorId: source.connectorId,
181
+ mcpUrl: source.mcpUrl,
182
+ error: err instanceof Error ? err.message : String(err),
183
+ });
184
+ }
185
+ }),
186
+ );
187
+
188
+ return out;
189
+ }
190
+
191
+ async function loadSourceTools(input: {
192
+ source: LinkedMcpSource;
193
+ fetchImpl?: typeof fetch;
194
+ signal?: AbortSignal;
195
+ }): Promise<McpToolDefinition[]> {
196
+ const client = await openRemoteMcp({
197
+ mcpUrl: input.source.mcpUrl,
198
+ accessToken: input.source.accessToken,
199
+ fetchImpl: input.fetchImpl,
200
+ signal: input.signal,
201
+ });
202
+ const remote = await client.listTools();
203
+ return remote.map((tool) => {
204
+ const name = namespaceRemoteTool(input.source.connectorId, tool.name);
205
+ const schema = ensureObjectSchema(tool.inputSchema);
206
+ return {
207
+ name,
208
+ description: `[${input.source.label}] ${tool.description}`,
209
+ inputSchema: schema,
210
+ async handler(raw: Record<string, unknown>): Promise<ToolResult> {
211
+ const { projectId: _projectId, ...args } = raw;
212
+ return client.callTool(tool.name, args);
213
+ },
214
+ };
215
+ });
216
+ }
217
+
218
+ function ensureObjectSchema(schema: Record<string, unknown>): Record<string, unknown> {
219
+ if (schema.type === "object" || schema.properties) return schema;
220
+ return { type: "object", properties: {}, ...(schema as object) };
221
+ }
222
+
223
+ function mapCallToolResult(result: unknown): ToolResult {
224
+ if (!result || typeof result !== "object") {
225
+ return textResult(String(result ?? ""));
226
+ }
227
+ const r = result as {
228
+ content?: unknown;
229
+ isError?: boolean;
230
+ structuredContent?: Record<string, unknown>;
231
+ };
232
+ const isError = r.isError === true;
233
+ const blocks = Array.isArray(r.content) ? r.content : [];
234
+ const textParts: string[] = [];
235
+ for (const block of blocks) {
236
+ if (!block || typeof block !== "object") continue;
237
+ const b = block as { type?: string; text?: string };
238
+ if (b.type === "text" && typeof b.text === "string") textParts.push(b.text);
239
+ else textParts.push(JSON.stringify(block));
240
+ }
241
+ if (textParts.length === 0 && r.structuredContent) {
242
+ return jsonResult(r.structuredContent, isError);
243
+ }
244
+ if (textParts.length === 0) {
245
+ return jsonResult(result as Record<string, unknown>, isError);
246
+ }
247
+ const text = textParts.join("\n");
248
+ try {
249
+ const parsed: unknown = JSON.parse(text);
250
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
251
+ return jsonResult(parsed, isError);
252
+ }
253
+ } catch {
254
+ /* plain text */
255
+ }
256
+ return textResult(text, isError);
257
+ }
258
+
259
+ async function readMcpResponse(res: Response): Promise<{
260
+ result?: unknown;
261
+ error?: unknown;
262
+ }> {
263
+ const raw = await res.text();
264
+ if (!res.ok) {
265
+ throw new Error(`MCP HTTP ${res.status}: ${raw.slice(0, 240) || res.statusText}`);
266
+ }
267
+ const contentType = res.headers.get("content-type") ?? "";
268
+ if (
269
+ contentType.includes("text/event-stream") ||
270
+ raw.startsWith("event:") ||
271
+ raw.includes("\ndata:")
272
+ ) {
273
+ const dataLines = raw
274
+ .split(/\r?\n/)
275
+ .filter((line) => line.startsWith("data:"))
276
+ .map((line) => line.slice(5).trimStart())
277
+ .filter((line) => line.length > 0 && line !== "[DONE]");
278
+ let last: { result?: unknown; error?: unknown } | null = null;
279
+ for (const line of dataLines) {
280
+ try {
281
+ last = JSON.parse(line) as { result?: unknown; error?: unknown };
282
+ } catch {
283
+ /* keep scanning */
284
+ }
285
+ }
286
+ if (!last) throw new Error("MCP SSE response had no data frames");
287
+ return last;
288
+ }
289
+ if (!raw.trim()) return {};
290
+ return JSON.parse(raw) as { result?: unknown; error?: unknown };
291
+ }
292
+
293
+ function withTimeout<T>(
294
+ run: (signal: AbortSignal) => Promise<T>,
295
+ ms: number,
296
+ outer?: AbortSignal,
297
+ ): Promise<T> {
298
+ const ctrl = new AbortController();
299
+ const onOuter = (): void => ctrl.abort();
300
+ if (outer?.aborted) ctrl.abort();
301
+ else outer?.addEventListener("abort", onOuter, { once: true });
302
+ const timer = setTimeout(() => ctrl.abort(), ms);
303
+ return run(ctrl.signal).finally(() => {
304
+ clearTimeout(timer);
305
+ outer?.removeEventListener("abort", onOuter);
306
+ });
307
+ }
@@ -0,0 +1,149 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { harnessHome } from "../desktop/secrets.ts";
4
+ import {
5
+ type IntegrationLogoKind,
6
+ integrationLogoKind,
7
+ integrationLogoUrl,
8
+ listedMcpCatalog,
9
+ type McpAuthKind,
10
+ type McpCatalogEntry,
11
+ } from "./catalog.ts";
12
+ import type { LinkedMcpSource } from "./remote-mcp.ts";
13
+
14
+ export interface StoredMcpConnection {
15
+ id: string;
16
+ label: string;
17
+ mcpUrl: string;
18
+ accessToken: string;
19
+ refreshToken?: string;
20
+ connectedAt: string;
21
+ }
22
+
23
+ export interface PublicIntegration {
24
+ id: string;
25
+ label: string;
26
+ description: string;
27
+ docsUrl: string;
28
+ logoUrl: string;
29
+ logoKind: IntegrationLogoKind;
30
+ glyph: string;
31
+ connected: boolean;
32
+ auth?: McpAuthKind;
33
+ }
34
+
35
+ interface StoreFile {
36
+ connections: StoredMcpConnection[];
37
+ }
38
+
39
+ export function integrationsPath(env: Record<string, string | undefined> = process.env): string {
40
+ return resolve(harnessHome(env), "integrations.json");
41
+ }
42
+
43
+ function readStore(env: Record<string, string | undefined> = process.env): StoreFile {
44
+ const path = integrationsPath(env);
45
+ if (!existsSync(path)) return { connections: [] };
46
+ try {
47
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as StoreFile;
48
+ if (!parsed || !Array.isArray(parsed.connections)) return { connections: [] };
49
+ return { connections: parsed.connections.filter(isStoredConnection) };
50
+ } catch {
51
+ return { connections: [] };
52
+ }
53
+ }
54
+
55
+ function isStoredConnection(value: unknown): value is StoredMcpConnection {
56
+ if (!value || typeof value !== "object") return false;
57
+ const row = value as Record<string, unknown>;
58
+ return (
59
+ typeof row.id === "string" &&
60
+ typeof row.label === "string" &&
61
+ typeof row.mcpUrl === "string" &&
62
+ typeof row.accessToken === "string" &&
63
+ typeof row.connectedAt === "string"
64
+ );
65
+ }
66
+
67
+ function writeStore(store: StoreFile, env: Record<string, string | undefined> = process.env): void {
68
+ const path = integrationsPath(env);
69
+ mkdirSync(dirname(path), { recursive: true });
70
+ writeFileSync(path, `${JSON.stringify(store, null, "\t")}\n`, { encoding: "utf8", mode: 0o600 });
71
+ try {
72
+ chmodSync(path, 0o600);
73
+ } catch {
74
+ // best-effort on filesystems that ignore mode
75
+ }
76
+ }
77
+
78
+ export function listStoredConnections(
79
+ env: Record<string, string | undefined> = process.env,
80
+ ): StoredMcpConnection[] {
81
+ return readStore(env).connections;
82
+ }
83
+
84
+ export function listPublicIntegrations(
85
+ env: Record<string, string | undefined> = process.env,
86
+ ): PublicIntegration[] {
87
+ const connected = new Set(listStoredConnections(env).map((row) => row.id));
88
+ return listedMcpCatalog().map((item) => toPublic(item, connected.has(item.id)));
89
+ }
90
+
91
+ export function linkedMcpSources(
92
+ env: Record<string, string | undefined> = process.env,
93
+ ): LinkedMcpSource[] {
94
+ return listStoredConnections(env).map((row) => ({
95
+ connectorId: row.id,
96
+ label: row.label,
97
+ mcpUrl: row.mcpUrl,
98
+ accessToken: row.accessToken,
99
+ }));
100
+ }
101
+
102
+ export function upsertConnection(
103
+ row: StoredMcpConnection,
104
+ env: Record<string, string | undefined> = process.env,
105
+ ): void {
106
+ const store = readStore(env);
107
+ store.connections = store.connections.filter((item) => item.id !== row.id);
108
+ store.connections.push(row);
109
+ writeStore(store, env);
110
+ }
111
+
112
+ export function removeConnection(
113
+ id: string,
114
+ env: Record<string, string | undefined> = process.env,
115
+ ): boolean {
116
+ const store = readStore(env);
117
+ const next = store.connections.filter((item) => item.id !== id);
118
+ if (next.length === store.connections.length) return false;
119
+ writeStore({ connections: next }, env);
120
+ return true;
121
+ }
122
+
123
+ export function connectionFromCatalog(
124
+ entry: McpCatalogEntry,
125
+ tokens: { accessToken: string; refreshToken?: string },
126
+ ): StoredMcpConnection {
127
+ return {
128
+ id: entry.id,
129
+ label: entry.label,
130
+ mcpUrl: entry.mcpUrl,
131
+ accessToken: tokens.accessToken,
132
+ ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),
133
+ connectedAt: new Date().toISOString(),
134
+ };
135
+ }
136
+
137
+ function toPublic(item: McpCatalogEntry, connected: boolean): PublicIntegration {
138
+ return {
139
+ id: item.id,
140
+ label: item.label,
141
+ description: item.description,
142
+ docsUrl: item.docsUrl,
143
+ logoUrl: integrationLogoUrl(item.id),
144
+ logoKind: integrationLogoKind(item.id),
145
+ glyph: item.glyph,
146
+ connected,
147
+ ...(item.auth ? { auth: item.auth } : {}),
148
+ };
149
+ }
@@ -0,0 +1,80 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { generateImage, generateVideo, transcribeAudio } from "./openrouter-generate.ts";
3
+
4
+ describe("openrouter media generate", () => {
5
+ test("image reads b64_json", async () => {
6
+ const media = await generateImage({
7
+ prompt: "a cat",
8
+ model: "black-forest-labs/flux.2-pro",
9
+ apiKey: "sk-test",
10
+ fetchImpl: async () =>
11
+ new Response(JSON.stringify({ data: [{ b64_json: "aaa" }] }), {
12
+ status: 200,
13
+ headers: { "content-type": "application/json" },
14
+ }),
15
+ });
16
+ expect(media).toEqual({
17
+ kind: "image",
18
+ mimeType: "image/png",
19
+ dataUrl: "data:image/png;base64,aaa",
20
+ });
21
+ });
22
+
23
+ test("image rejects an empty prompt", async () => {
24
+ expect(
25
+ generateImage({
26
+ prompt: " ",
27
+ model: "black-forest-labs/flux.2-pro",
28
+ apiKey: "sk-test",
29
+ fetchImpl: async () => new Response("no"),
30
+ }),
31
+ ).rejects.toThrow("Describe the image.");
32
+ });
33
+
34
+ test("video polls until the clip is ready", async () => {
35
+ let calls = 0;
36
+ const media = await generateVideo({
37
+ prompt: "waves",
38
+ model: "google/veo-3.1-lite",
39
+ apiKey: "sk-test",
40
+ sleep: async () => undefined,
41
+ fetchImpl: async (input) => {
42
+ calls += 1;
43
+ const url = String(input);
44
+ if (url.endsWith("/videos") && calls === 1) {
45
+ return new Response(JSON.stringify({ id: "vid_1", status: "pending" }), {
46
+ status: 200,
47
+ headers: { "content-type": "application/json" },
48
+ });
49
+ }
50
+ if (url.includes("/videos/vid_1") && !url.endsWith("/content")) {
51
+ return new Response(JSON.stringify({ id: "vid_1", status: "completed" }), {
52
+ status: 200,
53
+ headers: { "content-type": "application/json" },
54
+ });
55
+ }
56
+ return new Response(new Uint8Array([1, 2, 3]), {
57
+ status: 200,
58
+ headers: { "content-type": "video/mp4" },
59
+ });
60
+ },
61
+ });
62
+ expect(media.kind).toBe("video");
63
+ expect(media.dataUrl.startsWith("data:video/mp4;base64,")).toBe(true);
64
+ });
65
+
66
+ test("transcribe returns text", async () => {
67
+ const text = await transcribeAudio({
68
+ data: "abc",
69
+ format: "webm",
70
+ model: "openai/whisper-1",
71
+ apiKey: "sk-test",
72
+ fetchImpl: async () =>
73
+ new Response(JSON.stringify({ text: "hello there" }), {
74
+ status: 200,
75
+ headers: { "content-type": "application/json" },
76
+ }),
77
+ });
78
+ expect(text).toBe("hello there");
79
+ });
80
+ });