@codelia/runtime 0.1.48 → 0.1.50

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.
Files changed (3) hide show
  1. package/dist/index.cjs +559 -475
  2. package/dist/index.js +563 -483
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -394,12 +394,6 @@ var appendInitialAgentsContext = (systemPrompt, agentsContext) => {
394
394
  ${agentsContext}`;
395
395
  };
396
396
 
397
- // src/auth/openai-oauth.ts
398
- var import_node_child_process = require("child_process");
399
-
400
- // src/logger.ts
401
- var import_logger = require("@codelia/logger");
402
-
403
397
  // src/auth/oauth-utils.ts
404
398
  var import_node_http = require("http");
405
399
  var oauth = __toESM(require("oauth4webapi"), 1);
@@ -594,6 +588,12 @@ var startOAuthCallbackServer = (options) => {
594
588
  };
595
589
  };
596
590
 
591
+ // src/auth/openai-oauth.ts
592
+ var import_node_child_process = require("child_process");
593
+
594
+ // src/logger.ts
595
+ var import_logger = require("@codelia/logger");
596
+
597
597
  // src/auth/openai-oauth.ts
598
598
  var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
599
599
  var ISSUER = "https://auth.openai.com";
@@ -1012,135 +1012,6 @@ Working directory: ${workingDir}`;
1012
1012
  }
1013
1013
  };
1014
1014
 
1015
- // src/auth/openai-device-code.ts
1016
- var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
1017
- var ISSUER2 = "https://auth.openai.com";
1018
- var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
1019
- var DEFAULT_INTERVAL_SECONDS = 5;
1020
- var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
1021
- var deviceCodeTimeoutMs = () => readPositiveIntEnv(
1022
- "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
1023
- DEFAULT_TIMEOUT_MS
1024
- );
1025
- var sleep = (ms) => new Promise((resolve) => {
1026
- setTimeout(resolve, ms);
1027
- });
1028
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1029
- var parseIntervalSeconds = (value) => {
1030
- if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1031
- return Math.trunc(value);
1032
- }
1033
- if (typeof value === "string") {
1034
- const parsed = Number.parseInt(value.trim(), 10);
1035
- if (Number.isFinite(parsed) && parsed >= 0) {
1036
- return parsed;
1037
- }
1038
- }
1039
- return DEFAULT_INTERVAL_SECONDS;
1040
- };
1041
- var readResponseSnippet = async (response) => {
1042
- const text = await response.text().catch(() => "");
1043
- return text ? text.slice(0, 500) : "(empty)";
1044
- };
1045
- var requestDeviceCodeStart = async () => {
1046
- const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/usercode`, {
1047
- method: "POST",
1048
- headers: {
1049
- "Content-Type": "application/json",
1050
- Accept: "application/json"
1051
- },
1052
- body: JSON.stringify({ client_id: clientId2() })
1053
- });
1054
- if (!response.ok) {
1055
- if (response.status === 404) {
1056
- throw new Error("OpenAI device code login is not enabled for this client");
1057
- }
1058
- throw new Error(
1059
- `OpenAI device code request failed (${response.status}): ${await readResponseSnippet(response)}`
1060
- );
1061
- }
1062
- const payload = await response.json();
1063
- if (!isRecord(payload) || typeof payload.device_auth_id !== "string") {
1064
- throw new Error("OpenAI device code response is missing device_auth_id");
1065
- }
1066
- const userCode = typeof payload.user_code === "string" && payload.user_code.trim() || typeof payload.usercode === "string" && payload.usercode.trim() || null;
1067
- if (!userCode) {
1068
- throw new Error("OpenAI device code response is missing user_code");
1069
- }
1070
- return {
1071
- deviceAuthId: payload.device_auth_id,
1072
- userCode,
1073
- intervalSeconds: parseIntervalSeconds(payload.interval)
1074
- };
1075
- };
1076
- var pollDeviceCodeAuthorization = async (deviceAuthId, userCode, intervalSeconds) => {
1077
- const deadline = Date.now() + deviceCodeTimeoutMs();
1078
- while (Date.now() < deadline) {
1079
- const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/token`, {
1080
- method: "POST",
1081
- headers: {
1082
- "Content-Type": "application/json",
1083
- Accept: "application/json"
1084
- },
1085
- body: JSON.stringify({
1086
- device_auth_id: deviceAuthId,
1087
- user_code: userCode
1088
- })
1089
- });
1090
- if (response.ok) {
1091
- const payload = await response.json();
1092
- if (!isRecord(payload) || typeof payload.authorization_code !== "string" || typeof payload.code_challenge !== "string" || typeof payload.code_verifier !== "string") {
1093
- throw new Error(
1094
- "OpenAI device code token response is missing authorization_code/PKCE fields"
1095
- );
1096
- }
1097
- return {
1098
- authorization_code: payload.authorization_code,
1099
- code_challenge: payload.code_challenge,
1100
- code_verifier: payload.code_verifier
1101
- };
1102
- }
1103
- if (response.status !== 403 && response.status !== 404) {
1104
- throw new Error(
1105
- `OpenAI device code polling failed (${response.status}): ${await readResponseSnippet(response)}`
1106
- );
1107
- }
1108
- const now = Date.now();
1109
- if (now >= deadline) {
1110
- break;
1111
- }
1112
- const waitMs = Math.max(
1113
- 0,
1114
- Math.min(intervalSeconds * 1e3, deadline - now)
1115
- );
1116
- await sleep(waitMs);
1117
- }
1118
- throw new Error("OpenAI device code login timed out after 15 minutes");
1119
- };
1120
- var createOpenAiDeviceCodeSession = async () => {
1121
- const start = await requestDeviceCodeStart();
1122
- return {
1123
- verificationUrl: `${ISSUER2}/codex/device`,
1124
- userCode: start.userCode,
1125
- complete: async () => {
1126
- const authCode = await pollDeviceCodeAuthorization(
1127
- start.deviceAuthId,
1128
- start.userCode,
1129
- start.intervalSeconds
1130
- );
1131
- const pkce = {
1132
- challenge: authCode.code_challenge,
1133
- verifier: authCode.code_verifier
1134
- };
1135
- return exchangeCodeForTokens(
1136
- authCode.authorization_code,
1137
- `${ISSUER2}/deviceauth/callback`,
1138
- pkce
1139
- );
1140
- }
1141
- };
1142
- };
1143
-
1144
1015
  // src/rpc/transport.ts
1145
1016
  var describeRpcMessage = (msg) => {
1146
1017
  if ("method" in msg && typeof msg.method === "string") {
@@ -1292,6 +1163,137 @@ var requestUiPick = async (state, params) => {
1292
1163
  return requestUi(state, "ui.pick.request", params);
1293
1164
  };
1294
1165
 
1166
+ // src/auth/openai-device-code.ts
1167
+ var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
1168
+ var ISSUER2 = "https://auth.openai.com";
1169
+ var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
1170
+ var DEFAULT_INTERVAL_SECONDS = 5;
1171
+ var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
1172
+ var deviceCodeTimeoutMs = () => readPositiveIntEnv(
1173
+ "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
1174
+ DEFAULT_TIMEOUT_MS
1175
+ );
1176
+ var sleep = (ms) => new Promise((resolve) => {
1177
+ setTimeout(resolve, ms);
1178
+ });
1179
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1180
+ var parseIntervalSeconds = (value) => {
1181
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1182
+ return Math.trunc(value);
1183
+ }
1184
+ if (typeof value === "string") {
1185
+ const parsed = Number.parseInt(value.trim(), 10);
1186
+ if (Number.isFinite(parsed) && parsed >= 0) {
1187
+ return parsed;
1188
+ }
1189
+ }
1190
+ return DEFAULT_INTERVAL_SECONDS;
1191
+ };
1192
+ var readResponseSnippet = async (response) => {
1193
+ const text = await response.text().catch(() => "");
1194
+ return text ? text.slice(0, 500) : "(empty)";
1195
+ };
1196
+ var requestDeviceCodeStart = async () => {
1197
+ const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/usercode`, {
1198
+ method: "POST",
1199
+ headers: {
1200
+ "Content-Type": "application/json",
1201
+ Accept: "application/json"
1202
+ },
1203
+ body: JSON.stringify({ client_id: clientId2() })
1204
+ });
1205
+ if (!response.ok) {
1206
+ if (response.status === 404) {
1207
+ throw new Error(
1208
+ "OpenAI device code login is not enabled for this client"
1209
+ );
1210
+ }
1211
+ throw new Error(
1212
+ `OpenAI device code request failed (${response.status}): ${await readResponseSnippet(response)}`
1213
+ );
1214
+ }
1215
+ const payload = await response.json();
1216
+ if (!isRecord(payload) || typeof payload.device_auth_id !== "string") {
1217
+ throw new Error("OpenAI device code response is missing device_auth_id");
1218
+ }
1219
+ const userCode = typeof payload.user_code === "string" && payload.user_code.trim() || typeof payload.usercode === "string" && payload.usercode.trim() || null;
1220
+ if (!userCode) {
1221
+ throw new Error("OpenAI device code response is missing user_code");
1222
+ }
1223
+ return {
1224
+ deviceAuthId: payload.device_auth_id,
1225
+ userCode,
1226
+ intervalSeconds: parseIntervalSeconds(payload.interval)
1227
+ };
1228
+ };
1229
+ var pollDeviceCodeAuthorization = async (deviceAuthId, userCode, intervalSeconds) => {
1230
+ const deadline = Date.now() + deviceCodeTimeoutMs();
1231
+ while (Date.now() < deadline) {
1232
+ const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/token`, {
1233
+ method: "POST",
1234
+ headers: {
1235
+ "Content-Type": "application/json",
1236
+ Accept: "application/json"
1237
+ },
1238
+ body: JSON.stringify({
1239
+ device_auth_id: deviceAuthId,
1240
+ user_code: userCode
1241
+ })
1242
+ });
1243
+ if (response.ok) {
1244
+ const payload = await response.json();
1245
+ if (!isRecord(payload) || typeof payload.authorization_code !== "string" || typeof payload.code_challenge !== "string" || typeof payload.code_verifier !== "string") {
1246
+ throw new Error(
1247
+ "OpenAI device code token response is missing authorization_code/PKCE fields"
1248
+ );
1249
+ }
1250
+ return {
1251
+ authorization_code: payload.authorization_code,
1252
+ code_challenge: payload.code_challenge,
1253
+ code_verifier: payload.code_verifier
1254
+ };
1255
+ }
1256
+ if (response.status !== 403 && response.status !== 404) {
1257
+ throw new Error(
1258
+ `OpenAI device code polling failed (${response.status}): ${await readResponseSnippet(response)}`
1259
+ );
1260
+ }
1261
+ const now = Date.now();
1262
+ if (now >= deadline) {
1263
+ break;
1264
+ }
1265
+ const waitMs = Math.max(
1266
+ 0,
1267
+ Math.min(intervalSeconds * 1e3, deadline - now)
1268
+ );
1269
+ await sleep(waitMs);
1270
+ }
1271
+ throw new Error("OpenAI device code login timed out after 15 minutes");
1272
+ };
1273
+ var createOpenAiDeviceCodeSession = async () => {
1274
+ const start = await requestDeviceCodeStart();
1275
+ return {
1276
+ verificationUrl: `${ISSUER2}/codex/device`,
1277
+ userCode: start.userCode,
1278
+ complete: async () => {
1279
+ const authCode = await pollDeviceCodeAuthorization(
1280
+ start.deviceAuthId,
1281
+ start.userCode,
1282
+ start.intervalSeconds
1283
+ );
1284
+ const pkce = {
1285
+ challenge: authCode.code_challenge,
1286
+ verifier: authCode.code_verifier
1287
+ };
1288
+ return exchangeCodeForTokens(
1289
+ authCode.authorization_code,
1290
+ `${ISSUER2}/deviceauth/callback`,
1291
+ pkce
1292
+ );
1293
+ }
1294
+ };
1295
+ };
1296
+
1295
1297
  // src/auth/store.ts
