@unieai/rabi-tool-fs 0.2.1-rc.3 → 0.2.2-rc.5

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 (43) hide show
  1. package/lib/index.js +877 -60
  2. package/lib/types/apply-patch-output.d.ts +140 -0
  3. package/lib/types/apply-patch-presentation.d.ts +15 -0
  4. package/lib/types/apply-patch.d.ts +10 -0
  5. package/lib/types/diff.d.ts +6 -0
  6. package/lib/types/error.d.ts +8 -0
  7. package/lib/types/image-error.d.ts +25 -0
  8. package/lib/types/index.d.ts +3 -1
  9. package/lib/types/patch/execute.d.ts +17 -0
  10. package/lib/types/patch/index.d.ts +17 -0
  11. package/lib/types/patch/plan.d.ts +52 -0
  12. package/lib/types/patch/preflight.d.ts +18 -0
  13. package/lib/types/patch/types.d.ts +106 -0
  14. package/lib/types/read-image.d.ts +2 -0
  15. package/lib/types/sandbox.d.ts +13 -4
  16. package/locale/de.json +6 -0
  17. package/locale/es.json +6 -0
  18. package/locale/fr.json +6 -0
  19. package/locale/ja.json +6 -0
  20. package/locale/pt.json +6 -0
  21. package/locale/ru.json +6 -0
  22. package/package.json +20 -14
  23. package/src/apply-patch-output.ts +149 -0
  24. package/src/apply-patch-presentation.ts +47 -0
  25. package/src/apply-patch.ts +52 -0
  26. package/src/diff.ts +102 -0
  27. package/src/edit.ts +169 -0
  28. package/src/error.ts +42 -0
  29. package/src/image-error.ts +36 -0
  30. package/src/index.ts +103 -0
  31. package/src/mutation-result.ts +21 -0
  32. package/src/patch/execute.ts +121 -0
  33. package/src/patch/index.ts +36 -0
  34. package/src/patch/plan.ts +117 -0
  35. package/src/patch/preflight.ts +157 -0
  36. package/src/patch/types.ts +88 -0
  37. package/src/read-image.ts +391 -0
  38. package/src/read-render.ts +244 -0
  39. package/src/read-target.ts +34 -0
  40. package/src/read.ts +210 -0
  41. package/src/sandbox.ts +145 -0
  42. package/src/session-cwd.ts +25 -0
  43. package/src/write.ts +153 -0
package/lib/index.js CHANGED
@@ -1,10 +1,14 @@
1
1
  import z from "@unieai/schemastery";
2
- import { defineTool } from "@unieai/rabi-tools";
2
+ import { ToolArgsError, ToolContextUnavailableError, defineTool } from "@unieai/rabi-tools";
3
3
  import { FsError } from "@unieai/rabi-fs";
4
4
  import { readLangHintForPath as langFromPath } from "@unieai/rabi-util-code-language";
5
5
  import { structuredPatch } from "diff";
6
+ import { PatchParseError, applyHunks, parsePatch } from "@unieai/rabi-fs-patch";
7
+ import { assertNever } from "@unieai/rabi-util-values";
8
+ import { HarnessError } from "@unieai/rabi-llm";
6
9
  import { basename, extname } from "node:path";
7
10
  import { AttachmentError, AttachmentId } from "@unieai/rabi-attachment";
11
+ import { HarnessError as HarnessError$1 } from "@unieai/rabi-error";
8
12
  import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@unieai/rabi-sandbox";
9
13
  //#region lib/types/read-render.js
10
14
  /**
@@ -216,7 +220,7 @@ const READ_LIMIT = 2e3;
216
220
  */
217
221
  const STREAM_MIN_SIZE = 10 * 1024 * 1024;
218
222
  function parsePositiveInteger(value, name) {
219
- if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
223
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) throw new ToolArgsError([`${name} must be a positive integer`]);
220
224
  return value;
221
225
  }
222
226
  /**
@@ -226,10 +230,10 @@ function parsePositiveInteger(value, name) {
226
230
  * @returns the validated input with `offset` defaulted to 1 and `limit` to `maxLimit`.
227
231
  */
