@ainecto/cli 0.14.0-next.5 → 0.14.0-next.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/bin/ainecto.js +1251 -267
- package/dist/bin/ainecto.js.map +1 -1
- package/dist/bin/mcp.js +10 -1
- package/dist/bin/mcp.js.map +1 -1
- package/package.json +3 -2
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
|
-
//
|
|
28
|
+
// node_modules/@xterm/addon-serialize/lib/addon-serialize.js
|
|
29
29
|
var require_addon_serialize = __commonJS({
|
|
30
|
-
"
|
|
30
|
+
"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
|
-
//
|
|
394
|
+
// node_modules/@xterm/headless/lib-headless/xterm-headless.js
|
|
395
395
|
var require_xterm_headless = __commonJS({
|
|
396
|
-
"
|
|
396
|
+
"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(hostname3) {
|
|
5589
|
+
return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "::1" || hostname3 === "[::1]";
|
|
5590
5590
|
}
|
|
5591
5591
|
function assertEnv(value) {
|
|
5592
5592
|
if (value === void 0) {
|
|
@@ -5678,7 +5678,16 @@ 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.7" : UNBUNDLED_VERSION;
|
|
5682
|
+
var CLI_BUILD = true ? "f1e73b8" : void 0;
|
|
5683
|
+
function cliVersionLabel(version, build, release) {
|
|
5684
|
+
return release || build === void 0 ? version : `${version}-dev+${build}`;
|
|
5685
|
+
}
|
|
5686
|
+
var CLI_VERSION_LABEL = cliVersionLabel(
|
|
5687
|
+
CLI_VERSION,
|
|
5688
|
+
CLI_BUILD,
|
|
5689
|
+
true
|
|
5690
|
+
);
|
|
5682
5691
|
var PACKAGE_NAME = "@ainecto/mcp";
|
|
5683
5692
|
var CLI_USER_AGENT = `${PACKAGE_NAME} ${CLI_VERSION}`;
|
|
5684
5693
|
function bridgePackageSpec(version = CLI_VERSION) {
|
|
@@ -8613,12 +8622,12 @@ function readRecord(content) {
|
|
|
8613
8622
|
}
|
|
8614
8623
|
};
|
|
8615
8624
|
}
|
|
8616
|
-
function serializeRecord(
|
|
8625
|
+
function serializeRecord(record2) {
|
|
8617
8626
|
return `${JSON.stringify({
|
|
8618
8627
|
kind: RECORD_KIND,
|
|
8619
8628
|
version: RECORD_VERSION,
|
|
8620
|
-
files:
|
|
8621
|
-
createdDirectories:
|
|
8629
|
+
files: record2.files,
|
|
8630
|
+
createdDirectories: record2.createdDirectories
|
|
8622
8631
|
}, null, 2)}
|
|
8623
8632
|
`;
|
|
8624
8633
|
}
|
|
@@ -8875,20 +8884,20 @@ function planInit(input) {
|
|
|
8875
8884
|
const carriedRecord = previous.state === "valid" ? previous.record : emptyRecord();
|
|
8876
8885
|
const writes = [];
|
|
8877
8886
|
const notes = [];
|
|
8878
|
-
const
|
|
8887
|
+
const record2 = {
|
|
8879
8888
|
version: carriedRecord.version,
|
|
8880
8889
|
files: { ...carriedRecord.files },
|
|
8881
8890
|
createdDirectories: [...carriedRecord.createdDirectories]
|
|
8882
8891
|
};
|
|
8883
8892
|
const priorOf = (path, current) => {
|
|
8884
|
-
const prior =
|
|
8893
|
+
const prior = record2.files[path];
|
|
8885
8894
|
if (prior === void 0) {
|
|
8886
8895
|
return void 0;
|
|
8887
8896
|
}
|
|
8888
8897
|
if (sameOwned(prior.written, current) || sameOwned(prior.original, current)) {
|
|
8889
8898
|
return prior;
|
|
8890
8899
|
}
|
|
8891
|
-
delete
|
|
8900
|
+
delete record2.files[path];
|
|
8892
8901
|
notes.push(`${path}: it changed outside ainecto, so the older backup was dropped and this is the new baseline.`);
|
|
8893
8902
|
return void 0;
|
|
8894
8903
|
};
|
|
@@ -8897,7 +8906,7 @@ function planInit(input) {
|
|
|
8897
8906
|
if (prior === void 0 && original.at !== "absent") {
|
|
8898
8907
|
notes.push(`${path} already existed; its original was saved and --undo will restore it.`);
|
|
8899
8908
|
}
|
|
8900
|
-
|
|
8909
|
+
record2.files[path] = {
|
|
8901
8910
|
scope: "whole",
|
|
8902
8911
|
createdByUs: prior?.createdByUs ?? existing === void 0,
|
|
8903
8912
|
original,
|
|
@@ -8940,7 +8949,7 @@ function planInit(input) {
|
|
|
8940
8949
|
if (prior === void 0 && original.at !== "absent") {
|
|
8941
8950
|
notes.push(`${target.path}: your existing "${SERVER_NAME}" entry was saved and will be restored by --undo`);
|
|
8942
8951
|
}
|
|
8943
|
-
|
|
8952
|
+
record2.files[target.path] = {
|
|
8944
8953
|
scope: "entry",
|
|
8945
8954
|
createdByUs: prior?.createdByUs ?? existing === void 0,
|
|
8946
8955
|
original,
|
|
@@ -8985,7 +8994,7 @@ ${codexContent}`);
|
|
|
8985
8994
|
continue;
|
|
8986
8995
|
}
|
|
8987
8996
|
const blockNow = existing === void 0 ? void 0 : existingMarkerBlock(existing);
|
|
8988
|
-
const carried =
|
|
8997
|
+
const carried = record2.files[target.path];
|
|
8989
8998
|
let content;
|
|
8990
8999
|
try {
|
|
8991
9000
|
content = upsertMarkerBlock(existing, note);
|
|
@@ -9007,7 +9016,7 @@ ${codexContent}`);
|
|
|
9007
9016
|
if (prior === void 0 && original.at !== "absent") {
|
|
9008
9017
|
notes.push(`${target.path}: an existing ainecto block was saved and will be restored by --undo`);
|
|
9009
9018
|
}
|
|
9010
|
-
|
|
9019
|
+
record2.files[target.path] = {
|
|
9011
9020
|
scope: "block",
|
|
9012
9021
|
createdByUs: prior?.createdByUs ?? existing === void 0,
|
|
9013
9022
|
original,
|
|
@@ -9033,7 +9042,7 @@ ${codexContent}`);
|
|
|
9033
9042
|
if (existingConfig !== void 0 && theirConfig === void 0) {
|
|
9034
9043
|
notes.push(`${HARNESS_CONFIG_PATH} is not a JSON object \u2014 left untouched.`);
|
|
9035
9044
|
} else {
|
|
9036
|
-
const priorConfig =
|
|
9045
|
+
const priorConfig = record2.files[HARNESS_CONFIG_PATH];
|
|
9037
9046
|
const originalFields = {};
|
|
9038
9047
|
for (const field of OUR_CONFIG_FIELDS) {
|
|
9039
9048
|
const presentNow = theirConfig !== void 0 && hasField(theirConfig, field);
|
|
@@ -9065,7 +9074,7 @@ ${codexContent}`);
|
|
|
9065
9074
|
}
|
|
9066
9075
|
}
|
|
9067
9076
|
const mergedConfig = serialize({ ...retained, ...ourFields });
|
|
9068
|
-
|
|
9077
|
+
record2.files[HARNESS_CONFIG_PATH] = {
|
|
9069
9078
|
scope: "fields",
|
|
9070
9079
|
createdByUs: priorConfig?.createdByUs ?? existingConfig === void 0,
|
|
9071
9080
|
original: ABSENT,
|
|
@@ -9083,7 +9092,7 @@ ${codexContent}`);
|
|
|
9083
9092
|
}
|
|
9084
9093
|
}
|
|
9085
9094
|
const existingRecord = input.files.get(HARNESS_RECORD_PATH);
|
|
9086
|
-
const recordContent = serializeRecord(
|
|
9095
|
+
const recordContent = serializeRecord(record2);
|
|
9087
9096
|
if (recordContent !== existingRecord) {
|
|
9088
9097
|
writes.push({
|
|
9089
9098
|
path: HARNESS_RECORD_PATH,
|
|
@@ -9091,7 +9100,7 @@ ${codexContent}`);
|
|
|
9091
9100
|
existed: existingRecord !== void 0
|
|
9092
9101
|
});
|
|
9093
9102
|
}
|
|
9094
|
-
return { writes, deletes: [], notes, record };
|
|
9103
|
+
return { writes, deletes: [], notes, record: record2 };
|
|
9095
9104
|
}
|
|
9096
9105
|
function planUndo(input) {
|
|
9097
9106
|
const state = input.record ?? readRecord(input.files.get(HARNESS_RECORD_PATH));
|
|
@@ -9113,9 +9122,9 @@ function planUndo(input) {
|
|
|
9113
9122
|
tail();
|
|
9114
9123
|
return { writes, deletes, notes };
|
|
9115
9124
|
}
|
|
9116
|
-
const
|
|
9117
|
-
const remaining = { ...
|
|
9118
|
-
for (const [path, contract] of Object.entries(
|
|
9125
|
+
const record2 = state.record;
|
|
9126
|
+
const remaining = { ...record2.files };
|
|
9127
|
+
for (const [path, contract] of Object.entries(record2.files)) {
|
|
9119
9128
|
const outcome = undoOne(path, contract, input.files.get(path));
|
|
9120
9129
|
if (outcome.kind !== "unresolved" && outcome.kind !== "keep" && outcome.note !== void 0) {
|
|
9121
9130
|
notes.push(outcome.note);
|
|
@@ -9135,7 +9144,7 @@ function planUndo(input) {
|
|
|
9135
9144
|
tail();
|
|
9136
9145
|
if (input.files.get(HARNESS_RECORD_PATH) !== void 0) {
|
|
9137
9146
|
if (Object.keys(remaining).length > 0) {
|
|
9138
|
-
const reduced = { ...
|
|
9147
|
+
const reduced = { ...record2, files: remaining };
|
|
9139
9148
|
writes.push({ path: HARNESS_RECORD_PATH, content: serializeRecord(reduced), existed: true });
|
|
9140
9149
|
notes.push(
|
|
9141
9150
|
`${HARNESS_RECORD_PATH}: kept, with the finished items removed \u2014 it still holds the backups --undo needs. Run --undo again once the items above are resolved.`
|
|
@@ -9144,7 +9153,7 @@ function planUndo(input) {
|
|
|
9144
9153
|
deletes.push(HARNESS_RECORD_PATH);
|
|
9145
9154
|
}
|
|
9146
9155
|
}
|
|
9147
|
-
const removableDirectories = parentsOf(deletes).filter((directory) =>
|
|
9156
|
+
const removableDirectories = parentsOf(deletes).filter((directory) => record2.createdDirectories.includes(directory));
|
|
9148
9157
|
return { writes, deletes, notes, removableDirectories };
|
|
9149
9158
|
}
|
|
9150
9159
|
function unexplainedMarkers(existing, contract) {
|
|
@@ -9561,9 +9570,9 @@ async function applyPlan(root, plan, dryRun, snapshot, recordFirst = true) {
|
|
|
9561
9570
|
}
|
|
9562
9571
|
const applied = [];
|
|
9563
9572
|
try {
|
|
9564
|
-
const
|
|
9565
|
-
const recordWrites = plan.writes.filter((write) =>
|
|
9566
|
-
const recordDeletes = plan.deletes.filter((path) =>
|
|
9573
|
+
const isRecord14 = (path) => !recordFirst && path === HARNESS_RECORD_PATH;
|
|
9574
|
+
const recordWrites = plan.writes.filter((write) => isRecord14(write.path));
|
|
9575
|
+
const recordDeletes = plan.deletes.filter((path) => isRecord14(path));
|
|
9567
9576
|
const createdDirectories = [...plan.record?.createdDirectories ?? []];
|
|
9568
9577
|
const rememberDirectories = (directories) => {
|
|
9569
9578
|
for (const directory of directories) {
|
|
@@ -9605,8 +9614,8 @@ async function applyPlan(root, plan, dryRun, snapshot, recordFirst = true) {
|
|
|
9605
9614
|
};
|
|
9606
9615
|
try {
|
|
9607
9616
|
await apply(
|
|
9608
|
-
orderedWrites(plan.writes.filter((write) => !
|
|
9609
|
-
plan.deletes.filter((path) => !
|
|
9617
|
+
orderedWrites(plan.writes.filter((write) => !isRecord14(write.path)), recordFirst),
|
|
9618
|
+
plan.deletes.filter((path) => !isRecord14(path))
|
|
9610
9619
|
);
|
|
9611
9620
|
await recordDirectoriesOrExplain(false);
|
|
9612
9621
|
await apply(recordWrites, recordDeletes);
|
|
@@ -9626,9 +9635,9 @@ Already applied before this failure: ${applied.join(", ") || "(nothing)"}`
|
|
|
9626
9635
|
}
|
|
9627
9636
|
}
|
|
9628
9637
|
function orderedWrites(writes, recordFirst) {
|
|
9629
|
-
const
|
|
9638
|
+
const record2 = writes.filter((write) => write.path === HARNESS_RECORD_PATH);
|
|
9630
9639
|
const rest = writes.filter((write) => write.path !== HARNESS_RECORD_PATH);
|
|
9631
|
-
return recordFirst ? [...
|
|
9640
|
+
return recordFirst ? [...record2, ...rest] : [...rest, ...record2];
|
|
9632
9641
|
}
|
|
9633
9642
|
async function assertUnchangedSinceSnapshot(root, relativePath, snapshot) {
|
|
9634
9643
|
if (!snapshot.has(relativePath)) {
|
|
@@ -10472,6 +10481,7 @@ function assertNoArgs(command, argv) {
|
|
|
10472
10481
|
|
|
10473
10482
|
// src/adapters/cli/termCommand.ts
|
|
10474
10483
|
import { closeSync as closeSync2, writeSync } from "fs";
|
|
10484
|
+
import { hostname } from "os";
|
|
10475
10485
|
import { resolve as resolve3 } from "path";
|
|
10476
10486
|
|
|
10477
10487
|
// src/core/term/client.ts
|
|
@@ -10493,6 +10503,9 @@ var TermError = class extends Error {
|
|
|
10493
10503
|
}
|
|
10494
10504
|
code;
|
|
10495
10505
|
};
|
|
10506
|
+
function noSession(name) {
|
|
10507
|
+
return new TermError("TERM_NO_SESSION", `No session named "${name}" (no term sessions are running).`);
|
|
10508
|
+
}
|
|
10496
10509
|
|
|
10497
10510
|
// src/core/term/daemonLock.ts
|
|
10498
10511
|
var LINUX_ABSTRACT_SOCKET_NODE = [20, 8, 0];
|
|
@@ -10605,97 +10618,116 @@ function parseClientMessage(line) {
|
|
|
10605
10618
|
} catch {
|
|
10606
10619
|
throw new TermProtocolError("Not a JSON line.");
|
|
10607
10620
|
}
|
|
10608
|
-
const
|
|
10609
|
-
const op = stringField(
|
|
10621
|
+
const record2 = asRecord(value);
|
|
10622
|
+
const op = stringField(record2, "op");
|
|
10610
10623
|
if (op === "in") {
|
|
10611
|
-
return { op, d: stringField(
|
|
10624
|
+
return { op, d: stringField(record2, "d") };
|
|
10612
10625
|
}
|
|
10613
10626
|
if (op === "resize") {
|
|
10614
|
-
return { op, cols: sizeField(
|
|
10627
|
+
return { op, cols: sizeField(record2, "cols"), rows: sizeField(record2, "rows") };
|
|
10615
10628
|
}
|
|
10616
|
-
const id = stringField(
|
|
10629
|
+
const id = stringField(record2, "id");
|
|
10617
10630
|
switch (op) {
|
|
10618
10631
|
case "new":
|
|
10619
10632
|
return {
|
|
10620
10633
|
id,
|
|
10621
10634
|
op,
|
|
10622
|
-
name: stringField(
|
|
10623
|
-
cwd: stringField(
|
|
10624
|
-
command:
|
|
10625
|
-
env: stringMapField(
|
|
10626
|
-
cols: optionalSize(
|
|
10627
|
-
rows: optionalSize(
|
|
10635
|
+
name: stringField(record2, "name"),
|
|
10636
|
+
cwd: stringField(record2, "cwd"),
|
|
10637
|
+
command: record2.command === null ? null : stringArrayField(record2, "command"),
|
|
10638
|
+
env: stringMapField(record2, "env"),
|
|
10639
|
+
cols: optionalSize(record2, "cols"),
|
|
10640
|
+
rows: optionalSize(record2, "rows")
|
|
10628
10641
|
};
|
|
10629
10642
|
case "ls":
|
|
10630
10643
|
case "kill-server":
|
|
10631
10644
|
case "detach":
|
|
10632
10645
|
return { id, op };
|
|
10633
10646
|
case "send":
|
|
10634
|
-
return { id, op, name: stringField(
|
|
10647
|
+
return { id, op, name: stringField(record2, "name"), text: stringField(record2, "text"), paste: record2.paste === true };
|
|
10635
10648
|
case "key":
|
|
10636
|
-
return { id, op, name: stringField(
|
|
10649
|
+
return { id, op, name: stringField(record2, "name"), key: stringField(record2, "key") };
|
|
10637
10650
|
case "read":
|
|
10638
|
-
return { id, op, name: stringField(
|
|
10651
|
+
return { id, op, name: stringField(record2, "name"), scrollback: record2.scrollback === true, lines: optionalSize(record2, "lines") };
|
|
10639
10652
|
case "kill":
|
|
10640
10653
|
case "watch":
|
|
10641
|
-
return { id, op, name: stringField(
|
|
10654
|
+
return { id, op, name: stringField(record2, "name") };
|
|
10642
10655
|
case "restore":
|
|
10643
|
-
return { id, op, env: stringMapField(
|
|
10656
|
+
return { id, op, env: stringMapField(record2, "env") };
|
|
10644
10657
|
case "attach":
|
|
10645
|
-
return { id, op, name: stringField(
|
|
10658
|
+
return { id, op, name: stringField(record2, "name"), cols: sizeField(record2, "cols"), rows: sizeField(record2, "rows") };
|
|
10646
10659
|
default:
|
|
10647
10660
|
throw new TermProtocolError(`Unknown op "${op}".`);
|
|
10648
10661
|
}
|
|
10649
10662
|
}
|
|
10650
10663
|
function parseDaemonMessage(line) {
|
|
10651
|
-
const
|
|
10652
|
-
if (typeof
|
|
10653
|
-
switch (
|
|
10664
|
+
const record2 = asRecord(JSON.parse(line));
|
|
10665
|
+
if (typeof record2.event === "string") {
|
|
10666
|
+
switch (record2.event) {
|
|
10654
10667
|
case "screen":
|
|
10655
10668
|
case "out":
|
|
10656
|
-
return { event:
|
|
10669
|
+
return { event: record2.event, d: stringField(record2, "d") };
|
|
10657
10670
|
case "changed":
|
|
10658
10671
|
return { event: "changed" };
|
|
10659
10672
|
case "exit":
|
|
10660
10673
|
return {
|
|
10661
10674
|
event: "exit",
|
|
10662
|
-
exitCode: typeof
|
|
10663
|
-
signal: typeof
|
|
10664
|
-
reset: stringField(
|
|
10675
|
+
exitCode: typeof record2.exitCode === "number" ? record2.exitCode : 0,
|
|
10676
|
+
signal: typeof record2.signal === "number" ? record2.signal : 0,
|
|
10677
|
+
reset: stringField(record2, "reset")
|
|
10665
10678
|
};
|
|
10666
10679
|
default:
|
|
10667
|
-
throw new TermProtocolError(`Unknown event "${
|
|
10680
|
+
throw new TermProtocolError(`Unknown event "${record2.event}".`);
|
|
10668
10681
|
}
|
|
10669
10682
|
}
|
|
10670
|
-
const id = stringField(
|
|
10671
|
-
if (
|
|
10672
|
-
return { id, ok: true, data:
|
|
10683
|
+
const id = stringField(record2, "id");
|
|
10684
|
+
if (record2.ok === true) {
|
|
10685
|
+
return { id, ok: true, data: record2.data };
|
|
10673
10686
|
}
|
|
10674
|
-
const error = asRecord(
|
|
10687
|
+
const error = asRecord(record2.error);
|
|
10675
10688
|
return { id, ok: false, error: { code: stringField(error, "code"), message: stringField(error, "message") } };
|
|
10676
10689
|
}
|
|
10690
|
+
function listedSessions(data) {
|
|
10691
|
+
if (data && typeof data === "object" && "sessions" in data && Array.isArray(data.sessions)) {
|
|
10692
|
+
return data.sessions.filter(isListedSession);
|
|
10693
|
+
}
|
|
10694
|
+
return [];
|
|
10695
|
+
}
|
|
10696
|
+
function isListedSession(value) {
|
|
10697
|
+
if (!value || typeof value !== "object") {
|
|
10698
|
+
return false;
|
|
10699
|
+
}
|
|
10700
|
+
const session = value;
|
|
10701
|
+
return typeof session.name === "string" && typeof session.pid === "number" && typeof session.cwd === "string" && typeof session.cols === "number" && typeof session.rows === "number";
|
|
10702
|
+
}
|
|
10703
|
+
function readLines(data) {
|
|
10704
|
+
if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
|
|
10705
|
+
return data.lines.filter((line) => typeof line === "string");
|
|
10706
|
+
}
|
|
10707
|
+
throw new TermError("TERM_BAD_RESPONSE", "The term daemon answered read without lines.");
|
|
10708
|
+
}
|
|
10677
10709
|
function asRecord(value) {
|
|
10678
10710
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
10679
10711
|
throw new TermProtocolError("Expected a JSON object.");
|
|
10680
10712
|
}
|
|
10681
10713
|
return value;
|
|
10682
10714
|
}
|
|
10683
|
-
function stringField(
|
|
10684
|
-
const value =
|
|
10715
|
+
function stringField(record2, key) {
|
|
10716
|
+
const value = record2[key];
|
|
10685
10717
|
if (typeof value !== "string") {
|
|
10686
10718
|
throw new TermProtocolError(`"${key}" must be a string.`);
|
|
10687
10719
|
}
|
|
10688
10720
|
return value;
|
|
10689
10721
|
}
|
|
10690
|
-
function stringArrayField(
|
|
10691
|
-
const value =
|
|
10722
|
+
function stringArrayField(record2, key) {
|
|
10723
|
+
const value = record2[key];
|
|
10692
10724
|
if (!Array.isArray(value) || value.length === 0 || !value.every((item) => typeof item === "string")) {
|
|
10693
10725
|
throw new TermProtocolError(`"${key}" must be a non-empty string array.`);
|
|
10694
10726
|
}
|
|
10695
10727
|
return value;
|
|
10696
10728
|
}
|
|
10697
|
-
function stringMapField(
|
|
10698
|
-
const value = asRecord(
|
|
10729
|
+
function stringMapField(record2, key) {
|
|
10730
|
+
const value = asRecord(record2[key]);
|
|
10699
10731
|
const output = {};
|
|
10700
10732
|
for (const [name, item] of Object.entries(value)) {
|
|
10701
10733
|
if (typeof item === "string") {
|
|
@@ -10704,15 +10736,15 @@ function stringMapField(record, key) {
|
|
|
10704
10736
|
}
|
|
10705
10737
|
return output;
|
|
10706
10738
|
}
|
|
10707
|
-
function sizeField(
|
|
10708
|
-
const value =
|
|
10739
|
+
function sizeField(record2, key) {
|
|
10740
|
+
const value = record2[key];
|
|
10709
10741
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
|
|
10710
10742
|
throw new TermProtocolError(`"${key}" must be a positive integer.`);
|
|
10711
10743
|
}
|
|
10712
10744
|
return value;
|
|
10713
10745
|
}
|
|
10714
|
-
function optionalSize(
|
|
10715
|
-
return
|
|
10746
|
+
function optionalSize(record2, key) {
|
|
10747
|
+
return record2[key] === void 0 ? void 0 : sizeField(record2, key);
|
|
10716
10748
|
}
|
|
10717
10749
|
|
|
10718
10750
|
// src/core/term/client.ts
|
|
@@ -10949,8 +10981,8 @@ var DaemonLog = class {
|
|
|
10949
10981
|
enableRotation() {
|
|
10950
10982
|
this.rotating = true;
|
|
10951
10983
|
}
|
|
10952
|
-
write(
|
|
10953
|
-
const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...
|
|
10984
|
+
write(record2) {
|
|
10985
|
+
const line = `${JSON.stringify({ ts: (/* @__PURE__ */ new Date()).toISOString(), ...record2 })}
|
|
10954
10986
|
`;
|
|
10955
10987
|
try {
|
|
10956
10988
|
if (this.rotating) {
|
|
@@ -12149,7 +12181,9 @@ function termPaths(home = homedir2()) {
|
|
|
12149
12181
|
daemonInfo: join6(dir, "daemon.json"),
|
|
12150
12182
|
manifest: join6(dir, "sessions.json"),
|
|
12151
12183
|
log: join6(dir, "daemon.log"),
|
|
12152
|
-
previousLog: join6(dir, "daemon.log.1")
|
|
12184
|
+
previousLog: join6(dir, "daemon.log.1"),
|
|
12185
|
+
remoteLog: join6(dir, "remote.log"),
|
|
12186
|
+
previousRemoteLog: join6(dir, "remote.log.1")
|
|
12153
12187
|
};
|
|
12154
12188
|
}
|
|
12155
12189
|
|
|
@@ -12157,7 +12191,7 @@ function termPaths(home = homedir2()) {
|
|
|
12157
12191
|
async function waitForMatch(paths, name, pattern, range, timeoutMs) {
|
|
12158
12192
|
const client = await openTermClient(paths, { start: false });
|
|
12159
12193
|
if (!client) {
|
|
12160
|
-
throw
|
|
12194
|
+
throw noSession(name);
|
|
12161
12195
|
}
|
|
12162
12196
|
let dirty = false;
|
|
12163
12197
|
let ended;
|
|
@@ -12194,7 +12228,7 @@ async function waitForMatch(paths, name, pattern, range, timeoutMs) {
|
|
|
12194
12228
|
}
|
|
12195
12229
|
throw error;
|
|
12196
12230
|
}
|
|
12197
|
-
const lines =
|
|
12231
|
+
const lines = readLines(data);
|
|
12198
12232
|
for (const line of lines) {
|
|
12199
12233
|
const found = pattern.exec(line);
|
|
12200
12234
|
if (found) {
|
|
@@ -12221,11 +12255,363 @@ async function waitForMatch(paths, name, pattern, range, timeoutMs) {
|
|
|
12221
12255
|
client.close();
|
|
12222
12256
|
}
|
|
12223
12257
|
}
|
|
12224
|
-
|
|
12225
|
-
|
|
12226
|
-
|
|
12258
|
+
|
|
12259
|
+
// src/core/term/remote.ts
|
|
12260
|
+
import { StringDecoder } from "string_decoder";
|
|
12261
|
+
|
|
12262
|
+
// src/core/async/sleep.ts
|
|
12263
|
+
function sleep(ms, signal) {
|
|
12264
|
+
return new Promise((resolve4) => {
|
|
12265
|
+
if (signal.aborted) {
|
|
12266
|
+
resolve4();
|
|
12267
|
+
return;
|
|
12268
|
+
}
|
|
12269
|
+
const timer = setTimeout(done, ms);
|
|
12270
|
+
signal.addEventListener("abort", done, { once: true });
|
|
12271
|
+
function done() {
|
|
12272
|
+
clearTimeout(timer);
|
|
12273
|
+
signal.removeEventListener("abort", done);
|
|
12274
|
+
resolve4();
|
|
12275
|
+
}
|
|
12276
|
+
});
|
|
12277
|
+
}
|
|
12278
|
+
|
|
12279
|
+
// src/core/http/pcHttp.ts
|
|
12280
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
12281
|
+
var PcCallError = class extends Error {
|
|
12282
|
+
constructor(message, op, status, code) {
|
|
12283
|
+
super(message);
|
|
12284
|
+
this.op = op;
|
|
12285
|
+
this.status = status;
|
|
12286
|
+
this.code = code;
|
|
12287
|
+
this.name = "PcCallError";
|
|
12288
|
+
}
|
|
12289
|
+
op;
|
|
12290
|
+
status;
|
|
12291
|
+
code;
|
|
12292
|
+
/** 다시 해 볼 만한가 — 네트워크·기한·5xx·429. */
|
|
12293
|
+
get retryable() {
|
|
12294
|
+
return this.status === void 0 || this.status >= 500 || this.status === 429;
|
|
12295
|
+
}
|
|
12296
|
+
};
|
|
12297
|
+
function createPcHttp(input) {
|
|
12298
|
+
const fetchImpl = input.fetchImpl ?? fetch;
|
|
12299
|
+
const base = `${input.endpoint.replace(/\/+$/, "")}/${input.path}/`;
|
|
12300
|
+
const fail = input.error ?? ((message, op, status, code) => new PcCallError(message, op, status, code));
|
|
12301
|
+
const { log } = input.logging;
|
|
12302
|
+
let sessionToken;
|
|
12303
|
+
async function send(op, payload, token, options = {}) {
|
|
12304
|
+
const controller = new AbortController();
|
|
12305
|
+
const timer = setTimeout(
|
|
12306
|
+
() => controller.abort(new DOMException("timed out", "TimeoutError")),
|
|
12307
|
+
(options.holdMs ?? 0) + input.timeoutMs
|
|
12308
|
+
);
|
|
12309
|
+
const onStop = () => controller.abort(new DOMException("stopped", "AbortError"));
|
|
12310
|
+
options.signal?.addEventListener("abort", onStop, { once: true });
|
|
12311
|
+
const headers = { "Content-Type": "application/json", Accept: "application/json" };
|
|
12312
|
+
if (token) headers.Authorization = `Bearer ${token}`;
|
|
12313
|
+
if (sessionToken && op !== "open") headers[input.sessionHeader] = sessionToken;
|
|
12314
|
+
try {
|
|
12315
|
+
const response = await fetchImpl(base + op, { method: "POST", headers, body: payload, signal: controller.signal });
|
|
12316
|
+
await response.clone().arrayBuffer();
|
|
12317
|
+
return response;
|
|
12318
|
+
} catch (error) {
|
|
12319
|
+
throw controller.signal.aborted && controller.signal.reason instanceof Error ? controller.signal.reason : error;
|
|
12320
|
+
} finally {
|
|
12321
|
+
clearTimeout(timer);
|
|
12322
|
+
options.signal?.removeEventListener("abort", onStop);
|
|
12323
|
+
}
|
|
12324
|
+
}
|
|
12325
|
+
return {
|
|
12326
|
+
useSessionToken(token) {
|
|
12327
|
+
sessionToken = token;
|
|
12328
|
+
},
|
|
12329
|
+
async call(op, body, options) {
|
|
12330
|
+
const callId = randomUUID2();
|
|
12331
|
+
const payload = JSON.stringify(body);
|
|
12332
|
+
const started = Date.now();
|
|
12333
|
+
log.write(input.logging.request({ callId, op, bytes: Buffer.byteLength(payload, "utf8") }, options));
|
|
12334
|
+
let outcome = { ok: false, error: "no response" };
|
|
12335
|
+
try {
|
|
12336
|
+
let response = await send(op, payload, await input.tokenProvider.getAccessToken(), options);
|
|
12337
|
+
if (response.status === 401) {
|
|
12338
|
+
response = await send(op, payload, await input.tokenProvider.refreshAfterUnauthorized(), options);
|
|
12339
|
+
}
|
|
12340
|
+
const text = await response.text();
|
|
12341
|
+
const parsed = parseJson2(text);
|
|
12342
|
+
if (!response.ok) {
|
|
12343
|
+
const code = typeof parsed?.code === "string" ? parsed.code : void 0;
|
|
12344
|
+
outcome = { ok: false, status: response.status, code };
|
|
12345
|
+
throw fail(typeof parsed?.detail === "string" ? parsed.detail : `HTTP ${response.status}`, op, response.status, code);
|
|
12346
|
+
}
|
|
12347
|
+
outcome = { ok: true, status: response.status, body: parsed ?? {} };
|
|
12348
|
+
return parsed ?? {};
|
|
12349
|
+
} catch (error) {
|
|
12350
|
+
if (error instanceof PcCallError) throw error;
|
|
12351
|
+
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
12352
|
+
const reason = timedOut ? error.name : error instanceof Error ? error.message : String(error);
|
|
12353
|
+
outcome = { ok: false, error: reason };
|
|
12354
|
+
throw fail(timedOut ? `${op} timed out` : `${op} failed: ${reason}`, op);
|
|
12355
|
+
} finally {
|
|
12356
|
+
log.write(input.logging.response({ callId, op, ms: Date.now() - started }, outcome));
|
|
12357
|
+
}
|
|
12358
|
+
}
|
|
12359
|
+
};
|
|
12360
|
+
}
|
|
12361
|
+
function parseJson2(text) {
|
|
12362
|
+
if (!text) return void 0;
|
|
12363
|
+
try {
|
|
12364
|
+
const value = JSON.parse(text);
|
|
12365
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
12366
|
+
} catch {
|
|
12367
|
+
return void 0;
|
|
12227
12368
|
}
|
|
12228
|
-
|
|
12369
|
+
}
|
|
12370
|
+
|
|
12371
|
+
// src/core/term/remoteFrame.ts
|
|
12372
|
+
import { createHash as createHash6 } from "crypto";
|
|
12373
|
+
function screenFrame(lines, maxD) {
|
|
12374
|
+
const sizes = lines.map((line) => Buffer.byteLength(line, "utf8"));
|
|
12375
|
+
let start = 0;
|
|
12376
|
+
let bytes = sizes.reduce((sum, size) => sum + size, 0) + Math.max(0, lines.length - 1) * 2;
|
|
12377
|
+
while (start < lines.length && base64Length(bytes) > maxD) {
|
|
12378
|
+
bytes -= (sizes[start] ?? 0) + (start < lines.length - 1 ? 2 : 0);
|
|
12379
|
+
start += 1;
|
|
12380
|
+
}
|
|
12381
|
+
const text = lines.slice(start).join("\r\n");
|
|
12382
|
+
return {
|
|
12383
|
+
d: Buffer.from(text, "utf8").toString("base64"),
|
|
12384
|
+
hash: createHash6("sha256").update(text, "utf8").digest("hex"),
|
|
12385
|
+
dropped: start
|
|
12386
|
+
};
|
|
12387
|
+
}
|
|
12388
|
+
function frameBudget(frameMaxBytes, body) {
|
|
12389
|
+
return frameMaxBytes - Buffer.byteLength(JSON.stringify({ ...body, d: "" }), "utf8");
|
|
12390
|
+
}
|
|
12391
|
+
function base64Length(bytes) {
|
|
12392
|
+
return 4 * Math.ceil(bytes / 3);
|
|
12393
|
+
}
|
|
12394
|
+
|
|
12395
|
+
// src/core/term/remoteLimits.ts
|
|
12396
|
+
var CALL_TIMEOUT_MS = 1e4;
|
|
12397
|
+
var FRAME_MIN_INTERVAL_MS = 150;
|
|
12398
|
+
var FRAME_SCROLLBACK_LINES = 200;
|
|
12399
|
+
var RETRY_MIN_MS = 500;
|
|
12400
|
+
var RETRY_MAX_MS = 1e4;
|
|
12401
|
+
function retryWait(attempt, random) {
|
|
12402
|
+
return Math.min(RETRY_MIN_MS * 2 ** attempt, RETRY_MAX_MS) + Math.floor(random * RETRY_MIN_MS);
|
|
12403
|
+
}
|
|
12404
|
+
|
|
12405
|
+
// src/core/term/remote.ts
|
|
12406
|
+
function openRemoteLog(paths) {
|
|
12407
|
+
const log = new DaemonLog(paths.remoteLog, paths.previousRemoteLog);
|
|
12408
|
+
log.enableRotation();
|
|
12409
|
+
return log;
|
|
12410
|
+
}
|
|
12411
|
+
function createRemoteHttp(input) {
|
|
12412
|
+
return createPcHttp({
|
|
12413
|
+
endpoint: input.endpoint,
|
|
12414
|
+
path: "term/pc",
|
|
12415
|
+
tokenProvider: input.tokenProvider,
|
|
12416
|
+
timeoutMs: CALL_TIMEOUT_MS,
|
|
12417
|
+
sessionHeader: "X-Remote-Token",
|
|
12418
|
+
fetchImpl: input.fetchImpl,
|
|
12419
|
+
logging: {
|
|
12420
|
+
log: input.log,
|
|
12421
|
+
request: ({ callId, op, bytes }) => ({ event: "remote_call", callId, op, bytes }),
|
|
12422
|
+
response: ({ callId, op, ms }, outcome) => ({
|
|
12423
|
+
event: "remote_call_response",
|
|
12424
|
+
callId,
|
|
12425
|
+
op,
|
|
12426
|
+
...outcome.ok ? { ok: true, status: outcome.status, ...answerSummary(outcome.body) } : outcome,
|
|
12427
|
+
ms
|
|
12428
|
+
})
|
|
12429
|
+
}
|
|
12430
|
+
});
|
|
12431
|
+
}
|
|
12432
|
+
async function runRemote(deps) {
|
|
12433
|
+
const name = deps.session;
|
|
12434
|
+
const client = await openTermClient(deps.paths, { start: false });
|
|
12435
|
+
if (!client) {
|
|
12436
|
+
throw noSession(name);
|
|
12437
|
+
}
|
|
12438
|
+
let ending;
|
|
12439
|
+
const stopper = new AbortController();
|
|
12440
|
+
let dirty = true;
|
|
12441
|
+
let wakeFrame;
|
|
12442
|
+
const nudge = () => {
|
|
12443
|
+
const wake = wakeFrame;
|
|
12444
|
+
wakeFrame = void 0;
|
|
12445
|
+
wake?.();
|
|
12446
|
+
};
|
|
12447
|
+
const end = (outcome) => {
|
|
12448
|
+
if (ending) return;
|
|
12449
|
+
ending = outcome;
|
|
12450
|
+
stopper.abort();
|
|
12451
|
+
nudge();
|
|
12452
|
+
};
|
|
12453
|
+
const daemonFailed = (op, error) => {
|
|
12454
|
+
const code = error instanceof TermError ? error.code : "UNKNOWN";
|
|
12455
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12456
|
+
deps.log.write({ event: "remote_daemon_error", op, code, message });
|
|
12457
|
+
end(code === "TERM_NO_SESSION" ? { exitCode: 0, reason: `Session ${name} ended.`, close: true } : { exitCode: 1, reason: `The term daemon failed ${op} (${code}): ${message}`, close: true });
|
|
12458
|
+
};
|
|
12459
|
+
const onUserStop = () => end({ exitCode: 0, reason: "Stopped.", close: true });
|
|
12460
|
+
if (deps.signal.aborted) onUserStop();
|
|
12461
|
+
deps.signal.addEventListener("abort", onUserStop, { once: true });
|
|
12462
|
+
client.onEvent((event) => {
|
|
12463
|
+
if (event.event === "changed") {
|
|
12464
|
+
dirty = true;
|
|
12465
|
+
nudge();
|
|
12466
|
+
} else if (event.event === "exit") {
|
|
12467
|
+
end({ exitCode: 0, reason: `Session ${name} exited (${event.signal ? `signal ${event.signal}` : `code ${event.exitCode}`}).`, close: true });
|
|
12468
|
+
}
|
|
12469
|
+
});
|
|
12470
|
+
client.onClose(() => end({ exitCode: 1, reason: "Lost the connection to the term daemon.", close: true }));
|
|
12471
|
+
let remoteId;
|
|
12472
|
+
try {
|
|
12473
|
+
await client.request({ op: "watch", name });
|
|
12474
|
+
const listed = listedSessions(await client.request({ op: "ls" })).find((session) => session.name === name);
|
|
12475
|
+
if (!listed) {
|
|
12476
|
+
throw noSession(name);
|
|
12477
|
+
}
|
|
12478
|
+
const { cols, rows } = listed;
|
|
12479
|
+
if (ending) {
|
|
12480
|
+
return { exitCode: ending.exitCode, reason: ending.reason };
|
|
12481
|
+
}
|
|
12482
|
+
const opened = await deps.http.call("open", { session: name, hostName: deps.hostName, cliVersion: deps.cliVersion, cols, rows });
|
|
12483
|
+
const limits = serverLimits(opened.limits);
|
|
12484
|
+
if (typeof opened.remoteId !== "string" || typeof opened.remoteToken !== "string" || !limits) {
|
|
12485
|
+
throw new TermError("TERM_REMOTE_BAD_RESPONSE", "AiNecto answered open without remoteId, remoteToken or limits.");
|
|
12486
|
+
}
|
|
12487
|
+
const id = opened.remoteId;
|
|
12488
|
+
remoteId = id;
|
|
12489
|
+
deps.http.useSessionToken(opened.remoteToken);
|
|
12490
|
+
deps.log.write({ event: "remote_opened", remoteId: id, cols, rows, ...limits });
|
|
12491
|
+
deps.print(`Sharing ${name} (${cols}x${rows}) on AiNecto from ${deps.hostName}. Open the remote terminal in AiNecto to watch and type. Press Ctrl+C to stop.`);
|
|
12492
|
+
const refused = (error) => {
|
|
12493
|
+
if (error instanceof PcCallError && error.status === 404) {
|
|
12494
|
+
return { exitCode: 0, reason: `AiNecto no longer has this remote terminal open (${error.code ?? "404"}).`, close: false };
|
|
12495
|
+
}
|
|
12496
|
+
const what = error instanceof PcCallError ? `${error.op}: ${error.status ?? "-"} ${error.code ?? ""} ${error.message}`.replace(/\s+/g, " ") : error instanceof Error ? error.message : String(error);
|
|
12497
|
+
return { exitCode: 1, reason: `AiNecto refused the remote terminal (${what}).`, close: true };
|
|
12498
|
+
};
|
|
12499
|
+
const decoder = new StringDecoder("utf8");
|
|
12500
|
+
const pollLoop = async () => {
|
|
12501
|
+
let attempt = 0;
|
|
12502
|
+
while (!ending) {
|
|
12503
|
+
let answer;
|
|
12504
|
+
try {
|
|
12505
|
+
answer = await deps.http.call("poll", { remoteId: id }, { holdMs: limits.pollHoldSeconds * 1e3, signal: stopper.signal });
|
|
12506
|
+
} catch (error) {
|
|
12507
|
+
if (ending) return;
|
|
12508
|
+
if (!(error instanceof PcCallError) || !error.retryable) {
|
|
12509
|
+
end(refused(error));
|
|
12510
|
+
return;
|
|
12511
|
+
}
|
|
12512
|
+
await sleep(retryWait(attempt, Math.random()), stopper.signal);
|
|
12513
|
+
attempt += 1;
|
|
12514
|
+
continue;
|
|
12515
|
+
}
|
|
12516
|
+
attempt = 0;
|
|
12517
|
+
if (answer.state === "CLOSED") {
|
|
12518
|
+
end({ exitCode: 0, reason: `AiNecto closed this remote terminal (${typeof answer.reason === "string" ? answer.reason : "CLOSED"}).`, close: false });
|
|
12519
|
+
return;
|
|
12520
|
+
}
|
|
12521
|
+
for (const d of inputsIn(answer)) {
|
|
12522
|
+
const text = decoder.write(Buffer.from(d, "base64"));
|
|
12523
|
+
if (text === "") continue;
|
|
12524
|
+
try {
|
|
12525
|
+
await client.request({ op: "send", name, text, paste: false });
|
|
12526
|
+
} catch (error) {
|
|
12527
|
+
daemonFailed("send", error);
|
|
12528
|
+
return;
|
|
12529
|
+
}
|
|
12530
|
+
}
|
|
12531
|
+
}
|
|
12532
|
+
};
|
|
12533
|
+
const frameLoop = async () => {
|
|
12534
|
+
const budget = frameBudget(limits.frameMaxBytes, { remoteId: id, cols, rows });
|
|
12535
|
+
let sentHash;
|
|
12536
|
+
let lastRead = 0;
|
|
12537
|
+
let dropped = 0;
|
|
12538
|
+
let attempt = 0;
|
|
12539
|
+
while (!ending) {
|
|
12540
|
+
if (!dirty) {
|
|
12541
|
+
await new Promise((resolve4) => {
|
|
12542
|
+
wakeFrame = resolve4;
|
|
12543
|
+
});
|
|
12544
|
+
continue;
|
|
12545
|
+
}
|
|
12546
|
+
const gap = lastRead + FRAME_MIN_INTERVAL_MS - Date.now();
|
|
12547
|
+
if (gap > 0) {
|
|
12548
|
+
await sleep(gap, stopper.signal);
|
|
12549
|
+
continue;
|
|
12550
|
+
}
|
|
12551
|
+
dirty = false;
|
|
12552
|
+
lastRead = Date.now();
|
|
12553
|
+
let lines;
|
|
12554
|
+
try {
|
|
12555
|
+
lines = readLines(await client.request({ op: "read", name, scrollback: true, lines: FRAME_SCROLLBACK_LINES + rows }));
|
|
12556
|
+
} catch (error) {
|
|
12557
|
+
daemonFailed("read", error);
|
|
12558
|
+
return;
|
|
12559
|
+
}
|
|
12560
|
+
const frame = screenFrame(lines, budget);
|
|
12561
|
+
if (frame.dropped !== dropped) {
|
|
12562
|
+
dropped = frame.dropped;
|
|
12563
|
+
deps.log.write({ event: "remote_frame_trimmed", dropped });
|
|
12564
|
+
}
|
|
12565
|
+
if (frame.hash === sentHash) continue;
|
|
12566
|
+
try {
|
|
12567
|
+
await deps.http.call("frame", { remoteId: id, cols, rows, d: frame.d }, { signal: stopper.signal });
|
|
12568
|
+
sentHash = frame.hash;
|
|
12569
|
+
attempt = 0;
|
|
12570
|
+
} catch (error) {
|
|
12571
|
+
if (ending) return;
|
|
12572
|
+
if (!(error instanceof PcCallError) || !error.retryable) {
|
|
12573
|
+
end(refused(error));
|
|
12574
|
+
return;
|
|
12575
|
+
}
|
|
12576
|
+
await sleep(retryWait(attempt, Math.random()), stopper.signal);
|
|
12577
|
+
attempt += 1;
|
|
12578
|
+
dirty = true;
|
|
12579
|
+
}
|
|
12580
|
+
}
|
|
12581
|
+
};
|
|
12582
|
+
await Promise.all([pollLoop(), frameLoop()]);
|
|
12583
|
+
const outcome = ending ?? { exitCode: 1, reason: "The remote terminal stopped.", close: true };
|
|
12584
|
+
if (outcome.close) {
|
|
12585
|
+
try {
|
|
12586
|
+
await deps.http.call("close", { remoteId: id });
|
|
12587
|
+
} catch (error) {
|
|
12588
|
+
deps.print(`Could not tell AiNecto that sharing stopped: ${error instanceof Error ? error.message : String(error)}`);
|
|
12589
|
+
}
|
|
12590
|
+
}
|
|
12591
|
+
return { exitCode: outcome.exitCode, reason: outcome.reason };
|
|
12592
|
+
} finally {
|
|
12593
|
+
if (!remoteId) stopper.abort();
|
|
12594
|
+
deps.signal.removeEventListener("abort", onUserStop);
|
|
12595
|
+
client.close();
|
|
12596
|
+
}
|
|
12597
|
+
}
|
|
12598
|
+
function answerSummary(body) {
|
|
12599
|
+
return {
|
|
12600
|
+
...typeof body.state === "string" ? { state: body.state } : {},
|
|
12601
|
+
...typeof body.reason === "string" ? { reason: body.reason } : {},
|
|
12602
|
+
...Array.isArray(body.commands) ? { commands: body.commands.length } : {},
|
|
12603
|
+
...typeof body.version === "number" ? { version: body.version } : {}
|
|
12604
|
+
};
|
|
12605
|
+
}
|
|
12606
|
+
function serverLimits(value) {
|
|
12607
|
+
if (!value || typeof value !== "object") return void 0;
|
|
12608
|
+
const pollHoldSeconds = "pollHoldSeconds" in value ? value.pollHoldSeconds : void 0;
|
|
12609
|
+
const frameMaxBytes = "frameMaxBytes" in value ? value.frameMaxBytes : void 0;
|
|
12610
|
+
return typeof pollHoldSeconds === "number" && pollHoldSeconds >= 0 && typeof frameMaxBytes === "number" && frameMaxBytes > 0 ? { pollHoldSeconds, frameMaxBytes } : void 0;
|
|
12611
|
+
}
|
|
12612
|
+
function inputsIn(answer) {
|
|
12613
|
+
if (!Array.isArray(answer.commands)) return [];
|
|
12614
|
+
return answer.commands.flatMap((command) => command && typeof command === "object" && "type" in command && command.type === "input" && "d" in command && typeof command.d === "string" ? [command.d] : []);
|
|
12229
12615
|
}
|
|
12230
12616
|
|
|
12231
12617
|
// src/adapters/cli/termCommand.ts
|
|
@@ -12238,7 +12624,8 @@ var TERM_HELP_LINES = [
|
|
|
12238
12624
|
" ainecto term wait <name> --match REGEX [--timeout SECONDS] [--lines N] [--scrollback] until a screen line matches",
|
|
12239
12625
|
` ainecto term attach <name> watch and type in your terminal; detach with ${DETACH_HINT}`,
|
|
12240
12626
|
" ainecto term kill <name> \xB7 ainecto term kill-server",
|
|
12241
|
-
" ainecto term restore [--json] start again the sessions that were running when the daemon or the machine stopped"
|
|
12627
|
+
" ainecto term restore [--json] start again the sessions that were running when the daemon or the machine stopped",
|
|
12628
|
+
" ainecto term remote <name> show the session in AiNecto on the web (plain text) and type there (signed in; Ctrl+C to stop; log: ~/.ainecto/term/remote.log)"
|
|
12242
12629
|
];
|
|
12243
12630
|
async function executeTermCommand(input) {
|
|
12244
12631
|
const [action, ...rest] = input.argv;
|
|
@@ -12294,8 +12681,45 @@ async function executeTermCommand(input) {
|
|
|
12294
12681
|
case "daemon":
|
|
12295
12682
|
return await daemonCommand(paths, rest);
|
|
12296
12683
|
default:
|
|
12297
|
-
throw usage(`term new|ls|send|key|read|wait|attach|kill|kill-server|restore \u2014 see ainecto --help`);
|
|
12684
|
+
throw usage(`term new|ls|send|key|read|wait|attach|kill|kill-server|restore|remote \u2014 see ainecto --help`);
|
|
12685
|
+
}
|
|
12686
|
+
}
|
|
12687
|
+
async function executeTermRemote(input) {
|
|
12688
|
+
const name = singleName(parseArgs(input.argv, {}).positionals, "term remote <name>");
|
|
12689
|
+
const paths = termPaths();
|
|
12690
|
+
await ensurePrivateDir(paths.dir);
|
|
12691
|
+
const log = openRemoteLog(paths);
|
|
12692
|
+
const host = hostname();
|
|
12693
|
+
log.write({ event: "remote_start", pid: process.pid, version: CLI_VERSION_LABEL, endpoint: input.endpoint, host, session: name });
|
|
12694
|
+
const controller = new AbortController();
|
|
12695
|
+
const onSignal = () => controller.abort();
|
|
12696
|
+
process.once("SIGINT", onSignal);
|
|
12697
|
+
process.once("SIGTERM", onSignal);
|
|
12698
|
+
let result;
|
|
12699
|
+
try {
|
|
12700
|
+
result = await runRemote({
|
|
12701
|
+
paths,
|
|
12702
|
+
session: name,
|
|
12703
|
+
http: createRemoteHttp({ endpoint: input.endpoint, tokenProvider: input.auth, log }),
|
|
12704
|
+
log,
|
|
12705
|
+
hostName: host,
|
|
12706
|
+
cliVersion: CLI_VERSION_LABEL,
|
|
12707
|
+
signal: controller.signal,
|
|
12708
|
+
print: (line) => input.io.stderr.write(`${line}
|
|
12709
|
+
`)
|
|
12710
|
+
});
|
|
12711
|
+
} catch (error) {
|
|
12712
|
+
log.write({ event: "remote_stop", pid: process.pid, reason: `error: ${error instanceof Error ? error.message : String(error)}` });
|
|
12713
|
+
throw error;
|
|
12714
|
+
} finally {
|
|
12715
|
+
process.off("SIGINT", onSignal);
|
|
12716
|
+
process.off("SIGTERM", onSignal);
|
|
12717
|
+
}
|
|
12718
|
+
log.write({ event: "remote_stop", pid: process.pid, reason: result.reason, exitCode: result.exitCode });
|
|
12719
|
+
if (result.exitCode !== 0) {
|
|
12720
|
+
throw new TermError("TERM_REMOTE_FAILED", result.reason);
|
|
12298
12721
|
}
|
|
12722
|
+
return print(input, result, result.reason);
|
|
12299
12723
|
}
|
|
12300
12724
|
async function newSession(paths, argv, input) {
|
|
12301
12725
|
const args = parseArgs(argv, { cwd: "string" });
|
|
@@ -12316,7 +12740,7 @@ async function listSessions(paths, argv, input) {
|
|
|
12316
12740
|
parseArgs(argv, {});
|
|
12317
12741
|
const result = await termRequest(paths, { op: "ls" }, { start: false });
|
|
12318
12742
|
const data = result.daemon ? result.data : { sessions: [] };
|
|
12319
|
-
const sessions =
|
|
12743
|
+
const sessions = listedSessions(data);
|
|
12320
12744
|
const human = sessions.length === 0 ? "No term sessions." : renderTable(sessions.map((session) => ({
|
|
12321
12745
|
name: session.name,
|
|
12322
12746
|
pid: session.pid,
|
|
@@ -12463,9 +12887,6 @@ function print(input, data, human) {
|
|
|
12463
12887
|
`);
|
|
12464
12888
|
return 0;
|
|
12465
12889
|
}
|
|
12466
|
-
function noSession(name) {
|
|
12467
|
-
return new TermError("TERM_NO_SESSION", `No session named "${name}" (no term sessions are running).`);
|
|
12468
|
-
}
|
|
12469
12890
|
function usage(text) {
|
|
12470
12891
|
return new TermError("TERM_USAGE", `Usage: ainecto ${text}`);
|
|
12471
12892
|
}
|
|
@@ -12525,19 +12946,6 @@ function singleName(positionals, usageText) {
|
|
|
12525
12946
|
function countFlag(value) {
|
|
12526
12947
|
return typeof value === "number" ? value : void 0;
|
|
12527
12948
|
}
|
|
12528
|
-
function sessionsField(data) {
|
|
12529
|
-
if (data && typeof data === "object" && "sessions" in data && Array.isArray(data.sessions)) {
|
|
12530
|
-
return data.sessions.filter(isListedSession);
|
|
12531
|
-
}
|
|
12532
|
-
return [];
|
|
12533
|
-
}
|
|
12534
|
-
function isListedSession(value) {
|
|
12535
|
-
if (!value || typeof value !== "object") {
|
|
12536
|
-
return false;
|
|
12537
|
-
}
|
|
12538
|
-
const session = value;
|
|
12539
|
-
return typeof session.name === "string" && typeof session.pid === "number" && typeof session.cwd === "string";
|
|
12540
|
-
}
|
|
12541
12949
|
function linesField(data) {
|
|
12542
12950
|
if (data && typeof data === "object" && "lines" in data && Array.isArray(data.lines)) {
|
|
12543
12951
|
return data.lines.filter((line) => typeof line === "string");
|
|
@@ -12548,9 +12956,9 @@ function resetField(data) {
|
|
|
12548
12956
|
return data && typeof data === "object" && "reset" in data && typeof data.reset === "string" ? data.reset : void 0;
|
|
12549
12957
|
}
|
|
12550
12958
|
function restoreSummary(data) {
|
|
12551
|
-
const
|
|
12552
|
-
const names = (key) => Array.isArray(
|
|
12553
|
-
const failed = Array.isArray(
|
|
12959
|
+
const record2 = data && typeof data === "object" ? data : {};
|
|
12960
|
+
const names = (key) => Array.isArray(record2[key]) ? record2[key].filter((item) => typeof item === "string") : [];
|
|
12961
|
+
const failed = Array.isArray(record2.failed) ? record2.failed : [];
|
|
12554
12962
|
const parts = [
|
|
12555
12963
|
names("restored").length ? `Restored: ${names("restored").join(", ")}` : "",
|
|
12556
12964
|
names("running").length ? `Already running: ${names("running").join(", ")}` : "",
|
|
@@ -12563,10 +12971,11 @@ function restoreSummary(data) {
|
|
|
12563
12971
|
}
|
|
12564
12972
|
|
|
12565
12973
|
// src/adapters/cli/agentCommand.ts
|
|
12566
|
-
import { hostname } from "os";
|
|
12974
|
+
import { hostname as hostname2 } from "os";
|
|
12567
12975
|
|
|
12568
12976
|
// src/core/agent/agents.ts
|
|
12569
12977
|
var AGENT_IDS = ["claude-code", "codex"];
|
|
12978
|
+
var AGENT_MCP_CLIENT_NAMES = { "claude-code": "claude-code", codex: "codex-mcp-client" };
|
|
12570
12979
|
var DEFAULT_AGENT = "claude-code";
|
|
12571
12980
|
function isAgentId(value) {
|
|
12572
12981
|
return typeof value === "string" && AGENT_IDS.includes(value);
|
|
@@ -12580,8 +12989,8 @@ function agentReplySchema(textMaxCharacters) {
|
|
|
12580
12989
|
};
|
|
12581
12990
|
}
|
|
12582
12991
|
var AINECTO_MCP_SERVER = "ainecto";
|
|
12583
|
-
function ainectoBridge(nodePath, cliScript, endpoint) {
|
|
12584
|
-
return { command: nodePath, args: [cliScript, "--endpoint", endpoint, "mcp"] };
|
|
12992
|
+
function ainectoBridge(nodePath, cliScript, endpoint, agentName) {
|
|
12993
|
+
return { command: nodePath, args: [cliScript, "--endpoint", endpoint, "mcp", ...agentName ? ["--agent", agentName] : []] };
|
|
12585
12994
|
}
|
|
12586
12995
|
function agentEnv(env) {
|
|
12587
12996
|
const out = { ...env };
|
|
@@ -12861,7 +13270,13 @@ function claudeCodeAdapter(deps) {
|
|
|
12861
13270
|
}
|
|
12862
13271
|
return claudeAuthFromJson(run.stdout, run.code, run.stderrTail, hasApiKeyVariable(deps.env));
|
|
12863
13272
|
},
|
|
12864
|
-
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new ClaudeCodeSession(
|
|
13273
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new ClaudeCodeSession(
|
|
13274
|
+
conversationUuid,
|
|
13275
|
+
resumeRef,
|
|
13276
|
+
agentName,
|
|
13277
|
+
deps.args({ textMaxCharacters, resumeSessionId: resumeRef, agentName }),
|
|
13278
|
+
deps
|
|
13279
|
+
)
|
|
12865
13280
|
};
|
|
12866
13281
|
}
|
|
12867
13282
|
function hasApiKeyVariable(env) {
|
|
@@ -12887,8 +13302,9 @@ function claudeAuthFromJson(stdout, code, stderrTail, apiKeyVariable) {
|
|
|
12887
13302
|
};
|
|
12888
13303
|
}
|
|
12889
13304
|
var ClaudeCodeSession = class {
|
|
12890
|
-
constructor(conversationUuid, resumeRef, args, deps) {
|
|
13305
|
+
constructor(conversationUuid, resumeRef, agentName, args, deps) {
|
|
12891
13306
|
this.conversationUuid = conversationUuid;
|
|
13307
|
+
this.agentName = agentName;
|
|
12892
13308
|
this.deps = deps;
|
|
12893
13309
|
this.resumed = resumeRef !== void 0;
|
|
12894
13310
|
this.child = new AgentChild(deps.spawnImpl, CLAUDE, args, { cwd: deps.cwd, env: deps.env }, {
|
|
@@ -12898,6 +13314,7 @@ var ClaudeCodeSession = class {
|
|
|
12898
13314
|
deps.log.write({ event: "process_start", pid: this.child.pid, agent: this.agent, conversationUuid, resume: this.resumed });
|
|
12899
13315
|
}
|
|
12900
13316
|
conversationUuid;
|
|
13317
|
+
agentName;
|
|
12901
13318
|
deps;
|
|
12902
13319
|
agent = "claude-code";
|
|
12903
13320
|
resumed;
|
|
@@ -13113,7 +13530,7 @@ function codexAdapter(deps) {
|
|
|
13113
13530
|
await server.child.stop();
|
|
13114
13531
|
}
|
|
13115
13532
|
},
|
|
13116
|
-
open: ({ conversationUuid, resumeRef, textMaxCharacters }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, deps)
|
|
13533
|
+
open: ({ conversationUuid, resumeRef, textMaxCharacters, agentName }) => new CodexSession(conversationUuid, resumeRef, textMaxCharacters, agentName, deps)
|
|
13117
13534
|
};
|
|
13118
13535
|
}
|
|
13119
13536
|
var CodexRpc = class {
|
|
@@ -13213,12 +13630,13 @@ function startAppServer(deps, args, hooks) {
|
|
|
13213
13630
|
return { child, rpc };
|
|
13214
13631
|
}
|
|
13215
13632
|
var CodexSession = class {
|
|
13216
|
-
constructor(conversationUuid, resumeRef, textMaxCharacters, deps) {
|
|
13633
|
+
constructor(conversationUuid, resumeRef, textMaxCharacters, agentName, deps) {
|
|
13217
13634
|
this.conversationUuid = conversationUuid;
|
|
13218
13635
|
this.textMaxCharacters = textMaxCharacters;
|
|
13636
|
+
this.agentName = agentName;
|
|
13219
13637
|
this.deps = deps;
|
|
13220
13638
|
this.resumed = resumeRef !== void 0;
|
|
13221
|
-
const server = startAppServer(deps, deps.appServerArgs, {
|
|
13639
|
+
const server = startAppServer(deps, deps.appServerArgs(agentName), {
|
|
13222
13640
|
notification: (method, params) => this.onNotification(method, params),
|
|
13223
13641
|
exit: (exit) => this.onExit(exit)
|
|
13224
13642
|
});
|
|
@@ -13229,6 +13647,7 @@ var CodexSession = class {
|
|
|
13229
13647
|
}
|
|
13230
13648
|
conversationUuid;
|
|
13231
13649
|
textMaxCharacters;
|
|
13650
|
+
agentName;
|
|
13232
13651
|
deps;
|
|
13233
13652
|
agent = "codex";
|
|
13234
13653
|
resumed;
|
|
@@ -13375,102 +13794,129 @@ function toError(error) {
|
|
|
13375
13794
|
}
|
|
13376
13795
|
|
|
13377
13796
|
// src/core/agent/http.ts
|
|
13378
|
-
|
|
13379
|
-
var AgentCallError = class extends Error {
|
|
13797
|
+
var AgentCallError = class extends PcCallError {
|
|
13380
13798
|
constructor(message, op, status, code) {
|
|
13799
|
+
super(message, op, status, code);
|
|
13800
|
+
this.name = "AgentCallError";
|
|
13801
|
+
}
|
|
13802
|
+
};
|
|
13803
|
+
function createAgentHttp(input) {
|
|
13804
|
+
const http = createPcHttp({
|
|
13805
|
+
endpoint: input.endpoint,
|
|
13806
|
+
path: "agent/pc",
|
|
13807
|
+
tokenProvider: input.tokenProvider,
|
|
13808
|
+
timeoutMs: AGENT_CALL_TIMEOUT_MS,
|
|
13809
|
+
sessionHeader: "X-Link-Token",
|
|
13810
|
+
error: (message, op, status, code) => new AgentCallError(message, op, status, code),
|
|
13811
|
+
fetchImpl: input.fetchImpl,
|
|
13812
|
+
logging: {
|
|
13813
|
+
log: input.log,
|
|
13814
|
+
request: ({ callId, op, bytes }, options) => ({ event: "agent_call", callId, op, turnUuid: options?.turnUuid, bytes }),
|
|
13815
|
+
response: ({ callId, op, ms }, outcome) => ({
|
|
13816
|
+
event: "agent_call_response",
|
|
13817
|
+
callId,
|
|
13818
|
+
op,
|
|
13819
|
+
...outcome.ok ? { ok: true, status: outcome.status, offers: Array.isArray(outcome.body.offers) ? outcome.body.offers.length : void 0 } : outcome,
|
|
13820
|
+
ms
|
|
13821
|
+
})
|
|
13822
|
+
}
|
|
13823
|
+
});
|
|
13824
|
+
return { call: http.call, useLinkToken: http.useSessionToken };
|
|
13825
|
+
}
|
|
13826
|
+
|
|
13827
|
+
// src/core/agent/tools.ts
|
|
13828
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
13829
|
+
var TOOL_PREFIX = "mcp__ainecto__";
|
|
13830
|
+
var AgentToolError = class extends Error {
|
|
13831
|
+
constructor(message, tool, code, retryable = false) {
|
|
13381
13832
|
super(message);
|
|
13382
|
-
this.
|
|
13383
|
-
this.status = status;
|
|
13833
|
+
this.tool = tool;
|
|
13384
13834
|
this.code = code;
|
|
13385
|
-
this.
|
|
13835
|
+
this.retryable = retryable;
|
|
13836
|
+
this.name = "AgentToolError";
|
|
13386
13837
|
}
|
|
13387
|
-
|
|
13388
|
-
status;
|
|
13838
|
+
tool;
|
|
13389
13839
|
code;
|
|
13390
|
-
|
|
13391
|
-
get retryable() {
|
|
13392
|
-
return this.status === void 0 || this.status >= 500 || this.status === 429;
|
|
13393
|
-
}
|
|
13840
|
+
retryable;
|
|
13394
13841
|
};
|
|
13395
|
-
function
|
|
13396
|
-
const
|
|
13397
|
-
const
|
|
13398
|
-
|
|
13399
|
-
|
|
13400
|
-
|
|
13401
|
-
|
|
13402
|
-
|
|
13403
|
-
(
|
|
13404
|
-
|
|
13405
|
-
|
|
13406
|
-
|
|
13407
|
-
|
|
13408
|
-
|
|
13409
|
-
|
|
13842
|
+
function createAgentTools(input) {
|
|
13843
|
+
const asClients = /* @__PURE__ */ new Map();
|
|
13844
|
+
const clientFor = (identity) => {
|
|
13845
|
+
if (!identity || !input.clientAs) return input.client;
|
|
13846
|
+
const key = `${identity.agent}\0${identity.name}`;
|
|
13847
|
+
let found = asClients.get(key);
|
|
13848
|
+
if (!found) {
|
|
13849
|
+
found = input.clientAs(identity);
|
|
13850
|
+
asClients.set(key, found);
|
|
13851
|
+
}
|
|
13852
|
+
return found;
|
|
13853
|
+
};
|
|
13854
|
+
async function logged(tool, bytes, run, as) {
|
|
13855
|
+
const callId = randomUUID3();
|
|
13856
|
+
const started = Date.now();
|
|
13857
|
+
input.log.write({ event: "agent_call", callId, op: "tool", tool, ...as ? { agent: as.agent, agentName: as.name } : {}, bytes });
|
|
13858
|
+
let outcome = { ok: false, error: "no response" };
|
|
13410
13859
|
try {
|
|
13411
|
-
const
|
|
13412
|
-
|
|
13413
|
-
return
|
|
13860
|
+
const value = await run();
|
|
13861
|
+
outcome = { ok: true };
|
|
13862
|
+
return value;
|
|
13414
13863
|
} catch (error) {
|
|
13415
|
-
|
|
13864
|
+
const failure2 = toToolError(tool, error);
|
|
13865
|
+
outcome = { ok: false, ...failure2.code ? { code: failure2.code } : {}, error: failure2.message };
|
|
13866
|
+
throw failure2;
|
|
13416
13867
|
} finally {
|
|
13417
|
-
|
|
13418
|
-
options.signal?.removeEventListener("abort", onStop);
|
|
13868
|
+
input.log.write({ event: "agent_call_response", callId, op: "tool", tool, ...outcome, ms: Date.now() - started });
|
|
13419
13869
|
}
|
|
13420
13870
|
}
|
|
13421
13871
|
return {
|
|
13422
|
-
|
|
13423
|
-
|
|
13872
|
+
call(tool, args, options = {}) {
|
|
13873
|
+
return logged(tool, Buffer.byteLength(JSON.stringify(args), "utf8"), async () => {
|
|
13874
|
+
const raw = await clientFor(options.as).toolsCall(TOOL_PREFIX + tool, args);
|
|
13875
|
+
if (isToolError(raw)) throw new AgentToolError(toolErrorText(raw), tool, codeInText(toolErrorText(raw)));
|
|
13876
|
+
const payload = unwrapMcpToolPayload(raw);
|
|
13877
|
+
if (!isRecord13(payload)) throw new AgentToolError(`${tool} did not return an object.`, tool, "MCP_PROTOCOL_ERROR");
|
|
13878
|
+
return payload;
|
|
13879
|
+
}, options.as);
|
|
13424
13880
|
},
|
|
13425
|
-
|
|
13426
|
-
|
|
13427
|
-
const payload = JSON.stringify(body);
|
|
13428
|
-
const started = Date.now();
|
|
13429
|
-
input.log.write({ event: "agent_call", callId, op, turnUuid: options.turnUuid, bytes: Buffer.byteLength(payload, "utf8") });
|
|
13430
|
-
let outcome = {
|
|
13431
|
-
ok: false,
|
|
13432
|
-
error: "no response"
|
|
13433
|
-
};
|
|
13434
|
-
try {
|
|
13435
|
-
let response = await send(op, payload, await input.tokenProvider.getAccessToken(), options);
|
|
13436
|
-
if (response.status === 401) {
|
|
13437
|
-
response = await send(op, payload, await input.tokenProvider.refreshAfterUnauthorized(), options);
|
|
13438
|
-
}
|
|
13439
|
-
const text = await response.text();
|
|
13440
|
-
const parsed = parseJson2(text);
|
|
13441
|
-
if (!response.ok) {
|
|
13442
|
-
const code = typeof parsed?.code === "string" ? parsed.code : void 0;
|
|
13443
|
-
outcome = { ok: false, status: response.status, code };
|
|
13444
|
-
throw new AgentCallError(
|
|
13445
|
-
typeof parsed?.detail === "string" ? parsed.detail : `HTTP ${response.status}`,
|
|
13446
|
-
op,
|
|
13447
|
-
response.status,
|
|
13448
|
-
code
|
|
13449
|
-
);
|
|
13450
|
-
}
|
|
13451
|
-
const offers = Array.isArray(parsed?.offers) ? parsed.offers.length : void 0;
|
|
13452
|
-
outcome = { ok: true, status: response.status, offers };
|
|
13453
|
-
return parsed ?? {};
|
|
13454
|
-
} catch (error) {
|
|
13455
|
-
if (error instanceof AgentCallError) throw error;
|
|
13456
|
-
const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
|
|
13457
|
-
outcome = { ok: false, error: timedOut ? error.name : error instanceof Error ? error.message : String(error) };
|
|
13458
|
-
throw new AgentCallError(timedOut ? `${op} timed out` : `${op} failed: ${outcome.error}`, op);
|
|
13459
|
-
} finally {
|
|
13460
|
-
input.log.write({ event: "agent_call_response", callId, op, ...outcome, ms: Date.now() - started });
|
|
13461
|
-
}
|
|
13881
|
+
list() {
|
|
13882
|
+
return logged("tools/list", 0, () => input.client.toolsList());
|
|
13462
13883
|
}
|
|
13463
13884
|
};
|
|
13464
13885
|
}
|
|
13465
|
-
function
|
|
13466
|
-
|
|
13886
|
+
function toolsAs(tools, identity) {
|
|
13887
|
+
return {
|
|
13888
|
+
call: (tool, args, options) => tools.call(tool, args, { as: identity, ...options }),
|
|
13889
|
+
list: () => tools.list()
|
|
13890
|
+
};
|
|
13891
|
+
}
|
|
13892
|
+
function toToolError(tool, error) {
|
|
13893
|
+
if (error instanceof AgentToolError) return error;
|
|
13894
|
+
if (error instanceof McpRpcError) {
|
|
13895
|
+
const details = isRecord13(error.details) ? error.details : {};
|
|
13896
|
+
const data = isRecord13(details.data) ? details.data : {};
|
|
13897
|
+
const status = typeof details.status === "number" ? details.status : void 0;
|
|
13898
|
+
const code = typeof data.code === "string" ? data.code : typeof details.error === "string" ? details.error : error.code;
|
|
13899
|
+
const rpcCode = typeof details.code === "number" ? details.code : void 0;
|
|
13900
|
+
return new AgentToolError(
|
|
13901
|
+
error.message,
|
|
13902
|
+
tool,
|
|
13903
|
+
code,
|
|
13904
|
+
status !== void 0 && status >= 500 || rpcCode !== void 0 && (rpcCode >= 500 || rpcCode === -32603)
|
|
13905
|
+
);
|
|
13906
|
+
}
|
|
13907
|
+
return new AgentToolError(error instanceof Error ? error.message : String(error), tool, void 0, true);
|
|
13908
|
+
}
|
|
13909
|
+
function codeInText(text) {
|
|
13467
13910
|
try {
|
|
13468
|
-
const
|
|
13469
|
-
return
|
|
13911
|
+
const parsed = JSON.parse(text);
|
|
13912
|
+
return isRecord13(parsed) && typeof parsed.code === "string" ? parsed.code : void 0;
|
|
13470
13913
|
} catch {
|
|
13471
13914
|
return void 0;
|
|
13472
13915
|
}
|
|
13473
13916
|
}
|
|
13917
|
+
function isRecord13(value) {
|
|
13918
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13919
|
+
}
|
|
13474
13920
|
|
|
13475
13921
|
// src/core/agent/log.ts
|
|
13476
13922
|
function openAgentLog(paths) {
|
|
@@ -13488,13 +13934,73 @@ function agentPaths(home = homedir3()) {
|
|
|
13488
13934
|
dir,
|
|
13489
13935
|
work: join7(dir, "work"),
|
|
13490
13936
|
sessions: join7(dir, "sessions.json"),
|
|
13937
|
+
runs: join7(dir, "runs.json"),
|
|
13491
13938
|
log: join7(dir, "agent.log"),
|
|
13492
13939
|
previousLog: join7(dir, "agent.log.1")
|
|
13493
13940
|
};
|
|
13494
13941
|
}
|
|
13495
13942
|
|
|
13943
|
+
// src/core/agent/runs.ts
|
|
13944
|
+
import { readFile as readFile9, rename as rename6, writeFile as writeFile6 } from "fs/promises";
|
|
13945
|
+
var AgentRunLog = class {
|
|
13946
|
+
constructor(path, log) {
|
|
13947
|
+
this.path = path;
|
|
13948
|
+
this.log = log;
|
|
13949
|
+
}
|
|
13950
|
+
path;
|
|
13951
|
+
log;
|
|
13952
|
+
runs = /* @__PURE__ */ new Map();
|
|
13953
|
+
/** 읽어서 남은 줄을 돌려준다 — 결과는 로그 한 줄. */
|
|
13954
|
+
async load() {
|
|
13955
|
+
let reason;
|
|
13956
|
+
const runs = /* @__PURE__ */ new Map();
|
|
13957
|
+
try {
|
|
13958
|
+
const parsed = JSON.parse(await readFile9(this.path, "utf8"));
|
|
13959
|
+
for (const value of Array.isArray(parsed.runs) ? parsed.runs : []) {
|
|
13960
|
+
const e = value ?? {};
|
|
13961
|
+
if (typeof e.cardUuid === "string" && typeof e.startedAt === "string") {
|
|
13962
|
+
runs.set(e.cardUuid, {
|
|
13963
|
+
cardUuid: e.cardUuid,
|
|
13964
|
+
...typeof e.workId === "string" ? { workId: e.workId } : {},
|
|
13965
|
+
...typeof e.agent === "string" ? { agent: e.agent } : {},
|
|
13966
|
+
startedAt: e.startedAt
|
|
13967
|
+
});
|
|
13968
|
+
}
|
|
13969
|
+
}
|
|
13970
|
+
} catch (error) {
|
|
13971
|
+
reason = isNodeError(error, "ENOENT") ? "missing" : `unreadable: ${error instanceof Error ? error.message : String(error)}`;
|
|
13972
|
+
runs.clear();
|
|
13973
|
+
}
|
|
13974
|
+
this.runs = runs;
|
|
13975
|
+
this.log.write({ event: "runs_load", entries: runs.size, ...reason ? { reason } : {} });
|
|
13976
|
+
if (reason?.startsWith("unreadable")) await this.save();
|
|
13977
|
+
return [...runs.values()];
|
|
13978
|
+
}
|
|
13979
|
+
/** 돌기 시작(수락 직후) · 작업이 열리면 workId 를 더한다 — 처음 적은 시각은 그대로. */
|
|
13980
|
+
async started(cardUuid, workId, agent) {
|
|
13981
|
+
const before = this.runs.get(cardUuid);
|
|
13982
|
+
this.runs.set(cardUuid, {
|
|
13983
|
+
cardUuid,
|
|
13984
|
+
...workId ?? before?.workId ? { workId: workId ?? before?.workId } : {},
|
|
13985
|
+
agent,
|
|
13986
|
+
startedAt: before?.startedAt ?? (/* @__PURE__ */ new Date()).toISOString()
|
|
13987
|
+
});
|
|
13988
|
+
await this.save();
|
|
13989
|
+
}
|
|
13990
|
+
async finished(cardUuid) {
|
|
13991
|
+
if (!this.runs.delete(cardUuid)) return;
|
|
13992
|
+
await this.save();
|
|
13993
|
+
}
|
|
13994
|
+
async save() {
|
|
13995
|
+
const tmp = `${this.path}.tmp`;
|
|
13996
|
+
await writeFile6(tmp, `${JSON.stringify({ version: 1, runs: [...this.runs.values()] }, null, 2)}
|
|
13997
|
+
`, { mode: PRIVATE_FILE_MODE });
|
|
13998
|
+
await rename6(tmp, this.path);
|
|
13999
|
+
}
|
|
14000
|
+
};
|
|
14001
|
+
|
|
13496
14002
|
// src/core/agent/readiness.ts
|
|
13497
|
-
import { randomUUID as
|
|
14003
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
13498
14004
|
async function checkAgents(adapters, log) {
|
|
13499
14005
|
return await Promise.all(adapters.map(async (adapter) => {
|
|
13500
14006
|
const detected = await probe(
|
|
@@ -13528,7 +14034,7 @@ function openAgents(checks) {
|
|
|
13528
14034
|
return checks.filter((check) => check.installed).map((check) => ({ id: check.id, ready: check.ready, ...check.auth ? { auth: check.auth } : {} }));
|
|
13529
14035
|
}
|
|
13530
14036
|
async function probe(log, agent, kind, work, summary) {
|
|
13531
|
-
const callId =
|
|
14037
|
+
const callId = randomUUID4();
|
|
13532
14038
|
const started = Date.now();
|
|
13533
14039
|
log.write({ event: "agent_probe", callId, agent, probe: kind });
|
|
13534
14040
|
try {
|
|
@@ -13626,15 +14132,368 @@ function clip(text, max) {
|
|
|
13626
14132
|
return chars.length <= max ? chars.join("") : `${chars.slice(0, max - 1).join("")}\u2026`;
|
|
13627
14133
|
}
|
|
13628
14134
|
|
|
14135
|
+
// src/core/agent/todoRun.ts
|
|
14136
|
+
var TODO_KINDS = ["CARD_ASSIGNED", "DECISION_ANSWERED"];
|
|
14137
|
+
function resumeTodo(entry) {
|
|
14138
|
+
return { todoId: `resume:${entry.cardUuid}`, kind: "RESUME", cardUuid: entry.cardUuid, ...entry.workId ? { workId: entry.workId } : {} };
|
|
14139
|
+
}
|
|
14140
|
+
function todosIn(res) {
|
|
14141
|
+
const raw = Array.isArray(res.items) ? res.items : [];
|
|
14142
|
+
const items = raw.flatMap((value) => {
|
|
14143
|
+
const item = record(value);
|
|
14144
|
+
const target = record(item.target);
|
|
14145
|
+
const kind = item.kind;
|
|
14146
|
+
if (typeof item.todoId !== "string" || !isTodoKind(kind) || target.type !== "KANBAN_CARD" || typeof target.uuid !== "string") {
|
|
14147
|
+
return [];
|
|
14148
|
+
}
|
|
14149
|
+
return [{
|
|
14150
|
+
todoId: item.todoId,
|
|
14151
|
+
kind,
|
|
14152
|
+
cardUuid: target.uuid,
|
|
14153
|
+
...typeof target.commentId === "number" ? { commentId: target.commentId } : {}
|
|
14154
|
+
}];
|
|
14155
|
+
});
|
|
14156
|
+
const last = raw.length > 0 ? record(raw[raw.length - 1]).todoId : void 0;
|
|
14157
|
+
return { items, ...res.hasMore === true && typeof last === "string" ? { next: last } : {} };
|
|
14158
|
+
}
|
|
14159
|
+
function isTodoKind(value) {
|
|
14160
|
+
return typeof value === "string" && TODO_KINDS.includes(value);
|
|
14161
|
+
}
|
|
14162
|
+
function renewDelayMs(claimExpiresAt, nowMs) {
|
|
14163
|
+
if (typeof claimExpiresAt !== "string") return void 0;
|
|
14164
|
+
const at = Date.parse(claimExpiresAt);
|
|
14165
|
+
if (!Number.isFinite(at)) return void 0;
|
|
14166
|
+
return Math.max(0, Math.floor((at - nowMs) / 2));
|
|
14167
|
+
}
|
|
14168
|
+
function cardFactsOf(detail) {
|
|
14169
|
+
const d = record(detail);
|
|
14170
|
+
const card = record(d.card);
|
|
14171
|
+
if (typeof card.uuid !== "string" || typeof card.status !== "string") {
|
|
14172
|
+
throw new AgentToolError("The card detail has no uuid or status.", "kanban_list_cards", "MCP_PROTOCOL_ERROR");
|
|
14173
|
+
}
|
|
14174
|
+
const work = record(d.work);
|
|
14175
|
+
const owner = record(card.assignee);
|
|
14176
|
+
return {
|
|
14177
|
+
uuid: card.uuid,
|
|
14178
|
+
...typeof card.key === "string" ? { key: card.key } : {},
|
|
14179
|
+
title: str2(card.title),
|
|
14180
|
+
...typeof d.boardUuid === "string" ? { boardUuid: d.boardUuid } : {},
|
|
14181
|
+
status: card.status,
|
|
14182
|
+
...typeof card.assignmentState === "string" ? { assignmentState: card.assignmentState } : {},
|
|
14183
|
+
blocked: card.blocked === true,
|
|
14184
|
+
...typeof d.description === "string" && d.description.trim() ? { description: d.description } : {},
|
|
14185
|
+
criteria: (Array.isArray(d.criteria) ? d.criteria : []).flatMap((c) => {
|
|
14186
|
+
const v = record(c);
|
|
14187
|
+
return typeof v.text === "string" ? [{ text: v.text, done: v.done === true }] : [];
|
|
14188
|
+
}),
|
|
14189
|
+
...typeof owner.userId === "string" ? { ownerUserId: owner.userId } : {},
|
|
14190
|
+
...typeof work.workId === "string" ? { workId: work.workId } : {}
|
|
14191
|
+
};
|
|
14192
|
+
}
|
|
14193
|
+
function answerComments(listed, commentId) {
|
|
14194
|
+
const all = (Array.isArray(listed.comments) ? listed.comments : []).map(record).filter((c) => typeof c.id === "number");
|
|
14195
|
+
const rootOf = (c) => typeof c.rootCommentId === "number" ? c.rootCommentId : typeof c.parentCommentId === "number" ? c.parentCommentId : c.id;
|
|
14196
|
+
const roots = /* @__PURE__ */ new Set();
|
|
14197
|
+
const pointed = all.find((c) => c.id === commentId);
|
|
14198
|
+
if (pointed) roots.add(rootOf(pointed));
|
|
14199
|
+
for (const c of all) {
|
|
14200
|
+
if (c.kind === "QUESTION" && c.questionState !== "RESOLVED" && c.parentCommentId == null) roots.add(c.id);
|
|
14201
|
+
}
|
|
14202
|
+
return all.filter((c) => roots.has(rootOf(c))).map((c) => ({
|
|
14203
|
+
id: c.id,
|
|
14204
|
+
author: str2(record(c.author).displayName) || "?",
|
|
14205
|
+
kind: str2(c.kind) || "COMMENT",
|
|
14206
|
+
body: str2(c.body),
|
|
14207
|
+
...typeof c.questionState === "string" ? { questionState: c.questionState } : {}
|
|
14208
|
+
}));
|
|
14209
|
+
}
|
|
14210
|
+
var PROMPT_HEADS = {
|
|
14211
|
+
CARD_ASSIGNED: "[AiNecto auto-run] The person handed you this kanban card with auto-run. Do the work with the AiNecto tools.",
|
|
14212
|
+
DECISION_ANSWERED: "[AiNecto auto-run \u2014 continue] The person answered on this card (or asked for changes). Continue the same work.",
|
|
14213
|
+
RESUME: "[AiNecto auto-run \u2014 resume] This machine stopped while you were working this card. Continue the same work: first check what is already done with report_work_progress (CHECKPOINT)."
|
|
14214
|
+
};
|
|
14215
|
+
function todoPromptText(input) {
|
|
14216
|
+
const { card, workId } = input;
|
|
14217
|
+
const owner = card.ownerUserId ?? "the card's assignee";
|
|
14218
|
+
const lines = [
|
|
14219
|
+
PROMPT_HEADS[input.kind],
|
|
14220
|
+
"",
|
|
14221
|
+
`Card \xAB${card.title}\xBB (${card.key ? `${card.key}, ` : ""}cardUuid ${card.uuid}${card.boardUuid ? `, boardUuid ${card.boardUuid}` : ""}) \xB7 status ${card.status}${card.blocked ? " \xB7 blocked" : ""}`,
|
|
14222
|
+
`AI work: workId ${workId} \u2014 send this workId with every AiNecto call for this card and report each step with report_work_progress (read each response before going on).`
|
|
14223
|
+
];
|
|
14224
|
+
if (card.description) lines.push("", "Description:", card.description);
|
|
14225
|
+
if (card.criteria.length > 0) {
|
|
14226
|
+
lines.push("", "Done criteria:", ...card.criteria.map((c) => `- [${c.done ? "x" : " "}] ${c.text}`));
|
|
14227
|
+
}
|
|
14228
|
+
if (input.answers.length > 0) {
|
|
14229
|
+
lines.push(
|
|
14230
|
+
"",
|
|
14231
|
+
"Comments to read (oldest first):",
|
|
14232
|
+
...input.answers.map((a) => `- #${a.id} ${a.kind}${a.questionState ? ` (${a.questionState})` : ""} by ${a.author}: ${a.body}`)
|
|
14233
|
+
);
|
|
14234
|
+
lines.push("", `First read them: report_work_progress (it lists the comments to read \u2014 send \`read\` with its checkId), resolve_comments for the questions that are answered, and if the card is blocked, kanban_card_action {cardUuid: "${card.uuid}", action: "unblock"}. Then continue the work.`);
|
|
14235
|
+
}
|
|
14236
|
+
lines.push(
|
|
14237
|
+
"",
|
|
14238
|
+
"If you need the person's decision, do not guess. Ask and stop:",
|
|
14239
|
+
`1) create_comments {cardUuid: "${card.uuid}", workId: "${workId}", items: [{kind: "QUESTION", body: <your question>}]}`,
|
|
14240
|
+
`2) kanban_card_action {cardUuid: "${card.uuid}", action: "block", reason: <one line>, responderIds: ["${owner}"]}`,
|
|
14241
|
+
`3) report_work_progress {workId: "${workId}", stepId: <the step>, status: "BLOCKED"}`,
|
|
14242
|
+
"Then answer with what you asked. You will be called again on this card when they answer.",
|
|
14243
|
+
"",
|
|
14244
|
+
"Do not request review, approve, or finish the card yourself \u2014 this PC posts your answer as the result and asks the person to review it.",
|
|
14245
|
+
"Do not call finish_work: the AI work stays open until the person approves the result (finishing it early blocks the hand-over).",
|
|
14246
|
+
"Your answer (reply) is shown to the person in this card's auto-run conversation: say what you did, or what you asked."
|
|
14247
|
+
);
|
|
14248
|
+
return lines.join("\n");
|
|
14249
|
+
}
|
|
14250
|
+
async function runTodo(deps, todo) {
|
|
14251
|
+
const started = Date.now();
|
|
14252
|
+
deps.log.write({ event: "todo_run", todoId: todo.todoId, kind: todo.kind, cardUuid: todo.cardUuid });
|
|
14253
|
+
let outcome;
|
|
14254
|
+
let workId;
|
|
14255
|
+
let conversationUuid;
|
|
14256
|
+
let failure2;
|
|
14257
|
+
let warning;
|
|
14258
|
+
try {
|
|
14259
|
+
const ends = async (value) => {
|
|
14260
|
+
outcome = value;
|
|
14261
|
+
if (value !== "stopped") await deps.runs?.finished(todo.cardUuid);
|
|
14262
|
+
return value;
|
|
14263
|
+
};
|
|
14264
|
+
let card = await readCard(deps.tools, todo.cardUuid);
|
|
14265
|
+
if (todo.kind === "RESUME" && !resumable(card, todo.workId)) return await ends("not_runnable");
|
|
14266
|
+
if (todo.kind === "CARD_ASSIGNED" && card.assignmentState === "PENDING") {
|
|
14267
|
+
card = await act(deps.tools, card.uuid, "accept");
|
|
14268
|
+
await deps.runs?.started(card.uuid);
|
|
14269
|
+
}
|
|
14270
|
+
if (todo.kind !== "DECISION_ANSWERED" && card.status === "TODO") card = await act(deps.tools, card.uuid, "start");
|
|
14271
|
+
if (card.status !== "IN_PROGRESS") return await ends("not_runnable");
|
|
14272
|
+
workId = card.workId ?? await startWork(deps.tools, card.uuid);
|
|
14273
|
+
if (todo.kind !== "DECISION_ANSWERED") await deps.runs?.started(card.uuid, workId);
|
|
14274
|
+
conversationUuid = await postToRun(deps, card.uuid, workId, OPENINGS[todo.kind](card.title));
|
|
14275
|
+
const answers = todo.kind === "DECISION_ANSWERED" ? answerComments(await deps.tools.call("list_comments", { cardUuid: card.uuid, workId }), todo.commentId) : [];
|
|
14276
|
+
if (deps.signal.aborted) {
|
|
14277
|
+
outcome = "stopped";
|
|
14278
|
+
return outcome;
|
|
14279
|
+
}
|
|
14280
|
+
const reply = await deps.runAgent({
|
|
14281
|
+
todoId: todo.todoId,
|
|
14282
|
+
conversationUuid,
|
|
14283
|
+
text: todoPromptText({ kind: todo.kind, card, workId, answers })
|
|
14284
|
+
});
|
|
14285
|
+
if (deps.signal.aborted) {
|
|
14286
|
+
outcome = "stopped";
|
|
14287
|
+
return outcome;
|
|
14288
|
+
}
|
|
14289
|
+
await postToRun(deps, card.uuid, workId, reply.reply);
|
|
14290
|
+
if (reply.status !== "DONE") return await ends("agent_failed");
|
|
14291
|
+
const after = await readCard(deps.tools, card.uuid, workId);
|
|
14292
|
+
if (after.blocked) return await ends("decision_requested");
|
|
14293
|
+
if (after.status !== "IN_PROGRESS") return await ends("not_runnable");
|
|
14294
|
+
warning = await handOverResult(deps, after, workId, reply.reply);
|
|
14295
|
+
return await ends("review_requested");
|
|
14296
|
+
} catch (error) {
|
|
14297
|
+
failure2 = error instanceof Error ? error : new Error(String(error));
|
|
14298
|
+
throw error;
|
|
14299
|
+
} finally {
|
|
14300
|
+
deps.log.write({
|
|
14301
|
+
event: "todo_run_result",
|
|
14302
|
+
todoId: todo.todoId,
|
|
14303
|
+
kind: todo.kind,
|
|
14304
|
+
cardUuid: todo.cardUuid,
|
|
14305
|
+
outcome: outcome ?? `error: ${failure2?.message ?? "unknown"}`,
|
|
14306
|
+
...warning ? { warning } : {},
|
|
14307
|
+
...failure2 instanceof AgentToolError ? { tool: failure2.tool, ...failure2.code ? { code: failure2.code } : {} } : {},
|
|
14308
|
+
...workId ? { workId } : {},
|
|
14309
|
+
...conversationUuid ? { conversationUuid } : {},
|
|
14310
|
+
ms: Date.now() - started
|
|
14311
|
+
});
|
|
14312
|
+
}
|
|
14313
|
+
}
|
|
14314
|
+
var OPENINGS = {
|
|
14315
|
+
CARD_ASSIGNED: (title) => `\xAB${title}\xBB \uC791\uC5C5\uC744 \uC2DC\uC791\uD588\uC5B4\uC694.`,
|
|
14316
|
+
DECISION_ANSWERED: (title) => `\uB2F5\uC744 \uBC1B\uC544 \xAB${title}\xBB \uC791\uC5C5\uC744 \uC774\uC5B4 \uAC00\uC694.`,
|
|
14317
|
+
RESUME: (title) => `\uC774 PC \uAC00 \uB2E4\uC2DC \uCF1C\uC838 \xAB${title}\xBB \uC791\uC5C5\uC744 \uC774\uC5B4 \uAC00\uC694.`
|
|
14318
|
+
};
|
|
14319
|
+
function resumable(card, workId) {
|
|
14320
|
+
if (card.assignmentState !== "ACCEPTED" || card.blocked) return false;
|
|
14321
|
+
if (card.status !== "TODO" && card.status !== "IN_PROGRESS") return false;
|
|
14322
|
+
return !workId || !card.workId || card.workId === workId;
|
|
14323
|
+
}
|
|
14324
|
+
async function handOverResult(deps, card, workId, result) {
|
|
14325
|
+
await deps.tools.call("create_comments", {
|
|
14326
|
+
cardUuid: card.uuid,
|
|
14327
|
+
workId,
|
|
14328
|
+
items: [{ kind: "COMMENT", body: clip(result, deps.textMaxCharacters), resultReview: true }]
|
|
14329
|
+
});
|
|
14330
|
+
try {
|
|
14331
|
+
await deps.tools.call("report_work_progress", { workId, status: "CHECKPOINT" });
|
|
14332
|
+
return void 0;
|
|
14333
|
+
} catch (error) {
|
|
14334
|
+
if (error instanceof AgentToolError && error.code === "WORK_NOT_IN_PROGRESS") return `report_work_progress: ${error.code}`;
|
|
14335
|
+
throw error;
|
|
14336
|
+
}
|
|
14337
|
+
}
|
|
14338
|
+
async function readCard(tools, cardUuid, workId) {
|
|
14339
|
+
const res = await tools.call("kanban_list_cards", { cardUuids: [cardUuid], ...workId ? { workId } : {} });
|
|
14340
|
+
const cards = Array.isArray(res.cards) ? res.cards : [];
|
|
14341
|
+
return cardFactsOf(cards[0]);
|
|
14342
|
+
}
|
|
14343
|
+
async function act(tools, cardUuid, action) {
|
|
14344
|
+
const res = await tools.call("kanban_card_action", { cardUuid, action });
|
|
14345
|
+
return cardFactsOf(res.card);
|
|
14346
|
+
}
|
|
14347
|
+
async function startWork(tools, cardUuid) {
|
|
14348
|
+
const res = await tools.call("start_work", { cardUuid });
|
|
14349
|
+
const workId = typeof res.workId === "string" ? res.workId : record(res.work).workId;
|
|
14350
|
+
if (typeof workId !== "string") throw new AgentToolError("start_work returned no workId.", "start_work", "MCP_PROTOCOL_ERROR");
|
|
14351
|
+
return workId;
|
|
14352
|
+
}
|
|
14353
|
+
async function postToRun(deps, cardUuid, workId, body) {
|
|
14354
|
+
const res = await deps.tools.call("send_auto_run_message", { cardUuid, workId, body: clip(body, deps.textMaxCharacters) });
|
|
14355
|
+
if (typeof res.conversationUuid !== "string") {
|
|
14356
|
+
throw new AgentToolError("send_auto_run_message returned no conversationUuid.", "send_auto_run_message", "MCP_PROTOCOL_ERROR");
|
|
14357
|
+
}
|
|
14358
|
+
return res.conversationUuid;
|
|
14359
|
+
}
|
|
14360
|
+
function record(value) {
|
|
14361
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
14362
|
+
}
|
|
14363
|
+
function str2(value) {
|
|
14364
|
+
return typeof value === "string" ? value : "";
|
|
14365
|
+
}
|
|
14366
|
+
var STOP_WORK_ERRORS = /* @__PURE__ */ new Set(["CLOSED_BY_HUMAN", "SUPERSEDED", "ACCESS_LOST"]);
|
|
14367
|
+
async function updateTodo(tools, item) {
|
|
14368
|
+
const res = await tools.call("update_agent_todos", { items: [item] });
|
|
14369
|
+
return record(Array.isArray(res.results) ? res.results[0] : void 0);
|
|
14370
|
+
}
|
|
14371
|
+
async function claimTodo(tools, log, todo) {
|
|
14372
|
+
const result = await updateTodo(tools, { todoId: todo.todoId, action: "claim" });
|
|
14373
|
+
const ok = result.ok === true && typeof result.leaseToken === "string";
|
|
14374
|
+
log.write({
|
|
14375
|
+
event: "todo_lease",
|
|
14376
|
+
todoId: todo.todoId,
|
|
14377
|
+
action: "claim",
|
|
14378
|
+
ok,
|
|
14379
|
+
...ok ? {} : { error: str2(result.error) || "no leaseToken" },
|
|
14380
|
+
...typeof result.claimExpiresAt === "string" ? { next: result.claimExpiresAt } : {}
|
|
14381
|
+
});
|
|
14382
|
+
if (!ok) return void 0;
|
|
14383
|
+
return {
|
|
14384
|
+
todo,
|
|
14385
|
+
leaseToken: result.leaseToken,
|
|
14386
|
+
...typeof result.claimExpiresAt === "string" ? { claimExpiresAt: result.claimExpiresAt } : {}
|
|
14387
|
+
};
|
|
14388
|
+
}
|
|
14389
|
+
function keepLease(tools, log, claimed, onLost, now = Date.now) {
|
|
14390
|
+
let timer;
|
|
14391
|
+
let stopped = false;
|
|
14392
|
+
const schedule = (expiresAt) => {
|
|
14393
|
+
const delay = renewDelayMs(expiresAt, now());
|
|
14394
|
+
if (stopped || delay === void 0) return;
|
|
14395
|
+
timer = setTimeout(() => void renew(), delay);
|
|
14396
|
+
timer.unref?.();
|
|
14397
|
+
};
|
|
14398
|
+
const renew = async () => {
|
|
14399
|
+
if (stopped) return;
|
|
14400
|
+
let error;
|
|
14401
|
+
let next;
|
|
14402
|
+
try {
|
|
14403
|
+
const result = await updateTodo(tools, { todoId: claimed.todo.todoId, action: "renew", leaseToken: claimed.leaseToken });
|
|
14404
|
+
if (result.ok === true) {
|
|
14405
|
+
if (typeof result.leaseToken === "string") claimed.leaseToken = result.leaseToken;
|
|
14406
|
+
next = typeof result.claimExpiresAt === "string" ? result.claimExpiresAt : void 0;
|
|
14407
|
+
claimed.claimExpiresAt = next;
|
|
14408
|
+
} else {
|
|
14409
|
+
error = str2(result.error) || "renew refused";
|
|
14410
|
+
}
|
|
14411
|
+
} catch (failure2) {
|
|
14412
|
+
error = failure2 instanceof Error ? failure2.message : String(failure2);
|
|
14413
|
+
next = claimed.claimExpiresAt;
|
|
14414
|
+
}
|
|
14415
|
+
log.write({
|
|
14416
|
+
event: "todo_lease",
|
|
14417
|
+
todoId: claimed.todo.todoId,
|
|
14418
|
+
action: "renew",
|
|
14419
|
+
ok: error === void 0,
|
|
14420
|
+
...error ? { error } : {},
|
|
14421
|
+
...next ? { next } : {}
|
|
14422
|
+
});
|
|
14423
|
+
if (error !== void 0 && STOP_WORK_ERRORS.has(error)) {
|
|
14424
|
+
stopped = true;
|
|
14425
|
+
onLost(error);
|
|
14426
|
+
return;
|
|
14427
|
+
}
|
|
14428
|
+
if (error !== void 0 && next === void 0) return;
|
|
14429
|
+
if (next !== void 0 && Date.parse(next) <= now()) return;
|
|
14430
|
+
schedule(next);
|
|
14431
|
+
};
|
|
14432
|
+
schedule(claimed.claimExpiresAt);
|
|
14433
|
+
return {
|
|
14434
|
+
stop() {
|
|
14435
|
+
stopped = true;
|
|
14436
|
+
if (timer) clearTimeout(timer);
|
|
14437
|
+
}
|
|
14438
|
+
};
|
|
14439
|
+
}
|
|
14440
|
+
async function closeTodo(tools, log, claimed, action, note) {
|
|
14441
|
+
let error;
|
|
14442
|
+
try {
|
|
14443
|
+
const result = await updateTodo(tools, {
|
|
14444
|
+
todoId: claimed.todo.todoId,
|
|
14445
|
+
action,
|
|
14446
|
+
leaseToken: claimed.leaseToken,
|
|
14447
|
+
...action === "complete" && note ? { note } : {}
|
|
14448
|
+
});
|
|
14449
|
+
if (result.ok !== true) error = str2(result.error) || `${action} refused`;
|
|
14450
|
+
} catch (failure2) {
|
|
14451
|
+
error = failure2 instanceof Error ? failure2.message : String(failure2);
|
|
14452
|
+
}
|
|
14453
|
+
log.write({ event: "todo_lease", todoId: claimed.todo.todoId, action, ok: error === void 0, ...error ? { error } : {} });
|
|
14454
|
+
}
|
|
14455
|
+
|
|
13629
14456
|
// src/core/agent/serve.ts
|
|
13630
|
-
var PC_FEATURES = ["stop"];
|
|
14457
|
+
var PC_FEATURES = ["stop", "todos"];
|
|
14458
|
+
function pcFeatures(takesTodos) {
|
|
14459
|
+
return PC_FEATURES.filter((f) => f !== "todos" || takesTodos);
|
|
14460
|
+
}
|
|
14461
|
+
var todoKey = (todoId) => `todo:${todoId}`;
|
|
14462
|
+
var TODO_NOTES = {
|
|
14463
|
+
review_requested: "Worked the card and asked for review.",
|
|
14464
|
+
decision_requested: "Asked for a decision on the card.",
|
|
14465
|
+
not_runnable: "The card is no longer in progress.",
|
|
14466
|
+
agent_failed: "The agent run failed; see the auto-run conversation.",
|
|
14467
|
+
stopped: "Stopped."
|
|
14468
|
+
};
|
|
13631
14469
|
async function runAgentServe(deps) {
|
|
13632
|
-
const
|
|
14470
|
+
const folderName = deps.todos?.agentName;
|
|
14471
|
+
let opened;
|
|
14472
|
+
try {
|
|
14473
|
+
opened = await openLink(deps, openAgentsBody(deps.agents, folderName));
|
|
14474
|
+
} catch (error) {
|
|
14475
|
+
if (error instanceof AgentCallError && error.status === 400 && error.code === "AGENT_NAME_INVALID") {
|
|
14476
|
+
deps.print(`AiNecto did not accept the agent name \xAB${folderName ?? ""}\xBB in this folder's .ainecto/agent.local (${error.message}). Set a valid name with \`ainecto init --agent NAME\` (or delete .ainecto/agent.local), then run \`ainecto agent serve\` again.`);
|
|
14477
|
+
return { exitCode: 1, reason: "agent_name_invalid" };
|
|
14478
|
+
}
|
|
14479
|
+
throw error;
|
|
14480
|
+
}
|
|
13633
14481
|
const linkId = String(opened.linkId);
|
|
13634
14482
|
deps.http.useLinkToken(String(opened.linkToken));
|
|
13635
|
-
const limits =
|
|
13636
|
-
const
|
|
14483
|
+
const limits = serverLimits2(opened.limits);
|
|
14484
|
+
const displayName = (id) => deps.adapters.get(id)?.displayName ?? id;
|
|
14485
|
+
const names = deps.agents.map((a) => displayName(a.id)).join(" / ");
|
|
13637
14486
|
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.`);
|
|
14487
|
+
const { identities, refused } = identitiesIn(opened.agents, deps.adapters);
|
|
14488
|
+
for (const r of refused) {
|
|
14489
|
+
deps.print(`${displayName(r.agent)}: AiNecto refused its agent identity (${r.error}), so auto-run cards for ${displayName(r.agent)} are not taken here.` + (r.error === "AGENT_LIMIT" ? " Archive an agent you no longer use in AiNecto, then start `ainecto agent serve` again." : ""));
|
|
14490
|
+
}
|
|
14491
|
+
const todos = deps.todos && identities.length > 0 ? { tools: deps.todos.tools, runs: deps.todos.runs, identities } : void 0;
|
|
14492
|
+
if (todos) {
|
|
14493
|
+
deps.print(`Auto-run cards handed to ${identities.map((i) => `${displayName(i.agent)} (${i.name})`).join(" and ")} run here.`);
|
|
14494
|
+
} else if (deps.todos && refused.length === 0) {
|
|
14495
|
+
deps.print("Auto-run cards are not taken here: AiNecto did not give this connection an agent identity (update the server, or sign in to Claude Code or Codex).");
|
|
14496
|
+
}
|
|
13638
14497
|
const stopController = new AbortController();
|
|
13639
14498
|
let stopReason;
|
|
13640
14499
|
let exitCode2 = 0;
|
|
@@ -13644,11 +14503,13 @@ async function runAgentServe(deps) {
|
|
|
13644
14503
|
const queue = [];
|
|
13645
14504
|
const stopping = /* @__PURE__ */ new Set();
|
|
13646
14505
|
let current;
|
|
13647
|
-
|
|
13648
|
-
|
|
13649
|
-
|
|
13650
|
-
|
|
13651
|
-
|
|
14506
|
+
let todoInFlight;
|
|
14507
|
+
let wakeTodos;
|
|
14508
|
+
const requestStop = (key) => {
|
|
14509
|
+
if (stopping.has(key)) return;
|
|
14510
|
+
stopping.add(key);
|
|
14511
|
+
const running = current?.key === key;
|
|
14512
|
+
deps.log.write({ event: "stop_request", turnUuid: key, running, queued: queue.some((j) => jobKey(j) === key) });
|
|
13652
14513
|
if (running) void current?.session.interrupt();
|
|
13653
14514
|
};
|
|
13654
14515
|
const stop = (reason, code, message) => {
|
|
@@ -13658,6 +14519,7 @@ async function runAgentServe(deps) {
|
|
|
13658
14519
|
if (message) deps.print(message);
|
|
13659
14520
|
stopController.abort();
|
|
13660
14521
|
wakeWorker?.();
|
|
14522
|
+
wakeTodos?.();
|
|
13661
14523
|
for (const session of live.values()) void session.close();
|
|
13662
14524
|
};
|
|
13663
14525
|
const onUserStop = () => stop("signal", 0, "Stopping\u2026");
|
|
@@ -13685,7 +14547,7 @@ async function runAgentServe(deps) {
|
|
|
13685
14547
|
deps.log.write({ event: "offer", turnUuid: offer.turnUuid, conversationUuid: offer.conversationUuid, agent: offer.agent, duplicate });
|
|
13686
14548
|
if (duplicate) continue;
|
|
13687
14549
|
received.add(offer.turnUuid);
|
|
13688
|
-
queue.push(offer);
|
|
14550
|
+
queue.push({ kind: "chat", offer });
|
|
13689
14551
|
wakeWorker?.();
|
|
13690
14552
|
}
|
|
13691
14553
|
for (const turnUuid of stopsIn(res)) requestStop(turnUuid);
|
|
@@ -13700,9 +14562,9 @@ async function runAgentServe(deps) {
|
|
|
13700
14562
|
}
|
|
13701
14563
|
}
|
|
13702
14564
|
})();
|
|
13703
|
-
const sessionFor = async (adapter, conversationUuid) => {
|
|
14565
|
+
const sessionFor = async (adapter, conversationUuid, agentName) => {
|
|
13704
14566
|
const existing = live.get(adapter.id);
|
|
13705
|
-
if (existing && existing.conversationUuid === conversationUuid && existing.alive) return existing;
|
|
14567
|
+
if (existing && existing.conversationUuid === conversationUuid && existing.agentName === agentName && existing.alive) return existing;
|
|
13706
14568
|
if (existing) {
|
|
13707
14569
|
live.delete(adapter.id);
|
|
13708
14570
|
await existing.close();
|
|
@@ -13710,7 +14572,8 @@ async function runAgentServe(deps) {
|
|
|
13710
14572
|
const session = adapter.open({
|
|
13711
14573
|
conversationUuid,
|
|
13712
14574
|
resumeRef: deps.sessions.get(conversationUuid, adapter.id),
|
|
13713
|
-
textMaxCharacters: limits.textMaxCharacters
|
|
14575
|
+
textMaxCharacters: limits.textMaxCharacters,
|
|
14576
|
+
...agentName ? { agentName } : {}
|
|
13714
14577
|
});
|
|
13715
14578
|
live.set(adapter.id, session);
|
|
13716
14579
|
return session;
|
|
@@ -13724,18 +14587,19 @@ async function runAgentServe(deps) {
|
|
|
13724
14587
|
let failure2;
|
|
13725
14588
|
try {
|
|
13726
14589
|
try {
|
|
13727
|
-
session = adapter ? await sessionFor(adapter, offer.conversationUuid) : void 0;
|
|
14590
|
+
session = adapter ? await sessionFor(adapter, offer.conversationUuid, offer.agentName) : void 0;
|
|
13728
14591
|
} finally {
|
|
13729
14592
|
deps.log.write({
|
|
13730
14593
|
event: "agent_request",
|
|
13731
14594
|
turnUuid: offer.turnUuid,
|
|
14595
|
+
todoId: offer.todoId,
|
|
13732
14596
|
agent: offer.agent,
|
|
13733
14597
|
conversationUuid: offer.conversationUuid,
|
|
13734
14598
|
pid: session?.pid ?? -1,
|
|
13735
14599
|
textLength: offer.text.length
|
|
13736
14600
|
});
|
|
13737
14601
|
}
|
|
13738
|
-
if (stopping.has(offer.
|
|
14602
|
+
if (stopping.has(offer.key)) {
|
|
13739
14603
|
reply = stoppedReply(void 0, limits);
|
|
13740
14604
|
return reply;
|
|
13741
14605
|
}
|
|
@@ -13749,7 +14613,7 @@ async function runAgentServe(deps) {
|
|
|
13749
14613
|
};
|
|
13750
14614
|
return reply;
|
|
13751
14615
|
}
|
|
13752
|
-
current = {
|
|
14616
|
+
current = { key: offer.key, session };
|
|
13753
14617
|
try {
|
|
13754
14618
|
outcome = await session.send(agentPromptText(offer.text, offer.context), deps.turnTimeoutMs ?? AGENT_TURN_TIMEOUT_MS);
|
|
13755
14619
|
} finally {
|
|
@@ -13765,7 +14629,7 @@ async function runAgentServe(deps) {
|
|
|
13765
14629
|
} else if (session.sessionRef) {
|
|
13766
14630
|
await deps.sessions.set(offer.conversationUuid, adapter.id, session.sessionRef);
|
|
13767
14631
|
}
|
|
13768
|
-
reply = stopping.has(offer.
|
|
14632
|
+
reply = stopping.has(offer.key) ? stoppedReply(outcome, limits) : replyForOutcome(outcome, limits, adapter.displayName);
|
|
13769
14633
|
return reply;
|
|
13770
14634
|
} catch (error) {
|
|
13771
14635
|
failure2 = error instanceof Error ? error.message : String(error);
|
|
@@ -13776,6 +14640,7 @@ async function runAgentServe(deps) {
|
|
|
13776
14640
|
deps.log.write({
|
|
13777
14641
|
event: "agent_response",
|
|
13778
14642
|
turnUuid: offer.turnUuid,
|
|
14643
|
+
todoId: offer.todoId,
|
|
13779
14644
|
agent: offer.agent,
|
|
13780
14645
|
ms: Date.now() - started,
|
|
13781
14646
|
outcome: outcome?.kind ?? `error: ${failure2 ?? "unknown"}`,
|
|
@@ -13818,21 +14683,120 @@ async function runAgentServe(deps) {
|
|
|
13818
14683
|
}
|
|
13819
14684
|
}
|
|
13820
14685
|
};
|
|
14686
|
+
const runTodoJob = async (job) => {
|
|
14687
|
+
const t = todos;
|
|
14688
|
+
const { claimed, identity } = job;
|
|
14689
|
+
const runs = t.runs;
|
|
14690
|
+
let outcome;
|
|
14691
|
+
try {
|
|
14692
|
+
outcome = await runTodo({
|
|
14693
|
+
tools: toolsAs(t.tools, identity),
|
|
14694
|
+
...runs ? { runs: {
|
|
14695
|
+
started: (cardUuid, workId) => runs.started(cardUuid, workId, identity.agent),
|
|
14696
|
+
finished: (cardUuid) => runs.finished(cardUuid)
|
|
14697
|
+
} } : {},
|
|
14698
|
+
log: deps.log,
|
|
14699
|
+
textMaxCharacters: limits.textMaxCharacters,
|
|
14700
|
+
signal: stopController.signal,
|
|
14701
|
+
runAgent: ({ todoId, conversationUuid, text }) => runTurn({ key: todoKey(todoId), todoId, conversationUuid, agent: identity.agent, text, agentName: identity.name })
|
|
14702
|
+
}, job.todo);
|
|
14703
|
+
} catch {
|
|
14704
|
+
} finally {
|
|
14705
|
+
job.lease?.stop();
|
|
14706
|
+
}
|
|
14707
|
+
if (claimed && (stopReason || outcome === "stopped")) {
|
|
14708
|
+
await closeTodo(toolsAs(t.tools, identity), deps.log, claimed, "release");
|
|
14709
|
+
} else if (claimed && outcome !== void 0 && claimed.todo.kind === "DECISION_ANSWERED") {
|
|
14710
|
+
await closeTodo(toolsAs(t.tools, identity), deps.log, claimed, "complete", TODO_NOTES[outcome]);
|
|
14711
|
+
}
|
|
14712
|
+
todoInFlight = void 0;
|
|
14713
|
+
wakeTodos?.();
|
|
14714
|
+
};
|
|
13821
14715
|
const worker = (async () => {
|
|
13822
14716
|
while (!stopReason) {
|
|
13823
|
-
const
|
|
13824
|
-
if (!
|
|
14717
|
+
const job = queue.shift();
|
|
14718
|
+
if (!job) {
|
|
13825
14719
|
await new Promise((resolve4) => {
|
|
13826
14720
|
wakeWorker = resolve4;
|
|
13827
14721
|
});
|
|
13828
14722
|
wakeWorker = void 0;
|
|
13829
14723
|
continue;
|
|
13830
14724
|
}
|
|
13831
|
-
|
|
13832
|
-
|
|
14725
|
+
if (job.kind === "todo") {
|
|
14726
|
+
await runTodoJob(job);
|
|
14727
|
+
continue;
|
|
14728
|
+
}
|
|
14729
|
+
const reply = await runTurn({ key: job.offer.turnUuid, ...job.offer });
|
|
14730
|
+
if (!stopReason) await sendReply(job.offer, reply);
|
|
14731
|
+
}
|
|
14732
|
+
})();
|
|
14733
|
+
const takeTodo = async (identity) => {
|
|
14734
|
+
const tools = toolsAs(todos.tools, identity);
|
|
14735
|
+
let after;
|
|
14736
|
+
do {
|
|
14737
|
+
const page = todosIn(await tools.call(
|
|
14738
|
+
"list_agent_todos",
|
|
14739
|
+
{ state: ["OPEN"], kinds: [...TODO_KINDS], agent: identity.agentUuid, ...after ? { after } : {} }
|
|
14740
|
+
));
|
|
14741
|
+
for (const todo of page.items) {
|
|
14742
|
+
if (stopReason) return false;
|
|
14743
|
+
const claimed = await claimTodo(tools, deps.log, todo);
|
|
14744
|
+
if (!claimed) continue;
|
|
14745
|
+
todoInFlight = todo.cardUuid;
|
|
14746
|
+
const lease = keepLease(tools, deps.log, claimed, () => requestStop(todoKey(todo.todoId)));
|
|
14747
|
+
queue.push({ kind: "todo", todo, identity, claimed, lease });
|
|
14748
|
+
wakeWorker?.();
|
|
14749
|
+
return true;
|
|
14750
|
+
}
|
|
14751
|
+
after = page.next;
|
|
14752
|
+
} while (after && !stopReason);
|
|
14753
|
+
return false;
|
|
14754
|
+
};
|
|
14755
|
+
const todoLoop = (async () => {
|
|
14756
|
+
if (!todos) return;
|
|
14757
|
+
let resumes = [];
|
|
14758
|
+
try {
|
|
14759
|
+
resumes = todos.runs ? (await todos.runs.load()).flatMap((entry) => {
|
|
14760
|
+
const identity = todos.identities.find((i) => i.agent === (entry.agent ?? todos.identities[0]?.agent));
|
|
14761
|
+
return identity ? [{ todo: resumeTodo(entry), identity }] : [];
|
|
14762
|
+
}) : [];
|
|
14763
|
+
} catch {
|
|
14764
|
+
}
|
|
14765
|
+
let turn = 0;
|
|
14766
|
+
while (!stopReason) {
|
|
14767
|
+
if (!todoInFlight) {
|
|
14768
|
+
const resume = resumes.shift();
|
|
14769
|
+
if (resume) {
|
|
14770
|
+
todoInFlight = resume.todo.cardUuid;
|
|
14771
|
+
queue.push({ kind: "todo", todo: resume.todo, identity: resume.identity });
|
|
14772
|
+
wakeWorker?.();
|
|
14773
|
+
} else {
|
|
14774
|
+
for (let i = 0; i < todos.identities.length && !stopReason; i += 1) {
|
|
14775
|
+
const identity = todos.identities[(turn + i) % todos.identities.length];
|
|
14776
|
+
try {
|
|
14777
|
+
if (await takeTodo(identity)) {
|
|
14778
|
+
turn = (turn + i + 1) % todos.identities.length;
|
|
14779
|
+
break;
|
|
14780
|
+
}
|
|
14781
|
+
} catch {
|
|
14782
|
+
}
|
|
14783
|
+
}
|
|
14784
|
+
}
|
|
14785
|
+
}
|
|
14786
|
+
if (stopReason) return;
|
|
14787
|
+
await new Promise((resolve4) => {
|
|
14788
|
+
wakeTodos = resolve4;
|
|
14789
|
+
void sleep(limits.pollHoldSeconds * 1e3, stopController.signal).then(resolve4);
|
|
14790
|
+
});
|
|
14791
|
+
wakeTodos = void 0;
|
|
13833
14792
|
}
|
|
13834
14793
|
})();
|
|
13835
|
-
await Promise.allSettled([pollLoop, worker]);
|
|
14794
|
+
await Promise.allSettled([pollLoop, worker, todoLoop]);
|
|
14795
|
+
for (const job of queue.splice(0)) {
|
|
14796
|
+
if (job.kind !== "todo" || !job.claimed) continue;
|
|
14797
|
+
job.lease?.stop();
|
|
14798
|
+
await closeTodo(toolsAs(todos.tools, job.identity), deps.log, job.claimed, "release");
|
|
14799
|
+
}
|
|
13836
14800
|
deps.signal.removeEventListener("abort", onUserStop);
|
|
13837
14801
|
await Promise.all([...live.values()].map((session) => session.close()));
|
|
13838
14802
|
if (stopReason === "signal") {
|
|
@@ -13843,7 +14807,10 @@ async function runAgentServe(deps) {
|
|
|
13843
14807
|
}
|
|
13844
14808
|
return { exitCode: exitCode2, reason: stopReason ?? "unknown" };
|
|
13845
14809
|
}
|
|
13846
|
-
function
|
|
14810
|
+
function jobKey(job) {
|
|
14811
|
+
return job.kind === "chat" ? job.offer.turnUuid : todoKey(job.todo.todoId);
|
|
14812
|
+
}
|
|
14813
|
+
function serverLimits2(value) {
|
|
13847
14814
|
const v = value ?? {};
|
|
13848
14815
|
const num = (key) => {
|
|
13849
14816
|
const n = v[key];
|
|
@@ -13854,16 +14821,51 @@ function serverLimits(value) {
|
|
|
13854
14821
|
};
|
|
13855
14822
|
return { pollHoldSeconds: num("pollHoldSeconds"), textMaxCharacters: num("textMaxCharacters"), documentsMax: num("documentsMax") };
|
|
13856
14823
|
}
|
|
13857
|
-
async function openLink(deps) {
|
|
13858
|
-
const base = { hostName: deps.hostName, cliVersion: deps.cliVersion
|
|
13859
|
-
|
|
13860
|
-
|
|
13861
|
-
|
|
13862
|
-
|
|
13863
|
-
|
|
13864
|
-
|
|
14824
|
+
async function openLink(deps, agents) {
|
|
14825
|
+
const base = { hostName: deps.hostName, cliVersion: deps.cliVersion };
|
|
14826
|
+
const named = agents.some((a) => a.name !== void 0);
|
|
14827
|
+
const unnamed = agents.map(({ name: _name, ...rest }) => rest);
|
|
14828
|
+
const features = pcFeatures(deps.todos !== void 0);
|
|
14829
|
+
const older = features.filter((f) => f !== "todos");
|
|
14830
|
+
const attempts = [
|
|
14831
|
+
...deps.cliBuild ? [{ body: { ...base, cliBuild: deps.cliBuild, agents, features } }] : [],
|
|
14832
|
+
{ body: { ...base, agents, features }, ...deps.cliBuild ? { dropped: "cliBuild" } : {} },
|
|
14833
|
+
...older.length < features.length ? [{ body: { ...base, agents, features: older }, dropped: "features.todos" }] : [],
|
|
14834
|
+
...named ? [{ body: { ...base, agents: unnamed, features: older }, dropped: "agents.name" }] : [],
|
|
14835
|
+
{ body: { ...base, agents: unnamed }, dropped: "features" }
|
|
14836
|
+
];
|
|
14837
|
+
for (let i = 0; ; i += 1) {
|
|
14838
|
+
const attempt = attempts[i];
|
|
14839
|
+
if (attempt.dropped) deps.log.write({ event: "open_without_features", features: [attempt.dropped] });
|
|
14840
|
+
try {
|
|
14841
|
+
return await deps.http.call("open", attempt.body);
|
|
14842
|
+
} catch (error) {
|
|
14843
|
+
const old = error instanceof AgentCallError && error.status === 400 && error.code === "INVALID";
|
|
14844
|
+
if (!old || i === attempts.length - 1) throw error;
|
|
14845
|
+
}
|
|
13865
14846
|
}
|
|
13866
14847
|
}
|
|
14848
|
+
function folderKind(agents) {
|
|
14849
|
+
return agents.find((a) => a.ready && a.id === DEFAULT_AGENT)?.id ?? agents.find((a) => a.ready)?.id;
|
|
14850
|
+
}
|
|
14851
|
+
function openAgentsBody(agents, folderName) {
|
|
14852
|
+
const kind = folderName ? folderKind(agents) : void 0;
|
|
14853
|
+
return agents.map((a) => ({ id: a.id, ready: a.ready, ...a.auth ? { auth: a.auth } : {}, ...a.id === kind ? { name: folderName } : {} }));
|
|
14854
|
+
}
|
|
14855
|
+
function identitiesIn(value, adapters) {
|
|
14856
|
+
const identities = [];
|
|
14857
|
+
const refused = [];
|
|
14858
|
+
for (const raw of Array.isArray(value) ? value : []) {
|
|
14859
|
+
const a = raw ?? {};
|
|
14860
|
+
if (!isAgentId(a.id) || !adapters.has(a.id)) continue;
|
|
14861
|
+
if (typeof a.agentUuid === "string" && typeof a.name === "string") {
|
|
14862
|
+
identities.push({ agent: a.id, agentUuid: a.agentUuid, name: a.name });
|
|
14863
|
+
} else if (typeof a.error === "string") {
|
|
14864
|
+
refused.push({ agent: a.id, error: a.error });
|
|
14865
|
+
}
|
|
14866
|
+
}
|
|
14867
|
+
return { identities, refused };
|
|
14868
|
+
}
|
|
13867
14869
|
function stopsIn(res) {
|
|
13868
14870
|
return Array.isArray(res.stops) ? res.stops.filter((t) => typeof t === "string") : [];
|
|
13869
14871
|
}
|
|
@@ -13880,24 +14882,9 @@ function offersIn(res) {
|
|
|
13880
14882
|
}] : [];
|
|
13881
14883
|
});
|
|
13882
14884
|
}
|
|
13883
|
-
function sleep(ms, signal) {
|
|
13884
|
-
return new Promise((resolve4) => {
|
|
13885
|
-
if (signal.aborted) {
|
|
13886
|
-
resolve4();
|
|
13887
|
-
return;
|
|
13888
|
-
}
|
|
13889
|
-
const timer = setTimeout(done, ms);
|
|
13890
|
-
signal.addEventListener("abort", done, { once: true });
|
|
13891
|
-
function done() {
|
|
13892
|
-
clearTimeout(timer);
|
|
13893
|
-
signal.removeEventListener("abort", done);
|
|
13894
|
-
resolve4();
|
|
13895
|
-
}
|
|
13896
|
-
});
|
|
13897
|
-
}
|
|
13898
14885
|
|
|
13899
14886
|
// src/core/agent/sessions.ts
|
|
13900
|
-
import { readFile as
|
|
14887
|
+
import { readFile as readFile10, rename as rename7, writeFile as writeFile7 } from "fs/promises";
|
|
13901
14888
|
var AgentSessionMap = class {
|
|
13902
14889
|
constructor(path) {
|
|
13903
14890
|
this.path = path;
|
|
@@ -13906,7 +14893,7 @@ var AgentSessionMap = class {
|
|
|
13906
14893
|
map = emptyMap();
|
|
13907
14894
|
async load() {
|
|
13908
14895
|
try {
|
|
13909
|
-
const parsed = JSON.parse(await
|
|
14896
|
+
const parsed = JSON.parse(await readFile10(this.path, "utf8"));
|
|
13910
14897
|
const map = emptyMap();
|
|
13911
14898
|
map[DEFAULT_AGENT] = entries(parsed.conversations);
|
|
13912
14899
|
const byAgent = parsed.byAgent && typeof parsed.byAgent === "object" ? parsed.byAgent : {};
|
|
@@ -13933,13 +14920,13 @@ var AgentSessionMap = class {
|
|
|
13933
14920
|
async save() {
|
|
13934
14921
|
const byAgent = Object.fromEntries(AGENT_IDS.filter((id) => id !== DEFAULT_AGENT).map((id) => [id, this.map[id]]));
|
|
13935
14922
|
const tmp = `${this.path}.tmp`;
|
|
13936
|
-
await
|
|
14923
|
+
await writeFile7(
|
|
13937
14924
|
tmp,
|
|
13938
14925
|
`${JSON.stringify({ version: 2, conversations: this.map[DEFAULT_AGENT], byAgent }, null, 2)}
|
|
13939
14926
|
`,
|
|
13940
14927
|
{ mode: PRIVATE_FILE_MODE }
|
|
13941
14928
|
);
|
|
13942
|
-
await
|
|
14929
|
+
await rename7(tmp, this.path);
|
|
13943
14930
|
}
|
|
13944
14931
|
};
|
|
13945
14932
|
function emptyMap() {
|
|
@@ -13959,7 +14946,7 @@ function entries(value) {
|
|
|
13959
14946
|
|
|
13960
14947
|
// src/adapters/cli/agentCommand.ts
|
|
13961
14948
|
var AGENT_HELP_LINES = [
|
|
13962
|
-
" 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)"
|
|
14949
|
+
" ainecto agent serve [--env prod|dev] answer \xABMy agent\xBB requests from AiNecto Chat with Claude Code or Codex on this machine, and run the auto-run cards handed to them (name one: ainecto init --agent NAME) (Ctrl+C to stop; log: ~/.ainecto/agent/agent.log)"
|
|
13963
14950
|
];
|
|
13964
14951
|
function isAgentCommand(domain, action) {
|
|
13965
14952
|
return domain === "agent" && action === "serve";
|
|
@@ -13970,39 +14957,31 @@ async function executeAgentServe(input) {
|
|
|
13970
14957
|
await ensurePrivateDir(paths.dir);
|
|
13971
14958
|
await ensurePrivateDir(paths.work);
|
|
13972
14959
|
const log = openAgentLog(paths);
|
|
13973
|
-
const host =
|
|
13974
|
-
const
|
|
13975
|
-
const
|
|
13976
|
-
|
|
13977
|
-
|
|
13978
|
-
|
|
13979
|
-
|
|
13980
|
-
|
|
13981
|
-
|
|
13982
|
-
log
|
|
13983
|
-
|
|
13984
|
-
|
|
13985
|
-
op: "tools_list",
|
|
13986
|
-
ok: false,
|
|
13987
|
-
error: error instanceof Error ? error.message : String(error),
|
|
13988
|
-
ms: Date.now() - started
|
|
13989
|
-
});
|
|
13990
|
-
throw error;
|
|
13991
|
-
}
|
|
14960
|
+
const host = hostname2();
|
|
14961
|
+
const client = (agentName) => new McpRpcClient({ endpoint: input.endpoint, tokenProvider: input.auth, channel: "cli", ...agentName ? { agentName } : {} });
|
|
14962
|
+
const tools = createAgentTools({
|
|
14963
|
+
client: client(),
|
|
14964
|
+
clientAs: (identity) => {
|
|
14965
|
+
const as = client(identity.name);
|
|
14966
|
+
as.useAgent(AGENT_MCP_CLIENT_NAMES[identity.agent]);
|
|
14967
|
+
return as;
|
|
14968
|
+
},
|
|
14969
|
+
log
|
|
14970
|
+
});
|
|
14971
|
+
const writeTools = writeToolNames(await tools.list());
|
|
13992
14972
|
const cliScript = process.argv[1];
|
|
13993
14973
|
if (!cliScript) throw new Error("Cannot find the path of this CLI to start the AiNecto bridge for the agents.");
|
|
13994
|
-
const bridge = ainectoBridge(process.execPath, cliScript, input.endpoint);
|
|
14974
|
+
const bridge = (agentName) => ainectoBridge(process.execPath, cliScript, input.endpoint, agentName);
|
|
13995
14975
|
const shared = { spawnImpl: spawnAgent, cwd: paths.work, env: agentEnv(process.env), log, writeTools };
|
|
13996
|
-
const mcpConfig = claudeMcpConfig(bridge);
|
|
13997
14976
|
const all = [
|
|
13998
|
-
claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig, resumeSessionId }) }),
|
|
13999
|
-
codexAdapter({ ...shared, appServerArgs: codexAppServerArgs(bridge, writeTools), clientVersion: CLI_VERSION })
|
|
14977
|
+
claudeCodeAdapter({ ...shared, args: ({ textMaxCharacters, resumeSessionId, agentName }) => claudeAgentArgs({ schema: agentReplySchema(textMaxCharacters), mcpConfig: claudeMcpConfig(bridge(agentName)), resumeSessionId }) }),
|
|
14978
|
+
codexAdapter({ ...shared, appServerArgs: (agentName) => codexAppServerArgs(bridge(agentName), writeTools), clientVersion: CLI_VERSION })
|
|
14000
14979
|
];
|
|
14001
14980
|
const checks = await checkAgents(all, log);
|
|
14002
14981
|
log.write({
|
|
14003
14982
|
event: "serve_start",
|
|
14004
14983
|
pid: process.pid,
|
|
14005
|
-
version:
|
|
14984
|
+
version: CLI_VERSION_LABEL,
|
|
14006
14985
|
endpoint: input.endpoint,
|
|
14007
14986
|
host,
|
|
14008
14987
|
agents: checks.map(({ id, installed, ready, auth, version }) => ({ id, installed, ready, ...auth ? { auth } : {}, ...version ? { version } : {} }))
|
|
@@ -14038,10 +15017,12 @@ async function executeAgentServe(input) {
|
|
|
14038
15017
|
adapters,
|
|
14039
15018
|
agents,
|
|
14040
15019
|
hostName: host,
|
|
14041
|
-
cliVersion:
|
|
15020
|
+
cliVersion: CLI_VERSION_LABEL,
|
|
15021
|
+
...CLI_BUILD ? { cliBuild: CLI_BUILD } : {},
|
|
14042
15022
|
print: (line) => input.io.stderr.write(`${line}
|
|
14043
15023
|
`),
|
|
14044
|
-
signal: controller.signal
|
|
15024
|
+
signal: controller.signal,
|
|
15025
|
+
todos: { tools, agentName: input.agentName, runs: new AgentRunLog(paths.runs, log) }
|
|
14045
15026
|
});
|
|
14046
15027
|
log.write({ event: "serve_stop", pid: process.pid, reason: result.reason });
|
|
14047
15028
|
return result.exitCode;
|
|
@@ -14068,7 +15049,7 @@ async function runAinectoCli(argv, io) {
|
|
|
14068
15049
|
io.stdout.write(helpText());
|
|
14069
15050
|
return 0;
|
|
14070
15051
|
}
|
|
14071
|
-
if (parsed.positionals[0] === "term") {
|
|
15052
|
+
if (parsed.positionals[0] === "term" && parsed.positionals[1] !== "remote") {
|
|
14072
15053
|
return await executeTermCommand({ argv: parsed.positionals.slice(1), json: parsed.json, io });
|
|
14073
15054
|
}
|
|
14074
15055
|
const resolved = resolveEndpoint({ env: parsed.env, endpoint: parsed.endpoint });
|
|
@@ -14170,8 +15151,11 @@ async function runAinectoCli(argv, io) {
|
|
|
14170
15151
|
io
|
|
14171
15152
|
});
|
|
14172
15153
|
}
|
|
15154
|
+
if (domain === "term") {
|
|
15155
|
+
return await executeTermRemote({ argv: rest, json: parsed.json, io, endpoint: resolved.endpoint, auth: connect2().auth });
|
|
15156
|
+
}
|
|
14173
15157
|
if (isAgentCommand(domain, action)) {
|
|
14174
|
-
return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io });
|
|
15158
|
+
return await executeAgentServe({ endpoint: resolved.endpoint, env: resolved.env, auth: connect2().auth, io, agentName });
|
|
14175
15159
|
}
|
|
14176
15160
|
if (domain === "auth") {
|
|
14177
15161
|
return await handleAuth(action, connect2().auth, resolved.endpoint, parsed.json, io);
|