1296
1298
  var import_node_fs3 = require("fs");
1297
1299
  var import_storage2 = require("@codelia/storage");
@@ -2292,16 +2294,22 @@ var resolveApprovalModeForRuntime = async (options, deps = {}) => {
2292
2294
  if (options.requestStartupSelection) {
2293
2295
  const selected = await options.requestStartupSelection({ projectKey });
2294
2296
  if (selected) {
2295
- await persistProjectApprovalModeOrThrow(
2296
- store,
2297
- projectKey,
2298
- selected,
2299
- loadedPolicy
2300
- );
2297
+ const persistSelection = async () => {
2298
+ await persistProjectApprovalModeOrThrow(
2299
+ store,
2300
+ projectKey,
2301
+ selected,
2302
+ loadedPolicy
2303
+ );
2304
+ };
2305
+ if (!options.deferStartupSelectionPersist) {
2306
+ await persistSelection();
2307
+ }
2301
2308
  return {
2302
2309
  approvalMode: selected,
2303
2310
  source: "startup-selection",
2304
- projectKey
2311
+ projectKey,
2312
+ ...options.deferStartupSelectionPersist ? { persistSelection } : {}
2305
2313
  };
2306
2314
  }
2307
2315
  }
@@ -2705,7 +2713,11 @@ var SYSTEM_SHELL_ALLOWLIST = [
2705
2713
  "git ls-files",
2706
2714
  "git grep"
2707
2715
  ];
2708
- var SYSTEM_SHELL_ALLOWLIST_TRUSTED = [...SYSTEM_SHELL_ALLOWLIST, "sed", "awk"];
2716
+ var SYSTEM_SHELL_ALLOWLIST_TRUSTED = [
2717
+ ...SYSTEM_SHELL_ALLOWLIST,
2718
+ "sed",
2719
+ "awk"
2720
+ ];
2709
2721
  var buildSystemPermissions = (approvalMode = "minimal") => ({
2710
2722
  allow: [
2711
2723
  ...(approvalMode === "trusted" ? SYSTEM_TOOL_ALLOWLIST_TRUSTED : SYSTEM_TOOL_ALLOWLIST_MINIMAL).map((tool) => ({ tool })),
@@ -2975,23 +2987,29 @@ var SandboxContext = class _SandboxContext {
2975
2987
  rootDir;
2976
2988
  workingDir;
2977
2989
  sessionId;
2990
+ approvalMode;
2978
2991
  constructor(init) {
2979
2992
  this.rootDir = init.rootDir;
2980
2993
  this.workingDir = init.workingDir;
2981
2994
  this.sessionId = init.sessionId;
2995
+ this.approvalMode = init.approvalMode;
2982
2996
  }
2983
- static async create(rootDir) {
2997
+ static async create(rootDir, options = {}) {
2984
2998
  const sessionId = import_node_crypto.default.randomUUID().slice(0, 8);
2985
2999
  const root = rootDir ? import_node_path6.default.resolve(rootDir) : process.cwd();
2986
3000
  await import_node_fs5.promises.mkdir(root, { recursive: true });
2987
3001
  return new _SandboxContext({
2988
3002
  rootDir: root,
2989
3003
  workingDir: root,
2990
- sessionId
3004
+ sessionId,
3005
+ approvalMode: options.approvalMode ?? "minimal"
2991
3006
  });
2992
3007
  }
2993
3008
  resolvePath(targetPath) {
2994
3009
  const resolved = import_node_path6.default.isAbsolute(targetPath) ? import_node_path6.default.resolve(targetPath) : import_node_path6.default.resolve(this.workingDir, targetPath);
3010
+ if (this.approvalMode === "full-access") {
3011
+ return resolved;
3012
+ }
2995
3013
  const relative = import_node_path6.default.relative(this.rootDir, resolved);
2996
3014
  if (relative === "" || !relative.startsWith("..") && !import_node_path6.default.isAbsolute(relative)) {
2997
3015
  return resolved;
@@ -3634,7 +3652,7 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => (0, import_core
3634
3652
  const sandbox = await getSandboxContext(ctx, sandboxKey);
3635
3653
  resolvedPath = sandbox.resolvePath(input.path);
3636
3654
  } catch (error) {
3637
- return `Security error: ${String(error)}`;
3655
+ throw new Error(`Security error: ${String(error)}`);
3638
3656
  }
3639
3657
  try {
3640
3658
  const resolver = await getAgentsResolver(ctx, agentsResolverKey);
@@ -3840,7 +3858,9 @@ var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
3840
3858
  name: "edit",
3841
3859
  description: "Edit a file by replacing old_string with new_string.",
3842
3860
  input: import_zod4.z.object({
3843
- file_path: import_zod4.z.string().describe("File path under the sandbox root."),
3861
+ file_path: import_zod4.z.string().describe(
3862
+ "File path. Sandbox-bounded unless full-access mode is active."
3863
+ ),
3844
3864
  old_string: import_zod4.z.string().describe(
3845
3865
  "Text to find. Use empty string to replace the whole file content."
3846
3866
  ),
@@ -3997,11 +4017,11 @@ var walkFiles = async (startDir, visitor) => {
3997
4017
  }
3998
4018
  }
3999
4019
  };
4000
- var globMatch = async (searchDir, rootDir, pattern) => {
4020
+ var globMatch = async (searchDir, pattern) => {
4001
4021
  const regex = globToRegExp2(pattern.replaceAll("\\", "/"));
4002
4022
  const matches = [];
4003
4023
  await walkFiles(searchDir, async (filePath) => {
4004
- const relPath = import_node_path9.default.relative(rootDir, filePath).replaceAll("\\", "/");
4024
+ const relPath = import_node_path9.default.relative(searchDir, filePath).replaceAll("\\", "/");
4005
4025
  if (regex.test(relPath)) {
4006
4026
  matches.push(relPath);
4007
4027
  }
@@ -4022,13 +4042,11 @@ var createGlobSearchTool = (sandboxKey) => (0, import_core6.defineTool)({
4022
4042
  }),
4023
4043
  execute: async (input, ctx) => {
4024
4044
  let searchDir;
4025
- let rootDir;
4026
4045
  try {
4027
4046
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4028
- rootDir = sandbox.rootDir;
4029
4047
  searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4030
4048
  } catch (error) {
4031
- return `Security error: ${String(error)}`;
4049
+ throw new Error(`Security error: ${String(error)}`);
4032
4050
  }
4033
4051
  try {
4034
4052
  const stat = await import_node_fs9.promises.stat(searchDir);
@@ -4038,7 +4056,7 @@ var createGlobSearchTool = (sandboxKey) => (0, import_core6.defineTool)({
4038
4056
  } catch (error) {
4039
4057
  return `Error: ${String(error)}`;
4040
4058
  }
4041
- const matches = await globMatch(searchDir, rootDir, input.pattern);
4059
+ const matches = await globMatch(searchDir, input.pattern);
4042
4060
  if (!matches.length) {
4043
4061
  return `No files match pattern: ${input.pattern}`;
4044
4062
  }
@@ -4072,7 +4090,7 @@ var createGrepTool = (sandboxKey) => (0, import_core7.defineTool)({
4072
4090
  searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4073
4091
  pathLabel = input.path ?? searchDir;
4074
4092
  } catch (error) {
4075
- return `Security error: ${String(error)}`;
4093
+ throw new Error(`Security error: ${String(error)}`);
4076
4094
  }
4077
4095
  let regex;
4078
4096
  try {
@@ -4862,7 +4880,10 @@ var MAX_LINE_LENGTH = parsePositiveIntEnv(
4862
4880
  "CODELIA_READ_MAX_LINE_LENGTH",
4863
4881
  DEFAULT_MAX_LINE_LENGTH
4864
4882
  );
4865
- var MAX_BYTES = parsePositiveIntEnv("CODELIA_READ_MAX_BYTES", DEFAULT_MAX_BYTES);
4883
+ var MAX_BYTES = parsePositiveIntEnv(
4884
+ "CODELIA_READ_MAX_BYTES",
4885
+ DEFAULT_MAX_BYTES
4886
+ );
4866
4887
  var clipLongLine = (line) => {
4867
4888
  if (line.length <= MAX_LINE_LENGTH) {
4868
4889
  return line;
@@ -4902,7 +4923,9 @@ var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
4902
4923
  name: "read",
4903
4924
  description: "Read a text file with optional 0-based line offset and line limit.",
4904
4925
  input: import_zod8.z.object({
4905
- file_path: import_zod8.z.string().describe("File path under the sandbox root."),
4926
+ file_path: import_zod8.z.string().describe(
4927
+ "File path. Sandbox-bounded unless full-access mode is active."
4928
+ ),
4906
4929
  offset: import_zod8.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4907
4930
  limit: import_zod8.z.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4908
4931
  }),
@@ -4912,7 +4935,7 @@ var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
4912
4935
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4913
4936
  resolved = sandbox.resolvePath(input.file_path);
4914
4937
  } catch (error) {
4915
- return `Security error: ${String(error)}`;
4938
+ throw new Error(`Security error: ${String(error)}`);
4916
4939
  }
4917
4940
  try {
4918
4941
  const stat = await import_node_fs13.promises.stat(resolved);
@@ -4969,30 +4992,100 @@ var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
4969
4992
  outputLines.push(line);
4970
4993
  bytes += size;
4971
4994
  }
4972
- const numbered = outputLines.map(
4973
- (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4974
- );
4975
- const lastReadLine = offset + outputLines.length;
4976
- const hasMoreLines = lines.length > lastReadLine;
4977
- let output = numbered.join("\n");
4978
- if (truncatedByBytes || hasMoreLines) {
4979
- const reason = truncatedByBytes ? `[output truncated at ${MAX_BYTES} bytes]` : "Output has more lines.";
4980
- output += `
4981
-
4982
- ${reason} Use offset to read beyond line ${lastReadLine}.`;
4995
+ const numbered = outputLines.map(
4996
+ (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4997
+ );
4998
+ const lastReadLine = offset + outputLines.length;
4999
+ const hasMoreLines = lines.length > lastReadLine;
5000
+ let output = numbered.join("\n");
5001
+ if (truncatedByBytes || hasMoreLines) {
5002
+ const reason = truncatedByBytes ? `[output truncated at ${MAX_BYTES} bytes]` : "Output has more lines.";
5003
+ output += `
5004
+
5005
+ ${reason} Use offset to read beyond line ${lastReadLine}.`;
5006
+ }
5007
+ const truncatedLinesSummary = buildTruncatedLinesSummary(
5008
+ Array.from(new Set(truncatedLineNumbers))
5009
+ );
5010
+ if (truncatedLinesSummary) {
5011
+ output += `
5012
+
5013
+ ${truncatedLinesSummary}`;
5014
+ }
5015
+ if (firstClippedLineNumber !== null) {
5016
+ output += `
5017
+
5018
+ For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5019
+ }
5020
+ return output;
5021
+ } catch (error) {
5022
+ return `Error reading file: ${String(error)}`;
5023
+ }
5024
+ }
5025
+ });
5026
+
5027
+ // src/tools/read-line.ts
5028
+ var import_node_fs14 = require("fs");
5029
+ var import_core10 = require("@codelia/core");
5030
+ var import_zod9 = require("zod");
5031
+ var DEFAULT_CHAR_LIMIT = 1e4;
5032
+ var MAX_CHAR_LIMIT = 1e5;
5033
+ var createReadLineTool = (sandboxKey) => (0, import_core10.defineTool)({
5034
+ name: "read_line",
5035
+ description: "Read a single line segment by 1-based line number and 0-based char offset.",
5036
+ input: import_zod9.z.object({
5037
+ file_path: import_zod9.z.string().describe(
5038
+ "File path. Sandbox-bounded unless full-access mode is active."
5039
+ ),
5040
+ line_number: import_zod9.z.number().int().positive().describe("1-based line number to read."),
5041
+ char_offset: import_zod9.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5042
+ char_limit: import_zod9.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5043
+ }),
5044
+ execute: async (input, ctx) => {
5045
+ let resolved;
5046
+ try {
5047
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
5048
+ resolved = sandbox.resolvePath(input.file_path);
5049
+ } catch (error) {
5050
+ throw new Error(`Security error: ${String(error)}`);
5051
+ }
5052
+ try {
5053
+ const stat = await import_node_fs14.promises.stat(resolved);
5054
+ if (stat.isDirectory()) {
5055
+ return `Path is a directory: ${input.file_path}`;
5056
+ }
5057
+ } catch {
5058
+ return `File not found: ${input.file_path}`;
5059
+ }
5060
+ try {
5061
+ const content = await import_node_fs14.promises.readFile(resolved, "utf8");
5062
+ const lines = content.split(/\r?\n/);
5063
+ const lineIndex = input.line_number - 1;
5064
+ if (lineIndex >= lines.length) {
5065
+ return `Line number out of range: ${input.line_number} (total ${lines.length})`;
4983
5066
  }
4984
- const truncatedLinesSummary = buildTruncatedLinesSummary(
4985
- Array.from(new Set(truncatedLineNumbers))
4986
- );
4987
- if (truncatedLinesSummary) {
4988
- output += `
4989
-
4990
- ${truncatedLinesSummary}`;
5067
+ const line = lines[lineIndex] ?? "";
5068
+ const charOffset = input.char_offset ?? 0;
5069
+ const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5070
+ if (charOffset > line.length) {
5071
+ return `char_offset out of range: ${charOffset} (line length ${line.length})`;
4991
5072
  }
4992
- if (firstClippedLineNumber !== null) {
5073
+ const segment = line.slice(charOffset, charOffset + charLimit);
5074
+ const endOffset = charOffset + segment.length;
5075
+ const hasMore = endOffset < line.length;
5076
+ const header = [
5077
+ `line_number=${input.line_number}`,
5078
+ `line_length=${line.length}`,
5079
+ `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5080
+ ].join(" ");
5081
+ let output = `${header}
5082
+ ${segment}`;
5083
+ if (hasMore) {
4993
5084
  output += `
4994
5085
 
4995
- For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5086
+ Use char_offset=${endOffset} to continue.`;
5087
+ output += `
5088
+ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
4996
5089
  }
4997
5090
  return output;
4998
5091
  } catch (error) {
@@ -5002,8 +5095,8 @@ For full long-line content, use read_line({"file_path":"${input.file_path}","lin
5002
5095
  });
5003
5096
 
5004
5097
  // src/tools/search.ts
5005
- var import_core10 = require("@codelia/core");
5006
- var import_zod9 = require("zod");
5098
+ var import_core11 = require("@codelia/core");
5099
+ var import_zod10 = require("zod");
5007
5100
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
5008
5101
  var shouldKeepUrl = (url, allowedDomains) => {
5009
5102
  if (!allowedDomains.length) return true;
@@ -5119,14 +5212,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
5119
5212
  const parsed = parseBrave(payload);
5120
5213
  return normalizeEntries(parsed, allowedDomains, maxResults);
5121
5214
  };
5122
- var createSearchTool = (options) => (0, import_core10.defineTool)({
5215
+ var createSearchTool = (options) => (0, import_core11.defineTool)({
5123
5216
  name: "search",
5124
5217
  description: "Search the web and return concise source candidates.",
5125
- input: import_zod9.z.object({
5126
- query: import_zod9.z.string().min(1).describe("Search query."),
5127
- max_results: import_zod9.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5128
- backend: import_zod9.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5129
- allowed_domains: import_zod9.z.array(import_zod9.z.string().min(1)).optional().describe("Optional allowlist of domains.")
5218
+ input: import_zod10.z.object({
5219
+ query: import_zod10.z.string().min(1).describe("Search query."),
5220
+ max_results: import_zod10.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5221
+ backend: import_zod10.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5222
+ allowed_domains: import_zod10.z.array(import_zod10.z.string().min(1)).optional().describe("Optional allowlist of domains.")
5130
5223
  }),
5131
5224
  execute: async (input) => {
5132
5225
  const backend = input.backend ?? options.defaultBackend;
@@ -5162,9 +5255,9 @@ var createSearchTool = (options) => (0, import_core10.defineTool)({
5162
5255
 
5163
5256
  // src/tools/shell.ts
5164
5257
  var import_node_crypto6 = __toESM(require("crypto"), 1);
5165
- var import_core11 = require("@codelia/core");
5258
+ var import_core12 = require("@codelia/core");
5166
5259
  var import_storage7 = require("@codelia/storage");
5167
- var import_zod10 = require("zod");
5260
+ var import_zod11 = require("zod");
5168
5261
 
5169
5262
  // src/tasks/manager.ts
5170
5263
  var import_node_crypto5 = __toESM(require("crypto"), 1);
@@ -5288,7 +5381,10 @@ var TaskManager = class {
5288
5381
  return this.enqueueMutation(async () => {
5289
5382
  const current = await this.registry.get(taskId);
5290
5383
  if (!current) {
5291
- throw new TaskManagerError("task_not_found", `Task not found: ${taskId}`);
5384
+ throw new TaskManagerError(
5385
+ "task_not_found",
5386
+ `Task not found: ${taskId}`
5387
+ );
5292
5388
  }
5293
5389
  const next = updater(current);
5294
5390
  await this.registry.upsert(next);
@@ -5369,7 +5465,9 @@ var TaskManager = class {
5369
5465
  return task;
5370
5466
  }
5371
5467
  if (task.owner_runtime_id !== this.runtimeId) {
5372
- const ownerAlive = await this.processController.isProcessAlive(task.owner_pid);
5468
+ const ownerAlive = await this.processController.isProcessAlive(
5469
+ task.owner_pid
5470
+ );
5373
5471
  if (ownerAlive) {
5374
5472
  return task;
5375
5473
  }
@@ -5385,7 +5483,9 @@ var TaskManager = class {
5385
5483
  return task;
5386
5484
  }
5387
5485
  if (typeof task.executor_pid === "number") {
5388
- const executorAlive = await this.processController.isProcessAlive(task.executor_pid);
5486
+ const executorAlive = await this.processController.isProcessAlive(
5487
+ task.executor_pid
5488
+ );
5389
5489
  if (executorAlive) {
5390
5490
  return task;
5391
5491
  }
@@ -5407,7 +5507,10 @@ var TaskManager = class {
5407
5507
  async terminatePersistedTask(task, signal) {
5408
5508
  if (typeof task.executor_pgid === "number") {
5409
5509
  try {
5410
- await this.processController.terminateProcessGroup(task.executor_pgid, signal);
5510
+ await this.processController.terminateProcessGroup(
5511
+ task.executor_pgid,
5512
+ signal
5513
+ );
5411
5514
  } catch (error) {
5412
5515
  if (!isErrnoCode(error, "ESRCH")) {
5413
5516
  throw error;
@@ -5417,7 +5520,10 @@ var TaskManager = class {
5417
5520
  }
5418
5521
  if (typeof task.executor_pid === "number") {
5419
5522
  try {
5420
- await this.processController.terminateProcess(task.executor_pid, signal);
5523
+ await this.processController.terminateProcess(
5524
+ task.executor_pid,
5525
+ signal
5526
+ );
5421
5527
  } catch (error) {
5422
5528
  if (!isErrnoCode(error, "ESRCH")) {
5423
5529
  throw error;
@@ -5429,12 +5535,16 @@ var TaskManager = class {
5429
5535
  if (typeof task.executor_pid !== "number") {
5430
5536
  return;
5431
5537
  }
5432
- const alive = await this.processController.isProcessAlive(task.executor_pid);
5538
+ const alive = await this.processController.isProcessAlive(
5539
+ task.executor_pid
5540
+ );
5433
5541
  if (!alive) {
5434
5542
  return;
5435
5543
  }
5436
5544
  await this.sleep(this.gracePeriodMs);
5437
- const stillAlive = await this.processController.isProcessAlive(task.executor_pid);
5545
+ const stillAlive = await this.processController.isProcessAlive(
5546
+ task.executor_pid
5547
+ );
5438
5548
  if (!stillAlive) {
5439
5549
  return;
5440
5550
  }
@@ -5569,7 +5679,9 @@ var TaskManager = class {
5569
5679
  if (isTerminalTaskState(task.state)) {
5570
5680
  continue;
5571
5681
  }
5572
- const ownerAlive = await this.processController.isProcessAlive(task.owner_pid);
5682
+ const ownerAlive = await this.processController.isProcessAlive(
5683
+ task.owner_pid
5684
+ );
5573
5685
  if (ownerAlive) {
5574
5686
  continue;
5575
5687
  }
@@ -5639,7 +5751,9 @@ var DEBUG_MAX_COMMAND_CHARS = 200;
5639
5751
  var DEFAULT_TIMEOUT_SECONDS = 120;
5640
5752
  var MAX_TIMEOUT_SECONDS = 300;
5641
5753
  var MAX_TIMER_DELAY_MS = 2147483647;
5642
- var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(MAX_TIMER_DELAY_MS / 1e3);
5754
+ var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
5755
+ MAX_TIMER_DELAY_MS / 1e3
5756
+ );
5643
5757
  var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
5644
5758
  var summarizeCommand = (command) => {
5645
5759
  const normalized = command.trim().replace(/\s+/g, " ");
@@ -5904,7 +6018,10 @@ var startShellTask = (options) => {
5904
6018
  cancelRequested = false;
5905
6019
  terminateChild(child, "SIGTERM");
5906
6020
  scheduleForceKill();
5907
- fail(`Command timed out after ${Math.trunc(timeoutSeconds)}s`, "SIGTERM");
6021
+ fail(
6022
+ `Command timed out after ${Math.trunc(timeoutSeconds)}s`,
6023
+ "SIGTERM"
6024
+ );
5908
6025
  }, timeoutSeconds * 1e3);
5909
6026
  }
5910
6027
  });
@@ -5932,11 +6049,6 @@ var createToolSessionContextKey = (getSessionId) => ({
5932
6049
  var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
5933
6050
 
5934
6051
  // src/tools/shell.ts
5935
- var DEFAULT_TRUNCATED = {
5936
- stdout: false,
5937
- stderr: false,
5938
- combined: false
5939
- };
5940
6052
  var LIVE_LOG_TAIL_BYTES = 64 * 1024;
5941
6053
  var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
5942
6054
  var truncateUtf8Suffix2 = (value, maxBytes) => {
@@ -5976,23 +6088,25 @@ var SHELL_LABEL_MAX_CHARS = 80;
5976
6088
  var SHELL_LIST_DEFAULT_LIMIT = 20;
5977
6089
  var SHELL_LIST_MAX_LIMIT = 100;
5978
6090
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
5979
- var shellStateSchema = import_zod10.z.enum([
6091
+ var shellStateSchema = import_zod11.z.enum([
5980
6092
  "queued",
5981
6093
  "running",
5982
6094
  "completed",
5983
6095
  "failed",
5984
6096
  "cancelled"
5985
6097
  ]);
5986
- var shellRunSchema = import_zod10.z.object({
5987
- command: import_zod10.z.string().describe(
6098
+ var shellRunSchema = import_zod11.z.object({
6099
+ command: import_zod11.z.string().describe(
5988
6100
  "Shell command to execute as a runtime-managed child process in the current workspace."
5989
6101
  ),
5990
- label: import_zod10.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(`Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`),
5991
- timeout: import_zod10.z.number().int().positive().optional().describe(
6102
+ label: import_zod11.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6103
+ `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
6104
+ ),
6105
+ timeout: import_zod11.z.number().int().positive().optional().describe(
5992
6106
  `Execution timeout in seconds. Foreground default: ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Background accepts larger values up to ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit to keep the managed child job running until completion, cancel, or runtime exit.`
5993
6107
  ),
5994
- background: import_zod10.z.boolean().optional().describe(
5995
- "Detach the wait and return task info immediately. The runtime still owns the child process, so this is not persistence/daemonization. Manage it with shell_status/logs/wait/result/cancel. Default: false."
6108
+ background: import_zod11.z.boolean().optional().describe(
6109
+ "Detach the wait and return compact JSON with the task key immediately. The runtime still owns the child process, so this is not persistence/daemonization. Manage it with shell_status/logs/wait/result/cancel. Default: false."
5996
6110
  )
5997
6111
  }).superRefine((input, ctx) => {
5998
6112
  if (input.timeout === void 0) {
@@ -6001,7 +6115,7 @@ var shellRunSchema = import_zod10.z.object({
6001
6115
  if (input.background ?? false) {
6002
6116
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6003
6117
  ctx.addIssue({
6004
- code: import_zod10.z.ZodIssueCode.custom,
6118
+ code: import_zod11.z.ZodIssueCode.custom,
6005
6119
  path: ["timeout"],
6006
6120
  message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6007
6121
  });
@@ -6010,32 +6124,34 @@ var shellRunSchema = import_zod10.z.object({
6010
6124
  }
6011
6125
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6012
6126
  ctx.addIssue({
6013
- code: import_zod10.z.ZodIssueCode.custom,
6127
+ code: import_zod11.z.ZodIssueCode.custom,
6014
6128
  path: ["timeout"],
6015
6129
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6016
6130
  });
6017
6131
  }
6018
6132
  });
6019
- var shellTaskKeySchema = import_zod10.z.object({
6020
- key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list.")
6133
+ var shellTaskKeySchema = import_zod11.z.object({
6134
+ key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list.")
6021
6135
  });
6022
6136
  var shellWaitSchema = shellTaskKeySchema.extend({
6023
- wait_timeout: import_zod10.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6024
- `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. Returns still_running=true if the task has not finished before this window expires.`
6137
+ wait_timeout: import_zod11.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6138
+ `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. If the task is still running when the window expires, the tool returns compact status JSON instead of hanging.`
6025
6139
  )
6026
6140
  });
6027
- var shellStreamSchema = import_zod10.z.enum(["stdout", "stderr"]);
6028
- var shellListSchema = import_zod10.z.object({
6029
- limit: import_zod10.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6141
+ var shellStreamSchema = import_zod11.z.enum(["stdout", "stderr"]);
6142
+ var shellListSchema = import_zod11.z.object({
6143
+ limit: import_zod11.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6030
6144
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6031
6145
  ),
6032
6146
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6033
- include_terminal: import_zod10.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6147
+ include_terminal: import_zod11.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6034
6148
  });
6035
- var shellLogsSchema = import_zod10.z.object({
6036
- key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list."),
6149
+ var shellLogsSchema = import_zod11.z.object({
6150
+ key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list."),
6037
6151
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6038
- tail_lines: import_zod10.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(`Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`)
6152
+ tail_lines: import_zod11.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6153
+ `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
6154
+ )
6039
6155
  });
6040
6156
  var formatTaskError = (error) => {
6041
6157
  if (error instanceof TaskManagerError) {
@@ -6054,7 +6170,10 @@ var resolveShellTimeoutSeconds = (value, background) => {
6054
6170
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6055
6171
  }
6056
6172
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
6057
- return Math.max(1, Math.min(Math.trunc(requestedTimeout), MAX_TIMEOUT_SECONDS));
6173
+ return Math.max(
6174
+ 1,
6175
+ Math.min(Math.trunc(requestedTimeout), MAX_TIMEOUT_SECONDS)
6176
+ );
6058
6177
  };
6059
6178
  var formatShellTimeoutForLog = (value) => value === void 0 ? "none" : String(value);
6060
6179
  var normalizeShellTaskKey = (value) => {
@@ -6081,7 +6200,10 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6081
6200
  (await tasks.list()).filter((task) => task.kind === "shell" && typeof task.key === "string").map((task) => task.key)
6082
6201
  );
6083
6202
  for (const length of [8, 12, compactIdValue.length]) {
6084
- const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
6203
+ const suffix = compactIdValue.slice(
6204
+ 0,
6205
+ Math.min(length, compactIdValue.length)
6206
+ );
6085
6207
  if (!suffix) continue;
6086
6208
  const candidate2 = `${base}-${suffix}`;
6087
6209
  if (!usedKeys.has(candidate2)) return candidate2;
@@ -6094,62 +6216,69 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6094
6216
  }
6095
6217
  return candidate;
6096
6218
  };
6097
- var buildShellTaskHints = (taskKey, state) => ({
6098
- status: { key: taskKey },
6099
- logs: { key: taskKey },
6100
- wait: { key: taskKey },
6101
- result: { key: taskKey },
6102
- ...isTerminalTaskState(state) ? {} : { cancel: { key: taskKey } }
6219
+ var trimNonEmpty = (value) => {
6220
+ if (value === void 0 || value === null) return null;
6221
+ const trimmed = value.trimEnd();
6222
+ return trimmed.trim().length > 0 ? trimmed : null;
6223
+ };
6224
+ var pickShellOutput = (task) => {
6225
+ const stdout = trimNonEmpty(task.result?.stdout);
6226
+ const stderr = trimNonEmpty(task.result?.stderr);
6227
+ const exitCode = task.result?.exit_code;
6228
+ const preferError = task.state === "failed" || task.state === "cancelled" || exitCode !== null && exitCode !== void 0 && exitCode !== 0;
6229
+ const primaryStream = preferError ? "stderr" : "stdout";
6230
+ const primaryContent = primaryStream === "stderr" ? stderr : stdout;
6231
+ const secondaryContent = primaryStream === "stderr" ? stdout : stderr;
6232
+ const selectedStream = primaryContent ? primaryStream : secondaryContent ? primaryStream === "stderr" ? "stdout" : "stderr" : null;
6233
+ if (!selectedStream) {
6234
+ return null;
6235
+ }
6236
+ const field = preferError ? "error_output" : "output";
6237
+ const cacheId = selectedStream === "stderr" ? task.result?.stderr_cache_id : task.result?.stdout_cache_id;
6238
+ return {
6239
+ field,
6240
+ content: selectedStream === "stderr" ? stderr ?? "" : stdout ?? "",
6241
+ ...cacheId ? { cacheId } : {}
6242
+ };
6243
+ };
6244
+ var shellBasePayload = (task) => ({
6245
+ key: getShellTaskKey(task),
6246
+ state: task.state,
6247
+ ...task.title ? { command: task.title } : {}
6103
6248
  });
6104
- var toJsonValue = (value) => {
6105
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
6106
- return value;
6249
+ var shellStatusPayload = (task, options = {}) => ({
6250
+ ...shellBasePayload(task),
6251
+ ...options.background ? { background: true } : {},
6252
+ ...options.stillRunning ? { still_running: true } : {},
6253
+ ...options.aborted ? { aborted: true } : {}
6254
+ });
6255
+ var shellTerminalPayload = (task) => {
6256
+ const payload = shellBasePayload(task);
6257
+ if (task.result?.exit_code !== void 0 && task.result.exit_code !== null) {
6258
+ payload.exit_code = task.result.exit_code;
6107
6259
  }
6108
- if (Array.isArray(value)) {
6109
- return value.map((entry) => toJsonValue(entry));
6260
+ if (task.result?.duration_ms !== void 0 && task.result.duration_ms !== null) {
6261
+ payload.duration_ms = task.result.duration_ms;
6262
+ }
6263
+ if (task.failure_message) {
6264
+ payload.failure_message = task.failure_message;
6110
6265
  }
6111
- if (value && typeof value === "object") {
6112
- const objectValue = {};
6113
- for (const [key, entry] of Object.entries(value)) {
6114
- objectValue[key] = toJsonValue(entry);
6266
+ if (task.cancellation_reason) {
6267
+ payload.cancellation_reason = task.cancellation_reason;
6268
+ }
6269
+ const output = pickShellOutput(task);
6270
+ if (output) {
6271
+ payload[output.field] = output.content;
6272
+ if (output.cacheId) {
6273
+ payload.cache_id = output.cacheId;
6115
6274
  }
6116
- return objectValue;
6117
6275
  }
6118
- return String(value);
6276
+ return payload;
6119
6277
  };
6120
- var toShellTaskSummary = (task) => ({
6121
- task_id: task.task_id,
6122
- key: getShellTaskKey(task),
6123
- ...task.label ? { label: task.label } : {},
6124
- state: task.state,
6125
- ...task.title ? { title: task.title } : {},
6126
- ...task.working_directory ? { working_directory: task.working_directory } : {},
6127
- created_at: task.created_at,
6128
- updated_at: task.updated_at,
6129
- ...task.started_at ? { started_at: task.started_at } : {},
6130
- ...task.ended_at ? { ended_at: task.ended_at } : {},
6131
- exit_code: task.result?.exit_code ?? null,
6132
- duration_ms: task.result?.duration_ms ?? null,
6133
- result_available: isTerminalTaskState(task.state) && !!task.result,
6134
- ...task.failure_message ? { failure_message: task.failure_message } : {},
6278
+ var shellCancelPayload = (task) => ({
6279
+ ...shellBasePayload(task),
6135
6280
  ...task.cancellation_reason ? { cancellation_reason: task.cancellation_reason } : {},
6136
- ...task.cleanup_reason ? { cleanup_reason: task.cleanup_reason } : {}
6137
- });
6138
- var toShellTaskInfo = (task) => ({
6139
- ...toShellTaskSummary(task),
6140
- kind: task.kind,
6141
- workspace_mode: task.workspace_mode,
6142
- ...task.result?.child_session_id ?? task.child_session_id ? { child_session_id: task.result?.child_session_id ?? task.child_session_id } : {},
6143
- signal: task.result?.signal ?? null,
6144
- ...task.result?.summary ? { summary: task.result.summary } : {},
6145
- ...task.result?.stdout !== void 0 ? { stdout: task.result.stdout } : {},
6146
- ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
6147
- ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
6148
- ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
6149
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
6150
- ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
6151
- ...task.result?.artifacts ? { artifacts: toJsonValue(task.result.artifacts) } : {},
6152
- next_actions: buildShellTaskHints(getShellTaskKey(task), task.state)
6281
+ ...task.failure_message ? { failure_message: task.failure_message } : {}
6153
6282
  });
6154
6283
  var toShellListEntry = (task) => ({
6155
6284
  key: getShellTaskKey(task),
@@ -6182,7 +6311,10 @@ var resolveShellTask = async (tasks, input) => {
6182
6311
  const refs = matches.map((task) => task.task_id).join(", ");
6183
6312
  throw new Error(`multiple shell tasks matched key "${key}": ${refs}`);
6184
6313
  }
6185
- throw new TaskManagerError("task_not_found", `Shell task not found for key: ${key}`);
6314
+ throw new TaskManagerError(
6315
+ "task_not_found",
6316
+ `Shell task not found for key: ${key}`
6317
+ );
6186
6318
  };
6187
6319
  var tailContentByLines = (content, tailLines) => {
6188
6320
  if (content.length === 0) {
@@ -6205,7 +6337,10 @@ var tailContentByLines = (content, tailLines) => {
6205
6337
  };
6206
6338
  var resolveShellLogs = async (options) => {
6207
6339
  const taskKey = getShellTaskKey(options.task);
6208
- const live = await options.tasks.readOutput(options.task.task_id, options.stream);
6340
+ const live = await options.tasks.readOutput(
6341
+ options.task.task_id,
6342
+ options.stream
6343
+ );
6209
6344
  if (live !== null) {
6210
6345
  if (options.tailLines !== void 0) {
6211
6346
  const tailed = tailContentByLines(live, options.tailLines);
@@ -6324,7 +6459,10 @@ var waitForManagedTask = async (tasks, taskId, signal) => {
6324
6459
  throw error;
6325
6460
  }
6326
6461
  };
6327
- var resolveShellWaitTimeoutSeconds = (value) => Math.max(1, Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS));
6462
+ var resolveShellWaitTimeoutSeconds = (value) => Math.max(
6463
+ 1,
6464
+ Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS)
6465
+ );
6328
6466
  var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6329
6467
  let timeoutHandle;
6330
6468
  const waitPromise = waitForManagedTask(tasks, taskId, options.signal).then(
@@ -6369,9 +6507,9 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6369
6507
  };
6370
6508
  var createShellTool = (sandboxKey, options = {}) => {
6371
6509
  const shared = getSharedDeps(options);
6372
- return (0, import_core11.defineTool)({
6510
+ return (0, import_core12.defineTool)({
6373
6511
  name: "shell",
6374
- description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `background=true`, detach the wait and return task info you can inspect, wait on, or cancel later.",
6512
+ description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `background=true`, detach the wait and return compact JSON with the task key for follow-up tools.",
6375
6513
  input: shellRunSchema,
6376
6514
  execute: async (input, ctx) => {
6377
6515
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6382,7 +6520,10 @@ var createShellTool = (sandboxKey, options = {}) => {
6382
6520
  }
6383
6521
  const label = normalizeOptionalLabel(input.label);
6384
6522
  const background = input.background ?? false;
6385
- const timeoutSeconds = resolveShellTimeoutSeconds(input.timeout, background);
6523
+ const timeoutSeconds = resolveShellTimeoutSeconds(
6524
+ input.timeout,
6525
+ background
6526
+ );
6386
6527
  const commandSummary = summarizeCommand(command);
6387
6528
  (0, import_logger.debugLog)(
6388
6529
  `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
@@ -6411,19 +6552,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6411
6552
  })
6412
6553
  );
6413
6554
  if (background) {
6414
- return {
6415
- background: true,
6416
- task: toShellTaskInfo(task)
6417
- };
6555
+ return shellStatusPayload(task, { background: true });
6418
6556
  }
6419
- const settled = await waitForForegroundRun(shared.tasks, task.task_id, ctx.signal);
6557
+ const settled = await waitForForegroundRun(
6558
+ shared.tasks,
6559
+ task.task_id,
6560
+ ctx.signal
6561
+ );
6420
6562
  (0, import_logger.debugLog)(
6421
6563
  `shell.done task_id=${task.task_id} state=${settled.state} duration_ms=${settled.result?.duration_ms ?? -1}`
6422
6564
  );
6423
- return {
6424
- background: false,
6425
- task: toShellTaskInfo(settled)
6426
- };
6565
+ return shellTerminalPayload(settled);
6427
6566
  } catch (error) {
6428
6567
  throw formatTaskError(error);
6429
6568
  }
@@ -6432,7 +6571,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6432
6571
  };
6433
6572
  var createShellListTool = (options = {}) => {
6434
6573
  const shared = getSharedDeps(options);
6435
- return (0, import_core11.defineTool)({
6574
+ return (0, import_core12.defineTool)({
6436
6575
  name: "shell_list",
6437
6576
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6438
6577
  input: shellListSchema,
@@ -6463,14 +6602,14 @@ var createShellListTool = (options = {}) => {
6463
6602
  };
6464
6603
  var createShellStatusTool = (options = {}) => {
6465
6604
  const shared = getSharedDeps(options);
6466
- return (0, import_core11.defineTool)({
6605
+ return (0, import_core12.defineTool)({
6467
6606
  name: "shell_status",
6468
- description: "Get the current state and retained metadata for a shell task.",
6607
+ description: "Get the current state for a shell task as compact JSON.",
6469
6608
  input: shellTaskKeySchema,
6470
6609
  execute: async (input) => {
6471
6610
  try {
6472
6611
  const task = await resolveShellTask(shared.tasks, input);
6473
- return { task: toShellTaskInfo(task) };
6612
+ return shellStatusPayload(task);
6474
6613
  } catch (error) {
6475
6614
  throw formatTaskError(error);
6476
6615
  }
@@ -6479,7 +6618,7 @@ var createShellStatusTool = (options = {}) => {
6479
6618
  };
6480
6619
  var createShellLogsTool = (options = {}) => {
6481
6620
  const shared = getSharedDeps(options);
6482
- return (0, import_core11.defineTool)({
6621
+ return (0, import_core12.defineTool)({
6483
6622
  name: "shell_logs",
6484
6623
  description: "Read recent stdout or stderr for a running or finished shell task.",
6485
6624
  input: shellLogsSchema,
@@ -6501,9 +6640,9 @@ var createShellLogsTool = (options = {}) => {
6501
6640
  };
6502
6641
  var createShellWaitTool = (options = {}) => {
6503
6642
  const shared = getSharedDeps(options);
6504
- return (0, import_core11.defineTool)({
6643
+ return (0, import_core12.defineTool)({
6505
6644
  name: "shell_wait",
6506
- description: "Wait for a shell task within a bounded window and return its retained outcome; if the window expires first, return still_running=true.",
6645
+ description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6507
6646
  input: shellWaitSchema,
6508
6647
  execute: async (input, ctx) => {
6509
6648
  try {
@@ -6519,11 +6658,13 @@ var createShellWaitTool = (options = {}) => {
6519
6658
  signal: ctx.signal
6520
6659
  }
6521
6660
  );
6522
- return {
6523
- ...result.aborted ? { aborted: true } : {},
6524
- ...result.stillRunning ? { still_running: true } : {},
6525
- task: toShellTaskInfo(result.task)
6526
- };
6661
+ if (result.stillRunning || result.aborted) {
6662
+ return shellStatusPayload(result.task, {
6663
+ aborted: result.aborted,
6664
+ stillRunning: result.stillRunning
6665
+ });
6666
+ }
6667
+ return shellTerminalPayload(result.task);
6527
6668
  } catch (error) {
6528
6669
  throw formatTaskError(error);
6529
6670
  }
@@ -6532,14 +6673,14 @@ var createShellWaitTool = (options = {}) => {
6532
6673
  };
6533
6674
  var createShellResultTool = (options = {}) => {
6534
6675
  const shared = getSharedDeps(options);
6535
- return (0, import_core11.defineTool)({
6676
+ return (0, import_core12.defineTool)({
6536
6677
  name: "shell_result",
6537
- description: "Read the retained terminal result for a shell task.",
6678
+ description: "Read the retained terminal result for a shell task as compact JSON.",
6538
6679
  input: shellTaskKeySchema,
6539
6680
  execute: async (input) => {
6540
6681
  try {
6541
6682
  const task = await resolveShellTask(shared.tasks, input);
6542
- return { task: toShellTaskInfo(task) };
6683
+ return isTerminalTaskState(task.state) ? shellTerminalPayload(task) : shellStatusPayload(task);
6543
6684
  } catch (error) {
6544
6685
  throw formatTaskError(error);
6545
6686
  }
@@ -6548,9 +6689,9 @@ var createShellResultTool = (options = {}) => {
6548
6689
  };
6549
6690
  var createShellCancelTool = (options = {}) => {
6550
6691
  const shared = getSharedDeps(options);
6551
- return (0, import_core11.defineTool)({
6692
+ return (0, import_core12.defineTool)({
6552
6693
  name: "shell_cancel",
6553
- description: "Cancel a running shell task and return its retained terminal state.",
6694
+ description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6554
6695
  input: shellTaskKeySchema,
6555
6696
  execute: async (input) => {
6556
6697
  try {
@@ -6558,7 +6699,7 @@ var createShellCancelTool = (options = {}) => {
6558
6699
  const cancelled = await shared.tasks.cancel(task.task_id, {
6559
6700
  reason: "cancelled"
6560
6701
  });
6561
- return { task: toShellTaskInfo(cancelled) };
6702
+ return shellCancelPayload(cancelled);
6562
6703
  } catch (error) {
6563
6704
  throw formatTaskError(error);
6564
6705
  }
@@ -6567,16 +6708,16 @@ var createShellCancelTool = (options = {}) => {
6567
6708
  };
6568
6709
 
6569
6710
  // src/tools/skill-load.ts
6570
- var import_core12 = require("@codelia/core");
6571
- var import_zod11 = require("zod");
6572
- var SkillLoadInputSchema = import_zod11.z.object({
6573
- name: import_zod11.z.string().min(1).optional().describe("Exact skill name to load."),
6574
- path: import_zod11.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6711
+ var import_core13 = require("@codelia/core");
6712
+ var import_zod12 = require("zod");
6713
+ var SkillLoadInputSchema = import_zod12.z.object({
6714
+ name: import_zod12.z.string().min(1).optional().describe("Exact skill name to load."),
6715
+ path: import_zod12.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6575
6716
  }).refine((value) => !!value.name || !!value.path, {
6576
6717
  message: "name or path is required",
6577
6718
  path: ["name"]
6578
6719
  });
6579
- var createSkillLoadTool = (skillsResolverKey) => (0, import_core12.defineTool)({
6720
+ var createSkillLoadTool = (skillsResolverKey) => (0, import_core13.defineTool)({
6580
6721
  name: "skill_load",
6581
6722
  description: "Load full SKILL.md content by exact name or path.",
6582
6723
  input: SkillLoadInputSchema,
@@ -6622,15 +6763,15 @@ var createSkillLoadTool = (skillsResolverKey) => (0, import_core12.defineTool)({
6622
6763
  });
6623
6764
 
6624
6765
  // src/tools/skill-search.ts
6625
- var import_core13 = require("@codelia/core");
6626
- var import_zod12 = require("zod");
6627
- var createSkillSearchTool = (skillsResolverKey) => (0, import_core13.defineTool)({
6766
+ var import_core14 = require("@codelia/core");
6767
+ var import_zod13 = require("zod");
6768
+ var createSkillSearchTool = (skillsResolverKey) => (0, import_core14.defineTool)({
6628
6769
  name: "skill_search",
6629
6770
  description: "Search installed local skills by name, description, or path.",
6630
- input: import_zod12.z.object({
6631
- query: import_zod12.z.string().min(1).describe("Search query text."),
6632
- limit: import_zod12.z.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6633
- scope: import_zod12.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6771
+ input: import_zod13.z.object({
6772
+ query: import_zod13.z.string().min(1).describe("Search query text."),
6773
+ limit: import_zod13.z.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6774
+ scope: import_zod13.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6634
6775
  }),
6635
6776
  execute: async (input, ctx) => {
6636
6777
  try {
@@ -6653,8 +6794,8 @@ var createSkillSearchTool = (skillsResolverKey) => (0, import_core13.defineTool)
6653
6794
  });
6654
6795
 
6655
6796
  // src/tools/todo-mutate.ts
6656
- var import_core14 = require("@codelia/core");
6657
- var import_zod13 = require("zod");
6797
+ var import_core15 = require("@codelia/core");
6798
+ var import_zod14 = require("zod");
6658
6799
 
6659
6800
  // src/tools/todo-store.ts
6660
6801
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6764,37 +6905,37 @@ var pickNextTodo = (todos) => {
6764
6905
  var todoStore = /* @__PURE__ */ new Map();
6765
6906
 
6766
6907
  // src/tools/todo-mutate.ts
6767
- var todoStatusSchema = import_zod13.z.enum(["pending", "in_progress", "completed"]);
6768
- var todoPrioritySchema = import_zod13.z.number().int().min(1).max(5);
6769
- var todoItemSchema = import_zod13.z.object({
6770
- id: import_zod13.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6771
- content: import_zod13.z.string().min(1).describe("Todo item text."),
6908
+ var todoStatusSchema = import_zod14.z.enum(["pending", "in_progress", "completed"]);
6909
+ var todoPrioritySchema = import_zod14.z.number().int().min(1).max(5);
6910
+ var todoItemSchema = import_zod14.z.object({
6911
+ id: import_zod14.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6912
+ content: import_zod14.z.string().min(1).describe("Todo item text."),
6772
6913
  status: todoStatusSchema.describe("Todo status."),
6773
6914
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6774
- notes: import_zod13.z.string().optional().describe("Optional implementation notes."),
6775
- activeForm: import_zod13.z.string().optional().describe("Optional in-progress phrasing for UI display.")
6915
+ notes: import_zod14.z.string().optional().describe("Optional implementation notes."),
6916
+ activeForm: import_zod14.z.string().optional().describe("Optional in-progress phrasing for UI display.")
6776
6917
  });
6777
- var todoPatchItemSchema = import_zod13.z.object({
6778
- id: import_zod13.z.string().min(1).describe("Target todo ID."),
6779
- remove: import_zod13.z.boolean().optional().describe("Set true to remove the todo item."),
6780
- content: import_zod13.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6918
+ var todoPatchItemSchema = import_zod14.z.object({
6919
+ id: import_zod14.z.string().min(1).describe("Target todo ID."),
6920
+ remove: import_zod14.z.boolean().optional().describe("Set true to remove the todo item."),
6921
+ content: import_zod14.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6781
6922
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6782
6923
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6783
- notes: import_zod13.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6784
- activeForm: import_zod13.z.string().nullable().default(null).describe(
6924
+ notes: import_zod14.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6925
+ activeForm: import_zod14.z.string().nullable().default(null).describe(
6785
6926
  "Updated in-progress phrasing (null keeps current, empty clears)."
6786
6927
  )
6787
6928
  });
6788
- var todoNewInputSchema = import_zod13.z.object({
6789
- todos: import_zod13.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6929
+ var todoNewInputSchema = import_zod14.z.object({
6930
+ todos: import_zod14.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6790
6931
  }).strict();
6791
- var todoAppendInputSchema = import_zod13.z.object({
6792
- todos: import_zod13.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6932
+ var todoAppendInputSchema = import_zod14.z.object({
6933
+ todos: import_zod14.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6793
6934
  }).strict();
6794
- var todoPatchInputSchema = import_zod13.z.object({
6795
- updates: import_zod13.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6935
+ var todoPatchInputSchema = import_zod14.z.object({
6936
+ updates: import_zod14.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6796
6937
  }).strict();
6797
- var todoClearInputSchema = import_zod13.z.object({}).strict();
6938
+ var todoClearInputSchema = import_zod14.z.object({}).strict();
6798
6939
  var statusSymbol = {
6799
6940
  pending: "[ ]",
6800
6941
  in_progress: "[>]",
@@ -6889,7 +7030,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6889
7030
  }
6890
7031
  return formatSuccess(outputMode, nextTodos);
6891
7032
  };
6892
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => (0, import_core14.defineTool)({
7033
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
6893
7034
  name,
6894
7035
  description,
6895
7036
  input,
@@ -6906,11 +7047,7 @@ var createTodoNewTool = (sandboxKey, sessionContextKey) => createTodoMutationToo
6906
7047
  "todo_new",
6907
7048
  "Start or replace the in-session todo plan with a full task list.",
6908
7049
  todoNewInputSchema,
6909
- (sessionId, input) => applyTodoMutation(
6910
- sessionId,
6911
- { mode: "new", todos: input.todos },
6912
- "new"
6913
- ),
7050
+ (sessionId, input) => applyTodoMutation(sessionId, { mode: "new", todos: input.todos }, "new"),
6914
7051
  sandboxKey,
6915
7052
  sessionContextKey
6916
7053
  );
@@ -6948,17 +7085,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6948
7085
  );
6949
7086
 
6950
7087
  // src/tools/todo-read.ts
6951
- var import_core15 = require("@codelia/core");
6952
- var import_zod14 = require("zod");
7088
+ var import_core16 = require("@codelia/core");
7089
+ var import_zod15 = require("zod");
6953
7090
  var statusSymbol2 = {
6954
7091
  pending: "[ ]",
6955
7092
  in_progress: "[>]",
6956
7093
  completed: "[x]"
6957
7094
  };
6958
- var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
7095
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.defineTool)({
6959
7096
  name: "todo_read",
6960
7097
  description: "Read the in-session todo plan with execution order and next step.",
6961
- input: import_zod14.z.object({}),
7098
+ input: import_zod15.z.object({}),
6962
7099
  execute: async (_input, ctx) => {
6963
7100
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6964
7101
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -6994,15 +7131,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core15.de
6994
7131
  });
6995
7132
 
6996
7133
  // src/tools/tool-output-cache.ts
6997
- var import_core16 = require("@codelia/core");
6998
- var import_zod15 = require("zod");
6999
- var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
7134
+ var import_core17 = require("@codelia/core");
7135
+ var import_zod16 = require("zod");
7136
+ var createToolOutputCacheTool = (store) => (0, import_core17.defineTool)({
7000
7137
  name: "tool_output_cache",
7001
7138
  description: "Read cached tool output by ref_id.",
7002
- input: import_zod15.z.object({
7003
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7004
- offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7005
- limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return.")
7139
+ input: import_zod16.z.object({
7140
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7141
+ offset: import_zod16.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7142
+ limit: import_zod16.z.number().int().positive().optional().describe("Optional max number of lines to return.")
7006
7143
  }),
7007
7144
  execute: async (input) => {
7008
7145
  if (!store.read) {
@@ -7018,14 +7155,14 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
7018
7155
  }
7019
7156
  }
7020
7157
  });
7021
- var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
7158
+ var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
7022
7159
  name: "tool_output_cache_line",
7023
7160
  description: "Read a single cached output line segment by line number and char offset.",
7024
- input: import_zod15.z.object({
7025
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7026
- line_number: import_zod15.z.number().int().positive().describe("1-based line number to read."),
7027
- char_offset: import_zod15.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7028
- char_limit: import_zod15.z.number().int().positive().optional().describe("Max chars to return.")
7161
+ input: import_zod16.z.object({
7162
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7163
+ line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
7164
+ char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7165
+ char_limit: import_zod16.z.number().int().positive().optional().describe("Max chars to return.")
7029
7166
  }),
7030
7167
  execute: async (input) => {
7031
7168
  if (!store.readLine) {
@@ -7042,16 +7179,16 @@ var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
7042
7179
  }
7043
7180
  }
7044
7181
  });
7045
- var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7182
+ var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
7046
7183
  name: "tool_output_cache_grep",
7047
7184
  description: "Search cached tool output by ref_id.",
7048
- input: import_zod15.z.object({
7049
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7050
- pattern: import_zod15.z.string().describe("Text or regex pattern to search for."),
7051
- regex: import_zod15.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7052
- before: import_zod15.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7053
- after: import_zod15.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7054
- max_matches: import_zod15.z.number().int().positive().optional().describe("Maximum number of matches to return.")
7185
+ input: import_zod16.z.object({
7186
+ ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7187
+ pattern: import_zod16.z.string().describe("Text or regex pattern to search for."),
7188
+ regex: import_zod16.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7189
+ before: import_zod16.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7190
+ after: import_zod16.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7191
+ max_matches: import_zod16.z.number().int().positive().optional().describe("Maximum number of matches to return.")
7055
7192
  }),
7056
7193
  execute: async (input) => {
7057
7194
  if (!store.grep) {
@@ -7071,74 +7208,6 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7071
7208
  }
7072
7209
  });
7073
7210
 
7074
- // src/tools/read-line.ts
7075
- var import_node_fs14 = require("fs");
7076
- var import_core17 = require("@codelia/core");
7077
- var import_zod16 = require("zod");
7078
- var DEFAULT_CHAR_LIMIT = 1e4;
7079
- var MAX_CHAR_LIMIT = 1e5;
7080
- var createReadLineTool = (sandboxKey) => (0, import_core17.defineTool)({
7081
- name: "read_line",
7082
- description: "Read a single line segment by 1-based line number and 0-based char offset.",
7083
- input: import_zod16.z.object({
7084
- file_path: import_zod16.z.string().describe("File path under the sandbox root."),
7085
- line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
7086
- char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7087
- char_limit: import_zod16.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
7088
- }),
7089
- execute: async (input, ctx) => {
7090
- let resolved;
7091
- try {
7092
- const sandbox = await getSandboxContext(ctx, sandboxKey);
7093
- resolved = sandbox.resolvePath(input.file_path);
7094
- } catch (error) {
7095
- return `Security error: ${String(error)}`;
7096
- }
7097
- try {
7098
- const stat = await import_node_fs14.promises.stat(resolved);
7099
- if (stat.isDirectory()) {
7100
- return `Path is a directory: ${input.file_path}`;
7101
- }
7102
- } catch {
7103
- return `File not found: ${input.file_path}`;
7104
- }
7105
- try {
7106
- const content = await import_node_fs14.promises.readFile(resolved, "utf8");
7107
- const lines = content.split(/\r?\n/);
7108
- const lineIndex = input.line_number - 1;
7109
- if (lineIndex >= lines.length) {
7110
- return `Line number out of range: ${input.line_number} (total ${lines.length})`;
7111
- }
7112
- const line = lines[lineIndex] ?? "";
7113
- const charOffset = input.char_offset ?? 0;
7114
- const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
7115
- if (charOffset > line.length) {
7116
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
7117
- }
7118
- const segment = line.slice(charOffset, charOffset + charLimit);
7119
- const endOffset = charOffset + segment.length;
7120
- const hasMore = endOffset < line.length;
7121
- const header = [
7122
- `line_number=${input.line_number}`,
7123
- `line_length=${line.length}`,
7124
- `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
7125
- ].join(" ");
7126
- let output = `${header}
7127
- ${segment}`;
7128
- if (hasMore) {
7129
- output += `
7130
-
7131
- Use char_offset=${endOffset} to continue.`;
7132
- output += `
7133
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
7134
- }
7135
- return output;
7136
- } catch (error) {
7137
- return `Error reading file: ${String(error)}`;
7138
- }
7139
- }
7140
- });
7141
-
7142
7211
  // src/tools/write.ts
7143
7212
  var import_node_fs15 = require("fs");
7144
7213
  var import_node_path13 = __toESM(require("path"), 1);
@@ -7157,7 +7226,9 @@ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
7157
7226
  name: "write",
7158
7227
  description: "Write text to a file, creating parent directories if needed.",
7159
7228
  input: import_zod17.z.object({
7160
- file_path: import_zod17.z.string().describe("File path under the sandbox root."),
7229
+ file_path: import_zod17.z.string().describe(
7230
+ "File path. Sandbox-bounded unless full-access mode is active."
7231
+ ),
7161
7232
  content: import_zod17.z.string().describe("UTF-8 text content to write.")
7162
7233
  }),
7163
7234
  execute: async (input, ctx) => {
@@ -7166,7 +7237,7 @@ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
7166
7237
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7167
7238
  resolved = sandbox.resolvePath(input.file_path);
7168
7239
  } catch (error) {
7169
- return `Security error: ${String(error)}`;
7240
+ throw new Error(`Security error: ${String(error)}`);
7170
7241
  }
7171
7242
  try {
7172
7243
  await import_node_fs15.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
@@ -7661,9 +7732,21 @@ var createAgentFactory = (state, options = {}) => {
7661
7732
  if (state.agent) return state.agent;
7662
7733
  if (inFlight) return inFlight;
7663
7734
  inFlight = (async () => {
7664
- const rootDir = process.env.CODELIA_SANDBOX_ROOT;
7665
- const ctx = await SandboxContext.create(rootDir);
7666
- (0, import_logger.log)(`sandbox created at ${ctx.rootDir}`);
7735
+ const sandboxRoot = state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
7736
+ const approvalModeResolution = await resolveApprovalModeForRuntime({
7737
+ workingDir: sandboxRoot,
7738
+ runtimeSandboxRoot: sandboxRoot,
7739
+ requestStartupSelection: async ({ projectKey }) => {
7740
+ return requestApprovalModeStartupSelection(state, projectKey);
7741
+ },
7742
+ deferStartupSelectionPersist: true
7743
+ });
7744
+ const ctx = await SandboxContext.create(sandboxRoot, {
7745
+ approvalMode: approvalModeResolution.approvalMode
7746
+ });
7747
+ (0, import_logger.log)(
7748
+ `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
7749
+ );
7667
7750
  const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
7668
7751
  state.agentsResolver = agentsResolver;
7669
7752
  let skillsConfig;
@@ -7738,13 +7821,6 @@ var createAgentFactory = (state, options = {}) => {
7738
7821
  const message = error instanceof Error ? error.message : String(error);
7739
7822
  throw new Error(message);
7740
7823
  }
7741
- const approvalModeResolution = await resolveApprovalModeForRuntime({
7742
- workingDir: ctx.workingDir,
7743
- runtimeSandboxRoot: state.runtimeSandboxRoot,
7744
- requestStartupSelection: async ({ projectKey }) => {
7745
- return requestApprovalModeStartupSelection(state, projectKey);
7746
- }
7747
- });
7748
7824
  const permissionService = new PermissionService({
7749
7825
  approvalMode: approvalModeResolution.approvalMode,
7750
7826
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
@@ -8079,6 +8155,9 @@ var createAgentFactory = (state, options = {}) => {
8079
8155
  return { decision: "allow" };
8080
8156
  }
8081
8157
  });
8158
+ if (approvalModeResolution.persistSelection) {
8159
+ await approvalModeResolution.persistSelection();
8160
+ }
8082
8161
  state.agent = agent;
8083
8162
  return agent;
8084
8163
  })();
@@ -11013,7 +11092,7 @@ var import_node_path15 = __toESM(require("path"), 1);
11013
11092
  var import_protocol6 = require("@codelia/protocol");
11014
11093
  var import_storage11 = require("@codelia/storage");
11015
11094
  var COMMAND_PREVIEW_CHARS = 400;
11016
- var DEFAULT_TRUNCATED2 = {
11095
+ var DEFAULT_TRUNCATED = {
11017
11096
  stdout: false,
11018
11097
  stderr: false,
11019
11098
  combined: false
@@ -11151,12 +11230,12 @@ var toShellExecResult = (commandPreview, result) => ({
11151
11230
  signal: result?.signal ?? null,
11152
11231
  stdout: result?.stdout ?? "",
11153
11232
  stderr: result?.stderr ?? "",
11154
- truncated: result?.truncated ?? DEFAULT_TRUNCATED2,
11233
+ truncated: result?.truncated ?? DEFAULT_TRUNCATED,
11155
11234
  duration_ms: result?.duration_ms ?? 0,
11156
11235
  ...result?.stdout_cache_id ? { stdout_cache_id: result.stdout_cache_id } : {},
11157
11236
  ...result?.stderr_cache_id ? { stderr_cache_id: result.stderr_cache_id } : {}
11158
11237
  });
11159
- var toShellTaskInfo2 = (task) => ({
11238
+ var toShellTaskInfo = (task) => ({
11160
11239
  task_id: task.task_id,
11161
11240
  state: task.state,
11162
11241
  command_preview: task.title,
@@ -11169,7 +11248,7 @@ var toShellTaskInfo2 = (task) => ({
11169
11248
  signal: task.result?.signal ?? null,
11170
11249
  stdout: task.result?.stdout ?? "",
11171
11250
  stderr: task.result?.stderr ?? "",
11172
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED2,
11251
+ truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
11173
11252
  duration_ms: task.result?.duration_ms ?? null,
11174
11253
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11175
11254
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
@@ -11215,7 +11294,10 @@ var sendTaskError = (id, error) => {
11215
11294
  var requireShellTask = async (taskManager, taskId) => {
11216
11295
  const task = await taskManager.status(taskId);
11217
11296
  if (!task || task.kind !== "shell") {
11218
- throw new TaskManagerError("task_not_found", `Shell task not found: ${taskId}`);
11297
+ throw new TaskManagerError(
11298
+ "task_not_found",
11299
+ `Shell task not found: ${taskId}`
11300
+ );
11219
11301
  }
11220
11302
  return task;
11221
11303
  };
@@ -11373,7 +11455,7 @@ var createShellHandlers = ({
11373
11455
  const handleShellStart = async (id, params) => {
11374
11456
  try {
11375
11457
  const { task } = await spawnShell(params, "shell.start");
11376
- sendResult(id, toShellTaskInfo2(task));
11458
+ sendResult(id, toShellTaskInfo(task));
11377
11459
  } catch (error) {
11378
11460
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
11379
11461
  sendError(id, error);
@@ -11393,7 +11475,7 @@ var createShellHandlers = ({
11393
11475
  }
11394
11476
  try {
11395
11477
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
11396
- const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo2);
11478
+ const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo);
11397
11479
  const result = { tasks };
11398
11480
  sendResult(id, result);
11399
11481
  } catch (error) {
@@ -11411,7 +11493,7 @@ var createShellHandlers = ({
11411
11493
  }
11412
11494
  try {
11413
11495
  const task = await requireShellTask(shellTaskManager, taskId);
11414
- sendResult(id, toShellTaskInfo2(task));
11496
+ sendResult(id, toShellTaskInfo(task));
11415
11497
  } catch (error) {
11416
11498
  sendTaskError(id, error);
11417
11499
  }
@@ -11484,23 +11566,23 @@ var createShellHandlers = ({
11484
11566
  try {
11485
11567
  const existing = await requireShellTask(shellTaskManager, taskId);
11486
11568
  if (isTerminalTaskState(existing.state)) {
11487
- sendResult(id, toShellTaskInfo2(existing));
11569
+ sendResult(id, toShellTaskInfo(existing));
11488
11570
  return;
11489
11571
  }
11490
11572
  const controller = new AbortController();
11491
11573
  let timeoutHandle;
11492
11574
  let resolveDetached;
11493
- const detachPromise = new Promise(
11575
+ const detachPromise = new Promise((resolve) => {
11576
+ resolveDetached = (result) => resolve({ type: "detached", result });
11577
+ });
11578
+ const timeoutPromise = new Promise(
11494
11579
  (resolve) => {
11495
- resolveDetached = (result) => resolve({ type: "detached", result });
11580
+ timeoutHandle = setTimeout(() => {
11581
+ controller.abort();
11582
+ resolve({ type: "still_running" });
11583
+ }, waitTimeoutSeconds * 1e3);
11496
11584
  }
11497
11585
  );
11498
- const timeoutPromise = new Promise((resolve) => {
11499
- timeoutHandle = setTimeout(() => {
11500
- controller.abort();
11501
- resolve({ type: "still_running" });
11502
- }, waitTimeoutSeconds * 1e3);
11503
- });
11504
11586
  const unregister = registerActiveShellWait(taskId, {
11505
11587
  detach: (task) => {
11506
11588
  resolveDetached({
@@ -11530,7 +11612,7 @@ var createShellHandlers = ({
11530
11612
  if (outcome.type === "still_running") {
11531
11613
  const task = await requireShellTask(shellTaskManager, taskId);
11532
11614
  sendResult(id, {
11533
- ...toShellTaskInfo2(task),
11615
+ ...toShellTaskInfo(task),
11534
11616
  ...isTerminalTaskState(task.state) ? {} : { still_running: true }
11535
11617
  });
11536
11618
  return;
@@ -11538,7 +11620,7 @@ var createShellHandlers = ({
11538
11620
  if (outcome.type === "aborted") {
11539
11621
  return;
11540
11622
  }
11541
- sendResult(id, toShellTaskInfo2(outcome.task));
11623
+ sendResult(id, toShellTaskInfo(outcome.task));
11542
11624
  } finally {
11543
11625
  if (timeoutHandle) {
11544
11626
  clearTimeout(timeoutHandle);
@@ -11595,7 +11677,7 @@ var createShellHandlers = ({
11595
11677
  const task = await shellTaskManager.cancel(taskId, {
11596
11678
  reason: "cancelled"
11597
11679
  });
11598
- sendResult(id, toShellTaskInfo2(task));
11680
+ sendResult(id, toShellTaskInfo(task));
11599
11681
  } catch (error) {
11600
11682
  sendTaskError(id, error);
11601
11683
  }
@@ -11678,7 +11760,7 @@ var createSkillsHandlers = ({
11678
11760
  var import_node_path17 = __toESM(require("path"), 1);
11679
11761
  var import_protocol8 = require("@codelia/protocol");
11680
11762
  var import_storage12 = require("@codelia/storage");
11681
- var DEFAULT_TRUNCATED3 = {
11763
+ var DEFAULT_TRUNCATED2 = {
11682
11764
  stdout: false,
11683
11765
  stderr: false,
11684
11766
  combined: false
@@ -11784,7 +11866,7 @@ var toTaskInfo = (task) => ({
11784
11866
  ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
11785
11867
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11786
11868
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
11787
- ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED3 },
11869
+ ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED2 },
11788
11870
  ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
11789
11871
  ...task.result?.artifacts ? { artifacts: task.result.artifacts } : {}
11790
11872
  });
@@ -12705,7 +12787,9 @@ var startRuntime = () => {
12705
12787
  `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
12706
12788
  );
12707
12789
  for (const error of result.errors) {
12708
- (0, import_logger.log)(`tasks.shutdown error task_id=${error.task_id}: ${error.error}`);
12790
+ (0, import_logger.log)(
12791
+ `tasks.shutdown error task_id=${error.task_id}: ${error.error}`
12792
+ );
12709
12793
  }
12710
12794
  }
12711
12795
  })();