@codelia/runtime 0.1.48 → 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 +559 -475
  2. package/dist/index.js +563 -483
  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);
@@ -4971,30 +4994,100 @@ var createReadTool = (sandboxKey) => defineTool7({
4971
4994
  outputLines.push(line);
4972
4995
  bytes += size;
4973
4996
  }
4974
- const numbered = outputLines.map(
4975
- (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4976
- );
4977
- const lastReadLine = offset + outputLines.length;
4978
- const hasMoreLines = lines.length > lastReadLine;
4979
- let output = numbered.join("\n");
4980
- if (truncatedByBytes || hasMoreLines) {
4981
- const reason = truncatedByBytes ? `[output truncated at ${MAX_BYTES} bytes]` : "Output has more lines.";
4982
- output += `
4983
-
4984
- ${reason} Use offset to read beyond line ${lastReadLine}.`;
4997
+ const numbered = outputLines.map(
4998
+ (line, index) => `${String(index + offset + 1).padStart(5, " ")} ${line}`
4999
+ );
5000
+ const lastReadLine = offset + outputLines.length;
5001
+ const hasMoreLines = lines.length > lastReadLine;
5002
+ let output = numbered.join("\n");
5003
+ if (truncatedByBytes || hasMoreLines) {
5004
+ const reason = truncatedByBytes ? `[output truncated at ${MAX_BYTES} bytes]` : "Output has more lines.";
5005
+ output += `
5006
+
5007
+ ${reason} Use offset to read beyond line ${lastReadLine}.`;
5008
+ }
5009
+ const truncatedLinesSummary = buildTruncatedLinesSummary(
5010
+ Array.from(new Set(truncatedLineNumbers))
5011
+ );
5012
+ if (truncatedLinesSummary) {
5013
+ output += `
5014
+
5015
+ ${truncatedLinesSummary}`;
5016
+ }
5017
+ if (firstClippedLineNumber !== null) {
5018
+ output += `
5019
+
5020
+ For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5021
+ }
5022
+ return output;
5023
+ } catch (error) {
5024
+ return `Error reading file: ${String(error)}`;
5025
+ }
5026
+ }
5027
+ });
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})`;
4985
5068
  }
4986
- const truncatedLinesSummary = buildTruncatedLinesSummary(
4987
- Array.from(new Set(truncatedLineNumbers))
4988
- );
4989
- if (truncatedLinesSummary) {
4990
- output += `
4991
-
4992
- ${truncatedLinesSummary}`;
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})`;
4993
5074
  }
4994
- if (firstClippedLineNumber !== null) {
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) {
4995
5086
  output += `
4996
5087
 
4997
- For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
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}})`;
4998
5091
  }
4999
5092
  return output;
5000
5093
  } catch (error) {
@@ -5004,8 +5097,8 @@ For full long-line content, use read_line({"file_path":"${input.file_path}","lin
5004
5097
  });
5005
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,23 +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(
6102
+ var shellRunSchema = z11.object({
6103
+ command: z11.string().describe(
5996
6104
  "Shell command to execute as a runtime-managed child process in the current workspace."
5997
6105
  ),
5998
- 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.`),
5999
- timeout: z10.number().int().positive().optional().describe(
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(
6000
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.`
6001
6111
  ),
6002
- background: z10.boolean().optional().describe(
6003
- "Detach the wait and return task info immediately. The runtime still owns the child process, so this is not persistence/daemonization. Manage it with shell_status/logs/wait/result/cancel. Default: false."
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."
6004
6114
  )
6005
6115
  }).superRefine((input, ctx) => {
6006
6116
  if (input.timeout === void 0) {
@@ -6009,7 +6119,7 @@ var shellRunSchema = z10.object({
6009
6119
  if (input.background ?? false) {
6010
6120
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6011
6121
  ctx.addIssue({
6012
- code: z10.ZodIssueCode.custom,
6122
+ code: z11.ZodIssueCode.custom,
6013
6123
  path: ["timeout"],
6014
6124
  message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6015
6125
  });
@@ -6018,32 +6128,34 @@ var shellRunSchema = z10.object({
6018
6128
  }
6019
6129
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6020
6130
  ctx.addIssue({
6021
- code: z10.ZodIssueCode.custom,
6131
+ code: z11.ZodIssueCode.custom,
6022
6132
  path: ["timeout"],
6023
6133
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6024
6134
  });
6025
6135
  }
6026
6136
  });
6027
- var shellTaskKeySchema = z10.object({
6028
- 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.")
6029
6139
  });
6030
6140
  var shellWaitSchema = shellTaskKeySchema.extend({
6031
- wait_timeout: z10.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6032
- `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. Returns still_running=true if the task has not finished before this window expires.`
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.`
6033
6143
  )
6034
6144
  });
6035
- var shellStreamSchema = z10.enum(["stdout", "stderr"]);
6036
- var shellListSchema = z10.object({
6037
- 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(
6038
6148
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6039
6149
  ),
6040
6150
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6041
- 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.")
6042
6152
  });
