@codelia/runtime 0.1.53 → 0.1.55

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 +1502 -459
  2. package/dist/index.js +1481 -438
  3. package/package.json +9 -9
package/dist/index.cjs CHANGED
@@ -27,8 +27,8 @@ var import_node_path18 = __toESM(require("path"), 1);
27
27
  var import_storage14 = require("@codelia/storage");
28
28
 
29
29
  // src/agent-factory.ts
30
- var import_node_fs16 = require("fs");
31
- var import_core19 = require("@codelia/core");
30
+ var import_node_fs15 = require("fs");
31
+ var import_core20 = require("@codelia/core");
32
32
  var import_model_metadata2 = require("@codelia/model-metadata");
33
33
  var import_shared_types2 = require("@codelia/shared-types");
34
34
  var import_storage8 = require("@codelia/storage");
@@ -2661,8 +2661,7 @@ var parseRawArgsForPrompt = (rawArgs) => parseRawArgsObject(rawArgs);
2661
2661
  var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2662
2662
  "read",
2663
2663
  "read_line",
2664
- "grep",
2665
- "glob_search",
2664
+ "view_image",
2666
2665
  "todo_read",
2667
2666
  "todo_new",
2668
2667
  "todo_append",
@@ -2687,7 +2686,8 @@ var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2687
2686
  var SYSTEM_TOOL_ALLOWLIST_TRUSTED = [
2688
2687
  ...SYSTEM_TOOL_ALLOWLIST_MINIMAL,
2689
2688
  "write",
2690
- "edit"
2689
+ "edit",
2690
+ "apply_patch"
2691
2691
  ];
