@codelia/runtime 0.1.69 → 0.1.71

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
@@ -1680,6 +1712,144 @@ var AuthResolver = class _AuthResolver {
1680
1712
  }
1681
1713
  };
1682
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
+
1683
1853
  // src/effective-model.ts
1684
1854
  var MODEL_OVERRIDE_SESSION_META_KEY = "codelia_model_override";
1685
1855
  var mergeModelOverride = (config, override) => {
@@ -1693,7 +1863,7 @@ var mergeModelOverride = (config, override) => {
1693
1863
  };
1694
1864
  };
1695
1865
  var resolveEffectiveModelConfig = async (state, workingDir) => {
1696
- const config = await resolveModelConfig(workingDir);
1866
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
1697
1867
  const source = state.sessionModelOverride ? "session" : "config";
1698
1868
  return {
1699
1869
  ...mergeModelOverride(config, state.sessionModelOverride),
@@ -2452,20 +2622,29 @@ var resolveFastMode = (params) => {
2452
2622
  };
2453
2623
 
2454
2624
  // src/model-reasoning.ts
2455
- var REASONING_LEVEL_ORDER = [
2456
- "low",
2457
- "medium",
2458
- "high",
2459
- "xhigh"
2460
- ];
2625
+ var import_shared_types2 = require("@codelia/shared-types");
2626
+ var REASONING_LEVEL_ORDER = import_shared_types2.MODEL_REASONING_LEVELS;
2461
2627
  var DEFAULT_REASONING_LEVEL = "medium";
2462
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",
2463
2636
  "gpt-5.1",
2464
2637
  "gpt-5.1-2025-11-13",
2465
2638
  "gpt-5.1-codex",
2466
2639
  "gpt-5.1-codex-max",
2467
2640
  "gpt-5.1-codex-mini"
2468
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
+ ]);
2469
2648
  var ANTHROPIC_FALLBACK_PROFILE = {
2470
2649
  supportedLevels: ["low", "medium", "high"],
2471
2650
  budgetPresetByLevel: {
@@ -2481,33 +2660,62 @@ var ANTHROPIC_BUDGET_PRESET_TOKENS = {
2481
2660
  reasoning_xhigh: 49152
2482
2661
  };
2483
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
+ };
2484
2676
  var ANTHROPIC_REASONING_MODEL_TABLE = {
2677
+ "claude-fable-5": {
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
+ },
2485
2688
  "claude-opus-4-8": {
2486
- supportedLevels: ["low", "medium", "high", "xhigh"],
2689
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2487
2690
  budgetPresetByLevel: {
2488
2691
  low: "reasoning_low",
2489
2692
  medium: "reasoning_medium",
2490
2693
  high: "reasoning_high",
2491
- xhigh: "reasoning_xhigh"
2492
- }
2694
+ xhigh: "reasoning_xhigh",
2695
+ max: "reasoning_xhigh"
2696
+ },
2697
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2493
2698
  },
2494
2699
  "claude-opus-4-7": {
2495
- supportedLevels: ["low", "medium", "high", "xhigh"],
2700
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2496
2701
  budgetPresetByLevel: {
2497
2702
  low: "reasoning_low",
2498
2703
  medium: "reasoning_medium",
2499
2704
  high: "reasoning_high",
2500
- xhigh: "reasoning_xhigh"
2501
- }
2705
+ xhigh: "reasoning_xhigh",
2706
+ max: "reasoning_xhigh"
2707
+ },
2708
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2502
2709
  },
2503
2710
  "claude-opus-4-6": {
2504
- supportedLevels: ["low", "medium", "high", "xhigh"],
2711
+ supportedLevels: ["low", "medium", "high", "max"],
2505
2712
  budgetPresetByLevel: {
2506
2713
  low: "reasoning_low",
2507
2714
  medium: "reasoning_medium",
2508
2715
  high: "reasoning_high",
2509
- xhigh: "reasoning_xhigh"
2510
- }
2716
+ max: "reasoning_xhigh"
2717
+ },
2718
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2511
2719
  },
2512
2720
  "claude-opus-4-5": {
2513
2721
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2528,13 +2736,14 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2528
2736
  }
2529
2737
  },
2530
2738
  "claude-sonnet-4-6": {
2531
- supportedLevels: ["low", "medium", "high", "xhigh"],
2739
+ supportedLevels: ["low", "medium", "high", "max"],
2532
2740
  budgetPresetByLevel: {
2533
2741
  low: "reasoning_low",
2534
2742
  medium: "reasoning_medium",
2535
2743
  high: "reasoning_high",
2536
- xhigh: "reasoning_xhigh"
2537
- }
2744
+ max: "reasoning_xhigh"
2745
+ },
2746
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2538
2747
  },
2539
2748
  "claude-sonnet-4-5": {
2540
2749
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2572,10 +2781,12 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2572
2781
  }
2573
2782
  };
2574
2783
  var ANTHROPIC_ADAPTIVE_THINKING_MODELS = /* @__PURE__ */ new Set([
2784
+ "claude-fable-5",
2575
2785
  "claude-opus-4-8",
2576
- "claude-opus-4-7"
2786
+ "claude-opus-4-7",
2787
+ "claude-opus-4-6",
2788
+ "claude-sonnet-4-6"
2577
2789
  ]);
2578
- var toAnthropicOutputEffort = (level) => level === "xhigh" ? "max" : level;
2579
2790
  var normalizeRequestedReasoning = (value) => value ?? DEFAULT_REASONING_LEVEL;
