dsh-codex-style-computer-use 2.2.9 → 2.3.0

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 CHANGED
@@ -179,13 +179,35 @@ For a host that reports a disabled-prompt automatic refusal as “the user rejec
179
179
  | Mode | Observation | Actuation |
180
180
  |---|---|---|
181
181
  | `read-only` | allowed | denied |
182
- | `standard` | allowed | every action asks through the host's approval card |
182
+ | `standard` | allowed | every action asks through the host's approval card (with no card available it refuses) |
183
183
  | `autonomous` | allowed | allowed, high-risk operations still ask |
184
184
  | `unrestricted` | allowed | allowed (worker failsafe and rate limit still apply) |
185
185
 
186
- High-risk operations (closing a window, `alt+f4`, `win+r`, and the like) ask in every mode. Password
186
+ High-risk operations (closing a window, `alt+f4`, `win+r`, and the like) ask in every mode — as long
187
+ as the session can show a card; the full-access case is described below. Password
187
188
  fields are detected through UI Automation's `IsPassword` and refused by default.
188
189
 
190
+ **An ask is only honoured when the session can actually ask.** The host reports a per-session
191
+ approval policy; its `danger-full-access` preset selects `never`, where no card can be shown and
192
+ every `ask` is auto-rejected. The plugin therefore settles its own asks instead of forwarding an
193
+ unanswerable one:
194
+
195
+ - `autonomous` + proven full access: the high-risk action runs under the human's standing grant
196
+ (recorded as `escalated:"full-access"` in `policy.jsonl`).
197
+ - `standard`: refuses and says so. Full access is not an approval, and the mode's contract is
198
+ per-action consent — raise `automationMode` to `autonomous` if that is what you want.
199
+ - a delegated subagent session: refuses. `@deepseek-ai/dsh-subagent` pins `never` on every child
200
+ and copies the parent's sandbox, so neither fact is the human's grant.
201
+ - any sandbox without proven full access: refuses with an explicit
202
+ `approval prompts are unavailable in this session (approval policy: never)` reason that says
203
+ nothing ran and the user was not asked.
204
+
205
+ The host's legacy `the user rejected tool "…"` wording is corrected for `computer_*` calls, so an
206
+ automatic refusal is never reported as a human decision. Whenever a card can be shown, `standard`
207
+ and `autonomous` ask exactly as before. Gate diagnostics land in
208
+ `$DSH_HOME/data/computer-use/policy.jsonl` (modes, channel, verdict; launch URLs are redacted;
209
+ no typed text).
210
+
189
211
  ## Safety model
190
212
 
191
213
  - **Shared input** — ordinary user activity is allowed while the agent is thinking, observing or preparing. During actual actuation, typing, scrolling and buttons yield immediately; pointer movement has a 16-pixel displacement tolerance. Continued input or a held key/button for 2 seconds enters automatic waiting. After release and 3 quiet seconds, the agent must inspect the current target and continue the original task, without blindly replaying partial writes. A gentle pale-yellow edge gradient shows human ownership.
package/README.zh.md CHANGED
@@ -170,12 +170,29 @@ ID**:派发输入前会核对窗口身份与采样像素,因此过期的 mar
170
170
  | 模式 | 观察 | 操作 |
171
171
  |---|---|---|
172
172
  | `read-only` | 允许 | 拒绝 |
173
- | `standard` | 允许 | 每个动作都经宿主审批卡确认 |
173
+ | `standard` | 允许 | 每个动作都经宿主审批卡确认(无卡可用时拒绝) |
174
174
  | `autonomous` | 允许 | 允许,高危动作仍需确认 |
175
175
  | `unrestricted` | 允许 | 允许(worker 自身的失效保护与限速仍在) |
176
176
 
177
- 高危动作(关闭窗口、`alt+f4`、`win+r` 等)在任何模式下都要确认。
178
- 密码框通过 UI Automation 的 `IsPassword` 识别,默认拒绝输入。
177
+ 高危动作(关闭窗口、`alt+f4`、`win+r` 等)在任何模式下都要确认——前提是当前会话真的能弹卡;
178
+ 完全权限下的情形见下。密码框通过 UI Automation 的 `IsPassword` 识别,默认拒绝输入。
179
+
180
+ **只有在当前会话真的能弹卡时,`ask` 才会被交给宿主。** 宿主按会话给出审批策略;`danger-full-access`
181
+ 预设选的是 `never`,此时弹不出任何卡片,任何 `ask` 都会被自动拒绝。插件因此自己裁决这个 ask,而不是
182
+ 把一个无人可答的请求转发下去:
183
+
184
+ - `autonomous` + 已证实完全权限:高危动作按人的既有授权直接执行(`policy.jsonl` 记为
185
+ `escalated:"full-access"`)。
186
+ - `standard`:拒绝并说明原因。完全权限不是一次审批,而这个模式的契约是「逐次同意」;确实要放行,
187
+ 请把 `automationMode` 提到 `autonomous`。
188
+ - 被委派的 subagent 会话:拒绝。`@deepseek-ai/dsh-subagent` 给每个子会话钉死 `never` 并复制父会话
189
+ 沙箱,这两件事都不是人给的授权。
190
+ - 任何没有「已证实完全权限」的沙箱:明确拒绝,理由写明「本会话审批弹窗不可用(审批策略 `never`),
191
+ 没有执行任何动作,也没有询问用户」。
192
+
193
+ 宿主那句遗留的「the user rejected tool "…"」对 `computer_*` 调用会被改写,因此自动拒绝不会再被写成
194
+ 人的决定。只要还能弹卡,`standard` 与 `autonomous` 照旧询问。门禁诊断落在
195
+ `$DSH_HOME/data/computer-use/policy.jsonl`(模式、通道、裁决;启动 URL 已脱敏;不记录输入文本)。
179
196
 
180
197
  ## 安全模型
181
198
 
package/cordis.patch.yml CHANGED
@@ -6,6 +6,12 @@
6
6
  # (click / type / key / drag / scroll / clipboard write) goes through the host's approval card.
7
7
  # Raise it to `autonomous` (high-risk operations still ask) or `unrestricted` deliberately, in
8
8
  # Settings → computer-use, once you have decided the machine may be driven without a prompt.
