@codelia/runtime 0.1.84 → 0.1.85

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
@@ -13,17 +13,17 @@ var __copyProps = (to, from, except, desc) => {
13
13
  }
14
14
  return to;
15
15
  };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
16
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
17
  // If the importer is in node compatibility mode or this is not an ESM
18
18
  // file that has been converted to a CommonJS file using a Babel-
19
19
  // compatible transform (i.e. "__esModule" has not been set), then set
20
20
  // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
22
22
  mod
23
23
  ));
24
24
 
25
25
  // src/runtime.ts
26
- var import_storage21 = require("@codelia/storage");
26
+ var import_storage22 = require("@codelia/storage");
27
27
 
28
28
  // src/agent-factory.ts
29
29
  var import_core32 = require("@codelia/core");
@@ -828,12 +828,12 @@ var resolveImageGenerationConfig = async (workingDir) => {
828
828
  };
829
829
  };
830
830
  var updateImageGeneration = async (workingDir, image) => {
831
- const target = await resolveWriteTarget(
831
+ const target2 = await resolveWriteTarget(
832
832
  workingDir ?? process.cwd(),
833
833
  "image_generation"
834
834
  );
835
- await (0, import_config_loader.updateImageGenerationConfig)(target.path, image);
836
- return target;
835
+ await (0, import_config_loader.updateImageGenerationConfig)(target2.path, image);
836
+ return target2;
837
837
  };
838
838
  var resolveModelConfig = async (workingDir) => {
839
839
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
@@ -1014,14 +1014,14 @@ var resolveMcpServers = async (workingDir) => {
1014
1014
  ...Object.keys(projectServers)
1015
1015
  ]);
1016
1016
  const resolved = [];
1017
- for (const id of allIds) {
1018
- const project = projectServers[id];
1019
- const global = globalServers[id];
1017
+ for (const id2 of allIds) {
1018
+ const project = projectServers[id2];
1019
+ const global = globalServers[id2];
1020
1020
  const server = project ?? global;
1021
1021
  if (!server) continue;
1022
1022
  resolved.push({
1023
1023
  ...server,
1024
- id,
1024
+ id: id2,
1025
1025
  source: project ? "project" : "global",
1026
1026
  enabled: server.enabled !== false,
1027
1027
  request_timeout_ms: normalizeMcpTimeoutMs(server.request_timeout_ms)
@@ -1063,14 +1063,14 @@ var resolveWriteTarget = async (workingDir, group) => {
1063
1063
  return defaultScope === "project" ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
1064
1064
  };
1065
1065
  var updateModel = async (workingDir, model) => {
1066
- const target = await resolveWriteTarget(workingDir, "model");
1067
- await (0, import_config_loader.updateModelConfig)(target.path, model);
1068
- return target;
1066
+ const target2 = await resolveWriteTarget(workingDir, "model");
1067
+ await (0, import_config_loader.updateModelConfig)(target2.path, model);
1068
+ return target2;
1069
1069
  };
1070
1070
  var updateTuiTheme = async (workingDir, theme) => {
1071
- const target = await resolveWriteTarget(workingDir, "tui");
1072
- await (0, import_config_loader.updateTuiConfig)(target.path, { theme });
1073
- return target;
1071
+ const target2 = await resolveWriteTarget(workingDir, "tui");
1072
+ await (0, import_config_loader.updateTuiConfig)(target2.path, { theme });
1073
+ return target2;
1074
1074
  };
1075
1075
  var resolveReasoningEffort = (value) => {
1076
1076
  return resolveModelLevelOption(value, "model.reasoning", {
@@ -1756,10 +1756,10 @@ var import_protocol = require("@codelia/protocol");
1756
1756
  // src/rpc/transport.ts
1757
1757
  var import_node_async_hooks = require("async_hooks");
1758
1758
  var responseContext = new import_node_async_hooks.AsyncLocalStorage();
1759
- var withRpcResponseContext = (id, callback) => responseContext.run({ id, sent: false }, callback);
1760
- var hasRpcResponse = (id) => {
1759
+ var withRpcResponseContext = (id2, callback) => responseContext.run({ id: id2, sent: false }, callback);
1760
+ var hasRpcResponse = (id2) => {
1761
1761
  const current = responseContext.getStore();
1762
- return current?.id === id && current.sent;
1762
+ return current?.id === id2 && current.sent;
1763
1763
  };
1764
1764
  var describeRpcMessage = (msg) => {
1765
1765
  if ("method" in msg && typeof msg.method === "string") {
@@ -1835,12 +1835,12 @@ var sendAsync = async (msg) => new Promise((resolve) => {
1835
1835
  (0, import_logger.debugLog)(`transport.backpressure label=${label} bytes=${payload.length}`);
1836
1836
  }
1837
1837
  });
1838
- var sendError = (id, error) => {
1839
- const response = { jsonrpc: "2.0", id, error };
1838
+ var sendError = (id2, error) => {
1839
+ const response = { jsonrpc: "2.0", id: id2, error };
1840
1840
  sendResponse(response);
1841
1841
  };
1842
- var sendResult = (id, result) => {
1843
- const response = { jsonrpc: "2.0", id, result };
1842
+ var sendResult = (id2, result) => {
1843
+ const response = { jsonrpc: "2.0", id: id2, result };
1844
1844
  sendResponse(response);
1845
1845
  };
1846
1846
  var sendResponse = (response) => {
@@ -1935,17 +1935,17 @@ var sendRunMetrics = (state, params) => {
1935
1935
  // src/rpc/ui-requests.ts
1936
1936
  var requestUi = async (state, method, params, signal) => {
1937
1937
  if (signal?.aborted) return null;
1938
- const id = state.nextUiRequestId();
1938
+ const id2 = state.nextUiRequestId();
1939
1939
  const request = {
1940
1940
  jsonrpc: "2.0",
1941
- id,
1941
+ id: id2,
1942
1942
  method,
1943
1943
  params
1944
1944
  };
1945
- const response = state.waitForUiResponse(id);
1945
+ const response = state.waitForUiResponse(id2);
1946
1946
  const abort = () => state.resolveUiResponse({
1947
1947
  jsonrpc: "2.0",
1948
- id,
1948
+ id: id2,
1949
1949
  error: {
1950
1950
  code: import_protocol.RPC_ERROR_CODE.RUNTIME_INTERNAL,
1951
1951
  message: "UI request cancelled"
@@ -3074,9 +3074,9 @@ var excerptByBytes = (value, maxBytes) => {
3074
3074
  if (maxBytes <= markerBytes + 2) {
3075
3075
  return truncateUtf8Prefix(value, maxBytes);
3076
3076
  }
3077
- const budget = maxBytes - markerBytes;
3078
- const headBytes = Math.floor(budget / 2);
3079
- const tailBytes = budget - headBytes;
3077
+ const budget2 = maxBytes - markerBytes;
3078
+ const headBytes = Math.floor(budget2 / 2);
3079
+ const tailBytes = budget2 - headBytes;
3080
3080
  return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
3081
3081
  };
3082
3082
  var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
@@ -3626,14 +3626,14 @@ async function exportImageBytes(workspaceRoot, outputPath, bytes, mediaType = "i
3626
3626
  throw new ImageGenerationError(
3627
3627
  "Image export path must match the original PNG or JPEG format in this workspace."
3628
3628
  );
3629
- const target = import_node_path5.default.resolve(workspaceRoot, outputPath);
3629
+ const target2 = import_node_path5.default.resolve(workspaceRoot, outputPath);
3630
3630
  try {
3631
3631
  const root = await (0, import_promises.realpath)(workspaceRoot);
3632
- const parent = await (0, import_promises.realpath)(import_node_path5.default.dirname(target));
3632
+ const parent = await (0, import_promises.realpath)(import_node_path5.default.dirname(target2));
3633
3633
  const relative = import_node_path5.default.relative(root, parent);
3634
3634
  if (relative === ".." || relative.startsWith(`..${import_node_path5.default.sep}`) || import_node_path5.default.isAbsolute(relative))
3635
3635
  throw new Error("outside workspace");
3636
- const destination = import_node_path5.default.join(parent, import_node_path5.default.basename(target));
3636
+ const destination = import_node_path5.default.join(parent, import_node_path5.default.basename(target2));
3637
3637
  const file = await (0, import_promises.open)(destination, "wx", 384);
3638
3638
  try {
3639
3639
  await file.writeFile(bytes);
@@ -3994,15 +3994,15 @@ async function downloadImageSource(value, callerSignal, transport = requestImage
3994
3994
  async function readImageFile(sandbox, filePath, signal) {
3995
3995
  try {
3996
3996
  signal?.throwIfAborted();
3997
- const target = await (0, import_promises3.realpath)(sandbox.resolvePath(filePath));
3997
+ const target2 = await (0, import_promises3.realpath)(sandbox.resolvePath(filePath));
3998
3998
  if (sandbox.approvalMode !== "full-access") {
3999
3999
  const root = await (0, import_promises3.realpath)(sandbox.rootDir);
4000
- const relative = import_node_path7.default.relative(root, target);
4000
+ const relative = import_node_path7.default.relative(root, target2);
4001
4001
  if (relative === ".." || relative.startsWith(`..${import_node_path7.default.sep}`) || import_node_path7.default.isAbsolute(relative))
4002
4002
  throw new Error("outside sandbox");
4003
4003
  }
4004
4004
  const handle = await (0, import_promises3.open)(
4005
- target,
4005
+ target2,
4006
4006
  import_node_fs4.constants.O_RDONLY | (import_node_fs4.constants.O_NOFOLLOW ?? 0) | (import_node_fs4.constants.O_NONBLOCK ?? 0)
4007
4007
  );
4008
4008
  try {
@@ -5090,13 +5090,6 @@ var resolveFastMode = (params) => {
5090
5090
  return { enabled: false };
5091
5091
  };
5092
5092
  var effectiveFastMode = (params) => resolveFastMode(params).enabled ? params.requested ?? false : false;
5093
- var assertUltrafastAuth = (fast, method) => {
5094
- if (fast === "ultrafast" && method !== "api_key") {
5095
- throw new Error(
5096
- "Ultrafast requires OpenAI API-key authentication. Codex OAuth support is unverified; credentials will not be switched automatically."
5097
- );
5098
- }
5099
- };
5100
5093
 
5101
5094
  // src/model-reasoning.ts
5102
5095
  var import_core6 = require("@codelia/core");
@@ -5734,14 +5727,12 @@ var createRuntimeModel = async ({
5734
5727
  log: log2,
5735
5728
  getOpenAiAccessToken
5736
5729
  }) => {
5737
- if (config.fast === "ultrafast") {
5738
- resolveFastMode({
5739
- provider,
5740
- model: config.name ?? import_core8.OPENAI_DEFAULT_MODEL,
5741
- requested: config.fast
5742
- });
5743
- assertUltrafastAuth(config.fast, auth.method);
5744
- }
5730
+ const requestedFastMode = config.fast;
5731
+ const ultrafastMode = requestedFastMode === "ultrafast" ? resolveFastMode({
5732
+ provider,
5733
+ model: config.name ?? import_core8.OPENAI_DEFAULT_MODEL,
5734
+ requested: requestedFastMode
5735
+ }) : void 0;
5745
5736
  const endpoint = getResponsesProvider(config, provider);
5746
5737
  if (endpoint) {
5747
5738
  const modelName = config.name ?? Object.keys(endpoint.models)[0];
@@ -5764,7 +5755,6 @@ var createRuntimeModel = async ({
5764
5755
  };
5765
5756
  }
5766
5757
  const requestedReasoning = resolveReasoningEffort(config.reasoning) ?? "medium";
5767
- const requestedFastMode = config.fast;
5768
5758
  switch (provider) {
5769
5759
  case "deepseek": {
5770
5760
  const llm = new import_core8.ChatDeepSeek({
@@ -5784,8 +5774,6 @@ var createRuntimeModel = async ({
5784
5774
  if (!model)
5785
5775
  throw new Error(`Unsupported Google model: ${requestedModelName}`);
5786
5776
  const modelName = model.id;
5787
- if (config.fast === "ultrafast")
5788
- throw new Error("Google models do not support Fast mode");
5789
5777
  const effort = resolveReasoningEffort(config.reasoning);
5790
5778
  const reasoning = effort ? resolveGoogleReasoning({ model: modelName, requested: effort }) : void 0;
5791
5779
  if (reasoning?.fallbackApplied)
@@ -5810,7 +5798,7 @@ var createRuntimeModel = async ({
5810
5798
  });
5811
5799
  const textVerbosity = resolveTextVerbosity(config.verbosity);
5812
5800
  const websocketMode = config.experimental?.openai?.websocket_mode;
5813
- const fastMode = resolveFastMode({
5801
+ const fastMode = ultrafastMode ?? resolveFastMode({
5814
5802
  provider: "openai",
5815
5803
  model: modelName,
5816
5804
  requested: requestedFastMode
@@ -6371,9 +6359,9 @@ var excerptByBytes2 = (value, maxBytes) => {
6371
6359
  truncated: true
6372
6360
  };
6373
6361
  }
6374
- const budget = maxBytes - markerBytes;
6375
- const headBytes = Math.floor(budget / 2);
6376
- const tailBytes = budget - headBytes;
6362
+ const budget2 = maxBytes - markerBytes;
6363
+ const headBytes = Math.floor(budget2 / 2);
6364
+ const tailBytes = budget2 - headBytes;
6377
6365
  return {
6378
6366
  text: `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`,
6379
6367
  truncated: true
@@ -7174,9 +7162,9 @@ var resolveCdTarget = (segment, currentWorkingDir, rootDir) => {
7174
7162
  const tokens = segment.split(" ").filter(Boolean);
7175
7163
  if (tokens[0] !== "cd") return null;
7176
7164
  if (tokens.length !== 2) return null;
7177
- const target = tokens[1];
7178
- if (target === "-" || CD_UNSAFE_TARGET_PATTERN.test(target)) return null;
7179
- const resolved = import_node_path10.default.resolve(currentWorkingDir, target);
7165
+ const target2 = tokens[1];
7166
+ if (target2 === "-" || CD_UNSAFE_TARGET_PATTERN.test(target2)) return null;
7167
+ const resolved = import_node_path10.default.resolve(currentWorkingDir, target2);
7180
7168
  const relative = import_node_path10.default.relative(rootDir, resolved);
7181
7169
  if (relative === "" || !relative.startsWith("..") && !import_node_path10.default.isAbsolute(relative)) {
7182
7170
  return resolved;
@@ -7347,20 +7335,20 @@ var PermissionService = class {
7347
7335
  const parsed = parseRawArgsForPrompt(rawArgs);
7348
7336
  const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
7349
7337
  const content = parsed && typeof parsed.content === "string" ? parsed.content : "";
7350
- const target = filePath || "(unknown path)";
7338
+ const target2 = filePath || "(unknown path)";
7351
7339
  return {
7352
7340
  title: "Run tool?",
7353
- message: `write ${target} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
7341
+ message: `write ${target2} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
7354
7342
  };
7355
7343
  }
7356
7344
  if (toolName === "edit") {
7357
7345
  const parsed = parseRawArgsForPrompt(rawArgs);
7358
7346
  const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
7359
- const target = filePath || "(unknown path)";
7347
+ const target2 = filePath || "(unknown path)";
7360
7348
  const mode = parsed && typeof parsed.match_mode === "string" ? parsed.match_mode : "auto";
7361
7349
  return {
7362
7350
  title: "Run tool?",
7363
- message: `edit ${target} (match=${mode})${rememberPreview}`
7351
+ message: `edit ${target2} (match=${mode})${rememberPreview}`
7364
7352
  };
7365
7353
  }
7366
7354
  if (toolName === "apply_patch") {
@@ -8990,7 +8978,7 @@ var subagentModelSchema = import_zod8.z.object({
8990
8978
  reasoning: import_zod8.z.string().optional(),
8991
8979
  verbosity: import_zod8.z.string().optional(),
8992
8980
  fast: import_zod8.z.union([import_zod8.z.boolean(), import_zod8.z.literal("ultrafast")]).optional().describe(
8993
- 'Optional speed selection. true uses supported fast mode; "ultrafast" requires OpenAI API-key GPT-6 Astra/6.1 Sol and higher API pricing. No auth or tier fallback.'
8981
+ 'Optional speed selection. true uses supported fast mode. "ultrafast" requires OpenAI GPT-6.2 Astra/Sol, GPT-6 Astra, or GPT-6.1 Sol and an eligible account. Uses the existing OpenAI auth route.'
8994
8982
  ),
8995
8983
  experimental: import_zod8.z.object({
8996
8984
  openai: import_zod8.z.object({
@@ -9077,10 +9065,10 @@ var VolatileRunEventStoreFactory = class {
9077
9065
  var VolatileToolOutputCacheStore = class {
9078
9066
  records = /* @__PURE__ */ new Map();
9079
9067
  async save(record) {
9080
- const id = record.tool_call_id;
9081
- this.records.set(id, structuredClone(record));
9068
+ const id2 = record.tool_call_id;
9069
+ this.records.set(id2, structuredClone(record));
9082
9070
  return {
9083
- id,
9071
+ id: id2,
9084
9072
  byte_size: Buffer.byteLength(record.content, "utf8"),
9085
9073
  line_count: record.content.split(/\r?\n/).length
9086
9074
  };
@@ -11205,17 +11193,17 @@ var LaneManager = class {
11205
11193
  "zellij backend is not supported yet in lane MVP. Use tmux."
11206
11194
  );
11207
11195
  }
11208
- async startTmuxLane(target, worktreePath, seedContext) {
11196
+ async startTmuxLane(target2, worktreePath, seedContext) {
11209
11197
  const launchCommand = this.buildLaunchCommand(seedContext);
11210
11198
  await this.cmd("tmux", [
11211
11199
  "new-session",
11212
11200
  "-d",
11213
11201
  "-s",
11214
- target,
11202
+ target2,
11215
11203
  "-c",
11216
11204
  worktreePath
11217
11205
  ]);
11218
- const paneTarget = `${target}:0.0`;
11206
+ const paneTarget = `${target2}:0.0`;
11219
11207
  await this.cmd("tmux", [
11220
11208
  "send-keys",
11221
11209
  "-t",
@@ -11236,9 +11224,9 @@ var LaneManager = class {
11236
11224
  }
11237
11225
  return `${this.launchCommand} ${INITIAL_MESSAGE_FLAG} ${this.shellQuote(seed)}`;
11238
11226
  }
11239
- async isTmuxAlive(target) {
11227
+ async isTmuxAlive(target2) {
11240
11228
  try {
11241
- await this.cmd("tmux", ["has-session", "-t", target], {
11229
+ await this.cmd("tmux", ["has-session", "-t", target2], {
11242
11230
  timeoutMs: 5e3
11243
11231
  });
11244
11232
  return true;
@@ -11250,9 +11238,9 @@ var LaneManager = class {
11250
11238
  );
11251
11239
  }
11252
11240
  }
11253
- async stopTmuxLane(target) {
11241
+ async stopTmuxLane(target2) {
11254
11242
  try {
11255
- await this.cmd("tmux", ["kill-session", "-t", target], {
11243
+ await this.cmd("tmux", ["kill-session", "-t", target2], {
11256
11244
  timeoutMs: 1e4
11257
11245
  });
11258
11246
  } catch (error) {
@@ -11753,8 +11741,8 @@ var createReadTool = (sandboxKey) => (0, import_core17.defineTool)({
11753
11741
  if (bytes + size > MAX_BYTES) {
11754
11742
  if (outputLines.length === 0) {
11755
11743
  const prefix = `${String(index + 1).padStart(5, " ")} `;
11756
- const budget = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
11757
- const clippedByBytes = clipLineToByteBudget(line, budget);
11744
+ const budget2 = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
11745
+ const clippedByBytes = clipLineToByteBudget(line, budget2);
11758
11746
  if (clippedByBytes.length > 0) {
11759
11747
  outputLines.push(clippedByBytes);
11760
11748
  bytes = Buffer.byteLength(`${prefix}${clippedByBytes}`, "utf8");
@@ -12894,7 +12882,7 @@ var withPatchApplied = (currentTodos, updates) => {
12894
12882
  id: normalizeTodoId(update.id)
12895
12883
  }));
12896
12884
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
12897
- const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
12885
+ const missingIds = normalizedUpdates.map((update) => update.id).filter((id2) => !currentIds.has(id2));
12898
12886
  if (missingIds.length > 0) {
12899
12887
  const knownIds = currentTodos.map((todo) => todo.id);
12900
12888
  return {
@@ -13777,9 +13765,9 @@ function createConversationTools(store, currentSession) {
13777
13765
  const searchMessages = store.searchMessages.bind(store);
13778
13766
  const readMessage = store.readMessage.bind(store);
13779
13767
  const session = () => {
13780
- const id = currentSession();
13781
- if (!id) throw new Error("No active conversation");
13782
- return id;
13768
+ const id2 = currentSession();
13769
+ if (!id2) throw new Error("No active conversation");
13770
+ return id2;
13783
13771
  };
13784
13772
  return [
13785
13773
  (0, import_core29.defineTool)({
@@ -13875,9 +13863,9 @@ var waitForTaskOrMessage = async (coordinator, owner, taskId, signal) => {
13875
13863
  // src/tools/task.ts
13876
13864
  var createSubagentTaskTools = (coordinator, ownerSession, spawn7) => {
13877
13865
  const session = () => {
13878
- const id = ownerSession();
13879
- if (!id) throw new Error("No parent session");
13880
- return id;
13866
+ const id2 = ownerSession();
13867
+ if (!id2) throw new Error("No parent session");
13868
+ return id2;
13881
13869
  };
13882
13870
  const idSchema = import_zod34.z.object({
13883
13871
  task_id: import_zod34.z.string().min(1).describe(
@@ -14633,9 +14621,9 @@ var AttachmentTransferService = class {
14633
14621
  "Attachment upload staging is full; retry or cancel an unused upload"
14634
14622
  );
14635
14623
  }
14636
- const id = (0, import_storage14.createAttachmentId)();
14624
+ const id2 = (0, import_storage14.createAttachmentId)();
14637
14625
  const upload = {
14638
- id,
14626
+ id: id2,
14639
14627
  key: params.upload_key,
14640
14628
  sessionId,
14641
14629
  name: name2,
@@ -14646,10 +14634,10 @@ var AttachmentTransferService = class {
14646
14634
  expires: this.now() + this.limits.lease_ms,
14647
14635
  pins: 0
14648
14636
  };
14649
- this.uploads.set(id, upload);
14637
+ this.uploads.set(id2, upload);
14650
14638
  this.stagedBytes += upload.size;
14651
14639
  processStagedBytes += upload.size;
14652
- return { upload_id: id, offset: 0 };
14640
+ return { upload_id: id2, offset: 0 };
14653
14641
  });
14654
14642
  }
14655
14643
  async chunk(params, sessionId) {
@@ -14731,13 +14719,13 @@ var AttachmentTransferService = class {
14731
14719
  async resolveForAdmission(ids, sessionId, options) {
14732
14720
  return this.serial(async () => {
14733
14721
  const result = [];
14734
- for (const id of ids) {
14722
+ for (const id2 of ids) {
14735
14723
  const upload = this.eligibleUpload(
14736
- id,
14724
+ id2,
14737
14725
  sessionId,
14738
14726
  options?.allowDraft ?? false
14739
14727
  );
14740
- const record = upload?.record ?? await this.lookup(id, sessionId);
14728
+ const record = upload?.record ?? await this.lookup(id2, sessionId);
14741
14729
  if (!record)
14742
14730
  throw new AttachmentUploadError(
14743
14731
  "Attachment unavailable in this session; re-upload to retry"
@@ -14752,16 +14740,16 @@ var AttachmentTransferService = class {
14752
14740
  return this.serial(async () => {
14753
14741
  const pending = [];
14754
14742
  const entries = [];
14755
- for (const id of new Set(ids)) {
14743
+ for (const id2 of new Set(ids)) {
14756
14744
  const upload = this.eligibleUpload(
14757
- id,
14745
+ id2,
14758
14746
  sessionId,
14759
14747
  options?.allowDraft ?? false
14760
14748
  );
14761
14749
  if (upload?.bytes && upload.record) {
14762
14750
  pending.push(upload);
14763
14751
  entries.push({ record: upload.record, bytes: upload.bytes });
14764
- } else if (!await this.lookup(id, sessionId)) {
14752
+ } else if (!await this.lookup(id2, sessionId)) {
14765
14753
  throw new AttachmentUploadError(
14766
14754
  "Attachment unavailable in this session; re-upload to retry"
14767
14755
  );
@@ -14788,10 +14776,10 @@ var AttachmentTransferService = class {
14788
14776
  async pin(ids, sessionId) {
14789
14777
  return this.serial(async () => {
14790
14778
  const pinned = [];
14791
- for (const id of new Set(ids)) {
14792
- const upload = this.eligibleUpload(id, sessionId, false);
14779
+ for (const id2 of new Set(ids)) {
14780
+ const upload = this.eligibleUpload(id2, sessionId, false);
14793
14781
  if (upload?.bytes && upload.record) pinned.push(upload);
14794
- else if (!await this.lookup(id, sessionId))
14782
+ else if (!await this.lookup(id2, sessionId))
14795
14783
  throw new AttachmentUploadError(
14796
14784
  "Attachment unavailable in this session; re-upload to retry"
14797
14785
  );
@@ -14805,12 +14793,12 @@ var AttachmentTransferService = class {
14805
14793
  };
14806
14794
  });
14807
14795
  }
14808
- async read(id, sessionId, offset, length) {
14796
+ async read(id2, sessionId, offset, length) {
14809
14797
  try {
14810
- if (!(0, import_storage14.isAttachmentId)(id) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
14798
+ if (!(0, import_storage14.isAttachmentId)(id2) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
14811
14799
  throw new Error("Invalid attachment byte range");
14812
14800
  }
14813
- const bytes = await this.store.read(id, sessionId, offset, length);
14801
+ const bytes = await this.store.read(id2, sessionId, offset, length);
14814
14802
  if (bytes.length > length)
14815
14803
  throw new Error("Attachment adapter exceeded the requested byte range");
14816
14804
  return bytes;
@@ -14820,9 +14808,9 @@ var AttachmentTransferService = class {
14820
14808
  );
14821
14809
  }
14822
14810
  }
14823
- async lookup(id, sessionId) {
14811
+ async lookup(id2, sessionId) {
14824
14812
  try {
14825
- return (0, import_storage14.isAttachmentId)(id) ? await this.store.lookup(id, sessionId) : null;
14813
+ return (0, import_storage14.isAttachmentId)(id2) ? await this.store.lookup(id2, sessionId) : null;
14826
14814
  } catch {
14827
14815
  throw new AttachmentUploadError(
14828
14816
  "Attachment original is missing, corrupt or unavailable in this session"
@@ -14867,8 +14855,8 @@ var AttachmentTransferService = class {
14867
14855
  );
14868
14856
  }
14869
14857
  }
14870
- getUpload(id, sessionId) {
14871
- const upload = this.uploads.get(id);
14858
+ getUpload(id2, sessionId) {
14859
+ const upload = this.uploads.get(id2);
14872
14860
  if (!upload || upload.sessionId !== sessionId) {
14873
14861
  throw new AttachmentUploadError(
14874
14862
  "Attachment upload expired or is unavailable in this session"
@@ -14883,8 +14871,8 @@ var AttachmentTransferService = class {
14883
14871
  );
14884
14872
  }
14885
14873
  }
14886
- eligibleUpload(id, sessionId, allowDraft) {
14887
- const upload = this.uploads.get(id);
14874
+ eligibleUpload(id2, sessionId, allowDraft) {
14875
+ const upload = this.uploads.get(id2);
14888
14876
  if (!upload?.bytes || !upload.record) return void 0;
14889
14877
  const owner = upload.sessionId;
14890
14878
  return owner === sessionId || owner === null && allowDraft ? upload : void 0;
@@ -15004,8 +14992,8 @@ var matchesRequestId = (value, expectedRequestId) => {
15004
14992
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
15005
14993
  }
15006
14994
  if (!isRecord5(value)) return false;
15007
- const id = value.id;
15008
- return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
14995
+ const id2 = value.id;
14996
+ return typeof id2 === "string" || typeof id2 === "number" ? String(id2) === expectedRequestId : false;
15009
14997
  };
15010
14998
  var readSseBody = async (response, expectedRequestId) => {
15011
14999
  if (!expectedRequestId) {
@@ -15859,8 +15847,8 @@ var createMcpToolAdapter = (params) => {
15859
15847
  var OAUTH_TOKEN_EXPIRY_SKEW_MS = 6e4;
15860
15848
  var nowIso4 = () => (/* @__PURE__ */ new Date()).toISOString();
15861
15849
  var describeError2 = (error) => error instanceof Error ? error.message : String(error);
15862
- var toListServer = (id, runtime) => ({
15863
- id,
15850
+ var toListServer = (id2, runtime) => ({
15851
+ id: id2,
15864
15852
  transport: runtime.config.transport,
15865
15853
  source: runtime.config.source,
15866
15854
  enabled: runtime.config.enabled,
@@ -15908,7 +15896,7 @@ var McpManager = class {
15908
15896
  );
15909
15897
  }
15910
15898
  list(scope = "loaded") {
15911
- const servers = Array.from(this.servers.entries()).map(([id, runtime]) => toListServer(id, runtime)).sort((left, right) => left.id.localeCompare(right.id));
15899
+ const servers = Array.from(this.servers.entries()).map(([id2, runtime]) => toListServer(id2, runtime)).sort((left, right) => left.id.localeCompare(right.id));
15912
15900
  if (scope === "configured") {
15913
15901
  return { servers };
15914
15902
  }
@@ -16281,8 +16269,8 @@ var McpManager = class {
16281
16269
  };
16282
16270
 
16283
16271
  // src/rpc/handlers.ts
16284
- var import_protocol19 = require("@codelia/protocol");
16285
- var import_storage20 = require("@codelia/storage");
16272
+ var import_protocol20 = require("@codelia/protocol");
16273
+ var import_storage21 = require("@codelia/storage");
16286
16274
 
16287
16275
  // src/constants.ts
16288
16276
  var SERVER_NAME = "codelia-runtime";
@@ -16291,7 +16279,7 @@ var PROTOCOL_VERSION = "0";
16291
16279
 
16292
16280
  // src/rpc/attachment.ts
16293
16281
  var import_protocol3 = require("@codelia/protocol");
16294
- async function handleAttachmentUpload(state, id, method, params) {
16282
+ async function handleAttachmentUpload(state, id2, method, params) {
16295
16283
  const attachments = state.attachments;
16296
16284
  try {
16297
16285
  if (!attachments)
@@ -16303,7 +16291,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16303
16291
  switch (method) {
16304
16292
  case "attachment.upload.begin":
16305
16293
  return sendResult(
16306
- id,
16294
+ id2,
16307
16295
  await attachments.begin(
16308
16296
  params,
16309
16297
  state.sessionId
@@ -16311,7 +16299,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16311
16299
  );
16312
16300
  case "attachment.upload.chunk":
16313
16301
  return sendResult(
16314
- id,
16302
+ id2,
16315
16303
  await attachments.chunk(
16316
16304
  params,
16317
16305
  state.sessionId
@@ -16319,7 +16307,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16319
16307
  );
16320
16308
  case "attachment.upload.finish":
16321
16309
  return sendResult(
16322
- id,
16310
+ id2,
16323
16311
  await attachments.finish(
16324
16312
  params.upload_id,
16325
16313
  state.sessionId
@@ -16330,13 +16318,13 @@ async function handleAttachmentUpload(state, id, method, params) {
16330
16318
  params.upload_id,
16331
16319
  state.sessionId
16332
16320
  );
16333
- return sendResult(id, {
16321
+ return sendResult(id2, {
16334
16322
  ok: true
16335
16323
  });
16336
16324
  }
16337
16325
  } catch (error) {
16338
16326
  if (!(error instanceof AttachmentUploadError)) throw error;
16339
- sendError(id, {
16327
+ sendError(id2, {
16340
16328
  code: import_protocol3.RPC_ERROR_CODE.INVALID_PARAMS,
16341
16329
  message: error.message
16342
16330
  });
@@ -16345,9 +16333,9 @@ async function handleAttachmentUpload(state, id, method, params) {
16345
16333
 
16346
16334
  // src/rpc/auth.ts
16347
16335
  var import_protocol4 = require("@codelia/protocol");
16348
- var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16336
+ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id2, params) => {
16349
16337
  if (state.activeRunId) {
16350
- sendError(id, {
16338
+ sendError(id2, {
16351
16339
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_BUSY,
16352
16340
  message: "runtime busy"
16353
16341
  });
@@ -16355,14 +16343,14 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16355
16343
  }
16356
16344
  const provider = params?.provider;
16357
16345
  if (params?.confirmed !== void 0 && typeof params.confirmed !== "boolean") {
16358
- sendError(id, {
16346
+ sendError(id2, {
16359
16347
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16360
16348
  message: "confirmed must be a boolean"
16361
16349
  });
16362
16350
  return;
16363
16351
  }
16364
16352
  if (provider !== void 0 && (typeof provider !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(provider))) {
16365
- sendError(id, {
16353
+ sendError(id2, {
16366
16354
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16367
16355
  message: "invalid logout provider name"
16368
16356
  });
@@ -16380,7 +16368,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16380
16368
  if (hostAuth) {
16381
16369
  const credentials = state.effectiveEnvironment.adapters.credentialProvider;
16382
16370
  if (provider ? !credentials?.clearProviderAuth : !credentials?.clearAuth) {
16383
- sendError(id, {
16371
+ sendError(id2, {
16384
16372
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16385
16373
  message: provider ? "host auth provider does not support scoped logout" : "host auth provider does not support logout"
16386
16374
  });
@@ -16393,7 +16381,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16393
16381
  if (provider) {
16394
16382
  const auth = await store.load();
16395
16383
  if (!Object.hasOwn(auth.providers, provider) && !configuredProviders(config?.providers).includes(provider)) {
16396
- sendError(id, {
16384
+ sendError(id2, {
16397
16385
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16398
16386
  message: `unknown logout provider: ${provider}`
16399
16387
  });
@@ -16402,7 +16390,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16402
16390
  }
16403
16391
  const preconfirmed = params?.confirmed === true;
16404
16392
  if (!preconfirmed && !state.uiCapabilities?.supports_confirm) {
16405
- sendError(id, {
16393
+ sendError(id2, {
16406
16394
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16407
16395
  message: "UI confirmation is required for logout"
16408
16396
  });
@@ -16418,7 +16406,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16418
16406
  allow_reason: false
16419
16407
  });
16420
16408
  if (!confirm?.ok) {
16421
- sendResult(id, {
16409
+ sendResult(id2, {
16422
16410
  ok: false,
16423
16411
  auth_cleared: false,
16424
16412
  session_cleared: false,
@@ -16443,7 +16431,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16443
16431
  state.sessionAppend = null;
16444
16432
  state.sessionModelOverride = null;
16445
16433
  }
16446
- sendResult(id, {
16434
+ sendResult(id2, {
16447
16435
  ok: true,
16448
16436
  auth_cleared: true,
16449
16437
  session_cleared: clearSession,
@@ -16453,7 +16441,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16453
16441
  `auth.logout provider=${provider ?? "all"} session_cleared=${clearSession}`
16454
16442
  );
16455
16443
  } catch {
16456
- sendError(id, {
16444
+ sendError(id2, {
16457
16445
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16458
16446
  message: "auth logout failed"
16459
16447
  });
@@ -16487,9 +16475,9 @@ var saveProviderAuth = async (provider, auth) => {
16487
16475
  var createAuthManagementHandlers = ({ state, log: log2 }) => {
16488
16476
  let pending = null;
16489
16477
  let loginSeq = 0;
16490
- const rejectUnsupported = (id) => {
16478
+ const rejectUnsupported = (id2) => {
16491
16479
  if (supportsAuthManagement(state)) return false;
16492
- sendError(id, {
16480
+ sendError(id2, {
16493
16481
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16494
16482
  message: "auth is host-owned"
16495
16483
  });
@@ -16548,11 +16536,11 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16548
16536
  );
16549
16537
  return { config, providers: uniqueProviders(config.providers) };
16550
16538
  };
16551
- const handleStatus = async (id, params) => {
16552
- if (rejectUnsupported(id)) return;
16539
+ const handleStatus = async (id2, params) => {
16540
+ if (rejectUnsupported(id2)) return;
16553
16541
  const requested = params?.provider;
16554
16542
  if (requested !== void 0 && (typeof requested !== "string" || !PROVIDER_NAME_PATTERN.test(requested))) {
16555
- sendError(id, {
16543
+ sendError(id2, {
16556
16544
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16557
16545
  message: "invalid provider name"
16558
16546
  });
@@ -16561,7 +16549,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16561
16549
  try {
16562
16550
  const { config, providers } = await resolveProviders();
16563
16551
  if (requested !== void 0 && !providers.includes(requested)) {
16564
- sendError(id, {
16552
+ sendError(id2, {
16565
16553
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16566
16554
  message: `unknown provider: ${requested}`
16567
16555
  });
@@ -16597,18 +16585,18 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16597
16585
  }
16598
16586
  } : {}
16599
16587
  };
16600
- sendResult(id, result);
16588
+ sendResult(id2, result);
16601
16589
  } catch {
16602
- sendError(id, {
16590
+ sendError(id2, {
16603
16591
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16604
16592
  message: "auth status failed"
16605
16593
  });
16606
16594
  }
16607
16595
  };
16608
- const handleLogin = async (id, params) => {
16609
- if (rejectUnsupported(id)) return;
16596
+ const handleLogin = async (id2, params) => {
16597
+ if (rejectUnsupported(id2)) return;
16610
16598
  if (state.activeRunId) {
16611
- sendError(id, {
16599
+ sendError(id2, {
16612
16600
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16613
16601
  message: "runtime busy"
16614
16602
  });
@@ -16617,7 +16605,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16617
16605
  const provider = params?.provider;
16618
16606
  const method = params?.method;
16619
16607
  if (typeof provider !== "string" || !PROVIDER_NAME_PATTERN.test(provider)) {
16620
- sendError(id, {
16608
+ sendError(id2, {
16621
16609
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16622
16610
  message: "invalid provider name"
16623
16611
  });
@@ -16630,21 +16618,21 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16630
16618
  providers = resolved.providers;
16631
16619
  providerConfigs = resolved.config.providers;
16632
16620
  } catch {
16633
- sendError(id, {
16621
+ sendError(id2, {
16634
16622
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16635
16623
  message: "auth login failed"
16636
16624
  });
16637
16625
  return;
16638
16626
  }
16639
16627
  if (!providers.includes(provider)) {
16640
- sendError(id, {
16628
+ sendError(id2, {
16641
16629
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16642
16630
  message: `unknown provider: ${provider}`
16643
16631
  });
16644
16632
  return;
16645
16633
  }
16646
16634
  if (!method || !providerAuthMethods(provider, providerConfigs).includes(method)) {
16647
- sendError(id, {
16635
+ sendError(id2, {
16648
16636
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16649
16637
  message: `unsupported auth method for ${provider}`
16650
16638
  });
@@ -16654,7 +16642,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16654
16642
  const raw = params.api_key;
16655
16643
  const apiKey = typeof raw === "string" ? raw.trim() : "";
16656
16644
  if (!apiKey || apiKey.length > MAX_API_KEY_LENGTH || /\s/.test(apiKey)) {
16657
- sendError(id, {
16645
+ sendError(id2, {
16658
16646
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16659
16647
  message: "api_key must be a non-empty single-line string"
16660
16648
  });
@@ -16672,20 +16660,20 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16672
16660
  return "saved";
16673
16661
  });
16674
16662
  } catch {
16675
- sendError(id, {
16663
+ sendError(id2, {
16676
16664
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16677
16665
  message: "saving credentials failed"
16678
16666
  });
16679
16667
  return;
16680
16668
  }
16681
16669
  if (saved === "busy") {
16682
- sendError(id, {
16670
+ sendError(id2, {
16683
16671
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16684
16672
  message: "runtime busy"
16685
16673
  });
16686
16674
  return;
16687
16675
  }
16688
- sendResult(id, {
16676
+ sendResult(id2, {
16689
16677
  status: "completed",
16690
16678
  provider,
16691
16679
  method: "api_key"
@@ -16694,7 +16682,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16694
16682
  return;
16695
16683
  }
16696
16684
  if (pending) {
16697
- sendError(id, {
16685
+ sendError(id2, {
16698
16686
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16699
16687
  message: "another login is pending"
16700
16688
  });
@@ -16702,7 +16690,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16702
16690
  }
16703
16691
  const typed = params;
16704
16692
  if (typed.callback !== void 0 && typed.callback !== "loopback" && typed.callback !== "paste") {
16705
- sendError(id, {
16693
+ sendError(id2, {
16706
16694
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16707
16695
  message: "callback must be loopback or paste"
16708
16696
  });
@@ -16725,7 +16713,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16725
16713
  return false;
16726
16714
  }
16727
16715
  stop();
16728
- sendError(id, {
16716
+ sendError(id2, {
16729
16717
  code: import_protocol5.RPC_ERROR_CODE.USER_CANCELLED,
16730
16718
  message: "login cancelled"
16731
16719
  });
@@ -16738,7 +16726,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16738
16726
  });
16739
16727
  if (cancelledDuringSetup(session.stop)) return;
16740
16728
  login.completeFromInput = session.completeFromInput;
16741
- sendResult(id, {
16729
+ sendResult(id2, {
16742
16730
  status: "pending",
16743
16731
  login_id: login.id,
16744
16732
  provider,
@@ -16756,7 +16744,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16756
16744
  const session = await createOpenAiDeviceCodeSession();
16757
16745
  const abort = new AbortController();
16758
16746
  if (cancelledDuringSetup(() => abort.abort())) return;
16759
- sendResult(id, {
16747
+ sendResult(id2, {
16760
16748
  status: "pending",
16761
16749
  login_id: login.id,
16762
16750
  provider,
@@ -16774,17 +16762,17 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16774
16762
  } catch (error) {
16775
16763
  login.settled = true;
16776
16764
  if (pending === login) pending = null;
16777
- sendError(id, {
16765
+ sendError(id2, {
16778
16766
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16779
16767
  message: `auth login failed: ${failureMessage(error)}`
16780
16768
  });
16781
16769
  }
16782
16770
  };
16783
- const handleLoginComplete = async (id, params) => {
16784
- if (rejectUnsupported(id)) return;
16771
+ const handleLoginComplete = async (id2, params) => {
16772
+ if (rejectUnsupported(id2)) return;
16785
16773
  const login = pending;
16786
16774
  if (!login || login.id !== params?.login_id) {
16787
- sendError(id, {
16775
+ sendError(id2, {
16788
16776
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16789
16777
  message: "no matching pending login"
16790
16778
  });
@@ -16792,7 +16780,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16792
16780
  }
16793
16781
  const input = params?.callback_input;
16794
16782
  if (!login.completeFromInput || typeof input !== "string" || !input.trim() || input.length > MAX_CALLBACK_INPUT_LENGTH) {
16795
- sendError(id, {
16783
+ sendError(id2, {
16796
16784
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16797
16785
  message: "callback_input is required for a pending OAuth login"
16798
16786
  });
@@ -16802,27 +16790,27 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16802
16790
  try {
16803
16791
  completion = login.completeFromInput(input.trim());
16804
16792
  } catch {
16805
- sendError(id, {
16793
+ sendError(id2, {
16806
16794
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16807
16795
  message: "invalid OAuth callback input"
16808
16796
  });
16809
16797
  return;
16810
16798
  }
16811
- sendResult(id, { ok: true });
16799
+ sendResult(id2, { ok: true });
16812
16800
  completion.then(
16813
16801
  (tokens) => finishLogin(login, tokens),
16814
16802
  (error) => failLogin(login, error)
16815
16803
  );
16816
16804
  };
16817
- const handleLoginCancel = async (id, params) => {
16818
- if (rejectUnsupported(id)) return;
16805
+ const handleLoginCancel = async (id2, params) => {
16806
+ if (rejectUnsupported(id2)) return;
16819
16807
  const login = pending;
16820
16808
  if (!login || login.id !== params?.login_id) {
16821
- sendResult(id, { cancelled: false });
16809
+ sendResult(id2, { cancelled: false });
16822
16810
  return;
16823
16811
  }
16824
16812
  settle(login);
16825
- sendResult(id, { cancelled: true });
16813
+ sendResult(id2, { cancelled: true });
16826
16814
  notifyLogin(login, "cancelled");
16827
16815
  log2(`auth.login cancelled provider=${login.provider}`);
16828
16816
  };
@@ -16996,19 +16984,19 @@ var createConfigHandlers = ({
16996
16984
  state,
16997
16985
  log: log2
16998
16986
  }) => {
16999
- const rejectUnsupported = (id) => {
16987
+ const rejectUnsupported = (id2) => {
17000
16988
  if (supportsConfigReadWrite(state)) return false;
17001
- sendError(id, {
16989
+ sendError(id2, {
17002
16990
  code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
17003
16991
  message: "config read/write is not available for this runtime"
17004
16992
  });
17005
16993
  return true;
17006
16994
  };
17007
- const handleConfigGet = async (id, params) => {
17008
- if (rejectUnsupported(id)) return;
16995
+ const handleConfigGet = async (id2, params) => {
16996
+ if (rejectUnsupported(id2)) return;
17009
16997
  const keys = params?.keys;
17010
16998
  if (keys !== void 0 && (!Array.isArray(keys) || keys.length > MAX_KEYS_PER_REQUEST || keys.some((key) => typeof key !== "string" || !findConfigKey(key)))) {
17011
- sendError(id, {
16999
+ sendError(id2, {
17012
17000
  code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
17013
17001
  message: "keys must list known config keys"
17014
17002
  });
@@ -17021,18 +17009,18 @@ var createConfigHandlers = ({
17021
17009
  entries: specs.map((spec) => buildConfigEntry(spec, layers)),
17022
17010
  ...layers.errors.length ? { errors: layers.errors } : {}
17023
17011
  };
17024
- sendResult(id, result);
17012
+ sendResult(id2, result);
17025
17013
  };
17026
- const handleConfigSet = async (id, params) => {
17027
- if (rejectUnsupported(id)) return;
17014
+ const handleConfigSet = async (id2, params) => {
17015
+ if (rejectUnsupported(id2)) return;
17028
17016
  if (state.activeRunId) {
17029
- sendError(id, {
17017
+ sendError(id2, {
17030
17018
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_BUSY,
17031
17019
  message: "runtime busy"
17032
17020
  });
17033
17021
  return;
17034
17022
  }
17035
- const invalid = (message) => sendError(id, { code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS, message });
17023
+ const invalid = (message) => sendError(id2, { code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS, message });
17036
17024
  const scope = params?.scope;
17037
17025
  if (scope !== "global" && scope !== "project") {
17038
17026
  invalid("scope must be global or project");
@@ -17082,14 +17070,14 @@ var createConfigHandlers = ({
17082
17070
  return written;
17083
17071
  });
17084
17072
  } catch {
17085
- sendError(id, {
17073
+ sendError(id2, {
17086
17074
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17087
17075
  message: `${scope} config write failed`
17088
17076
  });
17089
17077
  return;
17090
17078
  }
17091
17079
  if (changed === "busy") {
17092
- sendError(id, {
17080
+ sendError(id2, {
17093
17081
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_BUSY,
17094
17082
  message: "runtime busy"
17095
17083
  });
@@ -17103,7 +17091,7 @@ var createConfigHandlers = ({
17103
17091
  entry: buildConfigEntry(spec, layers),
17104
17092
  applies: "next_run"
17105
17093
  };
17106
- sendResult(id, result);
17094
+ sendResult(id2, result);
17107
17095
  log2(
17108
17096
  `config.set ${spec.key} scope=${scope} ${unset ? "unset" : "set"} changed=${changed}`
17109
17097
  );
@@ -17194,7 +17182,7 @@ var createContextHandlers = ({
17194
17182
  return null;
17195
17183
  }
17196
17184
  };
17197
- const handleContextInspect = async (id, params) => {
17185
+ const handleContextInspect = async (id2, params) => {
17198
17186
  const includeAgents = params?.include_agents ?? true;
17199
17187
  const includeSkills = params?.include_skills ?? true;
17200
17188
  try {
@@ -17240,9 +17228,9 @@ var createContextHandlers = ({
17240
17228
  result.skills = snapshot;
17241
17229
  }
17242
17230
  }
17243
- sendResult(id, result);
17231
+ sendResult(id2, result);
17244
17232
  } catch (error) {
17245
- sendError(id, {
17233
+ sendError(id2, {
17246
17234
  code: import_protocol7.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17247
17235
  message: `context.inspect failed: ${String(error)}`
17248
17236
  });
@@ -17267,17 +17255,17 @@ var createContextUsageHandlers = ({
17267
17255
  state,
17268
17256
  log: log2
17269
17257
  }) => {
17270
- const handleContextUsage = async (id) => {
17258
+ const handleContextUsage = async (id2) => {
17271
17259
  try {
17272
17260
  const usage = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
17273
17261
  const result = {
17274
17262
  ...usage,
17275
17263
  ...state.sessionId ? { session_id: state.sessionId } : {}
17276
17264
  };
17277
- sendResult(id, result);
17265
+ sendResult(id2, result);
17278
17266
  } catch (error) {
17279
17267
  log2(`context.usage failed: ${String(error)}`);
17280
- sendError(id, {
17268
+ sendError(id2, {
17281
17269
  code: import_protocol8.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17282
17270
  message: "context usage unavailable"
17283
17271
  });
@@ -17516,14 +17504,14 @@ var createHistoryHandlers = ({
17516
17504
  if (!trimmed) return void 0;
17517
17505
  return import_node_path22.default.resolve(trimmed);
17518
17506
  };
17519
- const handleSessionList = async (id, params) => {
17507
+ const handleSessionList = async (id2, params) => {
17520
17508
  const limit = params?.limit ?? 50;
17521
17509
  const scope = params?.scope ?? "current_workspace";
17522
17510
  let sessions;
17523
17511
  try {
17524
17512
  sessions = await sessionStateStore.list();
17525
17513
  } catch (error) {
17526
- sendError(id, {
17514
+ sendError(id2, {
17527
17515
  code: import_protocol9.RPC_ERROR_CODE.SESSION_LIST_FAILED,
17528
17516
  message: `session list failed: ${String(error)}`
17529
17517
  });
@@ -17541,7 +17529,7 @@ var createHistoryHandlers = ({
17541
17529
  sessions: filtered,
17542
17530
  current_workspace_root: requestedWorkspaceRoot
17543
17531
  };
17544
- sendResult(id, result);
17532
+ sendResult(id2, result);
17545
17533
  };
17546
17534
  const collectRuns = async (sessionId, maxRuns) => {
17547
17535
  if (runIndex) {
@@ -17553,10 +17541,10 @@ var createHistoryHandlers = ({
17553
17541
  }
17554
17542
  return collectSessionRuns(sessionId, maxRuns, log2);
17555
17543
  };
17556
- const handleSessionHistory = async (id, params) => {
17544
+ const handleSessionHistory = async (id2, params) => {
17557
17545
  const sessionId = params?.session_id?.trim();
17558
17546
  if (!sessionId) {
17559
- sendError(id, {
17547
+ sendError(id2, {
17560
17548
  code: import_protocol9.RPC_ERROR_CODE.INVALID_PARAMS,
17561
17549
  message: "session_id is required"
17562
17550
  });
@@ -17569,7 +17557,7 @@ var createHistoryHandlers = ({
17569
17557
  runs: 0,
17570
17558
  events_sent: 0
17571
17559
  };
17572
- sendResult(id, result2);
17560
+ sendResult(id2, result2);
17573
17561
  return;
17574
17562
  }
17575
17563
  const runs = readRunLogs ? await collectRuns(sessionId, maxRuns) : [];
@@ -17584,6 +17572,7 @@ var createHistoryHandlers = ({
17584
17572
  }
17585
17573
  if (!record || typeof record !== "object") continue;
17586
17574
  if (record.type === "run.start") {
17575
+ if (record.source === "goal") continue;
17587
17576
  const input = runStartInputToHiddenMessage(record.input);
17588
17577
  if (input) {
17589
17578
  replayEvents.push({
@@ -17629,7 +17618,7 @@ var createHistoryHandlers = ({
17629
17618
  ...truncated ? { truncated: true } : {},
17630
17619
  ...resumeDiff ? { resume_diff: resumeDiff } : {}
17631
17620
  };
17632
- sendResult(id, result);
17621
+ sendResult(id2, result);
17633
17622
  };
17634
17623
  return { handleSessionList, handleSessionHistory };
17635
17624
  };
@@ -17750,23 +17739,23 @@ function createImageHandlers(state) {
17750
17739
  const codex = chat?.auth.method === "oauth";
17751
17740
  model = await pick(
17752
17741
  codex ? "Codex OAuth image model (current login; account-specific limits)" : "Image model (API billed; availability is account-specific)",
17753
- (codex ? import_config12.OPENAI_CODEX_IMAGE_MODELS : import_config12.OPENAI_IMAGE_MODELS).map((id) => ({
17754
- id,
17755
- label: id,
17742
+ (codex ? import_config12.OPENAI_CODEX_IMAGE_MODELS : import_config12.OPENAI_IMAGE_MODELS).map((id2) => ({
17743
+ id: id2,
17744
+ label: id2,
17756
17745
  ...codex ? {
17757
- detail: id === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
17746
+ detail: id2 === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
17758
17747
  } : {}
17759
17748
  }))
17760
17749
  );
17761
17750
  } else if (provider === "google") {
17762
17751
  model = await pick(
17763
17752
  "Gemini image model",
17764
- import_config12.GOOGLE_IMAGE_MODELS.map((id) => ({ id, label: id }))
17753
+ import_config12.GOOGLE_IMAGE_MODELS.map((id2) => ({ id: id2, label: id2 }))
17765
17754
  );
17766
17755
  if (!model) return null;
17767
17756
  const image_size = await pick(
17768
17757
  "Image size",
17769
- (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id) => ({ id, label: id }))
17758
+ (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id2) => ({ id: id2, label: id2 }))
17770
17759
  );
17771
17760
  if (!image_size) return null;
17772
17761
  const aspect_ratio = await pick(
@@ -17783,7 +17772,7 @@ function createImageHandlers(state) {
17783
17772
  "16:9",
17784
17773
  "21:9",
17785
17774
  ...model === "gemini-nano-banana-2.1" ? ["1:4", "4:1", "1:8", "8:1"] : []
17786
- ].map((id) => ({ id, label: id }))
17775
+ ].map((id2) => ({ id: id2, label: id2 }))
17787
17776
  );
17788
17777
  if (!aspect_ratio) return null;
17789
17778
  const format = await pick("Image output format", [
@@ -17829,7 +17818,7 @@ function createImageHandlers(state) {
17829
17818
  }
17830
17819
  );
17831
17820
  };
17832
- const handle = async (id, operation, params) => {
17821
+ const handle = async (id2, operation, params) => {
17833
17822
  let ownsConfiguration = false;
17834
17823
  try {
17835
17824
  const root = workspace();
@@ -17843,14 +17832,14 @@ function createImageHandlers(state) {
17843
17832
  root,
17844
17833
  () => state.sessionId
17845
17834
  ).read(parsed2.data.artifact_id);
17846
- sendResult(id, {
17835
+ sendResult(id2, {
17847
17836
  metadata,
17848
17837
  data_url: `data:${metadata.media_type};base64,${bytes.toString("base64")}`
17849
17838
  });
17850
17839
  return;
17851
17840
  }
17852
17841
  if (operation === "get") {
17853
- sendResult(id, await status(await resolveImageGenerationConfig(root)));
17842
+ sendResult(id2, await status(await resolveImageGenerationConfig(root)));
17854
17843
  return;
17855
17844
  }
17856
17845
  if (state.activeRunId || configuring)
@@ -17905,7 +17894,7 @@ function createImageHandlers(state) {
17905
17894
  config = await choose();
17906
17895
  }
17907
17896
  if (!config) {
17908
- sendResult(id, { message: "Image settings unchanged." });
17897
+ sendResult(id2, { message: "Image settings unchanged." });
17909
17898
  return;
17910
17899
  }
17911
17900
  const next = await status(config);
@@ -17922,7 +17911,7 @@ This saves image settings only; generation requests use the tool permission poli
17922
17911
  cancel_label: "Cancel"
17923
17912
  });
17924
17913
  if (!confirm?.ok) {
17925
- sendResult(id, { message: "Image settings unchanged." });
17914
+ sendResult(id2, { message: "Image settings unchanged." });
17926
17915
  return;
17927
17916
  }
17928
17917
  }
@@ -17934,9 +17923,9 @@ This saves image settings only; generation requests use the tool permission poli
17934
17923
  state.agent = null;
17935
17924
  state.tools = null;
17936
17925
  state.toolDefinitions = null;
17937
- sendResult(id, next);
17926
+ sendResult(id2, next);
17938
17927
  } catch (error) {
17939
- sendError(id, {
17928
+ sendError(id2, {
17940
17929
  code: import_protocol10.RPC_ERROR_CODE.INVALID_PARAMS,
17941
17930
  message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
17942
17931
  });
@@ -18116,13 +18105,13 @@ var parseOpenRouterModel = (value) => {
18116
18105
  return null;
18117
18106
  }
18118
18107
  const entry = value;
18119
- const id = typeof entry.id === "string" ? entry.id.trim() : "";
18120
- if (!id) {
18108
+ const id2 = typeof entry.id === "string" ? entry.id.trim() : "";
18109
+ if (!id2) {
18121
18110
  return null;
18122
18111
  }
18123
18112
  const topProvider = entry.top_provider && typeof entry.top_provider === "object" ? entry.top_provider : null;
18124
18113
  return {
18125
- id,
18114
+ id: id2,
18126
18115
  created: typeof entry.created === "number" && Number.isFinite(entry.created) ? entry.created : void 0,
18127
18116
  context_length: parsePositiveNumber(entry.context_length),
18128
18117
  top_provider: topProvider ? {
@@ -18291,12 +18280,13 @@ var createModelHandlers = ({
18291
18280
  model: name2,
18292
18281
  requested: fast
18293
18282
  });
18294
- if (fast === "ultrafast") {
18295
- const auth = state.effectiveEnvironment.auth.model === "host" ? await state.effectiveEnvironment.adapters.credentialProvider?.resolveProviderAuth(
18296
- provider
18297
- ) : (await new AuthStore().load()).providers[provider];
18298
- const method = auth?.method ?? (state.effectiveEnvironment.auth.model !== "host" && readEnvValue("OPENAI_API_KEY") ? "api_key" : "missing");
18299
- assertUltrafastAuth(fast, method);
18283
+ if (fast !== "ultrafast") return effectiveFast;
18284
+ const { auth: authPolicy, adapters } = state.effectiveEnvironment;
18285
+ const credentials = authPolicy.model === "host" ? await adapters.credentialProvider?.resolveProviderAuth(provider) : (await new AuthStore().load()).providers[provider] ?? readEnvValue("OPENAI_API_KEY");
18286
+ if (!credentials) {
18287
+ throw new Error(
18288
+ "Ultrafast requires OpenAI API-key or ChatGPT sign-in credentials."
18289
+ );
18300
18290
  }
18301
18291
  return effectiveFast;
18302
18292
  };
@@ -18315,7 +18305,7 @@ var createModelHandlers = ({
18315
18305
  meta: nextMeta
18316
18306
  });
18317
18307
  };
18318
- const handleModelList = async (id, params) => {
18308
+ const handleModelList = async (id2, params) => {
18319
18309
  const requestedProvider = params?.provider;
18320
18310
  const includeDetails = params?.include_details ?? false;
18321
18311
  let providers;
@@ -18342,7 +18332,7 @@ var createModelHandlers = ({
18342
18332
  });
18343
18333
  }
18344
18334
  } catch (error) {
18345
- sendError(id, {
18335
+ sendError(id2, {
18346
18336
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18347
18337
  message: String(error)
18348
18338
  });
@@ -18350,7 +18340,7 @@ var createModelHandlers = ({
18350
18340
  }
18351
18341
  const provider = requestedProvider ?? configuredProvider ?? "openai";
18352
18342
  if (!isSupportedProvider(provider, providers)) {
18353
- sendError(id, {
18343
+ sendError(id2, {
18354
18344
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18355
18345
  message: `unsupported provider: ${provider}`
18356
18346
  });
@@ -18369,7 +18359,7 @@ var createModelHandlers = ({
18369
18359
  models = result2.models;
18370
18360
  details = result2.details;
18371
18361
  } catch (error) {
18372
- sendError(id, {
18362
+ sendError(id2, {
18373
18363
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18374
18364
  message: String(error)
18375
18365
  });
@@ -18396,11 +18386,11 @@ var createModelHandlers = ({
18396
18386
  ...configuredFast !== void 0 ? { fast: configuredFast } : {},
18397
18387
  ...details ? { details } : {}
18398
18388
  };
18399
- sendResult(id, result);
18389
+ sendResult(id2, result);
18400
18390
  };
18401
- const handleModelSet = async (id, params) => {
18391
+ const handleModelSet = async (id2, params) => {
18402
18392
  if (state.activeRunId) {
18403
- sendError(id, {
18393
+ sendError(id2, {
18404
18394
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_BUSY,
18405
18395
  message: "runtime busy"
18406
18396
  });
@@ -18408,7 +18398,7 @@ var createModelHandlers = ({
18408
18398
  }
18409
18399
  const scope = params?.scope ?? "config";
18410
18400
  if (scope !== "config" && scope !== "session") {
18411
- sendError(id, {
18401
+ sendError(id2, {
18412
18402
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18413
18403
  message: `unsupported model scope: ${scope}`
18414
18404
  });
@@ -18417,7 +18407,7 @@ var createModelHandlers = ({
18417
18407
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
18418
18408
  if (params?.reset) {
18419
18409
  if (scope !== "session") {
18420
- sendError(id, {
18410
+ sendError(id2, {
18421
18411
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18422
18412
  message: "model reset is only supported for session scope"
18423
18413
  });
@@ -18428,7 +18418,7 @@ var createModelHandlers = ({
18428
18418
  const provider2 = config.provider ?? "openai";
18429
18419
  const name3 = config.name;
18430
18420
  if (!name3) {
18431
- sendError(id, {
18421
+ sendError(id2, {
18432
18422
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18433
18423
  message: "configured model name is missing"
18434
18424
  });
@@ -18444,7 +18434,7 @@ var createModelHandlers = ({
18444
18434
  config.fast
18445
18435
  );
18446
18436
  } catch (error) {
18447
- sendError(id, {
18437
+ sendError(id2, {
18448
18438
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18449
18439
  message: String(error)
18450
18440
  });
@@ -18463,10 +18453,10 @@ var createModelHandlers = ({
18463
18453
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
18464
18454
  ...config.fast !== void 0 ? { fast: effectiveFast } : {}
18465
18455
  };
18466
- sendResult(id, result);
18456
+ sendResult(id2, result);
18467
18457
  log2(`model.set reset session override -> ${provider2}/${name3}`);
18468
18458
  } catch (error) {
18469
- sendError(id, {
18459
+ sendError(id2, {
18470
18460
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18471
18461
  message: String(error)
18472
18462
  });
@@ -18476,7 +18466,7 @@ var createModelHandlers = ({
18476
18466
  const provider = params?.provider ?? "openai";
18477
18467
  let name2 = params?.name?.trim();
18478
18468
  if (!name2) {
18479
- sendError(id, {
18469
+ sendError(id2, {
18480
18470
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18481
18471
  message: "model name is required"
18482
18472
  });
@@ -18487,7 +18477,7 @@ var createModelHandlers = ({
18487
18477
  try {
18488
18478
  reasoning = resolveReasoningEffort(params.reasoning);
18489
18479
  } catch (error) {
18490
- sendError(id, {
18480
+ sendError(id2, {
18491
18481
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18492
18482
  message: String(error)
18493
18483
  });
@@ -18497,7 +18487,7 @@ var createModelHandlers = ({
18497
18487
  const configured = await resolveEnvironmentModelConfig(state, workingDir);
18498
18488
  const endpoint = getResponsesProvider(configured, provider);
18499
18489
  if (!isSupportedProvider(provider, configured.providers)) {
18500
- sendError(id, {
18490
+ sendError(id2, {
18501
18491
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18502
18492
  message: `unsupported provider: ${provider}`
18503
18493
  });
@@ -18510,7 +18500,7 @@ var createModelHandlers = ({
18510
18500
  provider
18511
18501
  );
18512
18502
  if (!spec) {
18513
- sendError(id, {
18503
+ sendError(id2, {
18514
18504
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18515
18505
  message: `unknown model: ${name2}`
18516
18506
  });
@@ -18543,16 +18533,16 @@ var createModelHandlers = ({
18543
18533
  }
18544
18534
  await validateFastSelection(provider, name2, candidate.fast);
18545
18535
  } catch (error) {
18546
- sendError(id, {
18536
+ sendError(id2, {
18547
18537
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18548
18538
  message: String(error)
18549
18539
  });
18550
18540
  return;
18551
18541
  }
18552
18542
  try {
18553
- let target = null;
18543
+ let target2 = null;
18554
18544
  if (scope === "config") {
18555
- target = await updateEnvironmentModel(state, workingDir, {
18545
+ target2 = await updateEnvironmentModel(state, workingDir, {
18556
18546
  provider,
18557
18547
  name: name2,
18558
18548
  ...reasoning ? { reasoning } : {},
@@ -18592,13 +18582,13 @@ var createModelHandlers = ({
18592
18582
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
18593
18583
  ...updatedConfig.fast !== void 0 ? { fast: effectiveFast } : {}
18594
18584
  };
18595
- sendResult(id, result);
18596
- const persistence = scope === "config" && target ? ` scope=${target.scope} path=${target.path}` : " scope=session";
18585
+ sendResult(id2, result);
18586
+ const persistence = scope === "config" && target2 ? ` scope=${target2.scope} path=${target2.path}` : " scope=session";
18597
18587
  log2(
18598
18588
  `model.set ${provider}/${name2}${effectiveReasoning ? ` reasoning=${effectiveReasoning}` : ""}${persistence}`
18599
18589
  );
18600
18590
  } catch (error) {
18601
- sendError(id, {
18591
+ sendError(id2, {
18602
18592
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18603
18593
  message: String(error)
18604
18594
  });
@@ -18653,18 +18643,18 @@ var createPermissionsHandlers = ({
18653
18643
  state,
18654
18644
  log: log2
18655
18645
  }) => {
18656
- const rejectUnsupported = (id) => {
18646
+ const rejectUnsupported = (id2) => {
18657
18647
  if (supportsConfigReadWrite(state)) return false;
18658
- sendError(id, {
18648
+ sendError(id2, {
18659
18649
  code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS,
18660
18650
  message: "permission rules are not available for this runtime"
18661
18651
  });
18662
18652
  return true;
18663
18653
  };
18664
- const handlePermissionsList = async (id, params) => {
18665
- if (rejectUnsupported(id)) return;
18654
+ const handlePermissionsList = async (id2, params) => {
18655
+ if (rejectUnsupported(id2)) return;
18666
18656
  if (params?.include_system !== void 0 && typeof params.include_system !== "boolean") {
18667
- sendError(id, {
18657
+ sendError(id2, {
18668
18658
  code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS,
18669
18659
  message: "include_system must be a boolean"
18670
18660
  });
@@ -18728,18 +18718,18 @@ var createPermissionsHandlers = ({
18728
18718
  rules,
18729
18719
  ...errors.length ? { errors } : {}
18730
18720
  };
18731
- sendResult(id, result);
18721
+ sendResult(id2, result);
18732
18722
  };
18733
- const handlePermissionsRemove = async (id, params) => {
18734
- if (rejectUnsupported(id)) return;
18723
+ const handlePermissionsRemove = async (id2, params) => {
18724
+ if (rejectUnsupported(id2)) return;
18735
18725
  if (state.activeRunId) {
18736
- sendError(id, {
18726
+ sendError(id2, {
18737
18727
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_BUSY,
18738
18728
  message: "runtime busy"
18739
18729
  });
18740
18730
  return;
18741
18731
  }
18742
- const invalid = (message) => sendError(id, { code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS, message });
18732
+ const invalid = (message) => sendError(id2, { code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS, message });
18743
18733
  const scope = params?.scope;
18744
18734
  const kind = params?.kind;
18745
18735
  if (scope !== "global" && scope !== "project") {
@@ -18770,21 +18760,21 @@ var createPermissionsHandlers = ({
18770
18760
  return count2;
18771
18761
  });
18772
18762
  } catch {
18773
- sendError(id, {
18763
+ sendError(id2, {
18774
18764
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18775
18765
  message: `${scope} config write failed`
18776
18766
  });
18777
18767
  return;
18778
18768
  }
18779
18769
  if (removed === "busy") {
18780
- sendError(id, {
18770
+ sendError(id2, {
18781
18771
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_BUSY,
18782
18772
  message: "runtime busy"
18783
18773
  });
18784
18774
  return;
18785
18775
  }
18786
18776
  const result = { scope, kind, path: path29, removed };
18787
- sendResult(id, result);
18777
+ sendResult(id2, result);
18788
18778
  log2(`permissions.remove scope=${scope} kind=${kind} removed=${removed}`);
18789
18779
  };
18790
18780
  return { handlePermissionsList, handlePermissionsRemove };
@@ -19163,7 +19153,7 @@ var buildResumeDiff = async (meta, state, options = {}) => {
19163
19153
  };
19164
19154
 
19165
19155
  // src/rpc/run.ts
19166
- var import_protocol13 = require("@codelia/protocol");
19156
+ var import_protocol14 = require("@codelia/protocol");
19167
19157
 
19168
19158
  // src/provider-errors.ts
19169
19159
  var import_core34 = require("@codelia/core");
@@ -19233,23 +19223,23 @@ var normalizeRunFailure = (error) => {
19233
19223
 
19234
19224
  // src/rpc/client-tool-requests.ts
19235
19225
  var requestClientToolCall = async (state, params, timeoutMs) => {
19236
- const id = state.nextUiRequestId();
19226
+ const id2 = state.nextUiRequestId();
19237
19227
  const request = {
19238
19228
  jsonrpc: "2.0",
19239
- id,
19229
+ id: id2,
19240
19230
  method: "client.tool.call",
19241
19231
  params
19242
19232
  };
19243
19233
  send(request);
19244
19234
  return await state.waitForUiResponse(
19245
- id,
19235
+ id2,
19246
19236
  timeoutMs,
19247
19237
  () => {
19248
19238
  const notification = {
19249
19239
  jsonrpc: "2.0",
19250
19240
  method: "client.tool.cancel",
19251
19241
  params: {
19252
- request_id: id,
19242
+ request_id: id2,
19253
19243
  run_id: params.run_id,
19254
19244
  name: params.name,
19255
19245
  reason: "timeout"
@@ -19359,8 +19349,550 @@ var createClientToolAdapters = ({
19359
19349
  });
19360
19350
  };
19361
19351
 
19362
- // src/rpc/run-debug.ts
19352
+ // src/rpc/goals.ts
19363
19353
  var import_core35 = require("@codelia/core");
19354
+ var import_protocol13 = require("@codelia/protocol");
19355
+ var import_storage18 = require("@codelia/storage");
19356
+ var import_zod36 = require("zod");
19357
+ var id = import_zod36.z.string().min(1).max(200);
19358
+ var revision = import_zod36.z.number().int().positive();
19359
+ var target = import_zod36.z.object({ session_id: id, goal_id: id, revision });
19360
+ var budget = import_zod36.z.number().int().positive().nullable();
19361
+ var schemas = {
19362
+ "goal.get": import_zod36.z.object({
19363
+ session_id: id.optional(),
19364
+ continuation_id: id.optional()
19365
+ }),
19366
+ "goal.set": target.partial().extend({
19367
+ objective: import_zod36.z.string().trim().min(1).max(8e3).optional(),
19368
+ token_budget: budget.optional()
19369
+ }),
19370
+ "goal.pause": import_zod36.z.object({
19371
+ session_id: id,
19372
+ goal_id: id,
19373
+ activation_id: id,
19374
+ run_id: id.optional(),
19375
+ continuation_id: id.optional()
19376
+ }),
19377
+ "goal.resume": target,
19378
+ "goal.clear": target
19379
+ };
19380
+ var readySchema = target.extend({
19381
+ continuation_id: id,
19382
+ after_run_id: id.optional()
19383
+ });
19384
+ var GoalConflict = class extends Error {
19385
+ constructor(message, reason = "conflict") {
19386
+ super(message);
19387
+ this.reason = reason;
19388
+ }
19389
+ reason;
19390
+ };
19391
+ var stamp = () => (/* @__PURE__ */ new Date()).toISOString();
19392
+ var transition = (goal, status, reason) => {
19393
+ if (goal.status !== status || goal.stop_reason !== reason)
19394
+ goal.stop_detail = void 0;
19395
+ goal.status = status;
19396
+ goal.stop_reason = reason;
19397
+ goal.revision += 1;
19398
+ goal.updated_at = stamp();
19399
+ };
19400
+ function stopForBudget(goal) {
19401
+ if (goal.token_budget === null) return false;
19402
+ if (goal.tokens_used >= goal.token_budget) {
19403
+ transition(goal, "budget_limited");
19404
+ return true;
19405
+ }
19406
+ if (!goal.usage_known) {
19407
+ transition(goal, "usage_limited");
19408
+ return true;
19409
+ }
19410
+ return false;
19411
+ }
19412
+ var readTarget = (entry, expected) => {
19413
+ if (!entry || entry.goal.goal_id !== expected.goal_id || entry.goal.revision !== expected.revision)
19414
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
19415
+ return entry;
19416
+ };
19417
+ var GoalController = class {
19418
+ constructor(state, store, sessions, workspaceRoot) {
19419
+ this.state = state;
19420
+ this.store = store;
19421
+ this.sessions = sessions;
19422
+ this.workspaceRoot = workspaceRoot;
19423
+ }
19424
+ state;
19425
+ store;
19426
+ sessions;
19427
+ workspaceRoot;
19428
+ activation = null;
19429
+ offer = null;
19430
+ activeRun;
19431
+ identity;
19432
+ get enabled() {
19433
+ return this.state.uiCapabilities?.supports_goals === true;
19434
+ }
19435
+ disarm() {
19436
+ this.activation = null;
19437
+ this.offer = null;
19438
+ }
19439
+ owns(goal) {
19440
+ return this.activation?.sessionId === goal.session_id && this.activation.goalId === goal.goal_id && this.activation.id === goal.activation_id;
19441
+ }
19442
+ arm(goal) {
19443
+ this.activation = {
19444
+ sessionId: goal.session_id,
19445
+ goalId: goal.goal_id,
19446
+ id: goal.activation_id
19447
+ };
19448
+ this.offer = null;
19449
+ }
19450
+ snapshot(sessionId, goal, acceptedRunId) {
19451
+ return {
19452
+ session_id: sessionId,
19453
+ goal,
19454
+ can_continue: Boolean(goal?.status === "active" && this.owns(goal)),
19455
+ ...acceptedRunId ? {
19456
+ accepted_run_id: acceptedRunId,
19457
+ ...this.state.activeRunId === acceptedRunId ? { active_run_id: acceptedRunId } : {}
19458
+ } : {}
19459
+ };
19460
+ }
19461
+ publish(goal) {
19462
+ if (this.enabled && this.state.sessionId === goal.session_id)
19463
+ send({
19464
+ jsonrpc: "2.0",
19465
+ method: "goal.updated",
19466
+ params: this.snapshot(goal.session_id, goal)
19467
+ });
19468
+ }
19469
+ ready(goal, afterRunId) {
19470
+ if (!this.enabled || this.state.activeRunId || this.state.sessionId !== goal.session_id || goal.status !== "active" || !this.owns(goal) || this.offer)
19471
+ return;
19472
+ this.offer = {
19473
+ session_id: goal.session_id,
19474
+ goal_id: goal.goal_id,
19475
+ revision: goal.revision,
19476
+ continuation_id: crypto.randomUUID(),
19477
+ ...afterRunId ? { after_run_id: afterRunId } : {}
19478
+ };
19479
+ send({ jsonrpc: "2.0", method: "goal.ready", params: this.offer });
19480
+ }
19481
+ bound(requested) {
19482
+ if (requested !== void 0 && requested !== this.state.sessionId)
19483
+ throw new GoalConflict("Goal request belongs to a different session.");
19484
+ return this.state.sessionId;
19485
+ }
19486
+ requireIdle() {
19487
+ if (this.state.activeRunId)
19488
+ throw new GoalConflict("Wait for the active run to finish.", "busy");
19489
+ }
19490
+ async recoverable(claim) {
19491
+ try {
19492
+ process.kill(claim.owner_pid, 0);
19493
+ } catch (error) {
19494
+ return error.code === "ESRCH";
19495
+ }
19496
+ if (!claim.owner_identity) return false;
19497
+ const current = await (0, import_storage18.getProcessIdentity)(claim.owner_pid, {
19498
+ canonicalEnvironment: true
19499
+ });
19500
+ return current !== null && current !== claim.owner_identity;
19501
+ }
19502
+ /** Pause intent is latched before joining the admission queue. */
19503
+ handle(requestId, method, raw, serialize, interrupt, onError) {
19504
+ if (!this.enabled) {
19505
+ sendError(requestId, {
19506
+ code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
19507
+ message: "Goals are unavailable on this connection."
19508
+ });
19509
+ return Promise.resolve();
19510
+ }
19511
+ const pause = method === "goal.pause" ? schemas[method].safeParse(raw) : void 0;
19512
+ const revoked = pause?.success && this.activation?.sessionId === pause.data.session_id && this.activation.goalId === pause.data.goal_id && this.activation.id === pause.data.activation_id;
19513
+ if (revoked) this.disarm();
19514
+ if (pause?.success && this.state.sessionId === pause.data.session_id) {
19515
+ const { goal_id, activation_id, run_id, continuation_id } = pause.data;
19516
+ const run = this.activeRun;
19517
+ if (run?.goal.goal_id === goal_id && run.goal.activation_id === activation_id && (run_id === run.runId || continuation_id !== void 0 && continuation_id === run.continuationId))
19518
+ interrupt(run.runId);
19519
+ }
19520
+ return serialize(async () => {
19521
+ let goal;
19522
+ let sessionId;
19523
+ let cleared = false;
19524
+ switch (method) {
19525
+ case "goal.get": {
19526
+ const params = schemas[method].parse(raw ?? {});
19527
+ sessionId = this.bound(params.session_id);
19528
+ const result = sessionId ? await this.store.read(sessionId, params.continuation_id) : null;
19529
+ sendResult(
19530
+ requestId,
19531
+ this.snapshot(
19532
+ sessionId,
19533
+ result?.entry?.goal ?? null,
19534
+ result?.acceptedRunId
19535
+ )
19536
+ );
19537
+ return;
19538
+ }
19539
+ case "goal.set": {
19540
+ const params = schemas[method].parse(raw);
19541
+ this.requireIdle();
19542
+ sessionId = this.bound(params.session_id);
19543
+ const fresh = sessionId === null;
19544
+ if (fresh && !params.objective)
19545
+ throw new GoalConflict("Set a goal first.");
19546
+ const key = sessionId ?? this.state.nextSessionId();
19547
+ if (fresh) {
19548
+ const root = this.workspaceRoot();
19549
+ const meta = mergeSessionModelOverrideIntoMeta(
19550
+ root ? { codelia_workspace_root: root } : void 0,
19551
+ this.state.sessionModelOverride
19552
+ );
19553
+ await this.sessions.save({
19554
+ schema_version: 1,
19555
+ session_id: key,
19556
+ updated_at: stamp(),
19557
+ messages: [],
19558
+ ...meta ? { meta } : {}
19559
+ });
19560
+ }
19561
+ let created = false;
19562
+ goal = await this.store.update(key, (tx) => {
19563
+ if (!tx.entry) {
19564
+ if (!params.objective || params.goal_id !== void 0 || params.revision !== void 0)
19565
+ throw new GoalConflict("Set a goal first.");
19566
+ const now = stamp();
19567
+ created = true;
19568
+ tx.entry = {
19569
+ goal: {
19570
+ session_id: key,
19571
+ goal_id: crypto.randomUUID(),
19572
+ revision: 1,
19573
+ objective: params.objective,
19574
+ status: "active",
19575
+ token_budget: params.token_budget ?? null,
19576
+ tokens_used: 0,
19577
+ usage_known: true,
19578
+ activation_id: crypto.randomUUID(),
19579
+ automatic_runs: 0,
19580
+ created_at: now,
19581
+ updated_at: now
19582
+ }
19583
+ };
19584
+ return tx.entry.goal;
19585
+ }
19586
+ const expected = target.parse(params);
19587
+ const entry = readTarget(tx.entry, expected);
19588
+ if (entry.claim)
19589
+ throw new GoalConflict("A goal run is still reserved.", "busy");
19590
+ if (entry.goal.status === "complete")
19591
+ throw new GoalConflict("Clear the completed goal first.");
19592
+ if (params.objective !== void 0) {
19593
+ entry.goal.objective = params.objective;
19594
+ entry.blocker = void 0;
19595
+ }
19596
+ if (params.token_budget !== void 0)
19597
+ entry.goal.token_budget = params.token_budget;
19598
+ if (entry.goal.status !== "active" || !stopForBudget(entry.goal))
19599
+ transition(entry.goal, entry.goal.status, entry.goal.stop_reason);
19600
+ return entry.goal;
19601
+ });
19602
+ if (fresh) {
19603
+ this.state.sessionId = key;
19604
+ this.state.attachments?.bindDraft(key);
19605
+ }
19606
+ sessionId = key;
19607
+ if (created) this.arm(goal);
19608
+ else this.offer = null;
19609
+ break;
19610
+ }
19611
+ case "goal.pause": {
19612
+ const params = schemas[method].parse(raw);
19613
+ this.bound(params.session_id);
19614
+ sessionId = params.session_id;
19615
+ if (!revoked)
19616
+ throw new GoalConflict("Goal is not active on this connection.");
19617
+ goal = await this.store.update(sessionId, ({ entry }) => {
19618
+ if (!entry || entry.goal.goal_id !== params.goal_id || entry.goal.activation_id !== params.activation_id)
19619
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
19620
+ if (entry.goal.status === "active")
19621
+ transition(entry.goal, "paused", "user");
19622
+ return entry.goal;
19623
+ });
19624
+ break;
19625
+ }
19626
+ case "goal.resume": {
19627
+ const params = schemas[method].parse(raw);
19628
+ this.bound(params.session_id);
19629
+ this.requireIdle();
19630
+ sessionId = params.session_id;
19631
+ const previous = readTarget(
19632
+ (await this.store.read(sessionId)).entry,
19633
+ params
19634
+ );
19635
+ if (previous.goal.status === "complete")
19636
+ throw new GoalConflict("Goal is complete.");
19637
+ const orphan = previous.claim;
19638
+ if (orphan && !await this.recoverable(orphan))
19639
+ throw new GoalConflict(
19640
+ "A goal run is still reserved by a live or unverified runtime.",
19641
+ "busy"
19642
+ );
19643
+ goal = await this.store.update(sessionId, (tx) => {
19644
+ const entry = readTarget(tx.entry, params);
19645
+ if (entry.claim?.run_id !== orphan?.run_id)
19646
+ throw new GoalConflict("Goal run reservation changed.", "busy");
19647
+ if (orphan?.pending_seq !== void 0)
19648
+ entry.goal.usage_known = false;
19649
+ entry.claim = void 0;
19650
+ if (stopForBudget(entry.goal)) return entry.goal;
19651
+ entry.goal.activation_id = crypto.randomUUID();
19652
+ entry.goal.automatic_runs = 0;
19653
+ entry.blocker = void 0;
19654
+ transition(entry.goal, "active");
19655
+ return entry.goal;
19656
+ });
19657
+ if (goal.status === "active") this.arm(goal);
19658
+ else this.disarm();
19659
+ break;
19660
+ }
19661
+ case "goal.clear": {
19662
+ const params = schemas[method].parse(raw);
19663
+ this.bound(params.session_id);
19664
+ this.requireIdle();
19665
+ sessionId = params.session_id;
19666
+ await this.store.update(sessionId, (tx) => {
19667
+ if (readTarget(tx.entry, params).claim)
19668
+ throw new GoalConflict("A goal run is still reserved.", "busy");
19669
+ tx.entry = null;
19670
+ });
19671
+ this.disarm();
19672
+ goal = null;
19673
+ cleared = true;
19674
+ }
19675
+ }
19676
+ const snapshot = this.snapshot(sessionId, goal);
19677
+ sendResult(requestId, snapshot);
19678
+ if (cleared)
19679
+ send({ jsonrpc: "2.0", method: "goal.cleared", params: snapshot });
19680
+ if (goal) {
19681
+ this.publish(goal);
19682
+ if (method === "goal.set" || method === "goal.resume") this.ready(goal);
19683
+ }
19684
+ }).catch((error) => {
19685
+ if (!(error instanceof GoalConflict) && !(error instanceof import_zod36.z.ZodError)) {
19686
+ if (method !== "goal.get") this.disarm();
19687
+ onError(error);
19688
+ }
19689
+ this.reject(requestId, error);
19690
+ });
19691
+ }
19692
+ reject(requestId, error) {
19693
+ const conflict = error instanceof GoalConflict ? error : null;
19694
+ sendError(requestId, {
19695
+ code: conflict?.reason === "busy" ? import_protocol13.RPC_ERROR_CODE.RUNTIME_BUSY : conflict || error instanceof import_zod36.z.ZodError ? import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
19696
+ message: conflict?.message ?? (error instanceof import_zod36.z.ZodError ? "Invalid goal parameters." : "Goal operation failed.")
19697
+ });
19698
+ }
19699
+ validateOffer(raw) {
19700
+ if (!this.enabled)
19701
+ throw new GoalConflict("Goals are unavailable on this connection.");
19702
+ const offer = readySchema.parse(raw);
19703
+ this.bound(offer.session_id);
19704
+ if (!this.offer || this.offer.continuation_id !== offer.continuation_id || this.offer.goal_id !== offer.goal_id || this.offer.revision !== offer.revision || this.offer.after_run_id !== offer.after_run_id)
19705
+ throw new GoalConflict("Continuation is stale or already used.");
19706
+ return offer;
19707
+ }
19708
+ canStart(run) {
19709
+ return this.owns(run.goal);
19710
+ }
19711
+ stopAfterStorageFailure(run) {
19712
+ if (this.owns(run.goal)) this.disarm();
19713
+ this.publish(run.goal);
19714
+ }
19715
+ async reserve(sessionId, runId, offer, compaction) {
19716
+ const saved = await this.store.read(sessionId).catch((error) => {
19717
+ if (offer || this.activation) throw error;
19718
+ return null;
19719
+ });
19720
+ const initial = saved?.entry;
19721
+ if (initial?.claim)
19722
+ throw new GoalConflict(
19723
+ "A goal run is already reserved for this session.",
19724
+ "busy"
19725
+ );
19726
+ if (initial?.goal.status !== "active" || !this.owns(initial.goal)) {
19727
+ if (offer) throw new GoalConflict("Goal is no longer active.");
19728
+ return;
19729
+ }
19730
+ this.identity ??= (0, import_storage18.getProcessIdentity)(process.pid, {
19731
+ canonicalEnvironment: true
19732
+ });
19733
+ const ownerIdentity = await this.identity;
19734
+ const run = await this.store.update(sessionId, (tx) => {
19735
+ if (offer) this.validateOffer(offer);
19736
+ const entry = tx.entry;
19737
+ if (entry?.claim)
19738
+ throw new GoalConflict(
19739
+ "A goal run is already reserved for this session.",
19740
+ "busy"
19741
+ );
19742
+ if (entry?.goal.status !== "active" || !this.owns(entry.goal)) {
19743
+ if (offer) throw new GoalConflict("Goal is no longer active.");
19744
+ return;
19745
+ }
19746
+ if (offer && (entry.goal.goal_id !== offer.goal_id || entry.goal.revision !== offer.revision || entry.goal.automatic_runs >= 3))
19747
+ throw new GoalConflict("Goal no longer accepts this continuation.");
19748
+ if (offer) {
19749
+ tx.consume(offer.continuation_id, entry.goal.goal_id, runId);
19750
+ entry.goal.automatic_runs += 1;
19751
+ }
19752
+ entry.claim = {
19753
+ run_id: runId,
19754
+ revision: entry.goal.revision,
19755
+ activation_id: entry.goal.activation_id,
19756
+ continuation_id: offer?.continuation_id,
19757
+ owner_pid: process.pid,
19758
+ owner_identity: ownerIdentity
19759
+ };
19760
+ return {
19761
+ goal: entry.goal,
19762
+ runId,
19763
+ continuationId: offer?.continuation_id,
19764
+ compaction
19765
+ };
19766
+ });
19767
+ if (run) {
19768
+ this.offer = null;
19769
+ this.activeRun = run;
19770
+ }
19771
+ return run;
19772
+ }
19773
+ tools(run) {
19774
+ return [
19775
+ (0, import_core35.defineTool)({
19776
+ name: "get_goal",
19777
+ description: "Read this run's session goal, including its objective, status, recorded tokens, and budget, or get {goal: null} if the run no longer holds the goal reservation.",
19778
+ input: import_zod36.z.object({}),
19779
+ execute: async () => {
19780
+ const entry = (await this.store.read(run.goal.session_id)).entry;
19781
+ const goal = entry?.claim?.run_id === run.runId ? entry.goal : null;
19782
+ return {
19783
+ type: "json",
19784
+ value: { goal },
19785
+ display_content: goal ? `Goal (${goal.status.replaceAll("_", " ")})
19786
+ ${goal.objective}` : "This run no longer holds the goal reservation."
19787
+ };
19788
+ }
19789
+ }),
19790
+ (0, import_core35.defineTool)({
19791
+ name: "update_goal",
19792
+ description: "Report verified goal completion or a blocker that prevents further work before giving your final answer.",
19793
+ input: import_zod36.z.object({
19794
+ status: import_zod36.z.enum(["complete", "blocked"]).describe(
19795
+ "Use complete after verifying every goal requirement, or blocked when a concrete obstacle prevents further work. Omit the tool call for ordinary progress."
19796
+ ),
19797
+ evidence: import_zod36.z.string().trim().min(1).max(2e3).describe(
19798
+ "For complete, state what you verified and the observed result. For blocked, state the obstacle and why it prevents further work."
19799
+ ),
19800
+ blocker_key: import_zod36.z.string().trim().min(1).max(200).optional().describe(
19801
+ "Required for blocked. Reuse the same short key for the same obstacle across runs. Three consecutive goal runs reporting the same key stop the goal."
19802
+ )
19803
+ }),
19804
+ execute: (report) => {
19805
+ if (report.status === "blocked" && !report.blocker_key)
19806
+ throw new Error("blocked requires blocker_key");
19807
+ if (!this.owns(run.goal)) throw new Error("Goal stopped or changed");
19808
+ run.report = report;
19809
+ const label = report.status === "complete" ? "Completion" : "Blocker";
19810
+ return {
19811
+ type: "json",
19812
+ value: {
19813
+ recorded: true,
19814
+ applied_after_successful_finalization: true
19815
+ },
19816
+ display_content: `${label} report recorded for evaluation after successful finalization.
19817
+ ${report.evidence}`
19818
+ };
19819
+ }
19820
+ })
19821
+ ];
19822
+ }
19823
+ observer(run) {
19824
+ return {
19825
+ started: async (seq) => this.store.update(run.goal.session_id, ({ entry }) => {
19826
+ if (entry?.claim?.run_id !== run.runId)
19827
+ throw new Error("Goal run reservation missing");
19828
+ entry.claim.pending_seq = seq;
19829
+ }),
19830
+ completed: async (seq, usage, uncertain) => this.store.update(run.goal.session_id, ({ entry }) => {
19831
+ if (entry?.claim?.run_id !== run.runId)
19832
+ throw new Error("Goal run reservation missing");
19833
+ const claim = entry.claim;
19834
+ if (claim.accounted_seq !== void 0 && claim.accounted_seq >= seq)
19835
+ return;
19836
+ if (claim.pending_seq !== seq)
19837
+ throw new Error("Goal invocation is missing its reservation");
19838
+ const input = usage?.input_tokens;
19839
+ const cached = usage?.input_cached_tokens ?? 0;
19840
+ const output = usage?.output_tokens;
19841
+ const tokens = typeof input === "number" && typeof output === "number" && [input, cached, output].every(
19842
+ (value) => Number.isSafeInteger(value) && value >= 0
19843
+ ) && cached <= input ? input - cached + output : null;
19844
+ if (tokens !== null && Number.isSafeInteger(entry.goal.tokens_used + tokens))
19845
+ entry.goal.tokens_used += tokens;
19846
+ else entry.goal.usage_known = false;
19847
+ if (uncertain) entry.goal.usage_known = false;
19848
+ entry.goal.updated_at = stamp();
19849
+ claim.pending_seq = void 0;
19850
+ claim.accounted_seq = seq;
19851
+ })
19852
+ };
19853
+ }
19854
+ async finish(run, outcome, saved) {
19855
+ if (this.activeRun?.runId === run.runId) this.activeRun = void 0;
19856
+ const goal = await this.store.update(run.goal.session_id, ({ entry }) => {
19857
+ if (entry?.claim?.run_id !== run.runId) return null;
19858
+ if (entry.claim.pending_seq !== void 0) entry.goal.usage_known = false;
19859
+ entry.claim = void 0;
19860
+ const goal2 = entry.goal;
19861
+ if (goal2.status !== "active" || goal2.revision !== run.goal.revision || !this.owns(goal2))
19862
+ return goal2;
19863
+ if (!saved) transition(goal2, "paused", "checkpoint_failed");
19864
+ else if (outcome !== "completed")
19865
+ transition(
19866
+ goal2,
19867
+ "paused",
19868
+ outcome === "error" ? "run_error" : "interrupted"
19869
+ );
19870
+ else if (run.compaction) stopForBudget(goal2);
19871
+ else if (run.report?.status === "complete") transition(goal2, "complete");
19872
+ else {
19873
+ const key = run.report?.blocker_key;
19874
+ entry.blocker = key && run.report?.status === "blocked" ? {
19875
+ key,
19876
+ runs: entry.blocker?.key === key ? entry.blocker.runs + 1 : 1
19877
+ } : void 0;
19878
+ if ((entry.blocker?.runs ?? 0) >= 3) {
19879
+ transition(goal2, "blocked", "blocker");
19880
+ goal2.stop_detail = run.report?.evidence;
19881
+ } else if (!stopForBudget(goal2) && goal2.automatic_runs >= 3)
19882
+ transition(goal2, "paused", "turn_limit");
19883
+ }
19884
+ return goal2;
19885
+ });
19886
+ if (goal) {
19887
+ if (goal.status !== "active" && this.owns(goal)) this.disarm();
19888
+ this.publish(goal);
19889
+ }
19890
+ return goal;
19891
+ }
19892
+ };
19893
+
19894
+ // src/rpc/run-debug.ts
19895
+ var import_core36 = require("@codelia/core");
19364
19896
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
19365
19897
  var DEBUG_MAX_LOG_CHARS = 2e4;
19366
19898
  var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
@@ -19378,7 +19910,7 @@ var stringifyUnknown = (value) => {
19378
19910
  }
19379
19911
  };
19380
19912
  var contentToDebugText = (content, maxChars) => {
19381
- const text = (0, import_core35.stringifyContent)(content, {
19913
+ const text = (0, import_core36.stringifyContent)(content, {
19382
19914
  mode: "log",
19383
19915
  joiner: "\n",
19384
19916
  includeOtherPayload: true
@@ -19962,7 +20494,8 @@ var createRunHandlers = ({
19962
20494
  runEventStoreFactory,
19963
20495
  sessionStateStore,
19964
20496
  appendSession,
19965
- beforeRunStart
20497
+ beforeRunStart,
20498
+ goalStore
19966
20499
  }) => {
19967
20500
  let activeRunAbort = null;
19968
20501
  const steerAttachments = /* @__PURE__ */ new Map();
@@ -19971,6 +20504,18 @@ var createRunHandlers = ({
19971
20504
  steerAttachments.delete(steerId);
19972
20505
  };
19973
20506
  let runStartQueue = Promise.resolve();
20507
+ const goals = goalStore ? new GoalController(
20508
+ state,
20509
+ goalStore,
20510
+ sessionStateStore,
20511
+ () => resolveSessionWorkspaceRoot(state)
20512
+ ) : void 0;
20513
+ const serializeAdmission = (action) => {
20514
+ const admit = () => state.withAdmissionLock(action);
20515
+ const queued = runStartQueue.then(admit);
20516
+ runStartQueue = queued.catch(() => void 0);
20517
+ return queued;
20518
+ };
19974
20519
  let runSteerQueue = Promise.resolve();
19975
20520
  let sessionOpenSettled = Promise.resolve();
19976
20521
  const normalizeRuntimeAgentHistory = (label, runtimeAgent) => {
@@ -20029,24 +20574,34 @@ var createRunHandlers = ({
20029
20574
  ...final !== void 0 ? { final } : {}
20030
20575
  });
20031
20576
  };
20032
- const handleRunStart = (id, params) => {
20577
+ const handleRunStart = (id2, params, continuation) => {
20033
20578
  let admittedRunId = null;
20034
20579
  let responseSent = false;
20580
+ let admittedGoal;
20035
20581
  const run = async () => {
20582
+ let offer;
20583
+ if (continuation !== void 0 && goals) {
20584
+ try {
20585
+ offer = goals.validateOffer(continuation);
20586
+ } catch (error) {
20587
+ goals.reject(id2, error);
20588
+ return;
20589
+ }
20590
+ }
20036
20591
  let initialInput;
20037
20592
  try {
20038
20593
  initialInput = normalizeRunInput(params.input);
20039
20594
  } catch (error) {
20040
- sendError(id, {
20041
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20595
+ sendError(id2, {
20596
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20042
20597
  message: String(error)
20043
20598
  });
20044
20599
  return;
20045
20600
  }
20046
20601
  const attachmentIds = runAttachmentIds(initialInput);
20047
20602
  if (params.force_compaction && attachmentIds.length > 0) {
20048
- sendError(id, {
20049
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20603
+ sendError(id2, {
20604
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20050
20605
  message: "A compaction run cannot admit new attachments"
20051
20606
  });
20052
20607
  return;
@@ -20055,16 +20610,16 @@ var createRunHandlers = ({
20055
20610
  try {
20056
20611
  await beforeRunStart();
20057
20612
  } catch (error) {
20058
- sendError(id, {
20059
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20613
+ sendError(id2, {
20614
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20060
20615
  message: `startup onboarding failed: ${String(error)}`
20061
20616
  });
20062
20617
  return;
20063
20618
  }
20064
20619
  }
20065
20620
  if (state.activeRunId) {
20066
- sendError(id, {
20067
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_BUSY,
20621
+ sendError(id2, {
20622
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
20068
20623
  message: "runtime busy"
20069
20624
  });
20070
20625
  return;
@@ -20080,15 +20635,15 @@ var createRunHandlers = ({
20080
20635
  try {
20081
20636
  resumeState = await sessionStateStore.load(requestedSessionId);
20082
20637
  } catch (error) {
20083
- sendError(id, {
20084
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20638
+ sendError(id2, {
20639
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20085
20640
  message: `session load failed: ${String(error)}`
20086
20641
  });
20087
20642
  return;
20088
20643
  }
20089
20644
  if (!resumeState) {
20090
- sendError(id, {
20091
- code: import_protocol13.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20645
+ sendError(id2, {
20646
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20092
20647
  message: "session not found"
20093
20648
  });
20094
20649
  return;
@@ -20098,8 +20653,8 @@ var createRunHandlers = ({
20098
20653
  try {
20099
20654
  resumeState = await sessionStateStore.load(state.sessionId);
20100
20655
  } catch (error) {
20101
- sendError(id, {
20102
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20656
+ sendError(id2, {
20657
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20103
20658
  message: `session reload failed: ${String(error)}`
20104
20659
  });
20105
20660
  return;
@@ -20109,8 +20664,8 @@ var createRunHandlers = ({
20109
20664
  }
20110
20665
  }
20111
20666
  if (resumeState?.meta?.codelia_subagent) {
20112
- sendError(id, {
20113
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20667
+ sendError(id2, {
20668
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20114
20669
  message: "Delegated sessions cannot be resumed as a root run"
20115
20670
  });
20116
20671
  return;
@@ -20133,8 +20688,8 @@ var createRunHandlers = ({
20133
20688
  }
20134
20689
  } catch (error) {
20135
20690
  state.sessionModelOverride = previousModelOverride;
20136
- sendError(id, {
20137
- code: error instanceof AttachmentAdmissionError ? import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20691
+ sendError(id2, {
20692
+ code: error instanceof AttachmentAdmissionError ? import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20138
20693
  message: error instanceof Error ? error.message : String(error)
20139
20694
  });
20140
20695
  return;
@@ -20150,8 +20705,8 @@ var createRunHandlers = ({
20150
20705
  });
20151
20706
  } catch (error) {
20152
20707
  state.sessionModelOverride = previousModelOverride;
20153
- sendError(id, {
20154
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20708
+ sendError(id2, {
20709
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20155
20710
  message: String(error)
20156
20711
  });
20157
20712
  return;
@@ -20163,8 +20718,8 @@ var createRunHandlers = ({
20163
20718
  });
20164
20719
  } catch {
20165
20720
  state.sessionModelOverride = previousModelOverride;
20166
- sendError(id, {
20167
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20721
+ sendError(id2, {
20722
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20168
20723
  message: "Could not claim the attachments for this conversation. Upload them again."
20169
20724
  });
20170
20725
  return;
@@ -20197,6 +20752,7 @@ var createRunHandlers = ({
20197
20752
  state.sessionId = sessionId;
20198
20753
  }
20199
20754
  const switchedSession = previousSessionId !== sessionId;
20755
+ if (switchedSession) goals?.disarm();
20200
20756
  if (loadedSessionState && resumeState) {
20201
20757
  const restoredTodos = readTodosFromSessionMeta(resumeState.meta);
20202
20758
  if (restoredTodos.length > 0) {
@@ -20216,9 +20772,33 @@ var createRunHandlers = ({
20216
20772
  ...runMeta
20217
20773
  };
20218
20774
  }
20775
+ if (goals?.enabled) {
20776
+ try {
20777
+ admittedGoal = await goals.reserve(
20778
+ sessionId,
20779
+ runId,
20780
+ offer,
20781
+ params.force_compaction === true
20782
+ );
20783
+ if (admittedGoal && !goals.canStart(admittedGoal)) {
20784
+ await goals.finish(admittedGoal, "cancelled", true);
20785
+ throw new Error("Goal was paused before launch.");
20786
+ }
20787
+ } catch (error) {
20788
+ goals.reject(id2, error);
20789
+ return;
20790
+ }
20791
+ }
20792
+ const goalTools = goals && admittedGoal && !admittedGoal.compaction ? goals.tools(admittedGoal) : [];
20793
+ if (admittedGoal && state.tools?.some(
20794
+ (tool) => goalTools.some((goalTool) => goalTool.name === tool.name)
20795
+ ))
20796
+ throw new Error("Goal tool name conflicts with a runtime tool.");
20219
20797
  state.autoApprovedClientToolNames = new Set(
20220
20798
  (params.tools ?? []).filter((tool) => tool.approval === "never").map((tool) => tool.name)
20221
20799
  );
20800
+ for (const tool of goalTools)
20801
+ state.autoApprovedClientToolNames.add(tool.name);
20222
20802
  const startedAt = nowIso5();
20223
20803
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
20224
20804
  admittedRunId = runId;
@@ -20403,6 +20983,15 @@ var createRunHandlers = ({
20403
20983
  });
20404
20984
  appendSession({
20405
20985
  type: "run.start",
20986
+ ...offer ? { source: "goal" } : {},
20987
+ ...admittedGoal ? {
20988
+ goal: {
20989
+ goal_id: admittedGoal.goal.goal_id,
20990
+ revision: admittedGoal.goal.revision,
20991
+ activation_id: admittedGoal.goal.activation_id,
20992
+ ...offer ? { continuation_id: offer.continuation_id } : {}
20993
+ }
20994
+ } : {},
20406
20995
  run_id: runId,
20407
20996
  session_id: sessionId,
20408
20997
  ts: nowIso5(),
@@ -20422,13 +21011,14 @@ var createRunHandlers = ({
20422
21011
  session_id: sessionId,
20423
21012
  ...sessionStore.filePath ? { session_log_path: sessionStore.filePath } : {}
20424
21013
  };
20425
- sendResult(id, result);
21014
+ sendResult(id2, result);
20426
21015
  responseSent = true;
20427
21016
  log2(`run.start ${runId}`);
20428
21017
  emitRunStatus(runId, "running");
20429
21018
  void (async () => {
20430
21019
  let finalResponse;
20431
- let sessionSaveChain = Promise.resolve();
21020
+ let outcome = "error";
21021
+ let sessionSaveChain = Promise.resolve(true);
20432
21022
  let lastSessionSaveAt = 0;
20433
21023
  const polledUnconfirmedSteers = [];
20434
21024
  const emitRunSummaryDiagnostics = () => {
@@ -20458,9 +21048,9 @@ var createRunHandlers = ({
20458
21048
  }
20459
21049
  return { unconsumed_steer_ids: unconsumedSteerIds };
20460
21050
  };
20461
- const queueSessionSave = async (reason) => {
21051
+ const queueSessionSave = (reason) => {
20462
21052
  sessionSaveChain = sessionSaveChain.then(async () => {
20463
- if (!sessionId) return;
21053
+ if (!sessionId) return false;
20464
21054
  const messages = runtimeAgent.getHistoryMessages();
20465
21055
  const snapshotMessages = normalizeToolCallHistory(
20466
21056
  stripStartupSystemMessages(
@@ -20501,10 +21091,12 @@ var createRunHandlers = ({
20501
21091
  await sessionStateStore.save(snapshot);
20502
21092
  state.sessionMeta = sessionMetaWithResumeContext ?? null;
20503
21093
  logRunDebug(log2, runId, `session.save ${reason}`);
21094
+ return true;
20504
21095
  }).catch((error) => {
20505
21096
  log2(`Error: session-state save failed: ${String(error)}`);
21097
+ return false;
20506
21098
  });
20507
- await sessionSaveChain;
21099
+ return sessionSaveChain;
20508
21100
  };
20509
21101
  const maybeDebouncedSessionSave = () => {
20510
21102
  const now = Date.now();
@@ -20571,7 +21163,17 @@ var createRunHandlers = ({
20571
21163
  pollMessages,
20572
21164
  signal: runAbortController.signal,
20573
21165
  forceCompaction: params.force_compaction,
20574
- tools: clientTools,
21166
+ tools: goalTools.length ? [
21167
+ ...goalTools,
21168
+ ...(clientTools ?? []).filter(
21169
+ (tool) => !goalTools.some((owned) => owned.name === tool.name)
21170
+ )
21171
+ ] : clientTools,
21172
+ ...goals && admittedGoal ? {
21173
+ runContext: `${offer ? "Continue work on the session goal" : "Session goal"} (follow newer user instructions): ${JSON.stringify(admittedGoal.goal.objective)}.`,
21174
+ runtimeInitiated: Boolean(offer),
21175
+ modelCallObserver: goals.observer(admittedGoal)
21176
+ } : {},
20575
21177
  toolChoice: params.tool_choice,
20576
21178
  ...streamDeltas ? { streamDeltas: true } : {}
20577
21179
  })) {
@@ -20645,6 +21247,7 @@ var createRunHandlers = ({
20645
21247
  await queueSessionSave("terminal");
20646
21248
  emitRunSummaryDiagnostics();
20647
21249
  const status = state.cancelRequested ? "cancelled" : "completed";
21250
+ outcome = status;
20648
21251
  const terminalExtras = buildTerminalStatusExtras();
20649
21252
  emitRunStatus(runId, status, void 0, void 0, terminalExtras);
20650
21253
  emitRunEnd(
@@ -20657,6 +21260,7 @@ var createRunHandlers = ({
20657
21260
  deltaCoalescer?.dispose();
20658
21261
  const err = error instanceof Error ? error : new Error(String(error));
20659
21262
  if (state.cancelRequested || isAbortLikeError(err)) {
21263
+ outcome = "cancelled";
20660
21264
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
20661
21265
  await queueSessionSave("cancelled");
20662
21266
  emitRunSummaryDiagnostics();
@@ -20697,40 +21301,53 @@ var createRunHandlers = ({
20697
21301
  if (state.cancelRequested) {
20698
21302
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
20699
21303
  }
20700
- await queueSessionSave("finally");
21304
+ const saved = await queueSessionSave("finally");
21305
+ const goalRun = admittedGoal;
21306
+ const finalOutcome = state.cancelRequested ? "cancelled" : outcome === "completed" && finalResponse === void 0 ? "error" : outcome;
21307
+ const goal = goals && goalRun ? await goals.finish(goalRun, finalOutcome, saved).catch((error) => {
21308
+ goals.stopAfterStorageFailure(goalRun);
21309
+ log2(`goal accounting failed: ${String(error)}`);
21310
+ return null;
21311
+ }) : null;
20701
21312
  if (activeRunAbort?.runId === runId) {
20702
21313
  activeRunAbort = null;
20703
21314
  }
20704
21315
  state.finishRun(runId);
21316
+ if (goal) goals?.ready(goal, runId);
20705
21317
  }
20706
21318
  })();
20707
21319
  };
20708
- const admit = () => state.withAdmissionLock(run);
20709
- const queued = runStartQueue.then(admit, admit).catch((error) => {
20710
- if (admittedRunId) {
20711
- const runId = admittedRunId;
20712
- if (activeRunAbort?.runId === runId) activeRunAbort = null;
20713
- state.finishRun(runId);
20714
- if (responseSent) {
20715
- try {
20716
- sendRunStatus(state, runId, "error", "runtime start failed");
20717
- } catch {
21320
+ return serializeAdmission(async () => {
21321
+ try {
21322
+ await run();
21323
+ return;
21324
+ } catch (error) {
21325
+ if (goals && admittedGoal) {
21326
+ await goals.finish(admittedGoal, "error", true).catch((cleanupError) => {
21327
+ goals.disarm();
21328
+ log2(`goal admission cleanup failed: ${String(cleanupError)}`);
21329
+ });
21330
+ }
21331
+ if (admittedRunId) {
21332
+ const runId = admittedRunId;
21333
+ if (activeRunAbort?.runId === runId) activeRunAbort = null;
21334
+ state.finishRun(runId);
21335
+ if (responseSent) {
21336
+ try {
21337
+ sendRunStatus(state, runId, "error", "runtime start failed");
21338
+ } catch {
21339
+ }
20718
21340
  }
20719
21341
  }
21342
+ throw error;
20720
21343
  }
20721
- throw error;
20722
21344
  });
20723
- runStartQueue = queued.then(
20724
- () => void 0,
20725
- () => void 0
20726
- );
20727
- return queued;
20728
21345
  };
20729
- const handleRunSteer = (id, params) => {
21346
+ const handleRunSteer = (id2, params) => {
20730
21347
  const runId = typeof params?.run_id === "string" ? params.run_id.trim() : "";
20731
21348
  if (!runId) {
20732
- sendError(id, {
20733
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21349
+ sendError(id2, {
21350
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20734
21351
  message: "run_id is required"
20735
21352
  });
20736
21353
  return Promise.resolve();
@@ -20739,15 +21356,15 @@ var createRunHandlers = ({
20739
21356
  try {
20740
21357
  initialInput = normalizeRunInput(params.input, "run.steer");
20741
21358
  } catch (error) {
20742
- sendError(id, {
20743
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21359
+ sendError(id2, {
21360
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20744
21361
  message: String(error)
20745
21362
  });
20746
21363
  return Promise.resolve();
20747
21364
  }
20748
21365
  if (isRunInputEmpty(initialInput)) {
20749
- sendError(id, {
20750
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21366
+ sendError(id2, {
21367
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20751
21368
  message: "run.steer input must not be empty"
20752
21369
  });
20753
21370
  return Promise.resolve();
@@ -20755,8 +21372,8 @@ var createRunHandlers = ({
20755
21372
  const clientSteerId = typeof params.client_steer_id === "string" && params.client_steer_id.trim() ? params.client_steer_id.trim() : void 0;
20756
21373
  const admitSteer = async () => {
20757
21374
  if (!state.canSteerRun(runId)) {
20758
- sendError(id, {
20759
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21375
+ sendError(id2, {
21376
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20760
21377
  message: "active run not found"
20761
21378
  });
20762
21379
  return;
@@ -20781,8 +21398,8 @@ var createRunHandlers = ({
20781
21398
  if (state.prepareRunImages)
20782
21399
  normalizedInput = await state.prepareRunImages(normalizedInput);
20783
21400
  } catch (error) {
20784
- sendError(id, {
20785
- code: error instanceof AttachmentAdmissionError ? import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21401
+ sendError(id2, {
21402
+ code: error instanceof AttachmentAdmissionError ? import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20786
21403
  message: error instanceof Error ? error.message : String(error)
20787
21404
  });
20788
21405
  return;
@@ -20795,8 +21412,8 @@ var createRunHandlers = ({
20795
21412
  sessionId
20796
21413
  );
20797
21414
  } catch {
20798
- sendError(id, {
20799
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21415
+ sendError(id2, {
21416
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20800
21417
  message: "Could not retain the attachments for this conversation. Upload them again."
20801
21418
  });
20802
21419
  return;
@@ -20804,8 +21421,8 @@ var createRunHandlers = ({
20804
21421
  }
20805
21422
  if (!state.canSteerRun(runId)) {
20806
21423
  releaseAttachments?.();
20807
- sendError(id, {
20808
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21424
+ sendError(id2, {
21425
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20809
21426
  message: "active run ended before steer could be queued"
20810
21427
  });
20811
21428
  return;
@@ -20820,7 +21437,7 @@ var createRunHandlers = ({
20820
21437
  ids: attachmentIds,
20821
21438
  release: releaseAttachments
20822
21439
  });
20823
- sendResult(id, {
21440
+ sendResult(id2, {
20824
21441
  ok: true,
20825
21442
  steer_id: steerId
20826
21443
  });
@@ -20833,74 +21450,108 @@ var createRunHandlers = ({
20833
21450
  );
20834
21451
  return queued;
20835
21452
  };
20836
- const handleRunCancel = (id, params) => {
20837
- if (state.cancelRun(params.run_id)) {
20838
- if (activeRunAbort?.runId === params.run_id) {
20839
- activeRunAbort.controller.abort(
20840
- new Error(params.reason ?? "cancelled by user")
20841
- );
20842
- }
20843
- sendResult(id, { ok: true });
21453
+ const interruptRun = (runId, reason = "cancelled by user") => {
21454
+ if (!state.cancelRun(runId)) return false;
21455
+ if (activeRunAbort?.runId === runId)
21456
+ activeRunAbort.controller.abort(new Error(reason));
21457
+ return true;
21458
+ };
21459
+ const handleGoal = (id2, method, raw) => {
21460
+ if (!goals?.enabled) {
21461
+ sendError(id2, {
21462
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21463
+ message: "Goals are unavailable on this connection."
21464
+ });
21465
+ return Promise.resolve();
21466
+ }
21467
+ if (method === "goal.continue") {
21468
+ const params = raw;
21469
+ return handleRunStart(
21470
+ id2,
21471
+ {
21472
+ input: { type: "text", text: "" },
21473
+ session_id: params?.session_id,
21474
+ tools: params?.tools,
21475
+ ui_context: params?.ui_context
21476
+ },
21477
+ raw ?? {}
21478
+ );
21479
+ }
21480
+ return goals.handle(
21481
+ id2,
21482
+ method,
21483
+ raw,
21484
+ serializeAdmission,
21485
+ interruptRun,
21486
+ (error) => log2(`goal operation failed: ${String(error)}`)
21487
+ );
21488
+ };
21489
+ const handleRunCancel = (id2, params) => {
21490
+ if (interruptRun(params.run_id, params.reason)) {
21491
+ sendResult(id2, { ok: true });
20844
21492
  log2(`run.cancel ${params.run_id} (${params.reason ?? "no reason"})`);
20845
21493
  return;
20846
21494
  }
20847
- sendError(id, {
20848
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21495
+ sendError(id2, {
21496
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20849
21497
  message: "run not found"
20850
21498
  });
20851
21499
  };
20852
- const handleSessionOpen = (id, params) => {
21500
+ const handleSessionOpen = (id2, params) => {
21501
+ const sessionId = params?.session_id?.trim();
21502
+ if (sessionId && sessionId !== state.sessionId && !state.activeRunId)
21503
+ goals?.disarm();
20853
21504
  const open3 = async () => {
20854
- const sessionId = params?.session_id?.trim();
20855
21505
  if (!sessionId) {
20856
- sendError(id, {
20857
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21506
+ sendError(id2, {
21507
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20858
21508
  message: "session_id is required"
20859
21509
  });
20860
21510
  return;
20861
21511
  }
20862
21512
  if (state.activeRunId) {
20863
- sendError(id, {
20864
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_BUSY,
21513
+ sendError(id2, {
21514
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
20865
21515
  message: "runtime busy"
20866
21516
  });
20867
21517
  return;
20868
21518
  }
20869
21519
  if (sessionId === state.sessionId) {
20870
- sendResult(id, { session_id: sessionId });
21520
+ sendResult(id2, { session_id: sessionId });
20871
21521
  return;
20872
21522
  }
20873
21523
  let opened;
20874
21524
  try {
20875
21525
  opened = await sessionStateStore.load(sessionId);
20876
21526
  } catch (error) {
20877
- sendError(id, {
20878
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
21527
+ sendError(id2, {
21528
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20879
21529
  message: `session load failed: ${String(error)}`
20880
21530
  });
20881
21531
  return;
20882
21532
  }
20883
21533
  if (!opened) {
20884
- sendError(id, {
20885
- code: import_protocol13.RPC_ERROR_CODE.SESSION_NOT_FOUND,
21534
+ sendError(id2, {
21535
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20886
21536
  message: "session not found"
20887
21537
  });
20888
21538
  return;
20889
21539
  }
20890
21540
  if (opened.meta?.codelia_subagent) {
20891
- sendError(id, {
20892
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21541
+ sendError(id2, {
21542
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20893
21543
  message: "Delegated sessions cannot be opened as a root session"
20894
21544
  });
20895
21545
  return;
20896
21546
  }
20897
21547
  state.attachments?.discardDraft();
21548
+ goals?.disarm();
20898
21549
  state.sessionId = sessionId;
20899
21550
  state.sessionMeta = toMetaObject(opened.meta) ?? null;
20900
21551
  state.sessionAppend = null;
20901
21552
  applySessionModelOverrideFromMeta(state, opened.meta);
20902
21553
  state.agent = null;
20903
- sendResult(id, { session_id: sessionId });
21554
+ sendResult(id2, { session_id: sessionId });
20904
21555
  log2(`session.open ${sessionId}`);
20905
21556
  };
20906
21557
  const queued = runStartQueue.then(open3, open3);
@@ -20913,6 +21564,7 @@ var createRunHandlers = ({
20913
21564
  };
20914
21565
  const afterSessionOpen = (task) => sessionOpenSettled.then(task);
20915
21566
  return {
21567
+ handleGoal,
20916
21568
  handleRunStart,
20917
21569
  handleRunSteer,
20918
21570
  handleRunCancel,
@@ -20922,25 +21574,25 @@ var createRunHandlers = ({
20922
21574
  };
20923
21575
 
20924
21576
  // src/rpc/session-lifecycle.ts
20925
- var import_protocol14 = require("@codelia/protocol");
20926
- var createSessionUpdateHandler = (options) => async (id, params) => {
21577
+ var import_protocol15 = require("@codelia/protocol");
21578
+ var createSessionUpdateHandler = (options) => async (id2, params) => {
20927
21579
  if (!options.sessions.updateMetadata) {
20928
- sendError(id, {
20929
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21580
+ sendError(id2, {
21581
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20930
21582
  message: "Session lifecycle updates are unavailable"
20931
21583
  });
20932
21584
  return;
20933
21585
  }
20934
21586
  if (!params || typeof params.session_id !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(params.session_id) || params.pinned !== void 0 && typeof params.pinned !== "boolean" || params.archived !== void 0 && typeof params.archived !== "boolean" || params.pinned === void 0 && params.archived === void 0) {
20935
- sendError(id, {
20936
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21587
+ sendError(id2, {
21588
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20937
21589
  message: "Expected session_id and a boolean pinned or archived update"
20938
21590
  });
20939
21591
  return;
20940
21592
  }
20941
21593
  if (params.archived && options.state.activeRunId && options.state.sessionId === params.session_id) {
20942
- sendError(id, {
20943
- code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
21594
+ sendError(id2, {
21595
+ code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
20944
21596
  message: "Wait for the active run before archiving this session"
20945
21597
  });
20946
21598
  return;
@@ -20958,10 +21610,10 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
20958
21610
  }
20959
21611
  }
20960
21612
  const result = { session };
20961
- sendResult(id, result);
21613
+ sendResult(id2, result);
20962
21614
  } catch (error) {
20963
- sendError(id, {
20964
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21615
+ sendError(id2, {
21616
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20965
21617
  message: `Session update failed: ${String(error)}`
20966
21618
  });
20967
21619
  }
@@ -20969,8 +21621,8 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
20969
21621
 
20970
21622
  // src/rpc/shell.ts
20971
21623
  var import_node_path24 = __toESM(require("path"), 1);
20972
- var import_protocol15 = require("@codelia/protocol");
20973
- var import_storage18 = require("@codelia/storage");
21624
+ var import_protocol16 = require("@codelia/protocol");
21625
+ var import_storage19 = require("@codelia/storage");
20974
21626
  var COMMAND_PREVIEW_CHARS = 400;
20975
21627
  var DEFAULT_TRUNCATED = {
20976
21628
  stdout: false,
@@ -21025,7 +21677,7 @@ var parseShellOutputRequest = (params) => {
21025
21677
  if (!taskId) {
21026
21678
  return {
21027
21679
  error: {
21028
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21680
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21029
21681
  message: "task_id is required"
21030
21682
  }
21031
21683
  };
@@ -21033,7 +21685,7 @@ var parseShellOutputRequest = (params) => {
21033
21685
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
21034
21686
  return {
21035
21687
  error: {
21036
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21688
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21037
21689
  message: "stream must be stdout or stderr"
21038
21690
  }
21039
21691
  };
@@ -21041,7 +21693,7 @@ var parseShellOutputRequest = (params) => {
21041
21693
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
21042
21694
  return {
21043
21695
  error: {
21044
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21696
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21045
21697
  message: "line_number cannot be combined with offset or limit"
21046
21698
  }
21047
21699
  };
@@ -21049,7 +21701,7 @@ var parseShellOutputRequest = (params) => {
21049
21701
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
21050
21702
  return {
21051
21703
  error: {
21052
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21704
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21053
21705
  message: "char_offset/char_limit require line_number"
21054
21706
  }
21055
21707
  };
@@ -21057,7 +21709,7 @@ var parseShellOutputRequest = (params) => {
21057
21709
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
21058
21710
  return {
21059
21711
  error: {
21060
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21712
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21061
21713
  message: "offset must be a non-negative number"
21062
21714
  }
21063
21715
  };
@@ -21065,7 +21717,7 @@ var parseShellOutputRequest = (params) => {
21065
21717
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
21066
21718
  return {
21067
21719
  error: {
21068
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21720
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21069
21721
  message: "limit must be a positive number"
21070
21722
  }
21071
21723
  };
@@ -21073,7 +21725,7 @@ var parseShellOutputRequest = (params) => {
21073
21725
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
21074
21726
  return {
21075
21727
  error: {
21076
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21728
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21077
21729
  message: "line_number must be a positive number"
21078
21730
  }
21079
21731
  };
@@ -21081,7 +21733,7 @@ var parseShellOutputRequest = (params) => {
21081
21733
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
21082
21734
  return {
21083
21735
  error: {
21084
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21736
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21085
21737
  message: "char_offset must be a non-negative number"
21086
21738
  }
21087
21739
  };
@@ -21089,7 +21741,7 @@ var parseShellOutputRequest = (params) => {
21089
21741
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
21090
21742
  return {
21091
21743
  error: {
21092
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21744
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21093
21745
  message: "char_limit must be a positive number"
21094
21746
  }
21095
21747
  };
@@ -21143,7 +21795,7 @@ var parseTaskId = (value) => {
21143
21795
  var toTaskRpcError = (error) => {
21144
21796
  if (!(error instanceof TaskManagerError)) {
21145
21797
  return {
21146
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21798
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21147
21799
  message: String(error)
21148
21800
  };
21149
21801
  }
@@ -21152,24 +21804,24 @@ var toTaskRpcError = (error) => {
21152
21804
  case "invalid_task_id":
21153
21805
  case "unsupported_workspace_mode":
21154
21806
  return {
21155
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21807
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21156
21808
  message: error.message
21157
21809
  };
21158
21810
  case "manager_shutting_down":
21159
21811
  return {
21160
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
21812
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_BUSY,
21161
21813
  message: error.message
21162
21814
  };
21163
21815
  default:
21164
21816
  return {
21165
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21817
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21166
21818
  message: error.message
21167
21819
  };
21168
21820
  }
21169
21821
  };
21170
- var sendTaskError = (id, error) => {
21822
+ var sendTaskError = (id2, error) => {
21171
21823
  const rpcError = toTaskRpcError(error);
21172
- sendError(id, rpcError);
21824
+ sendError(id2, rpcError);
21173
21825
  };
21174
21826
  var requireShellTask = async (taskManager, taskId) => {
21175
21827
  const task = await taskManager.status(taskId);
@@ -21186,7 +21838,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
21186
21838
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21187
21839
  return {
21188
21840
  error: {
21189
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21841
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21190
21842
  message: "timeout_seconds must be a positive number"
21191
21843
  }
21192
21844
  };
@@ -21200,7 +21852,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
21200
21852
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
21201
21853
  return {
21202
21854
  error: {
21203
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21855
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21204
21856
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
21205
21857
  }
21206
21858
  };
@@ -21214,7 +21866,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
21214
21866
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21215
21867
  return {
21216
21868
  error: {
21217
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21869
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21218
21870
  message: "wait_timeout_seconds must be a positive number"
21219
21871
  }
21220
21872
  };
@@ -21222,7 +21874,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
21222
21874
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
21223
21875
  return {
21224
21876
  error: {
21225
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21877
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21226
21878
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
21227
21879
  }
21228
21880
  };
@@ -21237,7 +21889,7 @@ var parseShellStartRequest = (state, params, options) => {
21237
21889
  if (!command) {
21238
21890
  return {
21239
21891
  error: {
21240
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21892
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21241
21893
  message: "command is required"
21242
21894
  }
21243
21895
  };
@@ -21253,7 +21905,7 @@ var parseShellStartRequest = (state, params, options) => {
21253
21905
  if (!cwd) {
21254
21906
  return {
21255
21907
  error: {
21256
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21908
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21257
21909
  message: "cwd is outside sandbox root"
21258
21910
  }
21259
21911
  };
@@ -21273,7 +21925,7 @@ var createShellHandlers = ({
21273
21925
  outputCache
21274
21926
  }) => {
21275
21927
  const shellTaskManager = taskManager ?? new TaskManager();
21276
- const shellOutputCache = outputCache ?? new import_storage18.ToolOutputCacheStoreImpl();
21928
+ const shellOutputCache = outputCache ?? new import_storage19.ToolOutputCacheStoreImpl();
21277
21929
  const activeShellWaits = /* @__PURE__ */ new Map();
21278
21930
  const registerActiveShellWait = (taskId, wait) => {
21279
21931
  const waits = activeShellWaits.get(taskId) ?? /* @__PURE__ */ new Set();
@@ -21315,40 +21967,40 @@ var createShellHandlers = ({
21315
21967
  );
21316
21968
  return { task, commandPreview: parsed.commandPreview };
21317
21969
  };
21318
- const handleShellExec = async (id, params) => {
21970
+ const handleShellExec = async (id2, params) => {
21319
21971
  try {
21320
21972
  const { task, commandPreview } = await spawnShell(params, "shell.exec");
21321
21973
  const finished = await shellTaskManager.wait(task.task_id);
21322
21974
  const result = toShellExecResult(commandPreview, finished.result);
21323
- sendResult(id, result);
21975
+ sendResult(id2, result);
21324
21976
  log2(
21325
21977
  `shell.exec.done origin=ui_bang duration_ms=${result.duration_ms} exit_code=${String(result.exit_code)} signal=${result.signal ?? "-"}`
21326
21978
  );
21327
21979
  } catch (error) {
21328
21980
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
21329
- sendError(id, error);
21981
+ sendError(id2, error);
21330
21982
  return;
21331
21983
  }
21332
- sendTaskError(id, error);
21984
+ sendTaskError(id2, error);
21333
21985
  }
21334
21986
  };
21335
- const handleShellStart = async (id, params) => {
21987
+ const handleShellStart = async (id2, params) => {
21336
21988
  try {
21337
21989
  const { task } = await spawnShell(params, "shell.start");
21338
- sendResult(id, toShellTaskInfo(task));
21990
+ sendResult(id2, toShellTaskInfo(task));
21339
21991
  } catch (error) {
21340
21992
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
21341
- sendError(id, error);
21993
+ sendError(id2, error);
21342
21994
  return;
21343
21995
  }
21344
- sendTaskError(id, error);
21996
+ sendTaskError(id2, error);
21345
21997
  }
21346
21998
  };
21347
- const handleShellList = async (id, params) => {
21999
+ const handleShellList = async (id2, params) => {
21348
22000
  const requestedLimit = params?.limit;
21349
22001
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
21350
- sendError(id, {
21351
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22002
+ sendError(id2, {
22003
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21352
22004
  message: "limit must be a positive number"
21353
22005
  });
21354
22006
  return;
@@ -21357,31 +22009,31 @@ var createShellHandlers = ({
21357
22009
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
21358
22010
  const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo);
21359
22011
  const result = { tasks };
21360
- sendResult(id, result);
22012
+ sendResult(id2, result);
21361
22013
  } catch (error) {
21362
- sendTaskError(id, error);
22014
+ sendTaskError(id2, error);
21363
22015
  }
21364
22016
  };
21365
- const handleShellStatus = async (id, params) => {
22017
+ const handleShellStatus = async (id2, params) => {
21366
22018
  const taskId = parseTaskId(params?.task_id);
21367
22019
  if (!taskId) {
21368
- sendError(id, {
21369
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22020
+ sendError(id2, {
22021
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21370
22022
  message: "task_id is required"
21371
22023
  });
21372
22024
  return;
21373
22025
  }
21374
22026
  try {
21375
22027
  const task = await requireShellTask(shellTaskManager, taskId);
21376
- sendResult(id, toShellTaskInfo(task));
22028
+ sendResult(id2, toShellTaskInfo(task));
21377
22029
  } catch (error) {
21378
- sendTaskError(id, error);
22030
+ sendTaskError(id2, error);
21379
22031
  }
21380
22032
  };
21381
- const handleShellOutput = async (id, params) => {
22033
+ const handleShellOutput = async (id2, params) => {
21382
22034
  const parsed = parseShellOutputRequest(params);
21383
22035
  if ("error" in parsed) {
21384
- sendError(id, parsed.error);
22036
+ sendError(id2, parsed.error);
21385
22037
  return;
21386
22038
  }
21387
22039
  try {
@@ -21393,8 +22045,8 @@ var createShellHandlers = ({
21393
22045
  parsed.stream
21394
22046
  );
21395
22047
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
21396
- sendError(id, {
21397
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
22048
+ sendError(id2, {
22049
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_BUSY,
21398
22050
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
21399
22051
  });
21400
22052
  return;
@@ -21422,16 +22074,16 @@ var createShellHandlers = ({
21422
22074
  content,
21423
22075
  ...cacheId ? { ref_id: cacheId } : {}
21424
22076
  };
21425
- sendResult(id, result);
22077
+ sendResult(id2, result);
21426
22078
  } catch (error) {
21427
- sendTaskError(id, error);
22079
+ sendTaskError(id2, error);
21428
22080
  }
21429
22081
  };
21430
- const handleShellWait = async (id, params) => {
22082
+ const handleShellWait = async (id2, params) => {
21431
22083
  const taskId = parseTaskId(params?.task_id);
21432
22084
  if (!taskId) {
21433
- sendError(id, {
21434
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22085
+ sendError(id2, {
22086
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21435
22087
  message: "task_id is required"
21436
22088
  });
21437
22089
  return;
@@ -21440,13 +22092,13 @@ var createShellHandlers = ({
21440
22092
  params?.wait_timeout_seconds
21441
22093
  );
21442
22094
  if (typeof waitTimeoutSeconds === "object") {
21443
- sendError(id, waitTimeoutSeconds.error);
22095
+ sendError(id2, waitTimeoutSeconds.error);
21444
22096
  return;
21445
22097
  }
21446
22098
  try {
21447
22099
  const existing = await requireShellTask(shellTaskManager, taskId);
21448
22100
  if (isTerminalTaskState(existing.state)) {
21449
- sendResult(id, toShellTaskInfo(existing));
22101
+ sendResult(id2, toShellTaskInfo(existing));
21450
22102
  return;
21451
22103
  }
21452
22104
  const controller = new AbortController();
@@ -21486,12 +22138,12 @@ var createShellHandlers = ({
21486
22138
  timeoutPromise
21487
22139
  ]);
21488
22140
  if (outcome.type === "detached") {
21489
- sendResult(id, outcome.result);
22141
+ sendResult(id2, outcome.result);
21490
22142
  return;
21491
22143
  }
21492
22144
  if (outcome.type === "still_running") {
21493
22145
  const task = await requireShellTask(shellTaskManager, taskId);
21494
- sendResult(id, {
22146
+ sendResult(id2, {
21495
22147
  ...toShellTaskInfo(task),
21496
22148
  ...isTerminalTaskState(task.state) ? {} : { still_running: true }
21497
22149
  });
@@ -21500,7 +22152,7 @@ var createShellHandlers = ({
21500
22152
  if (outcome.type === "aborted") {
21501
22153
  return;
21502
22154
  }
21503
- sendResult(id, toShellTaskInfo(outcome.task));
22155
+ sendResult(id2, toShellTaskInfo(outcome.task));
21504
22156
  } finally {
21505
22157
  if (timeoutHandle) {
21506
22158
  clearTimeout(timeoutHandle);
@@ -21508,14 +22160,14 @@ var createShellHandlers = ({
21508
22160
  unregister();
21509
22161
  }
21510
22162
  } catch (error) {
21511
- sendTaskError(id, error);
22163
+ sendTaskError(id2, error);
21512
22164
  }
21513
22165
  };
21514
- const handleShellDetach = async (id, params) => {
22166
+ const handleShellDetach = async (id2, params) => {
21515
22167
  const taskId = parseTaskId(params?.task_id);
21516
22168
  if (!taskId) {
21517
- sendError(id, {
21518
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22169
+ sendError(id2, {
22170
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21519
22171
  message: "task_id is required"
21520
22172
  });
21521
22173
  return;
@@ -21524,8 +22176,8 @@ var createShellHandlers = ({
21524
22176
  const task = await requireShellTask(shellTaskManager, taskId);
21525
22177
  const waits = activeShellWaits.get(taskId);
21526
22178
  if (!waits || waits.size === 0) {
21527
- sendError(id, {
21528
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22179
+ sendError(id2, {
22180
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21529
22181
  message: `no active shell.wait to detach for task: ${taskId}`
21530
22182
  });
21531
22183
  return;
@@ -21538,16 +22190,16 @@ var createShellHandlers = ({
21538
22190
  detached: true,
21539
22191
  state: task.state
21540
22192
  };
21541
- sendResult(id, result);
22193
+ sendResult(id2, result);
21542
22194
  } catch (error) {
21543
- sendTaskError(id, error);
22195
+ sendTaskError(id2, error);
21544
22196
  }
21545
22197
  };
21546
- const handleShellCancel = async (id, params) => {
22198
+ const handleShellCancel = async (id2, params) => {
21547
22199
  const taskId = parseTaskId(params?.task_id);
21548
22200
  if (!taskId) {
21549
- sendError(id, {
21550
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22201
+ sendError(id2, {
22202
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21551
22203
  message: "task_id is required"
21552
22204
  });
21553
22205
  return;
@@ -21557,9 +22209,9 @@ var createShellHandlers = ({
21557
22209
  const task = await shellTaskManager.cancel(taskId, {
21558
22210
  reason: "cancelled"
21559
22211
  });
21560
- sendResult(id, toShellTaskInfo(task));
22212
+ sendResult(id2, toShellTaskInfo(task));
21561
22213
  } catch (error) {
21562
- sendTaskError(id, error);
22214
+ sendTaskError(id2, error);
21563
22215
  }
21564
22216
  };
21565
22217
  return {
@@ -21576,19 +22228,19 @@ var createShellHandlers = ({
21576
22228
 
21577
22229
  // src/rpc/skills.ts
21578
22230
  var import_node_path25 = __toESM(require("path"), 1);
21579
- var import_protocol16 = require("@codelia/protocol");
22231
+ var import_protocol17 = require("@codelia/protocol");
21580
22232
  var createSkillsHandlers = ({
21581
22233
  state,
21582
22234
  log: log2
21583
22235
  }) => {
21584
- const handleSkillsList = async (id, params) => {
22236
+ const handleSkillsList = async (id2, params) => {
21585
22237
  const requestedCwd = params?.cwd ? import_node_path25.default.resolve(params.cwd) : void 0;
21586
22238
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
21587
22239
  const forceReload = params?.force_reload ?? false;
21588
22240
  if (!forceReload) {
21589
22241
  const cachedCatalog = state.skillsCatalogByCwd.get(workingDir);
21590
22242
  if (cachedCatalog) {
21591
- sendResult(id, {
22243
+ sendResult(id2, {
21592
22244
  skills: cachedCatalog.skills,
21593
22245
  errors: cachedCatalog.errors,
21594
22246
  truncated: cachedCatalog.truncated
@@ -21605,8 +22257,8 @@ var createSkillsHandlers = ({
21605
22257
  config: await resolveEnvironmentSkillsConfig(state, workingDir)
21606
22258
  });
21607
22259
  } catch (error) {
21608
- sendError(id, {
21609
- code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22260
+ sendError(id2, {
22261
+ code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21610
22262
  message: `skills resolver init failed: ${String(error)}`
21611
22263
  });
21612
22264
  return;
@@ -21624,11 +22276,11 @@ var createSkillsHandlers = ({
21624
22276
  errors: catalog.errors,
21625
22277
  truncated: catalog.truncated
21626
22278
  };
21627
- sendResult(id, result);
22279
+ sendResult(id2, result);
21628
22280
  } catch (error) {
21629
22281
  log2(`skills.list error: ${String(error)}`);
21630
- sendError(id, {
21631
- code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22282
+ sendError(id2, {
22283
+ code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21632
22284
  message: `skills list failed: ${String(error)}`
21633
22285
  });
21634
22286
  }
@@ -21638,11 +22290,11 @@ var createSkillsHandlers = ({
21638
22290
 
21639
22291
  // src/rpc/task.ts
21640
22292
  var import_node_path26 = __toESM(require("path"), 1);
21641
- var import_protocol18 = require("@codelia/protocol");
21642
- var import_storage19 = require("@codelia/storage");
22293
+ var import_protocol19 = require("@codelia/protocol");
22294
+ var import_storage20 = require("@codelia/storage");
21643
22295
 
21644
22296
  // src/rpc/tool.ts
21645
- var import_protocol17 = require("@codelia/protocol");
22297
+ var import_protocol18 = require("@codelia/protocol");
21646
22298
  var normalizeToolResult = (result) => {
21647
22299
  switch (result.type) {
21648
22300
  case "json":
@@ -21674,18 +22326,18 @@ var createToolHandlers = ({
21674
22326
  state,
21675
22327
  getAgent
21676
22328
  }) => {
21677
- const handleToolCall = async (id, params) => {
22329
+ const handleToolCall = async (id2, params) => {
21678
22330
  const toolName = params?.name;
21679
22331
  if (!toolName) {
21680
- sendError(id, {
21681
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22332
+ sendError(id2, {
22333
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21682
22334
  message: "tool name is required"
21683
22335
  });
21684
22336
  return;
21685
22337
  }
21686
22338
  if (toolName === "attachment_read" && state.attachments) {
21687
- sendError(id, {
21688
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22339
+ sendError(id2, {
22340
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21689
22341
  message: "attachment_read is only available during a model run"
21690
22342
  });
21691
22343
  return;
@@ -21695,8 +22347,8 @@ var createToolHandlers = ({
21695
22347
  }
21696
22348
  const tool = state.tools?.find((entry) => entry.name === toolName);
21697
22349
  if (!tool) {
21698
- sendError(id, {
21699
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22350
+ sendError(id2, {
22351
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21700
22352
  message: `unknown tool: ${toolName}`
21701
22353
  });
21702
22354
  return;
@@ -21710,10 +22362,10 @@ var createToolHandlers = ({
21710
22362
  ok: true,
21711
22363
  result: normalizeToolResult(result)
21712
22364
  };
21713
- sendResult(id, response);
22365
+ sendResult(id2, response);
21714
22366
  } catch (error) {
21715
- sendError(id, {
21716
- code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22367
+ sendError(id2, {
22368
+ code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21717
22369
  message: `tool call failed: ${String(error)}`
21718
22370
  });
21719
22371
  }
@@ -21776,7 +22428,7 @@ var parseTaskId2 = (value) => {
21776
22428
  var toTaskRpcError2 = (error) => {
21777
22429
  if (!(error instanceof TaskManagerError)) {
21778
22430
  return {
21779
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22431
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21780
22432
  message: String(error)
21781
22433
  };
21782
22434
  }
@@ -21785,23 +22437,23 @@ var toTaskRpcError2 = (error) => {
21785
22437
  case "invalid_task_id":
21786
22438
  case "unsupported_workspace_mode":
21787
22439
  return {
21788
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22440
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21789
22441
  message: error.message
21790
22442
  };
21791
22443
  case "manager_shutting_down":
21792
22444
  return {
21793
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_BUSY,
22445
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_BUSY,
21794
22446
  message: error.message
21795
22447
  };
21796
22448
  default:
21797
22449
  return {
21798
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22450
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21799
22451
  message: error.message
21800
22452
  };
21801
22453
  }
21802
22454
  };
21803
- var sendTaskError2 = (id, error) => {
21804
- sendError(id, toTaskRpcError2(error));
22455
+ var sendTaskError2 = (id2, error) => {
22456
+ sendError(id2, toTaskRpcError2(error));
21805
22457
  };
21806
22458
  var toTaskSummary = (task, progress) => ({
21807
22459
  name: task.subagent?.name,
@@ -21847,7 +22499,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
21847
22499
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21848
22500
  return {
21849
22501
  error: {
21850
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22502
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21851
22503
  message: "timeout_seconds must be a positive number"
21852
22504
  }
21853
22505
  };
@@ -21861,7 +22513,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
21861
22513
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
21862
22514
  return {
21863
22515
  error: {
21864
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22516
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21865
22517
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
21866
22518
  }
21867
22519
  };
@@ -21876,7 +22528,7 @@ var parseShellSpawnRequest = (state, params, options) => {
21876
22528
  if (!command) {
21877
22529
  return {
21878
22530
  error: {
21879
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22531
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21880
22532
  message: "command is required for shell tasks"
21881
22533
  }
21882
22534
  };
@@ -21892,7 +22544,7 @@ var parseShellSpawnRequest = (state, params, options) => {
21892
22544
  if (!cwd) {
21893
22545
  return {
21894
22546
  error: {
21895
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22547
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21896
22548
  message: "cwd is outside sandbox root"
21897
22549
  }
21898
22550
  };
@@ -21963,17 +22615,17 @@ var createTaskHandlers = ({
21963
22615
  getAgent
21964
22616
  }) => {
21965
22617
  const tasks = taskManager ?? new TaskManager();
21966
- const taskOutputCache = outputCache ?? new import_storage19.ToolOutputCacheStoreImpl();
22618
+ const taskOutputCache = outputCache ?? new import_storage20.ToolOutputCacheStoreImpl();
21967
22619
  subscribeTaskProgress(state, tasks);
21968
22620
  const requireScope = async (taskId) => {
21969
22621
  const task = await tasks.status(taskId);
21970
22622
  if (task?.kind === "subagent" && task.subagent?.owner_session_id !== state.sessionId)
21971
22623
  throw new TaskManagerError("task_not_found", "Task not found");
21972
22624
  };
21973
- const handleTaskSpawn = async (id, params) => {
22625
+ const handleTaskSpawn = async (id2, params) => {
21974
22626
  if (!params || !isTaskKind(params.kind)) {
21975
- sendError(id, {
21976
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22627
+ sendError(id2, {
22628
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21977
22629
  message: "kind must be shell or subagent"
21978
22630
  });
21979
22631
  return;
@@ -21989,19 +22641,19 @@ var createTaskHandlers = ({
21989
22641
  signal
21990
22642
  });
21991
22643
  sendResult(
21992
- id,
22644
+ id2,
21993
22645
  subagentTaskInfo(
21994
22646
  params.background === false ? await tasks.wait(task.task_id, { signal }) : task
21995
22647
  )
21996
22648
  );
21997
22649
  } catch (error) {
21998
- sendTaskError2(id, error);
22650
+ sendTaskError2(id2, error);
21999
22651
  }
22000
22652
  return;
22001
22653
  }
22002
22654
  if (params.kind !== "shell") {
22003
- sendError(id, {
22004
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22655
+ sendError(id2, {
22656
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22005
22657
  message: `task kind ${params.kind} is not supported yet.`
22006
22658
  });
22007
22659
  return;
@@ -22009,7 +22661,7 @@ var createTaskHandlers = ({
22009
22661
  const background = params.background !== false;
22010
22662
  const parsed = parseShellSpawnRequest(state, params, { background });
22011
22663
  if ("error" in parsed) {
22012
- sendError(id, parsed.error);
22664
+ sendError(id2, parsed.error);
22013
22665
  return;
22014
22666
  }
22015
22667
  try {
@@ -22036,30 +22688,30 @@ var createTaskHandlers = ({
22036
22688
  const result = background ? toTaskSummary(task, tasks.getProgress(task.task_id)) : toTaskInfo(
22037
22689
  await tasks.wait(task.task_id, { signal: state.activeRunSignal })
22038
22690
  );
22039
- sendResult(id, result);
22691
+ sendResult(id2, result);
22040
22692
  } catch (error) {
22041
- sendTaskError2(id, error);
22693
+ sendTaskError2(id2, error);
22042
22694
  }
22043
22695
  };
22044
- const handleTaskList = async (id, params) => {
22696
+ const handleTaskList = async (id2, params) => {
22045
22697
  const requestedLimit = params?.limit;
22046
22698
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
22047
- sendError(id, {
22048
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22699
+ sendError(id2, {
22700
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22049
22701
  message: "limit must be a positive number"
22050
22702
  });
22051
22703
  return;
22052
22704
  }
22053
22705
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
22054
- sendError(id, {
22055
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22706
+ sendError(id2, {
22707
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22056
22708
  message: "kind must be shell or subagent"
22057
22709
  });
22058
22710
  return;
22059
22711
  }
22060
22712
  if (params?.state !== void 0 && !isTaskState(params.state)) {
22061
- sendError(id, {
22062
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22713
+ sendError(id2, {
22714
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22063
22715
  message: "invalid task state"
22064
22716
  });
22065
22717
  return;
@@ -22070,16 +22722,16 @@ var createTaskHandlers = ({
22070
22722
  (task) => task.kind !== "subagent" || task.subagent?.owner_session_id === state.sessionId
22071
22723
  ).filter((task) => params?.kind ? task.kind === params.kind : true).filter((task) => params?.state ? task.state === params.state : true).slice(0, limit).map((task) => toTaskSummary(task, tasks.getProgress(task.task_id)));
22072
22724
  const result = { tasks: tasksList };
22073
- sendResult(id, result);
22725
+ sendResult(id2, result);
22074
22726
  } catch (error) {
22075
- sendTaskError2(id, error);
22727
+ sendTaskError2(id2, error);
22076
22728
  }
22077
22729
  };
22078
- const handleTaskStatus = async (id, params) => {
22730
+ const handleTaskStatus = async (id2, params) => {
22079
22731
  const taskId = parseTaskId2(params?.task_id);
22080
22732
  if (!taskId) {
22081
- sendError(id, {
22082
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22733
+ sendError(id2, {
22734
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22083
22735
  message: "task_id is required"
22084
22736
  });
22085
22737
  return;
@@ -22097,16 +22749,16 @@ var createTaskHandlers = ({
22097
22749
  task,
22098
22750
  tasks.getProgress(task.task_id)
22099
22751
  );
22100
- sendResult(id, result);
22752
+ sendResult(id2, result);
22101
22753
  } catch (error) {
22102
- sendTaskError2(id, error);
22754
+ sendTaskError2(id2, error);
22103
22755
  }
22104
22756
  };
22105
- const handleTaskWait = async (id, params) => {
22757
+ const handleTaskWait = async (id2, params) => {
22106
22758
  const taskId = parseTaskId2(params?.task_id);
22107
22759
  if (!taskId) {
22108
- sendError(id, {
22109
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22760
+ sendError(id2, {
22761
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22110
22762
  message: "task_id is required"
22111
22763
  });
22112
22764
  return;
@@ -22118,16 +22770,16 @@ var createTaskHandlers = ({
22118
22770
  task,
22119
22771
  tasks.getProgress(task.task_id)
22120
22772
  );
22121
- sendResult(id, result);
22773
+ sendResult(id2, result);
22122
22774
  } catch (error) {
22123
- sendTaskError2(id, error);
22775
+ sendTaskError2(id2, error);
22124
22776
  }
22125
22777
  };
22126
- const handleTaskCancel = async (id, params) => {
22778
+ const handleTaskCancel = async (id2, params) => {
22127
22779
  const taskId = parseTaskId2(params?.task_id);
22128
22780
  if (!taskId) {
22129
- sendError(id, {
22130
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22781
+ sendError(id2, {
22782
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22131
22783
  message: "task_id is required"
22132
22784
  });
22133
22785
  return;
@@ -22141,16 +22793,16 @@ var createTaskHandlers = ({
22141
22793
  task,
22142
22794
  tasks.getProgress(task.task_id)
22143
22795
  );
22144
- sendResult(id, result);
22796
+ sendResult(id2, result);
22145
22797
  } catch (error) {
22146
- sendTaskError2(id, error);
22798
+ sendTaskError2(id2, error);
22147
22799
  }
22148
22800
  };
22149
- const handleTaskResult = async (id, params) => {
22801
+ const handleTaskResult = async (id2, params) => {
22150
22802
  const taskId = parseTaskId2(params?.task_id);
22151
22803
  if (!taskId) {
22152
- sendError(id, {
22153
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22804
+ sendError(id2, {
22805
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22154
22806
  message: "task_id is required"
22155
22807
  });
22156
22808
  return;
@@ -22165,9 +22817,9 @@ var createTaskHandlers = ({
22165
22817
  );
22166
22818
  }
22167
22819
  const result = task.state === "completed" || task.state === "failed" || task.state === "cancelled" ? toTaskInfo(task, tasks.getProgress(task.task_id)) : null;
22168
- sendResult(id, result);
22820
+ sendResult(id2, result);
22169
22821
  } catch (error) {
22170
- sendTaskError2(id, error);
22822
+ sendTaskError2(id2, error);
22171
22823
  }
22172
22824
  };
22173
22825
  return {
@@ -22240,15 +22892,15 @@ var createRuntimeHandlers = ({
22240
22892
  }) => {
22241
22893
  const environment = state.effectiveEnvironment;
22242
22894
  const imageHandlers = createImageHandlers(state);
22243
- const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage20.SessionStateStoreImpl({
22895
+ const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage21.SessionStateStoreImpl({
22244
22896
  onError: (error, context) => {
22245
22897
  log2(
22246
22898
  `session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
22247
22899
  );
22248
22900
  }
22249
22901
  }));
22250
- const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage20.RunEventStoreFactoryImpl({
22251
- ...sessionStateStore instanceof import_storage20.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
22902
+ const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage21.RunEventStoreFactoryImpl({
22903
+ ...sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
22252
22904
  onRunIndexError: (error) => log2(`session run index error: ${String(error)}`)
22253
22905
  }));
22254
22906
  const mcpManager = injectedMcpManager ?? {
@@ -22382,7 +23034,9 @@ var createRuntimeHandlers = ({
22382
23034
  if (!startupOnboardingPromise) return;
22383
23035
  await startupOnboardingPromise;
22384
23036
  };
23037
+ const goalStore = isTuiLocalEnvironment(environment) && sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? sessionStateStore.goals : void 0;
22385
23038
  const {
23039
+ handleGoal,
22386
23040
  handleRunStart,
22387
23041
  handleRunSteer,
22388
23042
  handleRunCancel,
@@ -22395,7 +23049,8 @@ var createRuntimeHandlers = ({
22395
23049
  runEventStoreFactory,
22396
23050
  sessionStateStore,
22397
23051
  appendSession,
22398
- beforeRunStart: waitForStartupOnboarding
23052
+ beforeRunStart: waitForStartupOnboarding,
23053
+ goalStore
22399
23054
  });
22400
23055
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
22401
23056
  sessionStateStore,
@@ -22462,7 +23117,7 @@ var createRuntimeHandlers = ({
22462
23117
  taskManager: injectedTaskManager,
22463
23118
  outputCache: toolOutputCacheStore ?? void 0
22464
23119
  }) : null;
22465
- const handleInitialize = async (id, params) => {
23120
+ const handleInitialize = async (id2, params) => {
22466
23121
  let resolvedTheme;
22467
23122
  const environment2 = state.effectiveEnvironment;
22468
23123
  if (isTuiLocalEnvironment(environment2)) {
@@ -22498,6 +23153,7 @@ var createRuntimeHandlers = ({
22498
23153
  supports_session_open: true,
22499
23154
  supports_run_cancel: true,
22500
23155
  supports_run_steer: true,
23156
+ supports_goals: Boolean(goalStore),
22501
23157
  supports_run_diagnostics: true,
22502
23158
  supports_session_lifecycle: !!sessionStateStore.updateMetadata,
22503
23159
  supports_shell_exec: processEnabled,
@@ -22526,7 +23182,7 @@ var createRuntimeHandlers = ({
22526
23182
  },
22527
23183
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
22528
23184
  };
22529
- sendResult(id, result);
23185
+ sendResult(id2, result);
22530
23186
  log2(`initialize from ${params.client?.name ?? "unknown"}`);
22531
23187
  state.lastClientInfo = params.client ?? null;
22532
23188
  state.setUiCapabilities(params.ui_capabilities);
@@ -22538,42 +23194,42 @@ var createRuntimeHandlers = ({
22538
23194
  `ui.context.update cwd=${params.cwd ?? "-"} file=${params.active_file?.path ?? "-"}`
22539
23195
  );
22540
23196
  };
22541
- const handleThemeSet = async (id, params) => {
23197
+ const handleThemeSet = async (id2, params) => {
22542
23198
  if (state.activeRunId) {
22543
- sendError(id, {
22544
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_BUSY,
23199
+ sendError(id2, {
23200
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_BUSY,
22545
23201
  message: "runtime busy"
22546
23202
  });
22547
23203
  return;
22548
23204
  }
22549
23205
  const name2 = params?.name?.trim().toLowerCase();
22550
23206
  if (!name2) {
22551
- sendError(id, {
22552
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23207
+ sendError(id2, {
23208
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22553
23209
  message: "theme name is required"
22554
23210
  });
22555
23211
  return;
22556
23212
  }
22557
23213
  if (!SUPPORTED_TUI_THEMES.has(name2)) {
22558
- sendError(id, {
22559
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23214
+ sendError(id2, {
23215
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22560
23216
  message: `unsupported theme: ${name2}`
22561
23217
  });
22562
23218
  return;
22563
23219
  }
22564
23220
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
22565
23221
  try {
22566
- const target = await updateEnvironmentTuiTheme(state, workingDir, name2);
23222
+ const target2 = await updateEnvironmentTuiTheme(state, workingDir, name2);
22567
23223
  const result = {
22568
23224
  name: name2,
22569
- scope: target.scope,
22570
- path: target.path
23225
+ scope: target2.scope,
23226
+ path: target2.path
22571
23227
  };
22572
- sendResult(id, result);
22573
- log2(`theme.set ${name2} scope=${target.scope} path=${target.path}`);
23228
+ sendResult(id2, result);
23229
+ log2(`theme.set ${name2} scope=${target2.scope} path=${target2.path}`);
22574
23230
  } catch (error) {
22575
- sendError(id, {
22576
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
23231
+ sendError(id2, {
23232
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22577
23233
  message: String(error)
22578
23234
  });
22579
23235
  }
@@ -22594,7 +23250,7 @@ var createRuntimeHandlers = ({
22594
23250
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
22595
23251
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
22596
23252
  const rejectDisabled = (message) => sendError(req.id, {
22597
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23253
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22598
23254
  message
22599
23255
  });
22600
23256
  switch (req.method) {
@@ -22605,6 +23261,13 @@ var createRuntimeHandlers = ({
22605
23261
  case "attachment.upload.finish":
22606
23262
  case "attachment.upload.cancel":
22607
23263
  return handleAttachmentUpload(state, req.id, req.method, req.params);
23264
+ case "goal.get":
23265
+ case "goal.set":
23266
+ case "goal.pause":
23267
+ case "goal.resume":
23268
+ case "goal.clear":
23269
+ case "goal.continue":
23270
+ return handleGoal(req.id, req.method, req.params);
22608
23271
  case "run.start":
22609
23272
  return handleRunStart(req.id, req.params);
22610
23273
  case "run.steer":
@@ -22792,7 +23455,7 @@ var createRuntimeHandlers = ({
22792
23455
  return handleThemeSet(req.id, req.params);
22793
23456
  default:
22794
23457
  return sendError(req.id, {
22795
- code: import_protocol19.RPC_ERROR_CODE.METHOD_NOT_FOUND,
23458
+ code: import_protocol20.RPC_ERROR_CODE.METHOD_NOT_FOUND,
22796
23459
  message: "method not found"
22797
23460
  });
22798
23461
  }
@@ -22811,11 +23474,11 @@ var createRuntimeHandlers = ({
22811
23474
  log2("invalid rpc message");
22812
23475
  return;
22813
23476
  }
22814
- const id = typeof msg.id === "string" ? msg.id : void 0;
23477
+ const id2 = typeof msg.id === "string" ? msg.id : void 0;
22815
23478
  if (msg.jsonrpc !== "2.0" || "method" in msg && typeof msg.method !== "string") {
22816
- if (id !== void 0) {
22817
- sendError(id, {
22818
- code: import_protocol19.RPC_ERROR_CODE.INVALID_REQUEST,
23479
+ if (id2 !== void 0) {
23480
+ sendError(id2, {
23481
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_REQUEST,
22819
23482
  message: "invalid request"
22820
23483
  });
22821
23484
  } else {
@@ -22824,29 +23487,29 @@ var createRuntimeHandlers = ({
22824
23487
  return;
22825
23488
  }
22826
23489
  if (typeof msg.method === "string") {
22827
- if ("id" in msg && id === void 0) {
23490
+ if ("id" in msg && id2 === void 0) {
22828
23491
  log2("invalid rpc request id");
22829
23492
  return;
22830
23493
  }
22831
23494
  const invalid = validateRequestParams(msg.method, msg.params);
22832
23495
  if (invalid) {
22833
- if (id !== void 0)
22834
- sendError(id, {
22835
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23496
+ if (id2 !== void 0)
23497
+ sendError(id2, {
23498
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22836
23499
  message: invalid
22837
23500
  });
22838
23501
  else log2(`invalid rpc notification: ${msg.method}`);
22839
23502
  return;
22840
23503
  }
22841
- if (id !== void 0) {
22842
- void withRpcResponseContext(id, async () => {
23504
+ if (id2 !== void 0) {
23505
+ void withRpcResponseContext(id2, async () => {
22843
23506
  try {
22844
23507
  await handleRequest(msg);
22845
23508
  } catch {
22846
- if (!hasRpcResponse(id)) {
23509
+ if (!hasRpcResponse(id2)) {
22847
23510
  try {
22848
- sendError(id, {
22849
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
23511
+ sendError(id2, {
23512
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22850
23513
  message: "internal runtime error"
22851
23514
  });
22852
23515
  } catch {
@@ -22867,11 +23530,11 @@ var createRuntimeHandlers = ({
22867
23530
  }
22868
23531
  return;
22869
23532
  }
22870
- if (id !== void 0 && ("result" in msg || "error" in msg)) {
23533
+ if (id2 !== void 0 && ("result" in msg || "error" in msg)) {
22871
23534
  handleResponse(msg);
22872
- } else if (id !== void 0) {
22873
- sendError(id, {
22874
- code: import_protocol19.RPC_ERROR_CODE.INVALID_REQUEST,
23535
+ } else if (id2 !== void 0) {
23536
+ sendError(id2, {
23537
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_REQUEST,
22875
23538
  message: "invalid request"
22876
23539
  });
22877
23540
  } else {
@@ -23041,18 +23704,18 @@ var RuntimeState = class {
23041
23704
  this.uiRequestCounter += 1;
23042
23705
  return `ui_${this.uiRequestCounter}`;
23043
23706
  }
23044
- waitForUiResponse(id, timeoutMs, onTimeout) {
23707
+ waitForUiResponse(id2, timeoutMs, onTimeout) {
23045
23708
  return new Promise((resolve, reject) => {
23046
23709
  const resolveUnknown = (value) => resolve(value);
23047
23710
  const timeout = timeoutMs ? setTimeout(() => {
23048
23711
  try {
23049
23712
  onTimeout?.();
23050
23713
  } finally {
23051
- this.pendingUiRequests.delete(id);
23714
+ this.pendingUiRequests.delete(id2);
23052
23715
  reject(new Error("ui request timed out"));
23053
23716
  }
23054
23717
  }, timeoutMs) : void 0;
23055
- this.pendingUiRequests.set(id, {
23718
+ this.pendingUiRequests.set(id2, {
23056
23719
  resolve: resolveUnknown,
23057
23720
  reject,
23058
23721
  timeout
@@ -23094,41 +23757,41 @@ var import_node_url = require("url");
23094
23757
 
23095
23758
  // src/subagents/bootstrap.ts
23096
23759
  var import_node_path27 = __toESM(require("path"), 1);
23097
- var import_zod36 = require("zod");
23098
- var permissionRule = import_zod36.z.object({
23099
- tool: import_zod36.z.string(),
23100
- command: import_zod36.z.string().optional(),
23101
- command_glob: import_zod36.z.string().optional(),
23102
- skill_name: import_zod36.z.string().optional()
23760
+ var import_zod37 = require("zod");
23761
+ var permissionRule = import_zod37.z.object({
23762
+ tool: import_zod37.z.string(),
23763
+ command: import_zod37.z.string().optional(),
23764
+ command_glob: import_zod37.z.string().optional(),
23765
+ skill_name: import_zod37.z.string().optional()
23103
23766
  }).passthrough();
23104
- var subagentBootstrapSchema = import_zod36.z.object({
23105
- version: import_zod36.z.literal(1),
23106
- task_id: import_zod36.z.string().uuid(),
23107
- prompt: import_zod36.z.string().min(1).max(32768),
23108
- workspace_root: import_zod36.z.string().refine(import_node_path27.default.isAbsolute),
23109
- lineage: import_zod36.z.object({
23767
+ var subagentBootstrapSchema = import_zod37.z.object({
23768
+ version: import_zod37.z.literal(1),
23769
+ task_id: import_zod37.z.string().uuid(),
23770
+ prompt: import_zod37.z.string().min(1).max(32768),
23771
+ workspace_root: import_zod37.z.string().refine(import_node_path27.default.isAbsolute),
23772
+ lineage: import_zod37.z.object({
23110
23773
  name: subagentNameSchema.optional(),
23111
- tree_id: import_zod36.z.string().min(1),
23112
- node_id: import_zod36.z.string().uuid(),
23113
- parent_node_id: import_zod36.z.string().min(1),
23114
- owner_session_id: import_zod36.z.string().min(1),
23115
- depth: import_zod36.z.literal(1),
23116
- spawn_index: import_zod36.z.number().int().positive(),
23117
- context_mode: import_zod36.z.literal("fresh"),
23118
- effective_policy_id: import_zod36.z.string().min(1),
23119
- workspace_lease_id: import_zod36.z.string().min(1)
23774
+ tree_id: import_zod37.z.string().min(1),
23775
+ node_id: import_zod37.z.string().uuid(),
23776
+ parent_node_id: import_zod37.z.string().min(1),
23777
+ owner_session_id: import_zod37.z.string().min(1),
23778
+ depth: import_zod37.z.literal(1),
23779
+ spawn_index: import_zod37.z.number().int().positive(),
23780
+ context_mode: import_zod37.z.literal("fresh"),
23781
+ effective_policy_id: import_zod37.z.string().min(1),
23782
+ workspace_lease_id: import_zod37.z.string().min(1)
23120
23783
  }).strict(),
23121
23784
  model: subagentModelSchema,
23122
- permission: import_zod36.z.object({
23123
- tool_allowlist: import_zod36.z.array(import_zod36.z.enum(WRITABLE_TOOLS)).max(WRITABLE_TOOLS.length),
23124
- workspace_access: import_zod36.z.enum(["read-only", "read-write"]),
23125
- approval_mode: import_zod36.z.enum(["minimal", "trusted", "full-access"]),
23126
- parent_permissions: import_zod36.z.object({
23127
- allow: import_zod36.z.array(permissionRule).optional(),
23128
- deny: import_zod36.z.array(permissionRule).optional()
23785
+ permission: import_zod37.z.object({
23786
+ tool_allowlist: import_zod37.z.array(import_zod37.z.enum(WRITABLE_TOOLS)).max(WRITABLE_TOOLS.length),
23787
+ workspace_access: import_zod37.z.enum(["read-only", "read-write"]),
23788
+ approval_mode: import_zod37.z.enum(["minimal", "trusted", "full-access"]),
23789
+ parent_permissions: import_zod37.z.object({
23790
+ allow: import_zod37.z.array(permissionRule).optional(),
23791
+ deny: import_zod37.z.array(permissionRule).optional()
23129
23792
  }).strict().optional(),
23130
- max_steps: import_zod36.z.number().int().min(1).max(200),
23131
- timeout_seconds: import_zod36.z.number().int().min(1).max(3600).optional()
23793
+ max_steps: import_zod37.z.number().int().min(1).max(200),
23794
+ timeout_seconds: import_zod37.z.number().int().min(1).max(3600).optional()
23132
23795
  }).strict()
23133
23796
  }).strict().refine(
23134
23797
  (input) => input.lineage.node_id === input.task_id && input.lineage.workspace_lease_id === input.task_id && (input.permission.workspace_access === "read-write" || input.permission.tool_allowlist.every(
@@ -23258,10 +23921,10 @@ var prepareProcess = (input, options, channel) => {
23258
23921
  }
23259
23922
  }
23260
23923
  };
23261
- const send2 = (id, method, params) => {
23924
+ const send2 = (id2, method, params) => {
23262
23925
  if (!child?.stdin?.writable || closed) return;
23263
23926
  child.stdin.write(
23264
- `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
23927
+ `${JSON.stringify({ jsonrpc: "2.0", id: id2, method, params })}
23265
23928
  `
23266
23929
  );
23267
23930
  };
@@ -23527,7 +24190,7 @@ var startRuntime = async (options = {}) => {
23527
24190
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
23528
24191
  }
23529
24192
  }
23530
- const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage21.SessionStateStoreImpl({
24193
+ const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage22.SessionStateStoreImpl({
23531
24194
  onError: (error, context) => {
23532
24195
  (0, import_logger.log)(
23533
24196
  `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
@@ -23543,13 +24206,13 @@ var startRuntime = async (options = {}) => {
23543
24206
  );
23544
24207
  }
23545
24208
  }
23546
- const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage21.RunEventStoreFactoryImpl({
23547
- ...sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
24209
+ const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage22.RunEventStoreFactoryImpl({
24210
+ ...sessionStateStore instanceof import_storage22.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
23548
24211
  onRunIndexError: (error) => (0, import_logger.log)(`session run index error: ${String(error)}`)
23549
24212
  }));
23550
- if (environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage21.SessionStateStoreImpl) {
23551
- void (0, import_storage21.cleanupRunLogs)({
23552
- paths: (0, import_storage21.resolveStoragePaths)(),
24213
+ if (environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage22.SessionStateStoreImpl) {
24214
+ void (0, import_storage22.cleanupRunLogs)({
24215
+ paths: (0, import_storage22.resolveStoragePaths)(),
23553
24216
  sessions: sessionStateStore
23554
24217
  }).then((result) => {
23555
24218
  if (result.compressed || result.deleted || result.failed)
@@ -23647,10 +24310,10 @@ var startRuntime = async (options = {}) => {
23647
24310
  sessionStateStore,
23648
24311
  runEventStoreFactory,
23649
24312
  taskManager,
23650
- ...environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? {
24313
+ ...environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage22.SessionStateStoreImpl ? {
23651
24314
  cleanupSessionLogs: async (sessionId) => {
23652
- await (0, import_storage21.cleanupRunLogs)({
23653
- paths: (0, import_storage21.resolveStoragePaths)(),
24315
+ await (0, import_storage22.cleanupRunLogs)({
24316
+ paths: (0, import_storage22.resolveStoragePaths)(),
23654
24317
  sessions: sessionStateStore,
23655
24318
  sessionId
23656
24319
  });