@agent-commons/cli 0.5.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/dist/bin.js +1008 -302
- package/package.json +2 -2
package/dist/bin.js
CHANGED
|
@@ -24,7 +24,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
24
24
|
));
|
|
25
25
|
|
|
26
26
|
// src/bin.ts
|
|
27
|
-
var
|
|
27
|
+
var import_commander24 = require("commander");
|
|
28
28
|
var import_child_process3 = require("child_process");
|
|
29
29
|
|
|
30
30
|
// src/commands/login.ts
|
|
@@ -178,7 +178,7 @@ var sym = {
|
|
|
178
178
|
bullet: import_chalk.default.dim("\u2022"),
|
|
179
179
|
dot: import_chalk.default.dim("\xB7")
|
|
180
180
|
};
|
|
181
|
-
function banner(version = "0.
|
|
181
|
+
function banner(version = "0.6.2") {
|
|
182
182
|
console.log("");
|
|
183
183
|
console.log(import_chalk.default.cyan(" \u25C7"));
|
|
184
184
|
console.log(import_chalk.default.cyan(" \u256D\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"));
|
|
@@ -664,11 +664,11 @@ function agentsCommand() {
|
|
|
664
664
|
process.exit(1);
|
|
665
665
|
}
|
|
666
666
|
});
|
|
667
|
-
cmd.command("get <agentId>").description("Show details for an agent").option("--json", "Output as JSON").action(async (
|
|
667
|
+
cmd.command("get <agentId>").description("Show details for an agent").option("--json", "Output as JSON").action(async (agentId3, opts) => {
|
|
668
668
|
const spinner = spin("Fetching agent\u2026");
|
|
669
669
|
try {
|
|
670
670
|
const client = makeClient();
|
|
671
|
-
const res = await client.agents.get(
|
|
671
|
+
const res = await client.agents.get(agentId3);
|
|
672
672
|
const agent = res?.data ?? res;
|
|
673
673
|
spinner.stop();
|
|
674
674
|
if (opts.json) return jsonOut(agent);
|
|
@@ -747,10 +747,10 @@ ${sym.ok} Agent created`);
|
|
|
747
747
|
}
|
|
748
748
|
});
|
|
749
749
|
const runtime = cmd.command("runtime").description("Manage an agent runtime");
|
|
750
|
-
runtime.command("status <agentId>").description("Show managed runtime status and capabilities").option("--json", "Output as JSON").action(async (
|
|
750
|
+
runtime.command("status <agentId>").description("Show managed runtime status and capabilities").option("--json", "Output as JSON").action(async (agentId3, opts) => {
|
|
751
751
|
const spinner = spin("Fetching runtime status\u2026");
|
|
752
752
|
try {
|
|
753
|
-
const result = await makeClient().agents.getRuntime(
|
|
753
|
+
const result = await makeClient().agents.getRuntime(agentId3);
|
|
754
754
|
spinner.stop();
|
|
755
755
|
if (opts.json) return jsonOut(result.data);
|
|
756
756
|
detail([
|
|
@@ -768,13 +768,13 @@ ${sym.ok} Agent created`);
|
|
|
768
768
|
for (const action of ["deploy", "restart", "sleep"]) {
|
|
769
769
|
runtime.command(`${action} <agentId>`).description(
|
|
770
770
|
`${action[0].toUpperCase()}${action.slice(1)} the managed agent runtime`
|
|
771
|
-
).action(async (
|
|
771
|
+
).action(async (agentId3) => {
|
|
772
772
|
const spinner = spin(
|
|
773
773
|
`${action[0].toUpperCase()}${action.slice(1)}ing runtime\u2026`
|
|
774
774
|
);
|
|
775
775
|
try {
|
|
776
776
|
const client = makeClient();
|
|
777
|
-
const result = action === "deploy" ? await client.agents.deployRuntime(
|
|
777
|
+
const result = action === "deploy" ? await client.agents.deployRuntime(agentId3) : action === "restart" ? await client.agents.restartRuntime(agentId3) : await client.agents.sleepRuntime(agentId3);
|
|
778
778
|
spinner.stop();
|
|
779
779
|
console.log(`
|
|
780
780
|
${sym.ok} Runtime ${result.data.status}`);
|
|
@@ -887,12 +887,12 @@ function sessionsCommand() {
|
|
|
887
887
|
const spinner = spin("Fetching sessions\u2026");
|
|
888
888
|
try {
|
|
889
889
|
const client = makeClient();
|
|
890
|
-
const
|
|
891
|
-
const res =
|
|
890
|
+
const agentId3 = opts.agent;
|
|
891
|
+
const res = agentId3 ? await client.sessions.list(agentId3, cfg.initiator) : await client.sessions.listByUser(cfg.initiator);
|
|
892
892
|
const sessions = res?.data ?? res ?? [];
|
|
893
893
|
spinner.stop();
|
|
894
894
|
if (opts.json) return jsonOut(sessions);
|
|
895
|
-
section(`Sessions (${sessions.length})${
|
|
895
|
+
section(`Sessions (${sessions.length})${agentId3 ? ` \u2014 agent ${agentId3.slice(0, 8)}\u2026` : " \u2014 all agents"}`);
|
|
896
896
|
table(
|
|
897
897
|
sessions.map((s) => ({
|
|
898
898
|
ID: s.sessionId.slice(0, 8) + "\u2026",
|
|
@@ -933,8 +933,8 @@ function sessionsCommand() {
|
|
|
933
933
|
});
|
|
934
934
|
cmd.command("create").description("Create a new session").option("--agent <agentId>", "Agent ID").option("--title <title>", "Session title").option("--model <id>", "Model ID (e.g. gpt-5.4-mini, claude-sonnet-4-6)").option("--provider <provider>", "Model provider").option("--json", "Output as JSON").action(async (opts) => {
|
|
935
935
|
const cfg = loadConfig();
|
|
936
|
-
const
|
|
937
|
-
if (!
|
|
936
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
937
|
+
if (!agentId3) {
|
|
938
938
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId"));
|
|
939
939
|
process.exit(1);
|
|
940
940
|
}
|
|
@@ -946,7 +946,7 @@ function sessionsCommand() {
|
|
|
946
946
|
try {
|
|
947
947
|
const client = makeClient();
|
|
948
948
|
const res = await client.sessions.create({
|
|
949
|
-
agentId:
|
|
949
|
+
agentId: agentId3,
|
|
950
950
|
initiator: cfg.initiator,
|
|
951
951
|
title: opts.title,
|
|
952
952
|
...opts.model && { model: { modelId: opts.model, provider: opts.provider } }
|
|
@@ -1102,8 +1102,8 @@ ${sym.ok} Tool created`);
|
|
|
1102
1102
|
});
|
|
1103
1103
|
cmd.command("exec <toolName>").description("Execute a tool directly by name").option("--agent <agentId>", "Agent context for tool execution").option("--args <json>", "Tool arguments as JSON object", "{}").option("--json", "Output result as JSON").action(async (toolName, opts) => {
|
|
1104
1104
|
const cfg = loadConfig();
|
|
1105
|
-
const
|
|
1106
|
-
if (!
|
|
1105
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
1106
|
+
if (!agentId3) {
|
|
1107
1107
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
1108
1108
|
process.exit(1);
|
|
1109
1109
|
}
|
|
@@ -1119,7 +1119,7 @@ ${sym.ok} Tool created`);
|
|
|
1119
1119
|
try {
|
|
1120
1120
|
const client = makeClient();
|
|
1121
1121
|
const result = await client.run.once({
|
|
1122
|
-
agentId:
|
|
1122
|
+
agentId: agentId3,
|
|
1123
1123
|
messages: [{ role: "user", content: prompt }],
|
|
1124
1124
|
...cfg.initiator && { initiatorId: cfg.initiator }
|
|
1125
1125
|
});
|
|
@@ -1448,8 +1448,8 @@ ${sym.ok} Workflow created`);
|
|
|
1448
1448
|
}
|
|
1449
1449
|
const templateName = templateNameRaw;
|
|
1450
1450
|
const needsAgent = templateName === "agent-research-summary" || templateName === "multi-agent-field-report";
|
|
1451
|
-
const
|
|
1452
|
-
if (needsAgent && !
|
|
1451
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
1452
|
+
if (needsAgent && !agentId3) {
|
|
1453
1453
|
console.error(c.error("This template requires --agent <agentId> or a configured defaultAgentId."));
|
|
1454
1454
|
process.exit(1);
|
|
1455
1455
|
}
|
|
@@ -1473,7 +1473,7 @@ ${sym.ok} Workflow created`);
|
|
|
1473
1473
|
const ctx = {
|
|
1474
1474
|
ownerId: cfg.initiator,
|
|
1475
1475
|
prefix,
|
|
1476
|
-
agentId:
|
|
1476
|
+
agentId: agentId3,
|
|
1477
1477
|
reviewerAgentId: opts.reviewerAgent,
|
|
1478
1478
|
childWorkflowId
|
|
1479
1479
|
};
|
|
@@ -1493,7 +1493,7 @@ ${sym.ok} Workflow created`);
|
|
|
1493
1493
|
}
|
|
1494
1494
|
}
|
|
1495
1495
|
execution = await makeClient().workflows.execute(result.workflow.workflowId, {
|
|
1496
|
-
agentId:
|
|
1496
|
+
agentId: agentId3,
|
|
1497
1497
|
inputData,
|
|
1498
1498
|
userId: cfg.initiator
|
|
1499
1499
|
});
|
|
@@ -1564,7 +1564,7 @@ ${sym.ok} Execution started: ${c.id(execution.executionId)}`);
|
|
|
1564
1564
|
});
|
|
1565
1565
|
cmd.command("run <workflowId>").description("Execute a workflow").option("--agent <agentId>", "Agent context").option("--session <sessionId>", "Session context").option("--input <json>", "Input data as JSON string", "{}").option("--watch", "Stream execution progress via SSE").option("--json", "Output result as JSON").action(async (workflowId, opts) => {
|
|
1566
1566
|
const cfg = loadConfig();
|
|
1567
|
-
const
|
|
1567
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
1568
1568
|
let inputData = {};
|
|
1569
1569
|
try {
|
|
1570
1570
|
inputData = JSON.parse(opts.input);
|
|
@@ -1576,7 +1576,7 @@ ${sym.ok} Execution started: ${c.id(execution.executionId)}`);
|
|
|
1576
1576
|
try {
|
|
1577
1577
|
const client = makeClient();
|
|
1578
1578
|
const execution = await client.workflows.execute(workflowId, {
|
|
1579
|
-
agentId:
|
|
1579
|
+
agentId: agentId3,
|
|
1580
1580
|
sessionId: opts.session,
|
|
1581
1581
|
inputData
|
|
1582
1582
|
});
|
|
@@ -1721,12 +1721,12 @@ function taskCommand() {
|
|
|
1721
1721
|
const cmd = new import_commander7.Command("task").description("Manage and execute tasks").alias("t");
|
|
1722
1722
|
cmd.command("list").description("List tasks").option("--agent <agentId>", "Filter by agent ID").option("--session <sessionId>", "Filter by session ID").option("--json", "Output as JSON").action(async (opts) => {
|
|
1723
1723
|
const cfg = loadConfig();
|
|
1724
|
-
const
|
|
1724
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
1725
1725
|
const spinner = spin("Fetching tasks\u2026");
|
|
1726
1726
|
try {
|
|
1727
1727
|
const client = makeClient();
|
|
1728
1728
|
const filter = {};
|
|
1729
|
-
if (
|
|
1729
|
+
if (agentId3) filter.agentId = agentId3;
|
|
1730
1730
|
if (opts.session) filter.sessionId = opts.session;
|
|
1731
1731
|
if (cfg.initiator) {
|
|
1732
1732
|
filter.ownerId = cfg.initiator;
|
|
@@ -1782,8 +1782,8 @@ function taskCommand() {
|
|
|
1782
1782
|
});
|
|
1783
1783
|
cmd.command("create").description("Create a new task").requiredOption("--title <title>", "Task title").option("--agent <agentId>", "Agent ID").option("--session <sessionId>", "Session ID").option("--workflow <workflowId>", "Workflow ID to attach").option("--input <json>", "Input data as JSON", "{}").option("--timeout <ms>", "Execution timeout in milliseconds").option("--execute", "Execute immediately after creation").option("--watch", "Stream execution progress (implies --execute)").option("--json", "Output as JSON").action(async (opts) => {
|
|
1784
1784
|
const cfg = loadConfig();
|
|
1785
|
-
const
|
|
1786
|
-
if (!
|
|
1785
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
1786
|
+
if (!agentId3) {
|
|
1787
1787
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
1788
1788
|
process.exit(1);
|
|
1789
1789
|
}
|
|
@@ -1799,7 +1799,7 @@ function taskCommand() {
|
|
|
1799
1799
|
const client = makeClient();
|
|
1800
1800
|
const res = await client.tasks.create({
|
|
1801
1801
|
title: opts.title,
|
|
1802
|
-
agentId:
|
|
1802
|
+
agentId: agentId3,
|
|
1803
1803
|
sessionId: opts.session,
|
|
1804
1804
|
workflowId: opts.workflow,
|
|
1805
1805
|
inputData,
|
|
@@ -1905,14 +1905,237 @@ ${sym.fail} ${c.error(event.message ?? event.type)}`);
|
|
|
1905
1905
|
// src/commands/run.ts
|
|
1906
1906
|
var import_commander8 = require("commander");
|
|
1907
1907
|
var readline2 = __toESM(require("readline"));
|
|
1908
|
+
var import_fs6 = require("fs");
|
|
1909
|
+
var import_path4 = require("path");
|
|
1908
1910
|
|
|
1909
1911
|
// src/local-tools.ts
|
|
1910
1912
|
var import_fs5 = require("fs");
|
|
1911
1913
|
var import_path3 = require("path");
|
|
1912
1914
|
var import_child_process2 = require("child_process");
|
|
1915
|
+
var import_crypto = require("crypto");
|
|
1913
1916
|
var readline = __toESM(require("readline"));
|
|
1917
|
+
|
|
1918
|
+
// src/edit-preview.ts
|
|
1919
|
+
function editPreview(before, after, limit = 12e3) {
|
|
1920
|
+
if (before === after) return "(no content change)";
|
|
1921
|
+
const oldLines = before ? before.split("\n") : [];
|
|
1922
|
+
const newLines = after ? after.split("\n") : [];
|
|
1923
|
+
let start = 0;
|
|
1924
|
+
while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) start++;
|
|
1925
|
+
let oldEnd = oldLines.length, newEnd = newLines.length;
|
|
1926
|
+
while (oldEnd > start && newEnd > start && oldLines[oldEnd - 1] === newLines[newEnd - 1]) {
|
|
1927
|
+
oldEnd--;
|
|
1928
|
+
newEnd--;
|
|
1929
|
+
}
|
|
1930
|
+
const lines = [
|
|
1931
|
+
`@@ -${start + 1},${oldEnd - start} +${start + 1},${newEnd - start} @@`,
|
|
1932
|
+
...oldLines.slice(Math.max(0, start - 3), start).map((line) => ` ${line}`),
|
|
1933
|
+
...oldLines.slice(start, oldEnd).map((line) => `-${line}`),
|
|
1934
|
+
...newLines.slice(start, newEnd).map((line) => `+${line}`),
|
|
1935
|
+
...newLines.slice(newEnd, newEnd + 3).map((line) => ` ${line}`)
|
|
1936
|
+
];
|
|
1937
|
+
const preview = lines.join("\n").replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "?");
|
|
1938
|
+
return preview.length > limit ? preview.slice(0, limit) + "\n\u2026 (preview truncated)" : preview;
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
// src/disk-usage.ts
|
|
1942
|
+
var import_node_fs = require("fs");
|
|
1943
|
+
var import_node_path = require("path");
|
|
1944
|
+
async function scanDiskUsage(root, signal, allowPath) {
|
|
1945
|
+
if (!(await import_node_fs.promises.lstat(root)).isDirectory()) throw new Error("disk_usage requires a directory");
|
|
1946
|
+
const deadline = Date.now() + 15e3;
|
|
1947
|
+
const limit = 5e4;
|
|
1948
|
+
let scanned = 0;
|
|
1949
|
+
let skipped = 0;
|
|
1950
|
+
let incomplete = false;
|
|
1951
|
+
const measure = async (start) => {
|
|
1952
|
+
let bytes = 0;
|
|
1953
|
+
const pending = [start];
|
|
1954
|
+
while (pending.length) {
|
|
1955
|
+
if (signal?.aborted) throw new Error("Disk usage scan cancelled");
|
|
1956
|
+
if (scanned >= limit || Date.now() >= deadline) {
|
|
1957
|
+
incomplete = true;
|
|
1958
|
+
break;
|
|
1959
|
+
}
|
|
1960
|
+
const path = pending.pop();
|
|
1961
|
+
try {
|
|
1962
|
+
allowPath(path);
|
|
1963
|
+
const item = await import_node_fs.promises.lstat(path);
|
|
1964
|
+
scanned += 1;
|
|
1965
|
+
if (item.isSymbolicLink()) {
|
|
1966
|
+
skipped += 1;
|
|
1967
|
+
continue;
|
|
1968
|
+
}
|
|
1969
|
+
if (item.isDirectory()) {
|
|
1970
|
+
for await (const child of await import_node_fs.promises.opendir(path)) {
|
|
1971
|
+
if (pending.length + scanned >= limit || Date.now() >= deadline) {
|
|
1972
|
+
incomplete = true;
|
|
1973
|
+
break;
|
|
1974
|
+
}
|
|
1975
|
+
pending.push((0, import_node_path.join)(path, child.name));
|
|
1976
|
+
}
|
|
1977
|
+
} else if (item.isFile()) bytes += item.size;
|
|
1978
|
+
} catch {
|
|
1979
|
+
skipped += 1;
|
|
1980
|
+
}
|
|
1981
|
+
}
|
|
1982
|
+
return bytes;
|
|
1983
|
+
};
|
|
1984
|
+
const entries = [];
|
|
1985
|
+
for await (const child of await import_node_fs.promises.opendir(root)) {
|
|
1986
|
+
if (incomplete) break;
|
|
1987
|
+
if (child.isSymbolicLink()) {
|
|
1988
|
+
skipped += 1;
|
|
1989
|
+
continue;
|
|
1990
|
+
}
|
|
1991
|
+
const path = (0, import_node_path.join)(root, child.name);
|
|
1992
|
+
try {
|
|
1993
|
+
allowPath(path);
|
|
1994
|
+
} catch {
|
|
1995
|
+
skipped += 1;
|
|
1996
|
+
continue;
|
|
1997
|
+
}
|
|
1998
|
+
entries.push({ path: child.name, kind: child.isDirectory() ? "directory" : "file", sizeBytes: await measure(path) });
|
|
1999
|
+
}
|
|
2000
|
+
entries.sort((left, right) => right.sizeBytes - left.sizeBytes);
|
|
2001
|
+
return {
|
|
2002
|
+
scope: root,
|
|
2003
|
+
unit: "logical file bytes",
|
|
2004
|
+
entries: entries.slice(0, 30),
|
|
2005
|
+
scanned,
|
|
2006
|
+
skipped,
|
|
2007
|
+
incomplete,
|
|
2008
|
+
note: incomplete ? "The bounded scan stopped early. Sizes may be underestimates; narrow the path and scan again." : "Sizes cover this selected folder only, not the whole computer."
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
// src/office-text.ts
|
|
2013
|
+
var import_zlib = require("zlib");
|
|
2014
|
+
var MAX_ENTRY_BYTES = 4e7;
|
|
2015
|
+
function readEntries(buffer) {
|
|
2016
|
+
const floor = Math.max(0, buffer.length - 65557);
|
|
2017
|
+
let end = -1;
|
|
2018
|
+
for (let index = buffer.length - 22; index >= floor; index -= 1) {
|
|
2019
|
+
if (buffer.readUInt32LE(index) === 101010256) {
|
|
2020
|
+
end = index;
|
|
2021
|
+
break;
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
if (end < 0) throw new Error("Not a zip archive");
|
|
2025
|
+
const count = buffer.readUInt16LE(end + 10);
|
|
2026
|
+
let cursor = buffer.readUInt32LE(end + 16);
|
|
2027
|
+
const entries = [];
|
|
2028
|
+
for (let index = 0; index < count && cursor + 46 <= buffer.length; index += 1) {
|
|
2029
|
+
if (buffer.readUInt32LE(cursor) !== 33639248) break;
|
|
2030
|
+
const method = buffer.readUInt16LE(cursor + 10);
|
|
2031
|
+
const compressedSize = buffer.readUInt32LE(cursor + 20);
|
|
2032
|
+
const nameLength = buffer.readUInt16LE(cursor + 28);
|
|
2033
|
+
const extraLength = buffer.readUInt16LE(cursor + 30);
|
|
2034
|
+
const commentLength = buffer.readUInt16LE(cursor + 32);
|
|
2035
|
+
const offset = buffer.readUInt32LE(cursor + 42);
|
|
2036
|
+
const name = buffer.toString("utf8", cursor + 46, cursor + 46 + nameLength);
|
|
2037
|
+
entries.push({ name, method, compressedSize, offset });
|
|
2038
|
+
cursor += 46 + nameLength + extraLength + commentLength;
|
|
2039
|
+
}
|
|
2040
|
+
return entries;
|
|
2041
|
+
}
|
|
2042
|
+
function readEntry(buffer, entry) {
|
|
2043
|
+
if (buffer.readUInt32LE(entry.offset) !== 67324752) throw new Error("Corrupt zip entry");
|
|
2044
|
+
const nameLength = buffer.readUInt16LE(entry.offset + 26);
|
|
2045
|
+
const extraLength = buffer.readUInt16LE(entry.offset + 28);
|
|
2046
|
+
const start = entry.offset + 30 + nameLength + extraLength;
|
|
2047
|
+
const data = buffer.subarray(start, start + entry.compressedSize);
|
|
2048
|
+
if (entry.method === 0) return data.toString("utf8");
|
|
2049
|
+
if (entry.method === 8) {
|
|
2050
|
+
return (0, import_zlib.inflateRawSync)(data, { maxOutputLength: MAX_ENTRY_BYTES }).toString("utf8");
|
|
2051
|
+
}
|
|
2052
|
+
throw new Error(`Unsupported zip compression method ${entry.method}`);
|
|
2053
|
+
}
|
|
2054
|
+
function decodeXml(value) {
|
|
2055
|
+
return value.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code))).replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16))).replace(/&/g, "&");
|
|
2056
|
+
}
|
|
2057
|
+
function docxText(xml) {
|
|
2058
|
+
const paragraphs = xml.match(/<w:p[\s>][\s\S]*?<\/w:p>/g) ?? [];
|
|
2059
|
+
const lines = paragraphs.map((paragraph) => {
|
|
2060
|
+
const style = /<w:pStyle w:val="([^"]+)"/.exec(paragraph)?.[1] ?? "";
|
|
2061
|
+
const heading = /^(?:Heading|heading)\s?(\d)$/.exec(style)?.[1] ?? (style === "Title" ? "1" : "");
|
|
2062
|
+
const listItem = /<w:numPr>/.test(paragraph);
|
|
2063
|
+
const text = paragraph.replace(/<w:tab\/>/g, " ").replace(/<w:(?:br|cr)\/>/g, "\n").match(/<w:t(?:\s[^>]*)?>[\s\S]*?<\/w:t>|\t|\n/g)?.map((part) => part === " " || part === "\n" ? part : decodeXml(part.replace(/<[^>]+>/g, ""))).join("") ?? "";
|
|
2064
|
+
if (!text.trim()) return "";
|
|
2065
|
+
if (heading) return `${"#".repeat(Math.min(6, Number(heading)))} ${text.trim()}`;
|
|
2066
|
+
return listItem ? `- ${text.trim()}` : text;
|
|
2067
|
+
});
|
|
2068
|
+
return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
2069
|
+
}
|
|
2070
|
+
function drawingText(xml) {
|
|
2071
|
+
const paragraphs = xml.match(/<a:p[\s>][\s\S]*?<\/a:p>/g) ?? [];
|
|
2072
|
+
return paragraphs.map(
|
|
2073
|
+
(paragraph) => (paragraph.match(/<a:t>[\s\S]*?<\/a:t>/g) ?? []).map((part) => decodeXml(part.replace(/<[^>]+>/g, ""))).join("")
|
|
2074
|
+
).filter((line) => line.trim()).join("\n");
|
|
2075
|
+
}
|
|
2076
|
+
function slideNumber(name) {
|
|
2077
|
+
return Number(/(\d+)\.xml$/.exec(name)?.[1] ?? 0);
|
|
2078
|
+
}
|
|
2079
|
+
function extractOfficeOpenXmlText(buffer, extension) {
|
|
2080
|
+
let entries;
|
|
2081
|
+
try {
|
|
2082
|
+
entries = readEntries(buffer);
|
|
2083
|
+
} catch {
|
|
2084
|
+
return null;
|
|
2085
|
+
}
|
|
2086
|
+
const find = (name) => entries.find((entry) => entry.name === name);
|
|
2087
|
+
try {
|
|
2088
|
+
if (extension === ".docx") {
|
|
2089
|
+
const document = find("word/document.xml");
|
|
2090
|
+
return document ? docxText(readEntry(buffer, document)) : null;
|
|
2091
|
+
}
|
|
2092
|
+
if (extension === ".pptx") {
|
|
2093
|
+
const slides = entries.filter((entry) => /^ppt\/slides\/slide\d+\.xml$/.test(entry.name)).sort((left, right) => slideNumber(left.name) - slideNumber(right.name));
|
|
2094
|
+
if (!slides.length) return null;
|
|
2095
|
+
return slides.map((slide) => `## Slide ${slideNumber(slide.name)}
|
|
2096
|
+
${drawingText(readEntry(buffer, slide))}`).join("\n\n").trim();
|
|
2097
|
+
}
|
|
2098
|
+
if (extension === ".xlsx") {
|
|
2099
|
+
const shared = find("xl/sharedStrings.xml");
|
|
2100
|
+
const strings = shared ? (readEntry(buffer, shared).match(/<si>[\s\S]*?<\/si>/g) ?? []).map(
|
|
2101
|
+
(item) => (item.match(/<t(?:\s[^>]*)?>[\s\S]*?<\/t>/g) ?? []).map((part) => decodeXml(part.replace(/<[^>]+>/g, ""))).join("")
|
|
2102
|
+
) : [];
|
|
2103
|
+
const sheets = entries.filter((entry) => /^xl\/worksheets\/sheet\d+\.xml$/.test(entry.name)).sort((left, right) => slideNumber(left.name) - slideNumber(right.name));
|
|
2104
|
+
if (!sheets.length) return null;
|
|
2105
|
+
return sheets.map((sheet) => {
|
|
2106
|
+
const rows = (readEntry(buffer, sheet).match(/<row[\s\S]*?<\/row>/g) ?? []).slice(0, 2e3).map(
|
|
2107
|
+
(row) => (row.match(/<c[\s\S]*?<\/c>|<c[^>]*\/>/g) ?? []).map((cell) => {
|
|
2108
|
+
const value = /<v>([\s\S]*?)<\/v>/.exec(cell)?.[1] ?? /<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/.exec(cell)?.[1] ?? "";
|
|
2109
|
+
return /\bt="s"/.test(cell) ? strings[Number(value)] ?? "" : decodeXml(value);
|
|
2110
|
+
}).join(" ")
|
|
2111
|
+
);
|
|
2112
|
+
return `## Sheet ${slideNumber(sheet.name)}
|
|
2113
|
+
${rows.join("\n")}`;
|
|
2114
|
+
}).join("\n\n").trim();
|
|
2115
|
+
}
|
|
2116
|
+
} catch {
|
|
2117
|
+
return null;
|
|
2118
|
+
}
|
|
2119
|
+
return null;
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
// src/local-tools.ts
|
|
1914
2123
|
var pdfParse = require("pdf-parse/lib/pdf-parse.js");
|
|
1915
2124
|
var managedProcesses = /* @__PURE__ */ new Map();
|
|
2125
|
+
function stopProcessTree(proc) {
|
|
2126
|
+
const pid = proc.child.pid;
|
|
2127
|
+
if (!pid) return;
|
|
2128
|
+
if (process.platform === "win32") {
|
|
2129
|
+
const killer = (0, import_child_process2.spawn)("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
2130
|
+
killer.on("error", () => proc.child.kill("SIGTERM"));
|
|
2131
|
+
} else {
|
|
2132
|
+
try {
|
|
2133
|
+
process.kill(-pid, "SIGTERM");
|
|
2134
|
+
} catch {
|
|
2135
|
+
proc.child.kill("SIGTERM");
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
1916
2139
|
function capBuffer(existing, chunk, maxBytes) {
|
|
1917
2140
|
const joined = existing + chunk;
|
|
1918
2141
|
if (joined.length <= maxBytes) return joined;
|
|
@@ -1949,12 +2172,8 @@ function buildDirSnapshot(dir, maxDepth = 2) {
|
|
|
1949
2172
|
}
|
|
1950
2173
|
function readFileForContext(rootDir, filePath) {
|
|
1951
2174
|
try {
|
|
1952
|
-
const abs = (
|
|
1953
|
-
|
|
1954
|
-
if (rel.startsWith("..") || rel.startsWith("/")) return `[error: path escapes session root]`;
|
|
1955
|
-
for (const pat of [/\/\.ssh\//, /\/\.aws\//, /\/\.env$/, /\/\.env\./, /id_rsa/, /id_ed25519/]) {
|
|
1956
|
-
if (pat.test(abs)) return `[error: sensitive path blocked]`;
|
|
1957
|
-
}
|
|
2175
|
+
const abs = safePath(rootDir, filePath);
|
|
2176
|
+
assertNotSensitive(abs);
|
|
1958
2177
|
if (!(0, import_fs5.existsSync)(abs)) return `[error: file not found: ${filePath}]`;
|
|
1959
2178
|
const stat = (0, import_fs5.statSync)(abs);
|
|
1960
2179
|
if (stat.isDirectory()) return `[error: "${filePath}" is a directory \u2014 use list_directory]`;
|
|
@@ -1976,6 +2195,7 @@ ${fileContextBlocks.join("\n\n")}
|
|
|
1976
2195
|
You are running inside a CLI session with DIRECT access to the user's local machine. The following tools are in your tool list and execute on the user's machine in real time.
|
|
1977
2196
|
|
|
1978
2197
|
**Session root:** ${rootDir}
|
|
2198
|
+
Use paths relative to this root: "." lists the selected folder; "file.txt" reads a file directly inside it. Do not prefix relative paths with the selected folder's own name. The current root overrides folder names in older messages.
|
|
1979
2199
|
|
|
1980
2200
|
### Current file system (live snapshot)
|
|
1981
2201
|
|
|
@@ -1999,9 +2219,11 @@ ${fileSection}
|
|
|
1999
2219
|
| Tool | What it does |
|
|
2000
2220
|
|------|-------------|
|
|
2001
2221
|
| \`cli_list_directory\` | List files and folders at a path |
|
|
2002
|
-
| \`cli_read_file\` | Read a file (PDF and Word docs are extracted to text) |
|
|
2222
|
+
| \`cli_read_file\` | Read a bounded part of a file (PDF and Word docs are extracted to text) |
|
|
2223
|
+
| \`cli_search_file\` | Find passages and character offsets inside one large document |
|
|
2003
2224
|
| \`cli_write_file\` | Write or overwrite a file (user confirmation required) |
|
|
2004
2225
|
| \`cli_search_files\` | Find files matching a pattern |
|
|
2226
|
+
| \`cli_disk_usage\` | Measure and rank file and folder sizes inside the selected root (read only; bounded scan) |
|
|
2005
2227
|
| \`cli_run_command\` | Run a short command and return its output (user confirmation required) |
|
|
2006
2228
|
| \`cli_start_process\` | Start a long-running command in the background; returns a processId immediately |
|
|
2007
2229
|
| \`cli_wait_for_process\` | Block up to N seconds for a background process, then return current output |
|
|
@@ -2060,102 +2282,60 @@ function extractToolCall(text) {
|
|
|
2060
2282
|
}
|
|
2061
2283
|
return null;
|
|
2062
2284
|
}
|
|
2063
|
-
function injectAgcTrailer(command, args,
|
|
2285
|
+
function injectAgcTrailer(command, args, agentId3, agentName) {
|
|
2064
2286
|
if (command !== "git") return args;
|
|
2065
2287
|
if (!args.some((a) => a === "commit")) return args;
|
|
2066
2288
|
if (args.some((a) => a.includes("Co-Authored-By: agc"))) return args;
|
|
2067
|
-
const identity = agentName ? `${agentName} (agc)` :
|
|
2289
|
+
const identity = agentName ? `${agentName} (agc)` : agentId3 ? `agc/${agentId3}` : "agc agent";
|
|
2068
2290
|
return [...args, "--trailer", `Co-Authored-By: ${identity} <agc-agent@users.noreply.github.com>`];
|
|
2069
2291
|
}
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
const
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
if (
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
function installGitHook(rootDir, sessionId, agentId2, agentName) {
|
|
2085
|
-
const gitDir = findGitDir(rootDir);
|
|
2086
|
-
if (!gitDir) return;
|
|
2087
|
-
const hooksDir = (0, import_path3.join)(gitDir, "hooks");
|
|
2088
|
-
(0, import_fs5.mkdirSync)(hooksDir, { recursive: true });
|
|
2089
|
-
const hookPath = (0, import_path3.join)(hooksDir, "prepare-commit-msg");
|
|
2090
|
-
if ((0, import_fs5.existsSync)(hookPath)) {
|
|
2091
|
-
const existing = (0, import_fs5.readFileSync)(hookPath, "utf8");
|
|
2092
|
-
if (!existing.includes(AGC_HOOK_MARKER)) {
|
|
2093
|
-
(0, import_fs5.writeFileSync)(hookPath + HOOK_BACKUP_SUFFIX, existing, { mode: 493 });
|
|
2292
|
+
function safePath(root, userPath) {
|
|
2293
|
+
const canonicalRoot = (0, import_fs5.realpathSync)(root);
|
|
2294
|
+
const abs = (0, import_path3.resolve)(canonicalRoot, userPath);
|
|
2295
|
+
const inside = (path) => {
|
|
2296
|
+
const rel = (0, import_path3.relative)(canonicalRoot, path);
|
|
2297
|
+
return rel !== ".." && !rel.startsWith(`..${import_path3.sep}`) && !(0, import_path3.isAbsolute)(rel);
|
|
2298
|
+
};
|
|
2299
|
+
if (!inside(abs) && !(0, import_path3.isAbsolute)(userPath)) throw new Error(`Path "${userPath}" escapes the session root. Access denied.`);
|
|
2300
|
+
let ancestor = abs;
|
|
2301
|
+
while (!(0, import_fs5.existsSync)(ancestor)) {
|
|
2302
|
+
try {
|
|
2303
|
+
if ((0, import_fs5.lstatSync)(ancestor).isSymbolicLink()) throw new Error("Dangling symlink is not allowed.");
|
|
2304
|
+
} catch (error) {
|
|
2305
|
+
if (error.code !== "ENOENT") throw error;
|
|
2094
2306
|
}
|
|
2307
|
+
const parent = (0, import_path3.dirname)(ancestor);
|
|
2308
|
+
if (parent === ancestor) throw new Error("Cannot resolve path.");
|
|
2309
|
+
ancestor = parent;
|
|
2095
2310
|
}
|
|
2096
|
-
const
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
` : "";
|
|
2102
|
-
const hook = `#!/bin/sh
|
|
2103
|
-
${AGC_HOOK_MARKER}${sessionId}
|
|
2104
|
-
COMMIT_MSG_FILE="$1"
|
|
2105
|
-
COMMIT_SOURCE="$2"
|
|
2106
|
-
${chainLine}
|
|
2107
|
-
case "$COMMIT_SOURCE" in merge|squash) exit 0 ;; esac
|
|
2108
|
-
TRAILER="${trailer}"
|
|
2109
|
-
grep -qF "$TRAILER" "$COMMIT_MSG_FILE" 2>/dev/null && exit 0
|
|
2110
|
-
printf '\\n%s\\n' "$TRAILER" >> "$COMMIT_MSG_FILE"
|
|
2111
|
-
`;
|
|
2112
|
-
(0, import_fs5.writeFileSync)(hookPath, hook, { mode: 493 });
|
|
2113
|
-
}
|
|
2114
|
-
function removeGitHook(rootDir) {
|
|
2115
|
-
const gitDir = findGitDir(rootDir);
|
|
2116
|
-
if (!gitDir) return;
|
|
2117
|
-
const hookPath = (0, import_path3.join)(gitDir, "hooks", "prepare-commit-msg");
|
|
2118
|
-
if (!(0, import_fs5.existsSync)(hookPath)) return;
|
|
2119
|
-
const content = (0, import_fs5.readFileSync)(hookPath, "utf8");
|
|
2120
|
-
if (!content.includes(AGC_HOOK_MARKER)) return;
|
|
2121
|
-
const backupPath = hookPath + HOOK_BACKUP_SUFFIX;
|
|
2122
|
-
if ((0, import_fs5.existsSync)(backupPath)) {
|
|
2123
|
-
(0, import_fs5.writeFileSync)(hookPath, (0, import_fs5.readFileSync)(backupPath, "utf8"), { mode: 493 });
|
|
2124
|
-
(0, import_fs5.unlinkSync)(backupPath);
|
|
2125
|
-
} else {
|
|
2126
|
-
(0, import_fs5.unlinkSync)(hookPath);
|
|
2127
|
-
}
|
|
2311
|
+
const canonicalAncestor = (0, import_fs5.realpathSync)(ancestor);
|
|
2312
|
+
if (!inside(canonicalAncestor)) throw new Error(`Path "${userPath}" resolves outside the session root. Access denied.`);
|
|
2313
|
+
assertNotSensitive(abs);
|
|
2314
|
+
assertNotSensitive(canonicalAncestor);
|
|
2315
|
+
return (0, import_path3.resolve)(canonicalAncestor, (0, import_path3.relative)(ancestor, abs));
|
|
2128
2316
|
}
|
|
2129
|
-
function
|
|
2130
|
-
const
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2317
|
+
function readPath(root, userPath) {
|
|
2318
|
+
const path = safePath(root, userPath);
|
|
2319
|
+
if ((0, import_fs5.existsSync)(path) || (0, import_path3.isAbsolute)(userPath)) return path;
|
|
2320
|
+
const parts = userPath.split(/[\\/]/).filter(Boolean);
|
|
2321
|
+
if (parts[0] === (0, import_path3.basename)((0, import_fs5.realpathSync)(root))) {
|
|
2322
|
+
const candidate = safePath(root, parts.slice(1).join(import_path3.sep) || ".");
|
|
2323
|
+
if ((0, import_fs5.existsSync)(candidate)) return candidate;
|
|
2134
2324
|
}
|
|
2135
|
-
return
|
|
2325
|
+
return path;
|
|
2136
2326
|
}
|
|
2137
|
-
var BLOCKED_PATTERNS = [
|
|
2138
|
-
/\/\.ssh\//,
|
|
2139
|
-
/\/\.gnupg\//,
|
|
2140
|
-
/\/\.agc\//,
|
|
2141
|
-
/\/\.aws\//,
|
|
2142
|
-
/\/\.env$/,
|
|
2143
|
-
/\/\.env\./,
|
|
2144
|
-
/id_rsa/,
|
|
2145
|
-
/id_ed25519/
|
|
2146
|
-
];
|
|
2147
2327
|
function assertNotSensitive(abs) {
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
}
|
|
2328
|
+
const segments = abs.split(/[\\/]/);
|
|
2329
|
+
if (segments.some((part) => /^(?:\.ssh|\.gnupg|\.agc|\.aws|\.env(?:\..*)?|id_rsa|id_ed25519)$/i.test(part))) {
|
|
2330
|
+
throw new Error(`Access to "${abs}" is blocked for security reasons.`);
|
|
2152
2331
|
}
|
|
2153
2332
|
}
|
|
2154
2333
|
async function confirm(message, config, permissionKey) {
|
|
2155
|
-
if (config.autoApprove) return true;
|
|
2156
2334
|
const cached = config.permissions.get(permissionKey);
|
|
2157
2335
|
if (cached === "allow") return true;
|
|
2158
2336
|
if (cached === "deny") return false;
|
|
2337
|
+
if (config.autoApprove) return true;
|
|
2338
|
+
if (config.confirm) return config.confirm(message, permissionKey);
|
|
2159
2339
|
return new Promise((resolve2) => {
|
|
2160
2340
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
2161
2341
|
process.stdout.write(
|
|
@@ -2164,22 +2344,23 @@ async function confirm(message, config, permissionKey) {
|
|
|
2164
2344
|
\x1B[2m[y] Yes [n] No [A] Always allow this type [N] Never allow this type\x1B[0m
|
|
2165
2345
|
\x1B[36m?\x1B[0m `
|
|
2166
2346
|
);
|
|
2347
|
+
rl.once("close", () => resolve2(false));
|
|
2167
2348
|
rl.once("line", (answer) => {
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
if (a === "a") {
|
|
2349
|
+
const a = answer.trim();
|
|
2350
|
+
if (a === "A") {
|
|
2171
2351
|
config.permissions.set(permissionKey, "allow");
|
|
2172
2352
|
resolve2(true);
|
|
2173
|
-
} else if (a === "
|
|
2353
|
+
} else if (a === "N") {
|
|
2174
2354
|
config.permissions.set(permissionKey, "deny");
|
|
2175
2355
|
resolve2(false);
|
|
2176
2356
|
} else {
|
|
2177
|
-
resolve2(a === "y" || a === "yes"
|
|
2357
|
+
resolve2(a.toLowerCase() === "y" || a.toLowerCase() === "yes");
|
|
2178
2358
|
}
|
|
2359
|
+
rl.close();
|
|
2179
2360
|
});
|
|
2180
2361
|
});
|
|
2181
2362
|
}
|
|
2182
|
-
var OFFICE_EXTS = /* @__PURE__ */ new Set([".docx", ".doc", ".rtf", ".odt", ".pages"]);
|
|
2363
|
+
var OFFICE_EXTS = /* @__PURE__ */ new Set([".docx", ".doc", ".rtf", ".odt", ".pages", ".pptx", ".xlsx"]);
|
|
2183
2364
|
var PDF_EXTS = /* @__PURE__ */ new Set([".pdf"]);
|
|
2184
2365
|
var UNREADABLE_BINARY_EXTS = /* @__PURE__ */ new Set([
|
|
2185
2366
|
".png",
|
|
@@ -2211,9 +2392,7 @@ var UNREADABLE_BINARY_EXTS = /* @__PURE__ */ new Set([
|
|
|
2211
2392
|
".ai",
|
|
2212
2393
|
".sketch",
|
|
2213
2394
|
".figma",
|
|
2214
|
-
".xlsx",
|
|
2215
2395
|
".xls",
|
|
2216
|
-
".pptx",
|
|
2217
2396
|
".ppt"
|
|
2218
2397
|
]);
|
|
2219
2398
|
function extractViaCommand(cmd, cmdArgs) {
|
|
@@ -2224,17 +2403,16 @@ function extractViaCommand(cmd, cmdArgs) {
|
|
|
2224
2403
|
});
|
|
2225
2404
|
});
|
|
2226
2405
|
}
|
|
2227
|
-
async function extractPdfText(abs) {
|
|
2406
|
+
async function extractPdfText(abs, maxChars = 15e4) {
|
|
2228
2407
|
try {
|
|
2229
2408
|
const buffer = (0, import_fs5.readFileSync)(abs);
|
|
2230
2409
|
const data = await pdfParse(buffer);
|
|
2231
2410
|
const text2 = data.text?.trim();
|
|
2232
2411
|
if (text2) {
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
return text2.slice(0, MAX_CHARS) + `
|
|
2412
|
+
if (text2.length > maxChars) {
|
|
2413
|
+
return text2.slice(0, maxChars) + `
|
|
2236
2414
|
|
|
2237
|
-
[\u2026truncated \u2014 showing first ${
|
|
2415
|
+
[\u2026truncated \u2014 showing first ${maxChars.toLocaleString()} characters of ${text2.length.toLocaleString()} total]`;
|
|
2238
2416
|
}
|
|
2239
2417
|
return text2;
|
|
2240
2418
|
}
|
|
@@ -2245,52 +2423,134 @@ async function extractPdfText(abs) {
|
|
|
2245
2423
|
return `[Cannot extract PDF text: the file may be scanned/image-only or password-protected]`;
|
|
2246
2424
|
}
|
|
2247
2425
|
async function extractOfficeText(abs, ext) {
|
|
2426
|
+
const openXml = extractOfficeOpenXmlText((0, import_fs5.readFileSync)(abs), ext);
|
|
2427
|
+
if (openXml) return openXml;
|
|
2248
2428
|
const text = await extractViaCommand("textutil", ["-stdout", "-cat", "txt", abs]);
|
|
2249
2429
|
if (text) return text;
|
|
2250
|
-
return `[Cannot extract ${ext} text:
|
|
2430
|
+
return `[Cannot extract ${ext} text: this document format is not supported on this system]`;
|
|
2431
|
+
}
|
|
2432
|
+
var documentTextCache = /* @__PURE__ */ new Map();
|
|
2433
|
+
async function cachedDocumentText(abs, stat, ext) {
|
|
2434
|
+
const cached = documentTextCache.get(abs);
|
|
2435
|
+
if (cached?.size === stat.size && cached.mtimeMs === stat.mtimeMs) return cached.text;
|
|
2436
|
+
const text = PDF_EXTS.has(ext) ? await extractPdfText(abs, Number.MAX_SAFE_INTEGER) : await extractOfficeText(abs, ext);
|
|
2437
|
+
documentTextCache.delete(abs);
|
|
2438
|
+
if (text.length <= 2e6) documentTextCache.set(abs, { size: stat.size, mtimeMs: stat.mtimeMs, text });
|
|
2439
|
+
while (documentTextCache.size > 4) documentTextCache.delete(documentTextCache.keys().next().value);
|
|
2440
|
+
return text;
|
|
2251
2441
|
}
|
|
2252
2442
|
async function toolReadFile(args, cfg) {
|
|
2253
2443
|
const { path: userPath } = args;
|
|
2254
2444
|
if (!userPath) throw new Error('read_file requires a "path" argument');
|
|
2255
|
-
const abs =
|
|
2445
|
+
const abs = readPath(cfg.rootDir, userPath);
|
|
2256
2446
|
assertNotSensitive(abs);
|
|
2257
|
-
if (!(0, import_fs5.existsSync)(abs)) throw new Error(`File not found: ${userPath}
|
|
2447
|
+
if (!(0, import_fs5.existsSync)(abs)) throw new Error(`File not found: ${userPath} (resolved to ${abs}). List the parent directory and use a path relative to the selected workspace root: ${cfg.rootDir}.`);
|
|
2258
2448
|
const stat = (0, import_fs5.statSync)(abs);
|
|
2259
2449
|
if (stat.isDirectory()) throw new Error(`"${userPath}" is a directory, not a file`);
|
|
2260
2450
|
const ext = (0, import_path3.extname)(abs).toLowerCase();
|
|
2261
2451
|
if (PDF_EXTS.has(ext)) {
|
|
2262
2452
|
if (stat.size > 5e7) throw new Error(`PDF too large to read (${Math.round(stat.size / 1e6)} MB). Max 50 MB.`);
|
|
2263
|
-
return
|
|
2453
|
+
return pageFileText(await cachedDocumentText(abs, stat, ext), args.offset, userPath, true);
|
|
2264
2454
|
}
|
|
2265
2455
|
if (OFFICE_EXTS.has(ext)) {
|
|
2266
2456
|
if (stat.size > 2e7) throw new Error(`Document too large to read (${Math.round(stat.size / 1e6)} MB). Max 20 MB.`);
|
|
2267
|
-
return
|
|
2457
|
+
return pageFileText(await cachedDocumentText(abs, stat, ext), args.offset, userPath, true);
|
|
2268
2458
|
}
|
|
2269
2459
|
if (UNREADABLE_BINARY_EXTS.has(ext)) {
|
|
2270
2460
|
throw new Error(`Cannot read binary file "${userPath}" (${ext} format). Only text, PDF, and Office documents are supported.`);
|
|
2271
2461
|
}
|
|
2272
2462
|
if (stat.size > 5e5) throw new Error(`File too large to read (${Math.round(stat.size / 1024)} KB). Max 500 KB.`);
|
|
2273
|
-
return (0, import_fs5.readFileSync)(abs, "utf8");
|
|
2463
|
+
return pageFileText((0, import_fs5.readFileSync)(abs, "utf8"), args.offset, userPath, false);
|
|
2464
|
+
}
|
|
2465
|
+
async function toolSearchFile(args, cfg) {
|
|
2466
|
+
const path = String(args.path ?? "").trim();
|
|
2467
|
+
const query = String(args.query ?? "").trim().slice(0, 120);
|
|
2468
|
+
if (!path || !query) throw new Error("search_file requires a path and search query");
|
|
2469
|
+
const abs = safePath(cfg.rootDir, path);
|
|
2470
|
+
assertNotSensitive(abs);
|
|
2471
|
+
if (!(0, import_fs5.existsSync)(abs)) throw new Error(`File not found: ${path}`);
|
|
2472
|
+
const stat = (0, import_fs5.statSync)(abs);
|
|
2473
|
+
if (!stat.isFile()) throw new Error(`"${path}" is not a file`);
|
|
2474
|
+
const ext = (0, import_path3.extname)(abs).toLowerCase();
|
|
2475
|
+
if (PDF_EXTS.has(ext) && stat.size > 5e7) throw new Error("PDF exceeds the 50 MB Local read limit");
|
|
2476
|
+
if (OFFICE_EXTS.has(ext) && stat.size > 2e7) throw new Error("Document exceeds the 20 MB Local read limit");
|
|
2477
|
+
if (UNREADABLE_BINARY_EXTS.has(ext)) throw new Error(`Cannot search binary file "${path}"`);
|
|
2478
|
+
if (!PDF_EXTS.has(ext) && !OFFICE_EXTS.has(ext) && stat.size > 5e5) throw new Error("Text file exceeds the 500 KB Local read limit");
|
|
2479
|
+
const text = PDF_EXTS.has(ext) || OFFICE_EXTS.has(ext) ? await cachedDocumentText(abs, stat, ext) : (0, import_fs5.readFileSync)(abs, "utf8");
|
|
2480
|
+
return JSON.stringify(searchTextPassages(text, path, query, "Use cli_read_file with a matching offset for more context."));
|
|
2481
|
+
}
|
|
2482
|
+
function searchTextPassages(text, path, rawQuery, hint) {
|
|
2483
|
+
const query = rawQuery.trim().slice(0, 120);
|
|
2484
|
+
if (!query) throw new Error("A search query is required");
|
|
2485
|
+
const lower = text.toLowerCase();
|
|
2486
|
+
const phrase = query.toLowerCase();
|
|
2487
|
+
const terms = [...new Set(phrase.match(/[\p{L}\p{N}]{3,}/gu) ?? [])].slice(0, 8);
|
|
2488
|
+
const positions = [];
|
|
2489
|
+
const collect2 = (needle) => {
|
|
2490
|
+
let offset = 0;
|
|
2491
|
+
while (positions.length < 5e3) {
|
|
2492
|
+
const found = lower.indexOf(needle, offset);
|
|
2493
|
+
if (found < 0) break;
|
|
2494
|
+
positions.push(found);
|
|
2495
|
+
offset = found + Math.max(needle.length, 1);
|
|
2496
|
+
}
|
|
2497
|
+
};
|
|
2498
|
+
collect2(phrase);
|
|
2499
|
+
if (!positions.length) for (const term of terms) collect2(term);
|
|
2500
|
+
const ranked = positions.map((offset) => {
|
|
2501
|
+
const start = Math.max(0, offset - 180);
|
|
2502
|
+
const end = Math.min(text.length, offset + 320);
|
|
2503
|
+
const excerpt = text.slice(start, end).replace(/\s+/g, " ").trim();
|
|
2504
|
+
const score = terms.filter((term) => excerpt.toLowerCase().includes(term)).length;
|
|
2505
|
+
return { offset, score, excerpt };
|
|
2506
|
+
}).sort((a, b) => b.score - a.score || b.offset - a.offset);
|
|
2507
|
+
const selected = [];
|
|
2508
|
+
for (const match of ranked) {
|
|
2509
|
+
if (selected.some((entry) => Math.abs(entry.offset - match.offset) < 250)) continue;
|
|
2510
|
+
selected.push(match);
|
|
2511
|
+
if (selected.length >= 8) break;
|
|
2512
|
+
}
|
|
2513
|
+
return { path, query, totalChars: text.length, matches: selected.map(({ offset, excerpt }) => ({ offset, excerpt })), hint };
|
|
2514
|
+
}
|
|
2515
|
+
function pageFileText(text, rawOffset, path, includeTail) {
|
|
2516
|
+
const offset = rawOffset === void 0 ? 0 : Number(rawOffset);
|
|
2517
|
+
if (!Number.isSafeInteger(offset) || offset < 0 || offset > text.length) throw new Error("read_file offset must be a character position within the file");
|
|
2518
|
+
if (offset === 0 && text.length <= 7e3) return text;
|
|
2519
|
+
const end = Math.min(text.length, offset + 6e3);
|
|
2520
|
+
const next = end < text.length ? ` Use cli_read_file with path ${JSON.stringify(path)} and offset ${end} to continue.` : "";
|
|
2521
|
+
const tail = includeTail && offset === 0 && end < text.length - 1500 ? `
|
|
2522
|
+
|
|
2523
|
+
[Final 1,500 characters of document]
|
|
2524
|
+
${text.slice(-1500)}` : "";
|
|
2525
|
+
return `[Showing characters ${offset}-${end} of ${text.length}.${next}]
|
|
2526
|
+
${text.slice(offset, end)}${tail}`;
|
|
2274
2527
|
}
|
|
2275
2528
|
async function toolWriteFile(args, cfg) {
|
|
2276
2529
|
const { path: userPath, content } = args;
|
|
2277
2530
|
if (!userPath) throw new Error('write_file requires a "path" argument');
|
|
2278
|
-
if (content
|
|
2531
|
+
if (typeof content !== "string") throw new Error('write_file requires a string "content" argument');
|
|
2279
2532
|
const abs = safePath(cfg.rootDir, userPath);
|
|
2280
2533
|
assertNotSensitive(abs);
|
|
2534
|
+
const before = (0, import_fs5.existsSync)(abs) ? (0, import_fs5.readFileSync)(abs, "utf8") : "";
|
|
2535
|
+
const preview = editPreview(before, content);
|
|
2281
2536
|
const ok = await confirm(
|
|
2282
|
-
`Agent wants to write file: \x1B[1m${abs}\x1B[0m (${String(content).length} chars)
|
|
2537
|
+
`Agent wants to write file: \x1B[1m${abs}\x1B[0m (${String(content).length} chars)
|
|
2538
|
+
${preview}`,
|
|
2283
2539
|
cfg,
|
|
2284
2540
|
"write_file"
|
|
2285
2541
|
);
|
|
2286
2542
|
if (!ok) return "User denied write operation.";
|
|
2287
|
-
|
|
2288
|
-
(0, import_fs5.
|
|
2543
|
+
const checked = safePath(cfg.rootDir, userPath);
|
|
2544
|
+
if (((0, import_fs5.existsSync)(checked) ? (0, import_fs5.readFileSync)(checked, "utf8") : "") !== before) {
|
|
2545
|
+
return "Error: file changed during approval. Read it again before retrying.";
|
|
2546
|
+
}
|
|
2547
|
+
(0, import_fs5.mkdirSync)((0, import_path3.dirname)(checked), { recursive: true });
|
|
2548
|
+
(0, import_fs5.writeFileSync)(checked, content, "utf8");
|
|
2289
2549
|
return `Written ${String(content).length} bytes to ${userPath}`;
|
|
2290
2550
|
}
|
|
2291
2551
|
async function toolListDirectory(args, cfg) {
|
|
2292
2552
|
const userPath = args.path ?? ".";
|
|
2293
|
-
const abs =
|
|
2553
|
+
const abs = readPath(cfg.rootDir, userPath);
|
|
2294
2554
|
assertNotSensitive(abs);
|
|
2295
2555
|
if (!(0, import_fs5.existsSync)(abs)) throw new Error(`Directory not found: ${userPath}`);
|
|
2296
2556
|
const entries = (0, import_fs5.readdirSync)(abs, { withFileTypes: true });
|
|
@@ -2298,12 +2558,18 @@ async function toolListDirectory(args, cfg) {
|
|
|
2298
2558
|
const type = e.isDirectory() ? "d" : e.isSymbolicLink() ? "l" : "f";
|
|
2299
2559
|
return `[${type}] ${e.name}`;
|
|
2300
2560
|
});
|
|
2301
|
-
return
|
|
2561
|
+
return `Directory: ${abs}
|
|
2562
|
+
Session root: ${(0, import_fs5.realpathSync)(cfg.rootDir)}
|
|
2563
|
+
${lines.join("\n") || "(empty directory)"}`;
|
|
2564
|
+
}
|
|
2565
|
+
async function toolDiskUsage(args, cfg) {
|
|
2566
|
+
const root = safePath(cfg.rootDir, String(args.path ?? "."));
|
|
2567
|
+
return JSON.stringify(await scanDiskUsage(root, cfg.signal, assertNotSensitive));
|
|
2302
2568
|
}
|
|
2303
2569
|
async function toolSearchFiles(args, cfg) {
|
|
2304
2570
|
const { pattern, directory } = args;
|
|
2305
2571
|
if (!pattern) throw new Error('search_files requires a "pattern" argument');
|
|
2306
|
-
const baseDir =
|
|
2572
|
+
const baseDir = readPath(cfg.rootDir, directory ?? ".");
|
|
2307
2573
|
assertNotSensitive(baseDir);
|
|
2308
2574
|
const results = [];
|
|
2309
2575
|
const pat = new RegExp(
|
|
@@ -2359,9 +2625,10 @@ async function toolRunCommand(args, cfg) {
|
|
|
2359
2625
|
});
|
|
2360
2626
|
}
|
|
2361
2627
|
return new Promise((resolve2) => {
|
|
2362
|
-
(0, import_child_process2.execFile)(command, injectedArgs.map(String), { cwd: workDir, timeout: timeoutMs, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => {
|
|
2628
|
+
(0, import_child_process2.execFile)(command, injectedArgs.map(String), { cwd: workDir, timeout: timeoutMs, maxBuffer: 1024 * 1024, signal: cfg.signal }, (err, stdout, stderr) => {
|
|
2363
2629
|
const out = [stdout, stderr].filter(Boolean).join("\n--- stderr ---\n");
|
|
2364
|
-
if (err
|
|
2630
|
+
if (err) return resolve2(`Error: command failed (${err.code ?? "unknown"}): ${err.message}
|
|
2631
|
+
${out}`);
|
|
2365
2632
|
resolve2(out || "(no output)");
|
|
2366
2633
|
});
|
|
2367
2634
|
});
|
|
@@ -2379,11 +2646,14 @@ async function toolStartProcess(args, cfg) {
|
|
|
2379
2646
|
"start_process"
|
|
2380
2647
|
);
|
|
2381
2648
|
if (!ok) return JSON.stringify({ error: "User denied process start." });
|
|
2382
|
-
const
|
|
2649
|
+
const finished = [...managedProcesses.values()].filter((proc2) => proc2.status !== "running");
|
|
2650
|
+
for (const proc2 of finished.slice(0, Math.max(0, finished.length - 99))) managedProcesses.delete(proc2.id);
|
|
2651
|
+
const id = `proc_${(0, import_crypto.randomUUID)()}`;
|
|
2383
2652
|
const child = (0, import_child_process2.spawn)(command, cmdArgs.map(String), {
|
|
2384
2653
|
cwd: workDir,
|
|
2385
2654
|
stdio: ["ignore", "pipe", "pipe"],
|
|
2386
|
-
detached:
|
|
2655
|
+
detached: process.platform !== "win32",
|
|
2656
|
+
windowsHide: true
|
|
2387
2657
|
});
|
|
2388
2658
|
const proc = {
|
|
2389
2659
|
id,
|
|
@@ -2396,6 +2666,10 @@ async function toolStartProcess(args, cfg) {
|
|
|
2396
2666
|
endedAt: null,
|
|
2397
2667
|
child
|
|
2398
2668
|
};
|
|
2669
|
+
if (cfg.signal) {
|
|
2670
|
+
if (cfg.signal.aborted) stopProcessTree(proc);
|
|
2671
|
+
else cfg.signal.addEventListener("abort", () => stopProcessTree(proc), { once: true });
|
|
2672
|
+
}
|
|
2399
2673
|
child.stdout?.on("data", (chunk) => {
|
|
2400
2674
|
proc.stdout = capBuffer(proc.stdout, chunk.toString(), 2e5);
|
|
2401
2675
|
});
|
|
@@ -2403,7 +2677,7 @@ async function toolStartProcess(args, cfg) {
|
|
|
2403
2677
|
proc.stderr = capBuffer(proc.stderr, chunk.toString(), 5e4);
|
|
2404
2678
|
});
|
|
2405
2679
|
child.on("close", (code) => {
|
|
2406
|
-
proc.status = code === 0 ? "done" : "error";
|
|
2680
|
+
if (proc.status !== "killed") proc.status = code === 0 ? "done" : "error";
|
|
2407
2681
|
proc.exitCode = code;
|
|
2408
2682
|
proc.endedAt = /* @__PURE__ */ new Date();
|
|
2409
2683
|
});
|
|
@@ -2443,7 +2717,8 @@ async function toolWaitForProcess(args, _cfg) {
|
|
|
2443
2717
|
const proc = managedProcesses.get(processId);
|
|
2444
2718
|
if (!proc) return JSON.stringify({ error: `No process found with id "${processId}"` });
|
|
2445
2719
|
if (proc.status !== "running") return processSnapshot(proc);
|
|
2446
|
-
const
|
|
2720
|
+
const requested = typeof wait_seconds === "number" && Number.isFinite(wait_seconds) ? wait_seconds : 60;
|
|
2721
|
+
const maxWait = Math.max(0, Math.min(requested, 60)) * 1e3;
|
|
2447
2722
|
const deadline = Date.now() + maxWait;
|
|
2448
2723
|
await new Promise((resolve2) => {
|
|
2449
2724
|
const tick = setInterval(() => {
|
|
@@ -2461,7 +2736,7 @@ async function toolKillProcess(args, cfg) {
|
|
|
2461
2736
|
const proc = managedProcesses.get(processId);
|
|
2462
2737
|
if (!proc) return JSON.stringify({ error: `No process found with id "${processId}"` });
|
|
2463
2738
|
if (proc.status !== "running") return JSON.stringify({ error: `Process "${processId}" is not running (status: ${proc.status})` });
|
|
2464
|
-
proc
|
|
2739
|
+
stopProcessTree(proc);
|
|
2465
2740
|
proc.status = "killed";
|
|
2466
2741
|
proc.endedAt = /* @__PURE__ */ new Date();
|
|
2467
2742
|
cfg.appendLog({ type: "process_killed", processId, timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
@@ -2477,6 +2752,15 @@ async function toolListProcesses(_args, _cfg) {
|
|
|
2477
2752
|
}));
|
|
2478
2753
|
return JSON.stringify(list);
|
|
2479
2754
|
}
|
|
2755
|
+
function stopLocalProcesses() {
|
|
2756
|
+
for (const proc of managedProcesses.values()) {
|
|
2757
|
+
if (proc.status === "running") {
|
|
2758
|
+
stopProcessTree(proc);
|
|
2759
|
+
proc.status = "killed";
|
|
2760
|
+
proc.endedAt = /* @__PURE__ */ new Date();
|
|
2761
|
+
}
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2480
2764
|
async function runLocalTool(call, cfg) {
|
|
2481
2765
|
const { tool, args } = call;
|
|
2482
2766
|
cfg.appendLog({
|
|
@@ -2491,6 +2775,9 @@ async function runLocalTool(call, cfg) {
|
|
|
2491
2775
|
case "read_file":
|
|
2492
2776
|
result = await toolReadFile(args, cfg);
|
|
2493
2777
|
break;
|
|
2778
|
+
case "search_file":
|
|
2779
|
+
result = await toolSearchFile(args, cfg);
|
|
2780
|
+
break;
|
|
2494
2781
|
case "write_file":
|
|
2495
2782
|
result = await toolWriteFile(args, cfg);
|
|
2496
2783
|
break;
|
|
@@ -2500,6 +2787,9 @@ async function runLocalTool(call, cfg) {
|
|
|
2500
2787
|
case "search_files":
|
|
2501
2788
|
result = await toolSearchFiles(args, cfg);
|
|
2502
2789
|
break;
|
|
2790
|
+
case "disk_usage":
|
|
2791
|
+
result = await toolDiskUsage(args, cfg);
|
|
2792
|
+
break;
|
|
2503
2793
|
case "run_command":
|
|
2504
2794
|
result = await toolRunCommand(args, cfg);
|
|
2505
2795
|
break;
|
|
@@ -2519,7 +2809,7 @@ async function runLocalTool(call, cfg) {
|
|
|
2519
2809
|
result = await toolListProcesses(args, cfg);
|
|
2520
2810
|
break;
|
|
2521
2811
|
default:
|
|
2522
|
-
result = `Unknown tool: "${tool}". Available: read_file, write_file, list_directory, search_files, run_command, start_process, wait_for_process, process_status, kill_process, list_processes`;
|
|
2812
|
+
result = `Unknown tool: "${tool}". Available: read_file, search_file, write_file, list_directory, search_files, disk_usage, run_command, start_process, wait_for_process, process_status, kill_process, list_processes`;
|
|
2523
2813
|
}
|
|
2524
2814
|
} catch (err) {
|
|
2525
2815
|
result = `Error: ${err?.message ?? String(err)}`;
|
|
@@ -2536,19 +2826,72 @@ async function runLocalTool(call, cfg) {
|
|
|
2536
2826
|
|
|
2537
2827
|
// src/commands/run.ts
|
|
2538
2828
|
function runCommand() {
|
|
2539
|
-
|
|
2829
|
+
const append = (value, previous) => [...previous, value];
|
|
2830
|
+
return new import_commander8.Command("run").description("Send a single prompt to an agent and stream the response").argument("<prompt>", "Prompt text to send").option("--agent <agentId>", "Agent ID").option("--file <path>", "Upload and attach a file (repeatable, up to 25 MB each)", append, []).option("--attach <fileId>", "Attach an existing Library file ID (repeatable)", append, []).option("--session <sessionId>", "Resume an existing session by ID").option(
|
|
2831
|
+
"--new-session",
|
|
2832
|
+
"Create a new session and print its ID for future use"
|
|
2833
|
+
).option(
|
|
2834
|
+
"--computer",
|
|
2835
|
+
"Give the agent access to its persistent cloud computer"
|
|
2836
|
+
).option(
|
|
2837
|
+
"--local",
|
|
2838
|
+
"Enable local file system access (with permission prompts)"
|
|
2839
|
+
).option(
|
|
2840
|
+
"-y, --yes",
|
|
2841
|
+
"Enable local file system access and auto-approve all operations"
|
|
2842
|
+
).option("--no-stream", "Disable streaming (wait for full response)").option("--json", "Output raw event stream as JSON lines").option(
|
|
2843
|
+
"--provenance <mode>",
|
|
2844
|
+
"Provenance capture: off, metadata, or full",
|
|
2845
|
+
"metadata"
|
|
2846
|
+
).option(
|
|
2847
|
+
"--onchain-provenance",
|
|
2848
|
+
"Request an optional on-chain anchor for this run"
|
|
2849
|
+
).action(async (prompt, opts) => {
|
|
2540
2850
|
const cfg = loadConfig();
|
|
2541
|
-
const
|
|
2542
|
-
if (!
|
|
2543
|
-
console.error(
|
|
2851
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
2852
|
+
if (!agentId3) {
|
|
2853
|
+
console.error(
|
|
2854
|
+
c.error(
|
|
2855
|
+
"Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"
|
|
2856
|
+
)
|
|
2857
|
+
);
|
|
2544
2858
|
process.exit(1);
|
|
2545
2859
|
}
|
|
2546
2860
|
if (opts.session && opts.newSession) {
|
|
2547
|
-
console.error(
|
|
2861
|
+
console.error(
|
|
2862
|
+
c.error("Cannot use --session and --new-session together.")
|
|
2863
|
+
);
|
|
2864
|
+
process.exit(1);
|
|
2865
|
+
}
|
|
2866
|
+
if (!["off", "metadata", "full"].includes(opts.provenance)) {
|
|
2867
|
+
console.error(c.error("--provenance must be off, metadata, or full."));
|
|
2868
|
+
process.exit(1);
|
|
2869
|
+
}
|
|
2870
|
+
if (opts.onchainProvenance && opts.provenance === "off") {
|
|
2871
|
+
console.error(
|
|
2872
|
+
c.error("--onchain-provenance requires metadata or full capture.")
|
|
2873
|
+
);
|
|
2548
2874
|
process.exit(1);
|
|
2549
2875
|
}
|
|
2550
2876
|
const client = makeClient();
|
|
2551
2877
|
let sessionId = opts.session;
|
|
2878
|
+
const filePaths = opts.file;
|
|
2879
|
+
const attachmentIds = opts.attach;
|
|
2880
|
+
if (filePaths.length + attachmentIds.length > 10) {
|
|
2881
|
+
console.error(c.error("Attach no more than 10 files to a run."));
|
|
2882
|
+
process.exit(1);
|
|
2883
|
+
}
|
|
2884
|
+
try {
|
|
2885
|
+
for (const path of filePaths) {
|
|
2886
|
+
const stat = (0, import_fs6.statSync)(path);
|
|
2887
|
+
if (!stat.isFile() || stat.size < 1 || stat.size > 25 * 1024 * 1024) {
|
|
2888
|
+
throw new Error(`Choose a non-empty file up to 25 MB: ${path}`);
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
} catch (error) {
|
|
2892
|
+
printError(error);
|
|
2893
|
+
process.exit(1);
|
|
2894
|
+
}
|
|
2552
2895
|
if (opts.session) {
|
|
2553
2896
|
const spinner = spin("Loading session\u2026");
|
|
2554
2897
|
try {
|
|
@@ -2564,7 +2907,7 @@ function runCommand() {
|
|
|
2564
2907
|
const spinner = spin("Creating session\u2026");
|
|
2565
2908
|
try {
|
|
2566
2909
|
const res = await client.sessions.create({
|
|
2567
|
-
agentId:
|
|
2910
|
+
agentId: agentId3,
|
|
2568
2911
|
initiator: cfg.initiator ?? "",
|
|
2569
2912
|
title: `agc run ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16)}`,
|
|
2570
2913
|
source: "cli"
|
|
@@ -2578,6 +2921,24 @@ function runCommand() {
|
|
|
2578
2921
|
process.exit(1);
|
|
2579
2922
|
}
|
|
2580
2923
|
}
|
|
2924
|
+
const attachments = attachmentIds.map((fileId) => ({ fileId }));
|
|
2925
|
+
for (const path of filePaths) {
|
|
2926
|
+
const spinner = spin(`Uploading ${(0, import_path4.basename)(path)}\u2026`);
|
|
2927
|
+
try {
|
|
2928
|
+
const result = await client.files.upload(
|
|
2929
|
+
[{ data: new Blob([new Uint8Array((0, import_fs6.readFileSync)(path))]), name: (0, import_path4.basename)(path) }],
|
|
2930
|
+
{ agentId: agentId3, sessionId }
|
|
2931
|
+
);
|
|
2932
|
+
const fileId = result.data[0]?.fileId;
|
|
2933
|
+
if (!fileId) throw new Error(`The upload did not return a file ID for ${path}.`);
|
|
2934
|
+
attachments.push({ fileId });
|
|
2935
|
+
spinner.stop();
|
|
2936
|
+
} catch (error) {
|
|
2937
|
+
spinner.stop();
|
|
2938
|
+
printError(error);
|
|
2939
|
+
process.exit(1);
|
|
2940
|
+
}
|
|
2941
|
+
}
|
|
2581
2942
|
const localEnabled = opts.yes || opts.local;
|
|
2582
2943
|
const autoApprove = !!opts.yes;
|
|
2583
2944
|
let localToolsCfg = null;
|
|
@@ -2590,11 +2951,16 @@ function runCommand() {
|
|
|
2590
2951
|
appendLog: () => {
|
|
2591
2952
|
},
|
|
2592
2953
|
permissions: /* @__PURE__ */ new Map(),
|
|
2593
|
-
agentId:
|
|
2954
|
+
agentId: agentId3,
|
|
2594
2955
|
autoApprove
|
|
2595
2956
|
};
|
|
2596
2957
|
const snapshot = buildDirSnapshot(rootDir, 2);
|
|
2597
|
-
cliContext = buildLocalToolsManifest(
|
|
2958
|
+
cliContext = buildLocalToolsManifest(
|
|
2959
|
+
rootDir,
|
|
2960
|
+
snapshot,
|
|
2961
|
+
[],
|
|
2962
|
+
autoApprove
|
|
2963
|
+
);
|
|
2598
2964
|
}
|
|
2599
2965
|
if (!opts.json) {
|
|
2600
2966
|
const rows = [];
|
|
@@ -2603,10 +2969,16 @@ function runCommand() {
|
|
|
2603
2969
|
rows.push(["Session", label]);
|
|
2604
2970
|
}
|
|
2605
2971
|
if (localEnabled) {
|
|
2606
|
-
rows.push([
|
|
2972
|
+
rows.push([
|
|
2973
|
+
"Local tools",
|
|
2974
|
+
autoApprove ? c.warn("enabled (auto-approve on)") : c.success("enabled")
|
|
2975
|
+
]);
|
|
2607
2976
|
}
|
|
2608
2977
|
if (opts.computer) {
|
|
2609
|
-
rows.push([
|
|
2978
|
+
rows.push([
|
|
2979
|
+
"Cloud computer",
|
|
2980
|
+
c.success("enabled") + c.dim(" (persistent, remote)")
|
|
2981
|
+
]);
|
|
2610
2982
|
}
|
|
2611
2983
|
if (rows.length) {
|
|
2612
2984
|
detail(rows);
|
|
@@ -2614,12 +2986,17 @@ function runCommand() {
|
|
|
2614
2986
|
}
|
|
2615
2987
|
}
|
|
2616
2988
|
const params = {
|
|
2617
|
-
agentId:
|
|
2989
|
+
agentId: agentId3,
|
|
2618
2990
|
sessionId,
|
|
2619
2991
|
messages: [{ role: "user", content: prompt }],
|
|
2992
|
+
...attachments.length && { attachments },
|
|
2620
2993
|
...cfg.initiator && { initiatorId: cfg.initiator },
|
|
2621
2994
|
...opts.computer && { computerRequest: { enabled: true } },
|
|
2622
|
-
...cliContext && { cliContext }
|
|
2995
|
+
...cliContext && { cliContext },
|
|
2996
|
+
provenance: {
|
|
2997
|
+
mode: opts.provenance,
|
|
2998
|
+
onchain: Boolean(opts.onchainProvenance)
|
|
2999
|
+
}
|
|
2623
3000
|
};
|
|
2624
3001
|
if (opts.noStream && !localEnabled) {
|
|
2625
3002
|
const spinner = spin("Running\u2026");
|
|
@@ -2629,8 +3006,13 @@ function runCommand() {
|
|
|
2629
3006
|
if (opts.json) return jsonOut(result);
|
|
2630
3007
|
const text = result?.content ?? result?.text ?? result?.message ?? JSON.stringify(result);
|
|
2631
3008
|
console.log(text);
|
|
2632
|
-
if (sessionId)
|
|
2633
|
-
|
|
3009
|
+
if (sessionId)
|
|
3010
|
+
console.log(
|
|
3011
|
+
c.dim(
|
|
3012
|
+
`
|
|
3013
|
+
Session: ${sessionId} (resume with: agc run --session ${sessionId} "<prompt>")`
|
|
3014
|
+
)
|
|
3015
|
+
);
|
|
2634
3016
|
} catch (err) {
|
|
2635
3017
|
spinner.stop();
|
|
2636
3018
|
printError(err);
|
|
@@ -2662,7 +3044,10 @@ Session: ${sessionId} (resume with: agc run --session ${sessionId} "<prompt>")`
|
|
|
2662
3044
|
let result;
|
|
2663
3045
|
let toolOk = true;
|
|
2664
3046
|
try {
|
|
2665
|
-
result = await runLocalTool(
|
|
3047
|
+
result = await runLocalTool(
|
|
3048
|
+
{ tool: displayName, args: args ?? {} },
|
|
3049
|
+
localToolsCfg
|
|
3050
|
+
);
|
|
2666
3051
|
} catch (err) {
|
|
2667
3052
|
result = `Error: ${err?.message ?? String(err)}`;
|
|
2668
3053
|
toolOk = false;
|
|
@@ -2670,8 +3055,10 @@ Session: ${sessionId} (resume with: agc run --session ${sessionId} "<prompt>")`
|
|
|
2670
3055
|
const elapsed = ((Date.now() - startMs) / 1e3).toFixed(1);
|
|
2671
3056
|
readline2.cursorTo(process.stdout, 0);
|
|
2672
3057
|
readline2.clearLine(process.stdout, 0);
|
|
2673
|
-
process.stdout.write(
|
|
2674
|
-
`)
|
|
3058
|
+
process.stdout.write(
|
|
3059
|
+
` ${c.dim("\u2500")} ${c.bold(displayName)} ${toolOk ? sym.ok : sym.fail} ${c.dim("(" + elapsed + "s)")}
|
|
3060
|
+
`
|
|
3061
|
+
);
|
|
2675
3062
|
try {
|
|
2676
3063
|
await client.agents.submitCliToolResult(requestId, result);
|
|
2677
3064
|
} catch {
|
|
@@ -2688,20 +3075,29 @@ Session: ${sessionId} (resume with: agc run --session ${sessionId} "<prompt>")`
|
|
|
2688
3075
|
const elapsed = ((Date.now() - toolStartMs) / 1e3).toFixed(1);
|
|
2689
3076
|
readline2.cursorTo(process.stdout, 0);
|
|
2690
3077
|
readline2.clearLine(process.stdout, 0);
|
|
2691
|
-
process.stdout.write(
|
|
2692
|
-
`)
|
|
3078
|
+
process.stdout.write(
|
|
3079
|
+
` ${c.dim("\u2500")} ${c.bold(lastToolName)} ${sym.ok} ${c.dim("(" + elapsed + "s)")}
|
|
3080
|
+
`
|
|
3081
|
+
);
|
|
2693
3082
|
} else if (event.type === "final") {
|
|
2694
3083
|
if (hasOutput) process.stdout.write("\n");
|
|
2695
3084
|
const e = event;
|
|
2696
3085
|
const finalText = e.content ?? e.payload?.content ?? e.payload?.text ?? e.payload?.message;
|
|
2697
3086
|
if (finalText && !hasOutput) console.log(finalText);
|
|
2698
|
-
if (sessionId)
|
|
2699
|
-
|
|
3087
|
+
if (sessionId)
|
|
3088
|
+
console.log(
|
|
3089
|
+
c.dim(
|
|
3090
|
+
`
|
|
3091
|
+
Session: ${sessionId} (resume with: agc run --session ${sessionId} "<prompt>")`
|
|
3092
|
+
)
|
|
3093
|
+
);
|
|
2700
3094
|
break;
|
|
2701
3095
|
} else if (event.type === "error") {
|
|
2702
3096
|
if (hasOutput) process.stdout.write("\n");
|
|
2703
|
-
console.error(
|
|
2704
|
-
|
|
3097
|
+
console.error(
|
|
3098
|
+
`
|
|
3099
|
+
${sym.fail} ${c.error(event.message ?? "Error")}`
|
|
3100
|
+
);
|
|
2705
3101
|
process.exit(1);
|
|
2706
3102
|
}
|
|
2707
3103
|
}
|
|
@@ -2716,18 +3112,19 @@ ${sym.fail} ${c.error(event.message ?? "Error")}`);
|
|
|
2716
3112
|
// src/commands/chat.ts
|
|
2717
3113
|
var import_commander9 = require("commander");
|
|
2718
3114
|
var readline3 = __toESM(require("readline"));
|
|
2719
|
-
var
|
|
2720
|
-
var
|
|
3115
|
+
var import_fs7 = require("fs");
|
|
3116
|
+
var import_path5 = require("path");
|
|
2721
3117
|
var import_os3 = require("os");
|
|
2722
|
-
var SESSIONS_DIR = (0,
|
|
3118
|
+
var SESSIONS_DIR = (0, import_path5.join)((0, import_os3.homedir)(), ".agc", "sessions");
|
|
2723
3119
|
function ensureSessionsDir() {
|
|
2724
|
-
if (!(0,
|
|
3120
|
+
if (!(0, import_fs7.existsSync)(SESSIONS_DIR)) (0, import_fs7.mkdirSync)(SESSIONS_DIR, { recursive: true });
|
|
2725
3121
|
}
|
|
2726
3122
|
function appendSessionLog(sessionId, record) {
|
|
2727
3123
|
try {
|
|
3124
|
+
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(sessionId)) return;
|
|
2728
3125
|
ensureSessionsDir();
|
|
2729
|
-
const file = (0,
|
|
2730
|
-
(0,
|
|
3126
|
+
const file = (0, import_path5.join)(SESSIONS_DIR, `${sessionId}.jsonl`);
|
|
3127
|
+
(0, import_fs7.appendFileSync)(file, JSON.stringify(record) + "\n", { mode: 384 });
|
|
2731
3128
|
} catch {
|
|
2732
3129
|
}
|
|
2733
3130
|
}
|
|
@@ -2750,27 +3147,35 @@ var LOCAL_TOOLS_DISCLAIMER = `
|
|
|
2750
3147
|
${c.dim("and execute shell commands on your machine.")}
|
|
2751
3148
|
|
|
2752
3149
|
${c.dim("Rules:")}
|
|
2753
|
-
${sym.bullet} ${c.dim("
|
|
3150
|
+
${sym.bullet} ${c.dim("File tools are restricted to:")} ${c.primary(process.cwd())}
|
|
2754
3151
|
${sym.bullet} ${c.dim("Sensitive paths (.ssh, .env, .aws, credentials) are always blocked")}
|
|
2755
3152
|
${sym.bullet} ${c.dim("Write and run_command operations require your confirmation")}
|
|
2756
|
-
${sym.bullet} ${c.dim("
|
|
3153
|
+
${sym.bullet} ${c.dim("Approved commands run with your operating-system permissions; they are not sandboxed")}
|
|
2757
3154
|
|
|
2758
3155
|
${c.dim("Session activity is logged to")} ${c.primary("~/.agc/sessions/")}
|
|
2759
3156
|
`;
|
|
2760
3157
|
function chatCommand() {
|
|
2761
|
-
return new import_commander9.Command("chat").description("Start an interactive
|
|
3158
|
+
return new import_commander9.Command("chat").alias("code").description("Start an interactive coding session with an agent").argument("[prompt]", "Initial task to send when the session opens").option("--prompt-file <path>", "Read the initial task from a UTF-8 file (maximum 100 KB)").option("--read-only", "Allow local reads but deny local edits and commands").option("--agent <agentId>", "Agent ID (or set defaultAgentId in config)").option("--resume <sessionId>", "Resume an existing session by ID").option("--computer", "Give the agent access to its persistent cloud computer").option("--no-stream", "Disable token streaming (wait for full response)").option("--no-local", "Disable local file system access for the agent").action(async (prompt, opts) => {
|
|
3159
|
+
let initialPrompt = prompt;
|
|
3160
|
+
if (opts.promptFile) {
|
|
3161
|
+
if (prompt) throw new Error("Use either a prompt argument or --prompt-file, not both.");
|
|
3162
|
+
if ((0, import_fs7.statSync)(opts.promptFile).size > 1e5) throw new Error("Prompt file exceeds 100 KB.");
|
|
3163
|
+
initialPrompt = (0, import_fs7.readFileSync)(opts.promptFile, "utf8").trim();
|
|
3164
|
+
}
|
|
3165
|
+
if (!process.stdin.isTTY) throw new Error("Interactive coding requires a terminal. Use `agc run` for scripts.");
|
|
2762
3166
|
const localEnabled = opts.local !== false;
|
|
3167
|
+
if (localEnabled && opts.stream === false) throw new Error("Local tools require streaming. Use --no-local with --no-stream.");
|
|
2763
3168
|
const cfg = loadConfig();
|
|
2764
|
-
let
|
|
2765
|
-
if (!
|
|
3169
|
+
let agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
3170
|
+
if (!agentId3 && cfg.initiator) {
|
|
2766
3171
|
try {
|
|
2767
3172
|
const listed = await makeClient().agents.list(cfg.initiator);
|
|
2768
3173
|
const agents = listed?.data ?? listed ?? [];
|
|
2769
|
-
|
|
3174
|
+
agentId3 = agents.find((agent) => agent.isDefault)?.agentId ?? agents[0]?.agentId;
|
|
2770
3175
|
} catch {
|
|
2771
3176
|
}
|
|
2772
3177
|
}
|
|
2773
|
-
if (!
|
|
3178
|
+
if (!agentId3) {
|
|
2774
3179
|
console.error(c.error("No default agent is available. Specify --agent <agentId> or run `agc agents list`."));
|
|
2775
3180
|
process.exit(1);
|
|
2776
3181
|
}
|
|
@@ -2786,7 +3191,7 @@ function chatCommand() {
|
|
|
2786
3191
|
const spinner = spin("Creating session\u2026");
|
|
2787
3192
|
try {
|
|
2788
3193
|
const res = await client.sessions.create({
|
|
2789
|
-
agentId:
|
|
3194
|
+
agentId: agentId3,
|
|
2790
3195
|
initiator,
|
|
2791
3196
|
title: `agc chat ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 16)}`,
|
|
2792
3197
|
source: "cli"
|
|
@@ -2797,7 +3202,7 @@ function chatCommand() {
|
|
|
2797
3202
|
appendSessionLog(sessionId, {
|
|
2798
3203
|
type: "session_start",
|
|
2799
3204
|
sessionId,
|
|
2800
|
-
agentId:
|
|
3205
|
+
agentId: agentId3,
|
|
2801
3206
|
initiator,
|
|
2802
3207
|
source: "cli",
|
|
2803
3208
|
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -2812,12 +3217,8 @@ function chatCommand() {
|
|
|
2812
3217
|
try {
|
|
2813
3218
|
const res = await client.sessions.get(sessionId);
|
|
2814
3219
|
const session = res?.data ?? res;
|
|
2815
|
-
if (session.agentId
|
|
2816
|
-
|
|
2817
|
-
console.log(c.warn(` Note: session ${sessionId} was created with agent ${session.agentId}, not ${agentId2}`));
|
|
2818
|
-
} else {
|
|
2819
|
-
spinner.stop();
|
|
2820
|
-
}
|
|
3220
|
+
if (session.agentId) agentId3 = session.agentId;
|
|
3221
|
+
spinner.stop();
|
|
2821
3222
|
} catch {
|
|
2822
3223
|
spinner.stop();
|
|
2823
3224
|
console.error(c.error(`Session "${sessionId}" not found.`));
|
|
@@ -2827,10 +3228,10 @@ function chatCommand() {
|
|
|
2827
3228
|
let agentName;
|
|
2828
3229
|
let walletLine = "";
|
|
2829
3230
|
await Promise.allSettled([
|
|
2830
|
-
client.agents.get(
|
|
3231
|
+
client.agents.get(agentId3).then((res) => {
|
|
2831
3232
|
agentName = (res?.data ?? res)?.name;
|
|
2832
3233
|
}),
|
|
2833
|
-
client.wallets.primary(
|
|
3234
|
+
client.wallets.primary(agentId3).then(async (primary) => {
|
|
2834
3235
|
const w = primary?.data ?? primary;
|
|
2835
3236
|
if (w?.id) {
|
|
2836
3237
|
const bal = await client.wallets.balance(w.id).catch(() => null);
|
|
@@ -2842,9 +3243,9 @@ function chatCommand() {
|
|
|
2842
3243
|
})
|
|
2843
3244
|
]);
|
|
2844
3245
|
console.log(`
|
|
2845
|
-
${c.bold("Agent Commons
|
|
3246
|
+
${c.bold("Agent Commons \xB7 Code")}`);
|
|
2846
3247
|
const headerRows = [
|
|
2847
|
-
["Agent", agentName ? `${agentName} ${c.dim(
|
|
3248
|
+
["Agent", agentName ? `${agentName} ${c.dim(agentId3)}` : agentId3],
|
|
2848
3249
|
["Session", c.id(sessionId) + (isResume ? c.dim(" (resumed)") : c.dim(" (new)"))]
|
|
2849
3250
|
];
|
|
2850
3251
|
if (walletLine) headerRows.push(["Wallet", walletLine]);
|
|
@@ -2853,17 +3254,16 @@ ${c.bold("Agent Commons Chat")}`);
|
|
|
2853
3254
|
detail(headerRows);
|
|
2854
3255
|
let localToolsCfg = null;
|
|
2855
3256
|
if (localEnabled) {
|
|
2856
|
-
console.log(LOCAL_TOOLS_DISCLAIMER);
|
|
3257
|
+
console.log(opts.readOnly ? c.dim(" Local read-only mode: edits and commands are denied.\n") : LOCAL_TOOLS_DISCLAIMER);
|
|
2857
3258
|
const rootDir = process.cwd();
|
|
2858
3259
|
localToolsCfg = {
|
|
2859
3260
|
rootDir,
|
|
2860
3261
|
sessionId,
|
|
2861
|
-
agentId:
|
|
3262
|
+
agentId: agentId3,
|
|
2862
3263
|
agentName,
|
|
2863
3264
|
appendLog: (record) => appendSessionLog(sessionId, record),
|
|
2864
|
-
permissions:
|
|
3265
|
+
permissions: new Map(opts.readOnly ? ["write_file", "run_command", "start_process"].map((key) => [key, "deny"]) : [])
|
|
2865
3266
|
};
|
|
2866
|
-
installGitHook(rootDir, sessionId, agentId2, agentName);
|
|
2867
3267
|
appendSessionLog(sessionId, {
|
|
2868
3268
|
type: "local_tools_enabled",
|
|
2869
3269
|
rootDir,
|
|
@@ -2877,8 +3277,10 @@ ${c.bold("Agent Commons Chat")}`);
|
|
|
2877
3277
|
terminal: true,
|
|
2878
3278
|
prompt: c.primary("you") + c.dim(" \u203A ")
|
|
2879
3279
|
});
|
|
2880
|
-
|
|
3280
|
+
let busy = false;
|
|
3281
|
+
if (!initialPrompt) rl.prompt();
|
|
2881
3282
|
rl.on("line", async (line) => {
|
|
3283
|
+
if (busy) return;
|
|
2882
3284
|
const input = line.trim();
|
|
2883
3285
|
if (!input) {
|
|
2884
3286
|
rl.prompt();
|
|
@@ -2931,6 +3333,7 @@ Session saved. Resume with: agc chat --resume ${sessionId}`));
|
|
|
2931
3333
|
rl.prompt();
|
|
2932
3334
|
return;
|
|
2933
3335
|
}
|
|
3336
|
+
busy = true;
|
|
2934
3337
|
rl.pause();
|
|
2935
3338
|
appendSessionLog(sessionId, {
|
|
2936
3339
|
type: "message",
|
|
@@ -2944,6 +3347,11 @@ Session saved. Resume with: agc chat --resume ${sessionId}`));
|
|
|
2944
3347
|
const rootDir = localToolsCfg.rootDir;
|
|
2945
3348
|
const atRefs = [...input.matchAll(/@([\S]+)/g)].map((m) => m[1]);
|
|
2946
3349
|
const fileContextBlocks = [];
|
|
3350
|
+
if ((0, import_fs7.existsSync)((0, import_path5.join)(rootDir, "AGENTS.md"))) {
|
|
3351
|
+
fileContextBlocks.push(`Project instructions (AGENTS.md):
|
|
3352
|
+
${readFileForContext(rootDir, "AGENTS.md")}`);
|
|
3353
|
+
}
|
|
3354
|
+
if (opts.readOnly) fileContextBlocks.push("Local read-only mode: do not write files or execute commands. Local reads are available.");
|
|
2947
3355
|
for (const ref of atRefs) {
|
|
2948
3356
|
const content = readFileForContext(rootDir, ref);
|
|
2949
3357
|
fileContextBlocks.push(`**${ref}**
|
|
@@ -2955,13 +3363,13 @@ ${content}
|
|
|
2955
3363
|
cliContext = buildLocalToolsManifest(rootDir, snapshot, fileContextBlocks);
|
|
2956
3364
|
}
|
|
2957
3365
|
const params = {
|
|
2958
|
-
agentId:
|
|
3366
|
+
agentId: agentId3,
|
|
2959
3367
|
sessionId,
|
|
2960
3368
|
messages: [{ role: "user", content: userMessage }],
|
|
2961
3369
|
...opts.computer && { computerRequest: { enabled: true } },
|
|
2962
3370
|
...cliContext && { cliContext }
|
|
2963
3371
|
};
|
|
2964
|
-
if (opts.
|
|
3372
|
+
if (opts.stream === false) {
|
|
2965
3373
|
process.stdout.write(c.primary("agent") + c.dim(" \u203A "));
|
|
2966
3374
|
const spinner = spin("thinking\u2026");
|
|
2967
3375
|
try {
|
|
@@ -2982,12 +3390,12 @@ ${content}
|
|
|
2982
3390
|
${sym.fail} ${c.error(err.message ?? String(err))}`);
|
|
2983
3391
|
}
|
|
2984
3392
|
} else {
|
|
3393
|
+
const thinkingSpinner = spin("thinking\u2026");
|
|
2985
3394
|
try {
|
|
2986
3395
|
let hasOutput = false;
|
|
2987
3396
|
let agentContent = "";
|
|
2988
3397
|
let toolStartMs = 0;
|
|
2989
3398
|
let lastToolName = "";
|
|
2990
|
-
const thinkingSpinner = spin("thinking\u2026");
|
|
2991
3399
|
for await (const event of client.agents.stream(params)) {
|
|
2992
3400
|
if (event.type === "token") {
|
|
2993
3401
|
if (thinkingSpinner.isSpinning) {
|
|
@@ -3116,36 +3524,53 @@ ${sym.fail} ${c.error(event.message ?? "Stream error")}`);
|
|
|
3116
3524
|
if (thinkingSpinner.isSpinning) thinkingSpinner.stop();
|
|
3117
3525
|
process.stdout.write("\n");
|
|
3118
3526
|
if (localToolsCfg && agentContent) {
|
|
3119
|
-
await handleLocalToolLoop(agentContent, localToolsCfg, client,
|
|
3527
|
+
await handleLocalToolLoop(agentContent, localToolsCfg, client, agentId3, sessionId, appendSessionLog, !!opts.computer);
|
|
3120
3528
|
}
|
|
3121
3529
|
} catch (err) {
|
|
3122
3530
|
process.stdout.write("\n");
|
|
3123
3531
|
console.error(`${sym.fail} ${c.error(err.message ?? String(err))}`);
|
|
3532
|
+
} finally {
|
|
3533
|
+
thinkingSpinner.stop();
|
|
3124
3534
|
}
|
|
3125
3535
|
}
|
|
3126
3536
|
console.log();
|
|
3127
3537
|
readline3.cursorTo(process.stdout, 0);
|
|
3128
3538
|
readline3.clearLine(process.stdout, 0);
|
|
3539
|
+
busy = false;
|
|
3129
3540
|
rl.resume();
|
|
3130
3541
|
rl.prompt();
|
|
3131
3542
|
});
|
|
3132
3543
|
const cleanup = () => {
|
|
3133
|
-
|
|
3544
|
+
stopLocalProcesses();
|
|
3134
3545
|
};
|
|
3135
3546
|
rl.on("close", () => {
|
|
3136
3547
|
cleanup();
|
|
3137
3548
|
process.exit(0);
|
|
3138
3549
|
});
|
|
3550
|
+
rl.on("SIGINT", () => {
|
|
3551
|
+
cleanup();
|
|
3552
|
+
console.log(c.dim(`
|
|
3553
|
+
Session preserved. Resume with: agc code --resume ${sessionId}`));
|
|
3554
|
+
process.exit(130);
|
|
3555
|
+
});
|
|
3139
3556
|
process.on("SIGINT", () => {
|
|
3140
3557
|
cleanup();
|
|
3141
3558
|
console.log(c.dim(`
|
|
3142
3559
|
Session preserved. Resume with: agc chat --resume ${sessionId}`));
|
|
3143
3560
|
process.exit(130);
|
|
3144
3561
|
});
|
|
3562
|
+
process.on("SIGTERM", () => {
|
|
3563
|
+
cleanup();
|
|
3564
|
+
process.exit(143);
|
|
3565
|
+
});
|
|
3566
|
+
if (initialPrompt) {
|
|
3567
|
+
console.log(c.primary("you") + c.dim(" \u203A ") + initialPrompt);
|
|
3568
|
+
rl.emit("line", initialPrompt);
|
|
3569
|
+
}
|
|
3145
3570
|
});
|
|
3146
3571
|
}
|
|
3147
3572
|
var MAX_TOOL_DEPTH = 10;
|
|
3148
|
-
async function handleLocalToolLoop(agentText, cfg, client,
|
|
3573
|
+
async function handleLocalToolLoop(agentText, cfg, client, agentId3, sessionId, appendLog, computerEnabled = false, depth = 0) {
|
|
3149
3574
|
if (depth >= MAX_TOOL_DEPTH) {
|
|
3150
3575
|
console.log(c.dim(`
|
|
3151
3576
|
[local] Max tool depth reached (${MAX_TOOL_DEPTH}). Stopping tool loop.
|
|
@@ -3192,7 +3617,7 @@ ${result}
|
|
|
3192
3617
|
let loopToolName = "";
|
|
3193
3618
|
let loopToolStartMs = 0;
|
|
3194
3619
|
for await (const evt of client.agents.stream({
|
|
3195
|
-
agentId:
|
|
3620
|
+
agentId: agentId3,
|
|
3196
3621
|
sessionId,
|
|
3197
3622
|
messages: [{ role: "user", content: resultMsg }],
|
|
3198
3623
|
...computerEnabled && { computerRequest: { enabled: true } }
|
|
@@ -3238,7 +3663,7 @@ ${sym.fail} ${c.error(evt.message ?? "Stream error")}`);
|
|
|
3238
3663
|
console.error(`${sym.fail} ${c.error(err?.message ?? String(err))}`);
|
|
3239
3664
|
return;
|
|
3240
3665
|
}
|
|
3241
|
-
await handleLocalToolLoop(followContent, cfg, client,
|
|
3666
|
+
await handleLocalToolLoop(followContent, cfg, client, agentId3, sessionId, appendLog, computerEnabled, depth + 1);
|
|
3242
3667
|
}
|
|
3243
3668
|
function truncate(s, max) {
|
|
3244
3669
|
const str = String(s ?? "");
|
|
@@ -3248,6 +3673,8 @@ function toolArgSummary(toolName, args) {
|
|
|
3248
3673
|
switch (toolName) {
|
|
3249
3674
|
case "read_file":
|
|
3250
3675
|
return truncate(args.path ?? "", 60);
|
|
3676
|
+
case "search_file":
|
|
3677
|
+
return truncate(`${args.path ?? ""} \xB7 ${args.query ?? ""}`, 60);
|
|
3251
3678
|
case "write_file":
|
|
3252
3679
|
return truncate(args.path ?? "", 60);
|
|
3253
3680
|
case "delete_file":
|
|
@@ -3283,6 +3710,14 @@ function toolResultPreview(toolName, result) {
|
|
|
3283
3710
|
const lines = result.split("\n").length;
|
|
3284
3711
|
return `${lines} lines`;
|
|
3285
3712
|
}
|
|
3713
|
+
case "search_file": {
|
|
3714
|
+
try {
|
|
3715
|
+
const matches = JSON.parse(result)?.matches;
|
|
3716
|
+
return Array.isArray(matches) ? `${matches.length} passage${matches.length === 1 ? "" : "s"}` : "";
|
|
3717
|
+
} catch {
|
|
3718
|
+
return "";
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3286
3721
|
case "write_file":
|
|
3287
3722
|
return "written";
|
|
3288
3723
|
case "delete_file":
|
|
@@ -3885,19 +4320,19 @@ function walletCommand() {
|
|
|
3885
4320
|
const cmd = new import_commander12.Command("wallet").description("Manage agent wallets");
|
|
3886
4321
|
cmd.command("list").description("List all wallets for an agent").option("--agent <agentId>", "Agent ID (or use defaultAgentId from config)").option("--json", "Output as JSON").action(async (opts) => {
|
|
3887
4322
|
const cfg = loadConfig();
|
|
3888
|
-
const
|
|
3889
|
-
if (!
|
|
4323
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4324
|
+
if (!agentId3) {
|
|
3890
4325
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
3891
4326
|
process.exit(1);
|
|
3892
4327
|
}
|
|
3893
4328
|
const spinner = spin("Fetching wallets\u2026");
|
|
3894
4329
|
try {
|
|
3895
4330
|
const client = makeClient();
|
|
3896
|
-
const wallets = await client.wallets.list(
|
|
4331
|
+
const wallets = await client.wallets.list(agentId3);
|
|
3897
4332
|
spinner.stop();
|
|
3898
4333
|
if (opts.json) return jsonOut(wallets);
|
|
3899
4334
|
const list = wallets?.data ?? wallets ?? [];
|
|
3900
|
-
section(`Wallets for agent ${
|
|
4335
|
+
section(`Wallets for agent ${agentId3.slice(0, 8)}\u2026 (${list.length})`);
|
|
3901
4336
|
table(
|
|
3902
4337
|
list.map((w) => ({
|
|
3903
4338
|
ID: w.id.slice(0, 8) + "\u2026",
|
|
@@ -3917,19 +4352,19 @@ function walletCommand() {
|
|
|
3917
4352
|
});
|
|
3918
4353
|
cmd.command("show").description("Show the agent's primary wallet address").option("--agent <agentId>", "Agent ID (or use defaultAgentId from config)").option("--json", "Output as JSON").action(async (opts) => {
|
|
3919
4354
|
const cfg = loadConfig();
|
|
3920
|
-
const
|
|
3921
|
-
if (!
|
|
4355
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4356
|
+
if (!agentId3) {
|
|
3922
4357
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
3923
4358
|
process.exit(1);
|
|
3924
4359
|
}
|
|
3925
4360
|
const spinner = spin("Fetching primary wallet\u2026");
|
|
3926
4361
|
try {
|
|
3927
4362
|
const client = makeClient();
|
|
3928
|
-
const wallet = await client.wallets.primary(
|
|
4363
|
+
const wallet = await client.wallets.primary(agentId3);
|
|
3929
4364
|
spinner.stop();
|
|
3930
4365
|
if (!wallet) {
|
|
3931
|
-
console.log(c.warn(` No wallet found for agent ${
|
|
3932
|
-
console.log(c.dim(` Run: agc wallet create --agent ${
|
|
4366
|
+
console.log(c.warn(` No wallet found for agent ${agentId3}`));
|
|
4367
|
+
console.log(c.dim(` Run: agc wallet create --agent ${agentId3}`));
|
|
3933
4368
|
return;
|
|
3934
4369
|
}
|
|
3935
4370
|
const w = wallet?.data ?? wallet;
|
|
@@ -3950,8 +4385,8 @@ function walletCommand() {
|
|
|
3950
4385
|
});
|
|
3951
4386
|
cmd.command("balance").description("Show the agent's wallet USDC and ETH balance").option("--agent <agentId>", "Agent ID (or use defaultAgentId from config)").option("--wallet <walletId>", "Specific wallet ID (defaults to primary)").option("--json", "Output as JSON").action(async (opts) => {
|
|
3952
4387
|
const cfg = loadConfig();
|
|
3953
|
-
const
|
|
3954
|
-
if (!
|
|
4388
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4389
|
+
if (!agentId3) {
|
|
3955
4390
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
3956
4391
|
process.exit(1);
|
|
3957
4392
|
}
|
|
@@ -3960,11 +4395,11 @@ function walletCommand() {
|
|
|
3960
4395
|
const client = makeClient();
|
|
3961
4396
|
let walletId = opts.wallet;
|
|
3962
4397
|
if (!walletId) {
|
|
3963
|
-
const primary = await client.wallets.primary(
|
|
4398
|
+
const primary = await client.wallets.primary(agentId3);
|
|
3964
4399
|
const w = primary?.data ?? primary;
|
|
3965
4400
|
if (!w) {
|
|
3966
4401
|
spinner.stop();
|
|
3967
|
-
console.log(c.warn(` No wallet found. Run: agc wallet create --agent ${
|
|
4402
|
+
console.log(c.warn(` No wallet found. Run: agc wallet create --agent ${agentId3}`));
|
|
3968
4403
|
return;
|
|
3969
4404
|
}
|
|
3970
4405
|
walletId = w.id;
|
|
@@ -3991,8 +4426,8 @@ function walletCommand() {
|
|
|
3991
4426
|
});
|
|
3992
4427
|
cmd.command("create").description("Create a new wallet for an agent").option("--agent <agentId>", "Agent ID (or use defaultAgentId from config)").option("--type <type>", "Wallet type: eoa | external (default: eoa)", "eoa").option("--label <label>", "Wallet label (default: Primary)", "Primary").option("--address <address>", "For --type external: owner-provided address").option("--json", "Output as JSON").action(async (opts) => {
|
|
3993
4428
|
const cfg = loadConfig();
|
|
3994
|
-
const
|
|
3995
|
-
if (!
|
|
4429
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4430
|
+
if (!agentId3) {
|
|
3996
4431
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`"));
|
|
3997
4432
|
process.exit(1);
|
|
3998
4433
|
}
|
|
@@ -4004,7 +4439,7 @@ function walletCommand() {
|
|
|
4004
4439
|
try {
|
|
4005
4440
|
const client = makeClient();
|
|
4006
4441
|
const wallet = await client.wallets.create({
|
|
4007
|
-
agentId:
|
|
4442
|
+
agentId: agentId3,
|
|
4008
4443
|
walletType: opts.type,
|
|
4009
4444
|
label: opts.label,
|
|
4010
4445
|
externalAddress: opts.address
|
|
@@ -4162,22 +4597,22 @@ function memoryCommand() {
|
|
|
4162
4597
|
const cmd = new import_commander14.Command("memory").description("View and manage agent memories");
|
|
4163
4598
|
cmd.command("list").description("List memories for an agent").option("--agent <agentId>", "Agent ID (defaults to configured agent)").option("--type <type>", "Filter by type: episodic | semantic | procedural").option("--limit <n>", "Max results", "50").option("--json", "Output as JSON").action(async (opts) => {
|
|
4164
4599
|
const cfg = loadConfig();
|
|
4165
|
-
const
|
|
4166
|
-
if (!
|
|
4600
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4601
|
+
if (!agentId3) {
|
|
4167
4602
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId"));
|
|
4168
4603
|
process.exit(1);
|
|
4169
4604
|
}
|
|
4170
4605
|
const spinner = spin("Fetching memories\u2026");
|
|
4171
4606
|
try {
|
|
4172
4607
|
const client = makeClient();
|
|
4173
|
-
const res = await client.memory.list(
|
|
4608
|
+
const res = await client.memory.list(agentId3, {
|
|
4174
4609
|
type: opts.type,
|
|
4175
4610
|
limit: parseInt(opts.limit, 10)
|
|
4176
4611
|
});
|
|
4177
4612
|
const memories = res?.data ?? res ?? [];
|
|
4178
4613
|
spinner.stop();
|
|
4179
4614
|
if (opts.json) return jsonOut(memories);
|
|
4180
|
-
section(`Memories for ${
|
|
4615
|
+
section(`Memories for ${agentId3.slice(0, 12)}\u2026 (${memories.length})`);
|
|
4181
4616
|
if (memories.length === 0) {
|
|
4182
4617
|
console.log(c.dim(" No memories yet"));
|
|
4183
4618
|
return;
|
|
@@ -4199,15 +4634,15 @@ function memoryCommand() {
|
|
|
4199
4634
|
});
|
|
4200
4635
|
cmd.command("stats").description("Show memory statistics for an agent").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (opts) => {
|
|
4201
4636
|
const cfg = loadConfig();
|
|
4202
|
-
const
|
|
4203
|
-
if (!
|
|
4637
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4638
|
+
if (!agentId3) {
|
|
4204
4639
|
console.error(c.error("Specify --agent <agentId>"));
|
|
4205
4640
|
process.exit(1);
|
|
4206
4641
|
}
|
|
4207
4642
|
const spinner = spin("Fetching stats\u2026");
|
|
4208
4643
|
try {
|
|
4209
4644
|
const client = makeClient();
|
|
4210
|
-
const res = await client.memory.stats(
|
|
4645
|
+
const res = await client.memory.stats(agentId3);
|
|
4211
4646
|
const stats = res?.data ?? res;
|
|
4212
4647
|
spinner.stop();
|
|
4213
4648
|
if (opts.json) return jsonOut(stats);
|
|
@@ -4267,15 +4702,15 @@ ${sym.ok} Memory ${c.id(memoryId)} deleted`);
|
|
|
4267
4702
|
});
|
|
4268
4703
|
cmd.command("search <query>").description("Semantic search over agent memories").option("--agent <agentId>", "Agent ID").option("--limit <n>", "Max results", "10").option("--json", "Output as JSON").action(async (query, opts) => {
|
|
4269
4704
|
const cfg = loadConfig();
|
|
4270
|
-
const
|
|
4271
|
-
if (!
|
|
4705
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4706
|
+
if (!agentId3) {
|
|
4272
4707
|
console.error(c.error("Specify --agent <agentId>"));
|
|
4273
4708
|
process.exit(1);
|
|
4274
4709
|
}
|
|
4275
4710
|
const spinner = spin("Searching memories\u2026");
|
|
4276
4711
|
try {
|
|
4277
4712
|
const client = makeClient();
|
|
4278
|
-
const res = await client.memory.retrieve(
|
|
4713
|
+
const res = await client.memory.retrieve(agentId3, query, parseInt(opts.limit, 10));
|
|
4279
4714
|
const memories = res?.data ?? res ?? [];
|
|
4280
4715
|
spinner.stop();
|
|
4281
4716
|
if (opts.json) return jsonOut(memories);
|
|
@@ -4364,18 +4799,18 @@ function usageCommand() {
|
|
|
4364
4799
|
process.exit(1);
|
|
4365
4800
|
}
|
|
4366
4801
|
});
|
|
4367
|
-
cmd.command("agent <agentId>").description("Show detailed usage for a specific agent").option("--from <date>", "Start date (ISO)").option("--to <date>", "End date (ISO)").option("--json", "Output as JSON").action(async (
|
|
4802
|
+
cmd.command("agent <agentId>").description("Show detailed usage for a specific agent").option("--from <date>", "Start date (ISO)").option("--to <date>", "End date (ISO)").option("--json", "Output as JSON").action(async (agentId3, opts) => {
|
|
4368
4803
|
const spinner = spin("Fetching usage\u2026");
|
|
4369
4804
|
try {
|
|
4370
4805
|
const client = makeClient();
|
|
4371
|
-
const res = await client.usage.getAgentUsage(
|
|
4806
|
+
const res = await client.usage.getAgentUsage(agentId3, {
|
|
4372
4807
|
from: opts.from,
|
|
4373
4808
|
to: opts.to
|
|
4374
4809
|
});
|
|
4375
4810
|
const data = res?.data ?? res;
|
|
4376
4811
|
spinner.stop();
|
|
4377
4812
|
if (opts.json) return jsonOut(data);
|
|
4378
|
-
section(`Usage \u2014 ${
|
|
4813
|
+
section(`Usage \u2014 ${agentId3.slice(0, 12)}\u2026`);
|
|
4379
4814
|
detail([
|
|
4380
4815
|
["Calls", (data.callCount ?? 0).toLocaleString()],
|
|
4381
4816
|
["Input tokens", (data.totalInputTokens ?? 0).toLocaleString()],
|
|
@@ -4512,15 +4947,15 @@ function logsCommand() {
|
|
|
4512
4947
|
const cmd = new import_commander17.Command("logs").description("View agent activity logs");
|
|
4513
4948
|
cmd.command("list").alias("ls").description("List recent log entries for an agent").option("--agent <agentId>", "Agent ID (defaults to configured agent)").option("--session <sessionId>", "Filter by session ID").option("--status <status>", "Filter: success | error | warning").option("--limit <n>", "Max entries to show", "50").option("--json", "Output as JSON").action(async (opts) => {
|
|
4514
4949
|
const cfg = loadConfig();
|
|
4515
|
-
const
|
|
4516
|
-
if (!
|
|
4950
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4951
|
+
if (!agentId3) {
|
|
4517
4952
|
console.error(c.error("Specify --agent <agentId> or set defaultAgentId"));
|
|
4518
4953
|
process.exit(1);
|
|
4519
4954
|
}
|
|
4520
4955
|
const spinner = spin("Fetching logs\u2026");
|
|
4521
4956
|
try {
|
|
4522
4957
|
const client = makeClient();
|
|
4523
|
-
const res = await client.logs.list(
|
|
4958
|
+
const res = await client.logs.list(agentId3, {
|
|
4524
4959
|
limit: Number(opts.limit),
|
|
4525
4960
|
sessionId: opts.session
|
|
4526
4961
|
});
|
|
@@ -4528,7 +4963,7 @@ function logsCommand() {
|
|
|
4528
4963
|
if (opts.status) logs = logs.filter((l) => l.status === opts.status);
|
|
4529
4964
|
spinner.stop();
|
|
4530
4965
|
if (opts.json) return jsonOut(logs);
|
|
4531
|
-
section(`Logs \u2014 ${
|
|
4966
|
+
section(`Logs \u2014 ${agentId3.slice(0, 12)}\u2026 (${logs.length})`);
|
|
4532
4967
|
if (logs.length === 0) {
|
|
4533
4968
|
console.log(c.dim(" No logs yet"));
|
|
4534
4969
|
return;
|
|
@@ -4553,21 +4988,21 @@ function logsCommand() {
|
|
|
4553
4988
|
});
|
|
4554
4989
|
cmd.command("errors").description("Show only error log entries for an agent").option("--agent <agentId>", "Agent ID").option("--limit <n>", "Max entries", "20").option("--json", "Output as JSON").action(async (opts) => {
|
|
4555
4990
|
const cfg = loadConfig();
|
|
4556
|
-
const
|
|
4557
|
-
if (!
|
|
4991
|
+
const agentId3 = opts.agent ?? cfg.defaultAgentId;
|
|
4992
|
+
if (!agentId3) {
|
|
4558
4993
|
console.error(c.error("Specify --agent <agentId>"));
|
|
4559
4994
|
process.exit(1);
|
|
4560
4995
|
}
|
|
4561
4996
|
const spinner = spin("Fetching error logs\u2026");
|
|
4562
4997
|
try {
|
|
4563
4998
|
const client = makeClient();
|
|
4564
|
-
const res = await client.logs.list(
|
|
4999
|
+
const res = await client.logs.list(agentId3, {
|
|
4565
5000
|
limit: Number(opts.limit)
|
|
4566
5001
|
});
|
|
4567
5002
|
const errors = (res?.data ?? []).filter((l) => l.status === "error");
|
|
4568
5003
|
spinner.stop();
|
|
4569
5004
|
if (opts.json) return jsonOut(errors);
|
|
4570
|
-
section(`Errors \u2014 ${
|
|
5005
|
+
section(`Errors \u2014 ${agentId3.slice(0, 12)}\u2026 (${errors.length})`);
|
|
4571
5006
|
if (errors.length === 0) {
|
|
4572
5007
|
console.log(`${sym.ok} No errors found`);
|
|
4573
5008
|
return;
|
|
@@ -4596,13 +5031,13 @@ var RESOURCE_PROFILES = [
|
|
|
4596
5031
|
];
|
|
4597
5032
|
var RESOURCE_MODES = ["fixed", "elastic"];
|
|
4598
5033
|
function resolveAgentId(opts) {
|
|
4599
|
-
const
|
|
4600
|
-
if (!
|
|
5034
|
+
const agentId3 = opts.agent ?? loadConfig().defaultAgentId;
|
|
5035
|
+
if (!agentId3) {
|
|
4601
5036
|
throw new Error(
|
|
4602
5037
|
"Specify --agent <agentId> or set defaultAgentId with `agc config set defaultAgentId <id>`."
|
|
4603
5038
|
);
|
|
4604
5039
|
}
|
|
4605
|
-
return
|
|
5040
|
+
return agentId3;
|
|
4606
5041
|
}
|
|
4607
5042
|
function unwrap(response) {
|
|
4608
5043
|
return response?.data ?? response;
|
|
@@ -4653,17 +5088,17 @@ function parseNumber(value, name, options) {
|
|
|
4653
5088
|
}
|
|
4654
5089
|
return parsed;
|
|
4655
5090
|
}
|
|
4656
|
-
async function changeEnabled(
|
|
5091
|
+
async function changeEnabled(agentId3, enabled, json) {
|
|
4657
5092
|
const spinner = spin(`${enabled ? "Enabling" : "Disabling"} persistent cloud computer\u2026`);
|
|
4658
5093
|
try {
|
|
4659
|
-
const response = await makeClient().agents.updateComputerConfig(
|
|
5094
|
+
const response = await makeClient().agents.updateComputerConfig(agentId3, { enabled });
|
|
4660
5095
|
const config = unwrap(response);
|
|
4661
5096
|
spinner.stop();
|
|
4662
5097
|
if (json) return jsonOut(config);
|
|
4663
5098
|
console.log(`
|
|
4664
|
-
${sym.ok} Persistent cloud computer ${enabled ? "enabled" : "disabled"} for agent ${c.id(
|
|
5099
|
+
${sym.ok} Persistent cloud computer ${enabled ? "enabled" : "disabled"} for agent ${c.id(agentId3)}`);
|
|
4665
5100
|
if (enabled) {
|
|
4666
|
-
console.log(c.dim(` Wake it now with: agc computer wake --agent ${
|
|
5101
|
+
console.log(c.dim(` Wake it now with: agc computer wake --agent ${agentId3}`));
|
|
4667
5102
|
}
|
|
4668
5103
|
} catch (error) {
|
|
4669
5104
|
spinner.stop();
|
|
@@ -4671,12 +5106,12 @@ ${sym.ok} Persistent cloud computer ${enabled ? "enabled" : "disabled"} for agen
|
|
|
4671
5106
|
process.exitCode = 1;
|
|
4672
5107
|
}
|
|
4673
5108
|
}
|
|
4674
|
-
async function lifecycleAction(action,
|
|
5109
|
+
async function lifecycleAction(action, agentId3, reason, json) {
|
|
4675
5110
|
const verb = action === "wake" ? "Waking" : action === "sleep" ? "Sleeping" : "Restarting";
|
|
4676
5111
|
const spinner = spin(`${verb} persistent cloud computer\u2026`);
|
|
4677
5112
|
try {
|
|
4678
5113
|
const client = makeClient();
|
|
4679
|
-
const response = action === "wake" ? await client.agents.wakeComputer(
|
|
5114
|
+
const response = action === "wake" ? await client.agents.wakeComputer(agentId3, reason ? { reason } : void 0) : action === "sleep" ? await client.agents.sleepComputer(agentId3, reason ? { reason } : void 0) : await client.agents.restartComputer(agentId3, reason ? { reason } : void 0);
|
|
4680
5115
|
const computer = unwrap(response);
|
|
4681
5116
|
spinner.stop();
|
|
4682
5117
|
if (json) return jsonOut(computer);
|
|
@@ -4695,9 +5130,9 @@ function addAgentOption(command) {
|
|
|
4695
5130
|
function computerCommand() {
|
|
4696
5131
|
const command = new import_commander18.Command("computer").description("Manage an agent's one persistent cloud computer");
|
|
4697
5132
|
addAgentOption(command.command("status").description("Show persistent cloud computer status")).option("--json", "Output as JSON").action(async (opts) => {
|
|
4698
|
-
let
|
|
5133
|
+
let agentId3;
|
|
4699
5134
|
try {
|
|
4700
|
-
|
|
5135
|
+
agentId3 = resolveAgentId(opts);
|
|
4701
5136
|
} catch (error) {
|
|
4702
5137
|
printError(error);
|
|
4703
5138
|
process.exitCode = 1;
|
|
@@ -4705,7 +5140,7 @@ function computerCommand() {
|
|
|
4705
5140
|
}
|
|
4706
5141
|
const spinner = spin("Fetching persistent cloud computer\u2026");
|
|
4707
5142
|
try {
|
|
4708
|
-
const computer = unwrap(await makeClient().agents.getComputer(
|
|
5143
|
+
const computer = unwrap(await makeClient().agents.getComputer(agentId3));
|
|
4709
5144
|
spinner.stop();
|
|
4710
5145
|
if (opts.json) return jsonOut(computer);
|
|
4711
5146
|
displayComputer(computer);
|
|
@@ -4747,10 +5182,10 @@ function computerCommand() {
|
|
|
4747
5182
|
});
|
|
4748
5183
|
}
|
|
4749
5184
|
addAgentOption(command.command("resize").description("Resize the persistent cloud computer")).option("--profile <profile>", `Resource profile: ${RESOURCE_PROFILES.join(" | ")}`).option("--mode <mode>", `Resource mode: ${RESOURCE_MODES.join(" | ")}`).option("--vcpu <count>", "Requested virtual CPU count").option("--cpu <count>", "Alias for --vcpu").option("--memory <gib>", "Requested memory in GiB").option("--storage <gib>", "Requested persistent storage in GiB").option("--gpu-type <type>", "GPU type, such as nvidia-h100").option("--gpu-count <count>", "GPU count (0 removes GPU allocation)").option("--json", "Output as JSON").action(async (opts) => {
|
|
4750
|
-
let
|
|
5185
|
+
let agentId3;
|
|
4751
5186
|
let resize;
|
|
4752
5187
|
try {
|
|
4753
|
-
|
|
5188
|
+
agentId3 = resolveAgentId(opts);
|
|
4754
5189
|
if (opts.profile && !RESOURCE_PROFILES.includes(opts.profile)) {
|
|
4755
5190
|
throw new Error(`--profile must be one of: ${RESOURCE_PROFILES.join(", ")}.`);
|
|
4756
5191
|
}
|
|
@@ -4787,7 +5222,7 @@ function computerCommand() {
|
|
|
4787
5222
|
}
|
|
4788
5223
|
const spinner = spin("Resizing persistent cloud computer\u2026");
|
|
4789
5224
|
try {
|
|
4790
|
-
const computer = unwrap(await makeClient().agents.resizeComputer(
|
|
5225
|
+
const computer = unwrap(await makeClient().agents.resizeComputer(agentId3, resize));
|
|
4791
5226
|
spinner.stop();
|
|
4792
5227
|
if (opts.json) return jsonOut(computer);
|
|
4793
5228
|
console.log(`
|
|
@@ -4802,10 +5237,10 @@ ${sym.ok} Persistent cloud computer resize requested`);
|
|
|
4802
5237
|
addAgentOption(
|
|
4803
5238
|
command.command("exec").description("Run a command in the persistent cloud computer").argument("<command...>", "Command and arguments to run")
|
|
4804
5239
|
).option("--cwd <path>", "Working directory").option("--timeout <seconds>", "Command timeout in seconds", "120").option("--json", "Output as JSON").action(async (commandParts, opts) => {
|
|
4805
|
-
let
|
|
5240
|
+
let agentId3;
|
|
4806
5241
|
let timeoutSeconds;
|
|
4807
5242
|
try {
|
|
4808
|
-
|
|
5243
|
+
agentId3 = resolveAgentId(opts);
|
|
4809
5244
|
timeoutSeconds = parseNumber(opts.timeout, "Timeout");
|
|
4810
5245
|
} catch (error) {
|
|
4811
5246
|
printError(error);
|
|
@@ -4814,7 +5249,7 @@ ${sym.ok} Persistent cloud computer resize requested`);
|
|
|
4814
5249
|
}
|
|
4815
5250
|
const spinner = spin("Running command in persistent cloud computer\u2026");
|
|
4816
5251
|
try {
|
|
4817
|
-
const result = unwrap(await makeClient().agents.execComputer(
|
|
5252
|
+
const result = unwrap(await makeClient().agents.execComputer(agentId3, {
|
|
4818
5253
|
command: commandParts.join(" "),
|
|
4819
5254
|
...opts.cwd && { cwd: opts.cwd },
|
|
4820
5255
|
...timeoutSeconds !== void 0 && { timeoutSeconds }
|
|
@@ -4834,10 +5269,10 @@ ${sym.ok} Persistent cloud computer resize requested`);
|
|
|
4834
5269
|
}
|
|
4835
5270
|
});
|
|
4836
5271
|
addAgentOption(command.command("events").description("List recent persistent cloud computer events")).option("--limit <count>", "Maximum events", "50").option("--json", "Output as JSON").action(async (opts) => {
|
|
4837
|
-
let
|
|
5272
|
+
let agentId3;
|
|
4838
5273
|
let limit;
|
|
4839
5274
|
try {
|
|
4840
|
-
|
|
5275
|
+
agentId3 = resolveAgentId(opts);
|
|
4841
5276
|
limit = parseNumber(opts.limit, "Limit", { integer: true });
|
|
4842
5277
|
} catch (error) {
|
|
4843
5278
|
printError(error);
|
|
@@ -4846,7 +5281,7 @@ ${sym.ok} Persistent cloud computer resize requested`);
|
|
|
4846
5281
|
}
|
|
4847
5282
|
const spinner = spin("Fetching persistent cloud computer events\u2026");
|
|
4848
5283
|
try {
|
|
4849
|
-
const events = unwrap(await makeClient().agents.listComputerEvents(
|
|
5284
|
+
const events = unwrap(await makeClient().agents.listComputerEvents(agentId3, limit));
|
|
4850
5285
|
spinner.stop();
|
|
4851
5286
|
if (opts.json) return jsonOut(events);
|
|
4852
5287
|
section(`Cloud computer events (${events.length})`);
|
|
@@ -4870,8 +5305,8 @@ ${sym.ok} Persistent cloud computer resize requested`);
|
|
|
4870
5305
|
|
|
4871
5306
|
// src/commands/library.ts
|
|
4872
5307
|
var import_commander19 = require("commander");
|
|
4873
|
-
var
|
|
4874
|
-
var
|
|
5308
|
+
var import_fs8 = require("fs");
|
|
5309
|
+
var import_path6 = require("path");
|
|
4875
5310
|
function libraryCommand() {
|
|
4876
5311
|
const command = new import_commander19.Command("library").alias("files").description("Upload, find, and manage files in your Commons library");
|
|
4877
5312
|
command.command("list", { isDefault: true }).alias("ls").description("List library items").option("--query <text>", "Search names and descriptions").option("--source <source>", "Filter by source").option("--session <sessionId>", "Filter by session").option("--favorites", "Show favorites only").option("--limit <n>", "Maximum items", "50").option("--json", "Output as JSON").action(async (opts) => {
|
|
@@ -4933,8 +5368,8 @@ function libraryCommand() {
|
|
|
4933
5368
|
throw new Error("--storage must be either s3 or ipfs.");
|
|
4934
5369
|
}
|
|
4935
5370
|
const files = paths.map((path) => ({
|
|
4936
|
-
data: new Blob([new Uint8Array((0,
|
|
4937
|
-
name: (0,
|
|
5371
|
+
data: new Blob([new Uint8Array((0, import_fs8.readFileSync)(path))]),
|
|
5372
|
+
name: (0, import_path6.basename)(path)
|
|
4938
5373
|
}));
|
|
4939
5374
|
const result = await makeClient().files.upload(files, {
|
|
4940
5375
|
agentId: opts.agent,
|
|
@@ -4993,7 +5428,7 @@ ${sym.ok} Uploaded ${result.data.length} file${result.data.length === 1 ? "" : "
|
|
|
4993
5428
|
|
|
4994
5429
|
// src/commands/projects.ts
|
|
4995
5430
|
var import_commander20 = require("commander");
|
|
4996
|
-
var
|
|
5431
|
+
var import_fs9 = require("fs");
|
|
4997
5432
|
function agentId(value) {
|
|
4998
5433
|
const resolved = value ?? loadConfig().defaultAgentId;
|
|
4999
5434
|
if (!resolved) {
|
|
@@ -5005,7 +5440,7 @@ function agentId(value) {
|
|
|
5005
5440
|
}
|
|
5006
5441
|
function projectFiles(path) {
|
|
5007
5442
|
if (!path) return void 0;
|
|
5008
|
-
const parsed = JSON.parse((0,
|
|
5443
|
+
const parsed = JSON.parse((0, import_fs9.readFileSync)(path, "utf8"));
|
|
5009
5444
|
const files = Array.isArray(parsed) ? parsed : parsed.files;
|
|
5010
5445
|
if (!Array.isArray(files)) {
|
|
5011
5446
|
throw new Error("The files document must be an array or an object with a files array.");
|
|
@@ -5166,8 +5601,160 @@ ${sym.ok} Project published.`);
|
|
|
5166
5601
|
return command;
|
|
5167
5602
|
}
|
|
5168
5603
|
|
|
5169
|
-
// src/commands/
|
|
5604
|
+
// src/commands/arcade.ts
|
|
5170
5605
|
var import_commander21 = require("commander");
|
|
5606
|
+
var import_fs10 = require("fs");
|
|
5607
|
+
var import_path7 = require("path");
|
|
5608
|
+
function agentId2(value) {
|
|
5609
|
+
const resolved = value ?? loadConfig().defaultAgentId;
|
|
5610
|
+
if (!resolved) {
|
|
5611
|
+
throw new Error(
|
|
5612
|
+
"Specify --agent <agentId> or set a default with `agc config set defaultAgentId <id>`."
|
|
5613
|
+
);
|
|
5614
|
+
}
|
|
5615
|
+
return resolved;
|
|
5616
|
+
}
|
|
5617
|
+
var SOURCE_EXTENSIONS = /\.(html|css|js|mjs|cjs|ts|tsx|jsx|json|svg|md|txt)$/i;
|
|
5618
|
+
function readGameDirectory(root) {
|
|
5619
|
+
const files = [];
|
|
5620
|
+
const walk = (directory) => {
|
|
5621
|
+
for (const name of (0, import_fs10.readdirSync)(directory)) {
|
|
5622
|
+
if (name.startsWith(".") || name === "node_modules" || name === "dist") continue;
|
|
5623
|
+
const full = (0, import_path7.join)(directory, name);
|
|
5624
|
+
if ((0, import_fs10.statSync)(full).isDirectory()) walk(full);
|
|
5625
|
+
else if (SOURCE_EXTENSIONS.test(name)) {
|
|
5626
|
+
files.push({
|
|
5627
|
+
path: (0, import_path7.relative)(root, full).split(import_path7.sep).join("/"),
|
|
5628
|
+
content: (0, import_fs10.readFileSync)(full, "utf8")
|
|
5629
|
+
});
|
|
5630
|
+
}
|
|
5631
|
+
}
|
|
5632
|
+
};
|
|
5633
|
+
walk(root);
|
|
5634
|
+
if (!files.length) throw new Error(`No game source files found in ${root}.`);
|
|
5635
|
+
return files;
|
|
5636
|
+
}
|
|
5637
|
+
async function run(label, work) {
|
|
5638
|
+
const spinner = spin(label);
|
|
5639
|
+
try {
|
|
5640
|
+
const result = await work();
|
|
5641
|
+
spinner.stop();
|
|
5642
|
+
return result;
|
|
5643
|
+
} catch (error) {
|
|
5644
|
+
spinner.stop();
|
|
5645
|
+
printError(error);
|
|
5646
|
+
process.exit(1);
|
|
5647
|
+
}
|
|
5648
|
+
}
|
|
5649
|
+
function arcadeCommand() {
|
|
5650
|
+
const command = new import_commander21.Command("arcade").description(
|
|
5651
|
+
"Build, test, and publish Common Arcade games in your agent owner's account"
|
|
5652
|
+
);
|
|
5653
|
+
command.command("status").description("Check whether this platform is connected to Common Arcade").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (opts) => {
|
|
5654
|
+
const result = await run(
|
|
5655
|
+
"Checking Arcade connection\u2026",
|
|
5656
|
+
() => makeClient().arcade.status(agentId2(opts.agent))
|
|
5657
|
+
);
|
|
5658
|
+
if (opts.json) return jsonOut(result.data);
|
|
5659
|
+
console.log(
|
|
5660
|
+
result.data.connected ? `${sym.ok} Connected to Common Arcade.` : `${sym.fail} Common Arcade is not connected on this deployment.`
|
|
5661
|
+
);
|
|
5662
|
+
});
|
|
5663
|
+
command.command("list", { isDefault: true }).alias("ls").description("List Arcade game projects").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (opts) => {
|
|
5664
|
+
const result = await run(
|
|
5665
|
+
"Fetching Arcade projects\u2026",
|
|
5666
|
+
() => makeClient().arcade.list(agentId2(opts.agent))
|
|
5667
|
+
);
|
|
5668
|
+
if (opts.json) return jsonOut(result.data);
|
|
5669
|
+
section(`Arcade projects (${result.data.length})`);
|
|
5670
|
+
table(
|
|
5671
|
+
result.data.map((project) => ({
|
|
5672
|
+
ID: project.projectId,
|
|
5673
|
+
Title: project.title ?? "",
|
|
5674
|
+
Published: project.isPublished ? "yes" : "no",
|
|
5675
|
+
Studio: project.studioUrl
|
|
5676
|
+
})),
|
|
5677
|
+
["ID", "Title", "Published", "Studio"]
|
|
5678
|
+
);
|
|
5679
|
+
});
|
|
5680
|
+
command.command("get <projectId>").description("Show an Arcade game project").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (projectId, opts) => {
|
|
5681
|
+
const result = await run(
|
|
5682
|
+
"Fetching Arcade project\u2026",
|
|
5683
|
+
() => makeClient().arcade.get(agentId2(opts.agent), projectId)
|
|
5684
|
+
);
|
|
5685
|
+
if (opts.json) return jsonOut(result.data);
|
|
5686
|
+
const project = result.data;
|
|
5687
|
+
section(project.title ?? project.projectId);
|
|
5688
|
+
detail([
|
|
5689
|
+
["Project ID", c.id(project.projectId)],
|
|
5690
|
+
["Revision", String(project.revision)],
|
|
5691
|
+
["Files", project.document.files.map((file) => file.path).join(", ")],
|
|
5692
|
+
["Published", project.isPublished ? "yes" : "no"],
|
|
5693
|
+
["Thumbnail", project.hasThumbnail ? "yes" : "no"],
|
|
5694
|
+
["Studio", project.studioUrl]
|
|
5695
|
+
]);
|
|
5696
|
+
});
|
|
5697
|
+
command.command("create").description("Create an Arcade game project").requiredOption("--title <title>", "Game title").option("--description <text>", "How to play").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (opts) => {
|
|
5698
|
+
const result = await run(
|
|
5699
|
+
"Creating Arcade project\u2026",
|
|
5700
|
+
() => makeClient().arcade.create(agentId2(opts.agent), {
|
|
5701
|
+
title: opts.title,
|
|
5702
|
+
description: opts.description
|
|
5703
|
+
})
|
|
5704
|
+
);
|
|
5705
|
+
if (opts.json) return jsonOut(result.data);
|
|
5706
|
+
console.log(`
|
|
5707
|
+
${sym.ok} Arcade project created.`);
|
|
5708
|
+
detail([
|
|
5709
|
+
["Project ID", c.id(result.data.projectId)],
|
|
5710
|
+
["Studio", result.data.studioUrl]
|
|
5711
|
+
]);
|
|
5712
|
+
});
|
|
5713
|
+
command.command("push <projectId> <directory>").description("Upload a local game directory to an Arcade project").option("--agent <agentId>", "Agent ID").option("--entry <file>", "HTML entry file (default: index.html)").option("--runtime <file>", "Authoritative rules file, required to publish").option("--thumbnail <url>", "HTTPS thumbnail URL, required to publish").option("--replace", "Remove project files that are not in the directory").option("--json", "Output as JSON").action(async (projectId, directory, opts) => {
|
|
5714
|
+
const files = readGameDirectory(directory);
|
|
5715
|
+
const result = await run(
|
|
5716
|
+
`Uploading ${files.length} files\u2026`,
|
|
5717
|
+
() => makeClient().arcade.write(agentId2(opts.agent), projectId, {
|
|
5718
|
+
files,
|
|
5719
|
+
replaceFiles: Boolean(opts.replace),
|
|
5720
|
+
entryFile: opts.entry,
|
|
5721
|
+
thumbnail: opts.thumbnail,
|
|
5722
|
+
runtime: opts.runtime ? { entryFile: opts.runtime } : void 0
|
|
5723
|
+
})
|
|
5724
|
+
);
|
|
5725
|
+
if (opts.json) return jsonOut(result.data);
|
|
5726
|
+
console.log(`${sym.ok} Saved revision ${result.data.revision}.`);
|
|
5727
|
+
detail([["Studio", result.data.studioUrl]]);
|
|
5728
|
+
});
|
|
5729
|
+
command.command("test <projectId>").description("Run Arcade's validation and runtime harness").option("--agent <agentId>", "Agent ID").option("--steps <n>", "Steps to simulate", (value) => Number(value)).option("--seed <seed>", "Deterministic seed").action(async (projectId, opts) => {
|
|
5730
|
+
const result = await run(
|
|
5731
|
+
"Testing game\u2026",
|
|
5732
|
+
() => makeClient().arcade.test(agentId2(opts.agent), projectId, {
|
|
5733
|
+
steps: opts.steps,
|
|
5734
|
+
seed: opts.seed
|
|
5735
|
+
})
|
|
5736
|
+
);
|
|
5737
|
+
jsonOut(result.data);
|
|
5738
|
+
});
|
|
5739
|
+
command.command("publish <projectId>").description("Publish an Arcade game as an immutable release").option("--agent <agentId>", "Agent ID").option("--json", "Output as JSON").action(async (projectId, opts) => {
|
|
5740
|
+
const result = await run(
|
|
5741
|
+
"Publishing game\u2026",
|
|
5742
|
+
() => makeClient().arcade.publish(agentId2(opts.agent), projectId)
|
|
5743
|
+
);
|
|
5744
|
+
if (opts.json) return jsonOut(result.data);
|
|
5745
|
+
console.log(`
|
|
5746
|
+
${sym.ok} Game published.`);
|
|
5747
|
+
detail([
|
|
5748
|
+
["Release", result.data.releaseId],
|
|
5749
|
+
["Play", result.data.gameUrl],
|
|
5750
|
+
["Studio", result.data.studioUrl]
|
|
5751
|
+
]);
|
|
5752
|
+
});
|
|
5753
|
+
return command;
|
|
5754
|
+
}
|
|
5755
|
+
|
|
5756
|
+
// src/commands/api-keys.ts
|
|
5757
|
+
var import_commander22 = require("commander");
|
|
5171
5758
|
async function resolveProject(projectId) {
|
|
5172
5759
|
const projects = (await makeClient().developer.listProjects()).data;
|
|
5173
5760
|
const project = projectId ? projects.find((candidate) => candidate.id === projectId) : projects[0];
|
|
@@ -5179,7 +5766,7 @@ async function resolveProject(projectId) {
|
|
|
5179
5766
|
return project;
|
|
5180
5767
|
}
|
|
5181
5768
|
function apiKeysCommand() {
|
|
5182
|
-
const command = new
|
|
5769
|
+
const command = new import_commander22.Command("keys").alias("api-keys").description("Create and manage project-scoped developer API keys");
|
|
5183
5770
|
command.command("list", { isDefault: true }).alias("ls").description("List API keys for a developer project").option("--project <projectId>", "Developer project ID (defaults to newest)").option("--json", "Output as JSON").action(async (opts) => {
|
|
5184
5771
|
const spinner = spin("Fetching developer keys\u2026");
|
|
5185
5772
|
try {
|
|
@@ -5333,6 +5920,96 @@ ${sym.ok} Developer project created.`);
|
|
|
5333
5920
|
return command;
|
|
5334
5921
|
}
|
|
5335
5922
|
|
|
5923
|
+
// src/commands/provenance.ts
|
|
5924
|
+
var import_commander23 = require("commander");
|
|
5925
|
+
function printTrajectory(trajectory) {
|
|
5926
|
+
const sources = trajectory.events.flatMap(
|
|
5927
|
+
(event) => event.metadata?.lineage?.sources ?? []
|
|
5928
|
+
);
|
|
5929
|
+
const delegates = trajectory.events.flatMap(
|
|
5930
|
+
(event) => event.metadata?.lineage?.delegation ? [event.metadata.lineage.delegation] : []
|
|
5931
|
+
);
|
|
5932
|
+
const matches = trajectory.events.flatMap(
|
|
5933
|
+
(event) => event.metadata?.lineage?.library?.results ?? []
|
|
5934
|
+
);
|
|
5935
|
+
section("Provenance report");
|
|
5936
|
+
detail([
|
|
5937
|
+
["Runs", String(trajectory.summary?.runs ?? trajectory.runs?.length ?? 0)],
|
|
5938
|
+
[
|
|
5939
|
+
"Events",
|
|
5940
|
+
String(trajectory.summary?.events ?? trajectory.events?.length ?? 0)
|
|
5941
|
+
],
|
|
5942
|
+
[
|
|
5943
|
+
"Model / tool calls",
|
|
5944
|
+
`${trajectory.summary?.modelCalls ?? 0} / ${trajectory.summary?.toolCalls ?? 0}`
|
|
5945
|
+
],
|
|
5946
|
+
["Sources", String(sources.length)],
|
|
5947
|
+
["Agent delegations", String(delegates.length)],
|
|
5948
|
+
["Library matches", String(matches.length)],
|
|
5949
|
+
["Dropped events", String(trajectory.summary?.droppedEvents ?? 0)]
|
|
5950
|
+
]);
|
|
5951
|
+
if (sources.length) {
|
|
5952
|
+
section("Web sources");
|
|
5953
|
+
for (const source of sources)
|
|
5954
|
+
console.log(
|
|
5955
|
+
` ${c.primary(source.domain)} ${source.title ?? ""}
|
|
5956
|
+
${c.dim(source.url)}`
|
|
5957
|
+
);
|
|
5958
|
+
}
|
|
5959
|
+
if (delegates.length) {
|
|
5960
|
+
section("Agent contributions");
|
|
5961
|
+
for (const item of delegates)
|
|
5962
|
+
console.log(
|
|
5963
|
+
` ${item.fromAgentId ?? "workflow"} \u2192 ${c.primary(item.toAgentId)} ${c.dim(item.role ?? "")}`
|
|
5964
|
+
);
|
|
5965
|
+
}
|
|
5966
|
+
if (matches.length) {
|
|
5967
|
+
section("Library matches");
|
|
5968
|
+
for (const item of matches)
|
|
5969
|
+
console.log(
|
|
5970
|
+
` ${c.primary(`${item.percentageMatch}%`)} ${item.name ?? item.itemId} ${c.dim(`#${item.rank}`)}`
|
|
5971
|
+
);
|
|
5972
|
+
}
|
|
5973
|
+
}
|
|
5974
|
+
function provenanceCommand() {
|
|
5975
|
+
const cmd = new import_commander23.Command("provenance").description(
|
|
5976
|
+
"Inspect and export provenance and attribution trails"
|
|
5977
|
+
);
|
|
5978
|
+
cmd.command("session <sessionId>").description("Show a plain-language sources and contributors report").option("--json", "Output the complete machine-readable trajectory").action(async (sessionId, opts) => {
|
|
5979
|
+
const spinner = spin("Building provenance report\u2026");
|
|
5980
|
+
try {
|
|
5981
|
+
const { data } = await makeClient().provenance.session(sessionId);
|
|
5982
|
+
spinner.stop();
|
|
5983
|
+
if (opts.json) return jsonOut(data);
|
|
5984
|
+
printTrajectory(data);
|
|
5985
|
+
} catch (error) {
|
|
5986
|
+
spinner.stop();
|
|
5987
|
+
printError(error);
|
|
5988
|
+
process.exitCode = 1;
|
|
5989
|
+
}
|
|
5990
|
+
});
|
|
5991
|
+
cmd.command("workflow <executionId>").description("Show provenance for a workflow execution").option("--json", "Output the complete machine-readable trajectory").action(async (executionId, opts) => {
|
|
5992
|
+
const spinner = spin("Building workflow provenance report\u2026");
|
|
5993
|
+
try {
|
|
5994
|
+
const { data } = await makeClient().provenance.scope(
|
|
5995
|
+
"workflow",
|
|
5996
|
+
executionId
|
|
5997
|
+
);
|
|
5998
|
+
spinner.stop();
|
|
5999
|
+
if (opts.json) return jsonOut(data);
|
|
6000
|
+
printTrajectory(data);
|
|
6001
|
+
} catch (error) {
|
|
6002
|
+
spinner.stop();
|
|
6003
|
+
printError(error);
|
|
6004
|
+
process.exitCode = 1;
|
|
6005
|
+
}
|
|
6006
|
+
});
|
|
6007
|
+
cmd.command("bundle <traceId>").description("Export the standards-based EAA provenance bundle as JSON").action(
|
|
6008
|
+
async (traceId) => jsonOut((await makeClient().provenance.bundle(traceId)).data)
|
|
6009
|
+
);
|
|
6010
|
+
return cmd;
|
|
6011
|
+
}
|
|
6012
|
+
|
|
5336
6013
|
// src/bin.ts
|
|
5337
6014
|
async function interactiveMenu() {
|
|
5338
6015
|
banner();
|
|
@@ -5340,9 +6017,15 @@ async function interactiveMenu() {
|
|
|
5340
6017
|
const isSetup = !!((cfg.accessToken || cfg.apiKey || cfg.sessionToken) && (cfg.userId || cfg.initiator));
|
|
5341
6018
|
if (!isSetup) {
|
|
5342
6019
|
console.log(c.bold(" Welcome to Agent Commons CLI!"));
|
|
5343
|
-
console.log(
|
|
5344
|
-
|
|
5345
|
-
|
|
6020
|
+
console.log(
|
|
6021
|
+
c.dim(
|
|
6022
|
+
" Looks like this is your first time here \u2014 let's get you set up.\n"
|
|
6023
|
+
)
|
|
6024
|
+
);
|
|
6025
|
+
console.log(
|
|
6026
|
+
` ${sym.arrow} Running ${c.bold("agc login")} to configure your credentials\u2026
|
|
6027
|
+
`
|
|
6028
|
+
);
|
|
5346
6029
|
runSubcommand(["login"]);
|
|
5347
6030
|
return;
|
|
5348
6031
|
}
|
|
@@ -5353,7 +6036,11 @@ async function interactiveMenu() {
|
|
|
5353
6036
|
const action = await select("What would you like to do?", [
|
|
5354
6037
|
{ label: "Chat with an agent", value: "chat", hint: "agc chat" },
|
|
5355
6038
|
{ label: "Run an agent (one-shot)", value: "run", hint: "agc run" },
|
|
5356
|
-
{
|
|
6039
|
+
{
|
|
6040
|
+
label: "Manage an agent cloud computer",
|
|
6041
|
+
value: "computer",
|
|
6042
|
+
hint: "agc computer status"
|
|
6043
|
+
},
|
|
5357
6044
|
{ label: "View sessions", value: "sessions", hint: "agc sessions list" },
|
|
5358
6045
|
{ label: "Manage agents", value: "agents", hint: "agc agents list" },
|
|
5359
6046
|
{ label: "Tasks", value: "tasks", hint: "agc task list" },
|
|
@@ -5373,19 +6060,19 @@ async function interactiveMenu() {
|
|
|
5373
6060
|
process.exit(0);
|
|
5374
6061
|
}
|
|
5375
6062
|
const needsAgent = action === "chat" || action === "run" || action === "computer";
|
|
5376
|
-
const
|
|
5377
|
-
if (needsAgent && !
|
|
6063
|
+
const agentId3 = needsAgent ? cfg.defaultAgentId ?? await pickAgentInteractively(action) : void 0;
|
|
6064
|
+
if (needsAgent && !agentId3) return;
|
|
5378
6065
|
if (action === "run") {
|
|
5379
6066
|
const prompt = await askPrompt("Enter your prompt:");
|
|
5380
6067
|
if (!prompt) return;
|
|
5381
|
-
runSubcommand(["run", "--agent",
|
|
6068
|
+
runSubcommand(["run", "--agent", agentId3, prompt]);
|
|
5382
6069
|
return;
|
|
5383
6070
|
}
|
|
5384
6071
|
const commandMap = {
|
|
5385
|
-
chat: ["chat", "--agent",
|
|
6072
|
+
chat: ["chat", "--agent", agentId3],
|
|
5386
6073
|
run: [],
|
|
5387
6074
|
// handled above
|
|
5388
|
-
computer: ["computer", "status", "--agent",
|
|
6075
|
+
computer: ["computer", "status", "--agent", agentId3],
|
|
5389
6076
|
sessions: ["sessions", "list"],
|
|
5390
6077
|
agents: ["agents", "list"],
|
|
5391
6078
|
tasks: ["task", "list"],
|
|
@@ -5406,7 +6093,10 @@ async function interactiveMenu() {
|
|
|
5406
6093
|
async function askPrompt(question) {
|
|
5407
6094
|
const { createInterface: createInterface3 } = await import("readline");
|
|
5408
6095
|
return new Promise((resolve2) => {
|
|
5409
|
-
const rl = createInterface3({
|
|
6096
|
+
const rl = createInterface3({
|
|
6097
|
+
input: process.stdin,
|
|
6098
|
+
output: process.stdout
|
|
6099
|
+
});
|
|
5410
6100
|
process.stdout.write(`
|
|
5411
6101
|
${c.bold(question)}
|
|
5412
6102
|
${c.primary("\u203A")} `);
|
|
@@ -5434,26 +6124,35 @@ async function pickAgentInteractively(action) {
|
|
|
5434
6124
|
spinner.stop();
|
|
5435
6125
|
} catch {
|
|
5436
6126
|
spinner.stop();
|
|
5437
|
-
console.log(
|
|
6127
|
+
console.log(
|
|
6128
|
+
`
|
|
5438
6129
|
${c.warn("\u26A0")} Could not fetch agents. Check your sign-in and connection.
|
|
5439
|
-
`
|
|
6130
|
+
`
|
|
6131
|
+
);
|
|
5440
6132
|
return null;
|
|
5441
6133
|
}
|
|
5442
6134
|
if (agents.length === 0) {
|
|
5443
6135
|
console.log(`
|
|
5444
6136
|
${c.warn("\u26A0")} You don't have any agents yet.
|
|
5445
6137
|
`);
|
|
5446
|
-
const choice = await select(
|
|
5447
|
-
|
|
5448
|
-
|
|
5449
|
-
|
|
6138
|
+
const choice = await select(
|
|
6139
|
+
"What would you like to do?",
|
|
6140
|
+
[
|
|
6141
|
+
{
|
|
6142
|
+
label: "Create a new agent now",
|
|
6143
|
+
value: "create",
|
|
6144
|
+
hint: "agc agents create"
|
|
6145
|
+
},
|
|
6146
|
+
{ label: "Go back", value: "cancel" }
|
|
6147
|
+
]
|
|
6148
|
+
);
|
|
5450
6149
|
if (choice === "create") {
|
|
5451
6150
|
runSubcommand(["agents", "create"]);
|
|
5452
6151
|
}
|
|
5453
6152
|
return null;
|
|
5454
6153
|
}
|
|
5455
6154
|
console.log();
|
|
5456
|
-
const
|
|
6155
|
+
const agentId3 = await select(
|
|
5457
6156
|
action === "computer" ? "Choose the agent whose cloud computer you want to manage:" : `Choose an agent to ${action} with:`,
|
|
5458
6157
|
agents.map((a) => ({
|
|
5459
6158
|
label: a.name,
|
|
@@ -5466,15 +6165,17 @@ async function pickAgentInteractively(action) {
|
|
|
5466
6165
|
{ label: "No \u2014 just this once", value: false }
|
|
5467
6166
|
]);
|
|
5468
6167
|
if (saveDefault) {
|
|
5469
|
-
saveConfig({ defaultAgentId:
|
|
5470
|
-
const chosen = agents.find((a) => a.agentId ===
|
|
5471
|
-
console.log(
|
|
5472
|
-
`)
|
|
6168
|
+
saveConfig({ defaultAgentId: agentId3 });
|
|
6169
|
+
const chosen = agents.find((a) => a.agentId === agentId3);
|
|
6170
|
+
console.log(
|
|
6171
|
+
` ${sym.ok} ${c.dim("Default agent set to")} ${c.bold(chosen?.name ?? agentId3)}
|
|
6172
|
+
`
|
|
6173
|
+
);
|
|
5473
6174
|
}
|
|
5474
|
-
return
|
|
6175
|
+
return agentId3;
|
|
5475
6176
|
}
|
|
5476
|
-
var program = new
|
|
5477
|
-
program.name("agc").description("Agent Commons CLI \u2014 interact with the Agent Commons platform").version("0.
|
|
6177
|
+
var program = new import_commander24.Command();
|
|
6178
|
+
program.name("agc").description("Agent Commons CLI \u2014 interact with the Agent Commons platform").version("0.6.2", "-v, --version").showHelpAfterError("(run `agc --help` for usage)").configureHelp({
|
|
5478
6179
|
sortOptions: true,
|
|
5479
6180
|
sortSubcommands: true
|
|
5480
6181
|
}).addHelpText(
|
|
@@ -5492,7 +6193,8 @@ Docs: https://docs.agentcommons.io/docs/cli
|
|
|
5492
6193
|
await interactiveMenu();
|
|
5493
6194
|
});
|
|
5494
6195
|
program.hook("preAction", async (_thisCommand, actionCommand) => {
|
|
5495
|
-
if (actionCommand.name() === "login" || actionCommand.name() === "logout")
|
|
6196
|
+
if (actionCommand.name() === "login" || actionCommand.name() === "logout")
|
|
6197
|
+
return;
|
|
5496
6198
|
await ensureAccessToken();
|
|
5497
6199
|
});
|
|
5498
6200
|
program.addCommand(loginCommand());
|
|
@@ -5505,7 +6207,9 @@ program.addCommand(toolsCommand());
|
|
|
5505
6207
|
program.addCommand(connectionsCommand());
|
|
5506
6208
|
program.addCommand(libraryCommand());
|
|
5507
6209
|
program.addCommand(projectsCommand());
|
|
6210
|
+
program.addCommand(arcadeCommand());
|
|
5508
6211
|
program.addCommand(apiKeysCommand());
|
|
6212
|
+
program.addCommand(provenanceCommand());
|
|
5509
6213
|
program.addCommand(workflowCommand());
|
|
5510
6214
|
program.addCommand(taskCommand());
|
|
5511
6215
|
program.addCommand(runCommand());
|
|
@@ -5530,8 +6234,10 @@ program.on("command:*", () => {
|
|
|
5530
6234
|
process.exit(1);
|
|
5531
6235
|
});
|
|
5532
6236
|
program.parseAsync(process.argv).catch((error) => {
|
|
5533
|
-
console.error(
|
|
6237
|
+
console.error(
|
|
6238
|
+
`
|
|
5534
6239
|
${sym.fail} ${c.error(error instanceof Error ? error.message : String(error))}
|
|
5535
|
-
`
|
|
6240
|
+
`
|
|
6241
|
+
);
|
|
5536
6242
|
process.exitCode = 1;
|
|
5537
6243
|
});
|