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/README.md +11 -4
- package/lib/edit-pipeline.js +1 -1
- package/lib/fs-bridge.js +10 -3
- package/lib/hash-store.js +52 -27
- package/lib/index.js +34 -34
- package/lib/paths.js +18 -12
- package/lib/sandbox.js +97 -0
- package/lib/tool-batch-edit.js +86 -82
- package/lib/tool-edit.js +101 -96
- package/lib/tool-read.js +30 -27
- package/lib/tool-undo.js +65 -54
- package/lib/types/fs-bridge.d.ts +7 -2
- package/lib/types/hash-store.d.ts +13 -1
- package/lib/types/index.d.ts +1 -1
- package/lib/types/paths.d.ts +12 -8
- package/lib/types/sandbox.d.ts +70 -0
- package/lib/types/tool-batch-edit.d.ts +3 -2
- package/lib/types/tool-edit.d.ts +3 -2
- package/lib/types/tool-undo.d.ts +3 -2
- package/lib/types/workspace.d.ts +24 -0
- package/lib/workspace.js +30 -0
- package/lib/write-hook.js +49 -44
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -137,13 +137,20 @@ hash store).
|
|
|
137
137
|
## Store
|
|
138
138
|
|
|
139
139
|
Hash snapshots, served-state rows, and undo history live in one SQLite store
|
|
140
|
-
|
|
140
|
+
**co-located with the workspace being edited** — one store per session cwd:
|
|
141
141
|
|
|
142
|
-
-
|
|
143
|
-
|
|
142
|
+
- `<workspace>/.dsh_better_edit/hash-store.sqlite`
|
|
143
|
+
|
|
144
|
+
Parallel sessions in different workspaces keep separate stores (the session
|
|
145
|
+
cwd is carried through each tool call), so one project's anchors and undo
|
|
146
|
+
history never leak into another's. Outside a tool call (tests, previews) the
|
|
147
|
+
store falls back to the shared DeepSeek Harness home
|
|
148
|
+
(`$DSH_HOME/plugins/dsh-better-edit/hash-store.sqlite`).
|
|
144
149
|
|
|
145
150
|
A 7-day TTL prunes served rows; missing-file snapshots are pruned at startup.
|
|
146
|
-
Corrupt stores are quarantined and rebuilt automatically.
|
|
151
|
+
Corrupt stores are quarantined and rebuilt automatically. Moving to the
|
|
152
|
+
per-workspace layout does not migrate earlier undo history from the shared
|
|
153
|
+
home — treat any pre-0.1.2 undo entries as gone.
|
|
147
154
|
|
|
148
155
|
## Error codes
|
|
149
156
|
|
package/lib/edit-pipeline.js
CHANGED
|
@@ -14,7 +14,7 @@ import { loadServed, sessionKeyFor } from './served-store.js';
|
|
|
14
14
|
import { findSnapshotPathsByHashes } from './snapshot-store.js';
|
|
15
15
|
import { scanDrift } from './drift.js';
|
|
16
16
|
import { abortIf, isRec, rejectUnknownFields, splitLines } from './utils.js';
|
|
17
|
-
const ROOT_KS = new Set(['path', 'remove_from', 'remove_to', 'replacement_text']);
|
|
17
|
+
const ROOT_KS = new Set(['path', 'remove_from', 'remove_to', 'replacement_text', 'sandbox_permissions', 'justification']);
|
|
18
18
|
export function assertReq(request) {
|
|
19
19
|
if (!isRec(request)) {
|
|
20
20
|
throw new Error('[E_BAD_SHAPE] Edit request must be an object.');
|
package/lib/fs-bridge.js
CHANGED
|
@@ -71,7 +71,7 @@ export function ctxFsIO(fs, ctx) {
|
|
|
71
71
|
return mapFsError(error, absolutePath);
|
|
72
72
|
}
|
|
73
73
|
},
|
|
74
|
-
async writeText(absolutePath, content, signal, exec) {
|
|
74
|
+
async writeText(absolutePath, content, signal, exec, sandboxPolicy) {
|
|
75
75
|
try {
|
|
76
76
|
const target = await fs.resolve(absolutePath, {
|
|
77
77
|
...(signal !== undefined ? { signal } : {}),
|
|
@@ -80,12 +80,19 @@ export function ctxFsIO(fs, ctx) {
|
|
|
80
80
|
// createIfAbsent / replaceIfVersion; the bare default is
|
|
81
81
|
// undefined (unconditional) when no policy is mounted.
|
|
82
82
|
const intent = await ctx.waterfall("fs/write-intent", target, exec, () => undefined);
|
|
83
|
-
|
|
83
|
+
// The sandbox policy (session workspace root + mode) is what a
|
|
84
|
+
// confined backend checks: without it the backend falls back to
|
|
85
|
+
// the deployment default root and denies writes inside the
|
|
86
|
+
// session workspace under workspace-write.
|
|
87
|
+
const outcome = await fs.writeText(target, content, intent, signal, sandboxPolicy);
|
|
84
88
|
// Record the present observation (a no-op when no policy
|
|
85
89
|
// plugin listens), so later built-in tools see the new version.
|
|
86
90
|
ctx.emit("fs/observed", target, { kind: "present", version: outcome.version }, exec);
|
|
87
91
|
}
|
|
88
92
|
catch (error) {
|
|
93
|
+
// FS_SANDBOX_DENIED passes through raw; the tool layer maps it
|
|
94
|
+
// to the shared [sandbox: …] marker + escalation hint via its
|
|
95
|
+
// sandbox controller.
|
|
89
96
|
return mapFsError(error, absolutePath);
|
|
90
97
|
}
|
|
91
98
|
},
|
|
@@ -128,7 +135,7 @@ export function localIO() {
|
|
|
128
135
|
signal?.throwIfAborted();
|
|
129
136
|
return readFile(absolutePath, "utf-8");
|
|
130
137
|
},
|
|
131
|
-
async writeText(absolutePath, content, signal) {
|
|
138
|
+
async writeText(absolutePath, content, signal, _exec, _sandboxPolicy) {
|
|
132
139
|
signal?.throwIfAborted();
|
|
133
140
|
await writeAtomic(absolutePath, content);
|
|
134
141
|
},
|
package/lib/hash-store.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
-
import { readFile, rename, mkdir } from "fs/promises";
|
|
2
|
+
import { readFile, rename, mkdir } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
3
4
|
import { DatabaseSync } from "node:sqlite";
|
|
4
|
-
import { hashStorePath
|
|
5
|
+
import { hashStorePath } from "./paths.js";
|
|
6
|
+
import { workspaceCwd } from "./workspace.js";
|
|
5
7
|
import { errCode, splitLines } from "./utils.js";
|
|
6
8
|
import { initHasher, contentChecksum } from "./hashline/hasher.js";
|
|
7
9
|
import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
|
|
@@ -51,8 +53,9 @@ function withBusyRetry(fn) {
|
|
|
51
53
|
function openDbWithBusyRetry(storePath) {
|
|
52
54
|
return withBusyRetry(() => openDb(storePath));
|
|
53
55
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
+
/** One open store per store path (per workspace); parallel sessions share per-workspace dbs. */
|
|
57
|
+
const stores = new Map();
|
|
58
|
+
const openings = new Map();
|
|
56
59
|
let exitHandlerRegistered = false;
|
|
57
60
|
function openDb(storePath) {
|
|
58
61
|
const db = new DatabaseSync(storePath, {
|
|
@@ -232,9 +235,9 @@ function shutdownDb(db) {
|
|
|
232
235
|
db.close();
|
|
233
236
|
}
|
|
234
237
|
async function openStore(storePath) {
|
|
235
|
-
|
|
238
|
+
// Multi-store: never close another workspace's store when opening this one.
|
|
236
239
|
await initHasher();
|
|
237
|
-
await mkdir(
|
|
240
|
+
await mkdir(dirname(storePath), { recursive: true });
|
|
238
241
|
let existed = existsSync(storePath);
|
|
239
242
|
let opened;
|
|
240
243
|
try {
|
|
@@ -256,12 +259,12 @@ async function openStore(storePath) {
|
|
|
256
259
|
}
|
|
257
260
|
const { db, stmts } = opened;
|
|
258
261
|
if (!existed) {
|
|
259
|
-
await migrateLegacy(db);
|
|
262
|
+
await migrateLegacy(db, storePath);
|
|
260
263
|
}
|
|
261
264
|
withBusyRetry(() => {
|
|
262
265
|
stmts.servedPruneOlderThan(Date.now() - SERVED_TTL_MS);
|
|
263
266
|
});
|
|
264
|
-
|
|
267
|
+
stores.set(storePath, { path: storePath, db, stmts });
|
|
265
268
|
if (!exitHandlerRegistered) {
|
|
266
269
|
exitHandlerRegistered = true;
|
|
267
270
|
process.once("exit", () => shutdownHashStore());
|
|
@@ -274,38 +277,60 @@ async function openStore(storePath) {
|
|
|
274
277
|
}
|
|
275
278
|
return { stmts, engine: "node:sqlite" };
|
|
276
279
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
280
|
+
/** Resolve the store path for this call: explicit cwd, the active workspace, or the shared-home fallback. */
|
|
281
|
+
function storePathFor(cwd) {
|
|
282
|
+
return hashStorePath(cwd ?? workspaceCwd());
|
|
283
|
+
}
|
|
284
|
+
/**
|
|
285
|
+
* Load (and cache) the hash store for the given cwd — or, when omitted, the
|
|
286
|
+
* workspace active for this async execution (`withWorkspace`), falling back to
|
|
287
|
+
* the shared `$DSH_HOME` store outside a tool call.
|
|
288
|
+
* @param cwd - optional explicit workspace root; defaults to the active workspace.
|
|
289
|
+
*/
|
|
290
|
+
export function loadHashStore(cwd) {
|
|
291
|
+
const storePath = storePathFor(cwd);
|
|
292
|
+
const cached = stores.get(storePath);
|
|
293
|
+
if (cached && cached.db.isOpen) {
|
|
294
|
+
return Promise.resolve({ stmts: cached.stmts, engine: "node:sqlite" });
|
|
284
295
|
}
|
|
296
|
+
const existing = openings.get(storePath);
|
|
297
|
+
if (existing)
|
|
298
|
+
return existing;
|
|
285
299
|
const promise = openStore(storePath).finally(() => {
|
|
286
|
-
|
|
287
|
-
opening = null;
|
|
300
|
+
openings.delete(storePath);
|
|
288
301
|
});
|
|
289
|
-
|
|
302
|
+
openings.set(storePath, promise);
|
|
290
303
|
return promise;
|
|
291
304
|
}
|
|
305
|
+
/** The cached store for the active workspace (or the shared-home fallback), if open. */
|
|
306
|
+
function currentStore() {
|
|
307
|
+
return stores.get(storePathFor())?.db.isOpen ? stores.get(storePathFor()) : undefined;
|
|
308
|
+
}
|
|
309
|
+
/** Close every open store (process exit, HMR, tests). */
|
|
292
310
|
export function shutdownHashStore() {
|
|
293
|
-
|
|
294
|
-
shutdownDb(
|
|
295
|
-
cachedDb = null;
|
|
311
|
+
for (const [, entry] of stores) {
|
|
312
|
+
shutdownDb(entry.db);
|
|
296
313
|
}
|
|
314
|
+
stores.clear();
|
|
315
|
+
openings.clear();
|
|
297
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* Run `fn` inside one BEGIN IMMEDIATE transaction on the active workspace's
|
|
319
|
+
* store. Without an open store for this context the call runs bare (the
|
|
320
|
+
* caller has already loaded the store in every in-process path).
|
|
321
|
+
*/
|
|
298
322
|
export function withStore(fn) {
|
|
299
|
-
|
|
323
|
+
const store = currentStore();
|
|
324
|
+
if (store) {
|
|
300
325
|
withBusyRetry(() => {
|
|
301
|
-
|
|
326
|
+
store.db.exec("BEGIN IMMEDIATE");
|
|
302
327
|
try {
|
|
303
328
|
fn();
|
|
304
|
-
|
|
329
|
+
store.db.exec("COMMIT");
|
|
305
330
|
}
|
|
306
331
|
catch (e) {
|
|
307
332
|
try {
|
|
308
|
-
|
|
333
|
+
store.db.exec("ROLLBACK");
|
|
309
334
|
}
|
|
310
335
|
catch { }
|
|
311
336
|
throw e;
|
|
@@ -316,8 +341,8 @@ export function withStore(fn) {
|
|
|
316
341
|
fn();
|
|
317
342
|
}
|
|
318
343
|
}
|
|
319
|
-
async function migrateLegacy(db) {
|
|
320
|
-
const legacyPath =
|
|
344
|
+
async function migrateLegacy(db, storePath) {
|
|
345
|
+
const legacyPath = join(dirname(storePath), "hash-store.json");
|
|
321
346
|
let content;
|
|
322
347
|
try {
|
|
323
348
|
content = await readFile(legacyPath, "utf-8");
|
package/lib/index.js
CHANGED
|
@@ -11,17 +11,17 @@
|
|
|
11
11
|
* preview to write results.
|
|
12
12
|
* @module dsh-better-edit
|
|
13
13
|
*/
|
|
14
|
-
import { ctxFsIO } from
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from
|
|
14
|
+
import { ctxFsIO } from "./fs-bridge.js";
|
|
15
|
+
import { FsSandboxController } from "./sandbox.js";
|
|
16
|
+
import { registerReadTool } from "./tool-read.js";
|
|
17
|
+
import { registerEditTool } from "./tool-edit.js";
|
|
18
|
+
import { registerBatchEditTool } from "./tool-batch-edit.js";
|
|
19
|
+
import { registerUndoTool } from "./tool-undo.js";
|
|
20
|
+
import { registerWriteHook } from "./write-hook.js";
|
|
21
|
+
import { initHasher } from "./hashline/hasher.js";
|
|
22
|
+
import { EDIT_DESCRIPTION, EDIT_GUIDELINES, READ_GUIDELINES, BATCH_EDIT_GUIDELINES, UNDO_GUIDELINES, } from "./prompts.js";
|
|
23
23
|
/** Cordis plugin name used by loader diagnostics. */
|
|
24
|
-
export const name =
|
|
24
|
+
export const name = "dsh-better-edit";
|
|
25
25
|
/**
|
|
26
26
|
* Services the plugin's per-agent install touches: `tools` and `systemPrompt`
|
|
27
27
|
* for the shadow registrations, `fs` for the IO bridge. Cordis refuses
|
|
@@ -29,7 +29,7 @@ export const name = 'dsh-better-edit';
|
|
|
29
29
|
* inject"), so these MUST be listed or every agent install fails at
|
|
30
30
|
* session-start.
|
|
31
31
|
*/
|
|
32
|
-
export const inject = [
|
|
32
|
+
export const inject = ["tools", "systemPrompt", "fs"];
|
|
33
33
|
function installAgentTools(rootCtx, agent) {
|
|
34
34
|
return agent.ctx.effect(() => {
|
|
35
35
|
// `fs` is host-plane: use the plugin's own context (covered by
|
|
@@ -39,39 +39,40 @@ function installAgentTools(rootCtx, agent) {
|
|
|
39
39
|
const io = ctxFsIO(rootCtx.fs, rootCtx);
|
|
40
40
|
const disposers = [];
|
|
41
41
|
disposers.push(registerReadTool(rootCtx, agent.ctx, io));
|
|
42
|
-
|
|
43
|
-
disposers.push(
|
|
44
|
-
disposers.push(
|
|
42
|
+
const sandbox = new FsSandboxController(rootCtx);
|
|
43
|
+
disposers.push(registerEditTool(rootCtx, agent.ctx, io, sandbox));
|
|
44
|
+
disposers.push(registerBatchEditTool(rootCtx, agent.ctx, io, sandbox));
|
|
45
|
+
disposers.push(registerUndoTool(rootCtx, agent.ctx, io, sandbox));
|
|
45
46
|
disposers.push(registerWriteHook(rootCtx, agent.ctx, io));
|
|
46
47
|
// Shadow the preset's built-in tool guidance with the hashline contract.
|
|
47
48
|
// Same section names on the agent's own layer win over the preset's.
|
|
48
49
|
disposers.push(agent.ctx.systemPrompt.section({
|
|
49
|
-
name:
|
|
50
|
+
name: "tool:edit",
|
|
50
51
|
order: 102,
|
|
51
52
|
text: [
|
|
52
53
|
EDIT_DESCRIPTION,
|
|
53
|
-
|
|
54
|
-
EDIT_GUIDELINES.map((line) => `- ${line}`).join(
|
|
55
|
-
].join(
|
|
54
|
+
"",
|
|
55
|
+
EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
56
|
+
].join("\n"),
|
|
56
57
|
}));
|
|
57
58
|
disposers.push(agent.ctx.systemPrompt.section({
|
|
58
|
-
name:
|
|
59
|
+
name: "tool:read",
|
|
59
60
|
order: 100,
|
|
60
61
|
text: [
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
READ_GUIDELINES.map((line) => `- ${line}`).join(
|
|
64
|
-
].join(
|
|
62
|
+
"Use the read tool — not shell commands like cat — to inspect text files.",
|
|
63
|
+
"",
|
|
64
|
+
READ_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
65
|
+
].join("\n"),
|
|
65
66
|
}));
|
|
66
67
|
disposers.push(agent.ctx.systemPrompt.section({
|
|
67
|
-
name:
|
|
68
|
+
name: "tool:batch_edit",
|
|
68
69
|
order: 103,
|
|
69
|
-
text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join(
|
|
70
|
+
text: BATCH_EDIT_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
70
71
|
}));
|
|
71
72
|
disposers.push(agent.ctx.systemPrompt.section({
|
|
72
|
-
name:
|
|
73
|
+
name: "tool:undo_last_edit",
|
|
73
74
|
order: 104,
|
|
74
|
-
text: UNDO_GUIDELINES.map((line) => `- ${line}`).join(
|
|
75
|
+
text: UNDO_GUIDELINES.map((line) => `- ${line}`).join("\n"),
|
|
75
76
|
}));
|
|
76
77
|
return () => {
|
|
77
78
|
for (const dispose of disposers)
|
|
@@ -81,15 +82,14 @@ function installAgentTools(rootCtx, agent) {
|
|
|
81
82
|
}
|
|
82
83
|
/** Mount the bundle: initialize the store, then install tools per agent. */
|
|
83
84
|
export function apply(rootCtx) {
|
|
84
|
-
// Warm the hasher
|
|
85
|
-
//
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
.
|
|
89
|
-
rootCtx.logger.warn(`dsh-better-edit: hash-store warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
85
|
+
// Warm the hasher once; the per-workspace stores are opened lazily on the
|
|
86
|
+
// first tool call in each workspace (there is no shared store to prune at
|
|
87
|
+
// boot anymore).
|
|
88
|
+
initHasher().catch((error) => {
|
|
89
|
+
rootCtx.logger.warn(`dsh-better-edit: hasher warm-up failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
90
90
|
});
|
|
91
91
|
const registered = new WeakSet();
|
|
92
|
-
rootCtx.on(
|
|
92
|
+
rootCtx.on("agent/session-start", ({ agent }) => {
|
|
93
93
|
if (registered.has(agent))
|
|
94
94
|
return;
|
|
95
95
|
registered.add(agent);
|
package/lib/paths.js
CHANGED
|
@@ -2,22 +2,28 @@ import { homedir } from "node:os";
|
|
|
2
2
|
import { isAbsolute, resolve as resolvePath, join, dirname } from "node:path";
|
|
3
3
|
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
4
4
|
/**
|
|
5
|
-
* On-disk home for dsh-better-edit state
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* On-disk home for dsh-better-edit state. Inside a tool call the store lives
|
|
6
|
+
* co-located with the files being edited: `<workspace>/.dsh_better_edit/` (the
|
|
7
|
+
* workspace is the session cwd, carried through the execution by
|
|
8
|
+
* `withWorkspace`). Outside a tool call — tests, previews, startup — the store
|
|
9
|
+
* falls back to the shared DeepSeek Harness home
|
|
10
|
+
* (`$DSH_HOME/plugins/dsh-better-edit`, default `~/.dsh/plugins/dsh-better-edit`),
|
|
11
|
+
* so a caller without a workspace never writes into an arbitrary cwd.
|
|
12
|
+
* @param cwd - the workspace root, or undefined for the shared-home fallback.
|
|
9
13
|
*/
|
|
10
|
-
export function configDir() {
|
|
11
|
-
return
|
|
14
|
+
export function configDir(cwd) {
|
|
15
|
+
return cwd !== undefined
|
|
16
|
+
? join(resolvePath(cwd), ".dsh_better_edit")
|
|
17
|
+
: join(resolveDshHome(), "plugins", "dsh-better-edit");
|
|
12
18
|
}
|
|
13
|
-
export function hashStorePath() {
|
|
14
|
-
return join(configDir(), "hash-store.sqlite");
|
|
19
|
+
export function hashStorePath(cwd) {
|
|
20
|
+
return join(configDir(cwd), "hash-store.sqlite");
|
|
15
21
|
}
|
|
16
|
-
export function legacyHashStorePath() {
|
|
17
|
-
return join(configDir(), "hash-store.json");
|
|
22
|
+
export function legacyHashStorePath(cwd) {
|
|
23
|
+
return join(configDir(cwd), "hash-store.json");
|
|
18
24
|
}
|
|
19
|
-
export function hashStoreDir() {
|
|
20
|
-
return dirname(hashStorePath());
|
|
25
|
+
export function hashStoreDir(cwd) {
|
|
26
|
+
return dirname(hashStorePath(cwd));
|
|
21
27
|
}
|
|
22
28
|
function homeBase() {
|
|
23
29
|
const envHome = process.env.HOME;
|
package/lib/sandbox.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
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 { FsError } from '@deepseek-ai/dsh-fs';
|
|
13
|
+
import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, validateEscalationArgs, } from '@deepseek-ai/dsh-sandbox';
|
|
14
|
+
/**
|
|
15
|
+
* The filesystem escalation API: advertisement gating, per-call policy
|
|
16
|
+
* resolution, the one-approved wider retry, and denial-marker mapping. A pure
|
|
17
|
+
* product of `ctx` at plugin apply time.
|
|
18
|
+
*/
|
|
19
|
+
export class FsSandboxController {
|
|
20
|
+
ctx;
|
|
21
|
+
/** The escalation targets this composition advertises (`[]` when no confining backend is mounted). */
|
|
22
|
+
escalationModes;
|
|
23
|
+
/** Shared per-session policy resolver, required by a confining backend. */
|
|
24
|
+
policy;
|
|
25
|
+
constructor(ctx) {
|
|
26
|
+
this.ctx = ctx;
|
|
27
|
+
const defaultMode = ctx.fs.sandboxMode;
|
|
28
|
+
this.escalationModes = defaultMode === undefined ? [] : ESCALATION_TARGETS;
|
|
29
|
+
this.policy = defaultMode === undefined ? undefined : ctx.get('sandboxPolicy');
|
|
30
|
+
if (defaultMode !== undefined && this.policy === undefined) {
|
|
31
|
+
throw new Error('dsh-better-edit: the mounted filesystem confines but ctx.sandboxPolicy is missing');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The escalation schema fields for a mutating tool's `parameters`. Call it
|
|
36
|
+
* only under a confining backend (guard on {@link escalationModes}); the
|
|
37
|
+
* enum pins the closed target vocabulary, the strict-wider check happens
|
|
38
|
+
* per call at execution.
|
|
39
|
+
*/
|
|
40
|
+
schemaFields() {
|
|
41
|
+
return {
|
|
42
|
+
sandbox_permissions: {
|
|
43
|
+
type: 'string',
|
|
44
|
+
enum: [...this.escalationModes],
|
|
45
|
+
description: 'The wider sandbox mode this file operation needs. Only valid as a one-shot retry '
|
|
46
|
+
+ 'of an operation the sandbox just denied; requires justification and user approval.',
|
|
47
|
+
},
|
|
48
|
+
justification: {
|
|
49
|
+
type: 'string',
|
|
50
|
+
description: 'Required with sandbox_permissions: one sentence for the user explaining '
|
|
51
|
+
+ 'why this exact file operation needs the wider access.',
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The policy to stamp onto this mutation: an approved escalation grant (a
|
|
57
|
+
* strictly wider retry resolved through `ctx.approval` before anything
|
|
58
|
+
* executes), else the session's standing mode. The calling session's cwd is
|
|
59
|
+
* always carried as the workspace root, so `workspace-write` allows writes
|
|
60
|
+
* inside the session workspace.
|
|
61
|
+
* @param toolName - the mutating tool's name, for the approval audit trail.
|
|
62
|
+
* @param args - the call's escalation arguments.
|
|
63
|
+
* @param exec - the tool-execution context (agent, callId, signal).
|
|
64
|
+
* @returns the policy to pass to the mutation, or undefined for an
|
|
65
|
+
* unsandboxed backend.
|
|
66
|
+
*/
|
|
67
|
+
async resolvePolicy(toolName, args, exec) {
|
|
68
|
+
validateEscalationArgs(args.sandbox_permissions, args.justification);
|
|
69
|
+
const standingPolicy = this.policy?.resolve({ ...exec.agent ? { session: exec.agent.session } : {} });
|
|
70
|
+
if (args.sandbox_permissions === undefined || args.justification === undefined) {
|
|
71
|
+
return standingPolicy;
|
|
72
|
+
}
|
|
73
|
+
if (this.escalationModes.length === 0) {
|
|
74
|
+
throw new Error('sandbox_permissions is not available in this composition (no sandboxing filesystem to escalate)');
|
|
75
|
+
}
|
|
76
|
+
const policy = standingPolicy;
|
|
77
|
+
const approvedMode = await approveEscalation({ requestedMode: args.sandbox_permissions, justification: args.justification, effectiveMode: policy.mode, subject: 'operation' }, {
|
|
78
|
+
approver: this.ctx.get('approval'),
|
|
79
|
+
agent: exec.agent,
|
|
80
|
+
callId: exec.callId,
|
|
81
|
+
toolName,
|
|
82
|
+
signal: exec.signal,
|
|
83
|
+
});
|
|
84
|
+
return { ...policy, mode: approvedMode };
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Map a thrown provider error for the model: a `FS_SANDBOX_DENIED` becomes
|
|
88
|
+
* the shared `[sandbox: …]` denial marker plus the same-turn escalation
|
|
89
|
+
* hint, keeping the structured code. Any other error passes through.
|
|
90
|
+
*/
|
|
91
|
+
mapError(error, policy) {
|
|
92
|
+
if (!(error instanceof FsError) || error.code !== 'FS_SANDBOX_DENIED')
|
|
93
|
+
return error;
|
|
94
|
+
const mode = policy.mode;
|
|
95
|
+
return new FsError(`${sandboxDenialMarker(mode)}\n${escalationHintMarker('operation')}`, 'FS_SANDBOX_DENIED', { cause: error });
|
|
96
|
+
}
|
|
97
|
+
}
|