@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.js CHANGED
@@ -3,7 +3,7 @@ import path18 from "path";
3
3
  import { SessionStateStoreImpl as SessionStateStoreImpl2 } from "@codelia/storage";
4
4
 
5
5
  // src/agent-factory.ts
6
- import { promises as fs16 } from "fs";
6
+ import { promises as fs15 } from "fs";
7
7
  import {
8
8
  Agent,
9
9
  ANTHROPIC_DEFAULT_MODEL,
@@ -2663,8 +2663,7 @@ var parseRawArgsForPrompt = (rawArgs) => parseRawArgsObject(rawArgs);
2663
2663
  var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2664
2664
  "read",
2665
2665
  "read_line",
2666
- "grep",
2667
- "glob_search",
2666
+ "view_image",
2668
2667
  "todo_read",
2669
2668
  "todo_new",
2670
2669
  "todo_append",
@@ -2689,7 +2688,8 @@ var SYSTEM_TOOL_ALLOWLIST_MINIMAL = [
2689
2688
  var SYSTEM_TOOL_ALLOWLIST_TRUSTED = [
2690
2689
  ...SYSTEM_TOOL_ALLOWLIST_MINIMAL,
2691
2690
  "write",
2692
- "edit"
2691
+ "edit",
2692
+ "apply_patch"
2693
2693
  ];
2694
2694
  var SYSTEM_SHELL_ALLOWLIST = [
2695
2695
  "pwd",
@@ -2801,7 +2801,7 @@ var PermissionService = class {
2801
2801
  const target = filePath || "(unknown path)";
2802
2802
  return {
2803
2803
  title: "Run tool?",
2804
- message: `write ${target} (${content.length} bytes)${rememberPreview}`
2804
+ message: `write ${target} (${Buffer.byteLength(content, "utf8")} bytes)${rememberPreview}`
2805
2805
  };
2806
2806
  }
2807
2807
  if (toolName === "edit") {
@@ -2814,6 +2814,32 @@ var PermissionService = class {
2814
2814
  message: `edit ${target} (match=${mode})${rememberPreview}`
2815
2815
  };
2816
2816
  }
2817
+ if (toolName === "apply_patch") {
2818
+ const parsed = parseRawArgsForPrompt(rawArgs);
2819
+ const patch = parsed && typeof parsed.patch === "string" ? parsed.patch : "";
2820
+ const lineCount = patch ? patch.split(/\r?\n/).length : 0;
2821
+ return {
2822
+ title: "Run tool?",
2823
+ message: `apply_patch (${lineCount} line${lineCount === 1 ? "" : "s"})${rememberPreview}`
2824
+ };
2825
+ }
2826
+ if (toolName === "view_image") {
2827
+ const parsed = parseRawArgsForPrompt(rawArgs);
2828
+ const filePath = parsed && typeof parsed.file_path === "string" ? parsed.file_path.trim() : "";
2829
+ return {
2830
+ title: "Run tool?",
2831
+ message: `view_image ${filePath || "(unknown path)"}${rememberPreview}`
2832
+ };
2833
+ }
2834
+ if (toolName === "webfetch") {
2835
+ const parsed = parseRawArgsForPrompt(rawArgs);
2836
+ const url = parsed && typeof parsed.url === "string" ? parsed.url.trim() : "";
2837
+ const format = parsed && typeof parsed.output_format === "string" ? parsed.output_format : "markdown";
2838
+ return {
2839
+ title: "Run tool?",
2840
+ message: `webfetch ${url || "(unknown url)"} (${format})${rememberPreview}`
2841
+ };
2842
+ }
2817
2843
  return { title: "Run tool?", message: toolName };
2818
2844
  }
2819
2845
  evaluate(toolName, rawArgs) {
@@ -3676,30 +3702,96 @@ var createAgentsResolveTool = (sandboxKey, agentsResolverKey) => defineTool({
3676
3702
  }
3677
3703
  });
3678
3704
 
3679
- // src/tools/done.ts
3680
- import { defineTool as defineTool2, TaskComplete } from "@codelia/core";
3681
- import { z as z3 } from "zod";
3682
- var createDoneTool = () => defineTool2({
3683
- name: "done",
3684
- description: "Mark the task as complete and return a final message.",
3685
- input: z3.object({
3686
- message: z3.string().describe("Final user-facing completion message.")
3687
- }),
3688
- execute: async (input) => {
3689
- throw new TaskComplete(input.message);
3690
- }
3691
- });
3692
-
3693
- // src/tools/edit.ts
3694
- import crypto3 from "crypto";
3705
+ // src/tools/apply-patch.ts
3695
3706
  import { promises as fs7 } from "fs";
3696
3707
  import path8 from "path";
3697
- import { defineTool as defineTool3 } from "@codelia/core";
3698
- import { z as z4 } from "zod";
3708
+ import { defineTool as defineTool2 } from "@codelia/core";
3709
+ import { z as z3 } from "zod";
3699
3710
 
3700
3711
  // src/utils/diff.ts
3712
+ var DEFAULT_DIFF_PREVIEW_LINES = 120;
3713
+ var DEFAULT_DIFF_PREVIEW_BYTES = 16 * 1024;
3701
3714
  var normalizeLineEndings = (text) => text.replace(/\r\n/g, "\n");
3702
3715
  var toLines = (text) => text === "" ? [] : text.split("\n");
3716
+ var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
3717
+ var truncateUtf8Prefix = (value, maxBytes) => {
3718
+ if (maxBytes <= 0 || value.length === 0) return "";
3719
+ let bytes = 0;
3720
+ let out = "";
3721
+ for (const ch of value) {
3722
+ const next = utf8ByteLength(ch);
3723
+ if (bytes + next > maxBytes) break;
3724
+ out += ch;
3725
+ bytes += next;
3726
+ }
3727
+ return out;
3728
+ };
3729
+ var truncateUtf8Suffix = (value, maxBytes) => {
3730
+ if (maxBytes <= 0 || value.length === 0) return "";
3731
+ let bytes = 0;
3732
+ const chars = Array.from(value);
3733
+ const out = [];
3734
+ for (let index = chars.length - 1; index >= 0; index -= 1) {
3735
+ const ch = chars[index];
3736
+ const next = utf8ByteLength(ch);
3737
+ if (bytes + next > maxBytes) break;
3738
+ out.push(ch);
3739
+ bytes += next;
3740
+ }
3741
+ out.reverse();
3742
+ return out.join("");
3743
+ };
3744
+ var excerptByLines = (value, maxLines) => {
3745
+ const lines = value.split(/\r?\n/);
3746
+ if (lines.length <= maxLines) {
3747
+ return { text: value, truncated: false };
3748
+ }
3749
+ const headCount = Math.ceil(maxLines / 2);
3750
+ const tailCount = Math.floor(maxLines / 2);
3751
+ const omitted = lines.length - headCount - tailCount;
3752
+ return {
3753
+ text: [
3754
+ ...lines.slice(0, headCount),
3755
+ `...[${omitted} lines omitted]...`,
3756
+ ...lines.slice(lines.length - tailCount)
3757
+ ].join("\n"),
3758
+ truncated: true
3759
+ };
3760
+ };
3761
+ var excerptByBytes = (value, maxBytes) => {
3762
+ if (utf8ByteLength(value) <= maxBytes) {
3763
+ return { text: value, truncated: false };
3764
+ }
3765
+ const marker = "\n...[truncated by size]...\n";
3766
+ const markerBytes = utf8ByteLength(marker);
3767
+ if (maxBytes <= markerBytes + 2) {
3768
+ return {
3769
+ text: truncateUtf8Prefix(value, maxBytes),
3770
+ truncated: true
3771
+ };
3772
+ }
3773
+ const budget = maxBytes - markerBytes;
3774
+ const headBytes = Math.floor(budget / 2);
3775
+ const tailBytes = budget - headBytes;
3776
+ return {
3777
+ text: `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`,
3778
+ truncated: true
3779
+ };
3780
+ };
3781
+ var summarizeDiff = (diff, options = {}) => {
3782
+ const lineExcerpt = excerptByLines(
3783
+ diff,
3784
+ options.maxLines ?? DEFAULT_DIFF_PREVIEW_LINES
3785
+ );
3786
+ const byteExcerpt = excerptByBytes(
3787
+ lineExcerpt.text,
3788
+ options.maxBytes ?? DEFAULT_DIFF_PREVIEW_BYTES
3789
+ );
3790
+ return {
3791
+ preview: byteExcerpt.text,
3792
+ truncated: lineExcerpt.truncated || byteExcerpt.truncated
3793
+ };
3794
+ };
3703
3795
  var createUnifiedDiff = (filePath, before, after, context = 3) => {
3704
3796
  const oldText = normalizeLineEndings(before);
3705
3797
  const newText = normalizeLineEndings(after);
@@ -3748,7 +3840,657 @@ var createUnifiedDiff = (filePath, before, after, context = 3) => {
3748
3840
  ${lines.join("\n")}`;
3749
3841
  };
3750
3842
 
3843
+ // src/tools/diff-payload.ts
3844
+ import crypto3 from "crypto";
3845
+ var buildDiffPayload = async (options) => {
3846
+ if (!options.diff) {
3847
+ return {
3848
+ diff: options.emptyDiff ?? ""
3849
+ };
3850
+ }
3851
+ const summarized = summarizeDiff(options.diff);
3852
+ if (!summarized.truncated) {
3853
+ return { diff: summarized.preview };
3854
+ }
3855
+ if (!options.outputCacheStore) {
3856
+ return {
3857
+ diff: summarized.preview,
3858
+ diff_truncated: true
3859
+ };
3860
+ }
3861
+ try {
3862
+ const saved = await options.outputCacheStore.save({
3863
+ tool_call_id: `${options.toolName}_diff_${crypto3.randomUUID()}`,
3864
+ tool_name: options.toolName,
3865
+ content: options.diff
3866
+ });
3867
+ return {
3868
+ diff: summarized.preview,
3869
+ diff_truncated: true,
3870
+ diff_cache_id: saved.id
3871
+ };
3872
+ } catch (error) {
3873
+ const message = `Failed to persist full diff: ${String(error)}`;
3874
+ const context = options.debugContext ? ` ${options.debugContext}` : "";
3875
+ debugLog(
3876
+ `${options.toolName}.diff_cache_save_failed${context} error=${String(error)}`
3877
+ );
3878
+ return {
3879
+ diff: summarized.preview,
3880
+ diff_truncated: true,
3881
+ diff_cache_error: message
3882
+ };
3883
+ }
3884
+ };
3885
+
3886
+ // src/tools/apply-patch.ts
3887
+ var BEGIN_MARKER = "*** Begin Patch";
3888
+ var END_MARKER = "*** End Patch";
3889
+ var END_OF_FILE_MARKER = "*** End of File";
3890
+ var normalizePatchText = (value) => value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
3891
+ var isFileHeader = (line) => line.startsWith("*** Add File: ") || line.startsWith("*** Delete File: ") || line.startsWith("*** Update File: ");
3892
+ var requirePatchPath = (kind, value) => {
3893
+ const trimmed = value.trim();
3894
+ if (!trimmed) {
3895
+ throw new Error(`Patch parse failed: missing path in ${kind}`);
3896
+ }
3897
+ return trimmed;
3898
+ };
3899
+ var parsePatchHeader = (line) => {
3900
+ if (line.startsWith("*** Add File: ")) {
3901
+ return {
3902
+ kind: "add",
3903
+ filePath: requirePatchPath(
3904
+ "Add File",
3905
+ line.slice("*** Add File: ".length)
3906
+ )
3907
+ };
3908
+ }
3909
+ if (line.startsWith("*** Delete File: ")) {
3910
+ return {
3911
+ kind: "delete",
3912
+ filePath: requirePatchPath(
3913
+ "Delete File",
3914
+ line.slice("*** Delete File: ".length)
3915
+ )
3916
+ };
3917
+ }
3918
+ if (line.startsWith("*** Update File: ")) {
3919
+ return {
3920
+ kind: "update",
3921
+ filePath: requirePatchPath(
3922
+ "Update File",
3923
+ line.slice("*** Update File: ".length)
3924
+ )
3925
+ };
3926
+ }
3927
+ return null;
3928
+ };
3929
+ var parseAddFileLines = (lines, startIndex, endIndex) => {
3930
+ const output = [];
3931
+ let index = startIndex;
3932
+ while (index < endIndex) {
3933
+ const line = lines[index] ?? "";
3934
+ if (isFileHeader(line) || line === END_MARKER) {
3935
+ break;
3936
+ }
3937
+ if (!line.startsWith("+")) {
3938
+ throw new Error(
3939
+ `Patch parse failed: add file lines must start with '+' (line ${index + 1})`
3940
+ );
3941
+ }
3942
+ output.push(line.slice(1));
3943
+ index += 1;
3944
+ }
3945
+ return { lines: output, nextIndex: index };
3946
+ };
3947
+ var parseUpdateChunks = (lines, startIndex, endIndex, options = {}) => {
3948
+ const chunks = [];
3949
+ let index = startIndex;
3950
+ while (index < endIndex) {
3951
+ const line = lines[index] ?? "";
3952
+ if (isFileHeader(line) || line === END_MARKER) {
3953
+ break;
3954
+ }
3955
+ if (line.trim() === "") {
3956
+ index += 1;
3957
+ continue;
3958
+ }
3959
+ if (!line.startsWith("@@")) {
3960
+ throw new Error(
3961
+ `Patch parse failed: expected '@@' chunk header (line ${index + 1})`
3962
+ );
3963
+ }
3964
+ const changeContext = line.slice(2).trimStart() || void 0;
3965
+ index += 1;
3966
+ const oldLines = [];
3967
+ const newLines = [];
3968
+ let hasModification = false;
3969
+ let isEndOfFile = false;
3970
+ while (index < endIndex) {
3971
+ const bodyLine = lines[index] ?? "";
3972
+ if (bodyLine.startsWith("@@") || isFileHeader(bodyLine) || bodyLine === END_MARKER) {
3973
+ break;
3974
+ }
3975
+ if (bodyLine === END_OF_FILE_MARKER) {
3976
+ isEndOfFile = true;
3977
+ index += 1;
3978
+ break;
3979
+ }
3980
+ const marker = bodyLine[0];
3981
+ const content = bodyLine.slice(1);
3982
+ switch (marker) {
3983
+ case " ":
3984
+ oldLines.push(content);
3985
+ newLines.push(content);
3986
+ break;
3987
+ case "-":
3988
+ oldLines.push(content);
3989
+ hasModification = true;
3990
+ break;
3991
+ case "+":
3992
+ newLines.push(content);
3993
+ hasModification = true;
3994
+ break;
3995
+ default:
3996
+ throw new Error(
3997
+ `Patch parse failed: invalid change marker '${marker}' (line ${index + 1})`
3998
+ );
3999
+ }
4000
+ index += 1;
4001
+ }
4002
+ if (!hasModification) {
4003
+ throw new Error(
4004
+ `Patch parse failed: chunk must contain at least one '+' or '-' change (line ${index + 1})`
4005
+ );
4006
+ }
4007
+ chunks.push({
4008
+ ...changeContext ? { changeContext } : {},
4009
+ oldLines,
4010
+ newLines,
4011
+ ...isEndOfFile ? { isEndOfFile: true } : {}
4012
+ });
4013
+ }
4014
+ if (chunks.length === 0 && !options.allowEmpty) {
4015
+ throw new Error("Patch parse failed: update file section has no chunks");
4016
+ }
4017
+ return { chunks, nextIndex: index };
4018
+ };
4019
+ var parsePatch = (patchText) => {
4020
+ const normalized = normalizePatchText(patchText);
4021
+ const lines = normalized.split("\n");
4022
+ let first = 0;
4023
+ while (first < lines.length && lines[first]?.trim() === "") {
4024
+ first += 1;
4025
+ }
4026
+ let last = lines.length - 1;
4027
+ while (last >= first && lines[last]?.trim() === "") {
4028
+ last -= 1;
4029
+ }
4030
+ if (first > last) {
4031
+ throw new Error("Patch parse failed: patch is empty");
4032
+ }
4033
+ if (lines[first] !== BEGIN_MARKER || lines[last] !== END_MARKER) {
4034
+ throw new Error("Patch parse failed: missing Begin/End markers");
4035
+ }
4036
+ const parsed = [];
4037
+ let index = first + 1;
4038
+ while (index < last) {
4039
+ const line = lines[index] ?? "";
4040
+ if (line.trim() === "") {
4041
+ index += 1;
4042
+ continue;
4043
+ }
4044
+ const header = parsePatchHeader(line);
4045
+ if (!header) {
4046
+ throw new Error(
4047
+ `Patch parse failed: unexpected line outside file section (line ${index + 1})`
4048
+ );
4049
+ }
4050
+ if (header.kind === "add") {
4051
+ const addResult = parseAddFileLines(lines, index + 1, last);
4052
+ parsed.push({
4053
+ type: "add",
4054
+ filePath: header.filePath,
4055
+ lines: addResult.lines
4056
+ });
4057
+ index = addResult.nextIndex;
4058
+ continue;
4059
+ }
4060
+ if (header.kind === "delete") {
4061
+ parsed.push({
4062
+ type: "delete",
4063
+ filePath: header.filePath
4064
+ });
4065
+ index += 1;
4066
+ continue;
4067
+ }
4068
+ let moveTo;
4069
+ let nextIndex = index + 1;
4070
+ const maybeMove = lines[nextIndex] ?? "";
4071
+ if (maybeMove.startsWith("*** Move to: ")) {
4072
+ moveTo = requirePatchPath(
4073
+ "Move to",
4074
+ maybeMove.slice("*** Move to: ".length)
4075
+ );
4076
+ nextIndex += 1;
4077
+ }
4078
+ const updateResult = parseUpdateChunks(lines, nextIndex, last, {
4079
+ allowEmpty: Boolean(moveTo)
4080
+ });
4081
+ parsed.push({
4082
+ type: "update",
4083
+ filePath: header.filePath,
4084
+ ...moveTo ? { moveTo } : {},
4085
+ chunks: updateResult.chunks
4086
+ });
4087
+ index = updateResult.nextIndex;
4088
+ }
4089
+ if (parsed.length === 0) {
4090
+ throw new Error("Patch parse failed: no file changes found");
4091
+ }
4092
+ return parsed;
4093
+ };
4094
+ var renderAddedFile = (lines) => lines.length > 0 ? `${lines.join("\n")}
4095
+ ` : "";
4096
+ 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, " ");
4097
+ var tryMatchSequence = (lines, pattern, startIndex, eof, compare) => {
4098
+ if (pattern.length === 0) return -1;
4099
+ if (eof) {
4100
+ const fromEnd = lines.length - pattern.length;
4101
+ if (fromEnd >= startIndex) {
4102
+ let matches = true;
4103
+ for (let index = 0; index < pattern.length; index += 1) {
4104
+ if (!compare(lines[fromEnd + index] ?? "", pattern[index] ?? "")) {
4105
+ matches = false;
4106
+ break;
4107
+ }
4108
+ }
4109
+ if (matches) {
4110
+ return fromEnd;
4111
+ }
4112
+ }
4113
+ }
4114
+ for (let index = startIndex; index <= lines.length - pattern.length; index += 1) {
4115
+ let matches = true;
4116
+ for (let offset = 0; offset < pattern.length; offset += 1) {
4117
+ if (!compare(lines[index + offset] ?? "", pattern[offset] ?? "")) {
4118
+ matches = false;
4119
+ break;
4120
+ }
4121
+ }
4122
+ if (matches) {
4123
+ return index;
4124
+ }
4125
+ }
4126
+ return -1;
4127
+ };
4128
+ var seekSequence = (lines, pattern, startIndex, eof = false) => {
4129
+ const exact = tryMatchSequence(
4130
+ lines,
4131
+ pattern,
4132
+ startIndex,
4133
+ eof,
4134
+ (left, right) => {
4135
+ return left === right;
4136
+ }
4137
+ );
4138
+ if (exact !== -1) return exact;
4139
+ const trimRight = tryMatchSequence(
4140
+ lines,
4141
+ pattern,
4142
+ startIndex,
4143
+ eof,
4144
+ (left, right) => left.trimEnd() === right.trimEnd()
4145
+ );
4146
+ if (trimRight !== -1) return trimRight;
4147
+ const trimBoth = tryMatchSequence(
4148
+ lines,
4149
+ pattern,
4150
+ startIndex,
4151
+ eof,
4152
+ (left, right) => left.trim() === right.trim()
4153
+ );
4154
+ if (trimBoth !== -1) return trimBoth;
4155
+ return tryMatchSequence(lines, pattern, startIndex, eof, (left, right) => {
4156
+ return normalizeUnicodeLikePatch(left.trim()) === normalizeUnicodeLikePatch(right.trim());
4157
+ });
4158
+ };
4159
+ var applyLineReplacements = (lines, replacements) => {
4160
+ const result = [...lines];
4161
+ for (let index = replacements.length - 1; index >= 0; index -= 1) {
4162
+ const replacement = replacements[index];
4163
+ result.splice(
4164
+ replacement.startIndex,
4165
+ replacement.deleteCount,
4166
+ ...replacement.insertLines
4167
+ );
4168
+ }
4169
+ return result;
4170
+ };
4171
+ var computeLineReplacements = (lines, filePath, chunks) => {
4172
+ const replacements = [];
4173
+ let cursor = 0;
4174
+ for (const chunk of chunks) {
4175
+ if (chunk.changeContext) {
4176
+ const contextIndex = seekSequence(
4177
+ lines,
4178
+ [chunk.changeContext],
4179
+ cursor,
4180
+ false
4181
+ );
4182
+ if (contextIndex === -1) {
4183
+ throw new Error(
4184
+ `Patch apply failed: context '${chunk.changeContext}' not found in ${filePath}`
4185
+ );
4186
+ }
4187
+ cursor = contextIndex + 1;
4188
+ }
4189
+ if (chunk.oldLines.length === 0) {
4190
+ const insertAt = chunk.isEndOfFile ? lines.length : cursor;
4191
+ replacements.push({
4192
+ startIndex: insertAt,
4193
+ deleteCount: 0,
4194
+ insertLines: chunk.newLines
4195
+ });
4196
+ cursor = insertAt;
4197
+ continue;
4198
+ }
4199
+ const matchIndex = seekSequence(
4200
+ lines,
4201
+ chunk.oldLines,
4202
+ cursor,
4203
+ chunk.isEndOfFile ?? false
4204
+ );
4205
+ if (matchIndex === -1) {
4206
+ throw new Error(
4207
+ `Patch apply failed: expected lines not found in ${filePath}`
4208
+ );
4209
+ }
4210
+ replacements.push({
4211
+ startIndex: matchIndex,
4212
+ deleteCount: chunk.oldLines.length,
4213
+ insertLines: chunk.newLines
4214
+ });
4215
+ cursor = matchIndex + chunk.oldLines.length;
4216
+ }
4217
+ return replacements;
4218
+ };
4219
+ var deriveUpdatedContent = (filePath, before, chunks) => {
4220
+ const hadTrailingNewline = before.endsWith("\n");
4221
+ const lines = before.split("\n");
4222
+ if (hadTrailingNewline && lines.at(-1) === "") {
4223
+ lines.pop();
4224
+ }
4225
+ const replacements = computeLineReplacements(lines, filePath, chunks);
4226
+ const nextLines = applyLineReplacements(lines, replacements);
4227
+ const joined = nextLines.join("\n");
4228
+ if (joined === "") {
4229
+ return "";
4230
+ }
4231
+ return hadTrailingNewline ? `${joined}
4232
+ ` : joined;
4233
+ };
4234
+ var rewriteDiffPaths = (diff, oldPath, newPath) => {
4235
+ if (!diff) return diff;
4236
+ const lines = diff.split("\n");
4237
+ if (lines.length >= 2) {
4238
+ lines[0] = `--- ${oldPath}`;
4239
+ lines[1] = `+++ ${newPath}`;
4240
+ }
4241
+ return lines.join("\n");
4242
+ };
4243
+ var ensureFileText = async (resolvedPath, filePath) => {
4244
+ try {
4245
+ const stats = await fs7.stat(resolvedPath);
4246
+ if (stats.isDirectory()) {
4247
+ throw new Error(`Path is a directory: ${filePath}`);
4248
+ }
4249
+ return await fs7.readFile(resolvedPath, "utf8");
4250
+ } catch (error) {
4251
+ if (error.code === "ENOENT") {
4252
+ throw new Error(`File not found: ${filePath}`);
4253
+ }
4254
+ throw error;
4255
+ }
4256
+ };
4257
+ var ensureFileStats = async (resolvedPath, filePath) => {
4258
+ try {
4259
+ const stats = await fs7.stat(resolvedPath);
4260
+ if (stats.isDirectory()) {
4261
+ throw new Error(`Path is a directory: ${filePath}`);
4262
+ }
4263
+ return stats;
4264
+ } catch (error) {
4265
+ if (error.code === "ENOENT") {
4266
+ throw new Error(`File not found: ${filePath}`);
4267
+ }
4268
+ throw error;
4269
+ }
4270
+ };
4271
+ var preparePatchChanges = async (patches, sandbox) => {
4272
+ const prepared = [];
4273
+ const seenSources = /* @__PURE__ */ new Set();
4274
+ const seenTargets = /* @__PURE__ */ new Set();
4275
+ const vacatedEarlier = /* @__PURE__ */ new Set();
4276
+ for (const patch of patches) {
4277
+ const resolvedPath = sandbox.resolvePath(patch.filePath);
4278
+ if (seenSources.has(resolvedPath)) {
4279
+ throw new Error(
4280
+ `Patch apply failed: duplicate source path ${patch.filePath}`
4281
+ );
4282
+ }
4283
+ seenSources.add(resolvedPath);
4284
+ if (patch.type === "add") {
4285
+ try {
4286
+ await fs7.stat(resolvedPath);
4287
+ throw new Error(`File already exists: ${patch.filePath}`);
4288
+ } catch (error) {
4289
+ if (error.code !== "ENOENT") {
4290
+ throw error;
4291
+ }
4292
+ }
4293
+ if (seenTargets.has(resolvedPath)) {
4294
+ throw new Error(
4295
+ `Patch apply failed: duplicate target path ${patch.filePath}`
4296
+ );
4297
+ }
4298
+ seenTargets.add(resolvedPath);
4299
+ const after2 = renderAddedFile(patch.lines);
4300
+ prepared.push({
4301
+ kind: "add",
4302
+ filePath: patch.filePath,
4303
+ resolvedPath,
4304
+ before: "",
4305
+ after: after2,
4306
+ diff: createUnifiedDiff(patch.filePath, "", after2)
4307
+ });
4308
+ continue;
4309
+ }
4310
+ if (patch.type === "delete") {
4311
+ const before2 = await ensureFileText(resolvedPath, patch.filePath);
4312
+ prepared.push({
4313
+ kind: "delete",
4314
+ filePath: patch.filePath,
4315
+ resolvedPath,
4316
+ before: before2,
4317
+ after: "",
4318
+ diff: createUnifiedDiff(patch.filePath, before2, "")
4319
+ });
4320
+ vacatedEarlier.add(resolvedPath);
4321
+ continue;
4322
+ }
4323
+ const sourceStats = await ensureFileStats(resolvedPath, patch.filePath);
4324
+ const before = await fs7.readFile(resolvedPath, "utf8");
4325
+ const after = deriveUpdatedContent(patch.filePath, before, patch.chunks);
4326
+ if (patch.moveTo) {
4327
+ const resolvedMoveTo = sandbox.resolvePath(patch.moveTo);
4328
+ if (resolvedMoveTo !== resolvedPath) {
4329
+ try {
4330
+ await fs7.stat(resolvedMoveTo);
4331
+ if (!vacatedEarlier.has(resolvedMoveTo)) {
4332
+ throw new Error(`Move target already exists: ${patch.moveTo}`);
4333
+ }
4334
+ } catch (error) {
4335
+ if (error.code !== "ENOENT") {
4336
+ throw error;
4337
+ }
4338
+ }
4339
+ }
4340
+ if (seenTargets.has(resolvedMoveTo)) {
4341
+ throw new Error(
4342
+ `Patch apply failed: duplicate target path ${patch.moveTo}`
4343
+ );
4344
+ }
4345
+ seenTargets.add(resolvedMoveTo);
4346
+ prepared.push({
4347
+ kind: resolvedMoveTo === resolvedPath ? "update" : "move",
4348
+ filePath: patch.filePath,
4349
+ resolvedPath,
4350
+ moveTo: patch.moveTo,
4351
+ resolvedMoveTo,
4352
+ sourceMode: sourceStats.mode,
4353
+ before,
4354
+ after,
4355
+ diff: resolvedMoveTo === resolvedPath ? createUnifiedDiff(patch.filePath, before, after) : rewriteDiffPaths(
4356
+ createUnifiedDiff(patch.filePath, before, after),
4357
+ patch.filePath,
4358
+ patch.moveTo
4359
+ )
4360
+ });
4361
+ if (resolvedMoveTo !== resolvedPath) {
4362
+ vacatedEarlier.add(resolvedPath);
4363
+ }
4364
+ continue;
4365
+ }
4366
+ if (seenTargets.has(resolvedPath)) {
4367
+ throw new Error(
4368
+ `Patch apply failed: duplicate target path ${patch.filePath}`
4369
+ );
4370
+ }
4371
+ seenTargets.add(resolvedPath);
4372
+ prepared.push({
4373
+ kind: "update",
4374
+ filePath: patch.filePath,
4375
+ resolvedPath,
4376
+ before,
4377
+ after,
4378
+ diff: createUnifiedDiff(patch.filePath, before, after)
4379
+ });
4380
+ }
4381
+ return prepared;
4382
+ };
4383
+ var applyPreparedChanges = async (changes) => {
4384
+ for (const change of changes) {
4385
+ if (change.kind === "delete") {
4386
+ await fs7.unlink(change.resolvedPath);
4387
+ continue;
4388
+ }
4389
+ if (change.kind === "move" && change.resolvedMoveTo) {
4390
+ await fs7.mkdir(path8.dirname(change.resolvedMoveTo), { recursive: true });
4391
+ await fs7.writeFile(change.resolvedMoveTo, change.after, "utf8");
4392
+ if (typeof change.sourceMode === "number") {
4393
+ await fs7.chmod(change.resolvedMoveTo, change.sourceMode);
4394
+ }
4395
+ await fs7.unlink(change.resolvedPath);
4396
+ continue;
4397
+ }
4398
+ await fs7.mkdir(path8.dirname(change.resolvedPath), { recursive: true });
4399
+ await fs7.writeFile(change.resolvedPath, change.after, "utf8");
4400
+ }
4401
+ };
4402
+ var summarizeChanges = (changes, dryRun) => {
4403
+ const fileSummaries = changes.map((change) => {
4404
+ switch (change.kind) {
4405
+ case "add":
4406
+ return {
4407
+ action: "add",
4408
+ file_path: change.filePath,
4409
+ summary: `A ${change.filePath}`
4410
+ };
4411
+ case "delete":
4412
+ return {
4413
+ action: "delete",
4414
+ file_path: change.filePath,
4415
+ summary: `D ${change.filePath}`
4416
+ };
4417
+ case "move":
4418
+ return {
4419
+ action: "move",
4420
+ file_path: change.filePath,
4421
+ move_to: change.moveTo,
4422
+ summary: `R ${change.filePath} -> ${change.moveTo}`
4423
+ };
4424
+ case "update":
4425
+ return {
4426
+ action: "update",
4427
+ file_path: change.moveTo ?? change.filePath,
4428
+ summary: `M ${change.moveTo ?? change.filePath}`
4429
+ };
4430
+ default:
4431
+ throw new Error(`Unsupported patch change kind: ${change.kind}`);
4432
+ }
4433
+ });
4434
+ return {
4435
+ summary: dryRun ? `Patch preview ready for ${changes.length} file(s)` : `Applied patch to ${changes.length} file(s)`,
4436
+ files: fileSummaries
4437
+ };
4438
+ };
4439
+ var createApplyPatchTool = (sandboxKey, outputCacheStore) => defineTool2({
4440
+ name: "apply_patch",
4441
+ description: "Apply a codex-style multi-file patch; use dry_run to preview only.",
4442
+ input: z3.object({
4443
+ patch: z3.string().min(1).describe("Full patch text between *** Begin Patch and *** End Patch."),
4444
+ dry_run: z3.boolean().optional().describe("Preview the patch without writing files. Default false.")
4445
+ }),
4446
+ execute: async (input, ctx) => {
4447
+ const dryRun = input.dry_run ?? false;
4448
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
4449
+ const patches = parsePatch(input.patch);
4450
+ const prepared = await preparePatchChanges(patches, sandbox);
4451
+ const fullDiff = prepared.map((change) => change.diff).filter((diff) => diff.length > 0).join("\n\n");
4452
+ const diffPayload = await buildDiffPayload({
4453
+ toolName: "apply_patch",
4454
+ diff: fullDiff,
4455
+ outputCacheStore
4456
+ });
4457
+ const summary = summarizeChanges(prepared, dryRun);
4458
+ if (!dryRun) {
4459
+ try {
4460
+ await applyPreparedChanges(prepared);
4461
+ } catch (error) {
4462
+ throw new Error(`Error applying patch: ${String(error)}`);
4463
+ }
4464
+ }
4465
+ return {
4466
+ summary: summary.summary,
4467
+ file_count: prepared.length,
4468
+ files: summary.files,
4469
+ ...diffPayload
4470
+ };
4471
+ }
4472
+ });
4473
+
4474
+ // src/tools/done.ts
4475
+ import { defineTool as defineTool3, TaskComplete } from "@codelia/core";
4476
+ import { z as z4 } from "zod";
4477
+ var createDoneTool = () => defineTool3({
4478
+ name: "done",
4479
+ description: "Mark the task as complete and return a final message.",
4480
+ input: z4.object({
4481
+ message: z4.string().describe("Final user-facing completion message.")
4482
+ }),
4483
+ execute: async (input) => {
4484
+ throw new TaskComplete(input.message);
4485
+ }
4486
+ });
4487
+
3751
4488
  // src/tools/edit.ts
4489
+ import crypto4 from "crypto";
4490
+ import { promises as fs8 } from "fs";
4491
+ import path9 from "path";
4492
+ import { defineTool as defineTool4 } from "@codelia/core";
4493
+ import { z as z5 } from "zod";
3752
4494
  var trimLine = (line) => line.replace(/\r$/, "").trim();
3753
4495
  var lineRangeToIndices = (lines, startLine, lineCount) => {
3754
4496
  let startIndex = 0;
@@ -3855,25 +4597,25 @@ var applyReplacements = (content, matches, replacement) => {
3855
4597
  }
3856
4598
  return next;
3857
4599
  };
3858
- var hashContent = (content) => crypto3.createHash("sha256").update(content).digest("hex");
3859
- var createEditTool = (sandboxKey) => defineTool3({
4600
+ var hashContent = (content) => crypto4.createHash("sha256").update(content).digest("hex");
4601
+ var createEditTool = (sandboxKey, outputCacheStore) => defineTool4({
3860
4602
  name: "edit",
3861
4603
  description: "Edit a file by replacing old_string with new_string.",
3862
- input: z4.object({
3863
- file_path: z4.string().describe(
4604
+ input: z5.object({
4605
+ file_path: z5.string().describe(
3864
4606
  "File path. Sandbox-bounded unless full-access mode is active."
3865
4607
  ),
3866
- old_string: z4.string().describe(
4608
+ old_string: z5.string().describe(
3867
4609
  "Text to find. Use empty string to replace the whole file content."
3868
4610
  ),
3869
- new_string: z4.string().describe("Replacement text."),
3870
- replace_all: z4.boolean().optional().describe("Replace all matches when true. Default false."),
3871
- match_mode: z4.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
4611
+ new_string: z5.string().describe("Replacement text."),
4612
+ replace_all: z5.boolean().optional().describe("Replace all matches when true. Default false."),
4613
+ match_mode: z5.enum(["exact", "line_trimmed", "block_anchor", "auto"]).optional().describe(
3872
4614
  "Match strategy: exact, line_trimmed, block_anchor, or auto. Default auto."
3873
4615
  ),
3874
- expected_replacements: z4.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
3875
- dry_run: z4.boolean().optional().describe("Preview diff only when true. Default false."),
3876
- expected_hash: z4.string().optional().describe("Optional SHA-256 hash guard for current file content.")
4616
+ expected_replacements: z5.number().int().nonnegative().optional().describe("Expected replacement count (guard)."),
4617
+ dry_run: z5.boolean().optional().describe("Preview diff only when true. Default false."),
4618
+ expected_hash: z5.string().optional().describe("Optional SHA-256 hash guard for current file content.")
3877
4619
  }),
3878
4620
  execute: async (input, ctx) => {
3879
4621
  let resolved;
@@ -3898,12 +4640,12 @@ var createEditTool = (sandboxKey) => defineTool3({
3898
4640
  let content = "";
3899
4641
  let fileExists = false;
3900
4642
  try {
3901
- const stat = await fs7.stat(resolved);
4643
+ const stat = await fs8.stat(resolved);
3902
4644
  if (stat.isDirectory()) {
3903
4645
  throw new Error(`Path is a directory: ${input.file_path}`);
3904
4646
  }
3905
4647
  fileExists = true;
3906
- content = await fs7.readFile(resolved, "utf8");
4648
+ content = await fs8.readFile(resolved, "utf8");
3907
4649
  } catch (_error) {
3908
4650
  if (input.old_string !== "") {
3909
4651
  throw new Error(`File not found: ${input.file_path}`);
@@ -3953,13 +4695,18 @@ var createEditTool = (sandboxKey) => defineTool3({
3953
4695
  `Expected ${input.expected_replacements} replacements, found ${replacements}`
3954
4696
  );
3955
4697
  }
3956
- const diff = createUnifiedDiff(input.file_path, content, nextContent);
4698
+ const diffPayload = await buildDiffPayload({
4699
+ toolName: "edit",
4700
+ diff: createUnifiedDiff(input.file_path, content, nextContent),
4701
+ outputCacheStore,
4702
+ debugContext: `file=${input.file_path}`
4703
+ });
3957
4704
  if (dryRun) {
3958
4705
  return {
3959
4706
  summary: `Preview: ${replacements} replacement(s) in ${input.file_path}`,
3960
4707
  replacements,
3961
4708
  match_mode: modeUsed,
3962
- diff,
4709
+ ...diffPayload,
3963
4710
  file_path: input.file_path
3964
4711
  };
3965
4712
  }
@@ -3968,13 +4715,13 @@ var createEditTool = (sandboxKey) => defineTool3({
3968
4715
  summary: `No changes needed in ${input.file_path}`,
3969
4716
  replacements,
3970
4717
  match_mode: modeUsed,
3971
- diff,
4718
+ ...diffPayload,
3972
4719
  file_path: input.file_path
3973
4720
  };
3974
4721
  }
3975
4722
  try {
3976
- await fs7.mkdir(path8.dirname(resolved), { recursive: true });
3977
- await fs7.writeFile(resolved, nextContent, "utf8");
4723
+ await fs8.mkdir(path9.dirname(resolved), { recursive: true });
4724
+ await fs8.writeFile(resolved, nextContent, "utf8");
3978
4725
  } catch (error) {
3979
4726
  throw new Error(`Error editing file: ${String(error)}`);
3980
4727
  }
@@ -3982,171 +4729,21 @@ var createEditTool = (sandboxKey) => defineTool3({
3982
4729
  summary: `Replaced ${replacements} occurrence(s) in ${input.file_path}`,
3983
4730
  replacements,
3984
4731
  match_mode: modeUsed,
3985
- diff,
4732
+ ...diffPayload,
3986
4733
  file_path: input.file_path
3987
4734
  };
3988
4735
  }
3989
4736
  });
3990
4737
 
3991
- // src/tools/glob-search.ts
3992
- import { promises as fs9 } from "fs";
3993
- import { defineTool as defineTool4 } from "@codelia/core";
3994
- import { z as z5 } from "zod";
3995
-
3996
- // src/utils/glob.ts
3997
- import { promises as fs8 } from "fs";
3998
- import path9 from "path";
3999
- var globToRegExp2 = (pattern) => {
4000
- const normalized = pattern.replaceAll("\\", "/");
4001
- const globDirToken = "__GLOBSTAR_DIR__";
4002
- const globAnyToken = "__GLOBSTAR__";
4003
- const globSingleToken = "__GLOBSTAR_SINGLE__";
4004
- const globCharToken = "__GLOBSTAR_CHAR__";
4005
- const withTokens = normalized.replace(/\*\*\//g, globDirToken).replace(/\*\*/g, globAnyToken).replace(/\*/g, globSingleToken).replace(/\?/g, globCharToken);
4006
- const escaped = withTokens.replace(/[.+^$(){}|[\]\\]/g, "\\$&");
4007
- const withGlob = escaped.replace(new RegExp(globDirToken, "g"), "(?:.+/)?").replace(new RegExp(globAnyToken, "g"), ".+").replace(new RegExp(globSingleToken, "g"), "[^/]*").replace(new RegExp(globCharToken, "g"), ".");
4008
- return new RegExp(`^${withGlob}$`);
4009
- };
4010
- var walkFiles = async (startDir, visitor) => {
4011
- const entries = await fs8.readdir(startDir, { withFileTypes: true });
4012
- for (const entry of entries) {
4013
- const fullPath = path9.join(startDir, entry.name);
4014
- if (entry.isDirectory()) {
4015
- await walkFiles(fullPath, visitor);
4016
- } else if (entry.isFile()) {
4017
- const shouldContinue = await visitor(fullPath);
4018
- if (!shouldContinue) return;
4019
- }
4020
- }
4021
- };
4022
- var globMatch = async (searchDir, pattern) => {
4023
- const regex = globToRegExp2(pattern.replaceAll("\\", "/"));
4024
- const matches = [];
4025
- await walkFiles(searchDir, async (filePath) => {
4026
- const relPath = path9.relative(searchDir, filePath).replaceAll("\\", "/");
4027
- if (regex.test(relPath)) {
4028
- matches.push(relPath);
4029
- }
4030
- return matches.length < 200;
4031
- });
4032
- return matches;
4033
- };
4034
-
4035
- // src/tools/glob-search.ts
4036
- var createGlobSearchTool = (sandboxKey) => defineTool4({
4037
- name: "glob_search",
4038
- description: "Find files by glob pattern under a directory.",
4039
- input: z5.object({
4040
- pattern: z5.string().describe("Glob pattern (for example: **/*.ts)."),
4041
- path: z5.string().optional().describe(
4042
- "Optional directory path. Defaults to the current working directory."
4043
- )
4044
- }),
4045
- execute: async (input, ctx) => {
4046
- let searchDir;
4047
- try {
4048
- const sandbox = await getSandboxContext(ctx, sandboxKey);
4049
- searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4050
- } catch (error) {
4051
- throw new Error(`Security error: ${String(error)}`);
4052
- }
4053
- try {
4054
- const stat = await fs9.stat(searchDir);
4055
- if (!stat.isDirectory()) {
4056
- return `Path is not a directory: ${input.path}`;
4057
- }
4058
- } catch (error) {
4059
- return `Error: ${String(error)}`;
4060
- }
4061
- const matches = await globMatch(searchDir, input.pattern);
4062
- if (!matches.length) {
4063
- return `No files match pattern: ${input.pattern}`;
4064
- }
4065
- const limited = matches.slice(0, 50);
4066
- return `Found ${limited.length} file(s):
4067
- ${limited.join("\n")}`;
4068
- }
4069
- });
4070
-
4071
- // src/tools/grep.ts
4072
- import { promises as fs10 } from "fs";
4073
- import path10 from "path";
4738
+ // src/tools/lane.ts
4074
4739
  import { defineTool as defineTool5 } from "@codelia/core";
4075
4740
  import { z as z6 } from "zod";
4076
- var createGrepTool = (sandboxKey) => defineTool5({
4077
- name: "grep",
4078
- description: "Search file contents with a regex pattern.",
4079
- input: z6.object({
4080
- pattern: z6.string().describe("Regex pattern (JavaScript syntax)."),
4081
- path: z6.string().optional().describe(
4082
- "Optional file or directory path. Defaults to the current working directory."
4083
- )
4084
- }),
4085
- execute: async (input, ctx) => {
4086
- let searchDir;
4087
- let rootDir;
4088
- let pathLabel;
4089
- try {
4090
- const sandbox = await getSandboxContext(ctx, sandboxKey);
4091
- rootDir = sandbox.rootDir;
4092
- searchDir = input.path ? sandbox.resolvePath(input.path) : sandbox.workingDir;
4093
- pathLabel = input.path ?? searchDir;
4094
- } catch (error) {
4095
- throw new Error(`Security error: ${String(error)}`);
4096
- }
4097
- let regex;
4098
- try {
4099
- regex = new RegExp(input.pattern);
4100
- } catch (error) {
4101
- return `Invalid regex: ${String(error)}`;
4102
- }
4103
- const results = [];
4104
- const searchFile = async (filePath) => {
4105
- if (results.length >= 50) return false;
4106
- try {
4107
- const content = await fs10.readFile(filePath, "utf8");
4108
- const lines = content.split(/\r?\n/);
4109
- for (let i = 0; i < lines.length; i++) {
4110
- if (regex.test(lines[i])) {
4111
- const relPath = path10.relative(rootDir, filePath).replaceAll("\\", "/");
4112
- results.push(`${relPath}:${i + 1}: ${lines[i].slice(0, 100)}`);
4113
- if (results.length >= 50) return false;
4114
- }
4115
- }
4116
- } catch {
4117
- return true;
4118
- }
4119
- return true;
4120
- };
4121
- try {
4122
- const stats = await fs10.stat(searchDir);
4123
- if (stats.isFile()) {
4124
- await searchFile(searchDir);
4125
- } else if (stats.isDirectory()) {
4126
- await walkFiles(searchDir, searchFile);
4127
- } else {
4128
- return `Path is not a file or directory: ${pathLabel}`;
4129
- }
4130
- } catch (error) {
4131
- return `Error reading path: ${pathLabel} (${String(error)})`;
4132
- }
4133
- if (!results.length) {
4134
- return `No matches for: ${input.pattern}`;
4135
- }
4136
- return results.length >= 50 ? `${results.join("\n")}
4137
- ... (truncated)` : results.join("\n");
4138
- }
4139
- });
4140
-
4141
- // src/tools/lane.ts
4142
- import { defineTool as defineTool6 } from "@codelia/core";
4143
- import { z as z7 } from "zod";
4144
4741
 
4145
4742
  // src/lanes/manager.ts
4146
- import crypto4 from "crypto";
4147
- import { promises as fs12 } from "fs";
4743
+ import crypto5 from "crypto";
4744
+ import { promises as fs10 } from "fs";
4148
4745
  import os2 from "os";
4149
- import path12 from "path";
4746
+ import path11 from "path";
4150
4747
 
4151
4748
  // src/lanes/command.ts
4152
4749
  import { spawn as spawn2 } from "child_process";
@@ -4228,8 +4825,8 @@ ${stdout}`.trim();
4228
4825
  };
4229
4826
 
4230
4827
  // src/lanes/registry.ts
4231
- import { promises as fs11 } from "fs";
4232
- import path11 from "path";
4828
+ import { promises as fs9 } from "fs";
4829
+ import path10 from "path";
4233
4830
  import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
4234
4831
  var REGISTRY_DIRNAME = "lanes";
4235
4832
  var REGISTRY_FILENAME = "registry.json";
@@ -4237,7 +4834,7 @@ var nowIso = () => (/* @__PURE__ */ new Date()).toISOString();
4237
4834
  var sortByUpdatedDesc = (lanes) => [...lanes].sort((a, b) => b.updated_at.localeCompare(a.updated_at));
4238
4835
  var readJsonFile = async (filePath) => {
4239
4836
  try {
4240
- const raw = await fs11.readFile(filePath, "utf8");
4837
+ const raw = await fs9.readFile(filePath, "utf8");
4241
4838
  const parsed = JSON.parse(raw);
4242
4839
  if (!parsed || parsed.version !== 1 || !Array.isArray(parsed.lanes)) {
4243
4840
  return null;
@@ -4251,14 +4848,14 @@ var readJsonFile = async (filePath) => {
4251
4848
  }
4252
4849
  };
4253
4850
  var atomicWrite = async (filePath, payload) => {
4254
- const dir = path11.dirname(filePath);
4255
- const base = path11.basename(filePath);
4256
- const tmp = path11.join(
4851
+ const dir = path10.dirname(filePath);
4852
+ const base = path10.basename(filePath);
4853
+ const tmp = path10.join(
4257
4854
  dir,
4258
4855
  `${base}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
4259
4856
  );
4260
- await fs11.writeFile(tmp, payload, "utf8");
4261
- await fs11.rename(tmp, filePath);
4857
+ await fs9.writeFile(tmp, payload, "utf8");
4858
+ await fs9.rename(tmp, filePath);
4262
4859
  };
4263
4860
  var LaneRegistryStore = class {
4264
4861
  registryPath;
@@ -4268,10 +4865,10 @@ var LaneRegistryStore = class {
4268
4865
  return;
4269
4866
  }
4270
4867
  const root = resolveStoragePaths2().root;
4271
- this.registryPath = path11.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4868
+ this.registryPath = path10.join(root, REGISTRY_DIRNAME, REGISTRY_FILENAME);
4272
4869
  }
4273
4870
  async ensureDir() {
4274
- await fs11.mkdir(path11.dirname(this.registryPath), { recursive: true });
4871
+ await fs9.mkdir(path10.dirname(this.registryPath), { recursive: true });
4275
4872
  }
4276
4873
  async readAll() {
4277
4874
  await this.ensureDir();
@@ -4369,9 +4966,9 @@ var LaneManager = class {
4369
4966
  this.runner = options.runner ?? runCommand;
4370
4967
  this.registry = options.registry ?? new LaneRegistryStore();
4371
4968
  this.now = options.now ?? nowIso2;
4372
- this.randomId = options.randomId ?? (() => crypto4.randomUUID());
4969
+ this.randomId = options.randomId ?? (() => crypto5.randomUUID());
4373
4970
  this.launchCommand = options.launchCommand ?? process.env.CODELIA_LANE_LAUNCH_COMMAND?.trim() ?? "codelia";
4374
- this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path12.join(os2.homedir(), ".codelia", "worktrees");
4971
+ this.defaultWorktreeRoot = options.defaultWorktreeRoot ?? path11.join(os2.homedir(), ".codelia", "worktrees");
4375
4972
  }
4376
4973
  async cmd(command, args, options) {
4377
4974
  debugLog(`lane.cmd ${command} ${args.join(" ")}`);
@@ -4494,15 +5091,15 @@ var LaneManager = class {
4494
5091
  "rev-parse",
4495
5092
  "--git-common-dir"
4496
5093
  ]);
4497
- const commonDir = path12.resolve(worktreePath, stdout.trim());
4498
- if (path12.basename(commonDir) === ".git") {
4499
- return path12.dirname(commonDir);
5094
+ const commonDir = path11.resolve(worktreePath, stdout.trim());
5095
+ if (path11.basename(commonDir) === ".git") {
5096
+ return path11.dirname(commonDir);
4500
5097
  }
4501
5098
  return await this.resolveRepoRoot(worktreePath);
4502
5099
  }
4503
5100
  async isWorktreeDirty(worktreePath) {
4504
5101
  try {
4505
- await fs12.access(worktreePath);
5102
+ await fs10.access(worktreePath);
4506
5103
  } catch {
4507
5104
  return false;
4508
5105
  }
@@ -4516,7 +5113,7 @@ var LaneManager = class {
4516
5113
  }
4517
5114
  async removeWorktree(worktreePath, force) {
4518
5115
  try {
4519
- await fs12.access(worktreePath);
5116
+ await fs10.access(worktreePath);
4520
5117
  } catch {
4521
5118
  return;
4522
5119
  }
@@ -4541,7 +5138,7 @@ var LaneManager = class {
4541
5138
  const slug = toSlug(taskId);
4542
5139
  const shortId = laneId.slice(0, 8);
4543
5140
  const branchName = `lane/${slug}-${shortId}`;
4544
- const worktreePath = input.worktree_path ? path12.resolve(options.workingDir, input.worktree_path) : path12.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
5141
+ const worktreePath = input.worktree_path ? path11.resolve(options.workingDir, input.worktree_path) : path11.join(this.defaultWorktreeRoot, `${slug}-${shortId}`);
4545
5142
  const muxTarget = `codelia-lane-${shortId}`;
4546
5143
  const createdAt = this.now();
4547
5144
  const record = {
@@ -4552,14 +5149,14 @@ var LaneManager = class {
4552
5149
  mux_target: muxTarget,
4553
5150
  worktree_path: worktreePath,
4554
5151
  branch_name: branchName,
4555
- session_id: crypto4.randomUUID(),
5152
+ session_id: crypto5.randomUUID(),
4556
5153
  created_at: createdAt,
4557
5154
  updated_at: createdAt,
4558
5155
  last_activity_at: createdAt
4559
5156
  };
4560
5157
  await this.registry.upsert(record);
4561
5158
  try {
4562
- await fs12.mkdir(path12.dirname(worktreePath), { recursive: true });
5159
+ await fs10.mkdir(path11.dirname(worktreePath), { recursive: true });
4563
5160
  await this.cmd("git", [
4564
5161
  "-C",
4565
5162
  repoRoot,
@@ -4712,7 +5309,7 @@ var LaneManager = class {
4712
5309
 
4713
5310
  // src/tools/lane.ts
4714
5311
  var laneManager = new LaneManager();
4715
- var backendSchema = z7.enum(["tmux", "zellij"]);
5312
+ var backendSchema = z6.enum(["tmux", "zellij"]);
4716
5313
  var formatError = (error) => {
4717
5314
  if (error instanceof LaneManagerError) {
4718
5315
  return new Error(`${error.code}: ${error.message}`);
@@ -4739,17 +5336,17 @@ var buildLaneHints = (lane) => {
4739
5336
  }
4740
5337
  };
4741
5338
  };
4742
- var createLaneCreateTool = (sandboxKey) => defineTool6({
5339
+ var createLaneCreateTool = (sandboxKey) => defineTool5({
4743
5340
  name: "lane_create",
4744
5341
  description: "Create a Task lane (worktree slot) and start autonomous execution in tmux/zellij.",
4745
- input: z7.object({
4746
- task_id: z7.string().describe("Task identifier."),
4747
- base_ref: z7.string().optional().describe("Base git ref. Default: HEAD."),
4748
- worktree_path: z7.string().optional().describe(
5342
+ input: z6.object({
5343
+ task_id: z6.string().describe("Task identifier."),
5344
+ base_ref: z6.string().optional().describe("Base git ref. Default: HEAD."),
5345
+ worktree_path: z6.string().optional().describe(
4749
5346
  "Optional worktree path override. Default: ~/.codelia/worktrees/<task-slug>-<lane-id8>."
4750
5347
  ),
4751
5348
  mux_backend: backendSchema.optional().describe("Multiplexer backend. Default: tmux."),
4752
- seed_context: z7.string().optional().describe("Optional initial text context.")
5349
+ seed_context: z6.string().optional().describe("Optional initial text context.")
4753
5350
  }),
4754
5351
  execute: async (input, ctx) => {
4755
5352
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -4774,11 +5371,11 @@ var createLaneCreateTool = (sandboxKey) => defineTool6({
4774
5371
  }
4775
5372
  }
4776
5373
  });
4777
- var createLaneListTool = (sandboxKey) => defineTool6({
5374
+ var createLaneListTool = (sandboxKey) => defineTool5({
4778
5375
  name: "lane_list",
4779
5376
  description: "List Task lanes (worktree slots) and current states.",
4780
- input: z7.object({
4781
- include_closed: z7.boolean().optional().describe("Include closed lanes. Default: false.")
5377
+ input: z6.object({
5378
+ include_closed: z6.boolean().optional().describe("Include closed lanes. Default: false.")
4782
5379
  }),
4783
5380
  execute: async (input, ctx) => {
4784
5381
  await getSandboxContext(ctx, sandboxKey);
@@ -4798,11 +5395,11 @@ var createLaneListTool = (sandboxKey) => defineTool6({
4798
5395
  }
4799
5396
  }
4800
5397
  });
4801
- var createLaneStatusTool = (sandboxKey) => defineTool6({
5398
+ var createLaneStatusTool = (sandboxKey) => defineTool5({
4802
5399
  name: "lane_status",
4803
5400
  description: "Get Task lane status and backend liveness.",
4804
- input: z7.object({
4805
- lane_id: z7.string().describe("Lane id.")
5401
+ input: z6.object({
5402
+ lane_id: z6.string().describe("Lane id.")
4806
5403
  }),
4807
5404
  execute: async (input, ctx) => {
4808
5405
  await getSandboxContext(ctx, sandboxKey);
@@ -4817,13 +5414,13 @@ var createLaneStatusTool = (sandboxKey) => defineTool6({
4817
5414
  }
4818
5415
  }
4819
5416
  });
4820
- var createLaneCloseTool = (sandboxKey) => defineTool6({
5417
+ var createLaneCloseTool = (sandboxKey) => defineTool5({
4821
5418
  name: "lane_close",
4822
5419
  description: "Close a Task lane and optionally remove its worktree.",
4823
- input: z7.object({
4824
- lane_id: z7.string().describe("Lane id."),
4825
- remove_worktree: z7.boolean().optional().describe("Remove worktree. Default: true."),
4826
- force: z7.boolean().optional().describe("Force close/cleanup. Default: false.")
5420
+ input: z6.object({
5421
+ lane_id: z6.string().describe("Lane id."),
5422
+ remove_worktree: z6.boolean().optional().describe("Remove worktree. Default: true."),
5423
+ force: z6.boolean().optional().describe("Force close/cleanup. Default: false.")
4827
5424
  }),
4828
5425
  execute: async (input, ctx) => {
4829
5426
  await getSandboxContext(ctx, sandboxKey);
@@ -4842,13 +5439,13 @@ var createLaneCloseTool = (sandboxKey) => defineTool6({
4842
5439
  }
4843
5440
  }
4844
5441
  });
4845
- var createLaneGcTool = (sandboxKey) => defineTool6({
5442
+ var createLaneGcTool = (sandboxKey) => defineTool5({
4846
5443
  name: "lane_gc",
4847
5444
  description: "Close stale finished/error lanes after idle TTL.",
4848
- input: z7.object({
4849
- idle_ttl_minutes: z7.number().int().positive().describe("Idle TTL in minutes."),
4850
- remove_worktree: z7.boolean().optional().describe("Remove worktree on close. Default: false."),
4851
- force: z7.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
5445
+ input: z6.object({
5446
+ idle_ttl_minutes: z6.number().int().positive().describe("Idle TTL in minutes."),
5447
+ remove_worktree: z6.boolean().optional().describe("Remove worktree on close. Default: false."),
5448
+ force: z6.boolean().optional().describe("Force cleanup for dirty worktrees. Default: false.")
4852
5449
  }),
4853
5450
  execute: async (input, ctx) => {
4854
5451
  await getSandboxContext(ctx, sandboxKey);
@@ -4865,9 +5462,9 @@ var createLaneGcTool = (sandboxKey) => defineTool6({
4865
5462
  });
4866
5463
 
4867
5464
  // src/tools/read.ts
4868
- import { promises as fs13 } from "fs";
4869
- import { defineTool as defineTool7 } from "@codelia/core";
4870
- import { z as z8 } from "zod";
5465
+ import { promises as fs11 } from "fs";
5466
+ import { defineTool as defineTool6 } from "@codelia/core";
5467
+ import { z as z7 } from "zod";
4871
5468
  var DEFAULT_READ_LIMIT = 2e3;
4872
5469
  var DEFAULT_MAX_LINE_LENGTH = 1e3;
4873
5470
  var DEFAULT_MAX_BYTES = 64 * 1024;
@@ -4921,15 +5518,15 @@ var buildTruncatedLinesSummary = (lineNumbers) => {
4921
5518
  }
4922
5519
  return `[truncated lines: ${lineNumbers.join(", ")}]`;
4923
5520
  };
4924
- var createReadTool = (sandboxKey) => defineTool7({
5521
+ var createReadTool = (sandboxKey) => defineTool6({
4925
5522
  name: "read",
4926
5523
  description: "Read a text file with optional 0-based line offset and line limit.",
4927
- input: z8.object({
4928
- file_path: z8.string().describe(
5524
+ input: z7.object({
5525
+ file_path: z7.string().describe(
4929
5526
  "File path. Sandbox-bounded unless full-access mode is active."
4930
5527
  ),
4931
- offset: z8.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
4932
- limit: z8.number().int().positive().optional().describe("Max lines to read. Default 2000.")
5528
+ offset: z7.number().int().nonnegative().optional().describe("0-based start line. Default 0."),
5529
+ limit: z7.number().int().positive().optional().describe("Max lines to read. Default 2000.")
4933
5530
  }),
4934
5531
  execute: async (input, ctx) => {
4935
5532
  let resolved;
@@ -4940,7 +5537,7 @@ var createReadTool = (sandboxKey) => defineTool7({
4940
5537
  throw new Error(`Security error: ${String(error)}`);
4941
5538
  }
4942
5539
  try {
4943
- const stat = await fs13.stat(resolved);
5540
+ const stat = await fs11.stat(resolved);
4944
5541
  if (stat.isDirectory()) {
4945
5542
  return `Path is a directory: ${input.file_path}`;
4946
5543
  }
@@ -4948,7 +5545,7 @@ var createReadTool = (sandboxKey) => defineTool7({
4948
5545
  return `File not found: ${input.file_path}`;
4949
5546
  }
4950
5547
  try {
4951
- const content = await fs13.readFile(resolved, "utf8");
5548
+ const content = await fs11.readFile(resolved, "utf8");
4952
5549
  const lines = content.split(/\r?\n/);
4953
5550
  if (lines.length === 0) {
4954
5551
  return "";
@@ -5017,7 +5614,7 @@ ${truncatedLinesSummary}`;
5017
5614
  if (firstClippedLineNumber !== null) {
5018
5615
  output += `
5019
5616
 
5020
- For full long-line content, use read_line({"file_path":"${input.file_path}","line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5617
+ For full long-line content, use read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${firstClippedLineNumber},"char_offset":0,"char_limit":10000}).`;
5021
5618
  }
5022
5619
  return output;
5023
5620
  } catch (error) {
@@ -5027,21 +5624,25 @@ For full long-line content, use read_line({"file_path":"${input.file_path}","lin
5027
5624
  });
5028
5625
 
5029
5626
  // src/tools/read-line.ts
5030
- import { promises as fs14 } from "fs";
5031
- import { defineTool as defineTool8 } from "@codelia/core";
5032
- import { z as z9 } from "zod";
5627
+ import { promises as fs12 } from "fs";
5628
+ import { defineTool as defineTool7 } from "@codelia/core";
5629
+ import { z as z8 } from "zod";
5033
5630
  var DEFAULT_CHAR_LIMIT = 1e4;
5034
5631
  var MAX_CHAR_LIMIT = 1e5;
5035
- var createReadLineTool = (sandboxKey) => defineTool8({
5632
+ var GRAPHEME_SEGMENTER = new Intl.Segmenter(void 0, {
5633
+ granularity: "grapheme"
5634
+ });
5635
+ var splitGraphemes = (value) => Array.from(GRAPHEME_SEGMENTER.segment(value), ({ segment }) => segment);
5636
+ var createReadLineTool = (sandboxKey) => defineTool7({
5036
5637
  name: "read_line",
5037
5638
  description: "Read a single line segment by 1-based line number and 0-based char offset.",
5038
- input: z9.object({
5039
- file_path: z9.string().describe(
5639
+ input: z8.object({
5640
+ file_path: z8.string().describe(
5040
5641
  "File path. Sandbox-bounded unless full-access mode is active."
5041
5642
  ),
5042
- line_number: z9.number().int().positive().describe("1-based line number to read."),
5043
- char_offset: z9.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5044
- char_limit: z9.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5643
+ line_number: z8.number().int().positive().describe("1-based line number to read."),
5644
+ char_offset: z8.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
5645
+ char_limit: z8.number().int().positive().max(MAX_CHAR_LIMIT).optional().describe("Max chars to return. Default 10000.")
5045
5646
  }),
5046
5647
  execute: async (input, ctx) => {
5047
5648
  let resolved;
@@ -5052,7 +5653,7 @@ var createReadLineTool = (sandboxKey) => defineTool8({
5052
5653
  throw new Error(`Security error: ${String(error)}`);
5053
5654
  }
5054
5655
  try {
5055
- const stat = await fs14.stat(resolved);
5656
+ const stat = await fs12.stat(resolved);
5056
5657
  if (stat.isDirectory()) {
5057
5658
  return `Path is a directory: ${input.file_path}`;
5058
5659
  }
@@ -5060,24 +5661,26 @@ var createReadLineTool = (sandboxKey) => defineTool8({
5060
5661
  return `File not found: ${input.file_path}`;
5061
5662
  }
5062
5663
  try {
5063
- const content = await fs14.readFile(resolved, "utf8");
5664
+ const content = await fs12.readFile(resolved, "utf8");
5064
5665
  const lines = content.split(/\r?\n/);
5065
5666
  const lineIndex = input.line_number - 1;
5066
5667
  if (lineIndex >= lines.length) {
5067
5668
  return `Line number out of range: ${input.line_number} (total ${lines.length})`;
5068
5669
  }
5069
5670
  const line = lines[lineIndex] ?? "";
5671
+ const chars = splitGraphemes(line);
5070
5672
  const charOffset = input.char_offset ?? 0;
5071
5673
  const charLimit = input.char_limit ?? DEFAULT_CHAR_LIMIT;
5072
- if (charOffset > line.length) {
5073
- return `char_offset out of range: ${charOffset} (line length ${line.length})`;
5674
+ if (charOffset > chars.length) {
5675
+ return `char_offset out of range: ${charOffset} (line length ${chars.length})`;
5074
5676
  }
5075
- const segment = line.slice(charOffset, charOffset + charLimit);
5076
- const endOffset = charOffset + segment.length;
5077
- const hasMore = endOffset < line.length;
5677
+ const segmentChars = chars.slice(charOffset, charOffset + charLimit);
5678
+ const segment = segmentChars.join("");
5679
+ const endOffset = charOffset + segmentChars.length;
5680
+ const hasMore = endOffset < chars.length;
5078
5681
  const header = [
5079
5682
  `line_number=${input.line_number}`,
5080
- `line_length=${line.length}`,
5683
+ `line_length=${chars.length}`,
5081
5684
  `char_range=${charOffset}..${Math.max(endOffset - 1, charOffset - 1)}`
5082
5685
  ].join(" ");
5083
5686
  let output = `${header}
@@ -5087,7 +5690,7 @@ ${segment}`;
5087
5690
 
5088
5691
  Use char_offset=${endOffset} to continue.`;
5089
5692
  output += `
5090
- read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5693
+ read_line({"file_path":${JSON.stringify(input.file_path)},"line_number":${input.line_number},"char_offset":${endOffset},"char_limit":${charLimit}})`;
5091
5694
  }
5092
5695
  return output;
5093
5696
  } catch (error) {
@@ -5097,8 +5700,8 @@ read_line({"file_path":"${input.file_path}","line_number":${input.line_number},"
5097
5700
  });
5098
5701
 
5099
5702
  // src/tools/search.ts
5100
- import { defineTool as defineTool9 } from "@codelia/core";
5101
- import { z as z10 } from "zod";
5703
+ import { defineTool as defineTool8 } from "@codelia/core";
5704
+ import { z as z9 } from "zod";
5102
5705
  var normalizeDomain = (value) => value.trim().toLowerCase().replace(/\.+$/, "");
5103
5706
  var shouldKeepUrl = (url, allowedDomains) => {
5104
5707
  if (!allowedDomains.length) return true;
@@ -5214,14 +5817,14 @@ var runBraveSearch = async (query, maxResults, allowedDomains, apiKey) => {
5214
5817
  const parsed = parseBrave(payload);
5215
5818
  return normalizeEntries(parsed, allowedDomains, maxResults);
5216
5819
  };
5217
- var createSearchTool = (options) => defineTool9({
5820
+ var createSearchTool = (options) => defineTool8({
5218
5821
  name: "search",
5219
5822
  description: "Search the web and return concise source candidates.",
5220
- input: z10.object({
5221
- query: z10.string().min(1).describe("Search query."),
5222
- max_results: z10.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5223
- backend: z10.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5224
- allowed_domains: z10.array(z10.string().min(1)).optional().describe("Optional allowlist of domains.")
5823
+ input: z9.object({
5824
+ query: z9.string().min(1).describe("Search query."),
5825
+ max_results: z9.number().int().min(1).max(20).optional().describe("Max results. Default 5."),
5826
+ backend: z9.enum(["ddg", "brave"]).optional().describe("Search backend. Default comes from config."),
5827
+ allowed_domains: z9.array(z9.string().min(1)).optional().describe("Optional allowlist of domains.")
5225
5828
  }),
5226
5829
  execute: async (input) => {
5227
5830
  const backend = input.backend ?? options.defaultBackend;
@@ -5256,13 +5859,13 @@ var createSearchTool = (options) => defineTool9({
5256
5859
  });
5257
5860
 
5258
5861
  // src/tools/shell.ts
5259
- import crypto6 from "crypto";
5260
- import { defineTool as defineTool10 } from "@codelia/core";
5862
+ import crypto7 from "crypto";
5863
+ import { defineTool as defineTool9 } from "@codelia/core";
5261
5864
  import { ToolOutputCacheStoreImpl } from "@codelia/storage";
5262
- import { z as z11 } from "zod";
5865
+ import { z as z10 } from "zod";
5263
5866
 
5264
5867
  // src/tasks/manager.ts
5265
- import crypto5 from "crypto";
5868
+ import crypto6 from "crypto";
5266
5869
  import {
5267
5870
  TaskRegistryStore
5268
5871
  } from "@codelia/storage";
@@ -5361,10 +5964,10 @@ var TaskManager = class {
5361
5964
  shuttingDown = false;
5362
5965
  constructor(options = {}) {
5363
5966
  this.registry = options.registry ?? new TaskRegistryStore();
5364
- this.runtimeId = options.runtimeId ?? crypto5.randomUUID();
5967
+ this.runtimeId = options.runtimeId ?? crypto6.randomUUID();
5365
5968
  this.ownerPid = options.ownerPid ?? process.pid;
5366
5969
  this.now = options.now ?? nowIso3;
5367
- this.randomId = options.randomId ?? (() => crypto5.randomUUID());
5970
+ this.randomId = options.randomId ?? (() => crypto6.randomUUID());
5368
5971
  this.sleep = options.sleep ?? sleepDefault;
5369
5972
  this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
5370
5973
  this.gracePeriodMs = options.gracePeriodMs ?? DEFAULT_GRACE_PERIOD_MS;
@@ -5771,27 +6374,27 @@ var summarizeCommand = (command) => {
5771
6374
  var DEFAULT_EXCERPT_LINES = 80;
5772
6375
  var MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
5773
6376
  var FORCE_KILL_DELAY_MS = 2e3;
5774
- var utf8ByteLength = (value) => Buffer.byteLength(value, "utf8");
5775
- var truncateUtf8Prefix = (value, maxBytes) => {
6377
+ var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
6378
+ var truncateUtf8Prefix2 = (value, maxBytes) => {
5776
6379
  if (maxBytes <= 0 || value.length === 0) return "";
5777
6380
  let bytes = 0;
5778
6381
  let out = "";
5779
6382
  for (const ch of value) {
5780
- const next = utf8ByteLength(ch);
6383
+ const next = utf8ByteLength2(ch);
5781
6384
  if (bytes + next > maxBytes) break;
5782
6385
  out += ch;
5783
6386
  bytes += next;
5784
6387
  }
5785
6388
  return out;
5786
6389
  };
5787
- var truncateUtf8Suffix = (value, maxBytes) => {
6390
+ var truncateUtf8Suffix2 = (value, maxBytes) => {
5788
6391
  if (maxBytes <= 0 || value.length === 0) return "";
5789
6392
  let bytes = 0;
5790
6393
  const chars = Array.from(value);
5791
6394
  const out = [];
5792
6395
  for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
5793
6396
  const ch = chars[idx];
5794
- const next = utf8ByteLength(ch);
6397
+ const next = utf8ByteLength2(ch);
5795
6398
  if (bytes + next > maxBytes) break;
5796
6399
  out.push(ch);
5797
6400
  bytes += next;
@@ -5799,7 +6402,7 @@ var truncateUtf8Suffix = (value, maxBytes) => {
5799
6402
  out.reverse();
5800
6403
  return out.join("");
5801
6404
  };
5802
- var excerptByLines = (value) => {
6405
+ var excerptByLines2 = (value) => {
5803
6406
  const lines = value.split(/\r?\n/);
5804
6407
  if (lines.length <= DEFAULT_EXCERPT_LINES * 2) return value;
5805
6408
  const head = lines.slice(0, DEFAULT_EXCERPT_LINES);
@@ -5807,20 +6410,20 @@ var excerptByLines = (value) => {
5807
6410
  const omitted = lines.length - head.length - tail.length;
5808
6411
  return [...head, `...[${omitted} lines omitted]...`, ...tail].join("\n");
5809
6412
  };
5810
- var excerptByBytes = (value, maxBytes) => {
5811
- if (utf8ByteLength(value) <= maxBytes) return value;
6413
+ var excerptByBytes2 = (value, maxBytes) => {
6414
+ if (utf8ByteLength2(value) <= maxBytes) return value;
5812
6415
  const marker = "\n...[truncated by size]...\n";
5813
- const markerBytes = utf8ByteLength(marker);
6416
+ const markerBytes = utf8ByteLength2(marker);
5814
6417
  if (maxBytes <= markerBytes + 2) {
5815
- return truncateUtf8Prefix(value, maxBytes);
6418
+ return truncateUtf8Prefix2(value, maxBytes);
5816
6419
  }
5817
6420
  const budget = maxBytes - markerBytes;
5818
6421
  const headBytes = Math.floor(budget / 2);
5819
6422
  const tailBytes = budget - headBytes;
5820
- return `${truncateUtf8Prefix(value, headBytes)}${marker}${truncateUtf8Suffix(value, tailBytes)}`;
6423
+ return `${truncateUtf8Prefix2(value, headBytes)}${marker}${truncateUtf8Suffix2(value, tailBytes)}`;
5821
6424
  };
5822
- var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength(value) > MAX_INLINE_OUTPUT_BYTES;
5823
- var excerptText = (value) => excerptByBytes(excerptByLines(value), MAX_INLINE_OUTPUT_BYTES);
6425
+ var needsInlineTruncation = (value) => value.split(/\r?\n/).length > DEFAULT_EXCERPT_LINES * 2 || utf8ByteLength2(value) > MAX_INLINE_OUTPUT_BYTES;
6426
+ var excerptText = (value) => excerptByBytes2(excerptByLines2(value), MAX_INLINE_OUTPUT_BYTES);
5824
6427
  var buildShellTaskResultBase = (options) => {
5825
6428
  const stdoutTruncated = needsInlineTruncation(options.rawStdout);
5826
6429
  const stderrTruncated = needsInlineTruncation(options.rawStderr);
@@ -6054,15 +6657,15 @@ var getToolSessionContext = async (ctx, key) => ctx.resolve(key);
6054
6657
 
6055
6658
  // src/tools/shell.ts
6056
6659
  var LIVE_LOG_TAIL_BYTES = 64 * 1024;
6057
- var utf8ByteLength2 = (value) => Buffer.byteLength(value, "utf8");
6058
- var truncateUtf8Suffix2 = (value, maxBytes) => {
6660
+ var utf8ByteLength3 = (value) => Buffer.byteLength(value, "utf8");
6661
+ var truncateUtf8Suffix3 = (value, maxBytes) => {
6059
6662
  if (maxBytes <= 0 || value.length === 0) return "";
6060
6663
  let bytes = 0;
6061
6664
  const chars = Array.from(value);
6062
6665
  const out = [];
6063
6666
  for (let idx = chars.length - 1; idx >= 0; idx -= 1) {
6064
6667
  const ch = chars[idx];
6065
- const next = utf8ByteLength2(ch);
6668
+ const next = utf8ByteLength3(ch);
6066
6669
  if (bytes + next > maxBytes) break;
6067
6670
  out.push(ch);
6068
6671
  bytes += next;
@@ -6071,7 +6674,7 @@ var truncateUtf8Suffix2 = (value, maxBytes) => {
6071
6674
  return out.join("");
6072
6675
  };
6073
6676
  var tailLiveOutput = (value, maxBytes) => {
6074
- const totalBytes = utf8ByteLength2(value);
6677
+ const totalBytes = utf8ByteLength3(value);
6075
6678
  if (totalBytes <= maxBytes) {
6076
6679
  return {
6077
6680
  content: value,
@@ -6080,80 +6683,80 @@ var tailLiveOutput = (value, maxBytes) => {
6080
6683
  omittedBytes: 0
6081
6684
  };
6082
6685
  }
6083
- const content = truncateUtf8Suffix2(value, maxBytes);
6686
+ const content = truncateUtf8Suffix3(value, maxBytes);
6084
6687
  return {
6085
6688
  content,
6086
6689
  truncated: true,
6087
6690
  totalBytes,
6088
- omittedBytes: Math.max(0, totalBytes - utf8ByteLength2(content))
6691
+ omittedBytes: Math.max(0, totalBytes - utf8ByteLength3(content))
6089
6692
  };
6090
6693
  };
6091
6694
  var SHELL_LABEL_MAX_CHARS = 80;
6092
6695
  var SHELL_LIST_DEFAULT_LIMIT = 20;
6093
6696
  var SHELL_LIST_MAX_LIMIT = 100;
6094
6697
  var SHELL_LOGS_MAX_TAIL_LINES = 500;
6095
- var shellStateSchema = z11.enum([
6698
+ var shellStateSchema = z10.enum([
6096
6699
  "queued",
6097
6700
  "running",
6098
6701
  "completed",
6099
6702
  "failed",
6100
6703
  "cancelled"
6101
6704
  ]);
6102
- var shellRunSchema = z11.object({
6103
- command: z11.string().describe(
6705
+ var shellRunSchema = z10.object({
6706
+ command: z10.string().describe(
6104
6707
  "Shell command to execute as a runtime-managed child process in the current workspace."
6105
6708
  ),
6106
- label: z11.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6709
+ label: z10.string().max(SHELL_LABEL_MAX_CHARS).optional().describe(
6107
6710
  `Optional short task label used to build the returned task key. Max ${SHELL_LABEL_MAX_CHARS} chars.`
6108
6711
  ),
6109
- timeout: z11.number().int().positive().optional().describe(
6110
- `Execution timeout in seconds. Foreground default: ${DEFAULT_TIMEOUT_SECONDS}, max ${MAX_TIMEOUT_SECONDS}. Background accepts larger values up to ${MAX_EXECUTION_TIMEOUT_SECONDS}; omit to keep the managed child job running until completion, cancel, or runtime exit.`
6712
+ timeout: z10.number().int().positive().optional().describe(
6713
+ `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.`
6111
6714
  ),
6112
- background: z11.boolean().optional().describe(
6113
- "Detach the wait and return compact JSON with the task key immediately. The runtime still owns the child process, so this is not persistence/daemonization. Manage it with shell_status/logs/wait/result/cancel. Default: false."
6715
+ detached_wait: z10.boolean().optional().describe(
6716
+ "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."
6114
6717
  )
6115
6718
  }).superRefine((input, ctx) => {
6116
6719
  if (input.timeout === void 0) {
6117
6720
  return;
6118
6721
  }
6119
- if (input.background ?? false) {
6722
+ if (input.detached_wait ?? false) {
6120
6723
  if (input.timeout > MAX_EXECUTION_TIMEOUT_SECONDS) {
6121
6724
  ctx.addIssue({
6122
- code: z11.ZodIssueCode.custom,
6725
+ code: z10.ZodIssueCode.custom,
6123
6726
  path: ["timeout"],
6124
- message: `Background timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6727
+ message: `Detached-wait timeout must be ${MAX_EXECUTION_TIMEOUT_SECONDS} seconds or less. Omit timeout to run without an execution timer.`
6125
6728
  });
6126
6729
  }
6127
6730
  return;
6128
6731
  }
6129
6732
  if (input.timeout > MAX_TIMEOUT_SECONDS) {
6130
6733
  ctx.addIssue({
6131
- code: z11.ZodIssueCode.custom,
6734
+ code: z10.ZodIssueCode.custom,
6132
6735
  path: ["timeout"],
6133
6736
  message: `Foreground timeout must be ${MAX_TIMEOUT_SECONDS} seconds or less.`
6134
6737
  });
6135
6738
  }
6136
6739
  });
6137
- var shellTaskKeySchema = z11.object({
6138
- key: z11.string().describe("Canonical shell task key returned by shell or shell_list.")
6740
+ var shellTaskKeySchema = z10.object({
6741
+ key: z10.string().describe("Canonical shell task key returned by shell or shell_list.")
6139
6742
  });
6140
6743
  var shellWaitSchema = shellTaskKeySchema.extend({
6141
- wait_timeout: z11.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6744
+ wait_timeout: z10.number().int().positive().max(MAX_TIMEOUT_SECONDS).optional().describe(
6142
6745
  `Attached wait window in seconds. Default: ${DEFAULT_TIMEOUT_SECONDS}. Max ${MAX_TIMEOUT_SECONDS}. If the task is still running when the window expires, the tool returns compact status JSON instead of hanging.`
6143
6746
  )
6144
6747
  });
6145
- var shellStreamSchema = z11.enum(["stdout", "stderr"]);
6146
- var shellListSchema = z11.object({
6147
- limit: z11.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6748
+ var shellStreamSchema = z10.enum(["stdout", "stderr"]);
6749
+ var shellListSchema = z10.object({
6750
+ limit: z10.number().int().positive().max(SHELL_LIST_MAX_LIMIT).optional().describe(
6148
6751
  `Max tasks to return. Default: ${SHELL_LIST_DEFAULT_LIMIT}. Max ${SHELL_LIST_MAX_LIMIT}.`
6149
6752
  ),
6150
6753
  state: shellStateSchema.optional().describe("Exact state filter. Default: active tasks only."),
6151
- include_terminal: z11.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6754
+ include_terminal: z10.boolean().optional().describe("Include completed/failed/cancelled tasks. Default: false.")
6152
6755
  });
6153
- var shellLogsSchema = z11.object({
6154
- key: z11.string().describe("Canonical shell task key returned by shell or shell_list."),
6756
+ var shellLogsSchema = z10.object({
6757
+ key: z10.string().describe("Canonical shell task key returned by shell or shell_list."),
6155
6758
  stream: shellStreamSchema.optional().describe("Stream to read. Default: stdout."),
6156
- tail_lines: z11.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6759
+ tail_lines: z10.number().int().positive().max(SHELL_LOGS_MAX_TAIL_LINES).optional().describe(
6157
6760
  `Return only the last N lines. Max ${SHELL_LOGS_MAX_TAIL_LINES}.`
6158
6761
  )
6159
6762
  });
@@ -6169,8 +6772,8 @@ var normalizeOptionalLabel = (value) => {
6169
6772
  const label = value.trim();
6170
6773
  return label.length > 0 ? label : void 0;
6171
6774
  };
6172
- var resolveShellTimeoutSeconds = (value, background) => {
6173
- if (background) {
6775
+ var resolveShellTimeoutSeconds = (value, detachedWait) => {
6776
+ if (detachedWait) {
6174
6777
  return value === void 0 ? void 0 : Math.max(1, Math.trunc(value));
6175
6778
  }
6176
6779
  const requestedTimeout = value ?? DEFAULT_TIMEOUT_SECONDS;
@@ -6195,7 +6798,7 @@ var toShellKeyBase = (label) => {
6195
6798
  };
6196
6799
  var compactTaskId = (taskId) => {
6197
6800
  const compact = taskId.toLowerCase().replaceAll(/[^a-z0-9]+/g, "");
6198
- return compact || crypto6.createHash("sha256").update(taskId).digest("hex");
6801
+ return compact || crypto7.createHash("sha256").update(taskId).digest("hex");
6199
6802
  };
6200
6803
  var buildShellTaskKey = async (tasks, taskId, label) => {
6201
6804
  const base = toShellKeyBase(label);
@@ -6252,7 +6855,7 @@ var shellBasePayload = (task) => ({
6252
6855
  });
6253
6856
  var shellStatusPayload = (task, options = {}) => ({
6254
6857
  ...shellBasePayload(task),
6255
- ...options.background ? { background: true } : {},
6858
+ ...options.detachedWait ? { detached_wait: true } : {},
6256
6859
  ...options.stillRunning ? { still_running: true } : {},
6257
6860
  ...options.aborted ? { aborted: true } : {}
6258
6861
  });
@@ -6511,9 +7114,9 @@ var waitForManagedTaskWindow = async (tasks, taskId, options) => {
6511
7114
  };
6512
7115
  var createShellTool = (sandboxKey, options = {}) => {
6513
7116
  const shared = getSharedDeps(options);
6514
- return defineTool10({
7117
+ return defineTool9({
6515
7118
  name: "shell",
6516
- description: "Run a shell command as a runtime-managed child process in the sandbox. By default wait for completion; with `background=true`, detach the wait and return compact JSON with the task key for follow-up tools.",
7119
+ 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.",
6517
7120
  input: shellRunSchema,
6518
7121
  execute: async (input, ctx) => {
6519
7122
  const sandbox = await getSandboxContext(ctx, sandboxKey);
@@ -6523,17 +7126,17 @@ var createShellTool = (sandboxKey, options = {}) => {
6523
7126
  throw new Error("command is required.");
6524
7127
  }
6525
7128
  const label = normalizeOptionalLabel(input.label);
6526
- const background = input.background ?? false;
7129
+ const detachedWait = input.detached_wait ?? false;
6527
7130
  const timeoutSeconds = resolveShellTimeoutSeconds(
6528
7131
  input.timeout,
6529
- background
7132
+ detachedWait
6530
7133
  );
6531
7134
  const commandSummary = summarizeCommand(command);
6532
7135
  debugLog(
6533
- `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} background=${background} command="${commandSummary}"`
7136
+ `shell.start cwd=${sandbox.workingDir} timeout_s=${formatShellTimeoutForLog(timeoutSeconds)} detached_wait=${detachedWait} command="${commandSummary}"`
6534
7137
  );
6535
7138
  try {
6536
- const taskId = crypto6.randomUUID();
7139
+ const taskId = crypto7.randomUUID();
6537
7140
  const taskKey = await buildShellTaskKey(shared.tasks, taskId, label);
6538
7141
  const task = await shared.tasks.spawn(
6539
7142
  {
@@ -6555,8 +7158,8 @@ var createShellTool = (sandboxKey, options = {}) => {
6555
7158
  outputCache: shared.outputCacheStore
6556
7159
  })
6557
7160
  );
6558
- if (background) {
6559
- return shellStatusPayload(task, { background: true });
7161
+ if (detachedWait) {
7162
+ return shellStatusPayload(task, { detachedWait: true });
6560
7163
  }
6561
7164
  const settled = await waitForForegroundRun(
6562
7165
  shared.tasks,
@@ -6575,7 +7178,7 @@ var createShellTool = (sandboxKey, options = {}) => {
6575
7178
  };
6576
7179
  var createShellListTool = (options = {}) => {
6577
7180
  const shared = getSharedDeps(options);
6578
- return defineTool10({
7181
+ return defineTool9({
6579
7182
  name: "shell_list",
6580
7183
  description: "List retained shell tasks with compact summaries, defaulting to active tasks.",
6581
7184
  input: shellListSchema,
@@ -6606,7 +7209,7 @@ var createShellListTool = (options = {}) => {
6606
7209
  };
6607
7210
  var createShellStatusTool = (options = {}) => {
6608
7211
  const shared = getSharedDeps(options);
6609
- return defineTool10({
7212
+ return defineTool9({
6610
7213
  name: "shell_status",
6611
7214
  description: "Get the current state for a shell task as compact JSON.",
6612
7215
  input: shellTaskKeySchema,
@@ -6622,7 +7225,7 @@ var createShellStatusTool = (options = {}) => {
6622
7225
  };
6623
7226
  var createShellLogsTool = (options = {}) => {
6624
7227
  const shared = getSharedDeps(options);
6625
- return defineTool10({
7228
+ return defineTool9({
6626
7229
  name: "shell_logs",
6627
7230
  description: "Read recent stdout or stderr for a running or finished shell task.",
6628
7231
  input: shellLogsSchema,
@@ -6644,7 +7247,7 @@ var createShellLogsTool = (options = {}) => {
6644
7247
  };
6645
7248
  var createShellWaitTool = (options = {}) => {
6646
7249
  const shared = getSharedDeps(options);
6647
- return defineTool10({
7250
+ return defineTool9({
6648
7251
  name: "shell_wait",
6649
7252
  description: "Wait for a shell task within a bounded window and return compact JSON describing either the running status or terminal result.",
6650
7253
  input: shellWaitSchema,
@@ -6677,7 +7280,7 @@ var createShellWaitTool = (options = {}) => {
6677
7280
  };
6678
7281
  var createShellResultTool = (options = {}) => {
6679
7282
  const shared = getSharedDeps(options);
6680
- return defineTool10({
7283
+ return defineTool9({
6681
7284
  name: "shell_result",
6682
7285
  description: "Read the retained terminal result for a shell task as compact JSON.",
6683
7286
  input: shellTaskKeySchema,
@@ -6693,7 +7296,7 @@ var createShellResultTool = (options = {}) => {
6693
7296
  };
6694
7297
  var createShellCancelTool = (options = {}) => {
6695
7298
  const shared = getSharedDeps(options);
6696
- return defineTool10({
7299
+ return defineTool9({
6697
7300
  name: "shell_cancel",
6698
7301
  description: "Cancel a running shell task and return compact JSON for the cancelled state.",
6699
7302
  input: shellTaskKeySchema,
@@ -6712,16 +7315,16 @@ var createShellCancelTool = (options = {}) => {
6712
7315
  };
6713
7316
 
6714
7317
  // src/tools/skill-load.ts
6715
- import { defineTool as defineTool11 } from "@codelia/core";
6716
- import { z as z12 } from "zod";
6717
- var SkillLoadInputSchema = z12.object({
6718
- name: z12.string().min(1).optional().describe("Exact skill name to load."),
6719
- path: z12.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
7318
+ import { defineTool as defineTool10 } from "@codelia/core";
7319
+ import { z as z11 } from "zod";
7320
+ var SkillLoadInputSchema = z11.object({
7321
+ name: z11.string().min(1).optional().describe("Exact skill name to load."),
7322
+ path: z11.string().min(1).optional().describe("Absolute or workspace-relative path to SKILL.md.")
6720
7323
  }).refine((value) => !!value.name || !!value.path, {
6721
7324
  message: "name or path is required",
6722
7325
  path: ["name"]
6723
7326
  });
6724
- var createSkillLoadTool = (skillsResolverKey) => defineTool11({
7327
+ var createSkillLoadTool = (skillsResolverKey) => defineTool10({
6725
7328
  name: "skill_load",
6726
7329
  description: "Load full SKILL.md content by exact name or path.",
6727
7330
  input: SkillLoadInputSchema,
@@ -6767,15 +7370,15 @@ var createSkillLoadTool = (skillsResolverKey) => defineTool11({
6767
7370
  });
6768
7371
 
6769
7372
  // src/tools/skill-search.ts
6770
- import { defineTool as defineTool12 } from "@codelia/core";
6771
- import { z as z13 } from "zod";
6772
- var createSkillSearchTool = (skillsResolverKey) => defineTool12({
7373
+ import { defineTool as defineTool11 } from "@codelia/core";
7374
+ import { z as z12 } from "zod";
7375
+ var createSkillSearchTool = (skillsResolverKey) => defineTool11({
6773
7376
  name: "skill_search",
6774
7377
  description: "Search installed local skills by name, description, or path.",
6775
- input: z13.object({
6776
- query: z13.string().min(1).describe("Search query text."),
6777
- limit: z13.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
6778
- scope: z13.enum(["repo", "user"]).optional().describe("Optional scope filter.")
7378
+ input: z12.object({
7379
+ query: z12.string().min(1).describe("Search query text."),
7380
+ limit: z12.number().int().positive().optional().describe("Optional max result count (clamped by config)."),
7381
+ scope: z12.enum(["repo", "user"]).optional().describe("Optional scope filter.")
6779
7382
  }),
6780
7383
  execute: async (input, ctx) => {
6781
7384
  try {
@@ -6798,8 +7401,8 @@ var createSkillSearchTool = (skillsResolverKey) => defineTool12({
6798
7401
  });
6799
7402
 
6800
7403
  // src/tools/todo-mutate.ts
6801
- import { defineTool as defineTool13 } from "@codelia/core";
6802
- import { z as z14 } from "zod";
7404
+ import { defineTool as defineTool12 } from "@codelia/core";
7405
+ import { z as z13 } from "zod";
6803
7406
 
6804
7407
  // src/tools/todo-store.ts
6805
7408
  var TODO_SESSION_META_KEY = "codelia_todos";
@@ -6909,37 +7512,37 @@ var pickNextTodo = (todos) => {
6909
7512
  var todoStore = /* @__PURE__ */ new Map();
6910
7513
 
6911
7514
  // src/tools/todo-mutate.ts
6912
- var todoStatusSchema = z14.enum(["pending", "in_progress", "completed"]);
6913
- var todoPrioritySchema = z14.number().int().min(1).max(5);
6914
- var todoItemSchema = z14.object({
6915
- id: z14.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
6916
- content: z14.string().min(1).describe("Todo item text."),
7515
+ var todoStatusSchema = z13.enum(["pending", "in_progress", "completed"]);
7516
+ var todoPrioritySchema = z13.number().int().min(1).max(5);
7517
+ var todoItemSchema = z13.object({
7518
+ id: z13.string().min(1).optional().describe("Optional stable ID. Keep if the task already exists."),
7519
+ content: z13.string().min(1).describe("Todo item text."),
6917
7520
  status: todoStatusSchema.describe("Todo status."),
6918
7521
  priority: todoPrioritySchema.optional().describe("Priority 1(high)-5(low). Default is 3."),
6919
- notes: z14.string().optional().describe("Optional implementation notes."),
6920
- activeForm: z14.string().optional().describe("Optional in-progress phrasing for UI display.")
7522
+ notes: z13.string().optional().describe("Optional implementation notes."),
7523
+ activeForm: z13.string().optional().describe("Optional in-progress phrasing for UI display.")
6921
7524
  });
6922
- var todoPatchItemSchema = z14.object({
6923
- id: z14.string().min(1).describe("Target todo ID."),
6924
- remove: z14.boolean().optional().describe("Set true to remove the todo item."),
6925
- content: z14.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
7525
+ var todoPatchItemSchema = z13.object({
7526
+ id: z13.string().min(1).describe("Target todo ID."),
7527
+ remove: z13.boolean().optional().describe("Set true to remove the todo item."),
7528
+ content: z13.string().min(1).nullable().default(null).describe("Updated todo text (null keeps current)."),
6926
7529
  status: todoStatusSchema.nullable().default(null).describe("Updated status (null keeps current)."),
6927
7530
  priority: todoPrioritySchema.nullable().default(null).describe("Updated priority (null keeps current)."),
6928
- notes: z14.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
6929
- activeForm: z14.string().nullable().default(null).describe(
7531
+ notes: z13.string().nullable().default(null).describe("Updated notes (null keeps current, empty clears)."),
7532
+ activeForm: z13.string().nullable().default(null).describe(
6930
7533
  "Updated in-progress phrasing (null keeps current, empty clears)."
6931
7534
  )
6932
7535
  });
6933
- var todoNewInputSchema = z14.object({
6934
- todos: z14.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
7536
+ var todoNewInputSchema = z13.object({
7537
+ todos: z13.array(todoItemSchema).min(1).describe("Full todo list to start or replace the current plan.")
6935
7538
  }).strict();
6936
- var todoAppendInputSchema = z14.object({
6937
- todos: z14.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
7539
+ var todoAppendInputSchema = z13.object({
7540
+ todos: z13.array(todoItemSchema).min(1).describe("Todo items to append to the current plan.")
6938
7541
  }).strict();
6939
- var todoPatchInputSchema = z14.object({
6940
- updates: z14.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
7542
+ var todoPatchInputSchema = z13.object({
7543
+ updates: z13.array(todoPatchItemSchema).min(1).describe("Patch operations for existing todo items.")
6941
7544
  }).strict();
6942
- var todoClearInputSchema = z14.object({}).strict();
7545
+ var todoClearInputSchema = z13.object({}).strict();
6943
7546
  var statusSymbol = {
6944
7547
  pending: "[ ]",
6945
7548
  in_progress: "[>]",
@@ -7034,7 +7637,7 @@ var applyTodoMutation = (sessionId, input, outputMode) => {
7034
7637
  }
7035
7638
  return formatSuccess(outputMode, nextTodos);
7036
7639
  };
7037
- var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool13({
7640
+ var createTodoMutationTool = (name, description, input, executeMutation, sandboxKey, sessionContextKey) => defineTool12({
7038
7641
  name,
7039
7642
  description,
7040
7643
  input,
@@ -7089,17 +7692,17 @@ var createTodoClearTool = (sandboxKey, sessionContextKey) => createTodoMutationT
7089
7692
  );
7090
7693
 
7091
7694
  // src/tools/todo-read.ts
7092
- import { defineTool as defineTool14 } from "@codelia/core";
7093
- import { z as z15 } from "zod";
7695
+ import { defineTool as defineTool13 } from "@codelia/core";
7696
+ import { z as z14 } from "zod";
7094
7697
  var statusSymbol2 = {
7095
7698
  pending: "[ ]",
7096
7699
  in_progress: "[>]",
7097
7700
  completed: "[x]"
7098
7701
  };
7099
- var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
7702
+ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool13({
7100
7703
  name: "todo_read",
7101
7704
  description: "Read the in-session todo plan with execution order and next step.",
7102
- input: z15.object({}),
7705
+ input: z14.object({}),
7103
7706
  execute: async (_input, ctx) => {
7104
7707
  const sandbox = await getSandboxContext(ctx, sandboxKey);
7105
7708
  const sessionContext = sessionContextKey ? await getToolSessionContext(ctx, sessionContextKey) : null;
@@ -7135,15 +7738,15 @@ var createTodoReadTool = (sandboxKey, sessionContextKey) => defineTool14({
7135
7738
  });
7136
7739
 
7137
7740
  // src/tools/tool-output-cache.ts
7138
- import { defineTool as defineTool15 } from "@codelia/core";
7139
- import { z as z16 } from "zod";
7140
- var createToolOutputCacheTool = (store) => defineTool15({
7741
+ import { defineTool as defineTool14 } from "@codelia/core";
7742
+ import { z as z15 } from "zod";
7743
+ var createToolOutputCacheTool = (store) => defineTool14({
7141
7744
  name: "tool_output_cache",
7142
7745
  description: "Read cached tool output by ref_id.",
7143
- input: z16.object({
7144
- ref_id: z16.string().describe("Tool output reference ID."),
7145
- offset: z16.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7146
- limit: z16.number().int().positive().optional().describe("Optional max number of lines to return.")
7746
+ input: z15.object({
7747
+ ref_id: z15.string().describe("Tool output reference ID."),
7748
+ offset: z15.number().int().nonnegative().optional().describe("Optional 0-based line offset."),
7749
+ limit: z15.number().int().positive().optional().describe("Optional max number of lines to return.")
7147
7750
  }),
7148
7751
  execute: async (input) => {
7149
7752
  if (!store.read) {
@@ -7159,14 +7762,14 @@ var createToolOutputCacheTool = (store) => defineTool15({
7159
7762
  }
7160
7763
  }
7161
7764
  });
7162
- var createToolOutputCacheLineTool = (store) => defineTool15({
7765
+ var createToolOutputCacheLineTool = (store) => defineTool14({
7163
7766
  name: "tool_output_cache_line",
7164
7767
  description: "Read a single cached output line segment by line number and char offset.",
7165
- input: z16.object({
7166
- ref_id: z16.string().describe("Tool output reference ID."),
7167
- line_number: z16.number().int().positive().describe("1-based line number to read."),
7168
- char_offset: z16.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7169
- char_limit: z16.number().int().positive().optional().describe("Max chars to return.")
7768
+ input: z15.object({
7769
+ ref_id: z15.string().describe("Tool output reference ID."),
7770
+ line_number: z15.number().int().positive().describe("1-based line number to read."),
7771
+ char_offset: z15.number().int().nonnegative().optional().describe("0-based start character in the target line. Default 0."),
7772
+ char_limit: z15.number().int().positive().optional().describe("Max chars to return.")
7170
7773
  }),
7171
7774
  execute: async (input) => {
7172
7775
  if (!store.readLine) {
@@ -7183,16 +7786,16 @@ var createToolOutputCacheLineTool = (store) => defineTool15({
7183
7786
  }
7184
7787
  }
7185
7788
  });
7186
- var createToolOutputCacheGrepTool = (store) => defineTool15({
7789
+ var createToolOutputCacheGrepTool = (store) => defineTool14({
7187
7790
  name: "tool_output_cache_grep",
7188
7791
  description: "Search cached tool output by ref_id.",
7189
- input: z16.object({
7190
- ref_id: z16.string().describe("Tool output reference ID."),
7191
- pattern: z16.string().describe("Text or regex pattern to search for."),
7192
- regex: z16.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7193
- before: z16.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7194
- after: z16.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7195
- max_matches: z16.number().int().positive().optional().describe("Maximum number of matches to return.")
7792
+ input: z15.object({
7793
+ ref_id: z15.string().describe("Tool output reference ID."),
7794
+ pattern: z15.string().describe("Text or regex pattern to search for."),
7795
+ regex: z15.boolean().optional().describe("Interpret pattern as regex when true. Default false."),
7796
+ before: z15.number().int().nonnegative().optional().describe("Context lines before each match. Default 0."),
7797
+ after: z15.number().int().nonnegative().optional().describe("Context lines after each match. Default 0."),
7798
+ max_matches: z15.number().int().positive().optional().describe("Maximum number of matches to return.")
7196
7799
  }),
7197
7800
  execute: async (input) => {
7198
7801
  if (!store.grep) {
@@ -7212,28 +7815,420 @@ var createToolOutputCacheGrepTool = (store) => defineTool15({
7212
7815
  }
7213
7816
  });
7214
7817
 
7215
- // src/tools/write.ts
7216
- import { promises as fs15 } from "fs";
7217
- import path13 from "path";
7818
+ // src/tools/view-image.ts
7819
+ import { promises as fs13 } from "fs";
7820
+ import path12 from "path";
7821
+ import { defineTool as defineTool15 } from "@codelia/core";
7822
+ import { z as z16 } from "zod";
7823
+ var DEFAULT_MAX_BYTES2 = 5 * 1024 * 1024;
7824
+ var MAX_MAX_BYTES = 10 * 1024 * 1024;
7825
+ var MIME_BY_EXTENSION = {
7826
+ ".png": "image/png",
7827
+ ".jpg": "image/jpeg",
7828
+ ".jpeg": "image/jpeg",
7829
+ ".webp": "image/webp",
7830
+ ".gif": "image/gif"
7831
+ };
7832
+ var resolveImageMime = (filePath) => {
7833
+ return MIME_BY_EXTENSION[path12.extname(filePath).toLowerCase()] ?? null;
7834
+ };
7835
+ var createViewImageTool = (sandboxKey) => defineTool15({
7836
+ name: "view_image",
7837
+ description: "Load a local image file and return it as a multimodal content part.",
7838
+ input: z16.object({
7839
+ file_path: z16.string().describe(
7840
+ "Image file path. Sandbox-bounded unless full-access mode is active."
7841
+ ),
7842
+ detail: z16.enum(["auto", "low", "high"]).optional().describe("Image detail hint. Default auto."),
7843
+ max_bytes: z16.number().int().positive().max(MAX_MAX_BYTES).optional().describe("Max allowed file size in bytes. Default 5242880.")
7844
+ }),
7845
+ execute: async (input, ctx) => {
7846
+ let resolved;
7847
+ try {
7848
+ const sandbox = await getSandboxContext(ctx, sandboxKey);
7849
+ resolved = sandbox.resolvePath(input.file_path);
7850
+ } catch (error) {
7851
+ throw new Error(`Security error: ${String(error)}`);
7852
+ }
7853
+ const mediaType = resolveImageMime(input.file_path);
7854
+ if (!mediaType) {
7855
+ return `Unsupported image type: ${input.file_path}`;
7856
+ }
7857
+ try {
7858
+ const stat = await fs13.stat(resolved);
7859
+ if (stat.isDirectory()) {
7860
+ return `Path is a directory: ${input.file_path}`;
7861
+ }
7862
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES2;
7863
+ if (stat.size > maxBytes) {
7864
+ return `Image too large: ${input.file_path} (${stat.size} bytes > ${maxBytes} bytes)`;
7865
+ }
7866
+ const buffer = await fs13.readFile(resolved);
7867
+ const dataUrl = `data:${mediaType};base64,${buffer.toString("base64")}`;
7868
+ return [
7869
+ {
7870
+ type: "text",
7871
+ text: `Image loaded: ${input.file_path}
7872
+ `
7873
+ },
7874
+ {
7875
+ type: "image_url",
7876
+ image_url: {
7877
+ url: dataUrl,
7878
+ media_type: mediaType,
7879
+ detail: input.detail ?? "auto"
7880
+ }
7881
+ }
7882
+ ];
7883
+ } catch (error) {
7884
+ if (error.code === "ENOENT") {
7885
+ return `File not found: ${input.file_path}`;
7886
+ }
7887
+ return `Error loading image: ${String(error)}`;
7888
+ }
7889
+ }
7890
+ });
7891
+
7892
+ // src/tools/webfetch.ts
7218
7893
  import { defineTool as defineTool16 } from "@codelia/core";
7219
7894
  import { z as z17 } from "zod";
7220
- var buildDiffPreview = (content, filePath) => {
7221
- const diff = createUnifiedDiff(filePath, "", content);
7222
- if (!diff) {
7223
- return `--- ${filePath}
7224
- +++ ${filePath}
7225
- @@ -0,0 +0,0 @@`;
7895
+ var DEFAULT_TIMEOUT_MS3 = 1e4;
7896
+ var MAX_TIMEOUT_MS = 3e4;
7897
+ var DEFAULT_MAX_BYTES3 = 2e5;
7898
+ var MAX_MAX_BYTES2 = 1e6;
7899
+ var TLS_ERROR_CODES = /* @__PURE__ */ new Set([
7900
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
7901
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
7902
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
7903
+ "SELF_SIGNED_CERT_IN_CHAIN",
7904
+ "ERR_TLS_CERT_ALTNAME_INVALID",
7905
+ "CERT_HAS_EXPIRED",
7906
+ "CERT_NOT_YET_VALID"
7907
+ ]);
7908
+ 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();
7909
+ var decodeHtmlEntities = (value) => value.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, '"').replace(/&#39;/gi, "'");
7910
+ var htmlToText = (html) => {
7911
+ 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, "");
7912
+ const withBreaks = withoutScripts.replace(/<br\s*\/?>/gi, "\n").replace(
7913
+ /<\/(p|div|section|article|header|footer|main|aside|nav|tr|table|ul|ol|li|h[1-6])>/gi,
7914
+ "\n"
7915
+ ).replace(/<(li)[^>]*>/gi, "- ");
7916
+ const stripped = withBreaks.replace(/<[^>]+>/g, " ");
7917
+ return normalizeWhitespace(decodeHtmlEntities(stripped));
7918
+ };
7919
+ var htmlToMarkdown = (html) => {
7920
+ 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, "");
7921
+ const linked = withoutScripts.replace(
7922
+ /<a\s+[^>]*href=(["'])(.*?)\1[^>]*>([\s\S]*?)<\/a>/gi,
7923
+ (_match, _quote, href, text) => {
7924
+ const label = htmlToText(text) || href;
7925
+ return `[${label}](${href})`;
7926
+ }
7927
+ );
7928
+ const headed = linked.replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, (_m, text) => {
7929
+ return `# ${htmlToText(text)}
7930
+
7931
+ `;
7932
+ }).replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, (_m, text) => {
7933
+ return `## ${htmlToText(text)}
7934
+
7935
+ `;
7936
+ }).replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, (_m, text) => {
7937
+ return `### ${htmlToText(text)}
7938
+
7939
+ `;
7940
+ }).replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (_m, text) => {
7941
+ return `- ${htmlToText(text)}
7942
+ `;
7943
+ }).replace(/<br\s*\/?>/gi, "\n").replace(
7944
+ /<\/(p|div|section|article|header|footer|main|aside|nav|ul|ol)>/gi,
7945
+ "\n\n"
7946
+ );
7947
+ return normalizeWhitespace(
7948
+ decodeHtmlEntities(headed.replace(/<[^>]+>/g, " "))
7949
+ );
7950
+ };
7951
+ var isTextualContentType = (contentType) => {
7952
+ const normalized = contentType.toLowerCase();
7953
+ if (!normalized) return true;
7954
+ if (normalized.startsWith("text/")) return true;
7955
+ if (normalized.includes("json")) return true;
7956
+ if (normalized.includes("xml")) return true;
7957
+ if (normalized.includes("javascript")) return true;
7958
+ if (normalized.includes("xhtml")) return true;
7959
+ if (normalized.includes("svg")) return true;
7960
+ if (normalized.includes("markdown")) return true;
7961
+ if (normalized.includes("yaml")) return true;
7962
+ if (normalized.includes("x-www-form-urlencoded")) return true;
7963
+ return false;
7964
+ };
7965
+ var looksBinaryBuffer = (buffer) => {
7966
+ if (buffer.length === 0) return false;
7967
+ let suspicious = 0;
7968
+ const sample = Math.min(buffer.length, 512);
7969
+ for (let index = 0; index < sample; index += 1) {
7970
+ const byte = buffer[index] ?? 0;
7971
+ if (byte === 0) {
7972
+ return true;
7973
+ }
7974
+ const isControl = byte < 32 && byte !== 9 && byte !== 10 && byte !== 12 && byte !== 13;
7975
+ if (isControl) {
7976
+ suspicious += 1;
7977
+ }
7978
+ }
7979
+ return suspicious / sample > 0.1;
7980
+ };
7981
+ var readResponseBody = async (response, maxBytes) => {
7982
+ const contentLength = Number(response.headers.get("content-length"));
7983
+ if (!response.body) {
7984
+ const buffer = Buffer.from(await response.arrayBuffer());
7985
+ if (buffer.byteLength <= maxBytes) {
7986
+ return { buffer, truncated: false, byteSize: buffer.byteLength };
7987
+ }
7988
+ const truncated2 = buffer.subarray(0, maxBytes);
7989
+ return {
7990
+ buffer: truncated2,
7991
+ truncated: true,
7992
+ byteSize: Number.isFinite(contentLength) ? contentLength : buffer.byteLength
7993
+ };
7994
+ }
7995
+ const reader = response.body.getReader();
7996
+ const chunks = [];
7997
+ let total = 0;
7998
+ let truncated = false;
7999
+ while (true) {
8000
+ const { value, done } = await reader.read();
8001
+ if (done) break;
8002
+ if (!value) continue;
8003
+ if (total + value.byteLength > maxBytes) {
8004
+ const remaining = maxBytes - total;
8005
+ if (remaining > 0) {
8006
+ chunks.push(value.slice(0, remaining));
8007
+ total += remaining;
8008
+ }
8009
+ truncated = true;
8010
+ await reader.cancel();
8011
+ break;
8012
+ }
8013
+ chunks.push(value);
8014
+ total += value.byteLength;
8015
+ }
8016
+ const combined = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));
8017
+ return {
8018
+ buffer: combined,
8019
+ truncated,
8020
+ byteSize: Number.isFinite(contentLength) && contentLength > total ? contentLength : total
8021
+ };
8022
+ };
8023
+ var looksLikeHtml = (contentType, text) => contentType.includes("text/html") || /<html[\s>]|<!doctype html/i.test(text);
8024
+ var extractCharset = (contentType) => {
8025
+ const match = /charset\s*=\s*("?)([^;"\s]+)\1/i.exec(contentType);
8026
+ if (!match) return null;
8027
+ const charset = match[2]?.trim();
8028
+ return charset ? charset : null;
8029
+ };
8030
+ var decodeBuffer = (buffer, contentType) => {
8031
+ const charset = extractCharset(contentType);
8032
+ if (charset) {
8033
+ try {
8034
+ return new TextDecoder(charset).decode(buffer);
8035
+ } catch {
8036
+ }
8037
+ }
8038
+ return buffer.toString("utf8");
8039
+ };
8040
+ var extractTitle = (html) => {
8041
+ const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
8042
+ if (!match) return void 0;
8043
+ const title = htmlToText(match[1] ?? "");
8044
+ return title || void 0;
8045
+ };
8046
+ var describeUnknownError = (error) => {
8047
+ if (error instanceof Error && error.message) {
8048
+ return error.message;
7226
8049
  }
7227
- return diff;
8050
+ return String(error);
8051
+ };
8052
+ var extractNestedCode = (error) => {
8053
+ if (!error || typeof error !== "object") return null;
8054
+ const direct = error.code;
8055
+ if (typeof direct === "string" && direct.trim().length > 0) {
8056
+ return direct.trim();
8057
+ }
8058
+ const cause = error.cause;
8059
+ if (!cause || typeof cause !== "object") return null;
8060
+ const causeCode = cause.code;
8061
+ if (typeof causeCode === "string" && causeCode.trim().length > 0) {
8062
+ return causeCode.trim();
8063
+ }
8064
+ return null;
8065
+ };
8066
+ var extractNestedMessage = (error) => {
8067
+ if (!error || typeof error !== "object") return null;
8068
+ const cause = error.cause;
8069
+ if (!cause || typeof cause !== "object") return null;
8070
+ const causeMessage = cause.message;
8071
+ if (typeof causeMessage === "string" && causeMessage.trim().length > 0) {
8072
+ return causeMessage.trim();
8073
+ }
8074
+ return null;
8075
+ };
8076
+ var compactFetchErrorDetail = (options) => {
8077
+ const genericMessage = options.rawMessage.trim().length === 0 || options.rawMessage.trim().toLowerCase() === "fetch failed";
8078
+ const causeText = options.causeMessage && options.causeMessage.toLowerCase() !== "fetch failed" ? options.causeMessage : null;
8079
+ 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");
8080
+ return options.code ? `${primary} (code=${options.code})` : primary;
8081
+ };
8082
+ var classifyFetchError = (error, timeoutMs) => {
8083
+ if (error?.name === "AbortError") {
8084
+ return {
8085
+ kind: "timeout",
8086
+ detail: `timed out after ${timeoutMs}ms`
8087
+ };
8088
+ }
8089
+ const rawMessage = describeUnknownError(error);
8090
+ const message = rawMessage.toLowerCase();
8091
+ const code = extractNestedCode(error)?.toUpperCase() ?? null;
8092
+ const causeMessage = extractNestedMessage(error);
8093
+ if (code === "ENOTFOUND" || code === "EAI_AGAIN" || message.includes("getaddrinfo") || message.includes("dns")) {
8094
+ return {
8095
+ kind: "dns_error",
8096
+ detail: compactFetchErrorDetail({
8097
+ kind: "dns_error",
8098
+ rawMessage,
8099
+ code,
8100
+ causeMessage
8101
+ })
8102
+ };
8103
+ }
8104
+ if (code === "ECONNREFUSED" || message.includes("connection refused")) {
8105
+ return {
8106
+ kind: "connection_refused",
8107
+ detail: compactFetchErrorDetail({
8108
+ kind: "connection_refused",
8109
+ rawMessage,
8110
+ code,
8111
+ causeMessage
8112
+ })
8113
+ };
8114
+ }
8115
+ if (code === "ECONNRESET" || code === "EPIPE" || message.includes("socket hang up") || message.includes("connection reset")) {
8116
+ return {
8117
+ kind: "connection_reset",
8118
+ detail: compactFetchErrorDetail({
8119
+ kind: "connection_reset",
8120
+ rawMessage,
8121
+ code,
8122
+ causeMessage
8123
+ })
8124
+ };
8125
+ }
8126
+ 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")) {
8127
+ return {
8128
+ kind: "tls_error",
8129
+ detail: compactFetchErrorDetail({
8130
+ kind: "tls_error",
8131
+ rawMessage,
8132
+ code,
8133
+ causeMessage
8134
+ })
8135
+ };
8136
+ }
8137
+ return {
8138
+ kind: "network_error",
8139
+ detail: compactFetchErrorDetail({
8140
+ kind: "network_error",
8141
+ rawMessage,
8142
+ code,
8143
+ causeMessage
8144
+ })
8145
+ };
7228
8146
  };
7229
- var createWriteTool = (sandboxKey) => defineTool16({
8147
+ var createWebfetchTool = () => defineTool16({
8148
+ name: "webfetch",
8149
+ description: "Fetch an HTTP(S) URL and return bounded markdown, text, or HTML.",
8150
+ input: z17.object({
8151
+ url: z17.string().min(1).describe("HTTP(S) URL to fetch."),
8152
+ output_format: z17.enum(["markdown", "text", "html"]).optional().describe("Output format. Default markdown."),
8153
+ timeout_ms: z17.number().int().positive().max(MAX_TIMEOUT_MS).optional().describe("Fetch timeout in ms. Default 10000."),
8154
+ max_bytes: z17.number().int().positive().max(MAX_MAX_BYTES2).optional().describe("Max response bytes to keep. Default 200000.")
8155
+ }),
8156
+ execute: async (input) => {
8157
+ let url;
8158
+ try {
8159
+ url = new URL(input.url);
8160
+ } catch {
8161
+ return `Invalid URL: ${input.url}`;
8162
+ }
8163
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
8164
+ return `Unsupported URL protocol: ${url.protocol}`;
8165
+ }
8166
+ const timeoutMs = input.timeout_ms ?? DEFAULT_TIMEOUT_MS3;
8167
+ const maxBytes = input.max_bytes ?? DEFAULT_MAX_BYTES3;
8168
+ const outputFormat = input.output_format ?? "markdown";
8169
+ const controller = new AbortController();
8170
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
8171
+ try {
8172
+ const response = await fetch(url, {
8173
+ redirect: "follow",
8174
+ signal: controller.signal,
8175
+ headers: {
8176
+ 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"
8177
+ }
8178
+ });
8179
+ const contentType = response.headers.get("content-type") ?? "";
8180
+ const normalizedContentType = contentType.toLowerCase();
8181
+ if (contentType && !isTextualContentType(normalizedContentType)) {
8182
+ return `Unsupported content-type for webfetch: ${contentType.split(";")[0]}`;
8183
+ }
8184
+ const body = await readResponseBody(response, maxBytes);
8185
+ if (!contentType && looksBinaryBuffer(body.buffer)) {
8186
+ return "Unsupported content-type for webfetch: binary response";
8187
+ }
8188
+ const rawText = decodeBuffer(body.buffer, contentType);
8189
+ const isHtml = looksLikeHtml(normalizedContentType, rawText);
8190
+ let content = rawText;
8191
+ if (outputFormat === "html") {
8192
+ content = rawText;
8193
+ } else if (isHtml) {
8194
+ content = outputFormat === "text" ? htmlToText(rawText) : htmlToMarkdown(rawText);
8195
+ } else {
8196
+ content = normalizeWhitespace(rawText);
8197
+ }
8198
+ return {
8199
+ url: input.url,
8200
+ final_url: response.url || input.url,
8201
+ status: response.status,
8202
+ ok: response.ok,
8203
+ content_type: contentType || null,
8204
+ output_format: outputFormat,
8205
+ title: isHtml ? extractTitle(rawText) ?? null : null,
8206
+ content,
8207
+ truncated: body.truncated,
8208
+ byte_size: body.byteSize
8209
+ };
8210
+ } catch (error) {
8211
+ const classified = classifyFetchError(error, timeoutMs);
8212
+ return `Error fetching URL [${classified.kind}]: ${classified.detail}`;
8213
+ } finally {
8214
+ clearTimeout(timeout);
8215
+ }
8216
+ }
8217
+ });
8218
+
8219
+ // src/tools/write.ts
8220
+ import { promises as fs14 } from "fs";
8221
+ import path13 from "path";
8222
+ import { defineTool as defineTool17 } from "@codelia/core";
8223
+ import { z as z18 } from "zod";
8224
+ var createWriteTool = (sandboxKey, outputCacheStore) => defineTool17({
7230
8225
  name: "write",
7231
8226
  description: "Write text to a file, creating parent directories if needed.",
7232
- input: z17.object({
7233
- file_path: z17.string().describe(
8227
+ input: z18.object({
8228
+ file_path: z18.string().describe(
7234
8229
  "File path. Sandbox-bounded unless full-access mode is active."
7235
8230
  ),
7236
- content: z17.string().describe("UTF-8 text content to write.")
8231
+ content: z18.string().describe("UTF-8 text content to write.")
7237
8232
  }),
7238
8233
  execute: async (input, ctx) => {
7239
8234
  let resolved;
@@ -7244,12 +8239,28 @@ var createWriteTool = (sandboxKey) => defineTool16({
7244
8239
  throw new Error(`Security error: ${String(error)}`);
7245
8240
  }
7246
8241
  try {
7247
- await fs15.mkdir(path13.dirname(resolved), { recursive: true });
7248
- await fs15.writeFile(resolved, input.content, "utf8");
7249
- const diff = buildDiffPreview(input.content, input.file_path);
8242
+ let before = "";
8243
+ try {
8244
+ before = await fs14.readFile(resolved, "utf8");
8245
+ } catch (error) {
8246
+ if (error.code !== "ENOENT") {
8247
+ throw error;
8248
+ }
8249
+ }
8250
+ await fs14.mkdir(path13.dirname(resolved), { recursive: true });
8251
+ await fs14.writeFile(resolved, input.content, "utf8");
8252
+ const diffPayload = await buildDiffPayload({
8253
+ toolName: "write",
8254
+ diff: createUnifiedDiff(input.file_path, before, input.content),
8255
+ outputCacheStore,
8256
+ emptyDiff: `--- ${input.file_path}
8257
+ +++ ${input.file_path}
8258
+ @@ -0,0 +0,0 @@`,
8259
+ debugContext: `file=${input.file_path}`
8260
+ });
7250
8261
  return {
7251
- summary: `Wrote ${input.content.length} bytes to ${input.file_path}`,
7252
- diff,
8262
+ summary: `Wrote ${Buffer.byteLength(input.content, "utf8")} bytes to ${input.file_path}`,
8263
+ ...diffPayload,
7253
8264
  file_path: input.file_path
7254
8265
  };
7255
8266
  } catch (error) {
@@ -7291,14 +8302,15 @@ var createTools = (sandboxKey, agentsResolverKey, skillsResolverKey, options = {
7291
8302
  }),
7292
8303
  createReadTool(sandboxKey),
7293
8304
  createReadLineTool(sandboxKey),
7294
- createWriteTool(sandboxKey),
7295
- createEditTool(sandboxKey),
8305
+ createWriteTool(sandboxKey, options.toolOutputCacheStore),
8306
+ createEditTool(sandboxKey, options.toolOutputCacheStore),
8307
+ createApplyPatchTool(sandboxKey, options.toolOutputCacheStore),
8308
+ createViewImageTool(sandboxKey),
7296
8309
  createAgentsResolveTool(sandboxKey, agentsResolverKey),
7297
8310
  createSkillSearchTool(skillsResolverKey),
7298
8311
  createSkillLoadTool(skillsResolverKey),
8312
+ createWebfetchTool(),
7299
8313
  ...options.search ? [createSearchTool(options.search)] : [],
7300
- createGlobSearchTool(sandboxKey),
7301
- createGrepTool(sandboxKey),
7302
8314
  ...options.toolOutputCacheStore ? [
7303
8315
  createToolOutputCacheTool(options.toolOutputCacheStore),
7304
8316
  createToolOutputCacheLineTool(options.toolOutputCacheStore),
@@ -7788,6 +8800,9 @@ var createAgentFactory = (state, options = {}) => {
7788
8800
  const editTool = baseLocalTools.find(
7789
8801
  (tool) => tool.definition.name === "edit"
7790
8802
  );
8803
+ const applyPatchTool = baseLocalTools.find(
8804
+ (tool) => tool.definition.name === "apply_patch"
8805
+ );
7791
8806
  let mcpTools = [];
7792
8807
  if (options.mcpManager) {
7793
8808
  try {
@@ -8024,9 +9039,9 @@ var createAgentFactory = (state, options = {}) => {
8024
9039
  const resolved = sandbox.resolvePath(filePath);
8025
9040
  let before = "";
8026
9041
  try {
8027
- const stat = await fs16.stat(resolved);
9042
+ const stat = await fs15.stat(resolved);
8028
9043
  if (!stat.isDirectory()) {
8029
- before = await fs16.readFile(resolved, "utf8");
9044
+ before = await fs15.readFile(resolved, "utf8");
8030
9045
  }
8031
9046
  } catch {
8032
9047
  before = "";
@@ -8089,6 +9104,34 @@ var createAgentFactory = (state, options = {}) => {
8089
9104
  previewSummary = "Preview unavailable: dry-run failed";
8090
9105
  }
8091
9106
  }
9107
+ } else if (call.function.name === "apply_patch" && applyPatchTool) {
9108
+ const parsed = parseToolArgsObject(rawArgs);
9109
+ if (parsed) {
9110
+ const dryRunInput = { ...parsed, dry_run: true };
9111
+ try {
9112
+ const result = await applyPatchTool.executeRaw(
9113
+ JSON.stringify(dryRunInput),
9114
+ toolCtx
9115
+ );
9116
+ if (result && typeof result === "object") {
9117
+ const obj = unwrapToolJsonObject(result);
9118
+ if (!obj) {
9119
+ previewSummary = "Preview unavailable: unexpected dry-run output";
9120
+ } else {
9121
+ const diff = typeof obj.diff === "string" ? obj.diff : "";
9122
+ const summary = typeof obj.summary === "string" ? obj.summary : "";
9123
+ const preview = buildBoundedDiffPreview(diff);
9124
+ previewDiff = preview.diff;
9125
+ previewTruncated = preview.truncated;
9126
+ if (!previewDiff) {
9127
+ previewSummary = summary || "Preview: no diff content";
9128
+ }
9129
+ }
9130
+ }
9131
+ } catch {
9132
+ previewSummary = "Preview unavailable: dry-run failed";
9133
+ }
9134
+ }
8092
9135
  }
8093
9136
  if (runId) {
8094
9137
  if (previewDiff || previewSummary) {
@@ -8783,7 +9826,7 @@ var fetchDiscoveredOAuthConfig = async (serverUrl) => {
8783
9826
  };
8784
9827
 
8785
9828
  // src/mcp/tooling.ts
8786
- import crypto7 from "crypto";
9829
+ import crypto8 from "crypto";
8787
9830
  var MAX_SCHEMA_SIZE_BYTES = 64 * 1024;
8788
9831
  var MAX_TOOL_OUTPUT_CHARS = 1e5;
8789
9832
  var MAX_TOOLS_LIST_PAGES = 100;
@@ -8793,7 +9836,7 @@ var toSlug2 = (value) => {
8793
9836
  const slug = value.toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^_+|_+$/g, "");
8794
9837
  return slug || "tool";
8795
9838
  };
8796
- var hash8 = (value) => crypto7.createHash("sha256").update(value).digest("hex").slice(0, 8);
9839
+ var hash8 = (value) => crypto8.createHash("sha256").update(value).digest("hex").slice(0, 8);
8797
9840
  var clampToolName = (value) => {
8798
9841
  if (value.length <= 63) return value;
8799
9842
  return value.slice(0, 63);
@@ -9458,7 +10501,7 @@ var createContextHandlers = ({
9458
10501
  };
9459
10502
 
9460
10503
  // src/rpc/history.ts
9461
- import { createReadStream, promises as fs17 } from "fs";
10504
+ import { createReadStream, promises as fs16 } from "fs";
9462
10505
  import path14 from "path";
9463
10506
  import { createInterface as createInterface2 } from "readline";
9464
10507
  import {
@@ -9523,7 +10566,7 @@ var collectRunCandidates = async (log2) => {
9523
10566
  const sessionsDir = paths.sessionsDir;
9524
10567
  let yearEntries;
9525
10568
  try {
9526
- yearEntries = await fs17.readdir(sessionsDir, {
10569
+ yearEntries = await fs16.readdir(sessionsDir, {
9527
10570
  withFileTypes: true,
9528
10571
  encoding: "utf8"
9529
10572
  });
@@ -9538,7 +10581,7 @@ var collectRunCandidates = async (log2) => {
9538
10581
  const yearPath = path14.join(sessionsDir, yearEntry.name);
9539
10582
  let monthEntries;
9540
10583
  try {
9541
- monthEntries = await fs17.readdir(yearPath, {
10584
+ monthEntries = await fs16.readdir(yearPath, {
9542
10585
  withFileTypes: true,
9543
10586
  encoding: "utf8"
9544
10587
  });
@@ -9551,7 +10594,7 @@ var collectRunCandidates = async (log2) => {
9551
10594
  const monthPath = path14.join(yearPath, monthEntry.name);
9552
10595
  let dayEntries;
9553
10596
  try {
9554
- dayEntries = await fs17.readdir(monthPath, {
10597
+ dayEntries = await fs16.readdir(monthPath, {
9555
10598
  withFileTypes: true,
9556
10599
  encoding: "utf8"
9557
10600
  });
@@ -9564,7 +10607,7 @@ var collectRunCandidates = async (log2) => {
9564
10607
  const dayPath = path14.join(monthPath, dayEntry.name);
9565
10608
  let files;
9566
10609
  try {
9567
- files = await fs17.readdir(dayPath, {
10610
+ files = await fs16.readdir(dayPath, {
9568
10611
  withFileTypes: true,
9569
10612
  encoding: "utf8"
9570
10613
  });
@@ -9576,7 +10619,7 @@ var collectRunCandidates = async (log2) => {
9576
10619
  if (!file.name.endsWith(".jsonl")) continue;
9577
10620
  const filePath = path14.join(dayPath, file.name);
9578
10621
  try {
9579
- const stat = await fs17.stat(filePath);
10622
+ const stat = await fs16.stat(filePath);
9580
10623
  candidates.push({ path: filePath, mtimeMs: stat.mtimeMs });
9581
10624
  } catch {
9582
10625
  }
@@ -12662,7 +13705,7 @@ var createRuntimeHandlers = ({
12662
13705
  };
12663
13706
 
12664
13707
  // src/runtime-state.ts
12665
- import crypto8 from "crypto";
13708
+ import crypto9 from "crypto";
12666
13709
  var RuntimeState = class {
12667
13710
  runSeq = /* @__PURE__ */ new Map();
12668
13711
  uiRequestCounter = 0;
@@ -12688,10 +13731,10 @@ var RuntimeState = class {
12688
13731
  runtimeSandboxRoot = null;
12689
13732
  diagnosticsEnabled = false;
12690
13733
  nextRunId() {
12691
- return crypto8.randomUUID();
13734
+ return crypto9.randomUUID();
12692
13735
  }
12693
13736
  nextSessionId() {
12694
- return crypto8.randomUUID();
13737
+ return crypto9.randomUUID();
12695
13738
  }
12696
13739
  beginRun(runId, uiContext) {
12697
13740
  this.activeRunId = runId;