@deepseek-ai/dsh-tool-fs 0.2.2-alpha.2 → 0.2.2-rc.1

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.
package/lib/index.js CHANGED
@@ -3,6 +3,9 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import { FsError } from "@deepseek-ai/dsh-fs";
4
4
  import { readLangHintForPath as langFromPath } from "@deepseek-ai/dsh-util-code-language";
5
5
  import { structuredPatch } from "diff";
6
+ import { PatchParseError, applyHunks, parsePatch } from "@deepseek-ai/dsh-fs-patch";
7
+ import { assertNever } from "@deepseek-ai/dsh-util-values";
8
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
6
9
  import { basename, extname } from "node:path";
7
10
  import { AttachmentError, AttachmentId } from "@deepseek-ai/dsh-attachment";
8
11
  import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
@@ -444,6 +447,14 @@ function diffsFromMeta(meta) {
444
447
  return diffs;
445
448
  }
446
449
  /**
450
+ * Narrow the patch tool's optional stopped flag from persisted metadata.
451
+ * @param meta - opaque live or replayed result metadata.
452
+ * @returns true only for an explicit stopped flag.
453
+ */
454
+ function stoppedFromMeta(meta) {
455
+ return typeof meta === "object" && meta !== null && !Array.isArray(meta) && meta.stopped === true;
456
+ }
457
+ /**
447
458
  * Read the operation's file path even when the applied diff is empty.
448
459
  * @param meta - opaque persisted result metadata.
449
460
  * @returns the recorded path, or undefined for old or malformed metadata.
@@ -461,17 +472,6 @@ function pathFromMeta(meta) {
461
472
  * stable message shown to the model.
462
473
  * @module @deepseek-ai/dsh-tool-fs/src/error
463
474
  */
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
475
  function remediateFsError(error, displayPath) {
476
476
  if (!(error instanceof FsError)) return error;
477
477
  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 });