2580
2791
  var resolveNearestSupportedLevel = (requested, supportedLevels) => {
2581
2792
  const supported = new Set(supportedLevels);
@@ -2609,12 +2820,14 @@ var resolveReasoningAgainstSupportedLevels = ({
2609
2820
  supportedLevels
2610
2821
  };
2611
2822
  };
2612
- var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(model);
2823
+ var normalizeResponsesModelId = (model) => model.startsWith("openai/") ? model.slice("openai/".length) : model;
2824
+ var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2825
+ var supportsResponsesMax = (model) => RESPONSES_MAX_SUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2613
2826
  var resolveResponsesReasoning = ({
2614
2827
  model,
2615
2828
  requested
2616
2829
  }) => {
2617
- const supportedLevels = supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER : REASONING_LEVEL_ORDER.slice(0, 3);
2830
+ const supportedLevels = supportsResponsesMax(model) ? REASONING_LEVEL_ORDER : supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER.slice(0, 4) : REASONING_LEVEL_ORDER.slice(0, 3);
2618
2831
  const resolution = resolveReasoningAgainstSupportedLevels({
2619
2832
  requested,
2620
2833
  supportedLevels
@@ -2654,19 +2867,18 @@ var resolveAnthropicReasoning = ({
2654
2867
  );
2655
2868
  }
2656
2869
  const budgetTokens = ANTHROPIC_BUDGET_PRESET_TOKENS[preset];
2870
+ const outputEffort = profile.outputEffortByLevel?.[resolution.applied];
2657
2871
  return {
2658
2872
  ...resolution,
2659
2873
  ...ANTHROPIC_ADAPTIVE_THINKING_MODELS.has(model) ? {
2660
- thinking: { type: "adaptive" },
2661
- outputConfig: {
2662
- effort: toAnthropicOutputEffort(resolution.applied)
2663
- }
2874
+ thinking: { type: "adaptive" }
2664
2875
  } : {
2665
2876
  thinking: {
2666
2877
  type: "enabled",
2667
2878
  budget_tokens: budgetTokens
2668
2879
  }
2669
2880
  },
2881
+ ...outputEffort ? { outputConfig: { effort: outputEffort } } : {},
2670
2882
  budgetPreset: preset,
2671
2883
  usedFallbackModelProfile
2672
2884
  };
@@ -2686,10 +2898,10 @@ var resolveZaiReasoning = ({
2686
2898
  requested
2687
2899
  }) => {
2688
2900
  const normalizedRequested = normalizeRequestedReasoning(requested);
2689
- if (normalizedRequested === "xhigh") {
2901
+ if (normalizedRequested === "xhigh" || normalizedRequested === "max") {
2690
2902
  return {
2691
2903
  requested: normalizedRequested,
2692
- applied: "xhigh",
2904
+ applied: normalizedRequested,
2693
2905
  effort: "max",
2694
2906
  fallbackApplied: false,
2695
2907
  supportedLevels: REASONING_LEVEL_ORDER
@@ -2845,7 +3057,7 @@ var buildModelRegistry = async (llm, options = {}) => {
2845
3057
  // src/permissions/approval-mode.ts
2846
3058
  var import_node_fs4 = require("fs");
2847
3059
  var import_node_path4 = __toESM(require("path"), 1);
2848
- var import_shared_types = require("@codelia/shared-types");
3060
+ var import_shared_types3 = require("@codelia/shared-types");
2849
3061
  var import_storage4 = require("@codelia/storage");
2850
3062
  var normalizePath = async (value) => {
2851
3063
  const absolute = import_node_path4.default.resolve(value);
@@ -2866,7 +3078,7 @@ var parseApprovalModeOrThrow = (raw, source) => {
2866
3078
  `Invalid ${source}: missing value (expected ${APPROVAL_MODE_HINT})`
2867
3079
  );
2868
3080
  }
2869
- const parsed = (0, import_shared_types.parseApprovalMode)(raw);
3081
+ const parsed = (0, import_shared_types3.parseApprovalMode)(raw);
2870
3082
  if (!parsed) {
2871
3083
  throw new Error(
2872
3084
  `Invalid ${source}: '${raw}' (expected ${APPROVAL_MODE_HINT})`
@@ -2903,13 +3115,13 @@ var resolvePolicyApprovalMode = (policy, projectKey) => {
2903
3115
  if (!policy) {
2904
3116
  return void 0;
2905
3117
  }
2906
- const projectMode = (0, import_shared_types.parseApprovalMode)(
3118
+ const projectMode = (0, import_shared_types3.parseApprovalMode)(
2907
3119
  policy.projects?.[projectKey]?.approval_mode
2908
3120
  );
2909
3121
  if (projectMode) {
2910
3122
  return { approvalMode: projectMode, source: "project" };
2911
3123
  }
2912
- const defaultMode = (0, import_shared_types.parseApprovalMode)(policy.default?.approval_mode);
3124
+ const defaultMode = (0, import_shared_types3.parseApprovalMode)(policy.default?.approval_mode);
2913
3125
  if (defaultMode) {
2914
3126
  return { approvalMode: defaultMode, source: "default" };
2915
3127
  }
@@ -8851,6 +9063,12 @@ var buildHostedSearchToolDefinitions = (provider, options) => {
8851
9063
  };
8852
9064
  var OPENAI_OAUTH_ORIGINATOR = "codelia";
8853
9065
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
9066
+ var loadHostTools = async (providers) => {
9067
+ const groups = await Promise.all(
9068
+ providers.map((provider) => Promise.resolve(provider.getTools()))
9069
+ );
9070
+ return groups.flat();
9071
+ };
8854
9072
  var buildOpenAiClientOptions = (authResolver, auth) => {
8855
9073
  if (auth.method === "api_key") {
8856
9074
  return { apiKey: auth.api_key };
@@ -8858,6 +9076,9 @@ var buildOpenAiClientOptions = (authResolver, auth) => {
8858
9076
  let accountId = auth.oauth.account_id;
8859
9077
  const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
8860
9078
  const apiKey = async () => {
9079
+ if (!authResolver.getOpenAiAccessToken) {
9080
+ throw new Error("OpenAI OAuth token refresh is unavailable");
9081
+ }
8861
9082
  const result = await authResolver.getOpenAiAccessToken();
8862
9083
  accountId = result.accountId ?? accountId;
8863
9084
  return result.token;
@@ -8960,7 +9181,10 @@ var resolveAnthropicStaticModelMaxTokens = (model) => {
8960
9181
  }
8961
9182
  return null;
8962
9183
  };
8963
- var resolveAnthropicModelMaxTokens = async (model) => {
9184
+ var resolveAnthropicModelMaxTokens = async (model, options) => {
9185
+ if (!options.useMetadata) {
9186
+ return resolveAnthropicStaticModelMaxTokens(model);
9187
+ }
8964
9188
  const metadataService = new import_model_metadata2.ModelMetadataServiceImpl({
8965
9189
  storagePathService: new import_storage8.StoragePathServiceImpl()
8966
9190
  });
@@ -9008,7 +9232,7 @@ var requestApprovalModeStartupSelection = async (state, projectKey) => {
9008
9232
  items: APPROVAL_MODE_STARTUP_PICK_ITEMS,
9009
9233
  multi: false
9010
9234
  });
9011
- const picked = (0, import_shared_types2.parseApprovalMode)(selection?.ids?.[0]);
9235
+ const picked = (0, import_shared_types4.parseApprovalMode)(selection?.ids?.[0]);
9012
9236
  if (!picked) {
9013
9237
  (0, import_logger.log)(`approval_mode startup selection skipped project=${projectKey}`);
9014
9238
  return null;
@@ -9153,7 +9377,12 @@ var requestMcpOAuthTokens = async (state, serverId, oauth2, errorMessage) => {
9153
9377
  var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMessage) => {
9154
9378
  const runId = state.activeRunId ?? void 0;
9155
9379
  if (runId) {
9156
- sendRunStatus(runId, "awaiting_ui", `MCP auth required: ${serverId}`);
9380
+ sendRunStatus(
9381
+ state,
9382
+ runId,
9383
+ "awaiting_ui",
9384
+ `MCP auth required: ${serverId}`
9385
+ );
9157
9386
  }
9158
9387
  try {
9159
9388
  const tokens = await requestMcpOAuthTokens(
@@ -9168,7 +9397,7 @@ var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMe
9168
9397
  return tokens;
9169
9398
  } finally {
9170
9399
  if (runId) {
9171
- sendRunStatus(runId, "running");
9400
+ sendRunStatus(state, runId, "running");
9172
9401
  }
9173
9402
  }
9174
9403
  };
@@ -9178,60 +9407,85 @@ var createAgentFactory = (state, options = {}) => {
9178
9407
  if (state.agent) return state.agent;
9179
9408
  if (inFlight) return inFlight;
9180
9409
  inFlight = (async () => {
9181
- const sandboxRoot = state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
9182
- const approvalModeResolution = await resolveApprovalModeForRuntime({
9183
- workingDir: sandboxRoot,
9184
- runtimeSandboxRoot: sandboxRoot,
9185
- requestStartupSelection: async ({ projectKey }) => {
9186
- return requestApprovalModeStartupSelection(state, projectKey);
9187
- },
9188
- deferStartupSelectionPersist: true
9189
- });
9190
- const ctx = await SandboxContext.create(sandboxRoot, {
9191
- approvalMode: approvalModeResolution.approvalMode
9192
- });
9193
- (0, import_logger.log)(
9194
- `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
9195
- );
9196
- const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
9197
- state.agentsResolver = agentsResolver;
9198
- let skillsConfig;
9199
- let executionEnvironmentConfig;
9200
- try {
9201
- [skillsConfig, executionEnvironmentConfig] = await Promise.all([
9202
- resolveSkillsConfig(ctx.workingDir),
9203
- resolveExecutionEnvironmentConfig(ctx.workingDir)
9204
- ]);
9205
- } catch (error) {
9206
- const message = error instanceof Error ? error.message : String(error);
9207
- throw new Error(message);
9410
+ const environment = state.effectiveEnvironment;
9411
+ const workspaceRoot = environment.workspace.root ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? void 0;
9412
+ const localRuntimeEnabled = environment.workspace.filesystem === "enabled" || environment.workspace.process === "runtime" || environment.tools.builtin === "full-coding-agent";
9413
+ let approvalModeResolution = {
9414
+ approvalMode: "minimal",
9415
+ source: "environment",
9416
+ projectKey: workspaceRoot ?? "disabled-workspace"
9417
+ };
9418
+ let ctx = null;
9419
+ let sandboxKey = null;
9420
+ let agentsResolver = null;
9421
+ let skillsResolver = null;
9422
+ if (localRuntimeEnabled) {
9423
+ const sandboxRoot = workspaceRoot ?? process.cwd();
9424
+ approvalModeResolution = await resolveApprovalModeForRuntime({
9425
+ workingDir: sandboxRoot,
9426
+ runtimeSandboxRoot: sandboxRoot,
9427
+ requestStartupSelection: async ({ projectKey }) => {
9428
+ return requestApprovalModeStartupSelection(state, projectKey);
9429
+ },
9430
+ deferStartupSelectionPersist: true
9431
+ });
9432
+ ctx = await SandboxContext.create(sandboxRoot, {
9433
+ approvalMode: approvalModeResolution.approvalMode
9434
+ });
9435
+ (0, import_logger.log)(
9436
+ `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
9437
+ );
9438
+ state.runtimeWorkingDir = ctx.workingDir;
9439
+ state.runtimeSandboxRoot = ctx.rootDir;
9440
+ sandboxKey = createSandboxKey(ctx);
9441
+ }
9442
+ if (environment.context.projectInstructions === "from-workspace" && workspaceRoot) {
9443
+ agentsResolver = state.agentsResolver ?? await AgentsResolver.create(workspaceRoot);
9444
+ state.agentsResolver = agentsResolver;
9445
+ }
9446
+ if (environment.context.skills === "from-config" && workspaceRoot) {
9447
+ let skillsConfig;
9448
+ try {
9449
+ skillsConfig = await resolveEnvironmentSkillsConfig(
9450
+ state,
9451
+ workspaceRoot
9452
+ );
9453
+ } catch (error) {
9454
+ const message = error instanceof Error ? error.message : String(error);
9455
+ throw new Error(message);
9456
+ }
9457
+ skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
9458
+ workingDir: workspaceRoot,
9459
+ config: skillsConfig
9460
+ });
9461
+ state.skillsResolver = skillsResolver;
9462
+ state.updateSkillsSnapshot(workspaceRoot, skillsResolver.getSnapshot());
9208
9463
  }
9209
- const skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
9210
- workingDir: ctx.workingDir,
9211
- config: skillsConfig
9212
- });
9213
- state.skillsResolver = skillsResolver;
9214
- state.updateSkillsSnapshot(ctx.workingDir, skillsResolver.getSnapshot());
9215
- state.runtimeWorkingDir = ctx.workingDir;
9216
- state.runtimeSandboxRoot = ctx.rootDir;
9217
9464
  state.approvalMode = approvalModeResolution.approvalMode;
9218
- const sandboxKey = createSandboxKey(ctx);
9465
+ const toolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore ?? (environment.persistence.mode === "runtime" ? new import_storage8.ToolOutputCacheStoreImpl() : null);
9219
9466
  const todoSessionContextKey = createToolSessionContextKey(
9220
9467
  () => state.sessionId
9221
9468
  );
9222
- const agentsResolverKey = createAgentsResolverKey(agentsResolver);
9223
- const skillsResolverKey = createSkillsResolverKey(skillsResolver);
9224
- const toolOutputCacheStore = new import_storage8.ToolOutputCacheStoreImpl();
9225
- const baseLocalTools = createTools(
9226
- sandboxKey,
9227
- agentsResolverKey,
9228
- skillsResolverKey,
9229
- {
9230
- toolOutputCacheStore,
9231
- todoSessionContextKey,
9232
- taskManager: options.taskManager
9469
+ let baseLocalTools = [];
9470
+ if (environment.tools.builtin === "full-coding-agent") {
9471
+ if (!ctx || !sandboxKey || !agentsResolver || !skillsResolver) {
9472
+ throw new Error(
9473
+ "full coding-agent tools require local sandbox, AGENTS, and skills context"
9474
+ );
9233
9475
  }
9234
- );
9476
+ const agentsResolverKey = createAgentsResolverKey(agentsResolver);
9477
+ const skillsResolverKey = createSkillsResolverKey(skillsResolver);
9478
+ baseLocalTools = createTools(
9479
+ sandboxKey,
9480
+ agentsResolverKey,
9481
+ skillsResolverKey,
9482
+ {
9483
+ toolOutputCacheStore,
9484
+ todoSessionContextKey,
9485
+ taskManager: options.taskManager
9486
+ }
9487
+ );
9488
+ }
9235
9489
  const editTool = baseLocalTools.find(
9236
9490
  (tool) => tool.definition.name === "edit"
9237
9491
  );
@@ -9239,7 +9493,7 @@ var createAgentFactory = (state, options = {}) => {
9239
9493
  (tool) => tool.definition.name === "apply_patch"
9240
9494
  );
9241
9495
  let mcpTools = [];
9242
- if (options.mcpManager) {
9496
+ if (environment.tools.mcp === "from-config" && options.mcpManager) {
9243
9497
  try {
9244
9498
  mcpTools = await options.mcpManager.getTools({
9245
9499
  onStatus: (message) => {
@@ -9258,12 +9512,24 @@ var createAgentFactory = (state, options = {}) => {
9258
9512
  (0, import_logger.log)(`failed to load mcp tools: ${String(error)}`);
9259
9513
  }
9260
9514
  }
9261
- const baseSystemPrompt = await loadSystemPrompt(ctx.workingDir);
9262
- const executionEnvironmentContext = await buildExecutionEnvironmentContext({
9263
- workingDir: ctx.workingDir,
9264
- sandboxRoot: ctx.rootDir,
9265
- config: executionEnvironmentConfig
9266
- });
9515
+ const hostTools = environment.tools.host === "enabled" ? await loadHostTools(environment.adapters.toolProviders ?? []) : [];
9516
+ const hostToolNames = new Set(hostTools.map((tool) => tool.name));
9517
+ const baseSystemPrompt = await loadEnvironmentSystemPrompt(
9518
+ state,
9519
+ workspaceRoot
9520
+ );
9521
+ let executionEnvironmentContext = null;
9522
+ if (environment.context.executionEnvironment === "from-config" && workspaceRoot && ctx) {
9523
+ const executionEnvironmentConfig = await resolveEnvironmentExecutionEnvironmentConfig(
9524
+ state,
9525
+ workspaceRoot
9526
+ );
9527
+ executionEnvironmentContext = await buildExecutionEnvironmentContext({
9528
+ workingDir: workspaceRoot,
9529
+ sandboxRoot: ctx.rootDir,
9530
+ config: executionEnvironmentConfig
9531
+ });
9532
+ }
9267
9533
  state.executionEnvironmentContext = executionEnvironmentContext;
9268
9534
  if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
9269
9535
  alreadyLogged: state.executionEnvironmentDebugLogged
@@ -9276,16 +9542,16 @@ var createAgentFactory = (state, options = {}) => {
9276
9542
  );
9277
9543
  const withAgentsContext = appendInitialAgentsContext(
9278
9544
  withExecutionEnvironment,
9279
- agentsResolver.buildInitialContext()
9545
+ agentsResolver?.buildInitialContext() ?? null
9280
9546
  );
9281
9547
  const systemPrompt = appendInitialSkillsCatalog(
9282
9548
  withAgentsContext,
9283
- await skillsResolver.buildInitialContext()
9549
+ skillsResolver ? await skillsResolver.buildInitialContext() : null
9284
9550
  );
9285
9551
  state.systemPrompt = systemPrompt;
9286
9552
  let permissionsConfig;
9287
9553
  try {
9288
- permissionsConfig = await resolvePermissionsConfig(ctx.workingDir);
9554
+ permissionsConfig = environment.config.source === "disabled" || !workspaceRoot ? void 0 : await resolveEnvironmentPermissionsConfig(state, workspaceRoot);
9289
9555
  } catch (error) {
9290
9556
  const message = error instanceof Error ? error.message : String(error);
9291
9557
  throw new Error(message);
@@ -9294,42 +9560,56 @@ var createAgentFactory = (state, options = {}) => {
9294
9560
  approvalMode: approvalModeResolution.approvalMode,
9295
9561
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
9296
9562
  user: permissionsConfig,
9297
- bashPathGuard: {
9298
- rootDir: ctx.rootDir,
9299
- workingDir: ctx.workingDir
9300
- }
9563
+ ...ctx ? {
9564
+ bashPathGuard: {
9565
+ rootDir: ctx.rootDir,
9566
+ workingDir: ctx.workingDir
9567
+ }
9568
+ } : {}
9301
9569
  });
9302
9570
  (0, import_logger.log)(
9303
9571
  `approval_mode resolved=${approvalModeResolution.approvalMode} source=${approvalModeResolution.source} project=${approvalModeResolution.projectKey}`
9304
9572
  );
9305
9573
  let modelConfig;
9306
9574
  try {
9307
- modelConfig = await resolveEffectiveModelConfig(state, ctx.workingDir);
9575
+ modelConfig = await resolveEffectiveModelConfig(state, workspaceRoot);
9308
9576
  } catch (error) {
9309
9577
  const message = error instanceof Error ? error.message : String(error);
9310
9578
  throw new Error(message);
9311
9579
  }
9312
- const authResolver = await AuthResolver.create(state, import_logger.log);
9580
+ const authResolver = await createEnvironmentAuthResolver(state, import_logger.log);
9313
9581
  const provider = await authResolver.resolveProvider(modelConfig.provider);
9314
9582
  const providerAuth = await authResolver.resolveProviderAuth(provider);
9315
- const searchConfig = await resolveSearchConfig(ctx.workingDir);
9316
- const hostedSearchDefinitions = buildHostedSearchToolDefinitions(
9317
- provider,
9318
- searchConfig
9319
- );
9320
- if (searchConfig.mode === "native" && hostedSearchDefinitions.length === 0) {
9321
- throw new Error(
9322
- `search.mode=native is enabled, but native search is unavailable for provider '${provider}'.`
9583
+ let hostedSearchDefinitions = [];
9584
+ let localSearchTools = [];
9585
+ if (environment.tools.search === "from-config") {
9586
+ const searchConfig = await resolveEnvironmentSearchConfig(
9587
+ state,
9588
+ workspaceRoot
9589
+ );
9590
+ hostedSearchDefinitions = buildHostedSearchToolDefinitions(
9591
+ provider,
9592
+ searchConfig
9323
9593
  );
9594
+ if (searchConfig.mode === "native" && hostedSearchDefinitions.length === 0) {
9595
+ throw new Error(
9596
+ `search.mode=native is enabled, but native search is unavailable for provider '${provider}'.`
9597
+ );
9598
+ }
9599
+ const useLocalSearchTool = searchConfig.mode === "local" || searchConfig.mode === "auto" && hostedSearchDefinitions.length === 0;
9600
+ localSearchTools = useLocalSearchTool ? [
9601
+ createSearchTool({
9602
+ defaultBackend: searchConfig.local.backend,
9603
+ braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
9604
+ })
9605
+ ] : [];
9324
9606
  }
9325
- const useLocalSearchTool = searchConfig.mode === "local" || searchConfig.mode === "auto" && hostedSearchDefinitions.length === 0;
9326
- const localSearchTools = useLocalSearchTool ? [
9327
- createSearchTool({
9328
- defaultBackend: searchConfig.local.backend,
9329
- braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
9330
- })
9331
- ] : [];
9332
- const tools = [...baseLocalTools, ...localSearchTools, ...mcpTools];
9607
+ const tools = [
9608
+ ...baseLocalTools,
9609
+ ...localSearchTools,
9610
+ ...mcpTools,
9611
+ ...hostTools
9612
+ ];
9333
9613
  state.tools = tools;
9334
9614
  state.toolDefinitions = [
9335
9615
  ...tools.map((tool) => tool.definition),
@@ -9404,7 +9684,12 @@ var createAgentFactory = (state, options = {}) => {
9404
9684
  );
9405
9685
  }
9406
9686
  });
9407
- const modelMaxTokens = await resolveAnthropicModelMaxTokens(modelName);
9687
+ const modelMaxTokens = await resolveAnthropicModelMaxTokens(
9688
+ modelName,
9689
+ {
9690
+ useMetadata: environment.persistence.mode === "runtime"
9691
+ }
9692
+ );
9408
9693
  const maxTokens = resolveAnthropicMaxTokens({
9409
9694
  thinkingBudgetTokens: reasoning.thinking.type === "enabled" ? reasoning.thinking.budget_tokens : 0,
9410
9695
  modelLimitMaxTokens: modelMaxTokens
@@ -9461,9 +9746,9 @@ var createAgentFactory = (state, options = {}) => {
9461
9746
  state.currentModelProvider = provider;
9462
9747
  state.currentModelName = resolvedModelName;
9463
9748
  state.currentModelSource = modelConfig.source;
9464
- const modelRegistry = await buildModelRegistry(llm, {
9749
+ const modelRegistry = environment.persistence.mode === "runtime" ? await buildModelRegistry(llm, {
9465
9750
  strict: provider !== "openrouter"
9466
- });
9751
+ }) : import_core21.DEFAULT_MODEL_REGISTRY;
9467
9752
  const totalBudgetTrimEnabled = envTruthy(
9468
9753
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
9469
9754
  );
@@ -9478,6 +9763,12 @@ var createAgentFactory = (state, options = {}) => {
9478
9763
  },
9479
9764
  services: { toolOutputCacheStore },
9480
9765
  canExecuteTool: async (call, rawArgs, toolCtx) => {
9766
+ if (hostToolNames.has(call.function.name)) {
9767
+ (0, import_logger.debugLog)(
9768
+ `permission.evaluate tool=${call.function.name} decision=allow reason=host-tool`
9769
+ );
9770
+ return { decision: "allow" };
9771
+ }
9481
9772
  if (state.autoApprovedClientToolNames.has(call.function.name)) {
9482
9773
  (0, import_logger.debugLog)(
9483
9774
  `permission.evaluate tool=${call.function.name} decision=allow reason=client-tool-auto-approved`
@@ -9530,6 +9821,9 @@ var createAgentFactory = (state, options = {}) => {
9530
9821
  content
9531
9822
  }) ?? previewLanguage;
9532
9823
  try {
9824
+ if (!sandboxKey) {
9825
+ throw new Error("sandbox is unavailable");
9826
+ }
9533
9827
  const sandbox = await getSandboxContext(toolCtx, sandboxKey);
9534
9828
  const resolved = sandbox.resolvePath(filePath);
9535
9829
  let before = "";
@@ -9652,6 +9946,7 @@ var createAgentFactory = (state, options = {}) => {
9652
9946
  tool_call_id: call.id
9653
9947
  });
9654
9948
  await sendRunStatusAsync(
9949
+ state,
9655
9950
  runId,
9656
9951
  "awaiting_ui",
9657
9952
  "waiting for confirmation"
@@ -9667,7 +9962,7 @@ var createAgentFactory = (state, options = {}) => {
9667
9962
  allow_reason: true
9668
9963
  });
9669
9964
  if (runId) {
9670
- sendRunStatus(runId, "running");
9965
+ sendRunStatus(state, runId, "running");
9671
9966
  }
9672
9967
  if (!confirmResult?.ok) {
9673
9968
  const providedReason = confirmResult?.reason?.trim() ?? "";
@@ -9687,11 +9982,13 @@ var createAgentFactory = (state, options = {}) => {
9687
9982
  `permission.remember tool=${call.function.name} rules=${rules.length}`
9688
9983
  );
9689
9984
  if (rules.length) {
9690
- void appendPermissionAllowRules(ctx.workingDir, rules).catch(
9691
- (error) => {
9692
- (0, import_logger.log)(`failed to persist permission: ${String(error)}`);
9693
- }
9694
- );
9985
+ void appendEnvironmentPermissionAllowRules(
9986
+ state,
9987
+ workspaceRoot,
9988
+ rules
9989
+ ).catch((error) => {
9990
+ (0, import_logger.log)(`failed to persist permission: ${String(error)}`);
9991
+ });
9695
9992
  }
9696
9993
  }
9697
9994
  return { decision: "allow" };
@@ -9711,6 +10008,213 @@ var createAgentFactory = (state, options = {}) => {
9711
10008
  };
9712
10009
  };
9713
10010
 
10011
+ // src/environment.ts
10012
+ var import_node_path15 = __toESM(require("path"), 1);
10013
+ var cloneContract = (contract) => ({
10014
+ workspace: { ...contract.workspace },
10015
+ context: { ...contract.context },
10016
+ auth: { ...contract.auth },
10017
+ config: { ...contract.config },
10018
+ tools: { ...contract.tools },
10019
+ persistence: { ...contract.persistence },
10020
+ events: { ...contract.events }
10021
+ });
10022
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? import_node_path15.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
10023
+ var runtimeEnvironmentPresets = {
10024
+ "tui-local": {
10025
+ workspace: {
10026
+ filesystem: "enabled",
10027
+ process: "runtime"
10028
+ },
10029
+ context: {
10030
+ systemPrompt: "runtime-default",
10031
+ projectInstructions: "from-workspace",
10032
+ skills: "from-config",
10033
+ executionEnvironment: "from-config"
10034
+ },
10035
+ auth: { model: "runtime-default" },
10036
+ config: { source: "runtime-default" },
10037
+ tools: {
10038
+ builtin: "full-coding-agent",
10039
+ search: "from-config",
10040
+ mcp: "from-config",
10041
+ host: "disabled"
10042
+ },
10043
+ persistence: { mode: "runtime" },
10044
+ events: { live: "json-rpc" }
10045
+ },
10046
+ "embedded-no-local-tools": {
10047
+ workspace: {
10048
+ filesystem: "disabled",
10049
+ process: "disabled"
10050
+ },
10051
+ context: {
10052
+ systemPrompt: "host",
10053
+ projectInstructions: "disabled",
10054
+ skills: "disabled",
10055
+ executionEnvironment: "disabled"
10056
+ },
10057
+ auth: { model: "host" },
10058
+ config: { source: "host" },
10059
+ tools: {
10060
+ builtin: "none",
10061
+ search: "disabled",
10062
+ mcp: "disabled",
10063
+ host: "enabled"
10064
+ },
10065
+ persistence: { mode: "volatile" },
10066
+ events: { live: "host" }
10067
+ }
10068
+ };
10069
+ var expandEnvironmentInput = (input) => {
10070
+ if (!input) {
10071
+ return {
10072
+ contract: cloneContract(runtimeEnvironmentPresets["tui-local"]),
10073
+ sourcePreset: "tui-local"
10074
+ };
10075
+ }
10076
+ if ("preset" in input) {
10077
+ return {
10078
+ contract: cloneContract(runtimeEnvironmentPresets[input.preset]),
10079
+ sourcePreset: input.preset
10080
+ };
10081
+ }
10082
+ return { contract: cloneContract(input.contract) };
10083
+ };
10084
+ var requireAdapter = (condition, name, reason) => {
10085
+ if (!condition) return;
10086
+ throw new Error(`Runtime environment requires adapters.${name}: ${reason}`);
10087
+ };
10088
+ var rejectContract = (condition, reason) => {
10089
+ if (!condition) return;
10090
+ throw new Error(`Invalid runtime environment: ${reason}`);
10091
+ };
10092
+ var resolveToolNames = (contract) => {
10093
+ const modelVisible = [];
10094
+ const operatorOnly = [];
10095
+ const disabled = [];
10096
+ if (contract.tools.builtin === "full-coding-agent") {
10097
+ modelVisible.push("builtin:full-coding-agent");
10098
+ } else {
10099
+ disabled.push("builtin");
10100
+ }
10101
+ if (contract.tools.search === "from-config") {
10102
+ modelVisible.push("search:from-config");
10103
+ } else {
10104
+ disabled.push("search");
10105
+ }
10106
+ if (contract.tools.mcp === "from-config") {
10107
+ modelVisible.push("mcp:from-config");
10108
+ operatorOnly.push("mcp.list");
10109
+ } else {
10110
+ disabled.push("mcp");
10111
+ }
10112
+ if (contract.tools.host === "enabled") {
10113
+ modelVisible.push("host-tools");
10114
+ } else {
10115
+ disabled.push("host-tools");
10116
+ }
10117
+ if (contract.workspace.process === "runtime") {
10118
+ operatorOnly.push("shell.*", "task.*");
10119
+ } else {
10120
+ disabled.push("process");
10121
+ }
10122
+ if (contract.context.skills === "from-config") {
10123
+ operatorOnly.push("skills.list");
10124
+ } else {
10125
+ disabled.push("skills");
10126
+ }
10127
+ if (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config") {
10128
+ operatorOnly.push("context.inspect");
10129
+ } else {
10130
+ disabled.push("local-context");
10131
+ }
10132
+ return { modelVisible, operatorOnly, disabled };
10133
+ };
10134
+ var resolveRuntimeEnvironment = (options = {}) => {
10135
+ const { contract, sourcePreset } = expandEnvironmentInput(
10136
+ options.environment
10137
+ );
10138
+ const adapters = options.adapters ?? {};
10139
+ if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
10140
+ contract.workspace.root = import_node_path15.default.resolve(
10141
+ contract.workspace.root ?? defaultWorkspaceRoot()
10142
+ );
10143
+ } else if (contract.workspace.root) {
10144
+ contract.workspace.root = import_node_path15.default.resolve(contract.workspace.root);
10145
+ }
10146
+ rejectContract(
10147
+ 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"),
10148
+ "workspace filesystem is disabled but local workspace context/tools are enabled"
10149
+ );
10150
+ rejectContract(
10151
+ contract.workspace.process === "disabled" && contract.tools.builtin === "full-coding-agent",
10152
+ "full coding-agent builtin tools require runtime process support"
10153
+ );
10154
+ rejectContract(
10155
+ contract.tools.builtin === "full-coding-agent" && (contract.context.projectInstructions !== "from-workspace" || contract.context.skills !== "from-config"),
10156
+ "full coding-agent builtin tools require workspace project instructions and skills context"
10157
+ );
10158
+ rejectContract(
10159
+ contract.config.source === "disabled" && (contract.tools.search === "from-config" || contract.tools.mcp === "from-config" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config"),
10160
+ "config source is disabled but config-backed features are enabled"
10161
+ );
10162
+ rejectContract(
10163
+ contract.workspace.process === "runtime" && contract.persistence.mode === "volatile" && !adapters.stores?.taskManager,
10164
+ "runtime process support with volatile persistence requires adapters.stores.taskManager"
10165
+ );
10166
+ requireAdapter(
10167
+ contract.context.systemPrompt === "host" && !adapters.systemPromptProvider,
10168
+ "systemPromptProvider",
10169
+ "context.systemPrompt=host"
10170
+ );
10171
+ requireAdapter(
10172
+ contract.config.source === "host" && !adapters.configProvider,
10173
+ "configProvider",
10174
+ "config.source=host"
10175
+ );
10176
+ requireAdapter(
10177
+ contract.auth.model === "host" && !adapters.credentialProvider,
10178
+ "credentialProvider",
10179
+ "auth.model=host"
10180
+ );
10181
+ requireAdapter(
10182
+ contract.events.live === "host" && !adapters.eventSink,
10183
+ "eventSink",
10184
+ "events.live=host"
10185
+ );
10186
+ requireAdapter(
10187
+ contract.tools.host === "enabled" && !adapters.toolProviders,
10188
+ "toolProviders",
10189
+ "tools.host=enabled"
10190
+ );
10191
+ const resolvedTools = resolveToolNames(contract);
10192
+ const summary = {
10193
+ ...sourcePreset ? { source_preset: sourcePreset } : {},
10194
+ workspace: { ...contract.workspace },
10195
+ context: { ...contract.context },
10196
+ auth: { ...contract.auth },
10197
+ config: { ...contract.config },
10198
+ tools: {
10199
+ ...contract.tools,
10200
+ model_visible: [...resolvedTools.modelVisible],
10201
+ operator_only: [...resolvedTools.operatorOnly],
10202
+ disabled: [...resolvedTools.disabled]
10203
+ },
10204
+ persistence: { ...contract.persistence },
10205
+ events: { ...contract.events }
10206
+ };
10207
+ return {
10208
+ ...contract,
10209
+ ...sourcePreset ? { sourcePreset } : {},
10210
+ adapters,
10211
+ resolvedTools,
10212
+ summary
10213
+ };
10214
+ };
10215
+ 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";
10216
+ var isProcessEnabled = (environment) => environment.workspace.process === "runtime";
10217
+
9714
10218
  // src/mcp/auth-store.ts
9715
10219
  var import_storage9 = require("@codelia/storage");
9716
10220
 
@@ -10880,6 +11384,101 @@ var SERVER_NAME = "codelia-runtime";
10880
11384
  var SERVER_VERSION = "0.1.0";
10881
11385
  var PROTOCOL_VERSION = "0";
10882
11386
 
11387
+ // src/volatile-stores.ts
11388
+ var stringifyMessageContent = (value) => {
11389
+ if (typeof value === "string") return value;
11390
+ if (Array.isArray(value)) {
11391
+ const parts = value.map((part) => {
11392
+ if (!part || typeof part !== "object") return "";
11393
+ const record = part;
11394
+ return typeof record.text === "string" ? record.text : "";
11395
+ }).filter((part) => part.length > 0);
11396
+ return parts.length ? parts.join("") : void 0;
11397
+ }
11398
+ return void 0;
11399
+ };
11400
+ var toSummary = (state) => {
11401
+ let lastUserMessage;
11402
+ for (let index = state.messages.length - 1; index >= 0; index -= 1) {
11403
+ const message = state.messages[index];
11404
+ if (message?.role !== "user") continue;
11405
+ lastUserMessage = stringifyMessageContent(message.content);
11406
+ break;
11407
+ }
11408
+ return {
11409
+ session_id: state.session_id,
11410
+ updated_at: state.updated_at,
11411
+ ...state.run_id ? { run_id: state.run_id } : {},
11412
+ message_count: state.messages.length,
11413
+ ...lastUserMessage ? { last_user_message: lastUserMessage } : {}
11414
+ };
11415
+ };
11416
+ var VolatileSessionStateStore = class {
11417
+ states = /* @__PURE__ */ new Map();
11418
+ async load(sessionId) {
11419
+ const state = this.states.get(sessionId);
11420
+ return state ? structuredClone(state) : null;
11421
+ }
11422
+ async save(state) {
11423
+ this.states.set(state.session_id, structuredClone(state));
11424
+ }
11425
+ async list() {
11426
+ return Array.from(this.states.values()).map(toSummary).sort((left, right) => right.updated_at.localeCompare(left.updated_at));
11427
+ }
11428
+ };
11429
+ var VolatileRunEventStoreFactory = class {
11430
+ records = /* @__PURE__ */ new Map();
11431
+ create(init) {
11432
+ const records = [];
11433
+ this.records.set(init.runId, records);
11434
+ return {
11435
+ append: (record) => {
11436
+ records.push(structuredClone(record));
11437
+ }
11438
+ };
11439
+ }
11440
+ };
11441
+ var VolatileToolOutputCacheStore = class {
11442
+ records = /* @__PURE__ */ new Map();
11443
+ async save(record) {
11444
+ const id = record.tool_call_id;
11445
+ this.records.set(id, structuredClone(record));
11446
+ return {
11447
+ id,
11448
+ byte_size: Buffer.byteLength(record.content, "utf8"),
11449
+ line_count: record.content.split(/\r?\n/).length
11450
+ };
11451
+ }
11452
+ async read(refId, options = {}) {
11453
+ const record = this.records.get(refId);
11454
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11455
+ const lines = record.content.split(/\r?\n/);
11456
+ const offset = Math.max(0, Math.trunc(options.offset ?? 0));
11457
+ const limit = Math.max(1, Math.trunc(options.limit ?? lines.length));
11458
+ return lines.slice(offset, offset + limit).join("\n");
11459
+ }
11460
+ async readLine(refId, options) {
11461
+ const record = this.records.get(refId);
11462
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11463
+ const lines = record.content.split(/\r?\n/);
11464
+ const line = lines[options.line_number - 1];
11465
+ if (line === void 0) {
11466
+ return `Line number out of range: ${options.line_number} (total ${lines.length})`;
11467
+ }
11468
+ const offset = Math.max(0, Math.trunc(options.char_offset ?? 0));
11469
+ const limit = Math.max(1, Math.trunc(options.char_limit ?? line.length));
11470
+ return line.slice(offset, offset + limit);
11471
+ }
11472
+ async grep(refId, options) {
11473
+ const record = this.records.get(refId);
11474
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11475
+ const query = options.pattern.toLowerCase();
11476
+ return record.content.split(/\r?\n/).map((line, index) => ({ line, index })).filter(({ line }) => line.toLowerCase().includes(query)).slice(0, options.max_matches ?? 50).map(
11477
+ ({ line, index }) => `${String(index + 1).padStart(6, "0")} ${line}`
11478
+ ).join("\n");
11479
+ }
11480
+ };
11481
+
10883
11482
  // src/rpc/context.ts
10884
11483
  var import_protocol2 = require("@codelia/protocol");
10885
11484
  var createContextHandlers = ({
@@ -10887,10 +11486,14 @@ var createContextHandlers = ({
10887
11486
  log: log2
10888
11487
  }) => {
10889
11488
  const ensureAgentsResolver = async () => {
11489
+ if (state.effectiveEnvironment.context.projectInstructions !== "from-workspace") {
11490
+ return null;
11491
+ }
10890
11492
  if (state.agentsResolver) {
10891
11493
  return state.agentsResolver;
10892
11494
  }
10893
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11495
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11496
+ if (!workingDir) return null;
10894
11497
  try {
10895
11498
  const resolver = await AgentsResolver.create(workingDir);
10896
11499
  state.agentsResolver = resolver;
@@ -10905,14 +11508,18 @@ var createContextHandlers = ({
10905
11508
  }
10906
11509
  };
10907
11510
  const ensureSkillsResolver = async () => {
11511
+ if (state.effectiveEnvironment.context.skills !== "from-config") {
11512
+ return null;
11513
+ }
10908
11514
  if (state.skillsResolver) {
10909
11515
  return state.skillsResolver;
10910
11516
  }
10911
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11517
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11518
+ if (!workingDir) return null;
10912
11519
  try {
10913
11520
  const resolver = await SkillsResolver.create({
10914
11521
  workingDir,
10915
- config: await resolveSkillsConfig(workingDir)
11522
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
10916
11523
  });
10917
11524
  state.skillsResolver = resolver;
10918
11525
  state.runtimeWorkingDir = workingDir;
@@ -10926,16 +11533,23 @@ var createContextHandlers = ({
10926
11533
  }
10927
11534
  };
10928
11535
  const ensureExecutionEnvironmentContext = async () => {
11536
+ if (state.effectiveEnvironment.context.executionEnvironment !== "from-config") {
11537
+ return null;
11538
+ }
10929
11539
  if (state.executionEnvironmentContext) {
10930
11540
  return state.executionEnvironmentContext;
10931
11541
  }
10932
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11542
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11543
+ if (!workingDir) return null;
10933
11544
  const sandboxRoot = state.runtimeSandboxRoot ?? workingDir;
10934
11545
  try {
10935
11546
  const context = await buildExecutionEnvironmentContext({
10936
11547
  workingDir,
10937
11548
  sandboxRoot,
10938
- config: await resolveExecutionEnvironmentConfig(workingDir)
11549
+ config: await resolveEnvironmentExecutionEnvironmentConfig(
11550
+ state,
11551
+ workingDir
11552
+ )
10939
11553
  });
10940
11554
  state.executionEnvironmentContext = context;
10941
11555
  state.runtimeWorkingDir = workingDir;
@@ -10957,6 +11571,7 @@ var createContextHandlers = ({
10957
11571
  runtime_working_dir: state.runtimeWorkingDir ?? void 0,
10958
11572
  runtime_sandbox_root: state.runtimeSandboxRoot ?? void 0,
10959
11573
  execution_environment: executionEnvironment ?? void 0,
11574
+ runtime_environment: state.effectiveEnvironment.summary,
10960
11575
  ui_context: {
10961
11576
  cwd: state.lastUiContext?.cwd,
10962
11577
  workspace_root: state.lastUiContext?.workspace_root,
@@ -11006,7 +11621,7 @@ var createContextHandlers = ({
11006
11621
 
11007
11622
  // src/rpc/history.ts
11008
11623
  var import_node_fs16 = require("fs");
11009
- var import_node_path15 = __toESM(require("path"), 1);
11624
+ var import_node_path16 = __toESM(require("path"), 1);
11010
11625
  var import_node_readline2 = require("readline");
11011
11626
  var import_protocol3 = require("@codelia/protocol");
11012
11627
  var import_storage10 = require("@codelia/storage");
@@ -11080,7 +11695,7 @@ var collectRunCandidates = async (log2) => {
11080
11695
  for (const yearEntry of yearEntries) {
11081
11696
  if (!yearEntry.isDirectory()) continue;
11082
11697
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
11083
- const yearPath = import_node_path15.default.join(sessionsDir, yearEntry.name);
11698
+ const yearPath = import_node_path16.default.join(sessionsDir, yearEntry.name);
11084
11699
  let monthEntries;
11085
11700
  try {
11086
11701
  monthEntries = await import_node_fs16.promises.readdir(yearPath, {
@@ -11093,7 +11708,7 @@ var collectRunCandidates = async (log2) => {
11093
11708
  for (const monthEntry of monthEntries) {
11094
11709
  if (!monthEntry.isDirectory()) continue;
11095
11710
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
11096
- const monthPath = import_node_path15.default.join(yearPath, monthEntry.name);
11711
+ const monthPath = import_node_path16.default.join(yearPath, monthEntry.name);
11097
11712
  let dayEntries;
11098
11713
  try {
11099
11714
  dayEntries = await import_node_fs16.promises.readdir(monthPath, {
@@ -11106,7 +11721,7 @@ var collectRunCandidates = async (log2) => {
11106
11721
  for (const dayEntry of dayEntries) {
11107
11722
  if (!dayEntry.isDirectory()) continue;
11108
11723
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
11109
- const dayPath = import_node_path15.default.join(monthPath, dayEntry.name);
11724
+ const dayPath = import_node_path16.default.join(monthPath, dayEntry.name);
11110
11725
  let files;
11111
11726
  try {
11112
11727
  files = await import_node_fs16.promises.readdir(dayPath, {
@@ -11119,7 +11734,7 @@ var collectRunCandidates = async (log2) => {
11119
11734
  for (const file of files) {
11120
11735
  if (!file.isFile()) continue;
11121
11736
  if (!file.name.endsWith(".jsonl")) continue;
11122
- const filePath = import_node_path15.default.join(dayPath, file.name);
11737
+ const filePath = import_node_path16.default.join(dayPath, file.name);
11123
11738
  try {
11124
11739
  const stat = await import_node_fs16.promises.stat(filePath);
11125
11740
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -11147,7 +11762,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
11147
11762
  const header = parseRunHeader(headerLine);
11148
11763
  if (!header) continue;
11149
11764
  if (header.session_id !== sessionId) continue;
11150
- const runId = header.run_id ?? import_node_path15.default.basename(candidate.path, ".jsonl");
11765
+ const runId = header.run_id ?? import_node_path16.default.basename(candidate.path, ".jsonl");
11151
11766
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
11152
11767
  runs.push({
11153
11768
  path: candidate.path,
@@ -11193,14 +11808,16 @@ var sendHistoryEvent = (runId, seq, event) => {
11193
11808
  var createHistoryHandlers = ({
11194
11809
  sessionStateStore,
11195
11810
  log: log2,
11811
+ readRunLogs = true,
11196
11812
  getCurrentWorkspaceRoot,
11197
- buildResumeDiffSummary
11813
+ buildResumeDiffSummary,
11814
+ sendHistoryEvent: emitHistoryEvent = sendHistoryEvent
11198
11815
  }) => {
11199
11816
  const normalizeWorkspaceRoot = (value) => {
11200
11817
  if (typeof value !== "string") return void 0;
11201
11818
  const trimmed = value.trim();
11202
11819
  if (!trimmed) return void 0;
11203
- return import_node_path15.default.resolve(trimmed);
11820
+ return import_node_path16.default.resolve(trimmed);
11204
11821
  };
11205
11822
  const handleSessionList = async (id, params) => {
11206
11823
  const limit = params?.limit ?? 50;
@@ -11250,7 +11867,7 @@ var createHistoryHandlers = ({
11250
11867
  sendResult(id, result2);
11251
11868
  return;
11252
11869
  }
11253
- const runs = await collectSessionRuns(sessionId, maxRuns, log2);
11870
+ const runs = readRunLogs ? await collectSessionRuns(sessionId, maxRuns, log2) : [];
11254
11871
  const replayEvents = [];
11255
11872
  for (const run of runs) {
11256
11873
  for await (const line of readJsonl(run.path)) {
@@ -11287,7 +11904,7 @@ var createHistoryHandlers = ({
11287
11904
  const truncated = replayEvents.length > maxEvents;
11288
11905
  const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
11289
11906
  for (const event of selectedEvents) {
11290
- sendHistoryEvent(event.runId, event.seq, event.event);
11907
+ await emitHistoryEvent(event.runId, event.seq, event.event);
11291
11908
  }
11292
11909
  let resumeDiff;
11293
11910
  if (buildResumeDiffSummary) {
@@ -11396,7 +12013,10 @@ var sortModelsByReleaseDate = (models, provider, providerEntries) => {
11396
12013
  });
11397
12014
  return sortable.map((item) => item.model);
11398
12015
  };
11399
- var loadProviderModelEntries = async (provider) => {
12016
+ var loadProviderModelEntries = async (provider, state) => {
12017
+ if (state?.effectiveEnvironment.persistence.mode === "volatile") {
12018
+ return null;
12019
+ }
11400
12020
  const metadataService = new import_model_metadata3.ModelMetadataServiceImpl();
11401
12021
  const allEntries = await metadataService.getAllModelEntries();
11402
12022
  return allEntries[provider] ?? null;
@@ -11432,7 +12052,10 @@ var buildOpenRouterHeaders = (apiKey) => {
11432
12052
  }
11433
12053
  return headers;
11434
12054
  };
11435
- var resolveOpenRouterApiKey = async () => {
12055
+ var resolveOpenRouterApiKey = async (state) => {
12056
+ if (state?.effectiveEnvironment.auth.model === "host") {
12057
+ return null;
12058
+ }
11436
12059
  const envKey = readEnvValue("OPENROUTER_API_KEY");
11437
12060
  if (envKey) {
11438
12061
  return envKey;
@@ -11450,14 +12073,14 @@ var resolveOpenRouterApiKeyWithPrompt = async ({
11450
12073
  state,
11451
12074
  log: log2
11452
12075
  }) => {
11453
- const existing = await resolveOpenRouterApiKey();
12076
+ const existing = await resolveOpenRouterApiKey(state);
11454
12077
  if (existing) {
11455
12078
  return existing;
11456
12079
  }
11457
12080
  if (!state) {
11458
12081
  throw new Error("OpenRouter API key is required");
11459
12082
  }
11460
- const authResolver = await AuthResolver.create(state, log2);
12083
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
11461
12084
  const auth = await authResolver.resolveProviderAuth("openrouter");
11462
12085
  if (auth.method !== "api_key") {
11463
12086
  throw new Error("OpenRouter API key is required");
@@ -11568,7 +12191,7 @@ var buildProviderModelList = async ({
11568
12191
  providerEntries = providerEntriesOverride;
11569
12192
  } else {
11570
12193
  try {
11571
- providerEntries = await loadProviderModelEntries(provider);
12194
+ providerEntries = await loadProviderModelEntries(provider, state);
11572
12195
  } catch (error) {
11573
12196
  if (includeDetails) {
11574
12197
  log2(`model.list details error: ${error}`);
@@ -11734,7 +12357,7 @@ var createModelHandlers = ({
11734
12357
  try {
11735
12358
  clearSessionModelOverride(state);
11736
12359
  await persistSessionModelOverride();
11737
- const config = await resolveModelConfig(workingDir);
12360
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
11738
12361
  const provider2 = config.provider ?? "openai";
11739
12362
  const name2 = config.name;
11740
12363
  if (!name2) {
@@ -11812,7 +12435,7 @@ var createModelHandlers = ({
11812
12435
  try {
11813
12436
  let target = null;
11814
12437
  if (scope === "config") {
11815
- target = await updateModel(workingDir, {
12438
+ target = await updateEnvironmentModel(state, workingDir, {
11816
12439
  provider,
11817
12440
  name,
11818
12441
  ...reasoning ? { reasoning } : {},
@@ -11821,7 +12444,10 @@ var createModelHandlers = ({
11821
12444
  clearSessionModelOverride(state);
11822
12445
  await persistSessionModelOverride();
11823
12446
  } else {
11824
- const baseConfig = await resolveModelConfig(workingDir);
12447
+ const baseConfig = await resolveEnvironmentModelConfig(
12448
+ state,
12449
+ workingDir
12450
+ );
11825
12451
  setSessionModelOverride(state, baseConfig, {
11826
12452
  provider,
11827
12453
  name,
@@ -11870,7 +12496,7 @@ var createModelHandlers = ({
11870
12496
 
11871
12497
  // src/rpc/resume-context.ts
11872
12498
  var import_node_fs17 = require("fs");
11873
- var import_node_path16 = __toESM(require("path"), 1);
12499
+ var import_node_path17 = __toESM(require("path"), 1);
11874
12500
  var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11875
12501
  var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11876
12502
  var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
@@ -11879,7 +12505,7 @@ var normalizePath2 = (value) => {
11879
12505
  if (typeof value !== "string") return void 0;
11880
12506
  const trimmed = value.trim();
11881
12507
  if (!trimmed) return void 0;
11882
- return import_node_path16.default.resolve(trimmed);
12508
+ return import_node_path17.default.resolve(trimmed);
11883
12509
  };
11884
12510
  var normalizeMtime3 = (value) => {
11885
12511
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
@@ -12841,7 +13467,7 @@ var createRunHandlers = ({
12841
13467
  );
12842
13468
  };
12843
13469
  const emitRunStatus = (runId, status, message) => {
12844
- sendRunStatus(runId, status, message);
13470
+ sendRunStatus(state, runId, status, message);
12845
13471
  const suffix = message ? ` message=${message}` : "";
12846
13472
  logRunDebug(log2, runId, `status=${status} sent${suffix}`);
12847
13473
  appendSession({
@@ -13015,7 +13641,7 @@ var createRunHandlers = ({
13015
13641
  const emitRunDiagnostics = (params2) => {
13016
13642
  if (!state.diagnosticsEnabled) return;
13017
13643
  try {
13018
- sendRunDiagnostics(params2);
13644
+ sendRunDiagnostics(state, params2);
13019
13645
  } catch (error) {
13020
13646
  log2(`run diagnostics emit failed: ${String(error)}`);
13021
13647
  }
@@ -13147,6 +13773,9 @@ var createRunHandlers = ({
13147
13773
  os: process.platform,
13148
13774
  arch: process.arch,
13149
13775
  version: SERVER_VERSION
13776
+ },
13777
+ meta: {
13778
+ runtime_environment: state.effectiveEnvironment.summary
13150
13779
  }
13151
13780
  });
13152
13781
  appendSession({
@@ -13281,7 +13910,7 @@ var createRunHandlers = ({
13281
13910
  }
13282
13911
  const contextLeftPercent = runtimeAgent.getContextLeftPercent();
13283
13912
  if (contextLeftPercent !== null && state.updateContextLeftPercent(contextLeftPercent)) {
13284
- sendRunContext(runId, contextLeftPercent);
13913
+ sendRunContext(state, runId, contextLeftPercent);
13285
13914
  appendSession({
13286
13915
  type: "run.context",
13287
13916
  run_id: runId,
@@ -13372,7 +14001,7 @@ var createRunHandlers = ({
13372
14001
  };
13373
14002
 
13374
14003
  // src/rpc/shell.ts
13375
- var import_node_path17 = __toESM(require("path"), 1);
14004
+ var import_node_path18 = __toESM(require("path"), 1);
13376
14005
  var import_protocol6 = require("@codelia/protocol");
13377
14006
  var import_storage11 = require("@codelia/storage");
13378
14007
  var COMMAND_PREVIEW_CHARS = 400;
@@ -13387,14 +14016,14 @@ var truncateCommandPreview = (value) => {
13387
14016
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
13388
14017
  };
13389
14018
  var isWithin2 = (basePath, candidatePath) => {
13390
- const relative = import_node_path17.default.relative(basePath, candidatePath);
13391
- return relative === "" || !relative.startsWith("..") && !import_node_path17.default.isAbsolute(relative);
14019
+ const relative = import_node_path18.default.relative(basePath, candidatePath);
14020
+ return relative === "" || !relative.startsWith("..") && !import_node_path18.default.isAbsolute(relative);
13392
14021
  };
13393
14022
  var resolveShellCwd = (state, requestedCwd) => {
13394
14023
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
13395
14024
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
13396
14025
  if (!requestedCwd) return workingDir;
13397
- const resolved = import_node_path17.default.resolve(workingDir, requestedCwd);
14026
+ const resolved = import_node_path18.default.resolve(workingDir, requestedCwd);
13398
14027
  if (!isWithin2(rootDir, resolved)) {
13399
14028
  return null;
13400
14029
  }
@@ -13979,14 +14608,14 @@ var createShellHandlers = ({
13979
14608
  };
13980
14609
 
13981
14610
  // src/rpc/skills.ts
13982
- var import_node_path18 = __toESM(require("path"), 1);
14611
+ var import_node_path19 = __toESM(require("path"), 1);
13983
14612
  var import_protocol7 = require("@codelia/protocol");
13984
14613
  var createSkillsHandlers = ({
13985
14614
  state,
13986
14615
  log: log2
13987
14616
  }) => {
13988
14617
  const handleSkillsList = async (id, params) => {
13989
- const requestedCwd = params?.cwd ? import_node_path18.default.resolve(params.cwd) : void 0;
14618
+ const requestedCwd = params?.cwd ? import_node_path19.default.resolve(params.cwd) : void 0;
13990
14619
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
13991
14620
  const forceReload = params?.force_reload ?? false;
13992
14621
  if (!forceReload) {
@@ -14006,7 +14635,7 @@ var createSkillsHandlers = ({
14006
14635
  try {
14007
14636
  resolver = await SkillsResolver.create({
14008
14637
  workingDir,
14009
- config: await resolveSkillsConfig(workingDir)
14638
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
14010
14639
  });
14011
14640
  } catch (error) {
14012
14641
  sendError(id, {
@@ -14041,7 +14670,7 @@ var createSkillsHandlers = ({
14041
14670
  };
14042
14671
 
14043
14672
  // src/rpc/task.ts
14044
- var import_node_path19 = __toESM(require("path"), 1);
14673
+ var import_node_path20 = __toESM(require("path"), 1);
14045
14674
  var import_protocol8 = require("@codelia/protocol");
14046
14675
  var import_storage12 = require("@codelia/storage");
14047
14676
  var DEFAULT_TRUNCATED2 = {
@@ -14076,14 +14705,14 @@ var getPublicTaskKey = (task) => {
14076
14705
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
14077
14706
  };
14078
14707
  var isWithin3 = (basePath, candidatePath) => {
14079
- const relative = import_node_path19.default.relative(basePath, candidatePath);
14080
- return relative === "" || !relative.startsWith("..") && !import_node_path19.default.isAbsolute(relative);
14708
+ const relative = import_node_path20.default.relative(basePath, candidatePath);
14709
+ return relative === "" || !relative.startsWith("..") && !import_node_path20.default.isAbsolute(relative);
14081
14710
  };
14082
14711
  var resolveShellCwd2 = (state, requestedCwd) => {
14083
14712
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
14084
14713
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
14085
14714
  if (!requestedCwd) return workingDir;
14086
- const resolved = import_node_path19.default.resolve(workingDir, requestedCwd);
14715
+ const resolved = import_node_path20.default.resolve(workingDir, requestedCwd);
14087
14716
  if (!isWithin3(rootDir, resolved)) {
14088
14717
  return null;
14089
14718
  }
@@ -14487,6 +15116,7 @@ var SUPPORTED_TUI_THEMES = /* @__PURE__ */ new Set([
14487
15116
  "crimson",
14488
15117
  "wine"
14489
15118
  ]);
15119
+ var isReadableToolOutputCacheStore = (store) => !!store && typeof store.read === "function" && typeof store.readLine === "function";
14490
15120
  var createRuntimeHandlers = ({
14491
15121
  state,
14492
15122
  getAgent,
@@ -14497,19 +15127,24 @@ var createRuntimeHandlers = ({
14497
15127
  buildProviderModelList: injectedBuildProviderModelList,
14498
15128
  taskManager: injectedTaskManager
14499
15129
  }) => {
14500
- const sessionStateStore = injectedSessionStateStore ?? new import_storage13.SessionStateStoreImpl({
15130
+ const environment = state.effectiveEnvironment;
15131
+ const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage13.SessionStateStoreImpl({
14501
15132
  onError: (error, context) => {
14502
15133
  log2(
14503
15134
  `session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
14504
15135
  );
14505
15136
  }
14506
- });
14507
- const runEventStoreFactory = injectedRunEventStoreFactory ?? new import_storage13.RunEventStoreFactoryImpl();
15137
+ }));
15138
+ const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage13.RunEventStoreFactoryImpl());
14508
15139
  const mcpManager = injectedMcpManager ?? {
14509
15140
  start: async () => void 0,
14510
15141
  list: () => ({ servers: [] })
14511
15142
  };
14512
15143
  const buildProviderModelList2 = injectedBuildProviderModelList ?? buildProviderModelList;
15144
+ const adapterToolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore;
15145
+ const toolOutputCacheStore = isReadableToolOutputCacheStore(
15146
+ adapterToolOutputCacheStore
15147
+ ) ? adapterToolOutputCacheStore : environment.persistence.mode === "volatile" ? new VolatileToolOutputCacheStore() : void 0;
14513
15148
  let startupOnboardingPromise = null;
14514
15149
  let startupOnboardingStarted = false;
14515
15150
  const appendSession = (record) => {
@@ -14538,12 +15173,15 @@ var createRuntimeHandlers = ({
14538
15173
  return parts.join(" \u2022 ");
14539
15174
  };
14540
15175
  const runStartupOnboarding = async () => {
15176
+ if (!isTuiLocalEnvironment(state.effectiveEnvironment)) {
15177
+ return;
15178
+ }
14541
15179
  const supportsPick = !!state.uiCapabilities?.supports_pick;
14542
15180
  const supportsPrompt = !!state.uiCapabilities?.supports_prompt;
14543
15181
  if (!supportsPick || !supportsPrompt) {
14544
15182
  return;
14545
15183
  }
14546
- const authResolver = await AuthResolver.create(state, log2);
15184
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
14547
15185
  if (authResolver.hasAnyAvailableAuth()) {
14548
15186
  return;
14549
15187
  }
@@ -14593,7 +15231,7 @@ var createRuntimeHandlers = ({
14593
15231
  return;
14594
15232
  }
14595
15233
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14596
- const modelTarget = await updateModel(workingDir, {
15234
+ const modelTarget = await updateEnvironmentModel(state, workingDir, {
14597
15235
  provider,
14598
15236
  name: selectedModel
14599
15237
  });
@@ -14633,7 +15271,22 @@ var createRuntimeHandlers = ({
14633
15271
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
14634
15272
  sessionStateStore,
14635
15273
  log: log2,
14636
- getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd(),
15274
+ readRunLogs: environment.persistence.mode === "runtime",
15275
+ ...environment.events.live === "host" ? {
15276
+ sendHistoryEvent: async (runId, seq, event) => {
15277
+ const notify = {
15278
+ jsonrpc: "2.0",
15279
+ method: "agent.event",
15280
+ params: {
15281
+ run_id: runId,
15282
+ seq,
15283
+ event
15284
+ }
15285
+ };
15286
+ await sendNotificationAsync(state, notify);
15287
+ }
15288
+ } : {},
15289
+ getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? environment.workspace.root,
14637
15290
  buildResumeDiffSummary: async (meta) => {
14638
15291
  if (!hasStructuredResumeContextMeta(meta)) {
14639
15292
  return void 0;
@@ -14664,56 +15317,50 @@ var createRuntimeHandlers = ({
14664
15317
  state,
14665
15318
  getAgent
14666
15319
  });
14667
- const {
14668
- handleShellExec,
14669
- handleShellStart,
14670
- handleShellList,
14671
- handleShellStatus,
14672
- handleShellOutput,
14673
- handleShellWait,
14674
- handleShellDetach,
14675
- handleShellCancel
14676
- } = createShellHandlers({
15320
+ const processHandlersEnabled = state.effectiveEnvironment.workspace.process === "runtime";
15321
+ const shellHandlers = processHandlersEnabled ? createShellHandlers({
14677
15322
  state,
14678
15323
  log: log2,
14679
- taskManager: injectedTaskManager
14680
- });
14681
- const {
14682
- handleTaskSpawn,
14683
- handleTaskList,
14684
- handleTaskStatus,
14685
- handleTaskWait,
14686
- handleTaskCancel,
14687
- handleTaskResult
14688
- } = createTaskHandlers({
15324
+ taskManager: injectedTaskManager,
15325
+ outputCache: toolOutputCacheStore ?? void 0
15326
+ }) : null;
15327
+ const taskHandlers = processHandlersEnabled ? createTaskHandlers({
14689
15328
  state,
14690
15329
  log: log2,
14691
- taskManager: injectedTaskManager
14692
- });
15330
+ taskManager: injectedTaskManager,
15331
+ outputCache: toolOutputCacheStore ?? void 0
15332
+ }) : null;
14693
15333
  const handleInitialize = async (id, params) => {
14694
15334
  let resolvedTheme;
14695
- try {
14696
- const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14697
- resolvedTheme = (await resolveTuiConfig(workingDir)).theme;
14698
- } catch (error) {
14699
- log2(`initialize tui config load failed: ${String(error)}`);
15335
+ const environment2 = state.effectiveEnvironment;
15336
+ if (isTuiLocalEnvironment(environment2)) {
15337
+ try {
15338
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
15339
+ resolvedTheme = (await resolveEnvironmentTuiConfig(state, workingDir)).theme;
15340
+ } catch (error) {
15341
+ log2(`initialize tui config load failed: ${String(error)}`);
15342
+ }
14700
15343
  }
15344
+ const processEnabled = environment2.workspace.process === "runtime";
15345
+ const mcpEnabled = environment2.tools.mcp === "from-config";
15346
+ const skillsEnabled = environment2.context.skills === "from-config";
15347
+ const themeSetEnabled = isTuiLocalEnvironment(environment2) && environment2.config.source !== "disabled";
14701
15348
  const result = {
14702
15349
  protocol_version: PROTOCOL_VERSION,
14703
15350
  server: { name: SERVER_NAME, version: SERVER_VERSION },
14704
15351
  server_capabilities: {
14705
15352
  supports_run_cancel: true,
14706
15353
  supports_run_diagnostics: true,
14707
- supports_shell_exec: true,
14708
- supports_shell_tasks: true,
14709
- supports_shell_detach: true,
14710
- supports_tasks: true,
14711
- supports_ui_requests: true,
14712
- supports_mcp_list: true,
14713
- supports_skills_list: true,
15354
+ supports_shell_exec: processEnabled,
15355
+ supports_shell_tasks: processEnabled,
15356
+ supports_shell_detach: processEnabled,
15357
+ supports_tasks: processEnabled,
15358
+ supports_ui_requests: isTuiLocalEnvironment(environment2),
15359
+ supports_mcp_list: mcpEnabled,
15360
+ supports_skills_list: skillsEnabled,
14714
15361
  supports_context_inspect: true,
14715
15362
  supports_tool_call: true,
14716
- supports_theme_set: true,
15363
+ supports_theme_set: themeSetEnabled,
14717
15364
  supports_permission_preflight_events: true
14718
15365
  },
14719
15366
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
@@ -14755,7 +15402,7 @@ var createRuntimeHandlers = ({
14755
15402
  }
14756
15403
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14757
15404
  try {
14758
- const target = await updateTuiTheme(workingDir, name);
15405
+ const target = await updateEnvironmentTuiTheme(state, workingDir, name);
14759
15406
  const result = {
14760
15407
  name,
14761
15408
  scope: target.scope,
@@ -14780,6 +15427,31 @@ var createRuntimeHandlers = ({
14780
15427
  }
14781
15428
  const clearSession = params?.clear_session ?? true;
14782
15429
  try {
15430
+ if (state.effectiveEnvironment.auth.model === "host") {
15431
+ const clearAuth = state.effectiveEnvironment.adapters.credentialProvider?.clearAuth;
15432
+ if (!clearAuth) {
15433
+ sendError(id, {
15434
+ code: import_protocol10.RPC_ERROR_CODE.RUNTIME_INTERNAL,
15435
+ message: "host auth provider does not support logout"
15436
+ });
15437
+ return;
15438
+ }
15439
+ await clearAuth();
15440
+ state.agent = null;
15441
+ if (clearSession) {
15442
+ state.sessionId = null;
15443
+ state.sessionMeta = null;
15444
+ state.sessionAppend = null;
15445
+ state.sessionModelOverride = null;
15446
+ }
15447
+ sendResult(id, {
15448
+ ok: true,
15449
+ auth_cleared: true,
15450
+ session_cleared: clearSession
15451
+ });
15452
+ log2(`auth.logout host session_cleared=${clearSession}`);
15453
+ return;
15454
+ }
14783
15455
  const supportsConfirm = !!state.uiCapabilities?.supports_confirm;
14784
15456
  if (!supportsConfirm) {
14785
15457
  sendError(id, {
@@ -14833,6 +15505,13 @@ var createRuntimeHandlers = ({
14833
15505
  }
14834
15506
  };
14835
15507
  const handleRequest = async (req) => {
15508
+ const mcpEnabled = state.effectiveEnvironment.tools.mcp === "from-config";
15509
+ const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
15510
+ const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
15511
+ const rejectDisabled = (message) => sendError(req.id, {
15512
+ code: import_protocol10.RPC_ERROR_CODE.INVALID_PARAMS,
15513
+ message
15514
+ });
14836
15515
  switch (req.method) {
14837
15516
  case "initialize":
14838
15517
  return handleInitialize(req.id, req.params);
@@ -14853,44 +15532,120 @@ var createRuntimeHandlers = ({
14853
15532
  case "tool.call":
14854
15533
  return handleToolCall(req.id, req.params);
14855
15534
  case "shell.exec":
14856
- return handleShellExec(req.id, req.params);
15535
+ if (!shellHandlers)
15536
+ return rejectDisabled("process execution is disabled");
15537
+ return shellHandlers.handleShellExec(
15538
+ req.id,
15539
+ req.params
15540
+ );
14857
15541
  case "shell.start":
14858
- return handleShellStart(req.id, req.params);
15542
+ if (!shellHandlers)
15543
+ return rejectDisabled("process execution is disabled");
15544
+ return shellHandlers.handleShellStart(
15545
+ req.id,
15546
+ req.params
15547
+ );
14859
15548
  case "shell.list":
14860
- return handleShellList(req.id, req.params);
15549
+ if (!shellHandlers)
15550
+ return rejectDisabled("process execution is disabled");
15551
+ return shellHandlers.handleShellList(
15552
+ req.id,
15553
+ req.params
15554
+ );
14861
15555
  case "shell.status":
14862
- return handleShellStatus(req.id, req.params);
15556
+ if (!shellHandlers)
15557
+ return rejectDisabled("process execution is disabled");
15558
+ return shellHandlers.handleShellStatus(
15559
+ req.id,
15560
+ req.params
15561
+ );
14863
15562
  case "shell.output":
14864
- return handleShellOutput(req.id, req.params);
15563
+ if (!shellHandlers)
15564
+ return rejectDisabled("process execution is disabled");
15565
+ return shellHandlers.handleShellOutput(
15566
+ req.id,
15567
+ req.params
15568
+ );
14865
15569
  case "shell.wait":
14866
- return handleShellWait(req.id, req.params);
15570
+ if (!shellHandlers)
15571
+ return rejectDisabled("process execution is disabled");
15572
+ return shellHandlers.handleShellWait(
15573
+ req.id,
15574
+ req.params
15575
+ );
14867
15576
  case "shell.detach":
14868
- return handleShellDetach(req.id, req.params);
15577
+ if (!shellHandlers)
15578
+ return rejectDisabled("process execution is disabled");
15579
+ return shellHandlers.handleShellDetach(
15580
+ req.id,
15581
+ req.params
15582
+ );
14869
15583
  case "shell.cancel":
14870
- return handleShellCancel(req.id, req.params);
15584
+ if (!shellHandlers)
15585
+ return rejectDisabled("process execution is disabled");
15586
+ return shellHandlers.handleShellCancel(
15587
+ req.id,
15588
+ req.params
15589
+ );
14871
15590
  case "task.spawn":
14872
- return handleTaskSpawn(req.id, req.params);
15591
+ if (!taskHandlers)
15592
+ return rejectDisabled("process execution is disabled");
15593
+ return taskHandlers.handleTaskSpawn(
15594
+ req.id,
15595
+ req.params
15596
+ );
14873
15597
  case "task.list":
14874
- return handleTaskList(req.id, req.params);
15598
+ if (!taskHandlers)
15599
+ return rejectDisabled("process execution is disabled");
15600
+ return taskHandlers.handleTaskList(
15601
+ req.id,
15602
+ req.params
15603
+ );
14875
15604
  case "task.status":
14876
- return handleTaskStatus(req.id, req.params);
15605
+ if (!taskHandlers)
15606
+ return rejectDisabled("process execution is disabled");
15607
+ return taskHandlers.handleTaskStatus(
15608
+ req.id,
15609
+ req.params
15610
+ );
14877
15611
  case "task.wait":
14878
- return handleTaskWait(req.id, req.params);
15612
+ if (!taskHandlers)
15613
+ return rejectDisabled("process execution is disabled");
15614
+ return taskHandlers.handleTaskWait(
15615
+ req.id,
15616
+ req.params
15617
+ );
14879
15618
  case "task.cancel":
14880
- return handleTaskCancel(req.id, req.params);
15619
+ if (!taskHandlers)
15620
+ return rejectDisabled("process execution is disabled");
15621
+ return taskHandlers.handleTaskCancel(
15622
+ req.id,
15623
+ req.params
15624
+ );
14881
15625
  case "task.result":
14882
- return handleTaskResult(req.id, req.params);
15626
+ if (!taskHandlers)
15627
+ return rejectDisabled("process execution is disabled");
15628
+ return taskHandlers.handleTaskResult(
15629
+ req.id,
15630
+ req.params
15631
+ );
14883
15632
  case "mcp.list":
15633
+ if (!mcpEnabled) {
15634
+ return sendResult(req.id, { servers: [] });
15635
+ }
14884
15636
  await mcpManager.start?.();
14885
15637
  return sendResult(
14886
15638
  req.id,
14887
15639
  mcpManager.list(req.params?.scope)
14888
15640
  );
14889
15641
  case "skills.list":
15642
+ if (!skillsEnabled) return rejectDisabled("skills are disabled");
14890
15643
  return handleSkillsList(req.id, req.params);
14891
15644
  case "context.inspect":
14892
15645
  return handleContextInspect(req.id, req.params);
14893
15646
  case "theme.set":
15647
+ if (!themeSetEnabled)
15648
+ return rejectDisabled("theme setting is disabled");
14894
15649
  return handleThemeSet(req.id, req.params);
14895
15650
  default:
14896
15651
  return sendError(req.id, {
@@ -14925,6 +15680,7 @@ var createRuntimeHandlers = ({
14925
15680
  // src/runtime-state.ts
14926
15681
  var import_node_crypto9 = __toESM(require("crypto"), 1);
14927
15682
  var RuntimeState = class {
15683
+ effectiveEnvironment = resolveRuntimeEnvironment();
14928
15684
  runSeq = /* @__PURE__ */ new Map();
14929
15685
  uiRequestCounter = 0;
14930
15686
  pendingUiRequests = /* @__PURE__ */ new Map();
@@ -14956,6 +15712,9 @@ var RuntimeState = class {
14956
15712
  currentModelSource = null;
14957
15713
  sessionModelOverride = null;
14958
15714
  diagnosticsEnabled = false;
15715
+ setRuntimeEnvironment(options) {
15716
+ this.effectiveEnvironment = resolveRuntimeEnvironment(options);
15717
+ }
14959
15718
  nextRunId() {
14960
15719
  return import_node_crypto9.default.randomUUID();
14961
15720
  }
@@ -15055,33 +15814,42 @@ var envTruthy2 = (value) => {
15055
15814
  const normalized = value.trim().toLowerCase();
15056
15815
  return normalized === "1" || normalized === "true";
15057
15816
  };
15058
- var startRuntime = () => {
15059
- void (async () => {
15060
- const state = new RuntimeState();
15061
- state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
15062
- const workingDir = process.env.CODELIA_SANDBOX_ROOT ? import_node_path20.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
15817
+ var startRuntime = async (options = {}) => {
15818
+ const state = new RuntimeState();
15819
+ state.setRuntimeEnvironment(options);
15820
+ const environment = state.effectiveEnvironment;
15821
+ state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
15822
+ const workingDir = environment.workspace.root;
15823
+ if (workingDir) {
15063
15824
  state.runtimeWorkingDir = workingDir;
15064
15825
  state.runtimeSandboxRoot = workingDir;
15826
+ }
15827
+ if (environment.context.projectInstructions === "from-workspace" && workingDir) {
15065
15828
  try {
15066
15829
  state.agentsResolver = await AgentsResolver.create(workingDir);
15067
15830
  } catch (error) {
15068
15831
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
15069
15832
  }
15070
- const sessionStateStore = new import_storage14.SessionStateStoreImpl({
15071
- onError: (error, context) => {
15072
- (0, import_logger.log)(
15073
- `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
15074
- );
15075
- }
15076
- });
15833
+ }
15834
+ const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage14.SessionStateStoreImpl({
15835
+ onError: (error, context) => {
15836
+ (0, import_logger.log)(
15837
+ `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
15838
+ );
15839
+ }
15840
+ }));
15841
+ if (environment.persistence.mode === "runtime") {
15077
15842
  try {
15078
15843
  await sessionStateStore.list();
15079
15844
  } catch (error) {
15080
- (0, import_logger.log)(`Error: session index database is not available: ${String(error)}`);
15081
- process.exit(1);
15082
- return;
15845
+ throw new Error(
15846
+ `session index database is not available: ${String(error)}`
15847
+ );
15083
15848
  }
15084
- const taskManager = new TaskManager();
15849
+ }
15850
+ const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage14.RunEventStoreFactoryImpl());
15851
+ const taskManager = isProcessEnabled(environment) ? environment.adapters.stores?.taskManager ?? new TaskManager() : void 0;
15852
+ if (taskManager) {
15085
15853
  const recoveredTasks = await taskManager.recoverOrphanedTasks();
15086
15854
  if (recoveredTasks.recovered > 0 || recoveredTasks.errors.length > 0) {
15087
15855
  (0, import_logger.log)(
@@ -15091,76 +15859,81 @@ var startRuntime = () => {
15091
15859
  (0, import_logger.log)(`tasks.recover error task_id=${error.task_id}: ${error.error}`);
15092
15860
  }
15093
15861
  }
15094
- let shutdownPromise = null;
15095
- const shutdownTasks = async (reason) => {
15096
- if (shutdownPromise) {
15097
- await shutdownPromise;
15098
- return;
15099
- }
15100
- shutdownPromise = (async () => {
15101
- const result = await taskManager.shutdown();
15102
- if (result.cancelled > 0 || result.errors.length > 0) {
15103
- (0, import_logger.log)(
15104
- `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
15105
- );
15106
- for (const error of result.errors) {
15107
- (0, import_logger.log)(
15108
- `tasks.shutdown error task_id=${error.task_id}: ${error.error}`
15109
- );
15110
- }
15111
- }
15112
- })();
15862
+ }
15863
+ let shutdownPromise = null;
15864
+ const shutdownTasks = async (reason) => {
15865
+ if (!taskManager) return;
15866
+ if (shutdownPromise) {
15113
15867
  await shutdownPromise;
15114
- };
15115
- for (const signal of ["SIGINT", "SIGTERM"]) {
15116
- process.once(signal, () => {
15117
- void shutdownTasks(signal).finally(() => {
15118
- process.kill(process.pid, signal);
15119
- });
15120
- });
15868
+ return;
15121
15869
  }
15122
- process.once("beforeExit", () => {
15123
- void shutdownTasks("beforeExit");
15124
- });
15125
- process.stdin.once("end", () => {
15126
- void shutdownTasks("stdin.end");
15870
+ shutdownPromise = (async () => {
15871
+ const result = await taskManager.shutdown();
15872
+ if (result.cancelled > 0 || result.errors.length > 0) {
15873
+ (0, import_logger.log)(
15874
+ `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
15875
+ );
15876
+ for (const error of result.errors) {
15877
+ (0, import_logger.log)(`tasks.shutdown error task_id=${error.task_id}: ${error.error}`);
15878
+ }
15879
+ }
15880
+ })();
15881
+ await shutdownPromise;
15882
+ };
15883
+ for (const signal of ["SIGINT", "SIGTERM"]) {
15884
+ process.once(signal, () => {
15885
+ void shutdownTasks(signal).finally(() => {
15886
+ process.kill(process.pid, signal);
15887
+ });
15127
15888
  });
15128
- const mcpManager = new McpManager({ workingDir, log: import_logger.log });
15889
+ }
15890
+ process.once("beforeExit", () => {
15891
+ void shutdownTasks("beforeExit");
15892
+ });
15893
+ process.stdin.once("end", () => {
15894
+ void shutdownTasks("stdin.end");
15895
+ });
15896
+ const mcpManager = environment.tools.mcp === "from-config" && workingDir ? new McpManager({ workingDir, log: import_logger.log }) : void 0;
15897
+ if (mcpManager) {
15129
15898
  void mcpManager.start({
15130
15899
  onStatus: (message) => (0, import_logger.log)(`mcp: ${message}`),
15131
15900
  requestOAuthTokens: ({ server_id, oauth: oauth2, error }) => requestMcpOAuthTokensWithRunStatus(state, server_id, oauth2, error)
15132
15901
  });
15133
- const getAgent = createAgentFactory(state, { mcpManager, taskManager });
15134
- const { processMessage } = createRuntimeHandlers({
15135
- state,
15136
- getAgent,
15137
- log: import_logger.log,
15138
- mcpManager,
15139
- sessionStateStore,
15140
- taskManager
15141
- });
15142
- (0, import_logger.log)("runtime started");
15143
- process.stdin.setEncoding("utf8");
15144
- let buffer = "";
15145
- process.stdin.on("data", (chunk) => {
15146
- buffer += chunk;
15147
- let index = buffer.indexOf("\n");
15148
- while (index >= 0) {
15149
- const line = buffer.slice(0, index).trim();
15150
- buffer = buffer.slice(index + 1);
15151
- if (line) {
15152
- try {
15153
- const msg = JSON.parse(line);
15154
- processMessage(msg);
15155
- } catch (error) {
15156
- (0, import_logger.log)(`invalid json: ${String(error)}`);
15157
- }
15902
+ }
15903
+ const getAgent = createAgentFactory(state, { mcpManager, taskManager });
15904
+ const { processMessage } = createRuntimeHandlers({
15905
+ state,
15906
+ getAgent,
15907
+ log: import_logger.log,
15908
+ mcpManager,
15909
+ sessionStateStore,
15910
+ runEventStoreFactory,
15911
+ taskManager
15912
+ });
15913
+ (0, import_logger.log)("runtime started");
15914
+ process.stdin.setEncoding("utf8");
15915
+ let buffer = "";
15916
+ process.stdin.on("data", (chunk) => {
15917
+ buffer += chunk;
15918
+ let index = buffer.indexOf("\n");
15919
+ while (index >= 0) {
15920
+ const line = buffer.slice(0, index).trim();
15921
+ buffer = buffer.slice(index + 1);
15922
+ if (line) {
15923
+ try {
15924
+ const msg = JSON.parse(line);
15925
+ processMessage(msg);
15926
+ } catch (error) {
15927
+ (0, import_logger.log)(`invalid json: ${String(error)}`);
15158
15928
  }
15159
- index = buffer.indexOf("\n");
15160
15929
  }
15161
- });
15162
- })();
15930
+ index = buffer.indexOf("\n");
15931
+ }
15932
+ });
15163
15933
  };
15164
15934
 
15165
15935
  // src/index.ts
15166
- startRuntime();
15936
+ void startRuntime().catch((error) => {
15937
+ console.error(`runtime startup failed: ${String(error)}`);
15938
+ process.exitCode = 1;
15939
+ });