@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,349 @@
1
+ import { mkdir, readdir, readFile, unlink, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { newId } from "./ids.ts";
4
+
5
+ export const CHARS_PER_TOKEN = 4;
6
+ export const COMPACTION_THRESHOLD_RATIO = 0.6;
7
+ export const DEFAULT_CONTEXT_WINDOW_TOKENS = 200_000;
8
+
9
+ export type SessionMessage =
10
+ | { kind: "system"; text: string }
11
+ | { kind: "turn"; role: "user" | "assistant"; content: string }
12
+ | { kind: "thought"; text: string }
13
+ | {
14
+ kind: "tool";
15
+ name: string;
16
+ callId: string;
17
+ status: "ok" | "fail";
18
+ preview: string;
19
+ error?: string;
20
+ }
21
+ | {
22
+ kind: "compaction_checkpoint";
23
+ summary: string;
24
+ coversFromSeq: number;
25
+ coversToSeq: number;
26
+ };
27
+
28
+ export type ChatTranscriptLine =
29
+ | { kind: "user"; text: string }
30
+ | { kind: "assistant"; text: string }
31
+ | { kind: "thought"; text: string }
32
+ | {
33
+ kind: "tool";
34
+ name: string;
35
+ callId: string;
36
+ status: "ok" | "fail";
37
+ preview: string;
38
+ error?: string;
39
+ };
40
+
41
+ export interface Session {
42
+ id: string;
43
+ title: string;
44
+ createdAt: string;
45
+ updatedAt: string;
46
+ model?: string;
47
+ messages: SessionMessage[];
48
+ }
49
+
50
+ export interface SummarizerInput {
51
+ session: Session;
52
+ messages: SessionMessage[];
53
+ coversFromSeq: number;
54
+ coversToSeq: number;
55
+ }
56
+
57
+ export type SummarizerFn = (input: SummarizerInput) => Promise<string>;
58
+
59
+ export function estimateTokens(messages: SessionMessage[]): number {
60
+ let chars = 0;
61
+ for (const message of messages) chars += JSON.stringify(message).length;
62
+ return Math.floor(chars / CHARS_PER_TOKEN);
63
+ }
64
+
65
+ /** Highest `coversToSeq` among compaction checkpoints, or `-1` if none. */
66
+ export function latestCompactionCover(session: Session): number {
67
+ let covered = -1;
68
+ for (const message of session.messages) {
69
+ if (message.kind !== "compaction_checkpoint") continue;
70
+ if (message.coversToSeq > covered) covered = message.coversToSeq;
71
+ }
72
+ return covered;
73
+ }
74
+
75
+ /** Tokens the next turn would send: summaries plus uncovered turns. */
76
+ export function liveContextTokens(session: Session): number {
77
+ const coveredThrough = latestCompactionCover(session);
78
+ let chars = 0;
79
+ for (const summary of compactionSummaries(session)) chars += summary.length;
80
+ session.messages.forEach((message, seq) => {
81
+ if (seq <= coveredThrough) return;
82
+ chars += JSON.stringify(message).length;
83
+ });
84
+ return Math.floor(chars / CHARS_PER_TOKEN);
85
+ }
86
+
87
+ export function normalizeSessionTitle(raw: string, maxLen = 48): string {
88
+ const collapsed = raw.replace(/\s+/g, " ").trim();
89
+ if (!collapsed) return "";
90
+ if (collapsed.length <= maxLen) return collapsed;
91
+ return `${collapsed.slice(0, maxLen - 1).trimEnd()}…`;
92
+ }
93
+
94
+ export function titleFromUserMessage(message: string, maxLen = 48): string {
95
+ return normalizeSessionTitle(message, maxLen) || "New chat";
96
+ }
97
+
98
+ export function sessionToProviderMessages(session: Session): Array<{
99
+ role: "user" | "assistant";
100
+ content: string;
101
+ }> {
102
+ const coveredThrough = latestCompactionCover(session);
103
+ const out: Array<{ role: "user" | "assistant"; content: string }> = [];
104
+ session.messages.forEach((message, seq) => {
105
+ if (message.kind !== "turn") return;
106
+ if (seq <= coveredThrough) return;
107
+ out.push({ role: message.role, content: message.content });
108
+ });
109
+ return out;
110
+ }
111
+
112
+ export function sessionTranscript(session: Session): ChatTranscriptLine[] {
113
+ const lines: ChatTranscriptLine[] = [];
114
+ for (const message of session.messages) {
115
+ if (message.kind === "turn" && message.role === "user") {
116
+ lines.push({ kind: "user", text: message.content });
117
+ } else if (message.kind === "turn" && message.role === "assistant") {
118
+ lines.push({ kind: "assistant", text: message.content });
119
+ } else if (message.kind === "thought") {
120
+ lines.push({ kind: "thought", text: message.text });
121
+ } else if (message.kind === "tool") {
122
+ lines.push({
123
+ kind: "tool",
124
+ name: message.name,
125
+ callId: message.callId,
126
+ status: message.status,
127
+ preview: message.preview,
128
+ ...(message.error ? { error: message.error } : {}),
129
+ });
130
+ }
131
+ }
132
+ return lines;
133
+ }
134
+
135
+ export function compactionSummaries(session: Session): string[] {
136
+ return session.messages
137
+ .filter(
138
+ (m): m is Extract<SessionMessage, { kind: "compaction_checkpoint" }> =>
139
+ m.kind === "compaction_checkpoint",
140
+ )
141
+ .map((m) => m.summary);
142
+ }
143
+
144
+ function findLastCheckpointIndex(messages: SessionMessage[]): number {
145
+ for (let i = messages.length - 1; i >= 0; i--) {
146
+ if (messages[i]?.kind === "compaction_checkpoint") return i;
147
+ }
148
+ return -1;
149
+ }
150
+
151
+ export interface SessionStore {
152
+ create(systemText: string, model?: string): Promise<Session>;
153
+ get(id: string): Promise<Session | undefined>;
154
+ list(): Promise<Session[]>;
155
+ append(session: Session, message: SessionMessage): Promise<Session>;
156
+ save(session: Session): Promise<Session>;
157
+ setTitle(session: Session, title: string): Promise<Session>;
158
+ remove(id: string): Promise<boolean>;
159
+ maybeCompact(
160
+ session: Session,
161
+ contextWindowTokens: number,
162
+ summarize: SummarizerFn,
163
+ ): Promise<Session>;
164
+ }
165
+
166
+ /** Replace a user turn and drop everything after it, including later checkpoints. */
167
+ export function replaceUserTurn(session: Session, userTurnIndex: number, content: string): Session {
168
+ const trimmed = content.trim();
169
+ if (!trimmed) throw new Error("Message is empty.");
170
+ let seen = -1;
171
+ let cut = -1;
172
+ for (let i = 0; i < session.messages.length; i++) {
173
+ const message = session.messages[i];
174
+ if (message?.kind === "turn" && message.role === "user") {
175
+ seen++;
176
+ if (seen === userTurnIndex) {
177
+ cut = i;
178
+ break;
179
+ }
180
+ }
181
+ }
182
+ if (cut < 0) throw new Error("No user message to edit.");
183
+ const kept = session.messages.slice(0, cut).filter((message) => {
184
+ if (message.kind !== "compaction_checkpoint") return true;
185
+ return message.coversToSeq < cut;
186
+ });
187
+ return {
188
+ ...session,
189
+ title: userTurnIndex === 0 ? titleFromUserMessage(trimmed) : session.title,
190
+ messages: [...kept, { kind: "turn", role: "user", content: trimmed }],
191
+ };
192
+ }
193
+
194
+ export function sessionsDir(cwd: string): string {
195
+ return join(cwd, ".harness", "sessions");
196
+ }
197
+
198
+ function sessionPath(dir: string, id: string): string {
199
+ return join(dir, `${id}.json`);
200
+ }
201
+
202
+ async function persist(dir: string, session: Session): Promise<Session> {
203
+ await mkdir(dir, { recursive: true });
204
+ const next = { ...session, updatedAt: new Date().toISOString() };
205
+ await writeFile(sessionPath(dir, next.id), `${JSON.stringify(next, null, 2)}\n`, "utf8");
206
+ return next;
207
+ }
208
+
209
+ export function createFileSessionStore(cwd: string): SessionStore {
210
+ const dir = sessionsDir(cwd);
211
+ return {
212
+ async create(systemText, model) {
213
+ const now = new Date().toISOString();
214
+ const session: Session = {
215
+ id: newId("ses"),
216
+ title: "New chat",
217
+ createdAt: now,
218
+ updatedAt: now,
219
+ model,
220
+ messages: [{ kind: "system", text: systemText }],
221
+ };
222
+ return persist(dir, session);
223
+ },
224
+ async get(id) {
225
+ try {
226
+ const raw = await readFile(sessionPath(dir, id), "utf8");
227
+ return JSON.parse(raw) as Session;
228
+ } catch {
229
+ return undefined;
230
+ }
231
+ },
232
+ async list() {
233
+ try {
234
+ const names = await readdir(dir);
235
+ const sessions: Session[] = [];
236
+ for (const name of names) {
237
+ if (!name.endsWith(".json")) continue;
238
+ const raw = await readFile(join(dir, name), "utf8");
239
+ sessions.push(JSON.parse(raw) as Session);
240
+ }
241
+ sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
242
+ return sessions;
243
+ } catch {
244
+ return [];
245
+ }
246
+ },
247
+ async append(session, message) {
248
+ const next: Session = {
249
+ ...session,
250
+ messages: [...session.messages, message],
251
+ };
252
+ return persist(dir, next);
253
+ },
254
+ async save(session) {
255
+ return persist(dir, session);
256
+ },
257
+ async setTitle(session, title) {
258
+ const next = { ...session, title };
259
+ await mkdir(dir, { recursive: true });
260
+ await writeFile(sessionPath(dir, next.id), `${JSON.stringify(next, null, 2)}\n`, "utf8");
261
+ return next;
262
+ },
263
+ async remove(id) {
264
+ try {
265
+ await unlink(sessionPath(dir, id));
266
+ return true;
267
+ } catch {
268
+ return false;
269
+ }
270
+ },
271
+ async maybeCompact(session, contextWindowTokens, summarize) {
272
+ return compactSession(session, contextWindowTokens, summarize, (next) => persist(dir, next));
273
+ },
274
+ };
275
+ }
276
+
277
+ /** Ephemeral sessions for subagents — not listed in `/resume`. */
278
+ export function createMemorySessionStore(): SessionStore {
279
+ const byId = new Map<string, Session>();
280
+ const save = async (session: Session): Promise<Session> => {
281
+ const next = { ...session, updatedAt: new Date().toISOString() };
282
+ byId.set(next.id, next);
283
+ return next;
284
+ };
285
+ return {
286
+ async create(systemText, model) {
287
+ const now = new Date().toISOString();
288
+ return save({
289
+ id: newId("ses"),
290
+ title: "subagent",
291
+ createdAt: now,
292
+ updatedAt: now,
293
+ model,
294
+ messages: [{ kind: "system", text: systemText }],
295
+ });
296
+ },
297
+ async get(id) {
298
+ return byId.get(id);
299
+ },
300
+ async list() {
301
+ return [...byId.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
302
+ },
303
+ async append(session, message) {
304
+ return save({ ...session, messages: [...session.messages, message] });
305
+ },
306
+ async save(session) {
307
+ return save(session);
308
+ },
309
+ async setTitle(session, title) {
310
+ const next = { ...session, title };
311
+ byId.set(next.id, next);
312
+ return next;
313
+ },
314
+ async remove(id) {
315
+ return byId.delete(id);
316
+ },
317
+ async maybeCompact(session, contextWindowTokens, summarize) {
318
+ return compactSession(session, contextWindowTokens, summarize, save);
319
+ },
320
+ };
321
+ }
322
+
323
+ async function compactSession(
324
+ session: Session,
325
+ contextWindowTokens: number,
326
+ summarize: SummarizerFn,
327
+ save: (session: Session) => Promise<Session>,
328
+ ): Promise<Session> {
329
+ const threshold = contextWindowTokens * COMPACTION_THRESHOLD_RATIO;
330
+ if (liveContextTokens(session) < threshold) return session;
331
+ const lastCheckpointIndex = findLastCheckpointIndex(session.messages);
332
+ const coversFromSeq = lastCheckpointIndex + 1;
333
+ const coversToSeq = session.messages.length - 1;
334
+ if (coversFromSeq > coversToSeq) return session;
335
+ const span = session.messages.slice(coversFromSeq, coversToSeq + 1);
336
+ let summary: string;
337
+ try {
338
+ summary = await summarize({ session, messages: span, coversFromSeq, coversToSeq });
339
+ } catch {
340
+ return session;
341
+ }
342
+ return save({
343
+ ...session,
344
+ messages: [
345
+ ...session.messages,
346
+ { kind: "compaction_checkpoint", summary, coversFromSeq, coversToSeq },
347
+ ],
348
+ });
349
+ }
@@ -0,0 +1,143 @@
1
+ import { type Subprocess, spawn } from "bun";
2
+ import {
3
+ errorResult,
4
+ jsonResult,
5
+ type McpToolDefinition,
6
+ type ToolResult,
7
+ textResult,
8
+ } from "./mcp.ts";
9
+
10
+ interface JsonRpcResponse {
11
+ jsonrpc?: string;
12
+ id?: number | string | null;
13
+ result?: unknown;
14
+ error?: { code?: number; message?: string };
15
+ }
16
+
17
+ export interface StdioMcpClientOptions {
18
+ command: string;
19
+ args?: string[];
20
+ env?: Record<string, string>;
21
+ cwd?: string;
22
+ }
23
+
24
+ /**
25
+ * Spawn an extra MCP server over newline JSON-RPC and expose its tools
26
+ * as in-process {@link McpToolDefinition}s.
27
+ */
28
+ export async function loadStdioMcpTools(
29
+ options: StdioMcpClientOptions,
30
+ ): Promise<{ tools: McpToolDefinition[]; close: () => void }> {
31
+ const proc: Subprocess = spawn({
32
+ cmd: [options.command, ...(options.args ?? [])],
33
+ cwd: options.cwd,
34
+ env: { ...process.env, ...options.env },
35
+ stdin: "pipe",
36
+ stdout: "pipe",
37
+ stderr: "pipe",
38
+ });
39
+
40
+ let nextId = 1;
41
+ const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
42
+ let buffer = "";
43
+ let closed = false;
44
+
45
+ const failAll = (err: Error): void => {
46
+ for (const p of pending.values()) p.reject(err);
47
+ pending.clear();
48
+ };
49
+
50
+ const onLine = (line: string): void => {
51
+ const trimmed = line.trim();
52
+ if (!trimmed) return;
53
+ let msg: JsonRpcResponse;
54
+ try {
55
+ msg = JSON.parse(trimmed) as JsonRpcResponse;
56
+ } catch {
57
+ return;
58
+ }
59
+ if (typeof msg.id !== "number") return;
60
+ const waiter = pending.get(msg.id);
61
+ if (!waiter) return;
62
+ pending.delete(msg.id);
63
+ if (msg.error) waiter.reject(new Error(msg.error.message ?? "MCP error"));
64
+ else waiter.resolve(msg.result);
65
+ };
66
+
67
+ const stdout = proc.stdout;
68
+ if (stdout && typeof stdout !== "number") {
69
+ (async () => {
70
+ const reader = stdout.getReader();
71
+ const decoder = new TextDecoder();
72
+ try {
73
+ while (true) {
74
+ const { done, value } = await reader.read();
75
+ if (done) break;
76
+ buffer += decoder.decode(value, { stream: true });
77
+ let idx = buffer.indexOf("\n");
78
+ while (idx >= 0) {
79
+ onLine(buffer.slice(0, idx));
80
+ buffer = buffer.slice(idx + 1);
81
+ idx = buffer.indexOf("\n");
82
+ }
83
+ }
84
+ } catch (err) {
85
+ failAll(err instanceof Error ? err : new Error(String(err)));
86
+ }
87
+ })();
88
+ }
89
+
90
+ const rpc = (method: string, params?: Record<string, unknown>): Promise<unknown> => {
91
+ if (closed) return Promise.reject(new Error("MCP process closed"));
92
+ const id = nextId++;
93
+ const payload = JSON.stringify({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) });
94
+ const stdin = proc.stdin;
95
+ if (!stdin || typeof stdin === "number") return Promise.reject(new Error("MCP stdin closed"));
96
+ stdin.write(`${payload}\n`);
97
+ return new Promise((resolve, reject) => {
98
+ pending.set(id, { resolve, reject });
99
+ });
100
+ };
101
+
102
+ const close = (): void => {
103
+ closed = true;
104
+ failAll(new Error("MCP process closed"));
105
+ try {
106
+ proc.kill();
107
+ } catch {
108
+ // already gone
109
+ }
110
+ };
111
+
112
+ await rpc("initialize", {
113
+ protocolVersion: "2024-11-05",
114
+ capabilities: {},
115
+ clientInfo: { name: "caelence-harness", version: "0.1.0" },
116
+ });
117
+ await rpc("notifications/initialized").catch(() => undefined);
118
+
119
+ const listed = (await rpc("tools/list")) as {
120
+ tools?: Array<{ name: string; description?: string; inputSchema?: Record<string, unknown> }>;
121
+ };
122
+ const remote = listed.tools ?? [];
123
+ const prefix = options.command.replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "mcp";
124
+
125
+ const tools: McpToolDefinition[] = remote.map((t) => ({
126
+ name: `${prefix}__${t.name}`,
127
+ description: t.description ?? t.name,
128
+ inputSchema: t.inputSchema ?? { type: "object", properties: {} },
129
+ async handler(input) {
130
+ try {
131
+ const result = (await rpc("tools/call", { name: t.name, arguments: input })) as ToolResult;
132
+ if (result && Array.isArray(result.content)) return result;
133
+ if (result && typeof result === "object")
134
+ return jsonResult(result as unknown as Record<string, unknown>);
135
+ return textResult(String(result ?? ""));
136
+ } catch (err) {
137
+ return errorResult(err instanceof Error ? err.message : String(err));
138
+ }
139
+ },
140
+ }));
141
+
142
+ return { tools, close };
143
+ }