@dsmm/dsmm 0.3.7 → 0.3.9

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/guards.js CHANGED
@@ -6,26 +6,17 @@ import { resolveAdmittedDsmmRole } from "./role-policy.js";
6
6
  import { Context } from "@deepseek-ai/cordis";
7
7
  import { nativeStandingFullAccess } from "./permission-native-access.js";
8
8
  import { DsmmProfileError } from "./profiles.js";
9
+ import { simpleShellCommand, simpleShellDialect } from "./permission-native-command.js";
9
10
  export const DSMM_GUARD_PREFIX = "[dsmm safety]";
10
11
  const STRUCTURED_TODO_PATTERN = /^\[[^\]]+\]\s+\[[^\]]+\]\s+to\s+.+\s+-\s+expect\s+.+/u;
11
12
  function asRecord(value) {
12
13
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
13
14
  }
14
- function stringField(value, keys) {
15
- const record = asRecord(value);
16
- if (record === undefined)
17
- return undefined;
18
- for (const key of keys) {
19
- if (typeof record[key] === "string")
20
- return record[key];
21
- }
22
- return undefined;
23
- }
24
15
  function toolName(exec) {
25
16
  return exec.name.toLowerCase();
26
17
  }
27
18
  function commandText(exec) {
28
- return stringField(exec.arguments, ["command", "cmd", "script"]);
19
+ return simpleShellCommand(exec.arguments);
29
20
  }