@@ -543,7 +543,7 @@ function applyWriteTool(ctx, sandbox) {
543
543
  ctx.systemPrompt.section({
544
544
  name: "tool:write",
545
545
  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") + "."
546
+ 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
547
  });
548
548
  ctx.tools.register(defineTool({
549
549
  name: "write",
@@ -641,6 +641,775 @@ function applyWriteTool(ctx, sandbox) {
641
641
  }));
642
642
  }
643
643
  //#endregion
644
+ //#region lib/types/patch/plan.js
645
+ /**
646
+ * Resolve every operation without dropping repeated aliases or splitting moves.
647
+ * @param ctx - filesystem service owner.
648
+ * @param sandbox - filesystem diagnostic mapper.
649
+ * @param exec - session cwd and execution signal.
650
+ * @param request - raw patch and resolved per-call policy.
651
+ * @returns resolved operations sharing one target per canonical key, plus resolution refusals.
652
+ */
653
+ async function planPatch(ctx, sandbox, exec, request) {
654
+ const parsed = parsePatch(request.patch);
655
+ const targets = /* @__PURE__ */ new Map();
656
+ const resolve = async (path) => {
657
+ const target = await ctx.fs.resolve(path, await sessionResolveOptions(ctx, exec));
658
+ const prior = targets.get(target.targetKey);
659
+ if (prior) return prior;
660
+ targets.set(target.targetKey, target);
661
+ return target;
662
+ };
663
+ const result = {
664
+ operations: [],
665
+ refusals: []
666
+ };
667
+ for (const [index, operation] of parsed.entries()) {
668
+ const moveTo = operation.kind === "update" ? operation.moveTo : void 0;
669
+ const record = {
670
+ index,
671
+ kind: moveTo === void 0 ? operation.kind : "move",
672
+ path: operation.path,
673
+ patchLine: operation.lineNumber,
674
+ ...moveTo === void 0 ? {} : { destination: moveTo }
675
+ };
676
+ let failurePath = operation.path;
677
+ try {
678
+ const target = await resolve(operation.path);
679
+ record.path = target.displayPath;
680
+ const base = {
681
+ target,
682
+ rawPath: operation.path,
683
+ record
684
+ };
685
+ switch (operation.kind) {
686
+ case "add":
687
+ result.operations.push({
688
+ ...base,
689
+ kind: "add",
690
+ content: operation.content
691
+ });
692
+ break;
693
+ case "delete":
694
+ result.operations.push({
695
+ ...base,
696
+ kind: "delete"
697
+ });
698
+ break;
699
+ case "update":
700
+ if (operation.moveTo === void 0) result.operations.push({
701
+ ...base,
702
+ kind: "update",
703
+ hunks: operation.hunks
704
+ });
705
+ else {
706
+ failurePath = operation.moveTo;
707
+ const destination = await resolve(operation.moveTo);
708
+ record.destination = destination.displayPath;
709
+ result.operations.push({
710
+ ...base,
711
+ kind: "move",
712
+ destination,
713
+ hunks: operation.hunks
714
+ });
715
+ }
716
+ break;
717
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
718
+ default: assertNever(operation);
719
+ }
720
+ } catch (error) {
721
+ if (!(error instanceof FsError)) throw error;
722
+ result.refusals.push({
723
+ operation: record,
724
+ failure: patchFailure(sandbox, request.sandboxPolicy, error, failurePath)
725
+ });
726
+ }
727
+ }
728
+ return result;
729
+ }
730
+ /**
731
+ * Obtain a source guard without recording an observation.
732
+ * @param ctx - intent dispatcher.
733
+ * @param exec - opaque observation actor.
734
+ * @param target - resolved source.
735
+ * @param kind - deletion or edit-family source policy.
736
+ * @returns the observed version, or undefined for a bare provider.
737
+ */
738
+ function sourceIntent(ctx, exec, target, kind) {
739
+ return kind === "delete" ? ctx.waterfall("fs/delete-intent", target, exec, () => void 0) : ctx.waterfall("fs/edit-intent", target, exec, () => void 0);
740
+ }
741
+ /**
742
+ * Obtain a write guard without recording an observation.
743
+ * @param ctx - intent dispatcher.
744
+ * @param exec - opaque observation actor.
745
+ * @param target - resolved write destination.
746
+ * @returns the observed write intent, or undefined for a bare provider.
747
+ */
748
+ function destinationIntent(ctx, exec, target) {
749
+ return ctx.waterfall("fs/write-intent", target, exec, () => void 0);
750
+ }
751
+ /**
752
+ * Preserve filesystem codes while applying the existing model-facing error policy.
753
+ * @param sandbox - shared denial mapper.
754
+ * @param policy - policy supplied by the request.
755
+ * @param error - expected filesystem failure.
756
+ * @param path - display path whose operation failed.
757
+ * @returns the remediated code and message; unexpected mapper defects reject.
758
+ */
759
+ function patchFailure(sandbox, policy, error, path) {
760
+ const mapped = remediateFsError(sandbox.mapError(error, policy), path);
761
+ return {
762
+ code: mapped.code,
763
+ message: mapped.message
764
+ };
765
+ }
766
+ /**
767
+ * List all targets the operation can mutate, with destination first for a move.
768
+ * @param operation - resolved operation.
769
+ * @returns targets whose versions the uncertainty comparison records.
770
+ */
771
+ function mutationTargets(operation) {
772
+ return operation.kind === "move" ? [operation.destination, operation.target] : [operation.target];
773
+ }
774
+ //#endregion
775
+ //#region lib/types/patch/execute.js
776
+ async function unchanged(ctx, before) {
777
+ try {
778
+ for (const entry of before) if ((await ctx.fs.stat(entry.target))?.version !== entry.info?.version) return false;
779
+ return true;
780
+ } catch (error) {
781
+ if (!(error instanceof FsError)) throw error;
782
+ return false;
783
+ }
784
+ }
785
+ /**
786
+ * Commit a fully admitted plan; the first failure stops later operations without rollback.
787
+ * @param ctx - provider and observation dispatcher.
788
+ * @param sandbox - existing model-facing denial mapper.
789
+ * @param exec - session actor and cancellation signal.
790
+ * @param policy - request's resolved confinement policy.
791
+ * @param operations - operations that all passed preflight.
792
+ * @returns known changes, failed or unknown effects, and skipped successors in patch order.
793
+ */
794
+ async function commitPatch(ctx, sandbox, exec, policy, operations) {
795
+ const outcomes = operations.map((operation) => ({
796
+ status: "skipped",
797
+ operation: operation.record
798
+ }));
799
+ let cancelled = false;
800
+ for (const [index, operation] of operations.entries()) {
801
+ if (exec.signal.aborted) {
802
+ cancelled = true;
803
+ break;
804
+ }
805
+ let started = false;
806
+ let before = [];
807
+ let failurePath = operation.target.displayPath;
808
+ const target = operation.target;
809
+ const record = operation.record;
810
+ let outcome;
811
+ try {
812
+ before = await Promise.all(mutationTargets(operation).map(async (target) => ({
813
+ target,
814
+ info: await ctx.fs.stat(target, exec.signal)
815
+ })));
816
+ switch (operation.kind) {
817
+ case "add": {
818
+ const intent = await destinationIntent(ctx, exec, target);
819
+ started = true;
820
+ const result = await ctx.fs.writeText(target, operation.content, intent, exec.signal, policy);
821
+ ctx.emit("fs/observed", target, {
822
+ kind: "present",
823
+ version: result.version
824
+ }, exec);
825
+ outcome = {
826
+ status: "completed",
827
+ operation: record,
828
+ changes: [{
829
+ path: ctx.fs.processPath(target),
830
+ before: result.before,
831
+ after: result.after
832
+ }]
833
+ };
834
+ break;
835
+ }
836
+ case "update": {
837
+ const intent = await sourceIntent(ctx, exec, target, "edit");
838
+ started = true;
839
+ const result = await ctx.fs.patchText(target, operation.hunks, intent, exec.signal, policy);
840
+ ctx.emit("fs/observed", target, {
841
+ kind: "present",
842
+ version: result.version
843
+ }, exec);
844
+ outcome = {
845
+ status: "completed",
846
+ operation: record,
847
+ changes: [{
848
+ path: ctx.fs.processPath(target),
849
+ before: result.before,
850
+ after: result.after
851
+ }]
852
+ };
853
+ break;
854
+ }
855
+ case "delete": {
856
+ const intent = await sourceIntent(ctx, exec, target, "delete");
857
+ started = true;
858
+ const result = await ctx.fs.deleteFile(target, intent, exec.signal, policy);
859
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
860
+ outcome = {
861
+ status: "completed",
862
+ operation: record,
863
+ changes: [{
864
+ path: ctx.fs.processPath(target),
865
+ before: result.before,
866
+ after: null
867
+ }]
868
+ };
869
+ break;
870
+ }
871
+ case "move": {
872
+ const expectedSource = await sourceIntent(ctx, exec, target, "edit");
873
+ failurePath = operation.destination.displayPath;
874
+ const expectedDestination = await destinationIntent(ctx, exec, operation.destination);
875
+ started = true;
876
+ const result = await ctx.fs.moveFile(target, operation.destination, {
877
+ hunks: operation.hunks,
878
+ ...expectedSource === void 0 ? {} : { expectedSource },
879
+ ...expectedDestination === void 0 ? {} : { expectedDestination }
880
+ }, exec.signal, policy);
881
+ const changes = [{
882
+ path: ctx.fs.processPath(operation.destination),
883
+ before: result.destination.before,
884
+ after: result.destination.after
885
+ }];
886
+ ctx.emit("fs/observed", operation.destination, {
887
+ kind: "present",
888
+ version: result.destination.version
889
+ }, exec);
890
+ if (result.sourceDeleted) {
891
+ ctx.emit("fs/observed", target, { kind: "absent" }, exec);
892
+ outcome = {
893
+ status: "completed",
894
+ operation: record,
895
+ changes: [...changes, {
896
+ path: ctx.fs.processPath(target),
897
+ before: result.sourceBefore,
898
+ after: null
899
+ }]
900
+ };
901
+ } else outcome = {
902
+ status: "failed",
903
+ operation: record,
904
+ failure: patchFailure(sandbox, policy, new FsError(result.sourceFailure.message, result.sourceFailure.code), target.displayPath),
905
+ changes
906
+ };
907
+ break;
908
+ }
909
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
910
+ default: assertNever(operation);
911
+ }
912
+ } catch (error) {
913
+ if (!(error instanceof FsError)) throw error;
914
+ const failure = patchFailure(sandbox, policy, error, failurePath);
915
+ outcome = started && (error.code === "FS_ABORTED" || error.code === "FS_IO_ERROR" && !await unchanged(ctx, before)) ? {
916
+ status: "unknown",
917
+ operation: record,
918
+ failure: {
919
+ ...failure,
920
+ message: `${failure.message} — re-read the affected files before retrying`
921
+ }
922
+ } : {
923
+ status: "failed",
924
+ operation: record,
925
+ failure,
926
+ changes: []
927
+ };
928
+ }
929
+ outcomes[index] = outcome;
930
+ if (outcome.status !== "completed") {
931
+ cancelled = exec.signal.aborted;
932
+ break;
933
+ }
934
+ }
935
+ return {
936
+ phase: "commit",
937
+ outcomes,
938
+ affectedPaths: [...new Set(outcomes.flatMap((outcome) => "changes" in outcome ? outcome.changes.map((change) => change.path) : []))],
939
+ cancelled
940
+ };
941
+ }
942
+ //#endregion
943
+ //#region lib/types/patch/preflight.js
944
+ var Preflight = class {
945
+ ctx;
946
+ sandbox;
947
+ exec;
948
+ policy;
949
+ failurePath = "";
950
+ states = /* @__PURE__ */ new Map();
951
+ constructor(ctx, sandbox, exec, policy) {
952
+ this.ctx = ctx;
953
+ this.sandbox = sandbox;
954
+ this.exec = exec;
955
+ this.policy = policy;
956
+ }
957
+ async state(target) {
958
+ const known = this.states.get(target.targetKey);
959
+ if (known) return known;
960
+ const info = await this.ctx.fs.stat(target, this.exec.signal);
961
+ const state = {
962
+ exists: info !== void 0,
963
+ info,
964
+ touched: false
965
+ };
966
+ this.states.set(target.targetKey, state);
967
+ return state;
968
+ }
969
+ regular(state, target) {
970
+ if (state.info !== void 0 && state.info.type !== "file") throw new FsError(`cannot modify "${target.displayPath}": not a regular file`, "FS_NOT_REGULAR_FILE");
971
+ }
972
+ async source(state, target, kind) {
973
+ const intent = state.touched ? void 0 : await sourceIntent(this.ctx, this.exec, target, kind === "delete" ? "delete" : "edit");
974
+ if (!state.exists) throw new FsError(`cannot ${kind} "${target.displayPath}": not found`, "FS_NOT_FOUND");
975
+ this.regular(state, target);
976
+ 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");
977
+ }
978
+ async destination(state, target) {
979
+ const intent = state.touched ? void 0 : await destinationIntent(this.ctx, this.exec, target);
980
+ this.regular(state, target);
981
+ if (intent?.kind === "createIfAbsent" && state.exists) throw new FsError(`cannot overwrite existing "${target.displayPath}" without reading it first`, "FS_NOT_OBSERVED");
982
+ 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");
983
+ }
984
+ async content(state, target) {
985
+ if (state.content === void 0) {
986
+ const text = await this.ctx.fs.readText(target, this.exec.signal);
987
+ if (text.includes("\0")) throw new FsError(`cannot patch "${target.displayPath}": binary file`, "FS_NOT_TEXT");
988
+ state.content = text.replace(/\r\n/g, "\n");
989
+ }
990
+ return state.content;
991
+ }
992
+ publish(target, content) {
993
+ this.states.set(target.targetKey, {
994
+ exists: content !== void 0,
995
+ info: void 0,
996
+ touched: true,
997
+ ...content === void 0 ? {} : { content }
998
+ });
999
+ }
1000
+ /** Simulate one operation; a filesystem refusal becomes the operation's failure. */
1001
+ async check(operation) {
1002
+ this.failurePath = operation.target.displayPath;
1003
+ try {
1004
+ return await this.simulate(operation);
1005
+ } catch (error) {
1006
+ if (!(error instanceof FsError)) throw error;
1007
+ return patchFailure(this.sandbox, this.policy, error, this.failurePath);
1008
+ }
1009
+ }
1010
+ async simulate(operation) {
1011
+ if (operation.kind === "move" && operation.target.targetKey === operation.destination.targetKey) throw new FsError(`cannot move "${operation.target.displayPath}" to itself`, "FS_SAME_TARGET");
1012
+ if (operation.kind === "delete" || operation.kind === "move") {
1013
+ if ((await this.ctx.fs.lstat(operation.rawPath, await sessionResolveOptions(this.ctx, this.exec)))?.type === "symlink") return {
1014
+ code: "PATCH_SYMLINK_SOURCE",
1015
+ message: `cannot ${operation.kind} "${operation.target.displayPath}": path is a symbolic link — operate on its target path instead`
1016
+ };
1017
+ }
1018
+ const state = await this.state(operation.target);
1019
+ switch (operation.kind) {
1020
+ case "add":
1021
+ await this.destination(state, operation.target);
1022
+ this.publish(operation.target, operation.content);
1023
+ return;
1024
+ case "delete":
1025
+ await this.source(state, operation.target, "delete");
1026
+ this.publish(operation.target);
1027
+ return;
1028
+ case "update":
1029
+ case "move": {
1030
+ await this.source(state, operation.target, operation.kind === "move" ? "move" : "edit");
1031
+ if (operation.kind === "move") {
1032
+ this.failurePath = operation.destination.displayPath;
1033
+ await this.destination(await this.state(operation.destination), operation.destination);
1034
+ this.failurePath = operation.target.displayPath;
1035
+ }
1036
+ const result = applyHunks(await this.content(state, operation.target), operation.hunks);
1037
+ if (!result.ok) {
1038
+ const first = result.failure.pattern.slice(0, 1).join("");
1039
+ const characters = Array.from(first);
1040
+ const preview = characters.length > 80 ? `${characters.slice(0, 80).join("")}…` : first;
1041
+ return {
1042
+ code: "FS_PATCH_MISMATCH",
1043
+ hunkLine: result.failure.hunkLineNumber,
1044
+ message: `cannot patch "${operation.target.displayPath}": hunk at patch line ${result.failure.hunkLineNumber} (${result.failure.stage}) does not match — ${preview}`
1045
+ };
1046
+ }
1047
+ if (operation.kind === "move") {
1048
+ this.publish(operation.destination, result.after);
1049
+ this.publish(operation.target);
1050
+ } else this.publish(operation.target, result.after);
1051
+ return;
1052
+ }
1053
+ /* v8 ignore next -- Closed parsed-operation union; assertNever checks exhaustiveness at compile time. */
1054
+ default: return assertNever(operation);
1055
+ }
1056
+ }
1057
+ };
1058
+ /**
1059
+ * Collect every independent preflight refusal while simulating only admitted operations.
1060
+ * Sandbox containment is the provider's decision at commit, as for write and edit.
1061
+ * @param ctx - filesystem service owner; reads never emit observations.
1062
+ * @param sandbox - model-facing denial mapper.
1063
+ * @param exec - observation actor and cancellation signal.
1064
+ * @param policy - resolved confinement policy used to label refusals.
1065
+ * @param operations - complete resolved operation plan.
1066
+ * @returns refused operations in patch order; any refusal forbids the commit phase.
1067
+ */
1068
+ async function preflightPatch(ctx, sandbox, exec, policy, operations) {
1069
+ const preflight = new Preflight(ctx, sandbox, exec, policy);
1070
+ const refusals = [];
1071
+ for (const operation of operations) {
1072
+ const failure = await preflight.check(operation);
1073
+ if (failure !== void 0) refusals.push({
1074
+ operation: operation.record,
1075
+ failure
1076
+ });
1077
+ }
1078
+ return refusals;
1079
+ }
1080
+ //#endregion
1081
+ //#region lib/types/patch/index.js
1082
+ /**
1083
+ * Preflight a whole patch before sequential guarded mutations; business failures become records.
1084
+ * @param ctx - mounted filesystem and observation-policy events.
1085
+ * @param sandbox - denial mapper shared with existing filesystem tools.
1086
+ * @param exec - session cwd, observation actor, and cancellation signal.
1087
+ * @param request - raw patch and policy already resolved by the caller.
1088
+ * @returns the syntax failure, the preflight refusals, or ordered commit outcomes.
1089
+ * @throws unexpected programming defects without starting further operations.
1090
+ */
1091
+ async function executePatch(ctx, sandbox, exec, request) {
1092
+ let plan;
1093
+ try {
1094
+ plan = await planPatch(ctx, sandbox, exec, request);
1095
+ } catch (error) {
1096
+ if (!(error instanceof PatchParseError)) throw error;
1097
+ return {
1098
+ phase: "syntax",
1099
+ failure: {
1100
+ code: "PATCH_SYNTAX",
1101
+ message: error.message
1102
+ }
1103
+ };
1104
+ }
1105
+ const [first, ...rest] = [...plan.refusals, ...await preflightPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations)].sort((left, right) => left.operation.index - right.operation.index);
1106
+ if (first !== void 0) return {
1107
+ phase: "preflight",
1108
+ refusals: [first, ...rest]
1109
+ };
1110
+ return commitPatch(ctx, sandbox, exec, request.sandboxPolicy, plan.operations);
1111
+ }
1112
+ //#endregion
1113
+ //#region lib/types/apply-patch-output.js
1114
+ /** Canonical patch results, typed refusals, and compact model output. */
1115
+ /** Strict canonical output; full file texts feed rendering and are excluded from presentation metadata. */
1116
+ const patchOutputSchema = {
1117
+ type: "object",
1118
+ additionalProperties: false,
1119
+ properties: {
1120
+ phase: {
1121
+ type: "string",
1122
+ const: "commit",
1123
+ required: true
1124
+ },
1125
+ cancelled: {
1126
+ type: "boolean",
1127
+ required: true
1128
+ },
1129
+ operations: {
1130
+ type: "array",
1131
+ required: true,
1132
+ items: {
1133
+ type: "object",
1134
+ additionalProperties: false,
1135
+ properties: {
1136
+ index: {
1137
+ type: "integer",
1138
+ required: true
1139
+ },
1140
+ kind: {
1141
+ type: "string",
1142
+ enum: [
1143
+ "add",
1144
+ "update",
1145
+ "delete",
1146
+ "move"
1147
+ ],
1148
+ required: true
1149
+ },
1150
+ path: {
1151
+ type: "string",
1152
+ required: true
1153
+ },
1154
+ destination: { type: "string" },
1155
+ patchLine: {
1156
+ type: "integer",
1157
+ required: true
1158
+ },
1159
+ status: {
1160
+ type: "string",
1161
+ enum: [
1162
+ "completed",
1163
+ "failed",
1164
+ "unknown",
1165
+ "skipped"
1166
+ ],
1167
+ required: true
1168
+ },
1169
+ code: { type: "string" },
1170
+ message: { type: "string" },
1171
+ hunkLine: { type: "integer" },
1172
+ changes: {
1173
+ type: "array",
1174
+ items: {
1175
+ type: "object",
1176
+ additionalProperties: false,
1177
+ properties: {
1178
+ path: {
1179
+ type: "string",
1180
+ required: true
1181
+ },
1182
+ before: {
1183
+ required: true,
1184
+ oneOf: [{ type: "string" }, { type: "null" }]
1185
+ },
1186
+ after: {
1187
+ required: true,
1188
+ oneOf: [{ type: "string" }, { type: "null" }]
1189
+ }
1190
+ }
1191
+ }
1192
+ }
1193
+ }
1194
+ }
1195
+ },
1196
+ affectedPaths: {
1197
+ type: "array",
1198
+ items: { type: "string" },
1199
+ required: true
1200
+ }
1201
+ }
1202
+ };
1203
+ /** Patch syntax and symbolic-link refusals retain their own stable codes. */
1204
+ var PatchToolError = class extends HarnessError {};
1205
+ function rejection(code, message) {
1206
+ return code === "PATCH_SYNTAX" || code === "PATCH_SYMLINK_SOURCE" ? new PatchToolError(message, code) : new FsError(message, code);
1207
+ }
1208
+ function refusalError(first, ...rest) {
1209
+ const refusals = [first, ...rest];
1210
+ const lines = refusals.map(({ operation, failure }) => `- operation ${operation.index + 1} (${operation.kind} ${operation.path}, patch line ${operation.patchLine}): ${failure.message}`);
1211
+ return rejection(first.failure.code, `Patch rejected before any change (${refusals.length} problems):\n${lines.join("\n")}`);
1212
+ }
1213
+ /**
1214
+ * Convert a report into a commit value, or reject while no disk change exists.
1215
+ * A commit whose first operation failed without any change, such as a provider sandbox
1216
+ * denial, rejects like a preflight refusal so the error code reaches the same retry paths.
1217
+ * @param report - executor report.
1218
+ * @returns a flat, lossless JSON commit value, including partial failures.
1219
+ * @throws FsError or PatchToolError for syntax, preflight, or first-operation refusals.
1220
+ */
1221
+ function patchToolValue(report) {
1222
+ if (report.phase === "syntax") throw rejection(report.failure.code, report.failure.message);
1223
+ if (report.phase === "preflight") throw refusalError(...report.refusals);
1224
+ const [first, ...rest] = report.outcomes;
1225
+ if (first?.status === "failed" && first.changes.length === 0 && rest.every((outcome) => outcome.status === "skipped")) throw refusalError(first);
1226
+ return {
1227
+ phase: "commit",
1228
+ cancelled: report.cancelled,
1229
+ affectedPaths: report.affectedPaths,
1230
+ operations: report.outcomes.map((outcome) => ({
1231
+ ...outcome.operation,
1232
+ status: outcome.status,
1233
+ ..."failure" in outcome ? outcome.failure : {},
1234
+ ..."changes" in outcome ? { changes: outcome.changes } : {}
1235
+ }))
1236
+ };
1237
+ }
1238
+ /**
1239
+ * Identify a stopped commit, including cancellation before the next operation.
1240
+ * @param value - canonical patch result.
1241
+ * @returns whether the patch did not finish every operation.
1242
+ */
1243
+ function patchStopped(value) {
1244
+ return value.cancelled || value.operations.some((operation) => operation.status !== "completed");
1245
+ }
1246
+ function completedLines(operations) {
1247
+ return [
1248
+ "add",
1249
+ "update",
1250
+ "delete"
1251
+ ].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}`));
1252
+ }
1253
+ /**
1254
+ * Render completed paths and actionable stopped-operation diagnostics.
1255
+ * @param value - canonical patch result; paths already use the executor's display spelling.
1256
+ * @returns concise model-visible text without whole-file contents.
1257
+ */
1258
+ function renderPatch(value) {
1259
+ if (!patchStopped(value)) return value.operations.length === 0 ? "Success. No operations in patch." : ["Success. Updated the following files:", ...completedLines(value.operations)].join("\n");
1260
+ const completed = value.operations.filter((operation) => operation.status === "completed").length;
1261
+ const lines = [`Patch stopped after ${completed} of ${value.operations.length} operations.`];
1262
+ if (completed > 0) lines.push("Completed:", ...completedLines(value.operations));
1263
+ for (const [status, title] of [
1264
+ ["failed", "Failed:"],
1265
+ ["unknown", "Outcome unknown:"],
1266
+ ["skipped", "Not executed:"]
1267
+ ]) {
1268
+ const operations = value.operations.filter((operation) => operation.status === status);
1269
+ if (operations.length === 0) continue;
1270
+ lines.push(title);
1271
+ for (const operation of operations) {
1272
+ const label = `- operation ${operation.index + 1} (${operation.kind} ${operation.path}`;
1273
+ if (status === "skipped") {
1274
+ lines.push(`${label})`);
1275
+ continue;
1276
+ }
1277
+ const destination = operation.destination === void 0 ? "" : ` -> ${operation.destination}`;
1278
+ lines.push(`${label}${destination}, patch line ${operation.patchLine}): ${operation.message}`);
1279
+ if (status === "failed" && operation.kind === "move" && operation.changes?.length) lines.push(` destination ${operation.destination} was written; source ${operation.path} remains`);
1280
+ }
1281
+ }
1282
+ return lines.join("\n");
1283
+ }
1284
+ /**
1285
+ * Derive hunks only from known completed effects, including a partial move destination.
1286
+ * Creations store no diff, as for `write`; a removal without a bounded basis stores none either.
1287
+ * @param value - canonical commit value containing the provider's bounded baselines.
1288
+ * @returns serializable diff hunks and an explicit stopped flag; no whole-file change records.
1289
+ */
1290
+ function patchPresentationMeta(value) {
1291
+ return {
1292
+ diffs: value.operations.flatMap((operation) => {
1293
+ if (operation.status !== "completed" && operation.status !== "failed") return [];
1294
+ return (operation.changes ?? []).flatMap(({ path, before, after }) => {
1295
+ if (before === null) return [];
1296
+ if (after === null) return [{
1297
+ path,
1298
+ oldText: before,
1299
+ newText: ""
1300
+ }];
1301
+ return computeHunkDiffs(path, before, after);
1302
+ });
1303
+ }).map(({ path, oldText, newText }) => ({
1304
+ path,
1305
+ oldText,
1306
+ newText
1307
+ })),
1308
+ stopped: patchStopped(value)
1309
+ };
1310
+ }
1311
+ //#endregion
1312
+ //#region lib/types/apply-patch-presentation.js
1313
+ /** Pure patch call previews and known applied diff metadata for Host and Web replay. */
1314
+ /**
1315
+ * Preview the requested operations without resolving paths or reading the filesystem.
1316
+ * A deletion has no diff text to preview and appears only among the locations.
1317
+ * @param patch - raw patch argument.
1318
+ * @returns a diff call view, or undefined when syntax is invalid.
1319
+ */
1320
+ function presentPatchCall(patch) {
1321
+ let operations;
1322
+ try {
1323
+ operations = parsePatch(patch);
1324
+ } catch (error) {
1325
+ if (!(error instanceof PatchParseError)) throw error;
1326
+ return;
1327
+ }
1328
+ const diffs = operations.flatMap((operation) => {
1329
+ const path = operation.path;
1330
+ switch (operation.kind) {
1331
+ case "add": return [{
1332
+ path,
1333
+ oldText: null,
1334
+ newText: operation.content
1335
+ }];
1336
+ case "delete": return [];
1337
+ case "update": return [{
1338
+ path,
1339
+ oldText: operation.hunks.flatMap((hunk) => hunk.oldLines).join("\n") || null,
1340
+ newText: operation.hunks.flatMap((hunk) => hunk.newLines).join("\n")
1341
+ }];
1342
+ /* v8 ignore next -- Exhaustive closed parser union. */
1343
+ default: return assertNever(operation);
1344
+ }
1345
+ });
1346
+ const paths = new Set(operations.flatMap((operation) => operation.kind === "update" && operation.moveTo !== void 0 ? [operation.path, operation.moveTo] : [operation.path]));
1347
+ return {
1348
+ card: "diff",
1349
+ title: `Apply patch (${paths.size} ${paths.size === 1 ? "file" : "files"})`,
1350
+ diffs,
1351
+ locations: [...paths].map((path) => ({ path }))
1352
+ };
1353
+ }
1354
+ /**
1355
+ * Present applied metadata; failed or missing metadata uses generic result rendering.
1356
+ * @param result - live or replayed tool result.
1357
+ * @returns known applied hunks with a stopped title where appropriate.
1358
+ */
1359
+ function presentPatchResult(result) {
1360
+ if (result.isError) return void 0;
1361
+ const diffs = diffsFromMeta(result.meta);
1362
+ if (diffs === void 0) return void 0;
1363
+ return {
1364
+ card: "diff",
1365
+ title: stoppedFromMeta(result.meta) ? "Apply patch (stopped)" : "Apply patch",
1366
+ diffs
1367
+ };
1368
+ }
1369
+ //#endregion
1370
+ //#region lib/types/apply-patch.js
1371
+ /**
1372
+ * Register the patch tool and scope-aware guidance using the shared mutation controller.
1373
+ * @param ctx - plugin effect scope and filesystem services.
1374
+ * @param sandbox - per-call policy resolver and denial mapper.
1375
+ */
1376
+ function applyApplyPatchTool(ctx, sandbox) {
1377
+ ctx.systemPrompt.section({
1378
+ name: "tool:apply_patch",
1379
+ order: ctx.systemPrompt.getSectionOrder("TOOL_APPLY_PATCH"),
1380
+ 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."
1381
+ });
1382
+ ctx.tools.register(defineTool({
1383
+ name: "apply_patch",
1384
+ description: "Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions.",
1385
+ parameters: {
1386
+ input: {
1387
+ type: "string",
1388
+ required: true,
1389
+ description: "Codex 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."
1390
+ },
1391
+ ...sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}
1392
+ },
1393
+ output: {
1394
+ schema: patchOutputSchema,
1395
+ render: (_args, value) => [{
1396
+ type: "text",
1397
+ text: renderPatch(value)
1398
+ }],
1399
+ presentationMeta: (_args, value) => patchPresentationMeta(value)
1400
+ },
1401
+ async execute(args, exec) {
1402
+ const sandboxPolicy = await sandbox.resolvePolicy("apply_patch", args, exec);
1403
+ return patchToolValue(await executePatch(ctx, sandbox, exec, {
1404
+ patch: args.input,
1405
+ sandboxPolicy
1406
+ }));
1407
+ },
1408
+ presentCall: (args) => presentPatchCall(args.input),
1409
+ presentResult: (_args, result) => presentPatchResult(result)
1410
+ }));
1411
+ }
1412
+ //#endregion
644
1413
  //#region lib/types/edit.js
645
1414
  /**
646
1415
  * Model-facing literal edit, unique-match by default. It obtains an optional guard from the
@@ -684,7 +1453,7 @@ function applyEditTool(ctx, sandbox) {
684
1453
  ctx.systemPrompt.section({
685
1454
  name: "tool:edit",
686
1455
  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."
1456
+ 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
1457
  });
689
1458
  ctx.tools.register(defineTool({
690
1459
  name: "edit",
@@ -1157,20 +1926,6 @@ var FsSandboxController = class {
1157
1926
  mode: approvedMode
1158
1927
  };
1159
1928
  }
1160
- /**
1161
- * Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes a
1162
- * `FsError` whose text is the shared `[sandbox: …]` denial marker plus the
1163
- * same-turn escalation hint, so a policy denial reads identically to bash's
1164
- * WHILE keeping the structured `FS_SANDBOX_DENIED` code — `ToolRuntime`
1165
- * populates `result.error` only for `HarnessError` instances, so a plain
1166
- * `Error` would strip the code retry/observers key off. Any other error
1167
- * passes through unchanged. A `FS_SANDBOX_DENIED` only arises under a
1168
- * confining backend, which always advertises the escalation fields, so the
1169
- * hint always applies here.
1170
- * @param error - the error thrown by the mutation.
1171
- * @param policy - the policy stamped onto the call (names the mode in the marker).
1172
- * @returns the error to throw — the marker `FsError` for a sandbox denial, else the original.
1173
- */
1174
1929
  mapError(error, policy) {
1175
1930
  if (!(error instanceof FsError) || error.code !== "FS_SANDBOX_DENIED") return error;
1176
1931
  const mode = policy.mode;
@@ -1180,7 +1935,7 @@ var FsSandboxController = class {
1180
1935
  //#endregion
1181
1936
  //#region lib/types/index.js
1182
1937
  /**
1183
- * Model-facing read, read_image, write, and edit tools over `ctx.fs`. This package owns schemas, validation,
1938
+ * Model-facing read, read_image, write, edit, and apply_patch tools over `ctx.fs`. This package owns schemas, validation,
1184
1939
  * read windows, formatting, and observation events, never a concrete provider. An optional
1185
1940
  * event policy supplies mutation guards; without one the tools use unconditional provider calls.
1186
1941
  * @module @deepseek-ai/dsh-tool-fs
@@ -1199,6 +1954,7 @@ const Config = z.object({
1199
1954
  readImage: z.boolean().default(true),
1200
1955
  write: z.boolean().default(true),
1201
1956
  edit: z.boolean().default(true),
1957
+ applyPatch: z.boolean().default(false),
1202
1958
  readLimit: z.number().default(READ_LIMIT),
1203
1959
  readMaxLineLength: z.number().default(READ_MAX_LINE_LENGTH),
1204
1960
  readMaxBytes: z.number().default(READ_MAX_BYTES),
@@ -1224,10 +1980,11 @@ function apply(ctx, config) {
1224
1980
  if (resolved.readImage) ctx.inject(["attachments"], (imageCtx) => {
1225
1981
  applyReadImageTool(imageCtx);
1226
1982
  });
1227
- if (resolved.write || resolved.edit) {
1983
+ if (resolved.write || resolved.edit || resolved.applyPatch) {
1228
1984
  const sandbox = new FsSandboxController(ctx);
1229
1985
  if (resolved.write) applyWriteTool(ctx, sandbox);
1230
1986
  if (resolved.edit) applyEditTool(ctx, sandbox);
1987
+ if (resolved.applyPatch) applyApplyPatchTool(ctx, sandbox);
1231
1988
  }
1232
1989
  }
1233
1990
  //#endregion