@ainecto/cli 0.14.0-next.1 → 0.14.0-next.2
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 +885 -188
- 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.2" : 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,184 @@ 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);
|
|
12863
|
+
},
|
|
12864
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new ClaudeCodeSession(conversationUuid, resumeRef, deps.args({ textMaxCharacters, resumeSessionId: resumeRef }), deps)
|
|
12865
|
+
};
|
|
12866
|
+
}
|
|
12867
|
+
function claudeAuthFromJson(stdout, code, stderrTail) {
|
|
12868
|
+
let parsed;
|
|
12869
|
+
try {
|
|
12870
|
+
const value = JSON.parse(stdout);
|
|
12871
|
+
if (value && typeof value === "object" && !Array.isArray(value)) parsed = value;
|
|
12872
|
+
} catch {
|
|
12873
|
+
}
|
|
12874
|
+
if (!parsed) {
|
|
12875
|
+
return { ready: false, detail: `unreadable auth status (exit ${code ?? "-"})${stderrTail ? `: ${stderrTail}` : ""}` };
|
|
12876
|
+
}
|
|
12877
|
+
return {
|
|
12878
|
+
ready: parsed.loggedIn === true,
|
|
12879
|
+
method: typeof parsed.authMethod === "string" ? parsed.authMethod : void 0,
|
|
12880
|
+
plan: typeof parsed.subscriptionType === "string" ? parsed.subscriptionType : void 0
|
|
12881
|
+
};
|
|
12882
|
+
}
|
|
12883
|
+
var ClaudeCodeSession = class {
|
|
12884
|
+
constructor(conversationUuid, resumeRef, args, deps) {
|
|
12885
|
+
this.conversationUuid = conversationUuid;
|
|
12886
|
+
this.deps = deps;
|
|
12887
|
+
this.resumed = resumeRef !== void 0;
|
|
12888
|
+
this.child = new AgentChild(deps.spawnImpl, CLAUDE, args, { cwd: deps.cwd, env: deps.env }, {
|
|
12889
|
+
line: (line) => this.onLine(line),
|
|
12890
|
+
exit: (exit) => this.onExit(exit)
|
|
12694
12891
|
});
|
|
12892
|
+
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
12695
12893
|
}
|
|
12696
12894
|
conversationUuid;
|
|
12895
|
+
deps;
|
|
12896
|
+
agent = "claude-code";
|
|
12697
12897
|
resumed;
|
|
12698
|
-
|
|
12898
|
+
sessionRef;
|
|
12699
12899
|
child;
|
|
12700
12900
|
toolNames = /* @__PURE__ */ new Map();
|
|
12701
12901
|
pending;
|
|
12702
|
-
|
|
12703
|
-
exitInfo;
|
|
12704
|
-
exited;
|
|
12902
|
+
interrupts = 0;
|
|
12705
12903
|
get pid() {
|
|
12706
|
-
return this.child.pid
|
|
12904
|
+
return this.child.pid;
|
|
12707
12905
|
}
|
|
12708
12906
|
get alive() {
|
|
12709
|
-
return this.
|
|
12907
|
+
return this.child.alive;
|
|
12710
12908
|
}
|
|
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
|
-
}
|
|
12909
|
+
async send(text, timeoutMs) {
|
|
12910
|
+
const exit = this.child.exit;
|
|
12911
|
+
if (exit) return { kind: "exited", ...exit };
|
|
12716
12912
|
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);
|
|
12913
|
+
this.pending = { resolve: resolve4, facts: new WriteFactsCollector() };
|
|
12724
12914
|
});
|
|
12915
|
+
this.child.writeLine({ type: "user", message: { role: "user", content: text } });
|
|
12725
12916
|
try {
|
|
12726
|
-
return await
|
|
12917
|
+
return await withDeadline(outcome, timeoutMs, { kind: "timeout" });
|
|
12727
12918
|
} finally {
|
|
12728
|
-
clearTimeout(timer);
|
|
12729
12919
|
this.pending = void 0;
|
|
12730
12920
|
}
|
|
12731
12921
|
}
|
|
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);
|
|
12922
|
+
/** 실측: {@code control_request interrupt} → 13ms 뒤 그 차례가 끝나고 같은 프로세스가 이어진다(증적 three-agents ⑦). */
|
|
12923
|
+
async interrupt() {
|
|
12924
|
+
this.interrupts += 1;
|
|
12925
|
+
this.child.writeLine({ type: "control_request", request_id: `interrupt-${this.interrupts}`, request: { subtype: "interrupt" } });
|
|
12741
12926
|
}
|
|
12742
|
-
async
|
|
12743
|
-
|
|
12744
|
-
|
|
12745
|
-
|
|
12927
|
+
async close() {
|
|
12928
|
+
await this.child.stop();
|
|
12929
|
+
}
|
|
12930
|
+
onExit(exit) {
|
|
12931
|
+
this.deps.log.write({
|
|
12932
|
+
event: "process_exit",
|
|
12933
|
+
pid: this.child.pid,
|
|
12934
|
+
agent: this.agent,
|
|
12935
|
+
conversationUuid: this.conversationUuid,
|
|
12936
|
+
code: exit.code,
|
|
12937
|
+
signal: exit.signal
|
|
12746
12938
|
});
|
|
12747
|
-
|
|
12748
|
-
return await Promise.race([this.exited.then(() => true), timedOut]);
|
|
12749
|
-
} finally {
|
|
12750
|
-
clearTimeout(timer);
|
|
12751
|
-
}
|
|
12939
|
+
this.finish({ kind: "exited", ...exit });
|
|
12752
12940
|
}
|
|
12753
12941
|
finish(outcome) {
|
|
12754
12942
|
const pending = this.pending;
|
|
12755
12943
|
this.pending = void 0;
|
|
12756
12944
|
pending?.resolve(outcome);
|
|
12757
12945
|
}
|
|
12758
|
-
|
|
12946
|
+
onLine(line) {
|
|
12947
|
+
let event;
|
|
12948
|
+
try {
|
|
12949
|
+
event = JSON.parse(line);
|
|
12950
|
+
} catch {
|
|
12951
|
+
this.deps.log.write({ event: "bad_line", pid: this.child.pid, agent: this.agent, length: line.length });
|
|
12952
|
+
return;
|
|
12953
|
+
}
|
|
12759
12954
|
if (event.type === "system" && event.subtype === "init" && typeof event.session_id === "string") {
|
|
12760
|
-
this.
|
|
12955
|
+
this.sessionRef = event.session_id;
|
|
12761
12956
|
return;
|
|
12762
12957
|
}
|
|
12763
12958
|
const content = event.message?.content;
|
|
@@ -12773,25 +12968,21 @@ ${error.message}`;
|
|
|
12773
12968
|
for (const part of content) {
|
|
12774
12969
|
if (part.type !== "tool_result" || typeof part.tool_use_id !== "string") continue;
|
|
12775
12970
|
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
|
-
}
|
|
12971
|
+
if (!name?.startsWith(AINECTO_TOOL_PREFIX) || !this.deps.writeTools.has(name.slice(AINECTO_TOOL_PREFIX.length))) continue;
|
|
12972
|
+
this.pending.facts.add(part.content);
|
|
12780
12973
|
}
|
|
12781
12974
|
return;
|
|
12782
12975
|
}
|
|
12783
12976
|
if (event.type === "result") {
|
|
12784
|
-
if (typeof event.session_id === "string") this.
|
|
12785
|
-
const documents = this.pending?.documents ?? [];
|
|
12977
|
+
if (typeof event.session_id === "string") this.sessionRef = event.session_id;
|
|
12786
12978
|
this.finish({
|
|
12787
12979
|
kind: "result",
|
|
12788
|
-
documents,
|
|
12980
|
+
facts: this.pending?.facts.snapshot() ?? { documents: [], createdDocuments: [], cards: [] },
|
|
12789
12981
|
result: {
|
|
12790
12982
|
subtype: typeof event.subtype === "string" ? event.subtype : void 0,
|
|
12791
12983
|
isError: event.is_error === true,
|
|
12792
12984
|
structuredOutput: event.structured_output,
|
|
12793
12985
|
resultText: typeof event.result === "string" ? event.result : void 0,
|
|
12794
|
-
sessionId: this.sessionId,
|
|
12795
12986
|
numTurns: typeof event.num_turns === "number" ? event.num_turns : void 0,
|
|
12796
12987
|
costUsd: typeof event.total_cost_usd === "number" ? event.total_cost_usd : void 0
|
|
12797
12988
|
}
|
|
@@ -12800,6 +12991,381 @@ ${error.message}`;
|
|
|
12800
12991
|
}
|
|
12801
12992
|
};
|
|
12802
12993
|
|
|
12994
|
+
// src/core/agent/codexArgs.ts
|
|
12995
|
+
var CODEX = "codex";
|
|
12996
|
+
var THREAD_POLICY = { approvalPolicy: "never", sandbox: "read-only" };
|
|
12997
|
+
var CONFIG_KEY_PART = /^[A-Za-z0-9_-]+$/;
|
|
12998
|
+
var FEATURES_OFF = ["shell_tool", "plugins", "apps", "computer_use", "browser_use", "image_generation"];
|
|
12999
|
+
function codexAppServerArgs(bridge, writeTools) {
|
|
13000
|
+
const server = `mcp_servers.${AINECTO_MCP_SERVER}`;
|
|
13001
|
+
const config = [
|
|
13002
|
+
`${server}.command=${tomlString(bridge.command)}`,
|
|
13003
|
+
`${server}.args=[${bridge.args.map(tomlString).join(",")}]`,
|
|
13004
|
+
'approval_policy="never"',
|
|
13005
|
+
'sandbox_mode="read-only"',
|
|
13006
|
+
...FEATURES_OFF.map((feature) => `features.${feature}=false`),
|
|
13007
|
+
...[...writeTools].filter((tool) => CONFIG_KEY_PART.test(tool)).sort().map((tool) => `${server}.tools.${tool}.approval_mode="approve"`)
|
|
13008
|
+
];
|
|
13009
|
+
return ["app-server", ...config.flatMap((entry) => ["-c", entry])];
|
|
13010
|
+
}
|
|
13011
|
+
function tomlString(value) {
|
|
13012
|
+
return JSON.stringify(value);
|
|
13013
|
+
}
|
|
13014
|
+
function codexInitializeParams(clientVersion) {
|
|
13015
|
+
return { clientInfo: { name: "ainecto-cli", title: "AiNecto CLI", version: clientVersion } };
|
|
13016
|
+
}
|
|
13017
|
+
function codexOtherMcpServersOff(config) {
|
|
13018
|
+
const servers = config && typeof config === "object" ? config.mcp_servers : void 0;
|
|
13019
|
+
const names = servers && typeof servers === "object" ? Object.keys(servers).filter((name) => name !== AINECTO_MCP_SERVER).sort() : [];
|
|
13020
|
+
const bad = names.filter((name) => !CONFIG_KEY_PART.test(name));
|
|
13021
|
+
if (bad.length > 0) throw new Error(`cannot turn off Codex MCP server(s) ${bad.map((name) => JSON.stringify(name)).join(", ")}`);
|
|
13022
|
+
return { names, config: Object.fromEntries(names.map((name) => [`mcp_servers.${name}.enabled`, false])) };
|
|
13023
|
+
}
|
|
13024
|
+
function codexThreadStartParams(cwd, serversOff) {
|
|
13025
|
+
return { cwd, ...THREAD_POLICY, config: serversOff };
|
|
13026
|
+
}
|
|
13027
|
+
function codexThreadResumeParams(threadId, cwd, serversOff) {
|
|
13028
|
+
return { threadId, cwd, ...THREAD_POLICY, config: serversOff, excludeTurns: true };
|
|
13029
|
+
}
|
|
13030
|
+
function codexTurnStartParams(threadId, text, outputSchema) {
|
|
13031
|
+
return { threadId, input: [{ type: "text", text }], outputSchema };
|
|
13032
|
+
}
|
|
13033
|
+
function codexServerRequestAnswer(method) {
|
|
13034
|
+
switch (method) {
|
|
13035
|
+
case "mcpServer/elicitation/request":
|
|
13036
|
+
return { result: { action: "decline" } };
|
|
13037
|
+
case "item/commandExecution/requestApproval":
|
|
13038
|
+
case "item/fileChange/requestApproval":
|
|
13039
|
+
return { result: { decision: "decline" } };
|
|
13040
|
+
case "applyPatchApproval":
|
|
13041
|
+
case "execCommandApproval":
|
|
13042
|
+
return { result: { decision: "denied" } };
|
|
13043
|
+
default:
|
|
13044
|
+
return { error: { code: -32601, message: `ainecto agent serve does not answer ${method}` } };
|
|
13045
|
+
}
|
|
13046
|
+
}
|
|
13047
|
+
function codexAuthFromAccount(result) {
|
|
13048
|
+
const account = result.account && typeof result.account === "object" ? result.account : void 0;
|
|
13049
|
+
const method = typeof account?.type === "string" ? account.type : void 0;
|
|
13050
|
+
const plan = typeof account?.planType === "string" ? account.planType : void 0;
|
|
13051
|
+
if (account) return { ready: true, method, plan };
|
|
13052
|
+
if (result.requiresOpenaiAuth === false) return { ready: true, method: "none-required" };
|
|
13053
|
+
return { ready: false, detail: "not signed in (run `codex login`)" };
|
|
13054
|
+
}
|
|
13055
|
+
function codexTurnResult(turn, lastMessage) {
|
|
13056
|
+
const status = typeof turn.status === "string" ? turn.status : "unknown";
|
|
13057
|
+
const text = lastMessage ?? lastAgentMessageIn(turn.items);
|
|
13058
|
+
if (status !== "completed") {
|
|
13059
|
+
return { subtype: status, isError: true, resultText: errorMessage3(turn.error) ?? text };
|
|
13060
|
+
}
|
|
13061
|
+
if (text === void 0) return { subtype: status, isError: false };
|
|
13062
|
+
try {
|
|
13063
|
+
return { subtype: status, isError: false, structuredOutput: JSON.parse(text) };
|
|
13064
|
+
} catch {
|
|
13065
|
+
return { subtype: status, isError: false, resultText: text };
|
|
13066
|
+
}
|
|
13067
|
+
}
|
|
13068
|
+
function lastAgentMessageIn(items) {
|
|
13069
|
+
if (!Array.isArray(items)) return void 0;
|
|
13070
|
+
let text;
|
|
13071
|
+
for (const item of items) {
|
|
13072
|
+
if (item?.type === "agentMessage" && typeof item.text === "string") text = item.text;
|
|
13073
|
+
}
|
|
13074
|
+
return text;
|
|
13075
|
+
}
|
|
13076
|
+
function errorMessage3(error) {
|
|
13077
|
+
if (!error) return void 0;
|
|
13078
|
+
if (typeof error === "object" && typeof error.message === "string") {
|
|
13079
|
+
return error.message;
|
|
13080
|
+
}
|
|
13081
|
+
return JSON.stringify(error);
|
|
13082
|
+
}
|
|
13083
|
+
|
|
13084
|
+
// src/core/agent/codex.ts
|
|
13085
|
+
function codexAdapter(deps) {
|
|
13086
|
+
return {
|
|
13087
|
+
id: "codex",
|
|
13088
|
+
displayName: "Codex",
|
|
13089
|
+
detect: () => detectByVersion(deps.spawnImpl, CODEX, { cwd: deps.cwd, env: deps.env, timeoutMs: AGENT_CALL_TIMEOUT_MS }),
|
|
13090
|
+
async authStatus() {
|
|
13091
|
+
const server = startAppServer(deps, ["app-server"], {});
|
|
13092
|
+
try {
|
|
13093
|
+
const read = (async () => {
|
|
13094
|
+
await server.rpc.request("initialize", codexInitializeParams(deps.clientVersion));
|
|
13095
|
+
server.rpc.notify("initialized");
|
|
13096
|
+
return await server.rpc.request("account/read", { refreshToken: false });
|
|
13097
|
+
})();
|
|
13098
|
+
const result = await withDeadline(
|
|
13099
|
+
read.catch(toError),
|
|
13100
|
+
AGENT_CALL_TIMEOUT_MS,
|
|
13101
|
+
new Error("account/read timed out")
|
|
13102
|
+
);
|
|
13103
|
+
return result instanceof Error ? { ready: false, detail: result.message } : codexAuthFromAccount(result);
|
|
13104
|
+
} finally {
|
|
13105
|
+
await server.child.stop();
|
|
13106
|
+
}
|
|
13107
|
+
},
|
|
13108
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, deps)
|
|
13109
|
+
};
|
|
13110
|
+
}
|
|
13111
|
+
var CodexRpc = class {
|
|
13112
|
+
constructor(io) {
|
|
13113
|
+
this.io = io;
|
|
13114
|
+
}
|
|
13115
|
+
io;
|
|
13116
|
+
nextId = 0;
|
|
13117
|
+
waiting = /* @__PURE__ */ new Map();
|
|
13118
|
+
request(method, params) {
|
|
13119
|
+
this.nextId += 1;
|
|
13120
|
+
const id = this.nextId;
|
|
13121
|
+
this.io.log.write({ event: "agent_rpc", pid: this.io.pid(), agent: "codex", id, method });
|
|
13122
|
+
return new Promise((resolve4, reject) => {
|
|
13123
|
+
this.waiting.set(id, { method, started: Date.now(), resolve: resolve4, reject });
|
|
13124
|
+
if (!this.io.write({ id, method, params })) this.settle(id, new Error("codex is not running"));
|
|
13125
|
+
});
|
|
13126
|
+
}
|
|
13127
|
+
notify(method) {
|
|
13128
|
+
this.io.write({ method });
|
|
13129
|
+
}
|
|
13130
|
+
onLine(line) {
|
|
13131
|
+
let message;
|
|
13132
|
+
try {
|
|
13133
|
+
message = JSON.parse(line);
|
|
13134
|
+
} catch {
|
|
13135
|
+
this.io.log.write({ event: "bad_line", pid: this.io.pid(), agent: "codex", length: line.length });
|
|
13136
|
+
return;
|
|
13137
|
+
}
|
|
13138
|
+
const method = typeof message.method === "string" ? message.method : void 0;
|
|
13139
|
+
const params = message.params && typeof message.params === "object" ? message.params : {};
|
|
13140
|
+
if (message.id !== void 0 && method) {
|
|
13141
|
+
const answer = codexServerRequestAnswer(method);
|
|
13142
|
+
this.io.log.write({
|
|
13143
|
+
event: "agent_server_request",
|
|
13144
|
+
pid: this.io.pid(),
|
|
13145
|
+
agent: "codex",
|
|
13146
|
+
method,
|
|
13147
|
+
answer: "result" in answer ? JSON.stringify(answer.result) : `error ${answer.error.code}`
|
|
13148
|
+
});
|
|
13149
|
+
this.io.write({ id: message.id, ...answer });
|
|
13150
|
+
return;
|
|
13151
|
+
}
|
|
13152
|
+
if (typeof message.id === "number") {
|
|
13153
|
+
const error = message.error;
|
|
13154
|
+
if (error) {
|
|
13155
|
+
this.settle(message.id, new Error(typeof error.message === "string" ? error.message : JSON.stringify(error)));
|
|
13156
|
+
} else {
|
|
13157
|
+
this.settle(
|
|
13158
|
+
message.id,
|
|
13159
|
+
void 0,
|
|
13160
|
+
message.result && typeof message.result === "object" ? message.result : {}
|
|
13161
|
+
);
|
|
13162
|
+
}
|
|
13163
|
+
return;
|
|
13164
|
+
}
|
|
13165
|
+
if (method) this.io.notification(method, params);
|
|
13166
|
+
}
|
|
13167
|
+
/** 프로세스가 끝났다 — 기다리던 요청 전부에 응답 줄을 남기고 거절한다. */
|
|
13168
|
+
failAll(reason) {
|
|
13169
|
+
for (const id of [...this.waiting.keys()]) this.settle(id, new Error(reason));
|
|
13170
|
+
}
|
|
13171
|
+
settle(id, error, result) {
|
|
13172
|
+
const waiting = this.waiting.get(id);
|
|
13173
|
+
if (!waiting) return;
|
|
13174
|
+
this.waiting.delete(id);
|
|
13175
|
+
this.io.log.write({
|
|
13176
|
+
event: "agent_rpc_response",
|
|
13177
|
+
pid: this.io.pid(),
|
|
13178
|
+
agent: "codex",
|
|
13179
|
+
id,
|
|
13180
|
+
method: waiting.method,
|
|
13181
|
+
ok: error === void 0,
|
|
13182
|
+
...error ? { error: error.message } : {},
|
|
13183
|
+
ms: Date.now() - waiting.started
|
|
13184
|
+
});
|
|
13185
|
+
if (error) waiting.reject(error);
|
|
13186
|
+
else waiting.resolve(result ?? {});
|
|
13187
|
+
}
|
|
13188
|
+
};
|
|
13189
|
+
function startAppServer(deps, args, hooks) {
|
|
13190
|
+
const holder = {};
|
|
13191
|
+
const rpc = new CodexRpc({
|
|
13192
|
+
write: (message) => holder.child?.writeLine(message) ?? false,
|
|
13193
|
+
pid: () => holder.child?.pid ?? -1,
|
|
13194
|
+
log: deps.log,
|
|
13195
|
+
notification: (method, params) => hooks.notification?.(method, params)
|
|
13196
|
+
});
|
|
13197
|
+
const child = new AgentChild(deps.spawnImpl, CODEX, args, { cwd: deps.cwd, env: deps.env }, {
|
|
13198
|
+
line: (line) => rpc.onLine(line),
|
|
13199
|
+
exit: (exit) => {
|
|
13200
|
+
rpc.failAll(`codex exited (code ${exit.code ?? "-"}${exit.signal ? `, ${exit.signal}` : ""})${exit.stderrTail ? `: ${exit.stderrTail}` : ""}`);
|
|
13201
|
+
hooks.exit?.(exit);
|
|
13202
|
+
}
|
|
13203
|
+
});
|
|
13204
|
+
holder.child = child;
|
|
13205
|
+
return { child, rpc };
|
|
13206
|
+
}
|
|
13207
|
+
var CodexSession = class {
|
|
13208
|
+
constructor(conversationUuid, resumeRef, textMaxCharacters, deps) {
|
|
13209
|
+
this.conversationUuid = conversationUuid;
|
|
13210
|
+
this.textMaxCharacters = textMaxCharacters;
|
|
13211
|
+
this.deps = deps;
|
|
13212
|
+
this.resumed = resumeRef !== void 0;
|
|
13213
|
+
const server = startAppServer(deps, deps.appServerArgs, {
|
|
13214
|
+
notification: (method, params) => this.onNotification(method, params),
|
|
13215
|
+
exit: (exit) => this.onExit(exit)
|
|
13216
|
+
});
|
|
13217
|
+
this.child = server.child;
|
|
13218
|
+
this.rpc = server.rpc;
|
|
13219
|
+
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
13220
|
+
this.started = this.start(resumeRef).then(() => void 0, toError);
|
|
13221
|
+
}
|
|
13222
|
+
conversationUuid;
|
|
13223
|
+
textMaxCharacters;
|
|
13224
|
+
deps;
|
|
13225
|
+
agent = "codex";
|
|
13226
|
+
resumed;
|
|
13227
|
+
sessionRef;
|
|
13228
|
+
child;
|
|
13229
|
+
rpc;
|
|
13230
|
+
/** 준비(initialize·thread) — 실패하면 그 오류. */
|
|
13231
|
+
started;
|
|
13232
|
+
turn;
|
|
13233
|
+
/** 끝나지 않은 차례 — 기한을 넘긴 뒤에도 interrupt 할 수 있게 따로 둔다. */
|
|
13234
|
+
runningTurnId;
|
|
13235
|
+
get pid() {
|
|
13236
|
+
return this.child.pid;
|
|
13237
|
+
}
|
|
13238
|
+
get alive() {
|
|
13239
|
+
return this.child.alive;
|
|
13240
|
+
}
|
|
13241
|
+
async send(text, timeoutMs) {
|
|
13242
|
+
const work = (async () => {
|
|
13243
|
+
const failed = await this.started;
|
|
13244
|
+
if (failed) {
|
|
13245
|
+
await this.child.stop();
|
|
13246
|
+
const exit2 = this.child.exit;
|
|
13247
|
+
return {
|
|
13248
|
+
kind: "exited",
|
|
13249
|
+
code: exit2?.code ?? null,
|
|
13250
|
+
signal: exit2?.signal ?? null,
|
|
13251
|
+
stderrTail: [failed.message, exit2?.stderrTail].filter(Boolean).join("\n")
|
|
13252
|
+
};
|
|
13253
|
+
}
|
|
13254
|
+
const exit = this.child.exit;
|
|
13255
|
+
if (exit || !this.sessionRef) return { kind: "exited", code: exit?.code ?? null, signal: exit?.signal ?? null, stderrTail: exit?.stderrTail ?? "" };
|
|
13256
|
+
const turn = { resolve: () => {
|
|
13257
|
+
}, facts: new WriteFactsCollector() };
|
|
13258
|
+
const outcome = new Promise((resolve4) => {
|
|
13259
|
+
turn.resolve = resolve4;
|
|
13260
|
+
});
|
|
13261
|
+
this.turn = turn;
|
|
13262
|
+
try {
|
|
13263
|
+
const started = await this.rpc.request(
|
|
13264
|
+
"turn/start",
|
|
13265
|
+
codexTurnStartParams(this.sessionRef, text, agentReplySchema(this.textMaxCharacters))
|
|
13266
|
+
);
|
|
13267
|
+
const id = started.turn?.id;
|
|
13268
|
+
if (typeof id === "string") {
|
|
13269
|
+
turn.id = id;
|
|
13270
|
+
this.runningTurnId = id;
|
|
13271
|
+
}
|
|
13272
|
+
} catch (error) {
|
|
13273
|
+
if (this.child.alive) {
|
|
13274
|
+
this.finishTurn(turn, {
|
|
13275
|
+
kind: "result",
|
|
13276
|
+
facts: turn.facts.snapshot(),
|
|
13277
|
+
result: { subtype: "turn_start_failed", isError: true, resultText: toError(error).message }
|
|
13278
|
+
});
|
|
13279
|
+
}
|
|
13280
|
+
}
|
|
13281
|
+
return await outcome;
|
|
13282
|
+
})();
|
|
13283
|
+
try {
|
|
13284
|
+
return await withDeadline(work, timeoutMs, { kind: "timeout" });
|
|
13285
|
+
} finally {
|
|
13286
|
+
this.turn = void 0;
|
|
13287
|
+
}
|
|
13288
|
+
}
|
|
13289
|
+
/** 실측: {@code turn/interrupt} → 12ms 뒤 {@code interrupted}, 같은 thread 가 이어진다(증적 three-agents ⑦). B6 안에 답이 없으면 그대로 둔다. */
|
|
13290
|
+
async interrupt() {
|
|
13291
|
+
const turnId = this.runningTurnId;
|
|
13292
|
+
if (!turnId || !this.sessionRef || !this.child.alive) return;
|
|
13293
|
+
await withDeadline(
|
|
13294
|
+
this.rpc.request("turn/interrupt", { threadId: this.sessionRef, turnId }).then(() => void 0, () => void 0),
|
|
13295
|
+
AGENT_STOP_WAIT_MS,
|
|
13296
|
+
void 0
|
|
13297
|
+
);
|
|
13298
|
+
}
|
|
13299
|
+
async close() {
|
|
13300
|
+
await this.child.stop();
|
|
13301
|
+
}
|
|
13302
|
+
async start(resumeRef) {
|
|
13303
|
+
await this.rpc.request("initialize", codexInitializeParams(this.deps.clientVersion));
|
|
13304
|
+
this.rpc.notify("initialized");
|
|
13305
|
+
const read = await this.rpc.request("config/read", { cwd: this.deps.cwd });
|
|
13306
|
+
const off = codexOtherMcpServersOff(read.config);
|
|
13307
|
+
this.deps.log.write({ event: "agent_mcp_servers_off", pid: this.child.pid, agent: this.agent, names: off.names });
|
|
13308
|
+
const method = resumeRef ? "thread/resume" : "thread/start";
|
|
13309
|
+
const result = await this.rpc.request(
|
|
13310
|
+
method,
|
|
13311
|
+
resumeRef ? codexThreadResumeParams(resumeRef, this.deps.cwd, off.config) : codexThreadStartParams(this.deps.cwd, off.config)
|
|
13312
|
+
);
|
|
13313
|
+
const id = result.thread?.id;
|
|
13314
|
+
if (typeof id !== "string") throw new Error(`${method} returned no thread id`);
|
|
13315
|
+
this.sessionRef = id;
|
|
13316
|
+
}
|
|
13317
|
+
onExit(exit) {
|
|
13318
|
+
this.deps.log.write({
|
|
13319
|
+
event: "process_exit",
|
|
13320
|
+
pid: this.child.pid,
|
|
13321
|
+
agent: this.agent,
|
|
13322
|
+
conversationUuid: this.conversationUuid,
|
|
13323
|
+
code: exit.code,
|
|
13324
|
+
signal: exit.signal
|
|
13325
|
+
});
|
|
13326
|
+
this.runningTurnId = void 0;
|
|
13327
|
+
if (this.turn) this.finishTurn(this.turn, { kind: "exited", ...exit });
|
|
13328
|
+
}
|
|
13329
|
+
finishTurn(turn, outcome) {
|
|
13330
|
+
if (this.turn === turn) this.turn = void 0;
|
|
13331
|
+
turn.resolve(outcome);
|
|
13332
|
+
}
|
|
13333
|
+
onNotification(method, params) {
|
|
13334
|
+
if (method === "mcpServer/startupStatus/updated") {
|
|
13335
|
+
if (typeof params.name === "string" && typeof params.status === "string" && params.status !== "starting") {
|
|
13336
|
+
this.deps.log.write({
|
|
13337
|
+
event: "agent_mcp_server",
|
|
13338
|
+
pid: this.child.pid,
|
|
13339
|
+
agent: this.agent,
|
|
13340
|
+
name: params.name,
|
|
13341
|
+
status: params.status,
|
|
13342
|
+
...typeof params.error === "string" ? { error: params.error } : {}
|
|
13343
|
+
});
|
|
13344
|
+
}
|
|
13345
|
+
return;
|
|
13346
|
+
}
|
|
13347
|
+
if (params.threadId !== this.sessionRef) return;
|
|
13348
|
+
const turn = this.turn;
|
|
13349
|
+
if (method === "turn/completed") {
|
|
13350
|
+
const completed = params.turn && typeof params.turn === "object" ? params.turn : {};
|
|
13351
|
+
if (completed.id === this.runningTurnId) this.runningTurnId = void 0;
|
|
13352
|
+
if (!turn || turn.id !== void 0 && completed.id !== turn.id) return;
|
|
13353
|
+
this.finishTurn(turn, { kind: "result", facts: turn.facts.snapshot(), result: codexTurnResult(completed, turn.lastMessage) });
|
|
13354
|
+
return;
|
|
13355
|
+
}
|
|
13356
|
+
if (method !== "item/completed" || !turn) return;
|
|
13357
|
+
const item = params.item && typeof params.item === "object" ? params.item : {};
|
|
13358
|
+
if (item.type === "agentMessage" && typeof item.text === "string") {
|
|
13359
|
+
turn.lastMessage = item.text;
|
|
13360
|
+
} else if (item.type === "mcpToolCall" && item.server === AINECTO_MCP_SERVER && typeof item.tool === "string" && this.deps.writeTools.has(item.tool)) {
|
|
13361
|
+
turn.facts.add(item.result?.content);
|
|
13362
|
+
}
|
|
13363
|
+
}
|
|
13364
|
+
};
|
|
13365
|
+
function toError(error) {
|
|
13366
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
13367
|
+
}
|
|
13368
|
+
|
|
12803
13369
|
// src/core/agent/http.ts
|
|
12804
13370
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
12805
13371
|
var AgentCallError = class extends Error {
|
|
@@ -12919,6 +13485,55 @@ function agentPaths(home = homedir3()) {
|
|
|
12919
13485
|
};
|
|
12920
13486
|
}
|
|
12921
13487
|
|
|
13488
|
+
// src/core/agent/readiness.ts
|
|
13489
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
13490
|
+
async function checkAgents(adapters, log) {
|
|
13491
|
+
return await Promise.all(adapters.map(async (adapter) => {
|
|
13492
|
+
const detected = await probe(
|
|
13493
|
+
log,
|
|
13494
|
+
adapter.id,
|
|
13495
|
+
"detect",
|
|
13496
|
+
() => adapter.detect(),
|
|
13497
|
+
(d) => ({ installed: d.installed, version: d.version, detail: d.detail })
|
|
13498
|
+
);
|
|
13499
|
+
if (!detected?.installed) {
|
|
13500
|
+
return { id: adapter.id, installed: false, ready: false, detail: detected?.detail };
|
|
13501
|
+
}
|
|
13502
|
+
const auth = await probe(
|
|
13503
|
+
log,
|
|
13504
|
+
adapter.id,
|
|
13505
|
+
"auth",
|
|
13506
|
+
() => adapter.authStatus(),
|
|
13507
|
+
(a) => ({ ready: a.ready, method: a.method, plan: a.plan, detail: a.detail })
|
|
13508
|
+
);
|
|
13509
|
+
return { id: adapter.id, installed: true, version: detected.version, ready: auth?.ready === true, detail: auth?.detail };
|
|
13510
|
+
}));
|
|
13511
|
+
}
|
|
13512
|
+
function openAgents(checks) {
|
|
13513
|
+
return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready }));
|
|
13514
|
+
}
|
|
13515
|
+
async function probe(log, agent, kind, work, summary) {
|
|
13516
|
+
const callId = randomUUID3();
|
|
13517
|
+
const started = Date.now();
|
|
13518
|
+
log.write({ event: "agent_probe", callId, agent, probe: kind });
|
|
13519
|
+
try {
|
|
13520
|
+
const value = await work();
|
|
13521
|
+
log.write({ event: "agent_probe_response", callId, agent, probe: kind, ok: true, ...summary(value), ms: Date.now() - started });
|
|
13522
|
+
return value;
|
|
13523
|
+
} catch (error) {
|
|
13524
|
+
log.write({
|
|
13525
|
+
event: "agent_probe_response",
|
|
13526
|
+
callId,
|
|
13527
|
+
agent,
|
|
13528
|
+
probe: kind,
|
|
13529
|
+
ok: false,
|
|
13530
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
13531
|
+
ms: Date.now() - started
|
|
13532
|
+
});
|
|
13533
|
+
return void 0;
|
|
13534
|
+
}
|
|
13535
|
+
}
|
|
13536
|
+
|
|
12922
13537
|
// src/core/agent/prompt.ts
|
|
12923
13538
|
function agentPromptText(text, context) {
|
|
12924
13539
|
const parts = [];
|
|
@@ -12940,25 +13555,33 @@ function str(value) {
|
|
|
12940
13555
|
}
|
|
12941
13556
|
|
|
12942
13557
|
// src/core/agent/reply.ts
|
|
12943
|
-
function replyForOutcome(outcome, limits) {
|
|
12944
|
-
const
|
|
12945
|
-
const
|
|
13558
|
+
function replyForOutcome(outcome, limits, agentName) {
|
|
13559
|
+
const facts = outcome.kind === "result" ? outcome.facts : void 0;
|
|
13560
|
+
const documentUuids = facts ? facts.documents.slice(0, limits.documentsMax) : [];
|
|
13561
|
+
const createdDocumentUuids = facts ? facts.createdDocuments.filter((uuid) => documentUuids.includes(uuid)) : [];
|
|
13562
|
+
const cardUuids = facts ? facts.cards.slice(0, limits.documentsMax) : [];
|
|
13563
|
+
const attached = {
|
|
13564
|
+
documentUuids,
|
|
13565
|
+
...createdDocumentUuids.length > 0 ? { createdDocumentUuids } : {},
|
|
13566
|
+
...cardUuids.length > 0 ? { cardUuids } : {}
|
|
13567
|
+
};
|
|
13568
|
+
const failed = (errorCode2, text) => ({ status: "FAILED", errorCode: errorCode2, reply: clip(text, limits.textMaxCharacters), ...attached });
|
|
12946
13569
|
switch (outcome.kind) {
|
|
12947
13570
|
case "timeout":
|
|
12948
13571
|
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
13572
|
case "exited":
|
|
12950
|
-
return failed("AGENT_EXITED",
|
|
13573
|
+
return failed("AGENT_EXITED", `${agentName} \uAC00 \uB05D\uB0AC\uC5B4\uC694(code ${outcome.code ?? "-"}${outcome.signal ? `, ${outcome.signal}` : ""}).` + (outcome.stderrTail ? `
|
|
12951
13574
|
${outcome.stderrTail}` : ""));
|
|
12952
13575
|
case "result": {
|
|
12953
13576
|
const { result } = outcome;
|
|
12954
13577
|
if (result.isError) {
|
|
12955
|
-
return failed("AGENT_ERROR",
|
|
13578
|
+
return failed("AGENT_ERROR", `${agentName} \uAC00 \uC2E4\uD328\uD588\uC5B4\uC694(${result.subtype ?? "error"}).` + (result.resultText ? `
|
|
12956
13579
|
${result.resultText}` : ""));
|
|
12957
13580
|
}
|
|
12958
13581
|
const reply = result.structuredOutput?.reply;
|
|
12959
13582
|
const keys = result.structuredOutput && typeof result.structuredOutput === "object" ? Object.keys(result.structuredOutput) : [];
|
|
12960
13583
|
if (typeof reply === "string" && reply.trim().length > 0 && keys.length === 1 && codePoints(reply) <= limits.textMaxCharacters) {
|
|
12961
|
-
return { status: "DONE", reply,
|
|
13584
|
+
return { status: "DONE", reply, ...attached };
|
|
12962
13585
|
}
|
|
12963
13586
|
const raw = result.structuredOutput !== void 0 ? JSON.stringify(result.structuredOutput) : result.resultText ?? "";
|
|
12964
13587
|
return failed("SCHEMA_VIOLATION", `\uB2F5 \uD615\uC2DD\uC774 \uC5B4\uAE0B\uB0AC\uC5B4\uC694.
|
|
@@ -12976,16 +13599,17 @@ function clip(text, max) {
|
|
|
12976
13599
|
|
|
12977
13600
|
// src/core/agent/serve.ts
|
|
12978
13601
|
async function runAgentServe(deps) {
|
|
12979
|
-
const opened = await deps.http.call("open", { hostName: deps.hostName, cliVersion: deps.cliVersion });
|
|
13602
|
+
const opened = await deps.http.call("open", { hostName: deps.hostName, cliVersion: deps.cliVersion, agents: deps.agents });
|
|
12980
13603
|
const linkId = String(opened.linkId);
|
|
12981
13604
|
deps.http.useLinkToken(String(opened.linkToken));
|
|
12982
13605
|
const limits = serverLimits(opened.limits);
|
|
12983
|
-
deps.
|
|
13606
|
+
const names = deps.agents.map((a) => deps.adapters.get(a.id)?.displayName ?? a.id).join(" / ");
|
|
13607
|
+
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
13608
|
const stopController = new AbortController();
|
|
12985
13609
|
let stopReason;
|
|
12986
13610
|
let exitCode2 = 0;
|
|
12987
13611
|
let wakeWorker;
|
|
12988
|
-
|
|
13612
|
+
const live = /* @__PURE__ */ new Map();
|
|
12989
13613
|
const received = /* @__PURE__ */ new Set();
|
|
12990
13614
|
const queue = [];
|
|
12991
13615
|
const stop = (reason, code, message) => {
|
|
@@ -12995,7 +13619,7 @@ async function runAgentServe(deps) {
|
|
|
12995
13619
|
if (message) deps.print(message);
|
|
12996
13620
|
stopController.abort();
|
|
12997
13621
|
wakeWorker?.();
|
|
12998
|
-
void
|
|
13622
|
+
for (const session of live.values()) void session.close();
|
|
12999
13623
|
};
|
|
13000
13624
|
const onUserStop = () => stop("signal", 0, "Stopping\u2026");
|
|
13001
13625
|
if (deps.signal.aborted) onUserStop();
|
|
@@ -13019,7 +13643,7 @@ async function runAgentServe(deps) {
|
|
|
13019
13643
|
}
|
|
13020
13644
|
for (const offer of offersIn(res)) {
|
|
13021
13645
|
const duplicate = received.has(offer.turnUuid);
|
|
13022
|
-
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, duplicate });
|
|
13646
|
+
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, agent: offer.agent, duplicate });
|
|
13023
13647
|
if (duplicate) continue;
|
|
13024
13648
|
received.add(offer.turnUuid);
|
|
13025
13649
|
queue.push(offer);
|
|
@@ -13036,55 +13660,83 @@ async function runAgentServe(deps) {
|
|
|
13036
13660
|
}
|
|
13037
13661
|
}
|
|
13038
13662
|
})();
|
|
13663
|
+
const sessionFor = async (adapter, conversationUuid) => {
|
|
13664
|
+
const existing = live.get(adapter.id);
|
|
13665
|
+
if (existing && existing.conversationUuid === conversationUuid && existing.alive) return existing;
|
|
13666
|
+
if (existing) {
|
|
13667
|
+
live.delete(adapter.id);
|
|
13668
|
+
await existing.close();
|
|
13669
|
+
}
|
|
13670
|
+
const session = adapter.open({
|
|
13671
|
+
conversationUuid,
|
|
13672
|
+
resumeRef: deps.sessions.get(conversationUuid, adapter.id),
|
|
13673
|
+
textMaxCharacters: limits.textMaxCharacters
|
|
13674
|
+
});
|
|
13675
|
+
live.set(adapter.id, session);
|
|
13676
|
+
return session;
|
|
13677
|
+
};
|
|
13039
13678
|
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
13679
|
const started = Date.now();
|
|
13055
|
-
|
|
13680
|
+
const adapter = isAgentId(offer.agent) ? deps.adapters.get(offer.agent) : void 0;
|
|
13681
|
+
let session;
|
|
13056
13682
|
let outcome;
|
|
13057
13683
|
let reply;
|
|
13058
13684
|
let failure2;
|
|
13059
13685
|
try {
|
|
13060
|
-
|
|
13686
|
+
try {
|
|
13687
|
+
session = adapter ? await sessionFor(adapter, offer.conversationUuid) : void 0;
|
|
13688
|
+
} finally {
|
|
13689
|
+
deps.log.write({
|
|
13690
|
+
event: "agent_request",
|
|
13691
|
+
turnUuid: offer.turnUuid,
|
|
13692
|
+
agent: offer.agent,
|
|
13693
|
+
conversationUuid: offer.conversationUuid,
|
|
13694
|
+
pid: session?.pid ?? -1,
|
|
13695
|
+
textLength: offer.text.length
|
|
13696
|
+
});
|
|
13697
|
+
}
|
|
13698
|
+
if (!adapter || !session) {
|
|
13699
|
+
failure2 = "agent not installed";
|
|
13700
|
+
reply = {
|
|
13701
|
+
status: "FAILED",
|
|
13702
|
+
errorCode: "AGENT_NOT_INSTALLED",
|
|
13703
|
+
documentUuids: [],
|
|
13704
|
+
reply: clip(`\uC774 PC \uC5D0\uB294 \xAB${offer.agent}\xBB \uAC00 \uC124\uCE58\uB418\uC5B4 \uC788\uC9C0 \uC54A\uC544\uC694.`, limits.textMaxCharacters)
|
|
13705
|
+
};
|
|
13706
|
+
return reply;
|
|
13707
|
+
}
|
|
13708
|
+
outcome = await session.send(agentPromptText(offer.text, offer.context), deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
|
|
13061
13709
|
if (outcome.kind === "timeout") {
|
|
13062
|
-
await
|
|
13710
|
+
await session.interrupt();
|
|
13711
|
+
await session.close();
|
|
13063
13712
|
}
|
|
13064
13713
|
if (outcome.kind !== "result") {
|
|
13065
|
-
|
|
13066
|
-
if (
|
|
13067
|
-
} else if (
|
|
13068
|
-
await deps.sessions.set(offer.conversationUuid,
|
|
13714
|
+
if (live.get(adapter.id) === session) live.delete(adapter.id);
|
|
13715
|
+
if (session.resumed) await deps.sessions.forget(offer.conversationUuid, adapter.id);
|
|
13716
|
+
} else if (session.sessionRef) {
|
|
13717
|
+
await deps.sessions.set(offer.conversationUuid, adapter.id, session.sessionRef);
|
|
13069
13718
|
}
|
|
13070
|
-
reply = replyForOutcome(outcome, limits);
|
|
13719
|
+
reply = replyForOutcome(outcome, limits, adapter.displayName);
|
|
13071
13720
|
return reply;
|
|
13072
13721
|
} catch (error) {
|
|
13073
13722
|
failure2 = error instanceof Error ? error.message : String(error);
|
|
13074
|
-
reply = { status: "FAILED", errorCode: "AGENT_INTERNAL", reply: `The PC agent failed: ${failure2}
|
|
13723
|
+
reply = { status: "FAILED", errorCode: "AGENT_INTERNAL", reply: clip(`The PC agent failed: ${failure2}`, limits.textMaxCharacters), documentUuids: [] };
|
|
13075
13724
|
return reply;
|
|
13076
13725
|
} finally {
|
|
13077
13726
|
const result = outcome?.kind === "result" ? outcome.result : void 0;
|
|
13078
13727
|
deps.log.write({
|
|
13079
13728
|
event: "agent_response",
|
|
13080
13729
|
turnUuid: offer.turnUuid,
|
|
13730
|
+
agent: offer.agent,
|
|
13081
13731
|
ms: Date.now() - started,
|
|
13082
13732
|
outcome: outcome?.kind ?? `error: ${failure2 ?? "unknown"}`,
|
|
13083
13733
|
status: reply?.status ?? "FAILED",
|
|
13084
13734
|
errorCode: reply?.errorCode,
|
|
13085
13735
|
subtype: result?.subtype,
|
|
13086
|
-
sessionId:
|
|
13736
|
+
sessionId: session?.sessionRef,
|
|
13087
13737
|
documents: reply?.documentUuids.length ?? 0,
|
|
13738
|
+
createdDocuments: reply?.createdDocumentUuids?.length ?? 0,
|
|
13739
|
+
cards: reply?.cardUuids?.length ?? 0,
|
|
13088
13740
|
numTurns: result?.numTurns,
|
|
13089
13741
|
costUsd: result?.costUsd
|
|
13090
13742
|
});
|
|
@@ -13101,6 +13753,8 @@ async function runAgentServe(deps) {
|
|
|
13101
13753
|
status: reply.status,
|
|
13102
13754
|
reply: reply.reply,
|
|
13103
13755
|
documentUuids: reply.documentUuids,
|
|
13756
|
+
...reply.createdDocumentUuids ? { createdDocumentUuids: reply.createdDocumentUuids } : {},
|
|
13757
|
+
...reply.cardUuids ? { cardUuids: reply.cardUuids } : {},
|
|
13104
13758
|
...reply.errorCode ? { errorCode: reply.errorCode } : {}
|
|
13105
13759
|
}, { turnUuid: offer.turnUuid, signal: stopController.signal });
|
|
13106
13760
|
return;
|
|
@@ -13131,7 +13785,7 @@ async function runAgentServe(deps) {
|
|
|
13131
13785
|
})();
|
|
13132
13786
|
await Promise.allSettled([pollLoop, worker]);
|
|
13133
13787
|
deps.signal.removeEventListener("abort", onUserStop);
|
|
13134
|
-
await
|
|
13788
|
+
await Promise.all([...live.values()].map((session) => session.close()));
|
|
13135
13789
|
if (stopReason === "signal") {
|
|
13136
13790
|
try {
|
|
13137
13791
|
await deps.http.call("close", { linkId });
|
|
@@ -13159,6 +13813,7 @@ function offersIn(res) {
|
|
|
13159
13813
|
turnUuid: offer.turnUuid,
|
|
13160
13814
|
conversationUuid: offer.conversationUuid,
|
|
13161
13815
|
text: offer.text,
|
|
13816
|
+
agent: offer.agent === void 0 || offer.agent === null ? DEFAULT_AGENT : String(offer.agent),
|
|
13162
13817
|
context: offer.context && typeof offer.context === "object" ? offer.context : void 0
|
|
13163
13818
|
}] : [];
|
|
13164
13819
|
});
|
|
@@ -13186,55 +13841,73 @@ var AgentSessionMap = class {
|
|
|
13186
13841
|
this.path = path;
|
|
13187
13842
|
}
|
|
13188
13843
|
path;
|
|
13189
|
-
map =
|
|
13844
|
+
map = emptyMap();
|
|
13190
13845
|
async load() {
|
|
13191
13846
|
try {
|
|
13192
13847
|
const parsed = JSON.parse(await readFile9(this.path, "utf8"));
|
|
13193
|
-
|
|
13194
|
-
|
|
13848
|
+
const map = emptyMap();
|
|
13849
|
+
map[DEFAULT_AGENT] = entries(parsed.conversations);
|
|
13850
|
+
const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
|
|
13851
|
+
for (const id of AGENT_IDS) {
|
|
13852
|
+
if (id !== DEFAULT_AGENT) map[id] = entries(byAgent[id]);
|
|
13195
13853
|
}
|
|
13854
|
+
this.map = map;
|
|
13196
13855
|
} catch (error) {
|
|
13197
13856
|
if (isNodeError(error, "ENOENT")) return;
|
|
13198
|
-
this.map =
|
|
13857
|
+
this.map = emptyMap();
|
|
13199
13858
|
}
|
|
13200
13859
|
}
|
|
13201
|
-
get(conversationUuid) {
|
|
13202
|
-
return this.map[conversationUuid]?.sessionId;
|
|
13860
|
+
get(conversationUuid, agent) {
|
|
13861
|
+
return this.map[agent][conversationUuid]?.sessionId;
|
|
13203
13862
|
}
|
|
13204
|
-
async set(conversationUuid, sessionId) {
|
|
13205
|
-
this.map[conversationUuid] = { sessionId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
13863
|
+
async set(conversationUuid, agent, sessionId) {
|
|
13864
|
+
this.map[agent][conversationUuid] = { sessionId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
13206
13865
|
await this.save();
|
|
13207
13866
|
}
|
|
13208
|
-
async forget(conversationUuid) {
|
|
13209
|
-
delete this.map[conversationUuid];
|
|
13867
|
+
async forget(conversationUuid, agent) {
|
|
13868
|
+
delete this.map[agent][conversationUuid];
|
|
13210
13869
|
await this.save();
|
|
13211
13870
|
}
|
|
13212
13871
|
async save() {
|
|
13872
|
+
const byAgent = Object.fromEntries(AGENT_IDS.filter((id) => id !== DEFAULT_AGENT).map((id) => [id, this.map[id]]));
|
|
13213
13873
|
const tmp = `${this.path}.tmp`;
|
|
13214
|
-
await writeFile6(
|
|
13215
|
-
|
|
13874
|
+
await writeFile6(
|
|
13875
|
+
tmp,
|
|
13876
|
+
`${JSON.stringify({ version: 2, conversations: this.map[DEFAULT_AGENT], byAgent }, null, 2)}
|
|
13877
|
+
`,
|
|
13878
|
+
{ mode: PRIVATE_FILE_MODE }
|
|
13879
|
+
);
|
|
13216
13880
|
await rename6(tmp, this.path);
|
|
13217
13881
|
}
|
|
13218
13882
|
};
|
|
13883
|
+
function emptyMap() {
|
|
13884
|
+
return Object.fromEntries(AGENT_IDS.map((id) => [id, {}]));
|
|
13885
|
+
}
|
|
13886
|
+
function entries(value) {
|
|
13887
|
+
if (!value || typeof value !== "object") return {};
|
|
13888
|
+
const out = {};
|
|
13889
|
+
for (const [conversationUuid, entry] of Object.entries(value)) {
|
|
13890
|
+
const e = entry;
|
|
13891
|
+
if (e && typeof e.sessionId === "string") {
|
|
13892
|
+
out[conversationUuid] = { sessionId: e.sessionId, updatedAt: typeof e.updatedAt === "string" ? e.updatedAt : "" };
|
|
13893
|
+
}
|
|
13894
|
+
}
|
|
13895
|
+
return out;
|
|
13896
|
+
}
|
|
13219
13897
|
|
|
13220
13898
|
// src/adapters/cli/agentCommand.ts
|
|
13221
13899
|
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)"
|
|
13900
|
+
" 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
13901
|
];
|
|
13224
13902
|
function isAgentCommand(domain, action) {
|
|
13225
13903
|
return domain === "agent" && action === "serve";
|
|
13226
13904
|
}
|
|
13227
13905
|
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
13906
|
const paths = agentPaths();
|
|
13233
13907
|
await ensurePrivateDir(paths.dir);
|
|
13234
13908
|
await ensurePrivateDir(paths.work);
|
|
13235
13909
|
const log = openAgentLog(paths);
|
|
13236
13910
|
const host = hostname();
|
|
13237
|
-
log.write({ event: "serve_start", pid: process.pid, version: CLI_VERSION, endpoint: input.endpoint, host, claude: claude.stdout.trim() });
|
|
13238
13911
|
const rpc = new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli" });
|
|
13239
13912
|
const started = Date.now();
|
|
13240
13913
|
log.write({ event: "agent_call", callId: `tools-list-${started}`, op: "tools_list", bytes: 0 });
|
|
@@ -13253,25 +13926,49 @@ async function executeAgentServe(input) {
|
|
|
13253
13926
|
});
|
|
13254
13927
|
throw error;
|
|
13255
13928
|
}
|
|
13929
|
+
const cliScript = process.argv[1];
|
|
13930
|
+
if (!cliScript) throw new Error("Cannot find the path of this CLI to start the AiNecto bridge for the agents.");
|
|
13931
|
+
const bridge = ainectoBridge(process.execPath, cliScript, input.endpoint);
|
|
13932
|
+
const shared = { spawnImpl: spawnAgent, cwd: paths.work, env: agentEnv(process.env), log, writeTools };
|
|
13933
|
+
const mcpConfig = claudeMcpConfig(bridge);
|
|
13934
|
+
const all = [
|
|
13935
|
+
claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig, resumeSessionId }) }),
|
|
13936
|
+
codexAdapter({ ...shared, appServerArgs: codexAppServerArgs(bridge, writeTools), clientVersion: CLI_VERSION })
|
|
13937
|
+
];
|
|
13938
|
+
const checks = await checkAgents(all, log);
|
|
13939
|
+
log.write({
|
|
13940
|
+
event: "serve_start",
|
|
13941
|
+
pid: process.pid,
|
|
13942
|
+
version: CLI_VERSION,
|
|
13943
|
+
endpoint: input.endpoint,
|
|
13944
|
+
host,
|
|
13945
|
+
agents: checks.map(({ id, installed, ready, version }) => ({ id, installed, ready, ...version ? { version } : {} }))
|
|
13946
|
+
});
|
|
13947
|
+
const agents = openAgents(checks);
|
|
13948
|
+
if (agents.length === 0) {
|
|
13949
|
+
throw new Error("Neither Claude Code (`claude`) nor Codex (`codex`) is on PATH. Install one and sign in, then run `ainecto agent serve` again.");
|
|
13950
|
+
}
|
|
13951
|
+
for (const check of checks) {
|
|
13952
|
+
const name = all.find((adapter) => adapter.id === check.id)?.displayName ?? check.id;
|
|
13953
|
+
if (check.installed && !check.ready) {
|
|
13954
|
+
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.
|
|
13955
|
+
`);
|
|
13956
|
+
}
|
|
13957
|
+
}
|
|
13958
|
+
const adapters = new Map(all.filter((adapter) => agents.some((a) => a.id === adapter.id)).map((adapter) => [adapter.id, adapter]));
|
|
13256
13959
|
const sessions = new AgentSessionMap(paths.sessions);
|
|
13257
13960
|
await sessions.load();
|
|
13258
13961
|
const controller = new AbortController();
|
|
13259
13962
|
const onSignal = () => controller.abort();
|
|
13260
13963
|
process.once("SIGINT", onSignal);
|
|
13261
13964
|
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
13965
|
try {
|
|
13266
13966
|
const result = await runAgentServe({
|
|
13267
13967
|
http: createAgentHttp({ endpoint: input.endpoint, tokenProvider: input.auth, log }),
|
|
13268
13968
|
log,
|
|
13269
13969
|
sessions,
|
|
13270
|
-
|
|
13271
|
-
|
|
13272
|
-
spawnImpl: spawnClaude,
|
|
13273
|
-
cwd: paths.work,
|
|
13274
|
-
env: claudeAgentEnv(process.env),
|
|
13970
|
+
adapters,
|
|
13971
|
+
agents,
|
|
13275
13972
|
hostName: host,
|
|
13276
13973
|
cliVersion: CLI_VERSION,
|
|
13277
13974
|
print: (line) => input.io.stderr.write(`${line}
|