@linxin666/dsh-win-bash 0.4.18 → 0.4.19

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/gate.ts DELETED
@@ -1,308 +0,0 @@
1
- /**
2
- * LiangShen availability gate for the win_bash tool.
3
- *
4
- * win_bash serves sessions that run the LiangShen (梁神) preset, so its
5
- * availability follows that preset's DECLARATION: this gate asks the harness's
6
- * agent-preset registry whether a preset with id liangshen is declared, and the
7
- * entry registers no tool at all when it is not. The alternative — mounting a
8
- * tool whose every call refuses — teaches the model a capability the session
9
- * does not have, which is worse than an honest absence.
10
- *
11
- * The registry read is STRUCTURAL, not an import: this package does not depend
12
- * on @deepseek-ai/dsh-agent-preset-registry (a leaf plugin takes no SDK
13
- * dependency to read one optional service), so the single method consumed is
14
- * mirrored from the published declaration of
15
- * @deepseek-ai/dsh-agent-preset-registry@0.2.2-rc.1, lib/types/index.d.ts:
16
- *
17
- * export declare class AgentPresetRegistry {
18
- * list(): Promise<AgentPreset[]>
19
- * }
20
- * export interface AgentPreset {
21
- * readonly id: string
22
- * readonly name?: string
23
- * readonly broken?: string
24
- * }
25
- *
26
- * list() is the registry's public DEFINITION roster: it resolves every declared
27
- * definition, including activation failures (which each row reports), so it
28
- * answers exactly the "is this preset declared here" question. The narrower
29
- * resolve(id) cannot: it REJECTS for an undeclared id, so a probe built on it
30
- * would have to read a rejection as "absent" and could not tell that apart from
31
- * a real failure of a preset that IS declared.
32
- *
33
- * The service is read with ctx.get, never a hard inject: a deployment may
34
- * compose no preset registry at all, and waiting on one would pend this row
35
- * forever — which under the Host's boot gate fails the whole web boot rather
36
- * than this one plugin (the trap dsh-liangshen documents as issue #1712).
37
- *
38
- * Timing. Two facts about the pieces this talks to shape the verdict:
39
- *
40
- * 1. Rows in one loader group mount concurrently (the loader starts every entry
41
- * of a group in the same tick), so this row cannot assume the LiangShen row
42
- * ran first. The verdict therefore waits for the Host plugin tree to settle
43
- * before its first read, rather than reading during the boot race.
44
- * 2. The declaration does not arrive with that row's activation return: the
45
- * declaring plugin schedules it on its own detached promise chain (it
46
- * persists module rows, so it cannot block activation on the mount). The
47
- * tree can therefore settle one or more turns BEFORE the registry holds the
48
- * definition, and a single read would answer "not declared" for a
49
- * deployment that is about to declare it.
50
- *
51
- * So a read that already sees the declaration decides immediately and costs
52
- * nothing; a read that does not re-reads on a bounded schedule until the
53
- * declaration appears or the deadline passes. The wait is never paid in the
54
- * common case, and it never turns a late declaration into a refusal. It runs
55
- * entirely off the plugin's activation path (see the entry), so it delays no
56
- * boot work; it only decides when win_bash becomes available.
57
- *
58
- * The registry exposes NO declaration-change event. Its only declared preset
59
- * event is agent-preset/selected, which records one SESSION's committed preset
60
- * to that session's durable log (lib/types/types.d.ts) and says nothing about
61
- * the roster. The verdict is therefore decided once per mount, and a switch
62
- * toggle takes effect through the plugin manager's row refresh, which remounts
63
- * this row and re-runs the gate — the same freshness model the family's row
64
- * ledger uses.
65
- * @module @linxin666/dsh-win-bash/gate
66
- */
67
-
68
- import type { Context } from '@deepseek-ai/cordis'
69
-
70
- /** Preset id whose declaration makes win_bash available. */
71
- export const LIANGSHEN_PRESET_ID = 'liangshen'
72
-
73
- /** Upper bound on the wait for the Host plugin tree to settle, in milliseconds. */
74
- export const GATE_SETTLE_TIMEOUT_MS = 10_000
75
-
76
- /** Upper bound on one registry roster read, in milliseconds. */
77
- export const GATE_READ_TIMEOUT_MS = 10_000
78
-
79
- /**
80
- * How long a roster that does not yet declare LiangShen keeps being re-read,
81
- * in milliseconds. See the module header: the declaring plugin publishes the
82
- * definition on a detached chain, so the tree can settle first. Only paid when
83
- * the declaration is genuinely absent, since a visible one returns at once.
84
- */
85
- export const GATE_DECLARATION_WAIT_MS = 5_000
86
-
87
- /** Re-read cadence during {@link GATE_DECLARATION_WAIT_MS}, in milliseconds. */
88
- export const GATE_POLL_INTERVAL_MS = 250
89
-
90
- /**
91
- * The deadlines and cadence one gate run uses. The defaults are the shipped
92
- * values; tests pass small ones so a bounded wait is exercised without a slow
93
- * suite.
94
- */
95
- export interface GateOptions {
96
- /** Bound on the Host plugin-tree settle wait, in milliseconds. */
97
- settleTimeoutMs?: number
98
- /** Bound on one registry roster read, in milliseconds. */
99
- readTimeoutMs?: number
100
- /** Total time a late declaration may take to appear, in milliseconds. */
101
- declarationWaitMs?: number
102
- /** Re-read cadence during that wait, in milliseconds. */
103
- pollIntervalMs?: number
104
- }
105
-
106
- /** One roster row, as much of it as this gate reads. */
107
- export interface PresetRosterRow {
108
- /** Stable preset identifier. */
109
- readonly id: string
110
- }
111
-
112
- /** The one registry method this gate consumes. */
113
- export interface PresetRosterReader {
114
- /** Read every declared preset, including activation failures. */
115
- list(): Promise<readonly PresetRosterRow[]>
116
- }
117
-
118
- /** Why the gate reached its verdict. */
119
- export type GateReason =
120
- /** The registry declares the LiangShen preset. */
121
- | 'declared'
122
- /** The registry answered and declares no preset with the LiangShen id. */
123
- | 'not-declared'
124
- /** No agent-preset registry usable for this read is published. */
125
- | 'registry-absent'
126
- /** A registry is published, but its roster never answered. */
127
- | 'registry-unreadable'
128
-
129
- /** How far the Host plugin-tree settle got before the roster was read. */
130
- export type SettleStatus =
131
- /** Every Host loader entry and plugin lifecycle task finished. */
132
- | 'settled'
133
- /** No loader service is published, so there was nothing to settle. */
134
- | 'unavailable'
135
- /** The tree did not settle within the settle bound. */
136
- | 'timed-out'
137
-
138
- /** The gate's verdict: whether win_bash may register, and why. */
139
- export interface GateOutcome {
140
- /** True only for {@link GateReason} declared. */
141
- readonly allowed: boolean
142
- /** The reason, for the caller's log line. */
143
- readonly reason: GateReason
144
- /** Whether the Host tree settled before the roster was read. */
145
- readonly settled: SettleStatus
146
- /** How many roster reads the verdict cost. */
147
- readonly reads: number
148
- }
149
-
150
- /**
151
- * Whether a roster declares the preset this tool follows.
152
- * @param presets - rows as {@link PresetRosterReader.list} returns them.
153
- * @returns true when one row carries the LiangShen id.
154
- */
155
- export function declaresLiangShen(presets: readonly PresetRosterRow[]): boolean {
156
- return presets.some(preset => preset?.id === LIANGSHEN_PRESET_ID)
157
- }
158
-
159
- /**
160
- * Read one optional service without letting a refused lookup escape: a cordis
161
- * service proxy throws for a name it cannot resolve, and an absent optional
162
- * service is an ordinary state here, not an error.
163
- * @param ctx - the plugin context.
164
- * @param name - the service name.
165
- * @returns the service, or undefined when it is not resolvable.
166
- */
167
- function readService(ctx: Context, name: string): unknown {
168
- try {
169
- return (ctx as unknown as { get(key: string): unknown }).get(name)
170
- } catch {
171
- return undefined
172
- }
173
- }
174
-
175
- /**
176
- * The published registry, when this deployment has one shaped like the one this
177
- * gate consumes.
178
- * @param ctx - the plugin context.
179
- * @returns the reader, or undefined when no usable registry is published.
180
- */
181
- export function readPresetRegistry(ctx: Context): PresetRosterReader | undefined {
182
- const candidate = readService(ctx, 'agentPresets')
183
- if (candidate === null || typeof candidate !== 'object') return undefined
184
- if (typeof (candidate as { list?: unknown }).list !== 'function') return undefined
185
- return candidate as PresetRosterReader
186
- }
187
-
188
- /**
189
- * Run one promise with a deadline. The timer is always cleared, so a fast
190
- * answer leaves no stray handle behind.
191
- * @param work - the promise to bound.
192
- * @param timeoutMs - the bound in milliseconds.
193
- * @returns the promise's value.
194
- * @throws when the deadline passes first.
195
- */
196
- async function withDeadline<T>(work: Promise<T>, timeoutMs: number): Promise<T> {
197
- let timer: ReturnType<typeof setTimeout> | undefined
198
- try {
199
- return await Promise.race([
200
- work,
201
- new Promise<never>((_resolve, reject) => {
202
- timer = setTimeout(() => { reject(new Error('timed out after ' + timeoutMs.toString() + 'ms')) }, timeoutMs)
203
- }),
204
- ])
205
- } finally {
206
- if (timer !== undefined) clearTimeout(timer)
207
- }
208
- }
209
-
210
- /**
211
- * Wait until the Host loader tree has no pending import or lifecycle work.
212
- *
213
- * Waiting for the whole tree rather than this row's neighbours is deliberate:
214
- * the roster belongs to the deployment, not to one group, and the loader's own
215
- * await() is the only predicate that means "every row has been applied". A row
216
- * merely waiting for a service it will never get carries no pending task, so it
217
- * cannot hold this wait open; one that is genuinely mid-activation can, which is
218
- * exactly the case the bound covers.
219
- * @param ctx - the plugin context.
220
- * @param options - the deadlines for this run.
221
- * @returns how far the settle got.
222
- */
223
- export async function settleHostTree(ctx: Context, options: GateOptions = {}): Promise<SettleStatus> {
224
- const loader = readService(ctx, 'loader')
225
- if (loader === null || typeof loader !== 'object') return 'unavailable'
226
- const wait = (loader as { await?: unknown }).await
227
- if (typeof wait !== 'function') return 'unavailable'
228
- try {
229
- await withDeadline(
230
- Promise.resolve((wait as () => Promise<void>).call(loader)).then(() => undefined),
231
- options.settleTimeoutMs ?? GATE_SETTLE_TIMEOUT_MS,
232
- )
233
- return 'settled'
234
- } catch {
235
- return 'timed-out'
236
- }
237
- }
238
-
239
- /**
240
- * Sleep one timer turn.
241
- *
242
- * Production code, not a test helper: the wait IS the declaration window the
243
- * module header describes, and the gate is only ever reached from a mount.
244
- * @param ms - how long to wait.
245
- */
246
- function waitFor(ms: number): Promise<void> {
247
- return new Promise<void>((resolve) => { setTimeout(resolve, ms) })
248
- }
249
-
250
- /** One roster read, or undefined when the registry could not answer. */
251
- async function readRoster(
252
- registry: PresetRosterReader,
253
- timeoutMs: number,
254
- ): Promise<readonly PresetRosterRow[] | undefined> {
255
- try {
256
- const rows = await withDeadline(Promise.resolve(registry.list()), timeoutMs)
257
- return Array.isArray(rows) ? rows as readonly PresetRosterRow[] : undefined
258
- } catch {
259
- return undefined
260
- }
261
- }
262
-
263
- /**
264
- * Decide whether the LiangShen preset is declared in this deployment.
265
- *
266
- * Call this OFF the plugin's activation path — never awaited from a plugin
267
- * apply. list() is not a leaf read: it audits every declared preset and, for one
268
- * whose mounted subtree still has pending rows, awaits the Host loader tree
269
- * (agent-preset-registry lib/index.js diagnostic). A plugin whose activation
270
- * awaited this would wait on the loader tree while its OWN activation is among
271
- * the tasks that tree is waiting for, and neither wait would ever settle. The
272
- * entry calls this after its synchronous activation returned, which is what
273
- * keeps this a wait and not a deadlock.
274
- * @param ctx - the plugin context.
275
- * @param options - the deadlines and cadence for this run.
276
- * @returns the verdict, with the reason for the caller's log line.
277
- */
278
- export async function startLiangShenGate(ctx: Context, options: GateOptions = {}): Promise<GateOutcome> {
279
- const settled = await settleHostTree(ctx, options)
280
- const registry = readPresetRegistry(ctx)
281
- if (registry === undefined) return { allowed: false, reason: 'registry-absent', settled, reads: 0 }
282
- const readTimeoutMs = options.readTimeoutMs ?? GATE_READ_TIMEOUT_MS
283
- const pollIntervalMs = options.pollIntervalMs ?? GATE_POLL_INTERVAL_MS
284
- const waitMs = options.declarationWaitMs ?? GATE_DECLARATION_WAIT_MS
285
-
286
- let reads = 0
287
- const first = await readRoster(registry, readTimeoutMs)
288
- reads += 1
289
- if (first === undefined) return { allowed: false, reason: 'registry-unreadable', settled, reads }
290
- if (declaresLiangShen(first)) return { allowed: true, reason: 'declared', settled, reads }
291
-
292
- // Not declared yet. Re-read until the declaration appears or the window
293
- // closes: the declaring plugin publishes it off its activation return, so
294
- // \"not yet\" and \"not here\" are only distinguishable by waiting. A read
295
- // that fails mid-window is not the verdict — only a window that never
296
- // produced a successful answer at all is reported as unreadable.
297
- const deadline = Date.now() + waitMs
298
- let answered = false
299
- while (Date.now() < deadline) {
300
- await waitFor(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())))
301
- const rows = await readRoster(registry, readTimeoutMs)
302
- reads += 1
303
- if (rows === undefined) continue
304
- answered = true
305
- if (declaresLiangShen(rows)) return { allowed: true, reason: 'declared', settled, reads }
306
- }
307
- return { allowed: false, reason: answered ? 'not-declared' : 'registry-unreadable', settled, reads }
308
- }