30
21
  function allText(content) {
31
22
  let text = "";
@@ -91,12 +82,7 @@ export function isSafetyScopeActive(exec, settings, controller) {
91
82
  return isDsmmRoleId(resolveSelectedAgentPreset(exec.agent?.session));
92
83
  }
93
84
  function shellDialect(exec) {
94
- const name = toolName(exec);
95
- if (name === "bash" || name === "sh" || name === "zsh")
96
- return "posix";
97
- if (name === "pwsh" || name === "powershell")
98
- return "powershell";
99
- return undefined;
85
+ return simpleShellDialect(exec.name);
100
86
  }
101
87
  function shellSafetyDecision(exec) {
102
88
  const dialect = shellDialect(exec);
@@ -132,7 +118,7 @@ function shellDialectViolationDecision(violation) {
132
118
  reason: `${DSMM_GUARD_PREFIX} bash command appears to use PowerShell syntax (\`$env:\`). Use POSIX environment syntax for bash.`
133
119
  };
134
120
  }
135
- function gitWriteDecision(exec, settings) {
121
+ function gitWriteDecision(exec, settings, simple = false) {
136
122
  if (settings.guards.gitWriteGuard === "off")
137
123
  return undefined;
138
124
  const command = commandText(exec);
@@ -146,6 +132,8 @@ function gitWriteDecision(exec, settings) {
146
132
  reason: `${DSMM_GUARD_PREFIX} git write command is disabled by dsmm settings: git ${operation}`
147
133
  };
148
134
  }
135
+ if (simple)
136
+ return undefined;
149
137
  return {
150
138
  kind: "ask",
151
139
  reason: `${DSMM_GUARD_PREFIX} git write command requires explicit user approval before running: git ${operation}`
@@ -201,9 +189,11 @@ function todoDisciplineDecision(exec, settings) {
201
189
  reason: `${DSMM_GUARD_PREFIX} todo content must use "[WHERE] [HOW] to [WHY] - expect [RESULT]": ${malformed.content}`
202
190
  };
203
191
  }
204
- export function decidePreToolExecution(exec, settings, controller, nativeFullAccess = false) {
192
+ export function decidePreToolExecution(exec, settings, controller, nativeFullAccess = false, simple = false) {
205
193
  if (!isSafetyScopeActive(exec, settings, controller))
206
194
  return undefined;
195
+ if (simple)
196
+ return undefined;
207
197
  if (nativeFullAccess)
208
198
  return settings.guards.gitWriteGuard === "deny" ? gitWriteDecision(exec, settings) : undefined;
209
199
  if (settings.guards.shellCommandSafety) {
@@ -211,7 +201,7 @@ export function decidePreToolExecution(exec, settings, controller, nativeFullAcc
211
201
  if (shell !== undefined)
212
202
  return shell;
213
203
  }
214
- const git = gitWriteDecision(exec, settings);
204
+ const git = gitWriteDecision(exec, settings, simple);
215
205
  if (git !== undefined)
216
206
  return git;
217
207
  if (!settings.modules.deepwork.enabled)
@@ -269,7 +259,8 @@ export function registerSafetyGuards(ctx, controller, getSettings, rolePolicy) {
269
259
  return next();
270
260
  throw error;
271
261
  }
272
- const decision = decidePreToolExecution(exec, settings, controller, full);
262
+ const simple = Context.is(ctx) && await ctx.get("dsmmPermissionController")?.simpleCommandAllowed(execution) === true;
263
+ const decision = decidePreToolExecution(exec, settings, controller, full, simple);
273
264
  if (!full && settings.modules.deepwork.enabled && settings.guards.toolOutputTruncation.enabled && isSafetyScopeActive(exec, settings, controller))
274
265
  truncationLimits.set(exec, settings.guards.toolOutputTruncation.maxInlineBytes);
275
266
  if (decision === undefined)
@@ -32,7 +32,10 @@ export interface PermissionRegistration {
32
32
  readonly body: ToolDefinition["execute"];
33
33
  readonly identity: object;
34
34
  readonly signal?: AbortSignal;
35
+ readonly wrapper?: ToolDefinition["execute"];
36
+ readonly simpleOnly?: boolean;
35
37
  assertCurrent?(execution: Readonly<ToolExecution>): void;
38
+ assertIntegrity?(execution: Readonly<ToolExecution>): void;
36
39
  approval(): Context["approval"] | undefined;
37
40
  standingMode(execution: Readonly<ToolExecution>): string | undefined;
38
41
  unchanged(): boolean;
@@ -53,11 +56,14 @@ export declare class PermissionControl {
53
56
  private readonly requests;
54
57
  private readonly execution;
55
58
  constructor(ctx: Context, collaborators: PermissionControlCollaborators);
56
- compose(exec: Readonly<ToolExecution>, registration: PermissionRegistration, entry: NativeCommandEntry | undefined, action: "inherit" | "allow" | "ask", next: () => Promise<PreToolDecision>, cwd: string): Promise<PreToolDecision>;
59
+ compose(exec: Readonly<ToolExecution>, registration: PermissionRegistration, entry: NativeCommandEntry | undefined, action: "inherit" | "allow" | "ask", next: () => Promise<PreToolDecision>, cwd: string, simple?: boolean): Promise<PreToolDecision>;
60
+ private composeDecision;
57
61
  private checkIntegrity;
58
62
  guard(exec: Readonly<ToolExecution>): string | undefined;
59
63
  answerer(request: Request, next: () => Promise<Outcome>): Promise<Outcome>;
60
- run<T>(exec: ToolRunContext, args: unknown, registration: PermissionRegistration, body: (signal: AbortSignal) => Promise<T>): Promise<T>;
64
+ isSimple(exec: Readonly<ToolExecution>): boolean;
65
+ pending(registration: PermissionRegistration): boolean;
66
+ run<T>(exec: ToolRunContext, args: unknown, registration: PermissionRegistration, body: (signal: AbortSignal, args: unknown) => Promise<T>): Promise<T>;
61
67
  private request;
62
68
  /** Scoped original native body; a target fact is consumed only for its exact official request. */
63
69
  nativeApproval(request: Request, service: Context["approval"]): Promise<Outcome>;
@@ -28,8 +28,13 @@ export class PermissionControl {
28
28
  this.ctx = ctx;
29
29
  this.collaborators = collaborators;
30
30
  }
31
- async compose(exec, registration, entry, action, next, cwd) {
32
- const nativeOnly = nativeStandingFullAccess(this.ctx, exec.agent);
31
+ async compose(exec, registration, entry, action, next, cwd, simple = false) {
32
+ const previous = this.bindings.get(exec.token);
33
+ if (simple && previous?.simple) {
34
+ this.checkIntegrity(previous);
35
+ return this.composeDecision(previous, next, false);
36
+ }
37
+ const nativeOnly = !simple && nativeStandingFullAccess(this.ctx, exec.agent);
33
38
  const authority = nativeOnly ? undefined : this.collaborators.current(exec);
34
39
  if (authority !== undefined) {
35
40
  registration.assertCurrent?.(exec);
@@ -42,25 +47,29 @@ export class PermissionControl {
42
47
  if (authority === undefined)
43
48
  return;
44
49
  const current = this.collaborators.current(exec);
45
- if (current.agent !== authority.agent || current.root !== authority.root || current.realm !== authority.realm
50
+ if (current.signal.aborted || current.agent !== authority.agent || current.root !== authority.root || current.realm !== authority.realm
46
51
  || current.owner !== authority.owner || current.ownerGeneration !== authority.ownerGeneration)
47
52
  throw new PermissionRefusal("not-owned");
48
53
  } };
49
54
  const args = exec.arguments;
50
55
  const officialMode = !nativeOnly && (args.sandbox_permissions === "workspace-write" || args.sandbox_permissions === "danger-full-access") ? args.sandbox_permissions : undefined;
51
56
  const standing = registration.standingMode(exec);
52
- const target = officialMode ?? (entry === undefined ? undefined : isSandboxWidening(entry.sandboxMode, standing) ? entry.sandboxMode : standing ?? entry.sandboxMode);
57
+ const target = simple ? "danger-full-access" : officialMode ?? (entry === undefined ? undefined : isSandboxWidening(entry.sandboxMode, standing) ? entry.sandboxMode : standing ?? entry.sandboxMode);
53
58
  const reason = `DSMM command: ${String(args.command)}\nWorking directory: ${cwd}\nSandbox mode: ${target ?? "native standing policy"}. ${target === "danger-full-access" ? "Command execution may write outside the workspace to any OS-permitted location; this is not a cache-only or path-whitelist grant." : "Exact native tool invocation under the stated native sandbox policy."}`;
54
59
  const lifetime = new AbortController();
55
60
  const binding = { exec, args: exec.arguments, agent: exec.agent, callId: exec.callId, name: exec.name,
56
- registration, root: authority?.root, integrity, entry, officialMode,
61
+ registration, root: authority?.root, integrity, entry, officialMode, simple,
57
62
  target: target === "workspace-write" || target === "danger-full-access" ? target : undefined,
58
- reason, ask: action === "ask" || entry?.mode === "ask", lifetime,
63
+ reason, ask: !simple && (action === "ask" || entry?.mode === "ask"), lifetime,
59
64
  signal: AbortSignal.any([exec.signal, lifetime.signal, this.lifetime.signal,
60
65
  ...integrity.signal === undefined ? [] : [integrity.signal], ...registration.signal === undefined ? [] : [registration.signal]]),
61
66
  entered: false, nativeRequest: false };
62
67
  this.checkIntegrity(binding);
63
68
  this.bindings.set(exec.token, binding);
69
+ return this.composeDecision(binding, next, nativeOnly);
70
+ }
71
+ async composeDecision(binding, next, nativeOnly) {
72
+ const { exec, registration, entry, officialMode, reason } = binding;
64
73
  const downstream = await next();
65
74
  if (exec.signal.aborted)
66
75
  return { kind: "cancel" };
@@ -80,8 +89,8 @@ export class PermissionControl {
80
89
  const approval = registration.approval();
81
90
  if (approval === undefined || exec.agent === undefined)
82
91
  return { kind: "deny", reason: "Native approval is unavailable for this command." };
83
- const outcome = await approval.request({ agent: exec.agent, callId: exec.callId, toolName: exec.name,
84
- reason: reasons, displayReason, signal: binding.signal });
92
+ const request = { agent: exec.agent, callId: exec.callId, toolName: exec.name, reason: reasons, displayReason, signal: binding.signal };
93
+ const outcome = binding.simple ? await this.request(binding, request, approval, true) : await approval.request(request);
85
94
  if (exec.signal.aborted)
86
95
  return { kind: "cancel" };
87
96
  this.checkIntegrity(binding);
@@ -95,10 +104,11 @@ export class PermissionControl {
95
104
  throw new HarnessError("Permission-controlled call cancelled.", TOOL_ABORTED);
96
105
  const { exec, registration } = binding;
97
106
  if (exec.arguments !== binding.args || exec.agent !== binding.agent || exec.callId !== binding.callId || exec.name !== binding.name
98
- || !registration.active || !registration.unchanged() || registration.definition.execute !== registration.body
107
+ || !registration.active || !registration.unchanged() || registration.definition.execute !== (registration.wrapper ?? registration.body)
99
108
  || this.ctx.tools.get(binding.name, binding.agent) !== registration.registered)
100
109
  throw new PermissionRefusal("stale");
101
110
  binding.integrity.assertCurrent();
111
+ registration.assertIntegrity?.(exec);
102
112
  }
103
113
  guard(exec) {
104
114
  const binding = this.bindings.get(exec.token);
@@ -114,13 +124,31 @@ export class PermissionControl {
114
124
  }
115
125
  async answerer(request, next) {
116
126
  const owned = this.requests.get(request);
117
- if (owned === undefined)
118
- return next();
127
+ if (owned === undefined) {
128
+ const binding = this.execution.getStore();
129
+ if (binding === undefined || !binding.simple || binding.nativeRequest || request.agent !== binding.agent
130
+ || request.callId !== binding.callId || request.toolName !== binding.name || request.signal !== binding.signal)
131
+ return next();
132
+ this.checkIntegrity(binding);
133
+ binding.nativeRequest = true;
134
+ binding.approvedTarget = binding.target;
135
+ return "allowed-once";
136
+ }
119
137
  this.checkIntegrity(owned.binding);
120
138
  return owned.allow ? "allowed-once" : permissionOutcome(next, owned.binding.signal, "cancelled");
121
139
  }
140
+ isSimple(exec) {
141
+ const binding = this.bindings.get(exec.token);
142
+ if (binding?.simple !== true)
143
+ return false;
144
+ this.checkIntegrity(binding);
145
+ return true;
146
+ }
147
+ pending(registration) { return [...this.bindings.values()].some(binding => binding.registration === registration); }
122
148
  async run(exec, args, registration, body) {
123
149
  const binding = this.bindings.get(exec.token);
150
+ if (binding === undefined && registration.simpleOnly)
151
+ return body(exec.signal, args);
124
152
  if (binding === undefined || binding.registration !== registration || binding.entered || args !== binding.args)
125
153
  throw new PermissionRefusal("stale");
126
154
  binding.signal = AbortSignal.any([binding.signal, exec.signal]);
@@ -142,7 +170,8 @@ export class PermissionControl {
142
170
  }
143
171
  binding.mode = binding.approvedTarget;
144
172
  }
145
- return await this.execution.run(binding, () => body(binding.signal));
173
+ return await this.execution.run(binding, () => body(binding.signal, binding.simple ? Object.freeze({ ...args,
174
+ sandbox_permissions: "danger-full-access", justification: binding.reason }) : args));
146
175
  }
147
176
  finally {
148
177
  this.finish(binding.exec);
@@ -162,6 +191,8 @@ export class PermissionControl {
162
191
  /** Scoped original native body; a target fact is consumed only for its exact official request. */
163
192
  async nativeApproval(request, service) {
164
193
  const binding = this.execution.getStore();
194
+ if (binding?.simple)
195
+ return service.request(request);
165
196
  if (binding === undefined || binding.officialMode === undefined || binding.nativeRequest || request.agent !== binding.agent
166
197
  || request.callId !== binding.callId || request.toolName !== binding.registration.definition.name || request.signal !== binding.signal)
167
198
  return service.request(request);
@@ -206,7 +237,10 @@ export class PermissionControl {
206
237
  revokeAgent(agent) { for (const binding of this.bindings.values())
207
238
  if (binding.agent === agent || binding.root === agent)
208
239
  this.finish(binding.exec); }
209
- retire() { this.lifetime.abort(); for (const binding of this.bindings.values())
210
- this.finish(binding.exec); }
240
+ retire() { this.lifetime.abort(); for (const binding of this.bindings.values()) {
241
+ binding.lifetime.abort();
242
+ binding.mode = undefined;
243
+ binding.approvedTarget = undefined;
244
+ } }
211
245
  }
212
246
  //# sourceMappingURL=permission-control.js.map
@@ -40,8 +40,12 @@ export declare class DsmmPermissionController extends Service {
40
40
  readonly rules: PermissionRulesRuntimeSync;
41
41
  private readonly registrations;
42
42
  private readonly toolRegistrations;
43
+ private readonly stockRegistrations;
43
44
  private readonly lifetime;
44
45
  constructor(ctx: Context, options: PermissionControllerOptions);
46
+ /** Admit this exact simple match through the existing per-call native approval binding. */
47
+ simpleCommandAllowed(exec: Readonly<ToolExecution>): Promise<boolean>;
48
+ private stockRegistration;
45
49
  /** Public in-process facts for DSMM consumers; requested/configured modes never grant access. */
46
50
  nativeAccess(exec: Readonly<ToolExecution>): NativePermissionAccess;
47
51
  /** Optional public injection also captures definitions registered before Core publishes this service. */
@@ -1,9 +1,9 @@
1
1
  import { Service } from "@deepseek-ai/cordis";
2
2
  import { HarnessError } from "@deepseek-ai/dsh-llm";
3
3
  import { TOOL_ABORTED } from "@deepseek-ai/dsh-tools";
4
- import { isSandboxWidening, PermissionControl, PermissionRefusal, permissionApprovalAdapter } from "./permission-control.js";
4
+ import { isSandboxWidening, PermissionControl, PermissionRefusal, permissionApprovalAdapter, permissionOriginal } from "./permission-control.js";
5
5
  import { classifyPermissionShell } from "./permission-shell.js";
6
- import { nativeCommandMatch } from "./permission-native-command.js";
6
+ import { nativeCommandMatch, simpleCommandMatch, simpleShellCommand, simpleShellDialect } from "./permission-native-command.js";
7
7
  import { NATIVE_PERMISSION_CAPABILITIES, registerNativePermissionRules } from "./permission-native-rules.js";
8
8
  import { nativeStandingFullAccess } from "./permission-native-access.js";
9
9
  export const PERMISSION_CONTROLLER_INJECT = ["tools", "agents"];
@@ -46,6 +46,7 @@ export class DsmmPermissionController extends Service {
46
46
  rules;
47
47
  registrations = new Map();
48
48
  toolRegistrations = new Map();
49
+ stockRegistrations = new Map();
49
50
  lifetime = new AbortController();
50
51
  constructor(ctx, options) {
51
52
  super(ctx, "dsmmPermissionController");
@@ -65,6 +66,7 @@ export class DsmmPermissionController extends Service {
65
66
  if (this.rules.status().mounted) {
66
67
  registerNativePermissionRules(ctx, {
67
68
  runtime: this.rules,
69
+ simpleCommandAllowed: exec => this.permissions.isSimple(exec),
68
70
  captureIntegrity: options.authority.captureIntegrity === undefined ? undefined : exec => options.authority.captureIntegrity(exec),
69
71
  identify: definition => {
70
72
  const managed = this.registrations.get(definition);
@@ -90,7 +92,7 @@ export class DsmmPermissionController extends Service {
90
92
  return { signal: current.signal, assertCurrent: () => options.authority.assertCurrent(current, exec) };
91
93
  },
92
94
  assertCurrent: exec => authority.assertCurrent(authority.current(exec), exec),
93
- managedShellDecision: async (exec, action, downstream) => {
95
+ managedShellDecision: async (exec, action, downstream, snapshot) => {
94
96
  const definition = ctx.tools.get(exec.name, exec.agent), managed = definition === undefined ? undefined : this.registrations.get(definition);
95
97
  if (managed === undefined)
96
98
  throw new PermissionRefusal("stale");
@@ -98,7 +100,7 @@ export class DsmmPermissionController extends Service {
98
100
  const full = nativeStandingFullAccess(ctx, exec.agent);
99
101
  if (full)
100
102
  return this.permissions.compose(exec, managed.registration, undefined, "inherit", downstream, workspace);
101
- const policy = this.rules.getPolicy().policy;
103
+ const policy = (snapshot ?? this.rules.getPolicy()).policy;
102
104
  const entry = nativeCommandMatch(policy.nativeCommands, managed.kind, managed.shell, exec.arguments, workspace);
103
105
  if (entry === "ambiguous")
104
106
  managed.scope.logger.warn("Ambiguous native command sandbox modes; retaining native execution policy.");
@@ -108,13 +110,144 @@ export class DsmmPermissionController extends Service {
108
110
  return this.permissions.compose(exec, managed.registration, entry === "ambiguous" ? undefined : entry, action, downstream, operation.workingDirectory);
109
111
  },
110
112
  });
113
+ ctx.on("tools/pre-execute", async (exec, next) => {
114
+ if (!await this.simpleCommandAllowed(exec))
115
+ return next();
116
+ const definition = ctx.tools.get(exec.name, exec.agent);
117
+ const registration = definition === undefined ? undefined : this.registrations.get(definition)?.registration ?? this.stockRegistrations.get(definition)?.registration;
118
+ if (registration === undefined)
119
+ throw new PermissionRefusal("stale");
120
+ return this.permissions.compose(exec, registration, undefined, "allow", next, exec.agent?.session.header.cwd ?? "", true);
121
+ }, { global: true, prepend: true });
111
122
  ctx.tools.guard(exec => this.permissions.guard(exec));
123
+ ctx.on("tools/execute", async (exec, next) => {
124
+ const denied = this.permissions.guard(exec);
125
+ if (denied !== undefined)
126
+ throw new PermissionRefusal("stale");
127
+ return next();
128
+ }, { global: true });
112
129
  ctx.on("approval/request", permissionApprovalAdapter(ctx, (request, next) => this.permissions.answerer(request, next)), { prepend: true, global: true });
113
- ctx.on("tools/result", exec => { this.permissions.finish(exec); }, { global: true });
130
+ ctx.on("tools/result", exec => {
131
+ this.permissions.finish(exec);
132
+ for (const stock of this.stockRegistrations.values())
133
+ if (!stock.registration.active)
134
+ stock.dispose();
135
+ }, { global: true });
114
136
  ctx.on("agent/disposed", ({ agent }) => { this.permissions.revokeAgent(agent); }, { global: true });
115
137
  }
116
138
  ctx.effect(() => () => this.retire());
117
139
  }
140
+ /** Admit this exact simple match through the existing per-call native approval binding. */
141
+ async simpleCommandAllowed(exec) {
142
+ if (this.permissions.isSimple(exec))
143
+ return true;
144
+ if (!this.rules.status().mounted || this.lifetime.signal.aborted || exec.agent === undefined)
145
+ return false;
146
+ const agent = exec.agent, realm = agent.ctx;
147
+ const resolveTools = () => agent.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent.ctx.get("tools");
148
+ const tools = resolveTools(), definition = tools?.get(exec.name, agent);
149
+ if (tools === undefined || definition === undefined)
150
+ return false;
151
+ const managed = this.registrations.get(definition);
152
+ const dialect = managed?.shell.dialect ?? simpleShellDialect(exec.name);
153
+ const command = managed === undefined ? simpleShellCommand(exec.arguments) : Reflect.get(exec.arguments, managed.shell.commandField);
154
+ if (dialect === undefined || typeof command !== "string")
155
+ return false;
156
+ const body = definition.execute, args = exec.arguments, name = exec.name, callId = exec.callId, signal = exec.signal;
157
+ const registry = agent.ctx.get("agents"), workspace = agent.session.header.cwd;
158
+ const checkCall = () => {
159
+ if (signal.aborted || exec.signal !== signal || this.lifetime.signal.aborted)
160
+ throw new PermissionRefusal("cancelled");
161
+ const liveTools = resolveTools(), liveRegistry = agent.ctx.get("agents");
162
+ const stock = this.stockRegistrations.get(definition)?.registration;
163
+ const sameBody = definition.execute === body || stock?.active === true && stock.body === body
164
+ && definition.execute === stock.wrapper && stock.unchanged();
165
+ if (exec.agent !== agent || agent.ctx !== realm || registry === undefined || liveRegistry === undefined
166
+ || permissionOriginal(liveRegistry) !== permissionOriginal(registry) || liveRegistry.get(agent.id) !== agent
167
+ || exec.arguments !== args || exec.name !== name || exec.callId !== callId || agent.session.header.cwd !== workspace
168
+ || liveTools === undefined || permissionOriginal(liveTools) !== permissionOriginal(tools)
169
+ || tools.get(name, agent) !== definition || liveTools.get(name, agent) !== definition || !sameBody)
170
+ throw new PermissionRefusal("stale");
171
+ };
172
+ // Capture before refresh, but do not impose new gates on calls which never use simple.
173
+ let authority, failure;
174
+ try {
175
+ authority = this.options.authority.current(exec);
176
+ this.options.authority.assertCurrent(authority, exec);
177
+ }
178
+ catch (error) {
179
+ failure = error;
180
+ }
181
+ let snapshot;
182
+ try {
183
+ snapshot = await this.rules.refresh();
184
+ }
185
+ catch {
186
+ return false;
187
+ }
188
+ if (!simpleCommandMatch(snapshot.policy.nativeCommands, command, dialect))
189
+ return false;
190
+ if (failure !== undefined)
191
+ throw failure;
192
+ if (authority === undefined)
193
+ throw new PermissionRefusal("not-owned");
194
+ checkCall();
195
+ this.options.authority.assertCurrent(authority, exec);
196
+ const registration = managed?.registration ?? this.stockRegistration(definition, tools);
197
+ await this.permissions.compose(exec, registration, undefined, "allow", async () => ({ kind: "allow" }), workspace ?? "", true);
198
+ return true;
199
+ }
200
+ stockRegistration(definition, tools) {
201
+ const previous = this.stockRegistrations.get(definition);
202
+ if (previous?.registration.active && previous.registration.unchanged())
203
+ return previous.registration;
204
+ previous?.dispose();
205
+ if (this.stockRegistrations.has(definition))
206
+ throw new PermissionRefusal("stale");
207
+ const body = definition.execute, fields = Object.getOwnPropertyDescriptors(definition), outputFields = Object.getOwnPropertyDescriptors(definition.output);
208
+ const parameters = JSON.stringify(definition.parameters), outputSchema = JSON.stringify(definition.output.schema);
209
+ let registration, stock;
210
+ const wrapper = async (args, exec) => {
211
+ try {
212
+ return await this.permissions.run(exec, args, registration, async (signal, bodyArgs) => {
213
+ const value = await body.call(definition, bodyArgs, Object.freeze({ ...exec, signal,
214
+ deferContext: exec.deferContext.bind(exec), concludeTurn: exec.concludeTurn.bind(exec) }));
215
+ if (signal.aborted)
216
+ throw new HarnessError("Permission-controlled tool execution was cancelled.", TOOL_ABORTED);
217
+ return value;
218
+ });
219
+ }
220
+ finally {
221
+ if (!registration.active)
222
+ stock.dispose();
223
+ }
224
+ };
225
+ Object.defineProperty(definition, "execute", { ...fields.execute, value: wrapper });
226
+ const wrappedFields = Object.getOwnPropertyDescriptors(definition);
227
+ registration = { definition, registered: definition, body, wrapper, identity: Object.freeze({}), active: true, simpleOnly: true,
228
+ signal: this.lifetime.signal, approval: () => this.ctx.get("approval"),
229
+ standingMode: exec => this.ctx.get("sandboxPolicy")?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session }).mode,
230
+ unchanged: () => unchangedFields(definition, wrappedFields) && unchangedFields(definition.output, outputFields)
231
+ && JSON.stringify(definition.parameters) === parameters && JSON.stringify(definition.output.schema) === outputSchema,
232
+ assertIntegrity: exec => {
233
+ const agent = exec.agent;
234
+ const visible = agent?.ctx.get("agentPresets")?.serviceFor(agent, "tools") ?? agent?.ctx.get("tools") ?? tools;
235
+ if (permissionOriginal(visible) !== permissionOriginal(tools) || visible.get(exec.name, agent) !== definition)
236
+ throw new PermissionRefusal("stale");
237
+ },
238
+ };
239
+ stock = { registration, dispose: () => {
240
+ this.permissions.revokeRegistration(registration);
241
+ if (this.permissions.pending(registration))
242
+ return;
243
+ if (definition.execute === wrapper)
244
+ Object.defineProperty(definition, "execute", fields.execute);
245
+ if (this.stockRegistrations.get(definition) === stock)
246
+ this.stockRegistrations.delete(definition);
247
+ } };
248
+ this.stockRegistrations.set(definition, stock);
249
+ return registration;
250
+ }
118
251
  /** Public in-process facts for DSMM consumers; requested/configured modes never grant access. */
119
252
  nativeAccess(exec) {
120
253
  const mode = this.permissions.approvedTarget(exec);
@@ -226,8 +359,8 @@ export class DsmmPermissionController extends Service {
226
359
  throw new PermissionRefusal("unavailable");
227
360
  let registration;
228
361
  const wrapper = async (args, exec) => {
229
- return this.permissions.run(exec, args, registration, async (signal) => {
230
- const value = await body.call(definition, args, Object.freeze({ ...exec, signal,
362
+ return this.permissions.run(exec, args, registration, async (signal, bodyArgs) => {
363
+ const value = await body.call(definition, bodyArgs, Object.freeze({ ...exec, signal,
231
364
  deferContext: exec.deferContext.bind(exec), concludeTurn: exec.concludeTurn.bind(exec) }));
232
365
  if (signal.aborted)
233
366
  throw new HarnessError("Permission-controlled tool execution was cancelled.", TOOL_ABORTED);
@@ -306,6 +439,8 @@ export class DsmmPermissionController extends Service {
306
439
  managed.dispose();
307
440
  for (const managed of [...this.toolRegistrations.values()])
308
441
  managed.dispose();
442
+ for (const stock of [...this.stockRegistrations.values()])
443
+ stock.dispose();
309
444
  }
310
445
  }
311
446
  /** Parent supplies the real existing Core collaborators and A's sole runtime-sync owner. */
@@ -5,6 +5,10 @@ export declare function parseHostNativeCommands(input?: unknown): NativeCommands
5
5
  /** Finite literal grammar: ASCII blanks, bare literal tokens, and static quotes.
6
6
  * POSIX quote fragments concatenate; PowerShell quotes must enclose a whole operand.
7
7
  * Unsupported syntax retains the ordinary native path. */
8
- export declare function literalCommand(command: string, dialect: PermissionShellIdentity["dialect"]): readonly string[] | undefined;
8
+ export declare function literalCommand(command: string, dialect: PermissionShellIdentity["dialect"], mode?: "legacy" | "simple"): readonly string[] | undefined;
9
9
  export declare function nativeCommandMatch(settings: NativeCommandsSettings, tool: "bash" | "pwsh", identity: PermissionShellIdentity, args: unknown, workspace: string): NativeCommandEntry | "ambiguous" | undefined;
10
+ export declare function simpleShellDialect(name: string): PermissionShellIdentity["dialect"] | undefined;
11
+ export declare function simpleShellCommand(args: unknown): string | undefined;
12
+ /** A simple hit carries no legacy entry, cwd grant, read trust or sandbox target. */
13
+ export declare function simpleCommandMatch(settings: NativeCommandsSettings, command: string, dialect: PermissionShellIdentity["dialect"]): boolean;
10
14
  //# sourceMappingURL=permission-native-command.d.ts.map
@@ -1,10 +1,12 @@
1
1
  import { isAbsolute, normalize, parse, resolve } from "node:path";
2
- import { parseNativeCommandPattern, parseNativeCommands } from "./permission-settings.js";
2
+ import { parseNativeCommandPattern, parseNativeCommands, parseSimpleCommandPattern } from "./permission-settings.js";
3
3
  import { PermissionRefusal } from "./permission-errors.js";
4
4
  /** Host-only validation: Windows drive-relative roots never authorize an enhancement. */
5
5
  export function parseHostNativeCommands(input = {}) {
6
6
  const settings = parseNativeCommands(input);
7
7
  return Object.freeze({ enabled: settings.enabled, entries: Object.freeze(settings.entries.map(entry => {
8
+ if (typeof entry === "string")
9
+ return entry;
8
10
  const cwd = entry.match.workingDirectory;
9
11
  if (!isAbsolute(cwd) || process.platform === "win32" && parse(normalize(cwd)).root.length === 1)
10
12
  throw new PermissionRefusal("validation");
@@ -14,7 +16,7 @@ export function parseHostNativeCommands(input = {}) {
14
16
  /** Finite literal grammar: ASCII blanks, bare literal tokens, and static quotes.
15
17
  * POSIX quote fragments concatenate; PowerShell quotes must enclose a whole operand.
16
18
  * Unsupported syntax retains the ordinary native path. */
17
- export function literalCommand(command, dialect) {
19
+ export function literalCommand(command, dialect, mode = "legacy") {
18
20
  if (/[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u2018-\u201f]/u.test(command) || command.includes("--%"))
19
21
  return undefined;
20
22
  const words = [];
@@ -34,7 +36,7 @@ export function literalCommand(command, dialect) {
34
36
  quote = "";
35
37
  }
36
38
  }
37
- else if ((dialect === "powershell" && char === '"') || (quote === '"' && (char === "$" || char === "`")))
39
+ else if ((dialect === "powershell" && char === '"' && mode === "legacy") || (quote === '"' && (char === "$" || char === "`")))
38
40
  return undefined;
39
41
  else if (char === "\\" && dialect === "posix" && quote === '"' && /[\\$`"]/u.test(command[index + 1] ?? ""))
40
42
  return undefined;
@@ -67,7 +69,9 @@ export function literalCommand(command, dialect) {
67
69
  if (started)
68
70
  words.push(word);
69
71
  if (!words.length || words[0] === "" || words[0].includes("=") || dialect === "powershell" && /^(?:[\d+\-]|\.\d)/u.test(words[0])
70
- || /^(?:\.|eval|exec|invoke-expression|iex|cmd(?:\.exe)?|pwsh(?:\.exe)?|powershell(?:\.exe)?|bash|sh|zsh|env|sudo|node(?:\.exe)?|python[\d.]*(?:\.exe)?|command|builtin|time|if|then|elif|elseif|else|fi|for|foreach|while|until|do|done|case|esac|in|function|select|coproc|return|throw|exit|break|continue|trap|switch|try|catch|finally|class|enum|using|param|dynamicparam|filter|data|begin|process|end|configuration|workflow|parallel|sequence|default|define|from|var)$/iu.test(words[0].replace(/^.*[\\/]/u, "")))
72
+ || (mode === "legacy"
73
+ ? /^(?:\.|eval|exec|invoke-expression|iex|cmd(?:\.exe)?|pwsh(?:\.exe)?|powershell(?:\.exe)?|bash|sh|zsh|env|sudo|node(?:\.exe)?|python[\d.]*(?:\.exe)?|command|builtin|time|if|then|elif|elseif|else|fi|for|foreach|while|until|do|done|case|esac|in|function|select|coproc|return|throw|exit|break|continue|trap|switch|try|catch|finally|class|enum|using|param|dynamicparam|filter|data|begin|process|end|configuration|workflow|parallel|sequence|default|define|from|var)$/iu
74
+ : /^(?:\.|time|if|then|elif|elseif|else|fi|for|foreach|while|until|do|done|case|esac|in|function|select|coproc|return|throw|exit|break|continue|trap|switch|try|catch|finally|class|enum|using|param|dynamicparam|filter|data|begin|process|end|configuration|workflow|parallel|sequence|default|define|from|var)$/iu).test(mode === "legacy" ? words[0].replace(/^.*[\\/]/u, "") : words[0]))
71
75
  return undefined;
72
76
  return Object.freeze(words);
73
77
  }
@@ -81,7 +85,9 @@ export function nativeCommandMatch(settings, tool, identity, args, workspace) {
81
85
  const words = literalCommand(command, identity.dialect);
82
86
  if (words === undefined)
83
87
  return undefined;
84
- const matches = parseHostNativeCommands(settings).entries.filter(entry => {
88
+ const matches = parseHostNativeCommands(settings).entries.filter((entry) => {
89
+ if (typeof entry === "string")
90
+ return false;
85
91
  const match = entry.match;
86
92
  if (match.tool !== tool || normalize(match.workingDirectory) !== cwd)
87
93
  return false;
@@ -92,4 +98,28 @@ export function nativeCommandMatch(settings, tool, identity, args, workspace) {
92
98
  return "ambiguous";
93
99
  return matches.find(entry => entry.mode === "ask") ?? matches[0];
94
100
  }
101
+ export function simpleShellDialect(name) {
102
+ const lower = name.toLowerCase();
103
+ return ["bash", "sh", "zsh"].includes(lower) ? "posix" : ["pwsh", "powershell"].includes(lower) ? "powershell" : undefined;
104
+ }
105
+ export function simpleShellCommand(args) {
106
+ if (args === null || typeof args !== "object" || Array.isArray(args))
107
+ return undefined;
108
+ for (const field of ["command", "cmd", "script"]) {
109
+ const value = Reflect.get(args, field);
110
+ if (typeof value === "string")
111
+ return value;
112
+ }
113
+ return undefined;
114
+ }
115
+ /** A simple hit carries no legacy entry, cwd grant, read trust or sandbox target. */
116
+ export function simpleCommandMatch(settings, command, dialect) {
117
+ if (!settings.enabled)
118
+ return false;
119
+ const words = literalCommand(command, dialect, "simple");
120
+ if (words === undefined)
121
+ return false;
122
+ const executable = (value) => dialect === "powershell" ? value.replace(/\.exe$/iu, "") : value;
123
+ return settings.entries.some(entry => typeof entry === "string" && parseSimpleCommandPattern(entry).every((alternatives, index) => words[index] !== undefined && alternatives.some(value => index === 0 ? executable(value) === executable(words[0]) : value === words[index])));
124
+ }
95
125
  //# sourceMappingURL=permission-native-command.js.map
@@ -2,7 +2,7 @@ import type { Context } from "@deepseek-ai/cordis";
2
2
  import type { PreToolDecision, ToolDefinition, ToolExecution } from "@deepseek-ai/dsh-tools";
3
3
  import type { PermissionExecutionIntegrity } from "./permission-control.js";
4
4
  import type { PermissionShellIdentity } from "./permission-shell.js";
5
- import type { PermissionRulesRuntimeSync } from "./permission-rules.js";
5
+ import type { PermissionRuleSnapshot, PermissionRulesRuntimeSync } from "./permission-rules.js";
6
6
  import type { PermissionRulesStatus } from "./permission-rules.js";
7
7
  import type { PermissionRuleAction } from "./permission-settings.js";
8
8
  export interface NativePermissionFsTarget {
@@ -35,6 +35,7 @@ interface NativePermissionAuthority {
35
35
  }
36
36
  export interface NativePermissionRulesOptions {
37
37
  readonly runtime: PermissionRulesRuntimeSync;
38
+ simpleCommandAllowed?(execution: Readonly<ToolExecution>): boolean;
38
39
  captureIntegrity?(execution: Readonly<ToolExecution>): PermissionExecutionIntegrity;
39
40
  /** Exact registration identity, never trust a matching tool name alone. */
40
41
  identify(definition: ToolDefinition, execution: Readonly<ToolExecution>): NativePermissionToolIdentity | undefined;
@@ -43,7 +44,7 @@ export interface NativePermissionRulesOptions {
43
44
  /** Pure restriction fallback for standalone consumers without an authority capture. */
44
45
  assertCurrent(execution: Readonly<ToolExecution>): void;
45
46
  /** Compose this exact registration's native request; never creates an independent approval UI. */
46
- managedShellDecision?(execution: Readonly<ToolExecution>, action: Exclude<PermissionRuleAction, "deny">, downstream: () => Promise<PreToolDecision>): Promise<PreToolDecision>;
47
+ managedShellDecision?(execution: Readonly<ToolExecution>, action: Exclude<PermissionRuleAction, "deny">, downstream: () => Promise<PreToolDecision>, snapshot: PermissionRuleSnapshot | undefined): Promise<PreToolDecision>;
47
48
  }
48
49
  /** The public native search tools accept pattern/path/include only; no model-controlled rg flags. */
49
50
  export declare function parseNativePermissionReadPaths(kind: "read" | "glob" | "grep", input: unknown): readonly string[];
@@ -188,6 +188,8 @@ export function registerNativePermissionRules(ctx, options) {
188
188
  return intersectPermissionActions([access, ...rules]);
189
189
  };
190
190
  const unhook = ctx.on("tools/pre-execute", async (exec, next) => {
191
+ if (options.simpleCommandAllowed?.(exec))
192
+ return next();
191
193
  const definition = tools.get(exec.name, exec.agent);
192
194
  if (definition === undefined)
193
195
  return next();
@@ -226,7 +228,7 @@ export function registerNativePermissionRules(ctx, options) {
226
228
  if (action === "deny")
227
229
  return { kind: "deny", reason: "DSMM native permission rule denied this tool call." };
228
230
  if (identity.kind === "shell" && options.managedShellDecision !== undefined)
229
- return options.managedShellDecision(exec, action, next);
231
+ return options.managedShellDecision(exec, action, next, snapshot);
230
232
  const downstream = await next();
231
233
  if (exec.signal.aborted)
232
234
  return { kind: "cancel" };