@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.js CHANGED
@@ -382,12 +382,6 @@ var appendInitialAgentsContext = (systemPrompt, agentsContext) => {
382
382
  ${agentsContext}`;
383
383
  };
384
384
 
385
- // src/auth/openai-oauth.ts
386
- import { spawn } from "child_process";
387
-
388
- // src/logger.ts
389
- import { debugLog, isDebugEnabled, log } from "@codelia/logger";
390
-
391
385
  // src/auth/oauth-utils.ts
392
386
  import { createServer } from "http";
393
387
  import * as oauth from "oauth4webapi";
@@ -582,6 +576,12 @@ var startOAuthCallbackServer = (options) => {
582
576
  };
583
577
  };
584
578
 
579
+ // src/auth/openai-oauth.ts
580
+ import { spawn } from "child_process";
581
+
582
+ // src/logger.ts
583
+ import { debugLog, isDebugEnabled, log } from "@codelia/logger";
584
+
585
585
  // src/auth/openai-oauth.ts
586
586
  var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
587
587
  var ISSUER = "https://auth.openai.com";
@@ -1008,135 +1008,6 @@ Working directory: ${workingDir}`;
1008
1008
  }
1009
1009
  };
1010
1010
 
1011
- // src/auth/openai-device-code.ts
1012
- var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
1013
- var ISSUER2 = "https://auth.openai.com";
1014
- var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
1015
- var DEFAULT_INTERVAL_SECONDS = 5;
1016
- var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
1017
- var deviceCodeTimeoutMs = () => readPositiveIntEnv(
1018
- "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
1019
- DEFAULT_TIMEOUT_MS
1020
- );
1021
- var sleep = (ms) => new Promise((resolve) => {
1022
- setTimeout(resolve, ms);
1023
- });
1024
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1025
- var parseIntervalSeconds = (value) => {
1026
- if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1027
- return Math.trunc(value);
1028
- }
1029
- if (typeof value === "string") {
1030
- const parsed = Number.parseInt(value.trim(), 10);
1031
- if (Number.isFinite(parsed) && parsed >= 0) {
1032
- return parsed;
1033
- }
1034
- }
1035
- return DEFAULT_INTERVAL_SECONDS;
1036
- };
1037
- var readResponseSnippet = async (response) => {
1038
- const text = await response.text().catch(() => "");
1039
- return text ? text.slice(0, 500) : "(empty)";
1040
- };
1041
- var requestDeviceCodeStart = async () => {
1042
- const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/usercode`, {
1043
- method: "POST",
1044
- headers: {
1045
- "Content-Type": "application/json",
1046
- Accept: "application/json"
1047
- },
1048
- body: JSON.stringify({ client_id: clientId2() })
1049
- });
1050
- if (!response.ok) {
1051
- if (response.status === 404) {
1052
- throw new Error("OpenAI device code login is not enabled for this client");
1053
- }
1054
- throw new Error(
1055
- `OpenAI device code request failed (${response.status}): ${await readResponseSnippet(response)}`
1056
- );
1057
- }
1058
- const payload = await response.json();
1059
- if (!isRecord(payload) || typeof payload.device_auth_id !== "string") {
1060
- throw new Error("OpenAI device code response is missing device_auth_id");
1061
- }
1062
- const userCode = typeof payload.user_code === "string" && payload.user_code.trim() || typeof payload.usercode === "string" && payload.usercode.trim() || null;
1063
- if (!userCode) {
1064
- throw new Error("OpenAI device code response is missing user_code");
1065
- }
1066
- return {
1067
- deviceAuthId: payload.device_auth_id,
1068
- userCode,
1069
- intervalSeconds: parseIntervalSeconds(payload.interval)
1070
- };
1071
- };
1072
- var pollDeviceCodeAuthorization = async (deviceAuthId, userCode, intervalSeconds) => {
1073
- const deadline = Date.now() + deviceCodeTimeoutMs();
1074
- while (Date.now() < deadline) {
1075
- const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/token`, {
1076
- method: "POST",
1077
- headers: {
1078
- "Content-Type": "application/json",
1079
- Accept: "application/json"
1080
- },
1081
- body: JSON.stringify({
1082
- device_auth_id: deviceAuthId,
1083
- user_code: userCode
1084
- })
1085
- });
1086
- if (response.ok) {
1087
- const payload = await response.json();
1088
- if (!isRecord(payload) || typeof payload.authorization_code !== "string" || typeof payload.code_challenge !== "string" || typeof payload.code_verifier !== "string") {
1089
- throw new Error(
1090
- "OpenAI device code token response is missing authorization_code/PKCE fields"
1091
- );
1092
- }
1093
- return {
1094
- authorization_code: payload.authorization_code,
1095
- code_challenge: payload.code_challenge,
1096
- code_verifier: payload.code_verifier
1097
- };
1098
- }
1099
- if (response.status !== 403 && response.status !== 404) {
1100
- throw new Error(
1101
- `OpenAI device code polling failed (${response.status}): ${await readResponseSnippet(response)}`
1102
- );
1103
- }
1104
- const now = Date.now();
1105
- if (now >= deadline) {
1106
- break;
1107
- }
1108
- const waitMs = Math.max(
1109
- 0,
1110
- Math.min(intervalSeconds * 1e3, deadline - now)
1111
- );
1112
- await sleep(waitMs);
1113
- }
1114
- throw new Error("OpenAI device code login timed out after 15 minutes");
1115
- };
1116
- var createOpenAiDeviceCodeSession = async () => {
1117
- const start = await requestDeviceCodeStart();
1118
- return {
1119
- verificationUrl: `${ISSUER2}/codex/device`,
1120
- userCode: start.userCode,
1121
- complete: async () => {
1122
- const authCode = await pollDeviceCodeAuthorization(
1123
- start.deviceAuthId,
1124
- start.userCode,
1125
- start.intervalSeconds
1126
- );
1127
- const pkce = {
1128
- challenge: authCode.code_challenge,
1129
- verifier: authCode.code_verifier
1130
- };
1131
- return exchangeCodeForTokens(
1132
- authCode.authorization_code,
1133
- `${ISSUER2}/deviceauth/callback`,
1134
- pkce
1135
- );
1136
- }
1137
- };
1138
- };
1139
-
1140
1011
  // src/rpc/transport.ts
