replicas-engine 0.1.1684 → 0.1.1687

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.
@@ -0,0 +1,338 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'node:module';
3
+ const require = __createRequire(import.meta.url);
4
+ import {
5
+ getManagedPiMcpServers,
6
+ managedMcpServerProcess
7
+ } from "./chunk-BXZA2HFS.js";
8
+ import "./chunk-7ZDAVYTV.js";
9
+ import "./chunk-NYAS7KNX.js";
10
+ import {
11
+ isRecord
12
+ } from "./chunk-UZSNFLDQ.js";
13
+ import {
14
+ rankToolsByQuery
15
+ } from "./chunk-25TILJOA.js";
16
+ import "./chunk-VEQXQN22.js";
17
+
18
+ // src/codemode-mcp.ts
19
+ import { parseArgs } from "util";
20
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
21
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
22
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
23
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
24
+ import quickjsVariant from "@jitl/quickjs-singlefile-mjs-release-sync";
25
+ import { newQuickJSWASMModuleFromVariant } from "quickjs-emscripten-core";
26
+ import { z } from "zod";
27
+
28
+ // src/utils/codemode-catalog.ts
29
+ var DESCRIPTION_LIMIT_CHARS = 1200;
30
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
31
+ function typeOf(root, docs) {
32
+ const resolve = (schema, seen) => {
33
+ if (!isRecord(schema)) return schema;
34
+ if (typeof schema.$ref === "string") {
35
+ if (seen.includes(schema.$ref) || !schema.$ref.startsWith("#/")) return void 0;
36
+ seen.push(schema.$ref);
37
+ return resolve(schema.$ref.slice(2).split("/").reduce((node, key) => isRecord(node) ? node[key.replace(/~1/g, "/").replace(/~0/g, "~")] : void 0, root), seen);
38
+ }
39
+ if (!Array.isArray(schema.allOf)) return schema;
40
+ const { allOf, ...own } = schema;
41
+ const parts = [...allOf.map((part) => resolve(part, seen)), own].filter(isRecord);
42
+ return {
43
+ ...Object.assign({}, ...parts),
44
+ properties: Object.assign({}, ...parts.map((part) => part.properties)),
45
+ required: parts.flatMap((part) => Array.isArray(part.required) ? part.required : [])
46
+ };
47
+ };
48
+ const render = (unresolved, indent, refs) => {
49
+ const seen = [...refs];
50
+ const schema = resolve(unresolved, seen);
51
+ if (!isRecord(schema)) return "unknown";
52
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
53
+ if (schema.const !== void 0) return JSON.stringify(schema.const);
54
+ const union = [schema.anyOf, schema.oneOf].find(Array.isArray);
55
+ if (union) return [...new Set(union.map((member) => render(member, indent, seen)))].join(" | ");
56
+ if (Array.isArray(schema.type)) return schema.type.map((type) => render({ ...schema, type }, indent, seen)).join(" | ");
57
+ if (schema.type === "array") {
58
+ const item = render(schema.items, indent, seen);
59
+ return item.includes(" | ") ? `(${item})[]` : `${item}[]`;
60
+ }
61
+ if (schema.type === "object" || isRecord(schema.properties)) {
62
+ const properties = isRecord(schema.properties) ? Object.entries(schema.properties) : [];
63
+ if (properties.length === 0) return isRecord(schema.additionalProperties) ? `Record<string, ${render(schema.additionalProperties, indent, seen)}>` : "object";
64
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
65
+ const fields = properties.map(([key, value]) => {
66
+ const field = `${IDENTIFIER.test(key) ? key : JSON.stringify(key)}${required.has(key) ? "" : "?"}: ${render(value, `${indent} `, seen)}`;
67
+ const note = docs && isRecord(value) && typeof value.description === "string" ? ` // ${value.description.replace(/\s+/g, " ")}` : "";
68
+ return docs ? `${indent} ${field};${note}` : field;
69
+ });
70
+ return docs ? `{
71
+ ${fields.join("\n")}
72
+ ${indent}}` : `{ ${fields.join(", ")} }`;
73
+ }
74
+ if (schema.type === "integer" || schema.type === "number") return typeof schema.maximum === "number" ? `number /* max ${schema.maximum} */` : "number";
75
+ return typeof schema.type === "string" ? schema.type : "unknown";
76
+ };
77
+ return render(root, "", []);
78
+ }
79
+ function callExpression(tool, docs) {
80
+ const input = typeOf(tool.inputSchema, docs);
81
+ return `${IDENTIFIER.test(tool.name) ? tool.name : `[${JSON.stringify(tool.name)}]`}(${input === "object" ? "" : input})`;
82
+ }
83
+ function toolSignature(tool, docs) {
84
+ const expression = callExpression(tool, docs);
85
+ const signature = `tools.${tool.namespace}${expression.startsWith("[") ? "" : "."}${expression}: Promise<${typeOf(tool.outputSchema, docs)}>`;
86
+ if (!docs || !tool.description) return signature;
87
+ const description = tool.description.length > DESCRIPTION_LIMIT_CHARS ? `${tool.description.slice(0, DESCRIPTION_LIMIT_CHARS)}...` : tool.description;
88
+ return `/** ${description.trim()} */
89
+ ${signature}`;
90
+ }
91
+ function searchTools(catalog2, query, namespace) {
92
+ const scoped = namespace ? catalog2.filter((tool) => tool.namespace === namespace) : catalog2;
93
+ return query.trim() ? rankToolsByQuery(scoped, query, (tool) => ({ name: `${tool.namespace}.${tool.name}`, description: tool.description })) : scoped;
94
+ }
95
+ function renderCatalog(catalog2, failed2, connecting2, budgetChars) {
96
+ const namespaces = [...Map.groupBy(catalog2, (tool) => tool.namespace)];
97
+ const render = (list) => namespaces.map(([namespace, tools]) => `tools.${namespace} (${tools.length} tool${tools.length === 1 ? "" : "s"})${list(tools)}`).join("\n");
98
+ const listing = [
99
+ render((tools) => `:
100
+ ${tools.map((tool) => ` ${callExpression(tool, false)}`).join("\n")}`),
101
+ render((tools) => `: ${tools.map((tool) => tool.name).join(", ")}`)
102
+ ].find((candidate) => candidate.length <= budgetChars) ?? render(() => "");
103
+ return [
104
+ catalog2.length ? `Tools:
105
+ ${listing}` : "No MCP server is connected yet, so there are no tools to call.",
106
+ ...connecting2.length ? [`Still connecting, find their tools with \`search\`: ${connecting2.join(", ")}`] : [],
107
+ ...failed2.length ? [`Failed to connect: ${failed2.join(", ")}`] : []
108
+ ].join("\n");
109
+ }
110
+
111
+ // src/codemode-mcp.ts
112
+ var { values } = parseArgs({ options: { config: { type: "string" } }, strict: true });
113
+ var LISTING_BUDGET_CHARS = 8e3;
114
+ var STARTUP_WAIT_MS = 6e3;
115
+ var DEFAULT_EXECUTE_TIMEOUT_MS = 12e4;
116
+ var MAX_EXECUTE_TIMEOUT_MS = 30 * 6e4;
117
+ var MAX_OUTPUT_CHARS = 4e4;
118
+ var servers = Object.entries(await getManagedPiMcpServers(values.config));
119
+ var namespaceOf = (name) => name.replace(/[^A-Za-z0-9_$]/g, "_");
120
+ var namespaceOwners = new Map(servers.toReversed().map(([name]) => [namespaceOf(name), name]));
121
+ var clients = /* @__PURE__ */ new Map();
122
+ var catalog = [];
123
+ var failed = [];
124
+ var connecting = new Set(servers.map(([name]) => name));
125
+ var connections = Promise.all(servers.map(async ([name, entry]) => {
126
+ const namespace = namespaceOf(name);
127
+ try {
128
+ const owner = namespaceOwners.get(namespace);
129
+ if (owner !== name) throw new Error(`its name reads as tools.${namespace}, which ${owner} already uses; rename one`);
130
+ const client = new Client({ name: "replicas-codemode", version: "1.0.0" });
131
+ const { command, args, env } = managedMcpServerProcess(entry);
132
+ await client.connect(new StdioClientTransport({
133
+ command,
134
+ args,
135
+ env: { ...Object.fromEntries(Object.entries(process.env).filter((pair) => pair[1] !== void 0)), ...env },
136
+ stderr: "ignore"
137
+ }));
138
+ const listed = [];
139
+ for (let cursor; ; ) {
140
+ const page = await client.listTools({ cursor });
141
+ listed.push(...page.tools);
142
+ cursor = page.nextCursor;
143
+ if (!cursor) break;
144
+ }
145
+ clients.set(namespace, client);
146
+ catalog.push(...listed.map((tool) => ({ namespace, name: tool.name, description: tool.description ?? "", inputSchema: tool.inputSchema, outputSchema: tool.outputSchema })));
147
+ catalog.sort((a, b) => a.namespace.localeCompare(b.namespace) || a.name.localeCompare(b.name));
148
+ } catch (error) {
149
+ failed.push(`${name} (${error instanceof Error ? error.message : String(error)})`);
150
+ }
151
+ connecting.delete(name);
152
+ }));
153
+ await Promise.race([connections, new Promise((resolve) => setTimeout(resolve, STARTUP_WAIT_MS))]);
154
+ async function callTool(namespace, name, input, signal) {
155
+ const client = clients.get(namespace);
156
+ const tool = catalog.find((entry) => entry.namespace === namespace && entry.name === name);
157
+ if (!client || !tool) {
158
+ const closest = searchTools(catalog, `${namespace} ${name}`).slice(0, 3).map((entry) => toolSignature(entry, false));
159
+ throw new Error(`Unknown tool tools.${namespace}.${name}.${closest.length ? ` Did you mean:
160
+ ${closest.join("\n")}` : " Use the search tool to find tools."}`);
161
+ }
162
+ const result = await client.callTool({ name, arguments: isRecord(input) ? input : {} }, void 0, { signal, timeout: MAX_EXECUTE_TIMEOUT_MS, resetTimeoutOnProgress: true });
163
+ const content = Array.isArray(result.content) ? result.content : [];
164
+ const text = content.flatMap((part) => isRecord(part) && part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n");
165
+ if (result.isError) throw new Error(`tools.${namespace}.${name} failed: ${text || JSON.stringify(content)}`);
166
+ if (result.structuredContent !== void 0) return result.structuredContent;
167
+ if (text.length === 0 && content.length > 0) return content;
168
+ try {
169
+ return JSON.parse(text);
170
+ } catch {
171
+ return text;
172
+ }
173
+ }
174
+ var quickjs = await newQuickJSWASMModuleFromVariant(quickjsVariant);
175
+ var SCRIPT_MEMORY_BYTES = 256 * 1024 * 1024;
176
+ var MAX_UNBROKEN_COMPUTE_MS = 1e4;
177
+ var PRELUDE = `
178
+ globalThis.tools = new Proxy({}, { get: (_, namespace) => new Proxy({}, { get: (_, name) => (input) =>
179
+ __call(String(namespace), String(name), JSON.stringify(input === undefined ? {} : input)).then(JSON.parse) }) });
180
+ const show = (value) => {
181
+ if (typeof value === 'string') return value;
182
+ if (value instanceof Error) return value.name + ': ' + value.message;
183
+ try { return JSON.stringify(value) ?? String(value); } catch { return String(value); }
184
+ };
185
+ const log = (...values) => __log(values.map(show).join(' '));
186
+ globalThis.console = { log, info: log, warn: log, error: log, debug: log };
187
+ `;
188
+ function execute(code, timeoutMs, signal) {
189
+ return new Promise((resolve) => {
190
+ const deadline = Date.now() + timeoutMs;
191
+ const runtime = quickjs.newRuntime();
192
+ runtime.setMemoryLimit(SCRIPT_MEMORY_BYTES);
193
+ let computingSince = Date.now();
194
+ let stopped;
195
+ runtime.setInterruptHandler(() => {
196
+ if (Date.now() > deadline) stopped = `The script did not finish within ${timeoutMs} ms. Pass a larger timeout_ms if the work needs it.`;
197
+ else if (Date.now() - computingSince > MAX_UNBROKEN_COMPUTE_MS) stopped = `The script computed for more than ${MAX_UNBROKEN_COMPUTE_MS / 1e3} seconds without awaiting a tool call, so it was stopped. Check it for a loop that never ends.`;
198
+ return stopped !== void 0;
199
+ });
200
+ const lines = code.split("\n").length;
201
+ const context = runtime.newContext();
202
+ const abort = new AbortController();
203
+ const waiting = /* @__PURE__ */ new Set();
204
+ const logs = [];
205
+ let calls = 0;
206
+ let settled = false;
207
+ const settle = (outcome2) => {
208
+ if (settled) return;
209
+ settled = true;
210
+ clearTimeout(timer);
211
+ signal.removeEventListener("abort", cancel);
212
+ abort.abort();
213
+ try {
214
+ for (const deferred of waiting) deferred.dispose();
215
+ context.dispose();
216
+ runtime.dispose();
217
+ } catch {
218
+ }
219
+ const sections = [];
220
+ if (outcome2.error !== void 0) sections.push(outcome2.error);
221
+ else if (outcome2.value !== void 0) sections.push(outcome2.value);
222
+ else if (!logs.length) sections.push(`The script returned nothing${calls ? ` after ${calls} tool call${calls === 1 ? "" : "s"}` : ""}. End it with \`return <value>\` to read a result.`);
223
+ if (logs.length) sections.push(`[console]
224
+ ${logs.join("\n")}`);
225
+ const text = sections.join("\n\n");
226
+ resolve({
227
+ text: text.length > MAX_OUTPUT_CHARS ? `${text.slice(0, MAX_OUTPUT_CHARS)}
228
+
229
+ [Output cut at ${MAX_OUTPUT_CHARS} of ${text.length} characters. Return only the fields you need.]` : text,
230
+ isError: outcome2.error !== void 0
231
+ });
232
+ };
233
+ const cancel = () => settle({ error: "The call was cancelled." });
234
+ const timer = setTimeout(() => settle({ error: `The script did not finish within ${timeoutMs} ms. Pass a larger timeout_ms if the work needs it.` }), timeoutMs);
235
+ signal.addEventListener("abort", cancel);
236
+ const describe = (error) => {
237
+ if (stopped) return stopped;
238
+ if (!isRecord(error)) return String(error);
239
+ const line = Number(/script\.js:(\d+)/.exec(String(error.stack ?? ""))?.[1]) - 1;
240
+ return `${String(error.name ?? "Error")}: ${String(error.message)}${line >= 1 && line <= lines ? ` (script line ${line})` : ""}`;
241
+ };
242
+ const runJobs = () => {
243
+ if (settled) return;
244
+ computingSince = Date.now();
245
+ const jobs = runtime.executePendingJobs();
246
+ if (jobs.error) {
247
+ const error = describe(context.dump(jobs.error));
248
+ jobs.error.dispose();
249
+ settle({ error });
250
+ }
251
+ };
252
+ context.newFunction("__log", (line) => {
253
+ logs.push(context.getString(line));
254
+ }).consume((handle) => context.setProp(context.global, "__log", handle));
255
+ context.newFunction("__call", (namespace, name, input) => {
256
+ calls += 1;
257
+ const deferred = context.newPromise();
258
+ waiting.add(deferred);
259
+ const finish = (settleWith, text) => {
260
+ if (settled) return;
261
+ waiting.delete(deferred);
262
+ const value = settleWith === "resolve" ? context.newString(text) : context.newError(text);
263
+ deferred[settleWith](value);
264
+ value.dispose();
265
+ deferred.dispose();
266
+ runJobs();
267
+ };
268
+ callTool(context.getString(namespace), context.getString(name), JSON.parse(context.getString(input)), abort.signal).then(
269
+ (value) => finish("resolve", JSON.stringify(value === void 0 ? null : value)),
270
+ (error) => finish("reject", error instanceof Error ? error.message : String(error))
271
+ );
272
+ return deferred.handle;
273
+ }).consume((handle) => context.setProp(context.global, "__call", handle));
274
+ context.unwrapResult(context.evalCode(PRELUDE, "prelude.js")).dispose();
275
+ computingSince = Date.now();
276
+ const evaluated = context.evalCode(`(async () => {
277
+ ${code}
278
+ })().then((value) => { try { return typeof value === 'string' ? value : JSON.stringify(value); } catch (cause) { throw new Error("The script's return value cannot be written as JSON (" + cause.message + "). Return plain data."); } })`, "script.js");
279
+ if (evaluated.error) {
280
+ const error = context.dump(evaluated.error);
281
+ evaluated.error.dispose();
282
+ return settle({ error: `Script does not parse. ${describe(error)}` });
283
+ }
284
+ const outcome = context.resolvePromise(evaluated.value);
285
+ evaluated.value.dispose();
286
+ void outcome.then((result) => {
287
+ if (settled) return;
288
+ if (result.error) {
289
+ const error = describe(context.dump(result.error));
290
+ result.error.dispose();
291
+ return settle({ error });
292
+ }
293
+ const value = context.dump(result.value);
294
+ result.value.dispose();
295
+ settle({ value: typeof value === "string" ? value : void 0 });
296
+ });
297
+ runJobs();
298
+ });
299
+ }
300
+ var server = new McpServer({ name: "codemode", version: "1.0.0" }, {
301
+ instructions: `Tools callable inside \`execute\` as \`tools.<server>.<tool>(input)\`. A tool listed without \`(...)\` arguments needs \`search\` first to get its signature.
302
+ ${renderCatalog(catalog, failed, [...connecting], LISTING_BUDGET_CHARS)}`
303
+ });
304
+ server.registerTool("search", {
305
+ description: "Find tools callable inside `execute`. Returns each match as a TypeScript signature with its parameter docs. Pass `server` with an empty query to list the tools on one server.",
306
+ inputSchema: {
307
+ query: z.string().describe("Words describing what you need, or a tool name."),
308
+ server: z.string().optional().describe("Only search this server."),
309
+ limit: z.number().int().min(1).max(50).optional().describe("Most signatures to return. Defaults to 8."),
310
+ offset: z.number().int().min(0).optional().describe("Skip this many matches, to read past the first `limit`.")
311
+ },
312
+ annotations: { readOnlyHint: true }
313
+ }, ({ query, server: namespace, limit, offset = 0 }) => {
314
+ const matches = searchTools(catalog, query, namespace);
315
+ const shown = matches.slice(offset, offset + (limit ?? 8));
316
+ const rest = matches.length - offset - shown.length;
317
+ return { content: [{ type: "text", text: shown.length ? `${shown.map((tool) => toolSignature(tool, true)).join("\n\n")}${rest > 0 ? `
318
+
319
+ ${rest} more matched. Pass offset: ${offset + shown.length} to read on.` : ""}` : "No tools matched. Try other words, or list a server with an empty query." }] };
320
+ });
321
+ server.registerTool("execute", {
322
+ description: [
323
+ "Run JavaScript that calls tools from the connected MCP servers, and get back only what the script returns.",
324
+ "Call a tool as `await tools.<server>.<tool>({ ...input })`. It resolves to the parsed result (JSON when the tool returns JSON, otherwise text) and throws when the tool fails.",
325
+ "Do the whole job in one script: run independent calls with `Promise.all`, loop over pages, filter, join and aggregate in code, and `return` only the answer. Intermediate results stay out of your context.",
326
+ "The script is the body of an async JavaScript function: `await` and `return` work at the top level, and `console.log` output comes back with the result. It has no filesystem, shell or modules; use your other tools for those.",
327
+ "When you do not know the shape of a result, return one sample before writing the full script.",
328
+ "The servers and their tools are listed in the instructions of this MCP server."
329
+ ].join("\n"),
330
+ inputSchema: {
331
+ code: z.string().describe("The JavaScript to run."),
332
+ timeout_ms: z.number().int().min(1e3).max(MAX_EXECUTE_TIMEOUT_MS).optional().describe(`Stop the script after this long. Defaults to ${DEFAULT_EXECUTE_TIMEOUT_MS}.`)
333
+ }
334
+ }, async ({ code, timeout_ms }, { signal }) => {
335
+ const { text, isError } = await execute(code, timeout_ms ?? DEFAULT_EXECUTE_TIMEOUT_MS, signal);
336
+ return { content: [{ type: "text", text }], isError };
337
+ });
338
+ await server.connect(new StdioServerTransport());
@@ -3,13 +3,13 @@ import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import {
5
5
  evaluateCommandProtection
6
- } from "./chunk-6EPNWTJT.js";
7
- import "./chunk-IQFATVKH.js";
8
- import "./chunk-E56ZPU6O.js";
6
+ } from "./chunk-4WUIIT6Z.js";
7
+ import "./chunk-67ZXXRJ5.js";
8
+ import "./chunk-IL6OBS3T.js";
9
9
  import {
10
10
  isRecord
11
11
  } from "./chunk-UZSNFLDQ.js";
