@ainecto/mcp 0.14.0-next.1 → 0.14.0-next.3
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/dist/bin/ainecto.js +907 -189
- package/dist/bin/ainecto.js.map +1 -1
- package/dist/bin/mcp.js +1 -1
- package/package.json +1 -1
package/dist/bin/ainecto.js
CHANGED
|
@@ -5678,7 +5678,7 @@ function legacyRoleInput(flag, envVars = process.env) {
|
|
|
5678
5678
|
|
|
5679
5679
|
// src/core/version.ts
|
|
5680
5680
|
var UNBUNDLED_VERSION = "dev";
|
|
5681
|
-
var CLI_VERSION = true ? "0.14.0-next.
|
|
5681
|
+
var CLI_VERSION = true ? "0.14.0-next.3" : UNBUNDLED_VERSION;
|
|
5682
5682
|
var PACKAGE_NAME = "@ainecto/mcp";
|
|
5683
5683
|
var CLI_USER_AGENT = `${PACKAGE_NAME} ${CLI_VERSION}`;
|
|
5684
5684
|
function bridgePackageSpec(version = CLI_VERSION) {
|
|
@@ -7806,8 +7806,8 @@ var AGENT_TODOS_POLL_COMMAND_PATH = ["agent-todos", "poll"];
|
|
|
7806
7806
|
// src/adapters/cli/generatedCommandRouter.ts
|
|
7807
7807
|
function matchGeneratedCommand(tools, argv) {
|
|
7808
7808
|
const commandTokens = argv.filter((arg) => !arg.startsWith("-"));
|
|
7809
|
-
const
|
|
7810
|
-
const match =
|
|
7809
|
+
const entries2 = buildRouteEntries(tools, enrichments);
|
|
7810
|
+
const match = entries2.filter((entry) => isPrefix(entry.path, commandTokens)).sort((a, b) => b.path.length - a.path.length)[0];
|
|
7811
7811
|
if (!match) {
|
|
7812
7812
|
return void 0;
|
|
7813
7813
|
}
|
|
@@ -7855,15 +7855,15 @@ function renderGeneratedResult(result, options) {
|
|
|
7855
7855
|
}
|
|
7856
7856
|
function buildRouteEntries(tools, presentations) {
|
|
7857
7857
|
const byName = new Map(presentations.map((presentation) => [presentation.mcpName, presentation]));
|
|
7858
|
-
const
|
|
7858
|
+
const entries2 = [];
|
|
7859
7859
|
for (const tool of tools) {
|
|
7860
7860
|
const presentation = byName.get(tool.mcpName);
|
|
7861
|
-
|
|
7861
|
+
entries2.push({ path: tool.commandPath, tool, presentation });
|
|
7862
7862
|
for (const alias of presentation?.aliases ?? []) {
|
|
7863
|
-
|
|
7863
|
+
entries2.push({ path: alias.split(/\s+/).filter(Boolean), tool, presentation });
|
|
7864
7864
|
}
|
|
7865
7865
|
}
|
|
7866
|
-
return
|
|
7866
|
+
return entries2;
|
|
7867
7867
|
}
|
|
7868
7868
|
function isPrefix(prefix, values) {
|
|
7869
7869
|
return prefix.every((value, index) => values[index] === value);
|
|
@@ -8757,8 +8757,8 @@ function stableStringify2(value) {
|
|
|
8757
8757
|
return `[${value.map(stableStringify2).join(",")}]`;
|
|
8758
8758
|
}
|
|
8759
8759
|
if (value && typeof value === "object") {
|
|
8760
|
-
const
|
|
8761
|
-
return `{${
|
|
8760
|
+
const entries2 = Object.entries(value).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
|
|
8761
|
+
return `{${entries2.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify2(item)}`).join(",")}}`;
|
|
8762
8762
|
}
|
|
8763
8763
|
return JSON.stringify(value) ?? "null";
|
|
8764
8764
|
}
|
|
@@ -11894,7 +11894,7 @@ var TermDaemon = class {
|
|
|
11894
11894
|
assertSessionName(request.name);
|
|
11895
11895
|
const entry = { name: request.name, cwd: request.cwd, command: request.command, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
11896
11896
|
const session = await this.startSession(entry, request.env, request.cols, request.rows);
|
|
11897
|
-
this.updateManifest((
|
|
11897
|
+
this.updateManifest((entries2) => [...entries2.filter((item) => item.name !== entry.name), entry]);
|
|
11898
11898
|
return { data: session.info() };
|
|
11899
11899
|
}
|
|
11900
11900
|
case "ls":
|
|
@@ -11913,7 +11913,7 @@ var TermDaemon = class {
|
|
|
11913
11913
|
const session = this.session(request.name);
|
|
11914
11914
|
this.sessions.delete(request.name);
|
|
11915
11915
|
session.kill();
|
|
11916
|
-
this.updateManifest((
|
|
11916
|
+
this.updateManifest((entries2) => entries2.filter((item) => item.name !== request.name));
|
|
11917
11917
|
return { data: { name: request.name, killed: true } };
|
|
11918
11918
|
}
|
|
11919
11919
|
case "kill-server": {
|
|
@@ -11988,7 +11988,7 @@ var TermDaemon = class {
|
|
|
11988
11988
|
if (current) {
|
|
11989
11989
|
this.sessions.delete(session.name);
|
|
11990
11990
|
if (!kept) {
|
|
11991
|
-
this.updateManifest((
|
|
11991
|
+
this.updateManifest((entries2) => entries2.filter((item) => item.name !== session.name));
|
|
11992
11992
|
}
|
|
11993
11993
|
}
|
|
11994
11994
|
this.log.write({ event: "session_exit", name: session.name, pid: session.info().pid, exitCode: exitCode2, signal, kept });
|
|
@@ -12563,10 +12563,14 @@ function restoreSummary(data) {
|
|
|
12563
12563
|
}
|
|
12564
12564
|
|
|
12565
12565
|
// src/adapters/cli/agentCommand.ts
|
|
12566
|
-
import { spawnSync } from "child_process";
|
|
12567
12566
|
import { hostname } from "os";
|
|
12568
12567
|
|
|
12569
|
-
// src/core/agent/
|
|
12568
|
+
// src/core/agent/agents.ts
|
|
12569
|
+
var AGENT_IDS = ["claude-code", "codex"];
|
|
12570
|
+
var DEFAULT_AGENT = "claude-code";
|
|
12571
|
+
function isAgentId(value) {
|
|
12572
|
+
return typeof value === "string" && AGENT_IDS.includes(value);
|
|
12573
|
+
}
|
|
12570
12574
|
function agentReplySchema(textMaxCharacters) {
|
|
12571
12575
|
return {
|
|
12572
12576
|
type: "object",
|
|
@@ -12575,8 +12579,156 @@ function agentReplySchema(textMaxCharacters) {
|
|
|
12575
12579
|
properties: { reply: { type: "string", minLength: 1, maxLength: textMaxCharacters } }
|
|
12576
12580
|
};
|
|
12577
12581
|
}
|
|
12578
|
-
|
|
12579
|
-
|
|
12582
|
+
var AINECTO_MCP_SERVER = "ainecto";
|
|
12583
|
+
function ainectoBridge(nodePath, cliScript, endpoint) {
|
|
12584
|
+
return { command: nodePath, args: [cliScript, "--endpoint", endpoint, "mcp"] };
|
|
12585
|
+
}
|
|
12586
|
+
function agentEnv(env) {
|
|
12587
|
+
const out = { ...env };
|
|
12588
|
+
delete out.AINECTO_TOKEN;
|
|
12589
|
+
return out;
|
|
12590
|
+
}
|
|
12591
|
+
|
|
12592
|
+
// src/core/agent/child.ts
|
|
12593
|
+
import { spawn as spawn4 } from "child_process";
|
|
12594
|
+
import { createInterface as createInterface3 } from "readline";
|
|
12595
|
+
|
|
12596
|
+
// src/core/agent/limits.ts
|
|
12597
|
+
var AGENT_CALL_TIMEOUT_MS = 1e4;
|
|
12598
|
+
var AGENT_RETRY_MIN_MS = 500;
|
|
12599
|
+
var AGENT_RETRY_MAX_MS = 1e4;
|
|
12600
|
+
var AGENT_TURN_TIMEOUT_MS = 15 * 6e4;
|
|
12601
|
+
var AGENT_STOP_WAIT_MS = 5e3;
|
|
12602
|
+
function nextRetryDelay(previousMs) {
|
|
12603
|
+
if (previousMs === void 0) return AGENT_RETRY_MIN_MS;
|
|
12604
|
+
return Math.min(previousMs * 2, AGENT_RETRY_MAX_MS);
|
|
12605
|
+
}
|
|
12606
|
+
|
|
12607
|
+
// src/core/agent/child.ts
|
|
12608
|
+
var spawnAgent = (command, args, options) => spawn4(command, args, { cwd: options.cwd, env: options.env, stdio: ["pipe", "pipe", "pipe"] });
|
|
12609
|
+
var STDERR_KEEP = 2e3;
|
|
12610
|
+
var STDERR_TAIL = 500;
|
|
12611
|
+
var AgentChild = class {
|
|
12612
|
+
child;
|
|
12613
|
+
stderr = "";
|
|
12614
|
+
exitInfo;
|
|
12615
|
+
exited;
|
|
12616
|
+
constructor(spawnImpl, command, args, options, hooks) {
|
|
12617
|
+
this.child = spawnImpl(command, args, options);
|
|
12618
|
+
this.child.stderr.setEncoding("utf8");
|
|
12619
|
+
this.child.stderr.on("data", (chunk) => {
|
|
12620
|
+
this.stderr = (this.stderr + chunk).slice(-STDERR_KEEP);
|
|
12621
|
+
});
|
|
12622
|
+
this.exited = new Promise((resolve4) => {
|
|
12623
|
+
const done = (code, signal) => {
|
|
12624
|
+
if (this.exitInfo) return;
|
|
12625
|
+
this.exitInfo = { code, signal, stderrTail: this.stderrTail() };
|
|
12626
|
+
hooks.exit(this.exitInfo);
|
|
12627
|
+
resolve4();
|
|
12628
|
+
};
|
|
12629
|
+
this.child.on("exit", done);
|
|
12630
|
+
this.child.on("error", (error) => {
|
|
12631
|
+
this.stderr += `
|
|
12632
|
+
${error.message}`;
|
|
12633
|
+
done(null, null);
|
|
12634
|
+
});
|
|
12635
|
+
});
|
|
12636
|
+
this.child.stdin.on("error", () => {
|
|
12637
|
+
});
|
|
12638
|
+
createInterface3({ input: this.child.stdout }).on("line", hooks.line);
|
|
12639
|
+
}
|
|
12640
|
+
get pid() {
|
|
12641
|
+
return this.child.pid ?? -1;
|
|
12642
|
+
}
|
|
12643
|
+
get alive() {
|
|
12644
|
+
return this.exitInfo === void 0;
|
|
12645
|
+
}
|
|
12646
|
+
/** 끝났으면 그 사정, 아니면 undefined. */
|
|
12647
|
+
get exit() {
|
|
12648
|
+
return this.exitInfo;
|
|
12649
|
+
}
|
|
12650
|
+
stderrTail() {
|
|
12651
|
+
return this.stderr.trim().slice(-STDERR_TAIL);
|
|
12652
|
+
}
|
|
12653
|
+
/** 한 줄 쓰기 — 이미 끝난 프로세스면 쓰지 않고 false. */
|
|
12654
|
+
writeLine(message) {
|
|
12655
|
+
if (!this.alive) return false;
|
|
12656
|
+
this.child.stdin.write(`${JSON.stringify(message)}
|
|
12657
|
+
`);
|
|
12658
|
+
return true;
|
|
12659
|
+
}
|
|
12660
|
+
async stop() {
|
|
12661
|
+
if (!this.alive) return;
|
|
12662
|
+
this.child.stdin.end();
|
|
12663
|
+
if (await this.waitExit(AGENT_STOP_WAIT_MS)) return;
|
|
12664
|
+
this.child.kill("SIGTERM");
|
|
12665
|
+
if (await this.waitExit(AGENT_STOP_WAIT_MS)) return;
|
|
12666
|
+
this.child.kill("SIGKILL");
|
|
12667
|
+
await this.waitExit(AGENT_STOP_WAIT_MS);
|
|
12668
|
+
}
|
|
12669
|
+
async waitExit(ms) {
|
|
12670
|
+
return await withDeadline(this.exited.then(() => true), ms, false);
|
|
12671
|
+
}
|
|
12672
|
+
};
|
|
12673
|
+
async function withDeadline(work, ms, fallback) {
|
|
12674
|
+
let timer;
|
|
12675
|
+
const late = new Promise((resolve4) => {
|
|
12676
|
+
timer = setTimeout(() => resolve4(fallback), ms);
|
|
12677
|
+
});
|
|
12678
|
+
try {
|
|
12679
|
+
return await Promise.race([work, late]);
|
|
12680
|
+
} finally {
|
|
12681
|
+
clearTimeout(timer);
|
|
12682
|
+
}
|
|
12683
|
+
}
|
|
12684
|
+
async function runToEnd(spawnImpl, command, args, options) {
|
|
12685
|
+
return await new Promise((resolve4) => {
|
|
12686
|
+
let stdout = "";
|
|
12687
|
+
let stderr = "";
|
|
12688
|
+
let spawnError;
|
|
12689
|
+
let timedOut = false;
|
|
12690
|
+
let child;
|
|
12691
|
+
try {
|
|
12692
|
+
child = spawnImpl(command, args, { cwd: options.cwd, env: options.env });
|
|
12693
|
+
} catch (error) {
|
|
12694
|
+
resolve4({ spawnError: error instanceof Error ? error.message : String(error), timedOut, code: null, stdout, stderrTail: "" });
|
|
12695
|
+
return;
|
|
12696
|
+
}
|
|
12697
|
+
const timer = setTimeout(() => {
|
|
12698
|
+
timedOut = true;
|
|
12699
|
+
child.kill("SIGKILL");
|
|
12700
|
+
}, options.timeoutMs);
|
|
12701
|
+
child.stdout.setEncoding("utf8");
|
|
12702
|
+
child.stderr.setEncoding("utf8");
|
|
12703
|
+
child.stdout.on("data", (chunk) => {
|
|
12704
|
+
stdout += chunk;
|
|
12705
|
+
});
|
|
12706
|
+
child.stderr.on("data", (chunk) => {
|
|
12707
|
+
stderr = (stderr + chunk).slice(-STDERR_KEEP);
|
|
12708
|
+
});
|
|
12709
|
+
child.stdin.on("error", () => {
|
|
12710
|
+
});
|
|
12711
|
+
child.stdin.end();
|
|
12712
|
+
child.on("error", (error) => {
|
|
12713
|
+
spawnError = error.code ?? error.message;
|
|
12714
|
+
});
|
|
12715
|
+
child.on("close", (code) => {
|
|
12716
|
+
clearTimeout(timer);
|
|
12717
|
+
resolve4({ spawnError, timedOut, code, stdout, stderrTail: stderr.trim().slice(-STDERR_TAIL) });
|
|
12718
|
+
});
|
|
12719
|
+
});
|
|
12720
|
+
}
|
|
12721
|
+
async function detectByVersion(spawnImpl, command, options) {
|
|
12722
|
+
const run = await runToEnd(spawnImpl, command, ["--version"], options);
|
|
12723
|
+
if (run.spawnError || run.timedOut || run.code !== 0) {
|
|
12724
|
+
return { installed: false, detail: run.spawnError ?? (run.timedOut ? "timed out" : `exit ${run.code}`) };
|
|
12725
|
+
}
|
|
12726
|
+
return { installed: true, version: run.stdout.trim().split("\n")[0]?.trim() };
|
|
12727
|
+
}
|
|
12728
|
+
|
|
12729
|
+
// src/core/agent/claudeArgs.ts
|
|
12730
|
+
function claudeMcpConfig(bridge) {
|
|
12731
|
+
return { mcpServers: { [AINECTO_MCP_SERVER]: { command: bridge.command, args: bridge.args } } };
|
|
12580
12732
|
}
|
|
12581
12733
|
function claudeAgentArgs(input) {
|
|
12582
12734
|
const args = [
|
|
@@ -12595,7 +12747,7 @@ function claudeAgentArgs(input) {
|
|
|
12595
12747
|
"--mcp-config",
|
|
12596
12748
|
JSON.stringify(input.mcpConfig),
|
|
12597
12749
|
"--allowedTools",
|
|
12598
|
-
|
|
12750
|
+
`mcp__${AINECTO_MCP_SERVER}`,
|
|
12599
12751
|
"--permission-mode",
|
|
12600
12752
|
"dontAsk",
|
|
12601
12753
|
// 허용 밖은 묻지 않고 바로 거절(헤드리스에서 묻기 = 2분 대기)
|
|
@@ -12608,19 +12760,11 @@ function claudeAgentArgs(input) {
|
|
|
12608
12760
|
}
|
|
12609
12761
|
return args;
|
|
12610
12762
|
}
|
|
12611
|
-
|
|
12612
|
-
const out = { ...env };
|
|
12613
|
-
delete out.AINECTO_TOKEN;
|
|
12614
|
-
return out;
|
|
12615
|
-
}
|
|
12616
|
-
var AINECTO_TOOL_PREFIX = "mcp__ainecto__";
|
|
12617
|
-
|
|
12618
|
-
// src/core/agent/claudeProcess.ts
|
|
12619
|
-
import { spawn as spawn4 } from "child_process";
|
|
12620
|
-
import { createInterface as createInterface3 } from "readline";
|
|
12763
|
+
var AINECTO_TOOL_PREFIX = `mcp__${AINECTO_MCP_SERVER}__`;
|
|
12621
12764
|
|
|
12622
12765
|
// src/core/agent/documents.ts
|
|
12623
12766
|
var DOCUMENT_LINE = /📄[^\n]*?\/app\/docs\/([0-9a-f]{32})(?![0-9a-f])/gu;
|
|
12767
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
12624
12768
|
function documentUuidsIn(content) {
|
|
12625
12769
|
const out = [];
|
|
12626
12770
|
for (const text of texts(content)) {
|
|
@@ -12631,133 +12775,192 @@ function documentUuidsIn(content) {
|
|
|
12631
12775
|
}
|
|
12632
12776
|
return out;
|
|
12633
12777
|
}
|
|
12778
|
+
function writeResultFacts(content) {
|
|
12779
|
+
const documents = documentUuidsIn(content);
|
|
12780
|
+
const created = /* @__PURE__ */ new Set();
|
|
12781
|
+
const cards = [];
|
|
12782
|
+
for (const value of jsonObjectsIn(content)) {
|
|
12783
|
+
const top = value;
|
|
12784
|
+
if (Array.isArray(top.created)) {
|
|
12785
|
+
for (const item of top.created) {
|
|
12786
|
+
const uuid = item?.uuid;
|
|
12787
|
+
if (typeof uuid === "string") created.add(uuid);
|
|
12788
|
+
}
|
|
12789
|
+
}
|
|
12790
|
+
collectCards(value, cards);
|
|
12791
|
+
}
|
|
12792
|
+
return { documents, createdDocuments: documents.filter((uuid) => created.has(uuid)), cards };
|
|
12793
|
+
}
|
|
12794
|
+
var WriteFactsCollector = class {
|
|
12795
|
+
facts = { documents: [], createdDocuments: [], cards: [] };
|
|
12796
|
+
add(content) {
|
|
12797
|
+
const next = writeResultFacts(content);
|
|
12798
|
+
appendUnique(this.facts.documents, next.documents);
|
|
12799
|
+
appendUnique(this.facts.createdDocuments, next.createdDocuments);
|
|
12800
|
+
appendUnique(this.facts.cards, next.cards);
|
|
12801
|
+
}
|
|
12802
|
+
snapshot() {
|
|
12803
|
+
return { documents: [...this.facts.documents], createdDocuments: [...this.facts.createdDocuments], cards: [...this.facts.cards] };
|
|
12804
|
+
}
|
|
12805
|
+
};
|
|
12806
|
+
function writeToolNames(tools) {
|
|
12807
|
+
return new Set(tools.filter((tool) => tool.annotations?.readOnlyHint !== true).map((tool) => tool.name));
|
|
12808
|
+
}
|
|
12634
12809
|
function texts(content) {
|
|
12635
12810
|
if (typeof content === "string") return [content];
|
|
12636
12811
|
if (!Array.isArray(content)) return [];
|
|
12637
12812
|
return content.flatMap((part) => part && typeof part === "object" && typeof part.text === "string" ? [part.text] : []);
|
|
12638
12813
|
}
|
|
12639
|
-
function
|
|
12640
|
-
return
|
|
12814
|
+
function jsonObjectsIn(content) {
|
|
12815
|
+
return texts(content).flatMap((text) => {
|
|
12816
|
+
if (!text.trimStart().startsWith("{")) return [];
|
|
12817
|
+
try {
|
|
12818
|
+
const value = JSON.parse(text);
|
|
12819
|
+
return value && typeof value === "object" && !Array.isArray(value) ? [value] : [];
|
|
12820
|
+
} catch {
|
|
12821
|
+
return [];
|
|
12822
|
+
}
|
|
12823
|
+
});
|
|
12641
12824
|
}
|
|
12642
|
-
|
|
12643
|
-
|
|
12644
|
-
|
|
12645
|
-
|
|
12646
|
-
|
|
12647
|
-
|
|
12648
|
-
|
|
12649
|
-
|
|
12650
|
-
|
|
12651
|
-
|
|
12825
|
+
function collectCards(value, out) {
|
|
12826
|
+
if (Array.isArray(value)) {
|
|
12827
|
+
for (const item of value) collectCards(item, out);
|
|
12828
|
+
return;
|
|
12829
|
+
}
|
|
12830
|
+
if (!value || typeof value !== "object") return;
|
|
12831
|
+
for (const [key, child] of Object.entries(value)) {
|
|
12832
|
+
if (key === "cardUuid" && typeof child === "string" && HEX32.test(child)) {
|
|
12833
|
+
if (!out.includes(child)) out.push(child);
|
|
12834
|
+
} else {
|
|
12835
|
+
collectCards(child, out);
|
|
12836
|
+
}
|
|
12837
|
+
}
|
|
12838
|
+
}
|
|
12839
|
+
function appendUnique(target, items) {
|
|
12840
|
+
for (const item of items) {
|
|
12841
|
+
if (!target.includes(item)) target.push(item);
|
|
12842
|
+
}
|
|
12652
12843
|
}
|
|
12653
12844
|
|
|
12654
|
-
// src/core/agent/
|
|
12655
|
-
var
|
|
12656
|
-
|
|
12657
|
-
|
|
12658
|
-
|
|
12659
|
-
|
|
12660
|
-
|
|
12661
|
-
|
|
12662
|
-
|
|
12663
|
-
|
|
12664
|
-
|
|
12665
|
-
|
|
12666
|
-
|
|
12667
|
-
|
|
12668
|
-
|
|
12669
|
-
|
|
12670
|
-
if (this.exitInfo) return;
|
|
12671
|
-
this.exitInfo = { code, signal };
|
|
12672
|
-
options.log.write({ event: "process_exit", pid, conversationUuid, code, signal });
|
|
12673
|
-
this.finish({ kind: "exited", code, signal, stderrTail: this.stderrTail.trim().slice(-500) });
|
|
12674
|
-
resolve4();
|
|
12675
|
-
};
|
|
12676
|
-
this.child.on("exit", done);
|
|
12677
|
-
this.child.on("error", (error) => {
|
|
12678
|
-
this.stderrTail += `
|
|
12679
|
-
${error.message}`;
|
|
12680
|
-
done(null, null);
|
|
12681
|
-
});
|
|
12682
|
-
});
|
|
12683
|
-
this.child.stdin.on("error", () => {
|
|
12684
|
-
});
|
|
12685
|
-
createInterface3({ input: this.child.stdout }).on("line", (line) => {
|
|
12686
|
-
let event;
|
|
12687
|
-
try {
|
|
12688
|
-
event = JSON.parse(line);
|
|
12689
|
-
} catch {
|
|
12690
|
-
options.log.write({ event: "bad_line", pid, length: line.length });
|
|
12691
|
-
return;
|
|
12845
|
+
// src/core/agent/claudeCode.ts
|
|
12846
|
+
var CLAUDE = "claude";
|
|
12847
|
+
function claudeCodeAdapter(deps) {
|
|
12848
|
+
return {
|
|
12849
|
+
id: "claude-code",
|
|
12850
|
+
displayName: "Claude Code",
|
|
12851
|
+
detect: () => detectByVersion(deps.spawnImpl, CLAUDE, { cwd: deps.cwd, env: deps.env, timeoutMs: AGENT_CALL_TIMEOUT_MS }),
|
|
12852
|
+
async authStatus() {
|
|
12853
|
+
const run = await runToEnd(
|
|
12854
|
+
deps.spawnImpl,
|
|
12855
|
+
CLAUDE,
|
|
12856
|
+
["auth", "status", "--json"],
|
|
12857
|
+
{ cwd: deps.cwd, env: deps.env, timeoutMs: AGENT_CALL_TIMEOUT_MS }
|
|
12858
|
+
);
|
|
12859
|
+
if (run.spawnError || run.timedOut) {
|
|
12860
|
+
return { ready: false, detail: run.spawnError ?? "timed out" };
|
|
12692
12861
|
}
|
|
12693
|
-
|
|
12862
|
+
return claudeAuthFromJson(run.stdout, run.code, run.stderrTail, hasApiKeyVariable(deps.env));
|
|
12863
|
+
},
|
|
12864
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new ClaudeCodeSession(conversationUuid, resumeRef, deps.args({ textMaxCharacters, resumeSessionId: resumeRef }), deps)
|
|
12865
|
+
};
|
|
12866
|
+
}
|
|
12867
|
+
function hasApiKeyVariable(env) {
|
|
12868
|
+
return (env.ANTHROPIC_API_KEY ?? "") !== "";
|
|
12869
|
+
}
|
|
12870
|
+
function claudeAuthFromJson(stdout, code, stderrTail, apiKeyVariable) {
|
|
12871
|
+
let parsed;
|
|
12872
|
+
try {
|
|
12873
|
+
const value = JSON.parse(stdout);
|
|
12874
|
+
if (value && typeof value === "object" && !Array.isArray(value)) parsed = value;
|
|
12875
|
+
} catch {
|
|
12876
|
+
}
|
|
12877
|
+
if (apiKeyVariable) return { ready: true, mode: "apiKey", method: "ANTHROPIC_API_KEY" };
|
|
12878
|
+
if (!parsed) {
|
|
12879
|
+
return { ready: false, detail: `unreadable auth status (exit ${code ?? "-"})${stderrTail ? `: ${stderrTail}` : ""}` };
|
|
12880
|
+
}
|
|
12881
|
+
const ready = parsed.loggedIn === true;
|
|
12882
|
+
return {
|
|
12883
|
+
ready,
|
|
12884
|
+
...ready ? { mode: "subscription" } : {},
|
|
12885
|
+
method: typeof parsed.authMethod === "string" ? parsed.authMethod : void 0,
|
|
12886
|
+
plan: typeof parsed.subscriptionType === "string" ? parsed.subscriptionType : void 0
|
|
12887
|
+
};
|
|
12888
|
+
}
|
|
12889
|
+
var ClaudeCodeSession = class {
|
|
12890
|
+
constructor(conversationUuid, resumeRef, args, deps) {
|
|
12891
|
+
this.conversationUuid = conversationUuid;
|
|
12892
|
+
this.deps = deps;
|
|
12893
|
+
this.resumed = resumeRef !== void 0;
|
|
12894
|
+
this.child = new AgentChild(deps.spawnImpl, CLAUDE, args, { cwd: deps.cwd, env: deps.env }, {
|
|
12895
|
+
line: (line) => this.onLine(line),
|
|
12896
|
+
exit: (exit) => this.onExit(exit)
|
|
12694
12897
|
});
|
|
12898
|
+
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
12695
12899
|
}
|
|
12696
12900
|
conversationUuid;
|
|
12901
|
+
deps;
|
|
12902
|
+
agent = "claude-code";
|
|
12697
12903
|
resumed;
|
|
12698
|
-
|
|
12904
|
+
sessionRef;
|
|
12699
12905
|
child;
|
|
12700
12906
|
toolNames = /* @__PURE__ */ new Map();
|
|
12701
12907
|
pending;
|
|
12702
|
-
|
|
12703
|
-
exitInfo;
|
|
12704
|
-
exited;
|
|
12908
|
+
interrupts = 0;
|
|
12705
12909
|
get pid() {
|
|
12706
|
-
return this.child.pid
|
|
12910
|
+
return this.child.pid;
|
|
12707
12911
|
}
|
|
12708
12912
|
get alive() {
|
|
12709
|
-
return this.
|
|
12913
|
+
return this.child.alive;
|
|
12710
12914
|
}
|
|
12711
|
-
|
|
12712
|
-
|
|
12713
|
-
if (
|
|
12714
|
-
return { kind: "exited", code: this.exitInfo?.code ?? null, signal: this.exitInfo?.signal ?? null, stderrTail: this.stderrTail.trim().slice(-500) };
|
|
12715
|
-
}
|
|
12915
|
+
async send(text, timeoutMs) {
|
|
12916
|
+
const exit = this.child.exit;
|
|
12917
|
+
if (exit) return { kind: "exited", ...exit };
|
|
12716
12918
|
const outcome = new Promise((resolve4) => {
|
|
12717
|
-
this.pending = { resolve: resolve4,
|
|
12718
|
-
});
|
|
12719
|
-
this.child.stdin.write(`${JSON.stringify({ type: "user", message: { role: "user", content: text } })}
|
|
12720
|
-
`);
|
|
12721
|
-
let timer;
|
|
12722
|
-
const timeout = new Promise((resolve4) => {
|
|
12723
|
-
timer = setTimeout(() => resolve4({ kind: "timeout" }), timeoutMs);
|
|
12919
|
+
this.pending = { resolve: resolve4, facts: new WriteFactsCollector() };
|
|
12724
12920
|
});
|
|
12921
|
+
this.child.writeLine({ type: "user", message: { role: "user", content: text } });
|
|
12725
12922
|
try {
|
|
12726
|
-
return await
|
|
12923
|
+
return await withDeadline(outcome, timeoutMs, { kind: "timeout" });
|
|
12727
12924
|
} finally {
|
|
12728
|
-
clearTimeout(timer);
|
|
12729
12925
|
this.pending = void 0;
|
|
12730
12926
|
}
|
|
12731
12927
|
}
|
|
12732
|
-
/**
|
|
12733
|
-
async
|
|
12734
|
-
|
|
12735
|
-
this.child.
|
|
12736
|
-
if (await this.waitExit(AGENT_STOP_WAIT_MS)) return;
|
|
12737
|
-
this.child.kill("SIGTERM");
|
|
12738
|
-
if (await this.waitExit(AGENT_STOP_WAIT_MS)) return;
|
|
12739
|
-
this.child.kill("SIGKILL");
|
|
12740
|
-
await this.waitExit(AGENT_STOP_WAIT_MS);
|
|
12928
|
+
/** 실측: {@code control_request interrupt} → 13ms 뒤 그 차례가 끝나고 같은 프로세스가 이어진다(증적 three-agents ⑦). */
|
|
12929
|
+
async interrupt() {
|
|
12930
|
+
this.interrupts += 1;
|
|
12931
|
+
this.child.writeLine({ type: "control_request", request_id: `interrupt-${this.interrupts}`, request: { subtype: "interrupt" } });
|
|
12741
12932
|
}
|
|
12742
|
-
async
|
|
12743
|
-
|
|
12744
|
-
|
|
12745
|
-
|
|
12933
|
+
async close() {
|
|
12934
|
+
await this.child.stop();
|
|
12935
|
+
}
|
|
12936
|
+
onExit(exit) {
|
|
12937
|
+
this.deps.log.write({
|
|
12938
|
+
event: "process_exit",
|
|
12939
|
+
pid: this.child.pid,
|
|
12940
|
+
agent: this.agent,
|
|
12941
|
+
conversationUuid: this.conversationUuid,
|
|
12942
|
+
code: exit.code,
|
|
12943
|
+
signal: exit.signal
|
|
12746
12944
|
});
|
|
12747
|
-
|
|
12748
|
-
return await Promise.race([this.exited.then(() => true), timedOut]);
|
|
12749
|
-
} finally {
|
|
12750
|
-
clearTimeout(timer);
|
|
12751
|
-
}
|
|
12945
|
+
this.finish({ kind: "exited", ...exit });
|
|
12752
12946
|
}
|
|
12753
12947
|
finish(outcome) {
|
|
12754
12948
|
const pending = this.pending;
|
|
12755
12949
|
this.pending = void 0;
|
|
12756
12950
|
pending?.resolve(outcome);
|
|
12757
12951
|
}
|
|
12758
|
-
|
|
12952
|
+
onLine(line) {
|
|
12953
|
+
let event;
|
|
12954
|
+
try {
|
|
12955
|
+
event = JSON.parse(line);
|
|
12956
|
+
} catch {
|
|
12957
|
+
this.deps.log.write({ event: "bad_line", pid: this.child.pid, agent: this.agent, length: line.length });
|
|
12958
|
+
return;
|
|
12959
|
+
}
|
|
12759
12960
|
if (event.type === "system" && event.subtype === "init" && typeof event.session_id === "string") {
|
|
12760
|
-
this.
|
|
12961
|
+
this.sessionRef = event.session_id;
|
|
12962
|
+
const source = typeof event.apiKeySource === "string" ? event.apiKeySource : "none";
|
|
12963
|
+
this.deps.log.write({ event: "agent_auth_source", pid: this.child.pid, agent: this.agent, apiKeySource: source });
|
|
12761
12964
|
return;
|
|
12762
12965
|
}
|
|
12763
12966
|
const content = event.message?.content;
|
|
@@ -12773,25 +12976,21 @@ ${error.message}`;
|
|
|
12773
12976
|
for (const part of content) {
|
|
12774
12977
|
if (part.type !== "tool_result" || typeof part.tool_use_id !== "string") continue;
|
|
12775
12978
|
const name = this.toolNames.get(part.tool_use_id);
|
|
12776
|
-
if (!name?.startsWith(AINECTO_TOOL_PREFIX) || !writeTools.has(name.slice(AINECTO_TOOL_PREFIX.length))) continue;
|
|
12777
|
-
|
|
12778
|
-
if (!this.pending.documents.includes(uuid)) this.pending.documents.push(uuid);
|
|
12779
|
-
}
|
|
12979
|
+
if (!name?.startsWith(AINECTO_TOOL_PREFIX) || !this.deps.writeTools.has(name.slice(AINECTO_TOOL_PREFIX.length))) continue;
|
|
12980
|
+
this.pending.facts.add(part.content);
|
|
12780
12981
|
}
|
|
12781
12982
|
return;
|
|
12782
12983
|
}
|
|
12783
12984
|
if (event.type === "result") {
|
|
12784
|
-
if (typeof event.session_id === "string") this.
|
|
12785
|
-
const documents = this.pending?.documents ?? [];
|
|
12985
|
+
if (typeof event.session_id === "string") this.sessionRef = event.session_id;
|
|
12786
12986
|
this.finish({
|
|
12787
12987
|
kind: "result",
|
|
12788
|
-
documents,
|
|
12988
|
+
facts: this.pending?.facts.snapshot() ?? { documents: [], createdDocuments: [], cards: [] },
|
|
12789
12989
|
result: {
|
|
12790
12990
|
subtype: typeof event.subtype === "string" ? event.subtype : void 0,
|
|
12791
12991
|
isError: event.is_error === true,
|
|
12792
12992
|
structuredOutput: event.structured_output,
|
|
12793
12993
|
resultText: typeof event.result === "string" ? event.result : void 0,
|
|
12794
|
-
sessionId: this.sessionId,
|
|
12795
12994
|
numTurns: typeof event.num_turns === "number" ? event.num_turns : void 0,
|
|
12796
12995
|
costUsd: typeof event.total_cost_usd === "number" ? event.total_cost_usd : void 0
|
|
12797
12996
|
}
|
|
@@ -12800,6 +12999,381 @@ ${error.message}`;
|
|
|
12800
12999
|
}
|
|
12801
13000
|
};
|
|
12802
13001
|
|
|
13002
|
+
// src/core/agent/codexArgs.ts
|
|
13003
|
+
var CODEX = "codex";
|
|
13004
|
+
var THREAD_POLICY = { approvalPolicy: "never", sandbox: "read-only" };
|
|
13005
|
+
var CONFIG_KEY_PART = /^[A-Za-z0-9_-]+$/;
|
|
13006
|
+
var FEATURES_OFF = ["shell_tool", "plugins", "apps", "computer_use", "browser_use", "image_generation"];
|
|
13007
|
+
function codexAppServerArgs(bridge, writeTools) {
|
|
13008
|
+
const server = `mcp_servers.${AINECTO_MCP_SERVER}`;
|
|
13009
|
+
const config = [
|
|
13010
|
+
`${server}.command=${tomlString(bridge.command)}`,
|
|
13011
|
+
`${server}.args=[${bridge.args.map(tomlString).join(",")}]`,
|
|
13012
|
+
'approval_policy="never"',
|
|
13013
|
+
'sandbox_mode="read-only"',
|
|
13014
|
+
...FEATURES_OFF.map((feature) => `features.${feature}=false`),
|
|
13015
|
+
...[...writeTools].filter((tool) => CONFIG_KEY_PART.test(tool)).sort().map((tool) => `${server}.tools.${tool}.approval_mode="approve"`)
|
|
13016
|
+
];
|
|
13017
|
+
return ["app-server", ...config.flatMap((entry) => ["-c", entry])];
|
|
13018
|
+
}
|
|
13019
|
+
function tomlString(value) {
|
|
13020
|
+
return JSON.stringify(value);
|
|
13021
|
+
}
|
|
13022
|
+
function codexInitializeParams(clientVersion) {
|
|
13023
|
+
return { clientInfo: { name: "ainecto-cli", title: "AiNecto CLI", version: clientVersion } };
|
|
13024
|
+
}
|
|
13025
|
+
function codexOtherMcpServersOff(config) {
|
|
13026
|
+
const servers = config && typeof config === "object" ? config.mcp_servers : void 0;
|
|
13027
|
+
const names = servers && typeof servers === "object" ? Object.keys(servers).filter((name) => name !== AINECTO_MCP_SERVER).sort() : [];
|
|
13028
|
+
const bad = names.filter((name) => !CONFIG_KEY_PART.test(name));
|
|
13029
|
+
if (bad.length > 0) throw new Error(`cannot turn off Codex MCP server(s) ${bad.map((name) => JSON.stringify(name)).join(", ")}`);
|
|
13030
|
+
return { names, config: Object.fromEntries(names.map((name) => [`mcp_servers.${name}.enabled`, false])) };
|
|
13031
|
+
}
|
|
13032
|
+
function codexThreadStartParams(cwd, serversOff) {
|
|
13033
|
+
return { cwd, ...THREAD_POLICY, config: serversOff };
|
|
13034
|
+
}
|
|
13035
|
+
function codexThreadResumeParams(threadId, cwd, serversOff) {
|
|
13036
|
+
return { threadId, cwd, ...THREAD_POLICY, config: serversOff, excludeTurns: true };
|
|
13037
|
+
}
|
|
13038
|
+
function codexTurnStartParams(threadId, text, outputSchema) {
|
|
13039
|
+
return { threadId, input: [{ type: "text", text }], outputSchema };
|
|
13040
|
+
}
|
|
13041
|
+
function codexServerRequestAnswer(method) {
|
|
13042
|
+
switch (method) {
|
|
13043
|
+
case "mcpServer/elicitation/request":
|
|
13044
|
+
return { result: { action: "decline" } };
|
|
13045
|
+
case "item/commandExecution/requestApproval":
|
|
13046
|
+
case "item/fileChange/requestApproval":
|
|
13047
|
+
return { result: { decision: "decline" } };
|
|
13048
|
+
case "applyPatchApproval":
|
|
13049
|
+
case "execCommandApproval":
|
|
13050
|
+
return { result: { decision: "denied" } };
|
|
13051
|
+
default:
|
|
13052
|
+
return { error: { code: -32601, message: `ainecto agent serve does not answer ${method}` } };
|
|
13053
|
+
}
|
|
13054
|
+
}
|
|
13055
|
+
function codexAuthFromAccount(result) {
|
|
13056
|
+
const account = result.account && typeof result.account === "object" ? result.account : void 0;
|
|
13057
|
+
const method = typeof account?.type === "string" ? account.type : void 0;
|
|
13058
|
+
const plan = typeof account?.planType === "string" ? account.planType : void 0;
|
|
13059
|
+
if (account) return { ready: true, mode: method === "apiKey" ? "apiKey" : "subscription", method, plan };
|
|
13060
|
+
if (result.requiresOpenaiAuth === false) return { ready: true, method: "none-required" };
|
|
13061
|
+
return { ready: false, detail: "not signed in with an API key or ChatGPT (run `codex login`, or `codex login --with-api-key`)" };
|
|
13062
|
+
}
|
|
13063
|
+
function codexTurnResult(turn, lastMessage) {
|
|
13064
|
+
const status = typeof turn.status === "string" ? turn.status : "unknown";
|
|
13065
|
+
const text = lastMessage ?? lastAgentMessageIn(turn.items);
|
|
13066
|
+
if (status !== "completed") {
|
|
13067
|
+
return { subtype: status, isError: true, resultText: errorMessage3(turn.error) ?? text };
|
|
13068
|
+
}
|
|
13069
|
+
if (text === void 0) return { subtype: status, isError: false };
|
|
13070
|
+
try {
|
|
13071
|
+
return { subtype: status, isError: false, structuredOutput: JSON.parse(text) };
|
|
13072
|
+
} catch {
|
|
13073
|
+
return { subtype: status, isError: false, resultText: text };
|
|
13074
|
+
}
|
|
13075
|
+
}
|
|
13076
|
+
function lastAgentMessageIn(items) {
|
|
13077
|
+
if (!Array.isArray(items)) return void 0;
|
|
13078
|
+
let text;
|
|
13079
|
+
for (const item of items) {
|
|
13080
|
+
if (item?.type === "agentMessage" && typeof item.text === "string") text = item.text;
|
|
13081
|
+
}
|
|
13082
|
+
return text;
|
|
13083
|
+
}
|
|
13084
|
+
function errorMessage3(error) {
|
|
13085
|
+
if (!error) return void 0;
|
|
13086
|
+
if (typeof error === "object" && typeof error.message === "string") {
|
|
13087
|
+
return error.message;
|
|
13088
|
+
}
|
|
13089
|
+
return JSON.stringify(error);
|
|
13090
|
+
}
|
|
13091
|
+
|
|
13092
|
+
// src/core/agent/codex.ts
|
|
13093
|
+
function codexAdapter(deps) {
|
|
13094
|
+
return {
|
|
13095
|
+
id: "codex",
|
|
13096
|
+
displayName: "Codex",
|
|
13097
|
+
detect: () => detectByVersion(deps.spawnImpl, CODEX, { cwd: deps.cwd, env: deps.env, timeoutMs: AGENT_CALL_TIMEOUT_MS }),
|
|
13098
|
+
async authStatus() {
|
|
13099
|
+
const server = startAppServer(deps, ["app-server"], {});
|
|
13100
|
+
try {
|
|
13101
|
+
const read = (async () => {
|
|
13102
|
+
await server.rpc.request("initialize", codexInitializeParams(deps.clientVersion));
|
|
13103
|
+
server.rpc.notify("initialized");
|
|
13104
|
+
return await server.rpc.request("account/read", { refreshToken: false });
|
|
13105
|
+
})();
|
|
13106
|
+
const result = await withDeadline(
|
|
13107
|
+
read.catch(toError),
|
|
13108
|
+
AGENT_CALL_TIMEOUT_MS,
|
|
13109
|
+
new Error("account/read timed out")
|
|
13110
|
+
);
|
|
13111
|
+
return result instanceof Error ? { ready: false, detail: result.message } : codexAuthFromAccount(result);
|
|
13112
|
+
} finally {
|
|
13113
|
+
await server.child.stop();
|
|
13114
|
+
}
|
|
13115
|
+
},
|
|
13116
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, deps)
|
|
13117
|
+
};
|
|
13118
|
+
}
|
|
13119
|
+
var CodexRpc = class {
|
|
13120
|
+
constructor(io) {
|
|
13121
|
+
this.io = io;
|
|
13122
|
+
}
|
|
13123
|
+
io;
|
|
13124
|
+
nextId = 0;
|
|
13125
|
+
waiting = /* @__PURE__ */ new Map();
|
|
13126
|
+
request(method, params) {
|
|
13127
|
+
this.nextId += 1;
|
|
13128
|
+
const id = this.nextId;
|
|
13129
|
+
this.io.log.write({ event: "agent_rpc", pid: this.io.pid(), agent: "codex", id, method });
|
|
13130
|
+
return new Promise((resolve4, reject) => {
|
|
13131
|
+
this.waiting.set(id, { method, started: Date.now(), resolve: resolve4, reject });
|
|
13132
|
+
if (!this.io.write({ id, method, params })) this.settle(id, new Error("codex is not running"));
|
|
13133
|
+
});
|
|
13134
|
+
}
|
|
13135
|
+
notify(method) {
|
|
13136
|
+
this.io.write({ method });
|
|
13137
|
+
}
|
|
13138
|
+
onLine(line) {
|
|
13139
|
+
let message;
|
|
13140
|
+
try {
|
|
13141
|
+
message = JSON.parse(line);
|
|
13142
|
+
} catch {
|
|
13143
|
+
this.io.log.write({ event: "bad_line", pid: this.io.pid(), agent: "codex", length: line.length });
|
|
13144
|
+
return;
|
|
13145
|
+
}
|
|
13146
|
+
const method = typeof message.method === "string" ? message.method : void 0;
|
|
13147
|
+
const params = message.params && typeof message.params === "object" ? message.params : {};
|
|
13148
|
+
if (message.id !== void 0 && method) {
|
|
13149
|
+
const answer = codexServerRequestAnswer(method);
|
|
13150
|
+
this.io.log.write({
|
|
13151
|
+
event: "agent_server_request",
|
|
13152
|
+
pid: this.io.pid(),
|
|
13153
|
+
agent: "codex",
|
|
13154
|
+
method,
|
|
13155
|
+
answer: "result" in answer ? JSON.stringify(answer.result) : `error ${answer.error.code}`
|
|
13156
|
+
});
|
|
13157
|
+
this.io.write({ id: message.id, ...answer });
|
|
13158
|
+
return;
|
|
13159
|
+
}
|
|
13160
|
+
if (typeof message.id === "number") {
|
|
13161
|
+
const error = message.error;
|
|
13162
|
+
if (error) {
|
|
13163
|
+
this.settle(message.id, new Error(typeof error.message === "string" ? error.message : JSON.stringify(error)));
|
|
13164
|
+
} else {
|
|
13165
|
+
this.settle(
|
|
13166
|
+
message.id,
|
|
13167
|
+
void 0,
|
|
13168
|
+
message.result && typeof message.result === "object" ? message.result : {}
|
|
13169
|
+
);
|
|
13170
|
+
}
|
|
13171
|
+
return;
|
|
13172
|
+
}
|
|
13173
|
+
if (method) this.io.notification(method, params);
|
|
13174
|
+
}
|
|
13175
|
+
/** 프로세스가 끝났다 — 기다리던 요청 전부에 응답 줄을 남기고 거절한다. */
|
|
13176
|
+
failAll(reason) {
|
|
13177
|
+
for (const id of [...this.waiting.keys()]) this.settle(id, new Error(reason));
|
|
13178
|
+
}
|
|
13179
|
+
settle(id, error, result) {
|
|
13180
|
+
const waiting = this.waiting.get(id);
|
|
13181
|
+
if (!waiting) return;
|
|
13182
|
+
this.waiting.delete(id);
|
|
13183
|
+
this.io.log.write({
|
|
13184
|
+
event: "agent_rpc_response",
|
|
13185
|
+
pid: this.io.pid(),
|
|
13186
|
+
agent: "codex",
|
|
13187
|
+
id,
|
|
13188
|
+
method: waiting.method,
|
|
13189
|
+
ok: error === void 0,
|
|
13190
|
+
...error ? { error: error.message } : {},
|
|
13191
|
+
ms: Date.now() - waiting.started
|
|
13192
|
+
});
|
|
13193
|
+
if (error) waiting.reject(error);
|
|
13194
|
+
else waiting.resolve(result ?? {});
|
|
13195
|
+
}
|
|
13196
|
+
};
|
|
13197
|
+
function startAppServer(deps, args, hooks) {
|
|
13198
|
+
const holder = {};
|
|
13199
|
+
const rpc = new CodexRpc({
|
|
13200
|
+
write: (message) => holder.child?.writeLine(message) ?? false,
|
|
13201
|
+
pid: () => holder.child?.pid ?? -1,
|
|
13202
|
+
log: deps.log,
|
|
13203
|
+
notification: (method, params) => hooks.notification?.(method, params)
|
|
13204
|
+
});
|
|
13205
|
+
const child = new AgentChild(deps.spawnImpl, CODEX, args, { cwd: deps.cwd, env: deps.env }, {
|
|
13206
|
+
line: (line) => rpc.onLine(line),
|
|
13207
|
+
exit: (exit) => {
|
|
13208
|
+
rpc.failAll(`codex exited (code ${exit.code ?? "-"}${exit.signal ? `, ${exit.signal}` : ""})${exit.stderrTail ? `: ${exit.stderrTail}` : ""}`);
|
|
13209
|
+
hooks.exit?.(exit);
|
|
13210
|
+
}
|
|
13211
|
+
});
|
|
13212
|
+
holder.child = child;
|
|
13213
|
+
return { child, rpc };
|
|
13214
|
+
}
|
|
13215
|
+
var CodexSession = class {
|
|
13216
|
+
constructor(conversationUuid, resumeRef, textMaxCharacters, deps) {
|
|
13217
|
+
this.conversationUuid = conversationUuid;
|
|
13218
|
+
this.textMaxCharacters = textMaxCharacters;
|
|
13219
|
+
this.deps = deps;
|
|
13220
|
+
this.resumed = resumeRef !== void 0;
|
|
13221
|
+
const server = startAppServer(deps, deps.appServerArgs, {
|
|
13222
|
+
notification: (method, params) => this.onNotification(method, params),
|
|
13223
|
+
exit: (exit) => this.onExit(exit)
|
|
13224
|
+
});
|
|
13225
|
+
this.child = server.child;
|
|
13226
|
+
this.rpc = server.rpc;
|
|
13227
|
+
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
13228
|
+
this.started = this.start(resumeRef).then(() => void 0, toError);
|
|
13229
|
+
}
|
|
13230
|
+
conversationUuid;
|
|
13231
|
+
textMaxCharacters;
|
|
13232
|
+
deps;
|
|
13233
|
+
agent = "codex";
|
|
13234
|
+
resumed;
|
|
13235
|
+
sessionRef;
|
|
13236
|
+
child;
|
|
13237
|
+
rpc;
|
|
13238
|
+
/** 준비(initialize·thread) — 실패하면 그 오류. */
|
|
13239
|
+
started;
|
|
13240
|
+
turn;
|
|
13241
|
+
/** 끝나지 않은 차례 — 기한을 넘긴 뒤에도 interrupt 할 수 있게 따로 둔다. */
|
|
13242
|
+
runningTurnId;
|
|
13243
|
+
get pid() {
|
|
13244
|
+
return this.child.pid;
|
|
13245
|
+
}
|
|
13246
|
+
get alive() {
|
|
13247
|
+
return this.child.alive;
|
|
13248
|
+
}
|
|
13249
|
+
async send(text, timeoutMs) {
|
|
13250
|
+
const work = (async () => {
|
|
13251
|
+
const failed = await this.started;
|
|
13252
|
+
if (failed) {
|
|
13253
|
+
await this.child.stop();
|
|
13254
|
+
const exit2 = this.child.exit;
|
|
13255
|
+
return {
|
|
13256
|
+
kind: "exited",
|
|
13257
|
+
code: exit2?.code ?? null,
|
|
13258
|
+
signal: exit2?.signal ?? null,
|
|
13259
|
+
stderrTail: [failed.message, exit2?.stderrTail].filter(Boolean).join("\n")
|
|
13260
|
+
};
|
|
13261
|
+
}
|
|
13262
|
+
const exit = this.child.exit;
|
|
13263
|
+
if (exit || !this.sessionRef) return { kind: "exited", code: exit?.code ?? null, signal: exit?.signal ?? null, stderrTail: exit?.stderrTail ?? "" };
|
|
13264
|
+
const turn = { resolve: () => {
|
|
13265
|
+
}, facts: new WriteFactsCollector() };
|
|
13266
|
+
const outcome = new Promise((resolve4) => {
|
|
13267
|
+
turn.resolve = resolve4;
|
|
13268
|
+
});
|
|
13269
|
+
this.turn = turn;
|
|
13270
|
+
try {
|
|
13271
|
+
const started = await this.rpc.request(
|
|
13272
|
+
"turn/start",
|
|
13273
|
+
codexTurnStartParams(this.sessionRef, text, agentReplySchema(this.textMaxCharacters))
|
|
13274
|
+
);
|
|
13275
|
+
const id = started.turn?.id;
|
|
13276
|
+
if (typeof id === "string") {
|
|
13277
|
+
turn.id = id;
|
|
13278
|
+
this.runningTurnId = id;
|
|
13279
|
+
}
|
|
13280
|
+
} catch (error) {
|
|
13281
|
+
if (this.child.alive) {
|
|
13282
|
+
this.finishTurn(turn, {
|
|
13283
|
+
kind: "result",
|
|
13284
|
+
facts: turn.facts.snapshot(),
|
|
13285
|
+
result: { subtype: "turn_start_failed", isError: true, resultText: toError(error).message }
|
|
13286
|
+
});
|
|
13287
|
+
}
|
|
13288
|
+
}
|
|
13289
|
+
return await outcome;
|
|
13290
|
+
})();
|
|
13291
|
+
try {
|
|
13292
|
+
return await withDeadline(work, timeoutMs, { kind: "timeout" });
|
|
13293
|
+
} finally {
|
|
13294
|
+
this.turn = void 0;
|
|
13295
|
+
}
|
|
13296
|
+
}
|
|
13297
|
+
/** 실측: {@code turn/interrupt} → 12ms 뒤 {@code interrupted}, 같은 thread 가 이어진다(증적 three-agents ⑦). B6 안에 답이 없으면 그대로 둔다. */
|
|
13298
|
+
async interrupt() {
|
|
13299
|
+
const turnId = this.runningTurnId;
|
|
13300
|
+
if (!turnId || !this.sessionRef || !this.child.alive) return;
|
|
13301
|
+
await withDeadline(
|
|
13302
|
+
this.rpc.request("turn/interrupt", { threadId: this.sessionRef, turnId }).then(() => void 0, () => void 0),
|
|
13303
|
+
AGENT_STOP_WAIT_MS,
|
|
13304
|
+
void 0
|
|
13305
|
+
);
|
|
13306
|
+
}
|
|
13307
|
+
async close() {
|
|
13308
|
+
await this.child.stop();
|
|
13309
|
+
}
|
|
13310
|
+
async start(resumeRef) {
|
|
13311
|
+
await this.rpc.request("initialize", codexInitializeParams(this.deps.clientVersion));
|
|
13312
|
+
this.rpc.notify("initialized");
|
|
13313
|
+
const read = await this.rpc.request("config/read", { cwd: this.deps.cwd });
|
|
13314
|
+
const off = codexOtherMcpServersOff(read.config);
|
|
13315
|
+
this.deps.log.write({ event: "agent_mcp_servers_off", pid: this.child.pid, agent: this.agent, names: off.names });
|
|
13316
|
+
const method = resumeRef ? "thread/resume" : "thread/start";
|
|
13317
|
+
const result = await this.rpc.request(
|
|
13318
|
+
method,
|
|
13319
|
+
resumeRef ? codexThreadResumeParams(resumeRef, this.deps.cwd, off.config) : codexThreadStartParams(this.deps.cwd, off.config)
|
|
13320
|
+
);
|
|
13321
|
+
const id = result.thread?.id;
|
|
13322
|
+
if (typeof id !== "string") throw new Error(`${method} returned no thread id`);
|
|
13323
|
+
this.sessionRef = id;
|
|
13324
|
+
}
|
|
13325
|
+
onExit(exit) {
|
|
13326
|
+
this.deps.log.write({
|
|
13327
|
+
event: "process_exit",
|
|
13328
|
+
pid: this.child.pid,
|
|
13329
|
+
agent: this.agent,
|
|
13330
|
+
conversationUuid: this.conversationUuid,
|
|
13331
|
+
code: exit.code,
|
|
13332
|
+
signal: exit.signal
|
|
13333
|
+
});
|
|
13334
|
+
this.runningTurnId = void 0;
|
|
13335
|
+
if (this.turn) this.finishTurn(this.turn, { kind: "exited", ...exit });
|
|
13336
|
+
}
|
|
13337
|
+
finishTurn(turn, outcome) {
|
|
13338
|
+
if (this.turn === turn) this.turn = void 0;
|
|
13339
|
+
turn.resolve(outcome);
|
|
13340
|
+
}
|
|
13341
|
+
onNotification(method, params) {
|
|
13342
|
+
if (method === "mcpServer/startupStatus/updated") {
|
|
13343
|
+
if (typeof params.name === "string" && typeof params.status === "string" && params.status !== "starting") {
|
|
13344
|
+
this.deps.log.write({
|
|
13345
|
+
event: "agent_mcp_server",
|
|
13346
|
+
pid: this.child.pid,
|
|
13347
|
+
agent: this.agent,
|
|
13348
|
+
name: params.name,
|
|
13349
|
+
status: params.status,
|
|
13350
|
+
...typeof params.error === "string" ? { error: params.error } : {}
|
|
13351
|
+
});
|
|
13352
|
+
}
|
|
13353
|
+
return;
|
|
13354
|
+
}
|
|
13355
|
+
if (params.threadId !== this.sessionRef) return;
|
|
13356
|
+
const turn = this.turn;
|
|
13357
|
+
if (method === "turn/completed") {
|
|
13358
|
+
const completed = params.turn && typeof params.turn === "object" ? params.turn : {};
|
|
13359
|
+
if (completed.id === this.runningTurnId) this.runningTurnId = void 0;
|
|
13360
|
+
if (!turn || turn.id !== void 0 && completed.id !== turn.id) return;
|
|
13361
|
+
this.finishTurn(turn, { kind: "result", facts: turn.facts.snapshot(), result: codexTurnResult(completed, turn.lastMessage) });
|
|
13362
|
+
return;
|
|
13363
|
+
}
|
|
13364
|
+
if (method !== "item/completed" || !turn) return;
|
|
13365
|
+
const item = params.item && typeof params.item === "object" ? params.item : {};
|
|
13366
|
+
if (item.type === "agentMessage" && typeof item.text === "string") {
|
|
13367
|
+
turn.lastMessage = item.text;
|
|
13368
|
+
} else if (item.type === "mcpToolCall" && item.server === AINECTO_MCP_SERVER && typeof item.tool === "string" && this.deps.writeTools.has(item.tool)) {
|
|
13369
|
+
turn.facts.add(item.result?.content);
|
|
13370
|
+
}
|
|
13371
|
+
}
|
|
13372
|
+
};
|
|
13373
|
+
function toError(error) {
|
|
13374
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
13375
|
+
}
|
|
13376
|
+
|
|
12803
13377
|
// src/core/agent/http.ts
|
|
12804
13378
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
12805
13379
|
var AgentCallError = class extends Error {
|
|
@@ -12919,6 +13493,62 @@ function agentPaths(home = homedir3()) {
|
|
|
12919
13493
|
};
|
|
12920
13494
|
}
|
|
12921
13495
|
|
|
13496
|
+
// src/core/agent/readiness.ts
|
|
13497
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
13498
|
+
async function checkAgents(adapters, log) {
|
|
13499
|
+
return await Promise.all(adapters.map(async (adapter) => {
|
|
13500
|
+
const detected = await probe(
|
|
13501
|
+
log,
|
|
13502
|
+
adapter.id,
|
|
13503
|
+
"detect",
|
|
13504
|
+
() => adapter.detect(),
|
|
13505
|
+
(d) => ({ installed: d.installed, version: d.version, detail: d.detail })
|
|
13506
|
+
);
|
|
13507
|
+
if (!detected?.installed) {
|
|
13508
|
+
return { id: adapter.id, installed: false, ready: false, detail: detected?.detail };
|
|
13509
|
+
}
|
|
13510
|
+
const auth = await probe(
|
|
13511
|
+
log,
|
|
13512
|
+
adapter.id,
|
|
13513
|
+
"auth",
|
|
13514
|
+
() => adapter.authStatus(),
|
|
13515
|
+
(a) => ({ ready: a.ready, mode: a.mode, method: a.method, plan: a.plan, detail: a.detail })
|
|
13516
|
+
);
|
|
13517
|
+
return {
|
|
13518
|
+
id: adapter.id,
|
|
13519
|
+
installed: true,
|
|
13520
|
+
version: detected.version,
|
|
13521
|
+
ready: auth?.ready === true,
|
|
13522
|
+
auth: auth?.ready === true ? auth.mode : void 0,
|
|
13523
|
+
detail: auth?.detail
|
|
13524
|
+
};
|
|
13525
|
+
}));
|
|
13526
|
+
}
|
|
13527
|
+
function openAgents(checks) {
|
|
13528
|
+
return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready, ...check.auth ? { auth: check.auth } : {} }));
|
|
13529
|
+
}
|
|
13530
|
+
async function probe(log, agent, kind, work, summary) {
|
|
13531
|
+
const callId = randomUUID3();
|
|
13532
|
+
const started = Date.now();
|
|
13533
|
+
log.write({ event: "agent_probe", callId, agent, probe: kind });
|
|
13534
|
+
try {
|
|
13535
|
+
const value = await work();
|
|
13536
|
+
log.write({ event: "agent_probe_response", callId, agent, probe: kind, ok: true, ...summary(value), ms: Date.now() - started });
|
|
13537
|
+
return value;
|
|
13538
|
+
} catch (error) {
|
|
13539
|
+
log.write({
|
|
13540
|
+
event: "agent_probe_response",
|
|
13541
|
+
callId,
|
|
13542
|
+
agent,
|
|
13543
|
+
probe: kind,
|
|
13544
|
+
ok: false,
|
|
13545
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
13546
|
+
ms: Date.now() - started
|
|
13547
|
+
});
|
|
13548
|
+
return void 0;
|
|
13549
|
+
}
|
|
13550
|
+
}
|
|
13551
|
+
|
|
12922
13552
|
// src/core/agent/prompt.ts
|
|
12923
13553
|
function agentPromptText(text, context) {
|
|
12924
13554
|
const parts = [];
|
|
@@ -12940,25 +13570,33 @@ function str(value) {
|
|
|
12940
13570
|
}
|
|
12941
13571
|
|
|
12942
13572
|
// src/core/agent/reply.ts
|
|
12943
|
-
function replyForOutcome(outcome, limits) {
|
|
12944
|
-
const
|
|
12945
|
-
const
|
|
13573
|
+
function replyForOutcome(outcome, limits, agentName) {
|
|
13574
|
+
const facts = outcome.kind === "result" ? outcome.facts : void 0;
|
|
13575
|
+
const documentUuids = facts ? facts.documents.slice(0, limits.documentsMax) : [];
|
|
13576
|
+
const createdDocumentUuids = facts ? facts.createdDocuments.filter((uuid) => documentUuids.includes(uuid)) : [];
|
|
13577
|
+
const cardUuids = facts ? facts.cards.slice(0, limits.documentsMax) : [];
|
|
13578
|
+
const attached = {
|
|
13579
|
+
documentUuids,
|
|
13580
|
+
...createdDocumentUuids.length > 0 ? { createdDocumentUuids } : {},
|
|
13581
|
+
...cardUuids.length > 0 ? { cardUuids } : {}
|
|
13582
|
+
};
|
|
13583
|
+
const failed = (errorCode2, text) => ({ status: "FAILED", errorCode: errorCode2, reply: clip(text, limits.textMaxCharacters), ...attached });
|
|
12946
13584
|
switch (outcome.kind) {
|
|
12947
13585
|
case "timeout":
|
|
12948
13586
|
return failed("TURN_TIMEOUT", "\uC81C\uD55C \uC2DC\uAC04 \uC548\uC5D0 \uB05D\uB098\uC9C0 \uC54A\uC544 \uBA48\uCDC4\uC5B4\uC694. \uB2E4\uC2DC \uBCF4\uB0B4 \uC8FC\uC138\uC694.");
|
|
12949
13587
|
case "exited":
|
|
12950
|
-
return failed("AGENT_EXITED",
|
|
13588
|
+
return failed("AGENT_EXITED", `${agentName} \uAC00 \uB05D\uB0AC\uC5B4\uC694(code ${outcome.code ?? "-"}${outcome.signal ? `, ${outcome.signal}` : ""}).` + (outcome.stderrTail ? `
|
|
12951
13589
|
${outcome.stderrTail}` : ""));
|
|
12952
13590
|
case "result": {
|
|
12953
13591
|
const { result } = outcome;
|
|
12954
13592
|
if (result.isError) {
|
|
12955
|
-
return failed("AGENT_ERROR",
|
|
13593
|
+
return failed("AGENT_ERROR", `${agentName} \uAC00 \uC2E4\uD328\uD588\uC5B4\uC694(${result.subtype ?? "error"}).` + (result.resultText ? `
|
|
12956
13594
|
${result.resultText}` : ""));
|
|
12957
13595
|
}
|
|
12958
13596
|
const reply = result.structuredOutput?.reply;
|
|
12959
13597
|
const keys = result.structuredOutput && typeof result.structuredOutput === "object" ? Object.keys(result.structuredOutput) : [];
|
|
12960
13598
|
if (typeof reply === "string" && reply.trim().length > 0 && keys.length === 1 && codePoints(reply) <= limits.textMaxCharacters) {
|
|
12961
|
-
return { status: "DONE", reply,
|
|
13599
|
+
return { status: "DONE", reply, ...attached };
|
|
12962
13600
|
}
|
|
12963
13601
|
const raw = result.structuredOutput !== void 0 ? JSON.stringify(result.structuredOutput) : result.resultText ?? "";
|
|
12964
13602
|
return failed("SCHEMA_VIOLATION", `\uB2F5 \uD615\uC2DD\uC774 \uC5B4\uAE0B\uB0AC\uC5B4\uC694.
|
|
@@ -12976,16 +13614,17 @@ function clip(text, max) {
|
|
|
12976
13614
|
|
|
12977
13615
|
// src/core/agent/serve.ts
|
|
12978
13616
|
async function runAgentServe(deps) {
|
|
12979
|
-
const opened = await deps.http.call("open", { hostName: deps.hostName, cliVersion: deps.cliVersion });
|
|
13617
|
+
const opened = await deps.http.call("open", { hostName: deps.hostName, cliVersion: deps.cliVersion, agents: deps.agents });
|
|
12980
13618
|
const linkId = String(opened.linkId);
|
|
12981
13619
|
deps.http.useLinkToken(String(opened.linkToken));
|
|
12982
13620
|
const limits = serverLimits(opened.limits);
|
|
12983
|
-
deps.
|
|
13621
|
+
const names = deps.agents.map((a) => deps.adapters.get(a.id)?.displayName ?? a.id).join(" / ");
|
|
13622
|
+
deps.print(`Connected to AiNecto as ${deps.hostName}. Requests to \xABMy agent\xBB in AiNecto Chat now run in ${names} on this machine. Press Ctrl+C to stop.`);
|
|
12984
13623
|
const stopController = new AbortController();
|
|
12985
13624
|
let stopReason;
|
|
12986
13625
|
let exitCode2 = 0;
|
|
12987
13626
|
let wakeWorker;
|
|
12988
|
-
|
|
13627
|
+
const live = /* @__PURE__ */ new Map();
|
|
12989
13628
|
const received = /* @__PURE__ */ new Set();
|
|
12990
13629
|
const queue = [];
|
|
12991
13630
|
const stop = (reason, code, message) => {
|
|
@@ -12995,7 +13634,7 @@ async function runAgentServe(deps) {
|
|
|
12995
13634
|
if (message) deps.print(message);
|
|
12996
13635
|
stopController.abort();
|
|
12997
13636
|
wakeWorker?.();
|
|
12998
|
-
void
|
|
13637
|
+
for (const session of live.values()) void session.close();
|
|
12999
13638
|
};
|
|
13000
13639
|
const onUserStop = () => stop("signal", 0, "Stopping\u2026");
|
|
13001
13640
|
if (deps.signal.aborted) onUserStop();
|
|
@@ -13019,7 +13658,7 @@ async function runAgentServe(deps) {
|
|
|
13019
13658
|
}
|
|
13020
13659
|
for (const offer of offersIn(res)) {
|
|
13021
13660
|
const duplicate = received.has(offer.turnUuid);
|
|
13022
|
-
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, duplicate });
|
|
13661
|
+
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, agent: offer.agent, duplicate });
|
|
13023
13662
|
if (duplicate) continue;
|
|
13024
13663
|
received.add(offer.turnUuid);
|
|
13025
13664
|
queue.push(offer);
|
|
@@ -13036,55 +13675,83 @@ async function runAgentServe(deps) {
|
|
|
13036
13675
|
}
|
|
13037
13676
|
}
|
|
13038
13677
|
})();
|
|
13678
|
+
const sessionFor = async (adapter, conversationUuid) => {
|
|
13679
|
+
const existing = live.get(adapter.id);
|
|
13680
|
+
if (existing && existing.conversationUuid === conversationUuid && existing.alive) return existing;
|
|
13681
|
+
if (existing) {
|
|
13682
|
+
live.delete(adapter.id);
|
|
13683
|
+
await existing.close();
|
|
13684
|
+
}
|
|
13685
|
+
const session = adapter.open({
|
|
13686
|
+
conversationUuid,
|
|
13687
|
+
resumeRef: deps.sessions.get(conversationUuid, adapter.id),
|
|
13688
|
+
textMaxCharacters: limits.textMaxCharacters
|
|
13689
|
+
});
|
|
13690
|
+
live.set(adapter.id, session);
|
|
13691
|
+
return session;
|
|
13692
|
+
};
|
|
13039
13693
|
const runTurn = async (offer) => {
|
|
13040
|
-
if (current && (current.conversationUuid !== offer.conversationUuid || !current.alive)) {
|
|
13041
|
-
await current.stop();
|
|
13042
|
-
current = void 0;
|
|
13043
|
-
}
|
|
13044
|
-
if (!current) {
|
|
13045
|
-
const resumeSessionId = deps.sessions.get(offer.conversationUuid);
|
|
13046
|
-
current = new ClaudeAgentProcess(
|
|
13047
|
-
offer.conversationUuid,
|
|
13048
|
-
resumeSessionId !== void 0,
|
|
13049
|
-
deps.claudeArgs({ textMaxCharacters: limits.textMaxCharacters, resumeSessionId }),
|
|
13050
|
-
{ cwd: deps.cwd, env: deps.env, spawnImpl: deps.spawnImpl, writeTools: deps.writeTools, log: deps.log }
|
|
13051
|
-
);
|
|
13052
|
-
}
|
|
13053
|
-
const proc = current;
|
|
13054
13694
|
const started = Date.now();
|
|
13055
|
-
|
|
13695
|
+
const adapter = isAgentId(offer.agent) ? deps.adapters.get(offer.agent) : void 0;
|
|
13696
|
+
let session;
|
|
13056
13697
|
let outcome;
|
|
13057
13698
|
let reply;
|
|
13058
13699
|
let failure2;
|
|
13059
13700
|
try {
|
|
13060
|
-
|
|
13701
|
+
try {
|
|
13702
|
+
session = adapter ? await sessionFor(adapter, offer.conversationUuid) : void 0;
|
|
13703
|
+
} finally {
|
|
13704
|
+
deps.log.write({
|
|
13705
|
+
event: "agent_request",
|
|
13706
|
+
turnUuid: offer.turnUuid,
|
|
13707
|
+
agent: offer.agent,
|
|
13708
|
+
conversationUuid: offer.conversationUuid,
|
|
13709
|
+
pid: session?.pid ?? -1,
|
|
13710
|
+
textLength: offer.text.length
|
|
13711
|
+
});
|
|
13712
|
+
}
|
|
13713
|
+
if (!adapter || !session) {
|
|
13714
|
+
failure2 = "agent not installed";
|
|
13715
|
+
reply = {
|
|
13716
|
+
status: "FAILED",
|
|
13717
|
+
errorCode: "AGENT_NOT_INSTALLED",
|
|
13718
|
+
documentUuids: [],
|
|
13719
|
+
reply: clip(`\uC774 PC \uC5D0\uB294 \xAB${offer.agent}\xBB \uAC00 \uC124\uCE58\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC544\uC694.`, limits.textMaxCharacters)
|
|
13720
|
+
};
|
|
13721
|
+
return reply;
|
|
13722
|
+
}
|
|
13723
|
+
outcome = await session.send(agentPromptText(offer.text, offer.context), deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
|
|
13061
13724
|
if (outcome.kind === "timeout") {
|
|
13062
|
-
await
|
|
13725
|
+
await session.interrupt();
|
|
13726
|
+
await session.close();
|
|
13063
13727
|
}
|
|
13064
13728
|
if (outcome.kind !== "result") {
|
|
13065
|
-
|
|
13066
|
-
if (
|
|
13067
|
-
} else if (
|
|
13068
|
-
await deps.sessions.set(offer.conversationUuid,
|
|
13729
|
+
if (live.get(adapter.id) === session) live.delete(adapter.id);
|
|
13730
|
+
if (session.resumed) await deps.sessions.forget(offer.conversationUuid, adapter.id);
|
|
13731
|
+
} else if (session.sessionRef) {
|
|
13732
|
+
await deps.sessions.set(offer.conversationUuid, adapter.id, session.sessionRef);
|
|
13069
13733
|
}
|
|
13070
|
-
reply = replyForOutcome(outcome, limits);
|
|
13734
|
+
reply = replyForOutcome(outcome, limits, adapter.displayName);
|
|
13071
13735
|
return reply;
|
|
13072
13736
|
} catch (error) {
|
|
13073
13737
|
failure2 = error instanceof Error ? error.message : String(error);
|
|
13074
|
-
reply = { status: "FAILED", errorCode: "AGENT_INTERNAL", reply: `The PC agent failed: ${failure2}
|
|
13738
|
+
reply = { status: "FAILED", errorCode: "AGENT_INTERNAL", reply: clip(`The PC agent failed: ${failure2}`, limits.textMaxCharacters), documentUuids: [] };
|
|
13075
13739
|
return reply;
|
|
13076
13740
|
} finally {
|
|
13077
13741
|
const result = outcome?.kind === "result" ? outcome.result : void 0;
|
|
13078
13742
|
deps.log.write({
|
|
13079
13743
|
event: "agent_response",
|
|
13080
13744
|
turnUuid: offer.turnUuid,
|
|
13745
|
+
agent: offer.agent,
|
|
13081
13746
|
ms: Date.now() - started,
|
|
13082
13747
|
outcome: outcome?.kind ?? `error: ${failure2 ?? "unknown"}`,
|
|
13083
13748
|
status: reply?.status ?? "FAILED",
|
|
13084
13749
|
errorCode: reply?.errorCode,
|
|
13085
13750
|
subtype: result?.subtype,
|
|
13086
|
-
sessionId:
|
|
13751
|
+
sessionId: session?.sessionRef,
|
|
13087
13752
|
documents: reply?.documentUuids.length ?? 0,
|
|
13753
|
+
createdDocuments: reply?.createdDocumentUuids?.length ?? 0,
|
|
13754
|
+
cards: reply?.cardUuids?.length ?? 0,
|
|
13088
13755
|
numTurns: result?.numTurns,
|
|
13089
13756
|
costUsd: result?.costUsd
|
|
13090
13757
|
});
|
|
@@ -13101,6 +13768,8 @@ async function runAgentServe(deps) {
|
|
|
13101
13768
|
status: reply.status,
|
|
13102
13769
|
reply: reply.reply,
|
|
13103
13770
|
documentUuids: reply.documentUuids,
|
|
13771
|
+
...reply.createdDocumentUuids ? { createdDocumentUuids: reply.createdDocumentUuids } : {},
|
|
13772
|
+
...reply.cardUuids ? { cardUuids: reply.cardUuids } : {},
|
|
13104
13773
|
...reply.errorCode ? { errorCode: reply.errorCode } : {}
|
|
13105
13774
|
}, { turnUuid: offer.turnUuid, signal: stopController.signal });
|
|
13106
13775
|
return;
|
|
@@ -13131,7 +13800,7 @@ async function runAgentServe(deps) {
|
|
|
13131
13800
|
})();
|
|
13132
13801
|
await Promise.allSettled([pollLoop, worker]);
|
|
13133
13802
|
deps.signal.removeEventListener("abort", onUserStop);
|
|
13134
|
-
await
|
|
13803
|
+
await Promise.all([...live.values()].map((session) => session.close()));
|
|
13135
13804
|
if (stopReason === "signal") {
|
|
13136
13805
|
try {
|
|
13137
13806
|
await deps.http.call("close", { linkId });
|
|
@@ -13159,6 +13828,7 @@ function offersIn(res) {
|
|
|
13159
13828
|
turnUuid: offer.turnUuid,
|
|
13160
13829
|
conversationUuid: offer.conversationUuid,
|
|
13161
13830
|
text: offer.text,
|
|
13831
|
+
agent: offer.agent === void 0 || offer.agent === null ? DEFAULT_AGENT : String(offer.agent),
|
|
13162
13832
|
context: offer.context && typeof offer.context === "object" ? offer.context : void 0
|
|
13163
13833
|
}] : [];
|
|
13164
13834
|
});
|
|
@@ -13186,55 +13856,74 @@ var AgentSessionMap = class {
|
|
|
13186
13856
|
this.path = path;
|
|
13187
13857
|
}
|
|
13188
13858
|
path;
|
|
13189
|
-
map =
|
|
13859
|
+
map = emptyMap();
|
|
13190
13860
|
async load() {
|
|
13191
13861
|
try {
|
|
13192
13862
|
const parsed = JSON.parse(await readFile9(this.path, "utf8"));
|
|
13193
|
-
|
|
13194
|
-
|
|
13863
|
+
const map = emptyMap();
|
|
13864
|
+
map[DEFAULT_AGENT] = entries(parsed.conversations);
|
|
13865
|
+
const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
|
|
13866
|
+
for (const id of AGENT_IDS) {
|
|
13867
|
+
if (id !== DEFAULT_AGENT) map[id] = entries(byAgent[id]);
|
|
13195
13868
|
}
|
|
13869
|
+
this.map = map;
|
|
13196
13870
|
} catch (error) {
|
|
13197
13871
|
if (isNodeError(error, "ENOENT")) return;
|
|
13198
|
-
this.map =
|
|
13872
|
+
this.map = emptyMap();
|
|
13199
13873
|
}
|
|
13200
13874
|
}
|
|
13201
|
-
get(conversationUuid) {
|
|
13202
|
-
return this.map[conversationUuid]?.sessionId;
|
|
13875
|
+
get(conversationUuid, agent) {
|
|
13876
|
+
return this.map[agent][conversationUuid]?.sessionId;
|
|
13203
13877
|
}
|
|
13204
|
-
async set(conversationUuid, sessionId) {
|
|
13205
|
-
this.map[conversationUuid] = { sessionId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
13878
|
+
async set(conversationUuid, agent, sessionId) {
|
|
13879
|
+
this.map[agent][conversationUuid] = { sessionId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
13206
13880
|
await this.save();
|
|
13207
13881
|
}
|
|
13208
|
-
async forget(conversationUuid) {
|
|
13209
|
-
delete this.map[conversationUuid];
|
|
13882
|
+
async forget(conversationUuid, agent) {
|
|
13883
|
+
delete this.map[agent][conversationUuid];
|
|
13210
13884
|
await this.save();
|
|
13211
13885
|
}
|
|
13212
13886
|
async save() {
|
|
13887
|
+
const byAgent = Object.fromEntries(AGENT_IDS.filter((id) => id !== DEFAULT_AGENT).map((id) => [id, this.map[id]]));
|
|
13213
13888
|
const tmp = `${this.path}.tmp`;
|
|
13214
|
-
await writeFile6(
|
|
13215
|
-
|
|
13889
|
+
await writeFile6(
|
|
13890
|
+
tmp,
|
|
13891
|
+
`${JSON.stringify({ version: 2, conversations: this.map[DEFAULT_AGENT], byAgent }, null, 2)}
|
|
13892
|
+
`,
|
|
13893
|
+
{ mode: PRIVATE_FILE_MODE }
|
|
13894
|
+
);
|
|
13216
13895
|
await rename6(tmp, this.path);
|
|
13217
13896
|
}
|
|
13218
13897
|
};
|
|
13898
|
+
function emptyMap() {
|
|
13899
|
+
return Object.fromEntries(AGENT_IDS.map((id) => [id, {}]));
|
|
13900
|
+
}
|
|
13901
|
+
function entries(value) {
|
|
13902
|
+
if (!value || typeof value !== "object") return {};
|
|
13903
|
+
const out = {};
|
|
13904
|
+
for (const [conversationUuid, entry] of Object.entries(value)) {
|
|
13905
|
+
const e = entry;
|
|
13906
|
+
if (e && typeof e.sessionId === "string") {
|
|
13907
|
+
out[conversationUuid] = { sessionId: e.sessionId, updatedAt: typeof e.updatedAt === "string" ? e.updatedAt : "" };
|
|
13908
|
+
}
|
|
13909
|
+
}
|
|
13910
|
+
return out;
|
|
13911
|
+
}
|
|
13219
13912
|
|
|
13220
13913
|
// src/adapters/cli/agentCommand.ts
|
|
13221
13914
|
var AGENT_HELP_LINES = [
|
|
13222
|
-
" ainecto agent serve [--env prod|dev] answer \xABMy agent\xBB requests from AiNecto Chat with Claude Code on this machine (Ctrl+C to stop; log: ~/.ainecto/agent/agent.log)"
|
|
13915
|
+
" ainecto agent serve [--env prod|dev] answer \xABMy agent\xBB requests from AiNecto Chat with Claude Code or Codex on this machine (Ctrl+C to stop; log: ~/.ainecto/agent/agent.log)"
|
|
13223
13916
|
];
|
|
13224
13917
|
function isAgentCommand(domain, action) {
|
|
13225
13918
|
return domain === "agent" && action === "serve";
|
|
13226
13919
|
}
|
|
13920
|
+
var BILLED_TO = { "claude-code": "Anthropic", codex: "OpenAI" };
|
|
13227
13921
|
async function executeAgentServe(input) {
|
|
13228
|
-
const claude = spawnSync("claude", ["--version"], { encoding: "utf8" });
|
|
13229
|
-
if (claude.error || claude.status !== 0) {
|
|
13230
|
-
throw new Error("Claude Code (`claude`) is not on PATH. Install Claude Code and sign in, then run `ainecto agent serve` again.");
|
|
13231
|
-
}
|
|
13232
13922
|
const paths = agentPaths();
|
|
13233
13923
|
await ensurePrivateDir(paths.dir);
|
|
13234
13924
|
await ensurePrivateDir(paths.work);
|
|
13235
13925
|
const log = openAgentLog(paths);
|
|
13236
13926
|
const host = hostname();
|
|
13237
|
-
log.write({ event: "serve_start", pid: process.pid, version: CLI_VERSION, endpoint: input.endpoint, host, claude: claude.stdout.trim() });
|
|
13238
13927
|
const rpc = new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli" });
|
|
13239
13928
|
const started = Date.now();
|
|
13240
13929
|
log.write({ event: "agent_call", callId: `tools-list-${started}`, op: "tools_list", bytes: 0 });
|
|
@@ -13253,25 +13942,54 @@ async function executeAgentServe(input) {
|
|
|
13253
13942
|
});
|
|
13254
13943
|
throw error;
|
|
13255
13944
|
}
|
|
13945
|
+
const cliScript = process.argv[1];
|
|
13946
|
+
if (!cliScript) throw new Error("Cannot find the path of this CLI to start the AiNecto bridge for the agents.");
|
|
13947
|
+
const bridge = ainectoBridge(process.execPath, cliScript, input.endpoint);
|
|
13948
|
+
const shared = { spawnImpl: spawnAgent, cwd: paths.work, env: agentEnv(process.env), log, writeTools };
|
|
13949
|
+
const mcpConfig = claudeMcpConfig(bridge);
|
|
13950
|
+
const all = [
|
|
13951
|
+
claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig, resumeSessionId }) }),
|
|
13952
|
+
codexAdapter({ ...shared, appServerArgs: codexAppServerArgs(bridge, writeTools), clientVersion: CLI_VERSION })
|
|
13953
|
+
];
|
|
13954
|
+
const checks = await checkAgents(all, log);
|
|
13955
|
+
log.write({
|
|
13956
|
+
event: "serve_start",
|
|
13957
|
+
pid: process.pid,
|
|
13958
|
+
version: CLI_VERSION,
|
|
13959
|
+
endpoint: input.endpoint,
|
|
13960
|
+
host,
|
|
13961
|
+
agents: checks.map(({ id, installed, ready, auth, version }) => ({ id, installed, ready, ...auth ? { auth } : {}, ...version ? { version } : {} }))
|
|
13962
|
+
});
|
|
13963
|
+
const agents = openAgents(checks);
|
|
13964
|
+
if (agents.length === 0) {
|
|
13965
|
+
throw new Error("Neither Claude Code (`claude`) nor Codex (`codex`) is on PATH. Install one and sign in, then run `ainecto agent serve` again.");
|
|
13966
|
+
}
|
|
13967
|
+
for (const check of checks) {
|
|
13968
|
+
const name = all.find((adapter) => adapter.id === check.id)?.displayName ?? check.id;
|
|
13969
|
+
if (!check.installed) continue;
|
|
13970
|
+
if (check.ready) {
|
|
13971
|
+
input.io.stderr.write(check.auth === "apiKey" ? `${name}: runs on your own API key (billed to your ${BILLED_TO[check.id]} API account).
|
|
13972
|
+
` : `${name}: runs on your subscription login (uses your plan's limits).
|
|
13973
|
+
`);
|
|
13974
|
+
} else {
|
|
13975
|
+
input.io.stderr.write(`${name} is installed but not signed in${check.detail ? ` (${check.detail})` : ""}. Requests to ${name} will be refused until you sign in and run \`ainecto agent serve\` again.
|
|
13976
|
+
`);
|
|
13977
|
+
}
|
|
13978
|
+
}
|
|
13979
|
+
const adapters = new Map(all.filter((adapter) => agents.some((a) => a.id === adapter.id)).map((adapter) => [adapter.id, adapter]));
|
|
13256
13980
|
const sessions = new AgentSessionMap(paths.sessions);
|
|
13257
13981
|
await sessions.load();
|
|
13258
13982
|
const controller = new AbortController();
|
|
13259
13983
|
const onSignal = () => controller.abort();
|
|
13260
13984
|
process.once("SIGINT", onSignal);
|
|
13261
13985
|
process.once("SIGTERM", onSignal);
|
|
13262
|
-
const cliScript = process.argv[1];
|
|
13263
|
-
if (!cliScript) throw new Error("Cannot find the path of this CLI to start the AiNecto bridge for Claude Code.");
|
|
13264
|
-
const mcpConfig = agentMcpConfig(process.execPath, cliScript, input.endpoint);
|
|
13265
13986
|
try {
|
|
13266
13987
|
const result = await runAgentServe({
|
|
13267
13988
|
http: createAgentHttp({ endpoint: input.endpoint, tokenProvider: input.auth, log }),
|
|
13268
13989
|
log,
|
|
13269
13990
|
sessions,
|
|
13270
|
-
|
|
13271
|
-
|
|
13272
|
-
spawnImpl: spawnClaude,
|
|
13273
|
-
cwd: paths.work,
|
|
13274
|
-
env: claudeAgentEnv(process.env),
|
|
13991
|
+
adapters,
|
|
13992
|
+
agents,
|
|
13275
13993
|
hostName: host,
|
|
13276
13994
|
cliVersion: CLI_VERSION,
|
|
13277
13995
|
print: (line) => input.io.stderr.write(`${line}
|
|
@@ -13406,7 +14124,7 @@ async function runAinectoCli(argv, io) {
|
|
|
13406
14124
|
});
|
|
13407
14125
|
}
|
|
13408
14126
|
if (isAgentCommand(domain, action)) {
|
|
13409
|
-
return await executeAgentServe({ endpoint: resolved.endpoint, auth: connect2().auth, io });
|
|
14127
|
+
return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io });
|
|
13410
14128
|
}
|
|
13411
14129
|
if (domain === "auth") {
|
|
13412
14130
|
return await handleAuth(action, connect2().auth, resolved.endpoint, parsed.json, io);
|