2692
2692
  var SYSTEM_SHELL_ALLOWLIST = [
2693
2693
  "pwd",
@@ -2799,7 +2799,7 @@ var PermissionService = class {
2799
2799
  const target = filePath || "(unknown path)";
2800
2800
  return {
2801
2801
  title: "Run tool?",
2802
- message: `write ${target} (${content.length} bytes)${rememberPreview}`
2802
+ message: `write ${target} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
2803
2803
  };
2804
2804
  }
2805
2805
  if (toolName === "edit") {
@@ -2812,6 +2812,32 @@ var PermissionService = class {
2812
2812
  message: `edit ${target} (match=${mode})${rememberPreview}`
2813
2813
  };
2814
2814
  }
2815
+ if (toolName === "apply_patch") {
2816
+ const parsed = parseRawArgsForPrompt(rawArgs);
2817
+ const patch = parsed && typeof parsed.patch === "string" ? parsed.patch : "";
2818
+ const lineCount = patch ? patch.split(/\r?\n/).length : 0;
2819
+ return {
2820
+ title: "Run tool?",
2821
+ message: `apply_patch (${lineCount} line${lineCount === 1 ? "" : "s"})${rememberPreview}`
2822
+ };
2823
+ }
2824
+ if (toolName === "view_image") {
2825
+ const parsed = parseRawArgsForPrompt(rawArgs);
2826
+ const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
2827
+ return {
2828
+ title: "Run tool?",
2829
+ message: `view_image ${filePath || "(unknown path)"}${rememberPreview}`
2830
+ };
2831
+ }
2832
+ if (toolName === "webfetch") {
2833
+ const parsed = parseRawArgsForPrompt(rawArgs);
2834
+ const url = parsed && typeof parsed.url === "string" ? parsed.url.trim() : "";
2835
+ const format = parsed && typeof parsed.output_format === "string" ? parsed.output_format : "markdown";
2836
+ return {
2837
+ title: "Run tool?",
2838
+ message: `webfetch ${url || "(unknown url)"} (${format})${rememberPreview}`
2839
+ };
2840
+ }
2815
2841
  return { title: "Run tool?", message: toolName };
2816
2842
  }
2817
2843
  evaluate(toolName, rawArgs) {
@@ -3674,30 +3700,96 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => (0, import_core
3674
3700
  }
3675
3701
  });
3676
3702
 
3677
- // src/tools/done.ts
3678
- var import_core4 = require("@codelia/core");
3679
- var import_zod3 = require("zod");
3680
- var createDoneTool = () => (0, import_core4.defineTool)({
3681
- name: "done",
3682
- description: "Mark the task as complete and return a final message.",
3683
- input: import_zod3.z.object({
3684
- message: import_zod3.z.string().describe("Final user-facing completion message.")
3685
- }),
3686
- execute: async (input) => {
3687
- throw new import_core4.TaskComplete(input.message);
3688
- }
3689
- });
3690
-
3691
- // src/tools/edit.ts
3692
- var import_node_crypto3 = __toESM(require("crypto"), 1);
3703
+ // src/tools/apply-patch.ts
3693
3704
  var import_node_fs7 = require("fs");
3694
3705
  var import_node_path8 = __toESM(require("path"), 1);
3695
- var import_core5 = require("@codelia/core");
3696
- var import_zod4 = require("zod");
3706
+ var import_core4 = require("@codelia/core");
3707
+ var import_zod3 = require("zod");
3697
3708
 
3698
3709
  // src/utils/diff.ts
3710
+ var DEFAULT_DIFF_PREVIEW_LINES = 120;
3711
+ var DEFAULT_DIFF_PREVIEW_BYTES = 16 * 1024;
3699
3712
  var normalizeLineEndings = (text) => text.replace(/\r\n/g, "\n");
3700
3713
  var toLines = (text) => text === "" ? [] : text.split("\n");
3714
+ var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
3715
+ var truncateUtf8Prefix = (value, maxBytes) => {
3716
+ if (maxBytes <= 0 || value.length === 0) return "";
3717
+ let bytes = 0;
3718
+ let out = "";
3719
+ for (const ch of value) {
3720
+ const next = utf8ByteLength(ch);
3721
+ if (bytes + next > maxBytes) break;
3722
+ out += ch;
3723
+ bytes += next;
3724
+ }
3725
+ return out;
3726
+ };
3727
+ var truncateUtf8Suffix = (value, maxBytes) => {
3728
+ if (maxBytes <= 0 || value.length === 0) return "";
3729
+ let bytes = 0;
3730
+ const chars = Array.from(value);
3731
+ const out = [];
3732
+ for (let index = chars.length - 1; index >= 0; index -= 1) {
3733
+ const ch = chars[index];
3734
+ const next = utf8ByteLength(ch);
3735
+ if (bytes + next > maxBytes) break;
3736
+ out.push(ch);
3737
+ bytes += next;
3738
+ }
3739
+ out.reverse();
3740
+ return out.join("");
3741
+ };
3742
+ var excerptByLines = (value, maxLines) => {
3743
+ const lines = value.split(/\r?\n/);
3744
+ if (lines.length <= maxLines) {
3745
+ return { text: value, truncated: false };
3746
+ }
3747
+ const headCount = Math.ceil(maxLines / 2);
3748
+ const tailCount = Math.floor(maxLines / 2);
3749
+ const omitted = lines.length - headCount - tailCount;
3750
+ return {
3751
+ text: [
3752
+ ...lines.slice(0, headCount),
3753
+ `...[${omitted} lines omitted]...`,
3754
+ ...lines.slice(lines.length - tailCount)
3755
+ ].join("\n"),
3756
+ truncated: true
3757
+ };
3758
+ };
3759
+ var excerptByBytes = (value, maxBytes) => {
3760
+ if (utf8ByteLength(value) <= maxBytes) {
3761
+ return { text: value, truncated: false };
3762
+ }
3763
+ const marker = "\n...[truncated by size]...\n";
3764
+ const markerBytes = utf8ByteLength(marker);
3765
+ if (maxBytes <= markerBytes + 2) {
3766
+ return {
3767
+ text: truncateUtf8Prefix(value, maxBytes),
3768
+ truncated: true
3769
+ };
3770
+ }
3771
+ const budget = maxBytes - markerBytes;
3772
+ const headBytes = Math.floor(budget / 2);
3773
+ const tailBytes = budget - headBytes;
3774
+ return {
3775
+ text: `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`,
3776
+ truncated: true
3777
+ };
3778
+ };
3779
+ var summarizeDiff = (diff, options = {}) => {
3780
+ const lineExcerpt = excerptByLines(
3781
+ diff,
3782
+ options.maxLines ?? DEFAULT_DIFF_PREVIEW_LINES
3783
+ );
3784
+ const byteExcerpt = excerptByBytes(
3785
+ lineExcerpt.text,
3786
+ options.maxBytes ?? DEFAULT_DIFF_PREVIEW_BYTES
3787
+ );
3788
+ return {
3789
+ preview: byteExcerpt.text,
3790
+ truncated: lineExcerpt.truncated || byteExcerpt.truncated
3791
+ };
3792
+ };
3701
3793
  var createUnifiedDiff = (filePath, before, after, context = 3) => {
3702
3794
  const oldText = normalizeLineEndings(before);
3703
3795
  const newText = normalizeLineEndings(after);
@@ -3746,7 +3838,657 @@ var createUnifiedDiff = (filePath, before, after, context = 3) => {
3746
3838
  ${lines.join("\n")}`;
3747
3839
  };
3748
3840
 
3841
+ // src/tools/diff-payload.ts
3842
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
3843
+ var buildDiffPayload = async (options) => {
3844
+ if (!options.diff) {
3845
+ return {
3846
+ diff: options.emptyDiff ?? ""
3847
+ };
3848
+ }
3849
+ const summarized = summarizeDiff(options.diff);
3850
+ if (!summarized.truncated) {
3851
+ return { diff: summarized.preview };
3852
+ }
3853
+ if (!options.outputCacheStore) {
3854
+ return {
3855
+ diff: summarized.preview,
3856
+ diff_truncated: true
3857
+ };
3858
+ }
3859
+ try {
3860
+ const saved = await options.outputCacheStore.save({
3861
+ tool_call_id: `${options.toolName}_diff_${import_node_crypto3.default.randomUUID()}`,
3862
+ tool_name: options.toolName,
3863
+ content: options.diff
3864
+ });
3865
+ return {
3866
+ diff: summarized.preview,
3867
+ diff_truncated: true,
3868
+ diff_cache_id: saved.id
3869
+ };
3870
+ } catch (error) {
3871
+ const message = `Failed to persist full diff: ${String(error)}`;
3872
+ const context = options.debugContext ? ` ${options.debugContext}` : "";
3873
+ (0, import_logger.debugLog)(
3874
+ `${options.toolName}.diff_cache_save_failed${context} error=${String(error)}`
3875
+ );
3876
+ return {
3877
+ diff: summarized.preview,
3878
+ diff_truncated: true,
3879
+ diff_cache_error: message
3880
+ };
3881
+ }
3882
+ };
3883
+
3884
+ // src/tools/apply-patch.ts
3885
+ var BEGIN_MARKER = "*** Begin Patch";
3886
+ var END_MARKER = "*** End Patch";
3887
+ var END_OF_FILE_MARKER = "*** End of File";
3888
+ var normalizePatchText = (value) => value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3889
+ var isFileHeader = (line) => line.startsWith("*** Add File: ") || line.startsWith("*** Delete File: ") || line.startsWith("*** Update File: ");
3890
+ var requirePatchPath = (kind, value) => {
3891
+ const trimmed = value.trim();
3892
+ if (!trimmed) {
3893
+ throw new Error(`Patch parse failed: missing path in ${kind}`);
3894
+ }
3895
+ return trimmed;
3896
+ };
3897
+ var parsePatchHeader = (line) => {
3898
+ if (line.startsWith("*** Add File: ")) {
3899
+ return {
3900
+ kind: "add",
3901
+ filePath: requirePatchPath(
3902
+ "Add File",
3903
+ line.slice("*** Add File: ".length)
3904
+ )
3905
+ };
3906
+ }
3907
+ if (line.startsWith("*** Delete File: ")) {
3908
+ return {
3909
+ kind: "delete",
3910
+ filePath: requirePatchPath(
3911
+ "Delete File",
3912
+ line.slice("*** Delete File: ".length)
3913
+ )
3914
+ };
3915
+ }
3916
+ if (line.startsWith("*** Update File: ")) {
3917
+ return {
3918
+ kind: "update",
3919
+ filePath: requirePatchPath(
3920
+ "Update File",
3921
+ line.slice("*** Update File: ".length)
3922
+ )
3923
+ };
3924
+ }
3925
+ return null;
3926
+ };
3927
+ var parseAddFileLines = (lines, startIndex, endIndex) => {
3928
+ const output = [];
3929
+ let index = startIndex;
3930
+ while (index < endIndex) {
3931
+ const line = lines[index] ?? "";
3932
+ if (isFileHeader(line) || line === END_MARKER) {
3933
+ break;
3934
+ }
3935
+ if (!line.startsWith("+")) {
3936
+ throw new Error(
3937
+ `Patch parse failed: add file lines must start with '+' (line ${index + 1})`
3938
+ );
3939
+ }
3940
+ output.push(line.slice(1));
3941
+ index += 1;
3942
+ }
3943
+ return { lines: output, nextIndex: index };
3944
+ };
3945
+ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
3946
+ const chunks = [];
3947
+ let index = startIndex;
3948
+ while (index < endIndex) {
3949
+ const line = lines[index] ?? "";
3950
+ if (isFileHeader(line) || line === END_MARKER) {
3951
+ break;
3952
+ }
3953
+ if (line.trim() === "") {
3954
+ index += 1;
3955
+ continue;
3956
+ }
3957
+ if (!line.startsWith("@@")) {
3958
+ throw new Error(
3959
+ `Patch parse failed: expected '@@' chunk header (line ${index + 1})`
3960
+ );
3961
+ }
3962
+ const changeContext = line.slice(2).trimStart() || void 0;
3963
+ index += 1;
3964
+ const oldLines = [];
3965
+ const newLines = [];
3966
+ let hasModification = false;
3967
+ let isEndOfFile = false;
3968
+ while (index < endIndex) {
3969
+ const bodyLine = lines[index] ?? "";
3970
+ if (bodyLine.startsWith("@@") || isFileHeader(bodyLine) || bodyLine === END_MARKER) {
3971
+ break;
3972
+ }
3973
+ if (bodyLine === END_OF_FILE_MARKER) {
3974
+ isEndOfFile = true;
3975
+ index += 1;
3976
+ break;
3977
+ }
3978
+ const marker = bodyLine[0];
3979
+ const content = bodyLine.slice(1);
3980
+ switch (marker) {
3981
+ case " ":
3982
+ oldLines.push(content);
3983
+ newLines.push(content);
3984
+ break;
3985
+ case "-":
3986
+ oldLines.push(content);
3987
+ hasModification = true;
3988
+ break;
3989
+ case "+":
3990
+ newLines.push(content);
3991
+ hasModification = true;
3992
+ break;
3993
+ default:
3994
+ throw new Error(
3995
+ `Patch parse failed: invalid change marker '${marker}' (line ${index + 1})`
3996
+ );
3997
+ }
3998
+ index += 1;
3999
+ }
4000
+ if (!hasModification) {
4001
+ throw new Error(
4002
+ `Patch parse failed: chunk must contain at least one '+' or '-' change (line ${index + 1})`
4003
+ );
4004
+ }
4005
+ chunks.push({
4006
+ ...changeContext ? { changeContext } : {},
4007
+ oldLines,
4008
+ newLines,
4009
+ ...isEndOfFile ? { isEndOfFile: true } : {}
4010
+ });
4011
+ }
4012
+ if (chunks.length === 0 && !options.allowEmpty) {
4013
+ throw new Error("Patch parse failed: update file section has no chunks");
4014
+ }
4015
+ return { chunks, nextIndex: index };
4016
+ };
4017
+ var parsePatch = (patchText) => {
4018
+ const normalized = normalizePatchText(patchText);
4019
+ const lines = normalized.split("\n");
4020
+ let first = 0;
4021
+ while (first < lines.length && lines[first]?.trim() === "") {
4022
+ first += 1;
4023
+ }
4024
+ let last = lines.length - 1;
4025
+ while (last >= first && lines[last]?.trim() === "") {
4026
+ last -= 1;
4027
+ }
4028
+ if (first > last) {
4029
+ throw new Error("Patch parse failed: patch is empty");
4030
+ }
4031
+ if (lines[first] !== BEGIN_MARKER || lines[last] !== END_MARKER) {
4032
+ throw new Error("Patch parse failed: missing Begin/End markers");
4033
+ }
4034
+ const parsed = [];
4035
+ let index = first + 1;
4036
+ while (index < last) {
4037
+ const line = lines[index] ?? "";
4038
+ if (line.trim() === "") {
4039
+ index += 1;
4040
+ continue;
4041
+ }
4042
+ const header = parsePatchHeader(line);
4043
+ if (!header) {
4044
+ throw new Error(
4045
+ `Patch parse failed: unexpected line outside file section (line ${index + 1})`
4046
+ );
4047
+ }
4048
+ if (header.kind === "add") {
4049
+ const addResult = parseAddFileLines(lines, index + 1, last);
4050
+ parsed.push({
4051
+ type: "add",
4052
+ filePath: header.filePath,
4053
+ lines: addResult.lines
4054
+ });
4055
+ index = addResult.nextIndex;
4056
+ continue;
4057
+ }
4058
+ if (header.kind === "delete") {
4059
+ parsed.push({
4060
+ type: "delete",
4061
+ filePath: header.filePath
4062
+ });
4063
+ index += 1;
4064
+ continue;
4065
+ }
4066
+ let moveTo;
4067
+ let nextIndex = index + 1;
4068
+ const maybeMove = lines[nextIndex] ?? "";
4069
+ if (maybeMove.startsWith("*** Move to: ")) {
4070
+ moveTo = requirePatchPath(
4071
+ "Move to",
4072
+ maybeMove.slice("*** Move to: ".length)
4073
+ );
4074
+ nextIndex += 1;
4075
+ }
4076
+ const updateResult = parseUpdateChunks(lines, nextIndex, last, {
4077
+ allowEmpty: Boolean(moveTo)
4078
+ });
4079
+ parsed.push({
4080
+ type: "update",
4081
+ filePath: header.filePath,
4082
+ ...moveTo ? { moveTo } : {},
4083
+ chunks: updateResult.chunks
4084
+ });
4085
+ index = updateResult.nextIndex;
4086
+ }
4087
+ if (parsed.length === 0) {
4088
+ throw new Error("Patch parse failed: no file changes found");
4089
+ }
4090
+ return parsed;
4091
+ };
4092
+ var renderAddedFile = (lines) => lines.length > 0 ? `${lines.join("\n")}
4093
+ ` : "";
4094
+ var normalizeUnicodeLikePatch = (value) => value.replace(/[\u2018\u2019\u201A\u201B]/g, "'").replace(/[\u201C\u201D\u201E\u201F]/g, '"').replace(/[\u2010\u2011\u2012\u2013\u2014\u2015]/g, "-").replace(/\u2026/g, "...").replace(/\u00A0/g, " ");
4095
+ var tryMatchSequence = (lines, pattern, startIndex, eof, compare) => {
4096
+ if (pattern.length === 0) return -1;
4097
+ if (eof) {
4098
+ const fromEnd = lines.length - pattern.length;
4099
+ if (fromEnd >= startIndex) {
4100
+ let matches = true;
4101
+ for (let index = 0; index < pattern.length; index += 1) {
4102
+ if (!compare(lines[fromEnd + index] ?? "", pattern[index] ?? "")) {
4103
+ matches = false;
4104
+ break;
4105
+ }
4106
+ }
4107
+ if (matches) {
4108
+ return fromEnd;
4109
+ }
4110
+ }
4111
+ }
4112
+ for (let index = startIndex; index <= lines.length - pattern.length; index += 1) {
4113
+ let matches = true;
4114
+ for (let offset = 0; offset < pattern.length; offset += 1) {
4115
+ if (!compare(lines[index + offset] ?? "", pattern[offset] ?? "")) {
4116
+ matches = false;
4117
+ break;
4118
+ }
4119
+ }
4120
+ if (matches) {
4121
+ return index;
4122
+ }
4123
+ }
4124
+ return -1;
4125
+ };
4126
+ var seekSequence = (lines, pattern, startIndex, eof = false) => {
4127
+ const exact = tryMatchSequence(
4128
+ lines,
4129
+ pattern,
4130
+ startIndex,
4131
+ eof,
4132
+ (left, right) => {
4133
+ return left === right;
4134
+ }
4135
+ );
4136
+ if (exact !== -1) return exact;
4137
+ const trimRight = tryMatchSequence(
4138
+ lines,
4139
+ pattern,
4140
+ startIndex,
4141
+ eof,
4142
+ (left, right) => left.trimEnd() === right.trimEnd()
4143
+ );
4144
+ if (trimRight !== -1) return trimRight;
4145
+ const trimBoth = tryMatchSequence(
4146
+ lines,
4147
+ pattern,
4148
+ startIndex,
4149
+ eof,
4150
+ (left, right) => left.trim() === right.trim()
4151
+ );
4152
+ if (trimBoth !== -1) return trimBoth;
4153
+ return tryMatchSequence(lines, pattern, startIndex, eof, (left, right) => {
4154
+ return normalizeUnicodeLikePatch(left.trim()) === normalizeUnicodeLikePatch(right.trim());
4155
+ });
4156
+ };
4157
+ var applyLineReplacements = (lines, replacements) => {
4158
+ const result = [...lines];
4159
+ for (let index = replacements.length - 1; index >= 0; index -= 1) {
4160
+ const replacement = replacements[index];
4161
+ result.splice(
4162
+ replacement.startIndex,
4163
+ replacement.deleteCount,
4164
+ ...replacement.insertLines
4165
+ );
4166
+ }
4167
+ return result;
4168
+ };
4169
+ var computeLineReplacements = (lines, filePath, chunks) => {
4170
+ const replacements = [];
4171
+ let cursor = 0;
4172
+ for (const chunk of chunks) {
4173
+ if (chunk.changeContext) {
4174
+ const contextIndex = seekSequence(
4175
+ lines,
4176
+ [chunk.changeContext],
4177
+ cursor,
4178
+ false
4179
+ );
4180
+ if (contextIndex === -1) {
4181
+ throw new Error(
4182
+ `Patch apply failed: context '${chunk.changeContext}' not found in ${filePath}`
4183
+ );
4184
+ }
4185
+ cursor = contextIndex + 1;
4186
+ }
4187
+ if (chunk.oldLines.length === 0) {
4188
+ const insertAt = chunk.isEndOfFile ? lines.length : cursor;
4189
+ replacements.push({
4190
+ startIndex: insertAt,
4191
+ deleteCount: 0,
4192
+ insertLines: chunk.newLines
4193
+ });
4194
+ cursor = insertAt;
4195
+ continue;
4196
+ }
4197
+ const matchIndex = seekSequence(
4198
+ lines,
4199
+ chunk.oldLines,
4200
+ cursor,
4201
+ chunk.isEndOfFile ?? false
4202
+ );
4203
+ if (matchIndex === -1) {
4204
+ throw new Error(
4205
+ `Patch apply failed: expected lines not found in ${filePath}`
4206
+ );
4207
+ }
4208
+ replacements.push({
4209
+ startIndex: matchIndex,
4210
+ deleteCount: chunk.oldLines.length,
4211
+ insertLines: chunk.newLines
4212
+ });
4213
+ cursor = matchIndex + chunk.oldLines.length;
4214
+ }
4215
+ return replacements;
4216
+ };
4217
+ var deriveUpdatedContent = (filePath, before, chunks) => {
4218
+ const hadTrailingNewline = before.endsWith("\n");
4219
+ const lines = before.split("\n");
4220
+ if (hadTrailingNewline && lines.at(-1) === "") {
4221
+ lines.pop();
4222
+ }
4223
+ const replacements = computeLineReplacements(lines, filePath, chunks);
4224
+ const nextLines = applyLineReplacements(lines, replacements);
4225
+ const joined = nextLines.join("\n");
4226
+ if (joined === "") {
4227
+ return "";
4228
+ }
4229
+ return hadTrailingNewline ? `${joined}
4230
+ ` : joined;
4231
+ };
4232
+ var rewriteDiffPaths = (diff, oldPath, newPath) => {
4233
+ if (!diff) return diff;
4234
+ const lines = diff.split("\n");
4235
+ if (lines.length >= 2) {
4236
+ lines[0] = `--- ${oldPath}`;
4237
+ lines[1] = `+++ ${newPath}`;
4238
+ }
4239
+ return lines.join("\n");
4240
+ };
4241
+ var ensureFileText = async (resolvedPath, filePath) => {
4242
+ try {
4243
+ const stats = await import_node_fs7.promises.stat(resolvedPath);
4244
+ if (stats.isDirectory()) {
4245
+ throw new Error(`Path is a directory: ${filePath}`);
4246
+ }
4247
+ return await import_node_fs7.promises.readFile(resolvedPath, "utf8");
4248
+ } catch (error) {
4249
+ if (error.code === "ENOENT") {
4250
+ throw new Error(`File not found: ${filePath}`);
4251
+ }
4252
+ throw error;
4253
+ }
4254
+ };
4255
+ var ensureFileStats = async (resolvedPath, filePath) => {
4256
+ try {
4257
+ const stats = await import_node_fs7.promises.stat(resolvedPath);
4258
+ if (stats.isDirectory()) {
4259
+ throw new Error(`Path is a directory: ${filePath}`);
4260
+ }
4261
+ return stats;
4262
+ } catch (error) {
4263
+ if (error.code === "ENOENT") {
4264
+ throw new Error(`File not found: ${filePath}`);
4265
+ }
4266
+ throw error;
4267
+ }
4268
+ };
4269
+ var preparePatchChanges = async (patches, sandbox) => {
4270
+ const prepared = [];
4271
+ const seenSources = /* @__PURE__ */ new Set();
4272
+ const seenTargets = /* @__PURE__ */ new Set();
4273
+ const vacatedEarlier = /* @__PURE__ */ new Set();
4274
+ for (const patch of patches) {
4275
+ const resolvedPath = sandbox.resolvePath(patch.filePath);
4276
+ if (seenSources.has(resolvedPath)) {
4277
+ throw new Error(
4278
+ `Patch apply failed: duplicate source path ${patch.filePath}`
4279
+ );
4280
+ }
4281
+ seenSources.add(resolvedPath);
4282
+ if (patch.type === "add") {
4283
+ try {
4284
+ await import_node_fs7.promises.stat(resolvedPath);
4285
+ throw new Error(`File already exists: ${patch.filePath}`);
4286
+ } catch (error) {
4287
+ if (error.code !== "ENOENT") {
4288
+ throw error;
4289
+ }
4290
+ }
4291
+ if (seenTargets.has(resolvedPath)) {
4292
+ throw new Error(
4293
+ `Patch apply failed: duplicate target path ${patch.filePath}`
4294
+ );
4295
+ }
4296
+ seenTargets.add(resolvedPath);
4297
+ const after2 = renderAddedFile(patch.lines);
4298
+ prepared.push({
4299
+ kind: "add",
4300
+ filePath: patch.filePath,
4301
+ resolvedPath,
4302
+ before: "",
4303
+ after: after2,
4304
+ diff: createUnifiedDiff(patch.filePath, "", after2)
4305
+ });
4306
+ continue;
4307
+ }
4308
+ if (patch.type === "delete") {
4309
+ const before2 = await ensureFileText(resolvedPath, patch.filePath);
4310
+ prepared.push({
4311
+ kind: "delete",
4312
+ filePath: patch.filePath,
4313
+ resolvedPath,
4314
+ before: before2,
4315
+ after: "",
4316
+ diff: createUnifiedDiff(patch.filePath, before2, "")
4317
+ });
4318
+ vacatedEarlier.add(resolvedPath);
4319
+ continue;
4320
+ }
4321
+ const sourceStats = await ensureFileStats(resolvedPath, patch.filePath);
4322
+ const before = await import_node_fs7.promises.readFile(resolvedPath, "utf8");
4323
+ const after = deriveUpdatedContent(patch.filePath, before, patch.chunks);
4324
+ if (patch.moveTo) {
4325
+ const resolvedMoveTo = sandbox.resolvePath(patch.moveTo);
4326
+ if (resolvedMoveTo !== resolvedPath) {
4327
+ try {
4328
+ await import_node_fs7.promises.stat(resolvedMoveTo);
4329
+ if (!vacatedEarlier.has(resolvedMoveTo)) {
4330
+ throw new Error(`Move target already exists: ${patch.moveTo}`);
4331
+ }
4332
+ } catch (error) {
4333
+ if (error.code !== "ENOENT") {
4334
+ throw error;
4335
+ }
4336
+ }
4337
+ }
4338
+ if (seenTargets.has(resolvedMoveTo)) {
4339
+ throw new Error(
4340
+ `Patch apply failed: duplicate target path ${patch.moveTo}`
4341
+ );
4342
+ }
4343
+ seenTargets.add(resolvedMoveTo);
4344
+ prepared.push({
4345
+ kind: resolvedMoveTo === resolvedPath ? "update" : "move",
4346
+ filePath: patch.filePath,
4347
+ resolvedPath,
4348
+ moveTo: patch.moveTo,
4349
+ resolvedMoveTo,
4350
+ sourceMode: sourceStats.mode,
4351
+ before,
4352
+ after,
4353
+ diff: resolvedMoveTo === resolvedPath ? createUnifiedDiff(patch.filePath, before, after) : rewriteDiffPaths(
4354
+ createUnifiedDiff(patch.filePath, before, after),
4355
+ patch.filePath,
4356
+ patch.moveTo
4357
+ )
4358
+ });
4359
+ if (resolvedMoveTo !== resolvedPath) {
4360
+ vacatedEarlier.add(resolvedPath);
4361
+ }
4362
+ continue;
4363
+ }
4364
+ if (seenTargets.has(resolvedPath)) {
4365
+ throw new Error(
4366
+ `Patch apply failed: duplicate target path ${patch.filePath}`
4367
+ );
4368
+ }
4369
+ seenTargets.add(resolvedPath);
4370
+ prepared.push({
4371
+ kind: "update",
4372
+ filePath: patch.filePath,
4373
+ resolvedPath,
4374
+ before,
4375
+ after,
4376
+ diff: createUnifiedDiff(patch.filePath, before, after)
4377
+ });
4378
+ }
4379
+ return prepared;
4380
+ };
4381
+ var applyPreparedChanges = async (changes) => {
4382
+ for (const change of changes) {
4383
+ if (change.kind === "delete") {
4384
+ await import_node_fs7.promises.unlink(change.resolvedPath);
4385
+ continue;
4386
+ }
4387
+ if (change.kind === "move" && change.resolvedMoveTo) {
4388
+ await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(change.resolvedMoveTo), { recursive: true });
4389
+ await import_node_fs7.promises.writeFile(change.resolvedMoveTo, change.after, "utf8");
4390
+ if (typeof change.sourceMode === "number") {
4391
+ await import_node_fs7.promises.chmod(change.resolvedMoveTo, change.sourceMode);
4392
+ }
4393
+ await import_node_fs7.promises.unlink(change.resolvedPath);
4394
+ continue;
4395
+ }
4396
+ await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(change.resolvedPath), { recursive: true });
4397
+ await import_node_fs7.promises.writeFile(change.resolvedPath, change.after, "utf8");
4398
+ }
4399
+ };
4400
+ var summarizeChanges = (changes, dryRun) => {
4401
+ const fileSummaries = changes.map((change) => {
4402
+ switch (change.kind) {
4403
+ case "add":
4404
+ return {
4405
+ action: "add",
4406
+ file_path: change.filePath,
4407
+ summary: `A ${change.filePath}`
4408
+ };
4409
+ case "delete":
4410
+ return {
4411
+ action: "delete",
4412
+ file_path: change.filePath,
4413
+ summary: `D ${change.filePath}`
4414
+ };
4415
+ case "move":
4416
+ return {
4417
+ action: "move",
4418
+ file_path: change.filePath,
4419
+ move_to: change.moveTo,
4420
+ summary: `R ${change.filePath} -> ${change.moveTo}`
4421
+ };
4422
+ case "update":
4423
+ return {
4424
+ action: "update",
4425
+ file_path: change.moveTo ?? change.filePath,
4426
+ summary: `M ${change.moveTo ?? change.filePath}`
4427
+ };
4428
+ default:
4429
+ throw new Error(`Unsupported patch change kind: ${change.kind}`);
4430
+ }
4431
+ });
4432
+ return {
4433
+ summary: dryRun ? `Patch preview ready for ${changes.length} file(s)` : `Applied patch to ${changes.length} file(s)`,
4434
+ files: fileSummaries
4435
+ };
4436
+ };
4437
+ var createApplyPatchTool = (sandboxKey, outputCacheStore) => (0, import_core4.defineTool)({
4438
+ name: "apply_patch",
4439
+ description: "Apply a codex-style multi-file patch; use dry_run to preview only.",
4440
+ input: import_zod3.z.object({
4441
+ patch: import_zod3.z.string().min(1).describe("Full patch text between *** Begin Patch and *** End Patch."),
4442
+ dry_run: import_zod3.z.boolean().optional().describe("Preview the patch without writing files. Default false.")
4443
+ }),
4444
+ execute: async (input, ctx) => {
4445
+ const dryRun = input.dry_run ?? false;
4446
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
4447
+ const patches = parsePatch(input.patch);
4448
+ const prepared = await preparePatchChanges(patches, sandbox);
4449
+ const fullDiff = prepared.map((change) => change.diff).filter((diff) => diff.length > 0).join("\n\n");
4450
+ const diffPayload = await buildDiffPayload({
4451
+ toolName: "apply_patch",
4452
+ diff: fullDiff,
4453
+ outputCacheStore
4454
+ });
4455
+ const summary = summarizeChanges(prepared, dryRun);
4456
+ if (!dryRun) {
4457
+ try {
4458
+ await applyPreparedChanges(prepared);
4459
+ } catch (error) {
4460
+ throw new Error(`Error applying patch: ${String(error)}`);
4461
+ }
4462
+ }
4463
+ return {
4464
+ summary: summary.summary,
4465
+ file_count: prepared.length,
4466
+ files: summary.files,
4467
+ ...diffPayload
4468
+ };
4469
+ }
4470
+ });
4471
+
4472
+ // src/tools/done.ts
4473
+ var import_core5 = require("@codelia/core");
4474
+ var import_zod4 = require("zod");
4475
+ var createDoneTool = () => (0, import_core5.defineTool)({
4476
+ name: "done",
4477
+ description: "Mark the task as complete and return a final message.",
4478
+ input: import_zod4.z.object({
4479
+ message: import_zod4.z.string().describe("Final user-facing completion message.")
4480
+ }),
4481
+ execute: async (input) => {
4482
+ throw new import_core5.TaskComplete(input.message);
4483
+ }
4484
+ });
4485
+
3749
4486
  // src/tools/edit.ts
4487
+ var import_node_crypto4 = __toESM(require("crypto"), 1);
4488
+ var import_node_fs8 = require("fs");
4489
+ var import_node_path9 = __toESM(require("path"), 1);
4490
+ var import_core6 = require("@codelia/core");
4491
+ var import_zod5 = require("zod");
3750
4492
  var trimLine = (line) => line.replace(/\r$/, "").trim();
