@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.
Files changed (3) hide show
  1. package/dist/index.cjs +768 -489
  2. package/dist/index.js +768 -489
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/runtime.ts
26
- var import_node_path18 = __toESM(require("path"), 1);
26
+ var import_node_path19 = __toESM(require("path"), 1);
27
27
  var import_storage14 = require("@codelia/storage");
28
28
 
29
29
  // src/agent-factory.ts
@@ -762,6 +762,10 @@ var DEFAULT_SEARCH_MODE = "auto";
762
762
  var DEFAULT_SEARCH_NATIVE_PROVIDERS = ["openai", "anthropic"];
763
763
  var DEFAULT_SEARCH_LOCAL_BACKEND = "ddg";
764
764
  var DEFAULT_SEARCH_BRAVE_API_KEY_ENV = "BRAVE_SEARCH_API_KEY";
765
+ var DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_TIMEOUT_MS = 1e4;
766
+ var DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_COMMANDS = [
767
+ ["rg", "--version"]
768
+ ];
765
769
  var readEnvValue = (key) => {
766
770
  const value = process.env[key];
767
771
  if (!value) return void 0;
@@ -860,6 +864,39 @@ var resolveSkillsConfig = async (workingDir) => {
860
864
  const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
861
865
  return normalizeSkillsConfig(effective.skills);
862
866
  };
867
+ var normalizeExecutionEnvironmentConfig = (value) => {
868
+ const startupChecks = value?.startup_checks;
869
+ const enabled = startupChecks?.enabled !== false;
870
+ const timeoutMs = resolveSkillsLimit(
871
+ startupChecks?.timeout_ms,
872
+ DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_TIMEOUT_MS
873
+ );
874
+ const mode = startupChecks?.mode === "replace" ? "replace" : "append";
875
+ const configuredCommands = (startupChecks?.commands ?? []).map(
876
+ (command) => command.map((part) => part.trim()).filter((part) => part.length > 0)
877
+ ).filter((command) => command.length > 0);
878
+ const baseCommands = mode === "replace" ? configuredCommands : [
879
+ ...DEFAULT_EXECUTION_ENVIRONMENT_STARTUP_CHECK_COMMANDS.map(
880
+ (command) => [...command]
881
+ ),
882
+ ...configuredCommands
883
+ ];
884
+ const commands = Array.from(
885
+ new Map(baseCommands.map((command) => [command.join("\0"), command])).values()
886
+ );
887
+ return {
888
+ startupChecks: {
889
+ enabled,
890
+ commands,
891
+ timeoutMs
892
+ }
893
+ };
894
+ };
895
+ var resolveExecutionEnvironmentConfig = async (workingDir) => {
896
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
897
+ const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
898
+ return normalizeExecutionEnvironmentConfig(effective.execution_environment);
899
+ };
863
900
  var normalizeSearchConfig = (value) => {
864
901
  const mode = value?.mode === "auto" || value?.mode === "native" || value?.mode === "local" ? value.mode : DEFAULT_SEARCH_MODE;
865
902
  const providersRaw = value?.native?.providers ?? [
@@ -1636,6 +1673,496 @@ var AuthResolver = class _AuthResolver {
1636
1673
  }
1637
1674
  };
1638
1675
 
1676
+ // src/execution-environment.ts
1677
+ var import_node_os = __toESM(require("os"), 1);
1678
+ var import_node_path3 = __toESM(require("path"), 1);
1679
+
1680
+ // src/tasks/shell-executor.ts
1681
+ var import_node_child_process3 = require("child_process");
1682
+
1683
+ // src/tools/bash-utils.ts
1684
+ var import_node_child_process2 = require("child_process");
1685
+ var DEBUG_MAX_COMMAND_CHARS = 200;
1686
+ var DEFAULT_TIMEOUT_SECONDS = 120;
1687
+ var MAX_TIMEOUT_SECONDS = 300;
1688
+ var MAX_TIMER_DELAY_MS = 2147483647;
1689
+ var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
1690
+ MAX_TIMER_DELAY_MS / 1e3
1691
+ );
1692
+ var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
1693
+ var summarizeCommand = (command) => {
1694
+ const normalized = command.trim().replace(/\s+/g, " ");
1695
+ if (normalized.length <= DEBUG_MAX_COMMAND_CHARS) {
1696
+ return normalized;
1697
+ }
1698
+ return `${normalized.slice(0, DEBUG_MAX_COMMAND_CHARS)}...[truncated]`;
1699
+ };
1700
+
1701
+ // src/tasks/shell-executor.ts
1702
+ var DEFAULT_EXCERPT_LINES = 80;
1703
+ var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
1704
+ var FORCE_KILL_DELAY_MS = 2e3;
1705
+ var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
1706
+ var truncateUtf8Prefix = (value, maxBytes) => {
1707
+ if (maxBytes <= 0 || value.length === 0) return "";
1708
+ let bytes = 0;
1709
+ let out = "";
1710
+ for (const ch of value) {
1711
+ const next = utf8ByteLength(ch);
1712
+ if (bytes + next > maxBytes) break;
1713
+ out += ch;
1714
+ bytes += next;
1715
+ }
1716
+ return out;
1717
+ };
1718
+ var truncateUtf8Suffix = (value, maxBytes) => {
1719
+ if (maxBytes <= 0 || value.length === 0) return "";
1720
+ let bytes = 0;
1721
+ const chars = Array.from(value);
1722
+ const out = [];
1723
+ for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
1724
+ const ch = chars[idx];
1725
+ const next = utf8ByteLength(ch);
1726
+ if (bytes + next > maxBytes) break;
1727
+ out.push(ch);
1728
+ bytes += next;
1729
+ }
1730
+ out.reverse();
1731
+ return out.join("");
1732
+ };
1733
+ var excerptByLines = (value) => {
1734
+ const lines = value.split(/\r?\n/);
1735
+ if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
1736
+ const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
1737
+ const tail = lines.slice(lines.length - DEFAULT_EXCERPT_LINES);
1738
+ const omitted = lines.length - head.length - tail.length;
1739
+ return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
1740
+ };
1741
+ var excerptByBytes = (value, maxBytes) => {
1742
+ if (utf8ByteLength(value) <= maxBytes) return value;
1743
+ const marker = "\n...[truncated by size]...\n";
1744
+ const markerBytes = utf8ByteLength(marker);
1745
+ if (maxBytes <= markerBytes + 2) {
1746
+ return truncateUtf8Prefix(value, maxBytes);
1747
+ }
1748
+ const budget = maxBytes - markerBytes;
1749
+ const headBytes = Math.floor(budget / 2);
1750
+ const tailBytes = budget - headBytes;
1751
+ return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
1752
+ };
1753
+ var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
1754
+ var excerptText = (value) => excerptByBytes(excerptByLines(value), MAX_INLINE_OUTPUT_BYTES);
1755
+ var buildShellTaskResultBase = (options) => {
1756
+ const stdoutTruncated = needsInlineTruncation(options.rawStdout);
1757
+ const stderrTruncated = needsInlineTruncation(options.rawStderr);
1758
+ return {
1759
+ stdout: stdoutTruncated ? excerptText(options.rawStdout) : options.rawStdout,
1760
+ stderr: stderrTruncated ? excerptText(options.rawStderr) : options.rawStderr,
1761
+ exit_code: options.exitCode,
1762
+ signal: options.signal,
1763
+ duration_ms: options.durationMs,
1764
+ truncated: {
1765
+ stdout: stdoutTruncated,
1766
+ stderr: stderrTruncated,
1767
+ combined: stdoutTruncated || stderrTruncated
1768
+ }
1769
+ };
1770
+ };
1771
+ var buildShellTaskResult = async (outputCache, options) => {
1772
+ const base = buildShellTaskResultBase(options);
1773
+ let stdoutCacheId;
1774
+ let stderrCacheId;
1775
+ if (base.truncated?.stdout && options.rawStdout.length > 0) {
1776
+ const saved = await outputCache.save({
1777
+ tool_call_id: `${options.taskId}_stdout`,
1778
+ tool_name: options.toolName,
1779
+ content: options.rawStdout
1780
+ });
1781
+ stdoutCacheId = saved.id;
1782
+ }
1783
+ if (base.truncated?.stderr && options.rawStderr.length > 0) {
1784
+ const saved = await outputCache.save({
1785
+ tool_call_id: `${options.taskId}_stderr`,
1786
+ tool_name: options.toolName,
1787
+ content: options.rawStderr
1788
+ });
1789
+ stderrCacheId = saved.id;
1790
+ }
1791
+ return {
1792
+ ...base,
1793
+ ...stdoutCacheId ? { stdout_cache_id: stdoutCacheId } : {},
1794
+ ...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
1795
+ };
1796
+ };
1797
+ var spawnShellProcess = (command, cwd) => {
1798
+ const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
1799
+ if (shellPath) {
1800
+ return (0, import_node_child_process3.spawn)(shellPath, ["-lc", command], {
1801
+ cwd,
1802
+ stdio: ["ignore", "pipe", "pipe"],
1803
+ detached: true
1804
+ });
1805
+ }
1806
+ return (0, import_node_child_process3.spawn)(command, {
1807
+ cwd,
1808
+ shell: true,
1809
+ stdio: ["ignore", "pipe", "pipe"],
1810
+ detached: process.platform !== "win32"
1811
+ });
1812
+ };
1813
+ var terminateChild = (child, signal) => {
1814
+ if (typeof child.pid === "number" && process.platform !== "win32") {
1815
+ try {
1816
+ process.kill(-child.pid, signal);
1817
+ } catch {
1818
+ }
1819
+ }
1820
+ try {
1821
+ child.kill(signal);
1822
+ } catch {
1823
+ }
1824
+ };
1825
+ var startShellTask = (options) => {
1826
+ const timeoutSeconds = options.timeoutSeconds;
1827
+ if (timeoutSeconds !== void 0 && timeoutSeconds > MAX_EXECUTION_TIMEOUT_SECONDS) {
1828
+ throw new Error(
1829
+ `timeoutSeconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less to fit Node's timer range; omit timeoutSeconds to run without an execution timer.`
1830
+ );
1831
+ }
1832
+ const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
1833
+ const forceKillDelayMs = options.forceKillDelayMs ?? FORCE_KILL_DELAY_MS;
1834
+ const startedAt = Date.now();
1835
+ const child = (options.spawnProcess ?? spawnShellProcess)(
1836
+ options.command,
1837
+ options.cwd
1838
+ );
1839
+ const metadata = typeof child.pid === "number" ? {
1840
+ executor_pid: child.pid,
1841
+ executor_pgid: process.platform === "win32" ? void 0 : child.pid
1842
+ } : {};
1843
+ let stdout = "";
1844
+ let stderr = "";
1845
+ let totalBytes = 0;
1846
+ let settled = false;
1847
+ let cancelRequested = false;
1848
+ let timeoutHandle;
1849
+ let forceKillHandle;
1850
+ const clearForceKillHandle = () => {
1851
+ if (!forceKillHandle) return;
1852
+ clearTimeout(forceKillHandle);
1853
+ forceKillHandle = void 0;
1854
+ };
1855
+ const scheduleForceKill = () => {
1856
+ if (forceKillHandle) return;
1857
+ forceKillHandle = setTimeout(() => {
1858
+ forceKillHandle = void 0;
1859
+ terminateChild(child, "SIGKILL");
1860
+ }, forceKillDelayMs);
1861
+ };
1862
+ const wait = new Promise((resolve) => {
1863
+ const settle = async (outcome) => {
1864
+ if (settled) return;
1865
+ settled = true;
1866
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1867
+ let result;
1868
+ try {
1869
+ result = await buildShellTaskResult(options.outputCache, {
1870
+ taskId: options.taskId,
1871
+ toolName: options.toolName ?? "shell.exec",
1872
+ rawStdout: stdout,
1873
+ rawStderr: stderr,
1874
+ exitCode: outcome.exitCode,
1875
+ signal: outcome.signal,
1876
+ durationMs: Date.now() - startedAt
1877
+ });
1878
+ } catch {
1879
+ result = buildShellTaskResultBase({
1880
+ rawStdout: stdout,
1881
+ rawStderr: stderr,
1882
+ exitCode: outcome.exitCode,
1883
+ signal: outcome.signal,
1884
+ durationMs: Date.now() - startedAt
1885
+ });
1886
+ }
1887
+ resolve({
1888
+ state: outcome.state,
1889
+ result,
1890
+ ...outcome.failureMessage ? { failure_message: outcome.failureMessage } : {},
1891
+ ...outcome.cancellationReason ? { cancellation_reason: outcome.cancellationReason } : {}
1892
+ });
1893
+ };
1894
+ const fail = (message, signal) => {
1895
+ void settle({
1896
+ state: cancelRequested ? "cancelled" : "failed",
1897
+ exitCode: null,
1898
+ signal,
1899
+ failureMessage: cancelRequested ? void 0 : message,
1900
+ cancellationReason: cancelRequested ? "cancelled" : void 0
1901
+ });
1902
+ };
1903
+ const consumeChunk = (chunk, stream) => {
1904
+ if (settled) return;
1905
+ const text = chunk.toString("utf8");
1906
+ totalBytes += Buffer.byteLength(text, "utf8");
1907
+ if (totalBytes > maxOutputBytes) {
1908
+ terminateChild(child, "SIGTERM");
1909
+ scheduleForceKill();
1910
+ fail(
1911
+ `Command output exceeded max buffer of ${maxOutputBytes} bytes`,
1912
+ "SIGTERM"
1913
+ );
1914
+ return;
1915
+ }
1916
+ if (stream === "stdout") stdout += text;
1917
+ else stderr += text;
1918
+ };
1919
+ child.stdout.on("data", (chunk) => consumeChunk(chunk, "stdout"));
1920
+ child.stderr.on("data", (chunk) => consumeChunk(chunk, "stderr"));
1921
+ child.on("error", (error) => {
1922
+ fail(error.message, null);
1923
+ });
1924
+ child.on("close", (code, signal) => {
1925
+ clearForceKillHandle();
1926
+ if (settled) return;
1927
+ if (cancelRequested) {
1928
+ void settle({
1929
+ state: "cancelled",
1930
+ exitCode: code,
1931
+ signal: signal ?? null,
1932
+ cancellationReason: "cancelled"
1933
+ });
1934
+ return;
1935
+ }
1936
+ if (code === 0) {
1937
+ void settle({
1938
+ state: "completed",
1939
+ exitCode: code,
1940
+ signal: signal ?? null
1941
+ });
1942
+ return;
1943
+ }
1944
+ void settle({
1945
+ state: "failed",
1946
+ exitCode: code,
1947
+ signal: signal ?? null,
1948
+ failureMessage: `Command failed with exit code ${code ?? "unknown"}${signal ? ` signal ${signal}` : ""}`
1949
+ });
1950
+ });
1951
+ if (timeoutSeconds !== void 0) {
1952
+ timeoutHandle = setTimeout(() => {
1953
+ cancelRequested = false;
1954
+ terminateChild(child, "SIGTERM");
1955
+ scheduleForceKill();
1956
+ fail(
1957
+ `Command timed out after ${Math.trunc(timeoutSeconds)}s`,
1958
+ "SIGTERM"
1959
+ );
1960
+ }, timeoutSeconds * 1e3);
1961
+ }
1962
+ });
1963
+ return {
1964
+ metadata,
1965
+ wait,
1966
+ readOutput: async (stream) => stream === "stdout" ? stdout : stderr,
1967
+ cancel: async () => {
1968
+ if (settled) return;
1969
+ cancelRequested = true;
1970
+ terminateChild(child, "SIGTERM");
1971
+ scheduleForceKill();
1972
+ }
1973
+ };
1974
+ };
1975
+
1976
+ // src/execution-environment.ts
1977
+ var MAX_CHECK_OUTPUT_CHARS = 160;
1978
+ var MAX_CAPTURE_CHARS = 4096;
1979
+ var FORCE_KILL_DELAY_MS2 = 200;
1980
+ var firstNonEmptyLine = (value) => {
1981
+ for (const rawLine of value.split(/\r?\n/u)) {
1982
+ const line = rawLine.trim();
1983
+ if (line.length > 0) {
1984
+ return line;
1985
+ }
1986
+ }
1987
+ return void 0;
1988
+ };
1989
+ var truncate = (value, maxChars = MAX_CHECK_OUTPUT_CHARS) => {
1990
+ if (value.length <= maxChars) {
1991
+ return value;
1992
+ }
1993
+ return `${value.slice(0, Math.max(1, maxChars - 1))}\u2026`;
1994
+ };
1995
+ var appendCaptured = (current, chunk) => {
1996
+ const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
1997
+ if (current.length >= MAX_CAPTURE_CHARS) {
1998
+ return current;
1999
+ }
2000
+ return `${current}${text}`.slice(0, MAX_CAPTURE_CHARS);
2001
+ };
2002
+ var formatCommandLabel = (command) => JSON.stringify(command.join(" "));
2003
+ var shellQuote = (value) => {
2004
+ if (process.platform === "win32") {
2005
+ if (!value) return '""';
2006
+ return /^[A-Za-z0-9_./:-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
2007
+ }
2008
+ if (!value) return "''";
2009
+ return `'${value.replaceAll("'", "'\\''")}'`;
2010
+ };
2011
+ var buildShellCommand = (command) => command.map((part) => shellQuote(part)).join(" ");
2012
+ var describeExecutionEnvironmentHost = () => {
2013
+ const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
2014
+ const bashSyntaxGuaranteed = shellPath.length > 0 && import_node_path3.default.basename(shellPath).toLowerCase() === "bash";
2015
+ return {
2016
+ osDescription: `${import_node_os.default.type()} ${import_node_os.default.release()} (${process.platform} ${import_node_os.default.arch()})`,
2017
+ shellExecution: shellPath.length > 0 ? `${shellPath} -lc` : "platform shell via spawn(shell=true)",
2018
+ bashSyntaxGuaranteed
2019
+ };
2020
+ };
2021
+ var probeExecutionEnvironmentCommand = (command, timeoutMs, workingDir, probeOptions = {}) => {
2022
+ if (command.length === 0 || command[0].trim().length === 0) {
2023
+ return Promise.resolve("invalid command");
2024
+ }
2025
+ return new Promise((resolve) => {
2026
+ let stdout = "";
2027
+ let stderr = "";
2028
+ let settled = false;
2029
+ let timeoutHandle;
2030
+ let forceKillHandle;
2031
+ const clearForceKillHandle = () => {
2032
+ if (!forceKillHandle) return;
2033
+ clearTimeout(forceKillHandle);
2034
+ forceKillHandle = void 0;
2035
+ };
2036
+ const finish = (summary, options = {}) => {
2037
+ if (settled) return;
2038
+ settled = true;
2039
+ if (timeoutHandle) {
2040
+ clearTimeout(timeoutHandle);
2041
+ }
2042
+ if (!options.keepForceKill) {
2043
+ clearForceKillHandle();
2044
+ }
2045
+ resolve(summary);
2046
+ };
2047
+ let child;
2048
+ try {
2049
+ child = (probeOptions.spawnProcess ?? spawnShellProcess)(
2050
+ buildShellCommand(command),
2051
+ workingDir
2052
+ );
2053
+ } catch (error) {
2054
+ finish(`error: ${error instanceof Error ? error.message : String(error)}`);
2055
+ return;
2056
+ }
2057
+ timeoutHandle = setTimeout(() => {
2058
+ finish(`timeout after ${timeoutMs}ms`, { keepForceKill: true });
2059
+ (probeOptions.terminateProcess ?? terminateChild)(child, "SIGTERM");
2060
+ forceKillHandle = setTimeout(() => {
2061
+ forceKillHandle = void 0;
2062
+ (probeOptions.terminateProcess ?? terminateChild)(child, "SIGKILL");
2063
+ }, probeOptions.forceKillDelayMs ?? FORCE_KILL_DELAY_MS2);
2064
+ }, timeoutMs);
2065
+ child.on("error", (error) => {
2066
+ const errorCode = typeof error.code === "string" ? error.code : void 0;
2067
+ if (errorCode === "ENOENT") {
2068
+ finish("exit 127");
2069
+ return;
2070
+ }
2071
+ finish(
2072
+ `error: ${error instanceof Error ? error.message : String(error)}`
2073
+ );
2074
+ });
2075
+ child.stdout.on("data", (chunk) => {
2076
+ stdout = appendCaptured(stdout, chunk);
2077
+ });
2078
+ child.stderr.on("data", (chunk) => {
2079
+ stderr = appendCaptured(stderr, chunk);
2080
+ });
2081
+ child.on("close", (code, signal) => {
2082
+ clearForceKillHandle();
2083
+ if (settled) {
2084
+ return;
2085
+ }
2086
+ const line = firstNonEmptyLine(stdout) ?? firstNonEmptyLine(stderr);
2087
+ if (code === 0) {
2088
+ finish(line ? truncate(line) : "exit 0");
2089
+ return;
2090
+ }
2091
+ const exitSummary = code === null ? `signal ${signal ?? "unknown"}` : `exit ${code}`;
2092
+ finish(line ? `${truncate(line)} (${exitSummary})` : exitSummary);
2093
+ });
2094
+ });
2095
+ };
2096
+ var collectExecutionEnvironmentStartupChecks = async (options) => {
2097
+ if (!options.config.startupChecks.enabled) {
2098
+ return [];
2099
+ }
2100
+ const probeCommand = options.probeCommand ?? probeExecutionEnvironmentCommand;
2101
+ return Promise.all(
2102
+ options.config.startupChecks.commands.map(async (command) => ({
2103
+ command: [...command],
2104
+ summary: await probeCommand(
2105
+ command,
2106
+ options.config.startupChecks.timeoutMs,
2107
+ options.workingDir,
2108
+ options.probeOptions
2109
+ )
2110
+ }))
2111
+ );
2112
+ };
2113
+ var formatExecutionEnvironmentContext = (options) => {
2114
+ const lines = [
2115
+ "<execution_environment>",
2116
+ `os: ${options.hostInfo.osDescription}`,
2117
+ `shell tool execution environment: ${options.hostInfo.shellExecution}`,
2118
+ `bash syntax guaranteed: ${options.hostInfo.bashSyntaxGuaranteed ? "true" : "false"}`,
2119
+ `sandbox root: ${options.sandboxRoot}`,
2120
+ `working directory: ${options.workingDir}`
2121
+ ];
2122
+ if (options.startupChecks && options.startupChecks.length > 0) {
2123
+ lines.push("", "startup checks:");
2124
+ for (const check of options.startupChecks) {
2125
+ lines.push(
2126
+ `- ${formatCommandLabel(check.command)} => ${check.summary}`
2127
+ );
2128
+ }
2129
+ }
2130
+ lines.push("</execution_environment>");
2131
+ return lines.join("\n");
2132
+ };
2133
+ var buildExecutionEnvironmentContext = async (options) => {
2134
+ const startupChecks = await collectExecutionEnvironmentStartupChecks({
2135
+ config: options.config,
2136
+ workingDir: options.workingDir,
2137
+ probeCommand: options.probeCommand,
2138
+ probeOptions: options.probeOptions
2139
+ });
2140
+ return formatExecutionEnvironmentContext({
2141
+ workingDir: options.workingDir,
2142
+ sandboxRoot: options.sandboxRoot,
2143
+ hostInfo: options.hostInfo ?? describeExecutionEnvironmentHost(),
2144
+ startupChecks
2145
+ });
2146
+ };
2147
+ var appendInitialExecutionEnvironment = (systemPrompt, executionEnvironmentContext) => {
2148
+ if (!executionEnvironmentContext) {
2149
+ return systemPrompt;
2150
+ }
2151
+ return `${systemPrompt}
2152
+
2153
+ ${executionEnvironmentContext}`;
2154
+ };
2155
+ var logInitialExecutionEnvironmentDebug = (executionEnvironmentContext, options = {}) => {
2156
+ if (!executionEnvironmentContext || options.alreadyLogged) {
2157
+ return false;
2158
+ }
2159
+ (options.log ?? import_logger.debugLog)(
2160
+ `startup execution environment context
2161
+ ${executionEnvironmentContext}`
2162
+ );
2163
+ return true;
2164
+ };
2165
+
1639
2166
  // src/mcp/oauth.ts
1640
2167
  var DEFAULT_MCP_OAUTH_PORT = 1456;
1641
2168
  var DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS = 18e4;
@@ -2173,11 +2700,11 @@ var buildModelRegistry = async (llm, options = {}) => {
2173
2700
 
2174
2701
  // src/permissions/approval-mode.ts
2175
2702
  var import_node_fs4 = require("fs");
2176
- var import_node_path3 = __toESM(require("path"), 1);
2703
+ var import_node_path4 = __toESM(require("path"), 1);
2177
2704
  var import_shared_types = require("@codelia/shared-types");
2178
2705
  var import_storage4 = require("@codelia/storage");
2179
2706
  var normalizePath = async (value) => {
2180
- const absolute = import_node_path3.default.resolve(value);
2707
+ const absolute = import_node_path4.default.resolve(value);
2181
2708
  try {
2182
2709
  return await import_node_fs4.promises.realpath(absolute);
2183
2710
  } catch {
@@ -2317,10 +2844,10 @@ var resolveApprovalModeForRuntime = async (options, deps = {}) => {
2317
2844
  };
2318
2845
 
2319
2846
  // src/permissions/service.ts
2320
- var import_node_path5 = __toESM(require("path"), 1);
2847
+ var import_node_path6 = __toESM(require("path"), 1);
2321
2848
 
2322
2849
  // src/permissions/utils.ts
2323
- var import_node_path4 = __toESM(require("path"), 1);
2850
+ var import_node_path5 = __toESM(require("path"), 1);
2324
2851
  var REDIRECT_OPERATORS = /* @__PURE__ */ new Set(["<", ">", ">>", "2>", "2>>"]);
2325
2852
  var SPLIT_OPERATORS = [
2326
2853
  "2>>",
@@ -2612,7 +3139,7 @@ var deriveRememberCommand = (segment) => {
2612
3139
  if (primaryIndex > 0) return null;
2613
3140
  if (primaryIndex >= tokens.length) return null;
2614
3141
  const primaryToken = tokens[primaryIndex];
2615
- const primary = import_node_path4.default.basename(primaryToken);
3142
+ const primary = import_node_path5.default.basename(primaryToken);
2616
3143
  if (!primary || primary === "." || primary === "..") return null;
2617
3144
  if (!COMMAND_TOKEN_PATTERN.test(primary)) return null;
2618
3145
  if (COMMAND_WRAPPER_TOKENS.has(primary)) return null;
@@ -2648,9 +3175,9 @@ var resolveCdTarget = (segment, currentWorkingDir, rootDir) => {
2648
3175
  if (tokens.length !== 2) return null;
2649
3176
  const target = tokens[1];
2650
3177
  if (target === "-" || CD_UNSAFE_TARGET_PATTERN.test(target)) return null;
2651
- const resolved = import_node_path4.default.resolve(currentWorkingDir, target);
2652
- const relative = import_node_path4.default.relative(rootDir, resolved);
2653
- if (relative === "" || !relative.startsWith("..") && !import_node_path4.default.isAbsolute(relative)) {
3178
+ const resolved = import_node_path5.default.resolve(currentWorkingDir, target);
3179
+ const relative = import_node_path5.default.relative(rootDir, resolved);
3180
+ if (relative === "" || !relative.startsWith("..") && !import_node_path5.default.isAbsolute(relative)) {
2654
3181
  return resolved;
2655
3182
  }
2656
3183
  return null;
@@ -2756,8 +3283,8 @@ var PermissionService = class {
2756
3283
  this.approvalMode = options.approvalMode ?? "minimal";
2757
3284
  if (options.bashPathGuard) {
2758
3285
  this.bashPathGuard = {
2759
- rootDir: import_node_path5.default.resolve(options.bashPathGuard.rootDir),
2760
- workingDir: import_node_path5.default.resolve(options.bashPathGuard.workingDir)
3286
+ rootDir: import_node_path6.default.resolve(options.bashPathGuard.rootDir),
3287
+ workingDir: import_node_path6.default.resolve(options.bashPathGuard.workingDir)
2761
3288
  };
2762
3289
  }
2763
3290
  }
@@ -3002,7 +3529,7 @@ ${previewLines.join("\n")}`;
3002
3529
  // src/sandbox/context.ts
3003
3530
  var import_node_crypto = __toESM(require("crypto"), 1);
3004
3531
  var import_node_fs5 = require("fs");
3005
- var import_node_path6 = __toESM(require("path"), 1);
3532
+ var import_node_path7 = __toESM(require("path"), 1);
3006
3533
  var SecurityError = class extends Error {
3007
3534
  constructor(message) {
3008
3535
  super(message);
@@ -3022,7 +3549,7 @@ var SandboxContext = class _SandboxContext {
3022
3549
  }
3023
3550
  static async create(rootDir, options = {}) {
3024
3551
  const sessionId = import_node_crypto.default.randomUUID().slice(0, 8);
3025
- const root = rootDir ? import_node_path6.default.resolve(rootDir) : process.cwd();
3552
+ const root = rootDir ? import_node_path7.default.resolve(rootDir) : process.cwd();
3026
3553
  await import_node_fs5.promises.mkdir(root, { recursive: true });
3027
3554
  return new _SandboxContext({
3028
3555
  rootDir: root,
@@ -3032,12 +3559,12 @@ var SandboxContext = class _SandboxContext {
3032
3559
  });
3033
3560
  }
3034
3561
  resolvePath(targetPath) {
3035
- const resolved = import_node_path6.default.isAbsolute(targetPath) ? import_node_path6.default.resolve(targetPath) : import_node_path6.default.resolve(this.workingDir, targetPath);
3562
+ const resolved = import_node_path7.default.isAbsolute(targetPath) ? import_node_path7.default.resolve(targetPath) : import_node_path7.default.resolve(this.workingDir, targetPath);
3036
3563
  if (this.approvalMode === "full-access") {
3037
3564
  return resolved;
3038
3565
  }
3039
- const relative = import_node_path6.default.relative(this.rootDir, resolved);
3040
- if (relative === "" || !relative.startsWith("..") && !import_node_path6.default.isAbsolute(relative)) {
3566
+ const relative = import_node_path7.default.relative(this.rootDir, resolved);
3567
+ if (relative === "" || !relative.startsWith("..") && !import_node_path7.default.isAbsolute(relative)) {
3041
3568
  return resolved;
3042
3569
  }
3043
3570
  throw new SecurityError(
@@ -3061,8 +3588,8 @@ var getSkillsResolver = async (ctx, key) => ctx.resolve(key);
3061
3588
  // src/skills/resolver.ts
3062
3589
  var import_node_crypto2 = __toESM(require("crypto"), 1);
3063
3590
  var import_node_fs6 = require("fs");
3064
- var import_node_os = __toESM(require("os"), 1);
3065
- var import_node_path7 = __toESM(require("path"), 1);
3591
+ var import_node_os2 = __toESM(require("os"), 1);
3592
+ var import_node_path8 = __toESM(require("path"), 1);
3066
3593
  var DEFAULT_MARKERS2 = [".codelia", ".git", ".jj"];
3067
3594
  var SKILL_NAME_PATTERN2 = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
3068
3595
  var MAX_SKILL_FILES = 200;
@@ -3088,38 +3615,38 @@ var exists2 = async (targetPath) => {
3088
3615
  };
3089
3616
  var normalizeMtime2 = (value) => Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
3090
3617
  var resolvePathChain2 = (rootDir, targetDir) => {
3091
- const normalizedRoot = import_node_path7.default.resolve(rootDir);
3092
- const normalizedTarget = import_node_path7.default.resolve(targetDir);
3093
- const relative = import_node_path7.default.relative(normalizedRoot, normalizedTarget);
3094
- if (relative.startsWith("..") || import_node_path7.default.isAbsolute(relative) || relative === "..") {
3618
+ const normalizedRoot = import_node_path8.default.resolve(rootDir);
3619
+ const normalizedTarget = import_node_path8.default.resolve(targetDir);
3620
+ const relative = import_node_path8.default.relative(normalizedRoot, normalizedTarget);
3621
+ if (relative.startsWith("..") || import_node_path8.default.isAbsolute(relative) || relative === "..") {
3095
3622
  return [];
3096
3623
  }
3097
- const parts = relative.split(import_node_path7.default.sep).filter((part) => part.length > 0);
3624
+ const parts = relative.split(import_node_path8.default.sep).filter((part) => part.length > 0);
3098
3625
  const chain = [normalizedRoot];
3099
3626
  let current = normalizedRoot;
3100
3627
  for (const part of parts) {
3101
- current = import_node_path7.default.join(current, part);
3628
+ current = import_node_path8.default.join(current, part);
3102
3629
  chain.push(current);
3103
3630
  }
3104
3631
  return chain;
3105
3632
  };
3106
3633
  var findRootByMarkers2 = async (workingDir, markers) => {
3107
- let current = import_node_path7.default.resolve(workingDir);
3634
+ let current = import_node_path8.default.resolve(workingDir);
3108
3635
  while (true) {
3109
3636
  for (const marker of markers) {
3110
- if (await exists2(import_node_path7.default.join(current, marker))) {
3637
+ if (await exists2(import_node_path8.default.join(current, marker))) {
3111
3638
  return current;
3112
3639
  }
3113
3640
  }
3114
- const parent = import_node_path7.default.dirname(current);
3641
+ const parent = import_node_path8.default.dirname(current);
3115
3642
  if (parent === current) {
3116
- return import_node_path7.default.resolve(workingDir);
3643
+ return import_node_path8.default.resolve(workingDir);
3117
3644
  }
3118
3645
  current = parent;
3119
3646
  }
3120
3647
  };
3121
3648
  var tryResolvePath = async (targetPath) => {
3122
- const resolved = import_node_path7.default.resolve(targetPath);
3649
+ const resolved = import_node_path8.default.resolve(targetPath);
3123
3650
  try {
3124
3651
  return { resolved, canonical: await import_node_fs6.promises.realpath(resolved) };
3125
3652
  } catch {
@@ -3127,8 +3654,8 @@ var tryResolvePath = async (targetPath) => {
3127
3654
  }
3128
3655
  };
3129
3656
  var isWithin = (basePath, candidatePath) => {
3130
- const relative = import_node_path7.default.relative(basePath, candidatePath);
3131
- return relative === "" || !relative.startsWith("..") && !import_node_path7.default.isAbsolute(relative);
3657
+ const relative = import_node_path8.default.relative(basePath, candidatePath);
3658
+ return relative === "" || !relative.startsWith("..") && !import_node_path8.default.isAbsolute(relative);
3132
3659
  };
3133
3660
  var hashPath = (value) => import_node_crypto2.default.createHash("sha256").update(value).digest("hex").slice(0, 24);
3134
3661
  var parseFrontmatter = (content) => {
@@ -3177,12 +3704,12 @@ var SkillsResolver = class _SkillsResolver {
3177
3704
  }
3178
3705
  static async create(options) {
3179
3706
  const env = options.env ?? process.env;
3180
- const workingDir = import_node_path7.default.resolve(options.workingDir);
3707
+ const workingDir = import_node_path8.default.resolve(options.workingDir);
3181
3708
  const rootOverride = toTrimmed2(env.CODELIA_AGENTS_ROOT);
3182
3709
  const markers = parseMarkers2(env.CODELIA_AGENTS_MARKERS) ?? DEFAULT_MARKERS2;
3183
- const rootDir = rootOverride ? import_node_path7.default.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
3184
- const homeDir = toTrimmed2(env.HOME) ?? import_node_os.default.homedir();
3185
- const userSkillsDir = import_node_path7.default.join(import_node_path7.default.resolve(homeDir), ".agents", "skills");
3710
+ const rootDir = rootOverride ? import_node_path8.default.resolve(rootOverride) : await findRootByMarkers2(workingDir, markers);
3711
+ const homeDir = toTrimmed2(env.HOME) ?? import_node_os2.default.homedir();
3712
+ const userSkillsDir = import_node_path8.default.join(import_node_path8.default.resolve(homeDir), ".agents", "skills");
3186
3713
  const resolver = new _SkillsResolver({
3187
3714
  workingDir,
3188
3715
  rootDir,
@@ -3205,7 +3732,7 @@ var SkillsResolver = class _SkillsResolver {
3205
3732
  return;
3206
3733
  }
3207
3734
  for (const entry of entries) {
3208
- const entryPath = import_node_path7.default.join(dirPath, entry.name);
3735
+ const entryPath = import_node_path8.default.join(dirPath, entry.name);
3209
3736
  if (entry.isDirectory()) {
3210
3737
  await walk(entryPath);
3211
3738
  continue;
@@ -3222,7 +3749,7 @@ var SkillsResolver = class _SkillsResolver {
3222
3749
  const directories = resolvePathChain2(this.rootDir, this.workingDir);
3223
3750
  const skillFiles = [];
3224
3751
  for (const directoryPath of directories) {
3225
- const skillsRoot = import_node_path7.default.join(directoryPath, ".agents", "skills");
3752
+ const skillsRoot = import_node_path8.default.join(directoryPath, ".agents", "skills");
3226
3753
  if (!await exists2(skillsRoot)) continue;
3227
3754
  const files = await this.collectSkillFilesInTree(skillsRoot);
3228
3755
  skillFiles.push(...files);
@@ -3279,8 +3806,8 @@ var SkillsResolver = class _SkillsResolver {
3279
3806
  }
3280
3807
  };
3281
3808
  }
3282
- const dir = import_node_path7.default.dirname(normalized.canonical);
3283
- if (import_node_path7.default.basename(dir) !== name) {
3809
+ const dir = import_node_path8.default.dirname(normalized.canonical);
3810
+ if (import_node_path8.default.basename(dir) !== name) {
3284
3811
  return {
3285
3812
  error: {
3286
3813
  path: normalized.canonical,
@@ -3429,7 +3956,7 @@ var SkillsResolver = class _SkillsResolver {
3429
3956
  }
3430
3957
  const catalog = await this.getCatalog();
3431
3958
  const normalizedQuery = query.toLowerCase();
3432
- const queryPathCandidate = import_node_path7.default.resolve(this.workingDir, query);
3959
+ const queryPathCandidate = import_node_path8.default.resolve(this.workingDir, query);
3433
3960
  const queryTokens = new Set(tokenize(normalizedQuery));
3434
3961
  const scored = [];
3435
3962
  for (const skill of catalog.skills) {
@@ -3487,7 +4014,7 @@ var SkillsResolver = class _SkillsResolver {
3487
4014
  try {
3488
4015
  rootReal = await import_node_fs6.promises.realpath(skillDir);
3489
4016
  } catch {
3490
- rootReal = import_node_path7.default.resolve(skillDir);
4017
+ rootReal = import_node_path8.default.resolve(skillDir);
3491
4018
  }
3492
4019
  const files = [];
3493
4020
  let bytes = 0;
@@ -3505,7 +4032,7 @@ var SkillsResolver = class _SkillsResolver {
3505
4032
  }
3506
4033
  for (const entry of entries) {
3507
4034
  if (truncated) break;
3508
- const entryPath = import_node_path7.default.join(dirPath, entry.name);
4035
+ const entryPath = import_node_path8.default.join(dirPath, entry.name);
3509
4036
  if (entry.isSymbolicLink()) {
3510
4037
  continue;
3511
4038
  }
@@ -3520,7 +4047,7 @@ var SkillsResolver = class _SkillsResolver {
3520
4047
  try {
3521
4048
  realPath = await import_node_fs6.promises.realpath(entryPath);
3522
4049
  } catch {
3523
- realPath = import_node_path7.default.resolve(entryPath);
4050
+ realPath = import_node_path8.default.resolve(entryPath);
3524
4051
  }
3525
4052
  if (!isWithin(rootReal, realPath)) {
3526
4053
  continue;
@@ -3549,7 +4076,7 @@ var SkillsResolver = class _SkillsResolver {
3549
4076
  return { files, truncated };
3550
4077
  }
3551
4078
  async resolveByPath(pathInput) {
3552
- const resolved = import_node_path7.default.isAbsolute(pathInput) ? import_node_path7.default.resolve(pathInput) : import_node_path7.default.resolve(this.workingDir, pathInput);
4079
+ const resolved = import_node_path8.default.isAbsolute(pathInput) ? import_node_path8.default.resolve(pathInput) : import_node_path8.default.resolve(this.workingDir, pathInput);
3553
4080
  const resolvedTry = await tryResolvePath(resolved);
3554
4081
  const byCanonical = this.catalog.skills.find(
3555
4082
  (entry) => entry.path === resolvedTry.canonical
@@ -3619,7 +4146,7 @@ var SkillsResolver = class _SkillsResolver {
3619
4146
  }
3620
4147
  const list = await this.listSkillFiles(selected.dir);
3621
4148
  const filesXml = list.files.map((entry) => `<file>${entry}</file>`).join("\n");
3622
- const trailingSlashDir = selected.dir.endsWith(import_node_path7.default.sep) ? selected.dir : `${selected.dir}${import_node_path7.default.sep}`;
4149
+ const trailingSlashDir = selected.dir.endsWith(import_node_path8.default.sep) ? selected.dir : `${selected.dir}${import_node_path8.default.sep}`;
3623
4150
  const content = [
3624
4151
  `<skill_context name="${xmlEscape(selected.name)}" path="${xmlEscape(selected.path)}">`,
3625
4152
  skillBody.trimEnd(),
@@ -3702,7 +4229,7 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => (0, import_core
3702
4229
 
3703
4230
  // src/tools/apply-patch.ts
3704
4231
  var import_node_fs7 = require("fs");
3705
- var import_node_path8 = __toESM(require("path"), 1);
4232
+ var import_node_path9 = __toESM(require("path"), 1);
3706
4233
  var import_core4 = require("@codelia/core");
3707
4234
  var import_zod3 = require("zod");
3708
4235
 
@@ -3711,27 +4238,27 @@ var DEFAULT_DIFF_PREVIEW_LINES = 120;
3711
4238
  var DEFAULT_DIFF_PREVIEW_BYTES = 16 * 1024;
3712
4239
  var normalizeLineEndings = (text) => text.replace(/\r\n/g, "\n");
3713
4240
  var toLines = (text) => text === "" ? [] : text.split("\n");
3714
- var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
3715
- var truncateUtf8Prefix = (value, maxBytes) => {
4241
+ var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
4242
+ var truncateUtf8Prefix2 = (value, maxBytes) => {
3716
4243
  if (maxBytes <= 0 || value.length === 0) return "";
3717
4244
  let bytes = 0;
3718
4245
  let out = "";
3719
4246
  for (const ch of value) {
3720
- const next = utf8ByteLength(ch);
4247
+ const next = utf8ByteLength2(ch);
3721
4248
  if (bytes + next > maxBytes) break;
3722
4249
  out += ch;
3723
4250
  bytes += next;
3724
4251
  }
3725
4252
  return out;
3726
4253
  };
3727
- var truncateUtf8Suffix = (value, maxBytes) => {
4254
+ var truncateUtf8Suffix2 = (value, maxBytes) => {
3728
4255
  if (maxBytes <= 0 || value.length === 0) return "";
3729
4256
  let bytes = 0;
3730
4257
  const chars = Array.from(value);
3731
4258
  const out = [];
3732
4259
  for (let index = chars.length - 1; index >= 0; index -= 1) {
3733
4260
  const ch = chars[index];
3734
- const next = utf8ByteLength(ch);
4261
+ const next = utf8ByteLength2(ch);
3735
4262
  if (bytes + next > maxBytes) break;
3736
4263
  out.push(ch);
3737
4264
  bytes += next;
@@ -3739,7 +4266,7 @@ var truncateUtf8Suffix = (value, maxBytes) => {
3739
4266
  out.reverse();
3740
4267
  return out.join("");
3741
4268
  };
3742
- var excerptByLines = (value, maxLines) => {
4269
+ var excerptByLines2 = (value, maxLines) => {
3743
4270
  const lines = value.split(/\r?\n/);
3744
4271
  if (lines.length <= maxLines) {
3745
4272
  return { text: value, truncated: false };
@@ -3756,15 +4283,15 @@ var excerptByLines = (value, maxLines) => {
3756
4283
  truncated: true
3757
4284
  };
3758
4285
  };
3759
- var excerptByBytes = (value, maxBytes) => {
3760
- if (utf8ByteLength(value) <= maxBytes) {
4286
+ var excerptByBytes2 = (value, maxBytes) => {
4287
+ if (utf8ByteLength2(value) <= maxBytes) {
3761
4288
  return { text: value, truncated: false };
3762
4289
  }
3763
4290
  const marker = "\n...[truncated by size]...\n";
3764
- const markerBytes = utf8ByteLength(marker);
4291
+ const markerBytes = utf8ByteLength2(marker);
3765
4292
  if (maxBytes <= markerBytes + 2) {
3766
4293
  return {
3767
- text: truncateUtf8Prefix(value, maxBytes),
4294
+ text: truncateUtf8Prefix2(value, maxBytes),
3768
4295
  truncated: true
3769
4296
  };
3770
4297
  }
@@ -3772,16 +4299,16 @@ var excerptByBytes = (value, maxBytes) => {
3772
4299
  const headBytes = Math.floor(budget / 2);
3773
4300
  const tailBytes = budget - headBytes;
3774
4301
  return {
3775
- text: `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`,
4302
+ text: `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`,
3776
4303
  truncated: true
3777
4304
  };
3778
4305
  };
3779
4306
  var summarizeDiff = (diff, options = {}) => {
3780
- const lineExcerpt = excerptByLines(
4307
+ const lineExcerpt = excerptByLines2(
3781
4308
  diff,
3782
4309
  options.maxLines ?? DEFAULT_DIFF_PREVIEW_LINES
3783
4310
  );
3784
- const byteExcerpt = excerptByBytes(
4311
+ const byteExcerpt = excerptByBytes2(
3785
4312
  lineExcerpt.text,
3786
4313
  options.maxBytes ?? DEFAULT_DIFF_PREVIEW_BYTES
3787
4314
  );
@@ -3944,6 +4471,7 @@ var parseAddFileLines = (lines, startIndex, endIndex) => {
3944
4471
  };
3945
4472
  var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
3946
4473
  const chunks = [];
4474
+ let sectionHasModification = false;
3947
4475
  let index = startIndex;
3948
4476
  while (index < endIndex) {
3949
4477
  const line = lines[index] ?? "";
@@ -3997,11 +4525,7 @@ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
3997
4525
  }
3998
4526
  index += 1;
3999
4527
  }
4000
- if (!hasModification) {
4001
- throw new Error(
4002
- `Patch parse failed: chunk must contain at least one '+' or '-' change (line ${index + 1})`
4003
- );
4004
- }
4528
+ sectionHasModification ||= hasModification;
4005
4529
  chunks.push({
4006
4530
  ...changeContext ? { changeContext } : {},
4007
4531
  oldLines,
@@ -4012,6 +4536,11 @@ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
4012
4536
  if (chunks.length === 0 && !options.allowEmpty) {
4013
4537
  throw new Error("Patch parse failed: update file section has no chunks");
4014
4538
  }
4539
+ if (!sectionHasModification && !options.allowEmpty) {
4540
+ throw new Error(
4541
+ "Patch parse failed: update file section must contain at least one '+' or '-' change"
4542
+ );
4543
+ }
4015
4544
  return { chunks, nextIndex: index };
4016
4545
  };
4017
4546
  var parsePatch = (patchText) => {
@@ -4385,7 +4914,7 @@ var applyPreparedChanges = async (changes) => {
4385
4914
  continue;
4386
4915
  }
4387
4916
  if (change.kind === "move" && change.resolvedMoveTo) {
4388
- await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(change.resolvedMoveTo), { recursive: true });
4917
+ await import_node_fs7.promises.mkdir(import_node_path9.default.dirname(change.resolvedMoveTo), { recursive: true });
4389
4918
  await import_node_fs7.promises.writeFile(change.resolvedMoveTo, change.after, "utf8");
4390
4919
  if (typeof change.sourceMode === "number") {
4391
4920
  await import_node_fs7.promises.chmod(change.resolvedMoveTo, change.sourceMode);
@@ -4393,7 +4922,7 @@ var applyPreparedChanges = async (changes) => {
4393
4922
  await import_node_fs7.promises.unlink(change.resolvedPath);
4394
4923
  continue;
4395
4924
  }
4396
- await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(change.resolvedPath), { recursive: true });
4925
+ await import_node_fs7.promises.mkdir(import_node_path9.default.dirname(change.resolvedPath), { recursive: true });
4397
4926
  await import_node_fs7.promises.writeFile(change.resolvedPath, change.after, "utf8");
4398
4927
  }
4399
4928
  };
@@ -4486,7 +5015,7 @@ var createDoneTool = () => (0, import_core5.defineTool)({
4486
5015
  // src/tools/edit.ts
4487
5016
  var import_node_crypto4 = __toESM(require("crypto"), 1);
4488
5017
  var import_node_fs8 = require("fs");
4489
- var import_node_path9 = __toESM(require("path"), 1);
5018
+ var import_node_path10 = __toESM(require("path"), 1);
4490
5019
  var import_core6 = require("@codelia/core");
4491
5020
  var import_zod5 = require("zod");
4492
5021
  var trimLine = (line) => line.replace(/\r$/, "").trim();
@@ -4718,7 +5247,7 @@ var createEditTool = (sandboxKey, outputCacheStore) => (0, import_core6.defineTo
4718
5247
  };
4719
5248
  }
4720
5249
  try {
4721
- await import_node_fs8.promises.mkdir(import_node_path9.default.dirname(resolved), { recursive: true });
5250
+ await import_node_fs8.promises.mkdir(import_node_path10.default.dirname(resolved), { recursive: true });
4722
5251
  await import_node_fs8.promises.writeFile(resolved, nextContent, "utf8");
4723
5252
  } catch (error) {
4724
5253
  throw new Error(`Error editing file: ${String(error)}`);
@@ -4740,21 +5269,21 @@ var import_zod6 = require("zod");
4740
5269
  // src/lanes/manager.ts
4741
5270
  var import_node_crypto5 = __toESM(require("crypto"), 1);
4742
5271
  var import_node_fs10 = require("fs");
4743
- var import_node_os2 = __toESM(require("os"), 1);
4744
- var import_node_path11 = __toESM(require("path"), 1);
5272
+ var import_node_os3 = __toESM(require("os"), 1);
5273
+ var import_node_path12 = __toESM(require("path"), 1);
4745
5274
 
4746
5275
  // src/lanes/command.ts
4747
- var import_node_child_process2 = require("child_process");
5276
+ var import_node_child_process4 = require("child_process");
4748
5277
  var DEFAULT_TIMEOUT_MS2 = 3e4;
4749
5278
  var MAX_CAPTURE_BYTES = 512 * 1024;
4750
- var truncate = (value) => {
5279
+ var truncate2 = (value) => {
4751
5280
  if (value.length <= 8e3) return value;
4752
5281
  return `${value.slice(0, 8e3)}...[truncated]`;
4753
5282
  };
4754
5283
  var runCommand = async (command, args, options = {}) => {
4755
5284
  const timeoutMs = Math.max(1e3, options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
4756
5285
  return new Promise((resolve, reject) => {
4757
- const child = (0, import_node_child_process2.spawn)(command, args, {
5286
+ const child = (0, import_node_child_process4.spawn)(command, args, {
4758
5287
  cwd: options.cwd,
4759
5288
  stdio: ["ignore", "pipe", "pipe"]
4760
5289
  });
@@ -4803,7 +5332,7 @@ var runCommand = async (command, args, options = {}) => {
4803
5332
  }
4804
5333
  const detail = `${stderr}
4805
5334
  ${stdout}`.trim();
4806
- const message = detail ? `${command} ${args.join(" ")} failed (exit ${String(code)}): ${truncate(detail)}` : `${command} ${args.join(" ")} failed (exit ${String(code)})`;
5335
+ const message = detail ? `${command} ${args.join(" ")} failed (exit ${String(code)}): ${truncate2(detail)}` : `${command} ${args.join(" ")} failed (exit ${String(code)})`;
4807
5336
  finish(() => reject(new Error(message)));
4808
5337
  });
4809
5338
  const timer = setTimeout(() => {
@@ -4824,7 +5353,7 @@ ${stdout}`.trim();
4824
5353
 
4825
5354
  // src/lanes/registry.ts
4826
5355
  var import_node_fs9 = require("fs");
4827
- var import_node_path10 = __toESM(require("path"), 1);
5356
+ var import_node_path11 = __toESM(require("path"), 1);
4828
5357
  var import_storage5 = require("@codelia/storage");
4829
5358
  var REGISTRY_DIRNAME = "lanes";
4830
5359
  var REGISTRY_FILENAME = "registry.json";
@@ -4846,9 +5375,9 @@ var readJsonFile = async (filePath) => {
4846
5375
  }
4847
5376
  };
4848
5377
  var atomicWrite = async (filePath, payload) => {
4849
- const dir = import_node_path10.default.dirname(filePath);
4850
- const base = import_node_path10.default.basename(filePath);
4851
- const tmp = import_node_path10.default.join(
5378
+ const dir = import_node_path11.default.dirname(filePath);
5379
+ const base = import_node_path11.default.basename(filePath);
5380
+ const tmp = import_node_path11.default.join(
4852
5381
  dir,
4853
5382
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
4854
5383
  );
@@ -4863,10 +5392,10 @@ var LaneRegistryStore = class {
4863
5392
  return;
4864
5393
  }
4865
5394
  const root = (0, import_storage5.resolveStoragePaths)().root;
4866
- this.registryPath = import_node_path10.default.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
5395
+ this.registryPath = import_node_path11.default.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4867
5396
  }
4868
5397
  async ensureDir() {
4869
- await import_node_fs9.promises.mkdir(import_node_path10.default.dirname(this.registryPath), { recursive: true });
5398
+ await import_node_fs9.promises.mkdir(import_node_path11.default.dirname(this.registryPath), { recursive: true });
4870
5399
  }
4871
5400
  async readAll() {
4872
5401
  await this.ensureDir();
@@ -4966,7 +5495,7 @@ var LaneManager = class {
4966
5495
  this.now = options.now ?? nowIso2;
4967
5496
  this.randomId = options.randomId ?? (() => import_node_crypto5.default.randomUUID());
4968
5497
  this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
4969
- this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? import_node_path11.default.join(import_node_os2.default.homedir(), ".codelia", "worktrees");
5498
+ this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? import_node_path12.default.join(import_node_os3.default.homedir(), ".codelia", "worktrees");
4970
5499
  }
4971
5500
  async cmd(command, args, options) {
4972
5501
  (0, import_logger.debugLog)(`lane.cmd ${command} ${args.join(" ")}`);
@@ -5089,9 +5618,9 @@ var LaneManager = class {
5089
5618
  "rev-parse",
5090
5619
  "--git-common-dir"
5091
5620
  ]);
5092
- const commonDir = import_node_path11.default.resolve(worktreePath, stdout.trim());
5093
- if (import_node_path11.default.basename(commonDir) === ".git") {
5094
- return import_node_path11.default.dirname(commonDir);
5621
+ const commonDir = import_node_path12.default.resolve(worktreePath, stdout.trim());
5622
+ if (import_node_path12.default.basename(commonDir) === ".git") {
5623
+ return import_node_path12.default.dirname(commonDir);
5095
5624
  }
5096
5625
  return await this.resolveRepoRoot(worktreePath);
5097
5626
  }
@@ -5136,7 +5665,7 @@ var LaneManager = class {
5136
5665
  const slug = toSlug(taskId);
5137
5666
  const shortId = laneId.slice(0, 8);
5138
5667
  const branchName = `lane/${slug}-${shortId}`;
5139
- const worktreePath = input.worktree_path ? import_node_path11.default.resolve(options.workingDir, input.worktree_path) : import_node_path11.default.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
5668
+ const worktreePath = input.worktree_path ? import_node_path12.default.resolve(options.workingDir, input.worktree_path) : import_node_path12.default.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
5140
5669
  const muxTarget = `codelia-lane-${shortId}`;
5141
5670
  const createdAt = this.now();
5142
5671
  const record = {
@@ -5154,7 +5683,7 @@ var LaneManager = class {
5154
5683
  };
5155
5684
  await this.registry.upsert(record);
5156
5685
  try {
5157
- await import_node_fs10.promises.mkdir(import_node_path11.default.dirname(worktreePath), { recursive: true });
5686
+ await import_node_fs10.promises.mkdir(import_node_path12.default.dirname(worktreePath), { recursive: true });
5158
5687
  await this.cmd("git", [
5159
5688
  "-C",
5160
5689
  repoRoot,
@@ -6254,391 +6783,95 @@ var TaskManager = class {
6254
6783
  }
6255
6784
  const intervalMs = options.pollIntervalMs ?? this.pollIntervalMs;
6256
6785
  while (true) {
6257
- const task = await this.requireTask(taskId);
6258
- if (isTerminalTaskState(task.state)) {
6259
- return task;
6260
- }
6261
- await withAbort(this.sleep(intervalMs), options.signal);
6262
- }
6263
- }
6264
- async cancel(taskId, options = {}) {
6265
- const reason = options.reason ?? "cancelled";
6266
- const task = await this.requireTask(taskId);
6267
- if (isTerminalTaskState(task.state)) {
6268
- return task;
6269
- }
6270
- const active = this.activeTasks.get(taskId);
6271
- if (active?.handle.cancel) {
6272
- await active.handle.cancel(reason);
6273
- return this.wait(taskId);
6274
- }
6275
- return this.cancelWithoutLocalHandle(task, reason);
6276
- }
6277
- async recoverOrphanedTasks() {
6278
- const tasks = await this.registry.list();
6279
- let recovered = 0;
6280
- const errors = [];
6281
- for (const task of tasks) {
6282
- if (isTerminalTaskState(task.state)) {
6283
- continue;
6284
- }
6285
- const ownerAlive = await this.processController.isProcessAlive(
6286
- task.owner_pid
6287
- );
6288
- if (ownerAlive) {
6289
- continue;
6290
- }
6291
- try {
6292
- await this.terminatePersistedTask(task, "SIGTERM");
6293
- await this.forceTerminateIfStillAlive(task);
6294
- await this.finalizeTask(task.task_id, {
6295
- state: "cancelled",
6296
- cancellation_reason: OWNER_EXIT_REASON,
6297
- cleanup_reason: OWNER_EXIT_REASON
6298
- });
6299
- recovered += 1;
6300
- } catch (error) {
6301
- errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
6302
- }
6303
- }
6304
- return { recovered, errors };
6305
- }
6306
- async shutdown() {
6307
- this.shuttingDown = true;
6308
- const tasks = (await this.registry.list()).filter(
6309
- (task) => task.owner_runtime_id === this.runtimeId && !isTerminalTaskState(task.state)
6310
- );
6311
- let cancelled = 0;
6312
- const errors = [];
6313
- for (const task of tasks) {
6314
- try {
6315
- const result = await Promise.race([
6316
- this.cancel(task.task_id, { reason: OWNER_SHUTDOWN_REASON }).then(
6317
- (record) => ({ timedOut: false, record })
6318
- ),
6319
- this.sleep(this.gracePeriodMs).then(() => ({
6320
- timedOut: true,
6321
- record: null
6322
- }))
6323
- ]);
6324
- if (result.timedOut) {
6325
- const refreshed = await this.requireTask(task.task_id);
6326
- if (!isTerminalTaskState(refreshed.state)) {
6327
- await this.terminatePersistedTask(refreshed, "SIGKILL");
6328
- await this.finalizeTask(task.task_id, {
6329
- state: "cancelled",
6330
- cancellation_reason: OWNER_SHUTDOWN_REASON,
6331
- cleanup_reason: OWNER_SHUTDOWN_REASON
6332
- });
6333
- }
6334
- cancelled += 1;
6335
- continue;
6336
- }
6337
- if (result.record.state === "cancelled") {
6338
- cancelled += 1;
6339
- }
6340
- } catch (error) {
6341
- errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
6342
- }
6343
- }
6344
- return { cancelled, errors };
6345
- }
6346
- };
6347
-
6348
- // src/tasks/shell-executor.ts
6349
- var import_node_child_process4 = require("child_process");
6350
-
6351
- // src/tools/bash-utils.ts
6352
- var import_node_child_process3 = require("child_process");
6353
- var DEBUG_MAX_COMMAND_CHARS = 200;
6354
- var DEFAULT_TIMEOUT_SECONDS = 120;
6355
- var MAX_TIMEOUT_SECONDS = 300;
6356
- var MAX_TIMER_DELAY_MS = 2147483647;
6357
- var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
6358
- MAX_TIMER_DELAY_MS / 1e3
6359
- );
6360
- var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
6361
- var summarizeCommand = (command) => {
6362
- const normalized = command.trim().replace(/\s+/g, " ");
6363
- if (normalized.length <= DEBUG_MAX_COMMAND_CHARS) {
6364
- return normalized;
6365
- }
6366
- return `${normalized.slice(0, DEBUG_MAX_COMMAND_CHARS)}...[truncated]`;
6367
- };
6368
-
6369
- // src/tasks/shell-executor.ts
6370
- var DEFAULT_EXCERPT_LINES = 80;
6371
- var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
6372
- var FORCE_KILL_DELAY_MS = 2e3;
6373
- var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
6374
- var truncateUtf8Prefix2 = (value, maxBytes) => {
6375
- if (maxBytes <= 0 || value.length === 0) return "";
6376
- let bytes = 0;
6377
- let out = "";
6378
- for (const ch of value) {
6379
- const next = utf8ByteLength2(ch);
6380
- if (bytes + next > maxBytes) break;
6381
- out += ch;
6382
- bytes += next;
6383
- }
6384
- return out;
6385
- };
6386
- var truncateUtf8Suffix2 = (value, maxBytes) => {
6387
- if (maxBytes <= 0 || value.length === 0) return "";
6388
- let bytes = 0;
6389
- const chars = Array.from(value);
6390
- const out = [];
6391
- for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
6392
- const ch = chars[idx];
6393
- const next = utf8ByteLength2(ch);
6394
- if (bytes + next > maxBytes) break;
6395
- out.push(ch);
6396
- bytes += next;
6397
- }
6398
- out.reverse();
6399
- return out.join("");
6400
- };
6401
- var excerptByLines2 = (value) => {
6402
- const lines = value.split(/\r?\n/);
6403
- if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
6404
- const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
6405
- const tail = lines.slice(lines.length - DEFAULT_EXCERPT_LINES);
6406
- const omitted = lines.length - head.length - tail.length;
6407
- return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
6408
- };
6409
- var excerptByBytes2 = (value, maxBytes) => {
6410
- if (utf8ByteLength2(value) <= maxBytes) return value;
6411
- const marker = "\n...[truncated by size]...\n";
6412
- const markerBytes = utf8ByteLength2(marker);
6413
- if (maxBytes <= markerBytes + 2) {
6414
- return truncateUtf8Prefix2(value, maxBytes);
6415
- }
6416
- const budget = maxBytes - markerBytes;
6417
- const headBytes = Math.floor(budget / 2);
6418
- const tailBytes = budget - headBytes;
6419
- return `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`;
6420
- };
6421
- var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength2(value) > MAX_INLINE_OUTPUT_BYTES;
6422
- var excerptText = (value) => excerptByBytes2(excerptByLines2(value), MAX_INLINE_OUTPUT_BYTES);
6423
- var buildShellTaskResultBase = (options) => {
6424
- const stdoutTruncated = needsInlineTruncation(options.rawStdout);
6425
- const stderrTruncated = needsInlineTruncation(options.rawStderr);
6426
- return {
6427
- stdout: stdoutTruncated ? excerptText(options.rawStdout) : options.rawStdout,
6428
- stderr: stderrTruncated ? excerptText(options.rawStderr) : options.rawStderr,
6429
- exit_code: options.exitCode,
6430
- signal: options.signal,
6431
- duration_ms: options.durationMs,
6432
- truncated: {
6433
- stdout: stdoutTruncated,
6434
- stderr: stderrTruncated,
6435
- combined: stdoutTruncated || stderrTruncated
6436
- }
6437
- };
6438
- };
6439
- var buildShellTaskResult = async (outputCache, options) => {
6440
- const base = buildShellTaskResultBase(options);
6441
- let stdoutCacheId;
6442
- let stderrCacheId;
6443
- if (base.truncated?.stdout && options.rawStdout.length > 0) {
6444
- const saved = await outputCache.save({
6445
- tool_call_id: `${options.taskId}_stdout`,
6446
- tool_name: options.toolName,
6447
- content: options.rawStdout
6448
- });
6449
- stdoutCacheId = saved.id;
6450
- }
6451
- if (base.truncated?.stderr && options.rawStderr.length > 0) {
6452
- const saved = await outputCache.save({
6453
- tool_call_id: `${options.taskId}_stderr`,
6454
- tool_name: options.toolName,
6455
- content: options.rawStderr
6456
- });
6457
- stderrCacheId = saved.id;
6458
- }
6459
- return {
6460
- ...base,
6461
- ...stdoutCacheId ? { stdout_cache_id: stdoutCacheId } : {},
6462
- ...stderrCacheId ? { stderr_cache_id: stderrCacheId } : {}
6463
- };
6464
- };
6465
- var spawnShellProcess = (command, cwd) => {
6466
- const shellPath = process.platform === "win32" ? "" : process.env.SHELL?.trim() || "";
6467
- if (shellPath) {
6468
- return (0, import_node_child_process4.spawn)(shellPath, ["-lc", command], {
6469
- cwd,
6470
- stdio: ["ignore", "pipe", "pipe"],
6471
- detached: true
6472
- });
6473
- }
6474
- return (0, import_node_child_process4.spawn)(command, {
6475
- cwd,
6476
- shell: true,
6477
- stdio: ["ignore", "pipe", "pipe"],
6478
- detached: process.platform !== "win32"
6479
- });
6480
- };
6481
- var terminateChild = (child, signal) => {
6482
- if (typeof child.pid === "number" && process.platform !== "win32") {
6483
- try {
6484
- process.kill(-child.pid, signal);
6485
- } catch {
6786
+ const task = await this.requireTask(taskId);
6787
+ if (isTerminalTaskState(task.state)) {
6788
+ return task;
6789
+ }
6790
+ await withAbort(this.sleep(intervalMs), options.signal);
6486
6791
  }
6487
6792
  }
6488
- try {
6489
- child.kill(signal);
6490
- } catch {
6491
- }
6492
- };
6493
- var startShellTask = (options) => {
6494
- const timeoutSeconds = options.timeoutSeconds;
6495
- if (timeoutSeconds !== void 0 && timeoutSeconds > MAX_EXECUTION_TIMEOUT_SECONDS) {
6496
- throw new Error(
6497
- `timeoutSeconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less to fit Node's timer range; omit timeoutSeconds to run without an execution timer.`
6498
- );
6793
+ async cancel(taskId, options = {}) {
6794
+ const reason = options.reason ?? "cancelled";
6795
+ const task = await this.requireTask(taskId);
6796
+ if (isTerminalTaskState(task.state)) {
6797
+ return task;
6798
+ }
6799
+ const active = this.activeTasks.get(taskId);
6800
+ if (active?.handle.cancel) {
6801
+ await active.handle.cancel(reason);
6802
+ return this.wait(taskId);
6803
+ }
6804
+ return this.cancelWithoutLocalHandle(task, reason);
6499
6805
  }
6500
- const maxOutputBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;
6501
- const forceKillDelayMs = options.forceKillDelayMs ?? FORCE_KILL_DELAY_MS;
6502
- const startedAt = Date.now();
6503
- const child = (options.spawnProcess ?? spawnShellProcess)(
6504
- options.command,
6505
- options.cwd
6506
- );
6507
- const metadata = typeof child.pid === "number" ? {
6508
- executor_pid: child.pid,
6509
- executor_pgid: process.platform === "win32" ? void 0 : child.pid
6510
- } : {};
6511
- let stdout = "";
6512
- let stderr = "";
6513
- let totalBytes = 0;
6514
- let settled = false;
6515
- let cancelRequested = false;
6516
- let timeoutHandle;
6517
- let forceKillHandle;
6518
- const clearForceKillHandle = () => {
6519
- if (!forceKillHandle) return;
6520
- clearTimeout(forceKillHandle);
6521
- forceKillHandle = void 0;
6522
- };
6523
- const scheduleForceKill = () => {
6524
- if (forceKillHandle) return;
6525
- forceKillHandle = setTimeout(() => {
6526
- forceKillHandle = void 0;
6527
- terminateChild(child, "SIGKILL");
6528
- }, forceKillDelayMs);
6529
- };
6530
- const wait = new Promise((resolve) => {
6531
- const settle = async (outcome) => {
6532
- if (settled) return;
6533
- settled = true;
6534
- if (timeoutHandle) clearTimeout(timeoutHandle);
6535
- let result;
6536
- try {
6537
- result = await buildShellTaskResult(options.outputCache, {
6538
- taskId: options.taskId,
6539
- toolName: options.toolName ?? "shell.exec",
6540
- rawStdout: stdout,
6541
- rawStderr: stderr,
6542
- exitCode: outcome.exitCode,
6543
- signal: outcome.signal,
6544
- durationMs: Date.now() - startedAt
6545
- });
6546
- } catch {
6547
- result = buildShellTaskResultBase({
6548
- rawStdout: stdout,
6549
- rawStderr: stderr,
6550
- exitCode: outcome.exitCode,
6551
- signal: outcome.signal,
6552
- durationMs: Date.now() - startedAt
6553
- });
6806
+ async recoverOrphanedTasks() {
6807
+ const tasks = await this.registry.list();
6808
+ let recovered = 0;
6809
+ const errors = [];
6810
+ for (const task of tasks) {
6811
+ if (isTerminalTaskState(task.state)) {
6812
+ continue;
6554
6813
  }
6555
- resolve({
6556
- state: outcome.state,
6557
- result,
6558
- ...outcome.failureMessage ? { failure_message: outcome.failureMessage } : {},
6559
- ...outcome.cancellationReason ? { cancellation_reason: outcome.cancellationReason } : {}
6560
- });
6561
- };
6562
- const fail = (message, signal) => {
6563
- void settle({
6564
- state: cancelRequested ? "cancelled" : "failed",
6565
- exitCode: null,
6566
- signal,
6567
- failureMessage: cancelRequested ? void 0 : message,
6568
- cancellationReason: cancelRequested ? "cancelled" : void 0
6569
- });
6570
- };
6571
- const consumeChunk = (chunk, stream) => {
6572
- if (settled) return;
6573
- const text = chunk.toString("utf8");
6574
- totalBytes += Buffer.byteLength(text, "utf8");
6575
- if (totalBytes > maxOutputBytes) {
6576
- terminateChild(child, "SIGTERM");
6577
- scheduleForceKill();
6578
- fail(
6579
- `Command output exceeded max buffer of ${maxOutputBytes} bytes`,
6580
- "SIGTERM"
6581
- );
6582
- return;
6814
+ const ownerAlive = await this.processController.isProcessAlive(
6815
+ task.owner_pid
6816
+ );
6817
+ if (ownerAlive) {
6818
+ continue;
6583
6819
  }
6584
- if (stream === "stdout") stdout += text;
6585
- else stderr += text;
6586
- };
6587
- child.stdout.on("data", (chunk) => consumeChunk(chunk, "stdout"));
6588
- child.stderr.on("data", (chunk) => consumeChunk(chunk, "stderr"));
6589
- child.on("error", (error) => {
6590
- fail(error.message, null);
6591
- });
6592
- child.on("close", (code, signal) => {
6593
- clearForceKillHandle();
6594
- if (settled) return;
6595
- if (cancelRequested) {
6596
- void settle({
6820
+ try {
6821
+ await this.terminatePersistedTask(task, "SIGTERM");
6822
+ await this.forceTerminateIfStillAlive(task);
6823
+ await this.finalizeTask(task.task_id, {
6597
6824
  state: "cancelled",
6598
- exitCode: code,
6599
- signal: signal ?? null,
6600
- cancellationReason: "cancelled"
6601
- });
6602
- return;
6603
- }
6604
- if (code === 0) {
6605
- void settle({
6606
- state: "completed",
6607
- exitCode: code,
6608
- signal: signal ?? null
6825
+ cancellation_reason: OWNER_EXIT_REASON,
6826
+ cleanup_reason: OWNER_EXIT_REASON
6609
6827
  });
6610
- return;
6828
+ recovered += 1;
6829
+ } catch (error) {
6830
+ errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
6611
6831
  }
6612
- void settle({
6613
- state: "failed",
6614
- exitCode: code,
6615
- signal: signal ?? null,
6616
- failureMessage: `Command failed with exit code ${code ?? "unknown"}${signal ? ` signal ${signal}` : ""}`
6617
- });
6618
- });
6619
- if (timeoutSeconds !== void 0) {
6620
- timeoutHandle = setTimeout(() => {
6621
- cancelRequested = false;
6622
- terminateChild(child, "SIGTERM");
6623
- scheduleForceKill();
6624
- fail(
6625
- `Command timed out after ${Math.trunc(timeoutSeconds)}s`,
6626
- "SIGTERM"
6627
- );
6628
- }, timeoutSeconds * 1e3);
6629
6832
  }
6630
- });
6631
- return {
6632
- metadata,
6633
- wait,
6634
- readOutput: async (stream) => stream === "stdout" ? stdout : stderr,
6635
- cancel: async () => {
6636
- if (settled) return;
6637
- cancelRequested = true;
6638
- terminateChild(child, "SIGTERM");
6639
- scheduleForceKill();
6833
+ return { recovered, errors };
6834
+ }
6835
+ async shutdown() {
6836
+ this.shuttingDown = true;
6837
+ const tasks = (await this.registry.list()).filter(
6838
+ (task) => task.owner_runtime_id === this.runtimeId && !isTerminalTaskState(task.state)
6839
+ );
6840
+ let cancelled = 0;
6841
+ const errors = [];
6842
+ for (const task of tasks) {
6843
+ try {
6844
+ const result = await Promise.race([
6845
+ this.cancel(task.task_id, { reason: OWNER_SHUTDOWN_REASON }).then(
6846
+ (record) => ({ timedOut: false, record })
6847
+ ),
6848
+ this.sleep(this.gracePeriodMs).then(() => ({
6849
+ timedOut: true,
6850
+ record: null
6851
+ }))
6852
+ ]);
6853
+ if (result.timedOut) {
6854
+ const refreshed = await this.requireTask(task.task_id);
6855
+ if (!isTerminalTaskState(refreshed.state)) {
6856
+ await this.terminatePersistedTask(refreshed, "SIGKILL");
6857
+ await this.finalizeTask(task.task_id, {
6858
+ state: "cancelled",
6859
+ cancellation_reason: OWNER_SHUTDOWN_REASON,
6860
+ cleanup_reason: OWNER_SHUTDOWN_REASON
6861
+ });
6862
+ }
6863
+ cancelled += 1;
6864
+ continue;
6865
+ }
6866
+ if (result.record.state === "cancelled") {
6867
+ cancelled += 1;
6868
+ }
6869
+ } catch (error) {
6870
+ errors.push({ task_id: task.task_id, error: toErrorMessage(error) });
6871
+ }
6640
6872
  }
6641
- };
6873
+ return { cancelled, errors };
6874
+ }
6642
6875
  };
6643
6876
 
6644
6877
  // src/tools/session-context.ts
@@ -7813,7 +8046,7 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7813
8046
 
7814
8047
  // src/tools/view-image.ts
7815
8048
  var import_node_fs13 = require("fs");
7816
- var import_node_path12 = __toESM(require("path"), 1);
8049
+ var import_node_path13 = __toESM(require("path"), 1);
7817
8050
  var import_core17 = require("@codelia/core");
7818
8051
  var import_zod16 = require("zod");
7819
8052
  var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
@@ -7826,7 +8059,7 @@ var MIME_BY_EXTENSION = {
7826
8059
  ".gif": "image/gif"
7827
8060
  };
7828
8061
  var resolveImageMime = (filePath) => {
7829
- return MIME_BY_EXTENSION[import_node_path12.default.extname(filePath).toLowerCase()] ?? null;
8062
+ return MIME_BY_EXTENSION[import_node_path13.default.extname(filePath).toLowerCase()] ?? null;
7830
8063
  };
7831
8064
  var createViewImageTool = (sandboxKey) => (0, import_core17.defineTool)({
7832
8065
  name: "view_image",
@@ -8214,7 +8447,7 @@ var createWebfetchTool = () => (0, import_core18.defineTool)({
8214
8447
 
8215
8448
  // src/tools/write.ts
8216
8449
  var import_node_fs14 = require("fs");
8217
- var import_node_path13 = __toESM(require("path"), 1);
8450
+ var import_node_path14 = __toESM(require("path"), 1);
8218
8451
  var import_core19 = require("@codelia/core");
8219
8452
  var import_zod18 = require("zod");
8220
8453
  var createWriteTool = (sandboxKey, outputCacheStore) => (0, import_core19.defineTool)({
@@ -8243,7 +8476,7 @@ var createWriteTool = (sandboxKey, outputCacheStore) => (0, import_core19.define
8243
8476
  throw error;
8244
8477
  }
8245
8478
  }
8246
- await import_node_fs14.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
8479
+ await import_node_fs14.promises.mkdir(import_node_path14.default.dirname(resolved), { recursive: true });
8247
8480
  await import_node_fs14.promises.writeFile(resolved, input.content, "utf8");
8248
8481
  const diffPayload = await buildDiffPayload({
8249
8482
  toolName: "write",
@@ -8357,9 +8590,9 @@ var normalizeLanguage = (value) => {
8357
8590
  };
8358
8591
  var languageFromFilePath = (filePath) => {
8359
8592
  if (!filePath) return void 0;
8360
- const path19 = filePath.trim().replace(/^["']|["']$/g, "");
8361
- if (!path19 || path19 === "/dev/null") return void 0;
8362
- const normalizedPath = path19.replace(/^a\//, "").replace(/^b\//, "");
8593
+ const path20 = filePath.trim().replace(/^["']|["']$/g, "");
8594
+ if (!path20 || path20 === "/dev/null") return void 0;
8595
+ const normalizedPath = path20.replace(/^a\//, "").replace(/^b\//, "");
8363
8596
  const lastSlash = Math.max(
8364
8597
  normalizedPath.lastIndexOf("/"),
8365
8598
  normalizedPath.lastIndexOf("\\")
@@ -8762,8 +8995,12 @@ var createAgentFactory = (state, options = {}) => {
8762
8995
  const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
8763
8996
  state.agentsResolver = agentsResolver;
8764
8997
  let skillsConfig;
8998
+ let executionEnvironmentConfig;
8765
8999
  try {
8766
- skillsConfig = await resolveSkillsConfig(ctx.workingDir);
9000
+ [skillsConfig, executionEnvironmentConfig] = await Promise.all([
9001
+ resolveSkillsConfig(ctx.workingDir),
9002
+ resolveExecutionEnvironmentConfig(ctx.workingDir)
9003
+ ]);
8767
9004
  } catch (error) {
8768
9005
  const message = error instanceof Error ? error.message : String(error);
8769
9006
  throw new Error(message);
@@ -8820,8 +9057,23 @@ var createAgentFactory = (state, options = {}) => {
8820
9057
  }
8821
9058
  }
8822
9059
  const baseSystemPrompt = await loadSystemPrompt(ctx.workingDir);
8823
- const withAgentsContext = appendInitialAgentsContext(
9060
+ const executionEnvironmentContext = await buildExecutionEnvironmentContext({
9061
+ workingDir: ctx.workingDir,
9062
+ sandboxRoot: ctx.rootDir,
9063
+ config: executionEnvironmentConfig
9064
+ });
9065
+ state.executionEnvironmentContext = executionEnvironmentContext;
9066
+ if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
9067
+ alreadyLogged: state.executionEnvironmentDebugLogged
9068
+ })) {
9069
+ state.executionEnvironmentDebugLogged = true;
9070
+ }
9071
+ const withExecutionEnvironment = appendInitialExecutionEnvironment(
8824
9072
  baseSystemPrompt,
9073
+ executionEnvironmentContext
9074
+ );
9075
+ const withAgentsContext = appendInitialAgentsContext(
9076
+ withExecutionEnvironment,
8825
9077
  agentsResolver.buildInitialContext()
8826
9078
  );
8827
9079
  const systemPrompt = appendInitialSkillsCatalog(
@@ -9715,8 +9967,8 @@ var parseAuthorizationServerMetadata = (value) => {
9715
9967
  var buildAuthorizationServerMetadataUrl = (issuer) => {
9716
9968
  try {
9717
9969
  const parsed = new URL(issuer);
9718
- const path19 = parsed.pathname === "/" ? "" : parsed.pathname;
9719
- const basePath = path19.startsWith("/") ? path19 : `/${path19}`;
9970
+ const path20 = parsed.pathname === "/" ? "" : parsed.pathname;
9971
+ const basePath = path20.startsWith("/") ? path20 : `/${path20}`;
9720
9972
  const metadataPath = `/.well-known/oauth-authorization-server${basePath}`;
9721
9973
  return new URL(metadataPath, `${parsed.origin}/`).toString();
9722
9974
  } catch {
@@ -10426,13 +10678,38 @@ var createContextHandlers = ({
10426
10678
  return null;
10427
10679
  }
10428
10680
  };
10681
+ const ensureExecutionEnvironmentContext = async () => {
10682
+ if (state.executionEnvironmentContext) {
10683
+ return state.executionEnvironmentContext;
10684
+ }
10685
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
10686
+ const sandboxRoot = state.runtimeSandboxRoot ?? workingDir;
10687
+ try {
10688
+ const context = await buildExecutionEnvironmentContext({
10689
+ workingDir,
10690
+ sandboxRoot,
10691
+ config: await resolveExecutionEnvironmentConfig(workingDir)
10692
+ });
10693
+ state.executionEnvironmentContext = context;
10694
+ state.runtimeWorkingDir = workingDir;
10695
+ if (!state.runtimeSandboxRoot) {
10696
+ state.runtimeSandboxRoot = sandboxRoot;
10697
+ }
10698
+ return context;
10699
+ } catch (error) {
10700
+ log2(`context.inspect execution environment error: ${String(error)}`);
10701
+ return null;
10702
+ }
10703
+ };
10429
10704
  const handleContextInspect = async (id, params) => {
10430
10705
  const includeAgents = params?.include_agents ?? true;
10431
10706
  const includeSkills = params?.include_skills ?? true;
10432
10707
  try {
10708
+ const executionEnvironment = await ensureExecutionEnvironmentContext();
10433
10709
  const result = {
10434
10710
  runtime_working_dir: state.runtimeWorkingDir ?? void 0,
10435
10711
  runtime_sandbox_root: state.runtimeSandboxRoot ?? void 0,
10712
+ execution_environment: executionEnvironment ?? void 0,
10436
10713
  ui_context: {
10437
10714
  cwd: state.lastUiContext?.cwd,
10438
10715
  workspace_root: state.lastUiContext?.workspace_root,
@@ -10482,7 +10759,7 @@ var createContextHandlers = ({
10482
10759
 
10483
10760
  // src/rpc/history.ts
10484
10761
  var import_node_fs16 = require("fs");
10485
- var import_node_path14 = __toESM(require("path"), 1);
10762
+ var import_node_path15 = __toESM(require("path"), 1);
10486
10763
  var import_node_readline2 = require("readline");
10487
10764
  var import_protocol3 = require("@codelia/protocol");
10488
10765
  var import_storage10 = require("@codelia/storage");
@@ -10556,7 +10833,7 @@ var collectRunCandidates = async (log2) => {
10556
10833
  for (const yearEntry of yearEntries) {
10557
10834
  if (!yearEntry.isDirectory()) continue;
10558
10835
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
10559
- const yearPath = import_node_path14.default.join(sessionsDir, yearEntry.name);
10836
+ const yearPath = import_node_path15.default.join(sessionsDir, yearEntry.name);
10560
10837
  let monthEntries;
10561
10838
  try {
10562
10839
  monthEntries = await import_node_fs16.promises.readdir(yearPath, {
@@ -10569,7 +10846,7 @@ var collectRunCandidates = async (log2) => {
10569
10846
  for (const monthEntry of monthEntries) {
10570
10847
  if (!monthEntry.isDirectory()) continue;
10571
10848
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
10572
- const monthPath = import_node_path14.default.join(yearPath, monthEntry.name);
10849
+ const monthPath = import_node_path15.default.join(yearPath, monthEntry.name);
10573
10850
  let dayEntries;
10574
10851
  try {
10575
10852
  dayEntries = await import_node_fs16.promises.readdir(monthPath, {
@@ -10582,7 +10859,7 @@ var collectRunCandidates = async (log2) => {
10582
10859
  for (const dayEntry of dayEntries) {
10583
10860
  if (!dayEntry.isDirectory()) continue;
10584
10861
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
10585
- const dayPath = import_node_path14.default.join(monthPath, dayEntry.name);
10862
+ const dayPath = import_node_path15.default.join(monthPath, dayEntry.name);
10586
10863
  let files;
10587
10864
  try {
10588
10865
  files = await import_node_fs16.promises.readdir(dayPath, {
@@ -10595,7 +10872,7 @@ var collectRunCandidates = async (log2) => {
10595
10872
  for (const file of files) {
10596
10873
  if (!file.isFile()) continue;
10597
10874
  if (!file.name.endsWith(".jsonl")) continue;
10598
- const filePath = import_node_path14.default.join(dayPath, file.name);
10875
+ const filePath = import_node_path15.default.join(dayPath, file.name);
10599
10876
  try {
10600
10877
  const stat = await import_node_fs16.promises.stat(filePath);
10601
10878
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -10623,7 +10900,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
10623
10900
  const header = parseRunHeader(headerLine);
10624
10901
  if (!header) continue;
10625
10902
  if (header.session_id !== sessionId) continue;
10626
- const runId = header.run_id ?? import_node_path14.default.basename(candidate.path, ".jsonl");
10903
+ const runId = header.run_id ?? import_node_path15.default.basename(candidate.path, ".jsonl");
10627
10904
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
10628
10905
  runs.push({
10629
10906
  path: candidate.path,
@@ -12131,7 +12408,7 @@ var createRunHandlers = ({
12131
12408
  };
12132
12409
 
12133
12410
  // src/rpc/shell.ts
12134
- var import_node_path15 = __toESM(require("path"), 1);
12411
+ var import_node_path16 = __toESM(require("path"), 1);
12135
12412
  var import_protocol6 = require("@codelia/protocol");
12136
12413
  var import_storage11 = require("@codelia/storage");
12137
12414
  var COMMAND_PREVIEW_CHARS = 400;
@@ -12146,14 +12423,14 @@ var truncateCommandPreview = (value) => {
12146
12423
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
12147
12424
  };
12148
12425
  var isWithin2 = (basePath, candidatePath) => {
12149
- const relative = import_node_path15.default.relative(basePath, candidatePath);
12150
- return relative === "" || !relative.startsWith("..") && !import_node_path15.default.isAbsolute(relative);
12426
+ const relative = import_node_path16.default.relative(basePath, candidatePath);
12427
+ return relative === "" || !relative.startsWith("..") && !import_node_path16.default.isAbsolute(relative);
12151
12428
  };
12152
12429
  var resolveShellCwd = (state, requestedCwd) => {
12153
12430
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
12154
12431
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
12155
12432
  if (!requestedCwd) return workingDir;
12156
- const resolved = import_node_path15.default.resolve(workingDir, requestedCwd);
12433
+ const resolved = import_node_path16.default.resolve(workingDir, requestedCwd);
12157
12434
  if (!isWithin2(rootDir, resolved)) {
12158
12435
  return null;
12159
12436
  }
@@ -12738,14 +13015,14 @@ var createShellHandlers = ({
12738
13015
  };
12739
13016
 
12740
13017
  // src/rpc/skills.ts
12741
- var import_node_path16 = __toESM(require("path"), 1);
13018
+ var import_node_path17 = __toESM(require("path"), 1);
12742
13019
  var import_protocol7 = require("@codelia/protocol");
12743
13020
  var createSkillsHandlers = ({
12744
13021
  state,
12745
13022
  log: log2
12746
13023
  }) => {
12747
13024
  const handleSkillsList = async (id, params) => {
12748
- const requestedCwd = params?.cwd ? import_node_path16.default.resolve(params.cwd) : void 0;
13025
+ const requestedCwd = params?.cwd ? import_node_path17.default.resolve(params.cwd) : void 0;
12749
13026
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
12750
13027
  const forceReload = params?.force_reload ?? false;
12751
13028
  if (!forceReload) {
@@ -12800,7 +13077,7 @@ var createSkillsHandlers = ({
12800
13077
  };
12801
13078
 
12802
13079
  // src/rpc/task.ts
12803
- var import_node_path17 = __toESM(require("path"), 1);
13080
+ var import_node_path18 = __toESM(require("path"), 1);
12804
13081
  var import_protocol8 = require("@codelia/protocol");
12805
13082
  var import_storage12 = require("@codelia/storage");
12806
13083
  var DEFAULT_TRUNCATED2 = {
@@ -12835,14 +13112,14 @@ var getPublicTaskKey = (task) => {
12835
13112
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
12836
13113
  };
12837
13114
  var isWithin3 = (basePath, candidatePath) => {
12838
- const relative = import_node_path17.default.relative(basePath, candidatePath);
12839
- return relative === "" || !relative.startsWith("..") && !import_node_path17.default.isAbsolute(relative);
13115
+ const relative = import_node_path18.default.relative(basePath, candidatePath);
13116
+ return relative === "" || !relative.startsWith("..") && !import_node_path18.default.isAbsolute(relative);
12840
13117
  };
12841
13118
  var resolveShellCwd2 = (state, requestedCwd) => {
12842
13119
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
12843
13120
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
12844
13121
  if (!requestedCwd) return workingDir;
12845
- const resolved = import_node_path17.default.resolve(workingDir, requestedCwd);
13122
+ const resolved = import_node_path18.default.resolve(workingDir, requestedCwd);
12846
13123
  if (!isWithin3(rootDir, resolved)) {
12847
13124
  return null;
12848
13125
  }
@@ -13675,6 +13952,8 @@ var RuntimeState = class {
13675
13952
  lastClientInfo = null;
13676
13953
  uiCapabilities = null;
13677
13954
  systemPrompt = null;
13955
+ executionEnvironmentContext = null;
13956
+ executionEnvironmentDebugLogged = false;
13678
13957
  toolDefinitions = null;
13679
13958
  tools = null;
13680
13959
  sessionId = null;
@@ -13790,7 +14069,7 @@ var startRuntime = () => {
13790
14069
  void (async () => {
13791
14070
  const state = new RuntimeState();
13792
14071
  state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
13793
- const workingDir = process.env.CODELIA_SANDBOX_ROOT ? import_node_path18.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
14072
+ const workingDir = process.env.CODELIA_SANDBOX_ROOT ? import_node_path19.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
13794
14073
  state.runtimeWorkingDir = workingDir;
13795
14074
  state.runtimeSandboxRoot = workingDir;
13796
14075
  const sessionStateStore = new import_storage14.SessionStateStoreImpl({