@xi4z/dsh-utils-approval-policy 0.0.0-stage → 0.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/lib/index.js ADDED
@@ -0,0 +1,425 @@
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 z from '@deepseek-ai/schemastery';
73
+ export const name = 'dsh-approval-policy';
74
+ /** Settings-page schema; each key arrives as a volatile live reference. */
75
+ export const Config = z.object({
76
+ /** Session/turn origins treated as unattended. Default: subagent + scheduled. */
77
+ origins: z.array(z.union(['subagent', 'scheduled', 'cron', 'all'])).default(['subagent', 'scheduled']).volatile(),
78
+ /** Glob patterns matched against the requesting agent id; a hit gates every turn of that session. */
79
+ sessions: z.array(z.string()).default([]).volatile(),
80
+ /** Answer window in seconds (whole seconds; no .int() chain exists — min/max bound it); 0 denies without delegating. Default 60. */
81
+ windowSeconds: z.number().min(0).max(86400).default(60).volatile(),
82
+ /** Settled when the window expires; 'allowed-once' is not in the union. */
83
+ defaultOutcome: z.union(['rejected', 'unavailable']).default('rejected').volatile(),
84
+ /**
85
+ * Permission preset pinned into every new session; '' keeps the host default.
86
+ * 'auto' selects the experimental auto approval (requires the
87
+ * `@deepseek-ai/dsh-experimental-auto-review` bundle); any configured preset
88
+ * name is accepted. The host rejects 'auto' as its own `defaultPreset`, and
89
+ * the pinned value is a durable `permission/preset` event, so every later
90
+ * turn reads the real knobs instead of a component-side override.
91
+ */
92
+ defaultPermissionPreset: z.string().default('').volatile(),
93
+ /**
94
+ * Append the experimental auto approval's own content to the model-facing
95
+ * tool result when this gate's window (not a human, not another answerer)
96
+ * rejects a request the reviewer raised. Default true.
97
+ */
98
+ autoReviewContent: z.boolean().default(true).volatile(),
99
+ });
100
+ /** Canonical identity of the experimental per-call review preset. */
101
+ export const AUTO_REVIEW_PRESET = 'auto';
102
+ /**
103
+ * The reviewer-owned prefix of an approval reason raised by
104
+ * `@deepseek-ai/dsh-experimental-auto-review` when its review denies a call
105
+ * under the `ask` policy (`Auto review denied tool "<name>": <reason>`).
106
+ * Matching the reason rather than the session preset keeps the attribution
107
+ * correct when the policy switches between the ask and its settlement.
108
+ */
109
+ export const AUTO_REVIEW_REASON_PREFIX = 'Auto review denied tool "';
110
+ /** Structured error code the pipeline records for a rejected approval (newer host lines). */
111
+ const APPROVAL_REJECTED_CODE = 'APPROVAL_REJECTED';
112
+ /**
113
+ * The model-facing denial text the host pipeline renders for ANY `rejected`
114
+ * approval outcome (`packages/core/tools/src/pipeline.ts`). Host 0.2.2-rc.1
115
+ * records no structured error info, so the text is the only stable, version-
116
+ * tolerant discriminator; newer lines also carry `{ name: ApprovalError }`.
117
+ */
118
+ export function rejectedApprovalMessage(toolName) {
119
+ return `the user rejected tool "${toolName}"`;
120
+ }
121
+ /** Whether one failed tool result is the pipeline's rejection of an approval ask. */
122
+ export function isRejectedApprovalResult(result, toolName) {
123
+ if (!result.isError)
124
+ return false;
125
+ const info = result.error.info;
126
+ if (info !== undefined && (info.code === APPROVAL_REJECTED_CODE || info.name === 'ApprovalError'))
127
+ return true;
128
+ return result.error.message === rejectedApprovalMessage(toolName);
129
+ }
130
+ /** How long a window-rejected auto-review request may still claim its tool result. */
131
+ const AUTO_REVIEW_SETTLE_TTL_MS = 120_000;
132
+ /** Compiled glob: `*` matches anything, everything else is literal. */
133
+ export function globToRegExp(pattern) {
134
+ const escaped = pattern
135
+ .replace(/[.+^${}()|[\]\\?]/g, '\\$&')
136
+ .replace(/\*/g, '.*');
137
+ return new RegExp(`^(?:${escaped})$`);
138
+ }
139
+ /**
140
+ * Kinds that carry a turn's human/machine provenance. The host also injects
141
+ * SYNTHETIC context messages into the role='user' stream after a turn starts
142
+ * (runtime-context snapshots, skill-catalog reminders, …); they always sit
143
+ * after the real trigger and would shadow it, so the backward scan skips any
144
+ * user-role message whose kind is not one of these (a missing kind is legacy
145
+ * human input and counts as 'user'). Live-tested: without this skip, every
146
+ * cron/scheduled turn misclassified as interactive and slipped through
147
+ * unwindowed.
148
+ *
149
+ * 'user-question-reply' (dsh 0.2.0 timed ask, experimental) is the LATE
150
+ * answer to a timed-out question flowing back as a user-role message — hard
151
+ * proof a human was there. It stops the scan with the same standing as an
152
+ * explicit 'user' steer (the turn stays interactive); skipping it as
153
+ * synthetic would shadow it with the cron/schedule trigger that fired
154
+ * BEFORE the human answered.
155
+ */
156
+ const PROVENANCE_KINDS = new Set(['user', 'schedule', 'cron', 'user-question-reply']);
157
+ /**
158
+ * Read the origin facts off the request's agent. Both reads are best-effort:
159
+ * a projected agent without a live session yields `{}` (only `sessions`/`all`
160
+ * can then gate), and each fact independently degrades to undefined.
161
+ */
162
+ export function readFacts(agent) {
163
+ const session = agent?.session;
164
+ if (!session)
165
+ return {};
166
+ const facts = { headerOrigin: session.header?.origin };
167
+ const messages = session.deriveMessages?.();
168
+ if (messages) {
169
+ for (let i = messages.length - 1; i >= 0; i -= 1) {
170
+ const message = messages[i];
171
+ if (message?.role !== 'user')
172
+ continue;
173
+ const kind = message.source?.kind;
174
+ if (kind === undefined || PROVENANCE_KINDS.has(kind)) {
175
+ facts.lastUserMessageKind = kind ?? 'user';
176
+ break;
177
+ }
178
+ // synthetic context injection — keep scanning for the real trigger
179
+ }
180
+ }
181
+ return facts;
182
+ }
183
+ /** Gate predicate: explicit session hit → 'all' → session/turn origins. */
184
+ export function shouldGate(config, sessionId, facts) {
185
+ if (config.sessions.length > 0 && config.sessions.some((pattern) => {
186
+ try {
187
+ return globToRegExp(pattern).test(sessionId);
188
+ }
189
+ catch {
190
+ return false; // a malformed pattern must not break approvals
191
+ }
192
+ }))
193
+ return true;
194
+ const origins = config.origins;
195
+ if (origins.includes('all'))
196
+ return true;
197
+ if (origins.includes('subagent') && facts.headerOrigin === 'subagent')
198
+ return true;
199
+ const kind = facts.lastUserMessageKind;
200
+ if (kind === 'schedule' && origins.includes('scheduled'))
201
+ return true;
202
+ if (kind === 'cron' && origins.includes('cron'))
203
+ return true;
204
+ return false;
205
+ }
206
+ /**
207
+ * The gate: delegate first, race the downstream chain against the window.
208
+ *
209
+ * windowMs <= 0 denies immediately WITHOUT calling `decision` (the 0 = instant
210
+ * deny degenerate case — downstream never sees the request, mirroring the
211
+ * host's approval/policy=never); that settlement is reported as `'window'`
212
+ * because no answerer produced it. A fast `decision` (including an instant
213
+ * fail-closed 'unavailable' from an empty chain) passes through untouched;
214
+ * only a pending decision races the timer.
215
+ */
216
+ export async function raceGate(decision, windowMs, defaultOutcome) {
217
+ if (windowMs <= 0)
218
+ return { outcome: defaultOutcome, settledBy: 'window' };
219
+ // The window timer stays REF'd on purpose: an open window means the host
220
+ // turn is still owed an outcome, so the process must not drain the event
221
+ // loop before it settles. It is cleared as soon as the race settles
222
+ // (answer, rejection, or expiry) so a fast answer never leaves a stray
223
+ // timer holding the loop for the rest of the window.
224
+ let timer;
225
+ try {
226
+ const windowSettlement = new Promise((resolve) => {
227
+ timer = setTimeout(() => resolve({ outcome: defaultOutcome, settledBy: 'window' }), windowMs);
228
+ });
229
+ return await Promise.race([
230
+ decision().then((outcome) => ({ outcome, settledBy: 'downstream' })),
231
+ windowSettlement,
232
+ ]);
233
+ }
234
+ finally {
235
+ if (timer !== undefined)
236
+ clearTimeout(timer);
237
+ }
238
+ }
239
+ /** Whether an approval reason was raised by the experimental auto approval. */
240
+ export function isAutoReviewAsk(reason) {
241
+ return typeof reason === 'string' && reason.startsWith(AUTO_REVIEW_REASON_PREFIX);
242
+ }
243
+ /** Remember one settlement under its tool-call id (absent call ids cannot claim a result). */
244
+ export function recordAutoReviewSettle(store, callId, settle) {
245
+ if (callId === undefined || callId === '')
246
+ return;
247
+ store.set(callId, settle);
248
+ }
249
+ /**
250
+ * Take and forget the settlement for one tool call; expired entries are pruned
251
+ * first so a result arriving after the TTL never claims stale content.
252
+ */
253
+ export function takeAutoReviewSettle(store, callId, now) {
254
+ for (const [key, settle] of store) {
255
+ if (now - settle.at > AUTO_REVIEW_SETTLE_TTL_MS)
256
+ store.delete(key);
257
+ }
258
+ if (callId === undefined || callId === '')
259
+ return undefined;
260
+ const settle = store.get(callId);
261
+ if (settle === undefined)
262
+ return undefined;
263
+ store.delete(callId);
264
+ return settle;
265
+ }
266
+ /** The model-facing sentence appended to the denied tool result. */
267
+ export function autoReviewNotice(toolName, reason) {
268
+ return 'The unattended approval window expired before anyone answered, so this request was rejected '
269
+ + `instead of being answered by the user. The pending request for tool "${toolName}" came from the `
270
+ + `experimental auto approval (auto review); its content follows:\n\n${reason}`;
271
+ }
272
+ /** Append the auto approval's content to the model-facing result content. */
273
+ export function withAutoReviewContent(content, settle) {
274
+ return [
275
+ ...content,
276
+ { type: 'text', text: `\n\n${autoReviewNotice(settle.toolName, settle.reason)}` },
277
+ ];
278
+ }
279
+ const PERMISSION_EVENT_TYPES = new Set([
280
+ 'permission/preset',
281
+ 'sandbox/mode',
282
+ 'approval/policy',
283
+ 'session/end-seed',
284
+ ]);
285
+ /**
286
+ * Fold the permission-relevant facts out of a session log. A session that
287
+ * cannot expose its events is reported unreadable so the caller skips pinning
288
+ * instead of overriding a restored selection it cannot see.
289
+ */
290
+ export function readPermissionFacts(session) {
291
+ const events = session?.snapshotEvents?.();
292
+ if (events === undefined) {
293
+ return { readable: false, turnStarted: true, permissionState: true, seeded: true };
294
+ }
295
+ let turnStarted = false;
296
+ let permissionState = false;
297
+ let seeded = false;
298
+ for (const event of events) {
299
+ const type = event?.type;
300
+ if (type === 'turn/start')
301
+ turnStarted = true;
302
+ else if (type === 'session/end-seed') {
303
+ permissionState = true;
304
+ seeded = true;
305
+ }
306
+ else if (type !== undefined && PERMISSION_EVENT_TYPES.has(type))
307
+ permissionState = true;
308
+ }
309
+ return { readable: true, turnStarted, permissionState, seeded };
310
+ }
311
+ /**
312
+ * Decide whether a new session may take the configured default preset.
313
+ *
314
+ * A session qualifies while it has no turn and no seed boundary. It qualifies
315
+ * either before the host pinned its own default (no permission state yet — the
316
+ * gate ran first) or right after the host pinned exactly that default (the
317
+ * session is still untouched, so the pin is creation-time state rather than a
318
+ * user choice). Anything else is a resumed, seeded, or deliberately switched
319
+ * session and keeps its recorded permission.
320
+ */
321
+ export function shouldPinDefaultPreset(decision) {
322
+ const { configured, current, hostDefault, facts } = decision;
323
+ if (configured === '' || current === configured)
324
+ return false;
325
+ if (!facts.readable || facts.turnStarted || facts.seeded)
326
+ return false;
327
+ return !facts.permissionState || current === hostDefault;
328
+ }
329
+ /** Read the optional permission-presets service without importing its module. */
330
+ function permissionPresetsOf(ctx) {
331
+ return ctx.get('permissionPresets');
332
+ }
333
+ export function apply(ctx, config) {
334
+ const cfgNow = () => ({
335
+ origins: config.origins.get(),
336
+ sessions: config.sessions.get(),
337
+ windowSeconds: config.windowSeconds.get(),
338
+ defaultOutcome: config.defaultOutcome.get(),
339
+ defaultPermissionPreset: config.defaultPermissionPreset.get(),
340
+ autoReviewContent: config.autoReviewContent.get(),
341
+ });
342
+ /** Window-rejected auto-review requests, keyed by tool-call id. */
343
+ const pendingAutoReview = new Map();
344
+ const listener = async (request, next) => {
345
+ const cfg = cfgNow();
346
+ const sessionId = String(request.agent?.id ?? '');
347
+ if (!shouldGate(cfg, sessionId, readFacts(request.agent)))
348
+ return next();
349
+ const settlement = await raceGate(next, cfg.windowSeconds * 1000, cfg.defaultOutcome);
350
+ if (settlement.settledBy === 'window'
351
+ && settlement.outcome === 'rejected'
352
+ && cfg.autoReviewContent
353
+ && isAutoReviewAsk(request.reason)) {
354
+ recordAutoReviewSettle(pendingAutoReview, request.callId === undefined ? undefined : String(request.callId), {
355
+ toolName: request.toolName,
356
+ reason: request.reason,
357
+ at: Date.now(),
358
+ });
359
+ }
360
+ return settlement.outcome;
361
+ };
362
+ /**
363
+ * Append the reviewer's content to a rejection this gate produced. The
364
+ * listener delegates with next() first so every other post-execute policy
365
+ * still runs, then edits only the accepted content of an APPROVAL_REJECTED
366
+ * failure that matches a recorded window settlement.
367
+ */
368
+ const postExecute = async (exec, result, next) => {
369
+ if (!result.isError || !isRejectedApprovalResult(result, exec.name))
370
+ return next();
371
+ const settle = takeAutoReviewSettle(pendingAutoReview, exec.callId === undefined ? undefined : String(exec.callId), Date.now());
372
+ if (settle === undefined)
373
+ return next();
374
+ const downstream = await next();
375
+ if (downstream.kind !== 'accept')
376
+ return downstream;
377
+ // A value-replacing accept cannot apply to a failed result; leave it to the pipeline's own rejection.
378
+ if ('value' in downstream)
379
+ return downstream;
380
+ return {
381
+ kind: 'accept',
382
+ content: withAutoReviewContent(downstream.content ?? result.content, settle),
383
+ ...downstream.additionalContexts === undefined ? {} : { additionalContexts: downstream.additionalContexts },
384
+ };
385
+ };
386
+ /**
387
+ * Pin the configured default preset into a new session. A deployment that
388
+ * asks for a preset the composition does not publish throws here, which
389
+ * vetoes agent publication — a missing auto-review bundle must be visible,
390
+ * not a silently interactive session.
391
+ */
392
+ const pinDefaultPreset = (payload) => {
393
+ const configured = config.defaultPermissionPreset.get();
394
+ if (configured === '')
395
+ return;
396
+ const presets = permissionPresetsOf(ctx);
397
+ if (presets === undefined) {
398
+ throw new Error(`dsh-approval-policy: defaultPermissionPreset "${configured}" requires ctx.permissionPresets, which this composition does not mount`);
399
+ }
400
+ if (!presets.names.includes(configured)) {
401
+ 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`);
402
+ }
403
+ const session = payload.agent?.session;
404
+ if (session === undefined)
405
+ return;
406
+ if (shouldPinDefaultPreset({
407
+ configured,
408
+ current: presets.current(session),
409
+ hostDefault: presets.defaultPreset,
410
+ facts: readPermissionFacts(session),
411
+ }))
412
+ presets.set(session, configured);
413
+ };
414
+ // prepend keeps the gate ahead of interactive answerers regardless of
415
+ // plugin load order; gated requests still reach them via next().
416
+ const disposeGate = ctx.on('approval/request', listener, { prepend: true });
417
+ // prepend so the rejection is edited before later policies materialize it;
418
+ // next() still runs so no other post-execute policy is skipped.
419
+ const disposePostExecute = ctx.on('tools/post-execute', postExecute, { prepend: true });
420
+ const disposePin = ctx.on('agent/created', pinDefaultPreset);
421
+ ctx.effect(() => disposeGate);
422
+ ctx.effect(() => disposePostExecute);
423
+ ctx.effect(() => disposePin);
424
+ }
425
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AAGH,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAMxC,MAAM,CAAC,MAAM,IAAI,GAAG,qBAAqB,CAAA;AAYzC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,CAAC,MAAM,CAA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AC,kBAAkB,EAAE,QAAQ,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAA;IAC3E,2EAA2E;IAC3E,gEAAgE;IAChE,MAAM,kBAAkB,GAAG,GAAG,CAAC,EAAE,CAAC,oBAAoB,EAAE,WAAW,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAA;IACvF,MAAM,UAAU,GAAG,GAAG,CAAC,EAAE,CAAC,eAAe,EAAE,gBAAyB,CAAC,CAAA;IACrE,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,WAAW,CAAC,CAAA;IAC7B,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,CAAA;IACpC,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,CAAA;AAC9B,CAAC"}
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Unattended approval gate",
4
+ "description": "Bounds subagent / scheduled / cron approval requests with an answer window that settles fail-closed."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "无人值守审批门控",
4
+ "description": "给 subagent/定时/cron 的审批请求设定应答窗口,超时按 fail-closed 落定。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@xi4z/dsh-utils-approval-policy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "dsh-utils component: unattended approval gate that bounds approval requests and settles fail-closed.",
5
+ "license": "MIT",
6
+ "author": "xi4z",
7
+ "homepage": "https://github.com/xi4z/dsh-utils",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/xi4z/dsh-utils.git",
11
+ "directory": "packages/approval-policy"
12
+ },
13
+ "type": "module",
14
+ "main": "./lib/index.js",
15
+ "types": "./lib/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./lib/index.d.ts",
19
+ "import": "./lib/index.js",
20
+ "default": "./lib/index.js"
21
+ },
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./src/*": "./src/*",
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "lib",
28
+ "locale",
29
+ "src"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22.19.0"
33
+ },
34
+ "dependencies": {
35
+ "@deepseek-ai/schemastery": "~3.19.0"
36
+ },
37
+ "peerDependencies": {
38
+ "@deepseek-ai/cordis": "~4.1.0"
39
+ },
40
+ "devDependencies": {
41
+ "@deepseek-ai/cordis": "4.1.0",
42
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.2",
43
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.2",
44
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
45
+ "@deepseek-ai/dsh-user-approval": "0.2.2-rc.2",
46
+ "@types/node": "^24.0.0",
47
+ "typescript": "~5.9.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "build": "tsc -p tsconfig.json",
54
+ "check": "tsc --noEmit -p tsconfig.json",
55
+ "test": "node --test test/*.test.mjs"
56
+ }
6
57
  }