1141
1012
  var describeRpcMessage = (msg) => {
1142
1013
  if ("method" in msg && typeof msg.method === "string") {
@@ -1288,6 +1159,137 @@ var requestUiPick = async (state, params) => {
1288
1159
  return requestUi(state, "ui.pick.request", params);
1289
1160
  };
1290
1161
 
1162
+ // src/auth/openai-device-code.ts
1163
+ var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
1164
+ var ISSUER2 = "https://auth.openai.com";
1165
+ var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
1166
+ var DEFAULT_INTERVAL_SECONDS = 5;
1167
+ var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
1168
+ var deviceCodeTimeoutMs = () => readPositiveIntEnv(
1169
+ "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
1170
+ DEFAULT_TIMEOUT_MS
1171
+ );
1172
+ var sleep = (ms) => new Promise((resolve) => {
1173
+ setTimeout(resolve, ms);
1174
+ });
1175
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1176
+ var parseIntervalSeconds = (value) => {
1177
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
1178
+ return Math.trunc(value);
1179
+ }
1180
+ if (typeof value === "string") {
1181
+ const parsed = Number.parseInt(value.trim(), 10);
1182
+ if (Number.isFinite(parsed) && parsed >= 0) {
1183
+ return parsed;
1184
+ }
1185
+ }
1186
+ return DEFAULT_INTERVAL_SECONDS;
1187
+ };
1188
+ var readResponseSnippet = async (response) => {
1189
+ const text = await response.text().catch(() => "");
1190
+ return text ? text.slice(0, 500) : "(empty)";
1191
+ };
1192
+ var requestDeviceCodeStart = async () => {
1193
+ const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/usercode`, {
1194
+ method: "POST",
1195
+ headers: {
1196
+ "Content-Type": "application/json",
1197
+ Accept: "application/json"
1198
+ },
1199
+ body: JSON.stringify({ client_id: clientId2() })
1200
+ });
1201
+ if (!response.ok) {
1202
+ if (response.status === 404) {
1203
+ throw new Error(
1204
+ "OpenAI device code login is not enabled for this client"
1205
+ );
1206
+ }
1207
+ throw new Error(
1208
+ `OpenAI device code request failed (${response.status}): ${await readResponseSnippet(response)}`
1209
+ );
1210
+ }
1211
+ const payload = await response.json();
1212
+ if (!isRecord(payload) || typeof payload.device_auth_id !== "string") {
1213
+ throw new Error("OpenAI device code response is missing device_auth_id");
1214
+ }
1215
+ const userCode = typeof payload.user_code === "string" && payload.user_code.trim() || typeof payload.usercode === "string" && payload.usercode.trim() || null;
1216
+ if (!userCode) {
1217
+ throw new Error("OpenAI device code response is missing user_code");
1218
+ }
1219
+ return {
1220
+ deviceAuthId: payload.device_auth_id,
1221
+ userCode,
1222
+ intervalSeconds: parseIntervalSeconds(payload.interval)
1223
+ };
1224
+ };
1225
+ var pollDeviceCodeAuthorization = async (deviceAuthId, userCode, intervalSeconds) => {
1226
+ const deadline = Date.now() + deviceCodeTimeoutMs();
1227
+ while (Date.now() < deadline) {
1228
+ const response = await fetch(`${ISSUER2}/api/accounts/deviceauth/token`, {
1229
+ method: "POST",
1230
+ headers: {
1231
+ "Content-Type": "application/json",
1232
+ Accept: "application/json"
1233
+ },
1234
+ body: JSON.stringify({
1235
+ device_auth_id: deviceAuthId,
1236
+ user_code: userCode
1237
+ })
1238
+ });
1239
+ if (response.ok) {
1240
+ const payload = await response.json();
1241
+ if (!isRecord(payload) || typeof payload.authorization_code !== "string" || typeof payload.code_challenge !== "string" || typeof payload.code_verifier !== "string") {
1242
+ throw new Error(
1243
+ "OpenAI device code token response is missing authorization_code/PKCE fields"
1244
+ );
1245
+ }
1246
+ return {
1247
+ authorization_code: payload.authorization_code,
1248
+ code_challenge: payload.code_challenge,
1249
+ code_verifier: payload.code_verifier
1250
+ };
1251
+ }
1252
+ if (response.status !== 403 && response.status !== 404) {
1253
+ throw new Error(
1254
+ `OpenAI device code polling failed (${response.status}): ${await readResponseSnippet(response)}`
1255
+ );
1256
+ }
1257
+ const now = Date.now();
1258
+ if (now >= deadline) {
1259
+ break;
1260
+ }
1261
+ const waitMs = Math.max(
1262
+ 0,
1263
+ Math.min(intervalSeconds * 1e3, deadline - now)
1264
+ );
1265
+ await sleep(waitMs);
1266
+ }
1267
+ throw new Error("OpenAI device code login timed out after 15 minutes");
1268
+ };
1269
+ var createOpenAiDeviceCodeSession = async () => {
1270
+ const start = await requestDeviceCodeStart();
1271
+ return {
1272
+ verificationUrl: `${ISSUER2}/codex/device`,
1273
+ userCode: start.userCode,
1274
+ complete: async () => {
1275
+ const authCode = await pollDeviceCodeAuthorization(
1276
+ start.deviceAuthId,
1277
+ start.userCode,
1278
+ start.intervalSeconds
1279
+ );
1280
+ const pkce = {
1281
+ challenge: authCode.code_challenge,
1282
+ verifier: authCode.code_verifier
1283
+ };
1284
+ return exchangeCodeForTokens(
1285
+ authCode.authorization_code,
1286
+ `${ISSUER2}/deviceauth/callback`,
1287
+ pkce
1288
+ );
1289
+ }
1290
+ };
1291
+ };
1292
+
1291
1293
  // src/auth/store.ts
1292
1294
  import { promises as fs3 } from "fs";
1293
1295
  import { ensureStorageDirs, resolveStoragePaths } from "@codelia/storage";
@@ -2032,9 +2034,9 @@ var resolveAnthropicMaxTokens = ({
2032
2034
  import {
2033
2035
  applyModelMetadata,
2034
2036
  DEFAULT_MODEL_REGISTRY,
2037
+ registerModels,
2035
2038
  resolveModel,
2036
- resolveProviderModelId,
2037
- registerModels
2039
+ resolveProviderModelId
2038
2040
  } from "@codelia/core";
2039
2041
  import { ModelMetadataServiceImpl } from "@codelia/model-metadata";
2040
2042
  import { StoragePathServiceImpl as StoragePathServiceImpl2 } from "@codelia/storage";
@@ -2294,16 +2296,22 @@ var resolveApprovalModeForRuntime = async (options, deps = {}) => {
2294
2296
  if (options.requestStartupSelection) {
2295
2297
  const selected = await options.requestStartupSelection({ projectKey });
2296
2298
  if (selected) {
2297
- await persistProjectApprovalModeOrThrow(
2298
- store,
2299
- projectKey,
2300
- selected,
2301
- loadedPolicy
2302
- );
2299
+ const persistSelection = async () => {
2300
+ await persistProjectApprovalModeOrThrow(
2301
+ store,
2302
+ projectKey,
2303
+ selected,
2304
+ loadedPolicy
2305
+ );
2306
+ };
2307
+ if (!options.deferStartupSelectionPersist) {
2308
+ await persistSelection();
2309
+ }
2303
2310
  return {
2304
2311
  approvalMode: selected,
2305
2312
  source: "startup-selection",
2306
- projectKey
2313
+ projectKey,
2314
+ ...options.deferStartupSelectionPersist ? { persistSelection } : {}
2307
2315
  };
2308
2316
  }
2309
2317
  }
@@ -2707,7 +2715,11 @@ var SYSTEM_SHELL_ALLOWLIST = [
2707
2715
  "git ls-files",
2708
2716
  "git grep"
2709
2717
  ];
2710
- var SYSTEM_SHELL_ALLOWLIST_TRUSTED = [...SYSTEM_SHELL_ALLOWLIST, "sed", "awk"];
2718
+ var SYSTEM_SHELL_ALLOWLIST_TRUSTED = [
2719
+ ...SYSTEM_SHELL_ALLOWLIST,
2720
+ "sed",
2721
+ "awk"
2722
+ ];
2711
2723
  var buildSystemPermissions = (approvalMode = "minimal") => ({
2712
2724
  allow: [
2713
2725
  ...(approvalMode === "trusted" ? SYSTEM_TOOL_ALLOWLIST_TRUSTED : SYSTEM_TOOL_ALLOWLIST_MINIMAL).map((tool) => ({ tool })),
@@ -2977,23 +2989,29 @@ var SandboxContext = class _SandboxContext {
2977
2989
  rootDir;
2978
2990
  workingDir;
2979
2991
  sessionId;
2992
+ approvalMode;
2980
2993
  constructor(init) {
2981
2994
  this.rootDir = init.rootDir;
2982
2995
  this.workingDir = init.workingDir;
2983
2996
  this.sessionId = init.sessionId;
2997
+ this.approvalMode = init.approvalMode;
2984
2998
  }
2985
- static async create(rootDir) {
2999
+ static async create(rootDir, options = {}) {
2986
3000
  const sessionId = crypto.randomUUID().slice(0, 8);
2987
3001
  const root = rootDir ? path6.resolve(rootDir) : process.cwd();
2988
3002
  await fs5.mkdir(root, { recursive: true });
2989
3003
  return new _SandboxContext({
2990
3004
  rootDir: root,
2991
3005
  workingDir: root,
2992
- sessionId
3006
+ sessionId,
3007
+ approvalMode: options.approvalMode ?? "minimal"
2993
3008
  });
2994
3009
  }
2995
3010
  resolvePath(targetPath) {
2996
3011
  const resolved = path6.isAbsolute(targetPath) ? path6.resolve(targetPath) : path6.resolve(this.workingDir, targetPath);
3012
+ if (this.approvalMode === "full-access") {
3013
+ return resolved;
3014
+ }
2997
3015
  const relative = path6.relative(this.rootDir, resolved);
2998
3016
  if (relative === "" || !relative.startsWith("..") && !path6.isAbsolute(relative)) {
2999
3017
  return resolved;
@@ -3636,7 +3654,7 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool({
3636
3654
  const sandbox = await getSandboxContext(ctx, sandboxKey);
3637
3655
  resolvedPath = sandbox.resolvePath(input.path);
3638
3656
  } catch (error) {
3639
- return `Security error: ${String(error)}`;
3657
+ throw new Error(`Security error: ${String(error)}`);
3640
3658
  }
3641
3659
  try {
3642
3660
  const resolver = await getAgentsResolver(ctx, agentsResolverKey);
@@ -3842,7 +3860,9 @@ var createEditTool = (sandboxKey) => defineTool3({
3842
3860
  name: "edit",
3843
3861
  description: "Edit a file by replacing old_string with new_string.",
3844
3862
  input: z4.object({
3845
- file_path: z4.string().describe("File path under the sandbox root."),
3863
+ file_path: z4.string().describe(
3864
+ "File path. Sandbox-bounded unless full-access mode is active."
3865
+ ),
3846
3866
  old_string: z4.string().describe(
3847
3867
  "Text to find. Use empty string to replace the whole file content."
3848
3868
  ),
@@ -3999,11 +4019,11 @@ var walkFiles = async (startDir, visitor) => {
3999
4019
  }
4000
4020
  }
4001
4021
  };
4002
- var globMatch = async (searchDir, rootDir, pattern) => {
4022
+ var globMatch = async (searchDir, pattern) => {
4003
4023
  const regex = globToRegExp2(pattern.replaceAll("\\", "/"));
4004
4024
  const matches = [];
4005
4025
  await walkFiles(searchDir, async (filePath) => {
4006
- const relPath = path9.relative(rootDir, filePath).replaceAll("\\", "/");
4026
+ const relPath = path9.relative(searchDir, filePath).replaceAll("\\", "/");
4007
4027
  if (regex.test(relPath)) {
4008
4028
  matches.push(relPath);
4009
4029
  }
@@ -4024,13 +4044,11 @@ var createGlobSearchTool = (sandboxKey) => defineTool4({
4024
4044
  }),
4025
4045
  execute: async (input, ctx) => {
4026
4046
  let searchDir;
4027
- let rootDir;
4028
4047
  try {
4029
4048
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4030
- rootDir = sandbox.rootDir;
4031
4049
  searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4032
4050
  } catch (error) {
4033
- return `Security error: ${String(error)}`;
4051
+ throw new Error(`Security error: ${String(error)}`);
4034
4052
  }
4035
4053
  try {
4036
4054
  const stat = await fs9.stat(searchDir);
@@ -4040,7 +4058,7 @@ var createGlobSearchTool = (sandboxKey) => defineTool4({
4040
4058
  } catch (error) {
4041
4059
  return `Error: ${String(error)}`;
4042
4060
  }
4043
- const matches = await globMatch(searchDir, rootDir, input.pattern);
4061
+ const matches = await globMatch(searchDir, input.pattern);
4044
4062
  if (!matches.length) {
4045
4063
  return `No files match pattern: ${input.pattern}`;
4046
4064
  }
@@ -4074,7 +4092,7 @@ var createGrepTool = (sandboxKey) => defineTool5({
4074
4092
  searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4075
4093
  pathLabel = input.path ?? searchDir;
4076
4094
  } catch (error) {
4077
- return `Security error: ${String(error)}`;
4095
+ throw new Error(`Security error: ${String(error)}`);
4078
4096
  }
4079
4097
  let regex;
4080
4098
  try {
@@ -4864,7 +4882,10 @@ var MAX_LINE_LENGTH = parsePositiveIntEnv(
4864
4882
  "CODELIA_READ_MAX_LINE_LENGTH",
4865
4883
  DEFAULT_MAX_LINE_LENGTH
4866
4884
  );
4867
- var MAX_BYTES = parsePositiveIntEnv("CODELIA_READ_MAX_BYTES", DEFAULT_MAX_BYTES);
4885
+ var MAX_BYTES = parsePositiveIntEnv(
4886
+ "CODELIA_READ_MAX_BYTES",
4887
+ DEFAULT_MAX_BYTES
4888
+ );
4868
4889
  var clipLongLine = (line) => {
4869
4890
  if (line.length <= MAX_LINE_LENGTH) {
4870
4891
  return line;
@@ -4904,7 +4925,9 @@ var createReadTool = (sandboxKey) => defineTool7({
4904
4925
  name: "read",
4905
4926
  description: "Read a text file with optional 0-based line offset and line limit.",
4906
4927
  input: z8.object({
4907
- file_path: z8.string().describe("File path under the sandbox root."),
4928
+ file_path: z8.string().describe(
4929
+ "File path. Sandbox-bounded unless full-access mode is active."
4930
+ ),
4908
4931
  offset: z8.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4909
4932
  limit: z8.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4910
4933
  }),
@@ -4914,7 +4937,7 @@ var createReadTool = (sandboxKey) => defineTool7({
4914
4937
  const sandbox = await getSandboxContext(ctx, sandboxKey);
4915
4938
  resolved = sandbox.resolvePath(input.file_path);
4916
4939
  } catch (error) {
4917
- return `Security error: ${String(error)}`;
4940
+ throw new Error(`Security error: ${String(error)}`);
4918
4941
  }
4919
4942
  try {
4920
4943
  const stat = await fs13.stat(resolved);
@@ -5003,9 +5026,79 @@ For full long-line content, use read_line({"file_path":"${input.file_path}","lin
5003
5026
  }
5004
5027
  });
5005
5028
 
5029
+ // src/tools/read-line.ts
5030
+ import { promises as fs14 } from "fs";
5031
+ import { defineTool as defineTool8 } from "@codelia/core";
5032
+ import { z as z9 } from "zod";
5033
+ var DEFAULT_CHAR_LIMIT = 1e4;
5034
+ var MAX_CHAR_LIMIT = 1e5;
5035
+ var createReadLineTool = (sandboxKey) => defineTool8({
5036
+ name: "read_line",
5037
+ description: "Read a single line segment by 1-based line number and 0-based char offset.",
5038
+ input: z9.object({
5039
+ file_path: z9.string().describe(
5040
+ "File path. Sandbox-bounded unless full-access mode is active."
5041
+ ),
5042
+ line_number: z9.number().int().positive().describe("1-based line number to read."),
5043
+ char_offset: z9.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5044
+ char_limit: z9.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5045
+ }),
5046
+ execute: async (input, ctx) => {
5047
+ let resolved;
5048
+ try {
5049
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
5050
+ resolved = sandbox.resolvePath(input.file_path);
5051
+ } catch (error) {
5052
+ throw new Error(`Security error: ${String(error)}`);
5053
+ }
5054
+ try {
5055
+ const stat = await fs14.stat(resolved);
5056
+ if (stat.isDirectory()) {
5057
+ return `Path is a directory: ${input.file_path}`;
5058
+ }
5059
+ } catch {
5060
+ return `File not found: ${input.file_path}`;
5061
+ }
5062
+ try {
5063
+ const content = await fs14.readFile(resolved, "utf8");
5064
+ const lines = content.split(/\r?\n/);
5065
+ const lineIndex = input.line_number - 1;
5066
+ if (lineIndex >= lines.length) {
5067
+ return `Line number out of range: ${input.line_number} (total ${lines.length})`;
5068
+ }
5069
+ const line = lines[lineIndex] ?? "";
5070
+ const charOffset = input.char_offset ?? 0;
5071
+ const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5072
+ if (charOffset > line.length) {
5073
+ return `char_offset out of range: ${charOffset} (line length ${line.length})`;
5074
+ }
5075
+ const segment = line.slice(charOffset, charOffset + charLimit);
5076
+ const endOffset = charOffset + segment.length;
5077
+ const hasMore = endOffset < line.length;
5078
+ const header = [
5079
+ `line_number=${input.line_number}`,
5080
+ `line_length=${line.length}`,
5081
+ `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5082
+ ].join(" ");
5083
+ let output = `${header}
5084
+ ${segment}`;
5085
+ if (hasMore) {
5086
+ output += `
5087
+
5088
+ Use char_offset=${endOffset} to continue.`;
5089
+ output += `
5090
+ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5091
+ }
5092
+ return output;
5093
+ } catch (error) {
5094
+ return `Error reading file: ${String(error)}`;
5095
+ }
5096
+ }
5097
+ });
5098
+
5006
5099
  // src/tools/search.ts
5007
- import { defineTool as defineTool8 } from "@codelia/core";
5008
- import { z as z9 } from "zod";
5100
+ import { defineTool as defineTool9 } from "@codelia/core";
5101
+ import { z as z10 } from "zod";
5009
5102
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
5010
5103
  var shouldKeepUrl = (url, allowedDomains) => {
5011
5104
  if (!allowedDomains.length) return true;
@@ -5121,14 +5214,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
5121
5214
  const parsed = parseBrave(payload);
5122
5215
  return normalizeEntries(parsed, allowedDomains, maxResults);
5123
5216
  };
5124
- var createSearchTool = (options) => defineTool8({
5217
+ var createSearchTool = (options) => defineTool9({
5125
5218
  name: "search",
5126
5219
  description: "Search the web and return concise source candidates.",
5127
- input: z9.object({
5128
- query: z9.string().min(1).describe("Search query."),
5129
- max_results: z9.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5130
- backend: z9.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5131
- allowed_domains: z9.array(z9.string().min(1)).optional().describe("Optional allowlist of domains.")
5220
+ input: z10.object({
5221
+ query: z10.string().min(1).describe("Search query."),
5222
+ max_results: z10.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5223
+ backend: z10.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5224
+ allowed_domains: z10.array(z10.string().min(1)).optional().describe("Optional allowlist of domains.")
5132
5225
  }),
5133
5226
  execute: async (input) => {
5134
5227
  const backend = input.backend ?? options.defaultBackend;
@@ -5164,11 +5257,9 @@ var createSearchTool = (options) => defineTool8({
5164
5257
 
5165
5258
  // src/tools/shell.ts
5166
5259
  import crypto6 from "crypto";
5167
- import { defineTool as defineTool9 } from "@codelia/core";
5168
- import {
5169
- ToolOutputCacheStoreImpl
5170
- } from "@codelia/storage";
5171
- import { z as z10 } from "zod";
5260
+ import { defineTool as defineTool10 } from "@codelia/core";
5261
+ import { ToolOutputCacheStoreImpl } from "@codelia/storage";
5262
+ import { z as z11 } from "zod";
5172
5263
 
5173
5264
  // src/tasks/manager.ts
5174
5265
  import crypto5 from "crypto";
@@ -5294,7 +5385,10 @@ var TaskManager = class {
5294
5385
  return this.enqueueMutation(async () => {
5295
5386
  const current = await this.registry.get(taskId);
5296
5387
  if (!current) {
5297
- throw new TaskManagerError("task_not_found", `Task not found: ${taskId}`);
5388
+ throw new TaskManagerError(
5389
+ "task_not_found",
5390
+ `Task not found: ${taskId}`
5391
+ );
5298
5392
  }
5299
5393
  const next = updater(current);
5300
5394
  await this.registry.upsert(next);
@@ -5375,7 +5469,9 @@ var TaskManager = class {
5375
5469
  return task;
5376
5470
  }
5377
5471
  if (task.owner_runtime_id !== this.runtimeId) {
5378
- const ownerAlive = await this.processController.isProcessAlive(task.owner_pid);
5472
+ const ownerAlive = await this.processController.isProcessAlive(
5473
+ task.owner_pid
5474
+ );
5379
5475
  if (ownerAlive) {
5380
5476
  return task;
5381
5477
  }
@@ -5391,7 +5487,9 @@ var TaskManager = class {
5391
5487
  return task;
5392
5488
  }
5393
5489
  if (typeof task.executor_pid === "number") {
5394
- const executorAlive = await this.processController.isProcessAlive(task.executor_pid);
5490
+ const executorAlive = await this.processController.isProcessAlive(
5491
+ task.executor_pid
5492
+ );
5395
5493
  if (executorAlive) {
5396
5494
  return task;
5397
5495
  }
@@ -5413,7 +5511,10 @@ var TaskManager = class {
5413
5511
  async terminatePersistedTask(task, signal) {
5414
5512
  if (typeof task.executor_pgid === "number") {
5415
5513
  try {
5416
- await this.processController.terminateProcessGroup(task.executor_pgid, signal);
5514
+ await this.processController.terminateProcessGroup(
5515
+ task.executor_pgid,
5516
+ signal
5517
+ );
5417
5518
  } catch (error) {
5418
5519
  if (!isErrnoCode(error, "ESRCH")) {
5419
5520
  throw error;
@@ -5423,7 +5524,10 @@ var TaskManager = class {
5423
5524
  }
5424
5525
  if (typeof task.executor_pid === "number") {
5425
5526
  try {
5426
- await this.processController.terminateProcess(task.executor_pid, signal);
5527
+ await this.processController.terminateProcess(
5528
+ task.executor_pid,
5529
+ signal
5530
+ );
5427
5531
  } catch (error) {
5428
5532
  if (!isErrnoCode(error, "ESRCH")) {
5429
5533
  throw error;
@@ -5435,12 +5539,16 @@ var TaskManager = class {
5435
5539
  if (typeof task.executor_pid !== "number") {
5436
5540
  return;
5437
5541
  }
5438
- const alive = await this.processController.isProcessAlive(task.executor_pid);
5542
+ const alive = await this.processController.isProcessAlive(
5543
+ task.executor_pid
5544
+ );
5439
5545
  if (!alive) {
5440
5546
  return;
5441
5547
  }
5442
5548
  await this.sleep(this.gracePeriodMs);
5443
- const stillAlive = await this.processController.isProcessAlive(task.executor_pid);
5549
+ const stillAlive = await this.processController.isProcessAlive(
5550
+ task.executor_pid
5551
+ );
5444
5552
  if (!stillAlive) {
5445
5553
  return;
5446
5554
  }
@@ -5575,7 +5683,9 @@ var TaskManager = class {
5575
5683
  if (isTerminalTaskState(task.state)) {
5576
5684
  continue;
5577
5685
  }
5578
- const ownerAlive = await this.processController.isProcessAlive(task.owner_pid);
5686
+ const ownerAlive = await this.processController.isProcessAlive(
5687
+ task.owner_pid
5688
+ );
5579
5689
  if (ownerAlive) {
5580
5690
  continue;
5581
5691
  }
@@ -5637,9 +5747,7 @@ var TaskManager = class {
5637
5747
  };
5638
5748
 
5639
5749
  // src/tasks/shell-executor.ts
5640
- import {
5641
- spawn as spawn4
5642
- } from "child_process";
5750
+ import { spawn as spawn4 } from "child_process";
5643
5751
 
5644
5752
  // src/tools/bash-utils.ts
5645
5753
  import { spawn as spawn3 } from "child_process";
@@ -5647,7 +5755,9 @@ var DEBUG_MAX_COMMAND_CHARS = 200;
5647
5755
  var DEFAULT_TIMEOUT_SECONDS = 120;
5648
5756
  var MAX_TIMEOUT_SECONDS = 300;
5649
5757
  var MAX_TIMER_DELAY_MS = 2147483647;
5650
- var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(MAX_TIMER_DELAY_MS / 1e3);
5758
+ var MAX_EXECUTION_TIMEOUT_SECONDS = Math.floor(
5759
+ MAX_TIMER_DELAY_MS / 1e3
5760
+ );
5651
5761
  var MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
5652
5762
  var summarizeCommand = (command) => {
5653
5763
  const normalized = command.trim().replace(/\s+/g, " ");
@@ -5912,7 +6022,10 @@ var startShellTask = (options) => {
5912
6022
  cancelRequested = false;
5913
6023
  terminateChild(child, "SIGTERM");
5914
6024
  scheduleForceKill();
5915
- fail(`Command timed out after ${Math.trunc(timeoutSeconds)}s`, "SIGTERM");
6025
+ fail(
6026
+ `Command timed out after ${Math.trunc(timeoutSeconds)}s`,
6027
+ "SIGTERM"
6028
+ );
5916
6029
  }, timeoutSeconds * 1e3);
5917
6030
  }
5918
6031
  });
@@ -5940,11 +6053,6 @@ var createToolSessionContextKey = (getSessionId) => ({
5940
6053
  var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
5941
6054
 
5942
6055
  // src/tools/shell.ts
5943
- var DEFAULT_TRUNCATED = {
5944
- stdout: false,
5945
- stderr: false,
5946
- combined: false
5947
- };
5948
6056
  var LIVE_LOG_TAIL_BYTES = 64 * 1024;
5949
6057
  var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
5950
6058
  var truncateUtf8Suffix2 = (value, maxBytes) => {
@@ -5984,21 +6092,25 @@ var SHELL_LABEL_MAX_CHARS = 80;
5984
6092
  var SHELL_LIST_DEFAULT_LIMIT = 20;
5985
6093
  var SHELL_LIST_MAX_LIMIT = 100;
5986
6094
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
5987
- var shellStateSchema = z10.enum([
6095
+ var shellStateSchema = z11.enum([
5988
6096
  "queued",
5989
6097
  "running",
5990
6098
  "completed",
5991
6099
  "failed",
5992
6100
  "cancelled"
5993
6101
  ]);
5994
- var shellRunSchema = z10.object({
5995
- command: z10.string().describe("Shell command to execute in the current workspace."),
5996
- label: z10.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.`),
5997
- timeout: z10.number().int().positive().optional().describe(
5998
- `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.`
6102
+ var shellRunSchema = z11.object({
6103
+ command: z11.string().describe(
6104
+ "Shell command to execute as a runtime-managed child process in the current workspace."
5999
6105
  ),
6000
- background: z10.boolean().optional().describe(
6001
- "Return immediately with task info instead of waiting. Manage the task with shell_status/logs/wait/result/cancel. Default: false."
6106
+ label: z11.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6107
+ `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
6108
+ ),
6109
+ timeout: z11.number().int().positive().optional().describe(
6110
+ `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.`
6111
+ ),
6112
+ background: z11.boolean().optional().describe(
6113
+ "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."
6002
6114
  )
6003
6115
  }).superRefine((input, ctx) => {
6004
6116
  if (input.timeout === void 0) {
@@ -6007,7 +6119,7 @@ var shellRunSchema = z10.object({
6007
6119
  if (input.background ?? false) {
6008
6120
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6009
6121
  ctx.addIssue({
6010
- code: z10.ZodIssueCode.custom,
6122
+ code: z11.ZodIssueCode.custom,
6011
6123
  path: ["timeout"],
6012
6124
  message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6013
6125
  });
@@ -6016,27 +6128,34 @@ var shellRunSchema = z10.object({
6016
6128
  }
6017
6129
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6018
6130
  ctx.addIssue({
6019
- code: z10.ZodIssueCode.custom,
6131
+ code: z11.ZodIssueCode.custom,
6020
6132
  path: ["timeout"],
6021
6133
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6022
6134
  });
6023
6135
  }
6024
6136
  });
6025
- var shellTaskKeySchema = z10.object({
6026
- key: z10.string().describe("Canonical shell task key returned by shell or shell_list.")
6137
+ var shellTaskKeySchema = z11.object({
6138
+ key: z11.string().describe("Canonical shell task key returned by shell or shell_list.")
6139
+ });
6140
+ var shellWaitSchema = shellTaskKeySchema.extend({
6141
+ wait_timeout: z11.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6142
+ `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.`
6143
+ )
6027
6144
  });
6028
- var shellStreamSchema = z10.enum(["stdout", "stderr"]);
6029
- var shellListSchema = z10.object({
6030
- limit: z10.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6145
+ var shellStreamSchema = z11.enum(["stdout", "stderr"]);
6146
+ var shellListSchema = z11.object({
6147
+ limit: z11.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6031
6148
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6032
6149
  ),
6033
6150
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6034
- include_terminal: z10.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6151
+ include_terminal: z11.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6035
6152
  });
6036
- var shellLogsSchema = z10.object({
6037
- key: z10.string().describe("Canonical shell task key returned by shell or shell_list."),
6153
+ var shellLogsSchema = z11.object({
6154
+ key: z11.string().describe("Canonical shell task key returned by shell or shell_list."),
6038
6155
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6039
- tail_lines: z10.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(`Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`)
6156
+ tail_lines: z11.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6157
+ `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
6158
+ )
6040
6159
  });
6041
6160
  var formatTaskError = (error) => {
6042
6161
  if (error instanceof TaskManagerError) {
@@ -6055,7 +6174,10 @@ var resolveShellTimeoutSeconds = (value, background) => {
6055
6174
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6056
6175
  }
6057
6176
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
6058
- return Math.max(1, Math.min(Math.trunc(requestedTimeout), MAX_TIMEOUT_SECONDS));
6177
+ return Math.max(
6178
+ 1,
6179
+ Math.min(Math.trunc(requestedTimeout), MAX_TIMEOUT_SECONDS)
6180
+ );
6059
6181
  };
6060
6182
  var formatShellTimeoutForLog = (value) => value === void 0 ? "none" : String(value);
6061
6183
  var normalizeShellTaskKey = (value) => {
@@ -6082,7 +6204,10 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6082
6204
  (await tasks.list()).filter((task) => task.kind === "shell" && typeof task.key === "string").map((task) => task.key)
6083
6205
  );
6084
6206
  for (const length of [8, 12, compactIdValue.length]) {
6085
- const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
6207
+ const suffix = compactIdValue.slice(
6208
+ 0,
6209
+ Math.min(length, compactIdValue.length)
6210
+ );
6086
6211
  if (!suffix) continue;
6087
6212
  const candidate2 = `${base}-${suffix}`;
6088
6213
  if (!usedKeys.has(candidate2)) return candidate2;
@@ -6095,62 +6220,69 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6095
6220
  }
6096
6221
  return candidate;
6097
6222
  };
6098
- var buildShellTaskHints = (taskKey, state) => ({
6099
- status: { key: taskKey },
6100
- logs: { key: taskKey },
6101
- wait: { key: taskKey },
6102
- result: { key: taskKey },
6103
- ...isTerminalTaskState(state) ? {} : { cancel: { key: taskKey } }
6223
+ var trimNonEmpty = (value) => {
6224
+ if (value === void 0 || value === null) return null;
6225
+ const trimmed = value.trimEnd();
6226
+ return trimmed.trim().length > 0 ? trimmed : null;
6227
+ };
6228
+ var pickShellOutput = (task) => {
6229
+ const stdout = trimNonEmpty(task.result?.stdout);
6230
+ const stderr = trimNonEmpty(task.result?.stderr);
6231
+ const exitCode = task.result?.exit_code;
6232
+ const preferError = task.state === "failed" || task.state === "cancelled" || exitCode !== null && exitCode !== void 0 && exitCode !== 0;
6233
+ const primaryStream = preferError ? "stderr" : "stdout";
6234
+ const primaryContent = primaryStream === "stderr" ? stderr : stdout;
6235
+ const secondaryContent = primaryStream === "stderr" ? stdout : stderr;
6236
+ const selectedStream = primaryContent ? primaryStream : secondaryContent ? primaryStream === "stderr" ? "stdout" : "stderr" : null;
6237
+ if (!selectedStream) {
6238
+ return null;
6239
+ }
6240
+ const field = preferError ? "error_output" : "output";
6241
+ const cacheId = selectedStream === "stderr" ? task.result?.stderr_cache_id : task.result?.stdout_cache_id;
6242
+ return {
6243
+ field,
6244
+ content: selectedStream === "stderr" ? stderr ?? "" : stdout ?? "",
6245
+ ...cacheId ? { cacheId } : {}
6246
+ };
6247
+ };
6248
+ var shellBasePayload = (task) => ({
6249
+ key: getShellTaskKey(task),
6250
+ state: task.state,
6251
+ ...task.title ? { command: task.title } : {}
6104
6252
  });
6105
- var toJsonValue = (value) => {
6106
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
6107
- return value;
6253
+ var shellStatusPayload = (task, options = {}) => ({
6254
+ ...shellBasePayload(task),
6255
+ ...options.background ? { background: true } : {},
6256
+ ...options.stillRunning ? { still_running: true } : {},
6257
+ ...options.aborted ? { aborted: true } : {}
6258
+ });
6259
+ var shellTerminalPayload = (task) => {
6260
+ const payload = shellBasePayload(task);
6261
+ if (task.result?.exit_code !== void 0 && task.result.exit_code !== null) {
6262
+ payload.exit_code = task.result.exit_code;
6108
6263
  }
6109
- if (Array.isArray(value)) {
6110
- return value.map((entry) => toJsonValue(entry));
6264
+ if (task.result?.duration_ms !== void 0 && task.result.duration_ms !== null) {
6265
+ payload.duration_ms = task.result.duration_ms;
6266
+ }
6267
+ if (task.failure_message) {
6268
+ payload.failure_message = task.failure_message;
6269
+ }
6270
+ if (task.cancellation_reason) {
6271
+ payload.cancellation_reason = task.cancellation_reason;
6111
6272
  }
6112
- if (value && typeof value === "object") {
6113
- const objectValue = {};
6114
- for (const [key, entry] of Object.entries(value)) {
6115
- objectValue[key] = toJsonValue(entry);
6273
+ const output = pickShellOutput(task);
6274
+ if (output) {
6275
+ payload[output.field] = output.content;
6276
+ if (output.cacheId) {
6277
+ payload.cache_id = output.cacheId;
6116
6278
  }
6117
- return objectValue;
6118
6279
  }
6119
- return String(value);
6280
+ return payload;
6120
6281
  };
6121
- var toShellTaskSummary = (task) => ({
6122
- task_id: task.task_id,
6123
- key: getShellTaskKey(task),
6124
- ...task.label ? { label: task.label } : {},
6125
- state: task.state,
6126
- ...task.title ? { title: task.title } : {},
6127
- ...task.working_directory ? { working_directory: task.working_directory } : {},
6128
- created_at: task.created_at,
6129
- updated_at: task.updated_at,
6130
- ...task.started_at ? { started_at: task.started_at } : {},
6131
- ...task.ended_at ? { ended_at: task.ended_at } : {},
6132
- exit_code: task.result?.exit_code ?? null,
6133
- duration_ms: task.result?.duration_ms ?? null,
6134
- result_available: isTerminalTaskState(task.state) && !!task.result,
6135
- ...task.failure_message ? { failure_message: task.failure_message } : {},
6282
+ var shellCancelPayload = (task) => ({
6283
+ ...shellBasePayload(task),
6136
6284
  ...task.cancellation_reason ? { cancellation_reason: task.cancellation_reason } : {},
6137
- ...task.cleanup_reason ? { cleanup_reason: task.cleanup_reason } : {}
6138
- });
6139
- var toShellTaskInfo = (task) => ({
6140
- ...toShellTaskSummary(task),
6141
- kind: task.kind,
6142
- workspace_mode: task.workspace_mode,
6143
- ...task.result?.child_session_id ?? task.child_session_id ? { child_session_id: task.result?.child_session_id ?? task.child_session_id } : {},
6144
- signal: task.result?.signal ?? null,
6145
- ...task.result?.summary ? { summary: task.result.summary } : {},
6146
- ...task.result?.stdout !== void 0 ? { stdout: task.result.stdout } : {},
6147
- ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
6148
- ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
6149
- ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
6150
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
6151
- ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
6152
- ...task.result?.artifacts ? { artifacts: toJsonValue(task.result.artifacts) } : {},
6153
- next_actions: buildShellTaskHints(getShellTaskKey(task), task.state)
6285
+ ...task.failure_message ? { failure_message: task.failure_message } : {}
6154
6286
  });
6155
6287
  var toShellListEntry = (task) => ({
6156
6288
  key: getShellTaskKey(task),
@@ -6183,7 +6315,10 @@ var resolveShellTask = async (tasks, input) => {
6183
6315
  const refs = matches.map((task) => task.task_id).join(", ");
6184
6316
  throw new Error(`multiple shell tasks matched key "${key}": ${refs}`);
6185
6317
  }
6186
- throw new TaskManagerError("task_not_found", `Shell task not found for key: ${key}`);
6318
+ throw new TaskManagerError(
6319
+ "task_not_found",
6320
+ `Shell task not found for key: ${key}`
6321
+ );
6187
6322
  };
6188
6323
  var tailContentByLines = (content, tailLines) => {
6189
6324
  if (content.length === 0) {
@@ -6206,7 +6341,10 @@ var tailContentByLines = (content, tailLines) => {
6206
6341
  };
6207
6342
  var resolveShellLogs = async (options) => {
6208
6343
  const taskKey = getShellTaskKey(options.task);
6209
- const live = await options.tasks.readOutput(options.task.task_id, options.stream);
6344
+ const live = await options.tasks.readOutput(
6345
+ options.task.task_id,
6346
+ options.stream
6347
+ );
6210
6348
  if (live !== null) {
6211
6349
  if (options.tailLines !== void 0) {
6212
6350
  const tailed = tailContentByLines(live, options.tailLines);
@@ -6325,11 +6463,57 @@ var waitForManagedTask = async (tasks, taskId, signal) => {
6325
6463
  throw error;
6326
6464
  }
6327
6465
  };
6466
+ var resolveShellWaitTimeoutSeconds = (value) => Math.max(
6467
+ 1,
6468
+ Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS)
6469
+ );
6470
+ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6471
+ let timeoutHandle;
6472
+ const waitPromise = waitForManagedTask(tasks, taskId, options.signal).then(
6473
+ (result) => ({
6474
+ type: "task",
6475
+ result
6476
+ })
6477
+ );
6478
+ const timeoutPromise = new Promise((resolve) => {
6479
+ timeoutHandle = setTimeout(
6480
+ () => resolve({ type: "timeout" }),
6481
+ options.waitTimeoutSeconds * 1e3
6482
+ );
6483
+ });
6484
+ try {
6485
+ const outcome = await Promise.race([waitPromise, timeoutPromise]);
6486
+ if (outcome.type === "task") {
6487
+ return {
6488
+ task: outcome.result.task,
6489
+ aborted: outcome.result.aborted,
6490
+ stillRunning: false
6491
+ };
6492
+ }
6493
+ const task = await requireTask(tasks, taskId);
6494
+ if (isTerminalTaskState(task.state)) {
6495
+ return {
6496
+ task,
6497
+ aborted: false,
6498
+ stillRunning: false
6499
+ };
6500
+ }
6501
+ return {
6502
+ task,
6503
+ aborted: false,
6504
+ stillRunning: true
6505
+ };
6506
+ } finally {
6507
+ if (timeoutHandle) {
6508
+ clearTimeout(timeoutHandle);
6509
+ }
6510
+ }
6511
+ };
6328
6512
  var createShellTool = (sandboxKey, options = {}) => {
6329
6513
  const shared = getSharedDeps(options);
6330
- return defineTool9({
6514
+ return defineTool10({
6331
6515
  name: "shell",
6332
- 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.",
6516
+ 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.",
6333
6517
  input: shellRunSchema,
6334
6518
  execute: async (input, ctx) => {
6335
6519
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6340,7 +6524,10 @@ var createShellTool = (sandboxKey, options = {}) => {
6340
6524
  }
6341
6525
  const label = normalizeOptionalLabel(input.label);
6342
6526
  const background = input.background ?? false;
6343
- const timeoutSeconds = resolveShellTimeoutSeconds(input.timeout, background);
6527
+ const timeoutSeconds = resolveShellTimeoutSeconds(
6528
+ input.timeout,
6529
+ background
6530
+ );
6344
6531
  const commandSummary = summarizeCommand(command);
6345
6532
  debugLog(
6346
6533
  `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
@@ -6369,19 +6556,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6369
6556
  })
6370
6557
  );
6371
6558
  if (background) {
6372
- return {
6373
- background: true,
6374
- task: toShellTaskInfo(task)
6375
- };
6559
+ return shellStatusPayload(task, { background: true });
6376
6560
  }
6377
- const settled = await waitForForegroundRun(shared.tasks, task.task_id, ctx.signal);
6561
+ const settled = await waitForForegroundRun(
6562
+ shared.tasks,
6563
+ task.task_id,
6564
+ ctx.signal
6565
+ );
6378
6566
  debugLog(
6379
6567
  `shell.done task_id=${task.task_id} state=${settled.state} duration_ms=${settled.result?.duration_ms ?? -1}`
6380
6568
  );
6381
- return {
6382
- background: false,
6383
- task: toShellTaskInfo(settled)
6384
- };
6569
+ return shellTerminalPayload(settled);
6385
6570
  } catch (error) {
6386
6571
  throw formatTaskError(error);
6387
6572
  }
@@ -6390,7 +6575,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6390
6575
  };
6391
6576
  var createShellListTool = (options = {}) => {
6392
6577
  const shared = getSharedDeps(options);
6393
- return defineTool9({
6578
+ return defineTool10({
6394
6579
  name: "shell_list",
6395
6580
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6396
6581
  input: shellListSchema,
@@ -6421,14 +6606,14 @@ var createShellListTool = (options = {}) => {
6421
6606
  };
6422
6607
  var createShellStatusTool = (options = {}) => {
6423
6608
  const shared = getSharedDeps(options);
6424
- return defineTool9({
6609
+ return defineTool10({
6425
6610
  name: "shell_status",
6426
- description: "Get the current state and retained metadata for a shell task.",
6611
+ description: "Get the current state for a shell task as compact JSON.",
6427
6612
  input: shellTaskKeySchema,
6428
6613
  execute: async (input) => {
6429
6614
  try {
6430
6615
  const task = await resolveShellTask(shared.tasks, input);
6431
- return { task: toShellTaskInfo(task) };
6616
+ return shellStatusPayload(task);
6432
6617
  } catch (error) {
6433
6618
  throw formatTaskError(error);
6434
6619
  }
@@ -6437,7 +6622,7 @@ var createShellStatusTool = (options = {}) => {
6437
6622
  };
6438
6623
  var createShellLogsTool = (options = {}) => {
6439
6624
  const shared = getSharedDeps(options);
6440
- return defineTool9({
6625
+ return defineTool10({
6441
6626
  name: "shell_logs",
6442
6627
  description: "Read recent stdout or stderr for a running or finished shell task.",
6443
6628
  input: shellLogsSchema,
@@ -6459,22 +6644,31 @@ var createShellLogsTool = (options = {}) => {
6459
6644
  };
6460
6645
  var createShellWaitTool = (options = {}) => {
6461
6646
  const shared = getSharedDeps(options);
6462
- return defineTool9({
6647
+ return defineTool10({
6463
6648
  name: "shell_wait",
6464
- description: "Wait for a shell task to reach a terminal state and return its retained outcome.",
6465
- input: shellTaskKeySchema,
6649
+ description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6650
+ input: shellWaitSchema,
6466
6651
  execute: async (input, ctx) => {
6467
6652
  try {
6468
- const task = await resolveShellTask(shared.tasks, input);
6469
- const result = await waitForManagedTask(
6653
+ const waitInput = input;
6654
+ const task = await resolveShellTask(shared.tasks, waitInput);
6655
+ const result = await waitForManagedTaskWindow(
6470
6656
  shared.tasks,
6471
6657
  task.task_id,
6472
- ctx.signal
6658
+ {
6659
+ waitTimeoutSeconds: resolveShellWaitTimeoutSeconds(
6660
+ waitInput.wait_timeout
6661
+ ),
6662
+ signal: ctx.signal
6663
+ }
6473
6664
  );
6474
- return {
6475
- ...result.aborted ? { aborted: true } : {},
6476
- task: toShellTaskInfo(result.task)
6477
- };
6665
+ if (result.stillRunning || result.aborted) {
6666
+ return shellStatusPayload(result.task, {
6667
+ aborted: result.aborted,
6668
+ stillRunning: result.stillRunning
6669
+ });
6670
+ }
6671
+ return shellTerminalPayload(result.task);
6478
6672
  } catch (error) {
6479
6673
  throw formatTaskError(error);
6480
6674
  }
@@ -6483,14 +6677,14 @@ var createShellWaitTool = (options = {}) => {
6483
6677
  };
6484
6678
  var createShellResultTool = (options = {}) => {
6485
6679
  const shared = getSharedDeps(options);
6486
- return defineTool9({
6680
+ return defineTool10({
6487
6681
  name: "shell_result",
6488
- description: "Read the retained terminal result for a shell task.",
6682
+ description: "Read the retained terminal result for a shell task as compact JSON.",
6489
6683
  input: shellTaskKeySchema,
6490
6684
  execute: async (input) => {
6491
6685
  try {
6492
6686
  const task = await resolveShellTask(shared.tasks, input);
6493
- return { task: toShellTaskInfo(task) };
6687
+ return isTerminalTaskState(task.state) ? shellTerminalPayload(task) : shellStatusPayload(task);
6494
6688
  } catch (error) {
6495
6689
  throw formatTaskError(error);
6496
6690
  }
@@ -6499,9 +6693,9 @@ var createShellResultTool = (options = {}) => {
6499
6693
  };
6500
6694
  var createShellCancelTool = (options = {}) => {
6501
6695
  const shared = getSharedDeps(options);
6502
- return defineTool9({
6696
+ return defineTool10({
6503
6697
  name: "shell_cancel",
6504
- description: "Cancel a running shell task and return its retained terminal state.",
6698
+ description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6505
6699
  input: shellTaskKeySchema,
6506
6700
  execute: async (input) => {
6507
6701
  try {
@@ -6509,7 +6703,7 @@ var createShellCancelTool = (options = {}) => {
6509
6703
  const cancelled = await shared.tasks.cancel(task.task_id, {
6510
6704
  reason: "cancelled"
6511
6705
  });
6512
- return { task: toShellTaskInfo(cancelled) };
6706
+ return shellCancelPayload(cancelled);
6513
6707
  } catch (error) {
6514
6708
  throw formatTaskError(error);
6515
6709
  }
@@ -6518,16 +6712,16 @@ var createShellCancelTool = (options = {}) => {
6518
6712
  };
6519
6713
 
6520
6714
  // src/tools/skill-load.ts
6521
- import { defineTool as defineTool10 } from "@codelia/core";
6522
- import { z as z11 } from "zod";
6523
- var SkillLoadInputSchema = z11.object({
6524
- name: z11.string().min(1).optional().describe("Exact skill name to load."),
6525
- path: z11.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6715
+ import { defineTool as defineTool11 } from "@codelia/core";
6716
+ import { z as z12 } from "zod";
6717
+ var SkillLoadInputSchema = z12.object({
6718
+ name: z12.string().min(1).optional().describe("Exact skill name to load."),
6719
+ path: z12.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6526
6720
  }).refine((value) => !!value.name || !!value.path, {
6527
6721
  message: "name or path is required",
6528
6722
  path: ["name"]
6529
6723
  });
6530
- var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6724
+ var createSkillLoadTool = (skillsResolverKey) => defineTool11({
6531
6725
  name: "skill_load",
6532
6726
  description: "Load full SKILL.md content by exact name or path.",
6533
6727
  input: SkillLoadInputSchema,
@@ -6573,15 +6767,15 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6573
6767
  });
6574
6768
 
6575
6769
  // src/tools/skill-search.ts
6576
- import { defineTool as defineTool11 } from "@codelia/core";
6577
- import { z as z12 } from "zod";
6578
- var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6770
+ import { defineTool as defineTool12 } from "@codelia/core";
6771
+ import { z as z13 } from "zod";
6772
+ var createSkillSearchTool = (skillsResolverKey) => defineTool12({
6579
6773
  name: "skill_search",
6580
6774
  description: "Search installed local skills by name, description, or path.",
6581
- input: z12.object({
6582
- query: z12.string().min(1).describe("Search query text."),
6583
- limit: z12.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6584
- scope: z12.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6775
+ input: z13.object({
6776
+ query: z13.string().min(1).describe("Search query text."),
6777
+ limit: z13.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6778
+ scope: z13.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6585
6779
  }),
6586
6780
  execute: async (input, ctx) => {
6587
6781
  try {
@@ -6604,8 +6798,8 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6604
6798
  });
6605
6799
 
6606
6800
  // src/tools/todo-mutate.ts
6607
- import { defineTool as defineTool12 } from "@codelia/core";
6608
- import { z as z13 } from "zod";
6801
+ import { defineTool as defineTool13 } from "@codelia/core";
6802
+ import { z as z14 } from "zod";
6609
6803
 
6610
6804
  // src/tools/todo-store.ts
6611
6805
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6715,37 +6909,37 @@ var pickNextTodo = (todos) => {
6715
6909
  var todoStore = /* @__PURE__ */ new Map();
6716
6910
 
6717
6911
  // src/tools/todo-mutate.ts
6718
- var todoStatusSchema = z13.enum(["pending", "in_progress", "completed"]);
6719
- var todoPrioritySchema = z13.number().int().min(1).max(5);
6720
- var todoItemSchema = z13.object({
6721
- id: z13.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6722
- content: z13.string().min(1).describe("Todo item text."),
6912
+ var todoStatusSchema = z14.enum(["pending", "in_progress", "completed"]);
6913
+ var todoPrioritySchema = z14.number().int().min(1).max(5);
6914
+ var todoItemSchema = z14.object({
6915
+ id: z14.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6916
+ content: z14.string().min(1).describe("Todo item text."),
6723
6917
  status: todoStatusSchema.describe("Todo status."),
6724
6918
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6725
- notes: z13.string().optional().describe("Optional implementation notes."),
6726
- activeForm: z13.string().optional().describe("Optional in-progress phrasing for UI display.")
6919
+ notes: z14.string().optional().describe("Optional implementation notes."),
6920
+ activeForm: z14.string().optional().describe("Optional in-progress phrasing for UI display.")
6727
6921
  });
6728
- var todoPatchItemSchema = z13.object({
6729
- id: z13.string().min(1).describe("Target todo ID."),
6730
- remove: z13.boolean().optional().describe("Set true to remove the todo item."),
6731
- content: z13.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6922
+ var todoPatchItemSchema = z14.object({
6923
+ id: z14.string().min(1).describe("Target todo ID."),
6924
+ remove: z14.boolean().optional().describe("Set true to remove the todo item."),
6925
+ content: z14.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6732
6926
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6733
6927
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6734
- notes: z13.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6735
- activeForm: z13.string().nullable().default(null).describe(
6928
+ notes: z14.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6929
+ activeForm: z14.string().nullable().default(null).describe(
6736
6930
  "Updated in-progress phrasing (null keeps current, empty clears)."
6737
6931
  )
6738
6932
  });
6739
- var todoNewInputSchema = z13.object({
6740
- todos: z13.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6933
+ var todoNewInputSchema = z14.object({
6934
+ todos: z14.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6741
6935
  }).strict();
6742
- var todoAppendInputSchema = z13.object({
6743
- todos: z13.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6936
+ var todoAppendInputSchema = z14.object({
6937
+ todos: z14.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6744
6938
  }).strict();
6745
- var todoPatchInputSchema = z13.object({
6746
- updates: z13.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6939
+ var todoPatchInputSchema = z14.object({
6940
+ updates: z14.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6747
6941
  }).strict();
6748
- var todoClearInputSchema = z13.object({}).strict();
6942
+ var todoClearInputSchema = z14.object({}).strict();
6749
6943
  var statusSymbol = {
6750
6944
  pending: "[ ]",
6751
6945
  in_progress: "[>]",
@@ -6840,7 +7034,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6840
7034
  }
6841
7035
  return formatSuccess(outputMode, nextTodos);
6842
7036
  };
6843
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool12({
7037
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool13({
6844
7038
  name,
6845
7039
  description,
6846
7040
  input,
@@ -6857,11 +7051,7 @@ var createTodoNewTool = (sandboxKey, sessionContextKey) => createTodoMutationToo
6857
7051
  "todo_new",
6858
7052
  "Start or replace the in-session todo plan with a full task list.",
6859
7053
  todoNewInputSchema,
6860
- (sessionId, input) => applyTodoMutation(
6861
- sessionId,
6862
- { mode: "new", todos: input.todos },
6863
- "new"
6864
- ),
7054
+ (sessionId, input) => applyTodoMutation(sessionId, { mode: "new", todos: input.todos }, "new"),
6865
7055
  sandboxKey,
6866
7056
  sessionContextKey
6867
7057
  );
@@ -6899,17 +7089,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6899
7089
  );
6900
7090
 
6901
7091
  // src/tools/todo-read.ts
6902
- import { defineTool as defineTool13 } from "@codelia/core";
6903
- import { z as z14 } from "zod";
7092
+ import { defineTool as defineTool14 } from "@codelia/core";
7093
+ import { z as z15 } from "zod";
6904
7094
  var statusSymbol2 = {
6905
7095
  pending: "[ ]",
6906
7096
  in_progress: "[>]",
6907
7097
  completed: "[x]"
6908
7098
  };
6909
- var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7099
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
6910
7100
  name: "todo_read",
6911
7101
  description: "Read the in-session todo plan with execution order and next step.",
6912
- input: z14.object({}),
7102
+ input: z15.object({}),
6913
7103
  execute: async (_input, ctx) => {
6914
7104
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6915
7105
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -6945,15 +7135,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
6945
7135
  });
6946
7136
 
6947
7137
  // src/tools/tool-output-cache.ts
6948
- import { defineTool as defineTool14 } from "@codelia/core";
6949
- import { z as z15 } from "zod";
6950
- var createToolOutputCacheTool = (store) => defineTool14({
7138
+ import { defineTool as defineTool15 } from "@codelia/core";
7139
+ import { z as z16 } from "zod";
7140
+ var createToolOutputCacheTool = (store) => defineTool15({
6951
7141
  name: "tool_output_cache",
6952
7142
  description: "Read cached tool output by ref_id.",
6953
- input: z15.object({
6954
- ref_id: z15.string().describe("Tool output reference ID."),
6955
- offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
6956
- limit: z15.number().int().positive().optional().describe("Optional max number of lines to return.")
7143
+ input: z16.object({
7144
+ ref_id: z16.string().describe("Tool output reference ID."),
7145
+ offset: z16.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7146
+ limit: z16.number().int().positive().optional().describe("Optional max number of lines to return.")
6957
7147
  }),
6958
7148
  execute: async (input) => {
6959
7149
  if (!store.read) {
@@ -6969,14 +7159,14 @@ var createToolOutputCacheTool = (store) => defineTool14({
6969
7159
  }
6970
7160
  }
6971
7161
  });
6972
- var createToolOutputCacheLineTool = (store) => defineTool14({
7162
+ var createToolOutputCacheLineTool = (store) => defineTool15({
6973
7163
  name: "tool_output_cache_line",
6974
7164
  description: "Read a single cached output line segment by line number and char offset.",
6975
- input: z15.object({
6976
- ref_id: z15.string().describe("Tool output reference ID."),
6977
- line_number: z15.number().int().positive().describe("1-based line number to read."),
6978
- char_offset: z15.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
6979
- char_limit: z15.number().int().positive().optional().describe("Max chars to return.")
7165
+ input: z16.object({
7166
+ ref_id: z16.string().describe("Tool output reference ID."),
7167
+ line_number: z16.number().int().positive().describe("1-based line number to read."),
7168
+ char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7169
+ char_limit: z16.number().int().positive().optional().describe("Max chars to return.")
6980
7170
  }),
6981
7171
  execute: async (input) => {
6982
7172
  if (!store.readLine) {
@@ -6993,16 +7183,16 @@ var createToolOutputCacheLineTool = (store) => defineTool14({
6993
7183
  }
6994
7184
  }
6995
7185
  });
6996
- var createToolOutputCacheGrepTool = (store) => defineTool14({
7186
+ var createToolOutputCacheGrepTool = (store) => defineTool15({
6997
7187
  name: "tool_output_cache_grep",
6998
7188
  description: "Search cached tool output by ref_id.",
6999
- input: z15.object({
7000
- ref_id: z15.string().describe("Tool output reference ID."),
7001
- pattern: z15.string().describe("Text or regex pattern to search for."),
7002
- regex: z15.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7003
- before: z15.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7004
- after: z15.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7005
- max_matches: z15.number().int().positive().optional().describe("Maximum number of matches to return.")
7189
+ input: z16.object({
7190
+ ref_id: z16.string().describe("Tool output reference ID."),
7191
+ pattern: z16.string().describe("Text or regex pattern to search for."),
7192
+ regex: z16.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7193
+ before: z16.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7194
+ after: z16.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7195
+ max_matches: z16.number().int().positive().optional().describe("Maximum number of matches to return.")
7006
7196
  }),
7007
7197
  execute: async (input) => {
7008
7198
  if (!store.grep) {
@@ -7022,74 +7212,6 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
7022
7212
  }
7023
7213
  });
7024
7214
 
7025
- // src/tools/read-line.ts
7026
- import { promises as fs14 } from "fs";
7027
- import { defineTool as defineTool15 } from "@codelia/core";
7028
- import { z as z16 } from "zod";
7029
- var DEFAULT_CHAR_LIMIT = 1e4;
7030
- var MAX_CHAR_LIMIT = 1e5;
7031
- var createReadLineTool = (sandboxKey) => defineTool15({
7032
- name: "read_line",
7033
- description: "Read a single line segment by 1-based line number and 0-based char offset.",
7034
- input: z16.object({
7035
- file_path: z16.string().describe("File path under the sandbox root."),
7036
- line_number: z16.number().int().positive().describe("1-based line number to read."),
7037
- char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7038
- char_limit: z16.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
7039
- }),
7040
- execute: async (input, ctx) => {
7041
- let resolved;
7042
- try {
7043
- const sandbox = await getSandboxContext(ctx, sandboxKey);
7044
- resolved = sandbox.resolvePath(input.file_path);
7045
- } catch (error) {
7046
- return `Security error: ${String(error)}`;
7047
- }
7048
- try {
7049
- const stat = await fs14.stat(resolved);
7050
- if (stat.isDirectory()) {
7051
- return `Path is a directory: ${input.file_path}`;
7052
- }
7053
- } catch {
7054
- return `File not found: ${input.file_path}`;
7055
- }
7056
- try {
7057
- const content = await fs14.readFile(resolved, "utf8");
7058
- const lines = content.split(/\r?\n/);
7059
- const lineIndex = input.line_number - 1;
7060
- if (lineIndex >= lines.length) {
7061
- return `Line number out of range: ${input.line_number} (total ${lines.length})`;
7062
- }
7063
- const line = lines[lineIndex] ?? "";
7064
- const charOffset = input.char_offset ?? 0;
7065
- const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
7066
- if (charOffset > line.length) {
7067
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
7068
- }
7069
- const segment = line.slice(charOffset, charOffset + charLimit);
7070
- const endOffset = charOffset + segment.length;
7071
- const hasMore = endOffset < line.length;
7072
- const header = [
7073
- `line_number=${input.line_number}`,
7074
- `line_length=${line.length}`,
7075
- `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
7076
- ].join(" ");
7077
- let output = `${header}
7078
- ${segment}`;
7079
- if (hasMore) {
7080
- output += `
7081
-
7082
- Use char_offset=${endOffset} to continue.`;
7083
- output += `
7084
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
7085
- }
7086
- return output;
7087
- } catch (error) {
7088
- return `Error reading file: ${String(error)}`;
7089
- }
7090
- }
7091
- });
7092
-
7093
7215
  // src/tools/write.ts
7094
7216
  import { promises as fs15 } from "fs";
7095
7217
  import path13 from "path";
@@ -7108,7 +7230,9 @@ var createWriteTool = (sandboxKey) => defineTool16({
7108
7230
  name: "write",
7109
7231
  description: "Write text to a file, creating parent directories if needed.",
7110
7232
  input: z17.object({
7111
- file_path: z17.string().describe("File path under the sandbox root."),
7233
+ file_path: z17.string().describe(
7234
+ "File path. Sandbox-bounded unless full-access mode is active."
7235
+ ),
7112
7236
  content: z17.string().describe("UTF-8 text content to write.")
7113
7237
  }),
7114
7238
  execute: async (input, ctx) => {
@@ -7117,7 +7241,7 @@ var createWriteTool = (sandboxKey) => defineTool16({
7117
7241
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7118
7242
  resolved = sandbox.resolvePath(input.file_path);
7119
7243
  } catch (error) {
7120
- return `Security error: ${String(error)}`;
7244
+ throw new Error(`Security error: ${String(error)}`);
7121
7245
  }
7122
7246
  try {
7123
7247
  await fs15.mkdir(path13.dirname(resolved), { recursive: true });
@@ -7612,9 +7736,21 @@ var createAgentFactory = (state, options = {}) => {
7612
7736
  if (state.agent) return state.agent;
7613
7737
  if (inFlight) return inFlight;
7614
7738
  inFlight = (async () => {
7615
- const rootDir = process.env.CODELIA_SANDBOX_ROOT;
7616
- const ctx = await SandboxContext.create(rootDir);
7617
- log(`sandbox created at ${ctx.rootDir}`);
7739
+ const sandboxRoot = state.runtimeSandboxRoot ?? state.runtimeWorkingDir ?? process.cwd();
7740
+ const approvalModeResolution = await resolveApprovalModeForRuntime({
7741
+ workingDir: sandboxRoot,
7742
+ runtimeSandboxRoot: sandboxRoot,
7743
+ requestStartupSelection: async ({ projectKey }) => {
7744
+ return requestApprovalModeStartupSelection(state, projectKey);
7745
+ },
7746
+ deferStartupSelectionPersist: true
7747
+ });
7748
+ const ctx = await SandboxContext.create(sandboxRoot, {
7749
+ approvalMode: approvalModeResolution.approvalMode
7750
+ });
7751
+ log(
7752
+ `sandbox created at ${ctx.rootDir} approval_mode=${approvalModeResolution.approvalMode}`
7753
+ );
7618
7754
  const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
7619
7755
  state.agentsResolver = agentsResolver;
7620
7756
  let skillsConfig;
@@ -7689,13 +7825,6 @@ var createAgentFactory = (state, options = {}) => {
7689
7825
  const message = error instanceof Error ? error.message : String(error);
7690
7826
  throw new Error(message);
7691
7827
  }
7692
- const approvalModeResolution = await resolveApprovalModeForRuntime({
7693
- workingDir: ctx.workingDir,
7694
- runtimeSandboxRoot: state.runtimeSandboxRoot,
7695
- requestStartupSelection: async ({ projectKey }) => {
7696
- return requestApprovalModeStartupSelection(state, projectKey);
7697
- }
7698
- });
7699
7828
  const permissionService = new PermissionService({
7700
7829
  approvalMode: approvalModeResolution.approvalMode,
7701
7830
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
@@ -8030,6 +8159,9 @@ var createAgentFactory = (state, options = {}) => {
8030
8159
  return { decision: "allow" };
8031
8160
  }
8032
8161
  });
8162
+ if (approvalModeResolution.persistSelection) {
8163
+ await approvalModeResolution.persistSelection();
8164
+ }
8033
8165
  state.agent = agent;
8034
8166
  return agent;
8035
8167
  })();
@@ -10996,7 +11128,7 @@ import {
10996
11128
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
10997
11129
  } from "@codelia/storage";
10998
11130
  var COMMAND_PREVIEW_CHARS = 400;
10999
- var DEFAULT_TRUNCATED2 = {
11131
+ var DEFAULT_TRUNCATED = {
11000
11132
  stdout: false,
11001
11133
  stderr: false,
11002
11134
  combined: false
@@ -11134,12 +11266,12 @@ var toShellExecResult = (commandPreview, result) => ({
11134
11266
  signal: result?.signal ?? null,
11135
11267
  stdout: result?.stdout ?? "",
11136
11268
  stderr: result?.stderr ?? "",
11137
- truncated: result?.truncated ?? DEFAULT_TRUNCATED2,
11269
+ truncated: result?.truncated ?? DEFAULT_TRUNCATED,
11138
11270
  duration_ms: result?.duration_ms ?? 0,
11139
11271
  ...result?.stdout_cache_id ? { stdout_cache_id: result.stdout_cache_id } : {},
11140
11272
  ...result?.stderr_cache_id ? { stderr_cache_id: result.stderr_cache_id } : {}
11141
11273
  });
11142
- var toShellTaskInfo2 = (task) => ({
11274
+ var toShellTaskInfo = (task) => ({
11143
11275
  task_id: task.task_id,
11144
11276
  state: task.state,
11145
11277
  command_preview: task.title,
@@ -11152,7 +11284,7 @@ var toShellTaskInfo2 = (task) => ({
11152
11284
  signal: task.result?.signal ?? null,
11153
11285
  stdout: task.result?.stdout ?? "",
11154
11286
  stderr: task.result?.stderr ?? "",
11155
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED2,
11287
+ truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
11156
11288
  duration_ms: task.result?.duration_ms ?? null,
11157
11289
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11158
11290
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
@@ -11198,7 +11330,10 @@ var sendTaskError = (id, error) => {
11198
11330
  var requireShellTask = async (taskManager, taskId) => {
11199
11331
  const task = await taskManager.status(taskId);
11200
11332
  if (!task || task.kind !== "shell") {
11201
- throw new TaskManagerError("task_not_found", `Shell task not found: ${taskId}`);
11333
+ throw new TaskManagerError(
11334
+ "task_not_found",
11335
+ `Shell task not found: ${taskId}`
11336
+ );
11202
11337
  }
11203
11338
  return task;
11204
11339
  };
@@ -11230,6 +11365,28 @@ var resolveShellTimeoutSeconds2 = (requestedTimeout, background) => {
11230
11365
  }
11231
11366
  return background ? void 0 : DEFAULT_TIMEOUT_SECONDS;
11232
11367
  };
11368
+ var resolveShellWaitTimeoutSeconds2 = (requestedTimeout) => {
11369
+ if (requestedTimeout !== void 0) {
11370
+ if (!Number.isFinite(requestedTimeout) || requestedTimeout <= 0) {
11371
+ return {
11372
+ error: {
11373
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11374
+ message: "wait_timeout_seconds must be a positive number"
11375
+ }
11376
+ };
11377
+ }
11378
+ if (requestedTimeout > MAX_TIMEOUT_SECONDS) {
11379
+ return {
11380
+ error: {
11381
+ code: RPC_ERROR_CODE5.INVALID_PARAMS,
11382
+ message: `wait_timeout_seconds must be ${MAX_TIMEOUT_SECONDS} seconds or less`
11383
+ }
11384
+ };
11385
+ }
11386
+ return Math.max(1, Math.trunc(requestedTimeout));
11387
+ }
11388
+ return DEFAULT_TIMEOUT_SECONDS;
11389
+ };
11233
11390
  var formatShellTimeoutForLog2 = (value) => value === void 0 ? "none" : String(value);
11234
11391
  var parseShellStartRequest = (state, params, options) => {
11235
11392
  const command = params?.command?.trim() ?? "";
@@ -11334,7 +11491,7 @@ var createShellHandlers = ({
11334
11491
  const handleShellStart = async (id, params) => {
11335
11492
  try {
11336
11493
  const { task } = await spawnShell(params, "shell.start");
11337
- sendResult(id, toShellTaskInfo2(task));
11494
+ sendResult(id, toShellTaskInfo(task));
11338
11495
  } catch (error) {
11339
11496
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
11340
11497
  sendError(id, error);
@@ -11354,7 +11511,7 @@ var createShellHandlers = ({
11354
11511
  }
11355
11512
  try {
11356
11513
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
11357
- const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo2);
11514
+ const tasks = (await shellTaskManager.list()).filter((task) => task.kind === "shell").slice(0, limit).map(toShellTaskInfo);
11358
11515
  const result = { tasks };
11359
11516
  sendResult(id, result);
11360
11517
  } catch (error) {
@@ -11372,7 +11529,7 @@ var createShellHandlers = ({
11372
11529
  }
11373
11530
  try {
11374
11531
  const task = await requireShellTask(shellTaskManager, taskId);
11375
- sendResult(id, toShellTaskInfo2(task));
11532
+ sendResult(id, toShellTaskInfo(task));
11376
11533
  } catch (error) {
11377
11534
  sendTaskError(id, error);
11378
11535
  }
@@ -11435,17 +11592,31 @@ var createShellHandlers = ({
11435
11592
  });
11436
11593
  return;
11437
11594
  }
11595
+ const waitTimeoutSeconds = resolveShellWaitTimeoutSeconds2(
11596
+ params?.wait_timeout_seconds
11597
+ );
11598
+ if (typeof waitTimeoutSeconds === "object") {
11599
+ sendError(id, waitTimeoutSeconds.error);
11600
+ return;
11601
+ }
11438
11602
  try {
11439
11603
  const existing = await requireShellTask(shellTaskManager, taskId);
11440
11604
  if (isTerminalTaskState(existing.state)) {
11441
- sendResult(id, toShellTaskInfo2(existing));
11605
+ sendResult(id, toShellTaskInfo(existing));
11442
11606
  return;
11443
11607
  }
11444
11608
  const controller = new AbortController();
11609
+ let timeoutHandle;
11445
11610
  let resolveDetached;
11446
- const detachPromise = new Promise(
11611
+ const detachPromise = new Promise((resolve) => {
11612
+ resolveDetached = (result) => resolve({ type: "detached", result });
11613
+ });
11614
+ const timeoutPromise = new Promise(
11447
11615
  (resolve) => {
11448
- resolveDetached = (result) => resolve({ type: "detached", result });
11616
+ timeoutHandle = setTimeout(() => {
11617
+ controller.abort();
11618
+ resolve({ type: "still_running" });
11619
+ }, waitTimeoutSeconds * 1e3);
11449
11620
  }
11450
11621
  );
11451
11622
  const unregister = registerActiveShellWait(taskId, {
@@ -11465,16 +11636,31 @@ var createShellHandlers = ({
11465
11636
  }
11466
11637
  throw error;
11467
11638
  });
11468
- const outcome = await Promise.race([waitPromise, detachPromise]);
11639
+ const outcome = await Promise.race([
11640
+ waitPromise,
11641
+ detachPromise,
11642
+ timeoutPromise
11643
+ ]);
11469
11644
  if (outcome.type === "detached") {
11470
11645
  sendResult(id, outcome.result);
11471
11646
  return;
11472
11647
  }
11648
+ if (outcome.type === "still_running") {
11649
+ const task = await requireShellTask(shellTaskManager, taskId);
11650
+ sendResult(id, {
11651
+ ...toShellTaskInfo(task),
11652
+ ...isTerminalTaskState(task.state) ? {} : { still_running: true }
11653
+ });
11654
+ return;
11655
+ }
11473
11656
  if (outcome.type === "aborted") {
11474
11657
  return;
11475
11658
  }
11476
- sendResult(id, toShellTaskInfo2(outcome.task));
11659
+ sendResult(id, toShellTaskInfo(outcome.task));
11477
11660
  } finally {
11661
+ if (timeoutHandle) {
11662
+ clearTimeout(timeoutHandle);
11663
+ }
11478
11664
  unregister();
11479
11665
  }
11480
11666
  } catch (error) {
@@ -11527,7 +11713,7 @@ var createShellHandlers = ({
11527
11713
  const task = await shellTaskManager.cancel(taskId, {
11528
11714
  reason: "cancelled"
11529
11715
  });
11530
- sendResult(id, toShellTaskInfo2(task));
11716
+ sendResult(id, toShellTaskInfo(task));
11531
11717
  } catch (error) {
11532
11718
  sendTaskError(id, error);
11533
11719
  }
@@ -11614,7 +11800,7 @@ import {
11614
11800
  RPC_ERROR_CODE as RPC_ERROR_CODE7
11615
11801
  } from "@codelia/protocol";
11616
11802
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
11617
- var DEFAULT_TRUNCATED3 = {
11803
+ var DEFAULT_TRUNCATED2 = {
11618
11804
  stdout: false,
11619
11805
  stderr: false,
11620
11806
  combined: false
@@ -11720,7 +11906,7 @@ var toTaskInfo = (task) => ({
11720
11906
  ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
11721
11907
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11722
11908
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
11723
- ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED3 },
11909
+ ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED2 },
11724
11910
  ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
11725
11911
  ...task.result?.artifacts ? { artifacts: task.result.artifacts } : {}
11726
11912
  });
@@ -12643,7 +12829,9 @@ var startRuntime = () => {
12643
12829
  `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
12644
12830
  );
12645
12831
  for (const error of result.errors) {
12646
- log(`tasks.shutdown error task_id=${error.task_id}: ${error.error}`);
12832
+ log(
12833
+ `tasks.shutdown error task_id=${error.task_id}: ${error.error}`
12834
+ );
12647
12835
  }
12648
12836
  }
12649
12837
  })();