@codelia/runtime 0.1.69 → 0.1.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -23,14 +23,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/runtime.ts
26
- var import_node_path20 = __toESM(require("path"), 1);
27
26
  var import_storage14 = require("@codelia/storage");
28
27
 
29
28
  // src/agent-factory.ts
30
29
  var import_node_fs15 = require("fs");
31
30
  var import_core21 = require("@codelia/core");
32
31
  var import_model_metadata2 = require("@codelia/model-metadata");
33
- var import_shared_types2 = require("@codelia/shared-types");
32
+ var import_shared_types4 = require("@codelia/shared-types");
34
33
  var import_storage8 = require("@codelia/storage");
35
34
 
36
35
  // src/agents/context.ts
@@ -751,6 +750,7 @@ var import_node_path2 = __toESM(require("path"), 1);
751
750
  var import_config = require("@codelia/config");
752
751
  var import_config_loader = require("@codelia/config-loader");
753
752
  var import_core = require("@codelia/core");
753
+ var import_shared_types = require("@codelia/shared-types");
754
754
  var import_storage = require("@codelia/storage");
755
755
  var DEFAULT_SYSTEM_PROMPT = "You are a coding assistant.";
756
756
  var DEFAULT_MCP_REQUEST_TIMEOUT_MS = 3e4;