228
232
  function parseReadArgs(args, maxLimit) {
229
- if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
233
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(["file_path must be a non-empty string"]);
230
234
  const offset = args.offset === void 0 ? 1 : parsePositiveInteger(args.offset, "offset");
231
235
  const limit = args.limit === void 0 ? maxLimit : parsePositiveInteger(args.limit, "limit");
232
- if (limit > maxLimit) throw new Error(`limit must be less than or equal to ${maxLimit}`);
236
+ if (limit > maxLimit) throw new ToolArgsError([`limit must be less than or equal to ${maxLimit}`]);
233
237
  return {
234
238
  filePath: args.file_path,
235
239
  offset,
@@ -245,7 +249,7 @@ function applyReadTool(ctx, caps) {
245
249
  ctx.systemPrompt.section({
246
250
  name: "tool:read",
247
251
  order: ctx.systemPrompt.getSectionOrder("TOOL_READ"),
248
- text: ({ scope }) => ctx.tools.get("read", scope) === void 0 ? "" : "Use the read tool — not shell commands like cat — to inspect text files. Use offset and limit to continue reading large files."
252
+ text: ({ scope }) => ctx.tools.get("read", scope) === void 0 ? "" : "Use the read tool — not shell commands like cat, sed, head, or tail — to inspect text files. Use offset and limit to read a line range or continue a large file."
249
253
  });
250
254
  ctx.tools.register(defineTool({
251
255
  name: "read",
@@ -444,6 +448,14 @@ function diffsFromMeta(meta) {
444
448
  return diffs;
445
449
  }
446
450
  /**
451
+ * Narrow the patch tool's optional stopped flag from persisted metadata.
452
+ * @param meta - opaque live or replayed result metadata.
453
+ * @returns true only for an explicit stopped flag.
454
+ */
455
+ function stoppedFromMeta(meta) {
456
+ return typeof meta === "object" && meta !== null && !Array.isArray(meta) && meta.stopped === true;
457
+ }
458
+ /**
447
459
  * Read the operation's file path even when the applied diff is empty.
448
460
  * @param meta - opaque persisted result metadata.
449
461
  * @returns the recorded path, or undefined for old or malformed metadata.
@@ -461,17 +473,6 @@ function pathFromMeta(meta) {
461
473
  * stable message shown to the model.
462
474
  * @module @unieai/rabi-tool-fs/src/error
463
475
  */
464
- /**
465
- * Render the stable model-facing diagnostic for a guarded-mutation failure.
466
- * `FS_STALE_VERSION` keeps the provider's reason and appends its re-read
467
- * remedy. `FS_NOT_OBSERVED` replaces operation-specific policy/provider text
468
- * with one path-aware reason and read remedy. The original error remains the
469
- * cause, and both diagnostics preserve its code for machine routing. Anything
470
- * else passes through untouched.
471
- * @param error - the caught value from a write/edit execution.
472
- * @param displayPath - the resolved target path shown to the model.
473
- * @returns a remediated `FsError` for the two guarded-mutation codes, else the original value.
474
- */
475
476
  function remediateFsError(error, displayPath) {
476
477
  if (!(error instanceof FsError)) return error;
477
478
  if (error.code === "FS_NOT_OBSERVED") return new FsError(`cannot modify "${displayPath}": file has not been read — read the file, then retry`, error.code, { cause: error });
@@ -515,7 +516,7 @@ function mutationResult(ctx, target, outcome, exec) {
515
516
  * @returns the camelCased input; `content` passes through untouched.
516
517
  */
517
518
  function parseWriteArgs(args) {
518
- if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
519
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(["file_path must be a non-empty string"]);
519
520
  return {
520
521
  filePath: args.file_path,
521
522
  content: args.content
@@ -543,7 +544,7 @@ function applyWriteTool(ctx, sandbox) {
543
544
  ctx.systemPrompt.section({
544
545
  name: "tool:write",
545
546
  order: ctx.systemPrompt.getSectionOrder("TOOL_WRITE"),
546
- text: ({ scope }) => ctx.tools.get("write", scope) === void 0 ? "" : "Read an existing file before overwriting it with write (the default fs-observation-policy requires it)" + (ctx.tools.get("edit", scope) === void 0 ? "" : " and prefer edit for targeted changes") + "."
547
+ text: ({ scope }) => ctx.tools.get("write", scope) === void 0 ? "" : "Read an existing file before overwriting it with write" + (ctx.tools.get("edit", scope) === void 0 ? "" : " and prefer edit for targeted changes") + "."
547
548
  });
548
549
  ctx.tools.register(defineTool({
549
550
  name: "write",
@@ -641,6 +642,775 @@ function applyWriteTool(ctx, sandbox) {
641
642
  }));
642
643
  }
643
644
  //#endregion
645
+ //#region lib/types/patch/plan.js
646
+ /**
647
+ * Resolve every operation without dropping repeated aliases or splitting moves.
648
+ * @param ctx - filesystem service owner.
649
+ * @param sandbox - filesystem diagnostic mapper.
650
+ * @param exec - session cwd and execution signal.
651
+ * @param request - raw patch and resolved per-call policy.
652
+ * @returns resolved operations sharing one target per canonical key, plus resolution refusals.
653
+ */
654
+ async function planPatch(ctx, sandbox, exec, request) {
655
+ const parsed = parsePatch(request.patch);
656
+ const targets = /* @__PURE__ */ new Map();
657
+ const resolve = async (path) => {
658
+ const target = await ctx.fs.resolve(path, await sessionResolveOptions(ctx, exec));
659
+ const prior = targets.get(target.targetKey);
660
+ if (prior) return prior;
661
+ targets.set(target.targetKey, target);
662
+ return target;
663
+ };
664
+ const result = {
665
+ operations: [],
666
+ refusals: []
667
+ };
668
+ for (const [index, operation] of parsed.entries()) {
669
+ const moveTo = operation.kind === "update" ? operation.moveTo : void 0;
670
+ const record = {
671
+ index,
672
+ kind: moveTo === void 0 ? operation.kind : "move",
673
+ path: operation.path,
674
+ patchLine: operation.lineNumber,
675
+ ...moveTo === void 0 ? {} : { destination: moveTo }
676
+ };
677
+ let failurePath = operation.path;
678
+ try {
679
+ const target = await resolve(operation.path);
680
+ record.path = target.displayPath;
681
+ const base = {
682
+ target,
683
+ rawPath: operation.path,
684
+ record
685
+ };
686
+ switch (operation.kind) {
687
+ case "add":
688
+ result.operations.push({
689
+ ...base,
690
+ kind: "add",
691
+ content: operation.content
692
+ });
693
+ break;
694
+ case "delete":
695
+ result.operations.push({
696
+ ...base,
697
+ kind: "delete"
698
+ });
699
+ break;
700
+ case "update":
701
+ if (operation.moveTo === void 0) result.operations.push({
702
+ ...base,
703
+ kind: "update",
704
+ hunks: operation.hunks
705
+ });
706
+ else {
707
+ failurePath = operation.moveTo;
708
+ const destination = await resolve(operation.moveTo);
709
+ record.destination = destination.displayPath;
710
+ result.operations.push({
711
+ ...base,
712
+ kind: "move",
713
+ destination,
714
+ hunks: operation.hunks
715
+ });
716
+ }
717
+ break;
718
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
719
+ default: assertNever(operation);
720
+ }
721
+ } catch (error) {
722
+ if (!(error instanceof FsError)) throw error;
723
+ result.refusals.push({
724
+ operation: record,
725
+ failure: patchFailure(sandbox, request.sandboxPolicy, error, failurePath)
726
+ });
727
+ }
728
+ }
729
+ return result;
730
+ }
731
+ /**
732
+ * Obtain a source guard without recording an observation.
733
+ * @param ctx - intent dispatcher.
734
+ * @param exec - opaque observation actor.
735
+ * @param target - resolved source.
736
+ * @param kind - deletion or edit-family source policy.
737
+ * @returns the observed version, or undefined for a bare provider.
738
+ */
739
+ function sourceIntent(ctx, exec, target, kind) {
740
+ return kind === "delete" ? ctx.waterfall("fs/delete-intent", target, exec, () => void 0) : ctx.waterfall("fs/edit-intent", target, exec, () => void 0);
741
+ }
742
+ /**
743
+ * Obtain a write guard without recording an observation.
744
+ * @param ctx - intent dispatcher.
745
+ * @param exec - opaque observation actor.
746
+ * @param target - resolved write destination.
747
+ * @returns the observed write intent, or undefined for a bare provider.
748
+ */
749
+ function destinationIntent(ctx, exec, target) {
750
+ return ctx.waterfall("fs/write-intent", target, exec, () => void 0);
751
+ }
752
+ /**
753
+ * Preserve filesystem codes while applying the existing model-facing error policy.
754
+ * @param sandbox - shared denial mapper.
755
+ * @param policy - policy supplied by the request.
756
+ * @param error - expected filesystem failure.
757
+ * @param path - display path whose operation failed.
758
+ * @returns the remediated code and message; unexpected mapper defects reject.
759
+ */
760
+ function patchFailure(sandbox, policy, error, path) {
761
+ const mapped = remediateFsError(sandbox.mapError(error, policy), path);
762
+ return {
763
+ code: mapped.code,
764
+ message: mapped.message
765
+ };
766
+ }
767
+ /**
768
+ * List all targets the operation can mutate, with destination first for a move.
769
+ * @param operation - resolved operation.
770
+ * @returns targets whose versions the uncertainty comparison records.
771
+ */
772
+ function mutationTargets(operation) {
773
+ return operation.kind === "move" ? [operation.destination, operation.target] : [operation.target];
774
+ }
775
+ //#endregion
776
+ //#region lib/types/patch/execute.js
777
+ async function unchanged(ctx, before) {
778
+ try {
779
+ for (const entry of before) if ((await ctx.fs.stat(entry.target))?.version !== entry.info?.version) return false;
780
+ return true;
781
+ } catch (error) {
782
+ if (!(error instanceof FsError)) throw error;
783
+ return false;
784
+ }
785
+ }
786
+ /**
787
+ * Commit a fully admitted plan; the first failure stops later operations without rollback.
788
+ * @param ctx - provider and observation dispatcher.
789
+ * @param sandbox - existing model-facing denial mapper.
790
+ * @param exec - session actor and cancellation signal.
791
+ * @param policy - request's resolved confinement policy.
792
+ * @param operations - operations that all passed preflight.
793
+ * @returns known changes, failed or unknown effects, and skipped successors in patch order.
794
+ */
795
+ async function commitPatch(ctx, sandbox, exec, policy, operations) {
796
+ const outcomes = operations.map((operation) => ({
797
+ status: "skipped",
798
+ operation: operation.record
799
+ }));
800
+ let cancelled = false;
801
+ for (const [index, operation] of operations.entries()) {
802
+ if (exec.signal.aborted) {
803
+ cancelled = true;
804
+ break;
805
+ }
806
+ let started = false;
807
+ let before = [];
808
+ let failurePath = operation.target.displayPath;
809
+ const target = operation.target;
810
+ const record = operation.record;
811
+ let outcome;
812
+ try {
813
+ before = await Promise.all(mutationTargets(operation).map(async (target) => ({
814
+ target,
815
+ info: await ctx.fs.stat(target, exec.signal)
816
+ })));
817
+ switch (operation.kind) {
818
+ case "add": {
819
+ const intent = await destinationIntent(ctx, exec, target);
820
+ started = true;
821
+ const result = await ctx.fs.writeText(target, operation.content, intent, exec.signal, policy);
822
+ ctx.emit("fs/observed", target, {
823
+ kind: "present",
824
+ version: result.version
825
+ }, exec);
826
+ outcome = {
827
+ status: "completed",
828
+ operation: record,
829
+ changes: [{
830
+ path: ctx.fs.processPath(target),
831
+ before: result.before,
832
+ after: result.after
833
+ }]
834
+ };
835
+ break;
836
+ }
837
+ case "update": {
838
+ const intent = await sourceIntent(ctx, exec, target, "edit");
839
+ started = true;
840
+ const result = await ctx.fs.patchText(target, operation.hunks, intent, exec.signal, policy);
841
+ ctx.emit("fs/observed", target, {
842
+ kind: "present",
843
+ version: result.version
844
+ }, exec);
845
+ outcome = {
846
+ status: "completed",
847
+ operation: record,
848
+ changes: [{
849
+ path: ctx.fs.processPath(target),
850
+ before: result.before,
851
+ after: result.after
852
+ }]
853
+ };
854
+ break;
855
+ }
856
+ case "delete": {
857
+ const intent = await sourceIntent(ctx, exec, target, "delete");
858
+ started = true;
859
+ const result = await ctx.fs.deleteFile(target, intent, exec.signal, policy);
860
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
861
+ outcome = {
862
+ status: "completed",
863
+ operation: record,
864
+ changes: [{
865
+ path: ctx.fs.processPath(target),
866
+ before: result.before,
867
+ after: null
868
+ }]
869
+ };
870
+ break;
871
+ }
872
+ case "move": {
873
+ const expectedSource = await sourceIntent(ctx, exec, target, "edit");
874
+ failurePath = operation.destination.displayPath;
875
+ const expectedDestination = await destinationIntent(ctx, exec, operation.destination);
876
+ started = true;
877
+ const result = await ctx.fs.moveFile(target, operation.destination, {
878
+ hunks: operation.hunks,
879
+ ...expectedSource === void 0 ? {} : { expectedSource },
880
+ ...expectedDestination === void 0 ? {} : { expectedDestination }
881
+ }, exec.signal, policy);
882
+ const changes = [{
883
+ path: ctx.fs.processPath(operation.destination),
884
+ before: result.destination.before,
885
+ after: result.destination.after
886
+ }];
887
+ ctx.emit("fs/observed", operation.destination, {
888
+ kind: "present",
889
+ version: result.destination.version
890
+ }, exec);
891
+ if (result.sourceDeleted) {
892
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
893
+ outcome = {
894
+ status: "completed",
895
+ operation: record,
896
+ changes: [...changes, {
897
+ path: ctx.fs.processPath(target),
898
+ before: result.sourceBefore,
899
+ after: null
900
+ }]
901
+ };
902
+ } else outcome = {
903
+ status: "failed",
904
+ operation: record,
905
+ failure: patchFailure(sandbox, policy, new FsError(result.sourceFailure.message, result.sourceFailure.code), target.displayPath),
906
+ changes
907
+ };
908
+ break;
909
+ }
910
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
911
+ default: assertNever(operation);
912
+ }
913
+ } catch (error) {
914
+ if (!(error instanceof FsError)) throw error;
915
+ const failure = patchFailure(sandbox, policy, error, failurePath);
916
+ outcome = started && (error.code === "FS_ABORTED" || error.code === "FS_IO_ERROR" && !await unchanged(ctx, before)) ? {
917
+ status: "unknown",
918
+ operation: record,
919
+ failure: {
920
+ ...failure,
921
+ message: `${failure.message} — re-read the affected files before retrying`
922
+ }
923
+ } : {
924
+ status: "failed",
925
+ operation: record,
926
+ failure,
927
+ changes: []
928
+ };
929
+ }
930
+ outcomes[index] = outcome;
931
+ if (outcome.status !== "completed") {
932
+ cancelled = exec.signal.aborted;
933
+ break;
934
+ }
935
+ }
936
+ return {
937
+ phase: "commit",
938
+ outcomes,
939
+ affectedPaths: [...new Set(outcomes.flatMap((outcome) => "changes" in outcome ? outcome.changes.map((change) => change.path) : []))],
940
+ cancelled
941
+ };
942
+ }
943
+ //#endregion
944
+ //#region lib/types/patch/preflight.js
945
+ var Preflight = class {
946
+ ctx;
947
+ sandbox;
948
+ exec;
949
+ policy;
950
+ failurePath = "";
951
+ states = /* @__PURE__ */ new Map();
952
+ constructor(ctx, sandbox, exec, policy) {
953
+ this.ctx = ctx;
954
+ this.sandbox = sandbox;
955
+ this.exec = exec;
956
+ this.policy = policy;
957
+ }
958
+ async state(target) {
959
+ const known = this.states.get(target.targetKey);
960
+ if (known) return known;
961
+ const info = await this.ctx.fs.stat(target, this.exec.signal);
962
+ const state = {
963
+ exists: info !== void 0,
964
+ info,
965
+ touched: false
966
+ };
967
+ this.states.set(target.targetKey, state);
968
+ return state;
969
+ }
970
+ regular(state, target) {
971
+ if (state.info !== void 0 && state.info.type !== "file") throw new FsError(`cannot modify "${target.displayPath}": not a regular file`, "FS_NOT_REGULAR_FILE");
972
+ }
973
+ async source(state, target, kind) {
974
+ const intent = state.touched ? void 0 : await sourceIntent(this.ctx, this.exec, target, kind === "delete" ? "delete" : "edit");
975
+ if (!state.exists) throw new FsError(`cannot ${kind} "${target.displayPath}": not found`, "FS_NOT_FOUND");
976
+ this.regular(state, target);
977
+ if (intent !== void 0 && intent.version !== state.info?.version) throw new FsError(`cannot ${kind} "${target.displayPath}": file changed since it was read`, "FS_STALE_VERSION");
978
+ }
979
+ async destination(state, target) {
980
+ const intent = state.touched ? void 0 : await destinationIntent(this.ctx, this.exec, target);
981
+ this.regular(state, target);
982
+ if (intent?.kind === "createIfAbsent" && state.exists) throw new FsError(`cannot overwrite existing "${target.displayPath}" without reading it first`, "FS_NOT_OBSERVED");
983
+ if (intent?.kind === "replaceIfVersion" && (!state.exists || state.info?.version !== intent.version)) throw new FsError(`cannot write "${target.displayPath}": file changed since it was read`, "FS_STALE_VERSION");
984
+ }
985
+ async content(state, target) {
986
+ if (state.content === void 0) {
987
+ const text = await this.ctx.fs.readText(target, this.exec.signal);
988
+ if (text.includes("\0")) throw new FsError(`cannot patch "${target.displayPath}": binary file`, "FS_NOT_TEXT");
989
+ state.content = text.replace(/\r\n/g, "\n");
990
+ }
991
+ return state.content;
992
+ }
993
+ publish(target, content) {
994
+ this.states.set(target.targetKey, {
995
+ exists: content !== void 0,
996
+ info: void 0,
997
+ touched: true,
998
+ ...content === void 0 ? {} : { content }
999
+ });
1000
+ }
1001
+ /** Simulate one operation; a filesystem refusal becomes the operation's failure. */
1002
+ async check(operation) {
1003
+ this.failurePath = operation.target.displayPath;
1004
+ try {
1005
+ return await this.simulate(operation);
1006
+ } catch (error) {
1007
+ if (!(error instanceof FsError)) throw error;
1008
+ return patchFailure(this.sandbox, this.policy, error, this.failurePath);
1009
+ }
1010
+ }
1011
+ async simulate(operation) {
1012
+ if (operation.kind === "move" && operation.target.targetKey === operation.destination.targetKey) throw new FsError(`cannot move "${operation.target.displayPath}" to itself`, "FS_SAME_TARGET");
1013
+ if (operation.kind === "delete" || operation.kind === "move") {
1014
+ if ((await this.ctx.fs.lstat(operation.rawPath, await sessionResolveOptions(this.ctx, this.exec)))?.type === "symlink") return {
1015
+ code: "PATCH_SYMLINK_SOURCE",
1016
+ message: `cannot ${operation.kind} "${operation.target.displayPath}": path is a symbolic link — operate on its target path instead`
1017
+ };
1018
+ }
1019
+ const state = await this.state(operation.target);
1020
+ switch (operation.kind) {
1021
+ case "add":
1022
+ await this.destination(state, operation.target);
1023
+ this.publish(operation.target, operation.content);
1024
+ return;
1025
+ case "delete":
1026
+ await this.source(state, operation.target, "delete");
1027
+ this.publish(operation.target);
1028
+ return;
1029
+ case "update":
1030
+ case "move": {
1031
+ await this.source(state, operation.target, operation.kind === "move" ? "move" : "edit");
1032
+ if (operation.kind === "move") {
1033
+ this.failurePath = operation.destination.displayPath;
1034
+ await this.destination(await this.state(operation.destination), operation.destination);
1035
+ this.failurePath = operation.target.displayPath;
1036
+ }
1037
+ const result = applyHunks(await this.content(state, operation.target), operation.hunks);
1038
+ if (!result.ok) {
1039
+ const first = result.failure.pattern.slice(0, 1).join("");
1040
+ const characters = Array.from(first);
1041
+ const preview = characters.length > 80 ? `${characters.slice(0, 80).join("")}…` : first;
1042
+ return {
1043
+ code: "FS_PATCH_MISMATCH",
1044
+ hunkLine: result.failure.hunkLineNumber,
1045
+ message: `cannot patch "${operation.target.displayPath}": hunk at patch line ${result.failure.hunkLineNumber} (${result.failure.stage}) does not match — ${preview}`
1046
+ };
1047
+ }
1048
+ if (operation.kind === "move") {
1049
+ this.publish(operation.destination, result.after);
1050
+ this.publish(operation.target);
1051
+ } else this.publish(operation.target, result.after);
1052
+ return;
1053
+ }
1054
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
1055
+ default: return assertNever(operation);
1056
+ }
1057
+ }
1058
+ };
1059
+ /**
1060
+ * Collect every independent preflight refusal while simulating only admitted operations.
1061
+ * Sandbox containment is the provider's decision at commit, as for write and edit.
1062
+ * @param ctx - filesystem service owner; reads never emit observations.
1063
+ * @param sandbox - model-facing denial mapper.
1064
+ * @param exec - observation actor and cancellation signal.
1065
+ * @param policy - resolved confinement policy used to label refusals.
1066
+ * @param operations - complete resolved operation plan.
1067
+ * @returns refused operations in patch order; any refusal forbids the commit phase.
1068
+ */
1069
+ async function preflightPatch(ctx, sandbox, exec, policy, operations) {
1070
+ const preflight = new Preflight(ctx, sandbox, exec, policy);
1071
+ const refusals = [];
1072
+ for (const operation of operations) {
1073
+ const failure = await preflight.check(operation);
1074
+ if (failure !== void 0) refusals.push({
1075
+ operation: operation.record,
1076
+ failure
1077
+ });
1078
+ }
1079
+ return refusals;
1080
+ }
1081
+ //#endregion
1082
+ //#region lib/types/patch/index.js
1083
+ /**
1084
+ * Preflight a whole patch before sequential guarded mutations; business failures become records.
1085
+ * @param ctx - mounted filesystem and observation-policy events.
1086
+ * @param sandbox - denial mapper shared with existing filesystem tools.
1087
+ * @param exec - session cwd, observation actor, and cancellation signal.
1088
+ * @param request - raw patch and policy already resolved by the caller.
1089
+ * @returns the syntax failure, the preflight refusals, or ordered commit outcomes.
1090
+ * @throws unexpected programming defects without starting further operations.
1091
+ */
1092
+ async function executePatch(ctx, sandbox, exec, request) {
1093
+ let plan;
1094
+ try {
1095
+ plan = await planPatch(ctx, sandbox, exec, request);
1096
+ } catch (error) {
1097
+ if (!(error instanceof PatchParseError)) throw error;
1098
+ return {
1099
+ phase: "syntax",
1100
+ failure: {
1101
+ code: "PATCH_SYNTAX",
1102
+ message: error.message
1103
+ }
1104
+ };
1105
+ }
1106
+ const [first, ...rest] = [...plan.refusals, ...await preflightPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations)].sort((left, right) => left.operation.index - right.operation.index);
1107
+ if (first !== void 0) return {
1108
+ phase: "preflight",
1109
+ refusals: [first, ...rest]
1110
+ };
1111
+ return commitPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations);
1112
+ }
1113
+ //#endregion
1114
+ //#region lib/types/apply-patch-output.js
1115
+ /** Canonical patch results, typed refusals, and compact model output. */
1116
+ /** Strict canonical output; full file texts feed rendering and are excluded from presentation metadata. */
1117
+ const patchOutputSchema = {
1118
+ type: "object",
1119
+ additionalProperties: false,
1120
+ properties: {
1121
+ phase: {
1122
+ type: "string",
1123
+ const: "commit",
1124
+ required: true
1125
+ },
1126
+ cancelled: {
1127
+ type: "boolean",
1128
+ required: true
1129
+ },
1130
+ operations: {
1131
+ type: "array",
1132
+ required: true,
1133
+ items: {
1134
+ type: "object",
1135
+ additionalProperties: false,
1136
+ properties: {
1137
+ index: {
1138
+ type: "integer",
1139
+ required: true
1140
+ },
1141
+ kind: {
1142
+ type: "string",
1143
+ enum: [
1144
+ "add",
1145
+ "update",
1146
+ "delete",
1147
+ "move"
1148
+ ],
1149
+ required: true
1150
+ },
1151
+ path: {
1152
+ type: "string",
1153
+ required: true
1154
+ },
1155
+ destination: { type: "string" },
1156
+ patchLine: {
1157
+ type: "integer",
1158
+ required: true
1159
+ },
1160
+ status: {
1161
+ type: "string",
1162
+ enum: [
1163
+ "completed",
1164
+ "failed",
1165
+ "unknown",
1166
+ "skipped"
1167
+ ],
1168
+ required: true
1169
+ },
1170
+ code: { type: "string" },
1171
+ message: { type: "string" },
1172
+ hunkLine: { type: "integer" },
1173
+ changes: {
1174
+ type: "array",
1175
+ items: {
1176
+ type: "object",
1177
+ additionalProperties: false,
1178
+ properties: {
1179
+ path: {
1180
+ type: "string",
1181
+ required: true
1182
+ },
1183
+ before: {
1184
+ required: true,
1185
+ oneOf: [{ type: "string" }, { type: "null" }]
1186
+ },
1187
+ after: {
1188
+ required: true,
1189
+ oneOf: [{ type: "string" }, { type: "null" }]
1190
+ }
1191
+ }
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ },
1197
+ affectedPaths: {
1198
+ type: "array",
1199
+ items: { type: "string" },
1200
+ required: true
1201
+ }
1202
+ }
1203
+ };
1204
+ /** Patch syntax and symbolic-link refusals retain their own stable codes. */
1205
+ var PatchToolError = class extends HarnessError {};
1206
+ function rejection(code, message) {
1207
+ return code === "PATCH_SYNTAX" || code === "PATCH_SYMLINK_SOURCE" ? new PatchToolError(message, code) : new FsError(message, code);
1208
+ }
1209
+ function refusalError(first, ...rest) {
1210
+ const refusals = [first, ...rest];
1211
+ const lines = refusals.map(({ operation, failure }) => `- operation ${operation.index + 1} (${operation.kind} ${operation.path}, patch line ${operation.patchLine}): ${failure.message}`);
1212
+ return rejection(first.failure.code, `Patch rejected before any change (${refusals.length} problems):\n${lines.join("\n")}`);
1213
+ }
1214
+ /**
1215
+ * Convert a report into a commit value, or reject while no disk change exists.
1216
+ * A commit whose first operation failed without any change, such as a provider sandbox
1217
+ * denial, rejects like a preflight refusal so the error code reaches the same retry paths.
1218
+ * @param report - executor report.
1219
+ * @returns a flat, lossless JSON commit value, including partial failures.
1220
+ * @throws FsError or PatchToolError for syntax, preflight, or first-operation refusals.
1221
+ */
1222
+ function patchToolValue(report) {
1223
+ if (report.phase === "syntax") throw rejection(report.failure.code, report.failure.message);
1224
+ if (report.phase === "preflight") throw refusalError(...report.refusals);
1225
+ const [first, ...rest] = report.outcomes;
1226
+ if (first?.status === "failed" && first.changes.length === 0 && rest.every((outcome) => outcome.status === "skipped")) throw refusalError(first);
1227
+ return {
1228
+ phase: "commit",
1229
+ cancelled: report.cancelled,
1230
+ affectedPaths: report.affectedPaths,
1231
+ operations: report.outcomes.map((outcome) => ({
1232
+ ...outcome.operation,
1233
+ status: outcome.status,
1234
+ ..."failure" in outcome ? outcome.failure : {},
1235
+ ..."changes" in outcome ? { changes: outcome.changes } : {}
1236
+ }))
1237
+ };
1238
+ }
1239
+ /**
1240
+ * Identify a stopped commit, including cancellation before the next operation.
1241
+ * @param value - canonical patch result.
1242
+ * @returns whether the patch did not finish every operation.
1243
+ */
1244
+ function patchStopped(value) {
1245
+ return value.cancelled || value.operations.some((operation) => operation.status !== "completed");
1246
+ }
1247
+ function completedLines(operations) {
1248
+ return [
1249
+ "add",
1250
+ "update",
1251
+ "delete"
1252
+ ].flatMap((kind) => operations.filter((operation) => operation.status === "completed" && (operation.kind === "move" ? "update" : operation.kind) === kind).map((operation) => `${kind === "add" ? "A" : kind === "delete" ? "D" : "M"} ${operation.destination ?? operation.path}`));
1253
+ }
1254
+ /**
1255
+ * Render completed paths and actionable stopped-operation diagnostics.
1256
+ * @param value - canonical patch result; paths already use the executor's display spelling.
1257
+ * @returns concise model-visible text without whole-file contents.
1258
+ */
1259
+ function renderPatch(value) {
1260
+ if (!patchStopped(value)) return value.operations.length === 0 ? "Success. No operations in patch." : ["Success. Updated the following files:", ...completedLines(value.operations)].join("\n");
1261
+ const completed = value.operations.filter((operation) => operation.status === "completed").length;
1262
+ const lines = [`Patch stopped after ${completed} of ${value.operations.length} operations.`];
1263
+ if (completed > 0) lines.push("Completed:", ...completedLines(value.operations));
1264
+ for (const [status, title] of [
1265
+ ["failed", "Failed:"],
1266
+ ["unknown", "Outcome unknown:"],
1267
+ ["skipped", "Not executed:"]
1268
+ ]) {
1269
+ const operations = value.operations.filter((operation) => operation.status === status);
1270
+ if (operations.length === 0) continue;
1271
+ lines.push(title);
1272
+ for (const operation of operations) {
1273
+ const label = `- operation ${operation.index + 1} (${operation.kind} ${operation.path}`;
1274
+ if (status === "skipped") {
1275
+ lines.push(`${label})`);
1276
+ continue;
1277
+ }
1278
+ const destination = operation.destination === void 0 ? "" : ` -> ${operation.destination}`;
1279
+ lines.push(`${label}${destination}, patch line ${operation.patchLine}): ${operation.message}`);
1280
+ if (status === "failed" && operation.kind === "move" && operation.changes?.length) lines.push(` destination ${operation.destination} was written; source ${operation.path} remains`);
1281
+ }
1282
+ }
1283
+ return lines.join("\n");
1284
+ }
1285
+ /**
1286
+ * Derive hunks only from known completed effects, including a partial move destination.
1287
+ * Creations store no diff, as for `write`; a removal without a bounded basis stores none either.
1288
+ * @param value - canonical commit value containing the provider's bounded baselines.
1289
+ * @returns serializable diff hunks and an explicit stopped flag; no whole-file change records.
1290
+ */
1291
+ function patchPresentationMeta(value) {
1292
+ return {
1293
+ diffs: value.operations.flatMap((operation) => {
1294
+ if (operation.status !== "completed" && operation.status !== "failed") return [];
1295
+ return (operation.changes ?? []).flatMap(({ path, before, after }) => {
1296
+ if (before === null) return [];
1297
+ if (after === null) return [{
1298
+ path,
1299
+ oldText: before,
1300
+ newText: ""
1301
+ }];
1302
+ return computeHunkDiffs(path, before, after);
1303
+ });
1304
+ }).map(({ path, oldText, newText }) => ({
1305
+ path,
1306
+ oldText,
1307
+ newText
1308
+ })),
1309
+ stopped: patchStopped(value)
1310
+ };
1311
+ }
1312
+ //#endregion
1313
+ //#region lib/types/apply-patch-presentation.js
1314
+ /** Pure patch call previews and known applied diff metadata for Host and Web replay. */
1315
+ /**
1316
+ * Preview the requested operations without resolving paths or reading the filesystem.
1317
+ * A deletion has no diff text to preview and appears only among the locations.
1318
+ * @param patch - raw patch argument.
1319
+ * @returns a diff call view, or undefined when syntax is invalid.
1320
+ */
1321
+ function presentPatchCall(patch) {
1322
+ let operations;
1323
+ try {
1324
+ operations = parsePatch(patch);
1325
+ } catch (error) {
1326
+ if (!(error instanceof PatchParseError)) throw error;
1327
+ return;
1328
+ }
1329
+ const diffs = operations.flatMap((operation) => {
1330
+ const path = operation.path;
1331
+ switch (operation.kind) {
1332
+ case "add": return [{
1333
+ path,
1334
+ oldText: null,
1335
+ newText: operation.content
1336
+ }];
1337
+ case "delete": return [];
1338
+ case "update": return [{
1339
+ path,
1340
+ oldText: operation.hunks.flatMap((hunk) => hunk.oldLines).join("\n") || null,
1341
+ newText: operation.hunks.flatMap((hunk) => hunk.newLines).join("\n")
1342
+ }];
1343
+ /* v8 ignore next -- Exhaustive closed parser union. */
1344
+ default: return assertNever(operation);
1345
+ }
1346
+ });
1347
+ const paths = new Set(operations.flatMap((operation) => operation.kind === "update" && operation.moveTo !== void 0 ? [operation.path, operation.moveTo] : [operation.path]));
1348
+ return {
1349
+ card: "diff",
1350
+ title: `Apply patch (${paths.size} ${paths.size === 1 ? "file" : "files"})`,
1351
+ diffs,
1352
+ locations: [...paths].map((path) => ({ path }))
1353
+ };
1354
+ }
1355
+ /**
1356
+ * Present applied metadata; failed or missing metadata uses generic result rendering.
1357
+ * @param result - live or replayed tool result.
1358
+ * @returns known applied hunks with a stopped title where appropriate.
1359
+ */
1360
+ function presentPatchResult(result) {
1361
+ if (result.isError) return void 0;
1362
+ const diffs = diffsFromMeta(result.meta);
1363
+ if (diffs === void 0) return void 0;
1364
+ return {
1365
+ card: "diff",
1366
+ title: stoppedFromMeta(result.meta) ? "Apply patch (stopped)" : "Apply patch",
1367
+ diffs
1368
+ };
1369
+ }
1370
+ //#endregion
1371
+ //#region lib/types/apply-patch.js
1372
+ /**
1373
+ * Register the patch tool and scope-aware guidance using the shared mutation controller.
1374
+ * @param ctx - plugin effect scope and filesystem services.
1375
+ * @param sandbox - per-call policy resolver and denial mapper.
1376
+ */
1377
+ function applyApplyPatchTool(ctx, sandbox) {
1378
+ ctx.systemPrompt.section({
1379
+ name: "tool:apply_patch",
1380
+ order: ctx.systemPrompt.getSectionOrder("TOOL_APPLY_PATCH"),
1381
+ text: ({ scope }) => ctx.tools.get("apply_patch", scope) === void 0 ? "" : "Prefer apply_patch over separate edit calls for changes across files or separated regions. Give every hunk enough surrounding context lines to match one place in the current file. The whole patch is checked first (syntax, hunk matching, missing files) and a rejected patch changes nothing; once applying starts, operations run in order, stop at the first failure, and are not rolled back, so re-read affected files before retrying when needed."
1382
+ });
1383
+ ctx.tools.register(defineTool({
1384
+ name: "apply_patch",
1385
+ description: "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
1386
+ parameters: {
1387
+ input: {
1388
+ type: "string",
1389
+ required: true,
1390
+ description: "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory."
1391
+ },
1392
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
1393
+ },
1394
+ output: {
1395
+ schema: patchOutputSchema,
1396
+ render: (_args, value) => [{
1397
+ type: "text",
1398
+ text: renderPatch(value)
1399
+ }],
1400
+ presentationMeta: (_args, value) => patchPresentationMeta(value)
1401
+ },
1402
+ async execute(args, exec) {
1403
+ const sandboxPolicy = await sandbox.resolvePolicy("apply_patch", args, exec);
1404
+ return patchToolValue(await executePatch(ctx, sandbox, exec, {
1405
+ patch: args.input,
1406
+ sandboxPolicy
1407
+ }));
1408
+ },
1409
+ presentCall: (args) => presentPatchCall(args.input),
1410
+ presentResult: (_args, result) => presentPatchResult(result)
1411
+ }));
1412
+ }
1413
+ //#endregion
644
1414
  //#region lib/types/edit.js
645
1415
  /**
646
1416
  * Model-facing literal edit, unique-match by default. It obtains an optional guard from the
@@ -656,9 +1426,9 @@ function applyWriteTool(ctx, sandbox) {
656
1426
  * @returns the camelCased input with `replace_all` defaulted to false.
657
1427
  */
658
1428
  function parseEditArgs(args) {
659
- if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
660
- if (args.old_string.length === 0) throw new Error("old_string must be a non-empty string");
661
- if (args.old_string === args.new_string) throw new Error("old_string and new_string must differ");
1429
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(["file_path must be a non-empty string"]);
1430
+ if (args.old_string.length === 0) throw new ToolArgsError(["old_string must be a non-empty string"]);
1431
+ if (args.old_string === args.new_string) throw new ToolArgsError(["old_string and new_string must differ"]);
662
1432
  return {
663
1433
  filePath: args.file_path,
664
1434
  oldString: args.old_string,
@@ -684,7 +1454,7 @@ function applyEditTool(ctx, sandbox) {
684
1454
  ctx.systemPrompt.section({
685
1455
  name: "tool:edit",
686
1456
  order: ctx.systemPrompt.getSectionOrder("TOOL_EDIT"),
687
- text: ({ scope }) => ctx.tools.get("edit", scope) === void 0 ? "" : "Read a file before editing it (the default fs-observation-policy requires it), unless you just created or edited it in this session."
1457
+ text: ({ scope }) => ctx.tools.get("edit", scope) === void 0 ? "" : "Read a file before editing it unless you just created or edited it in this session."
688
1458
  });
689
1459
  ctx.tools.register(defineTool({
690
1460
  name: "edit",
@@ -786,6 +1556,23 @@ function applyEditTool(ctx, sandbox) {
786
1556
  }));
787
1557
  }
788
1558
  //#endregion
1559
+ //#region lib/types/image-error.js
1560
+ /** Typed `read_image` failures. @module @unieai/rabi-tool-fs/src/image-error */
1561
+ /** Typed `read_image` failure; `code` is one of {@link IMAGE_INPUT_ERROR_CODES}. */
1562
+ var ImageInputError = class extends HarnessError$1 {
1563
+ code;
1564
+ /**
1565
+ * @param message - model-facing refusal naming the path and the safe next step.
1566
+ * @param code - stable failure code.
1567
+ * @param options - standard `cause` chaining.
1568
+ */
1569
+ constructor(message, code, options) {
1570
+ super(message, code, options);
1571
+ this.name = "ImageInputError";
1572
+ this.code = code;
1573
+ }
1574
+ };
1575
+ //#endregion
789
1576
  //#region lib/types/read-image.js
790
1577
  /**
791
1578
  * The model-facing `read_image` tool commits a PNG/JPEG/WebP/GIF file. A path
@@ -905,19 +1692,21 @@ function imageMediaTypeForPath(filePath) {
905
1692
  * @param ctx - the plugin context used to resolve the optional `llm` service.
906
1693
  * @param exec - the tool-execution context supplying the calling agent.
907
1694
  * @param requestedPath - the raw, not-yet-resolved path rendered in refusal messages.
1695
+ * @throws ToolContextUnavailableError when no Agent route or `llm` service is available.
1696
+ * @throws ImageInputError `IMAGE_UNSUPPORTED_MODEL` when the route does not declare image input.
908
1697
  */
909
1698
  async function assertImageCapableRoute(ctx, exec, requestedPath) {
910
1699
  const routed = exec.agent?.session.requestHeader()?.config;
911
1700
  const provider = routed?.provider ?? exec.agent?.options.provider;
912
1701
  const model = routed?.model ?? exec.agent?.options.model;
913
1702
  const llm = ctx.get("llm");
914
- if (provider === void 0 || model === void 0 || llm === void 0) throw new Error(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`);
1703
+ if (provider === void 0 || model === void 0 || llm === void 0) throw new ToolContextUnavailableError(`cannot read "${requestedPath}" as an image: the current model route could not be resolved`);
915
1704
  const active = await llm.resolveModelInfo(provider, model, exec.signal);
916
- if (active.inputModalities === void 0 || !active.inputModalities.includes("image")) throw new Error(`cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`);
1705
+ if (active.inputModalities === void 0 || !active.inputModalities.includes("image")) throw new ImageInputError(`cannot read "${requestedPath}" as an image: model "${model}" does not declare image input; switch to an image-capable model to read images`, "IMAGE_UNSUPPORTED_MODEL");
917
1706
  }
918
1707
  /** Refuse a media type outside the deployment's accepted set, naming the offending path. */
919
1708
  function assertDeploymentAccepts(attachments, mediaType, displayPath) {
920
- if (!attachments.imageLimits.mediaTypes.includes(mediaType)) throw new Error(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`);
1709
+ if (!attachments.imageLimits.mediaTypes.includes(mediaType)) throw new ImageInputError(`cannot read "${displayPath}": ${mediaType} images are not accepted by this deployment`, "IMAGE_UNSUPPORTED_FORMAT");
921
1710
  }
922
1711
  /**
923
1712
  * Re-brand a structured image outcome into the durable attachment reference an
@@ -973,6 +1762,46 @@ function imageReadContent(value) {
973
1762
  }];
974
1763
  }
975
1764
  /**
1765
+ * Add the read path and the next step to one `saveImage` rejection. The attachment store
1766
+ * classifies its own failures, so an `AttachmentError` keeps its `name` and `code` and only
1767
+ * gains a message naming the file and remedy, with the original as `cause`; a code without
1768
+ * a remedy, and any value that is not an `AttachmentError`, passes through unchanged.
1769
+ * @param error - the value `saveImage` rejected with.
1770
+ * @param attachments - the store whose limits the message names.
1771
+ * @param facts - the path and media-type facts the message names.
1772
+ * @returns the error to throw from the tool body.
1773
+ */
1774
+ function saveFailure(error, attachments, facts) {
1775
+ if (!(error instanceof AttachmentError)) return error;
1776
+ const detail = saveFailureDetail(error, attachments, facts);
1777
+ return detail === void 0 ? error : new AttachmentError(`cannot read "${facts.displayPath}": ${detail}`, error.code, { cause: error });
1778
+ }
1779
+ /** The model-facing remedy for one attachment rejection, or undefined when the store message stands. */
1780
+ function saveFailureDetail(error, attachments, facts) {
1781
+ const { extension, mediaType, sniffed } = facts;
1782
+ switch (error.code) {
1783
+ case "IMAGE_DIMENSION_TOO_LARGE": return `at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`;
1784
+ case "IMAGE_TOO_MANY_PIXELS": return `the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`;
1785
+ case "IMAGE_TOO_LARGE":
1786
+ case "IMAGES_TOO_LARGE": return "the image cannot be stored within the deployment's byte limits; downscale the image and read the smaller copy";
1787
+ case "UNSUPPORTED_IMAGE_TYPE": return `${mediaType} images are not accepted by this deployment`;
1788
+ case "INVALID_IMAGE": return "the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt";
1789
+ case "IMAGE_TYPE_MISMATCH": return sniffed ? `the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt` : `the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`;
1790
+ case "ATTACHMENT_WRITE_FAILED": return /16-bit PNG/iu.test(error.message) ? "the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry" : void 0;
1791
+ case "TOO_MANY_IMAGES":
1792
+ case "INVALID_IMAGE_BASE64":
1793
+ case "INVALID_FILE_BASE64":
1794
+ case "INVALID_ATTACHMENT_REF":
1795
+ case "ATTACHMENT_CORRUPT":
1796
+ case "ATTACHMENT_NOT_FOUND":
1797
+ case "ATTACHMENT_READ_FAILED":
1798
+ case "ATTACHMENT_PROJECTION_UNSUPPORTED":
1799
+ case "ATTACHMENT_FILES_UNSUPPORTED": return;
1800
+ /* v8 ignore next -- Closed AttachmentErrorCode union; assertNever checks exhaustiveness at compile time. */
1801
+ default: return assertNever(error.code);
1802
+ }
1803
+ }
1804
+ /**
976
1805
  * Register the `read_image` tool into the given context. The composing plugin
977
1806
  * owns the attachments gate: `src/index.ts` calls this inside
978
1807
  * `ctx.inject(['attachments'], …)` so the tool exists only while a durable
@@ -1008,19 +1837,19 @@ function applyReadImageTool(ctx) {
1008
1837
  },
1009
1838
  isConcurrencySafe: () => true,
1010
1839
  async execute(args, exec) {
1011
- if (args.file_path.trim().length === 0) throw new Error("file_path must be a non-empty string");
1840
+ if (args.file_path.trim().length === 0) throw new ToolArgsError(["file_path must be a non-empty string"]);
1012
1841
  const extension = extname(args.file_path).toLowerCase();
1013
1842
  const declared = imageMediaTypeForPath(args.file_path);
1014
- if (declared === void 0 && extension !== "") throw new Error(`cannot read "${args.file_path}": the ${extension} extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`);
1843
+ if (declared === void 0 && extension !== "") throw new ImageInputError(`cannot read "${args.file_path}": the ${extension} extension does not declare a supported image format; read_image accepts PNG/JPEG/WebP/GIF files, including extension-less files in those formats`, "IMAGE_UNSUPPORTED_FORMAT");
1015
1844
  const attachments = ctx.get("attachments");
1016
- if (attachments === void 0) throw new Error(`cannot read "${args.file_path}" as an image: no attachment service is mounted`);
1845
+ if (attachments === void 0) throw new ToolContextUnavailableError(`cannot read "${args.file_path}" as an image: no attachment service is mounted`);
1017
1846
  if (declared !== void 0) assertDeploymentAccepts(attachments, declared, args.file_path);
1018
1847
  await assertImageCapableRoute(ctx, exec, args.file_path);
1019
1848
  const { target, info } = await resolveRegularReadTarget(ctx, exec, args.file_path);
1020
1849
  const byteCap = Math.min(attachments.imageLimits.maxImageBytes, attachments.imageLimits.maxMessageImageBytes);
1021
1850
  const data = await ctx.fs.readBytes(target, exec.signal, byteCap);
1022
1851
  const mediaType = declared ?? sniffImageMediaType(data);
1023
- if (mediaType === void 0) throw new Error(`cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`);
1852
+ if (mediaType === void 0) throw new ImageInputError(`cannot read "${target.displayPath}": the file content is not a supported image format; read_image accepts PNG/JPEG/WebP/GIF`, "IMAGE_UNSUPPORTED_FORMAT");
1024
1853
  if (declared === void 0) assertDeploymentAccepts(attachments, mediaType, target.displayPath);
1025
1854
  let ref;
1026
1855
  try {
@@ -1030,15 +1859,12 @@ function applyReadImageTool(ctx) {
1030
1859
  name: basename(target.displayPath)
1031
1860
  });
1032
1861
  } catch (error) {
1033
- if (!(error instanceof AttachmentError)) throw error;
1034
- if (error.code === "IMAGE_DIMENSION_TOO_LARGE") throw new Error(`cannot read "${target.displayPath}": at least one image side exceeds the ${attachments.imageLimits.maxImageDimension}px limit; downscale the image and read the smaller copy`, { cause: error });
1035
- if (error.code === "IMAGE_TOO_MANY_PIXELS") throw new Error(`cannot read "${target.displayPath}": the image exceeds the ${attachments.imageLimits.maxImagePixels}-pixel decoded-size limit; downscale the image and read the smaller copy`, { cause: error });
1036
- if (error.code === "IMAGE_TOO_LARGE") throw new Error(`cannot read "${target.displayPath}": the image cannot be stored within the deployment's byte limits; downscale the image and read the smaller copy`, { cause: error });
1037
- if (error.code === "ATTACHMENT_WRITE_FAILED" && /16-bit PNG/iu.test(error.message)) throw new Error(`cannot read "${target.displayPath}": the 16-bit PNG could not be converted to the normalized 8-bit sRGB form; convert it to an 8-bit PNG/JPEG/WebP and retry`, { cause: error });
1038
- if (error.code === "INVALID_IMAGE" && declared === void 0) throw new Error(`cannot read "${target.displayPath}": the bytes do not decode as a supported PNG/JPEG/WebP/GIF image; the file may be truncated or corrupt`, { cause: error });
1039
- if (error.code !== "IMAGE_TYPE_MISMATCH") throw error;
1040
- if (declared === void 0) throw new Error(`cannot read "${target.displayPath}": the file signature claims ${mediaType}, but the bytes decode as a different image format; the file may be corrupt`, { cause: error });
1041
- throw new Error(`cannot read "${target.displayPath}": the ${extension} extension declares ${mediaType}, but the bytes use a different image format; rename the file to match its actual format if it is PNG/JPEG/WebP/GIF, or convert it to one of those formats`, { cause: error });
1862
+ throw saveFailure(error, attachments, {
1863
+ displayPath: target.displayPath,
1864
+ extension,
1865
+ mediaType,
1866
+ sniffed: declared === void 0
1867
+ });
1042
1868
  }
1043
1869
  ctx.emit("fs/observed", target, {
1044
1870
  kind: "present",
@@ -1121,10 +1947,11 @@ var FsSandboxController = class {
1121
1947
  /**
1122
1948
  * The policy to stamp onto this mutation: an approved escalation grant (a
1123
1949
  * strictly wider retry resolved through `ctx.approval` before anything
1124
- * executes), else the Session's standing mode. Repeating the standing mode
1125
- * requires no approval. The workspace root is the original Session
1126
- * directory, or the deployment fallback when absent. Validates the escalation argument
1127
- * pairing first.
1950
+ * executes), else the Session's standing mode. An omitted or repeated mode
1951
+ * permits an omitted or blank justification; repeating the mode needs no
1952
+ * approval. A different mode requires a non-empty justification, and a
1953
+ * non-empty justification without a mode is rejected. The workspace root is
1954
+ * the original Session directory, or the deployment fallback when absent.
1128
1955
  * @param toolName - the mutating tool's name, for the approval audit trail.
1129
1956
  * @param args - the call's escalation arguments.
1130
1957
  * @param exec - the tool-execution context (agent, callId, signal).
@@ -1132,10 +1959,12 @@ var FsSandboxController = class {
1132
1959
  * unsandboxed backend.
1133
1960
  */
1134
1961
  async resolvePolicy(toolName, args, exec) {
1135
- validateEscalationArgs(args.sandbox_permissions, args.justification);
1136
1962
  const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
1963
+ if (args.sandbox_permissions !== void 0 && args.sandbox_permissions === standingPolicy?.mode) return standingPolicy;
1964
+ const justification = args.sandbox_permissions === void 0 && args.justification?.trim() === "" ? void 0 : args.justification;
1965
+ validateEscalationArgs(args.sandbox_permissions, justification);
1137
1966
  if (args.sandbox_permissions === void 0 || args.justification === void 0) return standingPolicy;
1138
- if (this.escalationModes.length === 0) throw new Error("sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)");
1967
+ if (this.escalationModes.length === 0) throw new ToolArgsError(["sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)"]);
1139
1968
  const policy = standingPolicy;
1140
1969
  const approvedMode = await approveEscalation({
1141
1970
  requestedMode: args.sandbox_permissions,
@@ -1154,20 +1983,6 @@ var FsSandboxController = class {
1154
1983
  mode: approvedMode
1155
1984
  };
1156
1985
  }
1157
- /**
1158
- * Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes a
1159
- * `FsError` whose text is the shared `[sandbox: …]` denial marker plus the
1160
- * same-turn escalation hint, so a policy denial reads identically to bash's
1161
- * WHILE keeping the structured `FS_SANDBOX_DENIED` code — `ToolRuntime`
1162
- * populates `result.error` only for `HarnessError` instances, so a plain
1163
- * `Error` would strip the code retry/observers key off. Any other error
1164
- * passes through unchanged. A `FS_SANDBOX_DENIED` only arises under a
1165
- * confining backend, which always advertises the escalation fields, so the
1166
- * hint always applies here.
1167
- * @param error - the error thrown by the mutation.
1168
- * @param policy - the policy stamped onto the call (names the mode in the marker).
1169
- * @returns the error to throw — the marker `FsError` for a sandbox denial, else the original.
1170
- */
1171
1986
  mapError(error, policy) {
1172
1987
  if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED") return error;
1173
1988
  const mode = policy.mode;
@@ -1177,7 +1992,7 @@ var FsSandboxController = class {
1177
1992
  //#endregion
1178
1993
  //#region lib/types/index.js
1179
1994
  /**
1180
- * Model-facing read, read_image, write, and edit tools over `ctx.fs`. This package owns schemas, validation,
1995
+ * Model-facing read, read_image, write, edit, and apply_patch tools over `ctx.fs`. This package owns schemas, validation,
1181
1996
  * read windows, formatting, and observation events, never a concrete provider. An optional
1182
1997
  * event policy supplies mutation guards; without one the tools use unconditional provider calls.
1183
1998
  * @module @unieai/rabi-tool-fs
@@ -1196,6 +2011,7 @@ const Config = z.object({
1196
2011
  readImage: z.boolean().default(true),
1197
2012
  write: z.boolean().default(true),
1198
2013
  edit: z.boolean().default(true),
2014
+ applyPatch: z.boolean().default(false),
1199
2015
  readLimit: z.number().default(READ_LIMIT),
1200
2016
  readMaxLineLength: z.number().default(READ_MAX_LINE_LENGTH),
1201
2017
  readMaxBytes: z.number().default(READ_MAX_BYTES),
@@ -1221,10 +2037,11 @@ function apply(ctx, config) {
1221
2037
  if (resolved.readImage) ctx.inject(["attachments"], (imageCtx) => {
1222
2038
  applyReadImageTool(imageCtx);
1223
2039
  });
1224
- if (resolved.write || resolved.edit) {
2040
+ if (resolved.write || resolved.edit || resolved.applyPatch) {
1225
2041
  const sandbox = new FsSandboxController(ctx);
1226
2042
  if (resolved.write) applyWriteTool(ctx, sandbox);
1227
2043
  if (resolved.edit) applyEditTool(ctx, sandbox);
2044
+ if (resolved.applyPatch) applyApplyPatchTool(ctx, sandbox);
1228
2045
  }
1229
2046
  }
1230
2047
  //#endregion