dsh-better-edit 0.1.0 → 0.1.2

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-read.js CHANGED
@@ -5,22 +5,23 @@
5
5
  * shown the lines it targets.
6
6
  * @module dsh-better-edit/tool-read
7
7
  */
8
- import { defineTool } from '@deepseek-ai/dsh-tools';
9
- import { normReq } from './edit-normalize.js';
10
- import { abortIf, isRec, rejectUnknownFields } from './utils.js';
11
- import { normFromText } from './file-reader.js';
12
- import { fmtReadPreview, MAX_HASH_LINES } from './read-render.js';
13
- import { recordServed, clearDriftReported } from './served-store.js';
14
- import { READ_DESCRIPTION } from './prompts.js';
15
- import { pathSchema } from './schema.js';
16
- import { execCwd, execSessionKey } from './dsh-context.js';
17
- const ROOT_KS = new Set(['path', 'offset', 'limit']);
8
+ import { defineTool } from "@deepseek-ai/dsh-tools";
9
+ import { normReq } from "./edit-normalize.js";
10
+ import { abortIf, isRec, rejectUnknownFields } from "./utils.js";
11
+ import { normFromText } from "./file-reader.js";
12
+ import { fmtReadPreview, MAX_HASH_LINES } from "./read-render.js";
13
+ import { recordServed, clearDriftReported } from "./served-store.js";
14
+ import { READ_DESCRIPTION } from "./prompts.js";
15
+ import { pathSchema } from "./schema.js";
16
+ import { execCwd, execSessionKey } from "./dsh-context.js";
17
+ import { withWorkspace } from "./workspace.js";
18
+ const ROOT_KS = new Set(["path", "offset", "limit"]);
18
19
  function assertReadReq(request) {
19
20
  if (!isRec(request)) {
20
- throw new Error('[E_BAD_SHAPE] Read request must be an object.');
21
+ throw new Error("[E_BAD_SHAPE] Read request must be an object.");
21
22
  }
22
- rejectUnknownFields(request, ROOT_KS, 'Read request');
23
- if (typeof request.path !== 'string' || request.path.length === 0) {
23
+ rejectUnknownFields(request, ROOT_KS, "Read request");
24
+ if (typeof request.path !== "string" || request.path.length === 0) {
24
25
  throw new Error('[E_BAD_SHAPE] Read request requires a non-empty "path" string.');
25
26
  }
26
27
  }
@@ -33,48 +34,54 @@ function assertReadReq(request) {
33
34
  */
34
35
  export function buildReadTool(io) {
35
36
  return defineTool({
36
- name: 'read',
37
+ name: "read",
37
38
  description: READ_DESCRIPTION,
38
39
  parameters: {
39
40
  path: pathSchema,
40
41
  offset: {
41
- type: 'number',
42
- description: 'Line number to start reading from (1-indexed)',
42
+ type: "number",
43
+ description: "Line number to start reading from (1-indexed)",
43
44
  },
44
45
  limit: {
45
- type: 'number',
46
- description: 'Maximum number of lines to read',
46
+ type: "number",
47
+ description: "Maximum number of lines to read",
47
48
  },
48
49
  },
49
50
  output: {
50
- schema: { type: 'string' },
51
- render: (_args, value) => [{ type: 'text', text: value }],
51
+ schema: { type: "string" },
52
+ render: (_args, value) => [{ type: "text", text: value }],
52
53
  },
53
54
  async execute(args, exec) {
54
- const cwd = execCwd(exec);
55
- const sessionKey = execSessionKey(exec);
56
- const signal = exec.signal;
57
- const canonical = normReq(args);
58
- assertReadReq(canonical);
59
- const rawPath = canonical.path;
60
- abortIf(signal);
61
- const absolutePath = await io.resolve(rawPath, cwd, signal);
62
- const rawText = await io.readText(absolutePath, signal);
63
- const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
64
- absolutePath,
65
- rawText,
66
- displayPath: rawPath,
67
- signal,
68
- maxLines: MAX_HASH_LINES,
55
+ return withWorkspace(execCwd(exec), async () => {
56
+ const cwd = execCwd(exec);
57
+ const sessionKey = execSessionKey(exec);
58
+ const signal = exec.signal;
59
+ const canonical = normReq(args);
60
+ assertReadReq(canonical);
61
+ const rawPath = canonical.path;
62
+ abortIf(signal);
63
+ const absolutePath = await io.resolve(rawPath, cwd, signal);
64
+ const rawText = await io.readText(absolutePath, signal);
65
+ const { normalized, fileHashes, hadUtf8DecodeErrors } = await normFromText({
66
+ absolutePath,
67
+ rawText,
68
+ displayPath: rawPath,
69
+ signal,
70
+ maxLines: MAX_HASH_LINES,
71
+ });
72
+ const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
73
+ if (preview.served.length > 0) {
74
+ await recordServed(sessionKey, absolutePath, preview.served);
75
+ }
76
+ await clearDriftReported(sessionKey, absolutePath);
77
+ // Record the present observation with the fs policy gate so later
78
+ // built-in write/edit calls see this file as observed at the
79
+ // version the model just read (a no-op when no policy listens).
80
+ await io.emitObserved(absolutePath, exec, signal);
81
+ return hadUtf8DecodeErrors
82
+ ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
83
+ : preview.text;
69
84
  });
70
- const preview = await fmtReadPreview(normalized, { offset: canonical.offset, limit: canonical.limit }, fileHashes, absolutePath);
71
- if (preview.served.length > 0) {
72
- await recordServed(sessionKey, absolutePath, preview.served);
73
- }
74
- await clearDriftReported(sessionKey, absolutePath);
75
- return hadUtf8DecodeErrors
76
- ? `${preview.text}\n\n[Non-UTF-8 bytes shown as U+FFFD; editing rewrites the file as UTF-8.]`
77
- : preview.text;
78
85
  },
79
86
  });
80
87
  }
package/lib/tool-undo.js CHANGED
@@ -4,23 +4,24 @@
4
4
  * external write clears the history instead of being overwritten.
5
5
  * @module dsh-better-edit/tool-undo
6
6
  */
7
- import { defineTool } from '@deepseek-ai/dsh-tools';
8
- import { toLF, stripBOM, genDiff, restoreEndings } from './edit-diff.js';
9
- import { cntDiff, splitLines, isRec, normalizeFilePath } from './utils.js';
10
- import { normReq } from './edit-normalize.js';
11
- import { upsertSnapshotFor } from './snapshot-store.js';
12
- import { contentChecksum } from './hashline/hasher.js';
13
- import { lineHashes, changedRange } from './hashline/index.js';
14
- import { getUndo, clearUndo } from './undo-edit.js';
15
- import { recordServedTruncated } from './served-store.js';
16
- import { UNDO_DESCRIPTION } from './prompts.js';
17
- import { execCwd, execSessionKey } from './dsh-context.js';
7
+ import { defineTool } from "@deepseek-ai/dsh-tools";
8
+ import { toLF, stripBOM, genDiff, restoreEndings } from "./edit-diff.js";
9
+ import { cntDiff, splitLines, isRec, normalizeFilePath } from "./utils.js";
10
+ import { normReq } from "./edit-normalize.js";
11
+ import { upsertSnapshotFor } from "./snapshot-store.js";
12
+ import { contentChecksum } from "./hashline/hasher.js";
13
+ import { lineHashes, changedRange } from "./hashline/index.js";
14
+ import { getUndo, clearUndo } from "./undo-edit.js";
15
+ import { recordServedTruncated } from "./served-store.js";
16
+ import { UNDO_DESCRIPTION } from "./prompts.js";
17
+ import { execCwd, execSessionKey } from "./dsh-context.js";
18
+ import { withWorkspace } from "./workspace.js";
18
19
  function assertUndoReq(request) {
19
20
  if (!isRec(request)) {
20
- throw new Error('[E_BAD_SHAPE] undo_last_edit request must be an object.');
21
+ throw new Error("[E_BAD_SHAPE] undo_last_edit request must be an object.");
21
22
  }
22
23
  normalizeFilePath(request);
23
- if (typeof request.path !== 'string' || request.path.length === 0) {
24
+ if (typeof request.path !== "string" || request.path.length === 0) {
24
25
  throw new Error('[E_BAD_SHAPE] undo_last_edit request requires a non-empty "path" string.');
25
26
  }
26
27
  }
@@ -33,80 +34,76 @@ function assertUndoReq(request) {
33
34
  */
34
35
  export function buildUndoTool(io) {
35
36
  return defineTool({
36
- name: 'undo_last_edit',
37
+ name: "undo_last_edit",
37
38
  description: UNDO_DESCRIPTION,
38
39
  parameters: {
39
40
  path: {
40
- type: 'string',
41
+ type: "string",
41
42
  required: true,
42
- description: 'Path to the file to undo',
43
+ description: "Path to the file to undo",
43
44
  },
44
45
  },
45
46
  output: {
46
- schema: { type: 'string' },
47
- render: (_args, value) => [{ type: 'text', text: value }],
47
+ schema: { type: "string" },
48
+ render: (_args, value) => [{ type: "text", text: value }],
48
49
  },
49
50
  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]')) {
51
+ return withWorkspace(execCwd(exec), async () => {
52
+ const cwd = execCwd(exec);
53
+ const sessionKey = execSessionKey(exec);
54
+ const signal = exec.signal;
55
+ const canonical = normReq(args);
56
+ assertUndoReq(canonical);
57
+ const path = canonical.path;
58
+ const absolutePath = await io.resolve(path, cwd, signal);
59
+ const undo = await getUndo(absolutePath);
60
+ if (!undo) {
61
+ return `No undo history for ${path}. There is no previous edit to revert.`;
62
+ }
63
+ let currentRaw;
64
+ try {
65
+ currentRaw = await io.readText(absolutePath, signal);
66
+ }
67
+ catch (error) {
68
+ const message = error instanceof Error ? error.message : String(error);
69
+ if (message.includes("[E_NOT_FOUND]")) {
70
+ await clearUndo(absolutePath);
71
+ return `[E_UNDO_STALE] Cannot undo last edit on ${path}: the file no longer exists. Call read() to inspect the current state.`;
72
+ }
73
+ throw error;
74
+ }
75
+ if (currentRaw !==
76
+ undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
68
77
  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.`;
78
+ 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.`;
79
+ }
80
+ const { text: currentStripped } = stripBOM(currentRaw);
81
+ const currentNormalized = toLF(currentStripped);
82
+ const currentHashes = await lineHashes(currentNormalized, absolutePath);
83
+ const diffResult = genDiff(undo.content, currentNormalized, 0, undefined, undo.hashes);
84
+ const linesAddedByEdit = cntDiff(diffResult.diff, "+");
85
+ const linesRemovedByEdit = cntDiff(diffResult.diff, "-");
86
+ const undoDiffResult = genDiff(currentNormalized, undo.content, 1, undo.hashes, currentHashes);
87
+ const undoDiff = undoDiffResult.diff;
88
+ const restoredRange = changedRange(currentNormalized, undo.content);
89
+ await io.writeText(absolutePath, undo.bom + restoreEndings(undo.content, undo.originalEnding), signal, exec);
90
+ try {
91
+ await upsertSnapshotFor(absolutePath, contentChecksum(undo.content), splitLines(undo.content).length, undo.hashes);
92
+ }
93
+ catch (error) {
94
+ console.error("Failed to restore hash store snapshot after undo:", error);
70
95
  }
71
- throw error;
72
- }
73
- if (currentRaw !==
74
- undo.bom + restoreEndings(undo.resultContent, undo.originalEnding)) {
75
96
  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);
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 [
104
- parts.join('\n'),
105
- '',
106
- 'Diff of the revert:',
107
- '',
108
- undoDiff,
109
- ].join('\n');
97
+ const parts = [`Undone last edit on ${path}.`];
98
+ if (linesAddedByEdit > 0 || linesRemovedByEdit > 0) {
99
+ parts.push(`Removed ${linesAddedByEdit} line(s) that were added and restored ${linesRemovedByEdit} line(s) that were removed.`);
100
+ }
101
+ parts.push("File reverted to previous state. The post-edit diff rows carry the restored file\u2019s fresh anchors for follow-up edits.");
102
+ if (undoDiffResult.servedRows.length > 0) {
103
+ await recordServedTruncated(sessionKey, absolutePath, undoDiffResult.servedRows, splitLines(undo.content).length, restoredRange?.firstChangedLine ?? 0);
104
+ }
105
+ return [parts.join("\n"), "", "Diff of the revert:", "", undoDiff].join("\n");
106
+ });
110
107
  },
111
108
  });
112
109
  }
@@ -1,20 +1,42 @@
1
1
  /**
2
2
  * IO seam for the hashline tool layer. The tools resolve, read, and write
3
3
  * through this bridge so they honor the deployment's `ctx.fs` backend — a
4
- * sandboxed or remote filesystem — instead of reaching around it. The local
5
- * implementation exists for tests and for pure-pipeline verification.
4
+ * sandboxed or remote filesystem — instead of reaching around it.
5
+ *
6
+ * The bridge also participates in dsh's `fs/*` event gate exactly like the
7
+ * built-in tools: writes dispatch `fs/write-intent` (so the observation policy
8
+ * derives its create/replace guard and stale-version checks) and every
9
+ * successful read/mutation emits `fs/observed` with the resulting version. A
10
+ * hashline tool that silently skipped those events would leave the policy's
11
+ * observed state stale, and the next built-in `write` on the same file would
12
+ * fail with `FS_NOT_OBSERVED` / `FS_STALE_VERSION`.
13
+ *
14
+ * The local implementation exists for tests and pure-pipeline verification.
6
15
  * @module dsh-better-edit/fs-bridge
7
16
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileSystem } from '@deepseek-ai/dsh-fs';
17
+ import type { Context } from "@deepseek-ai/cordis";
18
+ import type { FileSystem } from "@deepseek-ai/dsh-fs";
19
+ import type { ToolExecution } from "@deepseek-ai/dsh-tools";
10
20
  /** Text-IO operations the hashline tools need, keyed by canonical absolute path. */
11
21
  export interface FileIO {
12
22
  /** Resolve a (possibly relative) request path against the session cwd to a canonical absolute path. */
13
23
  resolve(path: string, cwd: string, signal?: AbortSignal): Promise<string>;
14
24
  /** Read whole text; missing files, directories, and binary content throw. */
15
25
  readText(absolutePath: string, signal?: AbortSignal): Promise<string>;
16
- /** Atomically write whole text, preserving mode when the file exists. */
17
- writeText(absolutePath: string, content: string, signal?: AbortSignal): Promise<void>;
26
+ /**
27
+ * 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
+ * `fs/observed` with the new version on success, so later built-in tools
30
+ * see a fresh observation.
31
+ * @param exec - the calling execution; carries the session the policy keys by.
32
+ */
33
+ writeText(absolutePath: string, content: string, signal?: AbortSignal, exec?: ToolExecution): Promise<void>;
34
+ /**
35
+ * Emit `fs/observed` (present at the current version) for a successful
36
+ * read, so the policy records that this session has seen the file.
37
+ * @param exec - the calling execution; carries the session the policy keys by.
38
+ */
39
+ emitObserved(absolutePath: string, exec?: ToolExecution, signal?: AbortSignal): Promise<void>;
18
40
  /** Opaque change-version for snapshot bookkeeping, or undefined when unavailable. */
19
41
  statVersion(absolutePath: string, signal?: AbortSignal): Promise<string | undefined>;
20
42
  }
@@ -27,6 +49,6 @@ export interface FileIO {
27
49
  */
28
50
  export declare function mapFsError(error: unknown, displayPath: string): never;
29
51
  /** FileIO over the deployment's `ctx.fs` service. */
30
- export declare function ctxFsIO(fs: FileSystem, _ctx: Context): FileIO;
52
+ export declare function ctxFsIO(fs: FileSystem, ctx: Context): FileIO;
31
53
  /** FileIO over the host filesystem directly (tests, previews, fallback). */
32
54
  export declare function localIO(): FileIO;
@@ -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,9 +11,17 @@
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
+ /**
18
+ * Services the plugin's per-agent install touches: `tools` and `systemPrompt`
19
+ * for the shadow registrations, `fs` for the IO bridge. Cordis refuses
20
+ * property access to an undeclared service ("cannot get property X without
21
+ * inject"), so these MUST be listed or every agent install fails at
22
+ * session-start.
23
+ */
24
+ export declare const inject: string[];
17
25
  /** One per-agent registration bundle, disposed with the agent. */
18
26
  interface AgentTools {
19
27
  dispose(): void;
@@ -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;
@@ -5,8 +5,8 @@
5
5
  * the failing item's current range is echoed as fresh serves.
6
6
  * @module dsh-better-edit/tool-batch-edit
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the `batch_edit` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context.
@@ -5,8 +5,8 @@
5
5
  * served-range verification, reject-and-serve) replaces the built-in one.
6
6
  * @module dsh-better-edit/tool-edit
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the hash-anchored `edit` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context (logger, lifecycle).
@@ -5,8 +5,8 @@
5
5
  * shown the lines it targets.
6
6
  * @module dsh-better-edit/tool-read
7
7
  */
8
- import type { Context } from '@deepseek-ai/cordis';
9
- import type { FileIO } from './fs-bridge.js';
8
+ import type { Context } from "@deepseek-ai/cordis";
9
+ import type { FileIO } from "./fs-bridge.js";
10
10
  /**
11
11
  * Register the hash-anchored `read` tool on the calling agent's scope.
12
12
  * @param _rootCtx - host context.
@@ -4,8 +4,8 @@
4
4
  * external write clears the history instead of being overwritten.
5
5
  * @module dsh-better-edit/tool-undo
6
6
  */
7
- import type { Context } from '@deepseek-ai/cordis';
8
- import type { FileIO } from './fs-bridge.js';
7
+ import type { Context } from "@deepseek-ai/cordis";
8
+ import type { FileIO } from "./fs-bridge.js";
9
9
  /**
10
10
  * Register the `undo_last_edit` tool on the calling agent's scope.
11
11
  * @param _rootCtx - host context.
@@ -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
+ }