3751
4493
  var lineRangeToIndices = (lines, startLine, lineCount) => {
3752
4494
  let startIndex = 0;
@@ -3853,25 +4595,25 @@ var applyReplacements = (content, matches, replacement) => {
3853
4595
  }
3854
4596
  return next;
3855
4597
  };
3856
- var hashContent = (content) => import_node_crypto3.default.createHash("sha256").update(content).digest("hex");
3857
- var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
4598
+ var hashContent = (content) => import_node_crypto4.default.createHash("sha256").update(content).digest("hex");
4599
+ var createEditTool = (sandboxKey, outputCacheStore) => (0, import_core6.defineTool)({
3858
4600
  name: "edit",
3859
4601
  description: "Edit a file by replacing old_string with new_string.",
3860
- input: import_zod4.z.object({
3861
- file_path: import_zod4.z.string().describe(
4602
+ input: import_zod5.z.object({
4603
+ file_path: import_zod5.z.string().describe(
3862
4604
  "File path. Sandbox-bounded unless full-access mode is active."
3863
4605
  ),
3864
- old_string: import_zod4.z.string().describe(
4606
+ old_string: import_zod5.z.string().describe(
3865
4607
  "Text to find. Use empty string to replace the whole file content."
3866
4608
  ),
3867
- new_string: import_zod4.z.string().describe("Replacement text."),
3868
- replace_all: import_zod4.z.boolean().optional().describe("Replace all matches when true. Default false."),
3869
- match_mode: import_zod4.z.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
4609
+ new_string: import_zod5.z.string().describe("Replacement text."),
4610
+ replace_all: import_zod5.z.boolean().optional().describe("Replace all matches when true. Default false."),
4611
+ match_mode: import_zod5.z.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
3870
4612
  "Match strategy: exact, line_trimmed, block_anchor, or auto. Default auto."
3871
4613
  ),
3872
- expected_replacements: import_zod4.z.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
3873
- dry_run: import_zod4.z.boolean().optional().describe("Preview diff only when true. Default false."),
3874
- expected_hash: import_zod4.z.string().optional().describe("Optional SHA-256 hash guard for current file content.")
4614
+ expected_replacements: import_zod5.z.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
4615
+ dry_run: import_zod5.z.boolean().optional().describe("Preview diff only when true. Default false."),
4616
+ expected_hash: import_zod5.z.string().optional().describe("Optional SHA-256 hash guard for current file content.")
3875
4617
  }),
3876
4618
  execute: async (input, ctx) => {
3877
4619
  let resolved;
@@ -3896,12 +4638,12 @@ var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
3896
4638
  let content = "";
3897
4639
  let fileExists = false;
3898
4640
  try {
3899
- const stat = await import_node_fs7.promises.stat(resolved);
4641
+ const stat = await import_node_fs8.promises.stat(resolved);
3900
4642
  if (stat.isDirectory()) {
3901
4643
  throw new Error(`Path is a directory: ${input.file_path}`);
3902
4644
  }
3903
4645
  fileExists = true;
3904
- content = await import_node_fs7.promises.readFile(resolved, "utf8");
4646
+ content = await import_node_fs8.promises.readFile(resolved, "utf8");
3905
4647
  } catch (_error) {
3906
4648
  if (input.old_string !== "") {
3907
4649
  throw new Error(`File not found: ${input.file_path}`);
@@ -3951,13 +4693,18 @@ var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
3951
4693
  `Expected ${input.expected_replacements} replacements, found ${replacements}`
3952
4694
  );
3953
4695
  }
3954
- const diff = createUnifiedDiff(input.file_path, content, nextContent);
4696
+ const diffPayload = await buildDiffPayload({
4697
+ toolName: "edit",
4698
+ diff: createUnifiedDiff(input.file_path, content, nextContent),
4699
+ outputCacheStore,
4700
+ debugContext: `file=${input.file_path}`
4701
+ });
3955
4702
  if (dryRun) {
3956
4703
  return {
3957
4704
  summary: `Preview: ${replacements} replacement(s) in ${input.file_path}`,
3958
4705
  replacements,
3959
4706
  match_mode: modeUsed,
3960
- diff,
4707
+ ...diffPayload,
3961
4708
  file_path: input.file_path
3962
4709
  };
3963
4710
  }
@@ -3966,13 +4713,13 @@ var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
3966
4713
  summary: `No changes needed in ${input.file_path}`,
3967
4714
  replacements,
3968
4715
  match_mode: modeUsed,
3969
- diff,
4716
+ ...diffPayload,
3970
4717
  file_path: input.file_path
3971
4718
  };
3972
4719
  }
3973
4720
  try {
3974
- await import_node_fs7.promises.mkdir(import_node_path8.default.dirname(resolved), { recursive: true });
3975
- await import_node_fs7.promises.writeFile(resolved, nextContent, "utf8");
4721
+ await import_node_fs8.promises.mkdir(import_node_path9.default.dirname(resolved), { recursive: true });
4722
+ await import_node_fs8.promises.writeFile(resolved, nextContent, "utf8");
3976
4723
  } catch (error) {
3977
4724
  throw new Error(`Error editing file: ${String(error)}`);
3978
4725
  }
@@ -3980,171 +4727,21 @@ var createEditTool = (sandboxKey) => (0, import_core5.defineTool)({
3980
4727
  summary: `Replaced ${replacements} occurrence(s) in ${input.file_path}`,
3981
4728
  replacements,
3982
4729
  match_mode: modeUsed,
3983
- diff,
4730
+ ...diffPayload,
3984
4731
  file_path: input.file_path
3985
4732
  };
3986
4733
  }
3987
4734
  });
3988
4735
 
3989
- // src/tools/glob-search.ts
3990
- var import_node_fs9 = require("fs");
3991
- var import_core6 = require("@codelia/core");
3992
- var import_zod5 = require("zod");
3993
-
3994
- // src/utils/glob.ts
3995
- var import_node_fs8 = require("fs");
3996
- var import_node_path9 = __toESM(require("path"), 1);
3997
- var globToRegExp2 = (pattern) => {
3998
- const normalized = pattern.replaceAll("\\", "/");
3999
- const globDirToken = "__GLOBSTAR_DIR__";
4000
- const globAnyToken = "__GLOBSTAR__";
4001
- const globSingleToken = "__GLOBSTAR_SINGLE__";
4002
- const globCharToken = "__GLOBSTAR_CHAR__";
4003
- const withTokens = normalized.replace(/\*\*\//g, globDirToken).replace(/\*\*/g, globAnyToken).replace(/\*/g, globSingleToken).replace(/\?/g, globCharToken);
4004
- const escaped = withTokens.replace(/[.+^$(){}|[\]\\]/g, "\\$&");
4005
- const withGlob = escaped.replace(new RegExp(globDirToken, "g"), "(?:.+/)?").replace(new RegExp(globAnyToken, "g"), ".+").replace(new RegExp(globSingleToken, "g"), "[^/]*").replace(new RegExp(globCharToken, "g"), ".");
4006
- return new RegExp(`^${withGlob}$`);
4007
- };
4008
- var walkFiles = async (startDir, visitor) => {
4009
- const entries = await import_node_fs8.promises.readdir(startDir, { withFileTypes: true });
4010
- for (const entry of entries) {
4011
- const fullPath = import_node_path9.default.join(startDir, entry.name);
4012
- if (entry.isDirectory()) {
4013
- await walkFiles(fullPath, visitor);
4014
- } else if (entry.isFile()) {
4015
- const shouldContinue = await visitor(fullPath);
4016
- if (!shouldContinue) return;
4017
- }
4018
- }
4019
- };
4020
- var globMatch = async (searchDir, pattern) => {
4021
- const regex = globToRegExp2(pattern.replaceAll("\\", "/"));
4022
- const matches = [];
4023
- await walkFiles(searchDir, async (filePath) => {
4024
- const relPath = import_node_path9.default.relative(searchDir, filePath).replaceAll("\\", "/");
4025
- if (regex.test(relPath)) {
4026
- matches.push(relPath);
4027
- }
4028
- return matches.length < 200;
4029
- });
4030
- return matches;
4031
- };
4032
-
4033
- // src/tools/glob-search.ts
4034
- var createGlobSearchTool = (sandboxKey) => (0, import_core6.defineTool)({
4035
- name: "glob_search",
4036
- description: "Find files by glob pattern under a directory.",
4037
- input: import_zod5.z.object({
4038
- pattern: import_zod5.z.string().describe("Glob pattern (for example: **/*.ts)."),
4039
- path: import_zod5.z.string().optional().describe(
4040
- "Optional directory path. Defaults to the current working directory."
4041
- )
4042
- }),
4043
- execute: async (input, ctx) => {
4044
- let searchDir;
4045
- try {
4046
- const sandbox = await getSandboxContext(ctx, sandboxKey);
4047
- searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4048
- } catch (error) {
4049
- throw new Error(`Security error: ${String(error)}`);
4050
- }
4051
- try {
4052
- const stat = await import_node_fs9.promises.stat(searchDir);
4053
- if (!stat.isDirectory()) {
4054
- return `Path is not a directory: ${input.path}`;
4055
- }
4056
- } catch (error) {
4057
- return `Error: ${String(error)}`;
4058
- }
4059
- const matches = await globMatch(searchDir, input.pattern);
4060
- if (!matches.length) {
4061
- return `No files match pattern: ${input.pattern}`;
4062
- }
4063
- const limited = matches.slice(0, 50);
4064
- return `Found ${limited.length} file(s):
4065
- ${limited.join("\n")}`;
4066
- }
4067
- });
4068
-
4069
- // src/tools/grep.ts
4070
- var import_node_fs10 = require("fs");
4071
- var import_node_path10 = __toESM(require("path"), 1);
4736
+ // src/tools/lane.ts
4072
4737
  var import_core7 = require("@codelia/core");
4073
4738
  var import_zod6 = require("zod");
4074
- var createGrepTool = (sandboxKey) => (0, import_core7.defineTool)({
4075
- name: "grep",
4076
- description: "Search file contents with a regex pattern.",
4077
- input: import_zod6.z.object({
4078
- pattern: import_zod6.z.string().describe("Regex pattern (JavaScript syntax)."),
4079
- path: import_zod6.z.string().optional().describe(
4080
- "Optional file or directory path. Defaults to the current working directory."
4081
- )
4082
- }),
4083
- execute: async (input, ctx) => {
4084
- let searchDir;
4085
- let rootDir;
4086
- let pathLabel;
4087
- try {
4088
- const sandbox = await getSandboxContext(ctx, sandboxKey);
4089
- rootDir = sandbox.rootDir;
4090
- searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4091
- pathLabel = input.path ?? searchDir;
4092
- } catch (error) {
4093
- throw new Error(`Security error: ${String(error)}`);
4094
- }
4095
- let regex;
4096
- try {
4097
- regex = new RegExp(input.pattern);
4098
- } catch (error) {
4099
- return `Invalid regex: ${String(error)}`;
4100
- }
4101
- const results = [];
4102
- const searchFile = async (filePath) => {
4103
- if (results.length >= 50) return false;
4104
- try {
4105
- const content = await import_node_fs10.promises.readFile(filePath, "utf8");
4106
- const lines = content.split(/\r?\n/);
4107
- for (let i = 0; i < lines.length; i++) {
4108
- if (regex.test(lines[i])) {
4109
- const relPath = import_node_path10.default.relative(rootDir, filePath).replaceAll("\\", "/");
4110
- results.push(`${relPath}:${i + 1}: ${lines[i].slice(0, 100)}`);
4111
- if (results.length >= 50) return false;
4112
- }
4113
- }
4114
- } catch {
4115
- return true;
4116
- }
4117
- return true;
4118
- };
4119
- try {
4120
- const stats = await import_node_fs10.promises.stat(searchDir);
4121
- if (stats.isFile()) {
4122
- await searchFile(searchDir);
4123
- } else if (stats.isDirectory()) {
4124
- await walkFiles(searchDir, searchFile);
4125
- } else {
4126
- return `Path is not a file or directory: ${pathLabel}`;
4127
- }
4128
- } catch (error) {
4129
- return `Error reading path: ${pathLabel} (${String(error)})`;
4130
- }
4131
- if (!results.length) {
4132
- return `No matches for: ${input.pattern}`;
4133
- }
4134
- return results.length >= 50 ? `${results.join("\n")}
4135
- ... (truncated)` : results.join("\n");
4136
- }
4137
- });
4138
-
4139
- // src/tools/lane.ts
4140
- var import_core8 = require("@codelia/core");
4141
- var import_zod7 = require("zod");
4142
4739
 
4143
4740
  // src/lanes/manager.ts
4144
- var import_node_crypto4 = __toESM(require("crypto"), 1);
4145
- var import_node_fs12 = require("fs");
4741
+ var import_node_crypto5 = __toESM(require("crypto"), 1);
4742
+ var import_node_fs10 = require("fs");
4146
4743
  var import_node_os2 = __toESM(require("os"), 1);
4147
- var import_node_path12 = __toESM(require("path"), 1);
4744
+ var import_node_path11 = __toESM(require("path"), 1);
4148
4745
 
4149
4746
  // src/lanes/command.ts
4150
4747
  var import_node_child_process2 = require("child_process");
@@ -4226,8 +4823,8 @@ ${stdout}`.trim();
4226
4823
  };
4227
4824
 
4228
4825
  // src/lanes/registry.ts
4229
- var import_node_fs11 = require("fs");
4230
- var import_node_path11 = __toESM(require("path"), 1);
4826
+ var import_node_fs9 = require("fs");
4827
+ var import_node_path10 = __toESM(require("path"), 1);
4231
4828
  var import_storage5 = require("@codelia/storage");
4232
4829
  var REGISTRY_DIRNAME = "lanes";
4233
4830
  var REGISTRY_FILENAME = "registry.json";
@@ -4235,7 +4832,7 @@ var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
4235
4832
  var sortByUpdatedDesc = (lanes) => [...lanes].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
4236
4833
  var readJsonFile = async (filePath) => {
4237
4834
  try {
4238
- const raw = await import_node_fs11.promises.readFile(filePath, "utf8");
4835
+ const raw = await import_node_fs9.promises.readFile(filePath, "utf8");
4239
4836
  const parsed = JSON.parse(raw);
4240
4837
  if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.lanes)) {
4241
4838
  return null;
@@ -4249,14 +4846,14 @@ var readJsonFile = async (filePath) => {
4249
4846
  }
4250
4847
  };
4251
4848
  var atomicWrite = async (filePath, payload) => {
4252
- const dir = import_node_path11.default.dirname(filePath);
4253
- const base = import_node_path11.default.basename(filePath);
4254
- const tmp = import_node_path11.default.join(
4849
+ const dir = import_node_path10.default.dirname(filePath);
4850
+ const base = import_node_path10.default.basename(filePath);
4851
+ const tmp = import_node_path10.default.join(
4255
4852
  dir,
4256
4853
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
4257
4854
  );
4258
- await import_node_fs11.promises.writeFile(tmp, payload, "utf8");
4259
- await import_node_fs11.promises.rename(tmp, filePath);
4855
+ await import_node_fs9.promises.writeFile(tmp, payload, "utf8");
4856
+ await import_node_fs9.promises.rename(tmp, filePath);
4260
4857
  };
4261
4858
  var LaneRegistryStore = class {
4262
4859
  registryPath;
@@ -4266,10 +4863,10 @@ var LaneRegistryStore = class {
4266
4863
  return;
4267
4864
  }
4268
4865
  const root = (0, import_storage5.resolveStoragePaths)().root;
4269
- this.registryPath = import_node_path11.default.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4866
+ this.registryPath = import_node_path10.default.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4270
4867
  }
4271
4868
  async ensureDir() {
4272
- await import_node_fs11.promises.mkdir(import_node_path11.default.dirname(this.registryPath), { recursive: true });
4869
+ await import_node_fs9.promises.mkdir(import_node_path10.default.dirname(this.registryPath), { recursive: true });
4273
4870
  }
4274
4871
  async readAll() {
4275
4872
  await this.ensureDir();
@@ -4367,9 +4964,9 @@ var LaneManager = class {
4367
4964
  this.runner = options.runner ?? runCommand;
4368
4965
  this.registry = options.registry ?? new LaneRegistryStore();
4369
4966
  this.now = options.now ?? nowIso2;
4370
- this.randomId = options.randomId ?? (() => import_node_crypto4.default.randomUUID());
4967
+ this.randomId = options.randomId ?? (() => import_node_crypto5.default.randomUUID());
4371
4968
  this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
4372
- this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? import_node_path12.default.join(import_node_os2.default.homedir(), ".codelia", "worktrees");
4969
+ this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? import_node_path11.default.join(import_node_os2.default.homedir(), ".codelia", "worktrees");
4373
4970
  }
4374
4971
  async cmd(command, args, options) {
4375
4972
  (0, import_logger.debugLog)(`lane.cmd ${command} ${args.join(" ")}`);
@@ -4492,15 +5089,15 @@ var LaneManager = class {
4492
5089
  "rev-parse",
4493
5090
  "--git-common-dir"
4494
5091
  ]);
4495
- const commonDir = import_node_path12.default.resolve(worktreePath, stdout.trim());
4496
- if (import_node_path12.default.basename(commonDir) === ".git") {
4497
- return import_node_path12.default.dirname(commonDir);
5092
+ const commonDir = import_node_path11.default.resolve(worktreePath, stdout.trim());
5093
+ if (import_node_path11.default.basename(commonDir) === ".git") {
5094
+ return import_node_path11.default.dirname(commonDir);
4498
5095
  }
4499
5096
  return await this.resolveRepoRoot(worktreePath);
4500
5097
  }
4501
5098
  async isWorktreeDirty(worktreePath) {
4502
5099
  try {
4503
- await import_node_fs12.promises.access(worktreePath);
5100
+ await import_node_fs10.promises.access(worktreePath);
4504
5101
  } catch {
4505
5102
  return false;
4506
5103
  }
@@ -4514,7 +5111,7 @@ var LaneManager = class {
4514
5111
  }
4515
5112
  async removeWorktree(worktreePath, force) {
4516
5113
  try {
4517
- await import_node_fs12.promises.access(worktreePath);
5114
+ await import_node_fs10.promises.access(worktreePath);
4518
5115
  } catch {
4519
5116
  return;
4520
5117
  }
@@ -4539,7 +5136,7 @@ var LaneManager = class {
4539
5136
  const slug = toSlug(taskId);
4540
5137
  const shortId = laneId.slice(0, 8);
4541
5138
  const branchName = `lane/${slug}-${shortId}`;
4542
- const worktreePath = input.worktree_path ? import_node_path12.default.resolve(options.workingDir, input.worktree_path) : import_node_path12.default.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
5139
+ const worktreePath = input.worktree_path ? import_node_path11.default.resolve(options.workingDir, input.worktree_path) : import_node_path11.default.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
4543
5140
  const muxTarget = `codelia-lane-${shortId}`;
4544
5141
  const createdAt = this.now();
4545
5142
  const record = {
@@ -4550,14 +5147,14 @@ var LaneManager = class {
4550
5147
  mux_target: muxTarget,
4551
5148
  worktree_path: worktreePath,
4552
5149
  branch_name: branchName,
4553
- session_id: import_node_crypto4.default.randomUUID(),
5150
+ session_id: import_node_crypto5.default.randomUUID(),
4554
5151
  created_at: createdAt,
4555
5152
  updated_at: createdAt,
4556
5153
  last_activity_at: createdAt
4557
5154
  };
4558
5155
  await this.registry.upsert(record);
4559
5156
  try {
4560
- await import_node_fs12.promises.mkdir(import_node_path12.default.dirname(worktreePath), { recursive: true });
5157
+ await import_node_fs10.promises.mkdir(import_node_path11.default.dirname(worktreePath), { recursive: true });
4561
5158
  await this.cmd("git", [
4562
5159
  "-C",
4563
5160
  repoRoot,
@@ -4710,7 +5307,7 @@ var LaneManager = class {
4710
5307
 
4711
5308
  // src/tools/lane.ts
4712
5309
  var laneManager = new LaneManager();
4713
- var backendSchema = import_zod7.z.enum(["tmux", "zellij"]);
5310
+ var backendSchema = import_zod6.z.enum(["tmux", "zellij"]);
4714
5311
  var formatError = (error) => {
4715
5312
  if (error instanceof LaneManagerError) {
4716
5313
  return new Error(`${error.code}: ${error.message}`);
@@ -4737,17 +5334,17 @@ var buildLaneHints = (lane) => {
4737
5334
  }
4738
5335
  };
4739
5336
  };
4740
- var createLaneCreateTool = (sandboxKey) => (0, import_core8.defineTool)({
5337
+ var createLaneCreateTool = (sandboxKey) => (0, import_core7.defineTool)({
4741
5338
  name: "lane_create",
4742
5339
  description: "Create a Task lane (worktree slot) and start autonomous execution in tmux/zellij.",
4743
- input: import_zod7.z.object({
4744
- task_id: import_zod7.z.string().describe("Task identifier."),
4745
- base_ref: import_zod7.z.string().optional().describe("Base git ref. Default: HEAD."),
4746
- worktree_path: import_zod7.z.string().optional().describe(
5340
+ input: import_zod6.z.object({
5341
+ task_id: import_zod6.z.string().describe("Task identifier."),
5342
+ base_ref: import_zod6.z.string().optional().describe("Base git ref. Default: HEAD."),
5343
+ worktree_path: import_zod6.z.string().optional().describe(
4747
5344
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
4748
5345
  ),
4749
5346
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
4750
- seed_context: import_zod7.z.string().optional().describe("Optional initial text context.")
5347
+ seed_context: import_zod6.z.string().optional().describe("Optional initial text context.")
4751
5348
  }),
4752
5349
  execute: async (input, ctx) => {
4753
5350
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -4772,11 +5369,11 @@ var createLaneCreateTool = (sandboxKey) => (0, import_core8.defineTool)({
4772
5369
  }
4773
5370
  }
4774
5371
  });
4775
- var createLaneListTool = (sandboxKey) => (0, import_core8.defineTool)({
5372
+ var createLaneListTool = (sandboxKey) => (0, import_core7.defineTool)({
4776
5373
  name: "lane_list",
4777
5374
  description: "List Task lanes (worktree slots) and current states.",
4778
- input: import_zod7.z.object({
4779
- include_closed: import_zod7.z.boolean().optional().describe("Include closed lanes. Default: false.")
5375
+ input: import_zod6.z.object({
5376
+ include_closed: import_zod6.z.boolean().optional().describe("Include closed lanes. Default: false.")
4780
5377
  }),
4781
5378
  execute: async (input, ctx) => {
4782
5379
  await getSandboxContext(ctx, sandboxKey);
@@ -4796,11 +5393,11 @@ var createLaneListTool = (sandboxKey) => (0, import_core8.defineTool)({
4796
5393
  }
4797
5394
  }
4798
5395
  });
4799
- var createLaneStatusTool = (sandboxKey) => (0, import_core8.defineTool)({
5396
+ var createLaneStatusTool = (sandboxKey) => (0, import_core7.defineTool)({
4800
5397
  name: "lane_status",
4801
5398
  description: "Get Task lane status and backend liveness.",
4802
- input: import_zod7.z.object({
4803
- lane_id: import_zod7.z.string().describe("Lane id.")
5399
+ input: import_zod6.z.object({
5400
+ lane_id: import_zod6.z.string().describe("Lane id.")
4804
5401
  }),
4805
5402
  execute: async (input, ctx) => {
4806
5403
  await getSandboxContext(ctx, sandboxKey);
@@ -4815,13 +5412,13 @@ var createLaneStatusTool = (sandboxKey) => (0, import_core8.defineTool)({
4815
5412
  }
4816
5413
  }
4817
5414
  });
4818
- var createLaneCloseTool = (sandboxKey) => (0, import_core8.defineTool)({
5415
+ var createLaneCloseTool = (sandboxKey) => (0, import_core7.defineTool)({
4819
5416
  name: "lane_close",
4820
5417
  description: "Close a Task lane and optionally remove its worktree.",
4821
- input: import_zod7.z.object({
4822
- lane_id: import_zod7.z.string().describe("Lane id."),
4823
- remove_worktree: import_zod7.z.boolean().optional().describe("Remove worktree. Default: true."),
4824
- force: import_zod7.z.boolean().optional().describe("Force close/cleanup. Default: false.")
5418
+ input: import_zod6.z.object({
5419
+ lane_id: import_zod6.z.string().describe("Lane id."),
5420
+ remove_worktree: import_zod6.z.boolean().optional().describe("Remove worktree. Default: true."),
5421
+ force: import_zod6.z.boolean().optional().describe("Force close/cleanup. Default: false.")
4825
5422
  }),
4826
5423
  execute: async (input, ctx) => {
4827
5424
  await getSandboxContext(ctx, sandboxKey);
@@ -4840,13 +5437,13 @@ var createLaneCloseTool = (sandboxKey) => (0, import_core8.defineTool)({
4840
5437
  }
4841
5438
  }
4842
5439
  });
4843
- var createLaneGcTool = (sandboxKey) => (0, import_core8.defineTool)({
5440
+ var createLaneGcTool = (sandboxKey) => (0, import_core7.defineTool)({
4844
5441
  name: "lane_gc",
4845
5442
  description: "Close stale finished/error lanes after idle TTL.",
4846
- input: import_zod7.z.object({
4847
- idle_ttl_minutes: import_zod7.z.number().int().positive().describe("Idle TTL in minutes."),
4848
- remove_worktree: import_zod7.z.boolean().optional().describe("Remove worktree on close. Default: false."),
4849
- force: import_zod7.z.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
5443
+ input: import_zod6.z.object({
5444
+ idle_ttl_minutes: import_zod6.z.number().int().positive().describe("Idle TTL in minutes."),
5445
+ remove_worktree: import_zod6.z.boolean().optional().describe("Remove worktree on close. Default: false."),
5446
+ force: import_zod6.z.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
4850
5447
  }),
4851
5448
  execute: async (input, ctx) => {
4852
5449
  await getSandboxContext(ctx, sandboxKey);
@@ -4863,9 +5460,9 @@ var createLaneGcTool = (sandboxKey) => (0, import_core8.defineTool)({
4863
5460
  });
4864
5461
 
4865
5462
  // src/tools/read.ts
4866
- var import_node_fs13 = require("fs");
4867
- var import_core9 = require("@codelia/core");
4868
- var import_zod8 = require("zod");
5463
+ var import_node_fs11 = require("fs");
5464
+ var import_core8 = require("@codelia/core");
5465
+ var import_zod7 = require("zod");
4869
5466
  var DEFAULT_READ_LIMIT = 2e3;
4870
5467
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
4871
5468
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -4919,15 +5516,15 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
4919
5516
  }
4920
5517
  return `[truncated lines: ${lineNumbers.join(", ")}]`;
4921
5518
  };
4922
- var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
5519
+ var createReadTool = (sandboxKey) => (0, import_core8.defineTool)({
4923
5520
  name: "read",
4924
5521
  description: "Read a text file with optional 0-based line offset and line limit.",
4925
- input: import_zod8.z.object({
4926
- file_path: import_zod8.z.string().describe(
5522
+ input: import_zod7.z.object({
5523
+ file_path: import_zod7.z.string().describe(
4927
5524
  "File path. Sandbox-bounded unless full-access mode is active."
4928
5525
  ),
4929
- offset: import_zod8.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4930
- limit: import_zod8.z.number().int().positive().optional().describe("Max lines to read. Default 2000.")
5526
+ offset: import_zod7.z.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
5527
+ limit: import_zod7.z.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4931
5528
  }),
4932
5529
  execute: async (input, ctx) => {
4933
5530
  let resolved;
@@ -4938,7 +5535,7 @@ var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
4938
5535
  throw new Error(`Security error: ${String(error)}`);
4939
5536
  }
4940
5537
  try {
4941
- const stat = await import_node_fs13.promises.stat(resolved);
5538
+ const stat = await import_node_fs11.promises.stat(resolved);
4942
5539
  if (stat.isDirectory()) {
4943
5540
  return `Path is a directory: ${input.file_path}`;
4944
5541
  }
@@ -4946,7 +5543,7 @@ var createReadTool = (sandboxKey) => (0, import_core9.defineTool)({
4946
5543
  return `File not found: ${input.file_path}`;
4947
5544
  }
4948
5545
  try {
4949
- const content = await import_node_fs13.promises.readFile(resolved, "utf8");
5546
+ const content = await import_node_fs11.promises.readFile(resolved, "utf8");
4950
5547
  const lines = content.split(/\r?\n/);
4951
5548
  if (lines.length === 0) {
4952
5549
  return "";
@@ -5015,7 +5612,7 @@ ${truncatedLinesSummary}`;
5015
5612
  if (firstClippedLineNumber !== null) {
5016
5613
  output += `
5017
5614
 
5018
- For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5615
+ For full long-line content, use read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5019
5616
  }
5020
5617
  return output;
5021
5618
  } catch (error) {
@@ -5025,21 +5622,25 @@ For full long-line content, use read_line({"file_path":"${input.file_path}","lin
5025
5622
  });
5026
5623
 
5027
5624
  // src/tools/read-line.ts
5028
- var import_node_fs14 = require("fs");
5029
- var import_core10 = require("@codelia/core");
5030
- var import_zod9 = require("zod");
5625
+ var import_node_fs12 = require("fs");
5626
+ var import_core9 = require("@codelia/core");
5627
+ var import_zod8 = require("zod");
5031
5628
  var DEFAULT_CHAR_LIMIT = 1e4;
5032
5629
  var MAX_CHAR_LIMIT = 1e5;
5033
- var createReadLineTool = (sandboxKey) => (0, import_core10.defineTool)({
5630
+ var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
5631
+ granularity: "grapheme"
5632
+ });
5633
+ var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
5634
+ var createReadLineTool = (sandboxKey) => (0, import_core9.defineTool)({
5034
5635
  name: "read_line",
5035
5636
  description: "Read a single line segment by 1-based line number and 0-based char offset.",
5036
- input: import_zod9.z.object({
5037
- file_path: import_zod9.z.string().describe(
5637
+ input: import_zod8.z.object({
5638
+ file_path: import_zod8.z.string().describe(
5038
5639
  "File path. Sandbox-bounded unless full-access mode is active."
5039
5640
  ),
5040
- line_number: import_zod9.z.number().int().positive().describe("1-based line number to read."),
5041
- char_offset: import_zod9.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5042
- char_limit: import_zod9.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5641
+ line_number: import_zod8.z.number().int().positive().describe("1-based line number to read."),
5642
+ char_offset: import_zod8.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5643
+ char_limit: import_zod8.z.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5043
5644
  }),
5044
5645
  execute: async (input, ctx) => {
5045
5646
  let resolved;
@@ -5050,7 +5651,7 @@ var createReadLineTool = (sandboxKey) => (0, import_core10.defineTool)({
5050
5651
  throw new Error(`Security error: ${String(error)}`);
5051
5652
  }
5052
5653
  try {
5053
- const stat = await import_node_fs14.promises.stat(resolved);
5654
+ const stat = await import_node_fs12.promises.stat(resolved);
5054
5655
  if (stat.isDirectory()) {
5055
5656
  return `Path is a directory: ${input.file_path}`;
5056
5657
  }
@@ -5058,24 +5659,26 @@ var createReadLineTool = (sandboxKey) => (0, import_core10.defineTool)({
5058
5659
  return `File not found: ${input.file_path}`;
5059
5660
  }
5060
5661
  try {
5061
- const content = await import_node_fs14.promises.readFile(resolved, "utf8");
5662
+ const content = await import_node_fs12.promises.readFile(resolved, "utf8");
5062
5663
  const lines = content.split(/\r?\n/);
5063
5664
  const lineIndex = input.line_number - 1;
5064
5665
  if (lineIndex >= lines.length) {
5065
5666
  return `Line number out of range: ${input.line_number} (total ${lines.length})`;
5066
5667
  }
5067
5668
  const line = lines[lineIndex] ?? "";
5669
+ const chars = splitGraphemes(line);
5068
5670
  const charOffset = input.char_offset ?? 0;
5069
5671
  const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5070
- if (charOffset > line.length) {
5071
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
5672
+ if (charOffset > chars.length) {
5673
+ return `char_offset out of range: ${charOffset} (line length ${chars.length})`;
5072
5674
  }
5073
- const segment = line.slice(charOffset, charOffset + charLimit);
5074
- const endOffset = charOffset + segment.length;
5075
- const hasMore = endOffset < line.length;
5675
+ const segmentChars = chars.slice(charOffset, charOffset + charLimit);
5676
+ const segment = segmentChars.join("");
5677
+ const endOffset = charOffset + segmentChars.length;
5678
+ const hasMore = endOffset < chars.length;
5076
5679
  const header = [
5077
5680
  `line_number=${input.line_number}`,
5078
- `line_length=${line.length}`,
5681
+ `line_length=${chars.length}`,
5079
5682
  `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5080
5683
  ].join(" ");
5081
5684
  let output = `${header}
@@ -5085,7 +5688,7 @@ ${segment}`;
5085
5688
 
5086
5689
  Use char_offset=${endOffset} to continue.`;
5087
5690
  output += `
5088
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5691
+ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5089
5692
  }
5090
5693
  return output;
5091
5694
  } catch (error) {
@@ -5095,8 +5698,8 @@ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"
5095
5698
  });
