@codelia/runtime 0.1.68 → 0.1.70

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 CHANGED
@@ -23,14 +23,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/runtime.ts
26
- var import_node_path20 = __toESM(require("path"), 1);
27
26
  var import_storage14 = require("@codelia/storage");
28
27
 
29
28
  // src/agent-factory.ts
30
29
  var import_node_fs15 = require("fs");
31
30
  var import_core21 = require("@codelia/core");
32
31
  var import_model_metadata2 = require("@codelia/model-metadata");
33
- var import_shared_types2 = require("@codelia/shared-types");
32
+ var import_shared_types4 = require("@codelia/shared-types");
34
33
  var import_storage8 = require("@codelia/storage");
35
34
 
36
35
  // src/agents/context.ts
@@ -751,6 +750,7 @@ var import_node_path2 = __toESM(require("path"), 1);
751
750
  var import_config = require("@codelia/config");
752
751
  var import_config_loader = require("@codelia/config-loader");
753
752
  var import_core = require("@codelia/core");
753
+ var import_shared_types = require("@codelia/shared-types");
754
754
  var import_storage = require("@codelia/storage");
755
755
  var DEFAULT_SYSTEM_PROMPT = "You are a coding assistant.";
756
756
  var DEFAULT_MCP_REQUEST_TIMEOUT_MS = 3e4;