9
+ #
10
+ # If the session's approval policy is `never` (DSH selects it for the danger-full-access preset)
11
+ # there is no card to show. `standard` then refuses rather than running, because full access is
12
+ # not an approval; `autonomous` runs the unanswerable high-risk ask under the full-access grant
13
+ # and records it as `escalated:"full-access"` in $DSH_HOME/data/computer-use/policy.jsonl. A
14
+ # delegated subagent session never inherits that grant.
9
15
  - insert:
10
16
  - id: computer-use
11
17
  name: dsh-codex-style-computer-use
@@ -1,39 +1,124 @@
1
1
  // Compatibility with hosts that conflate policy refusals and answerer refusals.
2
2
  // Delegate first so the host still owns every approval and durable audit pair.
3
+ //
4
+ // The host's `serviceAsk` maps a non-grant to a reason string. One of those strings —
5
+ // `the user rejected tool "X"` — is produced for BOTH a real human "no" and the deterministic
6
+ // auto-reject of the `never` approval policy, where no prompt was ever shown. This seam repairs
7
+ // the `never` case and only that wording: it runs only for computer_* tools, only after the host
8
+ // ran, and only by replacing the reason — the outcome, the borrowed signal and the
9
+ // approval/asked + approval/decided audit pair stay the host's. A rejection under the `ask`
10
+ // policy is left as a channel rejection without any claim about who answered (the answerer may
11
+ // be the human card or the Auto reviewer).
12
+ //
13
+ // 2026-11-12: the seam must also INSTALL reliably. A plugin applied before the tool registry is
14
+ // mounted has no `serviceAsk` to wrap, so it used to degrade to a warning in a log nobody reads
15
+ // and the misleading host wording reached the model. The registry is now also awaited through
16
+ // `ctx.inject`, installs are ref-counted per service (an out-of-order/FIFO unload can no longer
17
+ // leave a dead wrapper installed), and the returned status object (`installed` / `reason` /
18
+ // `rewrites`) is reported in the gate's own diagnostics so "seam never installed" is a visible
19
+ // fact rather than a guess.
20
+
21
+ const LEGACY_USER_REJECTION = /^the user rejected tool "([^"]*)"$/
22
+
23
+ // Identity that survives a TRACED PROXY. `ctx.get('tools')` hands out a fresh proxy on every
24
+ // call, so a WeakMap keyed on the object it returned can never dedupe two installs. The entry is
25
+ // carried on the wrapper function we install as the service's own `serviceAsk`, and read back
26
+ // through that property's DESCRIPTOR value — a plain function reference the proxy forwards — so
27
+ // two fibers wrapping one registry share one entry and restore it exactly once.
28
+ const OWNER = Symbol.for('dsh-computer-use.approval-attribution')
29
+
30
+ function installedEntry (tools) {
31
+ try {
32
+ const value = Object.getOwnPropertyDescriptor(tools, 'serviceAsk')?.value
33
+ return typeof value === 'function' && value[OWNER] ? value[OWNER] : null
34
+ } catch { return null }
35
+ }
36
+
37
+ /**
38
+ * One install leaves. The wrapper is removed only when the LAST install leaves, and only if the
39
+ * service still holds our wrapper — a host that replaced `serviceAsk` afterwards keeps its own.
40
+ */
41
+ function release (entry) {
42
+ entry.refs -= 1
43
+ if (entry.refs > 0) return
44
+ const tools = entry.tools
45
+ try {
46
+ if (Object.getOwnPropertyDescriptor(tools, 'serviceAsk')?.value !== entry.wrapped) return
47
+ if (entry.ownDescriptor) Object.defineProperty(tools, 'serviceAsk', entry.ownDescriptor)
48
+ else delete tools.serviceAsk
49
+ } catch { /* a failed restore must never break disposal */ }
50
+ }
51
+
3
52
  export function installApprovalAttribution (ctx, log) {
4
- const tools = ctx.get('tools')
5
- const original = tools?.serviceAsk
6
- if (typeof original !== 'function') {
7
- log.warn('approval attribution: host compatibility seam unavailable')
8
- return
9
- }
10
- const ownDescriptor = Object.getOwnPropertyDescriptor(tools, 'serviceAsk')
11
- const wrapped = async function (exec, ask) {
12
- let policy
13
- if (exec?.name?.startsWith('computer_') && exec.agent) {
14
- const approval = this.ctx?.get?.('approval')
15
- if (typeof approval?.effectivePolicy === 'function') policy = approval.effectivePolicy(exec.agent.session)
53
+ const state = { installed: false, reason: 'unknown', entry: null }
54
+ // `rewrites` follows whichever seam this install ended up sharing.
55
+ Object.defineProperty(state, 'rewrites', { get: () => state.entry?.rewrites ?? 0, enumerable: true })
56
+
57
+ const attach = (tools) => {
58
+ if (!tools || typeof tools.serviceAsk !== 'function') return false
59
+ const existing = installedEntry(tools)
60
+ if (existing) {
61
+ existing.refs += 1
62
+ ctx.effect(() => () => release(existing))
63
+ state.entry = existing
64
+ state.installed = true
65
+ state.reason = 'installed'
66
+ return true
16
67
  }
17
- const result = await original.call(this, exec, ask)
18
- // Newer/fixed hosts already provide their own reason. Only repair the exact
19
- // known legacy attribution; never reinterpret cancellation or a grant.
20
- if (!exec?.name?.startsWith('computer_') || result?.decision?.kind !== 'deny' ||
21
- result.decision.reason !== `the user rejected tool "${exec.name}"`) return result
22
- const reason = (policy === 'never'
23
- ? `tool "${exec.name}" requires approval, but approval prompts are disabled in this session (approval policy: never); the request was automatically rejected without asking the user`
24
- : `approval for tool "${exec.name}" was rejected by the approval channel`) +
25
- (ask?.reason ? `; approval required because: ${ask.reason}` : '')
26
- return { ...result, decision: { ...result.decision, reason } }
27
- }
28
- ctx.effect(() => {
29
- tools.serviceAsk = wrapped
30
- return () => {
31
- // Cordis returns a traced callable on get(); compare the stored method,
32
- // not that newly created callable, to identify our own replacement.
33
- if (Object.getOwnPropertyDescriptor(tools, 'serviceAsk')?.value !== wrapped) return
34
- if (ownDescriptor) Object.defineProperty(tools, 'serviceAsk', ownDescriptor)
35
- else delete tools.serviceAsk
68
+ const entry = { refs: 1, rewrites: 0, tools, original: tools.serviceAsk, ownDescriptor: Object.getOwnPropertyDescriptor(tools, 'serviceAsk'), wrapped: null }
69
+ entry.wrapped = async function (exec, ask) {
70
+ let policy = null
71
+ if (exec?.name?.startsWith('computer_') && exec.agent) {
72
+ // Every member read is guarded: a service whose getter throws must leave the policy
73
+ // unknown (say less), never reject the host's approval call.
74
+ try {
75
+ const approval = this.ctx?.get?.('approval')
76
+ const effectivePolicy = approval?.effectivePolicy
77
+ if (typeof effectivePolicy === 'function') policy = effectivePolicy.call(approval, exec.agent.session)
78
+ } catch { /* unknown policy: say less, not more */ }
79
+ }
80
+ const result = await entry.original.call(this, exec, ask)
81
+ if (!exec?.name?.startsWith('computer_') || result?.decision?.kind !== 'deny') return result
82
+ if (!LEGACY_USER_REJECTION.test(String(result.decision.reason ?? ''))) return result
83
+ entry.rewrites += 1
84
+ const reason = (policy === 'never'
85
+ ? `tool "${exec.name}" requires approval, but approval prompts are disabled in this session (approval policy: never); the request was automatically rejected without asking the user`
86
+ : `approval for tool "${exec.name}" was rejected by the approval channel`) +
87
+ (ask?.reason ? `; approval required because: ${ask.reason}` : '')
88
+ return { ...result, decision: { ...result.decision, reason } }
36
89
  }
37
- })
38
- log.info('approval attribution: installed for computer-use; host approvals and audit retained')
90
+ entry.wrapped[OWNER] = entry
91
+ ctx.effect(() => {
92
+ tools.serviceAsk = entry.wrapped
93
+ return () => release(entry)
94
+ })
95
+ state.entry = entry
96
+ state.installed = true
97
+ state.reason = 'installed'
98
+ log.info('approval attribution: installed for computer-use; host approvals and audit retained')
99
+ return true
100
+ }
101
+
102
+ let mounted = null
103
+ try { mounted = typeof ctx?.get === 'function' ? ctx.get('tools') : null } catch { mounted = null }
104
+ if (attach(mounted)) return state
105
+ // Not mounted yet: wait for the registry rather than warning into the void. `inject` runs the
106
+ // callback as soon as the service exists, including immediately when it already does; the
107
+ // reason is set BEFORE registering so a synchronous callback cannot be overwritten by it.
108
+ if (typeof ctx?.inject === 'function') {
109
+ state.reason = 'awaiting-tools'
110
+ try {
111
+ ctx.inject(['tools'], (child) => {
112
+ let tools = null
113
+ try { tools = child?.tools ?? (typeof child?.get === 'function' ? child.get('tools') : null) } catch { tools = null }
114
+ if (attach(tools)) return
115
+ state.reason = 'unavailable'
116
+ log.warn('approval attribution: tools service arrived without a serviceAsk seam')
117
+ })
118
+ return state
119
+ } catch { /* fall through to the warning */ }
120
+ }
121
+ state.reason = 'unavailable'
122
+ log.warn('approval attribution: host compatibility seam unavailable')
123
+ return state
39
124
  }
@@ -0,0 +1,178 @@
1
+ // approval-env.js — the approval-channel facts this gate is allowed to act on.
2
+ //
3
+ // WHY THIS MODULE EXISTS (measured, 2026-11-12)
4
+ // The policy gate used to answer `{kind:'ask'}` for a high-risk key in `autonomous` mode and
5
+ // hand it to the host. The host's approval service has two policies:
6
+ //
7
+ // * `ask` — an answerer may put a card in front of the human (the host logs approval/asked
8
+ // + approval/decided and routes it to the UI);
9
+ // * `never` — NOTHING is asked. `ApprovalService.decide()` returns `'rejected'` immediately,
10
+ // the tool layer maps that to `the user rejected tool "computer_key"`, and the
11
+ // model/human read a refusal that never happened. DSH selects this policy for the
12
+ // `danger-full-access` permission preset ("Full file access without approval
13
+ // prompts"), i.e. exactly the mode a human picks to say "stop asking me".
14
+ //
15
+ // So the plugin has to settle its OWN asks against the channel it actually has, which needs
16
+ // two facts about the CALLING session:
17
+ //
18
+ // 1. the effective APPROVAL POLICY (`ask` | `never`);
19
+ // 2. the effective SANDBOX MODE (`danger-full-access` is the human's explicit
20
+ // "this machine is pre-authorized" grant; see lib/policy.js applyApprovalChannel()).
21
+ //
22
+ // Reading them must never throw into the gate, and a service that is absent, remounted, or
23
+ // answers with an unknown shape leaves the fact UNKNOWN — unknown keeps the conservative path
24
+ // (`ask` stays `ask`), because guessing "full access" is the one guess that must never happen.
25
+ //
26
+ // The lookup is layered because a host may compose only some of these rows:
27
+ // sandbox : sandboxPolicy.resolve({session}).mode (authoritative, per session)
28
+ // → permissionPresets.permissionState(session).sandbox
29
+ // → the durable session record, NARROWING ONLY (lib/host-debug.js helper)
30
+ // approval : approval.effectivePolicy(session) (authoritative, per session)
31
+ //
32
+ // Both entering facts must be proven LIVE, because either one can widen what the machine does:
33
+ // "full access" suppresses a prompt, and "policy never" declares that no prompt can be shown.
34
+ // Two deliberate omissions follow from that:
35
+ // * `shell.sandboxMode` is NOT consulted. It is the DEPLOYMENT default, not the session's
36
+ // effective mode, so a host launched with full access would report full access for a session
37
+ // the human had switched back to workspace-write.
38
+ // * the durable session record may only NARROW the sandbox and is never read for the approval
39
+ // policy. It is a throttled cache (writeEveryEvents / writeIntervalMs), so right after
40
+ // switching away from full access it can still say "danger-full-access", and right after an
41
+ // approval-policy change it can still say "never"; a cache must never manufacture either
42
+ // grant, only remove one.
43
+ //
44
+ // `sources` names which layer answered, so a later failure is diagnosable from one log line.
45
+
46
+ export const SANDBOX_MODES = Object.freeze(['read-only', 'workspace-write', 'danger-full-access'])
47
+ export const APPROVAL_POLICIES = Object.freeze(['ask', 'never'])
48
+
49
+ const isSandboxMode = (value) => typeof value === 'string' && SANDBOX_MODES.includes(value)
50
+ const readService = (ctx, name) => {
51
+ try { return typeof ctx?.get === 'function' ? ctx.get(name) : undefined } catch { return undefined }
52
+ }
53
+
54
+ /**
55
+ * Resolve the approval-channel facts for one call.
56
+ * @param {object} request
57
+ * @param {object} [request.ctx] the plugin context; `get(name)` is optional and never trusted to throw
58
+ * @param {object|string|null} [request.session] the calling Agent's session object
59
+ * @param {string|null} [request.sessionId] the calling session id (disk fallback only)
60
+ * @param {((id: string|null) => object|null)|null} [request.durablePermission] optional disk reader
61
+ * @returns {{approvalPolicy: ('ask'|'never'|null), sandbox: (string|null),
62
+ * promptsAvailable: boolean, fullAccess: boolean, sources: string[]}}
63
+ */
64
+ export function readApprovalEnv ({ ctx, session = null, sessionId = null, durablePermission = null } = {}) {
65
+ const sources = []
66
+ let approvalPolicy = null
67
+ let sandbox = null
68
+ const usable = session !== null && session !== undefined
69
+
70
+ // Every member read goes through this: a service whose property GETTER throws must leave the
71
+ // fact unknown, not turn every computer_* call into "computer-use policy error" (that would be
72
+ // a fail-closed denial of working calls, i.e. a denial-of-service on the gate itself).
73
+ const member = (service, name) => {
74
+ try { return service == null ? undefined : service[name] } catch { return undefined }
75
+ }
76
+
77
+ const approval = readService(ctx, 'approval')
78
+ if (usable) {
79
+ const effectivePolicy = member(approval, 'effectivePolicy')
80
+ if (typeof effectivePolicy === 'function') {
81
+ try {
82
+ const policy = effectivePolicy.call(approval, session)
83
+ if (APPROVAL_POLICIES.includes(policy)) { approvalPolicy = policy; sources.push('approval.effectivePolicy') }
84
+ } catch { /* unknown policy keeps the conservative path */ }
85
+ }
86
+ }
87
+
88
+ const sandboxPolicy = readService(ctx, 'sandboxPolicy')
89
+ if (usable) {
90
+ const resolve = member(sandboxPolicy, 'resolve')
91
+ if (typeof resolve === 'function') {
92
+ try {
93
+ const mode = resolve.call(sandboxPolicy, { session })?.mode
94
+ if (isSandboxMode(mode)) { sandbox = mode; sources.push('sandboxPolicy.resolve') }
95
+ } catch { /* fall through to the next layer */ }
96
+ }
97
+ }
98
+
99
+ if (sandbox === null) {
100
+ const presets = readService(ctx, 'permissionPresets')
101
+ if (usable) {
102
+ const permissionState = member(presets, 'permissionState')
103
+ if (typeof permissionState === 'function') {
104
+ try {
105
+ const state = permissionState.call(presets, session)
106
+ if (isSandboxMode(state?.sandbox)) { sandbox = state.sandbox; sources.push('permissionPresets.permissionState') }
107
+ } catch { /* fall through */ }
108
+ }
109
+ }
110
+ }
111
+
112
+ if (sandbox === null && typeof durablePermission === 'function') {
113
+ try {
114
+ const record = durablePermission(sessionId)
115
+ // Narrowing only: a throttled cache may say "full access" after the human left it, so it
116
+ // can never be the evidence FOR an execution grant — only against one.
117
+ if (isSandboxMode(record?.sandbox) && record.sandbox !== 'danger-full-access') {
118
+ sandbox = record.sandbox
119
+ sources.push('session-record')
120
+ }
121
+ } catch { /* unknown stays unknown */ }
122
+ }
123
+
124
+ return {
125
+ approvalPolicy,
126
+ sandbox,
127
+ // No policy means no proof that prompts are unavailable: keep asking.
128
+ promptsAvailable: approvalPolicy !== 'never',
129
+ fullAccess: sandbox === 'danger-full-access',
130
+ // A delegated child inherits its parent's sandbox mode and has its approval policy pinned to
131
+ // `never` by @deepseek-ai/dsh-subagent. Neither fact is the human's grant: the human granted
132
+ // THIS conversation, not an arbitrary child that decides to drive the desktop on its own.
133
+ delegated: readDelegation(session),
134
+ sources,
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Is this session a delegated child rather than the human's own conversation?
140
+ *
141
+ * The header is the host's own durable identity (`@deepseek-ai/dsh-session` validates
142
+ * `origin: "subagent"`, `parentSession`, `delegationDepth`, `isSeeded`). Three real shapes exist:
143
+ *
144
+ * * the human's own session — no parent fields (`delegationDepth: 0`);
145
+ * * a delegated subagent child — `origin:"subagent"` + `delegationDepth: 1` + `parentSession`
146
+ * (all 260 child headers on this machine have all three);
147
+ * * a FORK of the human's own conversation (sidebar "fork") — `parentSession` + `isSeeded:true`
148
+ * and NO origin/delegationDepth. That is still the human's own
149
+ * conversation: it must keep the grant its parent had, not be
150
+ * refused as if a subagent had asked.
151
+ *
152
+ * So `origin`/`delegationDepth` decide, and a bare `parentSession` only counts as a child when
153
+ * the session is not seeded from its parent (the legacy child shape). A missing header on a live
154
+ * session cannot prove it is the human's, and is treated as delegated.
155
+ */
156
+ export function readDelegation (session) {
157
+ try {
158
+ if (session === null || session === undefined) return false
159
+ const header = session.header
160
+ if (header === null || header === undefined) return true
161
+ if (typeof header !== 'object') return true
162
+ if (header.origin === 'subagent') return true
163
+ const depth = header.delegationDepth
164
+ if (typeof depth === 'number' && Number.isFinite(depth) && depth > 0) return true
165
+ if (typeof header.parentSession === 'string' && header.parentSession.length > 0) {
166
+ return header.isSeeded !== true
167
+ }
168
+ return false
169
+ } catch { return true }
170
+ }
171
+
172
+ /** One-line, secret-free summary for logs and diagnostics. */
173
+ export function describeApprovalEnv (env) {
174
+ if (!env || typeof env !== 'object') return 'approval=? sandbox=?'
175
+ return `approval=${env.approvalPolicy ?? '?'} sandbox=${env.sandbox ?? '?'}` +
176
+ (env.delegated === true ? ' delegated' : '') +
177
+ (env.sources?.length ? ` (from ${env.sources.join('+')})` : '')
178
+ }
package/lib/audit.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // Every actuation the core emits lands here: {ts, op, args(redacted), result?|error?}.
3
3
  // Screenshots taken before risky ops (v1) will join the same stream.
4
4
 
5
- import { appendFileSync, mkdirSync, existsSync } from 'node:fs'
5
+ import { appendFileSync, mkdirSync, existsSync, renameSync, statSync } from 'node:fs'
6
6
  import { join } from 'node:path'
7
7
  import { homedir } from 'node:os'
8
8
  import { randomUUID } from 'node:crypto'
@@ -35,3 +35,64 @@ export function installAudit (cu, dataDir) {
35
35
  for (const event of events) cu.on(event, write)
36
36
  return () => { for (const event of events) cu.off(event, write) }
37
37
  }
38
+
39
+ // ---- gate diagnostics: WHO asked, WHO could have answered, WHAT was decided ------------------
40
+ // A separate stream from audit.jsonl on purpose: the actuation audit must keep its shape, and a
41
+ // policy question must stay answerable from a file the next report can attach. One line per
42
+ // gated call that reaches the decision (the procedure-gate deny and `acknowledge` return earlier
43
+ // by design), written after the decision, never containing typed text or clipboard contents.
44
+ // Bounded: past GATE_ROTATE_BYTES the stream becomes policy.jsonl.1 and a fresh file starts.
45
+ const GATE_ROTATE_BYTES = 4 * 1024 * 1024
46
+ export function appendGate (dataDir, rec) {
47
+ if (!dataDir || typeof dataDir.root !== 'string') return
48
+ try {
49
+ const file = join(dataDir.root, 'policy.jsonl')
50
+ try {
51
+ if (existsSync(file) && statSync(file).size > GATE_ROTATE_BYTES) renameSync(file, `${file}.1`)
52
+ } catch { /* a failed rotation must not lose the record we are about to append */ }
53
+ appendFileSync(file, JSON.stringify(rec) + '\n')
54
+ } catch { /* diagnostics must never break the decision */ }
55
+ }
56
+
57
+ // A launch target may be a URL carrying userinfo or a query token. The gate records and logs
58
+ // run through here, so neither the log line nor policy.jsonl can become a credential store.
59
+ const URL_SHAPE = /^([a-z][a-z0-9+.\-]*:\/\/)([^/?#]*)([^?#]*)([?#][\s\S]*)?$/i
60
+ function redactUrl (url) {
61
+ const match = URL_SHAPE.exec(url)
62
+ if (!match) return url
63
+ const authority = match[2].includes('@') ? match[2].slice(match[2].lastIndexOf('@') + 1) : match[2]
64
+ const tail = match[4] === undefined ? '' : (match[4][0] === '?' ? '?<redacted>' : '#<redacted>')
65
+ return `${match[1]}${authority}${match[3]}${tail}`
66
+ }
67
+ export function redactTarget (value) {
68
+ if (typeof value !== 'string') return value
69
+ return redactUrlTokens(value.slice(0, 400)).slice(0, 120)
70
+ }
71
+ /** Redact every URL-shaped token in free text: a target can embed one ("cmd https://u:p@h/?t=1"),
72
+ * and a decision reason quotes the target. */
73
+ const redactUrlTokens = (text) => text.replace(/[a-z][a-z0-9+.\-]*:\/\/[^\s"'<>)\]]+/gi, (token) => redactUrl(token))
74
+ export function redactReasonText (value) {
75
+ return typeof value === 'string' ? redactUrlTokens(value) : value
76
+ }
77
+
78
+ const GATE_ARG_KEYS = new Set(['combo', 'op', 'action', 'target', 'hwnd', 'button', 'clicks',
79
+ 'allowPassword', 'holdMs', 'mark', 'at', 'from', 'to', 'dir', 'lines', 'x', 'y', 'deltaX', 'deltaY'])
80
+
81
+ /** Argument summary safe to persist: identities, coordinates and lengths, never payload text.
82
+ * Every string goes through the URL redaction, so a URL stuffed into a coordinate field cannot
83
+ * smuggle credentials into the diagnostics either. */
84
+ export function gateArgSummary (name, args) {
85
+ const a = args || {}
86
+ const out = {}
87
+ for (const key of Object.keys(a)) {
88
+ if (!GATE_ARG_KEYS.has(key)) continue
89
+ const value = a[key]
90
+ if (key === 'target') out.target = redactTarget(value)
91
+ else if (typeof value === 'string') out[key] = redactUrlTokens(value).slice(0, 120)
92
+ else if (typeof value === 'number' || typeof value === 'boolean') out[key] = value
93
+ }
94
+ if (name === 'computer_type' && typeof a.text === 'string') out.textLength = a.text.length
95
+ if (name === 'computer_batch' && Array.isArray(a.actions)) out.steps = a.actions.length
96
+ return out
97
+ }
98
+
package/lib/index.js CHANGED
@@ -15,6 +15,12 @@ import { installHumanAttention } from './attention.js'
15
15
  // autonomous → actuation allowed except high-risk ops (still asks)
16
16
  // unrestricted → everything allowed (worker failsafe corner + rate limit remain)
17
17
  //
18
+ // `ask` is only honoured when the session CAN ask. Under the host's `never` approval policy —
19
+ // the one the danger-full-access preset selects — an ask is settled by policy.js instead:
20
+ // full access runs it under the human's standing grant, every other sandbox refuses and names
21
+ // the unavailable channel. It is never forwarded to a host that would answer `the user rejected
22
+ // tool "..."` on the user's behalf (measured 2026-11-12).
23
+ //
18
24
  // Two out-of-band behaviours live here rather than in the tool layer, because both are
19
25
  // triggered by things that happen while the MODEL is not calling anything:
20
26
  //
@@ -30,9 +36,10 @@ import { installHumanAttention } from './attention.js'
30
36
  import { defineTool } from '@deepseek-ai/dsh-tools'
31
37
  import Schema from '@deepseek-ai/schemastery'
32
38
  import { ComputerUse } from './core/index.js'
33
- import { policyDecision, HIGH_RISK_NOTE } from './policy.js'
39
+ import { policyDecision, HIGH_RISK_NOTE, ACTUATION_TOOLS } from './policy.js'
40
+ import { readApprovalEnv, describeApprovalEnv } from './approval-env.js'
34
41
  import { acknowledge, isAcked, ACK_HINT, isDrivingCall } from './skill-gate.js'
35
- import { mkDataDir, snapshotPath, installAudit } from './audit.js'
42
+ import { mkDataDir, snapshotPath, installAudit, appendGate, gateArgSummary, redactReasonText } from './audit.js'
36
43
  import { registerTools, isCycleStateOnly } from './tools.js'
37
44
  import { installToolExposure, ACTIVATION_TOOL } from './exposure.js'
38
45
  import { scopeOf } from '@deepseek-ai/dsh-scope'
@@ -503,7 +510,10 @@ export function apply (ctx, config) {
503
510
  return
504
511
  }
505
512
  if (!config.enabled) return
506
- installApprovalAttribution(ctx, log)
513
+ // Kept in scope: the gate's diagnostics report whether the legacy-attribution seam is live,
514
+ // because "the misleading wording reached the model" and "the seam was never installed" are
515
+ // different bugs and the next report must not have to guess which one happened.
516
+ const approvalSeam = installApprovalAttribution(ctx, log)
507
517
  // Harness compatibility: several fixtures evaluate this module with the `import` lines stripped
508
518
  // and only a fixed argument list (test-cycle-no-timeout and friends). `typeof <binding>` is safe
509
519
  // even when the binding was stripped, so the debug-gate wiring degrades to "not mounted" there
@@ -1278,9 +1288,50 @@ export function apply (ctx, config) {
1278
1288
  if (!isAcked(sessionKey(drv)) && isDrivingCall(exec.name, gArgs)) {
1279
1289
  return { kind: 'deny', reason: `READ THE PROCEDURE FIRST. ${ACK_HINT}` }
1280
1290
  }
1281
- const decision = policyDecision(exec.name, exec.arguments || {}, config.automationMode)
1282
- if (decision.kind !== 'allow' && decision.reason) {
1283
- log.info(`policy ${decision.kind}: ${exec.name} — ${decision.reason}`)
1291
+ // ---- THE APPROVAL CHANNEL IS PART OF THE DECISION ---------------------------------------
1292
+ // A policy `ask` is a request for a HUMAN. DSH's `never` approval policy (selected by the
1293
+ // danger-full-access preset) cannot deliver one: ApprovalService.decide() rejects at once
1294
+ // and the tool layer reports `the user rejected tool "..."` — measured 2026-11-12 on
1295
+ // `computer_key {combo:"backspace"}` in a full-access session where the human had touched
1296
+ // nothing. So the two facts that decide whether an ask is answerable are read HERE, per
1297
+ // call, and handed to policy.js, which settles the ask itself (lib/policy.js
1298
+ // applyApprovalChannel): full access runs it, anything else refuses in words that name the
1299
+ // unavailable channel instead of blaming the user. Unknown facts keep the old behaviour.
1300
+ const approvalEnv = readApprovalEnv({
1301
+ ctx,
1302
+ session: (exec.agent && exec.agent.session) || (typeof drv === 'object' ? drv : null),
1303
+ sessionId: sessionKey(drv),
1304
+ durablePermission: typeof sessionPermission === 'function' ? sessionPermission : null,
1305
+ })
1306
+ const rawDecision = policyDecision(exec.name, gArgs, config.automationMode)
1307
+ const decision = policyDecision(exec.name, gArgs, config.automationMode, approvalEnv)
1308
+ // An unanswerable ask that ran anyway is the one transition a reader must be able to see
1309
+ // without guessing: log it as such, never as a plain allow.
1310
+ const ranUnderFullAccess = rawDecision.kind === 'ask' && decision.kind === 'allow'
1311
+ // The reason may quote a launch target (`[target=…]`): redact URL userinfo/query tokens
1312
+ // before either the log or the durable record so neither can become a credential store.
1313
+ const safeReason = decision.reason ? redactReasonText(String(decision.reason)) : ''
1314
+ const gateLine = `gate ${exec.name} ${JSON.stringify(gateArgSummary(exec.name, gArgs))} ` +
1315
+ `automation=${config.automationMode} ${describeApprovalEnv(approvalEnv)} ` +
1316
+ `raw=${rawDecision.kind} final=${decision.kind}` +
1317
+ (ranUnderFullAccess ? ' (unanswerable ask ran under full access)' : '') +
1318
+ (decision.kind !== 'allow' && safeReason ? ` — ${safeReason}` : '')
1319
+ log.info(gateLine)
1320
+ // Durable, secret-free diagnostics for the next report. Observation calls only appear when
1321
+ // something other than "allow" happened, so a busy screenshot session cannot flood it.
1322
+ if (decision.kind !== 'allow' || ranUnderFullAccess || ACTUATION_TOOLS.has(exec.name) || exec.name === 'computer_ctrl') {
1323
+ appendGate(dataDir, {
1324
+ ts: Date.now(), tool: exec.name, args: gateArgSummary(exec.name, gArgs),
1325
+ automationMode: config.automationMode,
1326
+ approvalPolicy: approvalEnv.approvalPolicy, sandbox: approvalEnv.sandbox,
1327
+ promptsAvailable: approvalEnv.promptsAvailable, fullAccess: approvalEnv.fullAccess,
1328
+ delegated: approvalEnv.delegated === true,
1329
+ envSources: approvalEnv.sources, raw: rawDecision.kind, final: decision.kind,
1330
+ attributionSeam: approvalSeam?.installed === true ? 'installed' : (approvalSeam?.reason ?? 'absent'),
1331
+ ...(ranUnderFullAccess ? { escalated: 'full-access' } : {}),
1332
+ ...(safeReason ? { reason: safeReason.slice(0, 500) } : {}),
1333
+ ...(sessionKey(drv) ? { session: sessionKey(drv) } : {}),
1334
+ })
1284
1335
  }
1285
1336
  // RETURN the decision — do not hand it to next(). On this DSH build `next` is
1286
1337
  // `() => Promise<PreToolDecision>`: it takes NO arguments, so `next(decision)` silently
package/lib/policy.js CHANGED
@@ -1,8 +1,14 @@
1
1
  // policy.js — pure approval decision for dsh-computer-use.
2
2
  // Modeled on @anweat/dsh-browser's approval-policy.js: a pure function mapping
3
- // (toolName, args, automationMode) -> {kind:'allow'|'deny'|'ask', reason}.
3
+ // (toolName, args, automationMode, approvalEnv?) -> {kind:'allow'|'deny'|'ask', reason}.
4
4
  // Fail-closed by construction: unknown tool names are denied.
5
5
  //
6
+ // The 4th argument names THIS session's approval channel (see lib/approval-env.js). It exists
7
+ // because `ask` is a request for a HUMAN, and a channel that cannot reach one turns every ask
8
+ // into a silent auto-reject the host reports as `the user rejected tool "..."`. Full access is
9
+ // the human's standing "do not ask me" grant, so there an unanswerable ask runs; everywhere
10
+ // else it becomes an honest, explicitly-worded refusal. See applyApprovalChannel().
11
+ //
6
12
  // ⚠️ KEEP IN SYNC WITH THE TOOL SURFACE. A fail-closed list is only safe if it is also COMPLETE.
7
13
  // 2026-09-13: the tool set was rewritten from 28 names to 17 (merged + renamed) and this
8
14
  // allow-list was NOT updated, so the plugin's own gate would have denied most of its own tools
@@ -30,8 +36,8 @@ export const ACTUATION_TOOLS = new Set([
30
36
  'computer_launch', 'computer_focus',
31
37
  ])
32
38
 
33
- export const HIGH_RISK_NOTE = 'high-risk action (destructive key / closing a window / password field) — always requires human approval'
34
- export const LAUNCH_HIGH_RISK_NOTE = 'high-risk launch (executable / script / installer / UNC / file: target) — explorer will run what it resolves; always requires human approval'
39
+ export const HIGH_RISK_NOTE = 'high-risk action (destructive key / closing a window / password field) — normally requires human approval'
40
+ export const LAUNCH_HIGH_RISK_NOTE = 'high-risk launch (executable / script / installer / UNC / file: target) — explorer will run what it resolves; normally requires human approval'
35
41
 
36
42
  // A launch target that IS code (or points at it) escalates everywhere it can: the launcher
37
43
  // executes what it resolves, so argv discipline cannot make an .exe/.bat/UNC target "just a
@@ -41,7 +47,7 @@ export const LAUNCH_HIGH_RISK_NOTE = 'high-risk launch (executable / script / in
41
47
  const LAUNCH_CODE_TARGET = /\.(exe|scr|msi|hta|bat|cmd|com|pif|cpl|msc|reg|jse|vbe|vbs|ws|wsf|wsh|ps1|lnk|url|jar|application|appref-ms|appx|msix|gadget|sct)$/i
42
48
 
43
49
  /** @returns {{kind:'allow'|'deny'|'ask', reason?: string}} */
44
- export function policyDecision (name, args, mode) {
50
+ export function policyDecision (name, args, mode, approvalEnv) {
45
51
  const a = args || {}
46
52
 
47
53
  // ---- the two argument-dependent tools -------------------------------------------------
@@ -59,7 +65,7 @@ export function policyDecision (name, args, mode) {
59
65
  // the second answer of the ask protocol ("I cannot proceed") and the ask notice promises the
60
66
  // human the agent can give it — denying it made that answer dead in all four modes.
61
67
  if (act === 'exit') return { kind: 'allow' }
62
- if (act === 'calibrate' || act === 'indicator') return decideActuation(name, a, mode)
68
+ if (act === 'calibrate' || act === 'indicator') return decideActuation(name, a, mode, approvalEnv)
63
69
  return { kind: 'deny', reason: `unknown computer_ctrl action: ${act}` }
64
70
  }
65
71
 
@@ -74,15 +80,15 @@ export function policyDecision (name, args, mode) {
74
80
  if (name === 'computer_ask') return { kind: 'allow' }
75
81
  if (name === 'computer_clip') {
76
82
  if (a.text === undefined) return { kind: 'allow' } // read
77
- return decideActuation(name, a, mode) // write
83
+ return decideActuation(name, a, mode, approvalEnv) // write
78
84
  }
79
85
 
80
86
  if (OBSERVATION_TOOLS.has(name)) return { kind: 'allow' }
81
- if (ACTUATION_TOOLS.has(name)) return decideActuation(name, a, mode)
87
+ if (ACTUATION_TOOLS.has(name)) return decideActuation(name, a, mode, approvalEnv)
82
88
  return { kind: 'deny', reason: `unknown computer-use tool: ${name}` }
83
89
  }
84
90
 
85
- function decideActuation (name, a, mode) {
91
+ function decideActuation (name, a, mode, approvalEnv) {
86
92
  let hr
87
93
  try { hr = highRisk(name, a) } catch (error) { return { kind: 'deny', reason: error.message } }
88
94
  const note = name === 'computer_launch' ? LAUNCH_HIGH_RISK_NOTE : HIGH_RISK_NOTE
@@ -90,10 +96,12 @@ function decideActuation (name, a, mode) {
90
96
  case 'read-only':
91
97
  return { kind: 'deny', reason: `automationMode=read-only: ${name} drives the machine` }
92
98
  case 'standard':
93
- return hr ? { kind: 'ask', reason: note + riskSuffix(name, a) }
94
- : { kind: 'ask', reason: `automationMode=standard: actuation ${name}` }
99
+ return applyApprovalChannel(hr
100
+ ? { kind: 'ask', reason: note + riskSuffix(name, a) }
101
+ : { kind: 'ask', reason: `automationMode=standard: actuation ${name}` }, approvalEnv, mode)
95
102
  case 'autonomous':
96
- return hr ? { kind: 'ask', reason: note + riskSuffix(name, a) } : { kind: 'allow' }
103
+ return hr ? applyApprovalChannel({ kind: 'ask', reason: note + riskSuffix(name, a) }, approvalEnv, mode)
104
+ : { kind: 'allow' }
97
105
  case 'unrestricted':
98
106
  return { kind: 'allow' }
99
107
  default:
@@ -101,6 +109,78 @@ function decideActuation (name, a, mode) {
101
109
  }
102
110
  }
103
111
 
112
+ /** The sentence every unanswerable refusal must carry, so nobody reads it as a human decision. */
113
+ export const NO_APPROVAL_CHANNEL = 'approval prompts are unavailable in this session (approval policy: never)'
114
+
115
+ /**
116
+ * Settle one `ask` against the approval channel this session actually has.
117
+ *
118
+ * `ask` means "a human must decide". It is only meaningful when a human can be asked. The host
119
+ * approval service's `never` policy creates the exact opposite of an approval: it rejects at
120
+ * once, without a prompt, and the tool layer then reports `the user rejected tool "..."` — a
121
+ * decision the human never made (measured 2026-11-12 on `computer_key {combo:"backspace"}` in a
122
+ * `danger-full-access` session the user had explicitly granted).
123
+ *
124
+ * * prompts available → unchanged `ask`; the host owns the card and its audit pair.
125
+ * * prompts unavailable + full access + a mode that already runs unprompted actuation
126
+ * → `allow`. Full access IS the human's standing "do not ask
127
+ * me" grant, so suppressing a prompt that cannot be shown is
128
+ * not a widening: it is the grant the human already gave.
129
+ * * also unanswerable, but `standard`, or a delegated child session, or no proven full access
130
+ * → `deny` that says exactly which fact blocked it. Nothing
131
+ * ran, nobody was asked, and no refusal is attributed to the
132
+ * user.
133
+ *
134
+ * `standard` keeps failing closed on purpose: its whole contract is "every actuation is approved
135
+ * first", and full access is not an approval — it only means the prompt cannot be shown. Turning
136
+ * `standard` into `unrestricted` would silently delete the mode the user chose.
137
+ *
138
+ * A delegated child (`approvalEnv.delegated`) is never granted: `@deepseek-ai/dsh-subagent` pins
139
+ * `approval/policy = never` on every child and copies the parent's sandbox mode, so a full-access
140
+ * + never child is the *default shape* of a subagent, not evidence that the human authorized it.
141
+ *
142
+ * Unknown facts (`approvalEnv` absent, policy unknown, sandbox unknown) keep the original
143
+ * `ask`/deny: guessing full access is the one guess that must never be made here.
144
+ *
145
+ * @param {{kind: string, reason?: string}} decision the raw mode decision
146
+ * @param {{approvalPolicy?: string|null, sandbox?: string|null, promptsAvailable?: boolean,
147
+ * fullAccess?: boolean, delegated?: boolean}|null|undefined} approvalEnv
148
+ * @param {string} [mode] the automationMode that produced `decision`
149
+ * @returns {{kind: 'allow'|'deny'|'ask', reason?: string}}
150
+ */
151
+ export function applyApprovalChannel (decision, approvalEnv, mode) {
152
+ if (!decision || decision.kind !== 'ask' || !approvalEnv || typeof approvalEnv !== 'object') return decision
153
+ const unanswerable = approvalEnv.approvalPolicy === 'never' || approvalEnv.promptsAvailable === false
154
+ if (!unanswerable) return decision
155
+ if (approvalEnv.delegated === true) {
156
+ return {
157
+ kind: 'deny',
158
+ reason: `${decision.reason}; ${NO_APPROVAL_CHANNEL} and this is a delegated subagent session, ` +
159
+ 'whose approval policy the host pins to never — the human\'s full-access grant covers the ' +
160
+ 'conversation that started it, not a child driving the machine on its own. Nothing ran, and the user was not asked',
161
+ }
162
+ }
163
+ if (approvalEnv.fullAccess !== true && approvalEnv.sandbox !== 'danger-full-access') {
164
+ return {
165
+ kind: 'deny',
166
+ reason: `${decision.reason}; ${NO_APPROVAL_CHANNEL} and this session is not full access — nothing ran, and the user was not asked`,
167
+ }
168
+ }
169
+ if (mode !== 'autonomous' && mode !== 'unrestricted') {
170
+ return {
171
+ kind: 'deny',
172
+ reason: `${decision.reason}; ${NO_APPROVAL_CHANNEL} and automationMode=${mode ?? 'unknown'} asks before ` +
173
+ 'this actuation, so it cannot run unprompted — nothing ran, and the user was not asked. ' +
174
+ 'Raise automationMode to autonomous (Settings → computer-use) if this session\'s full access should run it without a prompt',
175
+ }
176
+ }
177
+ return {
178
+ kind: 'allow',
179
+ reason: `${decision.reason}; ${NO_APPROVAL_CHANNEL}, but this session has full access, so that required ` +
180
+ 'approval is satisfied by the standing full-access grant — executed without a prompt',
181
+ }
182
+ }
183
+
104
184
  /** Names the exact argument that escalated, so a refused batch names its offending step
105
185
  * (test report 2026-11-04: "ctrl+a then delete" read as a generic high-risk refusal and the
106
186
  * model had to guess which op tripped it). Empty string when there is nothing to add. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-codex-style-computer-use",
3
- "version": "2.2.9",
3
+ "version": "2.3.0",
4
4
  "description": "Codex-style Computer Use for DeepSeek Harness: Windows desktop control, screenshots, UI Automation, human input handoff, approval gates and prebuilt native workers. Install and update from dsh-market without PowerShell 7 or build steps.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -31,7 +31,7 @@ const excluded = {
31
31
  'test-approval-attention.mjs': 'alias imports test-attention.mjs, which is already run directly',
32
32
  }
33
33
  const reviewed = new Set([
34
- 'action-feedback', 'agent-pointer', 'approval-attribution', 'ask-invariants', 'ask-merge', 'ask-orphan', 'ask-release',
34
+ 'action-feedback', 'agent-pointer', 'approval-attribution', 'approval-channel', 'ask-invariants', 'ask-merge', 'ask-orphan', 'ask-release',
35
35
  'attention-native', 'attention', 'audit-completion', 'batch-coverage', 'buildusermessage', 'bundled-skill', 'client-export',
36
36
  'coactive', 'compact-feedback', 'control-targets', 'core-system-recovery', 'cursor', 'cycle-completion',
37
37
  'cycle-no-timeout', 'cycle-open', 'desktop-acceptance-io', 'desktop-ownership', 'drag-options', 'evidence-protocol',