@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xi4z
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/lib/index.d.ts ADDED
@@ -0,0 +1,297 @@
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
+ import type { Context } from '@deepseek-ai/cordis';
73
+ import z from '@deepseek-ai/schemastery';
74
+ import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval/types';
75
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
76
+ export declare const name = "dsh-approval-policy";
77
+ /** Origins a deployment may declare unattended (config vocabulary). */
78
+ export type UnattendedOrigin = 'subagent' | 'scheduled' | 'cron' | 'all';
79
+ /**
80
+ * The only outcomes a gate may settle with. 'allowed-once' is deliberately
81
+ * absent from this union AND from the config enum: an unattended default
82
+ * must never grant — fail closed is the whole point.
83
+ */
84
+ export type GatedOutcome = 'rejected' | 'unavailable';
85
+ /** Settings-page schema; each key arrives as a volatile live reference. */
86
+ export declare const Config: z<Schemastery.ObjectS<NoInfer<{
87
+ /** Session/turn origins treated as unattended. Default: subagent + scheduled. */
88
+ origins: z<NoInfer<("subagent" | "scheduled" | "cron" | "all")[]>, NoInfer<("subagent" | "scheduled" | "cron" | "all")[]>, "volatile-defined">;
89
+ /** Glob patterns matched against the requesting agent id; a hit gates every turn of that session. */
90
+ sessions: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
91
+ /** Answer window in seconds (whole seconds; no .int() chain exists — min/max bound it); 0 denies without delegating. Default 60. */
92
+ windowSeconds: z<number, number, "volatile-defined">;
93
+ /** Settled when the window expires; 'allowed-once' is not in the union. */
94
+ defaultOutcome: z<"rejected" | "unavailable", "rejected" | "unavailable", "volatile-defined">;
95
+ /**
96
+ * Permission preset pinned into every new session; '' keeps the host default.
97
+ * 'auto' selects the experimental auto approval (requires the
98
+ * `@deepseek-ai/dsh-experimental-auto-review` bundle); any configured preset
99
+ * name is accepted. The host rejects 'auto' as its own `defaultPreset`, and
100
+ * the pinned value is a durable `permission/preset` event, so every later
101
+ * turn reads the real knobs instead of a component-side override.
102
+ */
103
+ defaultPermissionPreset: z<string, string, "volatile-defined">;
104
+ /**
105
+ * Append the experimental auto approval's own content to the model-facing
106
+ * tool result when this gate's window (not a human, not another answerer)
107
+ * rejects a request the reviewer raised. Default true.
108
+ */
109
+ autoReviewContent: z<boolean, boolean, "volatile-defined">;
110
+ }>>, Schemastery.ObjectT<NoInfer<{
111
+ /** Session/turn origins treated as unattended. Default: subagent + scheduled. */
112
+ origins: z<NoInfer<("subagent" | "scheduled" | "cron" | "all")[]>, NoInfer<("subagent" | "scheduled" | "cron" | "all")[]>, "volatile-defined">;
113
+ /** Glob patterns matched against the requesting agent id; a hit gates every turn of that session. */
114
+ sessions: z<NoInfer<string[]>, NoInfer<string[]>, "volatile-defined">;
115
+ /** Answer window in seconds (whole seconds; no .int() chain exists — min/max bound it); 0 denies without delegating. Default 60. */
116
+ windowSeconds: z<number, number, "volatile-defined">;
117
+ /** Settled when the window expires; 'allowed-once' is not in the union. */
118
+ defaultOutcome: z<"rejected" | "unavailable", "rejected" | "unavailable", "volatile-defined">;
119
+ /**
120
+ * Permission preset pinned into every new session; '' keeps the host default.
121
+ * 'auto' selects the experimental auto approval (requires the
122
+ * `@deepseek-ai/dsh-experimental-auto-review` bundle); any configured preset
123
+ * name is accepted. The host rejects 'auto' as its own `defaultPreset`, and
124
+ * the pinned value is a durable `permission/preset` event, so every later
125
+ * turn reads the real knobs instead of a component-side override.
126
+ */
127
+ defaultPermissionPreset: z<string, string, "volatile-defined">;
128
+ /**
129
+ * Append the experimental auto approval's own content to the model-facing
130
+ * tool result when this gate's window (not a human, not another answerer)
131
+ * rejects a request the reviewer raised. Default true.
132
+ */
133
+ autoReviewContent: z<boolean, boolean, "volatile-defined">;
134
+ }>>, "plain">;
135
+ /** Volatile Config fields arrive as live references; `.get()` snapshots. */
136
+ interface VolatileRef<T> {
137
+ get(): T;
138
+ }
139
+ /** The runtime shape `apply` receives (every field volatile). */
140
+ export interface GateRuntimeConfig {
141
+ origins: VolatileRef<UnattendedOrigin[]>;
142
+ sessions: VolatileRef<string[]>;
143
+ windowSeconds: VolatileRef<number>;
144
+ defaultOutcome: VolatileRef<GatedOutcome>;
145
+ defaultPermissionPreset: VolatileRef<string>;
146
+ autoReviewContent: VolatileRef<boolean>;
147
+ }
148
+ /** Canonical identity of the experimental per-call review preset. */
149
+ export declare const AUTO_REVIEW_PRESET = "auto";
150
+ /**
151
+ * The reviewer-owned prefix of an approval reason raised by
152
+ * `@deepseek-ai/dsh-experimental-auto-review` when its review denies a call
153
+ * under the `ask` policy (`Auto review denied tool "<name>": <reason>`).
154
+ * Matching the reason rather than the session preset keeps the attribution
155
+ * correct when the policy switches between the ask and its settlement.
156
+ */
157
+ export declare const AUTO_REVIEW_REASON_PREFIX = "Auto review denied tool \"";
158
+ /**
159
+ * The model-facing denial text the host pipeline renders for ANY `rejected`
160
+ * approval outcome (`packages/core/tools/src/pipeline.ts`). Host 0.2.2-rc.1
161
+ * records no structured error info, so the text is the only stable, version-
162
+ * tolerant discriminator; newer lines also carry `{ name: ApprovalError }`.
163
+ */
164
+ export declare function rejectedApprovalMessage(toolName: string): string;
165
+ /** Whether one failed tool result is the pipeline's rejection of an approval ask. */
166
+ export declare function isRejectedApprovalResult(result: {
167
+ readonly isError: boolean;
168
+ readonly error: {
169
+ readonly message: string;
170
+ readonly info?: {
171
+ readonly name?: string;
172
+ readonly code?: string;
173
+ };
174
+ };
175
+ }, toolName: string): boolean;
176
+ /** Compiled glob: `*` matches anything, everything else is literal. */
177
+ export declare function globToRegExp(pattern: string): RegExp;
178
+ /** What the gate reads off the requesting agent to classify the turn. */
179
+ export interface OriginFacts {
180
+ /** session.header.origin when the live session is readable ('subagent' …). */
181
+ headerOrigin?: string;
182
+ /** source.kind of the session's last user message ('schedule', 'cron', 'user', …). */
183
+ lastUserMessageKind?: string;
184
+ }
185
+ /** Structural slices of the runtime faces — no closure type imports needed. */
186
+ interface MsgLike {
187
+ readonly role?: string;
188
+ readonly source?: {
189
+ readonly kind?: string;
190
+ };
191
+ }
192
+ interface EventLike {
193
+ readonly type?: string;
194
+ }
195
+ interface SessionLike {
196
+ readonly header?: {
197
+ readonly origin?: string;
198
+ };
199
+ deriveMessages?(): MsgLike[];
200
+ snapshotEvents?(): readonly EventLike[];
201
+ }
202
+ interface AgentLike {
203
+ readonly id?: unknown;
204
+ readonly session?: SessionLike;
205
+ }
206
+ /**
207
+ * Read the origin facts off the request's agent. Both reads are best-effort:
208
+ * a projected agent without a live session yields `{}` (only `sessions`/`all`
209
+ * can then gate), and each fact independently degrades to undefined.
210
+ */
211
+ export declare function readFacts(agent: AgentLike | undefined): OriginFacts;
212
+ /** Gate predicate: explicit session hit → 'all' → session/turn origins. */
213
+ export declare function shouldGate(config: {
214
+ readonly origins: readonly UnattendedOrigin[];
215
+ readonly sessions: readonly string[];
216
+ }, sessionId: string, facts: OriginFacts): boolean;
217
+ /** Which side of the race produced the settled outcome. */
218
+ export type GateSettledBy = 'downstream' | 'window';
219
+ /** One gate result: the outcome plus the side that produced it. */
220
+ export interface GateSettlement {
221
+ readonly outcome: ApprovalOutcome;
222
+ readonly settledBy: GateSettledBy;
223
+ }
224
+ /**
225
+ * The gate: delegate first, race the downstream chain against the window.
226
+ *
227
+ * windowMs <= 0 denies immediately WITHOUT calling `decision` (the 0 = instant
228
+ * deny degenerate case — downstream never sees the request, mirroring the
229
+ * host's approval/policy=never); that settlement is reported as `'window'`
230
+ * because no answerer produced it. A fast `decision` (including an instant
231
+ * fail-closed 'unavailable' from an empty chain) passes through untouched;
232
+ * only a pending decision races the timer.
233
+ */
234
+ export declare function raceGate(decision: () => Promise<ApprovalOutcome>, windowMs: number, defaultOutcome: GatedOutcome): Promise<GateSettlement>;
235
+ /** Whether an approval reason was raised by the experimental auto approval. */
236
+ export declare function isAutoReviewAsk(reason: string | undefined): boolean;
237
+ /** One window-rejected auto-review request waiting for its tool result. */
238
+ export interface AutoReviewSettle {
239
+ /** Tool whose approval the reviewer raised. */
240
+ readonly toolName: string;
241
+ /** The reviewer-owned approval reason, verbatim. */
242
+ readonly reason: string;
243
+ /** Wall clock of the settlement, for TTL pruning. */
244
+ readonly at: number;
245
+ }
246
+ /** Remember one settlement under its tool-call id (absent call ids cannot claim a result). */
247
+ export declare function recordAutoReviewSettle(store: Map<string, AutoReviewSettle>, callId: string | undefined, settle: AutoReviewSettle): void;
248
+ /**
249
+ * Take and forget the settlement for one tool call; expired entries are pruned
250
+ * first so a result arriving after the TTL never claims stale content.
251
+ */
252
+ export declare function takeAutoReviewSettle(store: Map<string, AutoReviewSettle>, callId: string | undefined, now: number): AutoReviewSettle | undefined;
253
+ /** The model-facing sentence appended to the denied tool result. */
254
+ export declare function autoReviewNotice(toolName: string, reason: string): string;
255
+ /** Append the auto approval's content to the model-facing result content. */
256
+ export declare function withAutoReviewContent(content: readonly ContentBlock[], settle: AutoReviewSettle): ContentBlock[];
257
+ /** What the permission projection already recorded in a session log. */
258
+ export interface PermissionFacts {
259
+ /** The session log was readable at all. */
260
+ readonly readable: boolean;
261
+ /** The session already started a turn (a resumed or user-driven session). */
262
+ readonly turnStarted: boolean;
263
+ /** The host (or a user) already recorded permission state. */
264
+ readonly permissionState: boolean;
265
+ /** The log carries the constructor-seed boundary of a seeded session. */
266
+ readonly seeded: boolean;
267
+ }
268
+ /**
269
+ * Fold the permission-relevant facts out of a session log. A session that
270
+ * cannot expose its events is reported unreadable so the caller skips pinning
271
+ * instead of overriding a restored selection it cannot see.
272
+ */
273
+ export declare function readPermissionFacts(session: SessionLike | undefined): PermissionFacts;
274
+ /** Inputs for the default-preset decision. */
275
+ export interface DefaultPresetDecision {
276
+ /** Configured preset name; '' means leave the session alone. */
277
+ readonly configured: string;
278
+ /** Preset the session currently resolves to. */
279
+ readonly current: string;
280
+ /** The host's deployment default preset. */
281
+ readonly hostDefault: string;
282
+ /** Permission facts folded from the session log. */
283
+ readonly facts: PermissionFacts;
284
+ }
285
+ /**
286
+ * Decide whether a new session may take the configured default preset.
287
+ *
288
+ * A session qualifies while it has no turn and no seed boundary. It qualifies
289
+ * either before the host pinned its own default (no permission state yet — the
290
+ * gate ran first) or right after the host pinned exactly that default (the
291
+ * session is still untouched, so the pin is creation-time state rather than a
292
+ * user choice). Anything else is a resumed, seeded, or deliberately switched
293
+ * session and keeps its recorded permission.
294
+ */
295
+ export declare function shouldPinDefaultPreset(decision: DefaultPresetDecision): boolean;
296
+ export declare function apply(ctx: Context, config: GateRuntimeConfig): void;
297
+ export {};