@@ -1028,10 +1028,10 @@ function resolveModelLevelOption(value, fieldName, options) {
1028
1028
  if (normalized === "low" || normalized === "medium" || normalized === "high") {
1029
1029
  return normalized;
1030
1030
  }
1031
- if (options.allowXhigh && normalized === "xhigh") {
1031
+ if (options.allowXhigh && (0, import_shared_types.isModelReasoningLevel)(normalized)) {
1032
1032
  return normalized;
1033
1033
  }
1034
- const expected = options.allowXhigh ? "low|medium|high|xhigh" : "low|medium|high";
1034
+ const expected = options.allowXhigh ? import_shared_types.MODEL_REASONING_LEVELS.join("|") : "low|medium|high";
1035
1035
  throw new Error(`Invalid ${fieldName}: ${value}. Expected ${expected}.`);
1036
1036
  }
1037
1037
  var loadSystemPrompt = async (workingDir) => {
@@ -1070,6 +1070,38 @@ var serializeMessage = (msg) => ({
1070
1070
  `,
1071
1071
  label: describeRpcMessage(msg)
1072
1072
  });
1073
+ var hostNotificationQueues = /* @__PURE__ */ new WeakMap();
1074
+ var enqueueHostNotification = (state, notify) => {
1075
+ const sink = state.effectiveEnvironment.adapters.eventSink;
1076
+ if (!sink) {
1077
+ (0, import_logger.log)(
1078
+ `transport.host-event.error label=${describeRpcMessage(notify)} message=event sink unavailable`
1079
+ );
1080
+ return Promise.resolve();
1081
+ }
1082
+ const previous = hostNotificationQueues.get(state) ?? Promise.resolve();
1083
+ const next = previous.then(() => sink.emit(notify)).catch((error) => {
1084
+ (0, import_logger.log)(
1085
+ `transport.host-event.error label=${describeRpcMessage(notify)} message=${String(error)}`
1086
+ );
1087
+ });
1088
+ hostNotificationQueues.set(state, next);
1089
+ return next;
1090
+ };
1091
+ var sendNotification = (state, notify) => {
1092
+ if (state.effectiveEnvironment.events.live === "host") {
1093
+ void enqueueHostNotification(state, notify);
1094
+ return;
1095
+ }
1096
+ send(notify);
1097
+ };
1098
+ var sendNotificationAsync = async (state, notify) => {
1099
+ if (state.effectiveEnvironment.events.live === "host") {
1100
+ await enqueueHostNotification(state, notify);
1101
+ return;
1102
+ }
1103
+ await sendAsync(notify);
1104
+ };
1073
1105
  var send = (msg) => {
1074
1106
  const { payload, label } = serializeMessage(msg);
1075
1107
  const writable = process.stdout.write(payload, (error) => {
@@ -1115,7 +1147,7 @@ var sendAgentEvent = (state, runId, event) => {
1115
1147
  event
1116
1148
  }
1117
1149
  };
1118
- send(notify);
1150
+ sendNotification(state, notify);
1119
1151
  return seq;
1120
1152
  };
1121
1153
  var sendAgentEventAsync = async (state, runId, event) => {
@@ -1130,10 +1162,10 @@ var sendAgentEventAsync = async (state, runId, event) => {
1130
1162
  event
1131
1163
  }
1132
1164
  };
1133
- await sendAsync(notify);
1165
+ await sendNotificationAsync(state, notify);
1134
1166
  return seq;
1135
1167
  };
1136
- var sendRunStatus = (runId, status, message) => {
1168
+ var sendRunStatus = (state, runId, status, message) => {
1137
1169
  const notify = {
1138
1170
  jsonrpc: "2.0",
1139
1171
  method: "run.status",
@@ -1143,9 +1175,9 @@ var sendRunStatus = (runId, status, message) => {
1143
1175
  message
1144
1176
  }
1145
1177
  };
1146
- send(notify);
1178
+ sendNotification(state, notify);
1147
1179
  };
1148
- var sendRunStatusAsync = async (runId, status, message) => {
1180
+ var sendRunStatusAsync = async (state, runId, status, message) => {
1149
1181
  const notify = {
1150
1182
  jsonrpc: "2.0",
1151
1183
  method: "run.status",
@@ -1155,9 +1187,9 @@ var sendRunStatusAsync = async (runId, status, message) => {
1155
1187
  message
1156
1188
  }
1157
1189
  };
1158
- await sendAsync(notify);
1190
+ await sendNotificationAsync(state, notify);
1159
1191
  };
1160
- var sendRunContext = (runId, contextLeftPercent) => {
1192
+ var sendRunContext = (state, runId, contextLeftPercent) => {
1161
1193
  const notify = {
1162
1194
  jsonrpc: "2.0",
1163
1195
  method: "run.context",
@@ -1166,15 +1198,15 @@ var sendRunContext = (runId, contextLeftPercent) => {
1166
1198
  context_left_percent: contextLeftPercent
1167
1199
  }
1168
1200
  };
1169
- send(notify);
1201
+ sendNotification(state, notify);
1170
1202
  };
1171
- var sendRunDiagnostics = (params) => {
1203
+ var sendRunDiagnostics = (state, params) => {
1172
1204
  const notify = {
1173
1205
  jsonrpc: "2.0",
1174
1206
  method: "run.diagnostics",
1175
1207
  params
1176
1208
  };
1177
- send(notify);
1209
+ sendNotification(state, notify);
1178
1210
  };
1179
1211
 
1180
1212
  // src/rpc/ui-requests.ts
@@ -1377,12 +1409,14 @@ var AuthStore = class {
1377
1409
  var SUPPORTED_PROVIDERS = [
1378
1410
  "openai",
1379
1411
  "anthropic",
1380
- "openrouter"
1412
+ "openrouter",
1413
+ "zai"
1381
1414
  ];
1382
1415
  var API_KEY_ENV = {
1383
1416
  openai: "OPENAI_API_KEY",
1384
1417
  anthropic: "ANTHROPIC_API_KEY",
1385
- openrouter: "OPENROUTER_API_KEY"
1418
+ openrouter: "OPENROUTER_API_KEY",
1419
+ zai: "ZAI_API_KEY"
1386
1420
  };
1387
1421
  var AuthResolver = class _AuthResolver {
1388
1422
  auth;
@@ -1428,7 +1462,7 @@ var AuthResolver = class _AuthResolver {
1428
1462
  items: SUPPORTED_PROVIDERS.map((provider) => ({
1429
1463
  id: provider,
1430
1464
  label: provider,
1431
- detail: provider === "openai" ? "OAuth (ChatGPT Plus/Pro) or API key" : provider === "openrouter" ? "API key (OpenRouter)" : "API key"
1465
+ detail: provider === "openai" ? "OAuth (ChatGPT Plus/Pro) or API key" : provider === "openrouter" ? "API key (OpenRouter)" : provider === "zai" ? "API key (Z.ai)" : "API key"
1432
1466
  })),
1433
1467
  multi: false
1434
1468
  });
@@ -1459,6 +1493,8 @@ var AuthResolver = class _AuthResolver {
1459
1493
  return "Anthropic API key";
1460
1494
  case "openrouter":
1461
1495
  return "OpenRouter API key";
1496
+ case "zai":
1497
+ return "Z.ai API key";
1462
1498
  default:
1463
1499
  return "API key";
1464
1500
  }
@@ -1676,6 +1712,211 @@ var AuthResolver = class _AuthResolver {
1676
1712
  }
1677
1713
  };
1678
1714
 
1715
+ // src/environment-services.ts
1716
+ var requireConfigProviderMethod = (method) => new Error(`host config provider does not implement ${method}`);
1717
+ var resolveEnvironmentModelConfig = async (state, workingDir) => {
1718
+ if (state.effectiveEnvironment.config.source === "host") {
1719
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1720
+ if (!provider?.resolveModelConfig) {
1721
+ throw requireConfigProviderMethod("resolveModelConfig");
1722
+ }
1723
+ return provider.resolveModelConfig(workingDir);
1724
+ }
1725
+ if (state.effectiveEnvironment.config.source === "disabled") {
1726
+ return {};
1727
+ }
1728
+ return resolveModelConfig(workingDir);
1729
+ };
1730
+ var resolveEnvironmentPermissionsConfig = async (state, workingDir) => {
1731
+ if (state.effectiveEnvironment.config.source === "host") {
1732
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1733
+ if (!provider?.resolvePermissionsConfig) {
1734
+ return void 0;
1735
+ }
1736
+ return provider.resolvePermissionsConfig(workingDir);
1737
+ }
1738
+ if (state.effectiveEnvironment.config.source === "disabled") {
1739
+ return void 0;
1740
+ }
1741
+ return resolvePermissionsConfig(workingDir);
1742
+ };
1743
+ var resolveEnvironmentSearchConfig = async (state, workingDir) => {
1744
+ if (state.effectiveEnvironment.config.source === "host") {
1745
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1746
+ if (!provider?.resolveSearchConfig) {
1747
+ throw requireConfigProviderMethod("resolveSearchConfig");
1748
+ }
1749
+ return provider.resolveSearchConfig(workingDir);
1750
+ }
1751
+ return resolveSearchConfig(workingDir);
1752
+ };
1753
+ var resolveEnvironmentSkillsConfig = async (state, workingDir) => {
1754
+ if (state.effectiveEnvironment.config.source === "host") {
1755
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1756
+ if (!provider?.resolveSkillsConfig) {
1757
+ throw requireConfigProviderMethod("resolveSkillsConfig");
1758
+ }
1759
+ return provider.resolveSkillsConfig(workingDir);
1760
+ }
1761
+ return resolveSkillsConfig(workingDir);
1762
+ };
1763
+ var resolveEnvironmentExecutionEnvironmentConfig = async (state, workingDir) => {
1764
+ if (state.effectiveEnvironment.config.source === "host") {
1765
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1766
+ if (!provider?.resolveExecutionEnvironmentConfig) {
1767
+ throw requireConfigProviderMethod("resolveExecutionEnvironmentConfig");
1768
+ }
1769
+ return provider.resolveExecutionEnvironmentConfig(workingDir);
1770
+ }
1771
+ return resolveExecutionEnvironmentConfig(workingDir);
1772
+ };
1773
+ var resolveEnvironmentTuiConfig = async (state, workingDir) => {
1774
+ if (state.effectiveEnvironment.config.source === "host") {
1775
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1776
+ if (!provider?.resolveTuiConfig) {
1777
+ return {};
1778
+ }
1779
+ return provider.resolveTuiConfig(workingDir);
1780
+ }
1781
+ if (state.effectiveEnvironment.config.source === "disabled") {
1782
+ return {};
1783
+ }
1784
+ return resolveTuiConfig(workingDir);
1785
+ };
1786
+ var updateEnvironmentModel = async (state, workingDir, model) => {
1787
+ if (state.effectiveEnvironment.config.source === "host") {
1788
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1789
+ if (!provider?.updateModel) {
1790
+ throw requireConfigProviderMethod("updateModel");
1791
+ }
1792
+ return provider.updateModel(workingDir, model);
1793
+ }
1794
+ if (state.effectiveEnvironment.config.source === "disabled") {
1795
+ throw new Error("config writes are disabled");
1796
+ }
1797
+ return updateModel(workingDir ?? process.cwd(), model);
1798
+ };
1799
+ var updateEnvironmentTuiTheme = async (state, workingDir, theme) => {
1800
+ if (state.effectiveEnvironment.config.source === "host") {
1801
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1802
+ if (!provider?.updateTuiTheme) {
1803
+ throw requireConfigProviderMethod("updateTuiTheme");
1804
+ }
1805
+ return provider.updateTuiTheme(workingDir, theme);
1806
+ }
1807
+ if (state.effectiveEnvironment.config.source === "disabled") {
1808
+ throw new Error("config writes are disabled");
1809
+ }
1810
+ return updateTuiTheme(workingDir ?? process.cwd(), theme);
1811
+ };
1812
+ var appendEnvironmentPermissionAllowRules = async (state, workingDir, rules) => {
1813
+ if (!rules.length) return;
1814
+ if (state.effectiveEnvironment.config.source === "host") {
1815
+ const provider = state.effectiveEnvironment.adapters.configProvider;
1816
+ if (!provider?.appendPermissionAllowRules) {
1817
+ throw requireConfigProviderMethod("appendPermissionAllowRules");
1818
+ }
1819
+ await provider.appendPermissionAllowRules(workingDir, rules);
1820
+ return;
1821
+ }
1822
+ if (state.effectiveEnvironment.config.source === "disabled") {
1823
+ throw new Error("config writes are disabled");
1824
+ }
1825
+ await appendPermissionAllowRules(workingDir ?? process.cwd(), rules);
1826
+ };
1827
+ var loadEnvironmentSystemPrompt = async (state, workingDir) => {
1828
+ if (state.effectiveEnvironment.context.systemPrompt === "host") {
1829
+ const provider = state.effectiveEnvironment.adapters.systemPromptProvider;
1830
+ if (!provider) {
1831
+ throw new Error("host system prompt provider is required");
1832
+ }
1833
+ return provider.loadSystemPrompt(workingDir);
1834
+ }
1835
+ return loadSystemPrompt(workingDir ?? process.cwd());
1836
+ };
1837
+ var createEnvironmentAuthResolver = async (state, log2) => {
1838
+ if (state.effectiveEnvironment.auth.model === "host") {
1839
+ const provider = state.effectiveEnvironment.adapters.credentialProvider;
1840
+ if (!provider) {
1841
+ throw new Error("host credential provider is required");
1842
+ }
1843
+ return {
1844
+ hasAnyAvailableAuth: provider.hasAnyAvailableAuth ?? (() => true),
1845
+ resolveProvider: provider.resolveProvider,
1846
+ resolveProviderAuth: provider.resolveProviderAuth,
1847
+ getOpenAiAccessToken: provider.getOpenAiAccessToken
1848
+ };
1849
+ }
1850
+ return AuthResolver.create(state, log2);
1851
+ };
1852
+
1853
+ // src/effective-model.ts
1854
+ var MODEL_OVERRIDE_SESSION_META_KEY = "codelia_model_override";
1855
+ var mergeModelOverride = (config, override) => {
1856
+ if (!override) return config;
1857
+ return {
1858
+ ...config,
1859
+ provider: override.provider ?? config.provider,
1860
+ name: override.name ?? config.name,
1861
+ reasoning: override.reasoning ?? config.reasoning,
1862
+ fast: override.fast ?? config.fast
1863
+ };
1864
+ };
1865
+ var resolveEffectiveModelConfig = async (state, workingDir) => {
1866
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
1867
+ const source = state.sessionModelOverride ? "session" : "config";
1868
+ return {
1869
+ ...mergeModelOverride(config, state.sessionModelOverride),
1870
+ source
1871
+ };
1872
+ };
1873
+ var setSessionModelOverride = (state, baseConfig, next) => {
1874
+ const current = mergeModelOverride(baseConfig, state.sessionModelOverride);
1875
+ state.sessionModelOverride = {
1876
+ provider: next.provider,
1877
+ name: next.name,
1878
+ reasoning: next.reasoning ?? current.reasoning,
1879
+ fast: next.fast ?? current.fast
1880
+ };
1881
+ return mergeModelOverride(baseConfig, state.sessionModelOverride);
1882
+ };
1883
+ var clearSessionModelOverride = (state) => {
1884
+ state.sessionModelOverride = null;
1885
+ };
1886
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1887
+ var pickString = (value) => typeof value === "string" && value.trim() ? value.trim() : void 0;
1888
+ var readSessionModelOverride = (meta) => {
1889
+ const raw = meta?.[MODEL_OVERRIDE_SESSION_META_KEY];
1890
+ if (!isRecord2(raw)) return null;
1891
+ const provider = pickString(raw.provider);
1892
+ const name = pickString(raw.name);
1893
+ const reasoning = pickString(raw.reasoning);
1894
+ if (!provider || !name) return null;
1895
+ return {
1896
+ provider,
1897
+ name,
1898
+ ...reasoning ? { reasoning } : {},
1899
+ ...typeof raw.fast === "boolean" ? { fast: raw.fast } : {}
1900
+ };
1901
+ };
1902
+ var mergeSessionModelOverrideIntoMeta = (meta, override) => {
1903
+ const nextMeta = meta ? { ...meta } : {};
1904
+ if (override?.provider && override.name) {
1905
+ nextMeta[MODEL_OVERRIDE_SESSION_META_KEY] = {
1906
+ provider: override.provider,
1907
+ name: override.name,
1908
+ ...override.reasoning ? { reasoning: override.reasoning } : {},
1909
+ ...override.fast !== void 0 ? { fast: override.fast } : {}
1910
+ };
1911
+ } else {
1912
+ delete nextMeta[MODEL_OVERRIDE_SESSION_META_KEY];
1913
+ }
1914
+ return Object.keys(nextMeta).length > 0 ? nextMeta : void 0;
1915
+ };
1916
+ var applySessionModelOverrideFromMeta = (state, meta) => {
1917
+ state.sessionModelOverride = readSessionModelOverride(meta);
1918
+ };
1919
+
1679
1920
  // src/execution-environment.ts
1680
1921
  var import_node_os = __toESM(require("os"), 1);
1681
1922
  var import_node_path3 = __toESM(require("path"), 1);
@@ -2171,7 +2412,7 @@ var DEFAULT_MCP_OAUTH_PORT = 1456;
2171
2412
  var DEFAULT_MCP_OAUTH_WAIT_TIMEOUT_MS = 18e4;
2172
2413
  var HTML_SUCCESS2 = "<!doctype html><html><head><title>codelia - MCP authorization successful</title></head><body><h2>Authorization successful</h2><p>You can close this window.</p></body></html>";
2173
2414
  var HTML_ERROR2 = (message) => `<!doctype html><html><head><title>codelia - MCP authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
2174
- var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2415
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2175
2416
  var oauthPort2 = () => readPositiveIntEnv("CODELIA_MCP_OAUTH_PORT", DEFAULT_MCP_OAUTH_PORT);
2176
2417
  var oauthWaitTimeoutMs = () => readPositiveIntEnv(
2177
2418
  "CODELIA_MCP_OAUTH_TIMEOUT_MS",
@@ -2202,7 +2443,7 @@ var ensureJsonResponse = async (response, errorLabel) => {
2202
2443
  return await response.json();
2203
2444
  };
2204
2445
  var parseTokenPayload = (value, creds) => {
2205
- if (!isRecord2(value) || typeof value.access_token !== "string") {
2446
+ if (!isRecord3(value) || typeof value.access_token !== "string") {
2206
2447
  throw new Error("OAuth token response missing access_token");
2207
2448
  }
2208
2449
  const expiresIn = typeof value.expires_in === "number" && Number.isFinite(value.expires_in) ? value.expires_in : void 0;
@@ -2263,7 +2504,7 @@ var registerDynamicClient = async (registrationUrl, redirectUri, serverId) => {
2263
2504
  response,
2264
2505
  "MCP OAuth dynamic client registration failed"
2265
2506
  );
2266
- if (!isRecord2(parsed) || typeof parsed.client_id !== "string") {
2507
+ if (!isRecord3(parsed) || typeof parsed.client_id !== "string") {
2267
2508
  throw new Error(
2268
2509
  "MCP OAuth dynamic registration response missing client_id"
2269
2510
  );
@@ -2381,20 +2622,29 @@ var resolveFastMode = (params) => {
2381
2622
  };
2382
2623
 
2383
2624
  // src/model-reasoning.ts
2384
- var REASONING_LEVEL_ORDER = [
2385
- "low",
2386
- "medium",
2387
- "high",
2388
- "xhigh"
2389
- ];
2625
+ var import_shared_types2 = require("@codelia/shared-types");
2626
+ var REASONING_LEVEL_ORDER = import_shared_types2.MODEL_REASONING_LEVELS;
2390
2627
  var DEFAULT_REASONING_LEVEL = "medium";
2391
2628
  var RESPONSES_XHIGH_UNSUPPORTED_MODELS = /* @__PURE__ */ new Set([
2629
+ "gpt-5",
2630
+ "gpt-5-mini",
2631
+ "gpt-5-mini-2025-08-07",
2632
+ "gpt-5-nano",
2633
+ "gpt-5-nano-2025-08-07",
2634
+ "gpt-5-codex",
2635
+ "gpt-5-codex-mini",
2392
2636
  "gpt-5.1",
2393
2637
  "gpt-5.1-2025-11-13",
2394
2638
  "gpt-5.1-codex",
2395
2639
  "gpt-5.1-codex-max",
2396
2640
  "gpt-5.1-codex-mini"
2397
2641
  ]);
2642
+ var RESPONSES_MAX_SUPPORTED_MODELS = /* @__PURE__ */ new Set([
2643
+ "gpt-5.6",
2644
+ "gpt-5.6-sol",
2645
+ "gpt-5.6-terra",
2646
+ "gpt-5.6-luna"
2647
+ ]);
2398
2648
  var ANTHROPIC_FALLBACK_PROFILE = {
2399
2649
  supportedLevels: ["low", "medium", "high"],
2400
2650
  budgetPresetByLevel: {
@@ -2410,24 +2660,51 @@ var ANTHROPIC_BUDGET_PRESET_TOKENS = {
2410
2660
  reasoning_xhigh: 49152
2411
2661
  };
2412
2662
  var ANTHROPIC_MAX_TOKENS_FALLBACK_HEADROOM = 4096;
2663
+ var ANTHROPIC_OUTPUT_EFFORT_ALL = {
2664
+ low: "low",
2665
+ medium: "medium",
2666
+ high: "high",
2667
+ xhigh: "xhigh",
2668
+ max: "max"
2669
+ };
2670
+ var ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH = {
2671
+ low: "low",
2672
+ medium: "medium",
2673
+ high: "high",
2674
+ max: "max"
2675
+ };
2413
2676
  var ANTHROPIC_REASONING_MODEL_TABLE = {
2677
+ "claude-opus-4-8": {
2678
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2679
+ budgetPresetByLevel: {
2680
+ low: "reasoning_low",
2681
+ medium: "reasoning_medium",
2682
+ high: "reasoning_high",
2683
+ xhigh: "reasoning_xhigh",
2684
+ max: "reasoning_xhigh"
2685
+ },
2686
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2687
+ },
2414
2688
  "claude-opus-4-7": {
2415
- supportedLevels: ["low", "medium", "high", "xhigh"],
2689
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2416
2690
  budgetPresetByLevel: {
2417
2691
  low: "reasoning_low",
2418
2692
  medium: "reasoning_medium",
2419
2693
  high: "reasoning_high",
2420
- xhigh: "reasoning_xhigh"
2421
- }
2694
+ xhigh: "reasoning_xhigh",
2695
+ max: "reasoning_xhigh"
2696
+ },
2697
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2422
2698
  },
2423
2699
  "claude-opus-4-6": {
2424
- supportedLevels: ["low", "medium", "high", "xhigh"],
2700
+ supportedLevels: ["low", "medium", "high", "max"],
2425
2701
  budgetPresetByLevel: {
2426
2702
  low: "reasoning_low",
2427
2703
  medium: "reasoning_medium",
2428
2704
  high: "reasoning_high",
2429
- xhigh: "reasoning_xhigh"
2430
- }
2705
+ max: "reasoning_xhigh"
2706
+ },
2707
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2431
2708
  },
2432
2709
  "claude-opus-4-5": {
2433
2710
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2448,13 +2725,14 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2448
2725
  }
2449
2726
  },
2450
2727
  "claude-sonnet-4-6": {
2451
- supportedLevels: ["low", "medium", "high", "xhigh"],
2728
+ supportedLevels: ["low", "medium", "high", "max"],
2452
2729
  budgetPresetByLevel: {
2453
2730
  low: "reasoning_low",
2454
2731
  medium: "reasoning_medium",
2455
2732
  high: "reasoning_high",
2456
- xhigh: "reasoning_xhigh"
2457
- }
2733
+ max: "reasoning_xhigh"
2734
+ },
2735
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2458
2736
  },
2459
2737
  "claude-sonnet-4-5": {
2460
2738
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2491,8 +2769,12 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2491
2769
  }
2492
2770
  }
2493
2771
  };
2494
- var ANTHROPIC_ADAPTIVE_THINKING_MODELS = /* @__PURE__ */ new Set(["claude-opus-4-7"]);
2495
- var toAnthropicOutputEffort = (level) => level === "xhigh" ? "max" : level;
2772
+ var ANTHROPIC_ADAPTIVE_THINKING_MODELS = /* @__PURE__ */ new Set([
2773
+ "claude-opus-4-8",
2774
+ "claude-opus-4-7",
2775
+ "claude-opus-4-6",
2776
+ "claude-sonnet-4-6"
2777
+ ]);
2496
2778
  var normalizeRequestedReasoning = (value) => value ?? DEFAULT_REASONING_LEVEL;
2497
2779
  var resolveNearestSupportedLevel = (requested, supportedLevels) => {
2498
2780
  const supported = new Set(supportedLevels);
@@ -2526,12 +2808,14 @@ var resolveReasoningAgainstSupportedLevels = ({
2526
2808
  supportedLevels
2527
2809
  };
2528
2810
  };
2529
- var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(model);
2811
+ var normalizeResponsesModelId = (model) => model.startsWith("openai/") ? model.slice("openai/".length) : model;
2812
+ var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2813
+ var supportsResponsesMax = (model) => RESPONSES_MAX_SUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2530
2814
  var resolveResponsesReasoning = ({
2531
2815
  model,
2532
2816
  requested
2533
2817
  }) => {
2534
- const supportedLevels = supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER : REASONING_LEVEL_ORDER.slice(0, 3);
2818
+ const supportedLevels = supportsResponsesMax(model) ? REASONING_LEVEL_ORDER : supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER.slice(0, 4) : REASONING_LEVEL_ORDER.slice(0, 3);
2535
2819
  const resolution = resolveReasoningAgainstSupportedLevels({
2536
2820
  requested,
2537
2821
  supportedLevels
@@ -2571,19 +2855,18 @@ var resolveAnthropicReasoning = ({
2571
2855
  );
2572
2856
  }
2573
2857
  const budgetTokens = ANTHROPIC_BUDGET_PRESET_TOKENS[preset];
2858
+ const outputEffort = profile.outputEffortByLevel?.[resolution.applied];
2574
2859
  return {
2575
2860
  ...resolution,
2576
2861
  ...ANTHROPIC_ADAPTIVE_THINKING_MODELS.has(model) ? {
2577
- thinking: { type: "adaptive" },
2578
- outputConfig: {
2579
- effort: toAnthropicOutputEffort(resolution.applied)
2580
- }
2862
+ thinking: { type: "adaptive" }
2581
2863
  } : {
2582
2864
  thinking: {
2583
2865
  type: "enabled",
2584
2866
  budget_tokens: budgetTokens
2585
2867
  }
2586
2868
  },
2869
+ ...outputEffort ? { outputConfig: { effort: outputEffort } } : {},
2587
2870
  budgetPreset: preset,
2588
2871
  usedFallbackModelProfile
2589
2872
  };
@@ -2599,6 +2882,27 @@ var resolveAnthropicMaxTokens = ({
2599
2882
  }
2600
2883
  return normalizedBudget + ANTHROPIC_MAX_TOKENS_FALLBACK_HEADROOM;
2601
2884
  };
2885
+ var resolveZaiReasoning = ({
2886
+ requested
2887
+ }) => {
2888
+ const normalizedRequested = normalizeRequestedReasoning(requested);
2889
+ if (normalizedRequested === "xhigh" || normalizedRequested === "max") {
2890
+ return {
2891
+ requested: normalizedRequested,
2892
+ applied: normalizedRequested,
2893
+ effort: "max",
2894
+ fallbackApplied: false,
2895
+ supportedLevels: REASONING_LEVEL_ORDER
2896
+ };
2897
+ }
2898
+ return {
2899
+ requested: normalizedRequested,
2900
+ applied: "high",
2901
+ effort: "high",
2902
+ fallbackApplied: normalizedRequested === "low" || normalizedRequested === "medium",
2903
+ supportedLevels: REASONING_LEVEL_ORDER
2904
+ };
2905
+ };
2602
2906
 
2603
2907
  // src/model-registry.ts
2604
2908
  var import_core3 = require("@codelia/core");
@@ -2687,7 +2991,8 @@ var withOpenRouterDynamicModel = (registry, llm, entry) => {
2687
2991
  openai: { ...registry.aliasesByProvider.openai },
2688
2992
  anthropic: { ...registry.aliasesByProvider.anthropic },
2689
2993
  openrouter: { ...registry.aliasesByProvider.openrouter },
2690
- google: { ...registry.aliasesByProvider.google }
2994
+ google: { ...registry.aliasesByProvider.google },
2995
+ zai: { ...registry.aliasesByProvider.zai }
2691
2996
  }
2692
2997
  };
2693
2998
  (0, import_core3.registerModels)(next, [
@@ -2740,7 +3045,7 @@ var buildModelRegistry = async (llm, options = {}) => {
2740
3045
  // src/permissions/approval-mode.ts
2741
3046
  var import_node_fs4 = require("fs");
2742
3047
  var import_node_path4 = __toESM(require("path"), 1);
2743
- var import_shared_types = require("@codelia/shared-types");
3048
+ var import_shared_types3 = require("@codelia/shared-types");
2744
3049
  var import_storage4 = require("@codelia/storage");
2745
3050
  var normalizePath = async (value) => {
2746
3051
  const absolute = import_node_path4.default.resolve(value);
@@ -2761,7 +3066,7 @@ var parseApprovalModeOrThrow = (raw, source) => {
2761
3066
  `Invalid ${source}: missing value (expected ${APPROVAL_MODE_HINT})`
2762
3067
  );
2763
3068
  }
2764
- const parsed = (0, import_shared_types.parseApprovalMode)(raw);
3069
+ const parsed = (0, import_shared_types3.parseApprovalMode)(raw);
2765
3070
  if (!parsed) {
2766
3071
  throw new Error(
2767
3072
  `Invalid ${source}: '${raw}' (expected ${APPROVAL_MODE_HINT})`
@@ -2798,13 +3103,13 @@ var resolvePolicyApprovalMode = (policy, projectKey) => {
2798
3103
  if (!policy) {
2799
3104
  return void 0;
2800
3105
  }
2801
- const projectMode = (0, import_shared_types.parseApprovalMode)(
3106
+ const projectMode = (0, import_shared_types3.parseApprovalMode)(
2802
3107
  policy.projects?.[projectKey]?.approval_mode
2803
3108
  );
2804
3109
  if (projectMode) {
2805
3110
  return { approvalMode: projectMode, source: "project" };
2806
3111
  }
2807
- const defaultMode = (0, import_shared_types.parseApprovalMode)(policy.default?.approval_mode);
3112
+ const defaultMode = (0, import_shared_types3.parseApprovalMode)(policy.default?.approval_mode);
2808
3113
  if (defaultMode) {
2809
3114
  return { approvalMode: defaultMode, source: "default" };
2810
3115
  }
@@ -7696,7 +8001,7 @@ var normalizeOptionalText = (value) => {
7696
8001
  return trimmed.length ? trimmed : void 0;
7697
8002
  };
7698
8003
  var isTodoStatus = (value) => value === "pending" || value === "in_progress" || value === "completed";
7699
- var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8004
+ var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7700
8005
  var normalizeTodoIdBase = (value) => {
7701
8006
  const trimmed = value.trim().toLowerCase();
7702
8007
  const withHyphen = trimmed.replace(/\s+/g, "-");
@@ -7756,7 +8061,7 @@ var readTodosFromSessionMeta = (meta) => {
7756
8061
  if (!Array.isArray(raw)) return [];
7757
8062
  const todos = [];
7758
8063
  for (const entry of raw) {
7759
- if (!isRecord3(entry)) continue;
8064
+ if (!isRecord4(entry)) continue;
7760
8065
  const status = entry.status;
7761
8066
  if (!isTodoStatus(status)) continue;
7762
8067
  const content = typeof entry.content === "string" ? entry.content : "";
@@ -8746,6 +9051,12 @@ var buildHostedSearchToolDefinitions = (provider, options) => {
8746
9051
  };
8747
9052
  var OPENAI_OAUTH_ORIGINATOR = "codelia";
8748
9053
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
9054
+ var loadHostTools = async (providers) => {
9055
+ const groups = await Promise.all(
9056
+ providers.map((provider) => Promise.resolve(provider.getTools()))
9057
+ );
9058
+ return groups.flat();
9059
+ };
8749
9060
  var buildOpenAiClientOptions = (authResolver, auth) => {
8750
9061
  if (auth.method === "api_key") {
8751
9062
  return { apiKey: auth.api_key };
@@ -8753,6 +9064,9 @@ var buildOpenAiClientOptions = (authResolver, auth) => {
8753
9064
  let accountId = auth.oauth.account_id;
8754
9065
  const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
8755
9066
  const apiKey = async () => {
9067
+ if (!authResolver.getOpenAiAccessToken) {
9068
+ throw new Error("OpenAI OAuth token refresh is unavailable");
9069
+ }
8756
9070
  const result = await authResolver.getOpenAiAccessToken();
8757
9071
  accountId = result.accountId ?? accountId;
8758
9072
  return result.token;
@@ -8818,6 +9132,13 @@ var buildOpenRouterClientOptions = (auth) => {
8818
9132
  ...Object.keys(headers).length ? { defaultHeaders: headers } : {}
8819
9133
  };
8820
9134
  };
9135
+ var buildZaiClientOptions = (auth) => {
9136
+ const baseURL = readEnvValue("ZAI_BASE_URL");
9137
+ return {
9138
+ apiKey: requireApiKeyAuth("Z.ai", auth),
9139
+ ...baseURL ? { baseURL } : {}
9140
+ };
9141
+ };
8821
9142
  var resolveModelMaxTokensFromEntry = (entry) => {
8822
9143
  const limits = entry?.limits;
8823
9144
  const candidates = [
@@ -8848,7 +9169,10 @@ var resolveAnthropicStaticModelMaxTokens = (model) => {
8848
9169
  }
8849
9170
  return null;
8850
9171
  };
8851
- var resolveAnthropicModelMaxTokens = async (model) => {
9172
+ var resolveAnthropicModelMaxTokens = async (model, options) => {
9173
+ if (!options.useMetadata) {
9174
+ return resolveAnthropicStaticModelMaxTokens(model);
9175
+ }
8852
9176
  const metadataService = new import_model_metadata2.ModelMetadataServiceImpl({
8853
9177
  storagePathService: new import_storage8.StoragePathServiceImpl()
8854
9178
  });
@@ -8896,7 +9220,7 @@ var requestApprovalModeStartupSelection = async (state, projectKey) => {
8896
9220
  items: APPROVAL_MODE_STARTUP_PICK_ITEMS,
8897
9221
  multi: false
8898
9222
  });
8899
- const picked = (0, import_shared_types2.parseApprovalMode)(selection?.ids?.[0]);
9223
+ const picked = (0, import_shared_types4.parseApprovalMode)(selection?.ids?.[0]);
8900
9224
  if (!picked) {
8901
9225
  (0, import_logger.log)(`approval_mode startup selection skipped project=${projectKey}`);
8902
9226
  return null;
@@ -9041,7 +9365,12 @@ var requestMcpOAuthTokens = async (state, serverId, oauth2, errorMessage) => {
9041
9365
  var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMessage) => {
9042
9366
  const runId = state.activeRunId ?? void 0;
9043
9367
  if (runId) {
9044
- sendRunStatus(runId, "awaiting_ui", `MCP auth required: ${serverId}`);
9368
+ sendRunStatus(
9369
+ state,
9370
+ runId,
9371
+ "awaiting_ui",
9372
+ `MCP auth required: ${serverId}`
9373
+ );
9045
9374
  }
9046
9375
  try {
9047
9376
  const tokens = await requestMcpOAuthTokens(
@@ -9056,7 +9385,7 @@ var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMe
9056
9385
  return tokens;
9057
9386
  } finally {
9058
9387
  if (runId) {
9059
- sendRunStatus(runId, "running");
9388
+ sendRunStatus(state, runId, "running");
9060
9389
  }
9061
9390
  }
9062
9391
  };
@@ -9066,60 +9395,85 @@ var createAgentFactory = (state, options = {}) => {
9066
9395
  if (state.agent) return state.agent;
9067
9396
  if (inFlight) return inFlight;
9068
9397
  inFlight = (async () => {
9069
- const sandboxRoot = state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
9070
- const approvalModeResolution = await resolveApprovalModeForRuntime({
9071
- workingDir: sandboxRoot,
9072
- runtimeSandboxRoot: sandboxRoot,
9073
- requestStartupSelection: async ({ projectKey }) => {
9074
- return requestApprovalModeStartupSelection(state, projectKey);
9075
- },
9076
- deferStartupSelectionPersist: true
9077
- });
9078
- const ctx = await SandboxContext.create(sandboxRoot, {
9079
- approvalMode: approvalModeResolution.approvalMode
9080
- });
9081
- (0, import_logger.log)(
9082
- `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
9083
- );
9084
- const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
9085
- state.agentsResolver = agentsResolver;
9086
- let skillsConfig;
9087
- let executionEnvironmentConfig;
9088
- try {
9089
- [skillsConfig, executionEnvironmentConfig] = await Promise.all([
9090
- resolveSkillsConfig(ctx.workingDir),
9091
- resolveExecutionEnvironmentConfig(ctx.workingDir)
9092
- ]);
9093
- } catch (error) {
9094
- const message = error instanceof Error ? error.message : String(error);
9095
- throw new Error(message);
9398
+ const environment = state.effectiveEnvironment;
9399
+ const workspaceRoot = environment.workspace.root ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? void 0;
9400
+ const localRuntimeEnabled = environment.workspace.filesystem === "enabled" || environment.workspace.process === "runtime" || environment.tools.builtin === "full-coding-agent";
9401
+ let approvalModeResolution = {
9402
+ approvalMode: "minimal",
9403
+ source: "environment",
9404
+ projectKey: workspaceRoot ?? "disabled-workspace"
9405
+ };
9406
+ let ctx = null;
9407
+ let sandboxKey = null;
9408
+ let agentsResolver = null;
9409
+ let skillsResolver = null;
9410
+ if (localRuntimeEnabled) {
9411
+ const sandboxRoot = workspaceRoot ?? process.cwd();
9412
+ approvalModeResolution = await resolveApprovalModeForRuntime({
9413
+ workingDir: sandboxRoot,
9414
+ runtimeSandboxRoot: sandboxRoot,
9415
+ requestStartupSelection: async ({ projectKey }) => {
9416
+ return requestApprovalModeStartupSelection(state, projectKey);
9417
+ },
9418
+ deferStartupSelectionPersist: true
9419
+ });
9420
+ ctx = await SandboxContext.create(sandboxRoot, {
9421
+ approvalMode: approvalModeResolution.approvalMode
9422
+ });
9423
+ (0, import_logger.log)(
9424
+ `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
9425
+ );
9426
+ state.runtimeWorkingDir = ctx.workingDir;
9427
+ state.runtimeSandboxRoot = ctx.rootDir;
9428
+ sandboxKey = createSandboxKey(ctx);
9429
+ }
9430
+ if (environment.context.projectInstructions === "from-workspace" && workspaceRoot) {
9431
+ agentsResolver = state.agentsResolver ?? await AgentsResolver.create(workspaceRoot);
9432
+ state.agentsResolver = agentsResolver;
9433
+ }
9434
+ if (environment.context.skills === "from-config" && workspaceRoot) {
9435
+ let skillsConfig;
9436
+ try {
9437
+ skillsConfig = await resolveEnvironmentSkillsConfig(
9438
+ state,
9439
+ workspaceRoot
9440
+ );
9441
+ } catch (error) {
9442
+ const message = error instanceof Error ? error.message : String(error);
9443
+ throw new Error(message);
9444
+ }
9445
+ skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
9446
+ workingDir: workspaceRoot,
9447
+ config: skillsConfig
9448
+ });
9449
+ state.skillsResolver = skillsResolver;
9450
+ state.updateSkillsSnapshot(workspaceRoot, skillsResolver.getSnapshot());
9096
9451
  }
9097
- const skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
9098
- workingDir: ctx.workingDir,
9099
- config: skillsConfig
9100
- });
9101
- state.skillsResolver = skillsResolver;
9102
- state.updateSkillsSnapshot(ctx.workingDir, skillsResolver.getSnapshot());
9103
- state.runtimeWorkingDir = ctx.workingDir;
9104
- state.runtimeSandboxRoot = ctx.rootDir;
9105
9452
  state.approvalMode = approvalModeResolution.approvalMode;
9106
- const sandboxKey = createSandboxKey(ctx);
9453
+ const toolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore ?? (environment.persistence.mode === "runtime" ? new import_storage8.ToolOutputCacheStoreImpl() : null);
9107
9454
  const todoSessionContextKey = createToolSessionContextKey(
9108
9455
  () => state.sessionId
9109
9456
  );
9110
- const agentsResolverKey = createAgentsResolverKey(agentsResolver);
9111
- const skillsResolverKey = createSkillsResolverKey(skillsResolver);
9112
- const toolOutputCacheStore = new import_storage8.ToolOutputCacheStoreImpl();
9113
- const baseLocalTools = createTools(
9114
- sandboxKey,
9115
- agentsResolverKey,
9116
- skillsResolverKey,
9117
- {
9118
- toolOutputCacheStore,
9119
- todoSessionContextKey,
9120
- taskManager: options.taskManager
9457
+ let baseLocalTools = [];
9458
+ if (environment.tools.builtin === "full-coding-agent") {
9459
+ if (!ctx || !sandboxKey || !agentsResolver || !skillsResolver) {
9460
+ throw new Error(
9461
+ "full coding-agent tools require local sandbox, AGENTS, and skills context"
9462
+ );
9121
9463
  }
9122
- );
9464
+ const agentsResolverKey = createAgentsResolverKey(agentsResolver);
9465
+ const skillsResolverKey = createSkillsResolverKey(skillsResolver);
9466
+ baseLocalTools = createTools(
9467
+ sandboxKey,
9468
+ agentsResolverKey,
9469
+ skillsResolverKey,
9470
+ {
9471
+ toolOutputCacheStore,
9472
+ todoSessionContextKey,
9473
+ taskManager: options.taskManager
9474
+ }
9475
+ );
9476
+ }
9123
9477
  const editTool = baseLocalTools.find(
9124
9478
  (tool) => tool.definition.name === "edit"
9125
9479
  );
@@ -9127,7 +9481,7 @@ var createAgentFactory = (state, options = {}) => {
9127
9481
  (tool) => tool.definition.name === "apply_patch"
9128
9482
  );
9129
9483
  let mcpTools = [];
9130
- if (options.mcpManager) {
9484
+ if (environment.tools.mcp === "from-config" && options.mcpManager) {
9131
9485
  try {
9132
9486
  mcpTools = await options.mcpManager.getTools({
9133
9487
  onStatus: (message) => {
@@ -9146,12 +9500,24 @@ var createAgentFactory = (state, options = {}) => {
9146
9500
  (0, import_logger.log)(`failed to load mcp tools: ${String(error)}`);
9147
9501
  }
9148
9502
  }
9149
- const baseSystemPrompt = await loadSystemPrompt(ctx.workingDir);
9150
- const executionEnvironmentContext = await buildExecutionEnvironmentContext({
9151
- workingDir: ctx.workingDir,
9152
- sandboxRoot: ctx.rootDir,
9153
- config: executionEnvironmentConfig
9154
- });
9503
+ const hostTools = environment.tools.host === "enabled" ? await loadHostTools(environment.adapters.toolProviders ?? []) : [];
9504
+ const hostToolNames = new Set(hostTools.map((tool) => tool.name));
9505
+ const baseSystemPrompt = await loadEnvironmentSystemPrompt(
9506
+ state,
9507
+ workspaceRoot
9508
+ );
9509
+ let executionEnvironmentContext = null;
9510
+ if (environment.context.executionEnvironment === "from-config" && workspaceRoot && ctx) {
9511
+ const executionEnvironmentConfig = await resolveEnvironmentExecutionEnvironmentConfig(
9512
+ state,
9513
+ workspaceRoot
9514
+ );
9515
+ executionEnvironmentContext = await buildExecutionEnvironmentContext({
9516
+ workingDir: workspaceRoot,
9517
+ sandboxRoot: ctx.rootDir,
9518
+ config: executionEnvironmentConfig
9519
+ });
9520
+ }
9155
9521
  state.executionEnvironmentContext = executionEnvironmentContext;
9156
9522
  if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
9157
9523
  alreadyLogged: state.executionEnvironmentDebugLogged
@@ -9164,16 +9530,16 @@ var createAgentFactory = (state, options = {}) => {
9164
9530
  );
9165
9531
  const withAgentsContext = appendInitialAgentsContext(
9166
9532
  withExecutionEnvironment,
9167
- agentsResolver.buildInitialContext()
9533
+ agentsResolver?.buildInitialContext() ?? null
9168
9534
  );
9169
9535
  const systemPrompt = appendInitialSkillsCatalog(
9170
9536
  withAgentsContext,
9171
- await skillsResolver.buildInitialContext()
9537
+ skillsResolver ? await skillsResolver.buildInitialContext() : null
9172
9538
  );
9173
9539
  state.systemPrompt = systemPrompt;
9174
9540
  let permissionsConfig;
9175
9541
  try {
9176
- permissionsConfig = await resolvePermissionsConfig(ctx.workingDir);
9542
+ permissionsConfig = environment.config.source === "disabled" || !workspaceRoot ? void 0 : await resolveEnvironmentPermissionsConfig(state, workspaceRoot);
9177
9543
  } catch (error) {
9178
9544
  const message = error instanceof Error ? error.message : String(error);
9179
9545
  throw new Error(message);
@@ -9182,42 +9548,56 @@ var createAgentFactory = (state, options = {}) => {
9182
9548
  approvalMode: approvalModeResolution.approvalMode,
9183
9549
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
9184
9550
  user: permissionsConfig,
9185
- bashPathGuard: {
9186
- rootDir: ctx.rootDir,
9187
- workingDir: ctx.workingDir
9188
- }
9551
+ ...ctx ? {
9552
+ bashPathGuard: {
9553
+ rootDir: ctx.rootDir,
9554
+ workingDir: ctx.workingDir
9555
+ }
9556
+ } : {}
9189
9557
  });
9190
9558
  (0, import_logger.log)(
9191
9559
  `approval_mode resolved=${approvalModeResolution.approvalMode} source=${approvalModeResolution.source} project=${approvalModeResolution.projectKey}`
9192
9560
  );
9193
9561
  let modelConfig;
9194
9562
  try {
9195
- modelConfig = await resolveModelConfig(ctx.workingDir);
9563
+ modelConfig = await resolveEffectiveModelConfig(state, workspaceRoot);
9196
9564
  } catch (error) {
9197
9565
  const message = error instanceof Error ? error.message : String(error);
9198
9566
  throw new Error(message);
9199
9567
  }
9200
- const authResolver = await AuthResolver.create(state, import_logger.log);
9568
+ const authResolver = await createEnvironmentAuthResolver(state, import_logger.log);
9201
9569
  const provider = await authResolver.resolveProvider(modelConfig.provider);
9202
9570
  const providerAuth = await authResolver.resolveProviderAuth(provider);
9203
- const searchConfig = await resolveSearchConfig(ctx.workingDir);
9204
- const hostedSearchDefinitions = buildHostedSearchToolDefinitions(
9205
- provider,
9206
- searchConfig
9207
- );
9208
- if (searchConfig.mode === "native" && hostedSearchDefinitions.length === 0) {
9209
- throw new Error(
9210
- `search.mode=native is enabled, but native search is unavailable for provider '${provider}'.`
9571
+ let hostedSearchDefinitions = [];
9572
+ let localSearchTools = [];
9573
+ if (environment.tools.search === "from-config") {
9574
+ const searchConfig = await resolveEnvironmentSearchConfig(
9575
+ state,
9576
+ workspaceRoot
9211
9577
  );
9578
+ hostedSearchDefinitions = buildHostedSearchToolDefinitions(
9579
+ provider,
9580
+ searchConfig
9581
+ );
9582
+ if (searchConfig.mode === "native" && hostedSearchDefinitions.length === 0) {
9583
+ throw new Error(
9584
+ `search.mode=native is enabled, but native search is unavailable for provider '${provider}'.`
9585
+ );
9586
+ }
9587
+ const useLocalSearchTool = searchConfig.mode === "local" || searchConfig.mode === "auto" && hostedSearchDefinitions.length === 0;
9588
+ localSearchTools = useLocalSearchTool ? [
9589
+ createSearchTool({
9590
+ defaultBackend: searchConfig.local.backend,
9591
+ braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
9592
+ })
9593
+ ] : [];
9212
9594
  }
9213
- const useLocalSearchTool = searchConfig.mode === "local" || searchConfig.mode === "auto" && hostedSearchDefinitions.length === 0;
9214
- const localSearchTools = useLocalSearchTool ? [
9215
- createSearchTool({
9216
- defaultBackend: searchConfig.local.backend,
9217
- braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
9218
- })
9219
- ] : [];
9220
- const tools = [...baseLocalTools, ...localSearchTools, ...mcpTools];
9595
+ const tools = [
9596
+ ...baseLocalTools,
9597
+ ...localSearchTools,
9598
+ ...mcpTools,
9599
+ ...hostTools
9600
+ ];
9221
9601
  state.tools = tools;
9222
9602
  state.toolDefinitions = [
9223
9603
  ...tools.map((tool) => tool.definition),
@@ -9292,7 +9672,12 @@ var createAgentFactory = (state, options = {}) => {
9292
9672
  );
9293
9673
  }
9294
9674
  });
9295
- const modelMaxTokens = await resolveAnthropicModelMaxTokens(modelName);
9675
+ const modelMaxTokens = await resolveAnthropicModelMaxTokens(
9676
+ modelName,
9677
+ {
9678
+ useMetadata: environment.persistence.mode === "runtime"
9679
+ }
9680
+ );
9296
9681
  const maxTokens = resolveAnthropicMaxTokens({
9297
9682
  thinkingBudgetTokens: reasoning.thinking.type === "enabled" ? reasoning.thinking.budget_tokens : 0,
9298
9683
  modelLimitMaxTokens: modelMaxTokens
@@ -9325,14 +9710,33 @@ var createAgentFactory = (state, options = {}) => {
9325
9710
  });
9326
9711
  break;
9327
9712
  }
9713
+ case "zai": {
9714
+ const modelName = modelConfig.name ?? import_core21.ZAI_DEFAULT_MODEL;
9715
+ resolvedModelName = modelName;
9716
+ const reasoning = resolveZaiReasoning({
9717
+ requested: requestedReasoning
9718
+ });
9719
+ const providerModelName = (0, import_core21.resolveProviderModelId)(import_core21.DEFAULT_MODEL_REGISTRY, modelName, "zai") ?? modelName;
9720
+ const supportsReasoningEffort = import_core21.ZAI_REASONING_EFFORT_MODELS.has(providerModelName);
9721
+ llm = new import_core21.ChatZai({
9722
+ ...buildZaiClientOptions(providerAuth),
9723
+ model: modelName,
9724
+ reasoningEffort: supportsReasoningEffort ? reasoning.effort : null,
9725
+ reasoningLevelRequested: reasoning.requested,
9726
+ reasoningLevelApplied: supportsReasoningEffort ? reasoning.applied : void 0,
9727
+ reasoningFallbackApplied: supportsReasoningEffort ? reasoning.fallbackApplied : void 0
9728
+ });
9729
+ break;
9730
+ }
9328
9731
  default:
9329
9732
  throw new Error(`Unsupported model.provider: ${provider}`);
9330
9733
  }
9331
9734
  state.currentModelProvider = provider;
9332
9735
  state.currentModelName = resolvedModelName;
9333
- const modelRegistry = await buildModelRegistry(llm, {
9736
+ state.currentModelSource = modelConfig.source;
9737
+ const modelRegistry = environment.persistence.mode === "runtime" ? await buildModelRegistry(llm, {
9334
9738
  strict: provider !== "openrouter"
9335
- });
9739
+ }) : import_core21.DEFAULT_MODEL_REGISTRY;
9336
9740
  const totalBudgetTrimEnabled = envTruthy(
9337
9741
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
9338
9742
  );
@@ -9347,6 +9751,12 @@ var createAgentFactory = (state, options = {}) => {
9347
9751
  },
9348
9752
  services: { toolOutputCacheStore },
9349
9753
  canExecuteTool: async (call, rawArgs, toolCtx) => {
9754
+ if (hostToolNames.has(call.function.name)) {
9755
+ (0, import_logger.debugLog)(
9756
+ `permission.evaluate tool=${call.function.name} decision=allow reason=host-tool`
9757
+ );
9758
+ return { decision: "allow" };
9759
+ }
9350
9760
  if (state.autoApprovedClientToolNames.has(call.function.name)) {
9351
9761
  (0, import_logger.debugLog)(
9352
9762
  `permission.evaluate tool=${call.function.name} decision=allow reason=client-tool-auto-approved`
@@ -9399,6 +9809,9 @@ var createAgentFactory = (state, options = {}) => {
9399
9809
  content
9400
9810
  }) ?? previewLanguage;
9401
9811
  try {
9812
+ if (!sandboxKey) {
9813
+ throw new Error("sandbox is unavailable");
9814
+ }
9402
9815
  const sandbox = await getSandboxContext(toolCtx, sandboxKey);
9403
9816
  const resolved = sandbox.resolvePath(filePath);
9404
9817
  let before = "";
@@ -9521,6 +9934,7 @@ var createAgentFactory = (state, options = {}) => {
9521
9934
  tool_call_id: call.id
9522
9935
  });
9523
9936
  await sendRunStatusAsync(
9937
+ state,
9524
9938
  runId,
9525
9939
  "awaiting_ui",
9526
9940
  "waiting for confirmation"
@@ -9536,7 +9950,7 @@ var createAgentFactory = (state, options = {}) => {
9536
9950
  allow_reason: true
9537
9951
  });
9538
9952
  if (runId) {
9539
- sendRunStatus(runId, "running");
9953
+ sendRunStatus(state, runId, "running");
9540
9954
  }
9541
9955
  if (!confirmResult?.ok) {
9542
9956
  const providedReason = confirmResult?.reason?.trim() ?? "";
@@ -9556,11 +9970,13 @@ var createAgentFactory = (state, options = {}) => {
9556
9970
  `permission.remember tool=${call.function.name} rules=${rules.length}`
9557
9971
  );
9558
9972
  if (rules.length) {
9559
- void appendPermissionAllowRules(ctx.workingDir, rules).catch(
9560
- (error) => {
9561
- (0, import_logger.log)(`failed to persist permission: ${String(error)}`);
9562
- }
9563
- );
9973
+ void appendEnvironmentPermissionAllowRules(
9974
+ state,
9975
+ workspaceRoot,
9976
+ rules
9977
+ ).catch((error) => {
9978
+ (0, import_logger.log)(`failed to persist permission: ${String(error)}`);
9979
+ });
9564
9980
  }
9565
9981
  }
9566
9982
  return { decision: "allow" };
@@ -9580,39 +9996,246 @@ var createAgentFactory = (state, options = {}) => {
9580
9996
  };
9581
9997
  };
9582
9998
 
9583
- // src/mcp/auth-store.ts
9584
- var import_storage9 = require("@codelia/storage");
9585
-
9586
- // src/mcp/manager.ts
9587
- var import_protocol = require("@codelia/protocol");
9588
-
9589
- // src/mcp/jsonrpc.ts
9590
- var JSON_RPC_VERSION = "2.0";
9591
- var CANCELLED_METHOD = "notifications/cancelled";
9592
- var createAbortError = (message) => {
9593
- const error = new Error(message);
9594
- error.name = "AbortError";
9595
- return error;
9596
- };
9597
- var isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9598
- var describeError = (error) => error instanceof Error ? error.message : String(error);
9599
- var normalizeRpcError = (method, error) => new Error(`MCP ${method} error (${error.code}): ${error.message}`);
9600
- var toLine = (value) => `${JSON.stringify(value)}
9601
- `;
9602
- var buildCancelParams = (requestId, reason) => ({
9603
- requestId,
9604
- reason
9999
+ // src/environment.ts
10000
+ var import_node_path15 = __toESM(require("path"), 1);
10001
+ var cloneContract = (contract) => ({
10002
+ workspace: { ...contract.workspace },
10003
+ context: { ...contract.context },
10004
+ auth: { ...contract.auth },
10005
+ config: { ...contract.config },
10006
+ tools: { ...contract.tools },
10007
+ persistence: { ...contract.persistence },
10008
+ events: { ...contract.events }
9605
10009
  });
9606
-
9607
- // src/mcp/sse.ts
9608
- var import_eventsource_parser = require("eventsource-parser");
9609
- var isEventStreamResponse = (response) => {
9610
- const contentType = response.headers.get("Content-Type")?.toLowerCase() ?? "";
9611
- return contentType.includes("text/event-stream");
10010
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? import_node_path15.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
10011
+ var runtimeEnvironmentPresets = {
10012
+ "tui-local": {
10013
+ workspace: {
10014
+ filesystem: "enabled",
10015
+ process: "runtime"
10016
+ },
10017
+ context: {
10018
+ systemPrompt: "runtime-default",
10019
+ projectInstructions: "from-workspace",
10020
+ skills: "from-config",
10021
+ executionEnvironment: "from-config"
10022
+ },
10023
+ auth: { model: "runtime-default" },
10024
+ config: { source: "runtime-default" },
10025
+ tools: {
10026
+ builtin: "full-coding-agent",
10027
+ search: "from-config",
10028
+ mcp: "from-config",
10029
+ host: "disabled"
10030
+ },
10031
+ persistence: { mode: "runtime" },
10032
+ events: { live: "json-rpc" }
10033
+ },
10034
+ "embedded-no-local-tools": {
10035
+ workspace: {
10036
+ filesystem: "disabled",
10037
+ process: "disabled"
10038
+ },
10039
+ context: {
10040
+ systemPrompt: "host",
10041
+ projectInstructions: "disabled",
10042
+ skills: "disabled",
10043
+ executionEnvironment: "disabled"
10044
+ },
10045
+ auth: { model: "host" },
10046
+ config: { source: "host" },
10047
+ tools: {
10048
+ builtin: "none",
10049
+ search: "disabled",
10050
+ mcp: "disabled",
10051
+ host: "enabled"
10052
+ },
10053
+ persistence: { mode: "volatile" },
10054
+ events: { live: "host" }
10055
+ }
9612
10056
  };
9613
- var parseSsePayload = (event) => {
9614
- const payload = event.data.trim();
9615
- if (!payload || payload === "[DONE]") return void 0;
10057
+ var expandEnvironmentInput = (input) => {
10058
+ if (!input) {
10059
+ return {
10060
+ contract: cloneContract(runtimeEnvironmentPresets["tui-local"]),
10061
+ sourcePreset: "tui-local"
10062
+ };
10063
+ }
10064
+ if ("preset" in input) {
10065
+ return {
10066
+ contract: cloneContract(runtimeEnvironmentPresets[input.preset]),
10067
+ sourcePreset: input.preset
10068
+ };
10069
+ }
10070
+ return { contract: cloneContract(input.contract) };
10071
+ };
10072
+ var requireAdapter = (condition, name, reason) => {
10073
+ if (!condition) return;
10074
+ throw new Error(`Runtime environment requires adapters.${name}: ${reason}`);
10075
+ };
10076
+ var rejectContract = (condition, reason) => {
10077
+ if (!condition) return;
10078
+ throw new Error(`Invalid runtime environment: ${reason}`);
10079
+ };
10080
+ var resolveToolNames = (contract) => {
10081
+ const modelVisible = [];
10082
+ const operatorOnly = [];
10083
+ const disabled = [];
10084
+ if (contract.tools.builtin === "full-coding-agent") {
10085
+ modelVisible.push("builtin:full-coding-agent");
10086
+ } else {
10087
+ disabled.push("builtin");
10088
+ }
10089
+ if (contract.tools.search === "from-config") {
10090
+ modelVisible.push("search:from-config");
10091
+ } else {
10092
+ disabled.push("search");
10093
+ }
10094
+ if (contract.tools.mcp === "from-config") {
10095
+ modelVisible.push("mcp:from-config");
10096
+ operatorOnly.push("mcp.list");
10097
+ } else {
10098
+ disabled.push("mcp");
10099
+ }
10100
+ if (contract.tools.host === "enabled") {
10101
+ modelVisible.push("host-tools");
10102
+ } else {
10103
+ disabled.push("host-tools");
10104
+ }
10105
+ if (contract.workspace.process === "runtime") {
10106
+ operatorOnly.push("shell.*", "task.*");
10107
+ } else {
10108
+ disabled.push("process");
10109
+ }
10110
+ if (contract.context.skills === "from-config") {
10111
+ operatorOnly.push("skills.list");
10112
+ } else {
10113
+ disabled.push("skills");
10114
+ }
10115
+ if (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config") {
10116
+ operatorOnly.push("context.inspect");
10117
+ } else {
10118
+ disabled.push("local-context");
10119
+ }
10120
+ return { modelVisible, operatorOnly, disabled };
10121
+ };
10122
+ var resolveRuntimeEnvironment = (options = {}) => {
10123
+ const { contract, sourcePreset } = expandEnvironmentInput(
10124
+ options.environment
10125
+ );
10126
+ const adapters = options.adapters ?? {};
10127
+ if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
10128
+ contract.workspace.root = import_node_path15.default.resolve(
10129
+ contract.workspace.root ?? defaultWorkspaceRoot()
10130
+ );
10131
+ } else if (contract.workspace.root) {
10132
+ contract.workspace.root = import_node_path15.default.resolve(contract.workspace.root);
10133
+ }
10134
+ rejectContract(
10135
+ contract.workspace.filesystem === "disabled" && (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config" || contract.tools.builtin === "full-coding-agent" || contract.tools.mcp === "from-config"),
10136
+ "workspace filesystem is disabled but local workspace context/tools are enabled"
10137
+ );
10138
+ rejectContract(
10139
+ contract.workspace.process === "disabled" && contract.tools.builtin === "full-coding-agent",
10140
+ "full coding-agent builtin tools require runtime process support"
10141
+ );
10142
+ rejectContract(
10143
+ contract.tools.builtin === "full-coding-agent" && (contract.context.projectInstructions !== "from-workspace" || contract.context.skills !== "from-config"),
10144
+ "full coding-agent builtin tools require workspace project instructions and skills context"
10145
+ );
10146
+ rejectContract(
10147
+ contract.config.source === "disabled" && (contract.tools.search === "from-config" || contract.tools.mcp === "from-config" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config"),
10148
+ "config source is disabled but config-backed features are enabled"
10149
+ );
10150
+ rejectContract(
10151
+ contract.workspace.process === "runtime" && contract.persistence.mode === "volatile" && !adapters.stores?.taskManager,
10152
+ "runtime process support with volatile persistence requires adapters.stores.taskManager"
10153
+ );
10154
+ requireAdapter(
10155
+ contract.context.systemPrompt === "host" && !adapters.systemPromptProvider,
10156
+ "systemPromptProvider",
10157
+ "context.systemPrompt=host"
10158
+ );
10159
+ requireAdapter(
10160
+ contract.config.source === "host" && !adapters.configProvider,
10161
+ "configProvider",
10162
+ "config.source=host"
10163
+ );
10164
+ requireAdapter(
10165
+ contract.auth.model === "host" && !adapters.credentialProvider,
10166
+ "credentialProvider",
10167
+ "auth.model=host"
10168
+ );
10169
+ requireAdapter(
10170
+ contract.events.live === "host" && !adapters.eventSink,
10171
+ "eventSink",
10172
+ "events.live=host"
10173
+ );
10174
+ requireAdapter(
10175
+ contract.tools.host === "enabled" && !adapters.toolProviders,
10176
+ "toolProviders",
10177
+ "tools.host=enabled"
10178
+ );
10179
+ const resolvedTools = resolveToolNames(contract);
10180
+ const summary = {
10181
+ ...sourcePreset ? { source_preset: sourcePreset } : {},
10182
+ workspace: { ...contract.workspace },
10183
+ context: { ...contract.context },
10184
+ auth: { ...contract.auth },
10185
+ config: { ...contract.config },
10186
+ tools: {
10187
+ ...contract.tools,
10188
+ model_visible: [...resolvedTools.modelVisible],
10189
+ operator_only: [...resolvedTools.operatorOnly],
10190
+ disabled: [...resolvedTools.disabled]
10191
+ },
10192
+ persistence: { ...contract.persistence },
10193
+ events: { ...contract.events }
10194
+ };
10195
+ return {
10196
+ ...contract,
10197
+ ...sourcePreset ? { sourcePreset } : {},
10198
+ adapters,
10199
+ resolvedTools,
10200
+ summary
10201
+ };
10202
+ };
10203
+ var isTuiLocalEnvironment = (environment) => environment.workspace.filesystem === "enabled" && environment.workspace.process === "runtime" && environment.context.systemPrompt === "runtime-default" && environment.context.projectInstructions === "from-workspace" && environment.context.skills === "from-config" && environment.context.executionEnvironment === "from-config" && environment.auth.model === "runtime-default" && environment.config.source === "runtime-default" && environment.tools.builtin === "full-coding-agent" && environment.tools.search === "from-config" && environment.tools.mcp === "from-config" && environment.tools.host === "disabled" && environment.persistence.mode === "runtime" && environment.events.live === "json-rpc";
10204
+ var isProcessEnabled = (environment) => environment.workspace.process === "runtime";
10205
+
10206
+ // src/mcp/auth-store.ts
10207
+ var import_storage9 = require("@codelia/storage");
10208
+
10209
+ // src/mcp/manager.ts
10210
+ var import_protocol = require("@codelia/protocol");
10211
+
10212
+ // src/mcp/jsonrpc.ts
10213
+ var JSON_RPC_VERSION = "2.0";
10214
+ var CANCELLED_METHOD = "notifications/cancelled";
10215
+ var createAbortError = (message) => {
10216
+ const error = new Error(message);
10217
+ error.name = "AbortError";
10218
+ return error;
10219
+ };
10220
+ var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10221
+ var describeError = (error) => error instanceof Error ? error.message : String(error);
10222
+ var normalizeRpcError = (method, error) => new Error(`MCP ${method} error (${error.code}): ${error.message}`);
10223
+ var toLine = (value) => `${JSON.stringify(value)}
10224
+ `;
10225
+ var buildCancelParams = (requestId, reason) => ({
10226
+ requestId,
10227
+ reason
10228
+ });
10229
+
10230
+ // src/mcp/sse.ts
10231
+ var import_eventsource_parser = require("eventsource-parser");
10232
+ var isEventStreamResponse = (response) => {
10233
+ const contentType = response.headers.get("Content-Type")?.toLowerCase() ?? "";
10234
+ return contentType.includes("text/event-stream");
10235
+ };
10236
+ var parseSsePayload = (event) => {
10237
+ const payload = event.data.trim();
10238
+ if (!payload || payload === "[DONE]") return void 0;
9616
10239
  try {
9617
10240
  return JSON.parse(payload);
9618
10241
  } catch (error) {
@@ -9628,7 +10251,7 @@ var matchesRequestId = (value, expectedRequestId) => {
9628
10251
  if (Array.isArray(value)) {
9629
10252
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
9630
10253
  }
9631
- if (!isRecord4(value)) return false;
10254
+ if (!isRecord5(value)) return false;
9632
10255
  const id = value.id;
9633
10256
  return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
9634
10257
  };
@@ -9924,7 +10547,7 @@ var StdioMcpClient = class {
9924
10547
  });
9925
10548
  }
9926
10549
  handleRpcResponse(value) {
9927
- if (!isRecord4(value)) return;
10550
+ if (!isRecord5(value)) return;
9928
10551
  const message = value;
9929
10552
  if (message.id === void 0 || message.id === null) return;
9930
10553
  const requestId = String(message.id);
@@ -10053,13 +10676,13 @@ var StdioMcpClient = class {
10053
10676
  };
10054
10677
 
10055
10678
  // src/mcp/oauth-helpers.ts
10056
- var isRecord5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10679
+ var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10057
10680
  var parseStringArray = (value) => {
10058
10681
  if (!Array.isArray(value)) return [];
10059
10682
  return value.filter((entry) => typeof entry === "string");
10060
10683
  };
10061
10684
  var parseProtectedResourceMetadata = (value) => {
10062
- if (!isRecord5(value)) return null;
10685
+ if (!isRecord6(value)) return null;
10063
10686
  return {
10064
10687
  ...typeof value.resource === "string" ? { resource: value.resource } : {},
10065
10688
  ...typeof value.token_endpoint === "string" ? { token_endpoint: value.token_endpoint } : {},
@@ -10068,7 +10691,7 @@ var parseProtectedResourceMetadata = (value) => {
10068
10691
  };
10069
10692
  };
10070
10693
  var parseAuthorizationServerMetadata = (value) => {
10071
- if (!isRecord5(value)) return null;
10694
+ if (!isRecord6(value)) return null;
10072
10695
  return {
10073
10696
  ...typeof value.issuer === "string" ? { issuer: value.issuer } : {},
10074
10697
  ...typeof value.authorization_endpoint === "string" ? { authorization_endpoint: value.authorization_endpoint } : {},
@@ -10092,7 +10715,7 @@ var buildAuthorizationServerMetadataUrl = (issuer) => {
10092
10715
  }
10093
10716
  };
10094
10717
  var parseTokenResponse = (value, current) => {
10095
- if (!isRecord5(value) || typeof value.access_token !== "string") {
10718
+ if (!isRecord6(value) || typeof value.access_token !== "string") {
10096
10719
  throw new Error("OAuth token response missing access_token");
10097
10720
  }
10098
10721
  const expiresIn = typeof value.expires_in === "number" && Number.isFinite(value.expires_in) ? value.expires_in : void 0;
@@ -10185,8 +10808,8 @@ var import_node_crypto8 = __toESM(require("crypto"), 1);
10185
10808
  var MAX_SCHEMA_SIZE_BYTES = 64 * 1024;
10186
10809
  var MAX_TOOL_OUTPUT_CHARS = 1e5;
10187
10810
  var MAX_TOOLS_LIST_PAGES = 100;
10188
- var isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10189
- var isMcpToolDescriptor = (value) => isRecord6(value) && typeof value.name === "string";
10811
+ var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10812
+ var isMcpToolDescriptor = (value) => isRecord7(value) && typeof value.name === "string";
10190
10813
  var toSlug2 = (value) => {
10191
10814
  const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
10192
10815
  return slug || "tool";
@@ -10209,7 +10832,7 @@ var fallbackSchema = () => ({
10209
10832
  additionalProperties: true
10210
10833
  });
10211
10834
  var normalizeSchema = (value) => {
10212
- if (!isRecord6(value)) return fallbackSchema();
10835
+ if (!isRecord7(value)) return fallbackSchema();
10213
10836
  let encoded = "";
10214
10837
  try {
10215
10838
  encoded = JSON.stringify(value);
@@ -10223,7 +10846,7 @@ var normalizeSchema = (value) => {
10223
10846
  };
10224
10847
  var stringifyMcpContentItem = (value) => {
10225
10848
  if (typeof value === "string") return value;
10226
- if (!isRecord6(value)) return JSON.stringify(value);
10849
+ if (!isRecord7(value)) return JSON.stringify(value);
10227
10850
  if (typeof value.text === "string") return value.text;
10228
10851
  try {
10229
10852
  return JSON.stringify(value);
@@ -10238,7 +10861,7 @@ var truncateText = (value, maxChars) => {
10238
10861
  };
10239
10862
  var toolResultToText = (value) => {
10240
10863
  if (typeof value === "string") return value;
10241
- if (!isRecord6(value)) {
10864
+ if (!isRecord7(value)) {
10242
10865
  try {
10243
10866
  return JSON.stringify(value);
10244
10867
  } catch {
@@ -10269,26 +10892,26 @@ var toolResultToText = (value) => {
10269
10892
  }
10270
10893
  };
10271
10894
  var parseNextCursor = (value) => {
10272
- if (!isRecord6(value)) return void 0;
10895
+ if (!isRecord7(value)) return void 0;
10273
10896
  if (typeof value.nextCursor === "string") return value.nextCursor;
10274
10897
  if (typeof value.next_cursor === "string") return value.next_cursor;
10275
10898
  return void 0;
10276
10899
  };
10277
10900
  var parseToolsList = (value) => {
10278
- if (!isRecord6(value) || !Array.isArray(value.tools)) return [];
10901
+ if (!isRecord7(value) || !Array.isArray(value.tools)) return [];
10279
10902
  return value.tools.filter(
10280
10903
  (entry) => isMcpToolDescriptor(entry)
10281
10904
  );
10282
10905
  };
10283
10906
  var isCallErrorResult = (value) => {
10284
- if (!isRecord6(value)) return false;
10907
+ if (!isRecord7(value)) return false;
10285
10908
  if (value.isError === true) return true;
10286
10909
  if (value.is_error === true) return true;
10287
10910
  return false;
10288
10911
  };
10289
10912
  var hasToolCapability = (value) => {
10290
- if (!isRecord6(value)) return false;
10291
- const caps = isRecord6(value.capabilities) ? value.capabilities : null;
10913
+ if (!isRecord7(value)) return false;
10914
+ const caps = isRecord7(value.capabilities) ? value.capabilities : null;
10292
10915
  if (!caps) return false;
10293
10916
  return caps.tools !== void 0;
10294
10917
  };
@@ -10749,6 +11372,101 @@ var SERVER_NAME = "codelia-runtime";
10749
11372
  var SERVER_VERSION = "0.1.0";
10750
11373
  var PROTOCOL_VERSION = "0";
10751
11374
 
11375
+ // src/volatile-stores.ts
11376
+ var stringifyMessageContent = (value) => {
11377
+ if (typeof value === "string") return value;
11378
+ if (Array.isArray(value)) {
11379
+ const parts = value.map((part) => {
11380
+ if (!part || typeof part !== "object") return "";
11381
+ const record = part;
11382
+ return typeof record.text === "string" ? record.text : "";
11383
+ }).filter((part) => part.length > 0);
11384
+ return parts.length ? parts.join("") : void 0;
11385
+ }
11386
+ return void 0;
11387
+ };
11388
+ var toSummary = (state) => {
11389
+ let lastUserMessage;
11390
+ for (let index = state.messages.length - 1; index >= 0; index -= 1) {
11391
+ const message = state.messages[index];
11392
+ if (message?.role !== "user") continue;
11393
+ lastUserMessage = stringifyMessageContent(message.content);
11394
+ break;
11395
+ }
11396
+ return {
11397
+ session_id: state.session_id,
11398
+ updated_at: state.updated_at,
11399
+ ...state.run_id ? { run_id: state.run_id } : {},
11400
+ message_count: state.messages.length,
11401
+ ...lastUserMessage ? { last_user_message: lastUserMessage } : {}
11402
+ };
11403
+ };
11404
+ var VolatileSessionStateStore = class {
11405
+ states = /* @__PURE__ */ new Map();
11406
+ async load(sessionId) {
11407
+ const state = this.states.get(sessionId);
11408
+ return state ? structuredClone(state) : null;
11409
+ }
11410
+ async save(state) {
11411
+ this.states.set(state.session_id, structuredClone(state));
11412
+ }
11413
+ async list() {
11414
+ return Array.from(this.states.values()).map(toSummary).sort((left, right) => right.updated_at.localeCompare(left.updated_at));
11415
+ }
11416
+ };
11417
+ var VolatileRunEventStoreFactory = class {
11418
+ records = /* @__PURE__ */ new Map();
11419
+ create(init) {
11420
+ const records = [];
11421
+ this.records.set(init.runId, records);
11422
+ return {
11423
+ append: (record) => {
11424
+ records.push(structuredClone(record));
11425
+ }
11426
+ };
11427
+ }
11428
+ };
11429
+ var VolatileToolOutputCacheStore = class {
11430
+ records = /* @__PURE__ */ new Map();
11431
+ async save(record) {
11432
+ const id = record.tool_call_id;
11433
+ this.records.set(id, structuredClone(record));
11434
+ return {
11435
+ id,
11436
+ byte_size: Buffer.byteLength(record.content, "utf8"),
11437
+ line_count: record.content.split(/\r?\n/).length
11438
+ };
11439
+ }
11440
+ async read(refId, options = {}) {
11441
+ const record = this.records.get(refId);
11442
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11443
+ const lines = record.content.split(/\r?\n/);
11444
+ const offset = Math.max(0, Math.trunc(options.offset ?? 0));
11445
+ const limit = Math.max(1, Math.trunc(options.limit ?? lines.length));
11446
+ return lines.slice(offset, offset + limit).join("\n");
11447
+ }
11448
+ async readLine(refId, options) {
11449
+ const record = this.records.get(refId);
11450
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11451
+ const lines = record.content.split(/\r?\n/);
11452
+ const line = lines[options.line_number - 1];
11453
+ if (line === void 0) {
11454
+ return `Line number out of range: ${options.line_number} (total ${lines.length})`;
11455
+ }
11456
+ const offset = Math.max(0, Math.trunc(options.char_offset ?? 0));
11457
+ const limit = Math.max(1, Math.trunc(options.char_limit ?? line.length));
11458
+ return line.slice(offset, offset + limit);
11459
+ }
11460
+ async grep(refId, options) {
11461
+ const record = this.records.get(refId);
11462
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11463
+ const query = options.pattern.toLowerCase();
11464
+ return record.content.split(/\r?\n/).map((line, index) => ({ line, index })).filter(({ line }) => line.toLowerCase().includes(query)).slice(0, options.max_matches ?? 50).map(
11465
+ ({ line, index }) => `${String(index + 1).padStart(6, "0")} ${line}`
11466
+ ).join("\n");
11467
+ }
11468
+ };
11469
+
10752
11470
  // src/rpc/context.ts
10753
11471
  var import_protocol2 = require("@codelia/protocol");
10754
11472
  var createContextHandlers = ({
@@ -10756,10 +11474,14 @@ var createContextHandlers = ({
10756
11474
  log: log2
10757
11475
  }) => {
10758
11476
  const ensureAgentsResolver = async () => {
11477
+ if (state.effectiveEnvironment.context.projectInstructions !== "from-workspace") {
11478
+ return null;
11479
+ }
10759
11480
  if (state.agentsResolver) {
10760
11481
  return state.agentsResolver;
10761
11482
  }
10762
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11483
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11484
+ if (!workingDir) return null;
10763
11485
  try {
10764
11486
  const resolver = await AgentsResolver.create(workingDir);
10765
11487
  state.agentsResolver = resolver;
@@ -10774,14 +11496,18 @@ var createContextHandlers = ({
10774
11496
  }
10775
11497
  };
10776
11498
  const ensureSkillsResolver = async () => {
11499
+ if (state.effectiveEnvironment.context.skills !== "from-config") {
11500
+ return null;
11501
+ }
10777
11502
  if (state.skillsResolver) {
10778
11503
  return state.skillsResolver;
10779
11504
  }
10780
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11505
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11506
+ if (!workingDir) return null;
10781
11507
  try {
10782
11508
  const resolver = await SkillsResolver.create({
10783
11509
  workingDir,
10784
- config: await resolveSkillsConfig(workingDir)
11510
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
10785
11511
  });
10786
11512
  state.skillsResolver = resolver;
10787
11513
  state.runtimeWorkingDir = workingDir;
@@ -10795,16 +11521,23 @@ var createContextHandlers = ({
10795
11521
  }
10796
11522
  };
10797
11523
  const ensureExecutionEnvironmentContext = async () => {
11524
+ if (state.effectiveEnvironment.context.executionEnvironment !== "from-config") {
11525
+ return null;
11526
+ }
10798
11527
  if (state.executionEnvironmentContext) {
10799
11528
  return state.executionEnvironmentContext;
10800
11529
  }
10801
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11530
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11531
+ if (!workingDir) return null;
10802
11532
  const sandboxRoot = state.runtimeSandboxRoot ?? workingDir;
10803
11533
  try {
10804
11534
  const context = await buildExecutionEnvironmentContext({
10805
11535
  workingDir,
10806
11536
  sandboxRoot,
10807
- config: await resolveExecutionEnvironmentConfig(workingDir)
11537
+ config: await resolveEnvironmentExecutionEnvironmentConfig(
11538
+ state,
11539
+ workingDir
11540
+ )
10808
11541
  });
10809
11542
  state.executionEnvironmentContext = context;
10810
11543
  state.runtimeWorkingDir = workingDir;
@@ -10826,6 +11559,7 @@ var createContextHandlers = ({
10826
11559
  runtime_working_dir: state.runtimeWorkingDir ?? void 0,
10827
11560
  runtime_sandbox_root: state.runtimeSandboxRoot ?? void 0,
10828
11561
  execution_environment: executionEnvironment ?? void 0,
11562
+ runtime_environment: state.effectiveEnvironment.summary,
10829
11563
  ui_context: {
10830
11564
  cwd: state.lastUiContext?.cwd,
10831
11565
  workspace_root: state.lastUiContext?.workspace_root,
@@ -10875,7 +11609,7 @@ var createContextHandlers = ({
10875
11609
 
10876
11610
  // src/rpc/history.ts
10877
11611
  var import_node_fs16 = require("fs");
10878
- var import_node_path15 = __toESM(require("path"), 1);
11612
+ var import_node_path16 = __toESM(require("path"), 1);
10879
11613
  var import_node_readline2 = require("readline");
10880
11614
  var import_protocol3 = require("@codelia/protocol");
10881
11615
  var import_storage10 = require("@codelia/storage");
@@ -10949,7 +11683,7 @@ var collectRunCandidates = async (log2) => {
10949
11683
  for (const yearEntry of yearEntries) {
10950
11684
  if (!yearEntry.isDirectory()) continue;
10951
11685
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
10952
- const yearPath = import_node_path15.default.join(sessionsDir, yearEntry.name);
11686
+ const yearPath = import_node_path16.default.join(sessionsDir, yearEntry.name);
10953
11687
  let monthEntries;
10954
11688
  try {
10955
11689
  monthEntries = await import_node_fs16.promises.readdir(yearPath, {
@@ -10962,7 +11696,7 @@ var collectRunCandidates = async (log2) => {
10962
11696
  for (const monthEntry of monthEntries) {
10963
11697
  if (!monthEntry.isDirectory()) continue;
10964
11698
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
10965
- const monthPath = import_node_path15.default.join(yearPath, monthEntry.name);
11699
+ const monthPath = import_node_path16.default.join(yearPath, monthEntry.name);
10966
11700
  let dayEntries;
10967
11701
  try {
10968
11702
  dayEntries = await import_node_fs16.promises.readdir(monthPath, {
@@ -10975,7 +11709,7 @@ var collectRunCandidates = async (log2) => {
10975
11709
  for (const dayEntry of dayEntries) {
10976
11710
  if (!dayEntry.isDirectory()) continue;
10977
11711
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
10978
- const dayPath = import_node_path15.default.join(monthPath, dayEntry.name);
11712
+ const dayPath = import_node_path16.default.join(monthPath, dayEntry.name);
10979
11713
  let files;
10980
11714
  try {
10981
11715
  files = await import_node_fs16.promises.readdir(dayPath, {
@@ -10988,7 +11722,7 @@ var collectRunCandidates = async (log2) => {
10988
11722
  for (const file of files) {
10989
11723
  if (!file.isFile()) continue;
10990
11724
  if (!file.name.endsWith(".jsonl")) continue;
10991
- const filePath = import_node_path15.default.join(dayPath, file.name);
11725
+ const filePath = import_node_path16.default.join(dayPath, file.name);
10992
11726
  try {
10993
11727
  const stat = await import_node_fs16.promises.stat(filePath);
10994
11728
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -11016,7 +11750,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
11016
11750
  const header = parseRunHeader(headerLine);
11017
11751
  if (!header) continue;
11018
11752
  if (header.session_id !== sessionId) continue;
11019
- const runId = header.run_id ?? import_node_path15.default.basename(candidate.path, ".jsonl");
11753
+ const runId = header.run_id ?? import_node_path16.default.basename(candidate.path, ".jsonl");
11020
11754
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
11021
11755
  runs.push({
11022
11756
  path: candidate.path,
@@ -11062,14 +11796,16 @@ var sendHistoryEvent = (runId, seq, event) => {
11062
11796
  var createHistoryHandlers = ({
11063
11797
  sessionStateStore,
11064
11798
  log: log2,
11799
+ readRunLogs = true,
11065
11800
  getCurrentWorkspaceRoot,
11066
- buildResumeDiffSummary
11801
+ buildResumeDiffSummary,
11802
+ sendHistoryEvent: emitHistoryEvent = sendHistoryEvent
11067
11803
  }) => {
11068
11804
  const normalizeWorkspaceRoot = (value) => {
11069
11805
  if (typeof value !== "string") return void 0;
11070
11806
  const trimmed = value.trim();
11071
11807
  if (!trimmed) return void 0;
11072
- return import_node_path15.default.resolve(trimmed);
11808
+ return import_node_path16.default.resolve(trimmed);
11073
11809
  };
11074
11810
  const handleSessionList = async (id, params) => {
11075
11811
  const limit = params?.limit ?? 50;
@@ -11119,7 +11855,7 @@ var createHistoryHandlers = ({
11119
11855
  sendResult(id, result2);
11120
11856
  return;
11121
11857
  }
11122
- const runs = await collectSessionRuns(sessionId, maxRuns, log2);
11858
+ const runs = readRunLogs ? await collectSessionRuns(sessionId, maxRuns, log2) : [];
11123
11859
  const replayEvents = [];
11124
11860
  for (const run of runs) {
11125
11861
  for await (const line of readJsonl(run.path)) {
@@ -11156,7 +11892,7 @@ var createHistoryHandlers = ({
11156
11892
  const truncated = replayEvents.length > maxEvents;
11157
11893
  const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
11158
11894
  for (const event of selectedEvents) {
11159
- sendHistoryEvent(event.runId, event.seq, event.event);
11895
+ await emitHistoryEvent(event.runId, event.seq, event.event);
11160
11896
  }
11161
11897
  let resumeDiff;
11162
11898
  if (buildResumeDiffSummary) {
@@ -11184,7 +11920,7 @@ var createHistoryHandlers = ({
11184
11920
  var import_core22 = require("@codelia/core");
11185
11921
  var import_model_metadata3 = require("@codelia/model-metadata");
11186
11922
  var import_protocol4 = require("@codelia/protocol");
11187
- var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter";
11923
+ var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter" || provider === "zai";
11188
11924
  var resolveProviderModelEntry2 = (providerEntries, provider, model) => {
11189
11925
  if (!providerEntries) {
11190
11926
  return null;
@@ -11265,7 +12001,10 @@ var sortModelsByReleaseDate = (models, provider, providerEntries) => {
11265
12001
  });
11266
12002
  return sortable.map((item) => item.model);
11267
12003
  };
11268
- var loadProviderModelEntries = async (provider) => {
12004
+ var loadProviderModelEntries = async (provider, state) => {
12005
+ if (state?.effectiveEnvironment.persistence.mode === "volatile") {
12006
+ return null;
12007
+ }
11269
12008
  const metadataService = new import_model_metadata3.ModelMetadataServiceImpl();
11270
12009
  const allEntries = await metadataService.getAllModelEntries();
11271
12010
  return allEntries[provider] ?? null;
@@ -11301,7 +12040,10 @@ var buildOpenRouterHeaders = (apiKey) => {
11301
12040
  }
11302
12041
  return headers;
11303
12042
  };
11304
- var resolveOpenRouterApiKey = async () => {
12043
+ var resolveOpenRouterApiKey = async (state) => {
12044
+ if (state?.effectiveEnvironment.auth.model === "host") {
12045
+ return null;
12046
+ }
11305
12047
  const envKey = readEnvValue("OPENROUTER_API_KEY");
11306
12048
  if (envKey) {
11307
12049
  return envKey;
@@ -11319,14 +12061,14 @@ var resolveOpenRouterApiKeyWithPrompt = async ({
11319
12061
  state,
11320
12062
  log: log2
11321
12063
  }) => {
11322
- const existing = await resolveOpenRouterApiKey();
12064
+ const existing = await resolveOpenRouterApiKey(state);
11323
12065
  if (existing) {
11324
12066
  return existing;
11325
12067
  }
11326
12068
  if (!state) {
11327
12069
  throw new Error("OpenRouter API key is required");
11328
12070
  }
11329
- const authResolver = await AuthResolver.create(state, log2);
12071
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
11330
12072
  const auth = await authResolver.resolveProviderAuth("openrouter");
11331
12073
  if (auth.method !== "api_key") {
11332
12074
  throw new Error("OpenRouter API key is required");
@@ -11437,7 +12179,7 @@ var buildProviderModelList = async ({
11437
12179
  providerEntries = providerEntriesOverride;
11438
12180
  } else {
11439
12181
  try {
11440
- providerEntries = await loadProviderModelEntries(provider);
12182
+ providerEntries = await loadProviderModelEntries(provider, state);
11441
12183
  } catch (error) {
11442
12184
  if (includeDetails) {
11443
12185
  log2(`model.list details error: ${error}`);
@@ -11449,7 +12191,8 @@ var buildProviderModelList = async ({
11449
12191
  openai: provider === "openai" ? providerEntries ?? {} : {},
11450
12192
  anthropic: provider === "anthropic" ? providerEntries ?? {} : {},
11451
12193
  openrouter: {},
11452
- google: {}
12194
+ google: {},
12195
+ zai: provider === "zai" ? providerEntries ?? {} : {}
11453
12196
  }
11454
12197
  });
11455
12198
  const models = sortModelsByReleaseDate(
@@ -11459,7 +12202,7 @@ var buildProviderModelList = async ({
11459
12202
  provider,
11460
12203
  providerEntries
11461
12204
  );
11462
- if (!includeDetails || !providerEntries) {
12205
+ if (!includeDetails || !providerEntries && provider !== "zai") {
11463
12206
  return { models };
11464
12207
  }
11465
12208
  const details = {};
@@ -11478,8 +12221,24 @@ var buildProviderModelList = async ({
11478
12221
  };
11479
12222
  var createModelHandlers = ({
11480
12223
  state,
11481
- log: log2
12224
+ log: log2,
12225
+ sessionStateStore
11482
12226
  }) => {
12227
+ const persistSessionModelOverride = async () => {
12228
+ const sessionId = state.sessionId;
12229
+ const snapshot = sessionId && sessionStateStore ? await sessionStateStore.load(sessionId) : null;
12230
+ const nextMeta = mergeSessionModelOverrideIntoMeta(
12231
+ snapshot?.meta ?? state.sessionMeta ?? void 0,
12232
+ state.sessionModelOverride
12233
+ );
12234
+ state.sessionMeta = nextMeta ?? null;
12235
+ if (!snapshot || !sessionStateStore) return;
12236
+ await sessionStateStore.save({
12237
+ ...snapshot,
12238
+ updated_at: (/* @__PURE__ */ new Date()).toISOString(),
12239
+ meta: nextMeta
12240
+ });
12241
+ };
11483
12242
  const handleModelList = async (id, params) => {
11484
12243
  const requestedProvider = params?.provider;
11485
12244
  const includeDetails = params?.include_details ?? false;
@@ -11491,11 +12250,14 @@ var createModelHandlers = ({
11491
12250
  return;
11492
12251
  }
11493
12252
  let current;
12253
+ let source = "config";
11494
12254
  let configuredProvider;
11495
12255
  let configuredReasoning;
11496
12256
  let configuredFast;
11497
12257
  try {
11498
- const config = await resolveModelConfig();
12258
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
12259
+ const config = await resolveEffectiveModelConfig(state, workingDir);
12260
+ source = config.source;
11499
12261
  configuredProvider = config.provider ?? "openai";
11500
12262
  configuredReasoning = resolveReasoningEffort(config.reasoning);
11501
12263
  if (!requestedProvider || requestedProvider === configuredProvider) {
@@ -11548,6 +12310,7 @@ var createModelHandlers = ({
11548
12310
  provider,
11549
12311
  models,
11550
12312
  current,
12313
+ source,
11551
12314
  ...configuredReasoning ? { reasoning: configuredReasoning } : {},
11552
12315
  ...configuredFast !== void 0 ? { fast: configuredFast } : {},
11553
12316
  ...details ? { details } : {}
@@ -11562,6 +12325,63 @@ var createModelHandlers = ({
11562
12325
  });
11563
12326
  return;
11564
12327
  }
12328
+ const scope = params?.scope ?? "config";
12329
+ if (scope !== "config" && scope !== "session") {
12330
+ sendError(id, {
12331
+ code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
12332
+ message: `unsupported model scope: ${scope}`
12333
+ });
12334
+ return;
12335
+ }
12336
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
12337
+ if (params?.reset) {
12338
+ if (scope !== "session") {
12339
+ sendError(id, {
12340
+ code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
12341
+ message: "model reset is only supported for session scope"
12342
+ });
12343
+ return;
12344
+ }
12345
+ try {
12346
+ clearSessionModelOverride(state);
12347
+ await persistSessionModelOverride();
12348
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
12349
+ const provider2 = config.provider ?? "openai";
12350
+ const name2 = config.name;
12351
+ if (!name2) {
12352
+ sendError(id, {
12353
+ code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
12354
+ message: "configured model name is missing"
12355
+ });
12356
+ return;
12357
+ }
12358
+ state.currentModelProvider = provider2;
12359
+ state.currentModelName = name2;
12360
+ state.currentModelSource = "config";
12361
+ state.agent = null;
12362
+ const effectiveReasoning = resolveReasoningEffort(config.reasoning);
12363
+ const effectiveFast = isSupportedProvider(provider2) ? resolveFastMode({
12364
+ provider: provider2,
12365
+ model: name2,
12366
+ requested: config.fast
12367
+ }).enabled : false;
12368
+ const result = {
12369
+ provider: provider2,
12370
+ name: name2,
12371
+ source: "config",
12372
+ ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
12373
+ ...config.fast !== void 0 ? { fast: effectiveFast } : {}
12374
+ };
12375
+ sendResult(id, result);
12376
+ log2(`model.set reset session override -> ${provider2}/${name2}`);
12377
+ } catch (error) {
12378
+ sendError(id, {
12379
+ code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
12380
+ message: String(error)
12381
+ });
12382
+ }
12383
+ return;
12384
+ }
11565
12385
  const provider = params?.provider ?? "openai";
11566
12386
  const name = params?.name?.trim();
11567
12387
  if (!name) {
@@ -11583,7 +12403,7 @@ var createModelHandlers = ({
11583
12403
  return;
11584
12404
  }
11585
12405
  }
11586
- if (provider !== "openai" && provider !== "anthropic" && provider !== "openrouter") {
12406
+ if (provider !== "openai" && provider !== "anthropic" && provider !== "openrouter" && provider !== "zai") {
11587
12407
  sendError(id, {
11588
12408
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
11589
12409
  message: `unsupported provider: ${provider}`
@@ -11601,17 +12421,37 @@ var createModelHandlers = ({
11601
12421
  }
11602
12422
  }
11603
12423
  try {
11604
- const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
11605
- const target = await updateModel(workingDir, {
11606
- provider,
11607
- name,
11608
- ...reasoning ? { reasoning } : {},
11609
- ...params.fast !== void 0 ? { fast: params.fast } : {}
11610
- });
12424
+ let target = null;
12425
+ if (scope === "config") {
12426
+ target = await updateEnvironmentModel(state, workingDir, {
12427
+ provider,
12428
+ name,
12429
+ ...reasoning ? { reasoning } : {},
12430
+ ...params.fast !== void 0 ? { fast: params.fast } : {}
12431
+ });
12432
+ clearSessionModelOverride(state);
12433
+ await persistSessionModelOverride();
12434
+ } else {
12435
+ const baseConfig = await resolveEnvironmentModelConfig(
12436
+ state,
12437
+ workingDir
12438
+ );
12439
+ setSessionModelOverride(state, baseConfig, {
12440
+ provider,
12441
+ name,
12442
+ ...reasoning ? { reasoning } : {},
12443
+ ...params.fast !== void 0 ? { fast: params.fast } : {}
12444
+ });
12445
+ await persistSessionModelOverride();
12446
+ }
11611
12447
  state.currentModelProvider = provider;
11612
12448
  state.currentModelName = name;
12449
+ state.currentModelSource = scope;
11613
12450
  state.agent = null;
11614
- const updatedConfig = await resolveModelConfig(workingDir);
12451
+ const updatedConfig = await resolveEffectiveModelConfig(
12452
+ state,
12453
+ workingDir
12454
+ );
11615
12455
  const effectiveReasoning = resolveReasoningEffort(
11616
12456
  updatedConfig.reasoning
11617
12457
  );
@@ -11623,12 +12463,14 @@ var createModelHandlers = ({
11623
12463
  const result = {
11624
12464
  provider,
11625
12465
  name,
12466
+ source: scope,
11626
12467
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
11627
12468
  ...updatedConfig.fast !== void 0 ? { fast: effectiveFast } : {}
11628
12469
  };
11629
12470
  sendResult(id, result);
12471
+ const persistence = scope === "config" && target ? ` scope=${target.scope} path=${target.path}` : " scope=session";
11630
12472
  log2(
11631
- `model.set ${provider}/${name}${effectiveReasoning ? ` reasoning=${effectiveReasoning}` : ""} scope=${target.scope} path=${target.path}`
12473
+ `model.set ${provider}/${name}${effectiveReasoning ? ` reasoning=${effectiveReasoning}` : ""}${persistence}`
11632
12474
  );
11633
12475
  } catch (error) {
11634
12476
  sendError(id, {
@@ -11642,7 +12484,7 @@ var createModelHandlers = ({
11642
12484
 
11643
12485
  // src/rpc/resume-context.ts
11644
12486
  var import_node_fs17 = require("fs");
11645
- var import_node_path16 = __toESM(require("path"), 1);
12487
+ var import_node_path17 = __toESM(require("path"), 1);
11646
12488
  var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11647
12489
  var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11648
12490
  var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
@@ -11651,7 +12493,7 @@ var normalizePath2 = (value) => {
11651
12493
  if (typeof value !== "string") return void 0;
11652
12494
  const trimmed = value.trim();
11653
12495
  if (!trimmed) return void 0;
11654
- return import_node_path16.default.resolve(trimmed);
12496
+ return import_node_path17.default.resolve(trimmed);
11655
12497
  };
11656
12498
  var normalizeMtime3 = (value) => {
11657
12499
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
@@ -12030,12 +12872,12 @@ var requestClientToolCall = async (state, params, timeoutMs) => {
12030
12872
 
12031
12873
  // src/tools/client.ts
12032
12874
  var DEFAULT_TIMEOUT_MS4 = 6e4;
12033
- var isRecord7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12875
+ var isRecord8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
12034
12876
  var normalizeClientToolResult = (value) => {
12035
12877
  if (typeof value === "string") {
12036
12878
  return { type: "text", text: value };
12037
12879
  }
12038
- if (isRecord7(value)) {
12880
+ if (isRecord8(value)) {
12039
12881
  if (value.type === "text" && typeof value.text === "string") {
12040
12882
  return { type: "text", text: value.text };
12041
12883
  }
@@ -12063,7 +12905,7 @@ var validateClientToolDefinition = (tool, existingNames) => {
12063
12905
  if (!tool.description.trim()) {
12064
12906
  throw new Error(`client tool description is required: ${tool.name}`);
12065
12907
  }
12066
- if (!isRecord7(tool.parameters)) {
12908
+ if (!isRecord8(tool.parameters)) {
12067
12909
  throw new Error(
12068
12910
  `client tool parameters must be a JSON schema: ${tool.name}`
12069
12911
  );
@@ -12102,7 +12944,7 @@ var createClientToolAdapters = ({
12102
12944
  let args;
12103
12945
  try {
12104
12946
  const parsed = JSON.parse(rawArgsJson);
12105
- args = isRecord7(parsed) ? parsed : { value: parsed };
12947
+ args = isRecord8(parsed) ? parsed : { value: parsed };
12106
12948
  } catch (error) {
12107
12949
  throw new Error(
12108
12950
  `Invalid tool arguments JSON for ${clientTool.name}: ${String(error)}`
@@ -12613,7 +13455,7 @@ var createRunHandlers = ({
12613
13455
  );
12614
13456
  };
12615
13457
  const emitRunStatus = (runId, status, message) => {
12616
- sendRunStatus(runId, status, message);
13458
+ sendRunStatus(state, runId, status, message);
12617
13459
  const suffix = message ? ` message=${message}` : "";
12618
13460
  logRunDebug(log2, runId, `status=${status} sent${suffix}`);
12619
13461
  appendSession({
@@ -12663,17 +13505,6 @@ var createRunHandlers = ({
12663
13505
  });
12664
13506
  return;
12665
13507
  }
12666
- let runtimeAgent;
12667
- try {
12668
- runtimeAgent = await getAgent();
12669
- } catch (error) {
12670
- sendError(id, {
12671
- code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
12672
- message: String(error)
12673
- });
12674
- return;
12675
- }
12676
- normalizeRuntimeAgentHistory("run.start preflight", runtimeAgent);
12677
13508
  const requestedSessionId = params.session_id?.trim() || void 0;
12678
13509
  let resumeState = null;
12679
13510
  const previousSessionId = state.sessionId;
@@ -12696,15 +13527,8 @@ var createRunHandlers = ({
12696
13527
  });
12697
13528
  return;
12698
13529
  }
12699
- await restoreSessionHistoryIntoAgent({
12700
- runtimeAgent,
12701
- resumeState,
12702
- sessionId: requestedSessionId
12703
- });
12704
- sessionId = requestedSessionId;
12705
- state.sessionId = sessionId;
12706
- loadedSessionState = true;
12707
- } else if (state.sessionId && runtimeAgent.getHistoryMessages().length === 0) {
13530
+ applySessionModelOverrideFromMeta(state, resumeState.meta);
13531
+ } else if (state.sessionId) {
12708
13532
  try {
12709
13533
  resumeState = await sessionStateStore.load(state.sessionId);
12710
13534
  } catch (error) {
@@ -12714,6 +13538,31 @@ var createRunHandlers = ({
12714
13538
  });
12715
13539
  return;
12716
13540
  }
13541
+ if (resumeState) {
13542
+ applySessionModelOverrideFromMeta(state, resumeState.meta);
13543
+ }
13544
+ }
13545
+ let runtimeAgent;
13546
+ try {
13547
+ runtimeAgent = await getAgent();
13548
+ } catch (error) {
13549
+ sendError(id, {
13550
+ code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
13551
+ message: String(error)
13552
+ });
13553
+ return;
13554
+ }
13555
+ normalizeRuntimeAgentHistory("run.start preflight", runtimeAgent);
13556
+ if (requestedSessionId && requestedSessionId !== state.sessionId) {
13557
+ await restoreSessionHistoryIntoAgent({
13558
+ runtimeAgent,
13559
+ resumeState,
13560
+ sessionId: requestedSessionId
13561
+ });
13562
+ sessionId = requestedSessionId;
13563
+ state.sessionId = sessionId;
13564
+ loadedSessionState = true;
13565
+ } else if (state.sessionId && runtimeAgent.getHistoryMessages().length === 0) {
12717
13566
  if (resumeState) {
12718
13567
  await restoreSessionHistoryIntoAgent({
12719
13568
  runtimeAgent,
@@ -12780,7 +13629,7 @@ var createRunHandlers = ({
12780
13629
  const emitRunDiagnostics = (params2) => {
12781
13630
  if (!state.diagnosticsEnabled) return;
12782
13631
  try {
12783
- sendRunDiagnostics(params2);
13632
+ sendRunDiagnostics(state, params2);
12784
13633
  } catch (error) {
12785
13634
  log2(`run diagnostics emit failed: ${String(error)}`);
12786
13635
  }
@@ -12879,7 +13728,8 @@ var createRunHandlers = ({
12879
13728
  };
12880
13729
  let modelConfig = null;
12881
13730
  try {
12882
- modelConfig = await resolveModelConfig();
13731
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? void 0;
13732
+ modelConfig = await resolveEffectiveModelConfig(state, workingDir);
12883
13733
  } catch (error) {
12884
13734
  log2(`session header model config error: ${error}`);
12885
13735
  }
@@ -12895,6 +13745,7 @@ var createRunHandlers = ({
12895
13745
  provider: modelConfig.provider,
12896
13746
  name: modelConfig.name,
12897
13747
  reasoning: modelConfig.reasoning,
13748
+ source: modelConfig.source,
12898
13749
  ...modelConfig.fast !== void 0 ? { fast: modelConfig.fast } : {}
12899
13750
  } : void 0,
12900
13751
  prompts: state.systemPrompt ? { system: state.systemPrompt } : void 0,
@@ -12910,6 +13761,9 @@ var createRunHandlers = ({
12910
13761
  os: process.platform,
12911
13762
  arch: process.arch,
12912
13763
  version: SERVER_VERSION
13764
+ },
13765
+ meta: {
13766
+ runtime_environment: state.effectiveEnvironment.summary
12913
13767
  }
12914
13768
  });
12915
13769
  appendSession({
@@ -12959,8 +13813,15 @@ var createRunHandlers = ({
12959
13813
  state.sessionMeta ?? void 0,
12960
13814
  getTodosForSession(sessionId)
12961
13815
  );
13816
+ const sessionMetaWithModelOverride = mergeSessionModelOverrideIntoMeta(
13817
+ sessionMeta,
13818
+ state.sessionModelOverride
13819
+ );
12962
13820
  const workspaceRoot = resolveSessionWorkspaceRoot(state);
12963
- const sessionMetaWithWorkspace = mergeWorkspaceRootIntoSessionMeta(sessionMeta, workspaceRoot);
13821
+ const sessionMetaWithWorkspace = mergeWorkspaceRootIntoSessionMeta(
13822
+ sessionMetaWithModelOverride,
13823
+ workspaceRoot
13824
+ );
12964
13825
  const sessionMetaWithResumeContext = mergeResumeContextIntoSessionMeta(
12965
13826
  sessionMetaWithWorkspace,
12966
13827
  state
@@ -13037,7 +13898,7 @@ var createRunHandlers = ({
13037
13898
  }
13038
13899
  const contextLeftPercent = runtimeAgent.getContextLeftPercent();
13039
13900
  if (contextLeftPercent !== null && state.updateContextLeftPercent(contextLeftPercent)) {
13040
- sendRunContext(runId, contextLeftPercent);
13901
+ sendRunContext(state, runId, contextLeftPercent);
13041
13902
  appendSession({
13042
13903
  type: "run.context",
13043
13904
  run_id: runId,
@@ -13128,7 +13989,7 @@ var createRunHandlers = ({
13128
13989
  };
13129
13990
 
13130
13991
  // src/rpc/shell.ts
13131
- var import_node_path17 = __toESM(require("path"), 1);
13992
+ var import_node_path18 = __toESM(require("path"), 1);
13132
13993
  var import_protocol6 = require("@codelia/protocol");
13133
13994
  var import_storage11 = require("@codelia/storage");
13134
13995
  var COMMAND_PREVIEW_CHARS = 400;
@@ -13143,14 +14004,14 @@ var truncateCommandPreview = (value) => {
13143
14004
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
13144
14005
  };
13145
14006
  var isWithin2 = (basePath, candidatePath) => {
13146
- const relative = import_node_path17.default.relative(basePath, candidatePath);
13147
- return relative === "" || !relative.startsWith("..") && !import_node_path17.default.isAbsolute(relative);
14007
+ const relative = import_node_path18.default.relative(basePath, candidatePath);
14008
+ return relative === "" || !relative.startsWith("..") && !import_node_path18.default.isAbsolute(relative);
13148
14009
  };
13149
14010
  var resolveShellCwd = (state, requestedCwd) => {
13150
14011
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
13151
14012
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
13152
14013
  if (!requestedCwd) return workingDir;
13153
- const resolved = import_node_path17.default.resolve(workingDir, requestedCwd);
14014
+ const resolved = import_node_path18.default.resolve(workingDir, requestedCwd);
13154
14015
  if (!isWithin2(rootDir, resolved)) {
13155
14016
  return null;
13156
14017
  }
@@ -13735,14 +14596,14 @@ var createShellHandlers = ({
13735
14596
  };
13736
14597
 
13737
14598
  // src/rpc/skills.ts
13738
- var import_node_path18 = __toESM(require("path"), 1);
14599
+ var import_node_path19 = __toESM(require("path"), 1);
13739
14600
  var import_protocol7 = require("@codelia/protocol");
13740
14601
  var createSkillsHandlers = ({
13741
14602
  state,
13742
14603
  log: log2
13743
14604
  }) => {
13744
14605
  const handleSkillsList = async (id, params) => {
13745
- const requestedCwd = params?.cwd ? import_node_path18.default.resolve(params.cwd) : void 0;
14606
+ const requestedCwd = params?.cwd ? import_node_path19.default.resolve(params.cwd) : void 0;
13746
14607
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
13747
14608
  const forceReload = params?.force_reload ?? false;
13748
14609
  if (!forceReload) {
@@ -13762,7 +14623,7 @@ var createSkillsHandlers = ({
13762
14623
  try {
13763
14624
  resolver = await SkillsResolver.create({
13764
14625
  workingDir,
13765
- config: await resolveSkillsConfig(workingDir)
14626
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
13766
14627
  });
13767
14628
  } catch (error) {
13768
14629
  sendError(id, {
@@ -13797,7 +14658,7 @@ var createSkillsHandlers = ({
13797
14658
  };
13798
14659
 
13799
14660
  // src/rpc/task.ts
13800
- var import_node_path19 = __toESM(require("path"), 1);
14661
+ var import_node_path20 = __toESM(require("path"), 1);
13801
14662
  var import_protocol8 = require("@codelia/protocol");
13802
14663
  var import_storage12 = require("@codelia/storage");
13803
14664
  var DEFAULT_TRUNCATED2 = {
@@ -13832,14 +14693,14 @@ var getPublicTaskKey = (task) => {
13832
14693
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
13833
14694
  };
13834
14695
  var isWithin3 = (basePath, candidatePath) => {
13835
- const relative = import_node_path19.default.relative(basePath, candidatePath);
13836
- return relative === "" || !relative.startsWith("..") && !import_node_path19.default.isAbsolute(relative);
14696
+ const relative = import_node_path20.default.relative(basePath, candidatePath);
14697
+ return relative === "" || !relative.startsWith("..") && !import_node_path20.default.isAbsolute(relative);
13837
14698
  };
13838
14699
  var resolveShellCwd2 = (state, requestedCwd) => {
13839
14700
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
13840
14701
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
13841
14702
  if (!requestedCwd) return workingDir;
13842
- const resolved = import_node_path19.default.resolve(workingDir, requestedCwd);
14703
+ const resolved = import_node_path20.default.resolve(workingDir, requestedCwd);
13843
14704
  if (!isWithin3(rootDir, resolved)) {
13844
14705
  return null;
13845
14706
  }
@@ -14243,6 +15104,7 @@ var SUPPORTED_TUI_THEMES = /* @__PURE__ */ new Set([
14243
15104
  "crimson",
14244
15105
  "wine"
14245
15106
  ]);
15107
+ var isReadableToolOutputCacheStore = (store) => !!store && typeof store.read === "function" && typeof store.readLine === "function";
14246
15108
  var createRuntimeHandlers = ({
14247
15109
  state,
14248
15110
  getAgent,
@@ -14253,19 +15115,24 @@ var createRuntimeHandlers = ({
14253
15115
  buildProviderModelList: injectedBuildProviderModelList,
14254
15116
  taskManager: injectedTaskManager
14255
15117
  }) => {
14256
- const sessionStateStore = injectedSessionStateStore ?? new import_storage13.SessionStateStoreImpl({
15118
+ const environment = state.effectiveEnvironment;
15119
+ const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage13.SessionStateStoreImpl({
14257
15120
  onError: (error, context) => {
14258
15121
  log2(
14259
15122
  `session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
14260
15123
  );
14261
15124
  }
14262
- });
14263
- const runEventStoreFactory = injectedRunEventStoreFactory ?? new import_storage13.RunEventStoreFactoryImpl();
15125
+ }));
15126
+ const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage13.RunEventStoreFactoryImpl());
14264
15127
  const mcpManager = injectedMcpManager ?? {
14265
15128
  start: async () => void 0,
14266
15129
  list: () => ({ servers: [] })
14267
15130
  };
14268
15131
  const buildProviderModelList2 = injectedBuildProviderModelList ?? buildProviderModelList;
15132
+ const adapterToolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore;
15133
+ const toolOutputCacheStore = isReadableToolOutputCacheStore(
15134
+ adapterToolOutputCacheStore
15135
+ ) ? adapterToolOutputCacheStore : environment.persistence.mode === "volatile" ? new VolatileToolOutputCacheStore() : void 0;
14269
15136
  let startupOnboardingPromise = null;
14270
15137
  let startupOnboardingStarted = false;
14271
15138
  const appendSession = (record) => {
@@ -14294,12 +15161,15 @@ var createRuntimeHandlers = ({
14294
15161
  return parts.join(" \u2022 ");
14295
15162
  };
14296
15163
  const runStartupOnboarding = async () => {
15164
+ if (!isTuiLocalEnvironment(state.effectiveEnvironment)) {
15165
+ return;
15166
+ }
14297
15167
  const supportsPick = !!state.uiCapabilities?.supports_pick;
14298
15168
  const supportsPrompt = !!state.uiCapabilities?.supports_prompt;
14299
15169
  if (!supportsPick || !supportsPrompt) {
14300
15170
  return;
14301
15171
  }
14302
- const authResolver = await AuthResolver.create(state, log2);
15172
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
14303
15173
  if (authResolver.hasAnyAvailableAuth()) {
14304
15174
  return;
14305
15175
  }
@@ -14308,7 +15178,7 @@ var createRuntimeHandlers = ({
14308
15178
  items: SUPPORTED_PROVIDERS.map((provider2) => ({
14309
15179
  id: provider2,
14310
15180
  label: provider2,
14311
- detail: provider2 === "openai" ? "OAuth (ChatGPT Plus/Pro) or API key" : provider2 === "openrouter" ? "API key (OpenRouter)" : "API key"
15181
+ detail: provider2 === "openai" ? "OAuth (ChatGPT Plus/Pro) or API key" : provider2 === "openrouter" ? "API key (OpenRouter)" : provider2 === "zai" ? "API key (Z.ai)" : "API key"
14312
15182
  })),
14313
15183
  multi: false
14314
15184
  });
@@ -14349,12 +15219,14 @@ var createRuntimeHandlers = ({
14349
15219
  return;
14350
15220
  }
14351
15221
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14352
- const modelTarget = await updateModel(workingDir, {
15222
+ const modelTarget = await updateEnvironmentModel(state, workingDir, {
14353
15223
  provider,
14354
15224
  name: selectedModel
14355
15225
  });
15226
+ state.sessionModelOverride = null;
14356
15227
  state.currentModelProvider = provider;
14357
15228
  state.currentModelName = selectedModel;
15229
+ state.currentModelSource = "config";
14358
15230
  state.agent = null;
14359
15231
  log2(
14360
15232
  `startup onboarding completed: ${provider}/${selectedModel} scope=${modelTarget.scope} path=${modelTarget.path}`
@@ -14387,7 +15259,22 @@ var createRuntimeHandlers = ({
14387
15259
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
14388
15260
  sessionStateStore,
14389
15261
  log: log2,
14390
- getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd(),
15262
+ readRunLogs: environment.persistence.mode === "runtime",
15263
+ ...environment.events.live === "host" ? {
15264
+ sendHistoryEvent: async (runId, seq, event) => {
15265
+ const notify = {
15266
+ jsonrpc: "2.0",
15267
+ method: "agent.event",
15268
+ params: {
15269
+ run_id: runId,
15270
+ seq,
15271
+ event
15272
+ }
15273
+ };
15274
+ await sendNotificationAsync(state, notify);
15275
+ }
15276
+ } : {},
15277
+ getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? environment.workspace.root,
14391
15278
  buildResumeDiffSummary: async (meta) => {
14392
15279
  if (!hasStructuredResumeContextMeta(meta)) {
14393
15280
  return void 0;
@@ -14403,7 +15290,8 @@ var createRuntimeHandlers = ({
14403
15290
  });
14404
15291
  const { handleModelList, handleModelSet } = createModelHandlers({
14405
15292
  state,
14406
- log: log2
15293
+ log: log2,
15294
+ sessionStateStore
14407
15295
  });
14408
15296
  const { handleContextInspect } = createContextHandlers({
14409
15297
  state,
@@ -14417,56 +15305,50 @@ var createRuntimeHandlers = ({
14417
15305
  state,
14418
15306
  getAgent
14419
15307
  });
14420
- const {
14421
- handleShellExec,
14422
- handleShellStart,
14423
- handleShellList,
14424
- handleShellStatus,
14425
- handleShellOutput,
14426
- handleShellWait,
14427
- handleShellDetach,
14428
- handleShellCancel
14429
- } = createShellHandlers({
15308
+ const processHandlersEnabled = state.effectiveEnvironment.workspace.process === "runtime";
15309
+ const shellHandlers = processHandlersEnabled ? createShellHandlers({
14430
15310
  state,
14431
15311
  log: log2,
14432
- taskManager: injectedTaskManager
14433
- });
14434
- const {
14435
- handleTaskSpawn,
14436
- handleTaskList,
14437
- handleTaskStatus,
14438
- handleTaskWait,
14439
- handleTaskCancel,
14440
- handleTaskResult
14441
- } = createTaskHandlers({
15312
+ taskManager: injectedTaskManager,
15313
+ outputCache: toolOutputCacheStore ?? void 0
15314
+ }) : null;
15315
+ const taskHandlers = processHandlersEnabled ? createTaskHandlers({
14442
15316
  state,
14443
15317
  log: log2,
14444
- taskManager: injectedTaskManager
14445
- });
15318
+ taskManager: injectedTaskManager,
15319
+ outputCache: toolOutputCacheStore ?? void 0
15320
+ }) : null;
14446
15321
  const handleInitialize = async (id, params) => {
14447
15322
  let resolvedTheme;
14448
- try {
14449
- const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14450
- resolvedTheme = (await resolveTuiConfig(workingDir)).theme;
14451
- } catch (error) {
14452
- log2(`initialize tui config load failed: ${String(error)}`);
15323
+ const environment2 = state.effectiveEnvironment;
15324
+ if (isTuiLocalEnvironment(environment2)) {
15325
+ try {
15326
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
15327
+ resolvedTheme = (await resolveEnvironmentTuiConfig(state, workingDir)).theme;
15328
+ } catch (error) {
15329
+ log2(`initialize tui config load failed: ${String(error)}`);
15330
+ }
14453
15331
  }
15332
+ const processEnabled = environment2.workspace.process === "runtime";
15333
+ const mcpEnabled = environment2.tools.mcp === "from-config";
15334
+ const skillsEnabled = environment2.context.skills === "from-config";
15335
+ const themeSetEnabled = isTuiLocalEnvironment(environment2) && environment2.config.source !== "disabled";
14454
15336
  const result = {
14455
15337
  protocol_version: PROTOCOL_VERSION,
14456
15338
  server: { name: SERVER_NAME, version: SERVER_VERSION },
14457
15339
  server_capabilities: {
14458
15340
  supports_run_cancel: true,
14459
15341
  supports_run_diagnostics: true,
14460
- supports_shell_exec: true,
14461
- supports_shell_tasks: true,
14462
- supports_shell_detach: true,
14463
- supports_tasks: true,
14464
- supports_ui_requests: true,
14465
- supports_mcp_list: true,
14466
- supports_skills_list: true,
15342
+ supports_shell_exec: processEnabled,
15343
+ supports_shell_tasks: processEnabled,
15344
+ supports_shell_detach: processEnabled,
15345
+ supports_tasks: processEnabled,
15346
+ supports_ui_requests: isTuiLocalEnvironment(environment2),
15347
+ supports_mcp_list: mcpEnabled,
15348
+ supports_skills_list: skillsEnabled,
14467
15349
  supports_context_inspect: true,
14468
15350
  supports_tool_call: true,
14469
- supports_theme_set: true,
15351
+ supports_theme_set: themeSetEnabled,
14470
15352
  supports_permission_preflight_events: true
14471
15353
  },
14472
15354
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
@@ -14508,7 +15390,7 @@ var createRuntimeHandlers = ({
14508
15390
  }
14509
15391
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14510
15392
  try {
14511
- const target = await updateTuiTheme(workingDir, name);
15393
+ const target = await updateEnvironmentTuiTheme(state, workingDir, name);
14512
15394
  const result = {
14513
15395
  name,
14514
15396
  scope: target.scope,
@@ -14533,6 +15415,31 @@ var createRuntimeHandlers = ({
14533
15415
  }
14534
15416
  const clearSession = params?.clear_session ?? true;
14535
15417
  try {
15418
+ if (state.effectiveEnvironment.auth.model === "host") {
15419
+ const clearAuth = state.effectiveEnvironment.adapters.credentialProvider?.clearAuth;
15420
+ if (!clearAuth) {
15421
+ sendError(id, {
15422
+ code: import_protocol10.RPC_ERROR_CODE.RUNTIME_INTERNAL,
15423
+ message: "host auth provider does not support logout"
15424
+ });
15425
+ return;
15426
+ }
15427
+ await clearAuth();
15428
+ state.agent = null;
15429
+ if (clearSession) {
15430
+ state.sessionId = null;
15431
+ state.sessionMeta = null;
15432
+ state.sessionAppend = null;
15433
+ state.sessionModelOverride = null;
15434
+ }
15435
+ sendResult(id, {
15436
+ ok: true,
15437
+ auth_cleared: true,
15438
+ session_cleared: clearSession
15439
+ });
15440
+ log2(`auth.logout host session_cleared=${clearSession}`);
15441
+ return;
15442
+ }
14536
15443
  const supportsConfirm = !!state.uiCapabilities?.supports_confirm;
14537
15444
  if (!supportsConfirm) {
14538
15445
  sendError(id, {
@@ -14569,6 +15476,7 @@ var createRuntimeHandlers = ({
14569
15476
  state.sessionId = null;
14570
15477
  state.sessionMeta = null;
14571
15478
  state.sessionAppend = null;
15479
+ state.sessionModelOverride = null;
14572
15480
  }
14573
15481
  const result = {
14574
15482
  ok: true,
@@ -14585,6 +15493,13 @@ var createRuntimeHandlers = ({
14585
15493
  }
14586
15494
  };
14587
15495
  const handleRequest = async (req) => {
15496
+ const mcpEnabled = state.effectiveEnvironment.tools.mcp === "from-config";
15497
+ const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
15498
+ const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
15499
+ const rejectDisabled = (message) => sendError(req.id, {
15500
+ code: import_protocol10.RPC_ERROR_CODE.INVALID_PARAMS,
15501
+ message
15502
+ });
14588
15503
  switch (req.method) {
14589
15504
  case "initialize":
14590
15505
  return handleInitialize(req.id, req.params);
@@ -14605,44 +15520,120 @@ var createRuntimeHandlers = ({
14605
15520
  case "tool.call":
14606
15521
  return handleToolCall(req.id, req.params);
14607
15522
  case "shell.exec":
14608
- return handleShellExec(req.id, req.params);
15523
+ if (!shellHandlers)
15524
+ return rejectDisabled("process execution is disabled");
15525
+ return shellHandlers.handleShellExec(
15526
+ req.id,
15527
+ req.params
15528
+ );
14609
15529
  case "shell.start":
14610
- return handleShellStart(req.id, req.params);
15530
+ if (!shellHandlers)
15531
+ return rejectDisabled("process execution is disabled");
15532
+ return shellHandlers.handleShellStart(
15533
+ req.id,
15534
+ req.params
15535
+ );
14611
15536
  case "shell.list":
14612
- return handleShellList(req.id, req.params);
15537
+ if (!shellHandlers)
15538
+ return rejectDisabled("process execution is disabled");
15539
+ return shellHandlers.handleShellList(
15540
+ req.id,
15541
+ req.params
15542
+ );
14613
15543
  case "shell.status":
14614
- return handleShellStatus(req.id, req.params);
15544
+ if (!shellHandlers)
15545
+ return rejectDisabled("process execution is disabled");
15546
+ return shellHandlers.handleShellStatus(
15547
+ req.id,
15548
+ req.params
15549
+ );
14615
15550
  case "shell.output":
14616
- return handleShellOutput(req.id, req.params);
15551
+ if (!shellHandlers)
15552
+ return rejectDisabled("process execution is disabled");
15553
+ return shellHandlers.handleShellOutput(
15554
+ req.id,
15555
+ req.params
15556
+ );
14617
15557
  case "shell.wait":
14618
- return handleShellWait(req.id, req.params);
15558
+ if (!shellHandlers)
15559
+ return rejectDisabled("process execution is disabled");
15560
+ return shellHandlers.handleShellWait(
15561
+ req.id,
15562
+ req.params
15563
+ );
14619
15564
  case "shell.detach":
14620
- return handleShellDetach(req.id, req.params);
15565
+ if (!shellHandlers)
15566
+ return rejectDisabled("process execution is disabled");
15567
+ return shellHandlers.handleShellDetach(
15568
+ req.id,
15569
+ req.params
15570
+ );
14621
15571
  case "shell.cancel":
14622
- return handleShellCancel(req.id, req.params);
15572
+ if (!shellHandlers)
15573
+ return rejectDisabled("process execution is disabled");
15574
+ return shellHandlers.handleShellCancel(
15575
+ req.id,
15576
+ req.params
15577
+ );
14623
15578
  case "task.spawn":
14624
- return handleTaskSpawn(req.id, req.params);
15579
+ if (!taskHandlers)
15580
+ return rejectDisabled("process execution is disabled");
15581
+ return taskHandlers.handleTaskSpawn(
15582
+ req.id,
15583
+ req.params
15584
+ );
14625
15585
  case "task.list":
14626
- return handleTaskList(req.id, req.params);
15586
+ if (!taskHandlers)
15587
+ return rejectDisabled("process execution is disabled");
15588
+ return taskHandlers.handleTaskList(
15589
+ req.id,
15590
+ req.params
15591
+ );
14627
15592
  case "task.status":
14628
- return handleTaskStatus(req.id, req.params);
15593
+ if (!taskHandlers)
15594
+ return rejectDisabled("process execution is disabled");
15595
+ return taskHandlers.handleTaskStatus(
15596
+ req.id,
15597
+ req.params
15598
+ );
14629
15599
  case "task.wait":
14630
- return handleTaskWait(req.id, req.params);
15600
+ if (!taskHandlers)
15601
+ return rejectDisabled("process execution is disabled");
15602
+ return taskHandlers.handleTaskWait(
15603
+ req.id,
15604
+ req.params
15605
+ );
14631
15606
  case "task.cancel":
14632
- return handleTaskCancel(req.id, req.params);
15607
+ if (!taskHandlers)
15608
+ return rejectDisabled("process execution is disabled");
15609
+ return taskHandlers.handleTaskCancel(
15610
+ req.id,
15611
+ req.params
15612
+ );
14633
15613
  case "task.result":
14634
- return handleTaskResult(req.id, req.params);
15614
+ if (!taskHandlers)
15615
+ return rejectDisabled("process execution is disabled");
15616
+ return taskHandlers.handleTaskResult(
15617
+ req.id,
15618
+ req.params
15619
+ );
14635
15620
  case "mcp.list":
15621
+ if (!mcpEnabled) {
15622
+ return sendResult(req.id, { servers: [] });
15623
+ }
14636
15624
  await mcpManager.start?.();
14637
15625
  return sendResult(
14638
15626
  req.id,
14639
15627
  mcpManager.list(req.params?.scope)
14640
15628
  );
14641
15629
  case "skills.list":
15630
+ if (!skillsEnabled) return rejectDisabled("skills are disabled");
14642
15631
  return handleSkillsList(req.id, req.params);
14643
15632
  case "context.inspect":
14644
15633
  return handleContextInspect(req.id, req.params);
14645
15634
  case "theme.set":
15635
+ if (!themeSetEnabled)
15636
+ return rejectDisabled("theme setting is disabled");
14646
15637
  return handleThemeSet(req.id, req.params);
14647
15638
  default:
14648
15639
  return sendError(req.id, {
@@ -14677,6 +15668,7 @@ var createRuntimeHandlers = ({
14677
15668
  // src/runtime-state.ts
14678
15669
  var import_node_crypto9 = __toESM(require("crypto"), 1);
14679
15670
  var RuntimeState = class {
15671
+ effectiveEnvironment = resolveRuntimeEnvironment();
14680
15672
  runSeq = /* @__PURE__ */ new Map();
14681
15673
  uiRequestCounter = 0;
14682
15674
  pendingUiRequests = /* @__PURE__ */ new Map();
@@ -14705,7 +15697,12 @@ var RuntimeState = class {
14705
15697
  approvalMode = null;
14706
15698
  currentModelProvider = null;
14707
15699
  currentModelName = null;
15700
+ currentModelSource = null;
15701
+ sessionModelOverride = null;
14708
15702
  diagnosticsEnabled = false;
15703
+ setRuntimeEnvironment(options) {
15704
+ this.effectiveEnvironment = resolveRuntimeEnvironment(options);
15705
+ }
14709
15706
  nextRunId() {
14710
15707
  return import_node_crypto9.default.randomUUID();
14711
15708
  }
@@ -14805,33 +15802,42 @@ var envTruthy2 = (value) => {
14805
15802
  const normalized = value.trim().toLowerCase();
14806
15803
  return normalized === "1" || normalized === "true";
14807
15804
  };
14808
- var startRuntime = () => {
14809
- void (async () => {
14810
- const state = new RuntimeState();
14811
- state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
14812
- const workingDir = process.env.CODELIA_SANDBOX_ROOT ? import_node_path20.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
15805
+ var startRuntime = async (options = {}) => {
15806
+ const state = new RuntimeState();
15807
+ state.setRuntimeEnvironment(options);
15808
+ const environment = state.effectiveEnvironment;
15809
+ state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
15810
+ const workingDir = environment.workspace.root;
15811
+ if (workingDir) {
14813
15812
  state.runtimeWorkingDir = workingDir;
14814
15813
  state.runtimeSandboxRoot = workingDir;
15814
+ }
15815
+ if (environment.context.projectInstructions === "from-workspace" && workingDir) {
14815
15816
  try {
14816
15817
  state.agentsResolver = await AgentsResolver.create(workingDir);
14817
15818
  } catch (error) {
14818
15819
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
14819
15820
  }
14820
- const sessionStateStore = new import_storage14.SessionStateStoreImpl({
14821
- onError: (error, context) => {
14822
- (0, import_logger.log)(
14823
- `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
14824
- );
14825
- }
14826
- });
15821
+ }
15822
+ const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage14.SessionStateStoreImpl({
15823
+ onError: (error, context) => {
15824
+ (0, import_logger.log)(
15825
+ `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
15826
+ );
15827
+ }
15828
+ }));
15829
+ if (environment.persistence.mode === "runtime") {
14827
15830
  try {
14828
15831
  await sessionStateStore.list();
14829
15832
  } catch (error) {
14830
- (0, import_logger.log)(`Error: session index database is not available: ${String(error)}`);
14831
- process.exit(1);
14832
- return;
15833
+ throw new Error(
15834
+ `session index database is not available: ${String(error)}`
15835
+ );
14833
15836
  }
14834
- const taskManager = new TaskManager();
15837
+ }
15838
+ const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage14.RunEventStoreFactoryImpl());
15839
+ const taskManager = isProcessEnabled(environment) ? environment.adapters.stores?.taskManager ?? new TaskManager() : void 0;
15840
+ if (taskManager) {
14835
15841
  const recoveredTasks = await taskManager.recoverOrphanedTasks();
14836
15842
  if (recoveredTasks.recovered > 0 || recoveredTasks.errors.length > 0) {
14837
15843
  (0, import_logger.log)(
@@ -14841,76 +15847,81 @@ var startRuntime = () => {
14841
15847
  (0, import_logger.log)(`tasks.recover error task_id=${error.task_id}: ${error.error}`);
14842
15848
  }
14843
15849
  }
14844
- let shutdownPromise = null;
14845
- const shutdownTasks = async (reason) => {
14846
- if (shutdownPromise) {
14847
- await shutdownPromise;
14848
- return;
14849
- }
14850
- shutdownPromise = (async () => {
14851
- const result = await taskManager.shutdown();
14852
- if (result.cancelled > 0 || result.errors.length > 0) {
14853
- (0, import_logger.log)(
14854
- `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
14855
- );
14856
- for (const error of result.errors) {
14857
- (0, import_logger.log)(
14858
- `tasks.shutdown error task_id=${error.task_id}: ${error.error}`
14859
- );
14860
- }
14861
- }
14862
- })();
15850
+ }
15851
+ let shutdownPromise = null;
15852
+ const shutdownTasks = async (reason) => {
15853
+ if (!taskManager) return;
15854
+ if (shutdownPromise) {
14863
15855
  await shutdownPromise;
14864
- };
14865
- for (const signal of ["SIGINT", "SIGTERM"]) {
14866
- process.once(signal, () => {
14867
- void shutdownTasks(signal).finally(() => {
14868
- process.kill(process.pid, signal);
14869
- });
14870
- });
15856
+ return;
14871
15857
  }
14872
- process.once("beforeExit", () => {
14873
- void shutdownTasks("beforeExit");
14874
- });
14875
- process.stdin.once("end", () => {
14876
- void shutdownTasks("stdin.end");
15858
+ shutdownPromise = (async () => {
15859
+ const result = await taskManager.shutdown();
15860
+ if (result.cancelled > 0 || result.errors.length > 0) {
15861
+ (0, import_logger.log)(
15862
+ `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
15863
+ );
15864
+ for (const error of result.errors) {
15865
+ (0, import_logger.log)(`tasks.shutdown error task_id=${error.task_id}: ${error.error}`);
15866
+ }
15867
+ }
15868
+ })();
15869
+ await shutdownPromise;
15870
+ };
15871
+ for (const signal of ["SIGINT", "SIGTERM"]) {
15872
+ process.once(signal, () => {
15873
+ void shutdownTasks(signal).finally(() => {
15874
+ process.kill(process.pid, signal);
15875
+ });
14877
15876
  });
14878
- const mcpManager = new McpManager({ workingDir, log: import_logger.log });
15877
+ }
15878
+ process.once("beforeExit", () => {
15879
+ void shutdownTasks("beforeExit");
15880
+ });
15881
+ process.stdin.once("end", () => {
15882
+ void shutdownTasks("stdin.end");
15883
+ });
15884
+ const mcpManager = environment.tools.mcp === "from-config" && workingDir ? new McpManager({ workingDir, log: import_logger.log }) : void 0;
15885
+ if (mcpManager) {
14879
15886
  void mcpManager.start({
14880
15887
  onStatus: (message) => (0, import_logger.log)(`mcp: ${message}`),
14881
15888
  requestOAuthTokens: ({ server_id, oauth: oauth2, error }) => requestMcpOAuthTokensWithRunStatus(state, server_id, oauth2, error)
14882
15889
  });
14883
- const getAgent = createAgentFactory(state, { mcpManager, taskManager });
14884
- const { processMessage } = createRuntimeHandlers({
14885
- state,
14886
- getAgent,
14887
- log: import_logger.log,
14888
- mcpManager,
14889
- sessionStateStore,
14890
- taskManager
14891
- });
14892
- (0, import_logger.log)("runtime started");
14893
- process.stdin.setEncoding("utf8");
14894
- let buffer = "";
14895
- process.stdin.on("data", (chunk) => {
14896
- buffer += chunk;
14897
- let index = buffer.indexOf("\n");
14898
- while (index >= 0) {
14899
- const line = buffer.slice(0, index).trim();
14900
- buffer = buffer.slice(index + 1);
14901
- if (line) {
14902
- try {
14903
- const msg = JSON.parse(line);
14904
- processMessage(msg);
14905
- } catch (error) {
14906
- (0, import_logger.log)(`invalid json: ${String(error)}`);
14907
- }
15890
+ }
15891
+ const getAgent = createAgentFactory(state, { mcpManager, taskManager });
15892
+ const { processMessage } = createRuntimeHandlers({
15893
+ state,
15894
+ getAgent,
15895
+ log: import_logger.log,
15896
+ mcpManager,
15897
+ sessionStateStore,
15898
+ runEventStoreFactory,
15899
+ taskManager
15900
+ });
15901
+ (0, import_logger.log)("runtime started");
15902
+ process.stdin.setEncoding("utf8");
15903
+ let buffer = "";
15904
+ process.stdin.on("data", (chunk) => {
15905
+ buffer += chunk;
15906
+ let index = buffer.indexOf("\n");
15907
+ while (index >= 0) {
15908
+ const line = buffer.slice(0, index).trim();
15909
+ buffer = buffer.slice(index + 1);
15910
+ if (line) {
15911
+ try {
15912
+ const msg = JSON.parse(line);
15913
+ processMessage(msg);
15914
+ } catch (error) {
15915
+ (0, import_logger.log)(`invalid json: ${String(error)}`);
14908
15916
  }
14909
- index = buffer.indexOf("\n");
14910
15917
  }
14911
- });
14912
- })();
15918
+ index = buffer.indexOf("\n");
15919
+ }
15920
+ });
14913
15921
  };
14914
15922
 
14915
15923
  // src/index.ts
14916
- startRuntime();
15924
+ void startRuntime().catch((error) => {
15925
+ console.error(`runtime startup failed: ${String(error)}`);
15926
+ process.exitCode = 1;
15927
+ });