@0perator/operator 0.0.6
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.
- package/README.md +73 -0
- package/dist/auth/client.js +94 -0
- package/dist/auth/commands.js +99 -0
- package/dist/auth/store.js +99 -0
- package/dist/background/index.js +64 -0
- package/dist/cli.js +407 -0
- package/dist/config/settings.js +85 -0
- package/dist/engine/agent.js +232 -0
- package/dist/engine/aurora.js +213 -0
- package/dist/engine/compaction.js +111 -0
- package/dist/engine/contract.js +8 -0
- package/dist/engine/messages.js +85 -0
- package/dist/engine/router-adapter.js +29 -0
- package/dist/engine/selfheal.js +46 -0
- package/dist/engine/toolcalls.js +164 -0
- package/dist/index.browser.js +22 -0
- package/dist/index.js +23 -0
- package/dist/mcp/client.js +95 -0
- package/dist/mcp/config.js +73 -0
- package/dist/mcp/index.js +101 -0
- package/dist/mcp/stdio.js +149 -0
- package/dist/memory/index.js +0 -0
- package/dist/observability/index.js +60 -0
- package/dist/permissions/audit.js +50 -0
- package/dist/permissions/index.js +48 -0
- package/dist/permissions/policy.js +54 -0
- package/dist/router/router.js +94 -0
- package/dist/session.js +265 -0
- package/dist/tools/executor.js +0 -0
- package/dist/tools/registry.js +380 -0
- package/dist/tools/sandbox.js +90 -0
- package/dist/ui/ActivitySpinner.js +48 -0
- package/dist/ui/App.js +16 -0
- package/dist/ui/AuthScreen.js +17 -0
- package/dist/ui/BgPanel.js +24 -0
- package/dist/ui/Composer.js +119 -0
- package/dist/ui/Header.js +22 -0
- package/dist/ui/StatusRule.js +11 -0
- package/dist/ui/ThinkingSpinner.js +61 -0
- package/dist/ui/ToolStep.js +32 -0
- package/dist/ui/Transcript.js +22 -0
- package/dist/ui/format.js +6 -0
- package/dist/ui/index.js +9 -0
- package/dist/ui/types.js +3 -0
- package/dist/ui/useInputHistory.js +97 -0
- package/dist/update.js +57 -0
- package/package.json +47 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Integration seam: makes Carmack's AuroraRouter (routeBySize/escalate/failover, ../router)
|
|
2
|
+
// satisfy the engine's Router contract (select/recover) that agent.ts consumes. Written by the
|
|
3
|
+
// engine lead during the tsi merge — the two lanes chose different Router shapes; this is the
|
|
4
|
+
// single adapter that binds them, and the surface kode-web imports rather than reimplementing.
|
|
5
|
+
import { AuroraRouter } from "../router/router.js";
|
|
6
|
+
const toRE = (e) => ({
|
|
7
|
+
base: e.base,
|
|
8
|
+
model: e.model,
|
|
9
|
+
ctxWindow: e.ctxLimit,
|
|
10
|
+
label: e.name,
|
|
11
|
+
});
|
|
12
|
+
function estimateTokens(messages, tools) {
|
|
13
|
+
const chars = JSON.stringify(messages).length + (tools ? JSON.stringify(tools).length : 0);
|
|
14
|
+
return Math.ceil(chars / 4); // SPEC §5 heuristic (chars/4), same as compaction.ts
|
|
15
|
+
}
|
|
16
|
+
/** Wrap an AuroraRouter so the agentic loop can call select()/recover(). */
|
|
17
|
+
export function engineRouter(inner = new AuroraRouter()) {
|
|
18
|
+
return {
|
|
19
|
+
select(messages, tools) {
|
|
20
|
+
return toRE(inner.routeBySize(estimateTokens(messages, tools)));
|
|
21
|
+
},
|
|
22
|
+
recover(failed, kind) {
|
|
23
|
+
// context_exceeded → jump to the largest window; busy/unavailable → hop to a healthy one.
|
|
24
|
+
const next = kind === "context_exceeded" ? inner.escalate() : inner.failover();
|
|
25
|
+
// If the router hands back the same endpoint, there's nowhere further to go → exhausted.
|
|
26
|
+
return next.base === failed.base ? null : toRE(next);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// A 400/413/500 whose body mentions any of these is really a context/memory-pressure failure, so the
|
|
2
|
+
// fix is a bigger window or compaction — not a blind resend.
|
|
3
|
+
const CTX_RE = /context|n_ctx|exceed|too long|too many tokens|maximum context|out of memory|kv cache/i;
|
|
4
|
+
function statusOf(err) {
|
|
5
|
+
const s = err?.status;
|
|
6
|
+
if (typeof s === "number" && Number.isFinite(s))
|
|
7
|
+
return s;
|
|
8
|
+
const m = err instanceof Error ? err.message : String(err);
|
|
9
|
+
const g = /\b([1-5]\d{2})\b/.exec(m);
|
|
10
|
+
return g ? Number(g[1]) : undefined;
|
|
11
|
+
}
|
|
12
|
+
/** What kind of failure this is, and therefore how to recover. */
|
|
13
|
+
export function classifyFailure(err) {
|
|
14
|
+
const s = statusOf(err);
|
|
15
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
16
|
+
if (s === 401 || s === 403)
|
|
17
|
+
return "auth"; // credentials — resending never helps
|
|
18
|
+
if (s === 413)
|
|
19
|
+
return "context"; // payload too large == context pressure
|
|
20
|
+
if (s === 400)
|
|
21
|
+
return CTX_RE.test(msg) ? "context" : "bad_request"; // the 400 body decides
|
|
22
|
+
if (s === 429 || (s !== undefined && s >= 500))
|
|
23
|
+
return "transient"; // rate-limit / server — back off + retry
|
|
24
|
+
if (s === undefined)
|
|
25
|
+
return "transient"; // network drop / timeout — back off + retry
|
|
26
|
+
return "bad_request"; // any other 4xx — don't spin on it
|
|
27
|
+
}
|
|
28
|
+
const BASE_BACKOFF_MS = 400;
|
|
29
|
+
const MAX_BACKOFF_MS = 8000;
|
|
30
|
+
/** Exponential backoff with full jitter (attempt is 0-based); honors a server Retry-After when present. */
|
|
31
|
+
export function backoffMs(attempt, err) {
|
|
32
|
+
const ra = err?.retryAfterMs;
|
|
33
|
+
if (typeof ra === "number" && ra > 0)
|
|
34
|
+
return Math.min(ra, MAX_BACKOFF_MS);
|
|
35
|
+
const cap = Math.min(BASE_BACKOFF_MS * 2 ** attempt, MAX_BACKOFF_MS);
|
|
36
|
+
return Math.round(cap / 2 + Math.random() * (cap / 2)); // 50-100% of the cap
|
|
37
|
+
}
|
|
38
|
+
/** Abortable sleep — rejects with onAbort() if the signal fires, so backoff can't swallow an interrupt. */
|
|
39
|
+
export function sleep(ms, signal, onAbort) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
if (signal?.aborted)
|
|
42
|
+
return reject(onAbort());
|
|
43
|
+
const t = setTimeout(resolve, ms);
|
|
44
|
+
signal?.addEventListener("abort", () => { clearTimeout(t); reject(onAbort()); }, { once: true });
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/** Coerce a raw XML parameter value string to its likely JSON type. */
|
|
2
|
+
function coerceParamValue(raw) {
|
|
3
|
+
const t = raw.trim();
|
|
4
|
+
if (t === "")
|
|
5
|
+
return "";
|
|
6
|
+
try {
|
|
7
|
+
return JSON.parse(t);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
return t; // plain string — not valid JSON, keep verbatim
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** True if a parsed JSON value looks like a tool-call object: {name, arguments|parameters}. */
|
|
14
|
+
function looksLikeToolCall(v) {
|
|
15
|
+
return typeof v === "object" && v !== null && typeof v.name === "string";
|
|
16
|
+
}
|
|
17
|
+
function toArgumentsString(v) {
|
|
18
|
+
const raw = v.arguments !== undefined ? v.arguments : v.parameters;
|
|
19
|
+
if (raw === undefined)
|
|
20
|
+
return "{}";
|
|
21
|
+
return typeof raw === "string" ? raw : JSON.stringify(raw);
|
|
22
|
+
}
|
|
23
|
+
/** Parse Qwen XML: <function=NAME><parameter=P>V</parameter>...</function> from inside a <tool_call> body. */
|
|
24
|
+
function parseQwenXmlFunction(body) {
|
|
25
|
+
const fnMatch = /<function=([^>]+)>([\s\S]*?)<\/function>/.exec(body);
|
|
26
|
+
if (!fnMatch)
|
|
27
|
+
return null;
|
|
28
|
+
const name = fnMatch[1].trim();
|
|
29
|
+
const paramsBody = fnMatch[2];
|
|
30
|
+
const args = {};
|
|
31
|
+
const paramRe = /<parameter=([^>]+)>([\s\S]*?)<\/parameter>/g;
|
|
32
|
+
let m;
|
|
33
|
+
while ((m = paramRe.exec(paramsBody))) {
|
|
34
|
+
args[m[1].trim()] = coerceParamValue(m[2]);
|
|
35
|
+
}
|
|
36
|
+
return { name, args };
|
|
37
|
+
}
|
|
38
|
+
/** Scan `text` for balanced `{...}` spans (top-level only) and return each raw substring + its [start,end). */
|
|
39
|
+
function findBalancedJsonSpans(text) {
|
|
40
|
+
const spans = [];
|
|
41
|
+
let depth = 0;
|
|
42
|
+
let start = -1;
|
|
43
|
+
let inString = false;
|
|
44
|
+
let escape = false;
|
|
45
|
+
for (let i = 0; i < text.length; i++) {
|
|
46
|
+
const ch = text[i];
|
|
47
|
+
if (inString) {
|
|
48
|
+
if (escape)
|
|
49
|
+
escape = false;
|
|
50
|
+
else if (ch === "\\")
|
|
51
|
+
escape = true;
|
|
52
|
+
else if (ch === '"')
|
|
53
|
+
inString = false;
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
if (ch === '"') {
|
|
57
|
+
inString = true;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (ch === "{") {
|
|
61
|
+
if (depth === 0)
|
|
62
|
+
start = i;
|
|
63
|
+
depth++;
|
|
64
|
+
}
|
|
65
|
+
else if (ch === "}") {
|
|
66
|
+
if (depth > 0) {
|
|
67
|
+
depth--;
|
|
68
|
+
if (depth === 0 && start >= 0) {
|
|
69
|
+
spans.push({ start, end: i + 1, raw: text.slice(start, i + 1) });
|
|
70
|
+
start = -1;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return spans;
|
|
76
|
+
}
|
|
77
|
+
let recoveryCounter = 0;
|
|
78
|
+
function nextRecoveredId() {
|
|
79
|
+
recoveryCounter += 1;
|
|
80
|
+
return `rc_${Date.now().toString(36)}_${recoveryCounter}`;
|
|
81
|
+
}
|
|
82
|
+
function buildToolCall(name, args) {
|
|
83
|
+
return {
|
|
84
|
+
id: nextRecoveredId(),
|
|
85
|
+
type: "function",
|
|
86
|
+
function: { name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) },
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Extract tool calls emitted as text. Removes every recognized span from the content so
|
|
91
|
+
* `cleanedContent` is safe to show/store as the assistant's prose.
|
|
92
|
+
*/
|
|
93
|
+
export function recoverToolCalls(content) {
|
|
94
|
+
const calls = [];
|
|
95
|
+
let remaining = "";
|
|
96
|
+
let cursor = 0;
|
|
97
|
+
// Pass 1: <tool_call>...</tool_call> — try JSON first, then Qwen XML.
|
|
98
|
+
const tagRe = /<tool_call>([\s\S]*?)<\/tool_call>/g;
|
|
99
|
+
let m;
|
|
100
|
+
while ((m = tagRe.exec(content))) {
|
|
101
|
+
remaining += content.slice(cursor, m.index);
|
|
102
|
+
cursor = m.index + m[0].length;
|
|
103
|
+
const body = m[1].trim();
|
|
104
|
+
let recognized = false;
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(body);
|
|
107
|
+
if (looksLikeToolCall(parsed)) {
|
|
108
|
+
calls.push(buildToolCall(parsed.name, toArgumentsString(parsed)));
|
|
109
|
+
recognized = true;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
const xml = parseQwenXmlFunction(body);
|
|
114
|
+
if (xml) {
|
|
115
|
+
calls.push(buildToolCall(xml.name, xml.args));
|
|
116
|
+
recognized = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (!recognized)
|
|
120
|
+
remaining += m[0]; // unrecognized — leave it visible rather than silently eating it
|
|
121
|
+
}
|
|
122
|
+
remaining += content.slice(cursor);
|
|
123
|
+
// Pass 2: fenced ```json / ```tool_call blocks.
|
|
124
|
+
let afterFences = "";
|
|
125
|
+
cursor = 0;
|
|
126
|
+
const fenceRe = /```(?:json|tool_call)?\s*\n?([\s\S]*?)```/g;
|
|
127
|
+
while ((m = fenceRe.exec(remaining))) {
|
|
128
|
+
afterFences += remaining.slice(cursor, m.index);
|
|
129
|
+
cursor = m.index + m[0].length;
|
|
130
|
+
const body = m[1].trim();
|
|
131
|
+
let recognized = false;
|
|
132
|
+
try {
|
|
133
|
+
const parsed = JSON.parse(body);
|
|
134
|
+
if (looksLikeToolCall(parsed)) {
|
|
135
|
+
calls.push(buildToolCall(parsed.name, toArgumentsString(parsed)));
|
|
136
|
+
recognized = true;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
// not JSON — leave the fence alone, it's probably a real code block in the reply
|
|
141
|
+
}
|
|
142
|
+
if (!recognized)
|
|
143
|
+
afterFences += m[0];
|
|
144
|
+
}
|
|
145
|
+
afterFences += remaining.slice(cursor);
|
|
146
|
+
// Pass 3: bare top-level JSON objects shaped like a tool call.
|
|
147
|
+
let final = "";
|
|
148
|
+
cursor = 0;
|
|
149
|
+
for (const span of findBalancedJsonSpans(afterFences)) {
|
|
150
|
+
try {
|
|
151
|
+
const parsed = JSON.parse(span.raw);
|
|
152
|
+
if (looksLikeToolCall(parsed)) {
|
|
153
|
+
final += afterFences.slice(cursor, span.start);
|
|
154
|
+
cursor = span.end;
|
|
155
|
+
calls.push(buildToolCall(parsed.name, toArgumentsString(parsed)));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
// not valid JSON on its own (e.g. spans false-positived across prose) — leave as-is
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
final += afterFences.slice(cursor);
|
|
163
|
+
return { calls, cleanedContent: final.replace(/\n{3,}/g, "\n\n").trim() };
|
|
164
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Browser-safe EngineClient entry (for kode-web / any DOM host). Same engine surface as
|
|
2
|
+
// index.ts but WITHOUT the node-only tool registry/executor (fs/child_process/etc). A browser
|
|
3
|
+
// host injects its own ToolExecutor (e.g. Electron main-process IPC), so it never needs the
|
|
4
|
+
// node tools here — importing this entry keeps node built-ins out of the web bundle.
|
|
5
|
+
export { ENGINE_CONTRACT } from "./engine/contract.js";
|
|
6
|
+
export { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
7
|
+
export { runTurn, TurnAbortedError } from "./engine/agent.js";
|
|
8
|
+
export { Conversation, buildMessages, assertValidMessages } from "./engine/messages.js";
|
|
9
|
+
export { streamChat, chat, health } from "./engine/aurora.js";
|
|
10
|
+
export { recoverToolCalls } from "./engine/toolcalls.js";
|
|
11
|
+
export { needsCompaction, compact, summaryPrompt, clampMaxTokens } from "./engine/compaction.js";
|
|
12
|
+
export { classifyFailure } from "./engine/selfheal.js"; // failure classification — pinned by conformance
|
|
13
|
+
export { engineRouter } from "./engine/router-adapter.js";
|
|
14
|
+
export { AuroraRouter } from "./router/router.js";
|
|
15
|
+
// MCP fleet-tool surface (SPEC §10), browser/JSCore-safe. The whole subsystem is node-free AT LOAD
|
|
16
|
+
// (config.ts + stdio.ts load node builtins lazily via variable-specifier imports), so this stays out of
|
|
17
|
+
// the neutral bundle's static graph. A browser/JSCore host builds `new McpHub([...http servers])` (its own
|
|
18
|
+
// injected list — NOT loadMcpConfig, which reads a file) and wraps its executor with withMcp. stdio
|
|
19
|
+
// servers are node-only and simply never instantiated off-node. McpHttpClient is pure fetch.
|
|
20
|
+
export { McpHub, withMcp } from "./mcp/index.js";
|
|
21
|
+
export { McpHttpClient } from "./mcp/client.js";
|
|
22
|
+
// NOTE: no ./tools/* here — those touch node fs/child_process. Web injects its own ToolExecutor.
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// kode-tsi FULL public surface (Node) — the "EngineClient" contract plus the node-only tool registry.
|
|
2
|
+
// Browser/JSCore hosts (kode-web, kode-mobile) import the node-free `./index.browser.js` instead and
|
|
3
|
+
// inject their own ToolExecutor; that barrel — not this one — is the shared engine bundle. This entry
|
|
4
|
+
// is for the Node CLI. kode-mobile's Swift is UI-only over the JS bundle (no engine reimplementation).
|
|
5
|
+
export { ENGINE_CONTRACT } from "./engine/contract.js";
|
|
6
|
+
export { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
7
|
+
export { runTurn, TurnAbortedError } from "./engine/agent.js";
|
|
8
|
+
export { Conversation, buildMessages, assertValidMessages } from "./engine/messages.js";
|
|
9
|
+
export { streamChat, chat, health } from "./engine/aurora.js";
|
|
10
|
+
export { recoverToolCalls } from "./engine/toolcalls.js";
|
|
11
|
+
export { needsCompaction, compact, summaryPrompt, clampMaxTokens } from "./engine/compaction.js";
|
|
12
|
+
export { classifyFailure } from "./engine/selfheal.js";
|
|
13
|
+
export { engineRouter } from "./engine/router-adapter.js";
|
|
14
|
+
export { AuroraRouter } from "./router/router.js";
|
|
15
|
+
export { Executor } from "./tools/executor.js";
|
|
16
|
+
export { registry, toSchemas } from "./tools/registry.js";
|
|
17
|
+
// MCP fleet-tool surface (SPEC §10) — the node barrel exposes the FULL subsystem (http + stdio + config
|
|
18
|
+
// file), for hosts that run in node (the CLI, and kode-web's Electron main process where the hub lives).
|
|
19
|
+
export { McpHub, withMcp } from "./mcp/index.js";
|
|
20
|
+
export { loadMcpConfig } from "./mcp/config.js";
|
|
21
|
+
export { McpHttpClient } from "./mcp/client.js";
|
|
22
|
+
// UI (kode-web can reuse these Ink components' patterns; kode-web renders its own React DOM tree)
|
|
23
|
+
export { App } from "./ui/index.js";
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** Flatten an MCP tools/call result's content array to a single string (shared by both transports). */
|
|
2
|
+
export function flattenResult(result) {
|
|
3
|
+
const text = (result?.content ?? [])
|
|
4
|
+
.map((c) => (c.type === "text" ? c.text ?? "" : `[${c.type}]`))
|
|
5
|
+
.join("\n")
|
|
6
|
+
.trim();
|
|
7
|
+
const out = text || "(no content)";
|
|
8
|
+
return result?.isError ? `error: ${out}` : out;
|
|
9
|
+
}
|
|
10
|
+
let RPC_ID = 0;
|
|
11
|
+
export class McpHttpClient {
|
|
12
|
+
url;
|
|
13
|
+
headers;
|
|
14
|
+
timeoutMs;
|
|
15
|
+
initializing = null; // memoized handshake — concurrent callers await the SAME one
|
|
16
|
+
constructor(url, headers = {}, timeoutMs = 20_000) {
|
|
17
|
+
this.url = url;
|
|
18
|
+
this.headers = headers;
|
|
19
|
+
this.timeoutMs = timeoutMs;
|
|
20
|
+
}
|
|
21
|
+
/** One JSON-RPC round-trip. Rejects on transport/HTTP/RPC error — callers (the hub) catch and degrade. */
|
|
22
|
+
async rpc(method, params = {}) {
|
|
23
|
+
const ctrl = new AbortController();
|
|
24
|
+
const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetch(this.url, {
|
|
27
|
+
method: "POST",
|
|
28
|
+
signal: ctrl.signal,
|
|
29
|
+
headers: {
|
|
30
|
+
"content-type": "application/json",
|
|
31
|
+
accept: "application/json, text/event-stream",
|
|
32
|
+
...this.headers,
|
|
33
|
+
},
|
|
34
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: ++RPC_ID, method, params }),
|
|
35
|
+
});
|
|
36
|
+
if (!res.ok)
|
|
37
|
+
throw new Error(`HTTP ${res.status}`);
|
|
38
|
+
const body = await res.text();
|
|
39
|
+
const msg = parseRpcBody(body);
|
|
40
|
+
if (msg && typeof msg === "object" && "error" in msg && msg.error) {
|
|
41
|
+
const e = msg.error;
|
|
42
|
+
throw new Error(`RPC error: ${e.message ?? JSON.stringify(msg.error)}`);
|
|
43
|
+
}
|
|
44
|
+
return msg?.result;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
clearTimeout(timer);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** Best-effort handshake. Lenient servers don't require it (compose.casa answers tools/list cold),
|
|
51
|
+
* but strict ones do — so we send it once and ignore failures rather than hard-gating on it. */
|
|
52
|
+
ensureInit() {
|
|
53
|
+
// Memoize the in-flight handshake: two concurrent first calls (e.g. listTools + callTool) must
|
|
54
|
+
// await the SAME initialize, not race past a boolean flag before the server has initialized.
|
|
55
|
+
if (!this.initializing) {
|
|
56
|
+
this.initializing = this.rpc("initialize", {
|
|
57
|
+
protocolVersion: "2024-11-05",
|
|
58
|
+
capabilities: {},
|
|
59
|
+
clientInfo: { name: "operator", version: "0.0.1" },
|
|
60
|
+
}).then(() => { }, () => { });
|
|
61
|
+
}
|
|
62
|
+
return this.initializing;
|
|
63
|
+
}
|
|
64
|
+
async listTools() {
|
|
65
|
+
await this.ensureInit();
|
|
66
|
+
const result = (await this.rpc("tools/list"));
|
|
67
|
+
return result?.tools ?? [];
|
|
68
|
+
}
|
|
69
|
+
async callTool(name, args) {
|
|
70
|
+
await this.ensureInit();
|
|
71
|
+
const result = (await this.rpc("tools/call", { name, arguments: args }));
|
|
72
|
+
return flattenResult(result);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Parse a JSON-RPC reply that may be plain JSON or an SSE stream (one or more `data:` lines). */
|
|
76
|
+
function parseRpcBody(body) {
|
|
77
|
+
const trimmed = body.trim();
|
|
78
|
+
if (trimmed.startsWith("{") || trimmed.startsWith("["))
|
|
79
|
+
return JSON.parse(trimmed);
|
|
80
|
+
// SSE framing: take the last non-empty `data:` payload that parses as a JSON-RPC message.
|
|
81
|
+
const datas = trimmed
|
|
82
|
+
.split("\n")
|
|
83
|
+
.filter((l) => l.startsWith("data:"))
|
|
84
|
+
.map((l) => l.slice(5).trim())
|
|
85
|
+
.filter(Boolean);
|
|
86
|
+
for (let i = datas.length - 1; i >= 0; i--) {
|
|
87
|
+
try {
|
|
88
|
+
return JSON.parse(datas[i]);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
/* try the next-earlier data line */
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
throw new Error("unparseable MCP response");
|
|
95
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// MCP config loader — SPEC §10. Reads the same mcp_servers.json the Python core uses (keyed by server
|
|
2
|
+
// name; each entry `transport` = "stdio" | "http" with command/args/env or url/headers), expands ${VAR}
|
|
3
|
+
// placeholders from the environment merged with a gitignored .mcp_secrets.json (so the committed config
|
|
4
|
+
// never carries real bearer tokens — same contract as the Python `_load_secrets`/`_expand`), and
|
|
5
|
+
// normalizes CC's `type` alias onto `transport`. Never throws — a missing/garbled file yields {}.
|
|
6
|
+
//
|
|
7
|
+
// node:fs/os/path are loaded LAZILY through a variable-specifier indirection (never a literal import) so
|
|
8
|
+
// this module is node-free AT LOAD — safe to pull into the browser/JSCore engine bundle (index.browser.ts).
|
|
9
|
+
// esbuild --platform=neutral can't resolve a variable specifier, so it leaves these as true runtime
|
|
10
|
+
// imports on the node path. A browser host only uses http MCP servers and injects its config directly;
|
|
11
|
+
// this file-reading path is the node CLI / Electron-main path and never runs in JSCore.
|
|
12
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
13
|
+
const env = () => (typeof process !== "undefined" ? process.env : {});
|
|
14
|
+
const VAR_RE = /\$\{([A-Z0-9_]+)\}/g;
|
|
15
|
+
async function defaultPath(file) {
|
|
16
|
+
const { homedir } = await nodeImport("node:os");
|
|
17
|
+
const { join } = await nodeImport("node:path");
|
|
18
|
+
return join(homedir(), ".axe", "cli", "backend", file);
|
|
19
|
+
}
|
|
20
|
+
async function readJson(path) {
|
|
21
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
22
|
+
return JSON.parse(await readFile(path, "utf8"));
|
|
23
|
+
}
|
|
24
|
+
async function loadSecrets(secretsPath) {
|
|
25
|
+
const merged = { ...env() };
|
|
26
|
+
try {
|
|
27
|
+
Object.assign(merged, (await readJson(secretsPath)));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
/* no secrets file — env-only, fine */
|
|
31
|
+
}
|
|
32
|
+
return merged;
|
|
33
|
+
}
|
|
34
|
+
function expand(obj, secrets) {
|
|
35
|
+
if (typeof obj === "string")
|
|
36
|
+
return obj.replace(VAR_RE, (m, k) => secrets[k] ?? m);
|
|
37
|
+
if (Array.isArray(obj))
|
|
38
|
+
return obj.map((v) => expand(v, secrets));
|
|
39
|
+
if (obj && typeof obj === "object") {
|
|
40
|
+
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, expand(v, secrets)]));
|
|
41
|
+
}
|
|
42
|
+
return obj;
|
|
43
|
+
}
|
|
44
|
+
/** Load + secret-expand + normalize the server map. Returns [] on any failure (never throws). Node path
|
|
45
|
+
* only (reads a file); browser/JSCore hosts inject their http server list into McpHub directly instead. */
|
|
46
|
+
export async function loadMcpConfig(configPath = env().KODE_MCP_CONFIG, secretsPath = env().KODE_MCP_SECRETS) {
|
|
47
|
+
const cfgPath = configPath ?? (await defaultPath("mcp_servers.json"));
|
|
48
|
+
const secPath = secretsPath ?? (await defaultPath(".mcp_secrets.json"));
|
|
49
|
+
let raw;
|
|
50
|
+
try {
|
|
51
|
+
raw = (await readJson(cfgPath));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return [];
|
|
55
|
+
}
|
|
56
|
+
const secrets = await loadSecrets(secPath);
|
|
57
|
+
const servers = (raw && typeof raw === "object" && "mcpServers" in raw ? raw.mcpServers : raw) ?? {};
|
|
58
|
+
return Object.entries(servers).map(([name, cfg]) => {
|
|
59
|
+
const c = expand(cfg, secrets);
|
|
60
|
+
const t = (c.type ?? c.transport ?? (c.url ? "http" : "stdio"));
|
|
61
|
+
const transport = t === "http" || t === "sse" || t === "streamable-http" ? "http" : "stdio";
|
|
62
|
+
return {
|
|
63
|
+
name,
|
|
64
|
+
transport,
|
|
65
|
+
url: c.url,
|
|
66
|
+
headers: c.headers,
|
|
67
|
+
command: c.command,
|
|
68
|
+
args: c.args,
|
|
69
|
+
env: c.env,
|
|
70
|
+
advertise: c.advertise !== false,
|
|
71
|
+
};
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { loadMcpConfig } from "./config.js";
|
|
2
|
+
import { McpHttpClient } from "./client.js";
|
|
3
|
+
import { McpStdioClient } from "./stdio.js";
|
|
4
|
+
const SEP = ":"; // namespace separator: "compose:compose_list"
|
|
5
|
+
/** Manages the fleet's MCP servers: lazy tool discovery, namespaced dispatch, health-gated. */
|
|
6
|
+
export class McpHub {
|
|
7
|
+
servers;
|
|
8
|
+
tools = new Map(); // namespaced name → remote tool
|
|
9
|
+
clients = []; // every started client, for shutdown()
|
|
10
|
+
ready = null;
|
|
11
|
+
constructor(servers) {
|
|
12
|
+
this.servers = servers;
|
|
13
|
+
}
|
|
14
|
+
/** Build a hub from the on-disk config (mcp_servers.json). Empty/absent config → an inert hub. */
|
|
15
|
+
static async fromConfig() {
|
|
16
|
+
return new McpHub(await loadMcpConfig());
|
|
17
|
+
}
|
|
18
|
+
/** Discover tools from every advertised server (HTTP + stdio), once. Failures are per-server
|
|
19
|
+
* (a down gateway or a missing stdio binary is skipped) so the rest still register — never throws. */
|
|
20
|
+
async discover() {
|
|
21
|
+
if (this.ready)
|
|
22
|
+
return this.ready;
|
|
23
|
+
this.ready = (async () => {
|
|
24
|
+
const advertised = this.servers.filter((s) => s.advertise);
|
|
25
|
+
await Promise.all(advertised.map(async (s) => {
|
|
26
|
+
const client = this.buildClient(s);
|
|
27
|
+
if (!client)
|
|
28
|
+
return;
|
|
29
|
+
this.clients.push(client);
|
|
30
|
+
try {
|
|
31
|
+
for (const def of await client.listTools()) {
|
|
32
|
+
this.tools.set(`${s.name}${SEP}${def.name}`, { server: s.name, client, def });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
client.stop?.(); // unreachable HTTP or a stdio binary that failed to start — drop it
|
|
37
|
+
}
|
|
38
|
+
}));
|
|
39
|
+
})();
|
|
40
|
+
return this.ready;
|
|
41
|
+
}
|
|
42
|
+
buildClient(s) {
|
|
43
|
+
if (s.transport === "http")
|
|
44
|
+
return s.url ? new McpHttpClient(s.url, s.headers ?? {}) : null;
|
|
45
|
+
return s.command ? new McpStdioClient(s.command, s.args ?? [], s.env ?? {}) : null;
|
|
46
|
+
}
|
|
47
|
+
/** Kill any spawned stdio servers (HTTP clients are stateless). Call on shell exit. */
|
|
48
|
+
shutdown() {
|
|
49
|
+
for (const c of this.clients)
|
|
50
|
+
c.stop?.();
|
|
51
|
+
}
|
|
52
|
+
/** Is a tool name one of ours (namespaced and known)? */
|
|
53
|
+
has(name) {
|
|
54
|
+
return this.tools.has(name);
|
|
55
|
+
}
|
|
56
|
+
/** OpenAI-format function schemas for every discovered remote tool (namespaced names). */
|
|
57
|
+
schemas() {
|
|
58
|
+
return [...this.tools.values()].map((t) => ({
|
|
59
|
+
type: "function",
|
|
60
|
+
function: {
|
|
61
|
+
name: `${t.server}${SEP}${t.def.name}`,
|
|
62
|
+
description: `[mcp:${t.server}] ${t.def.description ?? ""}`.trim(),
|
|
63
|
+
parameters: t.def.inputSchema ?? { type: "object", properties: {} },
|
|
64
|
+
},
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
/** Dispatch a namespaced remote call. Resolves to a string even on error (never rejects). */
|
|
68
|
+
async call(name, args) {
|
|
69
|
+
const t = this.tools.get(name);
|
|
70
|
+
if (!t)
|
|
71
|
+
return `error: unknown MCP tool ${name}`;
|
|
72
|
+
try {
|
|
73
|
+
return await t.client.callTool(t.def.name, args);
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
return `error calling ${name}: ${e instanceof Error ? e.message : String(e)}`;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
toolCount() {
|
|
80
|
+
return this.tools.size;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Compose the local executor with the MCP hub: local tools win, a namespaced name routes to MCP.
|
|
84
|
+
* With no hub (or an inert one) this is the local executor plus empty schemas — zero behavior change. */
|
|
85
|
+
export function withMcp(local, hub) {
|
|
86
|
+
return {
|
|
87
|
+
ready: () => hub?.discover() ?? Promise.resolve(),
|
|
88
|
+
mcpSchemas: () => hub?.schemas() ?? [],
|
|
89
|
+
execute: (name, args) => (hub?.has(name) ? hub.call(name, args) : local.execute(name, args)),
|
|
90
|
+
executeParallel: async (calls) => {
|
|
91
|
+
// Route each call to its lane, preserving order. Local calls keep the executor's own
|
|
92
|
+
// read-only/mutating parallelism; MCP calls run concurrently (they're remote & independent).
|
|
93
|
+
const localCalls = calls.filter((c) => !hub?.has(c.name));
|
|
94
|
+
const localResults = localCalls.length ? await local.executeParallel(localCalls) : [];
|
|
95
|
+
const localByIdx = new Map();
|
|
96
|
+
localCalls.forEach((c, i) => localByIdx.set(c.id, localResults[i]));
|
|
97
|
+
const mcpResults = await Promise.all(calls.map((c) => (hub?.has(c.name) ? hub.call(c.name, c.args) : Promise.resolve(localByIdx.get(c.id) ?? ""))));
|
|
98
|
+
return mcpResults;
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|