5096
5699
 
5097
5700
  // src/tools/search.ts
5098
- var import_core11 = require("@codelia/core");
5099
- var import_zod10 = require("zod");
5701
+ var import_core10 = require("@codelia/core");
5702
+ var import_zod9 = require("zod");
5100
5703
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
5101
5704
  var shouldKeepUrl = (url, allowedDomains) => {
5102
5705
  if (!allowedDomains.length) return true;
@@ -5212,14 +5815,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
5212
5815
  const parsed = parseBrave(payload);
5213
5816
  return normalizeEntries(parsed, allowedDomains, maxResults);
5214
5817
  };
5215
- var createSearchTool = (options) => (0, import_core11.defineTool)({
5818
+ var createSearchTool = (options) => (0, import_core10.defineTool)({
5216
5819
  name: "search",
5217
5820
  description: "Search the web and return concise source candidates.",
5218
- input: import_zod10.z.object({
5219
- query: import_zod10.z.string().min(1).describe("Search query."),
5220
- max_results: import_zod10.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5221
- backend: import_zod10.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5222
- allowed_domains: import_zod10.z.array(import_zod10.z.string().min(1)).optional().describe("Optional allowlist of domains.")
5821
+ input: import_zod9.z.object({
5822
+ query: import_zod9.z.string().min(1).describe("Search query."),
5823
+ max_results: import_zod9.z.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5824
+ backend: import_zod9.z.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5825
+ allowed_domains: import_zod9.z.array(import_zod9.z.string().min(1)).optional().describe("Optional allowlist of domains.")
5223
5826
  }),
5224
5827
  execute: async (input) => {
5225
5828
  const backend = input.backend ?? options.defaultBackend;
@@ -5254,13 +5857,13 @@ var createSearchTool = (options) => (0, import_core11.defineTool)({
5254
5857
  });
5255
5858
 
5256
5859
  // src/tools/shell.ts
5257
- var import_node_crypto6 = __toESM(require("crypto"), 1);
5258
- var import_core12 = require("@codelia/core");
5860
+ var import_node_crypto7 = __toESM(require("crypto"), 1);
5861
+ var import_core11 = require("@codelia/core");
5259
5862
  var import_storage7 = require("@codelia/storage");
5260
- var import_zod11 = require("zod");
5863
+ var import_zod10 = require("zod");
5261
5864
 
5262
5865
  // src/tasks/manager.ts
5263
- var import_node_crypto5 = __toESM(require("crypto"), 1);
5866
+ var import_node_crypto6 = __toESM(require("crypto"), 1);
5264
5867
  var import_storage6 = require("@codelia/storage");
5265
5868
 
5266
5869
  // src/tasks/process-control.ts
@@ -5357,10 +5960,10 @@ var TaskManager = class {
5357
5960
  shuttingDown = false;
5358
5961
  constructor(options = {}) {
5359
5962
  this.registry = options.registry ?? new import_storage6.TaskRegistryStore();
5360
- this.runtimeId = options.runtimeId ?? import_node_crypto5.default.randomUUID();
5963
+ this.runtimeId = options.runtimeId ?? import_node_crypto6.default.randomUUID();
5361
5964
  this.ownerPid = options.ownerPid ?? process.pid;
5362
5965
  this.now = options.now ?? nowIso3;
5363
- this.randomId = options.randomId ?? (() => import_node_crypto5.default.randomUUID());
5966
+ this.randomId = options.randomId ?? (() => import_node_crypto6.default.randomUUID());
5364
5967
  this.sleep = options.sleep ?? sleepDefault;
5365
5968
  this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5366
5969
  this.gracePeriodMs = options.gracePeriodMs ?? DEFAULT_GRACE_PERIOD_MS;
@@ -5767,27 +6370,27 @@ var summarizeCommand = (command) => {
5767
6370
  var DEFAULT_EXCERPT_LINES = 80;
5768
6371
  var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
5769
6372
  var FORCE_KILL_DELAY_MS = 2e3;
5770
- var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
5771
- var truncateUtf8Prefix = (value, maxBytes) => {
6373
+ var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
6374
+ var truncateUtf8Prefix2 = (value, maxBytes) => {
5772
6375
  if (maxBytes <= 0 || value.length === 0) return "";
5773
6376
  let bytes = 0;
5774
6377
  let out = "";
5775
6378
  for (const ch of value) {
5776
- const next = utf8ByteLength(ch);
6379
+ const next = utf8ByteLength2(ch);
5777
6380
  if (bytes + next > maxBytes) break;
5778
6381
  out += ch;
5779
6382
  bytes += next;
5780
6383
  }
5781
6384
  return out;
5782
6385
  };
5783
- var truncateUtf8Suffix = (value, maxBytes) => {
6386
+ var truncateUtf8Suffix2 = (value, maxBytes) => {
5784
6387
  if (maxBytes <= 0 || value.length === 0) return "";
5785
6388
  let bytes = 0;
5786
6389
  const chars = Array.from(value);
5787
6390
  const out = [];
5788
6391
  for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
5789
6392
  const ch = chars[idx];
5790
- const next = utf8ByteLength(ch);
6393
+ const next = utf8ByteLength2(ch);
5791
6394
  if (bytes + next > maxBytes) break;
5792
6395
  out.push(ch);
5793
6396
  bytes += next;
@@ -5795,7 +6398,7 @@ var truncateUtf8Suffix = (value, maxBytes) => {
5795
6398
  out.reverse();
5796
6399
  return out.join("");
5797
6400
  };
5798
- var excerptByLines = (value) => {
6401
+ var excerptByLines2 = (value) => {
5799
6402
  const lines = value.split(/\r?\n/);
5800
6403
  if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
5801
6404
  const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
@@ -5803,20 +6406,20 @@ var excerptByLines = (value) => {
5803
6406
  const omitted = lines.length - head.length - tail.length;
5804
6407
  return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
5805
6408
  };
5806
- var excerptByBytes = (value, maxBytes) => {
5807
- if (utf8ByteLength(value) <= maxBytes) return value;
6409
+ var excerptByBytes2 = (value, maxBytes) => {
6410
+ if (utf8ByteLength2(value) <= maxBytes) return value;
5808
6411
  const marker = "\n...[truncated by size]...\n";
5809
- const markerBytes = utf8ByteLength(marker);
6412
+ const markerBytes = utf8ByteLength2(marker);
5810
6413
  if (maxBytes <= markerBytes + 2) {
5811
- return truncateUtf8Prefix(value, maxBytes);
6414
+ return truncateUtf8Prefix2(value, maxBytes);
5812
6415
  }
5813
6416
  const budget = maxBytes - markerBytes;
5814
6417
  const headBytes = Math.floor(budget / 2);
5815
6418
  const tailBytes = budget - headBytes;
5816
- return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
6419
+ return `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`;
5817
6420
  };
5818
- var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
5819
- var excerptText = (value) => excerptByBytes(excerptByLines(value), MAX_INLINE_OUTPUT_BYTES);
6421
+ var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength2(value) > MAX_INLINE_OUTPUT_BYTES;
6422
+ var excerptText = (value) => excerptByBytes2(excerptByLines2(value), MAX_INLINE_OUTPUT_BYTES);
5820
6423
  var buildShellTaskResultBase = (options) => {
5821
6424
  const stdoutTruncated = needsInlineTruncation(options.rawStdout);
5822
6425
  const stderrTruncated = needsInlineTruncation(options.rawStderr);
@@ -6050,15 +6653,15 @@ var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
6050
6653
 
6051
6654
  // src/tools/shell.ts
6052
6655
  var LIVE_LOG_TAIL_BYTES = 64 * 1024;
6053
- var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
6054
- var truncateUtf8Suffix2 = (value, maxBytes) => {
6656
+ var utf8ByteLength3 = (value) => Buffer.byteLength(value, "utf8");
6657
+ var truncateUtf8Suffix3 = (value, maxBytes) => {
6055
6658
  if (maxBytes <= 0 || value.length === 0) return "";
6056
6659
  let bytes = 0;
6057
6660
  const chars = Array.from(value);
6058
6661
  const out = [];
6059
6662
  for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
6060
6663
  const ch = chars[idx];
6061
- const next = utf8ByteLength2(ch);
6664
+ const next = utf8ByteLength3(ch);
6062
6665
  if (bytes + next > maxBytes) break;
6063
6666
  out.push(ch);
6064
6667
  bytes += next;
@@ -6067,7 +6670,7 @@ var truncateUtf8Suffix2 = (value, maxBytes) => {
6067
6670
  return out.join("");
6068
6671
  };
6069
6672
  var tailLiveOutput = (value, maxBytes) => {
6070
- const totalBytes = utf8ByteLength2(value);
6673
+ const totalBytes = utf8ByteLength3(value);
6071
6674
  if (totalBytes <= maxBytes) {
6072
6675
  return {
6073
6676
  content: value,
@@ -6076,80 +6679,80 @@ var tailLiveOutput = (value, maxBytes) => {
6076
6679
  omittedBytes: 0
6077
6680
  };
6078
6681
  }
6079
- const content = truncateUtf8Suffix2(value, maxBytes);
6682
+ const content = truncateUtf8Suffix3(value, maxBytes);
6080
6683
  return {
6081
6684
  content,
6082
6685
  truncated: true,
6083
6686
  totalBytes,
6084
- omittedBytes: Math.max(0, totalBytes - utf8ByteLength2(content))
6687
+ omittedBytes: Math.max(0, totalBytes - utf8ByteLength3(content))
6085
6688
  };
6086
6689
  };
6087
6690
  var SHELL_LABEL_MAX_CHARS = 80;
6088
6691
  var SHELL_LIST_DEFAULT_LIMIT = 20;
6089
6692
  var SHELL_LIST_MAX_LIMIT = 100;
6090
6693
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
6091
- var shellStateSchema = import_zod11.z.enum([
6694
+ var shellStateSchema = import_zod10.z.enum([
6092
6695
  "queued",
6093
6696
  "running",
6094
6697
  "completed",
6095
6698
  "failed",
6096
6699
  "cancelled"
6097
6700
  ]);
6098
- var shellRunSchema = import_zod11.z.object({
6099
- command: import_zod11.z.string().describe(
6701
+ var shellRunSchema = import_zod10.z.object({
6702
+ command: import_zod10.z.string().describe(
6100
6703
  "Shell command to execute as a runtime-managed child process in the current workspace."
6101
6704
  ),
6102
- label: import_zod11.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6705
+ label: import_zod10.z.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6103
6706
  `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
6104
6707
  ),
6105
- timeout: import_zod11.z.number().int().positive().optional().describe(
6106
- `Execution timeout in seconds. Foreground default: ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Background accepts larger values up to ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit to keep the managed child job running until completion, cancel, or runtime exit.`
6708
+ timeout: import_zod10.z.number().int().positive().optional().describe(
6709
+ `Execution timeout in seconds. Foreground default: ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Detached-wait mode accepts larger values up to ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit to keep the managed child job running until completion, cancel, or runtime exit.`
6107
6710
  ),
6108
- background: import_zod11.z.boolean().optional().describe(
6109
- "Detach the wait and return compact JSON with the task key immediately. The runtime still owns the child process, so this is not persistence/daemonization. Manage it with shell_status/logs/wait/result/cancel. Default: false."
6711
+ detached_wait: import_zod10.z.boolean().optional().describe(
6712
+ "Skip the attached wait and return the task key immediately. The runtime still owns the child process. Use this only for finite jobs you will later inspect, wait on, or cancel. If you need a service-style process to keep running independently, start it with an explicit OS/shell-native out-of-process method such as `nohup`, `setsid`, `disown`, a service manager, or `docker compose up -d`, and verify readiness separately. Default: false."
6110
6713
  )
6111
6714
  }).superRefine((input, ctx) => {
6112
6715
  if (input.timeout === void 0) {
6113
6716
  return;
6114
6717
  }
6115
- if (input.background ?? false) {
6718
+ if (input.detached_wait ?? false) {
6116
6719
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6117
6720
  ctx.addIssue({
6118
- code: import_zod11.z.ZodIssueCode.custom,
6721
+ code: import_zod10.z.ZodIssueCode.custom,
6119
6722
  path: ["timeout"],
6120
- message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6723
+ message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6121
6724
  });
6122
6725
  }
6123
6726
  return;
6124
6727
  }
6125
6728
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6126
6729
  ctx.addIssue({
6127
- code: import_zod11.z.ZodIssueCode.custom,
6730
+ code: import_zod10.z.ZodIssueCode.custom,
6128
6731
  path: ["timeout"],
6129
6732
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6130
6733
  });
6131
6734
  }
6132
6735
  });
6133
- var shellTaskKeySchema = import_zod11.z.object({
6134
- key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list.")
6736
+ var shellTaskKeySchema = import_zod10.z.object({
6737
+ key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list.")
6135
6738
  });
6136
6739
  var shellWaitSchema = shellTaskKeySchema.extend({
6137
- wait_timeout: import_zod11.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6740
+ wait_timeout: import_zod10.z.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6138
6741
  `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. If the task is still running when the window expires, the tool returns compact status JSON instead of hanging.`
6139
6742
  )
6140
6743
  });
6141
- var shellStreamSchema = import_zod11.z.enum(["stdout", "stderr"]);
6142
- var shellListSchema = import_zod11.z.object({
6143
- limit: import_zod11.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6744
+ var shellStreamSchema = import_zod10.z.enum(["stdout", "stderr"]);
6745
+ var shellListSchema = import_zod10.z.object({
6746
+ limit: import_zod10.z.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6144
6747
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6145
6748
  ),
6146
6749
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6147
- include_terminal: import_zod11.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6750
+ include_terminal: import_zod10.z.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6148
6751
  });
6149
- var shellLogsSchema = import_zod11.z.object({
6150
- key: import_zod11.z.string().describe("Canonical shell task key returned by shell or shell_list."),
6752
+ var shellLogsSchema = import_zod10.z.object({
6753
+ key: import_zod10.z.string().describe("Canonical shell task key returned by shell or shell_list."),
6151
6754
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6152
- tail_lines: import_zod11.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6755
+ tail_lines: import_zod10.z.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6153
6756
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
6154
6757
  )
6155
6758
  });
@@ -6165,8 +6768,8 @@ var normalizeOptionalLabel = (value) => {
6165
6768
  const label = value.trim();
6166
6769
  return label.length > 0 ? label : void 0;
6167
6770
  };
6168
- var resolveShellTimeoutSeconds = (value, background) => {
6169
- if (background) {
6771
+ var resolveShellTimeoutSeconds = (value, detachedWait) => {
6772
+ if (detachedWait) {
6170
6773
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6171
6774
  }
6172
6775
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
@@ -6191,7 +6794,7 @@ var toShellKeyBase = (label) => {
6191
6794
  };
6192
6795
  var compactTaskId = (taskId) => {
6193
6796
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
6194
- return compact || import_node_crypto6.default.createHash("sha256").update(taskId).digest("hex");
6797
+ return compact || import_node_crypto7.default.createHash("sha256").update(taskId).digest("hex");
6195
6798
  };
6196
6799
  var buildShellTaskKey = async (tasks, taskId, label) => {
6197
6800
  const base = toShellKeyBase(label);
@@ -6248,7 +6851,7 @@ var shellBasePayload = (task) => ({
6248
6851
  });
6249
6852
  var shellStatusPayload = (task, options = {}) => ({
6250
6853
  ...shellBasePayload(task),
6251
- ...options.background ? { background: true } : {},
6854
+ ...options.detachedWait ? { detached_wait: true } : {},
6252
6855
  ...options.stillRunning ? { still_running: true } : {},
6253
6856
  ...options.aborted ? { aborted: true } : {}
6254
6857
  });
@@ -6507,9 +7110,9 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6507
7110
  };
6508
7111
  var createShellTool = (sandboxKey, options = {}) => {
6509
7112
  const shared = getSharedDeps(options);
6510
- return (0, import_core12.defineTool)({
7113
+ return (0, import_core11.defineTool)({
6511
7114
  name: "shell",
6512
- description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `background=true`, detach the wait and return compact JSON with the task key for follow-up tools.",
7115
+ description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `detached_wait=true`, skip the attached wait and return compact JSON with the task key for follow-up tools.",
6513
7116
  input: shellRunSchema,
6514
7117
  execute: async (input, ctx) => {
6515
7118
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6519,17 +7122,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6519
7122
  throw new Error("command is required.");
6520
7123
  }
6521
7124
  const label = normalizeOptionalLabel(input.label);
6522
- const background = input.background ?? false;
7125
+ const detachedWait = input.detached_wait ?? false;
6523
7126
  const timeoutSeconds = resolveShellTimeoutSeconds(
6524
7127
  input.timeout,
6525
- background
7128
+ detachedWait
6526
7129
  );
6527
7130
  const commandSummary = summarizeCommand(command);
6528
7131
  (0, import_logger.debugLog)(
6529
- `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
7132
+ `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} detached_wait=${detachedWait} command="${commandSummary}"`
6530
7133
  );
6531
7134
  try {
6532
- const taskId = import_node_crypto6.default.randomUUID();
7135
+ const taskId = import_node_crypto7.default.randomUUID();
6533
7136
  const taskKey = await buildShellTaskKey(shared.tasks, taskId, label);
6534
7137
  const task = await shared.tasks.spawn(
6535
7138
  {
@@ -6551,8 +7154,8 @@ var createShellTool = (sandboxKey, options = {}) => {
6551
7154
  outputCache: shared.outputCacheStore
6552
7155
  })
6553
7156
  );
6554
- if (background) {
6555
- return shellStatusPayload(task, { background: true });
7157
+ if (detachedWait) {
7158
+ return shellStatusPayload(task, { detachedWait: true });
6556
7159
  }
6557
7160
  const settled = await waitForForegroundRun(
6558
7161
  shared.tasks,
@@ -6571,7 +7174,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6571
7174
  };
6572
7175
  var createShellListTool = (options = {}) => {
6573
7176
  const shared = getSharedDeps(options);
6574
- return (0, import_core12.defineTool)({
7177
+ return (0, import_core11.defineTool)({
6575
7178
  name: "shell_list",
6576
7179
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6577
7180
  input: shellListSchema,
@@ -6602,7 +7205,7 @@ var createShellListTool = (options = {}) => {
6602
7205
  };
6603
7206
  var createShellStatusTool = (options = {}) => {
6604
7207
  const shared = getSharedDeps(options);
6605
- return (0, import_core12.defineTool)({
7208
+ return (0, import_core11.defineTool)({
6606
7209
  name: "shell_status",
6607
7210
  description: "Get the current state for a shell task as compact JSON.",
6608
7211
  input: shellTaskKeySchema,
@@ -6618,7 +7221,7 @@ var createShellStatusTool = (options = {}) => {
6618
7221
  };
6619
7222
  var createShellLogsTool = (options = {}) => {
6620
7223
  const shared = getSharedDeps(options);
6621
- return (0, import_core12.defineTool)({
7224
+ return (0, import_core11.defineTool)({
6622
7225
  name: "shell_logs",
6623
7226
  description: "Read recent stdout or stderr for a running or finished shell task.",
6624
7227
  input: shellLogsSchema,
@@ -6640,7 +7243,7 @@ var createShellLogsTool = (options = {}) => {
6640
7243
  };
6641
7244
  var createShellWaitTool = (options = {}) => {
6642
7245
  const shared = getSharedDeps(options);
6643
- return (0, import_core12.defineTool)({
7246
+ return (0, import_core11.defineTool)({
6644
7247
  name: "shell_wait",
6645
7248
  description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6646
7249
  input: shellWaitSchema,
@@ -6673,7 +7276,7 @@ var createShellWaitTool = (options = {}) => {
6673
7276
  };
6674
7277
  var createShellResultTool = (options = {}) => {
6675
7278
  const shared = getSharedDeps(options);
6676
- return (0, import_core12.defineTool)({
7279
+ return (0, import_core11.defineTool)({
6677
7280
  name: "shell_result",
6678
7281
  description: "Read the retained terminal result for a shell task as compact JSON.",
6679
7282
  input: shellTaskKeySchema,
@@ -6689,7 +7292,7 @@ var createShellResultTool = (options = {}) => {
6689
7292
  };
6690
7293
  var createShellCancelTool = (options = {}) => {
6691
7294
  const shared = getSharedDeps(options);
6692
- return (0, import_core12.defineTool)({
7295
+ return (0, import_core11.defineTool)({
6693
7296
  name: "shell_cancel",
6694
7297
  description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6695
7298
  input: shellTaskKeySchema,
@@ -6708,16 +7311,16 @@ var createShellCancelTool = (options = {}) => {
6708
7311
  };
6709
7312
 
6710
7313
  // src/tools/skill-load.ts
6711
- var import_core13 = require("@codelia/core");
6712
- var import_zod12 = require("zod");
6713
- var SkillLoadInputSchema = import_zod12.z.object({
6714
- name: import_zod12.z.string().min(1).optional().describe("Exact skill name to load."),
6715
- path: import_zod12.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
7314
+ var import_core12 = require("@codelia/core");
7315
+ var import_zod11 = require("zod");
7316
+ var SkillLoadInputSchema = import_zod11.z.object({
7317
+ name: import_zod11.z.string().min(1).optional().describe("Exact skill name to load."),
7318
+ path: import_zod11.z.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6716
7319
  }).refine((value) => !!value.name || !!value.path, {
6717
7320
  message: "name or path is required",
6718
7321
  path: ["name"]
6719
7322
  });
6720
- var createSkillLoadTool = (skillsResolverKey) => (0, import_core13.defineTool)({
7323
+ var createSkillLoadTool = (skillsResolverKey) => (0, import_core12.defineTool)({
6721
7324
  name: "skill_load",
6722
7325
  description: "Load full SKILL.md content by exact name or path.",
6723
7326
  input: SkillLoadInputSchema,
@@ -6763,15 +7366,15 @@ var createSkillLoadTool = (skillsResolverKey) => (0, import_core13.defineTool)({
6763
7366
  });
6764
7367
 
6765
7368
  // src/tools/skill-search.ts
6766
- var import_core14 = require("@codelia/core");
6767
- var import_zod13 = require("zod");
6768
- var createSkillSearchTool = (skillsResolverKey) => (0, import_core14.defineTool)({
7369
+ var import_core13 = require("@codelia/core");
7370
+ var import_zod12 = require("zod");
7371
+ var createSkillSearchTool = (skillsResolverKey) => (0, import_core13.defineTool)({
6769
7372
  name: "skill_search",
6770
7373
  description: "Search installed local skills by name, description, or path.",
6771
- input: import_zod13.z.object({
6772
- query: import_zod13.z.string().min(1).describe("Search query text."),
6773
- limit: import_zod13.z.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6774
- scope: import_zod13.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7374
+ input: import_zod12.z.object({
7375
+ query: import_zod12.z.string().min(1).describe("Search query text."),
7376
+ limit: import_zod12.z.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
7377
+ scope: import_zod12.z.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6775
7378
  }),
6776
7379
  execute: async (input, ctx) => {
6777
7380
  try {
@@ -6794,8 +7397,8 @@ var createSkillSearchTool = (skillsResolverKey) => (0, import_core14.defineTool)
6794
7397
  });
6795
7398
 
6796
7399
  // src/tools/todo-mutate.ts
6797
- var import_core15 = require("@codelia/core");
6798
- var import_zod14 = require("zod");
7400
+ var import_core14 = require("@codelia/core");
7401
+ var import_zod13 = require("zod");
6799
7402
 
6800
7403
  // src/tools/todo-store.ts
6801
7404
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6905,37 +7508,37 @@ var pickNextTodo = (todos) => {
6905
7508
  var todoStore = /* @__PURE__ */ new Map();
6906
7509
 
6907
7510
  // src/tools/todo-mutate.ts
6908
- var todoStatusSchema = import_zod14.z.enum(["pending", "in_progress", "completed"]);
6909
- var todoPrioritySchema = import_zod14.z.number().int().min(1).max(5);
6910
- var todoItemSchema = import_zod14.z.object({
6911
- id: import_zod14.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6912
- content: import_zod14.z.string().min(1).describe("Todo item text."),
7511
+ var todoStatusSchema = import_zod13.z.enum(["pending", "in_progress", "completed"]);
7512
+ var todoPrioritySchema = import_zod13.z.number().int().min(1).max(5);
7513
+ var todoItemSchema = import_zod13.z.object({
7514
+ id: import_zod13.z.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
7515
+ content: import_zod13.z.string().min(1).describe("Todo item text."),
6913
7516
  status: todoStatusSchema.describe("Todo status."),
6914
7517
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6915
- notes: import_zod14.z.string().optional().describe("Optional implementation notes."),
6916
- activeForm: import_zod14.z.string().optional().describe("Optional in-progress phrasing for UI display.")
7518
+ notes: import_zod13.z.string().optional().describe("Optional implementation notes."),
7519
+ activeForm: import_zod13.z.string().optional().describe("Optional in-progress phrasing for UI display.")
6917
7520
  });
6918
- var todoPatchItemSchema = import_zod14.z.object({
6919
- id: import_zod14.z.string().min(1).describe("Target todo ID."),
6920
- remove: import_zod14.z.boolean().optional().describe("Set true to remove the todo item."),
6921
- content: import_zod14.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
7521
+ var todoPatchItemSchema = import_zod13.z.object({
7522
+ id: import_zod13.z.string().min(1).describe("Target todo ID."),
7523
+ remove: import_zod13.z.boolean().optional().describe("Set true to remove the todo item."),
7524
+ content: import_zod13.z.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6922
7525
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6923
7526
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6924
- notes: import_zod14.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6925
- activeForm: import_zod14.z.string().nullable().default(null).describe(
7527
+ notes: import_zod13.z.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
7528
+ activeForm: import_zod13.z.string().nullable().default(null).describe(
6926
7529
  "Updated in-progress phrasing (null keeps current, empty clears)."
6927
7530
  )
6928
7531
  });
6929
- var todoNewInputSchema = import_zod14.z.object({
6930
- todos: import_zod14.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
7532
+ var todoNewInputSchema = import_zod13.z.object({
7533
+ todos: import_zod13.z.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6931
7534
  }).strict();
6932
- var todoAppendInputSchema = import_zod14.z.object({
6933
- todos: import_zod14.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
7535
+ var todoAppendInputSchema = import_zod13.z.object({
7536
+ todos: import_zod13.z.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6934
7537
  }).strict();
6935
- var todoPatchInputSchema = import_zod14.z.object({
6936
- updates: import_zod14.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
7538
+ var todoPatchInputSchema = import_zod13.z.object({
7539
+ updates: import_zod13.z.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6937
7540
  }).strict();
6938
- var todoClearInputSchema = import_zod14.z.object({}).strict();
7541
+ var todoClearInputSchema = import_zod13.z.object({}).strict();
6939
7542
  var statusSymbol = {
6940
7543
  pending: "[ ]",
6941
7544
  in_progress: "[>]",
@@ -7030,7 +7633,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
7030
7633
  }
7031
7634
  return formatSuccess(outputMode, nextTodos);
7032
7635
  };
7033
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
7636
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => (0, import_core14.defineTool)({
7034
7637
  name,
7035
7638
  description,
7036
7639
  input,
@@ -7085,17 +7688,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
7085
7688
  );
7086
7689
 
7087
7690
  // src/tools/todo-read.ts
7088
- var import_core16 = require("@codelia/core");
7089
- var import_zod15 = require("zod");
7691
+ var import_core15 = require("@codelia/core");
7692
+ var import_zod14 = require("zod");
7090
7693
  var statusSymbol2 = {
7091
7694
  pending: "[ ]",
7092
7695
  in_progress: "[>]",
7093
7696
  completed: "[x]"
7094
7697
  };
7095
- var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.defineTool)({
7698
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core15.defineTool)({
7096
7699
  name: "todo_read",
7097
7700
  description: "Read the in-session todo plan with execution order and next step.",
7098
- input: import_zod15.z.object({}),
7701
+ input: import_zod14.z.object({}),
7099
7702
  execute: async (_input, ctx) => {
7100
7703
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7101
7704
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -7131,15 +7734,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => (0, import_core16.de
7131
7734
  });
7132
7735
 
7133
7736
  // src/tools/tool-output-cache.ts
7134
- var import_core17 = require("@codelia/core");
7135
- var import_zod16 = require("zod");
7136
- var createToolOutputCacheTool = (store) => (0, import_core17.defineTool)({
7737
+ var import_core16 = require("@codelia/core");
7738
+ var import_zod15 = require("zod");
7739
+ var createToolOutputCacheTool = (store) => (0, import_core16.defineTool)({
7137
7740
  name: "tool_output_cache",
7138
7741
  description: "Read cached tool output by ref_id.",
7139
- input: import_zod16.z.object({
7140
- ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7141
- offset: import_zod16.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7142
- limit: import_zod16.z.number().int().positive().optional().describe("Optional max number of lines to return.")
7742
+ input: import_zod15.z.object({
7743
+ ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7744
+ offset: import_zod15.z.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7745
+ limit: import_zod15.z.number().int().positive().optional().describe("Optional max number of lines to return.")
7143
7746
  }),
7144
7747
  execute: async (input) => {
7145
7748
  if (!store.read) {
@@ -7155,14 +7758,14 @@ var createToolOutputCacheTool = (store) => (0, import_core17.defineTool)({
7155
7758
  }
7156
7759
  }
7157
7760
  });
7158
- var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
7761
+ var createToolOutputCacheLineTool = (store) => (0, import_core16.defineTool)({
7159
7762
  name: "tool_output_cache_line",
7160
7763
  description: "Read a single cached output line segment by line number and char offset.",
7161
- input: import_zod16.z.object({
7162
- ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7163
- line_number: import_zod16.z.number().int().positive().describe("1-based line number to read."),
7164
- char_offset: import_zod16.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7165
- char_limit: import_zod16.z.number().int().positive().optional().describe("Max chars to return.")
7764
+ input: import_zod15.z.object({
7765
+ ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7766
+ line_number: import_zod15.z.number().int().positive().describe("1-based line number to read."),
7767
+ char_offset: import_zod15.z.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7768
+ char_limit: import_zod15.z.number().int().positive().optional().describe("Max chars to return.")
7166
7769
  }),
7167
7770
  execute: async (input) => {
7168
7771
  if (!store.readLine) {
@@ -7179,16 +7782,16 @@ var createToolOutputCacheLineTool = (store) => (0, import_core17.defineTool)({
7179
7782
  }
7180
7783
  }
7181
7784
  });
7182
- var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
7785
+ var createToolOutputCacheGrepTool = (store) => (0, import_core16.defineTool)({
7183
7786
  name: "tool_output_cache_grep",
7184
7787
  description: "Search cached tool output by ref_id.",
7185
- input: import_zod16.z.object({
7186
- ref_id: import_zod16.z.string().describe("Tool output reference ID."),
7187
- pattern: import_zod16.z.string().describe("Text or regex pattern to search for."),
7188
- regex: import_zod16.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7189
- before: import_zod16.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7190
- after: import_zod16.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7191
- max_matches: import_zod16.z.number().int().positive().optional().describe("Maximum number of matches to return.")
7788
+ input: import_zod15.z.object({
7789
+ ref_id: import_zod15.z.string().describe("Tool output reference ID."),
7790
+ pattern: import_zod15.z.string().describe("Text or regex pattern to search for."),
7791
+ regex: import_zod15.z.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7792
+ before: import_zod15.z.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7793
+ after: import_zod15.z.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7794
+ max_matches: import_zod15.z.number().int().positive().optional().describe("Maximum number of matches to return.")
7192
7795
  }),
7193
7796
  execute: async (input) => {
7194
7797
  if (!store.grep) {
@@ -7208,28 +7811,420 @@ var createToolOutputCacheGrepTool = (store) => (0, import_core17.defineTool)({
7208
7811
  }
7209
7812
  });
7210
7813
 
7211
- // src/tools/write.ts
7212
- var import_node_fs15 = require("fs");
7213
- var import_node_path13 = __toESM(require("path"), 1);
7814
+ // src/tools/view-image.ts
7815
+ var import_node_fs13 = require("fs");
7816
+ var import_node_path12 = __toESM(require("path"), 1);
7817
+ var import_core17 = require("@codelia/core");
7818
+ var import_zod16 = require("zod");
7819
+ var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
7820
+ var MAX_MAX_BYTES = 10 * 1024 * 1024;
7821
+ var MIME_BY_EXTENSION = {
7822
+ ".png": "image/png",
7823
+ ".jpg": "image/jpeg",
7824
+ ".jpeg": "image/jpeg",
7825
+ ".webp": "image/webp",
7826
+ ".gif": "image/gif"
7827
+ };
7828
+ var resolveImageMime = (filePath) => {
7829
+ return MIME_BY_EXTENSION[import_node_path12.default.extname(filePath).toLowerCase()] ?? null;
7830
+ };
7831
+ var createViewImageTool = (sandboxKey) => (0, import_core17.defineTool)({
7832
+ name: "view_image",
7833
+ description: "Load a local image file and return it as a multimodal content part.",
7834
+ input: import_zod16.z.object({
7835
+ file_path: import_zod16.z.string().describe(
7836
+ "Image file path. Sandbox-bounded unless full-access mode is active."
7837
+ ),
7838
+ detail: import_zod16.z.enum(["auto", "low", "high"]).optional().describe("Image detail hint. Default auto."),
7839
+ max_bytes: import_zod16.z.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max allowed file size in bytes. Default 5242880.")
7840
+ }),
7841
+ execute: async (input, ctx) => {
7842
+ let resolved;
7843
+ try {
7844
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
7845
+ resolved = sandbox.resolvePath(input.file_path);
7846
+ } catch (error) {
7847
+ throw new Error(`Security error: ${String(error)}`);
7848
+ }
7849
+ const mediaType = resolveImageMime(input.file_path);
7850
+ if (!mediaType) {
7851
+ return `Unsupported image type: ${input.file_path}`;
7852
+ }
7853
+ try {
7854
+ const stat = await import_node_fs13.promises.stat(resolved);
7855
+ if (stat.isDirectory()) {
7856
+ return `Path is a directory: ${input.file_path}`;
7857
+ }
7858
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
7859
+ if (stat.size > maxBytes) {
7860
+ return `Image too large: ${input.file_path} (${stat.size} bytes > ${maxBytes} bytes)`;
7861
+ }
7862
+ const buffer = await import_node_fs13.promises.readFile(resolved);
7863
+ const dataUrl = `data:${mediaType};base64,${buffer.toString("base64")}`;
7864
+ return [
7865
+ {
7866
+ type: "text",
7867
+ text: `Image loaded: ${input.file_path}
7868
+ `
7869
+ },
7870
+ {
7871
+ type: "image_url",
7872
+ image_url: {
7873
+ url: dataUrl,
7874
+ media_type: mediaType,
7875
+ detail: input.detail ?? "auto"
7876
+ }
7877
+ }
7878
+ ];
7879
+ } catch (error) {
7880
+ if (error.code === "ENOENT") {
7881
+ return `File not found: ${input.file_path}`;
7882
+ }
7883
+ return `Error loading image: ${String(error)}`;
7884
+ }
7885
+ }
7886
+ });
7887
+
7888
+ // src/tools/webfetch.ts
7214
7889
  var import_core18 = require("@codelia/core");
7215
7890
  var import_zod17 = require("zod");
7216
- var buildDiffPreview = (content, filePath) => {
7217
- const diff = createUnifiedDiff(filePath, "", content);
7218
- if (!diff) {
7219
- return `--- ${filePath}
7220
- +++ ${filePath}
7221
- @@ -0,0 +0,0 @@`;
7891
+ var DEFAULT_TIMEOUT_MS3 = 1e4;
7892
+ var MAX_TIMEOUT_MS = 3e4;
7893
+ var DEFAULT_MAX_BYTES3 = 2e5;
7894
+ var MAX_MAX_BYTES2 = 1e6;
7895
+ var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
7896
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
7897
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
7898
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
7899
+ "SELF_SIGNED_CERT_IN_CHAIN",
7900
+ "ERR_TLS_CERT_ALTNAME_INVALID",
7901
+ "CERT_HAS_EXPIRED",
7902
+ "CERT_NOT_YET_VALID"
7903
+ ]);
7904
+ var normalizeWhitespace = (value) => value.replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
7905
+ var decodeHtmlEntities = (value) => value.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'");
7906
+ var htmlToText = (html) => {
7907
+ const withoutScripts = html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<noscript[\s\S]*?<\/noscript>/gi, "").replace(/<!--[\s\S]*?-->/g, "");
7908
+ const withBreaks = withoutScripts.replace(/<br\s*\/?>/gi, "\n").replace(
7909
+ /<\/(p|div|section|article|header|footer|main|aside|nav|tr|table|ul|ol|li|h[1-6])>/gi,
7910
+ "\n"
7911
+ ).replace(/<(li)[^>]*>/gi, "- ");
7912
+ const stripped = withBreaks.replace(/<[^>]+>/g, " ");
7913
+ return normalizeWhitespace(decodeHtmlEntities(stripped));
7914
+ };
7915
+ var htmlToMarkdown = (html) => {
7916
+ const withoutScripts = html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<noscript[\s\S]*?<\/noscript>/gi, "").replace(/<!--[\s\S]*?-->/g, "");
7917
+ const linked = withoutScripts.replace(
7918
+ /<a\s+[^>]*href=(["'])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi,
7919
+ (_match, _quote, href, text) => {
7920
+ const label = htmlToText(text) || href;
7921
+ return `[${label}](${href})`;
7922
+ }
7923
+ );
7924
+ const headed = linked.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, (_m, text) => {
7925
+ return `# ${htmlToText(text)}
7926
+
7927
+ `;
7928
+ }).replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, (_m, text) => {
7929
+ return `## ${htmlToText(text)}
7930
+
7931
+ `;
7932
+ }).replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, (_m, text) => {
7933
+ return `### ${htmlToText(text)}
7934
+
7935
+ `;
7936
+ }).replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m, text) => {
7937
+ return `- ${htmlToText(text)}
7938
+ `;
7939
+ }).replace(/<br\s*\/?>/gi, "\n").replace(
7940
+ /<\/(p|div|section|article|header|footer|main|aside|nav|ul|ol)>/gi,
7941
+ "\n\n"
7942
+ );
7943
+ return normalizeWhitespace(
7944
+ decodeHtmlEntities(headed.replace(/<[^>]+>/g, " "))
7945
+ );
7946
+ };
7947
+ var isTextualContentType = (contentType) => {
7948
+ const normalized = contentType.toLowerCase();
7949
+ if (!normalized) return true;
7950
+ if (normalized.startsWith("text/")) return true;
7951
+ if (normalized.includes("json")) return true;
7952
+ if (normalized.includes("xml")) return true;
7953
+ if (normalized.includes("javascript")) return true;
7954
+ if (normalized.includes("xhtml")) return true;
7955
+ if (normalized.includes("svg")) return true;
7956
+ if (normalized.includes("markdown")) return true;
7957
+ if (normalized.includes("yaml")) return true;
7958
+ if (normalized.includes("x-www-form-urlencoded")) return true;
7959
+ return false;
7960
+ };
7961
+ var looksBinaryBuffer = (buffer) => {
7962
+ if (buffer.length === 0) return false;
7963
+ let suspicious = 0;
7964
+ const sample = Math.min(buffer.length, 512);
7965
+ for (let index = 0; index < sample; index += 1) {
7966
+ const byte = buffer[index] ?? 0;
7967
+ if (byte === 0) {
7968
+ return true;
7969
+ }
7970
+ const isControl = byte < 32 && byte !== 9 && byte !== 10 && byte !== 12 && byte !== 13;
7971
+ if (isControl) {
7972
+ suspicious += 1;
7973
+ }
7974
+ }
7975
+ return suspicious / sample > 0.1;
7976
+ };
7977
+ var readResponseBody = async (response, maxBytes) => {
7978
+ const contentLength = Number(response.headers.get("content-length"));
7979
+ if (!response.body) {
7980
+ const buffer = Buffer.from(await response.arrayBuffer());
7981
+ if (buffer.byteLength <= maxBytes) {
7982
+ return { buffer, truncated: false, byteSize: buffer.byteLength };
7983
+ }
7984
+ const truncated2 = buffer.subarray(0, maxBytes);
7985
+ return {
7986
+ buffer: truncated2,
7987
+ truncated: true,
7988
+ byteSize: Number.isFinite(contentLength) ? contentLength : buffer.byteLength
7989
+ };
7990
+ }
7991
+ const reader = response.body.getReader();
7992
+ const chunks = [];
7993
+ let total = 0;
7994
+ let truncated = false;
7995
+ while (true) {
7996
+ const { value, done } = await reader.read();
7997
+ if (done) break;
7998
+ if (!value) continue;
7999
+ if (total + value.byteLength > maxBytes) {
8000
+ const remaining = maxBytes - total;
8001
+ if (remaining > 0) {
8002
+ chunks.push(value.slice(0, remaining));
8003
+ total += remaining;
8004
+ }
8005
+ truncated = true;
8006
+ await reader.cancel();
8007
+ break;
8008
+ }
8009
+ chunks.push(value);
8010
+ total += value.byteLength;
8011
+ }
8012
+ const combined = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
8013
+ return {
8014
+ buffer: combined,
8015
+ truncated,
8016
+ byteSize: Number.isFinite(contentLength) && contentLength > total ? contentLength : total
8017
+ };
8018
+ };
8019
+ var looksLikeHtml = (contentType, text) => contentType.includes("text/html") || /<html[\s>]|<!doctype html/i.test(text);
8020
+ var extractCharset = (contentType) => {
8021
+ const match = /charset\s*=\s*("?)([^;"\s]+)\1/i.exec(contentType);
8022
+ if (!match) return null;
8023
+ const charset = match[2]?.trim();
8024
+ return charset ? charset : null;
8025
+ };
8026
+ var decodeBuffer = (buffer, contentType) => {
8027
+ const charset = extractCharset(contentType);
8028
+ if (charset) {
8029
+ try {
8030
+ return new TextDecoder(charset).decode(buffer);
8031
+ } catch {
8032
+ }
8033
+ }
8034
+ return buffer.toString("utf8");
8035
+ };
8036
+ var extractTitle = (html) => {
8037
+ const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
8038
+ if (!match) return void 0;
8039
+ const title = htmlToText(match[1] ?? "");
8040
+ return title || void 0;
8041
+ };
8042
+ var describeUnknownError = (error) => {
8043
+ if (error instanceof Error && error.message) {
8044
+ return error.message;
8045
+ }
8046
+ return String(error);
8047
+ };
8048
+ var extractNestedCode = (error) => {
8049
+ if (!error || typeof error !== "object") return null;
8050
+ const direct = error.code;
8051
+ if (typeof direct === "string" && direct.trim().length > 0) {
8052
+ return direct.trim();
8053
+ }
8054
+ const cause = error.cause;
8055
+ if (!cause || typeof cause !== "object") return null;
8056
+ const causeCode = cause.code;
8057
+ if (typeof causeCode === "string" && causeCode.trim().length > 0) {
8058
+ return causeCode.trim();
8059
+ }
8060
+ return null;
8061
+ };
8062
+ var extractNestedMessage = (error) => {
8063
+ if (!error || typeof error !== "object") return null;
8064
+ const cause = error.cause;
8065
+ if (!cause || typeof cause !== "object") return null;
8066
+ const causeMessage = cause.message;
8067
+ if (typeof causeMessage === "string" && causeMessage.trim().length > 0) {
8068
+ return causeMessage.trim();
8069
+ }
8070
+ return null;
8071
+ };
8072
+ var compactFetchErrorDetail = (options) => {
8073
+ const genericMessage = options.rawMessage.trim().length === 0 || options.rawMessage.trim().toLowerCase() === "fetch failed";
8074
+ const causeText = options.causeMessage && options.causeMessage.toLowerCase() !== "fetch failed" ? options.causeMessage : null;
8075
+ const primary = !genericMessage ? options.rawMessage.trim() : causeText ?? (options.kind === "tls_error" ? "certificate validation failed" : options.kind === "dns_error" ? "dns lookup failed" : options.kind === "connection_refused" ? "connection refused" : options.kind === "connection_reset" ? "connection reset" : "network request failed");
8076
+ return options.code ? `${primary} (code=${options.code})` : primary;
8077
+ };
8078
+ var classifyFetchError = (error, timeoutMs) => {
8079
+ if (error?.name === "AbortError") {
8080
+ return {
8081
+ kind: "timeout",
8082
+ detail: `timed out after ${timeoutMs}ms`
8083
+ };
8084
+ }
8085
+ const rawMessage = describeUnknownError(error);
8086
+ const message = rawMessage.toLowerCase();
8087
+ const code = extractNestedCode(error)?.toUpperCase() ?? null;
8088
+ const causeMessage = extractNestedMessage(error);
8089
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN" || message.includes("getaddrinfo") || message.includes("dns")) {
8090
+ return {
8091
+ kind: "dns_error",
8092
+ detail: compactFetchErrorDetail({
8093
+ kind: "dns_error",
8094
+ rawMessage,
8095
+ code,
8096
+ causeMessage
8097
+ })
8098
+ };
8099
+ }
8100
+ if (code === "ECONNREFUSED" || message.includes("connection refused")) {
8101
+ return {
8102
+ kind: "connection_refused",
8103
+ detail: compactFetchErrorDetail({
8104
+ kind: "connection_refused",
8105
+ rawMessage,
8106
+ code,
8107
+ causeMessage
8108
+ })
8109
+ };
8110
+ }
8111
+ if (code === "ECONNRESET" || code === "EPIPE" || message.includes("socket hang up") || message.includes("connection reset")) {
8112
+ return {
8113
+ kind: "connection_reset",
8114
+ detail: compactFetchErrorDetail({
8115
+ kind: "connection_reset",
8116
+ rawMessage,
8117
+ code,
8118
+ causeMessage
8119
+ })
8120
+ };
8121
+ }
8122
+ if ((code?.startsWith("CERT_") ?? false) || (code?.startsWith("ERR_TLS_") ?? false) || code !== null && TLS_ERROR_CODES.has(code) || (code?.startsWith("ERR_SSL_") ?? false) || message.includes("tls") || message.includes("certificate") || message.includes("ssl")) {
8123
+ return {
8124
+ kind: "tls_error",
8125
+ detail: compactFetchErrorDetail({
8126
+ kind: "tls_error",
8127
+ rawMessage,
8128
+ code,
8129
+ causeMessage
8130
+ })
8131
+ };
7222
8132
  }
7223
- return diff;
8133
+ return {
8134
+ kind: "network_error",
8135
+ detail: compactFetchErrorDetail({
8136
+ kind: "network_error",
8137
+ rawMessage,
8138
+ code,
8139
+ causeMessage
8140
+ })
8141
+ };
7224
8142
  };
7225
- var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
8143
+ var createWebfetchTool = () => (0, import_core18.defineTool)({
8144
+ name: "webfetch",
8145
+ description: "Fetch an HTTP(S) URL and return bounded markdown, text, or HTML.",
8146
+ input: import_zod17.z.object({
8147
+ url: import_zod17.z.string().min(1).describe("HTTP(S) URL to fetch."),
8148
+ output_format: import_zod17.z.enum(["markdown", "text", "html"]).optional().describe("Output format. Default markdown."),
8149
+ timeout_ms: import_zod17.z.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe("Fetch timeout in ms. Default 10000."),
8150
+ max_bytes: import_zod17.z.number().int().positive().max(MAX_MAX_BYTES2).optional().describe("Max response bytes to keep. Default 200000.")
8151
+ }),
8152
+ execute: async (input) => {
8153
+ let url;
8154
+ try {
8155
+ url = new URL(input.url);
8156
+ } catch {
8157
+ return `Invalid URL: ${input.url}`;
8158
+ }
8159
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
8160
+ return `Unsupported URL protocol: ${url.protocol}`;
8161
+ }
8162
+ const timeoutMs = input.timeout_ms ?? DEFAULT_TIMEOUT_MS3;
8163
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES3;
8164
+ const outputFormat = input.output_format ?? "markdown";
8165
+ const controller = new AbortController();
8166
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
8167
+ try {
8168
+ const response = await fetch(url, {
8169
+ redirect: "follow",
8170
+ signal: controller.signal,
8171
+ headers: {
8172
+ Accept: outputFormat === "html" ? "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.8" : "text/html,text/plain,application/xhtml+xml;q=0.9,*/*;q=0.7"
8173
+ }
8174
+ });
8175
+ const contentType = response.headers.get("content-type") ?? "";
8176
+ const normalizedContentType = contentType.toLowerCase();
8177
+ if (contentType && !isTextualContentType(normalizedContentType)) {
8178
+ return `Unsupported content-type for webfetch: ${contentType.split(";")[0]}`;
8179
+ }
8180
+ const body = await readResponseBody(response, maxBytes);
8181
+ if (!contentType && looksBinaryBuffer(body.buffer)) {
8182
+ return "Unsupported content-type for webfetch: binary response";
8183
+ }
8184
+ const rawText = decodeBuffer(body.buffer, contentType);
8185
+ const isHtml = looksLikeHtml(normalizedContentType, rawText);
8186
+ let content = rawText;
8187
+ if (outputFormat === "html") {
8188
+ content = rawText;
8189
+ } else if (isHtml) {
8190
+ content = outputFormat === "text" ? htmlToText(rawText) : htmlToMarkdown(rawText);
8191
+ } else {
8192
+ content = normalizeWhitespace(rawText);
8193
+ }
8194
+ return {
8195
+ url: input.url,
8196
+ final_url: response.url || input.url,
8197
+ status: response.status,
8198
+ ok: response.ok,
8199
+ content_type: contentType || null,
8200
+ output_format: outputFormat,
8201
+ title: isHtml ? extractTitle(rawText) ?? null : null,
8202
+ content,
8203
+ truncated: body.truncated,
8204
+ byte_size: body.byteSize
8205
+ };
8206
+ } catch (error) {
8207
+ const classified = classifyFetchError(error, timeoutMs);
8208
+ return `Error fetching URL [${classified.kind}]: ${classified.detail}`;
8209
+ } finally {
8210
+ clearTimeout(timeout);
8211
+ }
8212
+ }
8213
+ });
8214
+
8215
+ // src/tools/write.ts
8216
+ var import_node_fs14 = require("fs");
8217
+ var import_node_path13 = __toESM(require("path"), 1);
8218
+ var import_core19 = require("@codelia/core");
8219
+ var import_zod18 = require("zod");
8220
+ var createWriteTool = (sandboxKey, outputCacheStore) => (0, import_core19.defineTool)({
7226
8221
  name: "write",
7227
8222
  description: "Write text to a file, creating parent directories if needed.",
7228
- input: import_zod17.z.object({
7229
- file_path: import_zod17.z.string().describe(
8223
+ input: import_zod18.z.object({
8224
+ file_path: import_zod18.z.string().describe(
7230
8225
  "File path. Sandbox-bounded unless full-access mode is active."
7231
8226
  ),
7232
- content: import_zod17.z.string().describe("UTF-8 text content to write.")
8227
+ content: import_zod18.z.string().describe("UTF-8 text content to write.")
7233
8228
  }),
7234
8229
  execute: async (input, ctx) => {
7235
8230
  let resolved;
@@ -7240,12 +8235,28 @@ var createWriteTool = (sandboxKey) => (0, import_core18.defineTool)({
7240
8235
  throw new Error(`Security error: ${String(error)}`);
7241
8236
  }
7242
8237
  try {
7243
- await import_node_fs15.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
7244
- await import_node_fs15.promises.writeFile(resolved, input.content, "utf8");
7245
- const diff = buildDiffPreview(input.content, input.file_path);
8238
+ let before = "";
8239
+ try {
8240
+ before = await import_node_fs14.promises.readFile(resolved, "utf8");
8241
+ } catch (error) {
8242
+ if (error.code !== "ENOENT") {
8243
+ throw error;
8244
+ }
8245
+ }
8246
+ await import_node_fs14.promises.mkdir(import_node_path13.default.dirname(resolved), { recursive: true });
8247
+ await import_node_fs14.promises.writeFile(resolved, input.content, "utf8");
8248
+ const diffPayload = await buildDiffPayload({
8249
+ toolName: "write",
8250
+ diff: createUnifiedDiff(input.file_path, before, input.content),
8251
+ outputCacheStore,
8252
+ emptyDiff: `--- ${input.file_path}
8253
+ +++ ${input.file_path}
8254
+ @@ -0,0 +0,0 @@`,
8255
+ debugContext: `file=${input.file_path}`
8256
+ });
7246
8257
  return {
7247
- summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
7248
- diff,
8258
+ summary: `Wrote ${Buffer.byteLength(input.content, "utf8")} bytes to ${input.file_path}`,
8259
+ ...diffPayload,
7249
8260
  file_path: input.file_path
7250
8261
  };
7251
8262
  } catch (error) {
@@ -7287,14 +8298,15 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
7287
8298
  }),
7288
8299
  createReadTool(sandboxKey),
7289
8300
  createReadLineTool(sandboxKey),
7290
- createWriteTool(sandboxKey),
7291
- createEditTool(sandboxKey),
8301
+ createWriteTool(sandboxKey, options.toolOutputCacheStore),
8302
+ createEditTool(sandboxKey, options.toolOutputCacheStore),
8303
+ createApplyPatchTool(sandboxKey, options.toolOutputCacheStore),
8304
+ createViewImageTool(sandboxKey),
7292
8305
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
7293
8306
  createSkillSearchTool(skillsResolverKey),
7294
8307
  createSkillLoadTool(skillsResolverKey),
8308
+ createWebfetchTool(),
7295
8309
  ...options.search ? [createSearchTool(options.search)] : [],
7296
- createGlobSearchTool(sandboxKey),
7297
- createGrepTool(sandboxKey),
7298
8310
  ...options.toolOutputCacheStore ? [
7299
8311
  createToolOutputCacheTool(options.toolOutputCacheStore),
7300
8312
  createToolOutputCacheLineTool(options.toolOutputCacheStore),
@@ -7784,6 +8796,9 @@ var createAgentFactory = (state, options = {}) => {
7784
8796
  const editTool = baseLocalTools.find(
7785
8797
  (tool) => tool.definition.name === "edit"
7786
8798
  );
8799
+ const applyPatchTool = baseLocalTools.find(
8800
+ (tool) => tool.definition.name === "apply_patch"
8801
+ );
7787
8802
  let mcpTools = [];
7788
8803
  if (options.mcpManager) {
7789
8804
  try {
@@ -7870,9 +8885,9 @@ var createAgentFactory = (state, options = {}) => {
7870
8885
  const requestedReasoning = resolveReasoningEffort(modelConfig.reasoning) ?? "medium";
7871
8886
  switch (provider) {
7872
8887
  case "openai": {
7873
- const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
7874
- const providerModelName = (0, import_core19.resolveProviderModelId)(
7875
- import_core19.DEFAULT_MODEL_REGISTRY,
8888
+ const modelName = modelConfig.name ?? import_core20.OPENAI_DEFAULT_MODEL;
8889
+ const providerModelName = (0, import_core20.resolveProviderModelId)(
8890
+ import_core20.DEFAULT_MODEL_REGISTRY,
7876
8891
  modelName,
7877
8892
  "openai"
7878
8893
  ) ?? modelName;
@@ -7882,7 +8897,7 @@ var createAgentFactory = (state, options = {}) => {
7882
8897
  });
7883
8898
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
7884
8899
  const websocketMode = modelConfig.experimental?.openai?.websocket_mode;
7885
- llm = new import_core19.ChatOpenAI({
8900
+ llm = new import_core20.ChatOpenAI({
7886
8901
  clientOptions: buildOpenAiClientOptions(authResolver, providerAuth),
7887
8902
  model: modelName,
7888
8903
  providerModel: providerModelName,
@@ -7896,13 +8911,13 @@ var createAgentFactory = (state, options = {}) => {
7896
8911
  break;
7897
8912
  }
7898
8913
  case "openrouter": {
7899
- const modelName = modelConfig.name ?? import_core19.OPENAI_DEFAULT_MODEL;
8914
+ const modelName = modelConfig.name ?? import_core20.OPENAI_DEFAULT_MODEL;
7900
8915
  const reasoning = resolveResponsesReasoning({
7901
8916
  model: modelName,
7902
8917
  requested: requestedReasoning
7903
8918
  });
7904
8919
  const textVerbosity = resolveTextVerbosity(modelConfig.verbosity);
7905
- llm = new import_core19.ChatOpenRouter({
8920
+ llm = new import_core20.ChatOpenRouter({
7906
8921
  clientOptions: buildOpenRouterClientOptions(providerAuth),
7907
8922
  model: modelName,
7908
8923
  reasoningEffort: reasoning.effort,
@@ -7914,7 +8929,7 @@ var createAgentFactory = (state, options = {}) => {
7914
8929
  break;
7915
8930
  }
7916
8931
  case "anthropic": {
7917
- const modelName = modelConfig.name ?? import_core19.ANTHROPIC_DEFAULT_MODEL;
8932
+ const modelName = modelConfig.name ?? import_core20.ANTHROPIC_DEFAULT_MODEL;
7918
8933
  const reasoning = resolveAnthropicReasoning({
7919
8934
  model: modelName,
7920
8935
  requested: requestedReasoning,
@@ -7934,7 +8949,7 @@ var createAgentFactory = (state, options = {}) => {
7934
8949
  `anthropic model '${modelName}' max token limit (${modelMaxTokens}) is not above thinking budget (${reasoning.thinking.budget_tokens}); using max_tokens=${maxTokens} to satisfy API constraint`
7935
8950
  );
7936
8951
  }
7937
- llm = new import_core19.ChatAnthropic({
8952
+ llm = new import_core20.ChatAnthropic({
7938
8953
  clientOptions: {
7939
8954
  apiKey: requireApiKeyAuth("Anthropic", providerAuth)
7940
8955
  },
@@ -7959,12 +8974,12 @@ var createAgentFactory = (state, options = {}) => {
7959
8974
  const totalBudgetTrimEnabled = envTruthy(
7960
8975
  process.env.CODELIA_TOOL_OUTPUT_TOTAL_TRIM
7961
8976
  );
7962
- const agent = new import_core19.Agent({
8977
+ const agent = new import_core20.Agent({
7963
8978
  llm,
7964
8979
  tools,
7965
8980
  hostedTools: hostedSearchDefinitions,
7966
8981
  systemPrompt,
7967
- modelRegistry: modelRegistry ?? import_core19.DEFAULT_MODEL_REGISTRY,
8982
+ modelRegistry: modelRegistry ?? import_core20.DEFAULT_MODEL_REGISTRY,
7968
8983
  toolOutputCache: {
7969
8984
  totalBudgetTrim: totalBudgetTrimEnabled
7970
8985
  },
@@ -8020,9 +9035,9 @@ var createAgentFactory = (state, options = {}) => {
8020
9035
  const resolved = sandbox.resolvePath(filePath);
8021
9036
  let before = "";
8022
9037
  try {
8023
- const stat = await import_node_fs16.promises.stat(resolved);
9038
+ const stat = await import_node_fs15.promises.stat(resolved);
8024
9039
  if (!stat.isDirectory()) {
8025
- before = await import_node_fs16.promises.readFile(resolved, "utf8");
9040
+ before = await import_node_fs15.promises.readFile(resolved, "utf8");
8026
9041
  }
8027
9042
  } catch {
8028
9043
  before = "";
@@ -8085,6 +9100,34 @@ var createAgentFactory = (state, options = {}) => {
8085
9100
  previewSummary = "Preview unavailable: dry-run failed";
8086
9101
  }
8087
9102
  }
9103
+ } else if (call.function.name === "apply_patch" && applyPatchTool) {
9104
+ const parsed = parseToolArgsObject(rawArgs);
9105
+ if (parsed) {
9106
+ const dryRunInput = { ...parsed, dry_run: true };
9107
+ try {
9108
+ const result = await applyPatchTool.executeRaw(
9109
+ JSON.stringify(dryRunInput),
9110
+ toolCtx
9111
+ );
9112
+ if (result && typeof result === "object") {
9113
+ const obj = unwrapToolJsonObject(result);
9114
+ if (!obj) {
9115
+ previewSummary = "Preview unavailable: unexpected dry-run output";
9116
+ } else {
9117
+ const diff = typeof obj.diff === "string" ? obj.diff : "";
9118
+ const summary = typeof obj.summary === "string" ? obj.summary : "";
9119
+ const preview = buildBoundedDiffPreview(diff);
9120
+ previewDiff = preview.diff;
9121
+ previewTruncated = preview.truncated;
9122
+ if (!previewDiff) {
9123
+ previewSummary = summary || "Preview: no diff content";
9124
+ }
9125
+ }
9126
+ }
9127
+ } catch {
9128
+ previewSummary = "Preview unavailable: dry-run failed";
9129
+ }
9130
+ }
8088
9131
  }
8089
9132
  if (runId) {
8090
9133
  if (previewDiff || previewSummary) {
@@ -8770,7 +9813,7 @@ var fetchDiscoveredOAuthConfig = async (serverUrl) => {
8770
9813
  };
8771
9814
 
8772
9815
  // src/mcp/tooling.ts
8773
- var import_node_crypto7 = __toESM(require("crypto"), 1);
9816
+ var import_node_crypto8 = __toESM(require("crypto"), 1);
8774
9817
  var MAX_SCHEMA_SIZE_BYTES = 64 * 1024;
8775
9818
  var MAX_TOOL_OUTPUT_CHARS = 1e5;
8776
9819
  var MAX_TOOLS_LIST_PAGES = 100;
@@ -8780,7 +9823,7 @@ var toSlug2 = (value) => {
8780
9823
  const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
8781
9824
  return slug || "tool";
8782
9825
  };
8783
- var hash8 = (value) => import_node_crypto7.default.createHash("sha256").update(value).digest("hex").slice(0, 8);
9826
+ var hash8 = (value) => import_node_crypto8.default.createHash("sha256").update(value).digest("hex").slice(0, 8);
8784
9827
  var clampToolName = (value) => {
8785
9828
  if (value.length <= 63) return value;
8786
9829
  return value.slice(0, 63);
@@ -9438,7 +10481,7 @@ var createContextHandlers = ({
9438
10481
  };
9439
10482
 
9440
10483
  // src/rpc/history.ts
9441
- var import_node_fs17 = require("fs");
10484
+ var import_node_fs16 = require("fs");
9442
10485
  var import_node_path14 = __toESM(require("path"), 1);
9443
10486
  var import_node_readline2 = require("readline");
9444
10487
  var import_protocol3 = require("@codelia/protocol");
@@ -9481,7 +10524,7 @@ var parseRunHeader = (headerLine) => {
9481
10524
  }
9482
10525
  };
9483
10526
  var readFirstLine = async (filePath) => {
9484
- const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
10527
+ const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
9485
10528
  const reader = (0, import_node_readline2.createInterface)({
9486
10529
  input: stream,
9487
10530
  crlfDelay: Number.POSITIVE_INFINITY
@@ -9501,7 +10544,7 @@ var collectRunCandidates = async (log2) => {
9501
10544
  const sessionsDir = paths.sessionsDir;
9502
10545
  let yearEntries;
9503
10546
  try {
9504
- yearEntries = await import_node_fs17.promises.readdir(sessionsDir, {
10547
+ yearEntries = await import_node_fs16.promises.readdir(sessionsDir, {
9505
10548
  withFileTypes: true,
9506
10549
  encoding: "utf8"
9507
10550
  });
@@ -9516,7 +10559,7 @@ var collectRunCandidates = async (log2) => {
9516
10559
  const yearPath = import_node_path14.default.join(sessionsDir, yearEntry.name);
9517
10560
  let monthEntries;
9518
10561
  try {
9519
- monthEntries = await import_node_fs17.promises.readdir(yearPath, {
10562
+ monthEntries = await import_node_fs16.promises.readdir(yearPath, {
9520
10563
  withFileTypes: true,
9521
10564
  encoding: "utf8"
9522
10565
  });
@@ -9529,7 +10572,7 @@ var collectRunCandidates = async (log2) => {
9529
10572
  const monthPath = import_node_path14.default.join(yearPath, monthEntry.name);
9530
10573
  let dayEntries;
9531
10574
  try {
9532
- dayEntries = await import_node_fs17.promises.readdir(monthPath, {
10575
+ dayEntries = await import_node_fs16.promises.readdir(monthPath, {
9533
10576
  withFileTypes: true,
9534
10577
  encoding: "utf8"
9535
10578
  });
@@ -9542,7 +10585,7 @@ var collectRunCandidates = async (log2) => {
9542
10585
  const dayPath = import_node_path14.default.join(monthPath, dayEntry.name);
9543
10586
  let files;
9544
10587
  try {
9545
- files = await import_node_fs17.promises.readdir(dayPath, {
10588
+ files = await import_node_fs16.promises.readdir(dayPath, {
9546
10589
  withFileTypes: true,
9547
10590
  encoding: "utf8"
9548
10591
  });
@@ -9554,7 +10597,7 @@ var collectRunCandidates = async (log2) => {
9554
10597
  if (!file.name.endsWith(".jsonl")) continue;
9555
10598
  const filePath = import_node_path14.default.join(dayPath, file.name);
9556
10599
  try {
9557
- const stat = await import_node_fs17.promises.stat(filePath);
10600
+ const stat = await import_node_fs16.promises.stat(filePath);
9558
10601
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
9559
10602
  } catch {
9560
10603
  }
@@ -9592,7 +10635,7 @@ var collectSessionRuns = async (sessionId, maxRuns, log2) => {
9592
10635
  return runs;
9593
10636
  };
9594
10637
  var readJsonl = async function* (filePath) {
9595
- const stream = (0, import_node_fs17.createReadStream)(filePath, { encoding: "utf8" });
10638
+ const stream = (0, import_node_fs16.createReadStream)(filePath, { encoding: "utf8" });
9596
10639
  let buffer = "";
9597
10640
  for await (const chunk of stream) {
9598
10641
  buffer += chunk;
@@ -9715,7 +10758,7 @@ var createHistoryHandlers = ({
9715
10758
  };
9716
10759
 
9717
10760
  // src/rpc/model.ts
9718
- var import_core20 = require("@codelia/core");
10761
+ var import_core21 = require("@codelia/core");
9719
10762
  var import_model_metadata3 = require("@codelia/model-metadata");
9720
10763
  var import_protocol4 = require("@codelia/protocol");
9721
10764
  var isSupportedProvider = (provider) => provider === "openai" || provider === "anthropic" || provider === "openrouter";
@@ -9723,7 +10766,7 @@ var resolveProviderModelEntry2 = (providerEntries, provider, model) => {
9723
10766
  if (!providerEntries) {
9724
10767
  return null;
9725
10768
  }
9726
- const providerModelId = (0, import_core20.resolveProviderModelId)(import_core20.DEFAULT_MODEL_REGISTRY, model, provider) ?? model;
10769
+ const providerModelId = (0, import_core21.resolveProviderModelId)(import_core21.DEFAULT_MODEL_REGISTRY, model, provider) ?? model;
9727
10770
  const candidates = [
9728
10771
  model,
9729
10772
  `${provider}/${model}`,
@@ -9752,7 +10795,7 @@ var normalizeUsdPer1M = (value) => {
9752
10795
  return value;
9753
10796
  };
9754
10797
  var buildModelListDetail = (entry, registry, provider, model) => {
9755
- const spec = (0, import_core20.resolveModel)(registry, model, provider);
10798
+ const spec = (0, import_core21.resolveModel)(registry, model, provider);
9756
10799
  if (!entry && !spec) return null;
9757
10800
  const detail = {};
9758
10801
  if (entry?.releaseDate?.trim()) {
@@ -9979,14 +11022,14 @@ var buildProviderModelList = async ({
9979
11022
  }
9980
11023
  }
9981
11024
  const models = sortModelsByReleaseDate(
9982
- (0, import_core20.listModels)(import_core20.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
11025
+ (0, import_core21.listModels)(import_core21.DEFAULT_MODEL_REGISTRY, provider).map((model) => model.id),
9983
11026
  provider,
9984
11027
  providerEntries
9985
11028
  );
9986
11029
  if (!includeDetails || !providerEntries) {
9987
11030
  return { models };
9988
11031
  }
9989
- const mergedRegistry = (0, import_core20.applyModelMetadata)(import_core20.DEFAULT_MODEL_REGISTRY, {
11032
+ const mergedRegistry = (0, import_core21.applyModelMetadata)(import_core21.DEFAULT_MODEL_REGISTRY, {
9990
11033
  models: {
9991
11034
  openai: provider === "openai" ? providerEntries : {},
9992
11035
  anthropic: provider === "anthropic" ? providerEntries : {},
@@ -10114,7 +11157,7 @@ var createModelHandlers = ({
10114
11157
  return;
10115
11158
  }
10116
11159
  if (provider !== "openrouter") {
10117
- const spec = (0, import_core20.resolveModel)(import_core20.DEFAULT_MODEL_REGISTRY, name, provider);
11160
+ const spec = (0, import_core21.resolveModel)(import_core21.DEFAULT_MODEL_REGISTRY, name, provider);
10118
11161
  if (!spec) {
10119
11162
  sendError(id, {
10120
11163
  code: import_protocol4.RPC_ERROR_CODE.INVALID_PARAMS,
@@ -10158,7 +11201,7 @@ var createModelHandlers = ({
10158
11201
  var import_protocol5 = require("@codelia/protocol");
10159
11202
 
10160
11203
  // src/rpc/run-debug.ts
10161
- var import_core21 = require("@codelia/core");
11204
+ var import_core22 = require("@codelia/core");
10162
11205
  var DEBUG_MAX_CONTENT_CHARS = 2e3;
10163
11206
  var DEBUG_MAX_LOG_CHARS = 2e4;
10164
11207
  var DEBUG_MAX_EVENT_RESULT_CHARS = 500;
@@ -10180,7 +11223,7 @@ var stringifyUnknown = (value) => {
10180
11223
  }
10181
11224
  };
10182
11225
  var contentToDebugText = (content, maxChars) => {
10183
- const text = (0, import_core21.stringifyContent)(content, {
11226
+ const text = (0, import_core22.stringifyContent)(content, {
10184
11227
  mode: "log",
10185
11228
  joiner: "\n",
10186
11229
  includeOtherPayload: true
@@ -12620,7 +13663,7 @@ var createRuntimeHandlers = ({
12620
13663
  };
12621
13664
 
12622
13665
  // src/runtime-state.ts
12623
- var import_node_crypto8 = __toESM(require("crypto"), 1);
13666
+ var import_node_crypto9 = __toESM(require("crypto"), 1);
12624
13667
  var RuntimeState = class {
12625
13668
  runSeq = /* @__PURE__ */ new Map();
12626
13669
  uiRequestCounter = 0;
@@ -12646,10 +13689,10 @@ var RuntimeState = class {
12646
13689
  runtimeSandboxRoot = null;
12647
13690
  diagnosticsEnabled = false;
12648
13691
  nextRunId() {
12649
- return import_node_crypto8.default.randomUUID();
13692
+ return import_node_crypto9.default.randomUUID();
12650
13693
  }
12651
13694
  nextSessionId() {
12652
- return import_node_crypto8.default.randomUUID();
13695
+ return import_node_crypto9.default.randomUUID();
12653
13696
  }
12654
13697
  beginRun(runId, uiContext) {
12655
13698
  this.activeRunId = runId;