@useavalon/caelence-agent 0.2.5-canary.3 → 0.2.5-canary.4

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.
@@ -21,8 +21,13 @@ export interface StdioMcpClientOptions {
21
21
  env?: Record<string, string>;
22
22
  cwd?: string;
23
23
  namePrefix?: string;
24
+ /** How long to wait for initialize + tools/list. Default 12s. */
25
+ initTimeoutMs?: number;
24
26
  }
25
27
 
28
+ const STDERR_TAIL_BYTES = 2000;
29
+ const STDERR_DRAIN_MS = 250;
30
+
26
31
  /**
27
32
  * Spawn an extra MCP server over newline JSON-RPC and expose its tools
28
33
  * as in-process {@link McpToolDefinition}s.
@@ -70,6 +75,37 @@ export async function loadStdioMcpTools(
70
75
  else waiter.resolve(msg.result);
71
76
  };
72
77
 
78
+ // Drain stderr so a chatty server cannot fill the pipe and stall. Keep a short tail for errors.
79
+ let stderrTail = "";
80
+ const stderr = proc.stderr;
81
+ let stderrDrained: Promise<void> = Promise.resolve();
82
+ if (stderr && typeof stderr !== "number") {
83
+ stderrDrained = (async () => {
84
+ const reader = stderr.getReader();
85
+ const decoder = new TextDecoder();
86
+ try {
87
+ while (true) {
88
+ const { done, value } = await reader.read();
89
+ if (done) break;
90
+ stderrTail = (stderrTail + decoder.decode(value, { stream: true })).slice(
91
+ -STDERR_TAIL_BYTES,
92
+ );
93
+ }
94
+ } catch {
95
+ // process went away
96
+ }
97
+ })();
98
+ }
99
+ const withStderr = async (err: Error): Promise<Error> => {
100
+ // A server that prints and exits may not have been read yet. Wait briefly, never long.
101
+ await Promise.race([
102
+ stderrDrained,
103
+ new Promise<void>((done) => setTimeout(done, STDERR_DRAIN_MS)),
104
+ ]);
105
+ const tail = stderrTail.trim();
106
+ return tail ? new Error(`${err.message}\n${tail}`) : err;
107
+ };
108
+
73
109
  const stdout = proc.stdout;
74
110
  if (stdout && typeof stdout !== "number") {
75
111
  (async () => {
@@ -108,6 +144,13 @@ export async function loadStdioMcpTools(
108
144
  });
109
145
  };
110
146
 
147
+ /** JSON-RPC notification: no id, no reply. */
148
+ const notify = (method: string): void => {
149
+ const stdin = proc.stdin;
150
+ if (closed || !stdin || typeof stdin === "number") return;
151
+ stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method })}\n`);
152
+ };
153
+
111
154
  const close = (): void => {
112
155
  closed = true;
113
156
  failAll(new Error("MCP process closed"));
@@ -118,7 +161,7 @@ export async function loadStdioMcpTools(
118
161
  }
119
162
  };
120
163
 
121
- const initMs = 12_000;
164
+ const initMs = options.initTimeoutMs ?? 12_000;
122
165
  let listed: {
123
166
  tools?: Array<{
124
167
  name: string;
@@ -136,7 +179,7 @@ export async function loadStdioMcpTools(
136
179
  capabilities: {},
137
180
  clientInfo: { name: "caelence-harness", version: "0.1.0" },
138
181
  });
139
- await rpc("notifications/initialized").catch(() => undefined);
182
+ notify("notifications/initialized");
140
183
  return rpc("tools/list");
141
184
  })(),
142
185
  new Promise<never>((_, reject) => {
@@ -155,7 +198,7 @@ export async function loadStdioMcpTools(
155
198
  };
156
199
  } catch (err) {
157
200
  close();
158
- throw err;
201
+ throw await withStderr(err instanceof Error ? err : new Error(String(err)));
159
202
  } finally {
160
203
  if (timer) clearTimeout(timer);
161
204
  }
@@ -171,7 +214,7 @@ export async function loadStdioMcpTools(
171
214
  async handler(input) {
172
215
  try {
173
216
  const result = (await rpc("tools/call", { name: t.name, arguments: input })) as ToolResult;
174
- if (result && Array.isArray(result.content)) return result;
217
+ if (result && Array.isArray(result.content)) return textOnlyResult(result);
175
218
  if (result && typeof result === "object")
176
219
  return jsonResult(result as unknown as Record<string, unknown>);
177
220
  return textResult(String(result ?? ""));
@@ -183,3 +226,20 @@ export async function loadStdioMcpTools(
183
226
 
184
227
  return { tools, close };
185
228
  }
229
+
230
+ /**
231
+ * The harness only carries text tool results. Replace image, audio, and resource blocks
232
+ * with a short placeholder so the model never sees `undefined`.
233
+ */
234
+ export function textOnlyResult(result: ToolResult): ToolResult {
235
+ const blocks = (result.content as unknown[]).map((block) => {
236
+ const b = block as { type?: string; text?: unknown; mimeType?: string; mime_type?: string };
237
+ if (b && b.type === "text" && typeof b.text === "string") {
238
+ return { type: "text" as const, text: b.text };
239
+ }
240
+ const kind = typeof b?.type === "string" ? b.type : "content";
241
+ const mime = b?.mimeType ?? b?.mime_type;
242
+ return { type: "text" as const, text: `[${kind}${mime ? ` ${mime}` : ""} omitted]` };
243
+ });
244
+ return { ...result, content: blocks };
245
+ }
@@ -0,0 +1,47 @@
1
+ import type { ApprovalRequest } from "../core/approval.ts";
2
+ import { isLikelyDestructive } from "../core/approval.ts";
3
+ import { clipState, readNoulAnswer } from "./client.ts";
4
+ import { decide, type ResolvedDecisions } from "./config.ts";
5
+
6
+ /**
7
+ * Decides whether a permission prompt can be skipped. It can only widen to "allow" when the
8
+ * tool call clearly matches what the user asked. It never denies: a refusal still needs a human
9
+ * or the host-side denylist. Any failure, low score, or destructive command means "ask".
10
+ */
11
+ export type ApprovalVerdict = "allow" | "ask";
12
+
13
+ export async function classifyToolApproval(
14
+ decisions: ResolvedDecisions,
15
+ req: ApprovalRequest,
16
+ userMessage: string | undefined,
17
+ signal?: AbortSignal,
18
+ ): Promise<ApprovalVerdict> {
19
+ if (!decisions.approvals) return "ask";
20
+ const command = typeof req.input.command === "string" ? req.input.command : "";
21
+ if (command && isLikelyDestructive(command)) return "ask";
22
+ if (!userMessage?.trim()) return "ask";
23
+
24
+ const json = await decide(
25
+ decisions,
26
+ {
27
+ user_message: clipState(userMessage, 1200),
28
+ tool_name: req.toolName,
29
+ tool_input: clipState(req.input),
30
+ },
31
+ {
32
+ safe_to_run: {
33
+ type: "noul",
34
+ instructions:
35
+ "Given the user's request, is this exact tool call something they asked for and safe to run without asking them first?",
36
+ criteria: {
37
+ true: "The call directly serves the request, only touches the project, and is easy to undo.",
38
+ false:
39
+ "The call is unrelated to the request, deletes or overwrites data, publishes or pushes anything, changes permissions, or reaches outside the project.",
40
+ },
41
+ },
42
+ },
43
+ signal,
44
+ );
45
+ const safe = readNoulAnswer(json, "safe_to_run");
46
+ return safe !== null && safe >= decisions.approvalThreshold ? "allow" : "ask";
47
+ }
@@ -0,0 +1,134 @@
1
+ import { OPENROUTER_DEFAULT_BASE_URL, stripTrailingSlashes } from "../config.ts";
2
+ import { PRODUCT_NAME } from "../product.ts";
3
+
4
+ /**
5
+ * Client for the OpenRouter Decisions API (https://openrouter.ai/docs/guides/community/jev).
6
+ * Decision models answer typed questions with probabilities and no text, so they cost far less
7
+ * than a chat call. Every function here returns null instead of throwing: a decision that
8
+ * cannot be made means "do what you did before", never "stop the turn".
9
+ */
10
+
11
+ /** Pinned. Probabilities shift between releases, so thresholds are tuned per version. */
12
+ export const DEFAULT_JEV_MODEL = "typesafe/jev-1.14";
13
+
14
+ /** The endpoint is alpha, so keep the wait short. A slow decision is a missed shortcut. */
15
+ export const DECISIONS_TIMEOUT_MS = 4_000;
16
+
17
+ export type FetchImpl = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
18
+
19
+ export interface ChoiceAnswerRaw {
20
+ type?: string;
21
+ choice?: string;
22
+ confidence?: number;
23
+ probabilities?: Record<string, number>;
24
+ }
25
+
26
+ export interface NoulAnswerRaw {
27
+ type?: string;
28
+ noul?: number;
29
+ }
30
+
31
+ export interface DecisionsResponse {
32
+ answers?: Record<string, ChoiceAnswerRaw | NoulAnswerRaw>;
33
+ usage?: { cost?: number; input_tokens?: number; output_tokens?: number };
34
+ }
35
+
36
+ export interface ChoiceAnswer {
37
+ choice: string;
38
+ confidence: number;
39
+ }
40
+
41
+ /** True only when the URL's hostname is openrouter.ai or one of its subdomains. */
42
+ function isOpenRouterHost(raw: string): boolean {
43
+ try {
44
+ const host = new URL(raw).hostname.toLowerCase();
45
+ return host === "openrouter.ai" || host.endsWith(".openrouter.ai");
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ /** `/api/alpha/decisions` lives beside `/api/v1`, not under it. */
52
+ export function decisionsUrl(baseUrl?: string): string {
53
+ const raw = baseUrl?.trim() || OPENROUTER_DEFAULT_BASE_URL;
54
+ if (isOpenRouterHost(raw)) return "https://openrouter.ai/api/alpha/decisions";
55
+ const origin = stripTrailingSlashes(raw)
56
+ .replace(/\/api\/v1$/, "")
57
+ .replace(/\/v1$/, "");
58
+ return `${origin}/api/alpha/decisions`;
59
+ }
60
+
61
+ export interface DecisionsRequest {
62
+ apiKey: string;
63
+ baseUrl?: string;
64
+ model?: string;
65
+ state: Record<string, unknown>;
66
+ questions: Record<string, unknown>;
67
+ timeoutMs?: number;
68
+ signal?: AbortSignal;
69
+ fetchImpl?: FetchImpl;
70
+ }
71
+
72
+ export async function submitDecisions(input: DecisionsRequest): Promise<DecisionsResponse | null> {
73
+ if (!input.apiKey.trim()) return null;
74
+ const fetchImpl = input.fetchImpl ?? globalThis.fetch;
75
+ const timeout = AbortSignal.timeout(input.timeoutMs ?? DECISIONS_TIMEOUT_MS);
76
+ const signal = input.signal ? AbortSignal.any([input.signal, timeout]) : timeout;
77
+ try {
78
+ const res = await fetchImpl(decisionsUrl(input.baseUrl), {
79
+ method: "POST",
80
+ signal,
81
+ headers: {
82
+ Authorization: `Bearer ${input.apiKey}`,
83
+ "Content-Type": "application/json",
84
+ "HTTP-Referer": "https://caelence.com",
85
+ "X-Title": PRODUCT_NAME,
86
+ },
87
+ body: JSON.stringify({
88
+ model: input.model ?? DEFAULT_JEV_MODEL,
89
+ state: input.state,
90
+ questions: input.questions,
91
+ }),
92
+ });
93
+ if (!res.ok) return null;
94
+ const json = (await res.json()) as DecisionsResponse;
95
+ return json && typeof json === "object" && json.answers ? json : null;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ function choiceConfidence(answer: ChoiceAnswerRaw): number {
102
+ if (typeof answer.confidence === "number") return answer.confidence;
103
+ const probs = Object.values(answer.probabilities ?? {});
104
+ return probs.length > 0 ? Math.max(...probs) : 0;
105
+ }
106
+
107
+ export function readChoiceAnswer(json: DecisionsResponse | null, key: string): ChoiceAnswer | null {
108
+ const answer = json?.answers?.[key] as ChoiceAnswerRaw | undefined;
109
+ if (!answer || typeof answer.choice !== "string" || !answer.choice) return null;
110
+ return { choice: answer.choice, confidence: choiceConfidence(answer) };
111
+ }
112
+
113
+ /** Probability that the answer is yes, 0 to 1. */
114
+ export function readNoulAnswer(json: DecisionsResponse | null, key: string): number | null {
115
+ const answer = json?.answers?.[key] as NoulAnswerRaw | undefined;
116
+ return typeof answer?.noul === "number" ? answer.noul : null;
117
+ }
118
+
119
+ /** Shorten long strings in a state object so a decision never ships a whole file. */
120
+ export function clipState(value: unknown, maxString = 600, depth = 0): unknown {
121
+ if (typeof value === "string") {
122
+ return value.length > maxString
123
+ ? `${value.slice(0, maxString)}… [${value.length} chars]`
124
+ : value;
125
+ }
126
+ if (depth >= 4 || value === null || typeof value !== "object") return value;
127
+ if (Array.isArray(value))
128
+ return value.slice(0, 20).map((v) => clipState(v, maxString, depth + 1));
129
+ const out: Record<string, unknown> = {};
130
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
131
+ out[key] = clipState(entry, maxString, depth + 1);
132
+ }
133
+ return out;
134
+ }
@@ -0,0 +1,83 @@
1
+ import type { HarnessConfig } from "../config.ts";
2
+ import { DEFAULT_JEV_MODEL, type FetchImpl, submitDecisions } from "./client.ts";
3
+
4
+ export interface HarnessDecisionsConfig {
5
+ /** Master switch. On by default whenever an OpenRouter key is set. */
6
+ enabled?: boolean;
7
+ /** Decision model. Default is a pinned Jev release. */
8
+ model?: string;
9
+ /** Floor for routing and shortcut choices. Default 0.6. */
10
+ minConfidence?: number;
11
+ /** Probability of "safe to run" needed to skip a permission prompt. Default 0.9. */
12
+ approvalThreshold?: number;
13
+ /** Let a host plug in direct-tool shortcuts. Default on. */
14
+ shortcuts?: boolean;
15
+ /** Skip the permission prompt when the tool call clearly matches the request. Default on. */
16
+ approvals?: boolean;
17
+ /** Skip memory extraction when the turn has nothing durable. Default on. */
18
+ memory?: boolean;
19
+ }
20
+
21
+ export interface ResolvedDecisions {
22
+ model: string;
23
+ minConfidence: number;
24
+ approvalThreshold: number;
25
+ shortcuts: boolean;
26
+ approvals: boolean;
27
+ memory: boolean;
28
+ apiKey: string;
29
+ baseUrl: string;
30
+ fetchImpl?: FetchImpl;
31
+ }
32
+
33
+ function offByEnv(env: Record<string, string | undefined>): boolean {
34
+ const raw = env.HARNESS_JEV?.trim().toLowerCase();
35
+ return raw === "0" || raw === "false" || raw === "off";
36
+ }
37
+
38
+ function unit(value: number | undefined, fallback: number): number {
39
+ return typeof value === "number" && value > 0 && value <= 1 ? value : fallback;
40
+ }
41
+
42
+ /** On unless the config or HARNESS_JEV=0 turns it off, or there is no OpenRouter key. */
43
+ export function resolveDecisions(
44
+ config: Pick<HarnessConfig, "decisions">,
45
+ apiKey: string,
46
+ baseUrl: string,
47
+ env: Record<string, string | undefined> = process.env,
48
+ fetchImpl?: FetchImpl,
49
+ ): ResolvedDecisions | undefined {
50
+ if (offByEnv(env)) return undefined;
51
+ const block = config.decisions;
52
+ if (block?.enabled === false) return undefined;
53
+ if (!apiKey.trim()) return undefined;
54
+ return {
55
+ model: (typeof block?.model === "string" ? block.model.trim() : "") || DEFAULT_JEV_MODEL,
56
+ minConfidence: unit(block?.minConfidence, 0.6),
57
+ approvalThreshold: unit(block?.approvalThreshold, 0.9),
58
+ shortcuts: block?.shortcuts !== false,
59
+ approvals: block?.approvals !== false,
60
+ memory: block?.memory !== false,
61
+ apiKey,
62
+ baseUrl,
63
+ ...(fetchImpl ? { fetchImpl } : {}),
64
+ };
65
+ }
66
+
67
+ /** Bind the key, model, and URL so a caller only supplies state and questions. */
68
+ export function decide(
69
+ resolved: ResolvedDecisions,
70
+ state: Record<string, unknown>,
71
+ questions: Record<string, unknown>,
72
+ signal?: AbortSignal,
73
+ ) {
74
+ return submitDecisions({
75
+ apiKey: resolved.apiKey,
76
+ baseUrl: resolved.baseUrl,
77
+ model: resolved.model,
78
+ state,
79
+ questions,
80
+ signal,
81
+ fetchImpl: resolved.fetchImpl,
82
+ });
83
+ }