6043
- var shellLogsSchema = z10.object({
6044
- 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."),
6045
6155
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6046
- 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
+ )
6047
6159
  });
6048
6160
  var formatTaskError = (error) => {
6049
6161
  if (error instanceof TaskManagerError) {
@@ -6062,7 +6174,10 @@ var resolveShellTimeoutSeconds = (value, background) => {
6062
6174
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6063
6175
  }
6064
6176
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
6065
- 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
+ );
6066
6181
  };
6067
6182
  var formatShellTimeoutForLog = (value) => value === void 0 ? "none" : String(value);
6068
6183
  var normalizeShellTaskKey = (value) => {
@@ -6089,7 +6204,10 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6089
6204
  (await tasks.list()).filter((task) => task.kind === "shell" && typeof task.key === "string").map((task) => task.key)
6090
6205
  );
6091
6206
  for (const length of [8, 12, compactIdValue.length]) {
6092
- const suffix = compactIdValue.slice(0, Math.min(length, compactIdValue.length));
6207
+ const suffix = compactIdValue.slice(
6208
+ 0,
6209
+ Math.min(length, compactIdValue.length)
6210
+ );
6093
6211
  if (!suffix) continue;
6094
6212
  const candidate2 = `${base}-${suffix}`;
6095
6213
  if (!usedKeys.has(candidate2)) return candidate2;
@@ -6102,62 +6220,69 @@ var buildShellTaskKey = async (tasks, taskId, label) => {
6102
6220
  }
6103
6221
  return candidate;
6104
6222
  };
6105
- var buildShellTaskHints = (taskKey, state) => ({
6106
- status: { key: taskKey },
6107
- logs: { key: taskKey },
6108
- wait: { key: taskKey },
6109
- result: { key: taskKey },
6110
- ...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 } : {}
6111
6252
  });
6112
- var toJsonValue = (value) => {
6113
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
6114
- 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;
6115
6263
  }
6116
- if (Array.isArray(value)) {
6117
- 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;
6118
6269
  }
