@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/sdk.cjs CHANGED
@@ -5,9 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
8
+ var __export = (target2, all) => {
9
9
  for (var name2 in all)
10
- __defProp(target, name2, { get: all[name2], enumerable: true });
10
+ __defProp(target2, name2, { get: all[name2], enumerable: true });
11
11
  };
12
12
  var __copyProps = (to, from, except, desc) => {
13
13
  if (from && typeof from === "object" || typeof from === "function") {
@@ -17,12 +17,12 @@ var __copyProps = (to, from, except, desc) => {
17
17
  }
18
18
  return to;
19
19
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ var __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
21
  // If the importer is in node compatibility mode or this is not an ESM
22
22
  // file that has been converted to a CommonJS file using a Babel-
23
23
  // compatible transform (i.e. "__esModule" has not been set), then set
24
24
  // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target2, "default", { value: mod, enumerable: true }) : target2,
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
@@ -35,7 +35,7 @@ __export(sdk_exports, {
35
35
  module.exports = __toCommonJS(sdk_exports);
36
36
 
37
37
  // src/runtime.ts
38
- var import_storage21 = require("@codelia/storage");
38
+ var import_storage22 = require("@codelia/storage");
39
39
 
40
40
  // src/agent-factory.ts
41
41
  var import_core32 = require("@codelia/core");
@@ -840,12 +840,12 @@ var resolveImageGenerationConfig = async (workingDir) => {
840
840
  };
841
841
  };
842
842
  var updateImageGeneration = async (workingDir, image) => {
843
- const target = await resolveWriteTarget(
843
+ const target2 = await resolveWriteTarget(
844
844
  workingDir ?? process.cwd(),
845
845
  "image_generation"
846
846
  );
847
- await (0, import_config_loader.updateImageGenerationConfig)(target.path, image);
848
- return target;
847
+ await (0, import_config_loader.updateImageGenerationConfig)(target2.path, image);
848
+ return target2;
849
849
  };
850
850
  var resolveModelConfig = async (workingDir) => {
851
851
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
@@ -1026,14 +1026,14 @@ var resolveMcpServers = async (workingDir) => {
1026
1026
  ...Object.keys(projectServers)
1027
1027
  ]);
1028
1028
  const resolved = [];
1029
- for (const id of allIds) {
1030
- const project = projectServers[id];
1031
- const global = globalServers[id];
1029
+ for (const id2 of allIds) {
1030
+ const project = projectServers[id2];
1031
+ const global = globalServers[id2];
1032
1032
  const server = project ?? global;
1033
1033
  if (!server) continue;
1034
1034
  resolved.push({
1035
1035
  ...server,
1036
- id,
1036
+ id: id2,
1037
1037
  source: project ? "project" : "global",
1038
1038
  enabled: server.enabled !== false,
1039
1039
  request_timeout_ms: normalizeMcpTimeoutMs(server.request_timeout_ms)
@@ -1075,14 +1075,14 @@ var resolveWriteTarget = async (workingDir, group) => {
1075
1075
  return defaultScope === "project" ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
1076
1076
  };
1077
1077
  var updateModel = async (workingDir, model) => {
1078
- const target = await resolveWriteTarget(workingDir, "model");
1079
- await (0, import_config_loader.updateModelConfig)(target.path, model);
1080
- return target;
1078
+ const target2 = await resolveWriteTarget(workingDir, "model");
1079
+ await (0, import_config_loader.updateModelConfig)(target2.path, model);
1080
+ return target2;
1081
1081
  };
1082
1082
  var updateTuiTheme = async (workingDir, theme) => {
1083
- const target = await resolveWriteTarget(workingDir, "tui");
1084
- await (0, import_config_loader.updateTuiConfig)(target.path, { theme });
1085
- return target;
1083
+ const target2 = await resolveWriteTarget(workingDir, "tui");
1084
+ await (0, import_config_loader.updateTuiConfig)(target2.path, { theme });
1085
+ return target2;
1086
1086
  };
1087
1087
  var resolveReasoningEffort = (value) => {
1088
1088
  return resolveModelLevelOption(value, "model.reasoning", {
@@ -1768,10 +1768,10 @@ var import_protocol = require("@codelia/protocol");
1768
1768
  // src/rpc/transport.ts
1769
1769
  var import_node_async_hooks = require("async_hooks");
1770
1770
  var responseContext = new import_node_async_hooks.AsyncLocalStorage();
1771
- var withRpcResponseContext = (id, callback) => responseContext.run({ id, sent: false }, callback);
1772
- var hasRpcResponse = (id) => {
1771
+ var withRpcResponseContext = (id2, callback) => responseContext.run({ id: id2, sent: false }, callback);
1772
+ var hasRpcResponse = (id2) => {
1773
1773
  const current = responseContext.getStore();
1774
- return current?.id === id && current.sent;
1774
+ return current?.id === id2 && current.sent;
1775
1775
  };
1776
1776
  var describeRpcMessage = (msg) => {
1777
1777
  if ("method" in msg && typeof msg.method === "string") {
@@ -1847,12 +1847,12 @@ var sendAsync = async (msg) => new Promise((resolve) => {
1847
1847
  (0, import_logger.debugLog)(`transport.backpressure label=${label} bytes=${payload.length}`);
1848
1848
  }
1849
1849
  });
1850
- var sendError = (id, error) => {
1851
- const response = { jsonrpc: "2.0", id, error };
1850
+ var sendError = (id2, error) => {
1851
+ const response = { jsonrpc: "2.0", id: id2, error };
1852
1852
  sendResponse(response);
1853
1853
  };
1854
- var sendResult = (id, result) => {
1855
- const response = { jsonrpc: "2.0", id, result };
1854
+ var sendResult = (id2, result) => {
1855
+ const response = { jsonrpc: "2.0", id: id2, result };
1856
1856
  sendResponse(response);
1857
1857
  };
1858
1858
  var sendResponse = (response) => {
@@ -1947,17 +1947,17 @@ var sendRunMetrics = (state, params) => {
1947
1947
  // src/rpc/ui-requests.ts
1948
1948
  var requestUi = async (state, method, params, signal) => {
1949
1949
  if (signal?.aborted) return null;
1950
- const id = state.nextUiRequestId();
1950
+ const id2 = state.nextUiRequestId();
1951
1951
  const request = {
1952
1952
  jsonrpc: "2.0",
1953
- id,
1953
+ id: id2,
1954
1954
  method,
1955
1955
  params
1956
1956
  };
1957
- const response = state.waitForUiResponse(id);
1957
+ const response = state.waitForUiResponse(id2);
1958
1958
  const abort = () => state.resolveUiResponse({
1959
1959
  jsonrpc: "2.0",
1960
- id,
1960
+ id: id2,
1961
1961
  error: {
1962
1962
  code: import_protocol.RPC_ERROR_CODE.RUNTIME_INTERNAL,
1963
1963
  message: "UI request cancelled"
@@ -3086,9 +3086,9 @@ var excerptByBytes = (value, maxBytes) => {
3086
3086
  if (maxBytes <= markerBytes + 2) {
3087
3087
  return truncateUtf8Prefix(value, maxBytes);
3088
3088
  }
3089
- const budget = maxBytes - markerBytes;
3090
- const headBytes = Math.floor(budget / 2);
3091
- const tailBytes = budget - headBytes;
3089
+ const budget2 = maxBytes - markerBytes;
3090
+ const headBytes = Math.floor(budget2 / 2);
3091
+ const tailBytes = budget2 - headBytes;
3092
3092
  return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
3093
3093
  };
3094
3094
  var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
@@ -3638,14 +3638,14 @@ async function exportImageBytes(workspaceRoot, outputPath, bytes, mediaType = "i
3638
3638
  throw new ImageGenerationError(
3639
3639
  "Image export path must match the original PNG or JPEG format in this workspace."
3640
3640
  );
3641
- const target = import_node_path5.default.resolve(workspaceRoot, outputPath);
3641
+ const target2 = import_node_path5.default.resolve(workspaceRoot, outputPath);
3642
3642
  try {
3643
3643
  const root = await (0, import_promises.realpath)(workspaceRoot);
3644
- const parent = await (0, import_promises.realpath)(import_node_path5.default.dirname(target));
3644
+ const parent = await (0, import_promises.realpath)(import_node_path5.default.dirname(target2));
3645
3645
  const relative = import_node_path5.default.relative(root, parent);
3646
3646
  if (relative === ".." || relative.startsWith(`..${import_node_path5.default.sep}`) || import_node_path5.default.isAbsolute(relative))
3647
3647
  throw new Error("outside workspace");
3648
- const destination = import_node_path5.default.join(parent, import_node_path5.default.basename(target));
3648
+ const destination = import_node_path5.default.join(parent, import_node_path5.default.basename(target2));
3649
3649
  const file = await (0, import_promises.open)(destination, "wx", 384);
3650
3650
  try {
3651
3651
  await file.writeFile(bytes);
@@ -4006,15 +4006,15 @@ async function downloadImageSource(value, callerSignal, transport = requestImage
4006
4006
  async function readImageFile(sandbox, filePath, signal) {
4007
4007
  try {
4008
4008
  signal?.throwIfAborted();
4009
- const target = await (0, import_promises3.realpath)(sandbox.resolvePath(filePath));
4009
+ const target2 = await (0, import_promises3.realpath)(sandbox.resolvePath(filePath));
4010
4010
  if (sandbox.approvalMode !== "full-access") {
4011
4011
  const root = await (0, import_promises3.realpath)(sandbox.rootDir);
4012
- const relative = import_node_path7.default.relative(root, target);
4012
+ const relative = import_node_path7.default.relative(root, target2);
4013
4013
  if (relative === ".." || relative.startsWith(`..${import_node_path7.default.sep}`) || import_node_path7.default.isAbsolute(relative))
4014
4014
  throw new Error("outside sandbox");
4015
4015
  }
4016
4016
  const handle = await (0, import_promises3.open)(
4017
- target,
4017
+ target2,
4018
4018
  import_node_fs4.constants.O_RDONLY | (import_node_fs4.constants.O_NOFOLLOW ?? 0) | (import_node_fs4.constants.O_NONBLOCK ?? 0)
4019
4019
  );
4020
4020
  try {
@@ -5102,13 +5102,6 @@ var resolveFastMode = (params) => {
5102
5102
  return { enabled: false };
5103
5103
  };
5104
5104
  var effectiveFastMode = (params) => resolveFastMode(params).enabled ? params.requested ?? false : false;
5105
- var assertUltrafastAuth = (fast, method) => {
5106
- if (fast === "ultrafast" && method !== "api_key") {
5107
- throw new Error(
5108
- "Ultrafast requires OpenAI API-key authentication. Codex OAuth support is unverified; credentials will not be switched automatically."
5109
- );
5110
- }
5111
- };
5112
5105
 
5113
5106
  // src/model-reasoning.ts
5114
5107
  var import_core6 = require("@codelia/core");
@@ -5746,14 +5739,12 @@ var createRuntimeModel = async ({
5746
5739
  log: log2,
5747
5740
  getOpenAiAccessToken
5748
5741
  }) => {
5749
- if (config.fast === "ultrafast") {
5750
- resolveFastMode({
5751
- provider,
5752
- model: config.name ?? import_core8.OPENAI_DEFAULT_MODEL,
5753
- requested: config.fast
5754
- });
5755
- assertUltrafastAuth(config.fast, auth.method);
5756
- }
5742
+ const requestedFastMode = config.fast;
5743
+ const ultrafastMode = requestedFastMode === "ultrafast" ? resolveFastMode({
5744
+ provider,
5745
+ model: config.name ?? import_core8.OPENAI_DEFAULT_MODEL,
5746
+ requested: requestedFastMode
5747
+ }) : void 0;
5757
5748
  const endpoint = getResponsesProvider(config, provider);
5758
5749
  if (endpoint) {
5759
5750
  const modelName = config.name ?? Object.keys(endpoint.models)[0];
@@ -5776,7 +5767,6 @@ var createRuntimeModel = async ({
5776
5767
  };
5777
5768
  }
5778
5769
  const requestedReasoning = resolveReasoningEffort(config.reasoning) ?? "medium";
5779
- const requestedFastMode = config.fast;
5780
5770
  switch (provider) {
5781
5771
  case "deepseek": {
5782
5772
  const llm = new import_core8.ChatDeepSeek({
@@ -5796,8 +5786,6 @@ var createRuntimeModel = async ({
5796
5786
  if (!model)
5797
5787
  throw new Error(`Unsupported Google model: ${requestedModelName}`);
5798
5788
  const modelName = model.id;
5799
- if (config.fast === "ultrafast")
5800
- throw new Error("Google models do not support Fast mode");
5801
5789
  const effort = resolveReasoningEffort(config.reasoning);
5802
5790
  const reasoning = effort ? resolveGoogleReasoning({ model: modelName, requested: effort }) : void 0;
5803
5791
  if (reasoning?.fallbackApplied)
@@ -5822,7 +5810,7 @@ var createRuntimeModel = async ({
5822
5810
  });
5823
5811
  const textVerbosity = resolveTextVerbosity(config.verbosity);
5824
5812
  const websocketMode = config.experimental?.openai?.websocket_mode;
5825
- const fastMode = resolveFastMode({
5813
+ const fastMode = ultrafastMode ?? resolveFastMode({
5826
5814
  provider: "openai",
5827
5815
  model: modelName,
5828
5816
  requested: requestedFastMode
@@ -6383,9 +6371,9 @@ var excerptByBytes2 = (value, maxBytes) => {
6383
6371
  truncated: true
6384
6372
  };
6385
6373
  }
6386
- const budget = maxBytes - markerBytes;
6387
- const headBytes = Math.floor(budget / 2);
6388
- const tailBytes = budget - headBytes;
6374
+ const budget2 = maxBytes - markerBytes;
6375
+ const headBytes = Math.floor(budget2 / 2);
6376
+ const tailBytes = budget2 - headBytes;
6389
6377
  return {
6390
6378
  text: `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`,
6391
6379
  truncated: true
@@ -7186,9 +7174,9 @@ var resolveCdTarget = (segment, currentWorkingDir, rootDir) => {
7186
7174
  const tokens = segment.split(" ").filter(Boolean);
7187
7175
  if (tokens[0] !== "cd") return null;
7188
7176
  if (tokens.length !== 2) return null;
7189
- const target = tokens[1];
7190
- if (target === "-" || CD_UNSAFE_TARGET_PATTERN.test(target)) return null;
7191
- const resolved = import_node_path10.default.resolve(currentWorkingDir, target);
7177
+ const target2 = tokens[1];
7178
+ if (target2 === "-" || CD_UNSAFE_TARGET_PATTERN.test(target2)) return null;
7179
+ const resolved = import_node_path10.default.resolve(currentWorkingDir, target2);
7192
7180
  const relative = import_node_path10.default.relative(rootDir, resolved);
7193
7181
  if (relative === "" || !relative.startsWith("..") && !import_node_path10.default.isAbsolute(relative)) {
7194
7182
  return resolved;
@@ -7359,20 +7347,20 @@ var PermissionService = class {
7359
7347
  const parsed = parseRawArgsForPrompt(rawArgs);
7360
7348
  const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
7361
7349
  const content = parsed && typeof parsed.content === "string" ? parsed.content : "";
7362
- const target = filePath || "(unknown path)";
7350
+ const target2 = filePath || "(unknown path)";
7363
7351
  return {
7364
7352
  title: "Run tool?",
7365
- message: `write ${target} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
7353
+ message: `write ${target2} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
7366
7354
  };
7367
7355
  }
7368
7356
  if (toolName === "edit") {
7369
7357
  const parsed = parseRawArgsForPrompt(rawArgs);
7370
7358
  const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
7371
- const target = filePath || "(unknown path)";
7359
+ const target2 = filePath || "(unknown path)";
7372
7360
  const mode = parsed && typeof parsed.match_mode === "string" ? parsed.match_mode : "auto";
7373
7361
  return {
7374
7362
  title: "Run tool?",
7375
- message: `edit ${target} (match=${mode})${rememberPreview}`
7363
+ message: `edit ${target2} (match=${mode})${rememberPreview}`
7376
7364
  };
7377
7365
  }
7378
7366
  if (toolName === "apply_patch") {
@@ -9002,7 +8990,7 @@ var subagentModelSchema = import_zod8.z.object({
9002
8990
  reasoning: import_zod8.z.string().optional(),
9003
8991
  verbosity: import_zod8.z.string().optional(),
9004
8992
  fast: import_zod8.z.union([import_zod8.z.boolean(), import_zod8.z.literal("ultrafast")]).optional().describe(
9005
- '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.'
8993
+ '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.'
9006
8994
  ),
9007
8995
  experimental: import_zod8.z.object({
9008
8996
  openai: import_zod8.z.object({
@@ -9089,10 +9077,10 @@ var VolatileRunEventStoreFactory = class {
9089
9077
  var VolatileToolOutputCacheStore = class {
9090
9078
  records = /* @__PURE__ */ new Map();
9091
9079
  async save(record) {
9092
- const id = record.tool_call_id;
9093
- this.records.set(id, structuredClone(record));
9080
+ const id2 = record.tool_call_id;
9081
+ this.records.set(id2, structuredClone(record));
9094
9082
  return {
9095
- id,
9083
+ id: id2,
9096
9084
  byte_size: Buffer.byteLength(record.content, "utf8"),
9097
9085
  line_count: record.content.split(/\r?\n/).length
9098
9086
  };
@@ -11217,17 +11205,17 @@ var LaneManager = class {
11217
11205
  "zellij backend is not supported yet in lane MVP. Use tmux."
11218
11206
  );
11219
11207
  }
11220
- async startTmuxLane(target, worktreePath, seedContext) {
11208
+ async startTmuxLane(target2, worktreePath, seedContext) {
11221
11209
  const launchCommand = this.buildLaunchCommand(seedContext);
11222
11210
  await this.cmd("tmux", [
11223
11211
  "new-session",
11224
11212
  "-d",
11225
11213
  "-s",
11226
- target,
11214
+ target2,
11227
11215
  "-c",
11228
11216
  worktreePath
11229
11217
  ]);
11230
- const paneTarget = `${target}:0.0`;
11218
+ const paneTarget = `${target2}:0.0`;
11231
11219
  await this.cmd("tmux", [
11232
11220
  "send-keys",
11233
11221
  "-t",
@@ -11248,9 +11236,9 @@ var LaneManager = class {
11248
11236
  }
11249
11237
  return `${this.launchCommand} ${INITIAL_MESSAGE_FLAG} ${this.shellQuote(seed)}`;
11250
11238
  }
11251
- async isTmuxAlive(target) {
11239
+ async isTmuxAlive(target2) {
11252
11240
  try {
11253
- await this.cmd("tmux", ["has-session", "-t", target], {
11241
+ await this.cmd("tmux", ["has-session", "-t", target2], {
11254
11242
  timeoutMs: 5e3
11255
11243
  });
11256
11244
  return true;
@@ -11262,9 +11250,9 @@ var LaneManager = class {
11262
11250
  );
11263
11251
  }
11264
11252
  }
11265
- async stopTmuxLane(target) {
11253
+ async stopTmuxLane(target2) {
11266
11254
  try {
11267
- await this.cmd("tmux", ["kill-session", "-t", target], {
11255
+ await this.cmd("tmux", ["kill-session", "-t", target2], {
11268
11256
  timeoutMs: 1e4
11269
11257
  });
11270
11258
  } catch (error) {
@@ -11765,8 +11753,8 @@ var createReadTool = (sandboxKey) => (0, import_core17.defineTool)({
11765
11753
  if (bytes + size > MAX_BYTES) {
11766
11754
  if (outputLines.length === 0) {
11767
11755
  const prefix = `${String(index + 1).padStart(5, " ")} `;
11768
- const budget = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
11769
- const clippedByBytes = clipLineToByteBudget(line, budget);
11756
+ const budget2 = MAX_BYTES - Buffer.byteLength(prefix, "utf8");
11757
+ const clippedByBytes = clipLineToByteBudget(line, budget2);
11770
11758
  if (clippedByBytes.length > 0) {
11771
11759
  outputLines.push(clippedByBytes);
11772
11760
  bytes = Buffer.byteLength(`${prefix}${clippedByBytes}`, "utf8");
@@ -12906,7 +12894,7 @@ var withPatchApplied = (currentTodos, updates) => {
12906
12894
  id: normalizeTodoId(update.id)
12907
12895
  }));
12908
12896
  const currentIds = new Set(currentTodos.map((todo) => todo.id));
12909
- const missingIds = normalizedUpdates.map((update) => update.id).filter((id) => !currentIds.has(id));
12897
+ const missingIds = normalizedUpdates.map((update) => update.id).filter((id2) => !currentIds.has(id2));
12910
12898
  if (missingIds.length > 0) {
12911
12899
  const knownIds = currentTodos.map((todo) => todo.id);
12912
12900
  return {
@@ -13789,9 +13777,9 @@ function createConversationTools(store, currentSession) {
13789
13777
  const searchMessages = store.searchMessages.bind(store);
13790
13778
  const readMessage = store.readMessage.bind(store);
13791
13779
  const session = () => {
13792
- const id = currentSession();
13793
- if (!id) throw new Error("No active conversation");
13794
- return id;
13780
+ const id2 = currentSession();
13781
+ if (!id2) throw new Error("No active conversation");
13782
+ return id2;
13795
13783
  };
13796
13784
  return [
13797
13785
  (0, import_core29.defineTool)({
@@ -13887,9 +13875,9 @@ var waitForTaskOrMessage = async (coordinator, owner, taskId, signal) => {
13887
13875
  // src/tools/task.ts
13888
13876
  var createSubagentTaskTools = (coordinator, ownerSession, spawn7) => {
13889
13877
  const session = () => {
13890
- const id = ownerSession();
13891
- if (!id) throw new Error("No parent session");
13892
- return id;
13878
+ const id2 = ownerSession();
13879
+ if (!id2) throw new Error("No parent session");
13880
+ return id2;
13893
13881
  };
13894
13882
  const idSchema = import_zod34.z.object({
13895
13883
  task_id: import_zod34.z.string().min(1).describe(
@@ -14645,9 +14633,9 @@ var AttachmentTransferService = class {
14645
14633
  "Attachment upload staging is full; retry or cancel an unused upload"
14646
14634
  );
14647
14635
  }
14648
- const id = (0, import_storage14.createAttachmentId)();
14636
+ const id2 = (0, import_storage14.createAttachmentId)();
14649
14637
  const upload = {
14650
- id,
14638
+ id: id2,
14651
14639
  key: params.upload_key,
14652
14640
  sessionId,
14653
14641
  name: name2,
@@ -14658,10 +14646,10 @@ var AttachmentTransferService = class {
14658
14646
  expires: this.now() + this.limits.lease_ms,
14659
14647
  pins: 0
14660
14648
  };
14661
- this.uploads.set(id, upload);
14649
+ this.uploads.set(id2, upload);
14662
14650
  this.stagedBytes += upload.size;
14663
14651
  processStagedBytes += upload.size;
14664
- return { upload_id: id, offset: 0 };
14652
+ return { upload_id: id2, offset: 0 };
14665
14653
  });
14666
14654
  }
14667
14655
  async chunk(params, sessionId) {
@@ -14743,13 +14731,13 @@ var AttachmentTransferService = class {
14743
14731
  async resolveForAdmission(ids, sessionId, options) {
14744
14732
  return this.serial(async () => {
14745
14733
  const result = [];
14746
- for (const id of ids) {
14734
+ for (const id2 of ids) {
14747
14735
  const upload = this.eligibleUpload(
14748
- id,
14736
+ id2,
14749
14737
  sessionId,
14750
14738
  options?.allowDraft ?? false
14751
14739
  );
14752
- const record = upload?.record ?? await this.lookup(id, sessionId);
14740
+ const record = upload?.record ?? await this.lookup(id2, sessionId);
14753
14741
  if (!record)
14754
14742
  throw new AttachmentUploadError(
14755
14743
  "Attachment unavailable in this session; re-upload to retry"
@@ -14764,16 +14752,16 @@ var AttachmentTransferService = class {
14764
14752
  return this.serial(async () => {
14765
14753
  const pending = [];
14766
14754
  const entries = [];
14767
- for (const id of new Set(ids)) {
14755
+ for (const id2 of new Set(ids)) {
14768
14756
  const upload = this.eligibleUpload(
14769
- id,
14757
+ id2,
14770
14758
  sessionId,
14771
14759
  options?.allowDraft ?? false
14772
14760
  );
14773
14761
  if (upload?.bytes && upload.record) {
14774
14762
  pending.push(upload);
14775
14763
  entries.push({ record: upload.record, bytes: upload.bytes });
14776
- } else if (!await this.lookup(id, sessionId)) {
14764
+ } else if (!await this.lookup(id2, sessionId)) {
14777
14765
  throw new AttachmentUploadError(
14778
14766
  "Attachment unavailable in this session; re-upload to retry"
14779
14767
  );
@@ -14800,10 +14788,10 @@ var AttachmentTransferService = class {
14800
14788
  async pin(ids, sessionId) {
14801
14789
  return this.serial(async () => {
14802
14790
  const pinned = [];
14803
- for (const id of new Set(ids)) {
14804
- const upload = this.eligibleUpload(id, sessionId, false);
14791
+ for (const id2 of new Set(ids)) {
14792
+ const upload = this.eligibleUpload(id2, sessionId, false);
14805
14793
  if (upload?.bytes && upload.record) pinned.push(upload);
14806
- else if (!await this.lookup(id, sessionId))
14794
+ else if (!await this.lookup(id2, sessionId))
14807
14795
  throw new AttachmentUploadError(
14808
14796
  "Attachment unavailable in this session; re-upload to retry"
14809
14797
  );
@@ -14817,12 +14805,12 @@ var AttachmentTransferService = class {
14817
14805
  };
14818
14806
  });
14819
14807
  }
14820
- async read(id, sessionId, offset, length) {
14808
+ async read(id2, sessionId, offset, length) {
14821
14809
  try {
14822
- if (!(0, import_storage14.isAttachmentId)(id) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
14810
+ if (!(0, import_storage14.isAttachmentId)(id2) || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0 || length > DEFAULT_LIMITS.max_chunk_bytes) {
14823
14811
  throw new Error("Invalid attachment byte range");
14824
14812
  }
14825
- const bytes = await this.store.read(id, sessionId, offset, length);
14813
+ const bytes = await this.store.read(id2, sessionId, offset, length);
14826
14814
  if (bytes.length > length)
14827
14815
  throw new Error("Attachment adapter exceeded the requested byte range");
14828
14816
  return bytes;
@@ -14832,9 +14820,9 @@ var AttachmentTransferService = class {
14832
14820
  );
14833
14821
  }
14834
14822
  }
14835
- async lookup(id, sessionId) {
14823
+ async lookup(id2, sessionId) {
14836
14824
  try {
14837
- return (0, import_storage14.isAttachmentId)(id) ? await this.store.lookup(id, sessionId) : null;
14825
+ return (0, import_storage14.isAttachmentId)(id2) ? await this.store.lookup(id2, sessionId) : null;
14838
14826
  } catch {
14839
14827
  throw new AttachmentUploadError(
14840
14828
  "Attachment original is missing, corrupt or unavailable in this session"
@@ -14879,8 +14867,8 @@ var AttachmentTransferService = class {
14879
14867
  );
14880
14868
  }
14881
14869
  }
14882
- getUpload(id, sessionId) {
14883
- const upload = this.uploads.get(id);
14870
+ getUpload(id2, sessionId) {
14871
+ const upload = this.uploads.get(id2);
14884
14872
  if (!upload || upload.sessionId !== sessionId) {
14885
14873
  throw new AttachmentUploadError(
14886
14874
  "Attachment upload expired or is unavailable in this session"
@@ -14895,8 +14883,8 @@ var AttachmentTransferService = class {
14895
14883
  );
14896
14884
  }
14897
14885
  }
14898
- eligibleUpload(id, sessionId, allowDraft) {
14899
- const upload = this.uploads.get(id);
14886
+ eligibleUpload(id2, sessionId, allowDraft) {
14887
+ const upload = this.uploads.get(id2);
14900
14888
  if (!upload?.bytes || !upload.record) return void 0;
14901
14889
  const owner = upload.sessionId;
14902
14890
  return owner === sessionId || owner === null && allowDraft ? upload : void 0;
@@ -15016,8 +15004,8 @@ var matchesRequestId = (value, expectedRequestId) => {
15016
15004
  return value.some((entry) => matchesRequestId(entry, expectedRequestId));
15017
15005
  }
15018
15006
  if (!isRecord5(value)) return false;
15019
- const id = value.id;
15020
- return typeof id === "string" || typeof id === "number" ? String(id) === expectedRequestId : false;
15007
+ const id2 = value.id;
15008
+ return typeof id2 === "string" || typeof id2 === "number" ? String(id2) === expectedRequestId : false;
15021
15009
  };
15022
15010
  var readSseBody = async (response, expectedRequestId) => {
15023
15011
  if (!expectedRequestId) {
@@ -15871,8 +15859,8 @@ var createMcpToolAdapter = (params) => {
15871
15859
  var OAUTH_TOKEN_EXPIRY_SKEW_MS = 6e4;
15872
15860
  var nowIso4 = () => (/* @__PURE__ */ new Date()).toISOString();
15873
15861
  var describeError2 = (error) => error instanceof Error ? error.message : String(error);
15874
- var toListServer = (id, runtime) => ({
15875
- id,
15862
+ var toListServer = (id2, runtime) => ({
15863
+ id: id2,
15876
15864
  transport: runtime.config.transport,
15877
15865
  source: runtime.config.source,
15878
15866
  enabled: runtime.config.enabled,
@@ -15920,7 +15908,7 @@ var McpManager = class {
15920
15908
  );
15921
15909
  }
15922
15910
  list(scope = "loaded") {
15923
- const servers = Array.from(this.servers.entries()).map(([id, runtime]) => toListServer(id, runtime)).sort((left, right) => left.id.localeCompare(right.id));
15911
+ const servers = Array.from(this.servers.entries()).map(([id2, runtime]) => toListServer(id2, runtime)).sort((left, right) => left.id.localeCompare(right.id));
15924
15912
  if (scope === "configured") {
15925
15913
  return { servers };
15926
15914
  }
@@ -16293,8 +16281,8 @@ var McpManager = class {
16293
16281
  };
16294
16282
 
16295
16283
  // src/rpc/handlers.ts
16296
- var import_protocol19 = require("@codelia/protocol");
16297
- var import_storage20 = require("@codelia/storage");
16284
+ var import_protocol20 = require("@codelia/protocol");
16285
+ var import_storage21 = require("@codelia/storage");
16298
16286
 
16299
16287
  // src/constants.ts
16300
16288
  var SERVER_NAME = "codelia-runtime";
@@ -16303,7 +16291,7 @@ var PROTOCOL_VERSION = "0";
16303
16291
 
16304
16292
  // src/rpc/attachment.ts
16305
16293
  var import_protocol3 = require("@codelia/protocol");
16306
- async function handleAttachmentUpload(state, id, method, params) {
16294
+ async function handleAttachmentUpload(state, id2, method, params) {
16307
16295
  const attachments = state.attachments;
16308
16296
  try {
16309
16297
  if (!attachments)
@@ -16315,7 +16303,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16315
16303
  switch (method) {
16316
16304
  case "attachment.upload.begin":
16317
16305
  return sendResult(
16318
- id,
16306
+ id2,
16319
16307
  await attachments.begin(
16320
16308
  params,
16321
16309
  state.sessionId
@@ -16323,7 +16311,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16323
16311
  );
16324
16312
  case "attachment.upload.chunk":
16325
16313
  return sendResult(
16326
- id,
16314
+ id2,
16327
16315
  await attachments.chunk(
16328
16316
  params,
16329
16317
  state.sessionId
@@ -16331,7 +16319,7 @@ async function handleAttachmentUpload(state, id, method, params) {
16331
16319
  );
16332
16320
  case "attachment.upload.finish":
16333
16321
  return sendResult(
16334
- id,
16322
+ id2,
16335
16323
  await attachments.finish(
16336
16324
  params.upload_id,
16337
16325
  state.sessionId
@@ -16342,13 +16330,13 @@ async function handleAttachmentUpload(state, id, method, params) {
16342
16330
  params.upload_id,
16343
16331
  state.sessionId
16344
16332
  );
16345
- return sendResult(id, {
16333
+ return sendResult(id2, {
16346
16334
  ok: true
16347
16335
  });
16348
16336
  }
16349
16337
  } catch (error) {
16350
16338
  if (!(error instanceof AttachmentUploadError)) throw error;
16351
- sendError(id, {
16339
+ sendError(id2, {
16352
16340
  code: import_protocol3.RPC_ERROR_CODE.INVALID_PARAMS,
16353
16341
  message: error.message
16354
16342
  });
@@ -16357,9 +16345,9 @@ async function handleAttachmentUpload(state, id, method, params) {
16357
16345
 
16358
16346
  // src/rpc/auth.ts
16359
16347
  var import_protocol4 = require("@codelia/protocol");
16360
- var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16348
+ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id2, params) => {
16361
16349
  if (state.activeRunId) {
16362
- sendError(id, {
16350
+ sendError(id2, {
16363
16351
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_BUSY,
16364
16352
  message: "runtime busy"
16365
16353
  });
@@ -16367,14 +16355,14 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16367
16355
  }
16368
16356
  const provider = params?.provider;
16369
16357
  if (params?.confirmed !== void 0 && typeof params.confirmed !== "boolean") {
16370
- sendError(id, {
16358
+ sendError(id2, {
16371
16359
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16372
16360
  message: "confirmed must be a boolean"
16373
16361
  });
16374
16362
  return;
16375
16363
  }
16376
16364
  if (provider !== void 0 && (typeof provider !== "string" || !/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(provider))) {
16377
- sendError(id, {
16365
+ sendError(id2, {
16378
16366
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16379
16367
  message: "invalid logout provider name"
16380
16368
  });
@@ -16392,7 +16380,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16392
16380
  if (hostAuth) {
16393
16381
  const credentials = state.effectiveEnvironment.adapters.credentialProvider;
16394
16382
  if (provider ? !credentials?.clearProviderAuth : !credentials?.clearAuth) {
16395
- sendError(id, {
16383
+ sendError(id2, {
16396
16384
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16397
16385
  message: provider ? "host auth provider does not support scoped logout" : "host auth provider does not support logout"
16398
16386
  });
@@ -16405,7 +16393,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16405
16393
  if (provider) {
16406
16394
  const auth = await store.load();
16407
16395
  if (!Object.hasOwn(auth.providers, provider) && !configuredProviders(config?.providers).includes(provider)) {
16408
- sendError(id, {
16396
+ sendError(id2, {
16409
16397
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
16410
16398
  message: `unknown logout provider: ${provider}`
16411
16399
  });
@@ -16414,7 +16402,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16414
16402
  }
16415
16403
  const preconfirmed = params?.confirmed === true;
16416
16404
  if (!preconfirmed && !state.uiCapabilities?.supports_confirm) {
16417
- sendError(id, {
16405
+ sendError(id2, {
16418
16406
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16419
16407
  message: "UI confirmation is required for logout"
16420
16408
  });
@@ -16430,7 +16418,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16430
16418
  allow_reason: false
16431
16419
  });
16432
16420
  if (!confirm?.ok) {
16433
- sendResult(id, {
16421
+ sendResult(id2, {
16434
16422
  ok: false,
16435
16423
  auth_cleared: false,
16436
16424
  session_cleared: false,
@@ -16455,7 +16443,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16455
16443
  state.sessionAppend = null;
16456
16444
  state.sessionModelOverride = null;
16457
16445
  }
16458
- sendResult(id, {
16446
+ sendResult(id2, {
16459
16447
  ok: true,
16460
16448
  auth_cleared: true,
16461
16449
  session_cleared: clearSession,
@@ -16465,7 +16453,7 @@ var createAuthLogoutHandler = ({ state, log: log2 }) => async (id, params) => {
16465
16453
  `auth.logout provider=${provider ?? "all"} session_cleared=${clearSession}`
16466
16454
  );
16467
16455
  } catch {
16468
- sendError(id, {
16456
+ sendError(id2, {
16469
16457
  code: import_protocol4.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16470
16458
  message: "auth logout failed"
16471
16459
  });
@@ -16499,9 +16487,9 @@ var saveProviderAuth = async (provider, auth) => {
16499
16487
  var createAuthManagementHandlers = ({ state, log: log2 }) => {
16500
16488
  let pending = null;
16501
16489
  let loginSeq = 0;
16502
- const rejectUnsupported = (id) => {
16490
+ const rejectUnsupported = (id2) => {
16503
16491
  if (supportsAuthManagement(state)) return false;
16504
- sendError(id, {
16492
+ sendError(id2, {
16505
16493
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16506
16494
  message: "auth is host-owned"
16507
16495
  });
@@ -16560,11 +16548,11 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16560
16548
  );
16561
16549
  return { config, providers: uniqueProviders(config.providers) };
16562
16550
  };
16563
- const handleStatus = async (id, params) => {
16564
- if (rejectUnsupported(id)) return;
16551
+ const handleStatus = async (id2, params) => {
16552
+ if (rejectUnsupported(id2)) return;
16565
16553
  const requested = params?.provider;
16566
16554
  if (requested !== void 0 && (typeof requested !== "string" || !PROVIDER_NAME_PATTERN.test(requested))) {
16567
- sendError(id, {
16555
+ sendError(id2, {
16568
16556
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16569
16557
  message: "invalid provider name"
16570
16558
  });
@@ -16573,7 +16561,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16573
16561
  try {
16574
16562
  const { config, providers } = await resolveProviders();
16575
16563
  if (requested !== void 0 && !providers.includes(requested)) {
16576
- sendError(id, {
16564
+ sendError(id2, {
16577
16565
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16578
16566
  message: `unknown provider: ${requested}`
16579
16567
  });
@@ -16609,18 +16597,18 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16609
16597
  }
16610
16598
  } : {}
16611
16599
  };
16612
- sendResult(id, result);
16600
+ sendResult(id2, result);
16613
16601
  } catch {
16614
- sendError(id, {
16602
+ sendError(id2, {
16615
16603
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16616
16604
  message: "auth status failed"
16617
16605
  });
16618
16606
  }
16619
16607
  };
16620
- const handleLogin = async (id, params) => {
16621
- if (rejectUnsupported(id)) return;
16608
+ const handleLogin = async (id2, params) => {
16609
+ if (rejectUnsupported(id2)) return;
16622
16610
  if (state.activeRunId) {
16623
- sendError(id, {
16611
+ sendError(id2, {
16624
16612
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16625
16613
  message: "runtime busy"
16626
16614
  });
@@ -16629,7 +16617,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16629
16617
  const provider = params?.provider;
16630
16618
  const method = params?.method;
16631
16619
  if (typeof provider !== "string" || !PROVIDER_NAME_PATTERN.test(provider)) {
16632
- sendError(id, {
16620
+ sendError(id2, {
16633
16621
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16634
16622
  message: "invalid provider name"
16635
16623
  });
@@ -16642,21 +16630,21 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16642
16630
  providers = resolved.providers;
16643
16631
  providerConfigs = resolved.config.providers;
16644
16632
  } catch {
16645
- sendError(id, {
16633
+ sendError(id2, {
16646
16634
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16647
16635
  message: "auth login failed"
16648
16636
  });
16649
16637
  return;
16650
16638
  }
16651
16639
  if (!providers.includes(provider)) {
16652
- sendError(id, {
16640
+ sendError(id2, {
16653
16641
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16654
16642
  message: `unknown provider: ${provider}`
16655
16643
  });
16656
16644
  return;
16657
16645
  }
16658
16646
  if (!method || !providerAuthMethods(provider, providerConfigs).includes(method)) {
16659
- sendError(id, {
16647
+ sendError(id2, {
16660
16648
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16661
16649
  message: `unsupported auth method for ${provider}`
16662
16650
  });
@@ -16666,7 +16654,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16666
16654
  const raw = params.api_key;
16667
16655
  const apiKey = typeof raw === "string" ? raw.trim() : "";
16668
16656
  if (!apiKey || apiKey.length > MAX_API_KEY_LENGTH || /\s/.test(apiKey)) {
16669
- sendError(id, {
16657
+ sendError(id2, {
16670
16658
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16671
16659
  message: "api_key must be a non-empty single-line string"
16672
16660
  });
@@ -16684,20 +16672,20 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16684
16672
  return "saved";
16685
16673
  });
16686
16674
  } catch {
16687
- sendError(id, {
16675
+ sendError(id2, {
16688
16676
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16689
16677
  message: "saving credentials failed"
16690
16678
  });
16691
16679
  return;
16692
16680
  }
16693
16681
  if (saved === "busy") {
16694
- sendError(id, {
16682
+ sendError(id2, {
16695
16683
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16696
16684
  message: "runtime busy"
16697
16685
  });
16698
16686
  return;
16699
16687
  }
16700
- sendResult(id, {
16688
+ sendResult(id2, {
16701
16689
  status: "completed",
16702
16690
  provider,
16703
16691
  method: "api_key"
@@ -16706,7 +16694,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16706
16694
  return;
16707
16695
  }
16708
16696
  if (pending) {
16709
- sendError(id, {
16697
+ sendError(id2, {
16710
16698
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_BUSY,
16711
16699
  message: "another login is pending"
16712
16700
  });
@@ -16714,7 +16702,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16714
16702
  }
16715
16703
  const typed = params;
16716
16704
  if (typed.callback !== void 0 && typed.callback !== "loopback" && typed.callback !== "paste") {
16717
- sendError(id, {
16705
+ sendError(id2, {
16718
16706
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16719
16707
  message: "callback must be loopback or paste"
16720
16708
  });
@@ -16737,7 +16725,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16737
16725
  return false;
16738
16726
  }
16739
16727
  stop();
16740
- sendError(id, {
16728
+ sendError(id2, {
16741
16729
  code: import_protocol5.RPC_ERROR_CODE.USER_CANCELLED,
16742
16730
  message: "login cancelled"
16743
16731
  });
@@ -16750,7 +16738,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16750
16738
  });
16751
16739
  if (cancelledDuringSetup(session.stop)) return;
16752
16740
  login.completeFromInput = session.completeFromInput;
16753
- sendResult(id, {
16741
+ sendResult(id2, {
16754
16742
  status: "pending",
16755
16743
  login_id: login.id,
16756
16744
  provider,
@@ -16768,7 +16756,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16768
16756
  const session = await createOpenAiDeviceCodeSession();
16769
16757
  const abort = new AbortController();
16770
16758
  if (cancelledDuringSetup(() => abort.abort())) return;
16771
- sendResult(id, {
16759
+ sendResult(id2, {
16772
16760
  status: "pending",
16773
16761
  login_id: login.id,
16774
16762
  provider,
@@ -16786,17 +16774,17 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16786
16774
  } catch (error) {
16787
16775
  login.settled = true;
16788
16776
  if (pending === login) pending = null;
16789
- sendError(id, {
16777
+ sendError(id2, {
16790
16778
  code: import_protocol5.RPC_ERROR_CODE.RUNTIME_INTERNAL,
16791
16779
  message: `auth login failed: ${failureMessage(error)}`
16792
16780
  });
16793
16781
  }
16794
16782
  };
16795
- const handleLoginComplete = async (id, params) => {
16796
- if (rejectUnsupported(id)) return;
16783
+ const handleLoginComplete = async (id2, params) => {
16784
+ if (rejectUnsupported(id2)) return;
16797
16785
  const login = pending;
16798
16786
  if (!login || login.id !== params?.login_id) {
16799
- sendError(id, {
16787
+ sendError(id2, {
16800
16788
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16801
16789
  message: "no matching pending login"
16802
16790
  });
@@ -16804,7 +16792,7 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16804
16792
  }
16805
16793
  const input = params?.callback_input;
16806
16794
  if (!login.completeFromInput || typeof input !== "string" || !input.trim() || input.length > MAX_CALLBACK_INPUT_LENGTH) {
16807
- sendError(id, {
16795
+ sendError(id2, {
16808
16796
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16809
16797
  message: "callback_input is required for a pending OAuth login"
16810
16798
  });
@@ -16814,27 +16802,27 @@ var createAuthManagementHandlers = ({ state, log: log2 }) => {
16814
16802
  try {
16815
16803
  completion = login.completeFromInput(input.trim());
16816
16804
  } catch {
16817
- sendError(id, {
16805
+ sendError(id2, {
16818
16806
  code: import_protocol5.RPC_ERROR_CODE.INVALID_PARAMS,
16819
16807
  message: "invalid OAuth callback input"
16820
16808
  });
16821
16809
  return;
16822
16810
  }
16823
- sendResult(id, { ok: true });
16811
+ sendResult(id2, { ok: true });
16824
16812
  completion.then(
16825
16813
  (tokens) => finishLogin(login, tokens),
16826
16814
  (error) => failLogin(login, error)
16827
16815
  );
16828
16816
  };
16829
- const handleLoginCancel = async (id, params) => {
16830
- if (rejectUnsupported(id)) return;
16817
+ const handleLoginCancel = async (id2, params) => {
16818
+ if (rejectUnsupported(id2)) return;
16831
16819
  const login = pending;
16832
16820
  if (!login || login.id !== params?.login_id) {
16833
- sendResult(id, { cancelled: false });
16821
+ sendResult(id2, { cancelled: false });
16834
16822
  return;
16835
16823
  }
16836
16824
  settle(login);
16837
- sendResult(id, { cancelled: true });
16825
+ sendResult(id2, { cancelled: true });
16838
16826
  notifyLogin(login, "cancelled");
16839
16827
  log2(`auth.login cancelled provider=${login.provider}`);
16840
16828
  };
@@ -17008,19 +16996,19 @@ var createConfigHandlers = ({
17008
16996
  state,
17009
16997
  log: log2
17010
16998
  }) => {
17011
- const rejectUnsupported = (id) => {
16999
+ const rejectUnsupported = (id2) => {
17012
17000
  if (supportsConfigReadWrite(state)) return false;
17013
- sendError(id, {
17001
+ sendError(id2, {
17014
17002
  code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
17015
17003
  message: "config read/write is not available for this runtime"
17016
17004
  });
17017
17005
  return true;
17018
17006
  };
17019
- const handleConfigGet = async (id, params) => {
17020
- if (rejectUnsupported(id)) return;
17007
+ const handleConfigGet = async (id2, params) => {
17008
+ if (rejectUnsupported(id2)) return;
17021
17009
  const keys = params?.keys;
17022
17010
  if (keys !== void 0 && (!Array.isArray(keys) || keys.length > MAX_KEYS_PER_REQUEST || keys.some((key) => typeof key !== "string" || !findConfigKey(key)))) {
17023
- sendError(id, {
17011
+ sendError(id2, {
17024
17012
  code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
17025
17013
  message: "keys must list known config keys"
17026
17014
  });
@@ -17033,18 +17021,18 @@ var createConfigHandlers = ({
17033
17021
  entries: specs.map((spec) => buildConfigEntry(spec, layers)),
17034
17022
  ...layers.errors.length ? { errors: layers.errors } : {}
17035
17023
  };
17036
- sendResult(id, result);
17024
+ sendResult(id2, result);
17037
17025
  };
17038
- const handleConfigSet = async (id, params) => {
17039
- if (rejectUnsupported(id)) return;
17026
+ const handleConfigSet = async (id2, params) => {
17027
+ if (rejectUnsupported(id2)) return;
17040
17028
  if (state.activeRunId) {
17041
- sendError(id, {
17029
+ sendError(id2, {
17042
17030
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_BUSY,
17043
17031
  message: "runtime busy"
17044
17032
  });
17045
17033
  return;
17046
17034
  }
17047
- const invalid = (message) => sendError(id, { code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS, message });
17035
+ const invalid = (message) => sendError(id2, { code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS, message });
17048
17036
  const scope = params?.scope;
17049
17037
  if (scope !== "global" && scope !== "project") {
17050
17038
  invalid("scope must be global or project");
@@ -17094,14 +17082,14 @@ var createConfigHandlers = ({
17094
17082
  return written;
17095
17083
  });
17096
17084
  } catch {
17097
- sendError(id, {
17085
+ sendError(id2, {
17098
17086
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17099
17087
  message: `${scope} config write failed`
17100
17088
  });
17101
17089
  return;
17102
17090
  }
17103
17091
  if (changed === "busy") {
17104
- sendError(id, {
17092
+ sendError(id2, {
17105
17093
  code: import_protocol6.RPC_ERROR_CODE.RUNTIME_BUSY,
17106
17094
  message: "runtime busy"
17107
17095
  });
@@ -17115,7 +17103,7 @@ var createConfigHandlers = ({
17115
17103
  entry: buildConfigEntry(spec, layers),
17116
17104
  applies: "next_run"
17117
17105
  };
17118
- sendResult(id, result);
17106
+ sendResult(id2, result);
17119
17107
  log2(
17120
17108
  `config.set ${spec.key} scope=${scope} ${unset ? "unset" : "set"} changed=${changed}`
17121
17109
  );
@@ -17206,7 +17194,7 @@ var createContextHandlers = ({
17206
17194
  return null;
17207
17195
  }
17208
17196
  };
17209
- const handleContextInspect = async (id, params) => {
17197
+ const handleContextInspect = async (id2, params) => {
17210
17198
  const includeAgents = params?.include_agents ?? true;
17211
17199
  const includeSkills = params?.include_skills ?? true;
17212
17200
  try {
@@ -17252,9 +17240,9 @@ var createContextHandlers = ({
17252
17240
  result.skills = snapshot;
17253
17241
  }
17254
17242
  }
17255
- sendResult(id, result);
17243
+ sendResult(id2, result);
17256
17244
  } catch (error) {
17257
- sendError(id, {
17245
+ sendError(id2, {
17258
17246
  code: import_protocol7.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17259
17247
  message: `context.inspect failed: ${String(error)}`
17260
17248
  });
@@ -17279,17 +17267,17 @@ var createContextUsageHandlers = ({
17279
17267
  state,
17280
17268
  log: log2
17281
17269
  }) => {
17282
- const handleContextUsage = async (id) => {
17270
+ const handleContextUsage = async (id2) => {
17283
17271
  try {
17284
17272
  const usage = state.agent ? state.agent.getContextUsage() : emptyUsage(state);
17285
17273
  const result = {
17286
17274
  ...usage,
17287
17275
  ...state.sessionId ? { session_id: state.sessionId } : {}
17288
17276
  };
17289
- sendResult(id, result);
17277
+ sendResult(id2, result);
17290
17278
  } catch (error) {
17291
17279
  log2(`context.usage failed: ${String(error)}`);
17292
- sendError(id, {
17280
+ sendError(id2, {
17293
17281
  code: import_protocol8.RPC_ERROR_CODE.RUNTIME_INTERNAL,
17294
17282
  message: "context usage unavailable"
17295
17283
  });
@@ -17528,14 +17516,14 @@ var createHistoryHandlers = ({
17528
17516
  if (!trimmed) return void 0;
17529
17517
  return import_node_path22.default.resolve(trimmed);
17530
17518
  };
17531
- const handleSessionList = async (id, params) => {
17519
+ const handleSessionList = async (id2, params) => {
17532
17520
  const limit = params?.limit ?? 50;
17533
17521
  const scope = params?.scope ?? "current_workspace";
17534
17522
  let sessions;
17535
17523
  try {
17536
17524
  sessions = await sessionStateStore.list();
17537
17525
  } catch (error) {
17538
- sendError(id, {
17526
+ sendError(id2, {
17539
17527
  code: import_protocol9.RPC_ERROR_CODE.SESSION_LIST_FAILED,
17540
17528
  message: `session list failed: ${String(error)}`
17541
17529
  });
@@ -17553,7 +17541,7 @@ var createHistoryHandlers = ({
17553
17541
  sessions: filtered,
17554
17542
  current_workspace_root: requestedWorkspaceRoot
17555
17543
  };
17556
- sendResult(id, result);
17544
+ sendResult(id2, result);
17557
17545
  };
17558
17546
  const collectRuns = async (sessionId, maxRuns) => {
17559
17547
  if (runIndex) {
@@ -17565,10 +17553,10 @@ var createHistoryHandlers = ({
17565
17553
  }
17566
17554
  return collectSessionRuns(sessionId, maxRuns, log2);
17567
17555
  };
17568
- const handleSessionHistory = async (id, params) => {
17556
+ const handleSessionHistory = async (id2, params) => {
17569
17557
  const sessionId = params?.session_id?.trim();
17570
17558
  if (!sessionId) {
17571
- sendError(id, {
17559
+ sendError(id2, {
17572
17560
  code: import_protocol9.RPC_ERROR_CODE.INVALID_PARAMS,
17573
17561
  message: "session_id is required"
17574
17562
  });
@@ -17581,7 +17569,7 @@ var createHistoryHandlers = ({
17581
17569
  runs: 0,
17582
17570
  events_sent: 0
17583
17571
  };
17584
- sendResult(id, result2);
17572
+ sendResult(id2, result2);
17585
17573
  return;
17586
17574
  }
17587
17575
  const runs = readRunLogs ? await collectRuns(sessionId, maxRuns) : [];
@@ -17596,6 +17584,7 @@ var createHistoryHandlers = ({
17596
17584
  }
17597
17585
  if (!record || typeof record !== "object") continue;
17598
17586
  if (record.type === "run.start") {
17587
+ if (record.source === "goal") continue;
17599
17588
  const input = runStartInputToHiddenMessage(record.input);
17600
17589
  if (input) {
17601
17590
  replayEvents.push({
@@ -17641,7 +17630,7 @@ var createHistoryHandlers = ({
17641
17630
  ...truncated ? { truncated: true } : {},
17642
17631
  ...resumeDiff ? { resume_diff: resumeDiff } : {}
17643
17632
  };
17644
- sendResult(id, result);
17633
+ sendResult(id2, result);
17645
17634
  };
17646
17635
  return { handleSessionList, handleSessionHistory };
17647
17636
  };
@@ -17762,23 +17751,23 @@ function createImageHandlers(state) {
17762
17751
  const codex = chat?.auth.method === "oauth";
17763
17752
  model = await pick(
17764
17753
  codex ? "Codex OAuth image model (current login; account-specific limits)" : "Image model (API billed; availability is account-specific)",
17765
- (codex ? import_config12.OPENAI_CODEX_IMAGE_MODELS : import_config12.OPENAI_IMAGE_MODELS).map((id) => ({
17766
- id,
17767
- label: id,
17754
+ (codex ? import_config12.OPENAI_CODEX_IMAGE_MODELS : import_config12.OPENAI_IMAGE_MODELS).map((id2) => ({
17755
+ id: id2,
17756
+ label: id2,
17768
17757
  ...codex ? {
17769
- detail: id === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
17758
+ detail: id2 === "gpt-image-2" ? "Inspected Codex tool default" : "Explicit request; support/effective model depends on the Codex backend"
17770
17759
  } : {}
17771
17760
  }))
17772
17761
  );
17773
17762
  } else if (provider === "google") {
17774
17763
  model = await pick(
17775
17764
  "Gemini image model",
17776
- import_config12.GOOGLE_IMAGE_MODELS.map((id) => ({ id, label: id }))
17765
+ import_config12.GOOGLE_IMAGE_MODELS.map((id2) => ({ id: id2, label: id2 }))
17777
17766
  );
17778
17767
  if (!model) return null;
17779
17768
  const image_size = await pick(
17780
17769
  "Image size",
17781
- (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id) => ({ id, label: id }))
17770
+ (model === "gemini-3.1-flash-lite-image" ? ["1K"] : ["1K", "2K", "4K"]).map((id2) => ({ id: id2, label: id2 }))
17782
17771
  );
17783
17772
  if (!image_size) return null;
17784
17773
  const aspect_ratio = await pick(
@@ -17795,7 +17784,7 @@ function createImageHandlers(state) {
17795
17784
  "16:9",
17796
17785
  "21:9",
17797
17786
  ...model === "gemini-nano-banana-2.1" ? ["1:4", "4:1", "1:8", "8:1"] : []
17798
- ].map((id) => ({ id, label: id }))
17787
+ ].map((id2) => ({ id: id2, label: id2 }))
17799
17788
  );
17800
17789
  if (!aspect_ratio) return null;
17801
17790
  const format = await pick("Image output format", [
@@ -17841,7 +17830,7 @@ function createImageHandlers(state) {
17841
17830
  }
17842
17831
  );
17843
17832
  };
17844
- const handle = async (id, operation, params) => {
17833
+ const handle = async (id2, operation, params) => {
17845
17834
  let ownsConfiguration = false;
17846
17835
  try {
17847
17836
  const root = workspace();
@@ -17855,14 +17844,14 @@ function createImageHandlers(state) {
17855
17844
  root,
17856
17845
  () => state.sessionId
17857
17846
  ).read(parsed2.data.artifact_id);
17858
- sendResult(id, {
17847
+ sendResult(id2, {
17859
17848
  metadata,
17860
17849
  data_url: `data:${metadata.media_type};base64,${bytes.toString("base64")}`
17861
17850
  });
17862
17851
  return;
17863
17852
  }
17864
17853
  if (operation === "get") {
17865
- sendResult(id, await status(await resolveImageGenerationConfig(root)));
17854
+ sendResult(id2, await status(await resolveImageGenerationConfig(root)));
17866
17855
  return;
17867
17856
  }
17868
17857
  if (state.activeRunId || configuring)
@@ -17917,7 +17906,7 @@ function createImageHandlers(state) {
17917
17906
  config = await choose();
17918
17907
  }
17919
17908
  if (!config) {
17920
- sendResult(id, { message: "Image settings unchanged." });
17909
+ sendResult(id2, { message: "Image settings unchanged." });
17921
17910
  return;
17922
17911
  }
17923
17912
  const next = await status(config);
@@ -17934,7 +17923,7 @@ This saves image settings only; generation requests use the tool permission poli
17934
17923
  cancel_label: "Cancel"
17935
17924
  });
17936
17925
  if (!confirm?.ok) {
17937
- sendResult(id, { message: "Image settings unchanged." });
17926
+ sendResult(id2, { message: "Image settings unchanged." });
17938
17927
  return;
17939
17928
  }
17940
17929
  }
@@ -17946,9 +17935,9 @@ This saves image settings only; generation requests use the tool permission poli
17946
17935
  state.agent = null;
17947
17936
  state.tools = null;
17948
17937
  state.toolDefinitions = null;
17949
- sendResult(id, next);
17938
+ sendResult(id2, next);
17950
17939
  } catch (error) {
17951
- sendError(id, {
17940
+ sendError(id2, {
17952
17941
  code: import_protocol10.RPC_ERROR_CODE.INVALID_PARAMS,
17953
17942
  message: error instanceof ImageGenerationError ? error.message : "Image operation failed; check settings, artifact and runtime storage. No credentials were changed."
17954
17943
  });
@@ -18128,13 +18117,13 @@ var parseOpenRouterModel = (value) => {
18128
18117
  return null;
18129
18118
  }
18130
18119
  const entry = value;
18131
- const id = typeof entry.id === "string" ? entry.id.trim() : "";
18132
- if (!id) {
18120
+ const id2 = typeof entry.id === "string" ? entry.id.trim() : "";
18121
+ if (!id2) {
18133
18122
  return null;
18134
18123
  }
18135
18124
  const topProvider = entry.top_provider && typeof entry.top_provider === "object" ? entry.top_provider : null;
18136
18125
  return {
18137
- id,
18126
+ id: id2,
18138
18127
  created: typeof entry.created === "number" && Number.isFinite(entry.created) ? entry.created : void 0,
18139
18128
  context_length: parsePositiveNumber(entry.context_length),
18140
18129
  top_provider: topProvider ? {
@@ -18303,12 +18292,13 @@ var createModelHandlers = ({
18303
18292
  model: name2,
18304
18293
  requested: fast
18305
18294
  });
18306
- if (fast === "ultrafast") {
18307
- const auth = state.effectiveEnvironment.auth.model === "host" ? await state.effectiveEnvironment.adapters.credentialProvider?.resolveProviderAuth(
18308
- provider
18309
- ) : (await new AuthStore().load()).providers[provider];
18310
- const method = auth?.method ?? (state.effectiveEnvironment.auth.model !== "host" && readEnvValue("OPENAI_API_KEY") ? "api_key" : "missing");
18311
- assertUltrafastAuth(fast, method);
18295
+ if (fast !== "ultrafast") return effectiveFast;
18296
+ const { auth: authPolicy, adapters } = state.effectiveEnvironment;
18297
+ const credentials = authPolicy.model === "host" ? await adapters.credentialProvider?.resolveProviderAuth(provider) : (await new AuthStore().load()).providers[provider] ?? readEnvValue("OPENAI_API_KEY");
18298
+ if (!credentials) {
18299
+ throw new Error(
18300
+ "Ultrafast requires OpenAI API-key or ChatGPT sign-in credentials."
18301
+ );
18312
18302
  }
18313
18303
  return effectiveFast;
18314
18304
  };
@@ -18327,7 +18317,7 @@ var createModelHandlers = ({
18327
18317
  meta: nextMeta
18328
18318
  });
18329
18319
  };
18330
- const handleModelList = async (id, params) => {
18320
+ const handleModelList = async (id2, params) => {
18331
18321
  const requestedProvider = params?.provider;
18332
18322
  const includeDetails = params?.include_details ?? false;
18333
18323
  let providers;
@@ -18354,7 +18344,7 @@ var createModelHandlers = ({
18354
18344
  });
18355
18345
  }
18356
18346
  } catch (error) {
18357
- sendError(id, {
18347
+ sendError(id2, {
18358
18348
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18359
18349
  message: String(error)
18360
18350
  });
@@ -18362,7 +18352,7 @@ var createModelHandlers = ({
18362
18352
  }
18363
18353
  const provider = requestedProvider ?? configuredProvider ?? "openai";
18364
18354
  if (!isSupportedProvider(provider, providers)) {
18365
- sendError(id, {
18355
+ sendError(id2, {
18366
18356
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18367
18357
  message: `unsupported provider: ${provider}`
18368
18358
  });
@@ -18381,7 +18371,7 @@ var createModelHandlers = ({
18381
18371
  models = result2.models;
18382
18372
  details = result2.details;
18383
18373
  } catch (error) {
18384
- sendError(id, {
18374
+ sendError(id2, {
18385
18375
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18386
18376
  message: String(error)
18387
18377
  });
@@ -18408,11 +18398,11 @@ var createModelHandlers = ({
18408
18398
  ...configuredFast !== void 0 ? { fast: configuredFast } : {},
18409
18399
  ...details ? { details } : {}
18410
18400
  };
18411
- sendResult(id, result);
18401
+ sendResult(id2, result);
18412
18402
  };
18413
- const handleModelSet = async (id, params) => {
18403
+ const handleModelSet = async (id2, params) => {
18414
18404
  if (state.activeRunId) {
18415
- sendError(id, {
18405
+ sendError(id2, {
18416
18406
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_BUSY,
18417
18407
  message: "runtime busy"
18418
18408
  });
@@ -18420,7 +18410,7 @@ var createModelHandlers = ({
18420
18410
  }
18421
18411
  const scope = params?.scope ?? "config";
18422
18412
  if (scope !== "config" && scope !== "session") {
18423
- sendError(id, {
18413
+ sendError(id2, {
18424
18414
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18425
18415
  message: `unsupported model scope: ${scope}`
18426
18416
  });
@@ -18429,7 +18419,7 @@ var createModelHandlers = ({
18429
18419
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
18430
18420
  if (params?.reset) {
18431
18421
  if (scope !== "session") {
18432
- sendError(id, {
18422
+ sendError(id2, {
18433
18423
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18434
18424
  message: "model reset is only supported for session scope"
18435
18425
  });
@@ -18440,7 +18430,7 @@ var createModelHandlers = ({
18440
18430
  const provider2 = config.provider ?? "openai";
18441
18431
  const name3 = config.name;
18442
18432
  if (!name3) {
18443
- sendError(id, {
18433
+ sendError(id2, {
18444
18434
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18445
18435
  message: "configured model name is missing"
18446
18436
  });
@@ -18456,7 +18446,7 @@ var createModelHandlers = ({
18456
18446
  config.fast
18457
18447
  );
18458
18448
  } catch (error) {
18459
- sendError(id, {
18449
+ sendError(id2, {
18460
18450
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18461
18451
  message: String(error)
18462
18452
  });
@@ -18475,10 +18465,10 @@ var createModelHandlers = ({
18475
18465
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
18476
18466
  ...config.fast !== void 0 ? { fast: effectiveFast } : {}
18477
18467
  };
18478
- sendResult(id, result);
18468
+ sendResult(id2, result);
18479
18469
  log2(`model.set reset session override -> ${provider2}/${name3}`);
18480
18470
  } catch (error) {
18481
- sendError(id, {
18471
+ sendError(id2, {
18482
18472
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18483
18473
  message: String(error)
18484
18474
  });
@@ -18488,7 +18478,7 @@ var createModelHandlers = ({
18488
18478
  const provider = params?.provider ?? "openai";
18489
18479
  let name2 = params?.name?.trim();
18490
18480
  if (!name2) {
18491
- sendError(id, {
18481
+ sendError(id2, {
18492
18482
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18493
18483
  message: "model name is required"
18494
18484
  });
@@ -18499,7 +18489,7 @@ var createModelHandlers = ({
18499
18489
  try {
18500
18490
  reasoning = resolveReasoningEffort(params.reasoning);
18501
18491
  } catch (error) {
18502
- sendError(id, {
18492
+ sendError(id2, {
18503
18493
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18504
18494
  message: String(error)
18505
18495
  });
@@ -18509,7 +18499,7 @@ var createModelHandlers = ({
18509
18499
  const configured = await resolveEnvironmentModelConfig(state, workingDir);
18510
18500
  const endpoint = getResponsesProvider(configured, provider);
18511
18501
  if (!isSupportedProvider(provider, configured.providers)) {
18512
- sendError(id, {
18502
+ sendError(id2, {
18513
18503
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18514
18504
  message: `unsupported provider: ${provider}`
18515
18505
  });
@@ -18522,7 +18512,7 @@ var createModelHandlers = ({
18522
18512
  provider
18523
18513
  );
18524
18514
  if (!spec) {
18525
- sendError(id, {
18515
+ sendError(id2, {
18526
18516
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18527
18517
  message: `unknown model: ${name2}`
18528
18518
  });
@@ -18555,16 +18545,16 @@ var createModelHandlers = ({
18555
18545
  }
18556
18546
  await validateFastSelection(provider, name2, candidate.fast);
18557
18547
  } catch (error) {
18558
- sendError(id, {
18548
+ sendError(id2, {
18559
18549
  code: import_protocol11.RPC_ERROR_CODE.INVALID_PARAMS,
18560
18550
  message: String(error)
18561
18551
  });
18562
18552
  return;
18563
18553
  }
18564
18554
  try {
18565
- let target = null;
18555
+ let target2 = null;
18566
18556
  if (scope === "config") {
18567
- target = await updateEnvironmentModel(state, workingDir, {
18557
+ target2 = await updateEnvironmentModel(state, workingDir, {
18568
18558
  provider,
18569
18559
  name: name2,
18570
18560
  ...reasoning ? { reasoning } : {},
@@ -18604,13 +18594,13 @@ var createModelHandlers = ({
18604
18594
  ...effectiveReasoning ? { reasoning: effectiveReasoning } : {},
18605
18595
  ...updatedConfig.fast !== void 0 ? { fast: effectiveFast } : {}
18606
18596
  };
18607
- sendResult(id, result);
18608
- const persistence = scope === "config" && target ? ` scope=${target.scope} path=${target.path}` : " scope=session";
18597
+ sendResult(id2, result);
18598
+ const persistence = scope === "config" && target2 ? ` scope=${target2.scope} path=${target2.path}` : " scope=session";
18609
18599
  log2(
18610
18600
  `model.set ${provider}/${name2}${effectiveReasoning ? ` reasoning=${effectiveReasoning}` : ""}${persistence}`
18611
18601
  );
18612
18602
  } catch (error) {
18613
- sendError(id, {
18603
+ sendError(id2, {
18614
18604
  code: import_protocol11.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18615
18605
  message: String(error)
18616
18606
  });
@@ -18665,18 +18655,18 @@ var createPermissionsHandlers = ({
18665
18655
  state,
18666
18656
  log: log2
18667
18657
  }) => {
18668
- const rejectUnsupported = (id) => {
18658
+ const rejectUnsupported = (id2) => {
18669
18659
  if (supportsConfigReadWrite(state)) return false;
18670
- sendError(id, {
18660
+ sendError(id2, {
18671
18661
  code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS,
18672
18662
  message: "permission rules are not available for this runtime"
18673
18663
  });
18674
18664
  return true;
18675
18665
  };
18676
- const handlePermissionsList = async (id, params) => {
18677
- if (rejectUnsupported(id)) return;
18666
+ const handlePermissionsList = async (id2, params) => {
18667
+ if (rejectUnsupported(id2)) return;
18678
18668
  if (params?.include_system !== void 0 && typeof params.include_system !== "boolean") {
18679
- sendError(id, {
18669
+ sendError(id2, {
18680
18670
  code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS,
18681
18671
  message: "include_system must be a boolean"
18682
18672
  });
@@ -18740,18 +18730,18 @@ var createPermissionsHandlers = ({
18740
18730
  rules,
18741
18731
  ...errors.length ? { errors } : {}
18742
18732
  };
18743
- sendResult(id, result);
18733
+ sendResult(id2, result);
18744
18734
  };
18745
- const handlePermissionsRemove = async (id, params) => {
18746
- if (rejectUnsupported(id)) return;
18735
+ const handlePermissionsRemove = async (id2, params) => {
18736
+ if (rejectUnsupported(id2)) return;
18747
18737
  if (state.activeRunId) {
18748
- sendError(id, {
18738
+ sendError(id2, {
18749
18739
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_BUSY,
18750
18740
  message: "runtime busy"
18751
18741
  });
18752
18742
  return;
18753
18743
  }
18754
- const invalid = (message) => sendError(id, { code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS, message });
18744
+ const invalid = (message) => sendError(id2, { code: import_protocol12.RPC_ERROR_CODE.INVALID_PARAMS, message });
18755
18745
  const scope = params?.scope;
18756
18746
  const kind = params?.kind;
18757
18747
  if (scope !== "global" && scope !== "project") {
@@ -18782,21 +18772,21 @@ var createPermissionsHandlers = ({
18782
18772
  return count2;
18783
18773
  });
18784
18774
  } catch {
18785
- sendError(id, {
18775
+ sendError(id2, {
18786
18776
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_INTERNAL,
18787
18777
  message: `${scope} config write failed`
18788
18778
  });
18789
18779
  return;
18790
18780
  }
18791
18781
  if (removed === "busy") {
18792
- sendError(id, {
18782
+ sendError(id2, {
18793
18783
  code: import_protocol12.RPC_ERROR_CODE.RUNTIME_BUSY,
18794
18784
  message: "runtime busy"
18795
18785
  });
18796
18786
  return;
18797
18787
  }
18798
18788
  const result = { scope, kind, path: path29, removed };
18799
- sendResult(id, result);
18789
+ sendResult(id2, result);
18800
18790
  log2(`permissions.remove scope=${scope} kind=${kind} removed=${removed}`);
18801
18791
  };
18802
18792
  return { handlePermissionsList, handlePermissionsRemove };
@@ -19175,7 +19165,7 @@ var buildResumeDiff = async (meta, state, options = {}) => {
19175
19165
  };
19176
19166
 
19177
19167
  // src/rpc/run.ts
19178
- var import_protocol13 = require("@codelia/protocol");
19168
+ var import_protocol14 = require("@codelia/protocol");
19179
19169
 
19180
19170
  // src/provider-errors.ts
19181
19171
  var import_core34 = require("@codelia/core");
@@ -19245,23 +19235,23 @@ var normalizeRunFailure = (error) => {
19245
19235
 
19246
19236
  // src/rpc/client-tool-requests.ts
19247
19237
  var requestClientToolCall = async (state, params, timeoutMs) => {
19248
- const id = state.nextUiRequestId();
19238
+ const id2 = state.nextUiRequestId();
19249
19239
  const request = {
19250
19240
  jsonrpc: "2.0",
19251
- id,
19241
+ id: id2,
19252
19242
  method: "client.tool.call",
19253
19243
  params
19254
19244
  };
19255
19245
  send(request);
19256
19246
  return await state.waitForUiResponse(
19257
- id,
19247
+ id2,
19258
19248
  timeoutMs,
19259
19249
  () => {
19260
19250
  const notification = {
19261
19251
  jsonrpc: "2.0",
19262
19252
  method: "client.tool.cancel",
19263
19253
  params: {
19264
- request_id: id,
19254
+ request_id: id2,
19265
19255
  run_id: params.run_id,
19266
19256
  name: params.name,
19267
19257
  reason: "timeout"
@@ -19371,8 +19361,550 @@ var createClientToolAdapters = ({
19371
19361
  });
19372
19362
  };
19373
19363
 
19374
- // src/rpc/run-debug.ts
19364
+ // src/rpc/goals.ts
19375
19365
  var import_core35 = require("@codelia/core");
19366
+ var import_protocol13 = require("@codelia/protocol");
19367
+ var import_storage18 = require("@codelia/storage");
19368
+ var import_zod36 = require("zod");
19369
+ var id = import_zod36.z.string().min(1).max(200);
19370
+ var revision = import_zod36.z.number().int().positive();
19371
+ var target = import_zod36.z.object({ session_id: id, goal_id: id, revision });
19372
+ var budget = import_zod36.z.number().int().positive().nullable();
19373
+ var schemas = {
19374
+ "goal.get": import_zod36.z.object({
19375
+ session_id: id.optional(),
19376
+ continuation_id: id.optional()
19377
+ }),
19378
+ "goal.set": target.partial().extend({
19379
+ objective: import_zod36.z.string().trim().min(1).max(8e3).optional(),
19380
+ token_budget: budget.optional()
19381
+ }),
19382
+ "goal.pause": import_zod36.z.object({
19383
+ session_id: id,
19384
+ goal_id: id,
19385
+ activation_id: id,
19386
+ run_id: id.optional(),
19387
+ continuation_id: id.optional()
19388
+ }),
19389
+ "goal.resume": target,
19390
+ "goal.clear": target
19391
+ };
19392
+ var readySchema = target.extend({
19393
+ continuation_id: id,
19394
+ after_run_id: id.optional()
19395
+ });
19396
+ var GoalConflict = class extends Error {
19397
+ constructor(message, reason = "conflict") {
19398
+ super(message);
19399
+ this.reason = reason;
19400
+ }
19401
+ reason;
19402
+ };
19403
+ var stamp = () => (/* @__PURE__ */ new Date()).toISOString();
19404
+ var transition = (goal, status, reason) => {
19405
+ if (goal.status !== status || goal.stop_reason !== reason)
19406
+ goal.stop_detail = void 0;
19407
+ goal.status = status;
19408
+ goal.stop_reason = reason;
19409
+ goal.revision += 1;
19410
+ goal.updated_at = stamp();
19411
+ };
19412
+ function stopForBudget(goal) {
19413
+ if (goal.token_budget === null) return false;
19414
+ if (goal.tokens_used >= goal.token_budget) {
19415
+ transition(goal, "budget_limited");
19416
+ return true;
19417
+ }
19418
+ if (!goal.usage_known) {
19419
+ transition(goal, "usage_limited");
19420
+ return true;
19421
+ }
19422
+ return false;
19423
+ }
19424
+ var readTarget = (entry, expected) => {
19425
+ if (!entry || entry.goal.goal_id !== expected.goal_id || entry.goal.revision !== expected.revision)
19426
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
19427
+ return entry;
19428
+ };
19429
+ var GoalController = class {
19430
+ constructor(state, store, sessions, workspaceRoot) {
19431
+ this.state = state;
19432
+ this.store = store;
19433
+ this.sessions = sessions;
19434
+ this.workspaceRoot = workspaceRoot;
19435
+ }
19436
+ state;
19437
+ store;
19438
+ sessions;
19439
+ workspaceRoot;
19440
+ activation = null;
19441
+ offer = null;
19442
+ activeRun;
19443
+ identity;
19444
+ get enabled() {
19445
+ return this.state.uiCapabilities?.supports_goals === true;
19446
+ }
19447
+ disarm() {
19448
+ this.activation = null;
19449
+ this.offer = null;
19450
+ }
19451
+ owns(goal) {
19452
+ return this.activation?.sessionId === goal.session_id && this.activation.goalId === goal.goal_id && this.activation.id === goal.activation_id;
19453
+ }
19454
+ arm(goal) {
19455
+ this.activation = {
19456
+ sessionId: goal.session_id,
19457
+ goalId: goal.goal_id,
19458
+ id: goal.activation_id
19459
+ };
19460
+ this.offer = null;
19461
+ }
19462
+ snapshot(sessionId, goal, acceptedRunId) {
19463
+ return {
19464
+ session_id: sessionId,
19465
+ goal,
19466
+ can_continue: Boolean(goal?.status === "active" && this.owns(goal)),
19467
+ ...acceptedRunId ? {
19468
+ accepted_run_id: acceptedRunId,
19469
+ ...this.state.activeRunId === acceptedRunId ? { active_run_id: acceptedRunId } : {}
19470
+ } : {}
19471
+ };
19472
+ }
19473
+ publish(goal) {
19474
+ if (this.enabled && this.state.sessionId === goal.session_id)
19475
+ send({
19476
+ jsonrpc: "2.0",
19477
+ method: "goal.updated",
19478
+ params: this.snapshot(goal.session_id, goal)
19479
+ });
19480
+ }
19481
+ ready(goal, afterRunId) {
19482
+ if (!this.enabled || this.state.activeRunId || this.state.sessionId !== goal.session_id || goal.status !== "active" || !this.owns(goal) || this.offer)
19483
+ return;
19484
+ this.offer = {
19485
+ session_id: goal.session_id,
19486
+ goal_id: goal.goal_id,
19487
+ revision: goal.revision,
19488
+ continuation_id: crypto.randomUUID(),
19489
+ ...afterRunId ? { after_run_id: afterRunId } : {}
19490
+ };
19491
+ send({ jsonrpc: "2.0", method: "goal.ready", params: this.offer });
19492
+ }
19493
+ bound(requested) {
19494
+ if (requested !== void 0 && requested !== this.state.sessionId)
19495
+ throw new GoalConflict("Goal request belongs to a different session.");
19496
+ return this.state.sessionId;
19497
+ }
19498
+ requireIdle() {
19499
+ if (this.state.activeRunId)
19500
+ throw new GoalConflict("Wait for the active run to finish.", "busy");
19501
+ }
19502
+ async recoverable(claim) {
19503
+ try {
19504
+ process.kill(claim.owner_pid, 0);
19505
+ } catch (error) {
19506
+ return error.code === "ESRCH";
19507
+ }
19508
+ if (!claim.owner_identity) return false;
19509
+ const current = await (0, import_storage18.getProcessIdentity)(claim.owner_pid, {
19510
+ canonicalEnvironment: true
19511
+ });
19512
+ return current !== null && current !== claim.owner_identity;
19513
+ }
19514
+ /** Pause intent is latched before joining the admission queue. */
19515
+ handle(requestId, method, raw, serialize, interrupt, onError) {
19516
+ if (!this.enabled) {
19517
+ sendError(requestId, {
19518
+ code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
19519
+ message: "Goals are unavailable on this connection."
19520
+ });
19521
+ return Promise.resolve();
19522
+ }
19523
+ const pause = method === "goal.pause" ? schemas[method].safeParse(raw) : void 0;
19524
+ 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;
19525
+ if (revoked) this.disarm();
19526
+ if (pause?.success && this.state.sessionId === pause.data.session_id) {
19527
+ const { goal_id, activation_id, run_id, continuation_id } = pause.data;
19528
+ const run = this.activeRun;
19529
+ 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))
19530
+ interrupt(run.runId);
19531
+ }
19532
+ return serialize(async () => {
19533
+ let goal;
19534
+ let sessionId;
19535
+ let cleared = false;
19536
+ switch (method) {
19537
+ case "goal.get": {
19538
+ const params = schemas[method].parse(raw ?? {});
19539
+ sessionId = this.bound(params.session_id);
19540
+ const result = sessionId ? await this.store.read(sessionId, params.continuation_id) : null;
19541
+ sendResult(
19542
+ requestId,
19543
+ this.snapshot(
19544
+ sessionId,
19545
+ result?.entry?.goal ?? null,
19546
+ result?.acceptedRunId
19547
+ )
19548
+ );
19549
+ return;
19550
+ }
19551
+ case "goal.set": {
19552
+ const params = schemas[method].parse(raw);
19553
+ this.requireIdle();
19554
+ sessionId = this.bound(params.session_id);
19555
+ const fresh = sessionId === null;
19556
+ if (fresh && !params.objective)
19557
+ throw new GoalConflict("Set a goal first.");
19558
+ const key = sessionId ?? this.state.nextSessionId();
19559
+ if (fresh) {
19560
+ const root = this.workspaceRoot();
19561
+ const meta = mergeSessionModelOverrideIntoMeta(
19562
+ root ? { codelia_workspace_root: root } : void 0,
19563
+ this.state.sessionModelOverride
19564
+ );
19565
+ await this.sessions.save({
19566
+ schema_version: 1,
19567
+ session_id: key,
19568
+ updated_at: stamp(),
19569
+ messages: [],
19570
+ ...meta ? { meta } : {}
19571
+ });
19572
+ }
19573
+ let created = false;
19574
+ goal = await this.store.update(key, (tx) => {
19575
+ if (!tx.entry) {
19576
+ if (!params.objective || params.goal_id !== void 0 || params.revision !== void 0)
19577
+ throw new GoalConflict("Set a goal first.");
19578
+ const now = stamp();
19579
+ created = true;
19580
+ tx.entry = {
19581
+ goal: {
19582
+ session_id: key,
19583
+ goal_id: crypto.randomUUID(),
19584
+ revision: 1,
19585
+ objective: params.objective,
19586
+ status: "active",
19587
+ token_budget: params.token_budget ?? null,
19588
+ tokens_used: 0,
19589
+ usage_known: true,
19590
+ activation_id: crypto.randomUUID(),
19591
+ automatic_runs: 0,
19592
+ created_at: now,
19593
+ updated_at: now
19594
+ }
19595
+ };
19596
+ return tx.entry.goal;
19597
+ }
19598
+ const expected = target.parse(params);
19599
+ const entry = readTarget(tx.entry, expected);
19600
+ if (entry.claim)
19601
+ throw new GoalConflict("A goal run is still reserved.", "busy");
19602
+ if (entry.goal.status === "complete")
19603
+ throw new GoalConflict("Clear the completed goal first.");
19604
+ if (params.objective !== void 0) {
19605
+ entry.goal.objective = params.objective;
19606
+ entry.blocker = void 0;
19607
+ }
19608
+ if (params.token_budget !== void 0)
19609
+ entry.goal.token_budget = params.token_budget;
19610
+ if (entry.goal.status !== "active" || !stopForBudget(entry.goal))
19611
+ transition(entry.goal, entry.goal.status, entry.goal.stop_reason);
19612
+ return entry.goal;
19613
+ });
19614
+ if (fresh) {
19615
+ this.state.sessionId = key;
19616
+ this.state.attachments?.bindDraft(key);
19617
+ }
19618
+ sessionId = key;
19619
+ if (created) this.arm(goal);
19620
+ else this.offer = null;
19621
+ break;
19622
+ }
19623
+ case "goal.pause": {
19624
+ const params = schemas[method].parse(raw);
19625
+ this.bound(params.session_id);
19626
+ sessionId = params.session_id;
19627
+ if (!revoked)
19628
+ throw new GoalConflict("Goal is not active on this connection.");
19629
+ goal = await this.store.update(sessionId, ({ entry }) => {
19630
+ if (!entry || entry.goal.goal_id !== params.goal_id || entry.goal.activation_id !== params.activation_id)
19631
+ throw new GoalConflict("Goal changed. Use /goal to refresh.");
19632
+ if (entry.goal.status === "active")
19633
+ transition(entry.goal, "paused", "user");
19634
+ return entry.goal;
19635
+ });
19636
+ break;
19637
+ }
19638
+ case "goal.resume": {
19639
+ const params = schemas[method].parse(raw);
19640
+ this.bound(params.session_id);
19641
+ this.requireIdle();
19642
+ sessionId = params.session_id;
19643
+ const previous = readTarget(
19644
+ (await this.store.read(sessionId)).entry,
19645
+ params
19646
+ );
19647
+ if (previous.goal.status === "complete")
19648
+ throw new GoalConflict("Goal is complete.");
19649
+ const orphan = previous.claim;
19650
+ if (orphan && !await this.recoverable(orphan))
19651
+ throw new GoalConflict(
19652
+ "A goal run is still reserved by a live or unverified runtime.",
19653
+ "busy"
19654
+ );
19655
+ goal = await this.store.update(sessionId, (tx) => {
19656
+ const entry = readTarget(tx.entry, params);
19657
+ if (entry.claim?.run_id !== orphan?.run_id)
19658
+ throw new GoalConflict("Goal run reservation changed.", "busy");
19659
+ if (orphan?.pending_seq !== void 0)
19660
+ entry.goal.usage_known = false;
19661
+ entry.claim = void 0;
19662
+ if (stopForBudget(entry.goal)) return entry.goal;
19663
+ entry.goal.activation_id = crypto.randomUUID();
19664
+ entry.goal.automatic_runs = 0;
19665
+ entry.blocker = void 0;
19666
+ transition(entry.goal, "active");
19667
+ return entry.goal;
19668
+ });
19669
+ if (goal.status === "active") this.arm(goal);
19670
+ else this.disarm();
19671
+ break;
19672
+ }
19673
+ case "goal.clear": {
19674
+ const params = schemas[method].parse(raw);
19675
+ this.bound(params.session_id);
19676
+ this.requireIdle();
19677
+ sessionId = params.session_id;
19678
+ await this.store.update(sessionId, (tx) => {
19679
+ if (readTarget(tx.entry, params).claim)
19680
+ throw new GoalConflict("A goal run is still reserved.", "busy");
19681
+ tx.entry = null;
19682
+ });
19683
+ this.disarm();
19684
+ goal = null;
19685
+ cleared = true;
19686
+ }
19687
+ }
19688
+ const snapshot = this.snapshot(sessionId, goal);
19689
+ sendResult(requestId, snapshot);
19690
+ if (cleared)
19691
+ send({ jsonrpc: "2.0", method: "goal.cleared", params: snapshot });
19692
+ if (goal) {
19693
+ this.publish(goal);
19694
+ if (method === "goal.set" || method === "goal.resume") this.ready(goal);
19695
+ }
19696
+ }).catch((error) => {
19697
+ if (!(error instanceof GoalConflict) && !(error instanceof import_zod36.z.ZodError)) {
19698
+ if (method !== "goal.get") this.disarm();
19699
+ onError(error);
19700
+ }
19701
+ this.reject(requestId, error);
19702
+ });
19703
+ }
19704
+ reject(requestId, error) {
19705
+ const conflict = error instanceof GoalConflict ? error : null;
19706
+ sendError(requestId, {
19707
+ 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,
19708
+ message: conflict?.message ?? (error instanceof import_zod36.z.ZodError ? "Invalid goal parameters." : "Goal operation failed.")
19709
+ });
19710
+ }
19711
+ validateOffer(raw) {
19712
+ if (!this.enabled)
19713
+ throw new GoalConflict("Goals are unavailable on this connection.");
19714
+ const offer = readySchema.parse(raw);
19715
+ this.bound(offer.session_id);
19716
+ 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)
19717
+ throw new GoalConflict("Continuation is stale or already used.");
19718
+ return offer;
19719
+ }
19720
+ canStart(run) {
19721
+ return this.owns(run.goal);
19722
+ }
19723
+ stopAfterStorageFailure(run) {
19724
+ if (this.owns(run.goal)) this.disarm();
19725
+ this.publish(run.goal);
19726
+ }
19727
+ async reserve(sessionId, runId, offer, compaction) {
19728
+ const saved = await this.store.read(sessionId).catch((error) => {
19729
+ if (offer || this.activation) throw error;
19730
+ return null;
19731
+ });
19732
+ const initial = saved?.entry;
19733
+ if (initial?.claim)
19734
+ throw new GoalConflict(
19735
+ "A goal run is already reserved for this session.",
19736
+ "busy"
19737
+ );
19738
+ if (initial?.goal.status !== "active" || !this.owns(initial.goal)) {
19739
+ if (offer) throw new GoalConflict("Goal is no longer active.");
19740
+ return;
19741
+ }
19742
+ this.identity ??= (0, import_storage18.getProcessIdentity)(process.pid, {
19743
+ canonicalEnvironment: true
19744
+ });
19745
+ const ownerIdentity = await this.identity;
19746
+ const run = await this.store.update(sessionId, (tx) => {
19747
+ if (offer) this.validateOffer(offer);
19748
+ const entry = tx.entry;
19749
+ if (entry?.claim)
19750
+ throw new GoalConflict(
19751
+ "A goal run is already reserved for this session.",
19752
+ "busy"
19753
+ );
19754
+ if (entry?.goal.status !== "active" || !this.owns(entry.goal)) {
19755
+ if (offer) throw new GoalConflict("Goal is no longer active.");
19756
+ return;
19757
+ }
19758
+ if (offer && (entry.goal.goal_id !== offer.goal_id || entry.goal.revision !== offer.revision || entry.goal.automatic_runs >= 3))
19759
+ throw new GoalConflict("Goal no longer accepts this continuation.");
19760
+ if (offer) {
19761
+ tx.consume(offer.continuation_id, entry.goal.goal_id, runId);
19762
+ entry.goal.automatic_runs += 1;
19763
+ }
19764
+ entry.claim = {
19765
+ run_id: runId,
19766
+ revision: entry.goal.revision,
19767
+ activation_id: entry.goal.activation_id,
19768
+ continuation_id: offer?.continuation_id,
19769
+ owner_pid: process.pid,
19770
+ owner_identity: ownerIdentity
19771
+ };
19772
+ return {
19773
+ goal: entry.goal,
19774
+ runId,
19775
+ continuationId: offer?.continuation_id,
19776
+ compaction
19777
+ };
19778
+ });
19779
+ if (run) {
19780
+ this.offer = null;
19781
+ this.activeRun = run;
19782
+ }
19783
+ return run;
19784
+ }
19785
+ tools(run) {
19786
+ return [
19787
+ (0, import_core35.defineTool)({
19788
+ name: "get_goal",
19789
+ 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.",
19790
+ input: import_zod36.z.object({}),
19791
+ execute: async () => {
19792
+ const entry = (await this.store.read(run.goal.session_id)).entry;
19793
+ const goal = entry?.claim?.run_id === run.runId ? entry.goal : null;
19794
+ return {
19795
+ type: "json",
19796
+ value: { goal },
19797
+ display_content: goal ? `Goal (${goal.status.replaceAll("_", " ")})
19798
+ ${goal.objective}` : "This run no longer holds the goal reservation."
19799
+ };
19800
+ }
19801
+ }),
19802
+ (0, import_core35.defineTool)({
19803
+ name: "update_goal",
19804
+ description: "Report verified goal completion or a blocker that prevents further work before giving your final answer.",
19805
+ input: import_zod36.z.object({
19806
+ status: import_zod36.z.enum(["complete", "blocked"]).describe(
19807
+ "Use complete after verifying every goal requirement, or blocked when a concrete obstacle prevents further work. Omit the tool call for ordinary progress."
19808
+ ),
19809
+ evidence: import_zod36.z.string().trim().min(1).max(2e3).describe(
19810
+ "For complete, state what you verified and the observed result. For blocked, state the obstacle and why it prevents further work."
19811
+ ),
19812
+ blocker_key: import_zod36.z.string().trim().min(1).max(200).optional().describe(
19813
+ "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."
19814
+ )
19815
+ }),
19816
+ execute: (report) => {
19817
+ if (report.status === "blocked" && !report.blocker_key)
19818
+ throw new Error("blocked requires blocker_key");
19819
+ if (!this.owns(run.goal)) throw new Error("Goal stopped or changed");
19820
+ run.report = report;
19821
+ const label = report.status === "complete" ? "Completion" : "Blocker";
19822
+ return {
19823
+ type: "json",
19824
+ value: {
19825
+ recorded: true,
19826
+ applied_after_successful_finalization: true
19827
+ },
19828
+ display_content: `${label} report recorded for evaluation after successful finalization.
19829
+ ${report.evidence}`
19830
+ };
19831
+ }
19832
+ })
19833
+ ];
19834
+ }
19835
+ observer(run) {
19836
+ return {
19837
+ started: async (seq) => this.store.update(run.goal.session_id, ({ entry }) => {
19838
+ if (entry?.claim?.run_id !== run.runId)
19839
+ throw new Error("Goal run reservation missing");
19840
+ entry.claim.pending_seq = seq;
19841
+ }),
19842
+ completed: async (seq, usage, uncertain) => this.store.update(run.goal.session_id, ({ entry }) => {
19843
+ if (entry?.claim?.run_id !== run.runId)
19844
+ throw new Error("Goal run reservation missing");
19845
+ const claim = entry.claim;
19846
+ if (claim.accounted_seq !== void 0 && claim.accounted_seq >= seq)
19847
+ return;
19848
+ if (claim.pending_seq !== seq)
19849
+ throw new Error("Goal invocation is missing its reservation");
19850
+ const input = usage?.input_tokens;
19851
+ const cached = usage?.input_cached_tokens ?? 0;
19852
+ const output = usage?.output_tokens;
19853
+ const tokens = typeof input === "number" && typeof output === "number" && [input, cached, output].every(
19854
+ (value) => Number.isSafeInteger(value) && value >= 0
19855
+ ) && cached <= input ? input - cached + output : null;
19856
+ if (tokens !== null && Number.isSafeInteger(entry.goal.tokens_used + tokens))
19857
+ entry.goal.tokens_used += tokens;
19858
+ else entry.goal.usage_known = false;
19859
+ if (uncertain) entry.goal.usage_known = false;
19860
+ entry.goal.updated_at = stamp();
19861
+ claim.pending_seq = void 0;
19862
+ claim.accounted_seq = seq;
19863
+ })
19864
+ };
19865
+ }
19866
+ async finish(run, outcome, saved) {
19867
+ if (this.activeRun?.runId === run.runId) this.activeRun = void 0;
19868
+ const goal = await this.store.update(run.goal.session_id, ({ entry }) => {
19869
+ if (entry?.claim?.run_id !== run.runId) return null;
19870
+ if (entry.claim.pending_seq !== void 0) entry.goal.usage_known = false;
19871
+ entry.claim = void 0;
19872
+ const goal2 = entry.goal;
19873
+ if (goal2.status !== "active" || goal2.revision !== run.goal.revision || !this.owns(goal2))
19874
+ return goal2;
19875
+ if (!saved) transition(goal2, "paused", "checkpoint_failed");
19876
+ else if (outcome !== "completed")
19877
+ transition(
19878
+ goal2,
19879
+ "paused",
19880
+ outcome === "error" ? "run_error" : "interrupted"
19881
+ );
19882
+ else if (run.compaction) stopForBudget(goal2);
19883
+ else if (run.report?.status === "complete") transition(goal2, "complete");
19884
+ else {
19885
+ const key = run.report?.blocker_key;
19886
+ entry.blocker = key && run.report?.status === "blocked" ? {
19887
+ key,
19888
+ runs: entry.blocker?.key === key ? entry.blocker.runs + 1 : 1
19889
+ } : void 0;
19890
+ if ((entry.blocker?.runs ?? 0) >= 3) {
19891
+ transition(goal2, "blocked", "blocker");
19892
+ goal2.stop_detail = run.report?.evidence;
19893
+ } else if (!stopForBudget(goal2) && goal2.automatic_runs >= 3)
19894
+ transition(goal2, "paused", "turn_limit");
19895
+ }
19896
+ return goal2;
19897
+ });
19898
+ if (goal) {
19899
+ if (goal.status !== "active" && this.owns(goal)) this.disarm();
19900
+ this.publish(goal);
19901
+ }
19902
+ return goal;
19903
+ }
19904
+ };
19905
+
19906
+ // src/rpc/run-debug.ts
19907
+ var import_core36 = require("@codelia/core");
19376
19908
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
19377
19909
  var DEBUG_MAX_LOG_CHARS = 2e4;
19378
19910
  var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
@@ -19390,7 +19922,7 @@ var stringifyUnknown = (value) => {
19390
19922
  }
19391
19923
  };
19392
19924
  var contentToDebugText = (content, maxChars) => {
19393
- const text = (0, import_core35.stringifyContent)(content, {
19925
+ const text = (0, import_core36.stringifyContent)(content, {
19394
19926
  mode: "log",
19395
19927
  joiner: "\n",
19396
19928
  includeOtherPayload: true
@@ -19974,7 +20506,8 @@ var createRunHandlers = ({
19974
20506
  runEventStoreFactory,
19975
20507
  sessionStateStore,
19976
20508
  appendSession,
19977
- beforeRunStart
20509
+ beforeRunStart,
20510
+ goalStore
19978
20511
  }) => {
19979
20512
  let activeRunAbort = null;
19980
20513
  const steerAttachments = /* @__PURE__ */ new Map();
@@ -19983,6 +20516,18 @@ var createRunHandlers = ({
19983
20516
  steerAttachments.delete(steerId);
19984
20517
  };
19985
20518
  let runStartQueue = Promise.resolve();
20519
+ const goals = goalStore ? new GoalController(
20520
+ state,
20521
+ goalStore,
20522
+ sessionStateStore,
20523
+ () => resolveSessionWorkspaceRoot(state)
20524
+ ) : void 0;
20525
+ const serializeAdmission = (action) => {
20526
+ const admit = () => state.withAdmissionLock(action);
20527
+ const queued = runStartQueue.then(admit);
20528
+ runStartQueue = queued.catch(() => void 0);
20529
+ return queued;
20530
+ };
19986
20531
  let runSteerQueue = Promise.resolve();
19987
20532
  let sessionOpenSettled = Promise.resolve();
19988
20533
  const normalizeRuntimeAgentHistory = (label, runtimeAgent) => {
@@ -20041,24 +20586,34 @@ var createRunHandlers = ({
20041
20586
  ...final !== void 0 ? { final } : {}
20042
20587
  });
20043
20588
  };
20044
- const handleRunStart = (id, params) => {
20589
+ const handleRunStart = (id2, params, continuation) => {
20045
20590
  let admittedRunId = null;
20046
20591
  let responseSent = false;
20592
+ let admittedGoal;
20047
20593
  const run = async () => {
20594
+ let offer;
20595
+ if (continuation !== void 0 && goals) {
20596
+ try {
20597
+ offer = goals.validateOffer(continuation);
20598
+ } catch (error) {
20599
+ goals.reject(id2, error);
20600
+ return;
20601
+ }
20602
+ }
20048
20603
  let initialInput;
20049
20604
  try {
20050
20605
  initialInput = normalizeRunInput(params.input);
20051
20606
  } catch (error) {
20052
- sendError(id, {
20053
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20607
+ sendError(id2, {
20608
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20054
20609
  message: String(error)
20055
20610
  });
20056
20611
  return;
20057
20612
  }
20058
20613
  const attachmentIds = runAttachmentIds(initialInput);
20059
20614
  if (params.force_compaction && attachmentIds.length > 0) {
20060
- sendError(id, {
20061
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20615
+ sendError(id2, {
20616
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20062
20617
  message: "A compaction run cannot admit new attachments"
20063
20618
  });
20064
20619
  return;
@@ -20067,16 +20622,16 @@ var createRunHandlers = ({
20067
20622
  try {
20068
20623
  await beforeRunStart();
20069
20624
  } catch (error) {
20070
- sendError(id, {
20071
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20625
+ sendError(id2, {
20626
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20072
20627
  message: `startup onboarding failed: ${String(error)}`
20073
20628
  });
20074
20629
  return;
20075
20630
  }
20076
20631
  }
20077
20632
  if (state.activeRunId) {
20078
- sendError(id, {
20079
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_BUSY,
20633
+ sendError(id2, {
20634
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
20080
20635
  message: "runtime busy"
20081
20636
  });
20082
20637
  return;
@@ -20092,15 +20647,15 @@ var createRunHandlers = ({
20092
20647
  try {
20093
20648
  resumeState = await sessionStateStore.load(requestedSessionId);
20094
20649
  } catch (error) {
20095
- sendError(id, {
20096
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20650
+ sendError(id2, {
20651
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20097
20652
  message: `session load failed: ${String(error)}`
20098
20653
  });
20099
20654
  return;
20100
20655
  }
20101
20656
  if (!resumeState) {
20102
- sendError(id, {
20103
- code: import_protocol13.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20657
+ sendError(id2, {
20658
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20104
20659
  message: "session not found"
20105
20660
  });
20106
20661
  return;
@@ -20110,8 +20665,8 @@ var createRunHandlers = ({
20110
20665
  try {
20111
20666
  resumeState = await sessionStateStore.load(state.sessionId);
20112
20667
  } catch (error) {
20113
- sendError(id, {
20114
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20668
+ sendError(id2, {
20669
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20115
20670
  message: `session reload failed: ${String(error)}`
20116
20671
  });
20117
20672
  return;
@@ -20121,8 +20676,8 @@ var createRunHandlers = ({
20121
20676
  }
20122
20677
  }
20123
20678
  if (resumeState?.meta?.codelia_subagent) {
20124
- sendError(id, {
20125
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20679
+ sendError(id2, {
20680
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20126
20681
  message: "Delegated sessions cannot be resumed as a root run"
20127
20682
  });
20128
20683
  return;
@@ -20145,8 +20700,8 @@ var createRunHandlers = ({
20145
20700
  }
20146
20701
  } catch (error) {
20147
20702
  state.sessionModelOverride = previousModelOverride;
20148
- sendError(id, {
20149
- code: error instanceof AttachmentAdmissionError ? import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20703
+ sendError(id2, {
20704
+ code: error instanceof AttachmentAdmissionError ? import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20150
20705
  message: error instanceof Error ? error.message : String(error)
20151
20706
  });
20152
20707
  return;
@@ -20162,8 +20717,8 @@ var createRunHandlers = ({
20162
20717
  });
20163
20718
  } catch (error) {
20164
20719
  state.sessionModelOverride = previousModelOverride;
20165
- sendError(id, {
20166
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20720
+ sendError(id2, {
20721
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20167
20722
  message: String(error)
20168
20723
  });
20169
20724
  return;
@@ -20175,8 +20730,8 @@ var createRunHandlers = ({
20175
20730
  });
20176
20731
  } catch {
20177
20732
  state.sessionModelOverride = previousModelOverride;
20178
- sendError(id, {
20179
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
20733
+ sendError(id2, {
20734
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20180
20735
  message: "Could not claim the attachments for this conversation. Upload them again."
20181
20736
  });
20182
20737
  return;
@@ -20209,6 +20764,7 @@ var createRunHandlers = ({
20209
20764
  state.sessionId = sessionId;
20210
20765
  }
20211
20766
  const switchedSession = previousSessionId !== sessionId;
20767
+ if (switchedSession) goals?.disarm();
20212
20768
  if (loadedSessionState && resumeState) {
20213
20769
  const restoredTodos = readTodosFromSessionMeta(resumeState.meta);
20214
20770
  if (restoredTodos.length > 0) {
@@ -20228,9 +20784,33 @@ var createRunHandlers = ({
20228
20784
  ...runMeta
20229
20785
  };
20230
20786
  }
20787
+ if (goals?.enabled) {
20788
+ try {
20789
+ admittedGoal = await goals.reserve(
20790
+ sessionId,
20791
+ runId,
20792
+ offer,
20793
+ params.force_compaction === true
20794
+ );
20795
+ if (admittedGoal && !goals.canStart(admittedGoal)) {
20796
+ await goals.finish(admittedGoal, "cancelled", true);
20797
+ throw new Error("Goal was paused before launch.");
20798
+ }
20799
+ } catch (error) {
20800
+ goals.reject(id2, error);
20801
+ return;
20802
+ }
20803
+ }
20804
+ const goalTools = goals && admittedGoal && !admittedGoal.compaction ? goals.tools(admittedGoal) : [];
20805
+ if (admittedGoal && state.tools?.some(
20806
+ (tool) => goalTools.some((goalTool) => goalTool.name === tool.name)
20807
+ ))
20808
+ throw new Error("Goal tool name conflicts with a runtime tool.");
20231
20809
  state.autoApprovedClientToolNames = new Set(
20232
20810
  (params.tools ?? []).filter((tool) => tool.approval === "never").map((tool) => tool.name)
20233
20811
  );
20812
+ for (const tool of goalTools)
20813
+ state.autoApprovedClientToolNames.add(tool.name);
20234
20814
  const startedAt = nowIso5();
20235
20815
  state.beginRun(runId, params.ui_context ?? state.lastUiContext);
20236
20816
  admittedRunId = runId;
@@ -20415,6 +20995,15 @@ var createRunHandlers = ({
20415
20995
  });
20416
20996
  appendSession({
20417
20997
  type: "run.start",
20998
+ ...offer ? { source: "goal" } : {},
20999
+ ...admittedGoal ? {
21000
+ goal: {
21001
+ goal_id: admittedGoal.goal.goal_id,
21002
+ revision: admittedGoal.goal.revision,
21003
+ activation_id: admittedGoal.goal.activation_id,
21004
+ ...offer ? { continuation_id: offer.continuation_id } : {}
21005
+ }
21006
+ } : {},
20418
21007
  run_id: runId,
20419
21008
  session_id: sessionId,
20420
21009
  ts: nowIso5(),
@@ -20434,13 +21023,14 @@ var createRunHandlers = ({
20434
21023
  session_id: sessionId,
20435
21024
  ...sessionStore.filePath ? { session_log_path: sessionStore.filePath } : {}
20436
21025
  };
20437
- sendResult(id, result);
21026
+ sendResult(id2, result);
20438
21027
  responseSent = true;
20439
21028
  log2(`run.start ${runId}`);
20440
21029
  emitRunStatus(runId, "running");
20441
21030
  void (async () => {
20442
21031
  let finalResponse;
20443
- let sessionSaveChain = Promise.resolve();
21032
+ let outcome = "error";
21033
+ let sessionSaveChain = Promise.resolve(true);
20444
21034
  let lastSessionSaveAt = 0;
20445
21035
  const polledUnconfirmedSteers = [];
20446
21036
  const emitRunSummaryDiagnostics = () => {
@@ -20470,9 +21060,9 @@ var createRunHandlers = ({
20470
21060
  }
20471
21061
  return { unconsumed_steer_ids: unconsumedSteerIds };
20472
21062
  };
20473
- const queueSessionSave = async (reason) => {
21063
+ const queueSessionSave = (reason) => {
20474
21064
  sessionSaveChain = sessionSaveChain.then(async () => {
20475
- if (!sessionId) return;
21065
+ if (!sessionId) return false;
20476
21066
  const messages = runtimeAgent.getHistoryMessages();
20477
21067
  const snapshotMessages = normalizeToolCallHistory(
20478
21068
  stripStartupSystemMessages(
@@ -20513,10 +21103,12 @@ var createRunHandlers = ({
20513
21103
  await sessionStateStore.save(snapshot);
20514
21104
  state.sessionMeta = sessionMetaWithResumeContext ?? null;
20515
21105
  logRunDebug(log2, runId, `session.save ${reason}`);
21106
+ return true;
20516
21107
  }).catch((error) => {
20517
21108
  log2(`Error: session-state save failed: ${String(error)}`);
21109
+ return false;
20518
21110
  });
20519
- await sessionSaveChain;
21111
+ return sessionSaveChain;
20520
21112
  };
20521
21113
  const maybeDebouncedSessionSave = () => {
20522
21114
  const now = Date.now();
@@ -20583,7 +21175,17 @@ var createRunHandlers = ({
20583
21175
  pollMessages,
20584
21176
  signal: runAbortController.signal,
20585
21177
  forceCompaction: params.force_compaction,
20586
- tools: clientTools,
21178
+ tools: goalTools.length ? [
21179
+ ...goalTools,
21180
+ ...(clientTools ?? []).filter(
21181
+ (tool) => !goalTools.some((owned) => owned.name === tool.name)
21182
+ )
21183
+ ] : clientTools,
21184
+ ...goals && admittedGoal ? {
21185
+ runContext: `${offer ? "Continue work on the session goal" : "Session goal"} (follow newer user instructions): ${JSON.stringify(admittedGoal.goal.objective)}.`,
21186
+ runtimeInitiated: Boolean(offer),
21187
+ modelCallObserver: goals.observer(admittedGoal)
21188
+ } : {},
20587
21189
  toolChoice: params.tool_choice,
20588
21190
  ...streamDeltas ? { streamDeltas: true } : {}
20589
21191
  })) {
@@ -20657,6 +21259,7 @@ var createRunHandlers = ({
20657
21259
  await queueSessionSave("terminal");
20658
21260
  emitRunSummaryDiagnostics();
20659
21261
  const status = state.cancelRequested ? "cancelled" : "completed";
21262
+ outcome = status;
20660
21263
  const terminalExtras = buildTerminalStatusExtras();
20661
21264
  emitRunStatus(runId, status, void 0, void 0, terminalExtras);
20662
21265
  emitRunEnd(
@@ -20669,6 +21272,7 @@ var createRunHandlers = ({
20669
21272
  deltaCoalescer?.dispose();
20670
21273
  const err = error instanceof Error ? error : new Error(String(error));
20671
21274
  if (state.cancelRequested || isAbortLikeError(err)) {
21275
+ outcome = "cancelled";
20672
21276
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
20673
21277
  await queueSessionSave("cancelled");
20674
21278
  emitRunSummaryDiagnostics();
@@ -20709,40 +21313,53 @@ var createRunHandlers = ({
20709
21313
  if (state.cancelRequested) {
20710
21314
  normalizeRuntimeAgentHistory(`run.cancel ${runId}`, runtimeAgent);
20711
21315
  }
20712
- await queueSessionSave("finally");
21316
+ const saved = await queueSessionSave("finally");
21317
+ const goalRun = admittedGoal;
21318
+ const finalOutcome = state.cancelRequested ? "cancelled" : outcome === "completed" && finalResponse === void 0 ? "error" : outcome;
21319
+ const goal = goals && goalRun ? await goals.finish(goalRun, finalOutcome, saved).catch((error) => {
21320
+ goals.stopAfterStorageFailure(goalRun);
21321
+ log2(`goal accounting failed: ${String(error)}`);
21322
+ return null;
21323
+ }) : null;
20713
21324
  if (activeRunAbort?.runId === runId) {
20714
21325
  activeRunAbort = null;
20715
21326
  }
20716
21327
  state.finishRun(runId);
21328
+ if (goal) goals?.ready(goal, runId);
20717
21329
  }
20718
21330
  })();
20719
21331
  };
20720
- const admit = () => state.withAdmissionLock(run);
20721
- const queued = runStartQueue.then(admit, admit).catch((error) => {
20722
- if (admittedRunId) {
20723
- const runId = admittedRunId;
20724
- if (activeRunAbort?.runId === runId) activeRunAbort = null;
20725
- state.finishRun(runId);
20726
- if (responseSent) {
20727
- try {
20728
- sendRunStatus(state, runId, "error", "runtime start failed");
20729
- } catch {
21332
+ return serializeAdmission(async () => {
21333
+ try {
21334
+ await run();
21335
+ return;
21336
+ } catch (error) {
21337
+ if (goals && admittedGoal) {
21338
+ await goals.finish(admittedGoal, "error", true).catch((cleanupError) => {
21339
+ goals.disarm();
21340
+ log2(`goal admission cleanup failed: ${String(cleanupError)}`);
21341
+ });
21342
+ }
21343
+ if (admittedRunId) {
21344
+ const runId = admittedRunId;
21345
+ if (activeRunAbort?.runId === runId) activeRunAbort = null;
21346
+ state.finishRun(runId);
21347
+ if (responseSent) {
21348
+ try {
21349
+ sendRunStatus(state, runId, "error", "runtime start failed");
21350
+ } catch {
21351
+ }
20730
21352
  }
20731
21353
  }
21354
+ throw error;
20732
21355
  }
20733
- throw error;
20734
21356
  });
20735
- runStartQueue = queued.then(
20736
- () => void 0,
20737
- () => void 0
20738
- );
20739
- return queued;
20740
21357
  };
20741
- const handleRunSteer = (id, params) => {
21358
+ const handleRunSteer = (id2, params) => {
20742
21359
  const runId = typeof params?.run_id === "string" ? params.run_id.trim() : "";
20743
21360
  if (!runId) {
20744
- sendError(id, {
20745
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21361
+ sendError(id2, {
21362
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20746
21363
  message: "run_id is required"
20747
21364
  });
20748
21365
  return Promise.resolve();
@@ -20751,15 +21368,15 @@ var createRunHandlers = ({
20751
21368
  try {
20752
21369
  initialInput = normalizeRunInput(params.input, "run.steer");
20753
21370
  } catch (error) {
20754
- sendError(id, {
20755
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21371
+ sendError(id2, {
21372
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20756
21373
  message: String(error)
20757
21374
  });
20758
21375
  return Promise.resolve();
20759
21376
  }
20760
21377
  if (isRunInputEmpty(initialInput)) {
20761
- sendError(id, {
20762
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21378
+ sendError(id2, {
21379
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20763
21380
  message: "run.steer input must not be empty"
20764
21381
  });
20765
21382
  return Promise.resolve();
@@ -20767,8 +21384,8 @@ var createRunHandlers = ({
20767
21384
  const clientSteerId = typeof params.client_steer_id === "string" && params.client_steer_id.trim() ? params.client_steer_id.trim() : void 0;
20768
21385
  const admitSteer = async () => {
20769
21386
  if (!state.canSteerRun(runId)) {
20770
- sendError(id, {
20771
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21387
+ sendError(id2, {
21388
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20772
21389
  message: "active run not found"
20773
21390
  });
20774
21391
  return;
@@ -20793,8 +21410,8 @@ var createRunHandlers = ({
20793
21410
  if (state.prepareRunImages)
20794
21411
  normalizedInput = await state.prepareRunImages(normalizedInput);
20795
21412
  } catch (error) {
20796
- sendError(id, {
20797
- code: error instanceof AttachmentAdmissionError ? import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol13.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21413
+ sendError(id2, {
21414
+ code: error instanceof AttachmentAdmissionError ? import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS : import_protocol14.RPC_ERROR_CODE.RUNTIME_INTERNAL,
20798
21415
  message: error instanceof Error ? error.message : String(error)
20799
21416
  });
20800
21417
  return;
@@ -20807,8 +21424,8 @@ var createRunHandlers = ({
20807
21424
  sessionId
20808
21425
  );
20809
21426
  } catch {
20810
- sendError(id, {
20811
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21427
+ sendError(id2, {
21428
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20812
21429
  message: "Could not retain the attachments for this conversation. Upload them again."
20813
21430
  });
20814
21431
  return;
@@ -20816,8 +21433,8 @@ var createRunHandlers = ({
20816
21433
  }
20817
21434
  if (!state.canSteerRun(runId)) {
20818
21435
  releaseAttachments?.();
20819
- sendError(id, {
20820
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21436
+ sendError(id2, {
21437
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20821
21438
  message: "active run ended before steer could be queued"
20822
21439
  });
20823
21440
  return;
@@ -20832,7 +21449,7 @@ var createRunHandlers = ({
20832
21449
  ids: attachmentIds,
20833
21450
  release: releaseAttachments
20834
21451
  });
20835
- sendResult(id, {
21452
+ sendResult(id2, {
20836
21453
  ok: true,
20837
21454
  steer_id: steerId
20838
21455
  });
@@ -20845,74 +21462,108 @@ var createRunHandlers = ({
20845
21462
  );
20846
21463
  return queued;
20847
21464
  };
20848
- const handleRunCancel = (id, params) => {
20849
- if (state.cancelRun(params.run_id)) {
20850
- if (activeRunAbort?.runId === params.run_id) {
20851
- activeRunAbort.controller.abort(
20852
- new Error(params.reason ?? "cancelled by user")
20853
- );
20854
- }
20855
- sendResult(id, { ok: true });
21465
+ const interruptRun = (runId, reason = "cancelled by user") => {
21466
+ if (!state.cancelRun(runId)) return false;
21467
+ if (activeRunAbort?.runId === runId)
21468
+ activeRunAbort.controller.abort(new Error(reason));
21469
+ return true;
21470
+ };
21471
+ const handleGoal = (id2, method, raw) => {
21472
+ if (!goals?.enabled) {
21473
+ sendError(id2, {
21474
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21475
+ message: "Goals are unavailable on this connection."
21476
+ });
21477
+ return Promise.resolve();
21478
+ }
21479
+ if (method === "goal.continue") {
21480
+ const params = raw;
21481
+ return handleRunStart(
21482
+ id2,
21483
+ {
21484
+ input: { type: "text", text: "" },
21485
+ session_id: params?.session_id,
21486
+ tools: params?.tools,
21487
+ ui_context: params?.ui_context
21488
+ },
21489
+ raw ?? {}
21490
+ );
21491
+ }
21492
+ return goals.handle(
21493
+ id2,
21494
+ method,
21495
+ raw,
21496
+ serializeAdmission,
21497
+ interruptRun,
21498
+ (error) => log2(`goal operation failed: ${String(error)}`)
21499
+ );
21500
+ };
21501
+ const handleRunCancel = (id2, params) => {
21502
+ if (interruptRun(params.run_id, params.reason)) {
21503
+ sendResult(id2, { ok: true });
20856
21504
  log2(`run.cancel ${params.run_id} (${params.reason ?? "no reason"})`);
20857
21505
  return;
20858
21506
  }
20859
- sendError(id, {
20860
- code: import_protocol13.RPC_ERROR_CODE.RUN_NOT_FOUND,
21507
+ sendError(id2, {
21508
+ code: import_protocol14.RPC_ERROR_CODE.RUN_NOT_FOUND,
20861
21509
  message: "run not found"
20862
21510
  });
20863
21511
  };
20864
- const handleSessionOpen = (id, params) => {
21512
+ const handleSessionOpen = (id2, params) => {
21513
+ const sessionId = params?.session_id?.trim();
21514
+ if (sessionId && sessionId !== state.sessionId && !state.activeRunId)
21515
+ goals?.disarm();
20865
21516
  const open3 = async () => {
20866
- const sessionId = params?.session_id?.trim();
20867
21517
  if (!sessionId) {
20868
- sendError(id, {
20869
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21518
+ sendError(id2, {
21519
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20870
21520
  message: "session_id is required"
20871
21521
  });
20872
21522
  return;
20873
21523
  }
20874
21524
  if (state.activeRunId) {
20875
- sendError(id, {
20876
- code: import_protocol13.RPC_ERROR_CODE.RUNTIME_BUSY,
21525
+ sendError(id2, {
21526
+ code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
20877
21527
  message: "runtime busy"
20878
21528
  });
20879
21529
  return;
20880
21530
  }
20881
21531
  if (sessionId === state.sessionId) {
20882
- sendResult(id, { session_id: sessionId });
21532
+ sendResult(id2, { session_id: sessionId });
20883
21533
  return;
20884
21534
  }
20885
21535
  let opened;
20886
21536
  try {
20887
21537
  opened = await sessionStateStore.load(sessionId);
20888
21538
  } catch (error) {
20889
- sendError(id, {
20890
- code: import_protocol13.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
21539
+ sendError(id2, {
21540
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_LOAD_FAILED,
20891
21541
  message: `session load failed: ${String(error)}`
20892
21542
  });
20893
21543
  return;
20894
21544
  }
20895
21545
  if (!opened) {
20896
- sendError(id, {
20897
- code: import_protocol13.RPC_ERROR_CODE.SESSION_NOT_FOUND,
21546
+ sendError(id2, {
21547
+ code: import_protocol14.RPC_ERROR_CODE.SESSION_NOT_FOUND,
20898
21548
  message: "session not found"
20899
21549
  });
20900
21550
  return;
20901
21551
  }
20902
21552
  if (opened.meta?.codelia_subagent) {
20903
- sendError(id, {
20904
- code: import_protocol13.RPC_ERROR_CODE.INVALID_PARAMS,
21553
+ sendError(id2, {
21554
+ code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
20905
21555
  message: "Delegated sessions cannot be opened as a root session"
20906
21556
  });
20907
21557
  return;
20908
21558
  }
20909
21559
  state.attachments?.discardDraft();
21560
+ goals?.disarm();
20910
21561
  state.sessionId = sessionId;
20911
21562
  state.sessionMeta = toMetaObject(opened.meta) ?? null;
20912
21563
  state.sessionAppend = null;
20913
21564
  applySessionModelOverrideFromMeta(state, opened.meta);
20914
21565
  state.agent = null;
20915
- sendResult(id, { session_id: sessionId });
21566
+ sendResult(id2, { session_id: sessionId });
20916
21567
  log2(`session.open ${sessionId}`);
20917
21568
  };
20918
21569
  const queued = runStartQueue.then(open3, open3);
@@ -20925,6 +21576,7 @@ var createRunHandlers = ({
20925
21576
  };
20926
21577
  const afterSessionOpen = (task) => sessionOpenSettled.then(task);
20927
21578
  return {
21579
+ handleGoal,
20928
21580
  handleRunStart,
20929
21581
  handleRunSteer,
20930
21582
  handleRunCancel,
@@ -20934,25 +21586,25 @@ var createRunHandlers = ({
20934
21586
  };
20935
21587
 
20936
21588
  // src/rpc/session-lifecycle.ts
20937
- var import_protocol14 = require("@codelia/protocol");
20938
- var createSessionUpdateHandler = (options) => async (id, params) => {
21589
+ var import_protocol15 = require("@codelia/protocol");
21590
+ var createSessionUpdateHandler = (options) => async (id2, params) => {
20939
21591
  if (!options.sessions.updateMetadata) {
20940
- sendError(id, {
20941
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21592
+ sendError(id2, {
21593
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20942
21594
  message: "Session lifecycle updates are unavailable"
20943
21595
  });
20944
21596
  return;
20945
21597
  }
20946
21598
  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) {
20947
- sendError(id, {
20948
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21599
+ sendError(id2, {
21600
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20949
21601
  message: "Expected session_id and a boolean pinned or archived update"
20950
21602
  });
20951
21603
  return;
20952
21604
  }
20953
21605
  if (params.archived && options.state.activeRunId && options.state.sessionId === params.session_id) {
20954
- sendError(id, {
20955
- code: import_protocol14.RPC_ERROR_CODE.RUNTIME_BUSY,
21606
+ sendError(id2, {
21607
+ code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
20956
21608
  message: "Wait for the active run before archiving this session"
20957
21609
  });
20958
21610
  return;
@@ -20970,10 +21622,10 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
20970
21622
  }
20971
21623
  }
20972
21624
  const result = { session };
20973
- sendResult(id, result);
21625
+ sendResult(id2, result);
20974
21626
  } catch (error) {
20975
- sendError(id, {
20976
- code: import_protocol14.RPC_ERROR_CODE.INVALID_PARAMS,
21627
+ sendError(id2, {
21628
+ code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
20977
21629
  message: `Session update failed: ${String(error)}`
20978
21630
  });
20979
21631
  }
@@ -20981,8 +21633,8 @@ var createSessionUpdateHandler = (options) => async (id, params) => {
20981
21633
 
20982
21634
  // src/rpc/shell.ts
20983
21635
  var import_node_path24 = __toESM(require("path"), 1);
20984
- var import_protocol15 = require("@codelia/protocol");
20985
- var import_storage18 = require("@codelia/storage");
21636
+ var import_protocol16 = require("@codelia/protocol");
21637
+ var import_storage19 = require("@codelia/storage");
20986
21638
  var COMMAND_PREVIEW_CHARS = 400;
20987
21639
  var DEFAULT_TRUNCATED = {
20988
21640
  stdout: false,
@@ -21037,7 +21689,7 @@ var parseShellOutputRequest = (params) => {
21037
21689
  if (!taskId) {
21038
21690
  return {
21039
21691
  error: {
21040
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21692
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21041
21693
  message: "task_id is required"
21042
21694
  }
21043
21695
  };
@@ -21045,7 +21697,7 @@ var parseShellOutputRequest = (params) => {
21045
21697
  if (params?.stream !== "stdout" && params?.stream !== "stderr") {
21046
21698
  return {
21047
21699
  error: {
21048
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21700
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21049
21701
  message: "stream must be stdout or stderr"
21050
21702
  }
21051
21703
  };
@@ -21053,7 +21705,7 @@ var parseShellOutputRequest = (params) => {
21053
21705
  if (params.line_number !== void 0 && (params.offset !== void 0 || params.limit !== void 0)) {
21054
21706
  return {
21055
21707
  error: {
21056
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21708
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21057
21709
  message: "line_number cannot be combined with offset or limit"
21058
21710
  }
21059
21711
  };
@@ -21061,7 +21713,7 @@ var parseShellOutputRequest = (params) => {
21061
21713
  if (params.line_number === void 0 && (params.char_offset !== void 0 || params.char_limit !== void 0)) {
21062
21714
  return {
21063
21715
  error: {
21064
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21716
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21065
21717
  message: "char_offset/char_limit require line_number"
21066
21718
  }
21067
21719
  };
@@ -21069,7 +21721,7 @@ var parseShellOutputRequest = (params) => {
21069
21721
  if (params.offset !== void 0 && (!Number.isFinite(params.offset) || params.offset < 0)) {
21070
21722
  return {
21071
21723
  error: {
21072
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21724
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21073
21725
  message: "offset must be a non-negative number"
21074
21726
  }
21075
21727
  };
@@ -21077,7 +21729,7 @@ var parseShellOutputRequest = (params) => {
21077
21729
  if (params.limit !== void 0 && (!Number.isFinite(params.limit) || params.limit <= 0)) {
21078
21730
  return {
21079
21731
  error: {
21080
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21732
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21081
21733
  message: "limit must be a positive number"
21082
21734
  }
21083
21735
  };
@@ -21085,7 +21737,7 @@ var parseShellOutputRequest = (params) => {
21085
21737
  if (params.line_number !== void 0 && (!Number.isFinite(params.line_number) || params.line_number <= 0)) {
21086
21738
  return {
21087
21739
  error: {
21088
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21740
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21089
21741
  message: "line_number must be a positive number"
21090
21742
  }
21091
21743
  };
@@ -21093,7 +21745,7 @@ var parseShellOutputRequest = (params) => {
21093
21745
  if (params.char_offset !== void 0 && (!Number.isFinite(params.char_offset) || params.char_offset < 0)) {
21094
21746
  return {
21095
21747
  error: {
21096
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21748
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21097
21749
  message: "char_offset must be a non-negative number"
21098
21750
  }
21099
21751
  };
@@ -21101,7 +21753,7 @@ var parseShellOutputRequest = (params) => {
21101
21753
  if (params.char_limit !== void 0 && (!Number.isFinite(params.char_limit) || params.char_limit <= 0)) {
21102
21754
  return {
21103
21755
  error: {
21104
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21756
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21105
21757
  message: "char_limit must be a positive number"
21106
21758
  }
21107
21759
  };
@@ -21155,7 +21807,7 @@ var parseTaskId = (value) => {
21155
21807
  var toTaskRpcError = (error) => {
21156
21808
  if (!(error instanceof TaskManagerError)) {
21157
21809
  return {
21158
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21810
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21159
21811
  message: String(error)
21160
21812
  };
21161
21813
  }
@@ -21164,24 +21816,24 @@ var toTaskRpcError = (error) => {
21164
21816
  case "invalid_task_id":
21165
21817
  case "unsupported_workspace_mode":
21166
21818
  return {
21167
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21819
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21168
21820
  message: error.message
21169
21821
  };
21170
21822
  case "manager_shutting_down":
21171
21823
  return {
21172
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
21824
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_BUSY,
21173
21825
  message: error.message
21174
21826
  };
21175
21827
  default:
21176
21828
  return {
21177
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21829
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21178
21830
  message: error.message
21179
21831
  };
21180
21832
  }
21181
21833
  };
21182
- var sendTaskError = (id, error) => {
21834
+ var sendTaskError = (id2, error) => {
21183
21835
  const rpcError = toTaskRpcError(error);
21184
- sendError(id, rpcError);
21836
+ sendError(id2, rpcError);
21185
21837
  };
21186
21838
  var requireShellTask = async (taskManager, taskId) => {
21187
21839
  const task = await taskManager.status(taskId);
@@ -21198,7 +21850,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
21198
21850
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21199
21851
  return {
21200
21852
  error: {
21201
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21853
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21202
21854
  message: "timeout_seconds must be a positive number"
21203
21855
  }
21204
21856
  };
@@ -21212,7 +21864,7 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
21212
21864
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
21213
21865
  return {
21214
21866
  error: {
21215
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21867
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21216
21868
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
21217
21869
  }
21218
21870
  };
@@ -21226,7 +21878,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
21226
21878
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21227
21879
  return {
21228
21880
  error: {
21229
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21881
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21230
21882
  message: "wait_timeout_seconds must be a positive number"
21231
21883
  }
21232
21884
  };
@@ -21234,7 +21886,7 @@ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
21234
21886
  if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
21235
21887
  return {
21236
21888
  error: {
21237
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21889
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21238
21890
  message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
21239
21891
  }
21240
21892
  };
@@ -21249,7 +21901,7 @@ var parseShellStartRequest = (state, params, options) => {
21249
21901
  if (!command) {
21250
21902
  return {
21251
21903
  error: {
21252
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21904
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21253
21905
  message: "command is required"
21254
21906
  }
21255
21907
  };
@@ -21265,7 +21917,7 @@ var parseShellStartRequest = (state, params, options) => {
21265
21917
  if (!cwd) {
21266
21918
  return {
21267
21919
  error: {
21268
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
21920
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21269
21921
  message: "cwd is outside sandbox root"
21270
21922
  }
21271
21923
  };
@@ -21285,7 +21937,7 @@ var createShellHandlers = ({
21285
21937
  outputCache
21286
21938
  }) => {
21287
21939
  const shellTaskManager = taskManager ?? new TaskManager();
21288
- const shellOutputCache = outputCache ?? new import_storage18.ToolOutputCacheStoreImpl();
21940
+ const shellOutputCache = outputCache ?? new import_storage19.ToolOutputCacheStoreImpl();
21289
21941
  const activeShellWaits = /* @__PURE__ */ new Map();
21290
21942
  const registerActiveShellWait = (taskId, wait) => {
21291
21943
  const waits = activeShellWaits.get(taskId) ?? /* @__PURE__ */ new Set();
@@ -21327,40 +21979,40 @@ var createShellHandlers = ({
21327
21979
  );
21328
21980
  return { task, commandPreview: parsed.commandPreview };
21329
21981
  };
21330
- const handleShellExec = async (id, params) => {
21982
+ const handleShellExec = async (id2, params) => {
21331
21983
  try {
21332
21984
  const { task, commandPreview } = await spawnShell(params, "shell.exec");
21333
21985
  const finished = await shellTaskManager.wait(task.task_id);
21334
21986
  const result = toShellExecResult(commandPreview, finished.result);
21335
- sendResult(id, result);
21987
+ sendResult(id2, result);
21336
21988
  log2(
21337
21989
  `shell.exec.done origin=ui_bang duration_ms=${result.duration_ms} exit_code=${String(result.exit_code)} signal=${result.signal ?? "-"}`
21338
21990
  );
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 handleShellStart = async (id, params) => {
21999
+ const handleShellStart = async (id2, params) => {
21348
22000
  try {
21349
22001
  const { task } = await spawnShell(params, "shell.start");
21350
- sendResult(id, toShellTaskInfo(task));
22002
+ sendResult(id2, toShellTaskInfo(task));
21351
22003
  } catch (error) {
21352
22004
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
21353
- sendError(id, error);
22005
+ sendError(id2, error);
21354
22006
  return;
21355
22007
  }
21356
- sendTaskError(id, error);
22008
+ sendTaskError(id2, error);
21357
22009
  }
21358
22010
  };
21359
- const handleShellList = async (id, params) => {
22011
+ const handleShellList = async (id2, params) => {
21360
22012
  const requestedLimit = params?.limit;
21361
22013
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
21362
- sendError(id, {
21363
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22014
+ sendError(id2, {
22015
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21364
22016
  message: "limit must be a positive number"
21365
22017
  });
21366
22018
  return;
@@ -21369,31 +22021,31 @@ var createShellHandlers = ({
21369
22021
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
21370
22022
  const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo);
21371
22023
  const result = { tasks };
21372
- sendResult(id, result);
22024
+ sendResult(id2, result);
21373
22025
  } catch (error) {
21374
- sendTaskError(id, error);
22026
+ sendTaskError(id2, error);
21375
22027
  }
21376
22028
  };
21377
- const handleShellStatus = async (id, params) => {
22029
+ const handleShellStatus = async (id2, params) => {
21378
22030
  const taskId = parseTaskId(params?.task_id);
21379
22031
  if (!taskId) {
21380
- sendError(id, {
21381
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22032
+ sendError(id2, {
22033
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21382
22034
  message: "task_id is required"
21383
22035
  });
21384
22036
  return;
21385
22037
  }
21386
22038
  try {
21387
22039
  const task = await requireShellTask(shellTaskManager, taskId);
21388
- sendResult(id, toShellTaskInfo(task));
22040
+ sendResult(id2, toShellTaskInfo(task));
21389
22041
  } catch (error) {
21390
- sendTaskError(id, error);
22042
+ sendTaskError(id2, error);
21391
22043
  }
21392
22044
  };
21393
- const handleShellOutput = async (id, params) => {
22045
+ const handleShellOutput = async (id2, params) => {
21394
22046
  const parsed = parseShellOutputRequest(params);
21395
22047
  if ("error" in parsed) {
21396
- sendError(id, parsed.error);
22048
+ sendError(id2, parsed.error);
21397
22049
  return;
21398
22050
  }
21399
22051
  try {
@@ -21405,8 +22057,8 @@ var createShellHandlers = ({
21405
22057
  parsed.stream
21406
22058
  );
21407
22059
  if (!cacheId && liveContent === null && !isTerminalTaskState(task.state)) {
21408
- sendError(id, {
21409
- code: import_protocol15.RPC_ERROR_CODE.RUNTIME_BUSY,
22060
+ sendError(id2, {
22061
+ code: import_protocol16.RPC_ERROR_CODE.RUNTIME_BUSY,
21410
22062
  message: `shell output is not retained yet for running task: ${parsed.taskId}`
21411
22063
  });
21412
22064
  return;
@@ -21434,16 +22086,16 @@ var createShellHandlers = ({
21434
22086
  content,
21435
22087
  ...cacheId ? { ref_id: cacheId } : {}
21436
22088
  };
21437
- sendResult(id, result);
22089
+ sendResult(id2, result);
21438
22090
  } catch (error) {
21439
- sendTaskError(id, error);
22091
+ sendTaskError(id2, error);
21440
22092
  }
21441
22093
  };
21442
- const handleShellWait = async (id, params) => {
22094
+ const handleShellWait = async (id2, params) => {
21443
22095
  const taskId = parseTaskId(params?.task_id);
21444
22096
  if (!taskId) {
21445
- sendError(id, {
21446
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22097
+ sendError(id2, {
22098
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21447
22099
  message: "task_id is required"
21448
22100
  });
21449
22101
  return;
@@ -21452,13 +22104,13 @@ var createShellHandlers = ({
21452
22104
  params?.wait_timeout_seconds
21453
22105
  );
21454
22106
  if (typeof waitTimeoutSeconds === "object") {
21455
- sendError(id, waitTimeoutSeconds.error);
22107
+ sendError(id2, waitTimeoutSeconds.error);
21456
22108
  return;
21457
22109
  }
21458
22110
  try {
21459
22111
  const existing = await requireShellTask(shellTaskManager, taskId);
21460
22112
  if (isTerminalTaskState(existing.state)) {
21461
- sendResult(id, toShellTaskInfo(existing));
22113
+ sendResult(id2, toShellTaskInfo(existing));
21462
22114
  return;
21463
22115
  }
21464
22116
  const controller = new AbortController();
@@ -21498,12 +22150,12 @@ var createShellHandlers = ({
21498
22150
  timeoutPromise
21499
22151
  ]);
21500
22152
  if (outcome.type === "detached") {
21501
- sendResult(id, outcome.result);
22153
+ sendResult(id2, outcome.result);
21502
22154
  return;
21503
22155
  }
21504
22156
  if (outcome.type === "still_running") {
21505
22157
  const task = await requireShellTask(shellTaskManager, taskId);
21506
- sendResult(id, {
22158
+ sendResult(id2, {
21507
22159
  ...toShellTaskInfo(task),
21508
22160
  ...isTerminalTaskState(task.state) ? {} : { still_running: true }
21509
22161
  });
@@ -21512,7 +22164,7 @@ var createShellHandlers = ({
21512
22164
  if (outcome.type === "aborted") {
21513
22165
  return;
21514
22166
  }
21515
- sendResult(id, toShellTaskInfo(outcome.task));
22167
+ sendResult(id2, toShellTaskInfo(outcome.task));
21516
22168
  } finally {
21517
22169
  if (timeoutHandle) {
21518
22170
  clearTimeout(timeoutHandle);
@@ -21520,14 +22172,14 @@ var createShellHandlers = ({
21520
22172
  unregister();
21521
22173
  }
21522
22174
  } catch (error) {
21523
- sendTaskError(id, error);
22175
+ sendTaskError(id2, error);
21524
22176
  }
21525
22177
  };
21526
- const handleShellDetach = async (id, params) => {
22178
+ const handleShellDetach = async (id2, params) => {
21527
22179
  const taskId = parseTaskId(params?.task_id);
21528
22180
  if (!taskId) {
21529
- sendError(id, {
21530
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22181
+ sendError(id2, {
22182
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21531
22183
  message: "task_id is required"
21532
22184
  });
21533
22185
  return;
@@ -21536,8 +22188,8 @@ var createShellHandlers = ({
21536
22188
  const task = await requireShellTask(shellTaskManager, taskId);
21537
22189
  const waits = activeShellWaits.get(taskId);
21538
22190
  if (!waits || waits.size === 0) {
21539
- sendError(id, {
21540
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22191
+ sendError(id2, {
22192
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21541
22193
  message: `no active shell.wait to detach for task: ${taskId}`
21542
22194
  });
21543
22195
  return;
@@ -21550,16 +22202,16 @@ var createShellHandlers = ({
21550
22202
  detached: true,
21551
22203
  state: task.state
21552
22204
  };
21553
- sendResult(id, result);
22205
+ sendResult(id2, result);
21554
22206
  } catch (error) {
21555
- sendTaskError(id, error);
22207
+ sendTaskError(id2, error);
21556
22208
  }
21557
22209
  };
21558
- const handleShellCancel = async (id, params) => {
22210
+ const handleShellCancel = async (id2, params) => {
21559
22211
  const taskId = parseTaskId(params?.task_id);
21560
22212
  if (!taskId) {
21561
- sendError(id, {
21562
- code: import_protocol15.RPC_ERROR_CODE.INVALID_PARAMS,
22213
+ sendError(id2, {
22214
+ code: import_protocol16.RPC_ERROR_CODE.INVALID_PARAMS,
21563
22215
  message: "task_id is required"
21564
22216
  });
21565
22217
  return;
@@ -21569,9 +22221,9 @@ var createShellHandlers = ({
21569
22221
  const task = await shellTaskManager.cancel(taskId, {
21570
22222
  reason: "cancelled"
21571
22223
  });
21572
- sendResult(id, toShellTaskInfo(task));
22224
+ sendResult(id2, toShellTaskInfo(task));
21573
22225
  } catch (error) {
21574
- sendTaskError(id, error);
22226
+ sendTaskError(id2, error);
21575
22227
  }
21576
22228
  };
21577
22229
  return {
@@ -21588,19 +22240,19 @@ var createShellHandlers = ({
21588
22240
 
21589
22241
  // src/rpc/skills.ts
21590
22242
  var import_node_path25 = __toESM(require("path"), 1);
21591
- var import_protocol16 = require("@codelia/protocol");
22243
+ var import_protocol17 = require("@codelia/protocol");
21592
22244
  var createSkillsHandlers = ({
21593
22245
  state,
21594
22246
  log: log2
21595
22247
  }) => {
21596
- const handleSkillsList = async (id, params) => {
22248
+ const handleSkillsList = async (id2, params) => {
21597
22249
  const requestedCwd = params?.cwd ? import_node_path25.default.resolve(params.cwd) : void 0;
21598
22250
  const workingDir = requestedCwd ?? state.runtimeWorkingDir ?? state.lastUiContext?.cwd ?? process.cwd();
21599
22251
  const forceReload = params?.force_reload ?? false;
21600
22252
  if (!forceReload) {
21601
22253
  const cachedCatalog = state.skillsCatalogByCwd.get(workingDir);
21602
22254
  if (cachedCatalog) {
21603
- sendResult(id, {
22255
+ sendResult(id2, {
21604
22256
  skills: cachedCatalog.skills,
21605
22257
  errors: cachedCatalog.errors,
21606
22258
  truncated: cachedCatalog.truncated
@@ -21617,8 +22269,8 @@ var createSkillsHandlers = ({
21617
22269
  config: await resolveEnvironmentSkillsConfig(state, workingDir)
21618
22270
  });
21619
22271
  } catch (error) {
21620
- sendError(id, {
21621
- code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22272
+ sendError(id2, {
22273
+ code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21622
22274
  message: `skills resolver init failed: ${String(error)}`
21623
22275
  });
21624
22276
  return;
@@ -21636,11 +22288,11 @@ var createSkillsHandlers = ({
21636
22288
  errors: catalog.errors,
21637
22289
  truncated: catalog.truncated
21638
22290
  };
21639
- sendResult(id, result);
22291
+ sendResult(id2, result);
21640
22292
  } catch (error) {
21641
22293
  log2(`skills.list error: ${String(error)}`);
21642
- sendError(id, {
21643
- code: import_protocol16.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22294
+ sendError(id2, {
22295
+ code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21644
22296
  message: `skills list failed: ${String(error)}`
21645
22297
  });
21646
22298
  }
@@ -21650,11 +22302,11 @@ var createSkillsHandlers = ({
21650
22302
 
21651
22303
  // src/rpc/task.ts
21652
22304
  var import_node_path26 = __toESM(require("path"), 1);
21653
- var import_protocol18 = require("@codelia/protocol");
21654
- var import_storage19 = require("@codelia/storage");
22305
+ var import_protocol19 = require("@codelia/protocol");
22306
+ var import_storage20 = require("@codelia/storage");
21655
22307
 
21656
22308
  // src/rpc/tool.ts
21657
- var import_protocol17 = require("@codelia/protocol");
22309
+ var import_protocol18 = require("@codelia/protocol");
21658
22310
  var normalizeToolResult = (result) => {
21659
22311
  switch (result.type) {
21660
22312
  case "json":
@@ -21686,18 +22338,18 @@ var createToolHandlers = ({
21686
22338
  state,
21687
22339
  getAgent
21688
22340
  }) => {
21689
- const handleToolCall = async (id, params) => {
22341
+ const handleToolCall = async (id2, params) => {
21690
22342
  const toolName = params?.name;
21691
22343
  if (!toolName) {
21692
- sendError(id, {
21693
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22344
+ sendError(id2, {
22345
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21694
22346
  message: "tool name is required"
21695
22347
  });
21696
22348
  return;
21697
22349
  }
21698
22350
  if (toolName === "attachment_read" && state.attachments) {
21699
- sendError(id, {
21700
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22351
+ sendError(id2, {
22352
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21701
22353
  message: "attachment_read is only available during a model run"
21702
22354
  });
21703
22355
  return;
@@ -21707,8 +22359,8 @@ var createToolHandlers = ({
21707
22359
  }
21708
22360
  const tool = state.tools?.find((entry) => entry.name === toolName);
21709
22361
  if (!tool) {
21710
- sendError(id, {
21711
- code: import_protocol17.RPC_ERROR_CODE.INVALID_PARAMS,
22362
+ sendError(id2, {
22363
+ code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
21712
22364
  message: `unknown tool: ${toolName}`
21713
22365
  });
21714
22366
  return;
@@ -21722,10 +22374,10 @@ var createToolHandlers = ({
21722
22374
  ok: true,
21723
22375
  result: normalizeToolResult(result)
21724
22376
  };
21725
- sendResult(id, response);
22377
+ sendResult(id2, response);
21726
22378
  } catch (error) {
21727
- sendError(id, {
21728
- code: import_protocol17.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22379
+ sendError(id2, {
22380
+ code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21729
22381
  message: `tool call failed: ${String(error)}`
21730
22382
  });
21731
22383
  }
@@ -21788,7 +22440,7 @@ var parseTaskId2 = (value) => {
21788
22440
  var toTaskRpcError2 = (error) => {
21789
22441
  if (!(error instanceof TaskManagerError)) {
21790
22442
  return {
21791
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22443
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21792
22444
  message: String(error)
21793
22445
  };
21794
22446
  }
@@ -21797,23 +22449,23 @@ var toTaskRpcError2 = (error) => {
21797
22449
  case "invalid_task_id":
21798
22450
  case "unsupported_workspace_mode":
21799
22451
  return {
21800
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22452
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21801
22453
  message: error.message
21802
22454
  };
21803
22455
  case "manager_shutting_down":
21804
22456
  return {
21805
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_BUSY,
22457
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_BUSY,
21806
22458
  message: error.message
21807
22459
  };
21808
22460
  default:
21809
22461
  return {
21810
- code: import_protocol18.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22462
+ code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
21811
22463
  message: error.message
21812
22464
  };
21813
22465
  }
21814
22466
  };
21815
- var sendTaskError2 = (id, error) => {
21816
- sendError(id, toTaskRpcError2(error));
22467
+ var sendTaskError2 = (id2, error) => {
22468
+ sendError(id2, toTaskRpcError2(error));
21817
22469
  };
21818
22470
  var toTaskSummary = (task, progress) => ({
21819
22471
  name: task.subagent?.name,
@@ -21859,7 +22511,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
21859
22511
  if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
21860
22512
  return {
21861
22513
  error: {
21862
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22514
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21863
22515
  message: "timeout_seconds must be a positive number"
21864
22516
  }
21865
22517
  };
@@ -21873,7 +22525,7 @@ var resolveShellTimeoutSeconds3 = (requestedTimeout, background) => {
21873
22525
  if (requestedTimeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
21874
22526
  return {
21875
22527
  error: {
21876
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22528
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21877
22529
  message: `background timeout_seconds must be ${MAX_EXECUTION_TIMEOUT_SECONDS} or less; omit timeout_seconds to run without an execution timer`
21878
22530
  }
21879
22531
  };
@@ -21888,7 +22540,7 @@ var parseShellSpawnRequest = (state, params, options) => {
21888
22540
  if (!command) {
21889
22541
  return {
21890
22542
  error: {
21891
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22543
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21892
22544
  message: "command is required for shell tasks"
21893
22545
  }
21894
22546
  };
@@ -21904,7 +22556,7 @@ var parseShellSpawnRequest = (state, params, options) => {
21904
22556
  if (!cwd) {
21905
22557
  return {
21906
22558
  error: {
21907
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22559
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21908
22560
  message: "cwd is outside sandbox root"
21909
22561
  }
21910
22562
  };
@@ -21975,17 +22627,17 @@ var createTaskHandlers = ({
21975
22627
  getAgent
21976
22628
  }) => {
21977
22629
  const tasks = taskManager ?? new TaskManager();
21978
- const taskOutputCache = outputCache ?? new import_storage19.ToolOutputCacheStoreImpl();
22630
+ const taskOutputCache = outputCache ?? new import_storage20.ToolOutputCacheStoreImpl();
21979
22631
  subscribeTaskProgress(state, tasks);
21980
22632
  const requireScope = async (taskId) => {
21981
22633
  const task = await tasks.status(taskId);
21982
22634
  if (task?.kind === "subagent" && task.subagent?.owner_session_id !== state.sessionId)
21983
22635
  throw new TaskManagerError("task_not_found", "Task not found");
21984
22636
  };
21985
- const handleTaskSpawn = async (id, params) => {
22637
+ const handleTaskSpawn = async (id2, params) => {
21986
22638
  if (!params || !isTaskKind(params.kind)) {
21987
- sendError(id, {
21988
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22639
+ sendError(id2, {
22640
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
21989
22641
  message: "kind must be shell or subagent"
21990
22642
  });
21991
22643
  return;
@@ -22001,19 +22653,19 @@ var createTaskHandlers = ({
22001
22653
  signal
22002
22654
  });
22003
22655
  sendResult(
22004
- id,
22656
+ id2,
22005
22657
  subagentTaskInfo(
22006
22658
  params.background === false ? await tasks.wait(task.task_id, { signal }) : task
22007
22659
  )
22008
22660
  );
22009
22661
  } catch (error) {
22010
- sendTaskError2(id, error);
22662
+ sendTaskError2(id2, error);
22011
22663
  }
22012
22664
  return;
22013
22665
  }
22014
22666
  if (params.kind !== "shell") {
22015
- sendError(id, {
22016
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22667
+ sendError(id2, {
22668
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22017
22669
  message: `task kind ${params.kind} is not supported yet.`
22018
22670
  });
22019
22671
  return;
@@ -22021,7 +22673,7 @@ var createTaskHandlers = ({
22021
22673
  const background = params.background !== false;
22022
22674
  const parsed = parseShellSpawnRequest(state, params, { background });
22023
22675
  if ("error" in parsed) {
22024
- sendError(id, parsed.error);
22676
+ sendError(id2, parsed.error);
22025
22677
  return;
22026
22678
  }
22027
22679
  try {
@@ -22048,30 +22700,30 @@ var createTaskHandlers = ({
22048
22700
  const result = background ? toTaskSummary(task, tasks.getProgress(task.task_id)) : toTaskInfo(
22049
22701
  await tasks.wait(task.task_id, { signal: state.activeRunSignal })
22050
22702
  );
22051
- sendResult(id, result);
22703
+ sendResult(id2, result);
22052
22704
  } catch (error) {
22053
- sendTaskError2(id, error);
22705
+ sendTaskError2(id2, error);
22054
22706
  }
22055
22707
  };
22056
- const handleTaskList = async (id, params) => {
22708
+ const handleTaskList = async (id2, params) => {
22057
22709
  const requestedLimit = params?.limit;
22058
22710
  if (requestedLimit !== void 0 && (!Number.isFinite(requestedLimit) || requestedLimit <= 0)) {
22059
- sendError(id, {
22060
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22711
+ sendError(id2, {
22712
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22061
22713
  message: "limit must be a positive number"
22062
22714
  });
22063
22715
  return;
22064
22716
  }
22065
22717
  if (params?.kind !== void 0 && !isTaskKind(params.kind)) {
22066
- sendError(id, {
22067
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22718
+ sendError(id2, {
22719
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22068
22720
  message: "kind must be shell or subagent"
22069
22721
  });
22070
22722
  return;
22071
22723
  }
22072
22724
  if (params?.state !== void 0 && !isTaskState(params.state)) {
22073
- sendError(id, {
22074
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22725
+ sendError(id2, {
22726
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22075
22727
  message: "invalid task state"
22076
22728
  });
22077
22729
  return;
@@ -22082,16 +22734,16 @@ var createTaskHandlers = ({
22082
22734
  (task) => task.kind !== "subagent" || task.subagent?.owner_session_id === state.sessionId
22083
22735
  ).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)));
22084
22736
  const result = { tasks: tasksList };
22085
- sendResult(id, result);
22737
+ sendResult(id2, result);
22086
22738
  } catch (error) {
22087
- sendTaskError2(id, error);
22739
+ sendTaskError2(id2, error);
22088
22740
  }
22089
22741
  };
22090
- const handleTaskStatus = async (id, params) => {
22742
+ const handleTaskStatus = async (id2, params) => {
22091
22743
  const taskId = parseTaskId2(params?.task_id);
22092
22744
  if (!taskId) {
22093
- sendError(id, {
22094
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22745
+ sendError(id2, {
22746
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22095
22747
  message: "task_id is required"
22096
22748
  });
22097
22749
  return;
@@ -22109,16 +22761,16 @@ var createTaskHandlers = ({
22109
22761
  task,
22110
22762
  tasks.getProgress(task.task_id)
22111
22763
  );
22112
- sendResult(id, result);
22764
+ sendResult(id2, result);
22113
22765
  } catch (error) {
22114
- sendTaskError2(id, error);
22766
+ sendTaskError2(id2, error);
22115
22767
  }
22116
22768
  };
22117
- const handleTaskWait = async (id, params) => {
22769
+ const handleTaskWait = async (id2, params) => {
22118
22770
  const taskId = parseTaskId2(params?.task_id);
22119
22771
  if (!taskId) {
22120
- sendError(id, {
22121
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22772
+ sendError(id2, {
22773
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22122
22774
  message: "task_id is required"
22123
22775
  });
22124
22776
  return;
@@ -22130,16 +22782,16 @@ var createTaskHandlers = ({
22130
22782
  task,
22131
22783
  tasks.getProgress(task.task_id)
22132
22784
  );
22133
- sendResult(id, result);
22785
+ sendResult(id2, result);
22134
22786
  } catch (error) {
22135
- sendTaskError2(id, error);
22787
+ sendTaskError2(id2, error);
22136
22788
  }
22137
22789
  };
22138
- const handleTaskCancel = async (id, params) => {
22790
+ const handleTaskCancel = async (id2, params) => {
22139
22791
  const taskId = parseTaskId2(params?.task_id);
22140
22792
  if (!taskId) {
22141
- sendError(id, {
22142
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22793
+ sendError(id2, {
22794
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22143
22795
  message: "task_id is required"
22144
22796
  });
22145
22797
  return;
@@ -22153,16 +22805,16 @@ var createTaskHandlers = ({
22153
22805
  task,
22154
22806
  tasks.getProgress(task.task_id)
22155
22807
  );
22156
- sendResult(id, result);
22808
+ sendResult(id2, result);
22157
22809
  } catch (error) {
22158
- sendTaskError2(id, error);
22810
+ sendTaskError2(id2, error);
22159
22811
  }
22160
22812
  };
22161
- const handleTaskResult = async (id, params) => {
22813
+ const handleTaskResult = async (id2, params) => {
22162
22814
  const taskId = parseTaskId2(params?.task_id);
22163
22815
  if (!taskId) {
22164
- sendError(id, {
22165
- code: import_protocol18.RPC_ERROR_CODE.INVALID_PARAMS,
22816
+ sendError(id2, {
22817
+ code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
22166
22818
  message: "task_id is required"
22167
22819
  });
22168
22820
  return;
@@ -22177,9 +22829,9 @@ var createTaskHandlers = ({
22177
22829
  );
22178
22830
  }
22179
22831
  const result = task.state === "completed" || task.state === "failed" || task.state === "cancelled" ? toTaskInfo(task, tasks.getProgress(task.task_id)) : null;
22180
- sendResult(id, result);
22832
+ sendResult(id2, result);
22181
22833
  } catch (error) {
22182
- sendTaskError2(id, error);
22834
+ sendTaskError2(id2, error);
22183
22835
  }
22184
22836
  };
22185
22837
  return {
@@ -22252,15 +22904,15 @@ var createRuntimeHandlers = ({
22252
22904
  }) => {
22253
22905
  const environment = state.effectiveEnvironment;
22254
22906
  const imageHandlers = createImageHandlers(state);
22255
- const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage20.SessionStateStoreImpl({
22907
+ const sessionStateStore = injectedSessionStateStore ?? environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage21.SessionStateStoreImpl({
22256
22908
  onError: (error, context) => {
22257
22909
  log2(
22258
22910
  `session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
22259
22911
  );
22260
22912
  }
22261
22913
  }));
22262
- const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage20.RunEventStoreFactoryImpl({
22263
- ...sessionStateStore instanceof import_storage20.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
22914
+ const runEventStoreFactory = injectedRunEventStoreFactory ?? environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage21.RunEventStoreFactoryImpl({
22915
+ ...sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
22264
22916
  onRunIndexError: (error) => log2(`session run index error: ${String(error)}`)
22265
22917
  }));
22266
22918
  const mcpManager = injectedMcpManager ?? {
@@ -22394,7 +23046,9 @@ var createRuntimeHandlers = ({
22394
23046
  if (!startupOnboardingPromise) return;
22395
23047
  await startupOnboardingPromise;
22396
23048
  };
23049
+ const goalStore = isTuiLocalEnvironment(environment) && sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? sessionStateStore.goals : void 0;
22397
23050
  const {
23051
+ handleGoal,
22398
23052
  handleRunStart,
22399
23053
  handleRunSteer,
22400
23054
  handleRunCancel,
@@ -22407,7 +23061,8 @@ var createRuntimeHandlers = ({
22407
23061
  runEventStoreFactory,
22408
23062
  sessionStateStore,
22409
23063
  appendSession,
22410
- beforeRunStart: waitForStartupOnboarding
23064
+ beforeRunStart: waitForStartupOnboarding,
23065
+ goalStore
22411
23066
  });
22412
23067
  const { handleSessionList, handleSessionHistory } = createHistoryHandlers({
22413
23068
  sessionStateStore,
@@ -22474,7 +23129,7 @@ var createRuntimeHandlers = ({
22474
23129
  taskManager: injectedTaskManager,
22475
23130
  outputCache: toolOutputCacheStore ?? void 0
22476
23131
  }) : null;
22477
- const handleInitialize = async (id, params) => {
23132
+ const handleInitialize = async (id2, params) => {
22478
23133
  let resolvedTheme;
22479
23134
  const environment2 = state.effectiveEnvironment;
22480
23135
  if (isTuiLocalEnvironment(environment2)) {
@@ -22510,6 +23165,7 @@ var createRuntimeHandlers = ({
22510
23165
  supports_session_open: true,
22511
23166
  supports_run_cancel: true,
22512
23167
  supports_run_steer: true,
23168
+ supports_goals: Boolean(goalStore),
22513
23169
  supports_run_diagnostics: true,
22514
23170
  supports_session_lifecycle: !!sessionStateStore.updateMetadata,
22515
23171
  supports_shell_exec: processEnabled,
@@ -22538,7 +23194,7 @@ var createRuntimeHandlers = ({
22538
23194
  },
22539
23195
  ...resolvedTheme ? { tui: { theme: resolvedTheme } } : {}
22540
23196
  };
22541
- sendResult(id, result);
23197
+ sendResult(id2, result);
22542
23198
  log2(`initialize from ${params.client?.name ?? "unknown"}`);
22543
23199
  state.lastClientInfo = params.client ?? null;
22544
23200
  state.setUiCapabilities(params.ui_capabilities);
@@ -22550,42 +23206,42 @@ var createRuntimeHandlers = ({
22550
23206
  `ui.context.update cwd=${params.cwd ?? "-"} file=${params.active_file?.path ?? "-"}`
22551
23207
  );
22552
23208
  };
22553
- const handleThemeSet = async (id, params) => {
23209
+ const handleThemeSet = async (id2, params) => {
22554
23210
  if (state.activeRunId) {
22555
- sendError(id, {
22556
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_BUSY,
23211
+ sendError(id2, {
23212
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_BUSY,
22557
23213
  message: "runtime busy"
22558
23214
  });
22559
23215
  return;
22560
23216
  }
22561
23217
  const name2 = params?.name?.trim().toLowerCase();
22562
23218
  if (!name2) {
22563
- sendError(id, {
22564
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23219
+ sendError(id2, {
23220
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22565
23221
  message: "theme name is required"
22566
23222
  });
22567
23223
  return;
22568
23224
  }
22569
23225
  if (!SUPPORTED_TUI_THEMES.has(name2)) {
22570
- sendError(id, {
22571
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23226
+ sendError(id2, {
23227
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22572
23228
  message: `unsupported theme: ${name2}`
22573
23229
  });
22574
23230
  return;
22575
23231
  }
22576
23232
  const workingDir = state.lastUiContext?.cwd ?? state.runtimeWorkingDir ?? process.cwd();
22577
23233
  try {
22578
- const target = await updateEnvironmentTuiTheme(state, workingDir, name2);
23234
+ const target2 = await updateEnvironmentTuiTheme(state, workingDir, name2);
22579
23235
  const result = {
22580
23236
  name: name2,
22581
- scope: target.scope,
22582
- path: target.path
23237
+ scope: target2.scope,
23238
+ path: target2.path
22583
23239
  };
22584
- sendResult(id, result);
22585
- log2(`theme.set ${name2} scope=${target.scope} path=${target.path}`);
23240
+ sendResult(id2, result);
23241
+ log2(`theme.set ${name2} scope=${target2.scope} path=${target2.path}`);
22586
23242
  } catch (error) {
22587
- sendError(id, {
22588
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
23243
+ sendError(id2, {
23244
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22589
23245
  message: String(error)
22590
23246
  });
22591
23247
  }
@@ -22606,7 +23262,7 @@ var createRuntimeHandlers = ({
22606
23262
  const skillsEnabled = state.effectiveEnvironment.context.skills === "from-config";
22607
23263
  const themeSetEnabled = isTuiLocalEnvironment(state.effectiveEnvironment) && state.effectiveEnvironment.config.source !== "disabled";
22608
23264
  const rejectDisabled = (message) => sendError(req.id, {
22609
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23265
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22610
23266
  message
22611
23267
  });
22612
23268
  switch (req.method) {
@@ -22617,6 +23273,13 @@ var createRuntimeHandlers = ({
22617
23273
  case "attachment.upload.finish":
22618
23274
  case "attachment.upload.cancel":
22619
23275
  return handleAttachmentUpload(state, req.id, req.method, req.params);
23276
+ case "goal.get":
23277
+ case "goal.set":
23278
+ case "goal.pause":
23279
+ case "goal.resume":
23280
+ case "goal.clear":
23281
+ case "goal.continue":
23282
+ return handleGoal(req.id, req.method, req.params);
22620
23283
  case "run.start":
22621
23284
  return handleRunStart(req.id, req.params);
22622
23285
  case "run.steer":
@@ -22804,7 +23467,7 @@ var createRuntimeHandlers = ({
22804
23467
  return handleThemeSet(req.id, req.params);
22805
23468
  default:
22806
23469
  return sendError(req.id, {
22807
- code: import_protocol19.RPC_ERROR_CODE.METHOD_NOT_FOUND,
23470
+ code: import_protocol20.RPC_ERROR_CODE.METHOD_NOT_FOUND,
22808
23471
  message: "method not found"
22809
23472
  });
22810
23473
  }
@@ -22823,11 +23486,11 @@ var createRuntimeHandlers = ({
22823
23486
  log2("invalid rpc message");
22824
23487
  return;
22825
23488
  }
22826
- const id = typeof msg.id === "string" ? msg.id : void 0;
23489
+ const id2 = typeof msg.id === "string" ? msg.id : void 0;
22827
23490
  if (msg.jsonrpc !== "2.0" || "method" in msg && typeof msg.method !== "string") {
22828
- if (id !== void 0) {
22829
- sendError(id, {
22830
- code: import_protocol19.RPC_ERROR_CODE.INVALID_REQUEST,
23491
+ if (id2 !== void 0) {
23492
+ sendError(id2, {
23493
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_REQUEST,
22831
23494
  message: "invalid request"
22832
23495
  });
22833
23496
  } else {
@@ -22836,29 +23499,29 @@ var createRuntimeHandlers = ({
22836
23499
  return;
22837
23500
  }
22838
23501
  if (typeof msg.method === "string") {
22839
- if ("id" in msg && id === void 0) {
23502
+ if ("id" in msg && id2 === void 0) {
22840
23503
  log2("invalid rpc request id");
22841
23504
  return;
22842
23505
  }
22843
23506
  const invalid = validateRequestParams(msg.method, msg.params);
22844
23507
  if (invalid) {
22845
- if (id !== void 0)
22846
- sendError(id, {
22847
- code: import_protocol19.RPC_ERROR_CODE.INVALID_PARAMS,
23508
+ if (id2 !== void 0)
23509
+ sendError(id2, {
23510
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_PARAMS,
22848
23511
  message: invalid
22849
23512
  });
22850
23513
  else log2(`invalid rpc notification: ${msg.method}`);
22851
23514
  return;
22852
23515
  }
22853
- if (id !== void 0) {
22854
- void withRpcResponseContext(id, async () => {
23516
+ if (id2 !== void 0) {
23517
+ void withRpcResponseContext(id2, async () => {
22855
23518
  try {
22856
23519
  await handleRequest(msg);
22857
23520
  } catch {
22858
- if (!hasRpcResponse(id)) {
23521
+ if (!hasRpcResponse(id2)) {
22859
23522
  try {
22860
- sendError(id, {
22861
- code: import_protocol19.RPC_ERROR_CODE.RUNTIME_INTERNAL,
23523
+ sendError(id2, {
23524
+ code: import_protocol20.RPC_ERROR_CODE.RUNTIME_INTERNAL,
22862
23525
  message: "internal runtime error"
22863
23526
  });
22864
23527
  } catch {
@@ -22879,11 +23542,11 @@ var createRuntimeHandlers = ({
22879
23542
  }
22880
23543
  return;
22881
23544
  }
22882
- if (id !== void 0 && ("result" in msg || "error" in msg)) {
23545
+ if (id2 !== void 0 && ("result" in msg || "error" in msg)) {
22883
23546
  handleResponse(msg);
22884
- } else if (id !== void 0) {
22885
- sendError(id, {
22886
- code: import_protocol19.RPC_ERROR_CODE.INVALID_REQUEST,
23547
+ } else if (id2 !== void 0) {
23548
+ sendError(id2, {
23549
+ code: import_protocol20.RPC_ERROR_CODE.INVALID_REQUEST,
22887
23550
  message: "invalid request"
22888
23551
  });
22889
23552
  } else {
@@ -23053,18 +23716,18 @@ var RuntimeState = class {
23053
23716
  this.uiRequestCounter += 1;
23054
23717
  return `ui_${this.uiRequestCounter}`;
23055
23718
  }
23056
- waitForUiResponse(id, timeoutMs, onTimeout) {
23719
+ waitForUiResponse(id2, timeoutMs, onTimeout) {
23057
23720
  return new Promise((resolve, reject) => {
23058
23721
  const resolveUnknown = (value) => resolve(value);
23059
23722
  const timeout = timeoutMs ? setTimeout(() => {
23060
23723
  try {
23061
23724
  onTimeout?.();
23062
23725
  } finally {
23063
- this.pendingUiRequests.delete(id);
23726
+ this.pendingUiRequests.delete(id2);
23064
23727
  reject(new Error("ui request timed out"));
23065
23728
  }
23066
23729
  }, timeoutMs) : void 0;
23067
- this.pendingUiRequests.set(id, {
23730
+ this.pendingUiRequests.set(id2, {
23068
23731
  resolve: resolveUnknown,
23069
23732
  reject,
23070
23733
  timeout
@@ -23106,41 +23769,41 @@ var import_node_url = require("url");
23106
23769
 
23107
23770
  // src/subagents/bootstrap.ts
23108
23771
  var import_node_path27 = __toESM(require("path"), 1);
23109
- var import_zod36 = require("zod");
23110
- var permissionRule = import_zod36.z.object({
23111
- tool: import_zod36.z.string(),
23112
- command: import_zod36.z.string().optional(),
23113
- command_glob: import_zod36.z.string().optional(),
23114
- skill_name: import_zod36.z.string().optional()
23772
+ var import_zod37 = require("zod");
23773
+ var permissionRule = import_zod37.z.object({
23774
+ tool: import_zod37.z.string(),
23775
+ command: import_zod37.z.string().optional(),
23776
+ command_glob: import_zod37.z.string().optional(),
23777
+ skill_name: import_zod37.z.string().optional()
23115
23778
  }).passthrough();
23116
- var subagentBootstrapSchema = import_zod36.z.object({
23117
- version: import_zod36.z.literal(1),
23118
- task_id: import_zod36.z.string().uuid(),
23119
- prompt: import_zod36.z.string().min(1).max(32768),
23120
- workspace_root: import_zod36.z.string().refine(import_node_path27.default.isAbsolute),
23121
- lineage: import_zod36.z.object({
23779
+ var subagentBootstrapSchema = import_zod37.z.object({
23780
+ version: import_zod37.z.literal(1),
23781
+ task_id: import_zod37.z.string().uuid(),
23782
+ prompt: import_zod37.z.string().min(1).max(32768),
23783
+ workspace_root: import_zod37.z.string().refine(import_node_path27.default.isAbsolute),
23784
+ lineage: import_zod37.z.object({
23122
23785
  name: subagentNameSchema.optional(),
23123
- tree_id: import_zod36.z.string().min(1),
23124
- node_id: import_zod36.z.string().uuid(),
23125
- parent_node_id: import_zod36.z.string().min(1),
23126
- owner_session_id: import_zod36.z.string().min(1),
23127
- depth: import_zod36.z.literal(1),
23128
- spawn_index: import_zod36.z.number().int().positive(),
23129
- context_mode: import_zod36.z.literal("fresh"),
23130
- effective_policy_id: import_zod36.z.string().min(1),
23131
- workspace_lease_id: import_zod36.z.string().min(1)
23786
+ tree_id: import_zod37.z.string().min(1),
23787
+ node_id: import_zod37.z.string().uuid(),
23788
+ parent_node_id: import_zod37.z.string().min(1),
23789
+ owner_session_id: import_zod37.z.string().min(1),
23790
+ depth: import_zod37.z.literal(1),
23791
+ spawn_index: import_zod37.z.number().int().positive(),
23792
+ context_mode: import_zod37.z.literal("fresh"),
23793
+ effective_policy_id: import_zod37.z.string().min(1),
23794
+ workspace_lease_id: import_zod37.z.string().min(1)
23132
23795
  }).strict(),
23133
23796
  model: subagentModelSchema,
23134
- permission: import_zod36.z.object({
23135
- tool_allowlist: import_zod36.z.array(import_zod36.z.enum(WRITABLE_TOOLS)).max(WRITABLE_TOOLS.length),
23136
- workspace_access: import_zod36.z.enum(["read-only", "read-write"]),
23137
- approval_mode: import_zod36.z.enum(["minimal", "trusted", "full-access"]),
23138
- parent_permissions: import_zod36.z.object({
23139
- allow: import_zod36.z.array(permissionRule).optional(),
23140
- deny: import_zod36.z.array(permissionRule).optional()
23797
+ permission: import_zod37.z.object({
23798
+ tool_allowlist: import_zod37.z.array(import_zod37.z.enum(WRITABLE_TOOLS)).max(WRITABLE_TOOLS.length),
23799
+ workspace_access: import_zod37.z.enum(["read-only", "read-write"]),
23800
+ approval_mode: import_zod37.z.enum(["minimal", "trusted", "full-access"]),
23801
+ parent_permissions: import_zod37.z.object({
23802
+ allow: import_zod37.z.array(permissionRule).optional(),
23803
+ deny: import_zod37.z.array(permissionRule).optional()
23141
23804
  }).strict().optional(),
23142
- max_steps: import_zod36.z.number().int().min(1).max(200),
23143
- timeout_seconds: import_zod36.z.number().int().min(1).max(3600).optional()
23805
+ max_steps: import_zod37.z.number().int().min(1).max(200),
23806
+ timeout_seconds: import_zod37.z.number().int().min(1).max(3600).optional()
23144
23807
  }).strict()
23145
23808
  }).strict().refine(
23146
23809
  (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(
@@ -23270,10 +23933,10 @@ var prepareProcess = (input, options, channel) => {
23270
23933
  }
23271
23934
  }
23272
23935
  };
23273
- const send2 = (id, method, params) => {
23936
+ const send2 = (id2, method, params) => {
23274
23937
  if (!child?.stdin?.writable || closed) return;
23275
23938
  child.stdin.write(
23276
- `${JSON.stringify({ jsonrpc: "2.0", id, method, params })}
23939
+ `${JSON.stringify({ jsonrpc: "2.0", id: id2, method, params })}
23277
23940
  `
23278
23941
  );
23279
23942
  };
@@ -23539,7 +24202,7 @@ var startRuntime = async (options = {}) => {
23539
24202
  (0, import_logger.log)(`agents resolver startup init failed: ${String(error)}`);
23540
24203
  }
23541
24204
  }
23542
- const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage21.SessionStateStoreImpl({
24205
+ const sessionStateStore = environment.adapters.stores?.sessionStateStore ?? (environment.persistence.mode === "volatile" ? new VolatileSessionStateStore() : new import_storage22.SessionStateStoreImpl({
23543
24206
  onError: (error, context) => {
23544
24207
  (0, import_logger.log)(
23545
24208
  `Error: session-state ${context.action} error${context.detail ? ` (${context.detail})` : ""}: ${String(error)}`
@@ -23555,13 +24218,13 @@ var startRuntime = async (options = {}) => {
23555
24218
  );
23556
24219
  }
23557
24220
  }
23558
- const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage21.RunEventStoreFactoryImpl({
23559
- ...sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
24221
+ const runEventStoreFactory = environment.adapters.stores?.runEventStoreFactory ?? (environment.persistence.mode === "volatile" ? new VolatileRunEventStoreFactory() : new import_storage22.RunEventStoreFactoryImpl({
24222
+ ...sessionStateStore instanceof import_storage22.SessionStateStoreImpl ? { runIndex: sessionStateStore } : {},
23560
24223
  onRunIndexError: (error) => (0, import_logger.log)(`session run index error: ${String(error)}`)
23561
24224
  }));
23562
- if (environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage21.SessionStateStoreImpl) {
23563
- void (0, import_storage21.cleanupRunLogs)({
23564
- paths: (0, import_storage21.resolveStoragePaths)(),
24225
+ if (environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage22.SessionStateStoreImpl) {
24226
+ void (0, import_storage22.cleanupRunLogs)({
24227
+ paths: (0, import_storage22.resolveStoragePaths)(),
23565
24228
  sessions: sessionStateStore
23566
24229
  }).then((result) => {
23567
24230
  if (result.compressed || result.deleted || result.failed)
@@ -23659,10 +24322,10 @@ var startRuntime = async (options = {}) => {
23659
24322
  sessionStateStore,
23660
24323
  runEventStoreFactory,
23661
24324
  taskManager,
23662
- ...environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage21.SessionStateStoreImpl ? {
24325
+ ...environment.persistence.mode === "runtime" && !environment.adapters.stores?.sessionStateStore && !environment.adapters.stores?.runEventStoreFactory && sessionStateStore instanceof import_storage22.SessionStateStoreImpl ? {
23663
24326
  cleanupSessionLogs: async (sessionId) => {
23664
- await (0, import_storage21.cleanupRunLogs)({
23665
- paths: (0, import_storage21.resolveStoragePaths)(),
24327
+ await (0, import_storage22.cleanupRunLogs)({
24328
+ paths: (0, import_storage22.resolveStoragePaths)(),
23666
24329
  sessions: sessionStateStore,
23667
24330
  sessionId
23668
24331
  });