@xi4z/dsh-utils-approval-policy 0.0.0-stage → 0.7.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/src/index.ts ADDED
@@ -0,0 +1,566 @@
1
+ /**
2
+ * `dsh-utils` approval-policy component: the unattended approval gate, with
3
+ * two additions for the experimental auto approval (the `auto` permission
4
+ * preset published by `@deepseek-ai/dsh-experimental-auto-review`):
5
+ *
6
+ * 1. `defaultPermissionPreset` — pin every NEW session to a configured
7
+ * preset. `"auto"` makes the experimental auto approval the deployment's
8
+ * default approval strategy; the host itself refuses `auto` as a
9
+ * `permissionPresets.defaultPreset` value (it is a current-session-only
10
+ * preset), so this is the one seam that can default a deployment to it.
11
+ * 2. `autoReviewContent` — when the window expires on a request the auto
12
+ * approval raised (the reviewer's `ask`), the model-facing tool result
13
+ * gains the reviewer's own content. The host's approval pipeline renders
14
+ * only "the user rejected tool X" for any `rejected` outcome, which would
15
+ * drop the reviewer's reason; this component appends it through
16
+ * `tools/post-execute` so the Agent reads what the auto approval decided
17
+ * and why, not just that the call was denied.
18
+ *
19
+ * The bundle mounts this component under the entry id `dsh-approval-policy`
20
+ * (`dsh-utils/approval-policy`); that entry id is also its settings namespace.
21
+ *
22
+ * On the host's 'approval/request' cordis waterfall this component is a racing
23
+ * gate answerer. For sessions/turns declared unattended (config: origins /
24
+ * sessions) it does not simply claim the request — it delegates with next()
25
+ * FIRST and races the downstream chain against a bounded window. Whoever
26
+ * settles first wins:
27
+ *
28
+ * - a downstream answerer answers inside the window → its answer wins
29
+ * (an instant fail-closed 'unavailable' from an empty chain passes
30
+ * through untouched — nothing to wait for);
31
+ * - the window expires → the configured fail-closed default settles the
32
+ * approval ('rejected'; 'unavailable' also allowed — 'allowed-once' is
33
+ * schema-forbidden). The turn proceeds denied instead of hanging;
34
+ * - the request's abort signal resolves 'cancelled' upstream — the host
35
+ * races the signal itself; a late window expiry is simply ignored.
36
+ *
37
+ * Unattended detection (config `origins`), in evaluation order:
38
+ *
39
+ * - sessions: glob-matched against the requesting agent id — an explicit
40
+ * name wins and gates EVERY turn of that session (session-level);
41
+ * - all: gate everything (opt-in escape hatch);
42
+ * - subagent: session.header.origin === 'subagent' (session-level — a
43
+ * subagent session is dedicated to delegation);
44
+ * - scheduled / cron: turn-level — the last PROVENANCE-bearing user
45
+ * message's source.kind is 'schedule' (host dsh-schedule) or 'cron'
46
+ * (dsh-cron). Synthetic context injections (runtime-context,
47
+ * skill-catalog, …) also ride role='user' and are skipped — they land
48
+ * after the trigger and would otherwise shadow it. Turn-level because
49
+ * those sessions are shared with humans: only machine-driven turns
50
+ * gate, and a human steering afterwards (last provenance message =
51
+ * human — 'user', or a timed-ask late reply 'user-question-reply')
52
+ * keeps the interactive default.
53
+ *
54
+ * The listener registers with prepend: true — the gate sits ahead of the
55
+ * interactive answerers (web remote answerer, dsh-feishu card) regardless of
56
+ * plugin load order, so an unattended request is windowed before a human
57
+ * surface claims it. Gated requests still reach those surfaces through
58
+ * next() inside the window. Interactive turns delegate immediately — the
59
+ * interactive default is unchanged.
60
+ *
61
+ * Audit: the host owns approval/asked + approval/decided — every decision,
62
+ * whichever answerer made it, lands in the session transcript. The gate
63
+ * never writes to the session log itself; the auto-approval addition rides the
64
+ * tool result the pipeline already materializes.
65
+ *
66
+ * Config: `export const Config` is the settings-page schema (all keys
67
+ * volatile, all defaults fail-closed-friendly); `apply` reads them through
68
+ * live references like dsh-cron does.
69
+ *
70
+ * @module dsh-utils/approval-policy
71
+ */
72
+
73
+ import type { Context } from '@deepseek-ai/cordis'
74
+ import z from '@deepseek-ai/schemastery'
75
+ import type { ApprovalOutcome, ApprovalRequestEvent } from '@deepseek-ai/dsh-user-approval/types'
76
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
77
+ import type { PostToolDecision, ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
78
+ import type {} from '@deepseek-ai/dsh-agent'
79
+
80
+ export const name = 'dsh-approval-policy'
81
+
82
+ /** Origins a deployment may declare unattended (config vocabulary). */
83
+ export type UnattendedOrigin = 'subagent' | 'scheduled' | 'cron' | 'all'
84
+
85
+ /**
86
+ * The only outcomes a gate may settle with. 'allowed-once' is deliberately
87
+ * absent from this union AND from the config enum: an unattended default
88
+ * must never grant — fail closed is the whole point.
89
+ */
90
+ export type GatedOutcome = 'rejected' | 'unavailable'
91
+
92
+ /** Settings-page schema; each key arrives as a volatile live reference. */
93
+ export const Config = z.object({
94
+ /** Session/turn origins treated as unattended. Default: subagent + scheduled. */
95
+ origins: z.array(z.union(['subagent', 'scheduled', 'cron', 'all'])).default(['subagent', 'scheduled']).volatile(),
96
+ /** Glob patterns matched against the requesting agent id; a hit gates every turn of that session. */
97
+ sessions: z.array(z.string()).default([]).volatile(),
98
+ /** Answer window in seconds (whole seconds; no .int() chain exists — min/max bound it); 0 denies without delegating. Default 60. */
99
+ windowSeconds: z.number().min(0).max(86400).default(60).volatile(),
100
+ /** Settled when the window expires; 'allowed-once' is not in the union. */
101
+ defaultOutcome: z.union(['rejected', 'unavailable']).default('rejected').volatile(),
102
+ /**
103
+ * Permission preset pinned into every new session; '' keeps the host default.
104
+ * 'auto' selects the experimental auto approval (requires the
105
+ * `@deepseek-ai/dsh-experimental-auto-review` bundle); any configured preset
106
+ * name is accepted. The host rejects 'auto' as its own `defaultPreset`, and
107
+ * the pinned value is a durable `permission/preset` event, so every later
108
+ * turn reads the real knobs instead of a component-side override.
109
+ */
110
+ defaultPermissionPreset: z.string().default('').volatile(),
111
+ /**
112
+ * Append the experimental auto approval's own content to the model-facing
113
+ * tool result when this gate's window (not a human, not another answerer)
114
+ * rejects a request the reviewer raised. Default true.
115
+ */
116
+ autoReviewContent: z.boolean().default(true).volatile(),
117
+ })
118
+
119
+ /** Volatile Config fields arrive as live references; `.get()` snapshots. */
120
+ interface VolatileRef<T> {
121
+ get(): T
122
+ }
123
+
124
+ /** The runtime shape `apply` receives (every field volatile). */
125
+ export interface GateRuntimeConfig {
126
+ origins: VolatileRef<UnattendedOrigin[]>
127
+ sessions: VolatileRef<string[]>
128
+ windowSeconds: VolatileRef<number>
129
+ defaultOutcome: VolatileRef<GatedOutcome>
130
+ defaultPermissionPreset: VolatileRef<string>
131
+ autoReviewContent: VolatileRef<boolean>
132
+ }
133
+
134
+ /** Canonical identity of the experimental per-call review preset. */
135
+ export const AUTO_REVIEW_PRESET = 'auto'
136
+
137
+ /**
138
+ * The reviewer-owned prefix of an approval reason raised by
139
+ * `@deepseek-ai/dsh-experimental-auto-review` when its review denies a call
140
+ * under the `ask` policy (`Auto review denied tool "<name>": <reason>`).
141
+ * Matching the reason rather than the session preset keeps the attribution
142
+ * correct when the policy switches between the ask and its settlement.
143
+ */
144
+ export const AUTO_REVIEW_REASON_PREFIX = 'Auto review denied tool "'
145
+
146
+ /** Structured error code the pipeline records for a rejected approval (newer host lines). */
147
+ const APPROVAL_REJECTED_CODE = 'APPROVAL_REJECTED'
148
+
149
+ /**
150
+ * The model-facing denial text the host pipeline renders for ANY `rejected`
151
+ * approval outcome (`packages/core/tools/src/pipeline.ts`). Host 0.2.2-rc.1
152
+ * records no structured error info, so the text is the only stable, version-
153
+ * tolerant discriminator; newer lines also carry `{ name: ApprovalError }`.
154
+ */
155
+ export function rejectedApprovalMessage(toolName: string): string {
156
+ return `the user rejected tool "${toolName}"`
157
+ }
158
+
159
+ /** Whether one failed tool result is the pipeline's rejection of an approval ask. */
160
+ export function isRejectedApprovalResult(
161
+ result: { readonly isError: boolean; readonly error: { readonly message: string; readonly info?: { readonly name?: string; readonly code?: string } } },
162
+ toolName: string,
163
+ ): boolean {
164
+ if (!result.isError) return false
165
+ const info = result.error.info
166
+ if (info !== undefined && (info.code === APPROVAL_REJECTED_CODE || info.name === 'ApprovalError')) return true
167
+ return result.error.message === rejectedApprovalMessage(toolName)
168
+ }
169
+
170
+ /** How long a window-rejected auto-review request may still claim its tool result. */
171
+ const AUTO_REVIEW_SETTLE_TTL_MS = 120_000
172
+
173
+ /** Compiled glob: `*` matches anything, everything else is literal. */
174
+ export function globToRegExp(pattern: string): RegExp {
175
+ const escaped = pattern
176
+ .replace(/[.+^${}()|[\]\\?]/g, '\\$&')
177
+ .replace(/\*/g, '.*')
178
+ return new RegExp(`^(?:${escaped})$`)
179
+ }
180
+
181
+ /** What the gate reads off the requesting agent to classify the turn. */
182
+ export interface OriginFacts {
183
+ /** session.header.origin when the live session is readable ('subagent' …). */
184
+ headerOrigin?: string
185
+ /** source.kind of the session's last user message ('schedule', 'cron', 'user', …). */
186
+ lastUserMessageKind?: string
187
+ }
188
+
189
+ /** Structural slices of the runtime faces — no closure type imports needed. */
190
+ interface MsgLike {
191
+ readonly role?: string
192
+ readonly source?: { readonly kind?: string }
193
+ }
194
+ interface EventLike {
195
+ readonly type?: string
196
+ }
197
+ interface SessionLike {
198
+ readonly header?: { readonly origin?: string }
199
+ deriveMessages?(): MsgLike[]
200
+ snapshotEvents?(): readonly EventLike[]
201
+ }
202
+ interface AgentLike {
203
+ readonly id?: unknown
204
+ readonly session?: SessionLike
205
+ }
206
+
207
+ /**
208
+ * Kinds that carry a turn's human/machine provenance. The host also injects
209
+ * SYNTHETIC context messages into the role='user' stream after a turn starts
210
+ * (runtime-context snapshots, skill-catalog reminders, …); they always sit
211
+ * after the real trigger and would shadow it, so the backward scan skips any
212
+ * user-role message whose kind is not one of these (a missing kind is legacy
213
+ * human input and counts as 'user'). Live-tested: without this skip, every
214
+ * cron/scheduled turn misclassified as interactive and slipped through
215
+ * unwindowed.
216
+ *
217
+ * 'user-question-reply' (dsh 0.2.0 timed ask, experimental) is the LATE
218
+ * answer to a timed-out question flowing back as a user-role message — hard
219
+ * proof a human was there. It stops the scan with the same standing as an
220
+ * explicit 'user' steer (the turn stays interactive); skipping it as
221
+ * synthetic would shadow it with the cron/schedule trigger that fired
222
+ * BEFORE the human answered.
223
+ */
224
+ const PROVENANCE_KINDS: ReadonlySet<string> = new Set(['user', 'schedule', 'cron', 'user-question-reply'])
225
+
226
+ /**
227
+ * Read the origin facts off the request's agent. Both reads are best-effort:
228
+ * a projected agent without a live session yields `{}` (only `sessions`/`all`
229
+ * can then gate), and each fact independently degrades to undefined.
230
+ */
231
+ export function readFacts(agent: AgentLike | undefined): OriginFacts {
232
+ const session = agent?.session
233
+ if (!session) return {}
234
+ const facts: OriginFacts = { headerOrigin: session.header?.origin }
235
+ const messages = session.deriveMessages?.()
236
+ if (messages) {
237
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
238
+ const message = messages[i]
239
+ if (message?.role !== 'user') continue
240
+ const kind = message.source?.kind
241
+ if (kind === undefined || PROVENANCE_KINDS.has(kind)) {
242
+ facts.lastUserMessageKind = kind ?? 'user'
243
+ break
244
+ }
245
+ // synthetic context injection — keep scanning for the real trigger
246
+ }
247
+ }
248
+ return facts
249
+ }
250
+
251
+ /** Gate predicate: explicit session hit → 'all' → session/turn origins. */
252
+ export function shouldGate(
253
+ config: { readonly origins: readonly UnattendedOrigin[]; readonly sessions: readonly string[] },
254
+ sessionId: string,
255
+ facts: OriginFacts,
256
+ ): boolean {
257
+ if (config.sessions.length > 0 && config.sessions.some((pattern) => {
258
+ try {
259
+ return globToRegExp(pattern).test(sessionId)
260
+ } catch {
261
+ return false // a malformed pattern must not break approvals
262
+ }
263
+ })) return true
264
+ const origins = config.origins
265
+ if (origins.includes('all')) return true
266
+ if (origins.includes('subagent') && facts.headerOrigin === 'subagent') return true
267
+ const kind = facts.lastUserMessageKind
268
+ if (kind === 'schedule' && origins.includes('scheduled')) return true
269
+ if (kind === 'cron' && origins.includes('cron')) return true
270
+ return false
271
+ }
272
+
273
+ /** Which side of the race produced the settled outcome. */
274
+ export type GateSettledBy = 'downstream' | 'window'
275
+
276
+ /** One gate result: the outcome plus the side that produced it. */
277
+ export interface GateSettlement {
278
+ readonly outcome: ApprovalOutcome
279
+ readonly settledBy: GateSettledBy
280
+ }
281
+
282
+ /**
283
+ * The gate: delegate first, race the downstream chain against the window.
284
+ *
285
+ * windowMs <= 0 denies immediately WITHOUT calling `decision` (the 0 = instant
286
+ * deny degenerate case — downstream never sees the request, mirroring the
287
+ * host's approval/policy=never); that settlement is reported as `'window'`
288
+ * because no answerer produced it. A fast `decision` (including an instant
289
+ * fail-closed 'unavailable' from an empty chain) passes through untouched;
290
+ * only a pending decision races the timer.
291
+ */
292
+ export async function raceGate(
293
+ decision: () => Promise<ApprovalOutcome>,
294
+ windowMs: number,
295
+ defaultOutcome: GatedOutcome,
296
+ ): Promise<GateSettlement> {
297
+ if (windowMs <= 0) return { outcome: defaultOutcome, settledBy: 'window' }
298
+ // The window timer stays REF'd on purpose: an open window means the host
299
+ // turn is still owed an outcome, so the process must not drain the event
300
+ // loop before it settles. It is cleared as soon as the race settles
301
+ // (answer, rejection, or expiry) so a fast answer never leaves a stray
302
+ // timer holding the loop for the rest of the window.
303
+ let timer: ReturnType<typeof setTimeout> | undefined
304
+ try {
305
+ const windowSettlement = new Promise<GateSettlement>((resolve) => {
306
+ timer = setTimeout(() => resolve({ outcome: defaultOutcome, settledBy: 'window' }), windowMs)
307
+ })
308
+ return await Promise.race([
309
+ decision().then((outcome): GateSettlement => ({ outcome, settledBy: 'downstream' })),
310
+ windowSettlement,
311
+ ])
312
+ } finally {
313
+ if (timer !== undefined) clearTimeout(timer)
314
+ }
315
+ }
316
+
317
+ /** Whether an approval reason was raised by the experimental auto approval. */
318
+ export function isAutoReviewAsk(reason: string | undefined): boolean {
319
+ return typeof reason === 'string' && reason.startsWith(AUTO_REVIEW_REASON_PREFIX)
320
+ }
321
+
322
+ /** One window-rejected auto-review request waiting for its tool result. */
323
+ export interface AutoReviewSettle {
324
+ /** Tool whose approval the reviewer raised. */
325
+ readonly toolName: string
326
+ /** The reviewer-owned approval reason, verbatim. */
327
+ readonly reason: string
328
+ /** Wall clock of the settlement, for TTL pruning. */
329
+ readonly at: number
330
+ }
331
+
332
+ /** Remember one settlement under its tool-call id (absent call ids cannot claim a result). */
333
+ export function recordAutoReviewSettle(
334
+ store: Map<string, AutoReviewSettle>,
335
+ callId: string | undefined,
336
+ settle: AutoReviewSettle,
337
+ ): void {
338
+ if (callId === undefined || callId === '') return
339
+ store.set(callId, settle)
340
+ }
341
+
342
+ /**
343
+ * Take and forget the settlement for one tool call; expired entries are pruned
344
+ * first so a result arriving after the TTL never claims stale content.
345
+ */
346
+ export function takeAutoReviewSettle(
347
+ store: Map<string, AutoReviewSettle>,
348
+ callId: string | undefined,
349
+ now: number,
350
+ ): AutoReviewSettle | undefined {
351
+ for (const [key, settle] of store) {
352
+ if (now - settle.at > AUTO_REVIEW_SETTLE_TTL_MS) store.delete(key)
353
+ }
354
+ if (callId === undefined || callId === '') return undefined
355
+ const settle = store.get(callId)
356
+ if (settle === undefined) return undefined
357
+ store.delete(callId)
358
+ return settle
359
+ }
360
+
361
+ /** The model-facing sentence appended to the denied tool result. */
362
+ export function autoReviewNotice(toolName: string, reason: string): string {
363
+ return 'The unattended approval window expired before anyone answered, so this request was rejected '
364
+ + `instead of being answered by the user. The pending request for tool "${toolName}" came from the `
365
+ + `experimental auto approval (auto review); its content follows:\n\n${reason}`
366
+ }
367
+
368
+ /** Append the auto approval's content to the model-facing result content. */
369
+ export function withAutoReviewContent(
370
+ content: readonly ContentBlock[],
371
+ settle: AutoReviewSettle,
372
+ ): ContentBlock[] {
373
+ return [
374
+ ...content,
375
+ { type: 'text', text: `\n\n${autoReviewNotice(settle.toolName, settle.reason)}` },
376
+ ]
377
+ }
378
+
379
+ /** What the permission projection already recorded in a session log. */
380
+ export interface PermissionFacts {
381
+ /** The session log was readable at all. */
382
+ readonly readable: boolean
383
+ /** The session already started a turn (a resumed or user-driven session). */
384
+ readonly turnStarted: boolean
385
+ /** The host (or a user) already recorded permission state. */
386
+ readonly permissionState: boolean
387
+ /** The log carries the constructor-seed boundary of a seeded session. */
388
+ readonly seeded: boolean
389
+ }
390
+
391
+ const PERMISSION_EVENT_TYPES: ReadonlySet<string> = new Set([
392
+ 'permission/preset',
393
+ 'sandbox/mode',
394
+ 'approval/policy',
395
+ 'session/end-seed',
396
+ ])
397
+
398
+ /**
399
+ * Fold the permission-relevant facts out of a session log. A session that
400
+ * cannot expose its events is reported unreadable so the caller skips pinning
401
+ * instead of overriding a restored selection it cannot see.
402
+ */
403
+ export function readPermissionFacts(session: SessionLike | undefined): PermissionFacts {
404
+ const events = session?.snapshotEvents?.()
405
+ if (events === undefined) {
406
+ return { readable: false, turnStarted: true, permissionState: true, seeded: true }
407
+ }
408
+ let turnStarted = false
409
+ let permissionState = false
410
+ let seeded = false
411
+ for (const event of events) {
412
+ const type = event?.type
413
+ if (type === 'turn/start') turnStarted = true
414
+ else if (type === 'session/end-seed') { permissionState = true; seeded = true }
415
+ else if (type !== undefined && PERMISSION_EVENT_TYPES.has(type)) permissionState = true
416
+ }
417
+ return { readable: true, turnStarted, permissionState, seeded }
418
+ }
419
+
420
+ /** Inputs for the default-preset decision. */
421
+ export interface DefaultPresetDecision {
422
+ /** Configured preset name; '' means leave the session alone. */
423
+ readonly configured: string
424
+ /** Preset the session currently resolves to. */
425
+ readonly current: string
426
+ /** The host's deployment default preset. */
427
+ readonly hostDefault: string
428
+ /** Permission facts folded from the session log. */
429
+ readonly facts: PermissionFacts
430
+ }
431
+
432
+ /**
433
+ * Decide whether a new session may take the configured default preset.
434
+ *
435
+ * A session qualifies while it has no turn and no seed boundary. It qualifies
436
+ * either before the host pinned its own default (no permission state yet — the
437
+ * gate ran first) or right after the host pinned exactly that default (the
438
+ * session is still untouched, so the pin is creation-time state rather than a
439
+ * user choice). Anything else is a resumed, seeded, or deliberately switched
440
+ * session and keeps its recorded permission.
441
+ */
442
+ export function shouldPinDefaultPreset(decision: DefaultPresetDecision): boolean {
443
+ const { configured, current, hostDefault, facts } = decision
444
+ if (configured === '' || current === configured) return false
445
+ if (!facts.readable || facts.turnStarted || facts.seeded) return false
446
+ return !facts.permissionState || current === hostDefault
447
+ }
448
+
449
+ /** Structural slice of `ctx.permissionPresets` (types only; no runtime import). */
450
+ interface PermissionPresetsLike {
451
+ readonly names: readonly string[]
452
+ readonly defaultPreset: string
453
+ current(session: unknown): string
454
+ set(session: unknown, name: string): void
455
+ }
456
+
457
+ /** Read the optional permission-presets service without importing its module. */
458
+ function permissionPresetsOf(ctx: Context): PermissionPresetsLike | undefined {
459
+ return (ctx as unknown as { get(name: string): PermissionPresetsLike | undefined }).get('permissionPresets')
460
+ }
461
+
462
+ /** Payload of the host's agent/created event, as this component reads it. */
463
+ interface AgentCreatedPayload {
464
+ readonly agent?: AgentLike
465
+ }
466
+
467
+ export function apply(ctx: Context, config: GateRuntimeConfig): void {
468
+ const cfgNow = () => ({
469
+ origins: config.origins.get(),
470
+ sessions: config.sessions.get(),
471
+ windowSeconds: config.windowSeconds.get(),
472
+ defaultOutcome: config.defaultOutcome.get(),
473
+ defaultPermissionPreset: config.defaultPermissionPreset.get(),
474
+ autoReviewContent: config.autoReviewContent.get(),
475
+ })
476
+
477
+ /** Window-rejected auto-review requests, keyed by tool-call id. */
478
+ const pendingAutoReview = new Map<string, AutoReviewSettle>()
479
+
480
+ const listener = async (
481
+ request: ApprovalRequestEvent,
482
+ next: () => Promise<ApprovalOutcome>,
483
+ ): Promise<ApprovalOutcome> => {
484
+ const cfg = cfgNow()
485
+ const sessionId = String(request.agent?.id ?? '')
486
+ if (!shouldGate(cfg, sessionId, readFacts(request.agent))) return next()
487
+ const settlement = await raceGate(next, cfg.windowSeconds * 1000, cfg.defaultOutcome)
488
+ if (settlement.settledBy === 'window'
489
+ && settlement.outcome === 'rejected'
490
+ && cfg.autoReviewContent
491
+ && isAutoReviewAsk(request.reason)) {
492
+ recordAutoReviewSettle(pendingAutoReview, request.callId === undefined ? undefined : String(request.callId), {
493
+ toolName: request.toolName,
494
+ reason: request.reason as string,
495
+ at: Date.now(),
496
+ })
497
+ }
498
+ return settlement.outcome
499
+ }
500
+
501
+ /**
502
+ * Append the reviewer's content to a rejection this gate produced. The
503
+ * listener delegates with next() first so every other post-execute policy
504
+ * still runs, then edits only the accepted content of an APPROVAL_REJECTED
505
+ * failure that matches a recorded window settlement.
506
+ */
507
+ const postExecute = async (
508
+ exec: ToolExecution,
509
+ result: Readonly<ToolExecutionResult>,
510
+ next: () => Promise<PostToolDecision>,
511
+ ): Promise<PostToolDecision> => {
512
+ if (!result.isError || !isRejectedApprovalResult(result, exec.name)) return next()
513
+ const settle = takeAutoReviewSettle(
514
+ pendingAutoReview,
515
+ exec.callId === undefined ? undefined : String(exec.callId),
516
+ Date.now(),
517
+ )
518
+ if (settle === undefined) return next()
519
+ const downstream = await next()
520
+ if (downstream.kind !== 'accept') return downstream
521
+ // A value-replacing accept cannot apply to a failed result; leave it to the pipeline's own rejection.
522
+ if ('value' in downstream) return downstream
523
+ return {
524
+ kind: 'accept',
525
+ content: withAutoReviewContent(downstream.content ?? result.content, settle),
526
+ ...downstream.additionalContexts === undefined ? {} : { additionalContexts: downstream.additionalContexts },
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Pin the configured default preset into a new session. A deployment that
532
+ * asks for a preset the composition does not publish throws here, which
533
+ * vetoes agent publication — a missing auto-review bundle must be visible,
534
+ * not a silently interactive session.
535
+ */
536
+ const pinDefaultPreset = (payload: AgentCreatedPayload): void => {
537
+ const configured = config.defaultPermissionPreset.get()
538
+ if (configured === '') return
539
+ const presets = permissionPresetsOf(ctx)
540
+ if (presets === undefined) {
541
+ throw new Error(`dsh-approval-policy: defaultPermissionPreset "${configured}" requires ctx.permissionPresets, which this composition does not mount`)
542
+ }
543
+ if (!presets.names.includes(configured)) {
544
+ throw new Error(`dsh-approval-policy: defaultPermissionPreset "${configured}" is not an available preset (available: ${presets.names.join(', ')}); preset "auto" requires the @deepseek-ai/dsh-experimental-auto-review bundle`)
545
+ }
546
+ const session = payload.agent?.session
547
+ if (session === undefined) return
548
+ if (shouldPinDefaultPreset({
549
+ configured,
550
+ current: presets.current(session),
551
+ hostDefault: presets.defaultPreset,
552
+ facts: readPermissionFacts(session),
553
+ })) presets.set(session, configured)
554
+ }
555
+
556
+ // prepend keeps the gate ahead of interactive answerers regardless of
557
+ // plugin load order; gated requests still reach them via next().
558
+ const disposeGate = ctx.on('approval/request', listener, { prepend: true })
559
+ // prepend so the rejection is edited before later policies materialize it;
560
+ // next() still runs so no other post-execute policy is skipped.
561
+ const disposePostExecute = ctx.on('tools/post-execute', postExecute, { prepend: true })
562
+ const disposePin = ctx.on('agent/created', pinDefaultPreset as never)
563
+ ctx.effect(() => disposeGate)
564
+ ctx.effect(() => disposePostExecute)
565
+ ctx.effect(() => disposePin)
566
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.