@xi4z/dsh-utils-approval-qq 0.0.0-stage → 0.9.1
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 +21 -0
- package/lib/index.d.ts +217 -0
- package/lib/index.js +485 -0
- package/lib/index.js.map +1 -0
- package/lib/translate.d.ts +40 -0
- package/lib/translate.js +71 -0
- package/lib/translate.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +54 -3
- package/src/index.ts +641 -0
- package/src/translate.ts +106 -0
- package/README.md +0 -3
package/src/index.ts
ADDED
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-utils approval-qq component: mirror a pending approval to QQ as a
|
|
3
|
+
* markdown card with two inline-keyboard buttons, and answer the host's
|
|
4
|
+
* approval waterfall from the click.
|
|
5
|
+
*
|
|
6
|
+
* Division of labour (see the bundle README):
|
|
7
|
+
*
|
|
8
|
+
* - This component owns the APPROVAL semantics: which request is mirrored,
|
|
9
|
+
* how the card reads, the race against the Web GUI, and what gets settled
|
|
10
|
+
* back into the waterfall. It holds no bot credential.
|
|
11
|
+
* - The relay (gotify-qq-relay with its approval listener) owns the QQ edge:
|
|
12
|
+
* sending the card, receiving INTERACTION_CREATE, acking inside 3s, storing
|
|
13
|
+
* the click, and sending the passive receipt. It never decides an approval.
|
|
14
|
+
*
|
|
15
|
+
* There is deliberately no TTL here. The only deadline is the unattended
|
|
16
|
+
* gate's own window (approval-policy windowSeconds), which this component
|
|
17
|
+
* reads through the approvalPolicyInfo service and echoes on the card:
|
|
18
|
+
* "N seconds left, then auto-reject". When that window expires the gate
|
|
19
|
+
* settles the request downstream, so this component closes the card silently
|
|
20
|
+
* and later clicks do nothing.
|
|
21
|
+
*
|
|
22
|
+
* The card is sent only after a short debounce: an auto-review decision inside
|
|
23
|
+
* that window means no human is needed, so no card is sent at all.
|
|
24
|
+
*
|
|
25
|
+
* @module dsh-utils/approval-qq
|
|
26
|
+
*/
|
|
27
|
+
import { hostname } from 'node:os'
|
|
28
|
+
import { randomBytes } from 'node:crypto'
|
|
29
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
30
|
+
import z from '@deepseek-ai/schemastery'
|
|
31
|
+
import type { ApprovalOutcome } from '@deepseek-ai/dsh-user-approval/types'
|
|
32
|
+
import { needsTranslation, translateToChinese, type LlmRuntime, type ModelRoute } from './translate.js'
|
|
33
|
+
|
|
34
|
+
export const name = 'dsh-approval-qq'
|
|
35
|
+
|
|
36
|
+
/** Settings-page schema. Every key is volatile: reads are live on each request. */
|
|
37
|
+
export const Config = z.object({
|
|
38
|
+
enabled: z.boolean().default(false).description('Mirror approvals to QQ. Off means the waterfall is untouched.').volatile(),
|
|
39
|
+
relayUrl: z.string().default('').description('Relay approval base URL, ending in /approval; supports ENV references.').volatile(),
|
|
40
|
+
sharedKey: z.string().default('').role('secret').description('Shared key for the relay approval endpoints. Write-only secret: editable in settings, never returned to the browser; configure it explicitly.').volatile(),
|
|
41
|
+
deviceLabel: z.string().default('').description('Human-readable device name shown on the card; empty = hostname.').volatile(),
|
|
42
|
+
sendDelayMs: z.natural().default(1200).description('Debounce before sending: an auto-decision inside it sends no card.').volatile(),
|
|
43
|
+
pollWaitSeconds: z.natural().min(1).max(30).default(25).description('Long-poll window while waiting for a click.').volatile(),
|
|
44
|
+
timeoutMs: z.natural().min(500).default(10000).description('Single relay HTTP timeout.').volatile(),
|
|
45
|
+
includeSubagents: z.boolean().default(true).description('Also mirror approvals raised by subagent sessions.').volatile(),
|
|
46
|
+
dryRun: z.boolean().default(false).description('Log the card instead of sending it.').volatile(),
|
|
47
|
+
allowReceipt: z.string().default('').description('Passive reply after an allow click; empty = no callback (silent).').volatile(),
|
|
48
|
+
denyReceipt: z.string().default('').description('Passive reply after a deny click; empty = no callback (silent).').volatile(),
|
|
49
|
+
translateEnglish: z.boolean().default(true).description('Translate English approval reasons to Chinese via the host model before rendering the card.').volatile(),
|
|
50
|
+
translateTimeoutMs: z.natural().min(200).default(4000).description('Translation budget; on timeout the original English is kept.').volatile(),
|
|
51
|
+
translateProvider: z.string().default('').description('Provider override for translation; empty = the host agentDefaultModel route.').volatile(),
|
|
52
|
+
translateModel: z.string().default('').description('Model override for translation; empty = the host agentDefaultModel route.').volatile(),
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
/** Volatile Config fields arrive as live references; .get() snapshots. */
|
|
56
|
+
interface VolatileRef<T> {
|
|
57
|
+
get(): T
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One setting as the Loader supplies it: a live reference, or a plain value in tests. */
|
|
61
|
+
type MaybeRef<T> = T | VolatileRef<T>
|
|
62
|
+
|
|
63
|
+
/** The runtime shape apply receives (every field volatile, every field optional). */
|
|
64
|
+
export interface ApprovalQqConfig {
|
|
65
|
+
readonly enabled?: MaybeRef<boolean>
|
|
66
|
+
readonly relayUrl?: MaybeRef<string>
|
|
67
|
+
readonly sharedKey?: MaybeRef<string>
|
|
68
|
+
readonly deviceLabel?: MaybeRef<string>
|
|
69
|
+
readonly sendDelayMs?: MaybeRef<number>
|
|
70
|
+
readonly pollWaitSeconds?: MaybeRef<number>
|
|
71
|
+
readonly timeoutMs?: MaybeRef<number>
|
|
72
|
+
readonly includeSubagents?: MaybeRef<boolean>
|
|
73
|
+
readonly dryRun?: MaybeRef<boolean>
|
|
74
|
+
readonly allowReceipt?: MaybeRef<string>
|
|
75
|
+
readonly denyReceipt?: MaybeRef<string>
|
|
76
|
+
readonly translateEnglish?: MaybeRef<boolean>
|
|
77
|
+
readonly translateTimeoutMs?: MaybeRef<number>
|
|
78
|
+
readonly translateProvider?: MaybeRef<string>
|
|
79
|
+
readonly translateModel?: MaybeRef<string>
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Normalized options with every default applied. */
|
|
83
|
+
export interface ResolvedOptions {
|
|
84
|
+
enabled: boolean
|
|
85
|
+
relayUrl: string
|
|
86
|
+
sharedKey: string
|
|
87
|
+
deviceLabel: string
|
|
88
|
+
sendDelayMs: number
|
|
89
|
+
pollWaitSeconds: number
|
|
90
|
+
timeoutMs: number
|
|
91
|
+
includeSubagents: boolean
|
|
92
|
+
dryRun: boolean
|
|
93
|
+
allowReceipt: string
|
|
94
|
+
denyReceipt: string
|
|
95
|
+
translateEnglish: boolean
|
|
96
|
+
translateTimeoutMs: number
|
|
97
|
+
translateProvider: string
|
|
98
|
+
translateModel: string
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Structural logger slice (matches the host logger without importing it). */
|
|
102
|
+
export interface Logger {
|
|
103
|
+
info(format: unknown, ...param: unknown[]): void
|
|
104
|
+
warn(format: unknown, ...param: unknown[]): void
|
|
105
|
+
debug?(format: unknown, ...param: unknown[]): void
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The read-only view approval-policy publishes on the cordis context. */
|
|
109
|
+
export interface ApprovalPolicyInfo {
|
|
110
|
+
describe(agent: unknown, sessionId: string): {
|
|
111
|
+
gated: boolean
|
|
112
|
+
windowMs: number
|
|
113
|
+
defaultOutcome: 'rejected' | 'unavailable'
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Structural session/agent/request slices, mirroring dsh types without importing them. */
|
|
118
|
+
interface SessionEventLike {
|
|
119
|
+
readonly type?: string
|
|
120
|
+
readonly data?: { readonly callId?: unknown; readonly arguments?: unknown }
|
|
121
|
+
}
|
|
122
|
+
interface SessionLike {
|
|
123
|
+
readonly header?: { readonly cwd?: string; readonly origin?: string }
|
|
124
|
+
readonly events?: readonly SessionEventLike[]
|
|
125
|
+
}
|
|
126
|
+
interface AgentLike {
|
|
127
|
+
readonly id?: unknown
|
|
128
|
+
readonly session?: SessionLike
|
|
129
|
+
}
|
|
130
|
+
export interface ApprovalRequestLike {
|
|
131
|
+
readonly agent: AgentLike
|
|
132
|
+
readonly toolName: string
|
|
133
|
+
readonly callId?: unknown
|
|
134
|
+
readonly reason?: string
|
|
135
|
+
readonly signal?: AbortSignal
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function unwrap<T>(value: MaybeRef<T> | undefined): T | undefined {
|
|
139
|
+
if (value !== null && typeof value === 'object' && typeof (value as VolatileRef<T>).get === 'function') {
|
|
140
|
+
return (value as VolatileRef<T>).get()
|
|
141
|
+
}
|
|
142
|
+
return value as T | undefined
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function text(value: unknown, fallback: string): string {
|
|
146
|
+
return typeof value === 'string' ? value : fallback
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function num(value: unknown, fallback: number, minimum = 0): number {
|
|
150
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= minimum ? value : fallback
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function bool(value: unknown, fallback: boolean): boolean {
|
|
154
|
+
return typeof value === 'boolean' ? value : fallback
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Expand name / name-with-fallback environment references in a setting. */
|
|
158
|
+
export function expandEnv(value: unknown): string {
|
|
159
|
+
const pattern = new RegExp('\\$\\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?}', 'g')
|
|
160
|
+
return String(value ?? '').replace(pattern, (_whole, key: string, fallback?: string) => {
|
|
161
|
+
const found = process.env[key]
|
|
162
|
+
return typeof found === 'string' && found.trim() !== '' ? found.trim() : (fallback ?? '')
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function safeHostname(): string {
|
|
167
|
+
try {
|
|
168
|
+
return hostname() || 'unknown'
|
|
169
|
+
} catch {
|
|
170
|
+
return 'unknown'
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Resolve the live config into one concrete option set. */
|
|
175
|
+
export function resolveOptions(config: ApprovalQqConfig | undefined): ResolvedOptions {
|
|
176
|
+
const value = <T>(key: keyof ApprovalQqConfig): T | undefined => unwrap<T>(config?.[key] as MaybeRef<T> | undefined)
|
|
177
|
+
const relayUrl = expandEnv(value<string>('relayUrl')).replace(/\/+$/, '')
|
|
178
|
+
return {
|
|
179
|
+
enabled: bool(value<boolean>('enabled'), false),
|
|
180
|
+
relayUrl: relayUrl === '' || /\/approval$/.test(relayUrl) ? relayUrl : relayUrl + '/approval',
|
|
181
|
+
// Deliberately not expandEnv: the shared key is an explicit write-only secret.
|
|
182
|
+
sharedKey: text(value<string>('sharedKey'), ''),
|
|
183
|
+
deviceLabel: text(value<string>('deviceLabel'), '') || safeHostname(),
|
|
184
|
+
sendDelayMs: num(value<number>('sendDelayMs'), 1200),
|
|
185
|
+
pollWaitSeconds: Math.min(30, Math.max(1, num(value<number>('pollWaitSeconds'), 25, 1))),
|
|
186
|
+
timeoutMs: num(value<number>('timeoutMs'), 10000, 500),
|
|
187
|
+
includeSubagents: bool(value<boolean>('includeSubagents'), true),
|
|
188
|
+
dryRun: bool(value<boolean>('dryRun'), false),
|
|
189
|
+
allowReceipt: text(value<string>('allowReceipt'), ''),
|
|
190
|
+
denyReceipt: text(value<string>('denyReceipt'), ''),
|
|
191
|
+
translateEnglish: bool(value<boolean>('translateEnglish'), true),
|
|
192
|
+
translateTimeoutMs: Math.max(200, num(value<number>('translateTimeoutMs'), 4000, 200)),
|
|
193
|
+
translateProvider: text(value<string>('translateProvider'), ''),
|
|
194
|
+
translateModel: text(value<string>('translateModel'), ''),
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Human-readable remaining time for the countdown line. */
|
|
199
|
+
export function formatDuration(ms: number): string {
|
|
200
|
+
const seconds = Math.max(1, Math.round(ms / 1000))
|
|
201
|
+
if (seconds < 90) return seconds + ' 秒'
|
|
202
|
+
const minutes = Math.round(seconds / 60)
|
|
203
|
+
if (minutes < 90) return minutes + ' 分钟'
|
|
204
|
+
return Math.round(minutes / 60) + ' 小时'
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** One deadline line: countdown plus the wall-clock deadline. */
|
|
208
|
+
export function deadlineLine(input: {
|
|
209
|
+
remainingMs: number
|
|
210
|
+
defaultOutcome: 'rejected' | 'unavailable'
|
|
211
|
+
now?: number
|
|
212
|
+
}): string {
|
|
213
|
+
const at = new Date((input.now ?? Date.now()) + input.remainingMs)
|
|
214
|
+
const clock = [at.getHours(), at.getMinutes(), at.getSeconds()]
|
|
215
|
+
.map((part) => String(part).padStart(2, '0'))
|
|
216
|
+
.join(':')
|
|
217
|
+
const penalty = input.defaultOutcome === 'unavailable'
|
|
218
|
+
? '将自动判定为不可用(fail-closed)'
|
|
219
|
+
: '将自动拒绝'
|
|
220
|
+
return '⏳ **' + formatDuration(input.remainingMs) + '内未处理' + penalty + '**(约 ' + clock + ')\n'
|
|
221
|
+
+ '自动拒绝后,再点按钮不会生效'
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Inputs for an approval card. */
|
|
225
|
+
export interface ApprovalCardInput {
|
|
226
|
+
readonly sessionId: string
|
|
227
|
+
readonly cwd?: string
|
|
228
|
+
readonly device?: string
|
|
229
|
+
readonly toolName: string
|
|
230
|
+
readonly command?: string
|
|
231
|
+
readonly reason?: string
|
|
232
|
+
readonly gated: boolean
|
|
233
|
+
readonly remainingMs?: number
|
|
234
|
+
readonly defaultOutcome?: 'rejected' | 'unavailable'
|
|
235
|
+
readonly now?: number
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function clip(value: string | undefined, limit: number): string | undefined {
|
|
239
|
+
if (value === undefined) return undefined
|
|
240
|
+
const trimmed = value.trim()
|
|
241
|
+
if (trimmed === '') return undefined
|
|
242
|
+
return trimmed.length <= limit ? trimmed : trimmed.slice(0, limit - 1) + '…'
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Triple-backtick fence, built from char codes so this module stays quote-safe. */
|
|
246
|
+
const FENCE = String.fromCharCode(96).repeat(3)
|
|
247
|
+
|
|
248
|
+
/** Render the markdown body of an approval card (the relay adds the keyboard). */
|
|
249
|
+
export function renderApprovalCard(input: ApprovalCardInput): string {
|
|
250
|
+
const shortId = String(input.sessionId).replace(/^session-/, '').slice(0, 8)
|
|
251
|
+
const lines: string[] = ['🔐 **执行审批**', '']
|
|
252
|
+
if (input.device) lines.push('设备: ' + input.device)
|
|
253
|
+
lines.push('会话: ' + shortId)
|
|
254
|
+
if (input.cwd) lines.push('目录: ' + input.cwd)
|
|
255
|
+
lines.push('')
|
|
256
|
+
lines.push('工具: ' + input.toolName)
|
|
257
|
+
const command = clip(input.command, 500)
|
|
258
|
+
if (command) {
|
|
259
|
+
lines.push('')
|
|
260
|
+
lines.push(FENCE)
|
|
261
|
+
lines.push(command)
|
|
262
|
+
lines.push(FENCE)
|
|
263
|
+
}
|
|
264
|
+
const reason = clip(input.reason, 200)
|
|
265
|
+
if (reason) {
|
|
266
|
+
lines.push('')
|
|
267
|
+
lines.push('原因: ' + reason)
|
|
268
|
+
}
|
|
269
|
+
if (input.gated && input.remainingMs !== undefined) {
|
|
270
|
+
lines.push('')
|
|
271
|
+
lines.push(deadlineLine({
|
|
272
|
+
remainingMs: input.remainingMs,
|
|
273
|
+
defaultOutcome: input.defaultOutcome ?? 'rejected',
|
|
274
|
+
now: input.now,
|
|
275
|
+
}))
|
|
276
|
+
}
|
|
277
|
+
return lines.join('\n')
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Find the gated command from the session log by tool-call id. */
|
|
281
|
+
export function commandOf(request: ApprovalRequestLike): string | undefined {
|
|
282
|
+
if (request.callId === undefined) return undefined
|
|
283
|
+
const events = request.agent?.session?.events
|
|
284
|
+
if (!events) return undefined
|
|
285
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
286
|
+
const event = events[index]
|
|
287
|
+
if (!event || event.type !== 'tool/call') continue
|
|
288
|
+
if (String(event.data?.callId) !== String(request.callId)) continue
|
|
289
|
+
const raw = event.data?.arguments
|
|
290
|
+
if (typeof raw !== 'string') return undefined
|
|
291
|
+
try {
|
|
292
|
+
const parsed: unknown = JSON.parse(raw)
|
|
293
|
+
if (parsed !== null && typeof parsed === 'object' && 'command' in parsed) {
|
|
294
|
+
const command = (parsed as { command?: unknown }).command
|
|
295
|
+
if (typeof command === 'string') return command
|
|
296
|
+
}
|
|
297
|
+
} catch {
|
|
298
|
+
// non-JSON arguments: fall back to the raw string below
|
|
299
|
+
}
|
|
300
|
+
return raw
|
|
301
|
+
}
|
|
302
|
+
return undefined
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** One relay long-poll result. */
|
|
306
|
+
export type RelayState =
|
|
307
|
+
| { state: 'pending' }
|
|
308
|
+
| { state: 'clicked'; choice: 'allow' | 'deny' }
|
|
309
|
+
| { state: 'closed'; reason?: string; outcome?: string }
|
|
310
|
+
|
|
311
|
+
/** The relay client slice the answerer needs (injectable for tests). */
|
|
312
|
+
export interface RelayClient {
|
|
313
|
+
create(input: { askId: string; markdown: string; device?: string }): Promise<{ messageId?: string }>
|
|
314
|
+
wait(askId: string, waitSeconds: number, signal?: AbortSignal): Promise<RelayState>
|
|
315
|
+
settle(askId: string, body: {
|
|
316
|
+
outcome: 'allowed-once' | 'rejected' | 'ignored'
|
|
317
|
+
reason?: string
|
|
318
|
+
receipt?: string
|
|
319
|
+
}): Promise<void>
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Build the HTTP client for the relay approval endpoints.
|
|
324
|
+
*
|
|
325
|
+
* baseUrl ends in /approval; endpoints are base, base/askId and
|
|
326
|
+
* base/askId/settle.
|
|
327
|
+
*/
|
|
328
|
+
export function createRelayClient(options: {
|
|
329
|
+
baseUrl: string
|
|
330
|
+
key: string
|
|
331
|
+
timeoutMs: number
|
|
332
|
+
fetchImpl?: typeof fetch
|
|
333
|
+
}): RelayClient {
|
|
334
|
+
const fetchImpl = options.fetchImpl ?? fetch
|
|
335
|
+
const base = options.baseUrl.replace(/\/+$/, '')
|
|
336
|
+
|
|
337
|
+
async function call(path: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {
|
|
338
|
+
const signals = [AbortSignal.timeout(options.timeoutMs)]
|
|
339
|
+
if (signal) signals.push(signal)
|
|
340
|
+
const response = await fetchImpl(base + path, {
|
|
341
|
+
...init,
|
|
342
|
+
headers: {
|
|
343
|
+
'content-type': 'application/json',
|
|
344
|
+
'x-approval-key': options.key,
|
|
345
|
+
...(init.headers ?? {}),
|
|
346
|
+
},
|
|
347
|
+
signal: signals.length === 1 ? signals[0] : AbortSignal.any(signals),
|
|
348
|
+
})
|
|
349
|
+
if (!response.ok) {
|
|
350
|
+
const body = await response.text().catch(() => '')
|
|
351
|
+
throw new Error('relay HTTP ' + response.status + ': ' + body.slice(0, 200))
|
|
352
|
+
}
|
|
353
|
+
return response
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
async create(input) {
|
|
358
|
+
const response = await call('', { method: 'POST', body: JSON.stringify(input) })
|
|
359
|
+
const body = await response.json().catch(() => ({})) as { messageId?: unknown }
|
|
360
|
+
return { messageId: typeof body.messageId === 'string' ? body.messageId : undefined }
|
|
361
|
+
},
|
|
362
|
+
async wait(askId, waitSeconds, signal) {
|
|
363
|
+
const response = await call('/' + encodeURIComponent(askId) + '?wait=' + waitSeconds, { method: 'GET' }, signal)
|
|
364
|
+
const body = await response.json().catch(() => ({})) as { state?: unknown, choice?: unknown, reason?: unknown, outcome?: unknown }
|
|
365
|
+
if (body.state === 'clicked' && (body.choice === 'allow' || body.choice === 'deny')) {
|
|
366
|
+
return { state: 'clicked', choice: body.choice }
|
|
367
|
+
}
|
|
368
|
+
if (body.state === 'closed') {
|
|
369
|
+
return {
|
|
370
|
+
state: 'closed',
|
|
371
|
+
reason: typeof body.reason === 'string' ? body.reason : undefined,
|
|
372
|
+
outcome: typeof body.outcome === 'string' ? body.outcome : undefined,
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
return { state: 'pending' }
|
|
376
|
+
},
|
|
377
|
+
async settle(askId, body) {
|
|
378
|
+
await call('/' + encodeURIComponent(askId) + '/settle', { method: 'POST', body: JSON.stringify(body) })
|
|
379
|
+
},
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Generate a 128-bit ask id (hex). */
|
|
384
|
+
export function randomAskId(): string {
|
|
385
|
+
return randomBytes(16).toString('hex')
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** What an answerer needs; everything injectable so the race is unit-testable. */
|
|
389
|
+
export interface AnswererDeps {
|
|
390
|
+
config: () => ResolvedOptions
|
|
391
|
+
policyInfo?: () => ApprovalPolicyInfo | undefined
|
|
392
|
+
relay: (cfg: ResolvedOptions) => RelayClient | undefined
|
|
393
|
+
now?: () => number
|
|
394
|
+
sleep?: (ms: number) => Promise<void>
|
|
395
|
+
randomId?: () => string
|
|
396
|
+
log?: Logger
|
|
397
|
+
/** Translate an English reason; undefined keeps the source text. */
|
|
398
|
+
translate?: (text: string, budgetMs: number, signal?: AbortSignal) => Promise<string | undefined>
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
type PollOutcome =
|
|
402
|
+
| { kind: 'clicked'; choice: 'allow' | 'deny' }
|
|
403
|
+
| { kind: 'closed' }
|
|
404
|
+
| { kind: 'aborted' }
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Long-poll the relay until a click, a close, or an abort. Network failures
|
|
408
|
+
* back off instead of ending the wait: the approval is still pending.
|
|
409
|
+
*/
|
|
410
|
+
async function waitForClick(relay: RelayClient, askId: string, cfg: ResolvedOptions, signal?: AbortSignal, sleepFn?: (ms: number) => Promise<void>): Promise<PollOutcome> {
|
|
411
|
+
const nap = sleepFn ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
|
|
412
|
+
let failures = 0
|
|
413
|
+
for (;;) {
|
|
414
|
+
if (signal?.aborted) return { kind: 'aborted' }
|
|
415
|
+
try {
|
|
416
|
+
const before = Date.now()
|
|
417
|
+
const state = await relay.wait(askId, cfg.pollWaitSeconds, signal)
|
|
418
|
+
failures = 0
|
|
419
|
+
if (state.state === 'clicked') return { kind: 'clicked', choice: state.choice }
|
|
420
|
+
if (state.state === 'closed') return { kind: 'closed' }
|
|
421
|
+
// A relay that answers `pending` instantly must not turn this into a hot
|
|
422
|
+
// loop; a real long-poll holds the connection for pollWaitSeconds.
|
|
423
|
+
if (Date.now() - before < 250) await new Promise<void>((resolve) => setTimeout(resolve, 250))
|
|
424
|
+
} catch {
|
|
425
|
+
failures += 1
|
|
426
|
+
await nap(Math.min(5000, 500 * failures))
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Build the approval/request answerer.
|
|
433
|
+
*
|
|
434
|
+
* Flow: read the gate window -> call next() immediately (the GUI/downstream
|
|
435
|
+
* chain starts and the window clock ticks) -> debounce -> send the card ->
|
|
436
|
+
* race downstream / click / abort -> settle the relay accordingly.
|
|
437
|
+
*/
|
|
438
|
+
export function createAnswerer(deps: AnswererDeps) {
|
|
439
|
+
return async function answerer(request: ApprovalRequestLike, next: () => Promise<ApprovalOutcome>): Promise<ApprovalOutcome> {
|
|
440
|
+
const cfg = deps.config()
|
|
441
|
+
if (!cfg.enabled || cfg.relayUrl === '' || cfg.sharedKey === '') return next()
|
|
442
|
+
if (!cfg.includeSubagents && request.agent?.session?.header?.origin === 'subagent') return next()
|
|
443
|
+
|
|
444
|
+
const relay = deps.relay(cfg)
|
|
445
|
+
if (!relay) return next()
|
|
446
|
+
|
|
447
|
+
const sessionId = String(request.agent?.id ?? '')
|
|
448
|
+
const info = deps.policyInfo?.()?.describe(request.agent, sessionId)
|
|
449
|
+
const gated = info?.gated === true
|
|
450
|
+
const windowMs = Math.max(0, info?.windowMs ?? 0)
|
|
451
|
+
// A zero window denies without letting anyone answer: don't send a dead card.
|
|
452
|
+
if (gated && windowMs <= 0) return next()
|
|
453
|
+
|
|
454
|
+
const now = deps.now ?? Date.now
|
|
455
|
+
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
|
|
456
|
+
const startedAt = now()
|
|
457
|
+
|
|
458
|
+
let downstreamSettled = false
|
|
459
|
+
const downstream = next().then((outcome) => {
|
|
460
|
+
downstreamSettled = true
|
|
461
|
+
return outcome
|
|
462
|
+
})
|
|
463
|
+
|
|
464
|
+
await sleep(cfg.sendDelayMs)
|
|
465
|
+
if (downstreamSettled) return downstream
|
|
466
|
+
|
|
467
|
+
const remainingBefore = gated ? windowMs - (now() - startedAt) : undefined
|
|
468
|
+
if (remainingBefore !== undefined && remainingBefore <= 0) return downstream
|
|
469
|
+
|
|
470
|
+
// English reasons (typically auto-review escalations) are translated before
|
|
471
|
+
// the card is rendered; a failed translation keeps the original text.
|
|
472
|
+
let reason = request.reason
|
|
473
|
+
if (cfg.translateEnglish && needsTranslation(reason) && deps.translate) {
|
|
474
|
+
const budget = remainingBefore !== undefined
|
|
475
|
+
? Math.max(800, Math.min(cfg.translateTimeoutMs, remainingBefore - 500))
|
|
476
|
+
: cfg.translateTimeoutMs
|
|
477
|
+
const translated = await deps.translate(reason as string, budget, request.signal).catch(() => undefined)
|
|
478
|
+
if (translated !== undefined) reason = translated
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const remainingMs = gated ? windowMs - (now() - startedAt) : undefined
|
|
482
|
+
if (remainingMs !== undefined && remainingMs <= 0) return downstream
|
|
483
|
+
|
|
484
|
+
const askId = (deps.randomId ?? randomAskId)()
|
|
485
|
+
const markdown = renderApprovalCard({
|
|
486
|
+
sessionId,
|
|
487
|
+
cwd: request.agent?.session?.header?.cwd,
|
|
488
|
+
device: cfg.deviceLabel,
|
|
489
|
+
toolName: request.toolName,
|
|
490
|
+
command: commandOf(request),
|
|
491
|
+
reason,
|
|
492
|
+
gated,
|
|
493
|
+
remainingMs,
|
|
494
|
+
defaultOutcome: info?.defaultOutcome,
|
|
495
|
+
now: now(),
|
|
496
|
+
})
|
|
497
|
+
|
|
498
|
+
if (cfg.dryRun) {
|
|
499
|
+
deps.log?.info('dsh-approval-qq: dryRun, would send askId=' + askId + ':\n' + markdown)
|
|
500
|
+
return downstream
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
try {
|
|
504
|
+
await relay.create({ askId, markdown, device: cfg.deviceLabel })
|
|
505
|
+
} catch (error) {
|
|
506
|
+
deps.log?.warn('dsh-approval-qq: card send failed, keeping the GUI chain: ' + String((error as Error)?.message ?? error))
|
|
507
|
+
return downstream
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
const pollAbort = new AbortController()
|
|
511
|
+
const signals: AbortSignal[] = [pollAbort.signal]
|
|
512
|
+
if (request.signal) signals.push(request.signal)
|
|
513
|
+
const pollSignal = AbortSignal.any(signals)
|
|
514
|
+
|
|
515
|
+
const aborted = new Promise<PollOutcome>((resolve) => {
|
|
516
|
+
if (request.signal?.aborted) {
|
|
517
|
+
resolve({ kind: 'aborted' })
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
request.signal?.addEventListener('abort', () => resolve({ kind: 'aborted' }), { once: true })
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
try {
|
|
524
|
+
const winner = await Promise.race([
|
|
525
|
+
downstream.then((outcome) => ({ kind: 'downstream' as const, outcome })),
|
|
526
|
+
waitForClick(relay, askId, cfg, pollSignal, sleep),
|
|
527
|
+
aborted,
|
|
528
|
+
])
|
|
529
|
+
|
|
530
|
+
if (winner.kind === 'downstream') {
|
|
531
|
+
const elapsed = now() - startedAt
|
|
532
|
+
const reason = gated && elapsed >= windowMs - 100 ? 'auto-rejected' : 'answered-elsewhere'
|
|
533
|
+
await relay.settle(askId, { outcome: 'ignored', reason }).catch(() => {})
|
|
534
|
+
return winner.outcome
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (winner.kind === 'aborted') {
|
|
538
|
+
await relay.settle(askId, { outcome: 'ignored', reason: 'aborted' }).catch(() => {})
|
|
539
|
+
return 'cancelled'
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
if (winner.kind === 'closed') {
|
|
543
|
+
// The relay closed the card without an honored click (restart/expiry race).
|
|
544
|
+
// Nothing to settle; treat the request as withdrawn.
|
|
545
|
+
return 'cancelled'
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
const outcome: ApprovalOutcome = winner.choice === 'allow' ? 'allowed-once' : 'rejected'
|
|
549
|
+
await relay.settle(askId, {
|
|
550
|
+
outcome,
|
|
551
|
+
receipt: winner.choice === 'allow' ? cfg.allowReceipt : cfg.denyReceipt,
|
|
552
|
+
}).catch((error) => {
|
|
553
|
+
deps.log?.warn('dsh-approval-qq: settle failed: ' + String((error as Error)?.message ?? error))
|
|
554
|
+
})
|
|
555
|
+
return outcome
|
|
556
|
+
} finally {
|
|
557
|
+
pollAbort.abort()
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* Activate the component.
|
|
564
|
+
* @param ctx - host Cordis context.
|
|
565
|
+
* @param config - row config; volatile fields arrive as live references.
|
|
566
|
+
*/
|
|
567
|
+
export function apply(ctx: Context, config: ApprovalQqConfig = {}): void {
|
|
568
|
+
const log = (ctx as unknown as { logger: Logger }).logger
|
|
569
|
+
const read = (): ResolvedOptions => resolveOptions(config)
|
|
570
|
+
|
|
571
|
+
const policyInfo = (): ApprovalPolicyInfo | undefined => {
|
|
572
|
+
const get = (ctx as unknown as { get?: (name: string) => unknown }).get
|
|
573
|
+
return typeof get === 'function' ? get('approvalPolicyInfo') as ApprovalPolicyInfo | undefined : undefined
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const serviceOf = (serviceName: string): unknown => {
|
|
577
|
+
const get = (ctx as unknown as { get?: (key: string) => unknown }).get
|
|
578
|
+
return typeof get === 'function' ? get(serviceName) : undefined
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const translationCache = new Map<string, string>()
|
|
582
|
+
const resolveModelRoute = (cfg: ResolvedOptions): ModelRoute | undefined => {
|
|
583
|
+
if (cfg.translateProvider !== '' && cfg.translateModel !== '') {
|
|
584
|
+
return { provider: cfg.translateProvider, model: cfg.translateModel }
|
|
585
|
+
}
|
|
586
|
+
try {
|
|
587
|
+
const selection = (serviceOf('agentDefaultModel') as {
|
|
588
|
+
currentSelection?: () => { provider?: unknown, model?: unknown }
|
|
589
|
+
} | undefined)?.currentSelection?.()
|
|
590
|
+
if (typeof selection?.provider === 'string' && typeof selection.model === 'string'
|
|
591
|
+
&& selection.provider !== '' && selection.model !== '') {
|
|
592
|
+
return { provider: selection.provider, model: selection.model }
|
|
593
|
+
}
|
|
594
|
+
} catch {
|
|
595
|
+
// a missing or projecting service is not fatal: fall back to English
|
|
596
|
+
}
|
|
597
|
+
return undefined
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const translate = async (source: string, budgetMs: number, signal?: AbortSignal): Promise<string | undefined> => {
|
|
601
|
+
const cached = translationCache.get(source)
|
|
602
|
+
if (cached !== undefined) return cached
|
|
603
|
+
const llm = serviceOf('llm') as LlmRuntime | undefined
|
|
604
|
+
if (!llm || typeof llm.stream !== 'function') return undefined
|
|
605
|
+
const route = resolveModelRoute(read())
|
|
606
|
+
if (route === undefined) {
|
|
607
|
+
log.warn('dsh-approval-qq: no model route for translation; keeping the English reason')
|
|
608
|
+
return undefined
|
|
609
|
+
}
|
|
610
|
+
try {
|
|
611
|
+
const translated = await translateToChinese(llm, route, source, { timeoutMs: budgetMs, signal })
|
|
612
|
+
if (translated === undefined) return undefined
|
|
613
|
+
if (translationCache.size >= 100) {
|
|
614
|
+
const oldest = translationCache.keys().next().value
|
|
615
|
+
if (oldest !== undefined) translationCache.delete(oldest)
|
|
616
|
+
}
|
|
617
|
+
translationCache.set(source, translated)
|
|
618
|
+
return translated
|
|
619
|
+
} catch (error) {
|
|
620
|
+
log.warn('dsh-approval-qq: translation failed: ' + String((error as Error)?.message ?? error))
|
|
621
|
+
return undefined
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
const answerer = createAnswerer({
|
|
626
|
+
config: read,
|
|
627
|
+
policyInfo,
|
|
628
|
+
relay: (cfg) => createRelayClient({ baseUrl: cfg.relayUrl, key: cfg.sharedKey, timeoutMs: cfg.timeoutMs }),
|
|
629
|
+
translate,
|
|
630
|
+
log,
|
|
631
|
+
})
|
|
632
|
+
|
|
633
|
+
const initial = read()
|
|
634
|
+
log.info(
|
|
635
|
+
'dsh-approval-qq: active (enabled=' + initial.enabled + ', relay=' + (initial.relayUrl === '' ? '<unset>' : initial.relayUrl) + ', '
|
|
636
|
+
+ 'device=' + initial.deviceLabel + ', sendDelay=' + initial.sendDelayMs + 'ms, dryRun=' + initial.dryRun + ')',
|
|
637
|
+
)
|
|
638
|
+
|
|
639
|
+
const dispose = ctx.on('approval/request', answerer as never, { prepend: true })
|
|
640
|
+
ctx.effect(() => dispose)
|
|
641
|
+
}
|