12
- import "./chunk-DRC5DLT3.js";
12
+ import "./chunk-25TILJOA.js";
13
13
  import "./chunk-VEQXQN22.js";
14
14
 
15
15
  // src/command-protection-hook.ts
@@ -14,12 +14,13 @@ import {
14
14
  recoverCompletedTurn,
15
15
  spawnMuseMsp,
16
16
  startMuseSession
17
- } from "./chunk-3UEBJH7C.js";
17
+ } from "./chunk-XL3IOGIZ.js";
18
+ import "./chunk-7ZDAVYTV.js";
18
19
  import {
19
20
  AppServerProcess,
20
21
  buildCodexAgentEnv
21
- } from "./chunk-KAVLAXPC.js";
22
- import "./chunk-E56ZPU6O.js";
22
+ } from "./chunk-JNVXGKRR.js";
23
+ import "./chunk-IL6OBS3T.js";
23
24
  import {
24
25
  AGENT,
25
26
  OPENCODE_GO_PROVIDER,
@@ -29,7 +30,7 @@ import {
29
30
  headlessAgentUsagePath,
30
31
  isRecord,
31
32
  withTimeout
32
- } from "./chunk-DRC5DLT3.js";
33
+ } from "./chunk-25TILJOA.js";
33
34
  import "./chunk-VEQXQN22.js";
34
35
 
35
36
  // src/headless-agent.ts