6119
- if (value && typeof value === "object") {
6120
- const objectValue = {};
6121
- for (const [key, entry] of Object.entries(value)) {
6122
- objectValue[key] = toJsonValue(entry);
6270
+ if (task.cancellation_reason) {
6271
+ payload.cancellation_reason = task.cancellation_reason;
6272
+ }
6273
+ const output = pickShellOutput(task);
6274
+ if (output) {
6275
+ payload[output.field] = output.content;
6276
+ if (output.cacheId) {
6277
+ payload.cache_id = output.cacheId;
6123
6278
  }
6124
- return objectValue;
6125
6279
  }
6126
- return String(value);
6280
+ return payload;
6127
6281
  };
6128
- var toShellTaskSummary = (task) => ({
6129
- task_id: task.task_id,
6130
- key: getShellTaskKey(task),
6131
- ...task.label ? { label: task.label } : {},
6132
- state: task.state,
6133
- ...task.title ? { title: task.title } : {},
6134
- ...task.working_directory ? { working_directory: task.working_directory } : {},
6135
- created_at: task.created_at,
6136
- updated_at: task.updated_at,
6137
- ...task.started_at ? { started_at: task.started_at } : {},
6138
- ...task.ended_at ? { ended_at: task.ended_at } : {},
6139
- exit_code: task.result?.exit_code ?? null,
6140
- duration_ms: task.result?.duration_ms ?? null,
6141
- result_available: isTerminalTaskState(task.state) && !!task.result,
6142
- ...task.failure_message ? { failure_message: task.failure_message } : {},
6282
+ var shellCancelPayload = (task) => ({
6283
+ ...shellBasePayload(task),
6143
6284
  ...task.cancellation_reason ? { cancellation_reason: task.cancellation_reason } : {},
6144
- ...task.cleanup_reason ? { cleanup_reason: task.cleanup_reason } : {}
6145
- });
6146
- var toShellTaskInfo = (task) => ({
6147
- ...toShellTaskSummary(task),
6148
- kind: task.kind,
6149
- workspace_mode: task.workspace_mode,
6150
- ...task.result?.child_session_id ?? task.child_session_id ? { child_session_id: task.result?.child_session_id ?? task.child_session_id } : {},
6151
- signal: task.result?.signal ?? null,
6152
- ...task.result?.summary ? { summary: task.result.summary } : {},
6153
- ...task.result?.stdout !== void 0 ? { stdout: task.result.stdout } : {},
6154
- ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
6155
- ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
6156
- ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
6157
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
6158
- ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
6159
- ...task.result?.artifacts ? { artifacts: toJsonValue(task.result.artifacts) } : {},
6160
- next_actions: buildShellTaskHints(getShellTaskKey(task), task.state)
6285
+ ...task.failure_message ? { failure_message: task.failure_message } : {}
6161
6286
  });
6162
6287
  var toShellListEntry = (task) => ({
6163
6288
  key: getShellTaskKey(task),
@@ -6190,7 +6315,10 @@ var resolveShellTask = async (tasks, input) => {
6190
6315
  const refs = matches.map((task) => task.task_id).join(", ");
6191
6316
  throw new Error(`multiple shell tasks matched key "${key}": ${refs}`);
6192
6317
  }
6193
- 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
+ );
6194
6322
  };
6195
6323
  var tailContentByLines = (content, tailLines) => {
6196
6324
  if (content.length === 0) {
@@ -6213,7 +6341,10 @@ var tailContentByLines = (content, tailLines) => {
6213
6341
  };
6214
6342
  var resolveShellLogs = async (options) => {
6215
6343
  const taskKey = getShellTaskKey(options.task);
6216
- 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
+ );
6217
6348
  if (live !== null) {
6218
6349
  if (options.tailLines !== void 0) {
6219
6350
  const tailed = tailContentByLines(live, options.tailLines);
@@ -6332,7 +6463,10 @@ var waitForManagedTask = async (tasks, taskId, signal) => {
6332
6463
  throw error;
6333
6464
  }
6334
6465
  };
6335
- var resolveShellWaitTimeoutSeconds = (value) => Math.max(1, Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS));
6466
+ var resolveShellWaitTimeoutSeconds = (value) => Math.max(
6467
+ 1,
6468
+ Math.min(Math.trunc(value ?? DEFAULT_TIMEOUT_SECONDS), MAX_TIMEOUT_SECONDS)
6469
+ );
6336
6470
  var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6337
6471
  let timeoutHandle;
6338
6472
  const waitPromise = waitForManagedTask(tasks, taskId, options.signal).then(
@@ -6377,9 +6511,9 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6377
6511
  };
6378
6512
  var createShellTool = (sandboxKey, options = {}) => {
6379
6513
  const shared = getSharedDeps(options);
6380
- return defineTool9({
6514
+ return defineTool10({
6381
6515
  name: "shell",
6382
- description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `background=true`, detach the wait and return task info you can inspect, wait on, or cancel later.",
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.",
6383
6517
  input: shellRunSchema,
6384
6518
  execute: async (input, ctx) => {
6385
6519
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6390,7 +6524,10 @@ var createShellTool = (sandboxKey, options = {}) => {
6390
6524
  }
6391
6525
  const label = normalizeOptionalLabel(input.label);
6392
6526
  const background = input.background ?? false;
6393
- const timeoutSeconds = resolveShellTimeoutSeconds(input.timeout, background);
6527
+ const timeoutSeconds = resolveShellTimeoutSeconds(
6528
+ input.timeout,
6529
+ background
6530
+ );
6394
6531
  const commandSummary = summarizeCommand(command);
6395
6532
  debugLog(
6396
6533
  `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
@@ -6419,19 +6556,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6419
6556
  })
6420
6557
  );
6421
6558
  if (background) {
6422
- return {
6423
- background: true,
6424
- task: toShellTaskInfo(task)
6425
- };
6559
+ return shellStatusPayload(task, { background: true });
6426
6560
  }
6427
- 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
+ );
6428
6566
  debugLog(
6429
6567
  `shell.done task_id=${task.task_id} state=${settled.state} duration_ms=${settled.result?.duration_ms ?? -1}`
6430
6568
  );
6431
- return {
6432
- background: false,
6433
- task: toShellTaskInfo(settled)
6434
- };
6569
+ return shellTerminalPayload(settled);
6435
6570
  } catch (error) {
6436
6571
  throw formatTaskError(error);
6437
6572
  }
@@ -6440,7 +6575,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6440
6575
  };
6441
6576
  var createShellListTool = (options = {}) => {
6442
6577
  const shared = getSharedDeps(options);
6443
- return defineTool9({
6578
+ return defineTool10({
6444
6579
  name: "shell_list",
6445
6580
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6446
6581
  input: shellListSchema,
@@ -6471,14 +6606,14 @@ var createShellListTool = (options = {}) => {
6471
6606
  };
6472
6607
  var createShellStatusTool = (options = {}) => {
6473
6608
  const shared = getSharedDeps(options);
6474
- return defineTool9({
6609
+ return defineTool10({
6475
6610
  name: "shell_status",
6476
- 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.",
6477
6612
  input: shellTaskKeySchema,
6478
6613
  execute: async (input) => {
6479
6614
  try {
6480
6615
  const task = await resolveShellTask(shared.tasks, input);
6481
- return { task: toShellTaskInfo(task) };
6616
+ return shellStatusPayload(task);
6482
6617
  } catch (error) {
6483
6618
  throw formatTaskError(error);
6484
6619
  }
@@ -6487,7 +6622,7 @@ var createShellStatusTool = (options = {}) => {
6487
6622
  };
6488
6623
  var createShellLogsTool = (options = {}) => {
6489
6624
  const shared = getSharedDeps(options);
6490
- return defineTool9({
6625
+ return defineTool10({
6491
6626
  name: "shell_logs",
6492
6627
  description: "Read recent stdout or stderr for a running or finished shell task.",
6493
6628
  input: shellLogsSchema,
@@ -6509,9 +6644,9 @@ var createShellLogsTool = (options = {}) => {
6509
6644
  };
6510
6645
  var createShellWaitTool = (options = {}) => {
6511
6646
  const shared = getSharedDeps(options);
6512
- return defineTool9({
6647
+ return defineTool10({
6513
6648
  name: "shell_wait",
6514
- description: "Wait for a shell task within a bounded window and return its retained outcome; if the window expires first, return still_running=true.",
6649
+ description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6515
6650
  input: shellWaitSchema,
6516
6651
  execute: async (input, ctx) => {
6517
6652
  try {
@@ -6527,11 +6662,13 @@ var createShellWaitTool = (options = {}) => {
6527
6662
  signal: ctx.signal
6528
6663
  }
6529
6664
  );
6530
- return {
6531
- ...result.aborted ? { aborted: true } : {},
6532
- ...result.stillRunning ? { still_running: true } : {},
6533
- task: toShellTaskInfo(result.task)
6534
- };
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);
6535
6672
  } catch (error) {
6536
6673
  throw formatTaskError(error);
6537
6674
  }
@@ -6540,14 +6677,14 @@ var createShellWaitTool = (options = {}) => {
6540
6677
  };
6541
6678
  var createShellResultTool = (options = {}) => {
6542
6679
  const shared = getSharedDeps(options);
6543
- return defineTool9({
6680
+ return defineTool10({
6544
6681
  name: "shell_result",
6545
- description: "Read the retained terminal result for a shell task.",
6682
+ description: "Read the retained terminal result for a shell task as compact JSON.",
6546
6683
  input: shellTaskKeySchema,
6547
6684
  execute: async (input) => {
6548
6685
  try {
6549
6686
  const task = await resolveShellTask(shared.tasks, input);
6550
- return { task: toShellTaskInfo(task) };
6687
+ return isTerminalTaskState(task.state) ? shellTerminalPayload(task) : shellStatusPayload(task);
6551
6688
  } catch (error) {
6552
6689
  throw formatTaskError(error);
6553
6690
  }
@@ -6556,9 +6693,9 @@ var createShellResultTool = (options = {}) => {
6556
6693
  };
6557
6694
  var createShellCancelTool = (options = {}) => {
6558
6695
  const shared = getSharedDeps(options);
6559
- return defineTool9({
6696
+ return defineTool10({
6560
6697
  name: "shell_cancel",
6561
- 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.",
6562
6699
  input: shellTaskKeySchema,
6563
6700
  execute: async (input) => {
6564
6701
  try {
@@ -6566,7 +6703,7 @@ var createShellCancelTool = (options = {}) => {
6566
6703
  const cancelled = await shared.tasks.cancel(task.task_id, {
6567
6704
  reason: "cancelled"
6568
6705
  });
6569
- return { task: toShellTaskInfo(cancelled) };
6706
+ return shellCancelPayload(cancelled);
6570
6707
  } catch (error) {
6571
6708
  throw formatTaskError(error);
6572
6709
  }
@@ -6575,16 +6712,16 @@ var createShellCancelTool = (options = {}) => {
6575
6712
  };
6576
6713
 
6577
6714
  // src/tools/skill-load.ts
6578
- import { defineTool as defineTool10 } from "@codelia/core";
6579
- import { z as z11 } from "zod";
6580
- var SkillLoadInputSchema = z11.object({
6581
- name: z11.string().min(1).optional().describe("Exact skill name to load."),
6582
- 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.")
6583
6720
  }).refine((value) => !!value.name || !!value.path, {
6584
6721
  message: "name or path is required",
6585
6722
  path: ["name"]
6586
6723
  });
6587
- var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6724
+ var createSkillLoadTool = (skillsResolverKey) => defineTool11({
6588
6725
  name: "skill_load",
6589
6726
  description: "Load full SKILL.md content by exact name or path.",
6590
6727
  input: SkillLoadInputSchema,
@@ -6630,15 +6767,15 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6630
6767
  });
6631
6768
 
6632
6769
  // src/tools/skill-search.ts
6633
- import { defineTool as defineTool11 } from "@codelia/core";
6634
- import { z as z12 } from "zod";
6635
- var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6770
+ import { defineTool as defineTool12 } from "@codelia/core";
6771
+ import { z as z13 } from "zod";
6772
+ var createSkillSearchTool = (skillsResolverKey) => defineTool12({
6636
6773
  name: "skill_search",
6637
6774
  description: "Search installed local skills by name, description, or path.",
6638
- input: z12.object({
6639
- query: z12.string().min(1).describe("Search query text."),
6640
- limit: z12.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6641
- 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.")
6642
6779
  }),
6643
6780
  execute: async (input, ctx) => {
6644
6781
  try {
@@ -6661,8 +6798,8 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6661
6798
  });
6662
6799
 
6663
6800
  // src/tools/todo-mutate.ts
6664
- import { defineTool as defineTool12 } from "@codelia/core";
6665
- import { z as z13 } from "zod";
6801
+ import { defineTool as defineTool13 } from "@codelia/core";
6802
+ import { z as z14 } from "zod";
6666
6803
 
6667
6804
  // src/tools/todo-store.ts
6668
6805
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6772,37 +6909,37 @@ var pickNextTodo = (todos) => {
6772
6909
  var todoStore = /* @__PURE__ */ new Map();
6773
6910
 
6774
6911
  // src/tools/todo-mutate.ts
6775
- var todoStatusSchema = z13.enum(["pending", "in_progress", "completed"]);
6776
- var todoPrioritySchema = z13.number().int().min(1).max(5);
6777
- var todoItemSchema = z13.object({
6778
- id: z13.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6779
- 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."),
6780
6917
  status: todoStatusSchema.describe("Todo status."),
6781
6918
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6782
- notes: z13.string().optional().describe("Optional implementation notes."),
6783
- 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.")
6784
6921
  });
6785
- var todoPatchItemSchema = z13.object({
6786
- id: z13.string().min(1).describe("Target todo ID."),
6787
- remove: z13.boolean().optional().describe("Set true to remove the todo item."),
6788
- 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)."),
6789
6926
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6790
6927
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6791
- notes: z13.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6792
- 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(
6793
6930
  "Updated in-progress phrasing (null keeps current, empty clears)."
6794
6931
  )
6795
6932
  });
6796
- var todoNewInputSchema = z13.object({
6797
- 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.")
6798
6935
  }).strict();
6799
- var todoAppendInputSchema = z13.object({
6800
- 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.")
6801
6938
  }).strict();
6802
- var todoPatchInputSchema = z13.object({
6803
- 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.")
6804
6941
  }).strict();
6805
- var todoClearInputSchema = z13.object({}).strict();
6942
+ var todoClearInputSchema = z14.object({}).strict();
6806
6943
  var statusSymbol = {
6807
6944
  pending: "[ ]",
6808
6945
  in_progress: "[>]",
@@ -6897,7 +7034,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
6897
7034
  }
6898
7035
  return formatSuccess(outputMode, nextTodos);
6899
7036
  };
6900
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool12({
7037
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool13({
6901
7038
  name,
6902
7039
  description,
6903
7040
  input,
@@ -6914,11 +7051,7 @@ var createTodoNewTool = (sandboxKey, sessionContextKey) => createTodoMutationToo
6914
7051
  "todo_new",
6915
7052
  "Start or replace the in-session todo plan with a full task list.",
6916
7053
  todoNewInputSchema,
6917
- (sessionId, input) => applyTodoMutation(
6918
- sessionId,
6919
- { mode: "new", todos: input.todos },
6920
- "new"
6921
- ),
7054
+ (sessionId, input) => applyTodoMutation(sessionId, { mode: "new", todos: input.todos }, "new"),
6922
7055
  sandboxKey,
6923
7056
  sessionContextKey
6924
7057
  );
@@ -6956,17 +7089,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
6956
7089
  );
6957
7090
 
6958
7091
  // src/tools/todo-read.ts
6959
- import { defineTool as defineTool13 } from "@codelia/core";
6960
- import { z as z14 } from "zod";
7092
+ import { defineTool as defineTool14 } from "@codelia/core";
7093
+ import { z as z15 } from "zod";
6961
7094
  var statusSymbol2 = {
6962
7095
  pending: "[ ]",
6963
7096
  in_progress: "[>]",
6964
7097
  completed: "[x]"
6965
7098
  };
6966
- var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7099
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
6967
7100
  name: "todo_read",
6968
7101
  description: "Read the in-session todo plan with execution order and next step.",
6969
- input: z14.object({}),
7102
+ input: z15.object({}),
6970
7103
  execute: async (_input, ctx) => {
6971
7104
  const sandbox = await getSandboxContext(ctx, sandboxKey);
6972
7105
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -7002,15 +7135,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7002
7135
  });
7003
7136
 
7004
7137
  // src/tools/tool-output-cache.ts
7005
- import { defineTool as defineTool14 } from "@codelia/core";
7006
- import { z as z15 } from "zod";
7007
- var createToolOutputCacheTool = (store) => defineTool14({
7138
+ import { defineTool as defineTool15 } from "@codelia/core";
7139
+ import { z as z16 } from "zod";
7140
+ var createToolOutputCacheTool = (store) => defineTool15({
7008
7141
  name: "tool_output_cache",
7009
7142
  description: "Read cached tool output by ref_id.",
7010
- input: z15.object({
7011
- ref_id: z15.string().describe("Tool output reference ID."),
7012
- offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7013
- 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.")
7014
7147
  }),
7015
7148
  execute: async (input) => {
7016
7149
  if (!store.read) {
@@ -7026,14 +7159,14 @@ var createToolOutputCacheTool = (store) => defineTool14({
7026
7159
  }
7027
7160
  }
7028
7161
  });
7029
- var createToolOutputCacheLineTool = (store) => defineTool14({
7162
+ var createToolOutputCacheLineTool = (store) => defineTool15({
7030
7163
  name: "tool_output_cache_line",
7031
7164
  description: "Read a single cached output line segment by line number and char offset.",
7032
- input: z15.object({
7033
- ref_id: z15.string().describe("Tool output reference ID."),
7034
- line_number: z15.number().int().positive().describe("1-based line number to read."),
7035
- char_offset: z15.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7036
- 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.")
7037
7170
  }),
7038
7171
  execute: async (input) => {
7039
7172
  if (!store.readLine) {
@@ -7050,16 +7183,16 @@ var createToolOutputCacheLineTool = (store) => defineTool14({
7050
7183
  }
7051
7184
  }
7052
7185
  });
7053
- var createToolOutputCacheGrepTool = (store) => defineTool14({
7186
+ var createToolOutputCacheGrepTool = (store) => defineTool15({
7054
7187
  name: "tool_output_cache_grep",
7055
7188
  description: "Search cached tool output by ref_id.",
7056
- input: z15.object({
7057
- ref_id: z15.string().describe("Tool output reference ID."),
7058
- pattern: z15.string().describe("Text or regex pattern to search for."),
7059
- regex: z15.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7060
- before: z15.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7061
- after: z15.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7062
- 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.")
7063
7196
  }),
7064
7197
  execute: async (input) => {
7065
7198
  if (!store.grep) {
@@ -7079,74 +7212,6 @@ var createToolOutputCacheGrepTool = (store) => defineTool14({
7079
7212
  }
7080
7213
  });
7081
7214
 
7082
- // src/tools/read-line.ts
7083
- import { promises as fs14 } from "fs";
7084
- import { defineTool as defineTool15 } from "@codelia/core";
7085
- import { z as z16 } from "zod";
7086
- var DEFAULT_CHAR_LIMIT = 1e4;
7087
- var MAX_CHAR_LIMIT = 1e5;
7088
- var createReadLineTool = (sandboxKey) => defineTool15({
7089
- name: "read_line",
7090
- description: "Read a single line segment by 1-based line number and 0-based char offset.",
7091
- input: z16.object({
7092
- file_path: z16.string().describe("File path under the sandbox root."),
7093
- line_number: z16.number().int().positive().describe("1-based line number to read."),
7094
- char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7095
- char_limit: z16.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
7096
- }),
7097
- execute: async (input, ctx) => {
7098
- let resolved;
7099
- try {
7100
- const sandbox = await getSandboxContext(ctx, sandboxKey);
7101
- resolved = sandbox.resolvePath(input.file_path);
7102
- } catch (error) {
7103
- return `Security error: ${String(error)}`;
7104
- }
7105
- try {
7106
- const stat = await fs14.stat(resolved);
7107
- if (stat.isDirectory()) {
7108
- return `Path is a directory: ${input.file_path}`;
7109
- }
7110
- } catch {
7111
- return `File not found: ${input.file_path}`;
7112
- }
7113
- try {
7114
- const content = await fs14.readFile(resolved, "utf8");
7115
- const lines = content.split(/\r?\n/);
7116
- const lineIndex = input.line_number - 1;
7117
- if (lineIndex >= lines.length) {
7118
- return `Line number out of range: ${input.line_number} (total ${lines.length})`;
7119
- }
7120
- const line = lines[lineIndex] ?? "";
7121
- const charOffset = input.char_offset ?? 0;
7122
- const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
7123
- if (charOffset > line.length) {
7124
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
7125
- }
7126
- const segment = line.slice(charOffset, charOffset + charLimit);
7127
- const endOffset = charOffset + segment.length;
7128
- const hasMore = endOffset < line.length;
7129
- const header = [
7130
- `line_number=${input.line_number}`,
7131
- `line_length=${line.length}`,
7132
- `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
7133
- ].join(" ");
7134
- let output = `${header}
7135
- ${segment}`;
7136
- if (hasMore) {
7137
- output += `
7138
-
7139
- Use char_offset=${endOffset} to continue.`;
7140
- output += `
7141
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
7142
- }
7143
- return output;
7144
- } catch (error) {
7145
- return `Error reading file: ${String(error)}`;
7146
- }
7147
- }
7148
- });
7149
-
7150
7215
  // src/tools/write.ts
7151
7216
  import { promises as fs15 } from "fs";
7152
7217
  import path13 from "path";
@@ -7165,7 +7230,9 @@ var createWriteTool = (sandboxKey) => defineTool16({
7165
7230
  name: "write",
7166
7231
  description: "Write text to a file, creating parent directories if needed.",
7167
7232
  input: z17.object({
7168
- 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
+ ),
7169
7236
  content: z17.string().describe("UTF-8 text content to write.")
7170
7237
  }),
7171
7238
  execute: async (input, ctx) => {
@@ -7174,7 +7241,7 @@ var createWriteTool = (sandboxKey) => defineTool16({
7174
7241
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7175
7242
  resolved = sandbox.resolvePath(input.file_path);
7176
7243
  } catch (error) {
7177
- return `Security error: ${String(error)}`;
7244
+ throw new Error(`Security error: ${String(error)}`);
7178
7245
  }
7179
7246
  try {
7180
7247
  await fs15.mkdir(path13.dirname(resolved), { recursive: true });
@@ -7669,9 +7736,21 @@ var createAgentFactory = (state, options = {}) => {
7669
7736
  if (state.agent) return state.agent;
7670
7737
  if (inFlight) return inFlight;
7671
7738
  inFlight = (async () => {
7672
- const rootDir = process.env.CODELIA_SANDBOX_ROOT;
7673
- const ctx = await SandboxContext.create(rootDir);
7674
- 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
+ );
7675
7754
  const agentsResolver = state.agentsResolver ?? await AgentsResolver.create(ctx.workingDir);
7676
7755
  state.agentsResolver = agentsResolver;
7677
7756
  let skillsConfig;
@@ -7746,13 +7825,6 @@ var createAgentFactory = (state, options = {}) => {
7746
7825
  const message = error instanceof Error ? error.message : String(error);
7747
7826
  throw new Error(message);
7748
7827
  }
7749
- const approvalModeResolution = await resolveApprovalModeForRuntime({
7750
- workingDir: ctx.workingDir,
7751
- runtimeSandboxRoot: state.runtimeSandboxRoot,
7752
- requestStartupSelection: async ({ projectKey }) => {
7753
- return requestApprovalModeStartupSelection(state, projectKey);
7754
- }
7755
- });
7756
7828
  const permissionService = new PermissionService({
7757
7829
  approvalMode: approvalModeResolution.approvalMode,
7758
7830
  system: buildSystemPermissions(approvalModeResolution.approvalMode),
@@ -8087,6 +8159,9 @@ var createAgentFactory = (state, options = {}) => {
8087
8159
  return { decision: "allow" };
8088
8160
  }
8089
8161
  });
8162
+ if (approvalModeResolution.persistSelection) {
8163
+ await approvalModeResolution.persistSelection();
8164
+ }
8090
8165
  state.agent = agent;
8091
8166
  return agent;
8092
8167
  })();
@@ -11053,7 +11128,7 @@ import {
11053
11128
  ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl3
11054
11129
  } from "@codelia/storage";
11055
11130
  var COMMAND_PREVIEW_CHARS = 400;
11056
- var DEFAULT_TRUNCATED2 = {
11131
+ var DEFAULT_TRUNCATED = {
11057
11132
  stdout: false,
11058
11133
  stderr: false,
11059
11134
  combined: false
@@ -11191,12 +11266,12 @@ var toShellExecResult = (commandPreview, result) => ({
11191
11266
  signal: result?.signal ?? null,
11192
11267
  stdout: result?.stdout ?? "",
11193
11268
  stderr: result?.stderr ?? "",
11194
- truncated: result?.truncated ?? DEFAULT_TRUNCATED2,
11269
+ truncated: result?.truncated ?? DEFAULT_TRUNCATED,
11195
11270
  duration_ms: result?.duration_ms ?? 0,
11196
11271
  ...result?.stdout_cache_id ? { stdout_cache_id: result.stdout_cache_id } : {},
11197
11272
  ...result?.stderr_cache_id ? { stderr_cache_id: result.stderr_cache_id } : {}
11198
11273
  });
11199
- var toShellTaskInfo2 = (task) => ({
11274
+ var toShellTaskInfo = (task) => ({
11200
11275
  task_id: task.task_id,
11201
11276
  state: task.state,
11202
11277
  command_preview: task.title,
@@ -11209,7 +11284,7 @@ var toShellTaskInfo2 = (task) => ({
11209
11284
  signal: task.result?.signal ?? null,
11210
11285
  stdout: task.result?.stdout ?? "",
11211
11286
  stderr: task.result?.stderr ?? "",
11212
- truncated: task.result?.truncated ?? DEFAULT_TRUNCATED2,
11287
+ truncated: task.result?.truncated ?? DEFAULT_TRUNCATED,
11213
11288
  duration_ms: task.result?.duration_ms ?? null,
11214
11289
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11215
11290
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
@@ -11255,7 +11330,10 @@ var sendTaskError = (id, error) => {
11255
11330
  var requireShellTask = async (taskManager, taskId) => {
11256
11331
  const task = await taskManager.status(taskId);
11257
11332
  if (!task || task.kind !== "shell") {
11258
- 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
+ );
11259
11337
  }
11260
11338
  return task;
11261
11339
  };
@@ -11413,7 +11491,7 @@ var createShellHandlers = ({
11413
11491
  const handleShellStart = async (id, params) => {
11414
11492
  try {
11415
11493
  const { task } = await spawnShell(params, "shell.start");
11416
- sendResult(id, toShellTaskInfo2(task));
11494
+ sendResult(id, toShellTaskInfo(task));
11417
11495
  } catch (error) {
11418
11496
  if (typeof error === "object" && error !== null && "code" in error && "message" in error) {
11419
11497
  sendError(id, error);
@@ -11433,7 +11511,7 @@ var createShellHandlers = ({
11433
11511
  }
11434
11512
  try {
11435
11513
  const limit = requestedLimit ? Math.trunc(requestedLimit) : void 0;
11436
- 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);
11437
11515
  const result = { tasks };
11438
11516
  sendResult(id, result);
11439
11517
  } catch (error) {
@@ -11451,7 +11529,7 @@ var createShellHandlers = ({
11451
11529
  }
11452
11530
  try {
11453
11531
  const task = await requireShellTask(shellTaskManager, taskId);
11454
- sendResult(id, toShellTaskInfo2(task));
11532
+ sendResult(id, toShellTaskInfo(task));
11455
11533
  } catch (error) {
11456
11534
  sendTaskError(id, error);
11457
11535
  }
@@ -11524,23 +11602,23 @@ var createShellHandlers = ({
11524
11602
  try {
11525
11603
  const existing = await requireShellTask(shellTaskManager, taskId);
11526
11604
  if (isTerminalTaskState(existing.state)) {
11527
- sendResult(id, toShellTaskInfo2(existing));
11605
+ sendResult(id, toShellTaskInfo(existing));
11528
11606
  return;
11529
11607
  }
11530
11608
  const controller = new AbortController();
11531
11609
  let timeoutHandle;
11532
11610
  let resolveDetached;
11533
- const detachPromise = new Promise(
11611
+ const detachPromise = new Promise((resolve) => {
11612
+ resolveDetached = (result) => resolve({ type: "detached", result });
11613
+ });
11614
+ const timeoutPromise = new Promise(
11534
11615
  (resolve) => {
11535
- resolveDetached = (result) => resolve({ type: "detached", result });
11616
+ timeoutHandle = setTimeout(() => {
11617
+ controller.abort();
11618
+ resolve({ type: "still_running" });
11619
+ }, waitTimeoutSeconds * 1e3);
11536
11620
  }
11537
11621
  );
11538
- const timeoutPromise = new Promise((resolve) => {
11539
- timeoutHandle = setTimeout(() => {
11540
- controller.abort();
11541
- resolve({ type: "still_running" });
11542
- }, waitTimeoutSeconds * 1e3);
11543
- });
11544
11622
  const unregister = registerActiveShellWait(taskId, {
11545
11623
  detach: (task) => {
11546
11624
  resolveDetached({
@@ -11570,7 +11648,7 @@ var createShellHandlers = ({
11570
11648
  if (outcome.type === "still_running") {
11571
11649
  const task = await requireShellTask(shellTaskManager, taskId);
11572
11650
  sendResult(id, {
11573
- ...toShellTaskInfo2(task),
11651
+ ...toShellTaskInfo(task),
11574
11652
  ...isTerminalTaskState(task.state) ? {} : { still_running: true }
11575
11653
  });
11576
11654
  return;
@@ -11578,7 +11656,7 @@ var createShellHandlers = ({
11578
11656
  if (outcome.type === "aborted") {
11579
11657
  return;
11580
11658
  }
11581
- sendResult(id, toShellTaskInfo2(outcome.task));
11659
+ sendResult(id, toShellTaskInfo(outcome.task));
11582
11660
  } finally {
11583
11661
  if (timeoutHandle) {
11584
11662
  clearTimeout(timeoutHandle);
@@ -11635,7 +11713,7 @@ var createShellHandlers = ({
11635
11713
  const task = await shellTaskManager.cancel(taskId, {
11636
11714
  reason: "cancelled"
11637
11715
  });
11638
- sendResult(id, toShellTaskInfo2(task));
11716
+ sendResult(id, toShellTaskInfo(task));
11639
11717
  } catch (error) {
11640
11718
  sendTaskError(id, error);
11641
11719
  }
@@ -11722,7 +11800,7 @@ import {
11722
11800
  RPC_ERROR_CODE as RPC_ERROR_CODE7
11723
11801
  } from "@codelia/protocol";
11724
11802
  import { ToolOutputCacheStoreImpl as ToolOutputCacheStoreImpl4 } from "@codelia/storage";
11725
- var DEFAULT_TRUNCATED3 = {
11803
+ var DEFAULT_TRUNCATED2 = {
11726
11804
  stdout: false,
11727
11805
  stderr: false,
11728
11806
  combined: false
@@ -11828,7 +11906,7 @@ var toTaskInfo = (task) => ({
11828
11906
  ...task.result?.stderr !== void 0 ? { stderr: task.result.stderr } : {},
11829
11907
  ...task.result?.stdout_cache_id ? { stdout_cache_id: task.result.stdout_cache_id } : {},
11830
11908
  ...task.result?.stderr_cache_id ? { stderr_cache_id: task.result.stderr_cache_id } : {},
11831
- ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED3 },
11909
+ ...task.result?.truncated ? { truncated: task.result.truncated } : { truncated: DEFAULT_TRUNCATED2 },
11832
11910
  ...task.result?.worktree_path ? { worktree_path: task.result.worktree_path } : {},
11833
11911
  ...task.result?.artifacts ? { artifacts: task.result.artifacts } : {}
11834
11912
  });
@@ -12751,7 +12829,9 @@ var startRuntime = () => {
12751
12829
  `tasks.shutdown reason=${reason} cancelled=${result.cancelled} errors=${result.errors.length}`
12752
12830
  );
12753
12831
  for (const error of result.errors) {
12754
- 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
+ );
12755
12835
  }
12756
12836
  }
12757
12837
  })();