@ainecto/cli 0.13.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 +1453 -23
- package/dist/bin/ainecto.js.map +1 -1
- package/dist/bin/mcp.js +1 -1
- package/dist/bin/mcp.js.map +1 -1
- package/package.json +1 -1
package/dist/bin/ainecto.js
CHANGED
|
@@ -25,9 +25,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
25
25
|
mod
|
|
26
26
|
));
|
|
27
27
|
|
|
28
|
-
// node_modules/@xterm/addon-serialize/lib/addon-serialize.js
|
|
28
|
+
// ../ainecto-cli/node_modules/@xterm/addon-serialize/lib/addon-serialize.js
|
|
29
29
|
var require_addon_serialize = __commonJS({
|
|
30
|
-
"node_modules/@xterm/addon-serialize/lib/addon-serialize.js"(exports, module) {
|
|
30
|
+
"../ainecto-cli/node_modules/@xterm/addon-serialize/lib/addon-serialize.js"(exports, module) {
|
|
31
31
|
"use strict";
|
|
32
32
|
!(function(t, e) {
|
|
33
33
|
"object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.SerializeAddon = e() : t.SerializeAddon = e();
|
|
@@ -391,9 +391,9 @@ var require_addon_serialize = __commonJS({
|
|
|
391
391
|
}
|
|
392
392
|
});
|
|
393
393
|
|
|
394
|
-
// node_modules/@xterm/headless/lib-headless/xterm-headless.js
|
|
394
|
+
// ../ainecto-cli/node_modules/@xterm/headless/lib-headless/xterm-headless.js
|
|
395
395
|
var require_xterm_headless = __commonJS({
|
|
396
|
-
"node_modules/@xterm/headless/lib-headless/xterm-headless.js"(exports) {
|
|
396
|
+
"../ainecto-cli/node_modules/@xterm/headless/lib-headless/xterm-headless.js"(exports) {
|
|
397
397
|
"use strict";
|
|
398
398
|
(() => {
|
|
399
399
|
"use strict";
|
|
@@ -5585,8 +5585,8 @@ function assertLoopbackRedirectUrl(value) {
|
|
|
5585
5585
|
}
|
|
5586
5586
|
throw new Error("OAuth redirect URI must be an http localhost loopback URL.");
|
|
5587
5587
|
}
|
|
5588
|
-
function isLoopbackHostname(
|
|
5589
|
-
return
|
|
5588
|
+
function isLoopbackHostname(hostname2) {
|
|
5589
|
+
return hostname2 === "localhost" || hostname2 === "127.0.0.1" || hostname2 === "::1" || hostname2 === "[::1]";
|
|
5590
5590
|
}
|
|
5591
5591
|
function assertEnv(value) {
|
|
5592
5592
|
if (value === void 0) {
|
|
@@ -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.
|
|
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 });
|
|
@@ -12562,8 +12562,1432 @@ function restoreSummary(data) {
|
|
|
12562
12562
|
return parts.length ? parts.join("\n") : "Nothing to restore.";
|
|
12563
12563
|
}
|
|
12564
12564
|
|
|
12565
|
-
// src/adapters/cli/
|
|
12565
|
+
// src/adapters/cli/agentCommand.ts
|
|
12566
|
+
import { hostname } from "os";
|
|
12567
|
+
|
|
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
|
+
}
|
|
12574
|
+
function agentReplySchema(textMaxCharacters) {
|
|
12575
|
+
return {
|
|
12576
|
+
type: "object",
|
|
12577
|
+
additionalProperties: false,
|
|
12578
|
+
required: ["reply"],
|
|
12579
|
+
properties: { reply: { type: "string", minLength: 1, maxLength: textMaxCharacters } }
|
|
12580
|
+
};
|
|
12581
|
+
}
|
|
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 } } };
|
|
12732
|
+
}
|
|
12733
|
+
function claudeAgentArgs(input) {
|
|
12734
|
+
const args = [
|
|
12735
|
+
"-p",
|
|
12736
|
+
"--input-format",
|
|
12737
|
+
"stream-json",
|
|
12738
|
+
"--output-format",
|
|
12739
|
+
"stream-json",
|
|
12740
|
+
"--verbose",
|
|
12741
|
+
"--json-schema",
|
|
12742
|
+
JSON.stringify(input.schema),
|
|
12743
|
+
"--tools",
|
|
12744
|
+
"",
|
|
12745
|
+
// 내장 도구(Bash·Read·Write·Edit·Agent·Skill·WebFetch…) 전부 끔
|
|
12746
|
+
"--strict-mcp-config",
|
|
12747
|
+
"--mcp-config",
|
|
12748
|
+
JSON.stringify(input.mcpConfig),
|
|
12749
|
+
"--allowedTools",
|
|
12750
|
+
`mcp__${AINECTO_MCP_SERVER}`,
|
|
12751
|
+
"--permission-mode",
|
|
12752
|
+
"dontAsk",
|
|
12753
|
+
// 허용 밖은 묻지 않고 바로 거절(헤드리스에서 묻기 = 2분 대기)
|
|
12754
|
+
"--setting-sources",
|
|
12755
|
+
""
|
|
12756
|
+
// 사용자·프로젝트 설정(플러그인·스킬·훅·권한) 끔
|
|
12757
|
+
];
|
|
12758
|
+
if (input.resumeSessionId) {
|
|
12759
|
+
args.push("--resume", input.resumeSessionId);
|
|
12760
|
+
}
|
|
12761
|
+
return args;
|
|
12762
|
+
}
|
|
12763
|
+
var AINECTO_TOOL_PREFIX = `mcp__${AINECTO_MCP_SERVER}__`;
|
|
12764
|
+
|
|
12765
|
+
// src/core/agent/documents.ts
|
|
12766
|
+
var DOCUMENT_LINE = /📄[^\n]*?\/app\/docs\/([0-9a-f]{32})(?![0-9a-f])/gu;
|
|
12767
|
+
var HEX32 = /^[0-9a-f]{32}$/;
|
|
12768
|
+
function documentUuidsIn(content) {
|
|
12769
|
+
const out = [];
|
|
12770
|
+
for (const text of texts(content)) {
|
|
12771
|
+
for (const match of text.matchAll(DOCUMENT_LINE)) {
|
|
12772
|
+
const uuid = match[1];
|
|
12773
|
+
if (uuid && !out.includes(uuid)) out.push(uuid);
|
|
12774
|
+
}
|
|
12775
|
+
}
|
|
12776
|
+
return out;
|
|
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
|
+
}
|
|
12809
|
+
function texts(content) {
|
|
12810
|
+
if (typeof content === "string") return [content];
|
|
12811
|
+
if (!Array.isArray(content)) return [];
|
|
12812
|
+
return content.flatMap((part) => part && typeof part === "object" && typeof part.text === "string" ? [part.text] : []);
|
|
12813
|
+
}
|
|
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
|
+
});
|
|
12824
|
+
}
|
|
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
|
+
}
|
|
12843
|
+
}
|
|
12844
|
+
|
|
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" };
|
|
12861
|
+
}
|
|
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)
|
|
12891
|
+
});
|
|
12892
|
+
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
12893
|
+
}
|
|
12894
|
+
conversationUuid;
|
|
12895
|
+
deps;
|
|
12896
|
+
agent = "claude-code";
|
|
12897
|
+
resumed;
|
|
12898
|
+
sessionRef;
|
|
12899
|
+
child;
|
|
12900
|
+
toolNames = /* @__PURE__ */ new Map();
|
|
12901
|
+
pending;
|
|
12902
|
+
interrupts = 0;
|
|
12903
|
+
get pid() {
|
|
12904
|
+
return this.child.pid;
|
|
12905
|
+
}
|
|
12906
|
+
get alive() {
|
|
12907
|
+
return this.child.alive;
|
|
12908
|
+
}
|
|
12909
|
+
async send(text, timeoutMs) {
|
|
12910
|
+
const exit = this.child.exit;
|
|
12911
|
+
if (exit) return { kind: "exited", ...exit };
|
|
12912
|
+
const outcome = new Promise((resolve4) => {
|
|
12913
|
+
this.pending = { resolve: resolve4, facts: new WriteFactsCollector() };
|
|
12914
|
+
});
|
|
12915
|
+
this.child.writeLine({ type: "user", message: { role: "user", content: text } });
|
|
12916
|
+
try {
|
|
12917
|
+
return await withDeadline(outcome, timeoutMs, { kind: "timeout" });
|
|
12918
|
+
} finally {
|
|
12919
|
+
this.pending = void 0;
|
|
12920
|
+
}
|
|
12921
|
+
}
|
|
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" } });
|
|
12926
|
+
}
|
|
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
|
|
12938
|
+
});
|
|
12939
|
+
this.finish({ kind: "exited", ...exit });
|
|
12940
|
+
}
|
|
12941
|
+
finish(outcome) {
|
|
12942
|
+
const pending = this.pending;
|
|
12943
|
+
this.pending = void 0;
|
|
12944
|
+
pending?.resolve(outcome);
|
|
12945
|
+
}
|
|
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
|
+
}
|
|
12954
|
+
if (event.type === "system" && event.subtype === "init" && typeof event.session_id === "string") {
|
|
12955
|
+
this.sessionRef = event.session_id;
|
|
12956
|
+
return;
|
|
12957
|
+
}
|
|
12958
|
+
const content = event.message?.content;
|
|
12959
|
+
if (event.type === "assistant" && Array.isArray(content)) {
|
|
12960
|
+
for (const part of content) {
|
|
12961
|
+
if (part.type === "tool_use" && typeof part.id === "string" && typeof part.name === "string") {
|
|
12962
|
+
this.toolNames.set(part.id, part.name);
|
|
12963
|
+
}
|
|
12964
|
+
}
|
|
12965
|
+
return;
|
|
12966
|
+
}
|
|
12967
|
+
if (event.type === "user" && Array.isArray(content) && this.pending) {
|
|
12968
|
+
for (const part of content) {
|
|
12969
|
+
if (part.type !== "tool_result" || typeof part.tool_use_id !== "string") continue;
|
|
12970
|
+
const name = this.toolNames.get(part.tool_use_id);
|
|
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);
|
|
12973
|
+
}
|
|
12974
|
+
return;
|
|
12975
|
+
}
|
|
12976
|
+
if (event.type === "result") {
|
|
12977
|
+
if (typeof event.session_id === "string") this.sessionRef = event.session_id;
|
|
12978
|
+
this.finish({
|
|
12979
|
+
kind: "result",
|
|
12980
|
+
facts: this.pending?.facts.snapshot() ?? { documents: [], createdDocuments: [], cards: [] },
|
|
12981
|
+
result: {
|
|
12982
|
+
subtype: typeof event.subtype === "string" ? event.subtype : void 0,
|
|
12983
|
+
isError: event.is_error === true,
|
|
12984
|
+
structuredOutput: event.structured_output,
|
|
12985
|
+
resultText: typeof event.result === "string" ? event.result : void 0,
|
|
12986
|
+
numTurns: typeof event.num_turns === "number" ? event.num_turns : void 0,
|
|
12987
|
+
costUsd: typeof event.total_cost_usd === "number" ? event.total_cost_usd : void 0
|
|
12988
|
+
}
|
|
12989
|
+
});
|
|
12990
|
+
}
|
|
12991
|
+
}
|
|
12992
|
+
};
|
|
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
|
+
|
|
13369
|
+
// src/core/agent/http.ts
|
|
13370
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
13371
|
+
var AgentCallError = class extends Error {
|
|
13372
|
+
constructor(message, op, status, code) {
|
|
13373
|
+
super(message);
|
|
13374
|
+
this.op = op;
|
|
13375
|
+
this.status = status;
|
|
13376
|
+
this.code = code;
|
|
13377
|
+
this.name = "AgentCallError";
|
|
13378
|
+
}
|
|
13379
|
+
op;
|
|
13380
|
+
status;
|
|
13381
|
+
code;
|
|
13382
|
+
/** 다시 해 볼 만한가 — 네트워크·기한·5xx·429. */
|
|
13383
|
+
get retryable() {
|
|
13384
|
+
return this.status === void 0 || this.status >= 500 || this.status === 429;
|
|
13385
|
+
}
|
|
13386
|
+
};
|
|
13387
|
+
function createAgentHttp(input) {
|
|
13388
|
+
const fetchImpl = input.fetchImpl ?? fetch;
|
|
13389
|
+
const base = `${input.endpoint.replace(/\/+$/, "")}/agent/pc/`;
|
|
13390
|
+
let linkToken;
|
|
13391
|
+
async function send(op, payload, token, options) {
|
|
13392
|
+
const controller = new AbortController();
|
|
13393
|
+
const timer = setTimeout(
|
|
13394
|
+
() => controller.abort(new DOMException("timed out", "TimeoutError")),
|
|
13395
|
+
(options.holdMs ?? 0) + AGENT_CALL_TIMEOUT_MS
|
|
13396
|
+
);
|
|
13397
|
+
const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
|
|
13398
|
+
options.signal?.addEventListener("abort", onStop, { once: true });
|
|
13399
|
+
const headers = { "Content-Type": "application/json", Accept: "application/json" };
|
|
13400
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
13401
|
+
if (linkToken && op !== "open") headers["X-Link-Token"] = linkToken;
|
|
13402
|
+
try {
|
|
13403
|
+
const response = await fetchImpl(base + op, { method: "POST", headers, body: payload, signal: controller.signal });
|
|
13404
|
+
await response.clone().arrayBuffer();
|
|
13405
|
+
return response;
|
|
13406
|
+
} catch (error) {
|
|
13407
|
+
throw controller.signal.aborted && controller.signal.reason instanceof Error ? controller.signal.reason : error;
|
|
13408
|
+
} finally {
|
|
13409
|
+
clearTimeout(timer);
|
|
13410
|
+
options.signal?.removeEventListener("abort", onStop);
|
|
13411
|
+
}
|
|
13412
|
+
}
|
|
13413
|
+
return {
|
|
13414
|
+
useLinkToken(token) {
|
|
13415
|
+
linkToken = token;
|
|
13416
|
+
},
|
|
13417
|
+
async call(op, body, options = {}) {
|
|
13418
|
+
const callId = randomUUID2();
|
|
13419
|
+
const payload = JSON.stringify(body);
|
|
13420
|
+
const started = Date.now();
|
|
13421
|
+
input.log.write({ event: "agent_call", callId, op, turnUuid: options.turnUuid, bytes: Buffer.byteLength(payload, "utf8") });
|
|
13422
|
+
let outcome = {
|
|
13423
|
+
ok: false,
|
|
13424
|
+
error: "no response"
|
|
13425
|
+
};
|
|
13426
|
+
try {
|
|
13427
|
+
let response = await send(op, payload, await input.tokenProvider.getAccessToken(), options);
|
|
13428
|
+
if (response.status === 401) {
|
|
13429
|
+
response = await send(op, payload, await input.tokenProvider.refreshAfterUnauthorized(), options);
|
|
13430
|
+
}
|
|
13431
|
+
const text = await response.text();
|
|
13432
|
+
const parsed = parseJson2(text);
|
|
13433
|
+
if (!response.ok) {
|
|
13434
|
+
const code = typeof parsed?.code === "string" ? parsed.code : void 0;
|
|
13435
|
+
outcome = { ok: false, status: response.status, code };
|
|
13436
|
+
throw new AgentCallError(
|
|
13437
|
+
typeof parsed?.detail === "string" ? parsed.detail : `HTTP ${response.status}`,
|
|
13438
|
+
op,
|
|
13439
|
+
response.status,
|
|
13440
|
+
code
|
|
13441
|
+
);
|
|
13442
|
+
}
|
|
13443
|
+
const offers = Array.isArray(parsed?.offers) ? parsed.offers.length : void 0;
|
|
13444
|
+
outcome = { ok: true, status: response.status, offers };
|
|
13445
|
+
return parsed ?? {};
|
|
13446
|
+
} catch (error) {
|
|
13447
|
+
if (error instanceof AgentCallError) throw error;
|
|
13448
|
+
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
13449
|
+
outcome = { ok: false, error: timedOut ? error.name : error instanceof Error ? error.message : String(error) };
|
|
13450
|
+
throw new AgentCallError(timedOut ? `${op} timed out` : `${op} failed: ${outcome.error}`, op);
|
|
13451
|
+
} finally {
|
|
13452
|
+
input.log.write({ event: "agent_call_response", callId, op, ...outcome, ms: Date.now() - started });
|
|
13453
|
+
}
|
|
13454
|
+
}
|
|
13455
|
+
};
|
|
13456
|
+
}
|
|
13457
|
+
function parseJson2(text) {
|
|
13458
|
+
if (!text) return void 0;
|
|
13459
|
+
try {
|
|
13460
|
+
const value = JSON.parse(text);
|
|
13461
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
13462
|
+
} catch {
|
|
13463
|
+
return void 0;
|
|
13464
|
+
}
|
|
13465
|
+
}
|
|
13466
|
+
|
|
13467
|
+
// src/core/agent/log.ts
|
|
13468
|
+
function openAgentLog(paths) {
|
|
13469
|
+
const log = new DaemonLog(paths.log, paths.previousLog);
|
|
13470
|
+
log.enableRotation();
|
|
13471
|
+
return log;
|
|
13472
|
+
}
|
|
13473
|
+
|
|
13474
|
+
// src/core/agent/paths.ts
|
|
12566
13475
|
import { homedir as homedir3 } from "os";
|
|
13476
|
+
import { join as join7 } from "path";
|
|
13477
|
+
function agentPaths(home = homedir3()) {
|
|
13478
|
+
const dir = join7(home, ".ainecto", "agent");
|
|
13479
|
+
return {
|
|
13480
|
+
dir,
|
|
13481
|
+
work: join7(dir, "work"),
|
|
13482
|
+
sessions: join7(dir, "sessions.json"),
|
|
13483
|
+
log: join7(dir, "agent.log"),
|
|
13484
|
+
previousLog: join7(dir, "agent.log.1")
|
|
13485
|
+
};
|
|
13486
|
+
}
|
|
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
|
+
|
|
13537
|
+
// src/core/agent/prompt.ts
|
|
13538
|
+
function agentPromptText(text, context) {
|
|
13539
|
+
const parts = [];
|
|
13540
|
+
const p = context?.project;
|
|
13541
|
+
if (p && typeof p.uuid === "string") {
|
|
13542
|
+
parts.push(`project \xAB${str(p.name)}\xBB (projectUuid ${p.uuid}${typeof p.workspaceUuid === "string" ? `, workspace \xAB${str(p.workspaceName)}\xBB ${p.workspaceUuid}` : ""})`);
|
|
13543
|
+
}
|
|
13544
|
+
const d = context?.openDocument;
|
|
13545
|
+
if (d && typeof d.uuid === "string") {
|
|
13546
|
+
parts.push(`open document \xAB${str(d.title)}\xBB (documentUuid ${d.uuid}${typeof d.type === "string" ? `, ${d.type}` : ""})`);
|
|
13547
|
+
}
|
|
13548
|
+
if (parts.length === 0) return text;
|
|
13549
|
+
return `[AiNecto context \u2014 "this project" / "this document" mean these] ${parts.join(" \xB7 ")}
|
|
13550
|
+
|
|
13551
|
+
${text}`;
|
|
13552
|
+
}
|
|
13553
|
+
function str(value) {
|
|
13554
|
+
return typeof value === "string" ? value : "";
|
|
13555
|
+
}
|
|
13556
|
+
|
|
13557
|
+
// src/core/agent/reply.ts
|
|
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 });
|
|
13569
|
+
switch (outcome.kind) {
|
|
13570
|
+
case "timeout":
|
|
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.");
|
|
13572
|
+
case "exited":
|
|
13573
|
+
return failed("AGENT_EXITED", `${agentName} \uAC00 \uB05D\uB0AC\uC5B4\uC694(code ${outcome.code ?? "-"}${outcome.signal ? `, ${outcome.signal}` : ""}).` + (outcome.stderrTail ? `
|
|
13574
|
+
${outcome.stderrTail}` : ""));
|
|
13575
|
+
case "result": {
|
|
13576
|
+
const { result } = outcome;
|
|
13577
|
+
if (result.isError) {
|
|
13578
|
+
return failed("AGENT_ERROR", `${agentName} \uAC00 \uC2E4\uD328\uD588\uC5B4\uC694(${result.subtype ?? "error"}).` + (result.resultText ? `
|
|
13579
|
+
${result.resultText}` : ""));
|
|
13580
|
+
}
|
|
13581
|
+
const reply = result.structuredOutput?.reply;
|
|
13582
|
+
const keys = result.structuredOutput && typeof result.structuredOutput === "object" ? Object.keys(result.structuredOutput) : [];
|
|
13583
|
+
if (typeof reply === "string" && reply.trim().length > 0 && keys.length === 1 && codePoints(reply) <= limits.textMaxCharacters) {
|
|
13584
|
+
return { status: "DONE", reply, ...attached };
|
|
13585
|
+
}
|
|
13586
|
+
const raw = result.structuredOutput !== void 0 ? JSON.stringify(result.structuredOutput) : result.resultText ?? "";
|
|
13587
|
+
return failed("SCHEMA_VIOLATION", `\uB2F5 \uD615\uC2DD\uC774 \uC5B4\uAE0B\uB0AC\uC5B4\uC694.
|
|
13588
|
+
${raw}`);
|
|
13589
|
+
}
|
|
13590
|
+
}
|
|
13591
|
+
}
|
|
13592
|
+
function codePoints(text) {
|
|
13593
|
+
return Array.from(text).length;
|
|
13594
|
+
}
|
|
13595
|
+
function clip(text, max) {
|
|
13596
|
+
const chars = Array.from(text.trim() || "-");
|
|
13597
|
+
return chars.length <= max ? chars.join("") : `${chars.slice(0, max - 1).join("")}\u2026`;
|
|
13598
|
+
}
|
|
13599
|
+
|
|
13600
|
+
// src/core/agent/serve.ts
|
|
13601
|
+
async function runAgentServe(deps) {
|
|
13602
|
+
const opened = await deps.http.call("open", { hostName: deps.hostName, cliVersion: deps.cliVersion, agents: deps.agents });
|
|
13603
|
+
const linkId = String(opened.linkId);
|
|
13604
|
+
deps.http.useLinkToken(String(opened.linkToken));
|
|
13605
|
+
const limits = serverLimits(opened.limits);
|
|
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.`);
|
|
13608
|
+
const stopController = new AbortController();
|
|
13609
|
+
let stopReason;
|
|
13610
|
+
let exitCode2 = 0;
|
|
13611
|
+
let wakeWorker;
|
|
13612
|
+
const live = /* @__PURE__ */ new Map();
|
|
13613
|
+
const received = /* @__PURE__ */ new Set();
|
|
13614
|
+
const queue = [];
|
|
13615
|
+
const stop = (reason, code, message) => {
|
|
13616
|
+
if (stopReason) return;
|
|
13617
|
+
stopReason = reason;
|
|
13618
|
+
exitCode2 = code;
|
|
13619
|
+
if (message) deps.print(message);
|
|
13620
|
+
stopController.abort();
|
|
13621
|
+
wakeWorker?.();
|
|
13622
|
+
for (const session of live.values()) void session.close();
|
|
13623
|
+
};
|
|
13624
|
+
const onUserStop = () => stop("signal", 0, "Stopping\u2026");
|
|
13625
|
+
if (deps.signal.aborted) onUserStop();
|
|
13626
|
+
deps.signal.addEventListener("abort", onUserStop, { once: true });
|
|
13627
|
+
const stopOnFatal = (error) => {
|
|
13628
|
+
if (error.code === "LINK_NOT_FOUND") {
|
|
13629
|
+
stop("link_not_found", 1, "This connection ended (the server restarted, or the link was closed). Run `ainecto agent serve` again.");
|
|
13630
|
+
} else if (error.status === 401 || error.status === 403) {
|
|
13631
|
+
stop("auth", 1, `AiNecto refused the CLI sign-in (${error.code ?? error.status}). Run \`ainecto auth login\` and start again.`);
|
|
13632
|
+
}
|
|
13633
|
+
};
|
|
13634
|
+
const pollLoop = (async () => {
|
|
13635
|
+
let delay;
|
|
13636
|
+
while (!stopReason) {
|
|
13637
|
+
try {
|
|
13638
|
+
const res = await deps.http.call("poll", { linkId }, { holdMs: limits.pollHoldSeconds * 1e3, signal: stopController.signal });
|
|
13639
|
+
delay = void 0;
|
|
13640
|
+
if (res.state === "CLOSED") {
|
|
13641
|
+
stop("replaced", 1, "Another PC connected as your agent, so this one stopped.");
|
|
13642
|
+
return;
|
|
13643
|
+
}
|
|
13644
|
+
for (const offer of offersIn(res)) {
|
|
13645
|
+
const duplicate = received.has(offer.turnUuid);
|
|
13646
|
+
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, agent: offer.agent, duplicate });
|
|
13647
|
+
if (duplicate) continue;
|
|
13648
|
+
received.add(offer.turnUuid);
|
|
13649
|
+
queue.push(offer);
|
|
13650
|
+
wakeWorker?.();
|
|
13651
|
+
}
|
|
13652
|
+
} catch (error) {
|
|
13653
|
+
if (stopReason) return;
|
|
13654
|
+
if (error instanceof AgentCallError && !error.retryable) {
|
|
13655
|
+
stopOnFatal(error);
|
|
13656
|
+
if (stopReason) return;
|
|
13657
|
+
}
|
|
13658
|
+
delay = nextRetryDelay(delay);
|
|
13659
|
+
await sleep(delay, stopController.signal);
|
|
13660
|
+
}
|
|
13661
|
+
}
|
|
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
|
+
};
|
|
13678
|
+
const runTurn = async (offer) => {
|
|
13679
|
+
const started = Date.now();
|
|
13680
|
+
const adapter = isAgentId(offer.agent) ? deps.adapters.get(offer.agent) : void 0;
|
|
13681
|
+
let session;
|
|
13682
|
+
let outcome;
|
|
13683
|
+
let reply;
|
|
13684
|
+
let failure2;
|
|
13685
|
+
try {
|
|
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);
|
|
13709
|
+
if (outcome.kind === "timeout") {
|
|
13710
|
+
await session.interrupt();
|
|
13711
|
+
await session.close();
|
|
13712
|
+
}
|
|
13713
|
+
if (outcome.kind !== "result") {
|
|
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);
|
|
13718
|
+
}
|
|
13719
|
+
reply = replyForOutcome(outcome, limits, adapter.displayName);
|
|
13720
|
+
return reply;
|
|
13721
|
+
} catch (error) {
|
|
13722
|
+
failure2 = error instanceof Error ? error.message : String(error);
|
|
13723
|
+
reply = { status: "FAILED", errorCode: "AGENT_INTERNAL", reply: clip(`The PC agent failed: ${failure2}`, limits.textMaxCharacters), documentUuids: [] };
|
|
13724
|
+
return reply;
|
|
13725
|
+
} finally {
|
|
13726
|
+
const result = outcome?.kind === "result" ? outcome.result : void 0;
|
|
13727
|
+
deps.log.write({
|
|
13728
|
+
event: "agent_response",
|
|
13729
|
+
turnUuid: offer.turnUuid,
|
|
13730
|
+
agent: offer.agent,
|
|
13731
|
+
ms: Date.now() - started,
|
|
13732
|
+
outcome: outcome?.kind ?? `error: ${failure2 ?? "unknown"}`,
|
|
13733
|
+
status: reply?.status ?? "FAILED",
|
|
13734
|
+
errorCode: reply?.errorCode,
|
|
13735
|
+
subtype: result?.subtype,
|
|
13736
|
+
sessionId: session?.sessionRef,
|
|
13737
|
+
documents: reply?.documentUuids.length ?? 0,
|
|
13738
|
+
createdDocuments: reply?.createdDocumentUuids?.length ?? 0,
|
|
13739
|
+
cards: reply?.cardUuids?.length ?? 0,
|
|
13740
|
+
numTurns: result?.numTurns,
|
|
13741
|
+
costUsd: result?.costUsd
|
|
13742
|
+
});
|
|
13743
|
+
}
|
|
13744
|
+
};
|
|
13745
|
+
const sendReply = async (offer, reply) => {
|
|
13746
|
+
let delay;
|
|
13747
|
+
for (; ; ) {
|
|
13748
|
+
try {
|
|
13749
|
+
await deps.http.call("reply", {
|
|
13750
|
+
linkId,
|
|
13751
|
+
turnUuid: offer.turnUuid,
|
|
13752
|
+
conversationUuid: offer.conversationUuid,
|
|
13753
|
+
status: reply.status,
|
|
13754
|
+
reply: reply.reply,
|
|
13755
|
+
documentUuids: reply.documentUuids,
|
|
13756
|
+
...reply.createdDocumentUuids ? { createdDocumentUuids: reply.createdDocumentUuids } : {},
|
|
13757
|
+
...reply.cardUuids ? { cardUuids: reply.cardUuids } : {},
|
|
13758
|
+
...reply.errorCode ? { errorCode: reply.errorCode } : {}
|
|
13759
|
+
}, { turnUuid: offer.turnUuid, signal: stopController.signal });
|
|
13760
|
+
return;
|
|
13761
|
+
} catch (error) {
|
|
13762
|
+
if (stopReason) return;
|
|
13763
|
+
if (error instanceof AgentCallError && !error.retryable) {
|
|
13764
|
+
stopOnFatal(error);
|
|
13765
|
+
return;
|
|
13766
|
+
}
|
|
13767
|
+
delay = nextRetryDelay(delay);
|
|
13768
|
+
await sleep(delay, stopController.signal);
|
|
13769
|
+
}
|
|
13770
|
+
}
|
|
13771
|
+
};
|
|
13772
|
+
const worker = (async () => {
|
|
13773
|
+
while (!stopReason) {
|
|
13774
|
+
const offer = queue.shift();
|
|
13775
|
+
if (!offer) {
|
|
13776
|
+
await new Promise((resolve4) => {
|
|
13777
|
+
wakeWorker = resolve4;
|
|
13778
|
+
});
|
|
13779
|
+
wakeWorker = void 0;
|
|
13780
|
+
continue;
|
|
13781
|
+
}
|
|
13782
|
+
const reply = await runTurn(offer);
|
|
13783
|
+
if (!stopReason) await sendReply(offer, reply);
|
|
13784
|
+
}
|
|
13785
|
+
})();
|
|
13786
|
+
await Promise.allSettled([pollLoop, worker]);
|
|
13787
|
+
deps.signal.removeEventListener("abort", onUserStop);
|
|
13788
|
+
await Promise.all([...live.values()].map((session) => session.close()));
|
|
13789
|
+
if (stopReason === "signal") {
|
|
13790
|
+
try {
|
|
13791
|
+
await deps.http.call("close", { linkId });
|
|
13792
|
+
} catch {
|
|
13793
|
+
}
|
|
13794
|
+
}
|
|
13795
|
+
return { exitCode: exitCode2, reason: stopReason ?? "unknown" };
|
|
13796
|
+
}
|
|
13797
|
+
function serverLimits(value) {
|
|
13798
|
+
const v = value ?? {};
|
|
13799
|
+
const num = (key) => {
|
|
13800
|
+
const n = v[key];
|
|
13801
|
+
if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) {
|
|
13802
|
+
throw new Error(`The server did not send limits.${key}; update the CLI or the server.`);
|
|
13803
|
+
}
|
|
13804
|
+
return n;
|
|
13805
|
+
};
|
|
13806
|
+
return { pollHoldSeconds: num("pollHoldSeconds"), textMaxCharacters: num("textMaxCharacters"), documentsMax: num("documentsMax") };
|
|
13807
|
+
}
|
|
13808
|
+
function offersIn(res) {
|
|
13809
|
+
if (!Array.isArray(res.offers)) return [];
|
|
13810
|
+
return res.offers.flatMap((o) => {
|
|
13811
|
+
const offer = o;
|
|
13812
|
+
return typeof offer.turnUuid === "string" && typeof offer.conversationUuid === "string" && typeof offer.text === "string" ? [{
|
|
13813
|
+
turnUuid: offer.turnUuid,
|
|
13814
|
+
conversationUuid: offer.conversationUuid,
|
|
13815
|
+
text: offer.text,
|
|
13816
|
+
agent: offer.agent === void 0 || offer.agent === null ? DEFAULT_AGENT : String(offer.agent),
|
|
13817
|
+
context: offer.context && typeof offer.context === "object" ? offer.context : void 0
|
|
13818
|
+
}] : [];
|
|
13819
|
+
});
|
|
13820
|
+
}
|
|
13821
|
+
function sleep(ms, signal) {
|
|
13822
|
+
return new Promise((resolve4) => {
|
|
13823
|
+
if (signal.aborted) {
|
|
13824
|
+
resolve4();
|
|
13825
|
+
return;
|
|
13826
|
+
}
|
|
13827
|
+
const timer = setTimeout(done, ms);
|
|
13828
|
+
signal.addEventListener("abort", done, { once: true });
|
|
13829
|
+
function done() {
|
|
13830
|
+
clearTimeout(timer);
|
|
13831
|
+
signal.removeEventListener("abort", done);
|
|
13832
|
+
resolve4();
|
|
13833
|
+
}
|
|
13834
|
+
});
|
|
13835
|
+
}
|
|
13836
|
+
|
|
13837
|
+
// src/core/agent/sessions.ts
|
|
13838
|
+
import { readFile as readFile9, rename as rename6, writeFile as writeFile6 } from "fs/promises";
|
|
13839
|
+
var AgentSessionMap = class {
|
|
13840
|
+
constructor(path) {
|
|
13841
|
+
this.path = path;
|
|
13842
|
+
}
|
|
13843
|
+
path;
|
|
13844
|
+
map = emptyMap();
|
|
13845
|
+
async load() {
|
|
13846
|
+
try {
|
|
13847
|
+
const parsed = JSON.parse(await readFile9(this.path, "utf8"));
|
|
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]);
|
|
13853
|
+
}
|
|
13854
|
+
this.map = map;
|
|
13855
|
+
} catch (error) {
|
|
13856
|
+
if (isNodeError(error, "ENOENT")) return;
|
|
13857
|
+
this.map = emptyMap();
|
|
13858
|
+
}
|
|
13859
|
+
}
|
|
13860
|
+
get(conversationUuid, agent) {
|
|
13861
|
+
return this.map[agent][conversationUuid]?.sessionId;
|
|
13862
|
+
}
|
|
13863
|
+
async set(conversationUuid, agent, sessionId) {
|
|
13864
|
+
this.map[agent][conversationUuid] = { sessionId, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
13865
|
+
await this.save();
|
|
13866
|
+
}
|
|
13867
|
+
async forget(conversationUuid, agent) {
|
|
13868
|
+
delete this.map[agent][conversationUuid];
|
|
13869
|
+
await this.save();
|
|
13870
|
+
}
|
|
13871
|
+
async save() {
|
|
13872
|
+
const byAgent = Object.fromEntries(AGENT_IDS.filter((id) => id !== DEFAULT_AGENT).map((id) => [id, this.map[id]]));
|
|
13873
|
+
const tmp = `${this.path}.tmp`;
|
|
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
|
+
);
|
|
13880
|
+
await rename6(tmp, this.path);
|
|
13881
|
+
}
|
|
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
|
+
}
|
|
13897
|
+
|
|
13898
|
+
// src/adapters/cli/agentCommand.ts
|
|
13899
|
+
var AGENT_HELP_LINES = [
|
|
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)"
|
|
13901
|
+
];
|
|
13902
|
+
function isAgentCommand(domain, action) {
|
|
13903
|
+
return domain === "agent" && action === "serve";
|
|
13904
|
+
}
|
|
13905
|
+
async function executeAgentServe(input) {
|
|
13906
|
+
const paths = agentPaths();
|
|
13907
|
+
await ensurePrivateDir(paths.dir);
|
|
13908
|
+
await ensurePrivateDir(paths.work);
|
|
13909
|
+
const log = openAgentLog(paths);
|
|
13910
|
+
const host = hostname();
|
|
13911
|
+
const rpc = new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli" });
|
|
13912
|
+
const started = Date.now();
|
|
13913
|
+
log.write({ event: "agent_call", callId: `tools-list-${started}`, op: "tools_list", bytes: 0 });
|
|
13914
|
+
let writeTools;
|
|
13915
|
+
try {
|
|
13916
|
+
writeTools = writeToolNames(await rpc.toolsList());
|
|
13917
|
+
log.write({ event: "agent_call_response", callId: `tools-list-${started}`, op: "tools_list", ok: true, ms: Date.now() - started });
|
|
13918
|
+
} catch (error) {
|
|
13919
|
+
log.write({
|
|
13920
|
+
event: "agent_call_response",
|
|
13921
|
+
callId: `tools-list-${started}`,
|
|
13922
|
+
op: "tools_list",
|
|
13923
|
+
ok: false,
|
|
13924
|
+
error: error instanceof Error ? error.message : String(error),
|
|
13925
|
+
ms: Date.now() - started
|
|
13926
|
+
});
|
|
13927
|
+
throw error;
|
|
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]));
|
|
13959
|
+
const sessions = new AgentSessionMap(paths.sessions);
|
|
13960
|
+
await sessions.load();
|
|
13961
|
+
const controller = new AbortController();
|
|
13962
|
+
const onSignal = () => controller.abort();
|
|
13963
|
+
process.once("SIGINT", onSignal);
|
|
13964
|
+
process.once("SIGTERM", onSignal);
|
|
13965
|
+
try {
|
|
13966
|
+
const result = await runAgentServe({
|
|
13967
|
+
http: createAgentHttp({ endpoint: input.endpoint, tokenProvider: input.auth, log }),
|
|
13968
|
+
log,
|
|
13969
|
+
sessions,
|
|
13970
|
+
adapters,
|
|
13971
|
+
agents,
|
|
13972
|
+
hostName: host,
|
|
13973
|
+
cliVersion: CLI_VERSION,
|
|
13974
|
+
print: (line) => input.io.stderr.write(`${line}
|
|
13975
|
+
`),
|
|
13976
|
+
signal: controller.signal
|
|
13977
|
+
});
|
|
13978
|
+
log.write({ event: "serve_stop", pid: process.pid, reason: result.reason });
|
|
13979
|
+
return result.exitCode;
|
|
13980
|
+
} catch (error) {
|
|
13981
|
+
log.write({ event: "serve_stop", pid: process.pid, reason: `error: ${error instanceof Error ? error.message : String(error)}` });
|
|
13982
|
+
throw error;
|
|
13983
|
+
} finally {
|
|
13984
|
+
process.off("SIGINT", onSignal);
|
|
13985
|
+
process.off("SIGTERM", onSignal);
|
|
13986
|
+
}
|
|
13987
|
+
}
|
|
13988
|
+
|
|
13989
|
+
// src/adapters/cli/ainectoCli.ts
|
|
13990
|
+
import { homedir as homedir4 } from "os";
|
|
12567
13991
|
async function runAinectoCli(argv, io) {
|
|
12568
13992
|
let parsed = { json: argv.includes("--json"), help: false, version: false, positionals: [] };
|
|
12569
13993
|
try {
|
|
@@ -12650,8 +14074,8 @@ async function runAinectoCli(argv, io) {
|
|
|
12650
14074
|
auth,
|
|
12651
14075
|
client: client2,
|
|
12652
14076
|
// ★외부 CLI 는 홈 폴더에서 돈다 — 지금 저장소의 local·project 범위 항목이 사용자 범위 판정에 끼지 않게.
|
|
12653
|
-
runner: systemCommandRunner({ cwd:
|
|
12654
|
-
home:
|
|
14077
|
+
runner: systemCommandRunner({ cwd: homedir4() }),
|
|
14078
|
+
home: homedir4(),
|
|
12655
14079
|
json: parsed.json,
|
|
12656
14080
|
io
|
|
12657
14081
|
});
|
|
@@ -12668,9 +14092,9 @@ async function runAinectoCli(argv, io) {
|
|
|
12668
14092
|
tokenStore,
|
|
12669
14093
|
auth,
|
|
12670
14094
|
client: client2,
|
|
12671
|
-
runner: systemCommandRunner({ cwd:
|
|
14095
|
+
runner: systemCommandRunner({ cwd: homedir4() }),
|
|
12672
14096
|
hereRunner: systemCommandRunner({ cwd: process.cwd() }),
|
|
12673
|
-
home:
|
|
14097
|
+
home: homedir4(),
|
|
12674
14098
|
cwd: process.cwd(),
|
|
12675
14099
|
envVars: process.env
|
|
12676
14100
|
},
|
|
@@ -12678,6 +14102,9 @@ async function runAinectoCli(argv, io) {
|
|
|
12678
14102
|
io
|
|
12679
14103
|
});
|
|
12680
14104
|
}
|
|
14105
|
+
if (isAgentCommand(domain, action)) {
|
|
14106
|
+
return await executeAgentServe({ endpoint: resolved.endpoint, auth: connect2().auth, io });
|
|
14107
|
+
}
|
|
12681
14108
|
if (domain === "auth") {
|
|
12682
14109
|
return await handleAuth(action, connect2().auth, resolved.endpoint, parsed.json, io);
|
|
12683
14110
|
}
|
|
@@ -12882,6 +14309,9 @@ function helpText() {
|
|
|
12882
14309
|
" ainecto init --agent NAME name the agent working in this folder: writes .ainecto/agent.local (do not commit it) and puts the name in .mcp.json, .cursor/mcp.json and .codex/config.toml",
|
|
12883
14310
|
" ainecto init --undo",
|
|
12884
14311
|
"",
|
|
14312
|
+
"Your PC agent (requests from AiNecto Chat, answered by Claude Code on this machine):",
|
|
14313
|
+
...AGENT_HELP_LINES,
|
|
14314
|
+
"",
|
|
12885
14315
|
"Terminal sessions on this machine (no tmux or cmux needed; macOS and Linux):",
|
|
12886
14316
|
...TERM_HELP_LINES,
|
|
12887
14317
|
""
|