@codelia/runtime 0.1.47 → 0.1.49

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 +644 -452
  2. package/dist/index.js +646 -458
  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);
@@ -4991,8 +5014,78 @@ ${truncatedLinesSummary}`;
4991
5014
  }
4992
5015
  if (firstClippedLineNumber !== null) {
4993
5016
  output += `
4994
-
4995
- For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
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})`;
5066
+ }
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})`;
5072
+ }
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) {
5084
+ output += `
5085
+
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,21 +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("Shell command to execute in the current workspace."),
5988
- 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.`),
5989
- timeout: import_zod10.z.number().int().positive().optional().describe(
5990
- `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 running until completion, cancel, or runtime exit.`
6098
+ var shellRunSchema = import_zod11.z.object({
6099
+ command: import_zod11.z.string().describe(
6100
+ "Shell command to execute as a runtime-managed child process in the current workspace."
5991
6101
  ),
5992
- background: import_zod10.z.boolean().optional().describe(
5993
- "Return immediately with task info instead of waiting. Manage the task with shell_status/logs/wait/result/cancel. Default: false."
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(
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.`
6107
+ ),
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."
5994
6110
  )
5995
6111
  }).superRefine((input, ctx) => {
5996
6112
  if (input.timeout === void 0) {
@@ -5999,7 +6115,7 @@ var shellRunSchema = import_zod10.z.object({
5999
6115
  if (input.background ?? false) {
6000
6116
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6001
6117
  ctx.addIssue({
6002
- code: import_zod10.z.ZodIssueCode.custom,
6118
+ code: import_zod11.z.ZodIssueCode.custom,
6003
6119
  path: ["timeout"],
6004
6120
  message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6005
6121
  });
@@ -6008,27 +6124,34 @@ var shellRunSchema = import_zod10.z.object({
6008
6124
  }
6009
6125
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6010
6126
  ctx.addIssue({
6011
- code: import_zod10.z.ZodIssueCode.custom,
6127
+ code: import_zod11.z.ZodIssueCode.custom,
6012
6128
  path: ["timeout"],
6013
6129
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6014
6130
  });
6015
6131
  }
6016
6132
  });
6017
- var shellTaskKeySchema = import_zod10.z.object({
6018
- 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.")
6135
+ });
6136
+ var shellWaitSchema = shellTaskKeySchema.extend({
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.`
6139
+ )
6019
6140
  });
6020
- var shellStreamSchema = import_zod10.z.enum(["stdout", "stderr"]);
6021
- var shellListSchema = import_zod10.z.object({
6022
- 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(
6023
6144
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6024
6145
  ),
6025
6146
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6026
- 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.")
6027
6148
  });
6028
- var shellLogsSchema = import_zod10.z.object({
6029
- 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."),
6030
6151
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6031
- 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
+ )
6032
6155
  });
6033
6156
  var formatTaskError = (error) => {
6034
6157
  if (error instanceof TaskManagerError) {
@@ -6047,7 +6170,10 @@ var resolveShellTimeoutSeconds = (value, background) => {
6047
6170
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6048
6171
  }
6049
6172
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
6050
- 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
+ );
6051
6177
  };
6052
6178
  var formatShellTimeoutForLog = (value) => value === void 0 ? "none" : String(value);
6053
6179
  var normalizeShellTaskKey = (value) => {
@@ -6074,7 +6200,10 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6074
6200
  (await tasks.list()).filter((task) => task.kind === "shell" && typeof task.key === "string").map((task) => task.key)
6075
6201
  );
6076
6202
  for (const length of [8, 12, compactIdValue.length]) {
6077
- const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
6203
+ const suffix = compactIdValue.slice(
6204
+ 0,
6205
+ Math.min(length, compactIdValue.length)
6206
+ );
6078
6207
  if (!suffix) continue;
6079
6208
  const candidate2 = `${base}-${suffix}`;
6080
6209
  if (!usedKeys.has(candidate2)) return candidate2;
@@ -6087,62 +6216,69 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6087
6216
  }
6088
6217
  return candidate;
6089
6218
  };
6090
- var buildShellTaskHints = (taskKey, state) => ({
6091
- status: { key: taskKey },
6092
- logs: { key: taskKey },
6093
- wait: { key: taskKey },
6094
- result: { key: taskKey },
6095
- ...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 } : {}
6096
6248
  });
6097
- var toJsonValue = (value) => {
6098
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
6099
- 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;
6100
6259
  }
6101
- if (Array.isArray(value)) {
6102
- 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;
6265
+ }
6266
+ if (task.cancellation_reason) {
6267
+ payload.cancellation_reason = task.cancellation_reason;
6103
6268
  }
