| 1 | package builtin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | |
| 10 | "reasonix/internal/fileops" |
| 11 | "reasonix/internal/fileutil" |
| 12 | fileenc "reasonix/internal/fileutil/encoding" |
| 13 | "reasonix/internal/sandbox" |
| 14 | "reasonix/internal/tool" |
| 15 | ) |
| 16 | |
| 17 | func init() { tool.RegisterBuiltin(writeFile{}) } |
| 18 | |
| 19 | // writeFile writes a file. roots, when non-empty, confines the target to the |
| 20 | // workspace (see confine); guard rejects Reasonix session-data targets even |
| 21 | // inside the roots (see SessionDataGuard); the zero value registered at init is |
| 22 | // unconfined and is overridden per run by ConfineWriters. workDir, when |
| 23 | // non-empty, is the directory a relative path resolves against (see resolveIn). |
| 24 | type writeFile struct { |
| 25 | roots []string |
| 26 | rootSet *sandbox.WritableRootSet |
| 27 | guard SessionDataGuard |
| 28 | managed ManagedConfigPaths |
| 29 | workDir string |
| 30 | // overlay, when non-nil, routes the write through the host transport so an |
| 31 | // open editor buffer updates too. Consulted only after write confinement, |
| 32 | // and only for plain-UTF-8 targets (the overlay is text-only, so non-UTF-8 |
| 33 | // files keep the local encoding-preserving path). |
| 34 | overlay FileOverlay |
| 35 | // receipt is an optional per-runtime effect hook. hadPrior means an existing |
| 36 | // file was overwritten; prior is its previous content. |
| 37 | receipt func(path string, hadPrior bool, prior []byte) |
| 38 | } |
| 39 | |
| 40 | func (writeFile) Name() string { return "write_file" } |
| 41 | |
| 42 | func (writeFile) Description() string { |
| 43 | return "Write content to a file at the given path (overwriting existing content). Creates parent directories as needed." |
| 44 | } |
| 45 | |
| 46 | func (writeFile) Schema() json.RawMessage { |
| 47 | return json.RawMessage(`{"type":"object","properties":{"path":{"type":"string","description":"File path"},"content":{"type":"string","description":"Full content to write"}},"required":["path","content"]}`) |
| 48 | } |
| 49 | |
| 50 | func (writeFile) ReadOnly() bool { return false } |
| 51 | |
| 52 | func (w writeFile) DeclareWriteAccess(args json.RawMessage) (tool.WriteAccessDeclaration, error) { |
| 53 | return declareFilePathWriteAccess(w.workDir, args) |
| 54 | } |
| 55 | |
| 56 | func (w writeFile) Execute(ctx context.Context, args json.RawMessage) (string, error) { |
| 57 | var p struct { |
| 58 | Path string `json:"path"` |
| 59 | Content string `json:"content"` |
| 60 | } |
| 61 | if err := json.Unmarshal(args, &p); err != nil { |
| 62 | return "", fmt.Errorf("invalid args: %w", err) |
| 63 | } |
| 64 | if p.Path == "" { |
| 65 | return "", fmt.Errorf("path is required") |
| 66 | } |
| 67 | p.Path = resolveIn(w.workDir, p.Path) |
| 68 | if err := confineWrite(ctx, effectiveWriteRoots(ctx, w.rootSet, w.roots), w.guard, w.managed, p.Path); err != nil { |
| 69 | return "", err |
| 70 | } |
| 71 | unlock := lockMutationPath(p.Path) |
| 72 | defer unlock() |
| 73 | // Preserve the existing file's encoding (GBK/UTF-16/BOM) on overwrite instead |
| 74 | // of always writing UTF-8, which would silently corrupt a non-UTF-8 file. A |
| 75 | // missing file yields enc=UTF8 — the right default for a new one. Reading via |
| 76 | // the overlay makes the no-op check see the same buffer Preview does. |
| 77 | src, rerr := readEditSource(ctx, w.overlay, p.Path) |
| 78 | if rerr != nil && !os.IsNotExist(rerr) { |
| 79 | return "", rerr |
| 80 | } |
| 81 | if rerr != nil && fileops.FromContext(ctx).Get(fileops.DiskTarget(p.Path, nil)).Kind == fileops.Present { |
| 82 | return "", &tool.OperationError{Diagnostic: tool.OperationDiagnostic{Code: tool.FSStaleVersion, Path: p.Path, Recovery: "the observed file was removed; read its current state before creating it again"}, Cause: ErrFileChanged} |
| 83 | } |
| 84 | if rerr == nil { |
| 85 | if err := src.requireObserved(ctx, w.overlay, p.Path); err != nil { |
| 86 | return "", err |
| 87 | } |
| 88 | if src.content == p.Content { |
| 89 | return fmt.Sprintf("%s already contains the exact content; no changes made", p.Path), nil |
| 90 | } |
| 91 | } |
| 92 | if err := src.assertUnchanged(ctx, w.overlay, p.Path); err != nil { |
| 93 | return "", err |
| 94 | } |
| 95 | // The host overlay applies the write to the editor buffer and the file in |
| 96 | // one step. Text-only, so it handles plain UTF-8 targets (and new files); |
| 97 | // non-UTF-8 files stay on the local encoding-preserving path below. |
| 98 | if w.overlay != nil && filepath.IsAbs(p.Path) && (rerr != nil || src.overlay) { |
| 99 | if err := src.recordWrite(ctx, p.Path, p.Content, "overlay", w.overlay); err != nil { |
| 100 | return "", err |
| 101 | } |
| 102 | if err := src.assertUnchanged(ctx, w.overlay, p.Path); err != nil { |
| 103 | return "", err |
| 104 | } |
| 105 | if ok, werr := w.overlay.WriteTextFile(ctx, p.Path, p.Content); ok { |
| 106 | if werr != nil { |
| 107 | fileops.FromContext(ctx).Forget(overlayObservationTarget(w.overlay, p.Path)) |
| 108 | return "", fmt.Errorf("write outcome unknown: %w", werr) |
| 109 | } |
| 110 | if w.receipt != nil { |
| 111 | w.receipt(p.Path, rerr == nil, []byte(src.content)) |
| 112 | } |
| 113 | fileops.FromContext(ctx).ObservePresent(overlayObservationTarget(w.overlay, p.Path), fileops.OverlayVersion(p.Content)) |
| 114 | return fmt.Sprintf("wrote %d bytes to %s", len(p.Content), p.Path), nil |
| 115 | } |
| 116 | if src.overlay { |
| 117 | fileops.FromContext(ctx).Forget(overlayObservationTarget(w.overlay, p.Path)) |
| 118 | return "", fmt.Errorf("write outcome unknown: original overlay did not confirm the write") |
| 119 | } |
| 120 | // A new target rejected before entry by the transport stays a local create. |
| 121 | } |
| 122 | if err := src.recordWrite(ctx, p.Path, p.Content, "disk", w.overlay); err != nil { |
| 123 | return "", err |
| 124 | } |
| 125 | if err := src.assertUnchanged(ctx, w.overlay, p.Path); err != nil { |
| 126 | return "", err |
| 127 | } |
| 128 | hadPrior := rerr == nil |
| 129 | var prior []byte |
| 130 | if hadPrior { |
| 131 | prior = []byte(src.content) |
| 132 | } |
| 133 | var writeErr error |
| 134 | if rerr != nil { |
| 135 | writeErr = createFileEncoded(p.Path, p.Content, src.enc) |
| 136 | } else { |
| 137 | writeErr = writeFileEncoded(p.Path, p.Content, src.enc) |
| 138 | } |
| 139 | if writeErr != nil { |
| 140 | if os.IsExist(writeErr) { |
| 141 | return "", &tool.OperationError{Diagnostic: tool.OperationDiagnostic{Code: tool.FSAlreadyExists, Path: p.Path, Recovery: "the file was created concurrently; read it before deciding whether to replace it"}, Cause: writeErr} |
| 142 | } |
| 143 | return "", fmt.Errorf("write %s: %w", p.Path, writeErr) |
| 144 | } |
| 145 | src.commitObservation(ctx, w.overlay, p.Path, p.Content) |
| 146 | if w.receipt != nil { |
| 147 | w.receipt(p.Path, hadPrior, prior) |
| 148 | } |
| 149 | return fmt.Sprintf("wrote %d bytes to %s", len(p.Content), p.Path), nil |
| 150 | } |
| 151 | |
| 152 | func createFileEncoded(path, content string, enc fileenc.Kind) error { |
| 153 | return fileutil.AtomicCreateFile(path, fileenc.Encode(content, enc), 0o644) |
| 154 | } |
| 155 | |
| 156 | // BindFileWriteReceipt returns t with a per-runtime write receipt callback when |
| 157 | // t is write_file. Other tools are returned unchanged. |
| 158 | func BindFileWriteReceipt(t tool.Tool, receipt func(path string, hadPrior bool, prior []byte)) tool.Tool { |
| 159 | w, ok := t.(writeFile) |
| 160 | if !ok { |
| 161 | return t |
| 162 | } |
| 163 | w.receipt = receipt |
| 164 | return w |
| 165 | } |
| 166 |