dsh-better-edit 0.1.1 → 0.1.3

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/tool-undo.js CHANGED
@@ -15,6 +15,8 @@ import { getUndo, clearUndo } from "./undo-edit.js";
15
15
  import { recordServedTruncated } from "./served-store.js";
16
16
  import { UNDO_DESCRIPTION } from "./prompts.js";
17
17
  import { execCwd, execSessionKey } from "./dsh-context.js";
18
+ import { FsSandboxController } from "./sandbox.js";
19
+ import { withWorkspace } from "./workspace.js";
18
20
  function assertUndoReq(request) {
19
21
  if (!isRec(request)) {
20
22
  throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
@@ -31,7 +33,7 @@ function assertUndoReq(request) {
31
33
  * @param io - the filesystem bridge.
32
34
  * @returns the exact disposer that unregisters the tool.
33
35
  */
34
- export function buildUndoTool(io) {
36
+ export function buildUndoTool(io, sandbox) {
35
37
  return defineTool({
36
38
  name: "undo_last_edit",
37
39
  description: UNDO_DESCRIPTION,
@@ -41,72 +43,81 @@ export function buildUndoTool(io) {
41
43
  required: true,
42
44
  description: "Path to the file to undo",
43
45
  },
46
+ ...(sandbox.escalationModes.length > 0 ? sandbox.schemaFields() : {}),
44
47
  },
45
48
  output: {
46
49
  schema: { type: "string" },
47
50
  render: (_args, value) => [{ type: "text", text: value }],
48
51
  },
49
52
  async execute(args, exec) {
50
- const cwd = execCwd(exec);
51
- const sessionKey = execSessionKey(exec);
52
- const signal = exec.signal;
53
- const canonical = normReq(args);
54
- assertUndoReq(canonical);
55
- const path = canonical.path;
56
- const absolutePath = await io.resolve(path, cwd, signal);
57
- const undo = await getUndo(absolutePath);
58
- if (!undo) {
59
- return `No undo history for ${path}. There is no previous edit to revert.`;
60
- }
61
- let currentRaw;
62
- try {
63
- currentRaw = await io.readText(absolutePath, signal);
64
- }
65
- catch (error) {
66
- const message = error instanceof Error ? error.message : String(error);
67
- if (message.includes("[E_NOT_FOUND]")) {
53
+ return withWorkspace(execCwd(exec), async () => {
54
+ const cwd = execCwd(exec);
55
+ const sessionKey = execSessionKey(exec);
56
+ const signal = exec.signal;
57
+ const canonical = normReq(args);
58
+ assertUndoReq(canonical);
59
+ const path = canonical.path;
60
+ const absolutePath = await io.resolve(path, cwd, signal);
61
+ const sandboxPolicy = await sandbox.resolvePolicy("undo_last_edit", canonical, exec);
62
+ const undo = await getUndo(absolutePath);
63
+ if (!undo) {
64
+ return `No undo history for ${path}. There is no previous edit to revert.`;
65
+ }
66
+ let currentRaw;
67
+ try {
68
+ currentRaw = await io.readText(absolutePath, signal);
69
+ }
70
+ catch (error) {
71
+ const message = error instanceof Error ? error.message : String(error);
72
+ if (message.includes("[E_NOT_FOUND]")) {
73
+ await clearUndo(absolutePath);
74
+ return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
75
+ }
76
+ throw error;
77
+ }
78
+ if (currentRaw !==
79
+ undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
68
80
  await clearUndo(absolutePath);
69
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
81
+ return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file was modified after the edit, so undoing would overwrite those changes. Call read() to inspect the current state.`;
82
+ }
83
+ const { text: currentStripped } = stripBOM(currentRaw);
84
+ const currentNormalized = toLF(currentStripped);
85
+ const currentHashes = await lineHashes(currentNormalized, absolutePath);
86
+ const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
87
+ const linesAddedByEdit = cntDiff(diffResult.diff, "+");
88
+ const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
89
+ const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
90
+ const undoDiff = undoDiffResult.diff;
91
+ const restoredRange = changedRange(currentNormalized, undo.content);
92
+ try {
93
+ await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec, sandboxPolicy);
94
+ }
95
+ catch (error) {
96
+ throw sandbox.mapError(error, sandboxPolicy);
97
+ }
98
+ try {
99
+ await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
100
+ }
101
+ catch (error) {
102
+ console.error("Failed to restore hash store snapshot after undo:", error);
70
103
  }
71
- throw error;
72
- }
73
- if (currentRaw !==
74
- undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
75
104
  await clearUndo(absolutePath);
76
- return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file was modified after the edit, so undoing would overwrite those changes. Call read() to inspect the current state.`;
77
- }
78
- const { text: currentStripped } = stripBOM(currentRaw);
79
- const currentNormalized = toLF(currentStripped);
80
- const currentHashes = await lineHashes(currentNormalized, absolutePath);
81
- const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
82
- const linesAddedByEdit = cntDiff(diffResult.diff, "+");
83
- const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
84
- const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
85
- const undoDiff = undoDiffResult.diff;
86
- const restoredRange = changedRange(currentNormalized, undo.content);
87
- await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec);
88
- try {
89
- await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
90
- }
91
- catch (error) {
92
- console.error("Failed to restore hash store snapshot after undo:", error);
93
- }
94
- await clearUndo(absolutePath);
95
- const parts = [`Undone last edit on ${path}.`];
96
- if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
97
- parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
98
- }
99
- parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
100
- if (undoDiffResult.servedRows.length > 0) {
101
- await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
102
- }
103
- return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
105
+ const parts = [`Undone last edit on ${path}.`];
106
+ if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
107
+ parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
108
+ }
109
+ parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
110
+ if (undoDiffResult.servedRows.length > 0) {
111
+ await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
112
+ }
113
+ return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
114
+ });
104
115
  },
105
116
  });
106
117
  }
107
118
  /**
108
119
  * Register the hashline tool on the calling agent’s scope (own layer).
109
120
  */
110
- export function registerUndoTool(_rootCtx, agentCtx, io) {
111
- return agentCtx.tools.register(buildUndoTool(io));
121
+ export function registerUndoTool(_rootCtx, agentCtx, io, sandbox) {
122
+ return agentCtx.tools.register(buildUndoTool(io, sandbox));
112
123
  }
@@ -17,6 +17,7 @@
17
17
  import type { Context } from "@deepseek-ai/cordis";
18
18
  import type { FileSystem } from "@deepseek-ai/dsh-fs";
19
19
  import type { ToolExecution } from "@deepseek-ai/dsh-tools";
20
+ import type { SandboxExecutionPolicy } from "@deepseek-ai/dsh-sandbox";
20
21
  /** Text-IO operations the hashline tools need, keyed by canonical absolute path. */
21
22
  export interface FileIO {
22
23
  /** Resolve a (possibly relative) request path against the session cwd to a canonical absolute path. */
@@ -25,12 +26,16 @@ export interface FileIO {
25
26
  readText(absolutePath: string, signal?: AbortSignal): Promise<string>;
26
27
  /**
27
28
  * Atomically write whole text, preserving mode when the file exists. On the
28
- * dsh backend this dispatches `fs/write-intent` (policy guard) and emits
29
+ * dsh backend this dispatches `fs/write-intent` (policy guard), stamps the
30
+ * sandbox policy (session workspace root + mode) onto the write, and emits
29
31
  * `fs/observed` with the new version on success, so later built-in tools
30
32
  * see a fresh observation.
31
33
  * @param exec - the calling execution; carries the session the policy keys by.
34
+ * @param sandboxPolicy - the per-call sandbox mode + workspace root the
35
+ * confined backend checks (resolved from the session by the tool layer);
36
+ * omitted on an unsandboxed backend.
32
37
  */
33
- writeText(absolutePath: string, content: string, signal?: AbortSignal, exec?: ToolExecution): Promise<void>;
38
+ writeText(absolutePath: string, content: string, signal?: AbortSignal, exec?: ToolExecution, sandboxPolicy?: SandboxExecutionPolicy): Promise<void>;
34
39
  /**
35
40
  * Emit `fs/observed` (present at the current version) for a successful
36
41
  * read, so the policy records that this session has seen the file.
@@ -22,8 +22,20 @@ export interface HashStore {
22
22
  readonly engine: "node:sqlite";
23
23
  }
24
24
  export declare function isCorruptionError(error: unknown): boolean;
25
- export declare function loadHashStore(): Promise<HashStore>;
25
+ /**
26
+ * Load (and cache) the hash store for the given cwd — or, when omitted, the
27
+ * workspace active for this async execution (`withWorkspace`), falling back to
28
+ * the shared `$DSH_HOME` store outside a tool call.
29
+ * @param cwd - optional explicit workspace root; defaults to the active workspace.
30
+ */
31
+ export declare function loadHashStore(cwd?: string): Promise<HashStore>;
32
+ /** Close every open store (process exit, HMR, tests). */
26
33
  export declare function shutdownHashStore(): void;
34
+ /**
35
+ * Run `fn` inside one BEGIN IMMEDIATE transaction on the active workspace's
36
+ * store. Without an open store for this context the call runs bare (the
37
+ * caller has already loaded the store in every in-process path).
38
+ */
27
39
  export declare function withStore(fn: () => void): void;
28
40
  export { getSnapshot, upsertSnapshot, findSnapshotPaths, pruneMissing, isValidHashList, isValidSnapshot, } from "./snapshot-store.js";
29
41
  export type { LegacySnapshot } from "./snapshot-store.js";
@@ -11,7 +11,7 @@
11
11
  * preview to write results.
12
12
  * @module dsh-better-edit
13
13
  */
14
- import type { Context } from '@deepseek-ai/cordis';
14
+ import type { Context } from "@deepseek-ai/cordis";
15
15
  /** Cordis plugin name used by loader diagnostics. */
16
16
  export declare const name = "dsh-better-edit";
17
17
  /**
@@ -1,11 +1,15 @@
1
1
  /**
2
- * On-disk home for dsh-better-edit state, under the DeepSeek Harness home
3
- * ($DSH_HOME, defaulting to ~/.dsh). The hashline hash snapshots, served-state
4
- * rows, and undo history live under a plugin-owned subdirectory so multiple
5
- * dsh installs on one machine share one coherent store keyed by absolute path.
2
+ * On-disk home for dsh-better-edit state. Inside a tool call the store lives
3
+ * co-located with the files being edited: `<workspace>/.dsh_better_edit/` (the
4
+ * workspace is the session cwd, carried through the execution by
5
+ * `withWorkspace`). Outside a tool call — tests, previews, startup — the store
6
+ * falls back to the shared DeepSeek Harness home
7
+ * (`$DSH_HOME/plugins/dsh-better-edit`, default `~/.dsh/plugins/dsh-better-edit`),
8
+ * so a caller without a workspace never writes into an arbitrary cwd.
9
+ * @param cwd - the workspace root, or undefined for the shared-home fallback.
6
10
  */
7
- export declare function configDir(): string;
8
- export declare function hashStorePath(): string;
9
- export declare function legacyHashStorePath(): string;
10
- export declare function hashStoreDir(): string;
11
+ export declare function configDir(cwd?: string): string;
12
+ export declare function hashStorePath(cwd?: string): string;
13
+ export declare function legacyHashStorePath(cwd?: string): string;
14
+ export declare function hashStoreDir(cwd?: string): string;
11
15
  export declare function toCwd(filePath: string, cwd: string): string;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The sandbox-escalation API for the hashline mutating tools, mirroring
3
+ * `@deepseek-ai/dsh-tool-fs`'s `FsSandboxController` (same vocabulary, same
4
+ * fail-closed approval sequence, shared `@deepseek-ai/dsh-sandbox` pieces) so
5
+ * `edit`/`batch_edit`/`undo_last_edit` escalate exactly like the built-in
6
+ * `write`/`edit` — and, critically, stamp the per-call policy with the SESSION
7
+ * workspace root. Without the policy the sandbox backend falls back to the
8
+ * deployment default root, so an edit inside the session workspace is denied
9
+ * under `workspace-write` even though the built-in `write` succeeds there.
10
+ * @module dsh-better-edit/sandbox
11
+ */
12
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import type { ToolExecution } from '@deepseek-ai/dsh-tools';
14
+ import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox';
15
+ /** The two escalation arguments a mutating tool may carry (advertised only under a confining backend). */
16
+ export interface FsEscalationArgs {
17
+ sandbox_permissions?: string;
18
+ justification?: string;
19
+ }
20
+ /** The schema fields for the escalation arguments, spread into a tool's `parameters` when a confining backend is mounted. */
21
+ export interface EscalationSchemaFields {
22
+ sandbox_permissions: {
23
+ type: 'string';
24
+ enum: string[];
25
+ description: string;
26
+ };
27
+ justification: {
28
+ type: 'string';
29
+ description: string;
30
+ };
31
+ }
32
+ /**
33
+ * The filesystem escalation API: advertisement gating, per-call policy
34
+ * resolution, the one-approved wider retry, and denial-marker mapping. A pure
35
+ * product of `ctx` at plugin apply time.
36
+ */
37
+ export declare class FsSandboxController {
38
+ private readonly ctx;
39
+ /** The escalation targets this composition advertises (`[]` when no confining backend is mounted). */
40
+ readonly escalationModes: readonly SandboxMode[];
41
+ /** Shared per-session policy resolver, required by a confining backend. */
42
+ private readonly policy;
43
+ constructor(ctx: Context);
44
+ /**
45
+ * The escalation schema fields for a mutating tool's `parameters`. Call it
46
+ * only under a confining backend (guard on {@link escalationModes}); the
47
+ * enum pins the closed target vocabulary, the strict-wider check happens
48
+ * per call at execution.
49
+ */
50
+ schemaFields(): EscalationSchemaFields;
51
+ /**
52
+ * The policy to stamp onto this mutation: an approved escalation grant (a
53
+ * strictly wider retry resolved through `ctx.approval` before anything
54
+ * executes), else the session's standing mode. The calling session's cwd is
55
+ * always carried as the workspace root, so `workspace-write` allows writes
56
+ * inside the session workspace.
57
+ * @param toolName - the mutating tool's name, for the approval audit trail.
58
+ * @param args - the call's escalation arguments.
59
+ * @param exec - the tool-execution context (agent, callId, signal).
60
+ * @returns the policy to pass to the mutation, or undefined for an
61
+ * unsandboxed backend.
62
+ */
63
+ resolvePolicy(toolName: string, args: FsEscalationArgs, exec: ToolExecution): Promise<SandboxExecutionPolicy | undefined>;
64
+ /**
65
+ * Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes
66
+ * the shared `[sandbox: …]` denial marker plus the same-turn escalation
67
+ * hint, keeping the structured code. Any other error passes through.
68
+ */
69
+ mapError(error: unknown, policy: SandboxExecutionPolicy | undefined): unknown;
70
+ }
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { Context } from "@deepseek-ai/cordis";
9
9
  import type { FileIO } from "./fs-bridge.js";
10
+ import type { FsSandboxController } from "./sandbox.js";
10
11
  /**
11
12
  * Register the `batch_edit` tool on the calling agent's scope.
12
13
  * @param _rootCtx - host context.
@@ -14,8 +15,8 @@ import type { FileIO } from "./fs-bridge.js";
14
15
  * @param io - the filesystem bridge.
15
16
  * @returns the exact disposer that unregisters the tool.
16
17
  */
17
- export declare function buildBatchEditTool(io: FileIO): import("@deepseek-ai/dsh-tools").ToolDefinition;
18
+ export declare function buildBatchEditTool(io: FileIO, sandbox: FsSandboxController): import("@deepseek-ai/dsh-tools").ToolDefinition;
18
19
  /**
19
20
  * Register the hashline tool on the calling agent’s scope (own layer).
20
21
  */
21
- export declare function registerBatchEditTool(_rootCtx: Context, agentCtx: Context, io: FileIO): () => void;
22
+ export declare function registerBatchEditTool(_rootCtx: Context, agentCtx: Context, io: FileIO, sandbox: FsSandboxController): () => void;
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { Context } from "@deepseek-ai/cordis";
9
9
  import type { FileIO } from "./fs-bridge.js";
10
+ import type { FsSandboxController } from "./sandbox.js";
10
11
  /**
11
12
  * Register the hash-anchored `edit` tool on the calling agent's scope.
12
13
  * @param _rootCtx - host context (logger, lifecycle).
@@ -15,8 +16,8 @@ import type { FileIO } from "./fs-bridge.js";
15
16
  * @param io - the filesystem bridge (ctx.fs backed in deployment).
16
17
  * @returns the exact disposer that unregisters the tool.
17
18
  */
18
- export declare function buildEditTool(io: FileIO): import("@deepseek-ai/dsh-tools").ToolDefinition;
19
+ export declare function buildEditTool(io: FileIO, sandbox: FsSandboxController): import("@deepseek-ai/dsh-tools").ToolDefinition;
19
20
  /**
20
21
  * Register the hashline tool on the calling agent’s scope (own layer).
21
22
  */
22
- export declare function registerEditTool(_rootCtx: Context, agentCtx: Context, io: FileIO): () => void;
23
+ export declare function registerEditTool(_rootCtx: Context, agentCtx: Context, io: FileIO, sandbox: FsSandboxController): () => void;
@@ -6,6 +6,7 @@
6
6
  */
7
7
  import type { Context } from "@deepseek-ai/cordis";
8
8
  import type { FileIO } from "./fs-bridge.js";
9
+ import { FsSandboxController } from "./sandbox.js";
9
10
  /**
10
11
  * Register the `undo_last_edit` tool on the calling agent's scope.
11
12
  * @param _rootCtx - host context.
@@ -13,8 +14,8 @@ import type { FileIO } from "./fs-bridge.js";
13
14
  * @param io - the filesystem bridge.
14
15
  * @returns the exact disposer that unregisters the tool.
15
16
  */
16
- export declare function buildUndoTool(io: FileIO): import("@deepseek-ai/dsh-tools").ToolDefinition;
17
+ export declare function buildUndoTool(io: FileIO, sandbox: FsSandboxController): import("@deepseek-ai/dsh-tools").ToolDefinition;
17
18
  /**
18
19
  * Register the hashline tool on the calling agent’s scope (own layer).
19
20
  */
20
- export declare function registerUndoTool(_rootCtx: Context, agentCtx: Context, io: FileIO): () => void;
21
+ export declare function registerUndoTool(_rootCtx: Context, agentCtx: Context, io: FileIO, sandbox: FsSandboxController): () => void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Per-call workspace context. dsh serves several sessions in one process, each
3
+ * with its own cwd, and only the tool execution knows which one it belongs to —
4
+ * so a module-global "current cwd" would race between parallel sessions. The
5
+ * store path is derived per tool call from the session cwd; this module carries
6
+ * that cwd through the async execution so every store access inside the call
7
+ * (served rows, undo, hash snapshots) lands in the right per-workspace store.
8
+ * @module dsh-better-edit/workspace
9
+ */
10
+ /**
11
+ * Run `fn` with the given workspace cwd active for this async execution.
12
+ * Every `loadHashStore()` (and any store access) inside `fn` resolves the
13
+ * `<cwd>/.dsh_better_edit` store.
14
+ * @param cwd - the session workspace root (absolute).
15
+ * @param fn - the tool body.
16
+ * @returns the body's result.
17
+ */
18
+ export declare function withWorkspace<T>(cwd: string, fn: () => Promise<T>): Promise<T>;
19
+ /**
20
+ * The workspace cwd active for this async execution, or undefined outside a
21
+ * tool call (tests, previews, startup) — callers fall back to the shared
22
+ * `$DSH_HOME` store then.
23
+ */
24
+ export declare function workspaceCwd(): string | undefined;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Per-call workspace context. dsh serves several sessions in one process, each
3
+ * with its own cwd, and only the tool execution knows which one it belongs to —
4
+ * so a module-global "current cwd" would race between parallel sessions. The
5
+ * store path is derived per tool call from the session cwd; this module carries
6
+ * that cwd through the async execution so every store access inside the call
7
+ * (served rows, undo, hash snapshots) lands in the right per-workspace store.
8
+ * @module dsh-better-edit/workspace
9
+ */
10
+ import { AsyncLocalStorage } from 'node:async_hooks';
11
+ const current = new AsyncLocalStorage();
12
+ /**
13
+ * Run `fn` with the given workspace cwd active for this async execution.
14
+ * Every `loadHashStore()` (and any store access) inside `fn` resolves the
15
+ * `<cwd>/.dsh_better_edit` store.
16
+ * @param cwd - the session workspace root (absolute).
17
+ * @param fn - the tool body.
18
+ * @returns the body's result.
19
+ */
20
+ export function withWorkspace(cwd, fn) {
21
+ return current.run(cwd, fn);
22
+ }
23
+ /**
24
+ * The workspace cwd active for this async execution, or undefined outside a
25
+ * tool call (tests, previews, startup) — callers fall back to the shared
26
+ * `$DSH_HOME` store then.
27
+ */
28
+ export function workspaceCwd() {
29
+ return current.getStore();
30
+ }
package/lib/write-hook.js CHANGED
@@ -9,6 +9,7 @@ import { normFromText } from './file-reader.js';
9
9
  import { fmtReadPreview, MAX_HASH_LINES } from './read-render.js';
10
10
  import { recordServed, clearDriftReported } from './served-store.js';
11
11
  import { execCwd, execSessionKey } from './dsh-context.js';
12
+ import { withWorkspace } from './workspace.js';
12
13
  const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
13
14
  /**
14
15
  * Register the post-write auto-read listener on the calling agent's scope.
@@ -23,50 +24,54 @@ const AUTO_READ_HEADING = '--- Auto-read (hashline anchors) ---';
23
24
  */
24
25
  export function registerWriteHook(rootCtx, agentCtx, io) {
25
26
  return agentCtx.on('tools/post-execute', async (exec, result, next) => {
26
- const decision = await next();
27
- if (exec.name !== 'write' ||
28
- result.isError ||
29
- decision.kind !== 'accept') {
30
- return decision;
31
- }
32
- const decisionContent = decision.content ?? result.content;
33
- const rawPath = exec.arguments
34
- ?.file_path ?? exec.arguments
35
- ?.path;
36
- if (typeof rawPath !== 'string')
37
- return decision;
38
- try {
39
- const cwd = execCwd(exec);
40
- const sessionKey = execSessionKey(exec);
41
- const signal = exec.signal;
42
- const absolutePath = await io.resolve(rawPath, cwd, signal);
43
- const rawText = await io.readText(absolutePath, signal);
44
- const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
45
- absolutePath,
46
- rawText,
47
- displayPath: rawPath,
48
- signal,
49
- maxLines: MAX_HASH_LINES,
27
+ return withWorkspace(execCwd(exec), async () => {
28
+ return withWorkspace(execCwd(exec), async () => {
29
+ const decision = await next();
30
+ if (exec.name !== 'write' ||
31
+ result.isError ||
32
+ decision.kind !== 'accept') {
33
+ return decision;
34
+ }
35
+ const decisionContent = decision.content ?? result.content;
36
+ const rawPath = exec.arguments
37
+ ?.file_path ?? exec.arguments
38
+ ?.path;
39
+ if (typeof rawPath !== 'string')
40
+ return decision;
41
+ try {
42
+ const cwd = execCwd(exec);
43
+ const sessionKey = execSessionKey(exec);
44
+ const signal = exec.signal;
45
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
46
+ const rawText = await io.readText(absolutePath, signal);
47
+ const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
48
+ absolutePath,
49
+ rawText,
50
+ displayPath: rawPath,
51
+ signal,
52
+ maxLines: MAX_HASH_LINES,
53
+ });
54
+ const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
55
+ if (preview.served.length > 0) {
56
+ await recordServed(sessionKey, absolutePath, preview.served);
57
+ }
58
+ await clearDriftReported(sessionKey, absolutePath);
59
+ const text = hadUtf8DecodeErrors
60
+ ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
61
+ : preview.text;
62
+ return {
63
+ kind: 'accept',
64
+ content: [
65
+ ...(decisionContent),
66
+ { type: 'text', text: `\n\n${AUTO_READ_HEADING}\n${text}` },
67
+ ],
68
+ };
69
+ }
70
+ catch (error) {
71
+ rootCtx.logger.warn(`dsh-better-edit: auto-read after write failed: ${error instanceof Error ? error.message : String(error)}`);
72
+ return decision;
73
+ }
50
74
  });
51
- const preview = await fmtReadPreview(normalized, {}, fileHashes, absolutePath);
52
- if (preview.served.length > 0) {
53
- await recordServed(sessionKey, absolutePath, preview.served);
54
- }
55
- await clearDriftReported(sessionKey, absolutePath);
56
- const text = hadUtf8DecodeErrors
57
- ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
58
- : preview.text;
59
- return {
60
- kind: 'accept',
61
- content: [
62
- ...(decisionContent),
63
- { type: 'text', text: `\n\n${AUTO_READ_HEADING}\n${text}` },
64
- ],
65
- };
66
- }
67
- catch (error) {
68
- rootCtx.logger.warn(`dsh-better-edit: auto-read after write failed: ${error instanceof Error ? error.message : String(error)}`);
69
- return decision;
70
- }
75
+ });
71
76
  });
72
77
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-better-edit",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "type": "module",
5
5
  "description": "Hash-anchored read/edit/batch_edit/undo_last_edit tools for DeepSeek Harness (dsh). Every line gets a unique 3-char hash (A-Za-z0-9) that stays stable across edits; stale or ambiguous anchors are rejected, never fuzzy-matched. Undo persists across restarts.",
6
6
  "main": "lib/index.js",
@@ -52,7 +52,8 @@
52
52
  "dependencies": {
53
53
  "diff": "^8.0.2",
54
54
  "file-type": "^21.3.0",
55
- "xxhash-wasm": "^1.1.0"
55
+ "xxhash-wasm": "^1.1.0",
56
+ "@deepseek-ai/dsh-sandbox": "^0.1.0-rc.6"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "@deepseek-ai/cordis": "^4.0.0",