@@ -1028,10 +1028,10 @@ function resolveModelLevelOption(value, fieldName, options) {
1028
1028
  if (normalized === "low" || normalized === "medium" || normalized === "high") {
1029
1029
  return normalized;
1030
1030
  }
1031
- if (options.allowXhigh && normalized === "xhigh") {
1031
+ if (options.allowXhigh && (0, import_shared_types.isModelReasoningLevel)(normalized)) {
1032
1032
  return normalized;
1033
1033
  }
1034
- const expected = options.allowXhigh ? "low|medium|high|xhigh" : "low|medium|high";
1034
+ const expected = options.allowXhigh ? import_shared_types.MODEL_REASONING_LEVELS.join("|") : "low|medium|high";
1035
1035
  throw new Error(`Invalid ${fieldName}: ${value}. Expected ${expected}.`);
1036
1036
  }
1037
1037
  var loadSystemPrompt = async (workingDir) => {
@@ -1070,6 +1070,38 @@ var serializeMessage = (msg) => ({
1070
1070
  `,
1071
1071
  label: describeRpcMessage(msg)
1072
1072
  });
1073
+ var hostNotificationQueues = /* @__PURE__ */ new WeakMap();
1074
+ var enqueueHostNotification = (state, notify) => {
1075
+ const sink = state.effectiveEnvironment.adapters.eventSink;
1076
+ if (!sink) {
1077
+ (0, import_logger.log)(
1078
+ `transport.host-event.error label=${describeRpcMessage(notify)} message=event sink unavailable`
1079
+ );
1080
+ return Promise.resolve();
1081
+ }
1082
+ const previous = hostNotificationQueues.get(state) ?? Promise.resolve();
1083
+ const next = previous.then(() => sink.emit(notify)).catch((error) => {
1084
+ (0, import_logger.log)(
1085
+ `transport.host-event.error label=${describeRpcMessage(notify)} message=${String(error)}`
1086
+ );
1087
+ });
1088
+ hostNotificationQueues.set(state, next);
1089
+ return next;
1090
+ };
1091
+ var sendNotification = (state, notify) => {
1092
+ if (state.effectiveEnvironment.events.live === "host") {
1093
+ void enqueueHostNotification(state, notify);
1094
+ return;
1095
+ }
1096
+ send(notify);
1097
+ };
1098
+ var sendNotificationAsync = async (state, notify) => {
1099
+ if (state.effectiveEnvironment.events.live === "host") {
1100
+ await enqueueHostNotification(state, notify);
1101
+ return;
1102
+ }
1103
+ await sendAsync(notify);
1104
+ };
1073
1105
  var send = (msg) => {
1074
1106
  const { payload, label } = serializeMessage(msg);
1075
1107
  const writable = process.stdout.write(payload, (error) => {
@@ -1115,7 +1147,7 @@ var sendAgentEvent = (state, runId, event) => {
1115
1147
  event
1116
1148
  }
1117
1149
  };
1118
- send(notify);
1150
+ sendNotification(state, notify);
1119
1151
  return seq;
1120
1152
  };
1121
1153
  var sendAgentEventAsync = async (state, runId, event) => {
@@ -1130,10 +1162,10 @@ var sendAgentEventAsync = async (state, runId, event) => {
1130
1162
  event
1131
1163
  }
1132
1164
  };
1133
- await sendAsync(notify);
1165
+ await sendNotificationAsync(state, notify);
1134
1166
  return seq;
1135
1167
  };
1136
- var sendRunStatus = (runId, status, message) => {
1168
+ var sendRunStatus = (state, runId, status, message) => {
1137
1169
  const notify = {
1138
1170
  jsonrpc: "2.0",
1139
1171
  method: "run.status",
@@ -1143,9 +1175,9 @@ var sendRunStatus = (runId, status, message) => {
1143
1175
  message
1144
1176
  }
1145
1177
  };
1146
- send(notify);
1178
+ sendNotification(state, notify);
1147
1179
  };
1148
- var sendRunStatusAsync = async (runId, status, message) => {
1180
+ var sendRunStatusAsync = async (state, runId, status, message) => {
1149
1181
  const notify = {
1150
1182
  jsonrpc: "2.0",
1151
1183
  method: "run.status",
@@ -1155,9 +1187,9 @@ var sendRunStatusAsync = async (runId, status, message) => {
1155
1187
  message
1156
1188
  }
1157
1189
  };
1158
- await sendAsync(notify);
1190
+ await sendNotificationAsync(state, notify);
1159
1191
  };
1160
- var sendRunContext = (runId, contextLeftPercent) => {
1192
+ var sendRunContext = (state, runId, contextLeftPercent) => {
1161
1193
  const notify = {
1162
1194
  jsonrpc: "2.0",
1163
1195
  method: "run.context",
@@ -1166,15 +1198,15 @@ var sendRunContext = (runId, contextLeftPercent) => {
1166
1198
  context_left_percent: contextLeftPercent
1167
1199
  }
1168
1200
  };
1169
- send(notify);
1201
+ sendNotification(state, notify);
1170
1202
  };
1171
- var sendRunDiagnostics = (params) => {
1203
+ var sendRunDiagnostics = (state, params) => {
1172
1204
  const notify = {
1173
1205
  jsonrpc: "2.0",
1174
1206
  method: "run.diagnostics",
1175
1207
  params
1176
1208
  };
1177
- send(notify);
1209
+ sendNotification(state, notify);
1178
1210
  };
1179
1211
 
1180
1212
  // src/rpc/ui-requests.ts
@@ -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,51 @@ 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 = {
2485
2677
  "claude-opus-4-8": {
2486
- supportedLevels: ["low", "medium", "high", "xhigh"],
2678
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2487
2679
  budgetPresetByLevel: {
2488
2680
  low: "reasoning_low",
2489
2681
  medium: "reasoning_medium",
2490
2682
  high: "reasoning_high",
2491
- xhigh: "reasoning_xhigh"
2492
- }
2683
+ xhigh: "reasoning_xhigh",
2684
+ max: "reasoning_xhigh"
2685
+ },
2686
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2493
2687
  },
2494
2688
  "claude-opus-4-7": {
2495
- supportedLevels: ["low", "medium", "high", "xhigh"],
2689
+ supportedLevels: ["low", "medium", "high", "xhigh", "max"],
2496
2690
  budgetPresetByLevel: {
2497
2691
  low: "reasoning_low",
2498
2692
  medium: "reasoning_medium",
2499
2693
  high: "reasoning_high",
2500
- xhigh: "reasoning_xhigh"
2501
- }
2694
+ xhigh: "reasoning_xhigh",
2695
+ max: "reasoning_xhigh"
2696
+ },
2697
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_ALL
2502
2698
  },
2503
2699
  "claude-opus-4-6": {
2504
- supportedLevels: ["low", "medium", "high", "xhigh"],
2700
+ supportedLevels: ["low", "medium", "high", "max"],
2505
2701
  budgetPresetByLevel: {
2506
2702
  low: "reasoning_low",
2507
2703
  medium: "reasoning_medium",
2508
2704
  high: "reasoning_high",
2509
- xhigh: "reasoning_xhigh"
2510
- }
2705
+ max: "reasoning_xhigh"
2706
+ },
2707
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2511
2708
  },
2512
2709
  "claude-opus-4-5": {
2513
2710
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2528,13 +2725,14 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2528
2725
  }
2529
2726
  },
2530
2727
  "claude-sonnet-4-6": {
2531
- supportedLevels: ["low", "medium", "high", "xhigh"],
2728
+ supportedLevels: ["low", "medium", "high", "max"],
2532
2729
  budgetPresetByLevel: {
2533
2730
  low: "reasoning_low",
2534
2731
  medium: "reasoning_medium",
2535
2732
  high: "reasoning_high",
2536
- xhigh: "reasoning_xhigh"
2537
- }
2733
+ max: "reasoning_xhigh"
2734
+ },
2735
+ outputEffortByLevel: ANTHROPIC_OUTPUT_EFFORT_WITHOUT_XHIGH
2538
2736
  },
2539
2737
  "claude-sonnet-4-5": {
2540
2738
  supportedLevels: ["low", "medium", "high", "xhigh"],
@@ -2573,9 +2771,10 @@ var ANTHROPIC_REASONING_MODEL_TABLE = {
2573
2771
  };
2574
2772
  var ANTHROPIC_ADAPTIVE_THINKING_MODELS = /* @__PURE__ */ new Set([
2575
2773
  "claude-opus-4-8",
2576
- "claude-opus-4-7"
2774
+ "claude-opus-4-7",
2775
+ "claude-opus-4-6",
2776
+ "claude-sonnet-4-6"
2577
2777
  ]);
2578
- var toAnthropicOutputEffort = (level) => level === "xhigh" ? "max" : level;
2579
2778
  var normalizeRequestedReasoning = (value) => value ?? DEFAULT_REASONING_LEVEL;
2580
2779
  var resolveNearestSupportedLevel = (requested, supportedLevels) => {
2581
2780
  const supported = new Set(supportedLevels);
@@ -2609,12 +2808,14 @@ var resolveReasoningAgainstSupportedLevels = ({
2609
2808
  supportedLevels
2610
2809
  };
2611
2810
  };
2612
- var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(model);
2811
+ var normalizeResponsesModelId = (model) => model.startsWith("openai/") ? model.slice("openai/".length) : model;
2812
+ var supportsResponsesXhigh = (model) => !RESPONSES_XHIGH_UNSUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2813
+ var supportsResponsesMax = (model) => RESPONSES_MAX_SUPPORTED_MODELS.has(normalizeResponsesModelId(model));
2613
2814
  var resolveResponsesReasoning = ({
2614
2815
  model,
2615
2816
  requested
2616
2817
  }) => {
2617
- const supportedLevels = supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER : REASONING_LEVEL_ORDER.slice(0, 3);
2818
+ const supportedLevels = supportsResponsesMax(model) ? REASONING_LEVEL_ORDER : supportsResponsesXhigh(model) ? REASONING_LEVEL_ORDER.slice(0, 4) : REASONING_LEVEL_ORDER.slice(0, 3);
2618
2819
  const resolution = resolveReasoningAgainstSupportedLevels({
2619
2820
  requested,
2620
2821
  supportedLevels
@@ -2654,19 +2855,18 @@ var resolveAnthropicReasoning = ({
2654
2855
  );
2655
2856
  }
2656
2857
  const budgetTokens = ANTHROPIC_BUDGET_PRESET_TOKENS[preset];
2858
+ const outputEffort = profile.outputEffortByLevel?.[resolution.applied];
2657
2859
  return {
2658
2860
  ...resolution,
2659
2861
  ...ANTHROPIC_ADAPTIVE_THINKING_MODELS.has(model) ? {
2660
- thinking: { type: "adaptive" },
2661
- outputConfig: {
2662
- effort: toAnthropicOutputEffort(resolution.applied)
2663
- }
2862
+ thinking: { type: "adaptive" }
2664
2863
  } : {
2665
2864
  thinking: {
2666
2865
  type: "enabled",
2667
2866
  budget_tokens: budgetTokens
2668
2867
  }
2669
2868
  },
2869
+ ...outputEffort ? { outputConfig: { effort: outputEffort } } : {},
2670
2870
  budgetPreset: preset,
2671
2871
  usedFallbackModelProfile
2672
2872
  };
@@ -2686,10 +2886,10 @@ var resolveZaiReasoning = ({
2686
2886
  requested
2687
2887
  }) => {
2688
2888
  const normalizedRequested = normalizeRequestedReasoning(requested);
2689
- if (normalizedRequested === "xhigh") {
2889
+ if (normalizedRequested === "xhigh" || normalizedRequested === "max") {
2690
2890
  return {
2691
2891
  requested: normalizedRequested,
2692
- applied: "xhigh",
2892
+ applied: normalizedRequested,
2693
2893
  effort: "max",
2694
2894
  fallbackApplied: false,
2695
2895
  supportedLevels: REASONING_LEVEL_ORDER
@@ -2845,7 +3045,7 @@ var buildModelRegistry = async (llm, options = {}) => {
2845
3045
  // src/permissions/approval-mode.ts
2846
3046
  var import_node_fs4 = require("fs");
2847
3047
  var import_node_path4 = __toESM(require("path"), 1);
2848
- var import_shared_types = require("@codelia/shared-types");
3048
+ var import_shared_types3 = require("@codelia/shared-types");
2849
3049
  var import_storage4 = require("@codelia/storage");
2850
3050
  var normalizePath = async (value) => {
2851
3051
  const absolute = import_node_path4.default.resolve(value);
@@ -2866,7 +3066,7 @@ var parseApprovalModeOrThrow = (raw, source) => {
2866
3066
  `Invalid ${source}: missing value (expected ${APPROVAL_MODE_HINT})`
2867
3067
  );
2868
3068
  }
2869
- const parsed = (0, import_shared_types.parseApprovalMode)(raw);
3069
+ const parsed = (0, import_shared_types3.parseApprovalMode)(raw);
2870
3070
  if (!parsed) {
2871
3071
  throw new Error(
2872
3072
  `Invalid ${source}: '${raw}' (expected ${APPROVAL_MODE_HINT})`
@@ -2903,13 +3103,13 @@ var resolvePolicyApprovalMode = (policy, projectKey) => {
2903
3103
  if (!policy) {
2904
3104
  return void 0;
2905
3105
  }
2906
- const projectMode = (0, import_shared_types.parseApprovalMode)(
3106
+ const projectMode = (0, import_shared_types3.parseApprovalMode)(
2907
3107
  policy.projects?.[projectKey]?.approval_mode
2908
3108
  );
2909
3109
  if (projectMode) {
2910
3110
  return { approvalMode: projectMode, source: "project" };
2911
3111
  }
2912
- const defaultMode = (0, import_shared_types.parseApprovalMode)(policy.default?.approval_mode);
3112
+ const defaultMode = (0, import_shared_types3.parseApprovalMode)(policy.default?.approval_mode);
2913
3113
  if (defaultMode) {
2914
3114
  return { approvalMode: defaultMode, source: "default" };
2915
3115
  }
@@ -8851,6 +9051,12 @@ var buildHostedSearchToolDefinitions = (provider, options) => {
8851
9051
  };
8852
9052
  var OPENAI_OAUTH_ORIGINATOR = "codelia";
8853
9053
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
9054
+ var loadHostTools = async (providers) => {
9055
+ const groups = await Promise.all(
9056
+ providers.map((provider) => Promise.resolve(provider.getTools()))
9057
+ );
9058
+ return groups.flat();
9059
+ };
8854
9060
  var buildOpenAiClientOptions = (authResolver, auth) => {
8855
9061
  if (auth.method === "api_key") {
8856
9062
  return { apiKey: auth.api_key };
@@ -8858,6 +9064,9 @@ var buildOpenAiClientOptions = (authResolver, auth) => {
8858
9064
  let accountId = auth.oauth.account_id;
8859
9065
  const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
8860
9066
  const apiKey = async () => {
9067
+ if (!authResolver.getOpenAiAccessToken) {
9068
+ throw new Error("OpenAI OAuth token refresh is unavailable");
9069
+ }
8861
9070
  const result = await authResolver.getOpenAiAccessToken();
8862
9071
  accountId = result.accountId ?? accountId;
8863
9072
  return result.token;
@@ -8960,7 +9169,10 @@ var resolveAnthropicStaticModelMaxTokens = (model) => {
8960
9169
  }
8961
9170
  return null;
8962
9171
  };
8963
- var resolveAnthropicModelMaxTokens = async (model) => {
9172
+ var resolveAnthropicModelMaxTokens = async (model, options) => {
9173
+ if (!options.useMetadata) {
9174
+ return resolveAnthropicStaticModelMaxTokens(model);
9175
+ }
8964
9176
  const metadataService = new import_model_metadata2.ModelMetadataServiceImpl({
8965
9177
  storagePathService: new import_storage8.StoragePathServiceImpl()
8966
9178
  });
@@ -9008,7 +9220,7 @@ var requestApprovalModeStartupSelection = async (state, projectKey) => {
9008
9220
  items: APPROVAL_MODE_STARTUP_PICK_ITEMS,
9009
9221
  multi: false
9010
9222
  });
9011
- const picked = (0, import_shared_types2.parseApprovalMode)(selection?.ids?.[0]);
9223
+ const picked = (0, import_shared_types4.parseApprovalMode)(selection?.ids?.[0]);
9012
9224
  if (!picked) {
9013
9225
  (0, import_logger.log)(`approval_mode startup selection skipped project=${projectKey}`);
9014
9226
  return null;
@@ -9153,7 +9365,12 @@ var requestMcpOAuthTokens = async (state, serverId, oauth2, errorMessage) => {
9153
9365
  var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMessage) => {
9154
9366
  const runId = state.activeRunId ?? void 0;
9155
9367
  if (runId) {
9156
- sendRunStatus(runId, "awaiting_ui", `MCP auth required: ${serverId}`);
9368
+ sendRunStatus(
9369
+ state,
9370
+ runId,
9371
+ "awaiting_ui",
9372
+ `MCP auth required: ${serverId}`
9373
+ );
9157
9374
  }
9158
9375
  try {
9159
9376
  const tokens = await requestMcpOAuthTokens(
@@ -9168,7 +9385,7 @@ var requestMcpOAuthTokensWithRunStatus = async (state, serverId, oauth2, errorMe
9168
9385
  return tokens;
9169
9386
  } finally {
9170
9387
  if (runId) {
9171
- sendRunStatus(runId, "running");
9388
+ sendRunStatus(state, runId, "running");
9172
9389
  }
9173
9390
  }
9174
9391
  };
@@ -9178,60 +9395,85 @@ var createAgentFactory = (state, options = {}) => {
9178
9395
  if (state.agent) return state.agent;
9179
9396
  if (inFlight) return inFlight;
9180
9397
  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);
9398
+ const environment = state.effectiveEnvironment;
9399
+ const workspaceRoot = environment.workspace.root ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? void 0;
9400
+ const localRuntimeEnabled = environment.workspace.filesystem === "enabled" || environment.workspace.process === "runtime" || environment.tools.builtin === "full-coding-agent";
9401
+ let approvalModeResolution = {
9402
+ approvalMode: "minimal",
9403
+ source: "environment",
9404
+ projectKey: workspaceRoot ?? "disabled-workspace"
9405
+ };
9406
+ let ctx = null;
9407
+ let sandboxKey = null;
9408
+ let agentsResolver = null;
9409
+ let skillsResolver = null;
9410
+ if (localRuntimeEnabled) {
9411
+ const sandboxRoot = workspaceRoot ?? process.cwd();
9412
+ approvalModeResolution = await resolveApprovalModeForRuntime({
9413
+ workingDir: sandboxRoot,
9414
+ runtimeSandboxRoot: sandboxRoot,
9415
+ requestStartupSelection: async ({ projectKey }) => {
9416
+ return requestApprovalModeStartupSelection(state, projectKey);
9417
+ },
9418
+ deferStartupSelectionPersist: true
9419
+ });
9420
+ ctx = await SandboxContext.create(sandboxRoot, {
9421
+ approvalMode: approvalModeResolution.approvalMode
9422
+ });
9423
+ (0, import_logger.log)(
9424
+ `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
9425
+ );
9426
+ state.runtimeWorkingDir = ctx.workingDir;
9427
+ state.runtimeSandboxRoot = ctx.rootDir;
9428
+ sandboxKey = createSandboxKey(ctx);
9429
+ }
9430
+ if (environment.context.projectInstructions === "from-workspace" && workspaceRoot) {
9431
+ agentsResolver = state.agentsResolver ?? await AgentsResolver.create(workspaceRoot);
9432
+ state.agentsResolver = agentsResolver;
9433
+ }
9434
+ if (environment.context.skills === "from-config" && workspaceRoot) {
9435
+ let skillsConfig;
9436
+ try {
9437
+ skillsConfig = await resolveEnvironmentSkillsConfig(
9438
+ state,
9439
+ workspaceRoot
9440
+ );
9441
+ } catch (error) {
9442
+ const message = error instanceof Error ? error.message : String(error);
9443
+ throw new Error(message);
9444
+ }
9445
+ skillsResolver = state.skillsResolver ?? await SkillsResolver.create({
9446
+ workingDir: workspaceRoot,
9447
+ config: skillsConfig
9448
+ });
9449
+ state.skillsResolver = skillsResolver;
9450
+ state.updateSkillsSnapshot(workspaceRoot, skillsResolver.getSnapshot());
9208
9451
  }
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
9452
  state.approvalMode = approvalModeResolution.approvalMode;
9218
- const sandboxKey = createSandboxKey(ctx);
9453
+ const toolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore ?? (environment.persistence.mode === "runtime" ? new import_storage8.ToolOutputCacheStoreImpl() : null);
9219
9454
  const todoSessionContextKey = createToolSessionContextKey(
9220
9455
  () => state.sessionId
9221
9456
  );
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
9457
+ let baseLocalTools = [];
9458
+ if (environment.tools.builtin === "full-coding-agent") {
9459
+ if (!ctx || !sandboxKey || !agentsResolver || !skillsResolver) {
9460
+ throw new Error(
9461
+ "full coding-agent tools require local sandbox, AGENTS, and skills context"
9462
+ );
9233
9463
  }
9234
- );
9464
+ const agentsResolverKey = createAgentsResolverKey(agentsResolver);
9465
+ const skillsResolverKey = createSkillsResolverKey(skillsResolver);
9466
+ baseLocalTools = createTools(
9467
+ sandboxKey,
9468
+ agentsResolverKey,
9469
+ skillsResolverKey,
9470
+ {
9471
+ toolOutputCacheStore,
9472
+ todoSessionContextKey,
9473
+ taskManager: options.taskManager
9474
+ }
9475
+ );
9476
+ }
9235
9477
  const editTool = baseLocalTools.find(
9236
9478
  (tool) => tool.definition.name === "edit"
9237
9479
  );
@@ -9239,7 +9481,7 @@ var createAgentFactory = (state, options = {}) => {
9239
9481
  (tool) => tool.definition.name === "apply_patch"
9240
9482
  );
9241
9483
  let mcpTools = [];
9242
- if (options.mcpManager) {
9484
+ if (environment.tools.mcp === "from-config" && options.mcpManager) {
9243
9485
  try {
9244
9486
  mcpTools = await options.mcpManager.getTools({
9245
9487
  onStatus: (message) => {
@@ -9258,12 +9500,24 @@ var createAgentFactory = (state, options = {}) => {
9258
9500
  (0, import_logger.log)(`failed to load mcp tools: ${String(error)}`);
9259
9501
  }
9260
9502
  }
9261
- const baseSystemPrompt = await loadSystemPrompt(ctx.workingDir);
9262
- const executionEnvironmentContext = await buildExecutionEnvironmentContext({
9263
- workingDir: ctx.workingDir,
9264
- sandboxRoot: ctx.rootDir,
9265
- config: executionEnvironmentConfig
9266
- });
9503
+ const hostTools = environment.tools.host === "enabled" ? await loadHostTools(environment.adapters.toolProviders ?? []) : [];
9504
+ const hostToolNames = new Set(hostTools.map((tool) => tool.name));
9505
+ const baseSystemPrompt = await loadEnvironmentSystemPrompt(
9506
+ state,
9507
+ workspaceRoot
9508
+ );
9509
+ let executionEnvironmentContext = null;
9510
+ if (environment.context.executionEnvironment === "from-config" && workspaceRoot && ctx) {
9511
+ const executionEnvironmentConfig = await resolveEnvironmentExecutionEnvironmentConfig(
9512
+ state,
9513
+ workspaceRoot
9514
+ );
9515
+ executionEnvironmentContext = await buildExecutionEnvironmentContext({
9516
+ workingDir: workspaceRoot,
9517
+ sandboxRoot: ctx.rootDir,
9518
+ config: executionEnvironmentConfig
9519
+ });
9520
+ }
9267
9521
  state.executionEnvironmentContext = executionEnvironmentContext;
9268
9522
  if (logInitialExecutionEnvironmentDebug(executionEnvironmentContext, {
9269
9523
  alreadyLogged: state.executionEnvironmentDebugLogged
@@ -9276,16 +9530,16 @@ var createAgentFactory = (state, options = {}) => {
9276
9530
  );
9277
9531
  const withAgentsContext = appendInitialAgentsContext(
9278
9532
  withExecutionEnvironment,
9279
- agentsResolver.buildInitialContext()
9533
+ agentsResolver?.buildInitialContext() ?? null
9280
9534
  );
9281
9535
  const systemPrompt = appendInitialSkillsCatalog(
9282
9536
  withAgentsContext,
9283
- await skillsResolver.buildInitialContext()
9537
+ skillsResolver ? await skillsResolver.buildInitialContext() : null
9284
9538
  );
9285
9539
  state.systemPrompt = systemPrompt;
9286
9540
  let permissionsConfig;
9287
9541
  try {
9288
- permissionsConfig = await resolvePermissionsConfig(ctx.workingDir);
9542
+ permissionsConfig = environment.config.source === "disabled" || !workspaceRoot ? void 0 : await resolveEnvironmentPermissionsConfig(state, workspaceRoot);
9289
9543
  } catch (error) {
9290
9544
  const message = error instanceof Error ? error.message : String(error);
9291
9545
  throw new Error(message);
@@ -9294,42 +9548,56 @@ var createAgentFactory = (state, options = {}) => {
9294
9548
  approvalMode: approvalModeResolution.approvalMode,
9295
9549
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
9296
9550
  user: permissionsConfig,
9297
- bashPathGuard: {
9298
- rootDir: ctx.rootDir,
9299
- workingDir: ctx.workingDir
9300
- }
9551
+ ...ctx ? {
9552
+ bashPathGuard: {
9553
+ rootDir: ctx.rootDir,
9554
+ workingDir: ctx.workingDir
9555
+ }
9556
+ } : {}
9301
9557
  });
9302
9558
  (0, import_logger.log)(
9303
9559
  `approval_mode resolved=${approvalModeResolution.approvalMode} source=${approvalModeResolution.source} project=${approvalModeResolution.projectKey}`
9304
9560
  );
9305
9561
  let modelConfig;
9306
9562
  try {
9307
- modelConfig = await resolveEffectiveModelConfig(state, ctx.workingDir);
9563
+ modelConfig = await resolveEffectiveModelConfig(state, workspaceRoot);
9308
9564
  } catch (error) {
9309
9565
  const message = error instanceof Error ? error.message : String(error);
9310
9566
  throw new Error(message);
9311
9567
  }
9312
- const authResolver = await AuthResolver.create(state, import_logger.log);
9568
+ const authResolver = await createEnvironmentAuthResolver(state, import_logger.log);
9313
9569
  const provider = await authResolver.resolveProvider(modelConfig.provider);
9314
9570
  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}'.`
9571
+ let hostedSearchDefinitions = [];
9572
+ let localSearchTools = [];
9573
+ if (environment.tools.search === "from-config") {
9574
+ const searchConfig = await resolveEnvironmentSearchConfig(
9575
+ state,
9576
+ workspaceRoot
9577
+ );
9578
+ hostedSearchDefinitions = buildHostedSearchToolDefinitions(
9579
+ provider,
9580
+ searchConfig
9323
9581
  );
9582
+ if (searchConfig.mode === "native" && hostedSearchDefinitions.length === 0) {
9583
+ throw new Error(
9584
+ `search.mode=native is enabled, but native search is unavailable for provider '${provider}'.`
9585
+ );
9586
+ }
9587
+ const useLocalSearchTool = searchConfig.mode === "local" || searchConfig.mode === "auto" && hostedSearchDefinitions.length === 0;
9588
+ localSearchTools = useLocalSearchTool ? [
9589
+ createSearchTool({
9590
+ defaultBackend: searchConfig.local.backend,
9591
+ braveApiKeyEnv: searchConfig.local.braveApiKeyEnv
9592
+ })
9593
+ ] : [];
9324
9594
  }
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];
9595
+ const tools = [
9596
+ ...baseLocalTools,
9597
+ ...localSearchTools,
9598
+ ...mcpTools,
9599
+ ...hostTools
9600
+ ];
9333
9601
  state.tools = tools;
9334
9602
  state.toolDefinitions = [
9335
9603
  ...tools.map((tool) => tool.definition),
@@ -9404,7 +9672,12 @@ var createAgentFactory = (state, options = {}) => {
9404
9672
  );
9405
9673
  }
9406
9674
  });
9407
- const modelMaxTokens = await resolveAnthropicModelMaxTokens(modelName);
9675
+ const modelMaxTokens = await resolveAnthropicModelMaxTokens(
9676
+ modelName,
9677
+ {
9678
+ useMetadata: environment.persistence.mode === "runtime"
9679
+ }
9680
+ );
9408
9681
  const maxTokens = resolveAnthropicMaxTokens({
9409
9682
  thinkingBudgetTokens: reasoning.thinking.type === "enabled" ? reasoning.thinking.budget_tokens : 0,
9410
9683
  modelLimitMaxTokens: modelMaxTokens
@@ -9461,9 +9734,9 @@ var createAgentFactory = (state, options = {}) => {
9461
9734
  state.currentModelProvider = provider;
9462
9735
  state.currentModelName = resolvedModelName;
9463
9736
  state.currentModelSource = modelConfig.source;
9464
- const modelRegistry = await buildModelRegistry(llm, {
9737
+ const modelRegistry = environment.persistence.mode === "runtime" ? await buildModelRegistry(llm, {
9465
9738
  strict: provider !== "openrouter"
9466
- });
9739
+ }) : import_core21.DEFAULT_MODEL_REGISTRY;
9467
9740
  const totalBudgetTrimEnabled = envTruthy(
9468
9741
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
9469
9742
  );
@@ -9478,6 +9751,12 @@ var createAgentFactory = (state, options = {}) => {
9478
9751
  },
9479
9752
  services: { toolOutputCacheStore },
9480
9753
  canExecuteTool: async (call, rawArgs, toolCtx) => {
9754
+ if (hostToolNames.has(call.function.name)) {
9755
+ (0, import_logger.debugLog)(
9756
+ `permission.evaluate tool=${call.function.name} decision=allow reason=host-tool`
9757
+ );
9758
+ return { decision: "allow" };
9759
+ }
9481
9760
  if (state.autoApprovedClientToolNames.has(call.function.name)) {
9482
9761
  (0, import_logger.debugLog)(
9483
9762
  `permission.evaluate tool=${call.function.name} decision=allow reason=client-tool-auto-approved`
@@ -9530,6 +9809,9 @@ var createAgentFactory = (state, options = {}) => {
9530
9809
  content
9531
9810
  }) ?? previewLanguage;
9532
9811
  try {
9812
+ if (!sandboxKey) {
9813
+ throw new Error("sandbox is unavailable");
9814
+ }
9533
9815
  const sandbox = await getSandboxContext(toolCtx, sandboxKey);
9534
9816
  const resolved = sandbox.resolvePath(filePath);
9535
9817
  let before = "";
@@ -9652,6 +9934,7 @@ var createAgentFactory = (state, options = {}) => {
9652
9934
  tool_call_id: call.id
9653
9935
  });
9654
9936
  await sendRunStatusAsync(
9937
+ state,
9655
9938
  runId,
9656
9939
  "awaiting_ui",
9657
9940
  "waiting for confirmation"
@@ -9667,7 +9950,7 @@ var createAgentFactory = (state, options = {}) => {
9667
9950
  allow_reason: true
9668
9951
  });
9669
9952
  if (runId) {
9670
- sendRunStatus(runId, "running");
9953
+ sendRunStatus(state, runId, "running");
9671
9954
  }
9672
9955
  if (!confirmResult?.ok) {
9673
9956
  const providedReason = confirmResult?.reason?.trim() ?? "";
@@ -9687,11 +9970,13 @@ var createAgentFactory = (state, options = {}) => {
9687
9970
  `permission.remember tool=${call.function.name} rules=${rules.length}`
9688
9971
  );
9689
9972
  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
- );
9973
+ void appendEnvironmentPermissionAllowRules(
9974
+ state,
9975
+ workspaceRoot,
9976
+ rules
9977
+ ).catch((error) => {
9978
+ (0, import_logger.log)(`failed to persist permission: ${String(error)}`);
9979
+ });
9695
9980
  }
9696
9981
  }
9697
9982
  return { decision: "allow" };
@@ -9711,6 +9996,213 @@ var createAgentFactory = (state, options = {}) => {
9711
9996
  };
9712
9997
  };
9713
9998
 
9999
+ // src/environment.ts
10000
+ var import_node_path15 = __toESM(require("path"), 1);
10001
+ var cloneContract = (contract) => ({
10002
+ workspace: { ...contract.workspace },
10003
+ context: { ...contract.context },
10004
+ auth: { ...contract.auth },
10005
+ config: { ...contract.config },
10006
+ tools: { ...contract.tools },
10007
+ persistence: { ...contract.persistence },
10008
+ events: { ...contract.events }
10009
+ });
10010
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? import_node_path15.default.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
10011
+ var runtimeEnvironmentPresets = {
10012
+ "tui-local": {
10013
+ workspace: {
10014
+ filesystem: "enabled",
10015
+ process: "runtime"
10016
+ },
10017
+ context: {
10018
+ systemPrompt: "runtime-default",
10019
+ projectInstructions: "from-workspace",
10020
+ skills: "from-config",
10021
+ executionEnvironment: "from-config"
10022
+ },
10023
+ auth: { model: "runtime-default" },
10024
+ config: { source: "runtime-default" },
10025
+ tools: {
10026
+ builtin: "full-coding-agent",
10027
+ search: "from-config",
10028
+ mcp: "from-config",
10029
+ host: "disabled"
10030
+ },
10031
+ persistence: { mode: "runtime" },
10032
+ events: { live: "json-rpc" }
10033
+ },
10034
+ "embedded-no-local-tools": {
10035
+ workspace: {
10036
+ filesystem: "disabled",
10037
+ process: "disabled"
10038
+ },
10039
+ context: {
10040
+ systemPrompt: "host",
10041
+ projectInstructions: "disabled",
10042
+ skills: "disabled",
10043
+ executionEnvironment: "disabled"
10044
+ },
10045
+ auth: { model: "host" },
10046
+ config: { source: "host" },
10047
+ tools: {
10048
+ builtin: "none",
10049
+ search: "disabled",
10050
+ mcp: "disabled",
10051
+ host: "enabled"
10052
+ },
10053
+ persistence: { mode: "volatile" },
10054
+ events: { live: "host" }
10055
+ }
10056
+ };
10057
+ var expandEnvironmentInput = (input) => {
10058
+ if (!input) {
10059
+ return {
10060
+ contract: cloneContract(runtimeEnvironmentPresets["tui-local"]),
10061
+ sourcePreset: "tui-local"
10062
+ };
10063
+ }
10064
+ if ("preset" in input) {
10065
+ return {
10066
+ contract: cloneContract(runtimeEnvironmentPresets[input.preset]),
10067
+ sourcePreset: input.preset
10068
+ };
10069
+ }
10070
+ return { contract: cloneContract(input.contract) };
10071
+ };
10072
+ var requireAdapter = (condition, name, reason) => {
10073
+ if (!condition) return;
10074
+ throw new Error(`Runtime environment requires adapters.${name}: ${reason}`);
10075
+ };
10076
+ var rejectContract = (condition, reason) => {
10077
+ if (!condition) return;
10078
+ throw new Error(`Invalid runtime environment: ${reason}`);
10079
+ };
10080
+ var resolveToolNames = (contract) => {
10081
+ const modelVisible = [];
10082
+ const operatorOnly = [];
10083
+ const disabled = [];
10084
+ if (contract.tools.builtin === "full-coding-agent") {
10085
+ modelVisible.push("builtin:full-coding-agent");
10086
+ } else {
10087
+ disabled.push("builtin");
10088
+ }
10089
+ if (contract.tools.search === "from-config") {
10090
+ modelVisible.push("search:from-config");
10091
+ } else {
10092
+ disabled.push("search");
10093
+ }
10094
+ if (contract.tools.mcp === "from-config") {
10095
+ modelVisible.push("mcp:from-config");
10096
+ operatorOnly.push("mcp.list");
10097
+ } else {
10098
+ disabled.push("mcp");
10099
+ }
10100
+ if (contract.tools.host === "enabled") {
10101
+ modelVisible.push("host-tools");
10102
+ } else {
10103
+ disabled.push("host-tools");
10104
+ }
10105
+ if (contract.workspace.process === "runtime") {
10106
+ operatorOnly.push("shell.*", "task.*");
10107
+ } else {
10108
+ disabled.push("process");
10109
+ }
10110
+ if (contract.context.skills === "from-config") {
10111
+ operatorOnly.push("skills.list");
10112
+ } else {
10113
+ disabled.push("skills");
10114
+ }
10115
+ if (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config") {
10116
+ operatorOnly.push("context.inspect");
10117
+ } else {
10118
+ disabled.push("local-context");
10119
+ }
10120
+ return { modelVisible, operatorOnly, disabled };
10121
+ };
10122
+ var resolveRuntimeEnvironment = (options = {}) => {
10123
+ const { contract, sourcePreset } = expandEnvironmentInput(
10124
+ options.environment
10125
+ );
10126
+ const adapters = options.adapters ?? {};
10127
+ if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
10128
+ contract.workspace.root = import_node_path15.default.resolve(
10129
+ contract.workspace.root ?? defaultWorkspaceRoot()
10130
+ );
10131
+ } else if (contract.workspace.root) {
10132
+ contract.workspace.root = import_node_path15.default.resolve(contract.workspace.root);
10133
+ }
10134
+ rejectContract(
10135
+ contract.workspace.filesystem === "disabled" && (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config" || contract.tools.builtin === "full-coding-agent" || contract.tools.mcp === "from-config"),
10136
+ "workspace filesystem is disabled but local workspace context/tools are enabled"
10137
+ );
10138
+ rejectContract(
10139
+ contract.workspace.process === "disabled" && contract.tools.builtin === "full-coding-agent",
10140
+ "full coding-agent builtin tools require runtime process support"
10141
+ );
10142
+ rejectContract(
10143
+ contract.tools.builtin === "full-coding-agent" && (contract.context.projectInstructions !== "from-workspace" || contract.context.skills !== "from-config"),
10144
+ "full coding-agent builtin tools require workspace project instructions and skills context"
10145
+ );
10146
+ rejectContract(
10147
+ contract.config.source === "disabled" && (contract.tools.search === "from-config" || contract.tools.mcp === "from-config" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config"),
10148
+ "config source is disabled but config-backed features are enabled"
10149
+ );
10150
+ rejectContract(
10151
+ contract.workspace.process === "runtime" && contract.persistence.mode === "volatile" && !adapters.stores?.taskManager,
10152
+ "runtime process support with volatile persistence requires adapters.stores.taskManager"
10153
+ );
10154
+ requireAdapter(
10155
+ contract.context.systemPrompt === "host" && !adapters.systemPromptProvider,
10156
+ "systemPromptProvider",
10157
+ "context.systemPrompt=host"
10158
+ );
10159
+ requireAdapter(
10160
+ contract.config.source === "host" && !adapters.configProvider,
10161
+ "configProvider",
10162
+ "config.source=host"
10163
+ );
10164
+ requireAdapter(
10165
+ contract.auth.model === "host" && !adapters.credentialProvider,
10166
+ "credentialProvider",
10167
+ "auth.model=host"
10168
+ );
10169
+ requireAdapter(
10170
+ contract.events.live === "host" && !adapters.eventSink,
10171
+ "eventSink",
10172
+ "events.live=host"
10173
+ );
10174
+ requireAdapter(
10175
+ contract.tools.host === "enabled" && !adapters.toolProviders,
10176
+ "toolProviders",
10177
+ "tools.host=enabled"
10178
+ );
10179
+ const resolvedTools = resolveToolNames(contract);
10180
+ const summary = {
10181
+ ...sourcePreset ? { source_preset: sourcePreset } : {},
10182
+ workspace: { ...contract.workspace },
10183
+ context: { ...contract.context },
10184
+ auth: { ...contract.auth },
10185
+ config: { ...contract.config },
10186
+ tools: {
10187
+ ...contract.tools,
10188
+ model_visible: [...resolvedTools.modelVisible],
10189
+ operator_only: [...resolvedTools.operatorOnly],
10190
+ disabled: [...resolvedTools.disabled]
10191
+ },
10192
+ persistence: { ...contract.persistence },
10193
+ events: { ...contract.events }
10194
+ };
10195
+ return {
10196
+ ...contract,
10197
+ ...sourcePreset ? { sourcePreset } : {},
10198
+ adapters,
10199
+ resolvedTools,
10200
+ summary
10201
+ };
10202
+ };
10203
+ var isTuiLocalEnvironment = (environment) => environment.workspace.filesystem === "enabled" && environment.workspace.process === "runtime" && environment.context.systemPrompt === "runtime-default" && environment.context.projectInstructions === "from-workspace" && environment.context.skills === "from-config" && environment.context.executionEnvironment === "from-config" && environment.auth.model === "runtime-default" && environment.config.source === "runtime-default" && environment.tools.builtin === "full-coding-agent" && environment.tools.search === "from-config" && environment.tools.mcp === "from-config" && environment.tools.host === "disabled" && environment.persistence.mode === "runtime" && environment.events.live === "json-rpc";
10204
+ var isProcessEnabled = (environment) => environment.workspace.process === "runtime";
10205
+
9714
10206
  // src/mcp/auth-store.ts
9715
10207
  var import_storage9 = require("@codelia/storage");
9716
10208
 
@@ -10880,6 +11372,101 @@ var SERVER_NAME = "codelia-runtime";
10880
11372
  var SERVER_VERSION = "0.1.0";
10881
11373
  var PROTOCOL_VERSION = "0";
10882
11374
 
11375
+ // src/volatile-stores.ts
11376
+ var stringifyMessageContent = (value) => {
11377
+ if (typeof value === "string") return value;
11378
+ if (Array.isArray(value)) {
11379
+ const parts = value.map((part) => {
11380
+ if (!part || typeof part !== "object") return "";
11381
+ const record = part;
11382
+ return typeof record.text === "string" ? record.text : "";
11383
+ }).filter((part) => part.length > 0);
11384
+ return parts.length ? parts.join("") : void 0;
11385
+ }
11386
+ return void 0;
11387
+ };
11388
+ var toSummary = (state) => {
11389
+ let lastUserMessage;
11390
+ for (let index = state.messages.length - 1; index >= 0; index -= 1) {
11391
+ const message = state.messages[index];
11392
+ if (message?.role !== "user") continue;
11393
+ lastUserMessage = stringifyMessageContent(message.content);
11394
+ break;
11395
+ }
11396
+ return {
11397
+ session_id: state.session_id,
11398
+ updated_at: state.updated_at,
11399
+ ...state.run_id ? { run_id: state.run_id } : {},
11400
+ message_count: state.messages.length,
11401
+ ...lastUserMessage ? { last_user_message: lastUserMessage } : {}
11402
+ };
11403
+ };
11404
+ var VolatileSessionStateStore = class {
11405
+ states = /* @__PURE__ */ new Map();
11406
+ async load(sessionId) {
11407
+ const state = this.states.get(sessionId);
11408
+ return state ? structuredClone(state) : null;
11409
+ }
11410
+ async save(state) {
11411
+ this.states.set(state.session_id, structuredClone(state));
11412
+ }
11413
+ async list() {
11414
+ return Array.from(this.states.values()).map(toSummary).sort((left, right) => right.updated_at.localeCompare(left.updated_at));
11415
+ }
11416
+ };
11417
+ var VolatileRunEventStoreFactory = class {
11418
+ records = /* @__PURE__ */ new Map();
11419
+ create(init) {
11420
+ const records = [];
11421
+ this.records.set(init.runId, records);
11422
+ return {
11423
+ append: (record) => {
11424
+ records.push(structuredClone(record));
11425
+ }
11426
+ };
11427
+ }
11428
+ };
11429
+ var VolatileToolOutputCacheStore = class {
11430
+ records = /* @__PURE__ */ new Map();
11431
+ async save(record) {
11432
+ const id = record.tool_call_id;
11433
+ this.records.set(id, structuredClone(record));
11434
+ return {
11435
+ id,
11436
+ byte_size: Buffer.byteLength(record.content, "utf8"),
11437
+ line_count: record.content.split(/\r?\n/).length
11438
+ };
11439
+ }
11440
+ async read(refId, options = {}) {
11441
+ const record = this.records.get(refId);
11442
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11443
+ const lines = record.content.split(/\r?\n/);
11444
+ const offset = Math.max(0, Math.trunc(options.offset ?? 0));
11445
+ const limit = Math.max(1, Math.trunc(options.limit ?? lines.length));
11446
+ return lines.slice(offset, offset + limit).join("\n");
11447
+ }
11448
+ async readLine(refId, options) {
11449
+ const record = this.records.get(refId);
11450
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11451
+ const lines = record.content.split(/\r?\n/);
11452
+ const line = lines[options.line_number - 1];
11453
+ if (line === void 0) {
11454
+ return `Line number out of range: ${options.line_number} (total ${lines.length})`;
11455
+ }
11456
+ const offset = Math.max(0, Math.trunc(options.char_offset ?? 0));
11457
+ const limit = Math.max(1, Math.trunc(options.char_limit ?? line.length));
11458
+ return line.slice(offset, offset + limit);
11459
+ }
11460
+ async grep(refId, options) {
11461
+ const record = this.records.get(refId);
11462
+ if (!record) throw new Error(`tool output not found: ${refId}`);
11463
+ const query = options.pattern.toLowerCase();
11464
+ return record.content.split(/\r?\n/).map((line, index) => ({ line, index })).filter(({ line }) => line.toLowerCase().includes(query)).slice(0, options.max_matches ?? 50).map(
11465
+ ({ line, index }) => `${String(index + 1).padStart(6, "0")} ${line}`
11466
+ ).join("\n");
11467
+ }
11468
+ };
11469
+
10883
11470
  // src/rpc/context.ts
10884
11471
  var import_protocol2 = require("@codelia/protocol");
10885
11472
  var createContextHandlers = ({
@@ -10887,10 +11474,14 @@ var createContextHandlers = ({
10887
11474
  log: log2
10888
11475
  }) => {
10889
11476
  const ensureAgentsResolver = async () => {
11477
+ if (state.effectiveEnvironment.context.projectInstructions !== "from-workspace") {
11478
+ return null;
11479
+ }
10890
11480
  if (state.agentsResolver) {
10891
11481
  return state.agentsResolver;
10892
11482
  }
10893
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11483
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11484
+ if (!workingDir) return null;
10894
11485
  try {
10895
11486
  const resolver = await AgentsResolver.create(workingDir);
10896
11487
  state.agentsResolver = resolver;
@@ -10905,14 +11496,18 @@ var createContextHandlers = ({
10905
11496
  }
10906
11497
  };
10907
11498
  const ensureSkillsResolver = async () => {
11499
+ if (state.effectiveEnvironment.context.skills !== "from-config") {
11500
+ return null;
11501
+ }
10908
11502
  if (state.skillsResolver) {
10909
11503
  return state.skillsResolver;
10910
11504
  }
10911
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11505
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11506
+ if (!workingDir) return null;
10912
11507
  try {
10913
11508
  const resolver = await SkillsResolver.create({
10914
11509
  workingDir,
10915
- config: await resolveSkillsConfig(workingDir)
11510
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
10916
11511
  });
10917
11512
  state.skillsResolver = resolver;
10918
11513
  state.runtimeWorkingDir = workingDir;
@@ -10926,16 +11521,23 @@ var createContextHandlers = ({
10926
11521
  }
10927
11522
  };
10928
11523
  const ensureExecutionEnvironmentContext = async () => {
11524
+ if (state.effectiveEnvironment.context.executionEnvironment !== "from-config") {
11525
+ return null;
11526
+ }
10929
11527
  if (state.executionEnvironmentContext) {
10930
11528
  return state.executionEnvironmentContext;
10931
11529
  }
10932
- const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
11530
+ const workingDir = state.runtimeWorkingDir ?? state.lastUiContext?.cwd;
11531
+ if (!workingDir) return null;
10933
11532
  const sandboxRoot = state.runtimeSandboxRoot ?? workingDir;
10934
11533
  try {
10935
11534
  const context = await buildExecutionEnvironmentContext({
10936
11535
  workingDir,
10937
11536
  sandboxRoot,
10938
- config: await resolveExecutionEnvironmentConfig(workingDir)
11537
+ config: await resolveEnvironmentExecutionEnvironmentConfig(
11538
+ state,
11539
+ workingDir
11540
+ )
10939
11541
  });
10940
11542
  state.executionEnvironmentContext = context;
10941
11543
  state.runtimeWorkingDir = workingDir;
@@ -10957,6 +11559,7 @@ var createContextHandlers = ({
10957
11559
  runtime_working_dir: state.runtimeWorkingDir ?? void 0,
10958
11560
  runtime_sandbox_root: state.runtimeSandboxRoot ?? void 0,
10959
11561
  execution_environment: executionEnvironment ?? void 0,
11562
+ runtime_environment: state.effectiveEnvironment.summary,
10960
11563
  ui_context: {
10961
11564
  cwd: state.lastUiContext?.cwd,
10962
11565
  workspace_root: state.lastUiContext?.workspace_root,
@@ -11006,7 +11609,7 @@ var createContextHandlers = ({
11006
11609
 
11007
11610
  // src/rpc/history.ts
11008
11611
  var import_node_fs16 = require("fs");
11009
- var import_node_path15 = __toESM(require("path"), 1);
11612
+ var import_node_path16 = __toESM(require("path"), 1);
11010
11613
  var import_node_readline2 = require("readline");
11011
11614
  var import_protocol3 = require("@codelia/protocol");
11012
11615
  var import_storage10 = require("@codelia/storage");
@@ -11080,7 +11683,7 @@ var collectRunCandidates = async (log2) => {
11080
11683
  for (const yearEntry of yearEntries) {
11081
11684
  if (!yearEntry.isDirectory()) continue;
11082
11685
  if (!/^\d{4}$/.test(yearEntry.name)) continue;
11083
- const yearPath = import_node_path15.default.join(sessionsDir, yearEntry.name);
11686
+ const yearPath = import_node_path16.default.join(sessionsDir, yearEntry.name);
11084
11687
  let monthEntries;
11085
11688
  try {
11086
11689
  monthEntries = await import_node_fs16.promises.readdir(yearPath, {
@@ -11093,7 +11696,7 @@ var collectRunCandidates = async (log2) => {
11093
11696
  for (const monthEntry of monthEntries) {
11094
11697
  if (!monthEntry.isDirectory()) continue;
11095
11698
  if (!/^\d{2}$/.test(monthEntry.name)) continue;
11096
- const monthPath = import_node_path15.default.join(yearPath, monthEntry.name);
11699
+ const monthPath = import_node_path16.default.join(yearPath, monthEntry.name);
11097
11700
  let dayEntries;
11098
11701
  try {
11099
11702
  dayEntries = await import_node_fs16.promises.readdir(monthPath, {
@@ -11106,7 +11709,7 @@ var collectRunCandidates = async (log2) => {
11106
11709
  for (const dayEntry of dayEntries) {
11107
11710
  if (!dayEntry.isDirectory()) continue;
11108
11711
  if (!/^\d{2}$/.test(dayEntry.name)) continue;
11109
- const dayPath = import_node_path15.default.join(monthPath, dayEntry.name);
11712
+ const dayPath = import_node_path16.default.join(monthPath, dayEntry.name);
11110
11713
  let files;
11111
11714
  try {
11112
11715
  files = await import_node_fs16.promises.readdir(dayPath, {
@@ -11119,7 +11722,7 @@ var collectRunCandidates = async (log2) => {
11119
11722
  for (const file of files) {
11120
11723
  if (!file.isFile()) continue;
11121
11724
  if (!file.name.endsWith(".jsonl")) continue;
11122
- const filePath = import_node_path15.default.join(dayPath, file.name);
11725
+ const filePath = import_node_path16.default.join(dayPath, file.name);
11123
11726
  try {
11124
11727
  const stat = await import_node_fs16.promises.stat(filePath);
11125
11728
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
@@ -11147,7 +11750,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
11147
11750
  const header = parseRunHeader(headerLine);
11148
11751
  if (!header) continue;
11149
11752
  if (header.session_id !== sessionId) continue;
11150
- const runId = header.run_id ?? import_node_path15.default.basename(candidate.path, ".jsonl");
11753
+ const runId = header.run_id ?? import_node_path16.default.basename(candidate.path, ".jsonl");
11151
11754
  const startedAt = header.started_at ?? new Date(candidate.mtimeMs).toISOString();
11152
11755
  runs.push({
11153
11756
  path: candidate.path,
@@ -11193,14 +11796,16 @@ var sendHistoryEvent = (runId, seq, event) => {
11193
11796
  var createHistoryHandlers = ({
11194
11797
  sessionStateStore,
11195
11798
  log: log2,
11799
+ readRunLogs = true,
11196
11800
  getCurrentWorkspaceRoot,
11197
- buildResumeDiffSummary
11801
+ buildResumeDiffSummary,
11802
+ sendHistoryEvent: emitHistoryEvent = sendHistoryEvent
11198
11803
  }) => {
11199
11804
  const normalizeWorkspaceRoot = (value) => {
11200
11805
  if (typeof value !== "string") return void 0;
11201
11806
  const trimmed = value.trim();
11202
11807
  if (!trimmed) return void 0;
11203
- return import_node_path15.default.resolve(trimmed);
11808
+ return import_node_path16.default.resolve(trimmed);
11204
11809
  };
11205
11810
  const handleSessionList = async (id, params) => {
11206
11811
  const limit = params?.limit ?? 50;
@@ -11250,7 +11855,7 @@ var createHistoryHandlers = ({
11250
11855
  sendResult(id, result2);
11251
11856
  return;
11252
11857
  }
11253
- const runs = await collectSessionRuns(sessionId, maxRuns, log2);
11858
+ const runs = readRunLogs ? await collectSessionRuns(sessionId, maxRuns, log2) : [];
11254
11859
  const replayEvents = [];
11255
11860
  for (const run of runs) {
11256
11861
  for await (const line of readJsonl(run.path)) {
@@ -11287,7 +11892,7 @@ var createHistoryHandlers = ({
11287
11892
  const truncated = replayEvents.length > maxEvents;
11288
11893
  const selectedEvents = truncated ? replayEvents.slice(replayEvents.length - maxEvents) : replayEvents;
11289
11894
  for (const event of selectedEvents) {
11290
- sendHistoryEvent(event.runId, event.seq, event.event);
11895
+ await emitHistoryEvent(event.runId, event.seq, event.event);
11291
11896
  }
11292
11897
  let resumeDiff;
11293
11898
  if (buildResumeDiffSummary) {
@@ -11396,7 +12001,10 @@ var sortModelsByReleaseDate = (models, provider, providerEntries) => {
11396
12001
  });
11397
12002
  return sortable.map((item) => item.model);
11398
12003
  };
11399
- var loadProviderModelEntries = async (provider) => {
12004
+ var loadProviderModelEntries = async (provider, state) => {
12005
+ if (state?.effectiveEnvironment.persistence.mode === "volatile") {
12006
+ return null;
12007
+ }
11400
12008
  const metadataService = new import_model_metadata3.ModelMetadataServiceImpl();
11401
12009
  const allEntries = await metadataService.getAllModelEntries();
11402
12010
  return allEntries[provider] ?? null;
@@ -11432,7 +12040,10 @@ var buildOpenRouterHeaders = (apiKey) => {
11432
12040
  }
11433
12041
  return headers;
11434
12042
  };
11435
- var resolveOpenRouterApiKey = async () => {
12043
+ var resolveOpenRouterApiKey = async (state) => {
12044
+ if (state?.effectiveEnvironment.auth.model === "host") {
12045
+ return null;
12046
+ }
11436
12047
  const envKey = readEnvValue("OPENROUTER_API_KEY");
11437
12048
  if (envKey) {
11438
12049
  return envKey;
@@ -11450,14 +12061,14 @@ var resolveOpenRouterApiKeyWithPrompt = async ({
11450
12061
  state,
11451
12062
  log: log2
11452
12063
  }) => {
11453
- const existing = await resolveOpenRouterApiKey();
12064
+ const existing = await resolveOpenRouterApiKey(state);
11454
12065
  if (existing) {
11455
12066
  return existing;
11456
12067
  }
11457
12068
  if (!state) {
11458
12069
  throw new Error("OpenRouter API key is required");
11459
12070
  }
11460
- const authResolver = await AuthResolver.create(state, log2);
12071
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
11461
12072
  const auth = await authResolver.resolveProviderAuth("openrouter");
11462
12073
  if (auth.method !== "api_key") {
11463
12074
  throw new Error("OpenRouter API key is required");
@@ -11568,7 +12179,7 @@ var buildProviderModelList = async ({
11568
12179
  providerEntries = providerEntriesOverride;
11569
12180
  } else {
11570
12181
  try {
11571
- providerEntries = await loadProviderModelEntries(provider);
12182
+ providerEntries = await loadProviderModelEntries(provider, state);
11572
12183
  } catch (error) {
11573
12184
  if (includeDetails) {
11574
12185
  log2(`model.list details error: ${error}`);
@@ -11734,7 +12345,7 @@ var createModelHandlers = ({
11734
12345
  try {
11735
12346
  clearSessionModelOverride(state);
11736
12347
  await persistSessionModelOverride();
11737
- const config = await resolveModelConfig(workingDir);
12348
+ const config = await resolveEnvironmentModelConfig(state, workingDir);
11738
12349
  const provider2 = config.provider ?? "openai";
11739
12350
  const name2 = config.name;
11740
12351
  if (!name2) {
@@ -11812,7 +12423,7 @@ var createModelHandlers = ({
11812
12423
  try {
11813
12424
  let target = null;
11814
12425
  if (scope === "config") {
11815
- target = await updateModel(workingDir, {
12426
+ target = await updateEnvironmentModel(state, workingDir, {
11816
12427
  provider,
11817
12428
  name,
11818
12429
  ...reasoning ? { reasoning } : {},
@@ -11821,7 +12432,10 @@ var createModelHandlers = ({
11821
12432
  clearSessionModelOverride(state);
11822
12433
  await persistSessionModelOverride();
11823
12434
  } else {
11824
- const baseConfig = await resolveModelConfig(workingDir);
12435
+ const baseConfig = await resolveEnvironmentModelConfig(
12436
+ state,
12437
+ workingDir
12438
+ );
11825
12439
  setSessionModelOverride(state, baseConfig, {
11826
12440
  provider,
11827
12441
  name,
@@ -11870,7 +12484,7 @@ var createModelHandlers = ({
11870
12484
 
11871
12485
  // src/rpc/resume-context.ts
11872
12486
  var import_node_fs17 = require("fs");
11873
- var import_node_path16 = __toESM(require("path"), 1);
12487
+ var import_node_path17 = __toESM(require("path"), 1);
11874
12488
  var RESUME_CONTEXT_META_KEY = "codelia_resume_context";
11875
12489
  var RESUME_CONTEXT_SCHEMA_VERSION = 1;
11876
12490
  var RESUME_DIFF_TAG = '<system-reminder type="session.resume.diff">';
@@ -11879,7 +12493,7 @@ var normalizePath2 = (value) => {
11879
12493
  if (typeof value !== "string") return void 0;
11880
12494
  const trimmed = value.trim();
11881
12495
  if (!trimmed) return void 0;
11882
- return import_node_path16.default.resolve(trimmed);
12496
+ return import_node_path17.default.resolve(trimmed);
11883
12497
  };
11884
12498
  var normalizeMtime3 = (value) => {
11885
12499
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
@@ -12841,7 +13455,7 @@ var createRunHandlers = ({
12841
13455
  );
12842
13456
  };
12843
13457
  const emitRunStatus = (runId, status, message) => {
12844
- sendRunStatus(runId, status, message);
13458
+ sendRunStatus(state, runId, status, message);
12845
13459
  const suffix = message ? ` message=${message}` : "";
12846
13460
  logRunDebug(log2, runId, `status=${status} sent${suffix}`);
12847
13461
  appendSession({
@@ -13015,7 +13629,7 @@ var createRunHandlers = ({
13015
13629
  const emitRunDiagnostics = (params2) => {
13016
13630
  if (!state.diagnosticsEnabled) return;
13017
13631
  try {
13018
- sendRunDiagnostics(params2);
13632
+ sendRunDiagnostics(state, params2);
13019
13633
  } catch (error) {
13020
13634
  log2(`run diagnostics emit failed: ${String(error)}`);
13021
13635
  }
@@ -13147,6 +13761,9 @@ var createRunHandlers = ({
13147
13761
  os: process.platform,
13148
13762
  arch: process.arch,
13149
13763
  version: SERVER_VERSION
13764
+ },
13765
+ meta: {
13766
+ runtime_environment: state.effectiveEnvironment.summary
13150
13767
  }
13151
13768
  });
13152
13769
  appendSession({
@@ -13281,7 +13898,7 @@ var createRunHandlers = ({
13281
13898
  }
13282
13899
  const contextLeftPercent = runtimeAgent.getContextLeftPercent();
13283
13900
  if (contextLeftPercent !== null && state.updateContextLeftPercent(contextLeftPercent)) {
13284
- sendRunContext(runId, contextLeftPercent);
13901
+ sendRunContext(state, runId, contextLeftPercent);
13285
13902
  appendSession({
13286
13903
  type: "run.context",
13287
13904
  run_id: runId,
@@ -13372,7 +13989,7 @@ var createRunHandlers = ({
13372
13989
  };
13373
13990
 
13374
13991
  // src/rpc/shell.ts
13375
- var import_node_path17 = __toESM(require("path"), 1);
13992
+ var import_node_path18 = __toESM(require("path"), 1);
13376
13993
  var import_protocol6 = require("@codelia/protocol");
13377
13994
  var import_storage11 = require("@codelia/storage");
13378
13995
  var COMMAND_PREVIEW_CHARS = 400;
@@ -13387,14 +14004,14 @@ var truncateCommandPreview = (value) => {
13387
14004
  return `${trimmed.slice(0, COMMAND_PREVIEW_CHARS)}...[truncated]`;
13388
14005
  };
13389
14006
  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);
14007
+ const relative = import_node_path18.default.relative(basePath, candidatePath);
14008
+ return relative === "" || !relative.startsWith("..") && !import_node_path18.default.isAbsolute(relative);
13392
14009
  };
13393
14010
  var resolveShellCwd = (state, requestedCwd) => {
13394
14011
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
13395
14012
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
13396
14013
  if (!requestedCwd) return workingDir;
13397
- const resolved = import_node_path17.default.resolve(workingDir, requestedCwd);
14014
+ const resolved = import_node_path18.default.resolve(workingDir, requestedCwd);
13398
14015
  if (!isWithin2(rootDir, resolved)) {
13399
14016
  return null;
13400
14017
  }
@@ -13979,14 +14596,14 @@ var createShellHandlers = ({
13979
14596
  };
13980
14597
 
13981
14598
  // src/rpc/skills.ts
13982
- var import_node_path18 = __toESM(require("path"), 1);
14599
+ var import_node_path19 = __toESM(require("path"), 1);
13983
14600
  var import_protocol7 = require("@codelia/protocol");
13984
14601
  var createSkillsHandlers = ({
13985
14602
  state,
13986
14603
  log: log2
13987
14604
  }) => {
13988
14605
  const handleSkillsList = async (id, params) => {
13989
- const requestedCwd = params?.cwd ? import_node_path18.default.resolve(params.cwd) : void 0;
14606
+ const requestedCwd = params?.cwd ? import_node_path19.default.resolve(params.cwd) : void 0;
13990
14607
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
13991
14608
  const forceReload = params?.force_reload ?? false;
13992
14609
  if (!forceReload) {
@@ -14006,7 +14623,7 @@ var createSkillsHandlers = ({
14006
14623
  try {
14007
14624
  resolver = await SkillsResolver.create({
14008
14625
  workingDir,
14009
- config: await resolveSkillsConfig(workingDir)
14626
+ config: await resolveEnvironmentSkillsConfig(state, workingDir)
14010
14627
  });
14011
14628
  } catch (error) {
14012
14629
  sendError(id, {
@@ -14041,7 +14658,7 @@ var createSkillsHandlers = ({
14041
14658
  };
14042
14659
 
14043
14660
  // src/rpc/task.ts
14044
- var import_node_path19 = __toESM(require("path"), 1);
14661
+ var import_node_path20 = __toESM(require("path"), 1);
14045
14662
  var import_protocol8 = require("@codelia/protocol");
14046
14663
  var import_storage12 = require("@codelia/storage");
14047
14664
  var DEFAULT_TRUNCATED2 = {
@@ -14076,14 +14693,14 @@ var getPublicTaskKey = (task) => {
14076
14693
  return suffix ? `${toShellKeyBase2(task.label)}-${suffix}` : void 0;
14077
14694
  };
14078
14695
  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);
14696
+ const relative = import_node_path20.default.relative(basePath, candidatePath);
14697
+ return relative === "" || !relative.startsWith("..") && !import_node_path20.default.isAbsolute(relative);
14081
14698
  };
14082
14699
  var resolveShellCwd2 = (state, requestedCwd) => {
14083
14700
  const workingDir = state.runtimeWorkingDir ?? process.cwd();
14084
14701
  const rootDir = state.runtimeSandboxRoot ?? workingDir;
14085
14702
  if (!requestedCwd) return workingDir;
14086
- const resolved = import_node_path19.default.resolve(workingDir, requestedCwd);
14703
+ const resolved = import_node_path20.default.resolve(workingDir, requestedCwd);
14087
14704
  if (!isWithin3(rootDir, resolved)) {
14088
14705
  return null;
14089
14706
  }
@@ -14487,6 +15104,7 @@ var SUPPORTED_TUI_THEMES = /* @__PURE__ */ new Set([
14487
15104
  "crimson",
14488
15105
  "wine"
14489
15106
  ]);
15107
+ var isReadableToolOutputCacheStore = (store) => !!store && typeof store.read === "function" && typeof store.readLine === "function";
14490
15108
  var createRuntimeHandlers = ({
14491
15109
  state,
14492
15110
  getAgent,
@@ -14497,19 +15115,24 @@ var createRuntimeHandlers = ({
14497
15115
  buildProviderModelList: injectedBuildProviderModelList,
14498
15116
  taskManager: injectedTaskManager
14499
15117
  }) => {
14500
- const sessionStateStore = injectedSessionStateStore ?? new import_storage13.SessionStateStoreImpl({
15118
+ const environment = state.effectiveEnvironment;
15119
+ const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage13.SessionStateStoreImpl({
14501
15120
  onError: (error, context) => {
14502
15121
  log2(
14503
15122
  `session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
14504
15123
  );
14505
15124
  }
14506
- });
14507
- const runEventStoreFactory = injectedRunEventStoreFactory ?? new import_storage13.RunEventStoreFactoryImpl();
15125
+ }));
15126
+ const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage13.RunEventStoreFactoryImpl());
14508
15127
  const mcpManager = injectedMcpManager ?? {
14509
15128
  start: async () => void 0,
14510
15129
  list: () => ({ servers: [] })
14511
15130
  };
14512
15131
  const buildProviderModelList2 = injectedBuildProviderModelList ?? buildProviderModelList;
15132
+ const adapterToolOutputCacheStore = environment.adapters.stores?.toolOutputCacheStore;
15133
+ const toolOutputCacheStore = isReadableToolOutputCacheStore(
15134
+ adapterToolOutputCacheStore
15135
+ ) ? adapterToolOutputCacheStore : environment.persistence.mode === "volatile" ? new VolatileToolOutputCacheStore() : void 0;
14513
15136
  let startupOnboardingPromise = null;
14514
15137
  let startupOnboardingStarted = false;
14515
15138
  const appendSession = (record) => {
@@ -14538,12 +15161,15 @@ var createRuntimeHandlers = ({
14538
15161
  return parts.join(" \u2022 ");
14539
15162
  };
14540
15163
  const runStartupOnboarding = async () => {
15164
+ if (!isTuiLocalEnvironment(state.effectiveEnvironment)) {
15165
+ return;
15166
+ }
14541
15167
  const supportsPick = !!state.uiCapabilities?.supports_pick;
14542
15168
  const supportsPrompt = !!state.uiCapabilities?.supports_prompt;
14543
15169
  if (!supportsPick || !supportsPrompt) {
14544
15170
  return;
14545
15171
  }
14546
- const authResolver = await AuthResolver.create(state, log2);
15172
+ const authResolver = await createEnvironmentAuthResolver(state, log2);
14547
15173
  if (authResolver.hasAnyAvailableAuth()) {
14548
15174
  return;
14549
15175
  }
@@ -14593,7 +15219,7 @@ var createRuntimeHandlers = ({
14593
15219
  return;
14594
15220
  }
14595
15221
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14596
- const modelTarget = await updateModel(workingDir, {
15222
+ const modelTarget = await updateEnvironmentModel(state, workingDir, {
14597
15223
  provider,
14598
15224
  name: selectedModel
14599
15225
  });
@@ -14633,7 +15259,22 @@ var createRuntimeHandlers = ({
14633
15259
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
14634
15260
  sessionStateStore,
14635
15261
  log: log2,
14636
- getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd(),
15262
+ readRunLogs: environment.persistence.mode === "runtime",
15263
+ ...environment.events.live === "host" ? {
15264
+ sendHistoryEvent: async (runId, seq, event) => {
15265
+ const notify = {
15266
+ jsonrpc: "2.0",
15267
+ method: "agent.event",
15268
+ params: {
15269
+ run_id: runId,
15270
+ seq,
15271
+ event
15272
+ }
15273
+ };
15274
+ await sendNotificationAsync(state, notify);
15275
+ }
15276
+ } : {},
15277
+ getCurrentWorkspaceRoot: () => state.lastUiContext?.workspace_root ?? state.agentsResolver?.getRootDir() ?? state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? environment.workspace.root,
14637
15278
  buildResumeDiffSummary: async (meta) => {
14638
15279
  if (!hasStructuredResumeContextMeta(meta)) {
14639
15280
  return void 0;
@@ -14664,56 +15305,50 @@ var createRuntimeHandlers = ({
14664
15305
  state,
14665
15306
  getAgent
14666
15307
  });
14667
- const {
14668
- handleShellExec,
14669
- handleShellStart,
14670
- handleShellList,
14671
- handleShellStatus,
14672
- handleShellOutput,
14673
- handleShellWait,
14674
- handleShellDetach,
14675
- handleShellCancel
14676
- } = createShellHandlers({
15308
+ const processHandlersEnabled = state.effectiveEnvironment.workspace.process === "runtime";
15309
+ const shellHandlers = processHandlersEnabled ? createShellHandlers({
14677
15310
  state,
14678
15311
  log: log2,
14679
- taskManager: injectedTaskManager
14680
- });
14681
- const {
14682
- handleTaskSpawn,
14683
- handleTaskList,
14684
- handleTaskStatus,
14685
- handleTaskWait,
14686
- handleTaskCancel,
14687
- handleTaskResult
14688
- } = createTaskHandlers({
15312
+ taskManager: injectedTaskManager,
15313
+ outputCache: toolOutputCacheStore ?? void 0
15314
+ }) : null;
15315
+ const taskHandlers = processHandlersEnabled ? createTaskHandlers({
14689
15316
  state,
14690
15317
  log: log2,
14691
- taskManager: injectedTaskManager
14692
- });
15318
+ taskManager: injectedTaskManager,
15319
+ outputCache: toolOutputCacheStore ?? void 0
15320
+ }) : null;
14693
15321
  const handleInitialize = async (id, params) => {
14694
15322
  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)}`);
15323
+ const environment2 = state.effectiveEnvironment;
15324
+ if (isTuiLocalEnvironment(environment2)) {
15325
+ try {
15326
+ const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
15327
+ resolvedTheme = (await resolveEnvironmentTuiConfig(state, workingDir)).theme;
15328
+ } catch (error) {
15329
+ log2(`initialize tui config load failed: ${String(error)}`);
15330
+ }
14700
15331
  }
15332
+ const processEnabled = environment2.workspace.process === "runtime";
15333
+ const mcpEnabled = environment2.tools.mcp === "from-config";
15334
+ const skillsEnabled = environment2.context.skills === "from-config";
15335
+ const themeSetEnabled = isTuiLocalEnvironment(environment2) && environment2.config.source !== "disabled";
14701
15336
  const result = {
14702
15337
  protocol_version: PROTOCOL_VERSION,
14703
15338
  server: { name: SERVER_NAME, version: SERVER_VERSION },
14704
15339
  server_capabilities: {
14705
15340
  supports_run_cancel: true,
14706
15341
  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,
15342
+ supports_shell_exec: processEnabled,
15343
+ supports_shell_tasks: processEnabled,
15344
+ supports_shell_detach: processEnabled,
15345
+ supports_tasks: processEnabled,
15346
+ supports_ui_requests: isTuiLocalEnvironment(environment2),
15347
+ supports_mcp_list: mcpEnabled,
15348
+ supports_skills_list: skillsEnabled,
14714
15349
  supports_context_inspect: true,
14715
15350
  supports_tool_call: true,
14716
- supports_theme_set: true,
15351
+ supports_theme_set: themeSetEnabled,
14717
15352
  supports_permission_preflight_events: true
14718
15353
  },
14719
15354
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
@@ -14755,7 +15390,7 @@ var createRuntimeHandlers = ({
14755
15390
  }
14756
15391
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
14757
15392
  try {
14758
- const target = await updateTuiTheme(workingDir, name);
15393
+ const target = await updateEnvironmentTuiTheme(state, workingDir, name);
14759
15394
  const result = {
14760
15395
  name,
14761
15396
  scope: target.scope,
@@ -14780,6 +15415,31 @@ var createRuntimeHandlers = ({
14780
15415
  }
14781
15416
  const clearSession = params?.clear_session ?? true;
14782
15417
  try {
15418
+ if (state.effectiveEnvironment.auth.model === "host") {
15419
+ const clearAuth = state.effectiveEnvironment.adapters.credentialProvider?.clearAuth;
15420
+ if (!clearAuth) {
15421
+ sendError(id, {
15422
+ code: import_protocol10.RPC_ERROR_CODE.RUNTIME_INTERNAL,
15423
+ message: "host auth provider does not support logout"
15424
+ });
15425
+ return;
15426
+ }
15427
+ await clearAuth();
15428
+ state.agent = null;
15429
+ if (clearSession) {
15430
+ state.sessionId = null;
15431
+ state.sessionMeta = null;
15432
+ state.sessionAppend = null;
15433
+ state.sessionModelOverride = null;
15434
+ }
15435
+ sendResult(id, {
15436
+ ok: true,
15437
+ auth_cleared: true,
15438
+ session_cleared: clearSession
15439
+ });
15440
+ log2(`auth.logout host session_cleared=${clearSession}`);
15441
+ return;
15442
+ }
14783
15443
  const supportsConfirm = !!state.uiCapabilities?.supports_confirm;
14784
15444
  if (!supportsConfirm) {
14785
15445
  sendError(id, {
@@ -14833,6 +15493,13 @@ var createRuntimeHandlers = ({
14833
15493
  }
14834
15494
  };
14835
15495
  const handleRequest = async (req) => {
15496
+ const mcpEnabled = state.effectiveEnvironment.tools.mcp === "from-config";
15497
+ const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
15498
+ const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
15499
+ const rejectDisabled = (message) => sendError(req.id, {
15500
+ code: import_protocol10.RPC_ERROR_CODE.INVALID_PARAMS,
15501
+ message
15502
+ });
14836
15503
  switch (req.method) {
14837
15504
  case "initialize":
14838
15505
  return handleInitialize(req.id, req.params);
@@ -14853,44 +15520,120 @@ var createRuntimeHandlers = ({
14853
15520
  case "tool.call":
14854
15521
  return handleToolCall(req.id, req.params);
14855
15522
  case "shell.exec":
14856
- return handleShellExec(req.id, req.params);
15523
+ if (!shellHandlers)
15524
+ return rejectDisabled("process execution is disabled");
15525
+ return shellHandlers.handleShellExec(
15526
+ req.id,
15527
+ req.params
15528
+ );
14857
15529
  case "shell.start":
14858
- return handleShellStart(req.id, req.params);
15530
+ if (!shellHandlers)
15531
+ return rejectDisabled("process execution is disabled");
15532
+ return shellHandlers.handleShellStart(
15533
+ req.id,
15534
+ req.params
15535
+ );
14859
15536
  case "shell.list":
14860
- return handleShellList(req.id, req.params);
15537
+ if (!shellHandlers)
15538
+ return rejectDisabled("process execution is disabled");
15539
+ return shellHandlers.handleShellList(
15540
+ req.id,
15541
+ req.params
15542
+ );
14861
15543
  case "shell.status":
14862
- return handleShellStatus(req.id, req.params);
15544
+ if (!shellHandlers)
15545
+ return rejectDisabled("process execution is disabled");
15546
+ return shellHandlers.handleShellStatus(
15547
+ req.id,
15548
+ req.params
15549
+ );
14863
15550
  case "shell.output":
14864
- return handleShellOutput(req.id, req.params);
15551
+ if (!shellHandlers)
15552
+ return rejectDisabled("process execution is disabled");
15553
+ return shellHandlers.handleShellOutput(
15554
+ req.id,
15555
+ req.params
15556
+ );
14865
15557
  case "shell.wait":
14866
- return handleShellWait(req.id, req.params);
15558
+ if (!shellHandlers)
15559
+ return rejectDisabled("process execution is disabled");
15560
+ return shellHandlers.handleShellWait(
15561
+ req.id,
15562
+ req.params
15563
+ );
14867
15564
  case "shell.detach":
14868
- return handleShellDetach(req.id, req.params);
15565
+ if (!shellHandlers)
15566
+ return rejectDisabled("process execution is disabled");
15567
+ return shellHandlers.handleShellDetach(
15568
+ req.id,
15569
+ req.params
15570
+ );
14869
15571
  case "shell.cancel":
14870
- return handleShellCancel(req.id, req.params);
15572
+ if (!shellHandlers)
15573
+ return rejectDisabled("process execution is disabled");
15574
+ return shellHandlers.handleShellCancel(
15575
+ req.id,
15576
+ req.params
15577
+ );
14871
15578
  case "task.spawn":
14872
- return handleTaskSpawn(req.id, req.params);
15579
+ if (!taskHandlers)
15580
+ return rejectDisabled("process execution is disabled");
15581
+ return taskHandlers.handleTaskSpawn(
15582
+ req.id,
15583
+ req.params
15584
+ );
14873
15585
  case "task.list":
14874
- return handleTaskList(req.id, req.params);
15586
+ if (!taskHandlers)
15587
+ return rejectDisabled("process execution is disabled");
15588
+ return taskHandlers.handleTaskList(
15589
+ req.id,
15590
+ req.params
15591
+ );
14875
15592
  case "task.status":
14876
- return handleTaskStatus(req.id, req.params);
15593
+ if (!taskHandlers)
15594
+ return rejectDisabled("process execution is disabled");
15595
+ return taskHandlers.handleTaskStatus(
15596
+ req.id,
15597
+ req.params
15598
+ );
14877
15599
  case "task.wait":
14878
- return handleTaskWait(req.id, req.params);
15600
+ if (!taskHandlers)
15601
+ return rejectDisabled("process execution is disabled");
15602
+ return taskHandlers.handleTaskWait(
15603
+ req.id,
15604
+ req.params
15605
+ );
14879
15606
  case "task.cancel":
14880
- return handleTaskCancel(req.id, req.params);
15607
+ if (!taskHandlers)
15608
+ return rejectDisabled("process execution is disabled");
15609
+ return taskHandlers.handleTaskCancel(
15610
+ req.id,
15611
+ req.params
15612
+ );
14881
15613
  case "task.result":
14882
- return handleTaskResult(req.id, req.params);
15614
+ if (!taskHandlers)
15615
+ return rejectDisabled("process execution is disabled");
15616
+ return taskHandlers.handleTaskResult(
15617
+ req.id,
15618
+ req.params
15619
+ );
14883
15620
  case "mcp.list":
15621
+ if (!mcpEnabled) {
15622
+ return sendResult(req.id, { servers: [] });
15623
+ }
14884
15624
  await mcpManager.start?.();
14885
15625
  return sendResult(
14886
15626
  req.id,
14887
15627
  mcpManager.list(req.params?.scope)
14888
15628
  );
14889
15629
  case "skills.list":
15630
+ if (!skillsEnabled) return rejectDisabled("skills are disabled");
14890
15631
  return handleSkillsList(req.id, req.params);
14891
15632
  case "context.inspect":
14892
15633
  return handleContextInspect(req.id, req.params);
14893
15634
  case "theme.set":
15635
+ if (!themeSetEnabled)
15636
+ return rejectDisabled("theme setting is disabled");
14894
15637
  return handleThemeSet(req.id, req.params);
14895
15638
  default:
14896
15639
  return sendError(req.id, {
@@ -14925,6 +15668,7 @@ var createRuntimeHandlers = ({
14925
15668
  // src/runtime-state.ts
14926
15669
  var import_node_crypto9 = __toESM(require("crypto"), 1);
14927
15670
  var RuntimeState = class {
15671
+ effectiveEnvironment = resolveRuntimeEnvironment();
14928
15672
  runSeq = /* @__PURE__ */ new Map();
14929
15673
  uiRequestCounter = 0;
14930
15674
  pendingUiRequests = /* @__PURE__ */ new Map();
@@ -14956,6 +15700,9 @@ var RuntimeState = class {
14956
15700
  currentModelSource = null;
14957
15701
  sessionModelOverride = null;
14958
15702
  diagnosticsEnabled = false;
15703
+ setRuntimeEnvironment(options) {
15704
+ this.effectiveEnvironment = resolveRuntimeEnvironment(options);
15705
+ }
14959
15706
  nextRunId() {
14960
15707
  return import_node_crypto9.default.randomUUID();
14961
15708
  }
@@ -15055,33 +15802,42 @@ var envTruthy2 = (value) => {
15055
15802
  const normalized = value.trim().toLowerCase();
15056
15803
  return normalized === "1" || normalized === "true";
15057
15804
  };
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();
15805
+ var startRuntime = async (options = {}) => {
15806
+ const state = new RuntimeState();
15807
+ state.setRuntimeEnvironment(options);
15808
+ const environment = state.effectiveEnvironment;
15809
+ state.diagnosticsEnabled = envTruthy2(process.env.CODELIA_DIAGNOSTICS);
15810
+ const workingDir = environment.workspace.root;
15811
+ if (workingDir) {
15063
15812
  state.runtimeWorkingDir = workingDir;
15064
15813
  state.runtimeSandboxRoot = workingDir;
15814
+ }
15815
+ if (environment.context.projectInstructions === "from-workspace" && workingDir) {
15065
15816
  try {
15066
15817
  state.agentsResolver = await AgentsResolver.create(workingDir);
15067
15818
  } catch (error) {
15068
15819
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
15069
15820
  }
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
- });
15821
+ }
15822
+ const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage14.SessionStateStoreImpl({
15823
+ onError: (error, context) => {
15824
+ (0, import_logger.log)(
15825
+ `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
15826
+ );
15827
+ }
15828
+ }));
15829
+ if (environment.persistence.mode === "runtime") {
15077
15830
  try {
15078
15831
  await sessionStateStore.list();
15079
15832
  } catch (error) {
15080
- (0, import_logger.log)(`Error: session index database is not available: ${String(error)}`);
15081
- process.exit(1);
15082
- return;
15833
+ throw new Error(
15834
+ `session index database is not available: ${String(error)}`
15835
+ );
15083
15836
  }
15084
- const taskManager = new TaskManager();
15837
+ }
15838
+ const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage14.RunEventStoreFactoryImpl());
15839
+ const taskManager = isProcessEnabled(environment) ? environment.adapters.stores?.taskManager ?? new TaskManager() : void 0;
15840
+ if (taskManager) {
15085
15841
  const recoveredTasks = await taskManager.recoverOrphanedTasks();
15086
15842
  if (recoveredTasks.recovered > 0 || recoveredTasks.errors.length > 0) {
15087
15843
  (0, import_logger.log)(
@@ -15091,76 +15847,81 @@ var startRuntime = () => {
15091
15847
  (0, import_logger.log)(`tasks.recover error task_id=${error.task_id}: ${error.error}`);
15092
15848
  }
15093
15849
  }
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
- })();
15850
+ }
15851
+ let shutdownPromise = null;
15852
+ const shutdownTasks = async (reason) => {
15853
+ if (!taskManager) return;
15854
+ if (shutdownPromise) {
15113
15855
  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
- });
15856
+ return;
15121
15857
  }
15122
- process.once("beforeExit", () => {
15123
- void shutdownTasks("beforeExit");
15124
- });
15125
- process.stdin.once("end", () => {
15126
- void shutdownTasks("stdin.end");
15858
+ shutdownPromise = (async () => {
15859
+ const result = await taskManager.shutdown();
15860
+ if (result.cancelled > 0 || result.errors.length > 0) {
15861
+ (0, import_logger.log)(
15862
+ `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
15863
+ );
15864
+ for (const error of result.errors) {
15865
+ (0, import_logger.log)(`tasks.shutdown error task_id=${error.task_id}: ${error.error}`);
15866
+ }
15867
+ }
15868
+ })();
15869
+ await shutdownPromise;
15870
+ };
15871
+ for (const signal of ["SIGINT", "SIGTERM"]) {
15872
+ process.once(signal, () => {
15873
+ void shutdownTasks(signal).finally(() => {
15874
+ process.kill(process.pid, signal);
15875
+ });
15127
15876
  });
15128
- const mcpManager = new McpManager({ workingDir, log: import_logger.log });
15877
+ }
15878
+ process.once("beforeExit", () => {
15879
+ void shutdownTasks("beforeExit");
15880
+ });
15881
+ process.stdin.once("end", () => {
15882
+ void shutdownTasks("stdin.end");
15883
+ });
15884
+ const mcpManager = environment.tools.mcp === "from-config" && workingDir ? new McpManager({ workingDir, log: import_logger.log }) : void 0;
15885
+ if (mcpManager) {
15129
15886
  void mcpManager.start({
15130
15887
  onStatus: (message) => (0, import_logger.log)(`mcp: ${message}`),
15131
15888
  requestOAuthTokens: ({ server_id, oauth: oauth2, error }) => requestMcpOAuthTokensWithRunStatus(state, server_id, oauth2, error)
15132
15889
  });
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
- }
15890
+ }
15891
+ const getAgent = createAgentFactory(state, { mcpManager, taskManager });
15892
+ const { processMessage } = createRuntimeHandlers({
15893
+ state,
15894
+ getAgent,
15895
+ log: import_logger.log,
15896
+ mcpManager,
15897
+ sessionStateStore,
15898
+ runEventStoreFactory,
15899
+ taskManager
15900
+ });
15901
+ (0, import_logger.log)("runtime started");
15902
+ process.stdin.setEncoding("utf8");
15903
+ let buffer = "";
15904
+ process.stdin.on("data", (chunk) => {
15905
+ buffer += chunk;
15906
+ let index = buffer.indexOf("\n");
15907
+ while (index >= 0) {
15908
+ const line = buffer.slice(0, index).trim();
15909
+ buffer = buffer.slice(index + 1);
15910
+ if (line) {
15911
+ try {
15912
+ const msg = JSON.parse(line);
15913
+ processMessage(msg);
15914
+ } catch (error) {
15915
+ (0, import_logger.log)(`invalid json: ${String(error)}`);
15158
15916
  }
15159
- index = buffer.indexOf("\n");
15160
15917
  }
15161
- });
15162
- })();
15918
+ index = buffer.indexOf("\n");
15919
+ }
15920
+ });
15163
15921
  };
15164
15922
 
15165
15923
  // src/index.ts
15166
- startRuntime();
15924
+ void startRuntime().catch((error) => {
15925
+ console.error(`runtime startup failed: ${String(error)}`);
15926
+ process.exitCode = 1;
15927
+ });