@codelia/runtime 0.1.55 → 0.1.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +768 -489
- package/dist/index.js +768 -489
- package/package.json +9 -9
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/runtime.ts
|
|
2
|
-
import
|
|
2
|
+
import path19 from "path";
|
|
3
3
|
import { SessionStateStoreImpl as SessionStateStoreImpl2 } from "@codelia/storage";
|
|
4
4
|
|
|
5
5
|
// src/agent-factory.ts
|
|
@@ -758,6 +758,10 @@ var DEFAULT_SEARCH_MODE = "auto";
|
|
|
758
758
|
var DEFAULT_SEARCH_NATIVE_PROVIDERS = ["openai", "anthropic"];
|
|
759
759
|
var DEFAULT_SEARCH_LOCAL_BACKEND = "ddg";
|
|
760
760
|
var DEFAULT_SEARCH_BRAVE_API_KEY_ENV = "BRAVE_SEARCH_API_KEY";
|
|
761
|
+
var DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_TIMEOUT_MS = 1e4;
|
|
762
|
+
var DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_COMMANDS = [
|
|
763
|
+
["rg", "--version"]
|
|
764
|
+
];
|
|
761
765
|
var readEnvValue = (key) => {
|
|
762
766
|
const value = process.env[key];
|
|
763
767
|
if (!value) return void 0;
|
|
@@ -856,6 +860,39 @@ var resolveSkillsConfig = async (workingDir) => {
|
|
|
856
860
|
const effective = configRegistry.resolve([globalConfig, projectConfig]);
|
|
857
861
|
return normalizeSkillsConfig(effective.skills);
|
|
858
862
|
};
|
|
863
|
+
var normalizeExecutionEnvironmentConfig = (value) => {
|
|
864
|
+
const startupChecks = value?.startup_checks;
|
|
865
|
+
const enabled = startupChecks?.enabled !== false;
|
|
866
|
+
const timeoutMs = resolveSkillsLimit(
|
|
867
|
+
startupChecks?.timeout_ms,
|
|
868
|
+
DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_TIMEOUT_MS
|
|
869
|
+
);
|
|
870
|
+
const mode = startupChecks?.mode === "replace" ? "replace" : "append";
|
|
871
|
+
const configuredCommands = (startupChecks?.commands ?? []).map(
|
|
872
|
+
(command) => command.map((part) => part.trim()).filter((part) => part.length > 0)
|
|
873
|
+
).filter((command) => command.length > 0);
|
|
874
|
+
const baseCommands = mode === "replace" ? configuredCommands : [
|
|
875
|
+
...DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_COMMANDS.map(
|
|
876
|
+
(command) => [...command]
|
|
877
|
+
),
|
|
878
|
+
...configuredCommands
|
|
879
|
+
];
|
|
880
|
+
const commands = Array.from(
|
|
881
|
+
new Map(baseCommands.map((command) => [command.join("\0"), command])).values()
|
|
882
|
+
);
|
|
883
|
+
return {
|
|
884
|
+
startupChecks: {
|
|
885
|
+
enabled,
|
|
886
|
+
commands,
|
|
887
|
+
timeoutMs
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
};
|
|
891
|
+
var resolveExecutionEnvironmentConfig = async (workingDir) => {
|
|
892
|
+
const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
|
|
893
|
+
const effective = configRegistry.resolve([globalConfig, projectConfig]);
|
|
894
|
+
return normalizeExecutionEnvironmentConfig(effective.execution_environment);
|
|
895
|
+
};
|
|
859
896
|
var normalizeSearchConfig = (value) => {
|
|
860
897
|
const mode = value?.mode === "auto" || value?.mode === "native" || value?.mode === "local" ? value.mode : DEFAULT_SEARCH_MODE;
|
|
861
898
|
const providersRaw = value?.native?.providers ?? [
|
|
@@ -1632,6 +1669,496 @@ var AuthResolver = class _AuthResolver {
|
|
|
1632
1669
|
}
|
|
1633
1670
|
};
|
|
1634
1671
|
|
|
1672
|
+
// src/execution-environment.ts
|
|
1673
|
+
import os from "os";
|
|
1674
|
+
import path3 from "path";
|
|
1675
|
+
|
|
1676
|
+
// src/tasks/shell-executor.ts
|
|
1677
|
+
import { spawn as spawn3 } from "child_process";
|
|
1678
|
+
|
|
1679
|
+
// src/tools/bash-utils.ts
|
|
1680
|
+
import { spawn as spawn2 } from "child_process";
|
|
1681
|
+
var DEBUG_MAX_COMMAND_CHARS = 200;
|
|
1682
|
+
var DEFAULT_TIMEOUT_SECONDS = 120;
|
|
1683
|
+
var MAX_TIMEOUT_SECONDS = 300;
|
|
1684
|
+
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
1685
|
+
var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
|
|
1686
|
+
MAX_TIMER_DELAY_MS / 1e3
|
|
1687
|
+
);
|
|
1688
|
+
var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
1689
|
+
var summarizeCommand = (command) => {
|
|
1690
|
+
const normalized = command.trim().replace(/\s+/g, " ");
|
|
1691
|
+
if (normalized.length <= DEBUG_MAX_COMMAND_CHARS) {
|
|
1692
|
+
return normalized;
|
|
1693
|
+
}
|
|
1694
|
+
return `${normalized.slice(0, DEBUG_MAX_COMMAND_CHARS)}...[truncated]`;
|
|
1695
|
+
};
|
|
1696
|
+
|
|
1697
|
+
// src/tasks/shell-executor.ts
|
|
1698
|
+
var DEFAULT_EXCERPT_LINES = 80;
|
|
1699
|
+
var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
|
|
1700
|
+
var FORCE_KILL_DELAY_MS = 2e3;
|
|
1701
|
+
var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
|
|
1702
|
+
var truncateUtf8Prefix = (value, maxBytes) => {
|
|
1703
|
+
if (maxBytes <= 0 || value.length === 0) return "";
|
|
1704
|
+
let bytes = 0;
|
|
1705
|
+
let out = "";
|
|
1706
|
+
for (const ch of value) {
|
|
1707
|
+
const next = utf8ByteLength(ch);
|
|
1708
|
+
if (bytes + next > maxBytes) break;
|
|
1709
|
+
out += ch;
|
|
1710
|
+
bytes += next;
|
|
1711
|
+
}
|
|
1712
|
+
return out;
|
|
1713
|
+
};
|
|
1714
|
+
var truncateUtf8Suffix = (value, maxBytes) => {
|
|
1715
|
+
if (maxBytes <= 0 || value.length === 0) return "";
|
|
1716
|
+
let bytes = 0;
|
|
1717
|
+
const chars = Array.from(value);
|
|
1718
|
+
const out = [];
|
|
1719
|
+
for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
|
|
1720
|
+
const ch = chars[idx];
|
|
1721
|
+
const next = utf8ByteLength(ch);
|
|
1722
|
+
if (bytes + next > maxBytes) break;
|
|
1723
|
+
out.push(ch);
|
|
1724
|
+
bytes += next;
|
|
1725
|
+
}
|
|
1726
|
+
out.reverse();
|
|
1727
|
+
return out.join("");
|
|
1728
|
+
};
|
|
1729
|
+
var excerptByLines = (value) => {
|
|
1730
|
+
const lines = value.split(/\r?\n/);
|
|
1731
|
+
if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
|
|
1732
|
+
const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
|
|
1733
|
+
const tail = lines.slice(lines.length - DEFAULT_EXCERPT_LINES);
|
|
1734
|
+
const omitted = lines.length - head.length - tail.length;
|
|
1735
|
+
return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
|
|
1736
|
+
};
|
|
1737
|
+
var excerptByBytes = (value, maxBytes) => {
|
|
1738
|
+
if (utf8ByteLength(value) <= maxBytes) return value;
|
|
1739
|
+
const marker = "\n...[truncated by size]...\n";
|
|
1740
|
+
const markerBytes = utf8ByteLength(marker);
|
|
1741
|
+
if (maxBytes <= markerBytes + 2) {
|
|
1742
|
+
return truncateUtf8Prefix(value, maxBytes);
|
|
1743
|
+
}
|
|
1744
|
+
const budget = maxBytes - markerBytes;
|
|
1745
|
+
const headBytes = Math.floor(budget / 2);
|
|
1746
|
+
const tailBytes = budget - headBytes;
|
|
1747
|
+
return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
|
|
1748
|
+
};
|
|
1749
|
+
var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
|
|
1750
|
+
var excerptText = (value) => excerptByBytes(excerptByLines(value), MAX_INLINE_OUTPUT_BYTES);
|
|
1751
|
+
var buildShellTaskResultBase = (options) => {
|
|
1752
|
+
const stdoutTruncated = needsInlineTruncation(options.rawStdout);
|
|
1753
|
+
const stderrTruncated = needsInlineTruncation(options.rawStderr);
|
|
1754
|
+
return {
|
|
1755
|
+
stdout: stdoutTruncated ? excerptText(options.rawStdout) : options.rawStdout,
|
|
1756
|
+
stderr: stderrTruncated ? excerptText(options.rawStderr) : options.rawStderr,
|
|
1757
|
+
exit_code: options.exitCode,
|
|
1758
|
+
signal: options.signal,
|
|
1759
|
+
duration_ms: options.durationMs,
|
|
1760
|
+
truncated: {
|
|
1761
|
+
stdout: stdoutTruncated,
|
|
1762
|
+
stderr: stderrTruncated,
|
|
1763
|
+
combined: stdoutTruncated || stderrTruncated
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
1766
|
+
};
|
|
1767
|
+
var buildShellTaskResult = async (outputCache, options) => {
|
|
1768
|
+
const base = buildShellTaskResultBase(options);
|
|
1769
|
+
let stdoutCacheId;
|
|
1770
|
+
let stderrCacheId;
|
|
1771
|
+
if (base.truncated?.stdout && options.rawStdout.length > 0) {
|
|
1772
|
+
const saved = await outputCache.save({
|
|
1773
|
+
tool_call_id: `${options.taskId}_stdout`,
|
|
1774
|
+
tool_name: options.toolName,
|
|
1775
|
+
content: options.rawStdout
|
|
1776
|
+
});
|
|
1777
|
+
stdoutCacheId = saved.id;
|
|
1778
|
+
}
|
|
1779
|
+
if (base.truncated?.stderr && options.rawStderr.length > 0) {
|
|
1780
|
+
const saved = await outputCache.save({
|
|
1781
|
+
tool_call_id: `${options.taskId}_stderr`,
|
|
1782
|
+
tool_name: options.toolName,
|
|
1783
|
+
content: options.rawStderr
|
|
1784
|
+
});
|
|
1785
|
+
stderrCacheId = saved.id;
|
|
1786
|
+
}
|
|
1787
|
+
return {
|
|
1788
|
+
...base,
|
|
1789
|
+
...stdoutCacheId ? { stdout_cache_id: stdoutCacheId } : {},
|
|
1790
|
+
...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
|
|
1791
|
+
};
|
|
1792
|
+
};
|
|
1793
|
+
var spawnShellProcess = (command, cwd) => {
|
|
1794
|
+
const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
|
|
1795
|
+
if (shellPath) {
|
|
1796
|
+
return spawn3(shellPath, ["-lc", command], {
|
|
1797
|
+
cwd,
|
|
1798
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1799
|
+
detached: true
|
|
1800
|
+
});
|
|
1801
|
+
}
|
|
1802
|
+
return spawn3(command, {
|
|
1803
|
+
cwd,
|
|
1804
|
+
shell: true,
|
|
1805
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1806
|
+
detached: process.platform !== "win32"
|
|
1807
|
+
});
|
|
1808
|
+
};
|
|
1809
|
+
var terminateChild = (child, signal) => {
|
|
1810
|
+
if (typeof child.pid === "number" && process.platform !== "win32") {
|
|
1811
|
+
try {
|
|
1812
|
+
process.kill(-child.pid, signal);
|
|
1813
|
+
} catch {
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
try {
|
|
1817
|
+
child.kill(signal);
|
|
1818
|
+
} catch {
|
|
1819
|
+
}
|
|
1820
|
+
};
|
|
1821
|
+
var startShellTask = (options) => {
|
|
1822
|
+
const timeoutSeconds = options.timeoutSeconds;
|
|
1823
|
+
if (timeoutSeconds !== void 0 && timeoutSeconds > MAX_EXECUTION_TIMEOUT_SECONDS) {
|
|
1824
|
+
throw new Error(
|
|
1825
|
+
`timeoutSeconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less to fit Node's timer range; omit timeoutSeconds to run without an execution timer.`
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
|
|
1829
|
+
const forceKillDelayMs = options.forceKillDelayMs ?? FORCE_KILL_DELAY_MS;
|
|
1830
|
+
const startedAt = Date.now();
|
|
1831
|
+
const child = (options.spawnProcess ?? spawnShellProcess)(
|
|
1832
|
+
options.command,
|
|
1833
|
+
options.cwd
|
|
1834
|
+
);
|
|
1835
|
+
const metadata = typeof child.pid === "number" ? {
|
|
1836
|
+
executor_pid: child.pid,
|
|
1837
|
+
executor_pgid: process.platform === "win32" ? void 0 : child.pid
|
|
1838
|
+
} : {};
|
|
1839
|
+
let stdout = "";
|
|
1840
|
+
let stderr = "";
|
|
1841
|
+
let totalBytes = 0;
|
|
1842
|
+
let settled = false;
|
|
1843
|
+
let cancelRequested = false;
|
|
1844
|
+
let timeoutHandle;
|
|
1845
|
+
let forceKillHandle;
|
|
1846
|
+
const clearForceKillHandle = () => {
|
|
1847
|
+
if (!forceKillHandle) return;
|
|
1848
|
+
clearTimeout(forceKillHandle);
|
|
1849
|
+
forceKillHandle = void 0;
|
|
1850
|
+
};
|
|
1851
|
+
const scheduleForceKill = () => {
|
|
1852
|
+
if (forceKillHandle) return;
|
|
1853
|
+
forceKillHandle = setTimeout(() => {
|
|
1854
|
+
forceKillHandle = void 0;
|
|
1855
|
+
terminateChild(child, "SIGKILL");
|
|
1856
|
+
}, forceKillDelayMs);
|
|
1857
|
+
};
|
|
1858
|
+
const wait = new Promise((resolve) => {
|
|
1859
|
+
const settle = async (outcome) => {
|
|
1860
|
+
if (settled) return;
|
|
1861
|
+
settled = true;
|
|
1862
|
+
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
1863
|
+
let result;
|
|
1864
|
+
try {
|
|
1865
|
+
result = await buildShellTaskResult(options.outputCache, {
|
|
1866
|
+
taskId: options.taskId,
|
|
1867
|
+
toolName: options.toolName ?? "shell.exec",
|
|
1868
|
+
rawStdout: stdout,
|
|
1869
|
+
rawStderr: stderr,
|
|
1870
|
+
exitCode: outcome.exitCode,
|
|
1871
|
+
signal: outcome.signal,
|
|
1872
|
+
durationMs: Date.now() - startedAt
|
|
1873
|
+
});
|
|
1874
|
+
} catch {
|
|
1875
|
+
result = buildShellTaskResultBase({
|
|
1876
|
+
rawStdout: stdout,
|
|
1877
|
+
rawStderr: stderr,
|
|
1878
|
+
exitCode: outcome.exitCode,
|
|
1879
|
+
signal: outcome.signal,
|
|
1880
|
+
durationMs: Date.now() - startedAt
|
|
1881
|
+
});
|
|
1882
|
+
}
|
|
1883
|
+
resolve({
|
|
1884
|
+
state: outcome.state,
|
|
1885
|
+
result,
|
|
1886
|
+
...outcome.failureMessage ? { failure_message: outcome.failureMessage } : {},
|
|
1887
|
+
...outcome.cancellationReason ? { cancellation_reason: outcome.cancellationReason } : {}
|
|
1888
|
+
});
|
|
1889
|
+
};
|
|
1890
|
+
const fail = (message, signal) => {
|
|
1891
|
+
void settle({
|
|
1892
|
+
state: cancelRequested ? "cancelled" : "failed",
|
|
1893
|
+
exitCode: null,
|
|
1894
|
+
signal,
|
|
1895
|
+
failureMessage: cancelRequested ? void 0 : message,
|
|
1896
|
+
cancellationReason: cancelRequested ? "cancelled" : void 0
|
|
1897
|
+
});
|
|
1898
|
+
};
|
|
1899
|
+
const consumeChunk = (chunk, stream) => {
|
|
1900
|
+
if (settled) return;
|
|
1901
|
+
const text = chunk.toString("utf8");
|
|
1902
|
+
totalBytes += Buffer.byteLength(text, "utf8");
|
|
1903
|
+
if (totalBytes > maxOutputBytes) {
|
|
1904
|
+
terminateChild(child, "SIGTERM");
|
|
1905
|
+
scheduleForceKill();
|
|
1906
|
+
fail(
|
|
1907
|
+
`Command output exceeded max buffer of ${maxOutputBytes} bytes`,
|
|
1908
|
+
"SIGTERM"
|
|
1909
|
+
);
|
|
1910
|
+
return;
|
|
1911
|
+
}
|
|
1912
|
+
if (stream === "stdout") stdout += text;
|
|
1913
|
+
else stderr += text;
|
|
1914
|
+
};
|
|
1915
|
+
child.stdout.on("data", (chunk) => consumeChunk(chunk, "stdout"));
|
|
1916
|
+
child.stderr.on("data", (chunk) => consumeChunk(chunk, "stderr"));
|
|
1917
|
+
child.on("error", (error) => {
|
|
1918
|
+
fail(error.message, null);
|
|
1919
|
+
});
|
|
1920
|
+
child.on("close", (code, signal) => {
|
|
1921
|
+
clearForceKillHandle();
|
|
1922
|
+
if (settled) return;
|
|
1923
|
+
if (cancelRequested) {
|
|
1924
|
+
void settle({
|
|
1925
|
+
state: "cancelled",
|
|
1926
|
+
exitCode: code,
|
|
1927
|
+
signal: signal ?? null,
|
|
1928
|
+
cancellationReason: "cancelled"
|
|
1929
|
+
});
|
|
1930
|
+
return;
|
|
1931
|
+
}
|
|
1932
|
+
if (code === 0) {
|
|
1933
|
+
void settle({
|
|
1934
|
+
state: "completed",
|
|
1935
|
+
exitCode: code,
|
|
1936
|
+
signal: signal ?? null
|
|
1937
|
+
});
|
|
1938
|
+
return;
|
|
1939
|
+
}
|
|
1940
|
+
void settle({
|
|
1941
|
+
state: "failed",
|
|
1942
|
+
exitCode: code,
|
|
1943
|
+
signal: signal ?? null,
|
|
1944
|
+
failureMessage: `Command failed with exit code ${code ?? "unknown"}${signal ? ` signal ${signal}` : ""}`
|
|
1945
|
+
});
|
|
1946
|
+
});
|
|
1947
|
+
if (timeoutSeconds !== void 0) {
|
|
1948
|
+
timeoutHandle = setTimeout(() => {
|
|
1949
|
+
cancelRequested = false;
|
|
1950
|
+
terminateChild(child, "SIGTERM");
|
|
1951
|
+
scheduleForceKill();
|
|
1952
|
+
fail(
|
|
1953
|
+
`Command timed out after ${Math.trunc(timeoutSeconds)}s`,
|
|
1954
|
+
"SIGTERM"
|
|
1955
|
+
);
|
|
1956
|
+
}, timeoutSeconds * 1e3);
|
|
1957
|
+
}
|
|
1958
|
+
});
|
|
1959
|
+
return {
|
|
1960
|
+
metadata,
|
|
1961
|
+
wait,
|
|
1962
|
+
readOutput: async (stream) => stream === "stdout" ? stdout : stderr,
|
|
1963
|
+
cancel: async () => {
|
|
1964
|
+
if (settled) return;
|
|
1965
|
+
cancelRequested = true;
|
|
1966
|
+
terminateChild(child, "SIGTERM");
|
|
1967
|
+
scheduleForceKill();
|
|
1968
|
+
}
|
|
1969
|
+
};
|
|
1970
|
+
};
|
|
1971
|
+
|
|
1972
|
+
// src/execution-environment.ts
|
|
1973
|
+
var MAX_CHECK_OUTPUT_CHARS = 160;
|
|
1974
|
+
var MAX_CAPTURE_CHARS = 4096;
|
|
1975
|
+
var FORCE_KILL_DELAY_MS2 = 200;
|
|
1976
|
+
var firstNonEmptyLine = (value) => {
|
|
1977
|
+
for (const rawLine of value.split(/\r?\n/u)) {
|
|
1978
|
+
const line = rawLine.trim();
|
|
1979
|
+
if (line.length > 0) {
|
|
1980
|
+
return line;
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
return void 0;
|
|
1984
|
+
};
|
|
1985
|
+
var truncate = (value, maxChars = MAX_CHECK_OUTPUT_CHARS) => {
|
|
1986
|
+
if (value.length <= maxChars) {
|
|
1987
|
+
return value;
|
|
1988
|
+
}
|
|
1989
|
+
return `${value.slice(0, Math.max(1, maxChars - 1))}\u2026`;
|
|
1990
|
+
};
|
|
1991
|
+
var appendCaptured = (current, chunk) => {
|
|
1992
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
1993
|
+
if (current.length >= MAX_CAPTURE_CHARS) {
|
|
1994
|
+
return current;
|
|
1995
|
+
}
|
|
1996
|
+
return `${current}${text}`.slice(0, MAX_CAPTURE_CHARS);
|
|
1997
|
+
};
|
|
1998
|
+
var formatCommandLabel = (command) => JSON.stringify(command.join(" "));
|
|
1999
|
+
var shellQuote = (value) => {
|
|
2000
|
+
if (process.platform === "win32") {
|
|
2001
|
+
if (!value) return '""';
|
|
2002
|
+
return /^[A-Za-z0-9_./:-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
|
|
2003
|
+
}
|
|
2004
|
+
if (!value) return "''";
|
|
2005
|
+
return `'${value.replaceAll("'", "'\\''")}'`;
|
|
2006
|
+
};
|
|
2007
|
+
var buildShellCommand = (command) => command.map((part) => shellQuote(part)).join(" ");
|
|
2008
|
+
var describeExecutionEnvironmentHost = () => {
|
|
2009
|
+
const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
|
|
2010
|
+
const bashSyntaxGuaranteed = shellPath.length > 0 && path3.basename(shellPath).toLowerCase() === "bash";
|
|
2011
|
+
return {
|
|
2012
|
+
osDescription: `${os.type()} ${os.release()} (${process.platform} ${os.arch()})`,
|
|
2013
|
+
shellExecution: shellPath.length > 0 ? `${shellPath} -lc` : "platform shell via spawn(shell=true)",
|
|
2014
|
+
bashSyntaxGuaranteed
|
|
2015
|
+
};
|
|
2016
|
+
};
|
|
2017
|
+
var probeExecutionEnvironmentCommand = (command, timeoutMs, workingDir, probeOptions = {}) => {
|
|
2018
|
+
if (command.length === 0 || command[0].trim().length === 0) {
|
|
2019
|
+
return Promise.resolve("invalid command");
|
|
2020
|
+
}
|
|
2021
|
+
return new Promise((resolve) => {
|
|
2022
|
+
let stdout = "";
|
|
2023
|
+
let stderr = "";
|
|
2024
|
+
let settled = false;
|
|
2025
|
+
let timeoutHandle;
|
|
2026
|
+
let forceKillHandle;
|
|
2027
|
+
const clearForceKillHandle = () => {
|
|
2028
|
+
if (!forceKillHandle) return;
|
|
2029
|
+
clearTimeout(forceKillHandle);
|
|
2030
|
+
forceKillHandle = void 0;
|
|
2031
|
+
};
|
|
2032
|
+
const finish = (summary, options = {}) => {
|
|
2033
|
+
if (settled) return;
|
|
2034
|
+
settled = true;
|
|
2035
|
+
if (timeoutHandle) {
|
|
2036
|
+
clearTimeout(timeoutHandle);
|
|
2037
|
+
}
|
|
2038
|
+
if (!options.keepForceKill) {
|
|
2039
|
+
clearForceKillHandle();
|
|
2040
|
+
}
|
|
2041
|
+
resolve(summary);
|
|
2042
|
+
};
|
|
2043
|
+
let child;
|
|
2044
|
+
try {
|
|
2045
|
+
child = (probeOptions.spawnProcess ?? spawnShellProcess)(
|
|
2046
|
+
buildShellCommand(command),
|
|
2047
|
+
workingDir
|
|
2048
|
+
);
|
|
2049
|
+
} catch (error) {
|
|
2050
|
+
finish(`error: ${error instanceof Error ? error.message : String(error)}`);
|
|
2051
|
+
return;
|
|
2052
|
+
}
|
|
2053
|
+
timeoutHandle = setTimeout(() => {
|
|
2054
|
+
finish(`timeout after ${timeoutMs}ms`, { keepForceKill: true });
|
|
2055
|
+
(probeOptions.terminateProcess ?? terminateChild)(child, "SIGTERM");
|
|
2056
|
+
forceKillHandle = setTimeout(() => {
|
|
2057
|
+
forceKillHandle = void 0;
|
|
2058
|
+
(probeOptions.terminateProcess ?? terminateChild)(child, "SIGKILL");
|
|
2059
|
+
}, probeOptions.forceKillDelayMs ?? FORCE_KILL_DELAY_MS2);
|
|
2060
|
+
}, timeoutMs);
|
|
2061
|
+
child.on("error", (error) => {
|
|
2062
|
+
const errorCode = typeof error.code === "string" ? error.code : void 0;
|
|
2063
|
+
if (errorCode === "ENOENT") {
|
|
2064
|
+
finish("exit 127");
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
finish(
|
|
2068
|
+
`error: ${error instanceof Error ? error.message : String(error)}`
|
|
2069
|
+
);
|
|
2070
|
+
});
|
|
2071
|
+
child.stdout.on("data", (chunk) => {
|
|
2072
|
+
stdout = appendCaptured(stdout, chunk);
|
|
2073
|
+
});
|
|
2074
|
+
child.stderr.on("data", (chunk) => {
|
|
2075
|
+
stderr = appendCaptured(stderr, chunk);
|
|
2076
|
+
});
|
|
2077
|
+
child.on("close", (code, signal) => {
|
|
2078
|
+
clearForceKillHandle();
|
|
2079
|
+
if (settled) {
|
|
2080
|
+
return;
|
|
2081
|
+
}
|
|
2082
|
+
const line = firstNonEmptyLine(stdout) ?? firstNonEmptyLine(stderr);
|
|
2083
|
+
if (code === 0) {
|
|
2084
|
+
finish(line ? truncate(line) : "exit 0");
|
|
2085
|
+
return;
|
|
2086
|
+
}
|
|
2087
|
+
const exitSummary = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
|
|
2088
|
+
finish(line ? `${truncate(line)} (${exitSummary})` : exitSummary);
|
|
2089
|
+
});
|
|
2090
|
+
});
|
|
2091
|
+
};
|
|
2092
|
+
var collectExecutionEnvironmentStartupChecks = async (options) => {
|
|
2093
|
+
if (!options.config.startupChecks.enabled) {
|
|
2094
|
+
return [];
|
|
2095
|
+
}
|
|
2096
|
+
const probeCommand = options.probeCommand ?? probeExecutionEnvironmentCommand;
|
|
2097
|
+
return Promise.all(
|
|
2098
|
+
options.config.startupChecks.commands.map(async (command) => ({
|
|
2099
|
+
command: [...command],
|
|
2100
|
+
summary: await probeCommand(
|
|
2101
|
+
command,
|
|
2102
|
+
options.config.startupChecks.timeoutMs,
|
|
2103
|
+
options.workingDir,
|
|
2104
|
+
options.probeOptions
|
|
2105
|
+
)
|
|
2106
|
+
}))
|
|
2107
|
+
);
|
|
2108
|
+
};
|
|
2109
|
+
var formatExecutionEnvironmentContext = (options) => {
|
|
2110
|
+
const lines = [
|
|
2111
|
+
"<execution_environment>",
|
|
2112
|
+
`os: ${options.hostInfo.osDescription}`,
|
|
2113
|
+
`shell tool execution environment: ${options.hostInfo.shellExecution}`,
|
|
2114
|
+
`bash syntax guaranteed: ${options.hostInfo.bashSyntaxGuaranteed ? "true" : "false"}`,
|
|
2115
|
+
`sandbox root: ${options.sandboxRoot}`,
|
|
2116
|
+
`working directory: ${options.workingDir}`
|
|
2117
|
+
];
|
|
2118
|
+
if (options.startupChecks && options.startupChecks.length > 0) {
|
|
2119
|
+
lines.push("", "startup checks:");
|
|
2120
|
+
for (const check of options.startupChecks) {
|
|
2121
|
+
lines.push(
|
|
2122
|
+
`- ${formatCommandLabel(check.command)} => ${check.summary}`
|
|
2123
|
+
);
|
|
2124
|
+
}
|
|
2125
|
+
}
|
|
2126
|
+
lines.push("</execution_environment>");
|
|
2127
|
+
return lines.join("\n");
|
|
2128
|
+
};
|
|
2129
|
+
var buildExecutionEnvironmentContext = async (options) => {
|
|
2130
|
+
const startupChecks = await collectExecutionEnvironmentStartupChecks({
|
|
2131
|
+
config: options.config,
|
|
2132
|
+
workingDir: options.workingDir,
|
|
2133
|
+
probeCommand: options.probeCommand,
|
|
2134
|
+
probeOptions: options.probeOptions
|
|
2135
|
+
});
|
|
2136
|
+
return formatExecutionEnvironmentContext({
|
|
2137
|
+
workingDir: options.workingDir,
|
|
2138
|
+
sandboxRoot: options.sandboxRoot,
|
|
2139
|
+
hostInfo: options.hostInfo ?? describeExecutionEnvironmentHost(),
|
|
2140
|
+
startupChecks
|
|
2141
|
+
});
|
|
2142
|
+
};
|
|
2143
|
+
var appendInitialExecutionEnvironment = (systemPrompt, executionEnvironmentContext) => {
|
|
2144
|
+
if (!executionEnvironmentContext) {
|
|
2145
|
+
return systemPrompt;
|
|
2146
|
+
}
|
|
2147
|
+
return `${systemPrompt}
|
|
2148
|
+
|
|
2149
|
+
${executionEnvironmentContext}`;
|
|
2150
|
+
};
|
|
2151
|
+
var logInitialExecutionEnvironmentDebug = (executionEnvironmentContext, options = {}) => {
|
|
2152
|
+
if (!executionEnvironmentContext || options.alreadyLogged) {
|
|
2153
|
+
return false;
|
|
2154
|
+
}
|
|
2155
|
+
(options.log ?? debugLog)(
|
|
2156
|
+
`startup execution environment context
|
|
2157
|
+
${executionEnvironmentContext}`
|
|
2158
|
+
);
|
|
2159
|
+
return true;
|
|
2160
|
+
};
|
|
2161
|
+
|
|
1635
2162
|
// src/mcp/oauth.ts
|
|
1636
2163
|
var DEFAULT_MCP_OAUTH_PORT = 1456;
|
|
1637
2164
|
var DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS = 18e4;
|
|
@@ -2175,11 +2702,11 @@ var buildModelRegistry = async (llm, options = {}) => {
|
|
|
2175
2702
|
|
|
2176
2703
|
// src/permissions/approval-mode.ts
|
|
2177
2704
|
import { promises as fs4 } from "fs";
|
|
2178
|
-
import
|
|
2705
|
+
import path4 from "path";
|
|
2179
2706
|
import { parseApprovalMode } from "@codelia/shared-types";
|
|
2180
2707
|
import { ProjectsPolicyStore } from "@codelia/storage";
|
|
2181
2708
|
var normalizePath = async (value) => {
|
|
2182
|
-
const absolute =
|
|
2709
|
+
const absolute = path4.resolve(value);
|
|
2183
2710
|
try {
|
|
2184
2711
|
return await fs4.realpath(absolute);
|
|
2185
2712
|
} catch {
|
|
@@ -2319,10 +2846,10 @@ var resolveApprovalModeForRuntime = async (options, deps = {}) => {
|
|
|
2319
2846
|
};
|
|
2320
2847
|
|
|
2321
2848
|
// src/permissions/service.ts
|
|
2322
|
-
import
|
|
2849
|
+
import path6 from "path";
|
|
2323
2850
|
|
|
2324
2851
|
// src/permissions/utils.ts
|
|
2325
|
-
import
|
|
2852
|
+
import path5 from "path";
|
|
2326
2853
|
var REDIRECT_OPERATORS = /* @__PURE__ */ new Set(["<", ">", ">>", "2>", "2>>"]);
|
|
2327
2854
|
var SPLIT_OPERATORS = [
|
|
2328
2855
|
"2>>",
|
|
@@ -2614,7 +3141,7 @@ var deriveRememberCommand = (segment) => {
|
|
|
2614
3141
|
if (primaryIndex > 0) return null;
|
|
2615
3142
|
if (primaryIndex >= tokens.length) return null;
|
|
2616
3143
|
const primaryToken = tokens[primaryIndex];
|
|
2617
|
-
const primary =
|
|
3144
|
+
const primary = path5.basename(primaryToken);
|
|
2618
3145
|
if (!primary || primary === "." || primary === "..") return null;
|
|
2619
3146
|
if (!COMMAND_TOKEN_PATTERN.test(primary)) return null;
|
|
2620
3147
|
if (COMMAND_WRAPPER_TOKENS.has(primary)) return null;
|
|
@@ -2650,9 +3177,9 @@ var resolveCdTarget = (segment, currentWorkingDir, rootDir) => {
|
|
|
2650
3177
|
if (tokens.length !== 2) return null;
|
|
2651
3178
|
const target = tokens[1];
|
|
2652
3179
|
if (target === "-" || CD_UNSAFE_TARGET_PATTERN.test(target)) return null;
|
|
2653
|
-
const resolved =
|
|
2654
|
-
const relative =
|
|
2655
|
-
if (relative === "" || !relative.startsWith("..") && !
|
|
3180
|
+
const resolved = path5.resolve(currentWorkingDir, target);
|
|
3181
|
+
const relative = path5.relative(rootDir, resolved);
|
|
3182
|
+
if (relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative)) {
|
|
2656
3183
|
return resolved;
|
|
2657
3184
|
}
|
|
2658
3185
|
return null;
|
|
@@ -2758,8 +3285,8 @@ var PermissionService = class {
|
|
|
2758
3285
|
this.approvalMode = options.approvalMode ?? "minimal";
|
|
2759
3286
|
if (options.bashPathGuard) {
|
|
2760
3287
|
this.bashPathGuard = {
|
|
2761
|
-
rootDir:
|
|
2762
|
-
workingDir:
|
|
3288
|
+
rootDir: path6.resolve(options.bashPathGuard.rootDir),
|
|
3289
|
+
workingDir: path6.resolve(options.bashPathGuard.workingDir)
|
|
2763
3290
|
};
|
|
2764
3291
|
}
|
|
2765
3292
|
}
|
|
@@ -3004,7 +3531,7 @@ ${previewLines.join("\n")}`;
|
|
|
3004
3531
|
// src/sandbox/context.ts
|
|
3005
3532
|
import crypto from "crypto";
|
|
3006
3533
|
import { promises as fs5 } from "fs";
|
|
3007
|
-
import
|
|
3534
|
+
import path7 from "path";
|
|
3008
3535
|
var SecurityError = class extends Error {
|
|
3009
3536
|
constructor(message) {
|
|
3010
3537
|
super(message);
|
|
@@ -3024,7 +3551,7 @@ var SandboxContext = class _SandboxContext {
|
|
|
3024
3551
|
}
|
|
3025
3552
|
static async create(rootDir, options = {}) {
|
|
3026
3553
|
const sessionId = crypto.randomUUID().slice(0, 8);
|
|
3027
|
-
const root = rootDir ?
|
|
3554
|
+
const root = rootDir ? path7.resolve(rootDir) : process.cwd();
|
|
3028
3555
|
await fs5.mkdir(root, { recursive: true });
|
|
3029
3556
|
return new _SandboxContext({
|
|
3030
3557
|
rootDir: root,
|
|
@@ -3034,12 +3561,12 @@ var SandboxContext = class _SandboxContext {
|
|
|
3034
3561
|
});
|
|
3035
3562
|
}
|
|
3036
3563
|
resolvePath(targetPath) {
|
|
3037
|
-
const resolved =
|
|
3564
|
+
const resolved = path7.isAbsolute(targetPath) ? path7.resolve(targetPath) : path7.resolve(this.workingDir, targetPath);
|
|
3038
3565
|
if (this.approvalMode === "full-access") {
|
|
3039
3566
|
return resolved;
|
|
3040
3567
|
}
|
|
3041
|
-
const relative =
|
|
3042
|
-
if (relative === "" || !relative.startsWith("..") && !
|
|
3568
|
+
const relative = path7.relative(this.rootDir, resolved);
|
|
3569
|
+
if (relative === "" || !relative.startsWith("..") && !path7.isAbsolute(relative)) {
|
|
3043
3570
|
return resolved;
|
|
3044
3571
|
}
|
|
3045
3572
|
throw new SecurityError(
|
|
@@ -3063,8 +3590,8 @@ var getSkillsResolver = async (ctx, key) => ctx.resolve(key);
|
|
|
3063
3590
|
// src/skills/resolver.ts
|
|
3064
3591
|
import crypto2 from "crypto";
|
|
3065
3592
|
import { promises as fs6 } from "fs";
|
|
3066
|
-
import
|
|
3067
|
-
import
|
|
3593
|
+
import os2 from "os";
|
|
3594
|
+
import path8 from "path";
|
|
3068
3595
|
var DEFAULT_MARKERS2 = [".codelia", ".git", ".jj"];
|
|
3069
3596
|
var SKILL_NAME_PATTERN2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
3070
3597
|
var MAX_SKILL_FILES = 200;
|
|
@@ -3090,38 +3617,38 @@ var exists2 = async (targetPath) => {
|
|
|
3090
3617
|
};
|
|
3091
3618
|
var normalizeMtime2 = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
|
|
3092
3619
|
var resolvePathChain2 = (rootDir, targetDir) => {
|
|
3093
|
-
const normalizedRoot =
|
|
3094
|
-
const normalizedTarget =
|
|
3095
|
-
const relative =
|
|
3096
|
-
if (relative.startsWith("..") ||
|
|
3620
|
+
const normalizedRoot = path8.resolve(rootDir);
|
|
3621
|
+
const normalizedTarget = path8.resolve(targetDir);
|
|
3622
|
+
const relative = path8.relative(normalizedRoot, normalizedTarget);
|
|
3623
|
+
if (relative.startsWith("..") || path8.isAbsolute(relative) || relative === "..") {
|
|
3097
3624
|
return [];
|
|
3098
3625
|
}
|
|
3099
|
-
const parts = relative.split(
|
|
3626
|
+
const parts = relative.split(path8.sep).filter((part) => part.length > 0);
|
|
3100
3627
|
const chain = [normalizedRoot];
|
|
3101
3628
|
let current = normalizedRoot;
|
|
3102
3629
|
for (const part of parts) {
|
|
3103
|
-
current =
|
|
3630
|
+
current = path8.join(current, part);
|
|
3104
3631
|
chain.push(current);
|
|
3105
3632
|
}
|
|
3106
3633
|
return chain;
|
|
3107
3634
|
};
|
|
3108
3635
|
var findRootByMarkers2 = async (workingDir, markers) => {
|
|
3109
|
-
let current =
|
|
3636
|
+
let current = path8.resolve(workingDir);
|
|
3110
3637
|
while (true) {
|
|
3111
3638
|
for (const marker of markers) {
|
|
3112
|
-
if (await exists2(
|
|
3639
|
+
if (await exists2(path8.join(current, marker))) {
|
|
3113
3640
|
return current;
|
|
3114
3641
|
}
|
|
3115
3642
|
}
|
|
3116
|
-
const parent =
|
|
3643
|
+
const parent = path8.dirname(current);
|
|
3117
3644
|
if (parent === current) {
|
|
3118
|
-
return
|
|
3645
|
+
return path8.resolve(workingDir);
|
|
3119
3646
|
}
|
|
3120
3647
|
current = parent;
|
|
3121
3648
|
}
|
|
3122
3649
|
};
|
|
3123
3650
|
var tryResolvePath = async (targetPath) => {
|
|
3124
|
-
const resolved =
|
|
3651
|
+
const resolved = path8.resolve(targetPath);
|
|
3125
3652
|
try {
|
|
3126
3653
|
return { resolved, canonical: await fs6.realpath(resolved) };
|
|
3127
3654
|
} catch {
|
|
@@ -3129,8 +3656,8 @@ var tryResolvePath = async (targetPath) => {
|
|
|
3129
3656
|
}
|
|
3130
3657
|
};
|
|
3131
3658
|
var isWithin = (basePath, candidatePath) => {
|
|
3132
|
-
const relative =
|
|
3133
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
3659
|
+
const relative = path8.relative(basePath, candidatePath);
|
|
3660
|
+
return relative === "" || !relative.startsWith("..") && !path8.isAbsolute(relative);
|
|
3134
3661
|
};
|
|
3135
3662
|
var hashPath = (value) => crypto2.createHash("sha256").update(value).digest("hex").slice(0, 24);
|
|
3136
3663
|
var parseFrontmatter = (content) => {
|
|
@@ -3179,12 +3706,12 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3179
3706
|
}
|
|
3180
3707
|
static async create(options) {
|
|
3181
3708
|
const env = options.env ?? process.env;
|
|
3182
|
-
const workingDir =
|
|
3709
|
+
const workingDir = path8.resolve(options.workingDir);
|
|
3183
3710
|
const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
|
|
3184
3711
|
const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
|
|
3185
|
-
const rootDir = rootOverride ?
|
|
3186
|
-
const homeDir = toTrimmed2(env.HOME) ??
|
|
3187
|
-
const userSkillsDir =
|
|
3712
|
+
const rootDir = rootOverride ? path8.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
|
|
3713
|
+
const homeDir = toTrimmed2(env.HOME) ?? os2.homedir();
|
|
3714
|
+
const userSkillsDir = path8.join(path8.resolve(homeDir), ".agents", "skills");
|
|
3188
3715
|
const resolver = new _SkillsResolver({
|
|
3189
3716
|
workingDir,
|
|
3190
3717
|
rootDir,
|
|
@@ -3207,7 +3734,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3207
3734
|
return;
|
|
3208
3735
|
}
|
|
3209
3736
|
for (const entry of entries) {
|
|
3210
|
-
const entryPath =
|
|
3737
|
+
const entryPath = path8.join(dirPath, entry.name);
|
|
3211
3738
|
if (entry.isDirectory()) {
|
|
3212
3739
|
await walk(entryPath);
|
|
3213
3740
|
continue;
|
|
@@ -3224,7 +3751,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3224
3751
|
const directories = resolvePathChain2(this.rootDir, this.workingDir);
|
|
3225
3752
|
const skillFiles = [];
|
|
3226
3753
|
for (const directoryPath of directories) {
|
|
3227
|
-
const skillsRoot =
|
|
3754
|
+
const skillsRoot = path8.join(directoryPath, ".agents", "skills");
|
|
3228
3755
|
if (!await exists2(skillsRoot)) continue;
|
|
3229
3756
|
const files = await this.collectSkillFilesInTree(skillsRoot);
|
|
3230
3757
|
skillFiles.push(...files);
|
|
@@ -3281,8 +3808,8 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3281
3808
|
}
|
|
3282
3809
|
};
|
|
3283
3810
|
}
|
|
3284
|
-
const dir =
|
|
3285
|
-
if (
|
|
3811
|
+
const dir = path8.dirname(normalized.canonical);
|
|
3812
|
+
if (path8.basename(dir) !== name) {
|
|
3286
3813
|
return {
|
|
3287
3814
|
error: {
|
|
3288
3815
|
path: normalized.canonical,
|
|
@@ -3431,7 +3958,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3431
3958
|
}
|
|
3432
3959
|
const catalog = await this.getCatalog();
|
|
3433
3960
|
const normalizedQuery = query.toLowerCase();
|
|
3434
|
-
const queryPathCandidate =
|
|
3961
|
+
const queryPathCandidate = path8.resolve(this.workingDir, query);
|
|
3435
3962
|
const queryTokens = new Set(tokenize(normalizedQuery));
|
|
3436
3963
|
const scored = [];
|
|
3437
3964
|
for (const skill of catalog.skills) {
|
|
@@ -3489,7 +4016,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3489
4016
|
try {
|
|
3490
4017
|
rootReal = await fs6.realpath(skillDir);
|
|
3491
4018
|
} catch {
|
|
3492
|
-
rootReal =
|
|
4019
|
+
rootReal = path8.resolve(skillDir);
|
|
3493
4020
|
}
|
|
3494
4021
|
const files = [];
|
|
3495
4022
|
let bytes = 0;
|
|
@@ -3507,7 +4034,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3507
4034
|
}
|
|
3508
4035
|
for (const entry of entries) {
|
|
3509
4036
|
if (truncated) break;
|
|
3510
|
-
const entryPath =
|
|
4037
|
+
const entryPath = path8.join(dirPath, entry.name);
|
|
3511
4038
|
if (entry.isSymbolicLink()) {
|
|
3512
4039
|
continue;
|
|
3513
4040
|
}
|
|
@@ -3522,7 +4049,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3522
4049
|
try {
|
|
3523
4050
|
realPath = await fs6.realpath(entryPath);
|
|
3524
4051
|
} catch {
|
|
3525
|
-
realPath =
|
|
4052
|
+
realPath = path8.resolve(entryPath);
|
|
3526
4053
|
}
|
|
3527
4054
|
if (!isWithin(rootReal, realPath)) {
|
|
3528
4055
|
continue;
|
|
@@ -3551,7 +4078,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3551
4078
|
return { files, truncated };
|
|
3552
4079
|
}
|
|
3553
4080
|
async resolveByPath(pathInput) {
|
|
3554
|
-
const resolved =
|
|
4081
|
+
const resolved = path8.isAbsolute(pathInput) ? path8.resolve(pathInput) : path8.resolve(this.workingDir, pathInput);
|
|
3555
4082
|
const resolvedTry = await tryResolvePath(resolved);
|
|
3556
4083
|
const byCanonical = this.catalog.skills.find(
|
|
3557
4084
|
(entry) => entry.path === resolvedTry.canonical
|
|
@@ -3621,7 +4148,7 @@ var SkillsResolver = class _SkillsResolver {
|
|
|
3621
4148
|
}
|
|
3622
4149
|
const list = await this.listSkillFiles(selected.dir);
|
|
3623
4150
|
const filesXml = list.files.map((entry) => `<file>${entry}</file>`).join("\n");
|
|
3624
|
-
const trailingSlashDir = selected.dir.endsWith(
|
|
4151
|
+
const trailingSlashDir = selected.dir.endsWith(path8.sep) ? selected.dir : `${selected.dir}${path8.sep}`;
|
|
3625
4152
|
const content = [
|
|
3626
4153
|
`<skill_context name="${xmlEscape(selected.name)}" path="${xmlEscape(selected.path)}">`,
|
|
3627
4154
|
skillBody.trimEnd(),
|
|
@@ -3704,7 +4231,7 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool({
|
|
|
3704
4231
|
|
|
3705
4232
|
// src/tools/apply-patch.ts
|
|
3706
4233
|
import { promises as fs7 } from "fs";
|
|
3707
|
-
import
|
|
4234
|
+
import path9 from "path";
|
|
3708
4235
|
import { defineTool as defineTool2 } from "@codelia/core";
|
|
3709
4236
|
import { z as z3 } from "zod";
|
|
3710
4237
|
|
|
@@ -3713,27 +4240,27 @@ var DEFAULT_DIFF_PREVIEW_LINES = 120;
|
|
|
3713
4240
|
var DEFAULT_DIFF_PREVIEW_BYTES = 16 * 1024;
|
|
3714
4241
|
var normalizeLineEndings = (text) => text.replace(/\r\n/g, "\n");
|
|
3715
4242
|
var toLines = (text) => text === "" ? [] : text.split("\n");
|
|
3716
|
-
var
|
|
3717
|
-
var
|
|
4243
|
+
var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
|
|
4244
|
+
var truncateUtf8Prefix2 = (value, maxBytes) => {
|
|
3718
4245
|
if (maxBytes <= 0 || value.length === 0) return "";
|
|
3719
4246
|
let bytes = 0;
|
|
3720
4247
|
let out = "";
|
|
3721
4248
|
for (const ch of value) {
|
|
3722
|
-
const next =
|
|
4249
|
+
const next = utf8ByteLength2(ch);
|
|
3723
4250
|
if (bytes + next > maxBytes) break;
|
|
3724
4251
|
out += ch;
|
|
3725
4252
|
bytes += next;
|
|
3726
4253
|
}
|
|
3727
4254
|
return out;
|
|
3728
4255
|
};
|
|
3729
|
-
var
|
|
4256
|
+
var truncateUtf8Suffix2 = (value, maxBytes) => {
|
|
3730
4257
|
if (maxBytes <= 0 || value.length === 0) return "";
|
|
3731
4258
|
let bytes = 0;
|
|
3732
4259
|
const chars = Array.from(value);
|
|
3733
4260
|
const out = [];
|
|
3734
4261
|
for (let index = chars.length - 1; index >= 0; index -= 1) {
|
|
3735
4262
|
const ch = chars[index];
|
|
3736
|
-
const next =
|
|
4263
|
+
const next = utf8ByteLength2(ch);
|
|
3737
4264
|
if (bytes + next > maxBytes) break;
|
|
3738
4265
|
out.push(ch);
|
|
3739
4266
|
bytes += next;
|
|
@@ -3741,7 +4268,7 @@ var truncateUtf8Suffix = (value, maxBytes) => {
|
|
|
3741
4268
|
out.reverse();
|
|
3742
4269
|
return out.join("");
|
|
3743
4270
|
};
|
|
3744
|
-
var
|
|
4271
|
+
var excerptByLines2 = (value, maxLines) => {
|
|
3745
4272
|
const lines = value.split(/\r?\n/);
|
|
3746
4273
|
if (lines.length <= maxLines) {
|
|
3747
4274
|
return { text: value, truncated: false };
|
|
@@ -3758,15 +4285,15 @@ var excerptByLines = (value, maxLines) => {
|
|
|
3758
4285
|
truncated: true
|
|
3759
4286
|
};
|
|
3760
4287
|
};
|
|
3761
|
-
var
|
|
3762
|
-
if (
|
|
4288
|
+
var excerptByBytes2 = (value, maxBytes) => {
|
|
4289
|
+
if (utf8ByteLength2(value) <= maxBytes) {
|
|
3763
4290
|
return { text: value, truncated: false };
|
|
3764
4291
|
}
|
|
3765
4292
|
const marker = "\n...[truncated by size]...\n";
|
|
3766
|
-
const markerBytes =
|
|
4293
|
+
const markerBytes = utf8ByteLength2(marker);
|
|
3767
4294
|
if (maxBytes <= markerBytes + 2) {
|
|
3768
4295
|
return {
|
|
3769
|
-
text:
|
|
4296
|
+
text: truncateUtf8Prefix2(value, maxBytes),
|
|
3770
4297
|
truncated: true
|
|
3771
4298
|
};
|
|
3772
4299
|
}
|
|
@@ -3774,16 +4301,16 @@ var excerptByBytes = (value, maxBytes) => {
|
|
|
3774
4301
|
const headBytes = Math.floor(budget / 2);
|
|
3775
4302
|
const tailBytes = budget - headBytes;
|
|
3776
4303
|
return {
|
|
3777
|
-
text: `${
|
|
4304
|
+
text: `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`,
|
|
3778
4305
|
truncated: true
|
|
3779
4306
|
};
|
|
3780
4307
|
};
|
|
3781
4308
|
var summarizeDiff = (diff, options = {}) => {
|
|
3782
|
-
const lineExcerpt =
|
|
4309
|
+
const lineExcerpt = excerptByLines2(
|
|
3783
4310
|
diff,
|
|
3784
4311
|
options.maxLines ?? DEFAULT_DIFF_PREVIEW_LINES
|
|
3785
4312
|
);
|
|
3786
|
-
const byteExcerpt =
|
|
4313
|
+
const byteExcerpt = excerptByBytes2(
|
|
3787
4314
|
lineExcerpt.text,
|
|
3788
4315
|
options.maxBytes ?? DEFAULT_DIFF_PREVIEW_BYTES
|
|
3789
4316
|
);
|
|
@@ -3946,6 +4473,7 @@ var parseAddFileLines = (lines, startIndex, endIndex) => {
|
|
|
3946
4473
|
};
|
|
3947
4474
|
var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
|
|
3948
4475
|
const chunks = [];
|
|
4476
|
+
let sectionHasModification = false;
|
|
3949
4477
|
let index = startIndex;
|
|
3950
4478
|
while (index < endIndex) {
|
|
3951
4479
|
const line = lines[index] ?? "";
|
|
@@ -3999,11 +4527,7 @@ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
|
|
|
3999
4527
|
}
|
|
4000
4528
|
index += 1;
|
|
4001
4529
|
}
|
|
4002
|
-
|
|
4003
|
-
throw new Error(
|
|
4004
|
-
`Patch parse failed: chunk must contain at least one '+' or '-' change (line ${index + 1})`
|
|
4005
|
-
);
|
|
4006
|
-
}
|
|
4530
|
+
sectionHasModification ||= hasModification;
|
|
4007
4531
|
chunks.push({
|
|
4008
4532
|
...changeContext ? { changeContext } : {},
|
|
4009
4533
|
oldLines,
|
|
@@ -4014,6 +4538,11 @@ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
|
|
|
4014
4538
|
if (chunks.length === 0 && !options.allowEmpty) {
|
|
4015
4539
|
throw new Error("Patch parse failed: update file section has no chunks");
|
|
4016
4540
|
}
|
|
4541
|
+
if (!sectionHasModification && !options.allowEmpty) {
|
|
4542
|
+
throw new Error(
|
|
4543
|
+
"Patch parse failed: update file section must contain at least one '+' or '-' change"
|
|
4544
|
+
);
|
|
4545
|
+
}
|
|
4017
4546
|
return { chunks, nextIndex: index };
|
|
4018
4547
|
};
|
|
4019
4548
|
var parsePatch = (patchText) => {
|
|
@@ -4387,7 +4916,7 @@ var applyPreparedChanges = async (changes) => {
|
|
|
4387
4916
|
continue;
|
|
4388
4917
|
}
|
|
4389
4918
|
if (change.kind === "move" && change.resolvedMoveTo) {
|
|
4390
|
-
await fs7.mkdir(
|
|
4919
|
+
await fs7.mkdir(path9.dirname(change.resolvedMoveTo), { recursive: true });
|
|
4391
4920
|
await fs7.writeFile(change.resolvedMoveTo, change.after, "utf8");
|
|
4392
4921
|
if (typeof change.sourceMode === "number") {
|
|
4393
4922
|
await fs7.chmod(change.resolvedMoveTo, change.sourceMode);
|
|
@@ -4395,7 +4924,7 @@ var applyPreparedChanges = async (changes) => {
|
|
|
4395
4924
|
await fs7.unlink(change.resolvedPath);
|
|
4396
4925
|
continue;
|
|
4397
4926
|
}
|
|
4398
|
-
await fs7.mkdir(
|
|
4927
|
+
await fs7.mkdir(path9.dirname(change.resolvedPath), { recursive: true });
|
|
4399
4928
|
await fs7.writeFile(change.resolvedPath, change.after, "utf8");
|
|
4400
4929
|
}
|
|
4401
4930
|
};
|
|
@@ -4488,7 +5017,7 @@ var createDoneTool = () => defineTool3({
|
|
|
4488
5017
|
// src/tools/edit.ts
|
|
4489
5018
|
import crypto4 from "crypto";
|
|
4490
5019
|
import { promises as fs8 } from "fs";
|
|
4491
|
-
import
|
|
5020
|
+
import path10 from "path";
|
|
4492
5021
|
import { defineTool as defineTool4 } from "@codelia/core";
|
|
4493
5022
|
import { z as z5 } from "zod";
|
|
4494
5023
|
var trimLine = (line) => line.replace(/\r$/, "").trim();
|
|
@@ -4720,7 +5249,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => defineTool4({
|
|
|
4720
5249
|
};
|
|
4721
5250
|
}
|
|
4722
5251
|
try {
|
|
4723
|
-
await fs8.mkdir(
|
|
5252
|
+
await fs8.mkdir(path10.dirname(resolved), { recursive: true });
|
|
4724
5253
|
await fs8.writeFile(resolved, nextContent, "utf8");
|
|
4725
5254
|
} catch (error) {
|
|
4726
5255
|
throw new Error(`Error editing file: ${String(error)}`);
|
|
@@ -4742,21 +5271,21 @@ import { z as z6 } from "zod";
|
|
|
4742
5271
|
// src/lanes/manager.ts
|
|
4743
5272
|
import crypto5 from "crypto";
|
|
4744
5273
|
import { promises as fs10 } from "fs";
|
|
4745
|
-
import
|
|
4746
|
-
import
|
|
5274
|
+
import os3 from "os";
|
|
5275
|
+
import path12 from "path";
|
|
4747
5276
|
|
|
4748
5277
|
// src/lanes/command.ts
|
|
4749
|
-
import { spawn as
|
|
5278
|
+
import { spawn as spawn4 } from "child_process";
|
|
4750
5279
|
var DEFAULT_TIMEOUT_MS2 = 3e4;
|
|
4751
5280
|
var MAX_CAPTURE_BYTES = 512 * 1024;
|
|
4752
|
-
var
|
|
5281
|
+
var truncate2 = (value) => {
|
|
4753
5282
|
if (value.length <= 8e3) return value;
|
|
4754
5283
|
return `${value.slice(0, 8e3)}...[truncated]`;
|
|
4755
5284
|
};
|
|
4756
5285
|
var runCommand = async (command, args, options = {}) => {
|
|
4757
5286
|
const timeoutMs = Math.max(1e3, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
|
|
4758
5287
|
return new Promise((resolve, reject) => {
|
|
4759
|
-
const child =
|
|
5288
|
+
const child = spawn4(command, args, {
|
|
4760
5289
|
cwd: options.cwd,
|
|
4761
5290
|
stdio: ["ignore", "pipe", "pipe"]
|
|
4762
5291
|
});
|
|
@@ -4805,7 +5334,7 @@ var runCommand = async (command, args, options = {}) => {
|
|
|
4805
5334
|
}
|
|
4806
5335
|
const detail = `${stderr}
|
|
4807
5336
|
${stdout}`.trim();
|
|
4808
|
-
const message = detail ? `${command} ${args.join(" ")} failed (exit ${String(code)}): ${
|
|
5337
|
+
const message = detail ? `${command} ${args.join(" ")} failed (exit ${String(code)}): ${truncate2(detail)}` : `${command} ${args.join(" ")} failed (exit ${String(code)})`;
|
|
4809
5338
|
finish(() => reject(new Error(message)));
|
|
4810
5339
|
});
|
|
4811
5340
|
const timer = setTimeout(() => {
|
|
@@ -4826,7 +5355,7 @@ ${stdout}`.trim();
|
|
|
4826
5355
|
|
|
4827
5356
|
// src/lanes/registry.ts
|
|
4828
5357
|
import { promises as fs9 } from "fs";
|
|
4829
|
-
import
|
|
5358
|
+
import path11 from "path";
|
|
4830
5359
|
import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
|
|
4831
5360
|
var REGISTRY_DIRNAME = "lanes";
|
|
4832
5361
|
var REGISTRY_FILENAME = "registry.json";
|
|
@@ -4848,9 +5377,9 @@ var readJsonFile = async (filePath) => {
|
|
|
4848
5377
|
}
|
|
4849
5378
|
};
|
|
4850
5379
|
var atomicWrite = async (filePath, payload) => {
|
|
4851
|
-
const dir =
|
|
4852
|
-
const base =
|
|
4853
|
-
const tmp =
|
|
5380
|
+
const dir = path11.dirname(filePath);
|
|
5381
|
+
const base = path11.basename(filePath);
|
|
5382
|
+
const tmp = path11.join(
|
|
4854
5383
|
dir,
|
|
4855
5384
|
`${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
|
|
4856
5385
|
);
|
|
@@ -4865,10 +5394,10 @@ var LaneRegistryStore = class {
|
|
|
4865
5394
|
return;
|
|
4866
5395
|
}
|
|
4867
5396
|
const root = resolveStoragePaths2().root;
|
|
4868
|
-
this.registryPath =
|
|
5397
|
+
this.registryPath = path11.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
|
|
4869
5398
|
}
|
|
4870
5399
|
async ensureDir() {
|
|
4871
|
-
await fs9.mkdir(
|
|
5400
|
+
await fs9.mkdir(path11.dirname(this.registryPath), { recursive: true });
|
|
4872
5401
|
}
|
|
4873
5402
|
async readAll() {
|
|
4874
5403
|
await this.ensureDir();
|
|
@@ -4968,7 +5497,7 @@ var LaneManager = class {
|
|
|
4968
5497
|
this.now = options.now ?? nowIso2;
|
|
4969
5498
|
this.randomId = options.randomId ?? (() => crypto5.randomUUID());
|
|
4970
5499
|
this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
|
|
4971
|
-
this.defaultWorktreeRoot = options.defaultWorktreeRoot ??
|
|
5500
|
+
this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path12.join(os3.homedir(), ".codelia", "worktrees");
|
|
4972
5501
|
}
|
|
4973
5502
|
async cmd(command, args, options) {
|
|
4974
5503
|
debugLog(`lane.cmd ${command} ${args.join(" ")}`);
|
|
@@ -5091,9 +5620,9 @@ var LaneManager = class {
|
|
|
5091
5620
|
"rev-parse",
|
|
5092
5621
|
"--git-common-dir"
|
|
5093
5622
|
]);
|
|
5094
|
-
const commonDir =
|
|
5095
|
-
if (
|
|
5096
|
-
return
|
|
5623
|
+
const commonDir = path12.resolve(worktreePath, stdout.trim());
|
|
5624
|
+
if (path12.basename(commonDir) === ".git") {
|
|
5625
|
+
return path12.dirname(commonDir);
|
|
5097
5626
|
}
|
|
5098
5627
|
return await this.resolveRepoRoot(worktreePath);
|
|
5099
5628
|
}
|
|
@@ -5138,7 +5667,7 @@ var LaneManager = class {
|
|
|
5138
5667
|
const slug = toSlug(taskId);
|
|
5139
5668
|
const shortId = laneId.slice(0, 8);
|
|
5140
5669
|
const branchName = `lane/${slug}-${shortId}`;
|
|
5141
|
-
const worktreePath = input.worktree_path ?
|
|
5670
|
+
const worktreePath = input.worktree_path ? path12.resolve(options.workingDir, input.worktree_path) : path12.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
|
|
5142
5671
|
const muxTarget = `codelia-lane-${shortId}`;
|
|
5143
5672
|
const createdAt = this.now();
|
|
5144
5673
|
const record = {
|
|
@@ -5156,7 +5685,7 @@ var LaneManager = class {
|
|
|
5156
5685
|
};
|
|
5157
5686
|
await this.registry.upsert(record);
|
|
5158
5687
|
try {
|
|
5159
|
-
await fs10.mkdir(
|
|
5688
|
+
await fs10.mkdir(path12.dirname(worktreePath), { recursive: true });
|
|
5160
5689
|
await this.cmd("git", [
|
|
5161
5690
|
"-C",
|
|
5162
5691
|
repoRoot,
|
|
@@ -6258,391 +6787,95 @@ var TaskManager = class {
|
|
|
6258
6787
|
}
|
|
6259
6788
|
const intervalMs = options.pollIntervalMs ?? this.pollIntervalMs;
|
|
6260
6789
|
while (true) {
|
|
6261
|
-
const task = await this.requireTask(taskId);
|
|
6262
|
-
if (isTerminalTaskState(task.state)) {
|
|
6263
|
-
return task;
|
|
6264
|
-
}
|
|
6265
|
-
await withAbort(this.sleep(intervalMs), options.signal);
|
|
6266
|
-
}
|
|
6267
|
-
}
|
|
6268
|
-
async cancel(taskId, options = {}) {
|
|
6269
|
-
const reason = options.reason ?? "cancelled";
|
|
6270
|
-
const task = await this.requireTask(taskId);
|
|
6271
|
-
if (isTerminalTaskState(task.state)) {
|
|
6272
|
-
return task;
|
|
6273
|
-
}
|
|
6274
|
-
const active = this.activeTasks.get(taskId);
|
|
6275
|
-
if (active?.handle.cancel) {
|
|
6276
|
-
await active.handle.cancel(reason);
|
|
6277
|
-
return this.wait(taskId);
|
|
6278
|
-
}
|
|
6279
|
-
return this.cancelWithoutLocalHandle(task, reason);
|
|
6280
|
-
}
|
|
6281
|
-
async recoverOrphanedTasks() {
|
|
6282
|
-
const tasks = await this.registry.list();
|
|
6283
|
-
let recovered = 0;
|
|
6284
|
-
const errors = [];
|
|
6285
|
-
for (const task of tasks) {
|
|
6286
|
-
if (isTerminalTaskState(task.state)) {
|
|
6287
|
-
continue;
|
|
6288
|
-
}
|
|
6289
|
-
const ownerAlive = await this.processController.isProcessAlive(
|
|
6290
|
-
task.owner_pid
|
|
6291
|
-
);
|
|
6292
|
-
if (ownerAlive) {
|
|
6293
|
-
continue;
|
|
6294
|
-
}
|
|
6295
|
-
try {
|
|
6296
|
-
await this.terminatePersistedTask(task, "SIGTERM");
|
|
6297
|
-
await this.forceTerminateIfStillAlive(task);
|
|
6298
|
-
await this.finalizeTask(task.task_id, {
|
|
6299
|
-
state: "cancelled",
|
|
6300
|
-
cancellation_reason: OWNER_EXIT_REASON,
|
|
6301
|
-
cleanup_reason: OWNER_EXIT_REASON
|
|
6302
|
-
});
|
|
6303
|
-
recovered += 1;
|
|
6304
|
-
} catch (error) {
|
|
6305
|
-
errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
|
|
6306
|
-
}
|
|
6307
|
-
}
|
|
6308
|
-
return { recovered, errors };
|
|
6309
|
-
}
|
|
6310
|
-
async shutdown() {
|
|
6311
|
-
this.shuttingDown = true;
|
|
6312
|
-
const tasks = (await this.registry.list()).filter(
|
|
6313
|
-
(task) => task.owner_runtime_id === this.runtimeId && !isTerminalTaskState(task.state)
|
|
6314
|
-
);
|
|
6315
|
-
let cancelled = 0;
|
|
6316
|
-
const errors = [];
|
|
6317
|
-
for (const task of tasks) {
|
|
6318
|
-
try {
|
|
6319
|
-
const result = await Promise.race([
|
|
6320
|
-
this.cancel(task.task_id, { reason: OWNER_SHUTDOWN_REASON }).then(
|
|
6321
|
-
(record) => ({ timedOut: false, record })
|
|
6322
|
-
),
|
|
6323
|
-
this.sleep(this.gracePeriodMs).then(() => ({
|
|
6324
|
-
timedOut: true,
|
|
6325
|
-
record: null
|
|
6326
|
-
}))
|
|
6327
|
-
]);
|
|
6328
|
-
if (result.timedOut) {
|
|
6329
|
-
const refreshed = await this.requireTask(task.task_id);
|
|
6330
|
-
if (!isTerminalTaskState(refreshed.state)) {
|
|
6331
|
-
await this.terminatePersistedTask(refreshed, "SIGKILL");
|
|
6332
|
-
await this.finalizeTask(task.task_id, {
|
|
6333
|
-
state: "cancelled",
|
|
6334
|
-
cancellation_reason: OWNER_SHUTDOWN_REASON,
|
|
6335
|
-
cleanup_reason: OWNER_SHUTDOWN_REASON
|
|
6336
|
-
});
|
|
6337
|
-
}
|
|
6338
|
-
cancelled += 1;
|
|
6339
|
-
continue;
|
|
6340
|
-
}
|
|
6341
|
-
if (result.record.state === "cancelled") {
|
|
6342
|
-
cancelled += 1;
|
|
6343
|
-
}
|
|
6344
|
-
} catch (error) {
|
|
6345
|
-
errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
|
|
6346
|
-
}
|
|
6347
|
-
}
|
|
6348
|
-
return { cancelled, errors };
|
|
6349
|
-
}
|
|
6350
|
-
};
|
|
6351
|
-
|
|
6352
|
-
// src/tasks/shell-executor.ts
|
|
6353
|
-
import { spawn as spawn4 } from "child_process";
|
|
6354
|
-
|
|
6355
|
-
// src/tools/bash-utils.ts
|
|
6356
|
-
import { spawn as spawn3 } from "child_process";
|
|
6357
|
-
var DEBUG_MAX_COMMAND_CHARS = 200;
|
|
6358
|
-
var DEFAULT_TIMEOUT_SECONDS = 120;
|
|
6359
|
-
var MAX_TIMEOUT_SECONDS = 300;
|
|
6360
|
-
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
6361
|
-
var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
|
|
6362
|
-
MAX_TIMER_DELAY_MS / 1e3
|
|
6363
|
-
);
|
|
6364
|
-
var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
6365
|
-
var summarizeCommand = (command) => {
|
|
6366
|
-
const normalized = command.trim().replace(/\s+/g, " ");
|
|
6367
|
-
if (normalized.length <= DEBUG_MAX_COMMAND_CHARS) {
|
|
6368
|
-
return normalized;
|
|
6369
|
-
}
|
|
6370
|
-
return `${normalized.slice(0, DEBUG_MAX_COMMAND_CHARS)}...[truncated]`;
|
|
6371
|
-
};
|
|
6372
|
-
|
|
6373
|
-
// src/tasks/shell-executor.ts
|
|
6374
|
-
var DEFAULT_EXCERPT_LINES = 80;
|
|
6375
|
-
var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
|
|
6376
|
-
var FORCE_KILL_DELAY_MS = 2e3;
|
|
6377
|
-
var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
|
|
6378
|
-
var truncateUtf8Prefix2 = (value, maxBytes) => {
|
|
6379
|
-
if (maxBytes <= 0 || value.length === 0) return "";
|
|
6380
|
-
let bytes = 0;
|
|
6381
|
-
let out = "";
|
|
6382
|
-
for (const ch of value) {
|
|
6383
|
-
const next = utf8ByteLength2(ch);
|
|
6384
|
-
if (bytes + next > maxBytes) break;
|
|
6385
|
-
out += ch;
|
|
6386
|
-
bytes += next;
|
|
6387
|
-
}
|
|
6388
|
-
return out;
|
|
6389
|
-
};
|
|
6390
|
-
var truncateUtf8Suffix2 = (value, maxBytes) => {
|
|
6391
|
-
if (maxBytes <= 0 || value.length === 0) return "";
|
|
6392
|
-
let bytes = 0;
|
|
6393
|
-
const chars = Array.from(value);
|
|
6394
|
-
const out = [];
|
|
6395
|
-
for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
|
|
6396
|
-
const ch = chars[idx];
|
|
6397
|
-
const next = utf8ByteLength2(ch);
|
|
6398
|
-
if (bytes + next > maxBytes) break;
|
|
6399
|
-
out.push(ch);
|
|
6400
|
-
bytes += next;
|
|
6401
|
-
}
|
|
6402
|
-
out.reverse();
|
|
6403
|
-
return out.join("");
|
|
6404
|
-
};
|
|
6405
|
-
var excerptByLines2 = (value) => {
|
|
6406
|
-
const lines = value.split(/\r?\n/);
|
|
6407
|
-
if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
|
|
6408
|
-
const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
|
|
6409
|
-
const tail = lines.slice(lines.length - DEFAULT_EXCERPT_LINES);
|
|
6410
|
-
const omitted = lines.length - head.length - tail.length;
|
|
6411
|
-
return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
|
|
6412
|
-
};
|
|
6413
|
-
var excerptByBytes2 = (value, maxBytes) => {
|
|
6414
|
-
if (utf8ByteLength2(value) <= maxBytes) return value;
|
|
6415
|
-
const marker = "\n...[truncated by size]...\n";
|
|
6416
|
-
const markerBytes = utf8ByteLength2(marker);
|
|
6417
|
-
if (maxBytes <= markerBytes + 2) {
|
|
6418
|
-
return truncateUtf8Prefix2(value, maxBytes);
|
|
6419
|
-
}
|
|
6420
|
-
const budget = maxBytes - markerBytes;
|
|
6421
|
-
const headBytes = Math.floor(budget / 2);
|
|
6422
|
-
const tailBytes = budget - headBytes;
|
|
6423
|
-
return `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`;
|
|
6424
|
-
};
|
|
6425
|
-
var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength2(value) > MAX_INLINE_OUTPUT_BYTES;
|
|
6426
|
-
var excerptText = (value) => excerptByBytes2(excerptByLines2(value), MAX_INLINE_OUTPUT_BYTES);
|
|
6427
|
-
var buildShellTaskResultBase = (options) => {
|
|
6428
|
-
const stdoutTruncated = needsInlineTruncation(options.rawStdout);
|
|
6429
|
-
const stderrTruncated = needsInlineTruncation(options.rawStderr);
|
|
6430
|
-
return {
|
|
6431
|
-
stdout: stdoutTruncated ? excerptText(options.rawStdout) : options.rawStdout,
|
|
6432
|
-
stderr: stderrTruncated ? excerptText(options.rawStderr) : options.rawStderr,
|
|
6433
|
-
exit_code: options.exitCode,
|
|
6434
|
-
signal: options.signal,
|
|
6435
|
-
duration_ms: options.durationMs,
|
|
6436
|
-
truncated: {
|
|
6437
|
-
stdout: stdoutTruncated,
|
|
6438
|
-
stderr: stderrTruncated,
|
|
6439
|
-
combined: stdoutTruncated || stderrTruncated
|
|
6440
|
-
}
|
|
6441
|
-
};
|
|
6442
|
-
};
|
|
6443
|
-
var buildShellTaskResult = async (outputCache, options) => {
|
|
6444
|
-
const base = buildShellTaskResultBase(options);
|
|
6445
|
-
let stdoutCacheId;
|
|
6446
|
-
let stderrCacheId;
|
|
6447
|
-
if (base.truncated?.stdout && options.rawStdout.length > 0) {
|
|
6448
|
-
const saved = await outputCache.save({
|
|
6449
|
-
tool_call_id: `${options.taskId}_stdout`,
|
|
6450
|
-
tool_name: options.toolName,
|
|
6451
|
-
content: options.rawStdout
|
|
6452
|
-
});
|
|
6453
|
-
stdoutCacheId = saved.id;
|
|
6454
|
-
}
|
|
6455
|
-
if (base.truncated?.stderr && options.rawStderr.length > 0) {
|
|
6456
|
-
const saved = await outputCache.save({
|
|
6457
|
-
tool_call_id: `${options.taskId}_stderr`,
|
|
6458
|
-
tool_name: options.toolName,
|
|
6459
|
-
content: options.rawStderr
|
|
6460
|
-
});
|
|
6461
|
-
stderrCacheId = saved.id;
|
|
6462
|
-
}
|
|
6463
|
-
return {
|
|
6464
|
-
...base,
|
|
6465
|
-
...stdoutCacheId ? { stdout_cache_id: stdoutCacheId } : {},
|
|
6466
|
-
...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
|
|
6467
|
-
};
|
|
6468
|
-
};
|
|
6469
|
-
var spawnShellProcess = (command, cwd) => {
|
|
6470
|
-
const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
|
|
6471
|
-
if (shellPath) {
|
|
6472
|
-
return spawn4(shellPath, ["-lc", command], {
|
|
6473
|
-
cwd,
|
|
6474
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
6475
|
-
detached: true
|
|
6476
|
-
});
|
|
6477
|
-
}
|
|
6478
|
-
return spawn4(command, {
|
|
6479
|
-
cwd,
|
|
6480
|
-
shell: true,
|
|
6481
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
6482
|
-
detached: process.platform !== "win32"
|
|
6483
|
-
});
|
|
6484
|
-
};
|
|
6485
|
-
var terminateChild = (child, signal) => {
|
|
6486
|
-
if (typeof child.pid === "number" && process.platform !== "win32") {
|
|
6487
|
-
try {
|
|
6488
|
-
process.kill(-child.pid, signal);
|
|
6489
|
-
} catch {
|
|
6790
|
+
const task = await this.requireTask(taskId);
|
|
6791
|
+
if (isTerminalTaskState(task.state)) {
|
|
6792
|
+
return task;
|
|
6793
|
+
}
|
|
6794
|
+
await withAbort(this.sleep(intervalMs), options.signal);
|
|
6490
6795
|
}
|
|
6491
6796
|
}
|
|
6492
|
-
|
|
6493
|
-
|
|
6494
|
-
|
|
6495
|
-
|
|
6496
|
-
|
|
6497
|
-
|
|
6498
|
-
|
|
6499
|
-
|
|
6500
|
-
|
|
6501
|
-
|
|
6502
|
-
|
|
6797
|
+
async cancel(taskId, options = {}) {
|
|
6798
|
+
const reason = options.reason ?? "cancelled";
|
|
6799
|
+
const task = await this.requireTask(taskId);
|
|
6800
|
+
if (isTerminalTaskState(task.state)) {
|
|
6801
|
+
return task;
|
|
6802
|
+
}
|
|
6803
|
+
const active = this.activeTasks.get(taskId);
|
|
6804
|
+
if (active?.handle.cancel) {
|
|
6805
|
+
await active.handle.cancel(reason);
|
|
6806
|
+
return this.wait(taskId);
|
|
6807
|
+
}
|
|
6808
|
+
return this.cancelWithoutLocalHandle(task, reason);
|
|
6503
6809
|
}
|
|
6504
|
-
|
|
6505
|
-
|
|
6506
|
-
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
const metadata = typeof child.pid === "number" ? {
|
|
6512
|
-
executor_pid: child.pid,
|
|
6513
|
-
executor_pgid: process.platform === "win32" ? void 0 : child.pid
|
|
6514
|
-
} : {};
|
|
6515
|
-
let stdout = "";
|
|
6516
|
-
let stderr = "";
|
|
6517
|
-
let totalBytes = 0;
|
|
6518
|
-
let settled = false;
|
|
6519
|
-
let cancelRequested = false;
|
|
6520
|
-
let timeoutHandle;
|
|
6521
|
-
let forceKillHandle;
|
|
6522
|
-
const clearForceKillHandle = () => {
|
|
6523
|
-
if (!forceKillHandle) return;
|
|
6524
|
-
clearTimeout(forceKillHandle);
|
|
6525
|
-
forceKillHandle = void 0;
|
|
6526
|
-
};
|
|
6527
|
-
const scheduleForceKill = () => {
|
|
6528
|
-
if (forceKillHandle) return;
|
|
6529
|
-
forceKillHandle = setTimeout(() => {
|
|
6530
|
-
forceKillHandle = void 0;
|
|
6531
|
-
terminateChild(child, "SIGKILL");
|
|
6532
|
-
}, forceKillDelayMs);
|
|
6533
|
-
};
|
|
6534
|
-
const wait = new Promise((resolve) => {
|
|
6535
|
-
const settle = async (outcome) => {
|
|
6536
|
-
if (settled) return;
|
|
6537
|
-
settled = true;
|
|
6538
|
-
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
6539
|
-
let result;
|
|
6540
|
-
try {
|
|
6541
|
-
result = await buildShellTaskResult(options.outputCache, {
|
|
6542
|
-
taskId: options.taskId,
|
|
6543
|
-
toolName: options.toolName ?? "shell.exec",
|
|
6544
|
-
rawStdout: stdout,
|
|
6545
|
-
rawStderr: stderr,
|
|
6546
|
-
exitCode: outcome.exitCode,
|
|
6547
|
-
signal: outcome.signal,
|
|
6548
|
-
durationMs: Date.now() - startedAt
|
|
6549
|
-
});
|
|
6550
|
-
} catch {
|
|
6551
|
-
result = buildShellTaskResultBase({
|
|
6552
|
-
rawStdout: stdout,
|
|
6553
|
-
rawStderr: stderr,
|
|
6554
|
-
exitCode: outcome.exitCode,
|
|
6555
|
-
signal: outcome.signal,
|
|
6556
|
-
durationMs: Date.now() - startedAt
|
|
6557
|
-
});
|
|
6810
|
+
async recoverOrphanedTasks() {
|
|
6811
|
+
const tasks = await this.registry.list();
|
|
6812
|
+
let recovered = 0;
|
|
6813
|
+
const errors = [];
|
|
6814
|
+
for (const task of tasks) {
|
|
6815
|
+
if (isTerminalTaskState(task.state)) {
|
|
6816
|
+
continue;
|
|
6558
6817
|
}
|
|
6559
|
-
|
|
6560
|
-
|
|
6561
|
-
|
|
6562
|
-
|
|
6563
|
-
|
|
6564
|
-
});
|
|
6565
|
-
};
|
|
6566
|
-
const fail = (message, signal) => {
|
|
6567
|
-
void settle({
|
|
6568
|
-
state: cancelRequested ? "cancelled" : "failed",
|
|
6569
|
-
exitCode: null,
|
|
6570
|
-
signal,
|
|
6571
|
-
failureMessage: cancelRequested ? void 0 : message,
|
|
6572
|
-
cancellationReason: cancelRequested ? "cancelled" : void 0
|
|
6573
|
-
});
|
|
6574
|
-
};
|
|
6575
|
-
const consumeChunk = (chunk, stream) => {
|
|
6576
|
-
if (settled) return;
|
|
6577
|
-
const text = chunk.toString("utf8");
|
|
6578
|
-
totalBytes += Buffer.byteLength(text, "utf8");
|
|
6579
|
-
if (totalBytes > maxOutputBytes) {
|
|
6580
|
-
terminateChild(child, "SIGTERM");
|
|
6581
|
-
scheduleForceKill();
|
|
6582
|
-
fail(
|
|
6583
|
-
`Command output exceeded max buffer of ${maxOutputBytes} bytes`,
|
|
6584
|
-
"SIGTERM"
|
|
6585
|
-
);
|
|
6586
|
-
return;
|
|
6818
|
+
const ownerAlive = await this.processController.isProcessAlive(
|
|
6819
|
+
task.owner_pid
|
|
6820
|
+
);
|
|
6821
|
+
if (ownerAlive) {
|
|
6822
|
+
continue;
|
|
6587
6823
|
}
|
|
6588
|
-
|
|
6589
|
-
|
|
6590
|
-
|
|
6591
|
-
|
|
6592
|
-
child.stderr.on("data", (chunk) => consumeChunk(chunk, "stderr"));
|
|
6593
|
-
child.on("error", (error) => {
|
|
6594
|
-
fail(error.message, null);
|
|
6595
|
-
});
|
|
6596
|
-
child.on("close", (code, signal) => {
|
|
6597
|
-
clearForceKillHandle();
|
|
6598
|
-
if (settled) return;
|
|
6599
|
-
if (cancelRequested) {
|
|
6600
|
-
void settle({
|
|
6824
|
+
try {
|
|
6825
|
+
await this.terminatePersistedTask(task, "SIGTERM");
|
|
6826
|
+
await this.forceTerminateIfStillAlive(task);
|
|
6827
|
+
await this.finalizeTask(task.task_id, {
|
|
6601
6828
|
state: "cancelled",
|
|
6602
|
-
|
|
6603
|
-
|
|
6604
|
-
cancellationReason: "cancelled"
|
|
6605
|
-
});
|
|
6606
|
-
return;
|
|
6607
|
-
}
|
|
6608
|
-
if (code === 0) {
|
|
6609
|
-
void settle({
|
|
6610
|
-
state: "completed",
|
|
6611
|
-
exitCode: code,
|
|
6612
|
-
signal: signal ?? null
|
|
6829
|
+
cancellation_reason: OWNER_EXIT_REASON,
|
|
6830
|
+
cleanup_reason: OWNER_EXIT_REASON
|
|
6613
6831
|
});
|
|
6614
|
-
|
|
6832
|
+
recovered += 1;
|
|
6833
|
+
} catch (error) {
|
|
6834
|
+
errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
|
|
6615
6835
|
}
|
|
6616
|
-
void settle({
|
|
6617
|
-
state: "failed",
|
|
6618
|
-
exitCode: code,
|
|
6619
|
-
signal: signal ?? null,
|
|
6620
|
-
failureMessage: `Command failed with exit code ${code ?? "unknown"}${signal ? ` signal ${signal}` : ""}`
|
|
6621
|
-
});
|
|
6622
|
-
});
|
|
6623
|
-
if (timeoutSeconds !== void 0) {
|
|
6624
|
-
timeoutHandle = setTimeout(() => {
|
|
6625
|
-
cancelRequested = false;
|
|
6626
|
-
terminateChild(child, "SIGTERM");
|
|
6627
|
-
scheduleForceKill();
|
|
6628
|
-
fail(
|
|
6629
|
-
`Command timed out after ${Math.trunc(timeoutSeconds)}s`,
|
|
6630
|
-
"SIGTERM"
|
|
6631
|
-
);
|
|
6632
|
-
}, timeoutSeconds * 1e3);
|
|
6633
6836
|
}
|
|
6634
|
-
|
|
6635
|
-
|
|
6636
|
-
|
|
6637
|
-
|
|
6638
|
-
|
|
6639
|
-
|
|
6640
|
-
|
|
6641
|
-
|
|
6642
|
-
|
|
6643
|
-
|
|
6837
|
+
return { recovered, errors };
|
|
6838
|
+
}
|
|
6839
|
+
async shutdown() {
|
|
6840
|
+
this.shuttingDown = true;
|
|
6841
|
+
const tasks = (await this.registry.list()).filter(
|
|
6842
|
+
(task) => task.owner_runtime_id === this.runtimeId && !isTerminalTaskState(task.state)
|
|
6843
|
+
);
|
|
6844
|
+
let cancelled = 0;
|
|
6845
|
+
const errors = [];
|
|
6846
|
+
for (const task of tasks) {
|
|
6847
|
+
try {
|
|
6848
|
+
const result = await Promise.race([
|
|
6849
|
+
this.cancel(task.task_id, { reason: OWNER_SHUTDOWN_REASON }).then(
|
|
6850
|
+
(record) => ({ timedOut: false, record })
|
|
6851
|
+
),
|
|
6852
|
+
this.sleep(this.gracePeriodMs).then(() => ({
|
|
6853
|
+
timedOut: true,
|
|
6854
|
+
record: null
|
|
6855
|
+
}))
|
|
6856
|
+
]);
|
|
6857
|
+
if (result.timedOut) {
|
|
6858
|
+
const refreshed = await this.requireTask(task.task_id);
|
|
6859
|
+
if (!isTerminalTaskState(refreshed.state)) {
|
|
6860
|
+
await this.terminatePersistedTask(refreshed, "SIGKILL");
|
|
6861
|
+
await this.finalizeTask(task.task_id, {
|
|
6862
|
+
state: "cancelled",
|
|
6863
|
+
cancellation_reason: OWNER_SHUTDOWN_REASON,
|
|
6864
|
+
cleanup_reason: OWNER_SHUTDOWN_REASON
|
|
6865
|
+
});
|
|
6866
|
+
}
|
|
6867
|
+
cancelled += 1;
|
|
6868
|
+
continue;
|
|
6869
|
+
}
|
|
6870
|
+
if (result.record.state === "cancelled") {
|
|
6871
|
+
cancelled += 1;
|
|
6872
|
+
}
|
|
6873
|
+
} catch (error) {
|
|
6874
|
+
errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
|
|
6875
|
+
}
|
|
6644
6876
|
}
|
|
6645
|
-
|
|
6877
|
+
return { cancelled, errors };
|
|
6878
|
+
}
|
|
6646
6879
|
};
|
|
6647
6880
|
|
|
6648
6881
|
// src/tools/session-context.ts
|
|
@@ -7817,7 +8050,7 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
|
|
|
7817
8050
|
|
|
7818
8051
|
// src/tools/view-image.ts
|
|
7819
8052
|
import { promises as fs13 } from "fs";
|
|
7820
|
-
import
|
|
8053
|
+
import path13 from "path";
|
|
7821
8054
|
import { defineTool as defineTool15 } from "@codelia/core";
|
|
7822
8055
|
import { z as z16 } from "zod";
|
|
7823
8056
|
var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
|
|
@@ -7830,7 +8063,7 @@ var MIME_BY_EXTENSION = {
|
|
|
7830
8063
|
".gif": "image/gif"
|
|
7831
8064
|
};
|
|
7832
8065
|
var resolveImageMime = (filePath) => {
|
|
7833
|
-
return MIME_BY_EXTENSION[
|
|
8066
|
+
return MIME_BY_EXTENSION[path13.extname(filePath).toLowerCase()] ?? null;
|
|
7834
8067
|
};
|
|
7835
8068
|
var createViewImageTool = (sandboxKey) => defineTool15({
|
|
7836
8069
|
name: "view_image",
|
|
@@ -8218,7 +8451,7 @@ var createWebfetchTool = () => defineTool16({
|
|
|
8218
8451
|
|
|
8219
8452
|
// src/tools/write.ts
|
|
8220
8453
|
import { promises as fs14 } from "fs";
|
|
8221
|
-
import
|
|
8454
|
+
import path14 from "path";
|
|
8222
8455
|
import { defineTool as defineTool17 } from "@codelia/core";
|
|
8223
8456
|
import { z as z18 } from "zod";
|
|
8224
8457
|
var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
|
|
@@ -8247,7 +8480,7 @@ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
|
|
|
8247
8480
|
throw error;
|
|
8248
8481
|
}
|
|
8249
8482
|
}
|
|
8250
|
-
await fs14.mkdir(
|
|
8483
|
+
await fs14.mkdir(path14.dirname(resolved), { recursive: true });
|
|
8251
8484
|
await fs14.writeFile(resolved, input.content, "utf8");
|
|
8252
8485
|
const diffPayload = await buildDiffPayload({
|
|
8253
8486
|
toolName: "write",
|
|
@@ -8361,9 +8594,9 @@ var normalizeLanguage = (value) => {
|
|
|
8361
8594
|
};
|
|
8362
8595
|
var languageFromFilePath = (filePath) => {
|
|
8363
8596
|
if (!filePath) return void 0;
|
|
8364
|
-
const
|
|
8365
|
-
if (!
|
|
8366
|
-
const normalizedPath =
|
|
8597
|
+
const path20 = filePath.trim().replace(/^["']|["']$/g, "");
|
|
8598
|
+
if (!path20 || path20 === "/dev/null") return void 0;
|
|
8599
|
+
const normalizedPath = path20.replace(/^a\//, "").replace(/^b\//, "");
|
|
8367
8600
|
const lastSlash = Math.max(
|
|
8368
8601
|
normalizedPath.lastIndexOf("/"),
|
|
8369
8602
|
normalizedPath.lastIndexOf("\\")
|
|
@@ -8766,8 +8999,12 @@ var createAgentFactory = (state, options = {}) => {
|
|
|
8766
8999
|
const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
|
|
8767
9000
|
state.agentsResolver = agentsResolver;
|
|
8768
9001
|
let skillsConfig;
|
|
9002
|
+
let executionEnvironmentConfig;
|
|
8769
9003
|
try {
|
|
8770
|
-
skillsConfig = await
|
|
9004
|
+
[skillsConfig, executionEnvironmentConfig] = await Promise.all([
|
|
9005
|
+
resolveSkillsConfig(ctx.workingDir),
|
|
9006
|
+
resolveExecutionEnvironmentConfig(ctx.workingDir)
|
|
9007
|
+
]);
|
|
8771
9008
|
} catch (error) {
|
|
8772
9009
|
const message = error instanceof Error ? error.message : String(error);
|
|
8773
9010
|
throw new Error(message);
|
|
@@ -8824,8 +9061,23 @@ var createAgentFactory = (state, options = {}) => {
|
|
|
8824
9061
|
}
|
|
8825
9062
|
}
|
|
8826
9063
|
const baseSystemPrompt = await loadSystemPrompt(ctx.workingDir);
|
|
8827
|
-
const
|
|
9064
|
+
const executionEnvironmentContext = await buildExecutionEnvironmentContext({
|
|
9065
|
+
workingDir: ctx.workingDir,
|
|
9066
|
+
sandboxRoot: ctx.rootDir,
|
|
9067
|
+
config: executionEnvironmentConfig
|
|
9068
|
+
});
|
|
9069
|
+
state.executionEnvironmentContext = executionEnvironmentContext;
|
|
9070
|
+
if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
|
|
9071
|
+
alreadyLogged: state.executionEnvironmentDebugLogged
|
|
9072
|
+
})) {
|
|
9073
|
+
state.executionEnvironmentDebugLogged = true;
|
|
9074
|
+
}
|
|
9075
|
+
const withExecutionEnvironment = appendInitialExecutionEnvironment(
|
|
8828
9076
|
baseSystemPrompt,
|
|
9077
|
+
executionEnvironmentContext
|
|
9078
|
+
);
|
|
9079
|
+
const withAgentsContext = appendInitialAgentsContext(
|
|
9080
|
+
withExecutionEnvironment,
|
|
8829
9081
|
agentsResolver.buildInitialContext()
|
|
8830
9082
|
);
|
|
8831
9083
|
const systemPrompt = appendInitialSkillsCatalog(
|
|
@@ -9728,8 +9980,8 @@ var parseAuthorizationServerMetadata = (value) => {
|
|
|
9728
9980
|
var buildAuthorizationServerMetadataUrl = (issuer) => {
|
|
9729
9981
|
try {
|
|
9730
9982
|
const parsed = new URL(issuer);
|
|
9731
|
-
const
|
|
9732
|
-
const basePath =
|
|
9983
|
+
const path20 = parsed.pathname === "/" ? "" : parsed.pathname;
|
|
9984
|
+
const basePath = path20.startsWith("/") ? path20 : `/${path20}`;
|
|
9733
9985
|
const metadataPath = `/.well-known/oauth-authorization-server${basePath}`;
|
|
9734
9986
|
return new URL(metadataPath, `${parsed.origin}/`).toString();
|
|
9735
9987
|
} catch {
|
|
@@ -10446,13 +10698,38 @@ var createContextHandlers = ({
|
|
|
10446
10698
|
return null;
|
|
10447
10699
|
}
|
|
10448
10700
|
};
|
|
10701
|
+
const ensureExecutionEnvironmentContext = async () => {
|
|
10702
|
+
if (state.executionEnvironmentContext) {
|
|
10703
|
+
return state.executionEnvironmentContext;
|
|
10704
|
+
}
|
|
10705
|
+
const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
|
|
10706
|
+
const sandboxRoot = state.runtimeSandboxRoot ?? workingDir;
|
|
10707
|
+
try {
|
|
10708
|
+
const context = await buildExecutionEnvironmentContext({
|
|
10709
|
+
workingDir,
|
|
10710
|
+
sandboxRoot,
|
|
10711
|
+
config: await resolveExecutionEnvironmentConfig(workingDir)
|
|
10712
|
+
});
|
|
10713
|
+
state.executionEnvironmentContext = context;
|
|
10714
|
+
state.runtimeWorkingDir = workingDir;
|
|
10715
|
+
if (!state.runtimeSandboxRoot) {
|
|
10716
|
+
state.runtimeSandboxRoot = sandboxRoot;
|
|
10717
|
+
}
|
|
10718
|
+
return context;
|
|
10719
|
+
} catch (error) {
|
|
10720
|
+
log2(`context.inspect execution environment error: ${String(error)}`);
|
|
10721
|
+
return null;
|
|
10722
|
+
}
|
|
10723
|
+
};
|
|
10449
10724
|
const handleContextInspect = async (id, params) => {
|
|
10450
10725
|
const includeAgents = params?.include_agents ?? true;
|
|
10451
10726
|
const includeSkills = params?.include_skills ?? true;
|
|
10452
10727
|
try {
|
|
10728
|
+
const executionEnvironment = await ensureExecutionEnvironmentContext();
|
|
10453
10729
|
const result = {
|
|
10454
10730
|
runtime_working_dir: state.runtimeWorkingDir ?? void 0,
|
|
10455
10731
|
runtime_sandbox_root: state.runtimeSandboxRoot ?? void 0,
|
|
10732
|
+
execution_environment: executionEnvironment ?? void 0,
|
|
10456
10733
|
ui_context: {
|
|
10457
10734
|
cwd: state.lastUiContext?.cwd,
|
|
10458
10735
|
workspace_root: state.lastUiContext?.workspace_root,
|
|
@@ -10502,7 +10779,7 @@ var createContextHandlers = ({
|
|
|
10502
10779
|
|
|
10503
10780
|
// src/rpc/history.ts
|
|
10504
10781
|
import { createReadStream, promises as fs16 } from "fs";
|
|
10505
|
-
import
|
|
10782
|
+
import path15 from "path";
|
|
10506
10783
|
import { createInterface as createInterface2 } from "readline";
|
|
10507
10784
|
import {
|
|
10508
10785
|
RPC_ERROR_CODE as RPC_ERROR_CODE2
|
|
@@ -10578,7 +10855,7 @@ var collectRunCandidates = async (log2) => {
|
|
|
10578
10855
|
for (const yearEntry of yearEntries) {
|
|
10579
10856
|
if (!yearEntry.isDirectory()) continue;
|
|
10580
10857
|
if (!/^\d{4}$/.test(yearEntry.name)) continue;
|
|
10581
|
-
const yearPath =
|
|
10858
|
+
const yearPath = path15.join(sessionsDir, yearEntry.name);
|
|
10582
10859
|
let monthEntries;
|
|
10583
10860
|
try {
|
|
10584
10861
|
monthEntries = await fs16.readdir(yearPath, {
|
|
@@ -10591,7 +10868,7 @@ var collectRunCandidates = async (log2) => {
|
|
|
10591
10868
|
for (const monthEntry of monthEntries) {
|
|
10592
10869
|
if (!monthEntry.isDirectory()) continue;
|
|
10593
10870
|
if (!/^\d{2}$/.test(monthEntry.name)) continue;
|
|
10594
|
-
const monthPath =
|
|
10871
|
+
const monthPath = path15.join(yearPath, monthEntry.name);
|
|
10595
10872
|
let dayEntries;
|
|
10596
10873
|
try {
|
|
10597
10874
|
dayEntries = await fs16.readdir(monthPath, {
|
|
@@ -10604,7 +10881,7 @@ var collectRunCandidates = async (log2) => {
|
|
|
10604
10881
|
for (const dayEntry of dayEntries) {
|
|
10605
10882
|
if (!dayEntry.isDirectory()) continue;
|
|
10606
10883
|
if (!/^\d{2}$/.test(dayEntry.name)) continue;
|
|
10607
|
-
const dayPath =
|
|
10884
|
+
const dayPath = path15.join(monthPath, dayEntry.name);
|
|
10608
10885
|
let files;
|
|
10609
10886
|
try {
|
|
10610
10887
|
files = await fs16.readdir(dayPath, {
|
|
@@ -10617,7 +10894,7 @@ var collectRunCandidates = async (log2) => {
|
|
|
10617
10894
|
for (const file of files) {
|
|
10618
10895
|
if (!file.isFile()) continue;
|
|
10619
10896
|
if (!file.name.endsWith(".jsonl")) continue;
|
|
10620
|
-
const filePath =
|
|
10897
|
+
const filePath = path15.join(dayPath, file.name);
|
|
10621
10898
|
try {
|
|
10622
10899
|
const stat = await fs16.stat(filePath);
|
|
10623
10900
|
candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
|
|
@@ -10645,7 +10922,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
|
|
|
10645
10922
|
const header = parseRunHeader(headerLine);
|
|
10646
10923
|
if (!header) continue;
|
|
10647
10924
|
if (header.session_id !== sessionId) continue;
|
|
10648
|
-
const runId = header.run_id ??
|
|
10925
|
+
const runId = header.run_id ?? path15.basename(candidate.path, ".jsonl");
|
|
10649
10926
|
const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
|
|
10650
10927
|
runs.push({
|
|
10651
10928
|
path: candidate.path,
|
|
@@ -12163,7 +12440,7 @@ var createRunHandlers = ({
|
|
|
12163
12440
|
};
|
|
12164
12441
|
|
|
12165
12442
|
// src/rpc/shell.ts
|
|
12166
|
-
import
|
|
12443
|
+
import path16 from "path";
|
|
12167
12444
|
import {
|
|
12168
12445
|
RPC_ERROR_CODE as RPC_ERROR_CODE5
|
|
12169
12446
|
} from "@codelia/protocol";
|
|
@@ -12182,14 +12459,14 @@ var truncateCommandPreview = (value) => {
|
|
|
12182
12459
|
return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
|
|
12183
12460
|
};
|
|
12184
12461
|
var isWithin2 = (basePath, candidatePath) => {
|
|
12185
|
-
const relative =
|
|
12186
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
12462
|
+
const relative = path16.relative(basePath, candidatePath);
|
|
12463
|
+
return relative === "" || !relative.startsWith("..") && !path16.isAbsolute(relative);
|
|
12187
12464
|
};
|
|
12188
12465
|
var resolveShellCwd = (state, requestedCwd) => {
|
|
12189
12466
|
const workingDir = state.runtimeWorkingDir ?? process.cwd();
|
|
12190
12467
|
const rootDir = state.runtimeSandboxRoot ?? workingDir;
|
|
12191
12468
|
if (!requestedCwd) return workingDir;
|
|
12192
|
-
const resolved =
|
|
12469
|
+
const resolved = path16.resolve(workingDir, requestedCwd);
|
|
12193
12470
|
if (!isWithin2(rootDir, resolved)) {
|
|
12194
12471
|
return null;
|
|
12195
12472
|
}
|
|
@@ -12774,7 +13051,7 @@ var createShellHandlers = ({
|
|
|
12774
13051
|
};
|
|
12775
13052
|
|
|
12776
13053
|
// src/rpc/skills.ts
|
|
12777
|
-
import
|
|
13054
|
+
import path17 from "path";
|
|
12778
13055
|
import {
|
|
12779
13056
|
RPC_ERROR_CODE as RPC_ERROR_CODE6
|
|
12780
13057
|
} from "@codelia/protocol";
|
|
@@ -12783,7 +13060,7 @@ var createSkillsHandlers = ({
|
|
|
12783
13060
|
log: log2
|
|
12784
13061
|
}) => {
|
|
12785
13062
|
const handleSkillsList = async (id, params) => {
|
|
12786
|
-
const requestedCwd = params?.cwd ?
|
|
13063
|
+
const requestedCwd = params?.cwd ? path17.resolve(params.cwd) : void 0;
|
|
12787
13064
|
const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
|
|
12788
13065
|
const forceReload = params?.force_reload ?? false;
|
|
12789
13066
|
if (!forceReload) {
|
|
@@ -12838,7 +13115,7 @@ var createSkillsHandlers = ({
|
|
|
12838
13115
|
};
|
|
12839
13116
|
|
|
12840
13117
|
// src/rpc/task.ts
|
|
12841
|
-
import
|
|
13118
|
+
import path18 from "path";
|
|
12842
13119
|
import {
|
|
12843
13120
|
RPC_ERROR_CODE as RPC_ERROR_CODE7
|
|
12844
13121
|
} from "@codelia/protocol";
|
|
@@ -12875,14 +13152,14 @@ var getPublicTaskKey = (task) => {
|
|
|
12875
13152
|
return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
|
|
12876
13153
|
};
|
|
12877
13154
|
var isWithin3 = (basePath, candidatePath) => {
|
|
12878
|
-
const relative =
|
|
12879
|
-
return relative === "" || !relative.startsWith("..") && !
|
|
13155
|
+
const relative = path18.relative(basePath, candidatePath);
|
|
13156
|
+
return relative === "" || !relative.startsWith("..") && !path18.isAbsolute(relative);
|
|
12880
13157
|
};
|
|
12881
13158
|
var resolveShellCwd2 = (state, requestedCwd) => {
|
|
12882
13159
|
const workingDir = state.runtimeWorkingDir ?? process.cwd();
|
|
12883
13160
|
const rootDir = state.runtimeSandboxRoot ?? workingDir;
|
|
12884
13161
|
if (!requestedCwd) return workingDir;
|
|
12885
|
-
const resolved =
|
|
13162
|
+
const resolved = path18.resolve(workingDir, requestedCwd);
|
|
12886
13163
|
if (!isWithin3(rootDir, resolved)) {
|
|
12887
13164
|
return null;
|
|
12888
13165
|
}
|
|
@@ -13717,6 +13994,8 @@ var RuntimeState = class {
|
|
|
13717
13994
|
lastClientInfo = null;
|
|
13718
13995
|
uiCapabilities = null;
|
|
13719
13996
|
systemPrompt = null;
|
|
13997
|
+
executionEnvironmentContext = null;
|
|
13998
|
+
executionEnvironmentDebugLogged = false;
|
|
13720
13999
|
toolDefinitions = null;
|
|
13721
14000
|
tools = null;
|
|
13722
14001
|
sessionId = null;
|
|
@@ -13832,7 +14111,7 @@ var startRuntime = () => {
|
|
|
13832
14111
|
void (async () => {
|
|
13833
14112
|
const state = new RuntimeState();
|
|
13834
14113
|
state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
|
|
13835
|
-
const workingDir = process.env.CODELIA_SANDBOX_ROOT ?
|
|
14114
|
+
const workingDir = process.env.CODELIA_SANDBOX_ROOT ? path19.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
|
|
13836
14115
|
state.runtimeWorkingDir = workingDir;
|
|
13837
14116
|
state.runtimeSandboxRoot = workingDir;
|
|
13838
14117
|
const sessionStateStore = new SessionStateStoreImpl2({
|