6104
- if (value && typeof value === "object") {
6105
- const objectValue = {};
6106
- for (const [key, entry] of Object.entries(value)) {
6107
- objectValue[key] = toJsonValue(entry);
6269
+ const output = pickShellOutput(task);
6270
+ if (output) {
6271
+ payload[output.field] = output.content;
6272
+ if (output.cacheId) {
6273
+ payload.cache_id = output.cacheId;
6108
6274
  }
6109
- return objectValue;
6110
6275
  }
6111
- return String(value);
6276
+ return payload;
6112
6277
  };
6113
- var toShellTaskSummary = (task) => ({
6114
- task_id: task.task_id,
6115
- key: getShellTaskKey(task),
6116
- ...task.label ? { label: task.label } : {},
6117
- state: task.state,
6118
- ...task.title ? { title: task.title } : {},
6119
- ...task.working_directory ? { working_directory: task.working_directory } : {},
6120
- created_at: task.created_at,
6121
- updated_at: task.updated_at,
6122
- ...task.started_at ? { started_at: task.started_at } : {},
6123
- ...task.ended_at ? { ended_at: task.ended_at } : {},
6124
- exit_code: task.result?.exit_code ?? null,
6125
- duration_ms: task.result?.duration_ms ?? null,
6126
- result_available: isTerminalTaskState(task.state) && !!task.result,
6127
- ...task.failure_message ? { failure_message: task.failure_message } : {},
6278
+ var shellCancelPayload = (task) => ({
6279
+ ...shellBasePayload(task),
6128
6280
  ...task.cancellation_reason ? { cancellation_reason: task.cancellation_reason } : {},
6129
- ...task.cleanup_reason ? { cleanup_reason: task.cleanup_reason } : {}
6130
- });
6131
- var toShellTaskInfo = (task) => ({
6132
- ...toShellTaskSummary(task),
6133
- kind: task.kind,
6134
- workspace_mode: task.workspace_mode,
6135
- ...task.result?.child_session_id ?? task.child_session_id ? { child_session_id: task.result?.child_session_id ?? task.child_session_id } : {},
6136
- signal: task.result?.signal ?? null,
6137
- ...task.result?.summary ? { summary: task.result.summary } : {},
6138
- ...task.result?.stdout !== void 0 ? { stdout: task.result.stdout } : {},
6139
- ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
6140
- ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
6141
- ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
6142
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
6143
- ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
6144
- ...task.result?.artifacts ? { artifacts: toJsonValue(task.result.artifacts) } : {},
6145
- next_actions: buildShellTaskHints(getShellTaskKey(task), task.state)
6281
+ ...task.failure_message ? { failure_message: task.failure_message } : {}
6146
6282
  });
6147
6283
  var toShellListEntry = (task) => ({
6148
6284
  key: getShellTaskKey(task),
@@ -6175,7 +6311,10 @@ var resolveShellTask = async (tasks, input) => {
6175
6311
  const refs = matches.map((task) => task.task_id).join(", ");
6176
6312
  throw new Error(`multiple shell tasks matched key "${key}": ${refs}`);
6177
6313
  }
6178
- 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
+ );
6179
6318
  };
6180
6319
  var tailContentByLines = (content, tailLines) => {
6181
6320
  if (content.length === 0) {
@@ -6198,7 +6337,10 @@ var tailContentByLines = (content, tailLines) => {
6198
6337
  };
6199
6338
  var resolveShellLogs = async (options) => {
6200
6339
  const taskKey = getShellTaskKey(options.task);
6201
- 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
+ );
6202
6344
  if (live !== null) {
6203
6345
  if (options.tailLines !== void 0) {
6204
6346
  const tailed = tailContentByLines(live, options.tailLines);
@@ -6317,11 +6459,57 @@ var waitForManagedTask = async (tasks, taskId, signal) => {
6317
6459
  throw error;
6318
6460
  }
6319
6461
  };
6462
+ var resolveShellWaitTimeoutSeconds = (value) => Math.max(
6463
+ 1,
6464
+ Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS)
6465
+ );
6466
+ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6467
+ let timeoutHandle;
6468
+ const waitPromise = waitForManagedTask(tasks, taskId, options.signal).then(
6469
+ (result) => ({
6470
+ type: "task",
6471
+ result
6472
+ })
6473
+ );
6474
+ const timeoutPromise = new Promise((resolve) => {
6475
+ timeoutHandle = setTimeout(
6476
+ () => resolve({ type: "timeout" }),
6477
+ options.waitTimeoutSeconds * 1e3
6478
+ );
6479
+ });
6480
+ try {
6481
+ const outcome = await Promise.race([waitPromise, timeoutPromise]);
6482
+ if (outcome.type === "task") {
6483
+ return {
6484
+ task: outcome.result.task,
6485
+ aborted: outcome.result.aborted,
6486
+ stillRunning: false
6487
+ };
6488
+ }
6489
+ const task = await requireTask(tasks, taskId);
6490
+ if (isTerminalTaskState(task.state)) {
6491
+ return {
6492
+ task,
6493
+ aborted: false,
6494
+ stillRunning: false
6495
+ };
6496
+ }
6497
+ return {
6498
+ task,
6499
+ aborted: false,
6500
+ stillRunning: true
6501
+ };
6502
+ } finally {
6503
+ if (timeoutHandle) {
6504
+ clearTimeout(timeoutHandle);
6505
+ }
6506
+ }
6507
+ };
6320
6508
  var createShellTool = (sandboxKey, options = {}) => {
6321
6509
  const shared = getSharedDeps(options);
6322
- return (0, import_core11.defineTool)({
6510
+ return (0, import_core12.defineTool)({
6323
6511
  name: "shell",
6324
- description: "Run a shell command in the sandbox. By default wait for completion; with `background=true`, return a task 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.",
6325
6513
  input: shellRunSchema,
6326
6514
  execute: async (input, ctx) => {
6327
6515
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6332,7 +6520,10 @@ var createShellTool = (sandboxKey, options = {}) => {
6332
6520
  }
6333
6521
  const label = normalizeOptionalLabel(input.label);
6334
6522
  const background = input.background ?? false;
6335
- const timeoutSeconds = resolveShellTimeoutSeconds(input.timeout, background);
6523
+ const timeoutSeconds = resolveShellTimeoutSeconds(
6524
+ input.timeout,
6525
+ background
6526
+ );
6336
6527
  const commandSummary = summarizeCommand(command);
6337
6528
  (0, import_logger.debugLog)(
6338
6529
  `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
@@ -6361,19 +6552,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6361
6552
  })
6362
6553
  );
6363
6554
  if (background) {
6364
- return {
6365
- background: true,
6366
- task: toShellTaskInfo(task)
6367
- };
6555
+ return shellStatusPayload(task, { background: true });
6368
6556
  }
6369
- 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
+ );
6370
6562
  (0, import_logger.debugLog)(
6371
6563
  `shell.done task_id=${task.task_id} state=${settled.state} duration_ms=${settled.result?.duration_ms ?? -1}`
6372
6564
  );
6373
- return {
6374
- background: false,
6375
- task: toShellTaskInfo(settled)
6376
- };
6565
+ return shellTerminalPayload(settled);
6377
6566
  } catch (error) {
6378
6567
  throw formatTaskError(error);
6379
6568
  }
@@ -6382,7 +6571,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6382
6571
  };
6383
6572
  var createShellListTool = (options = {}) => {
6384
6573
  const shared = getSharedDeps(options);
6385
- return (0, import_core11.defineTool)({
6574
+ return (0, import_core12.defineTool)({
6386
6575
  name: "shell_list",
6387
6576
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6388
6577
  input: shellListSchema,
@@ -6413,14 +6602,14 @@ var createShellListTool = (options = {}) => {
6413
6602
  };
6414
6603
  var createShellStatusTool = (options = {}) => {
6415
6604
  const shared = getSharedDeps(options);
6416
- return (0, import_core11.defineTool)({
6605
+ return (0, import_core12.defineTool)({
6417
6606
  name: "shell_status",
6418
- 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.",
6419
6608
  input: shellTaskKeySchema,
6420
6609
  execute: async (input) => {
6421
6610
  try {
6422
6611
  const task = await resolveShellTask(shared.tasks, input);
6423
- return { task: toShellTaskInfo(task) };
6612
+ return shellStatusPayload(task);
6424
6613
  } catch (error) {
6425
6614
  throw formatTaskError(error);
6426
6615
  }
@@ -6429,7 +6618,7 @@ var createShellStatusTool = (options = {}) => {
6429
6618
  };
6430
6619
  var createShellLogsTool = (options = {}) => {
6431
6620
  const shared = getSharedDeps(options);
6432
- return (0, import_core11.defineTool)({
6621
+ return (0, import_core12.defineTool)({
6433
6622
  name: "shell_logs",
6434
6623
  description: "Read recent stdout or stderr for a running or finished shell task.",
6435
6624
  input: shellLogsSchema,
@@ -6451,22 +6640,31 @@ var createShellLogsTool = (options = {}) => {
6451
6640
  };
6452
6641
  var createShellWaitTool = (options = {}) => {
6453
6642
  const shared = getSharedDeps(options);
6454
- return (0, import_core11.defineTool)({
6643
+ return (0, import_core12.defineTool)({
6455
6644
  name: "shell_wait",
6456
- description: "Wait for a shell task to reach a terminal state and return its retained outcome.",
6457
- input: shellTaskKeySchema,
6645
+ description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6646
+ input: shellWaitSchema,
6458
6647
  execute: async (input, ctx) => {
6459
6648
  try {
6460
- const task = await resolveShellTask(shared.tasks, input);
6461
- const result = await waitForManagedTask(
6649
+ const waitInput = input;
6650
+ const task = await resolveShellTask(shared.tasks, waitInput);
6651
+ const result = await waitForManagedTaskWindow(
6462
6652
  shared.tasks,
6463
6653
  task.task_id,
6464
- ctx.signal
6654
+ {
6655
+ waitTimeoutSeconds: resolveShellWaitTimeoutSeconds(
6656
+ waitInput.wait_timeout
6657
+ ),
6658
+ signal: ctx.signal
6659
+ }
6465
6660
  );
6466
- return {
6467
- ...result.aborted ? { aborted: true } : {},
6468
- task: toShellTaskInfo(result.task)
6469
- };
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);
6470
6668
  } catch (error) {
6471
6669
  throw formatTaskError(error);
6472
6670
  }
@@ -6475,14 +6673,14 @@ var createShellWaitTool = (options = {}) => {
6475
6673
  };
6476
6674
  var createShellResultTool = (options = {}) => {
6477
6675
  const shared = getSharedDeps(options);
6478
- return (0, import_core11.defineTool)({
6676
+ return (0, import_core12.defineTool)({
6479
6677
  name: "shell_result",
6480
- description: "Read the retained terminal result for a shell task.",
6678
+ description: "Read the retained terminal result for a shell task as compact JSON.",
6481
6679
  input: shellTaskKeySchema,
6482
6680
  execute: async (input) => {
6483
6681
  try {
6484
6682
  const task = await resolveShellTask(shared.tasks, input);
6485
- return { task: toShellTaskInfo(task) };
6683
+ return isTerminalTaskState(task.state) ? shellTerminalPayload(task) : shellStatusPayload(task);
6486
6684
  } catch (error) {
6487
6685
  throw formatTaskError(error);
6488
6686
  }
@@ -6491,9 +6689,9 @@ var createShellResultTool = (options = {}) => {
6491
6689
  };
6492
6690
  var createShellCancelTool = (options = {}) => {
6493
6691
  const shared = getSharedDeps(options);
6494
- return (0, import_core11.defineTool)({
6692
+ return (0, import_core12.defineTool)({
6495
6693
  name: "shell_cancel",
6496
- 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.",
6497
6695
  input: shellTaskKeySchema,
6498
6696
  execute: async (input) => {
6499
6697
  try {
@@ -6501,7 +6699,7 @@ var createShellCancelTool = (options = {}) => {
6501
6699
  const cancelled = await shared.tasks.cancel(task.task_id, {
6502
6700
  reason: "cancelled"
6503
6701
  });
6504
- return { task: toShellTaskInfo(cancelled) };
6702
+ return shellCancelPayload(cancelled);
6505
6703
  } catch (error) {
6506
6704
  throw formatTaskError(error);
6507
6705
  }
@@ -6510,16 +6708,16 @@ var createShellCancelTool = (options = {}) => {
6510
6708
  };
6511
6709
 
6512
6710
  // src/tools/skill-load.ts
6513
- var import_core12 = require("@codelia/core");
6514
- var import_zod11 = require("zod");
6515
- var SkillLoadInputSchema = import_zod11.z.object({
6516
- name: import_zod11.z.string().min(1).optional().describe("Exact skill name to load."),
6517
- 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.")
6518
6716
  }).refine((value) => !!value.name || !!value.path, {
6519
6717
  message: "name or path is required",
6520
6718
  path: ["name"]
6521
6719
  });
6522
- var createSkillLoadTool = (skillsResolverKey) => (0, import_core12.defineTool)({
6720
+ var createSkillLoadTool = (skillsResolverKey) => (0, import_core13.defineTool)({
6523
6721
  name: "skill_load",
6524
6722
  description: "Load full SKILL.md content by exact name or path.",
6525
6723
  input: SkillLoadInputSchema,
@@ -6565,15 +6763,15 @@ var createSkillLoadTool = (skillsResolverKey) => (0, import_core12.defineTool)({
6565
6763
  });
6566
6764
 
6567
6765
  // src/tools/skill-search.ts
6568
- var import_core13 = require("@codelia/core");
6569
- var import_zod12 = require("zod");
6570
- 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)({
6571
6769
  name: "skill_search",
6572
6770
  description: "Search installed local skills by name, description, or path.",
6573
- input: import_zod12.z.object({
6574
- query: import_zod12.z.string().min(1).describe("Search query text."),
6575
- limit: import_zod12.z.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6576
- 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.")
6577
6775
  }),
6578
6776
  execute: async (input, ctx) => {
6579
6777
  try {
@@ -6596,8 +6794,8 @@ var createSkillSearchTool = (skillsResolverKey) => (0, import_core13.defineTool)
6596
6794
  });
6597
6795
 
6598
6796
  // src/tools/todo-mutate.ts
6599
- var import_core14 = require("@codelia/core");
6600
- var import_zod13 = require("zod");
6797
+ var import_core15 = require("@codelia/core");
6798
+ var import_zod14 = require("zod");
6601
6799
 
6602
6800
  // src/tools/todo-store.ts
6603
6801
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6707,37 +6905,37 @@ var pickNextTodo = (todos) => {
6707
6905
  var todoStore = /* @__PURE__ */ new Map();
6708
6906
 
6709
6907
  // src/tools/todo-mutate.ts
6710
- var todoStatusSchema = import_zod13.z.enum(["pending", "in_progress", "completed"]);
6711
- var todoPrioritySchema = import_zod13.z.number().int().min(1).max(5);
6712
- var todoItemSchema = import_zod13.z.object({
6713
- id: import_zod13.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6714
- 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."),
6715
6913
  status: todoStatusSchema.describe("Todo status."),
6716
6914
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6717
- notes: import_zod13.z.string().optional().describe("Optional implementation notes."),
6718
- 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.")
6719
6917
  });
6720
- var todoPatchItemSchema = import_zod13.z.object({
6721
- id: import_zod13.z.string().min(1).describe("Target todo ID."),
6722
- remove: import_zod13.z.boolean().optional().describe("Set true to remove the todo item."),
6723
- 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)."),
6724
6922
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6725
6923
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6726
- notes: import_zod13.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6727
- 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(
6728
6926
  "Updated in-progress phrasing (null keeps current, empty clears)."
6729
6927
  )
6730
6928
  });
6731
- var todoNewInputSchema = import_zod13.z.object({
6732
- 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.")
6733
6931
  }).strict();
6734
- var todoAppendInputSchema = import_zod13.z.object({
6735
- 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.")
6736
6934
  }).strict();
6737
- var todoPatchInputSchema = import_zod13.z.object({
6738
- 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.")
6739
6937
  }).strict();
6740
- var todoClearInputSchema = import_zod13.z.object({}).strict();
6938
+ var todoClearInputSchema = import_zod14.z.object({}).strict();
6741
6939
  var statusSymbol = {
6742
6940
  pending: "[ ]",
6743
6941
  in_progress: "[>]",
@@ -6832,7 +7030,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6832
7030
  }
6833
7031
  return formatSuccess(outputMode, nextTodos);
6834
7032
  };
6835
- 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)({
6836
7034
  name,
6837
7035
  description,
6838
7036
  input,
@@ -6849,11 +7047,7 @@ var createTodoNewTool = (sandboxKey, sessionContextKey) => createTodoMutationToo
6849
7047
  "todo_new",
6850
7048
  "Start or replace the in-session todo plan with a full task list.",
6851
7049
  todoNewInputSchema,
6852
- (sessionId, input) => applyTodoMutation(
6853
- sessionId,
6854
- { mode: "new", todos: input.todos },
6855
- "new"
6856
- ),
7050
+ (sessionId, input) => applyTodoMutation(sessionId, { mode: "new", todos: input.todos }, "new"),
6857
7051
  sandboxKey,
6858
7052
  sessionContextKey
6859
7053
  );
@@ -6891,17 +7085,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6891
7085
  );
6892
7086
 
6893
7087
  // src/tools/todo-read.ts
6894
- var import_core15 = require("@codelia/core");
6895
- var import_zod14 = require("zod");
7088
+ var import_core16 = require("@codelia/core");
7089
+ var import_zod15 = require("zod");
6896
7090
  var statusSymbol2 = {
6897
7091
  pending: "[ ]",
6898
7092
  in_progress: "[>]",
6899
7093
  completed: "[x]"
6900
7094
  };
6901
- var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
7095
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.defineTool)({
6902
7096
  name: "todo_read",
6903
7097
  description: "Read the in-session todo plan with execution order and next step.",
6904
- input: import_zod14.z.object({}),
7098
+ input: import_zod15.z.object({}),
6905
7099
  execute: async (_input, ctx) => {
6906
7100
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6907
7101
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -6937,15 +7131,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core15.de
6937
7131
  });
6938
7132
 
6939
7133
  // src/tools/tool-output-cache.ts
6940
- var import_core16 = require("@codelia/core");
6941
- var import_zod15 = require("zod");
6942
- 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)({
6943
7137
  name: "tool_output_cache",
6944
7138
  description: "Read cached tool output by ref_id.",
6945
- input: import_zod15.z.object({
6946
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
6947
- offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
6948
- 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.")
6949
7143
  }),
6950
7144
  execute: async (input) => {
6951
7145
  if (!store.read) {
@@ -6961,14 +7155,14 @@ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
6961
7155
  }
6962
7156
  }
6963
7157
  });
6964
- var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
7158
+ var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
6965
7159
  name: "tool_output_cache_line",
6966
7160
  description: "Read a single cached output line segment by line number and char offset.",
6967
- input: import_zod15.z.object({
6968
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
6969
- line_number: import_zod15.z.number().int().positive().describe("1-based line number to read."),
6970
- char_offset: import_zod15.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
6971
- 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.")
6972
7166
  }),
6973
7167
  execute: async (input) => {
6974
7168
  if (!store.readLine) {
@@ -6985,16 +7179,16 @@ var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
6985
7179
  }
6986
7180
  }
6987
7181
  });
6988
- var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7182
+ var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
6989
7183
  name: "tool_output_cache_grep",
6990
7184
  description: "Search cached tool output by ref_id.",
6991
- input: import_zod15.z.object({
6992
- ref_id: import_zod15.z.string().describe("Tool output reference ID."),
6993
- pattern: import_zod15.z.string().describe("Text or regex pattern to search for."),
6994
- regex: import_zod15.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
6995
- before: import_zod15.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
6996
- after: import_zod15.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
6997
- 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.")
6998
7192
  }),
6999
7193
  execute: async (input) => {
7000
7194
  if (!store.grep) {
@@ -7014,74 +7208,6 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7014
7208
  }
7015
7209
  });
7016
7210
 
7017
- // src/tools/read-line.ts
7018
- var import_node_fs14 = require("fs");
7019
- var import_core17 = require("@codelia/core");
7020
- var import_zod16 = require("zod");
7021
- var DEFAULT_CHAR_LIMIT = 1e4;
7022
- var MAX_CHAR_LIMIT = 1e5;
7023
- var createReadLineTool = (sandboxKey) => (0, import_core17.defineTool)({
7024
- name: "read_line",
7025
- description: "Read a single line segment by 1-based line number and 0-based char offset.",
7026
- input: import_zod16.z.object({
7027
- file_path: import_zod16.z.string().describe("File path under the sandbox root."),
7028
- line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
7029
- char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7030
- char_limit: import_zod16.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
7031
- }),
7032
- execute: async (input, ctx) => {
7033
- let resolved;
7034
- try {
7035
- const sandbox = await getSandboxContext(ctx, sandboxKey);
7036
- resolved = sandbox.resolvePath(input.file_path);
7037
- } catch (error) {
7038
- return `Security error: ${String(error)}`;
7039
- }
7040
- try {
7041
- const stat = await import_node_fs14.promises.stat(resolved);
7042
- if (stat.isDirectory()) {
7043
- return `Path is a directory: ${input.file_path}`;
7044
- }
7045
- } catch {
7046
- return `File not found: ${input.file_path}`;
7047
- }
7048
- try {
7049
- const content = await import_node_fs14.promises.readFile(resolved, "utf8");
7050
- const lines = content.split(/\r?\n/);
7051
- const lineIndex = input.line_number - 1;
7052
- if (lineIndex >= lines.length) {
7053
- return `Line number out of range: ${input.line_number} (total ${lines.length})`;
7054
- }
7055
- const line = lines[lineIndex] ?? "";
7056
- const charOffset = input.char_offset ?? 0;
7057
- const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
7058
- if (charOffset > line.length) {
7059
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
7060
- }
7061
- const segment = line.slice(charOffset, charOffset + charLimit);
7062
- const endOffset = charOffset + segment.length;
7063
- const hasMore = endOffset < line.length;
7064
- const header = [
7065
- `line_number=${input.line_number}`,
7066
- `line_length=${line.length}`,
7067
- `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
7068
- ].join(" ");
7069
- let output = `${header}
7070
- ${segment}`;
7071
- if (hasMore) {
7072
- output += `
7073
-
7074
- Use char_offset=${endOffset} to continue.`;
7075
- output += `
7076
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
7077
- }
7078
- return output;
7079
- } catch (error) {
7080
- return `Error reading file: ${String(error)}`;
7081
- }
7082
- }
7083
- });
7084
-
7085
7211
  // src/tools/write.ts
7086
7212
  var import_node_fs15 = require("fs");
7087
7213
  var import_node_path13 = __toESM(require("path"), 1);
@@ -7100,7 +7226,9 @@ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
7100
7226
  name: "write",
7101
7227
  description: "Write text to a file, creating parent directories if needed.",
7102
7228
  input: import_zod17.z.object({
7103
- 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
+ ),
7104
7232
  content: import_zod17.z.string().describe("UTF-8 text content to write.")
7105
7233
  }),
7106
7234
  execute: async (input, ctx) => {
@@ -7109,7 +7237,7 @@ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
7109
7237
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7110
7238
  resolved = sandbox.resolvePath(input.file_path);
7111
7239
  } catch (error) {
7112
- return `Security error: ${String(error)}`;
7240
+ throw new Error(`Security error: ${String(error)}`);
7113
7241
  }
7114
7242
  try {
7115
7243
  await import_node_fs15.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
@@ -7604,9 +7732,21 @@ var createAgentFactory = (state, options = {}) => {
7604
7732
  if (state.agent) return state.agent;
7605
7733
  if (inFlight) return inFlight;
7606
7734
  inFlight = (async () => {
7607
- const rootDir = process.env.CODELIA_SANDBOX_ROOT;
7608
- const ctx = await SandboxContext.create(rootDir);
7609
- (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
+ );
7610
7750
  const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
7611
7751
  state.agentsResolver = agentsResolver;
7612
7752
  let skillsConfig;
@@ -7681,13 +7821,6 @@ var createAgentFactory = (state, options = {}) => {
7681
7821
  const message = error instanceof Error ? error.message : String(error);
7682
7822
  throw new Error(message);
7683
7823
  }
7684
- const approvalModeResolution = await resolveApprovalModeForRuntime({
7685
- workingDir: ctx.workingDir,
7686
- runtimeSandboxRoot: state.runtimeSandboxRoot,
7687
- requestStartupSelection: async ({ projectKey }) => {
7688
- return requestApprovalModeStartupSelection(state, projectKey);
7689
- }
7690
- });
7691
7824
  const permissionService = new PermissionService({
7692
7825
  approvalMode: approvalModeResolution.approvalMode,
7693
7826
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
@@ -8022,6 +8155,9 @@ var createAgentFactory = (state, options = {}) => {
8022
8155
  return { decision: "allow" };
8023
8156
  }
8024
8157
  });
8158
+ if (approvalModeResolution.persistSelection) {
8159
+ await approvalModeResolution.persistSelection();
8160
+ }
8025
8161
  state.agent = agent;
8026
8162
  return agent;
8027
8163
  })();
@@ -10956,7 +11092,7 @@ var import_node_path15 = __toESM(require("path"), 1);
10956
11092
  var import_protocol6 = require("@codelia/protocol");
10957
11093
  var import_storage11 = require("@codelia/storage");
10958
11094
  var COMMAND_PREVIEW_CHARS = 400;
10959
- var DEFAULT_TRUNCATED2 = {
11095
+ var DEFAULT_TRUNCATED = {
10960
11096
  stdout: false,
10961
11097
  stderr: false,
10962
11098
  combined: false
@@ -11094,12 +11230,12 @@ var toShellExecResult = (commandPreview, result) => ({
11094
11230
  signal: result?.signal ?? null,
11095
11231
  stdout: result?.stdout ?? "",
11096
11232
  stderr: result?.stderr ?? "",
11097
- truncated: result?.truncated ?? DEFAULT_TRUNCATED2,
11233
+ truncated: result?.truncated ?? DEFAULT_TRUNCATED,
11098
11234
  duration_ms: result?.duration_ms ?? 0,
11099
11235
  ...result?.stdout_cache_id ? { stdout_cache_id: result.stdout_cache_id } : {},
11100
11236
  ...result?.stderr_cache_id ? { stderr_cache_id: result.stderr_cache_id } : {}
11101
11237
  });
11102
- var toShellTaskInfo2 = (task) => ({
11238
+ var toShellTaskInfo = (task) => ({
11103
11239
  task_id: task.task_id,
11104
11240
  state: task.state,
11105
11241
  command_preview: task.title,
@@ -11112,7 +11248,7 @@ var toShellTaskInfo2 = (task) => ({
11112
11248
  signal: task.result?.signal ?? null,
11113
11249
  stdout: task.result?.stdout ?? "",
11114
11250
  stderr: task.result?.stderr ?? "",
11115
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED2,
11251
+ truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
11116
11252
  duration_ms: task.result?.duration_ms ?? null,
11117
11253
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11118
11254
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
@@ -11158,7 +11294,10 @@ var sendTaskError = (id, error) => {
11158
11294
  var requireShellTask = async (taskManager, taskId) => {
11159
11295
  const task = await taskManager.status(taskId);
11160
11296
  if (!task || task.kind !== "shell") {
11161
- 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
+ );
11162
11301
  }
11163
11302
  return task;
11164
11303
  };
@@ -11190,6 +11329,28 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11190
11329
  }
11191
11330
  return background ? void 0 : DEFAULT_TIMEOUT_SECONDS;
11192
11331
  };
11332
+ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11333
+ if (requestedTimeout !== void 0) {
11334
+ if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11335
+ return {
11336
+ error: {
11337
+ code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
11338
+ message: "wait_timeout_seconds must be a positive number"
11339
+ }
11340
+ };
11341
+ }
11342
+ if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
11343
+ return {
11344
+ error: {
11345
+ code: import_protocol6.RPC_ERROR_CODE.INVALID_PARAMS,
11346
+ message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
11347
+ }
11348
+ };
11349
+ }
11350
+ return Math.max(1, Math.trunc(requestedTimeout));
11351
+ }
11352
+ return DEFAULT_TIMEOUT_SECONDS;
11353
+ };
11193
11354
  var formatShellTimeoutForLog2 = (value) => value === void 0 ? "none" : String(value);
11194
11355
  var parseShellStartRequest = (state, params, options) => {
11195
11356
  const command = params?.command?.trim() ?? "";
@@ -11294,7 +11455,7 @@ var createShellHandlers = ({
11294
11455
  const handleShellStart = async (id, params) => {
11295
11456
  try {
11296
11457
  const { task } = await spawnShell(params, "shell.start");
11297
- sendResult(id, toShellTaskInfo2(task));
11458
+ sendResult(id, toShellTaskInfo(task));
11298
11459
  } catch (error) {
11299
11460
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
11300
11461
  sendError(id, error);
@@ -11314,7 +11475,7 @@ var createShellHandlers = ({
11314
11475
  }
11315
11476
  try {
11316
11477
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
11317
- 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);
11318
11479
  const result = { tasks };
11319
11480
  sendResult(id, result);
11320
11481
  } catch (error) {
@@ -11332,7 +11493,7 @@ var createShellHandlers = ({
11332
11493
  }
11333
11494
  try {
11334
11495
  const task = await requireShellTask(shellTaskManager, taskId);
11335
- sendResult(id, toShellTaskInfo2(task));
11496
+ sendResult(id, toShellTaskInfo(task));
11336
11497
  } catch (error) {
11337
11498
  sendTaskError(id, error);
11338
11499
  }
@@ -11395,17 +11556,31 @@ var createShellHandlers = ({
11395
11556
  });
11396
11557
  return;
11397
11558
  }
11559
+ const waitTimeoutSeconds = resolveShellWaitTimeoutSeconds2(
11560
+ params?.wait_timeout_seconds
11561
+ );
11562
+ if (typeof waitTimeoutSeconds === "object") {
11563
+ sendError(id, waitTimeoutSeconds.error);
11564
+ return;
11565
+ }
11398
11566
  try {
11399
11567
  const existing = await requireShellTask(shellTaskManager, taskId);
11400
11568
  if (isTerminalTaskState(existing.state)) {
11401
- sendResult(id, toShellTaskInfo2(existing));
11569
+ sendResult(id, toShellTaskInfo(existing));
11402
11570
  return;
11403
11571
  }
11404
11572
  const controller = new AbortController();
11573
+ let timeoutHandle;
11405
11574
  let resolveDetached;
11406
- const detachPromise = new Promise(
11575
+ const detachPromise = new Promise((resolve) => {
11576
+ resolveDetached = (result) => resolve({ type: "detached", result });
11577
+ });
11578
+ const timeoutPromise = new Promise(
11407
11579
  (resolve) => {
11408
- resolveDetached = (result) => resolve({ type: "detached", result });
11580
+ timeoutHandle = setTimeout(() => {
11581
+ controller.abort();
11582
+ resolve({ type: "still_running" });
11583
+ }, waitTimeoutSeconds * 1e3);
11409
11584
  }
11410
11585
  );
11411
11586
  const unregister = registerActiveShellWait(taskId, {
@@ -11425,16 +11600,31 @@ var createShellHandlers = ({
11425
11600
  }
11426
11601
  throw error;
11427
11602
  });
11428
- const outcome = await Promise.race([waitPromise, detachPromise]);
11603
+ const outcome = await Promise.race([
11604
+ waitPromise,
11605
+ detachPromise,
11606
+ timeoutPromise
11607
+ ]);
11429
11608
  if (outcome.type === "detached") {
11430
11609
  sendResult(id, outcome.result);
11431
11610
  return;
11432
11611
  }
11612
+ if (outcome.type === "still_running") {
11613
+ const task = await requireShellTask(shellTaskManager, taskId);
11614
+ sendResult(id, {
11615
+ ...toShellTaskInfo(task),
11616
+ ...isTerminalTaskState(task.state) ? {} : { still_running: true }
11617
+ });
11618
+ return;
11619
+ }
11433
11620
  if (outcome.type === "aborted") {
11434
11621
  return;
11435
11622
  }
11436
- sendResult(id, toShellTaskInfo2(outcome.task));
11623
+ sendResult(id, toShellTaskInfo(outcome.task));
11437
11624
  } finally {
11625
+ if (timeoutHandle) {
11626
+ clearTimeout(timeoutHandle);
11627
+ }
11438
11628
  unregister();
11439
11629
  }
11440
11630
  } catch (error) {
@@ -11487,7 +11677,7 @@ var createShellHandlers = ({
11487
11677
  const task = await shellTaskManager.cancel(taskId, {
11488
11678
  reason: "cancelled"
11489
11679
  });
11490
- sendResult(id, toShellTaskInfo2(task));
11680
+ sendResult(id, toShellTaskInfo(task));
11491
11681
  } catch (error) {
11492
11682
  sendTaskError(id, error);
11493
11683
  }
@@ -11570,7 +11760,7 @@ var createSkillsHandlers = ({
11570
11760
  var import_node_path17 = __toESM(require("path"), 1);
11571
11761
  var import_protocol8 = require("@codelia/protocol");
11572
11762
  var import_storage12 = require("@codelia/storage");
11573
- var DEFAULT_TRUNCATED3 = {
11763
+ var DEFAULT_TRUNCATED2 = {
11574
11764
  stdout: false,
11575
11765
  stderr: false,
11576
11766
  combined: false
@@ -11676,7 +11866,7 @@ var toTaskInfo = (task) => ({
11676
11866
  ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
11677
11867
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11678
11868
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
11679
- ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED3 },
11869
+ ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED2 },
11680
11870
  ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
11681
11871
  ...task.result?.artifacts ? { artifacts: task.result.artifacts } : {}
11682
11872
  });
@@ -12597,7 +12787,9 @@ var startRuntime = () => {
12597
12787
  `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
12598
12788
  );
12599
12789
  for (const error of result.errors) {
12600
- (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
+ );
12601
12793
  }
12602
12794
  }
12603
12795
  })();