@linxin666/dsh-liangshen 0.4.7 → 0.4.9

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.
Files changed (35) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +10 -8
  3. package/README.zh.md +10 -8
  4. package/lib/client.js +102 -55
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +9 -1
  7. package/lib/types/client/PluginSettingsCard.d.ts +60 -0
  8. package/package.json +15 -15
  9. package/presets/liangshen/agent.cordis.yml +76 -18
  10. package/presets/liangshen/dispatcher-rules.mjs +128 -47
  11. package/presets/liangshen/fact-ledger.mjs +14 -0
  12. package/presets/liangshen/subagent-routes.mjs +396 -0
  13. package/presets/liangshen/tool-catalog.mjs +7 -4
  14. package/src/client/PluginSettingsCard.tsx +140 -20
  15. package/src/client/settings-card.module.css +141 -11
  16. package/src/composition.test.ts +20 -0
  17. package/src/composition.ts +10 -2
  18. package/tools/benchmark-live-run.mjs +116 -14
  19. package/tools/benchmark-report.mjs +44 -0
  20. package/tools/check-dispatcher-rules.mjs +130 -0
  21. package/tools/probe-selftest.mjs +130 -0
  22. package/tools/probes/budget-ledger/env.mjs +103 -0
  23. package/tools/probes/budget-ledger/grade.mjs +31 -0
  24. package/tools/probes/budget-ledger/strategies.mjs +25 -0
  25. package/tools/probes/oncall-backlog/env.mjs +141 -0
  26. package/tools/probes/oncall-backlog/grade.mjs +28 -0
  27. package/tools/probes/oncall-backlog/strategies.mjs +37 -0
  28. package/tools/probes/prior-override/env.mjs +153 -0
  29. package/tools/probes/prior-override/grade.mjs +31 -0
  30. package/tools/probes/prior-override/strategies.mjs +30 -0
  31. package/tools/probes/refresh-quota/env.mjs +140 -0
  32. package/tools/probes/refresh-quota/grade.mjs +30 -0
  33. package/tools/probes/refresh-quota/strategies.mjs +29 -0
  34. package/tools/probes/shared.mjs +75 -0
  35. package/tools/tasks/liangshen-v41-probes.json +59 -0
@@ -0,0 +1,396 @@
1
+ /**
2
+ * subagent-routes — the LiangShen preset's authorization guard for delegated
3
+ * child routes.
4
+ *
5
+ * The harness records a Session's authorized child routes as a durable
6
+ * `subagent/model-selection-policy` event, but its own delegation tool only
7
+ * rejects an EXPLICIT route outside that list: a call that names no
8
+ * `provider`/`model` falls back to the configured child defaults or to the
9
+ * parent's own route. A session whose allowlist authorizes only one family
10
+ * would therefore still spawn children on the parent's route simply because
11
+ * nobody named one — or, for `subagent_fork`, because the tool cannot name one
12
+ * at all.
13
+ *
14
+ * This row closes that gap from the preset plane. Whenever the calling Session
15
+ * (or the nearest ancestor that recorded one) carries an allowlist, every
16
+ * delegation the row polices must resolve to an authorized route:
17
+ *
18
+ * - `explicit` tools publish `provider`/`model`; the call must name a complete
19
+ * pair, and that pair must be on the list;
20
+ * - `inherit` tools publish neither and start the child on the caller's own
21
+ * route; the guard forbids a route override there and checks the inherited
22
+ * route against the same list, because "the tool cannot choose" is not the
23
+ * same as "the choice is authorized".
24
+ *
25
+ * The mode a tool is policed in is configuration, but its PARAMETERS are a
26
+ * runtime fact: a composition written for an older cohort mounts the tool with
27
+ * neither route field, and demanding a pair from it would be a denial no call
28
+ * could satisfy. The guard therefore asks the registry which fields the tool
29
+ * actually declares, and enforces such a tool through the route its child
30
+ * would inherit.
31
+ *
32
+ * The guard is deliberately fail-open on every fact it cannot read (no policy
33
+ * event, no session registry, no registry probe): a delegation the harness can
34
+ * resolve is never blocked by a missing observation, and the row only ever
35
+ * adds a denial it can justify from the durable log.
36
+ */
37
+
38
+ /** Cordis plugin name used by loader diagnostics. */
39
+ export const name = 'liangshen-subagent-routes'
40
+
41
+ /**
42
+ * Services this row reads.
43
+ *
44
+ * A preset row runs in its own fiber, where a service it does not declare is
45
+ * not readable at all: `ctx.tools` against an undeclared `tools` throws
46
+ * "cannot get property \"tools\" without inject" and fails the preset's load
47
+ * audit. The guard reads the registry for its `guard` seam and its `definitions`
48
+ * probe, so declaring it is what lets the row mount and stay mounted.
49
+ */
50
+ export const inject = ['tools']
51
+
52
+ /** Durable event carrying a Session's authorized child routes. */
53
+ export const POLICY_EVENT = 'subagent/model-selection-policy'
54
+
55
+ /** Delegation tools whose calls must name an authorized route pair. */
56
+ export const DEFAULT_EXPLICIT_TOOLS = ['subagent']
57
+
58
+ /**
59
+ * Delegation tools that start their child on the caller's own route.
60
+ * `subagent_fork` is the shipped one; `spawn_teammate` belongs here for the
61
+ * same reason at one remove — it creates its child with no `agentOptions`, so
62
+ * policing it as an explicit tool would deny every creation.
63
+ */
64
+ export const DEFAULT_INHERIT_TOOLS = ['subagent_fork', 'spawn_teammate']
65
+
66
+ /** How far the policy lookup follows the Session chain before giving up. */
67
+ export const MAX_ANCESTOR_DEPTH = 8
68
+
69
+ /** How many early events one Session is scanned for its policy event. */
70
+ export const MAX_POLICY_SCAN = 256
71
+
72
+ /** Read one value as a non-empty string. */
73
+ function asString(value) {
74
+ return typeof value === 'string' && value.length > 0 ? value : undefined
75
+ }
76
+
77
+ /** Read one value as a plain record. */
78
+ function asRecord(value) {
79
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined
80
+ }
81
+
82
+ /**
83
+ * Parse the `allowedModels` payload of one policy event.
84
+ * @param data - Raw event payload.
85
+ * @returns the authorized routes, or undefined when the payload is malformed.
86
+ */
87
+ export function parseAllowedRoutes(data) {
88
+ const record = asRecord(data)
89
+ if (record === undefined) return undefined
90
+ const entries = record['allowedModels']
91
+ if (!Array.isArray(entries)) return undefined
92
+ const routes = []
93
+ for (const entry of entries) {
94
+ const route = asRecord(entry)
95
+ const provider = asString(route?.['provider'])
96
+ const model = asString(route?.['model'])
97
+ if (provider === undefined || model === undefined) return undefined
98
+ routes.push({ provider, model })
99
+ }
100
+ return routes
101
+ }
102
+
103
+ /** The events of one session, tolerating both snapshot shapes. */
104
+ function sessionEvents(session) {
105
+ if (Array.isArray(session?.events)) return session.events
106
+ if (typeof session?.snapshotEvents === 'function') {
107
+ try {
108
+ const snapshot = session.snapshotEvents()
109
+ if (Array.isArray(snapshot)) return snapshot
110
+ } catch {
111
+ return undefined
112
+ }
113
+ }
114
+ return undefined
115
+ }
116
+
117
+ /**
118
+ * The authorized routes a session recorded, if any.
119
+ *
120
+ * The policy is appended before the Session's first model request, so the scan
121
+ * stays short; the bound keeps a Session without one from walking its whole
122
+ * log. Both the durable `eventAt(seq)` reader and a plain events array are
123
+ * accepted, because the row may run against a Host that exposes only one.
124
+ * @param session - Session-like record.
125
+ * @returns the recorded routes, or undefined when this Session recorded none.
126
+ */
127
+ export function policyRoutesOf(session) {
128
+ if (session === undefined || session === null) return undefined
129
+ if (typeof session.eventAt === 'function') {
130
+ for (let seq = 0; seq < MAX_POLICY_SCAN; seq += 1) {
131
+ let event
132
+ try {
133
+ event = session.eventAt(seq)
134
+ } catch {
135
+ return undefined
136
+ }
137
+ if (event === undefined) return undefined
138
+ if (event?.type !== POLICY_EVENT) continue
139
+ const routes = parseAllowedRoutes(event.data)
140
+ if (routes !== undefined) return routes
141
+ }
142
+ return undefined
143
+ }
144
+ const events = sessionEvents(session)
145
+ if (events === undefined) return undefined
146
+ for (const event of events.slice(0, MAX_POLICY_SCAN)) {
147
+ if (event?.type !== POLICY_EVENT) continue
148
+ const routes = parseAllowedRoutes(event.data)
149
+ if (routes !== undefined) return routes
150
+ }
151
+ return undefined
152
+ }
153
+
154
+ /**
155
+ * Resolve the allowlist a delegation from this agent must respect: the agent's
156
+ * own recorded policy, else the nearest ancestor Session that recorded one.
157
+ *
158
+ * The walk only crosses parent links that the delegation seam itself created
159
+ * (`origin: subagent`), so an unrelated parent Session cannot impose a list on
160
+ * a delegation it does not own.
161
+ * @param agent - Calling agent.
162
+ * @param sessions - Session registry, when the Host exposes one.
163
+ * @returns the authorized routes, or undefined when no Session recorded any.
164
+ */
165
+ export function authorizedRoutesFor(agent, sessions) {
166
+ let session = agent?.session
167
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH && session !== undefined; depth += 1) {
168
+ const recorded = policyRoutesOf(session)
169
+ if (recorded !== undefined) return recorded
170
+ const header = asRecord(session?.header)
171
+ if (header?.['origin'] !== 'subagent') return undefined
172
+ const parentId = asString(header['parentSession'])
173
+ if (parentId === undefined || typeof sessions?.get !== 'function') return undefined
174
+ try {
175
+ session = sessions.get(parentId)
176
+ } catch {
177
+ return undefined
178
+ }
179
+ }
180
+ return undefined
181
+ }
182
+
183
+ /**
184
+ * The route an inherit-mode child would run on: the caller's own effective
185
+ * request route. The latest request header owns it after a mid-session model
186
+ * switch, with the creation options as the fallback before the first request.
187
+ * @param agent - Calling agent.
188
+ * @returns the inherited route fields, each absent when its source omitted it.
189
+ */
190
+ export function inheritedRouteOf(agent) {
191
+ let header
192
+ try {
193
+ header = typeof agent?.session?.requestHeader === 'function' ? agent.session.requestHeader() : undefined
194
+ } catch {
195
+ header = undefined
196
+ }
197
+ const config = asRecord(header?.config)
198
+ const provider = asString(config?.['provider'])
199
+ const model = asString(config?.['model'])
200
+ if (provider !== undefined || model !== undefined) {
201
+ return { provider, model, reasoningEffort: asString(config?.['reasoningEffort']) }
202
+ }
203
+ return { provider: asString(agent?.options?.provider), model: asString(agent?.options?.model) }
204
+ }
205
+
206
+ /** Whether one route is on an allowlist. */
207
+ export function routesInclude(routes, provider, model) {
208
+ return (Array.isArray(routes) ? routes : [])
209
+ .some(route => route.provider === provider && route.model === model)
210
+ }
211
+
212
+ /** Render an allowlist for a denial reason. */
213
+ export function authorizedRoutesText(routes) {
214
+ const list = Array.isArray(routes) ? routes : []
215
+ if (list.length === 0) return 'no route is authorized (the Session allowlist is empty)'
216
+ return list.map(route => `"${route.provider}/${route.model}"`).join(', ')
217
+ }
218
+
219
+ /** The route pair one delegation call named, each half possibly absent. */
220
+ export function namedRouteOf(args) {
221
+ const record = asRecord(args) ?? {}
222
+ return { provider: asString(record['provider']), model: asString(record['model']) }
223
+ }
224
+
225
+ /** How one delegation tool resolves the child route this guard authorizes. */
226
+ export function delegationModeOf(toolName, explicitToolNames, inheritToolNames) {
227
+ if ((Array.isArray(inheritToolNames) ? inheritToolNames : []).includes(toolName)) return 'inherit'
228
+ if ((Array.isArray(explicitToolNames) ? explicitToolNames : DEFAULT_EXPLICIT_TOOLS).includes(toolName)) return 'explicit'
229
+ return undefined
230
+ }
231
+
232
+ /**
233
+ * Ask the tool registry whether one delegation tool currently declares the
234
+ * route fields. The answer is read per call: an HMR replacement or a preset
235
+ * change can remount the tool, and a stale answer would put the guard back on
236
+ * the branch no call can satisfy.
237
+ * @param tools - Tool registry from the Host context.
238
+ * @param agent - Calling agent, whose scope selects the visible definitions.
239
+ * @param toolName - Tool being dispatched.
240
+ * @returns whether the tool declares a route field, or undefined when the
241
+ * registry cannot answer (which keeps the configured mode in charge).
242
+ */
243
+ export function routeParameterProbe(tools, agent, toolName) {
244
+ if (typeof tools?.definitions !== 'function') return undefined
245
+ let definitions
246
+ try {
247
+ definitions = tools.definitions(agent)
248
+ } catch {
249
+ return undefined
250
+ }
251
+ const definition = (Array.isArray(definitions) ? definitions : []).find(entry => entry?.name === toolName)
252
+ const parameters = asRecord(definition?.parameters)
253
+ if (parameters === undefined) return undefined
254
+ return parameters['provider'] !== undefined || parameters['model'] !== undefined
255
+ }
256
+
257
+ /** Denial reason for a delegation that named a route on an inherit-only tool. */
258
+ export function overrideReason(toolName, provider, model, allowed) {
259
+ return `subagent model selection: "${toolName}" keeps its child on the calling agent's route and has no provider/model fields, `
260
+ + `so the route "${provider}/${model}" cannot be selected through it. Use a delegation tool that exposes `
261
+ + `provider and model and pass one of ${authorizedRoutesText(allowed)}.`
262
+ }
263
+
264
+ /** Denial reason for a delegation whose inherited route is unauthorized. */
265
+ export function inheritedReason(toolName, inherited, allowed) {
266
+ const route = inherited.provider === undefined || inherited.model === undefined
267
+ ? 'the calling agent\'s route'
268
+ : `"${inherited.provider}/${inherited.model}"`
269
+ return `subagent model selection: "${toolName}" keeps its child on ${route}, which this Session's allowlist `
270
+ + `does not authorize, so it is unavailable for now. Its child cannot be re-routed, so either delegate through a `
271
+ + `tool that exposes provider and model — passing one of ${authorizedRoutesText(allowed)} — or continue on an `
272
+ + `authorized model for this Session, after which "${toolName}" works again.`
273
+ }
274
+
275
+ /**
276
+ * The denial for a delegation that would inherit the caller's route, or
277
+ * undefined when that route is authorized (or cannot be read at all — a route
278
+ * the guard cannot resolve is left to the harness rather than guessed).
279
+ * @param agent - Calling agent whose route the child inherits.
280
+ * @param toolName - Tool being dispatched.
281
+ * @param allowed - Routes the calling Session authorizes.
282
+ * @returns a denial reason, or undefined when the inherited route is allowed.
283
+ */
284
+ export function inheritedRouteDenial(agent, toolName, allowed) {
285
+ const inherited = inheritedRouteOf(agent)
286
+ if (inherited.provider !== undefined && inherited.model !== undefined
287
+ && routesInclude(allowed, inherited.provider, inherited.model)) return undefined
288
+ return inheritedReason(toolName, inherited, allowed)
289
+ }
290
+
291
+ /** Denial reason for an explicit tool whose call named no complete pair. */
292
+ export function missingPairReason(toolName, named, inherited, allowed) {
293
+ const half = named.provider === undefined && named.model === undefined
294
+ ? 'names no provider or model'
295
+ : `names only ${named.provider === undefined ? 'model' : 'provider'}`
296
+ return `subagent model selection: the call to "${toolName}" ${half}, so the child would run on `
297
+ + `${inherited.provider === undefined || inherited.model === undefined ? 'the parent route' : `"${inherited.provider}/${inherited.model}"`}, `
298
+ + `which this Session's allowlist does not authorize. Pass an authorized provider and model — ${authorizedRoutesText(allowed)} — `
299
+ + `with an optional reasoning_effort.`
300
+ }
301
+
302
+ /** Denial reason for a call that named a route outside the allowlist. */
303
+ export function unauthorizedReason(toolName, provider, model, allowed) {
304
+ return `subagent model selection: the model this call to "${toolName}" selected ("${provider}/${model}") is not on the `
305
+ + `Session allowlist. Pass an authorized provider and model — ${authorizedRoutesText(allowed)} — with an optional reasoning_effort.`
306
+ }
307
+
308
+ /**
309
+ * Decide whether one delegation call must be refused.
310
+ *
311
+ * Every unreadable fact resolves to "no opinion": an absent policy event, an
312
+ * absent session registry, or a registry that cannot name the tool's fields all
313
+ * leave the call to the harness.
314
+ * @param input - Calling agent, tool name, arguments, and policy sources.
315
+ * @returns a denial reason, or undefined to leave the call untouched.
316
+ */
317
+ export function delegationDenialReason(input) {
318
+ const {
319
+ agent, toolName, args, sessions,
320
+ explicitToolNames = DEFAULT_EXPLICIT_TOOLS,
321
+ inheritToolNames = DEFAULT_INHERIT_TOOLS,
322
+ probe,
323
+ } = input ?? {}
324
+ const mode = delegationModeOf(toolName, explicitToolNames, inheritToolNames)
325
+ if (mode === undefined) return undefined
326
+ const allowed = authorizedRoutesFor(agent, sessions)
327
+ if (allowed === undefined) return undefined
328
+ const named = namedRouteOf(args)
329
+ const complete = named.provider !== undefined && named.model !== undefined
330
+ if (mode === 'inherit') {
331
+ // A named pair can only be an attempt to re-route the child away from the
332
+ // route the tool exists to preserve: the more precise diagnostic comes first.
333
+ if (complete) return overrideReason(toolName, named.provider, named.model, allowed)
334
+ return inheritedRouteDenial(agent, toolName, allowed)
335
+ }
336
+ // A tool mounted without route fields cannot be handed the pair a policy
337
+ // expects, so it is policed through the route its child would inherit.
338
+ //
339
+ // A COMPLETE pair is never reclassified here. The probe resolves the registry
340
+ // view from the call, which can be a scope that does not carry this preset's
341
+ // delegation registration, so it can answer "no route fields" for a tool the
342
+ // model was in fact shown WITH them. Denying the pair there produced a denial
343
+ // no call could satisfy and made every routed dispatch impossible. The pair
344
+ // still faces the allowlist check below, so this branch can only soften an
345
+ // impossible denial — never an authorization.
346
+ const declares = probe?.(agent, toolName)
347
+ if (declares === false) {
348
+ // A bare or half-named call keeps the old behaviour: police the route the
349
+ // child would inherit. Only the COMPLETE pair falls through.
350
+ if (!complete) return inheritedRouteDenial(agent, toolName, allowed)
351
+ }
352
+ if (!complete) return missingPairReason(toolName, named, inheritedRouteOf(agent), allowed)
353
+ if (!routesInclude(allowed, named.provider, named.model)) {
354
+ return unauthorizedReason(toolName, named.provider, named.model, allowed)
355
+ }
356
+ return undefined
357
+ }
358
+
359
+ /**
360
+ * Install the guard for the calling scope.
361
+ * @param ctx - Host context carrying the tool registry (and optionally sessions).
362
+ * @param config - Row configuration.
363
+ * @returns a disposer that removes the guard, or undefined when the scope has
364
+ * no tool registry to guard.
365
+ */
366
+ export function installSubagentRoutes(ctx, config = {}) {
367
+ const tools = ctx?.tools
368
+ if (typeof tools?.guard !== 'function') return undefined
369
+ const explicitToolNames = Array.isArray(config.explicitTools) ? config.explicitTools : DEFAULT_EXPLICIT_TOOLS
370
+ const inheritToolNames = Array.isArray(config.inheritTools) ? config.inheritTools : DEFAULT_INHERIT_TOOLS
371
+ const sessions = typeof ctx?.get === 'function' ? ctx.get('sessions') : undefined
372
+ return tools.guard(execution => delegationDenialReason({
373
+ agent: execution?.agent,
374
+ toolName: execution?.name,
375
+ args: execution?.arguments,
376
+ sessions,
377
+ explicitToolNames,
378
+ inheritToolNames,
379
+ probe: (agent, toolName) => routeParameterProbe(tools, agent, toolName),
380
+ }))
381
+ }
382
+
383
+ /**
384
+ * Mount the row: register the guard for this scope, with an off switch.
385
+ * @param ctx - Cordis context of the composing scope.
386
+ * @param config - Row configuration; omitted fields select the shipped names.
387
+ */
388
+ export function apply(ctx, config = {}) {
389
+ if (config.enabled === false) return
390
+ ctx.effect(() => {
391
+ const dispose = installSubagentRoutes(ctx, config)
392
+ // A Host without the guard seam keeps the harness's own delegation behavior
393
+ // instead of failing the preset's load.
394
+ return dispose ?? (() => undefined)
395
+ }, 'liangshen: subagent route guard')
396
+ }
@@ -793,6 +793,10 @@ export function apply(ctx, config) {
793
793
 
794
794
  const tools = agent?.ctx?.tools
795
795
  if (tools === undefined || typeof tools.presentAs !== 'function') {
796
+ // No composition row replaces this declaration: `presentAs` is how a
797
+ // preset selects its wire, so a scope that cannot reach it runs the
798
+ // native surface no matter what `presentation` says. Report it once
799
+ // instead of leaving the operator's setting silently unapplied.
796
800
  agentDeclareFailed.add(agent)
797
801
  warnOnce('runtime', 'no scoped tools view to declare the presentation through — keeping the native tool surface')
798
802
  return false
@@ -958,9 +962,9 @@ export function apply(ctx, config) {
958
962
  if (agent !== undefined && !agentDeclared.has(agent) && transportReady()) {
959
963
  // Under 'ptc' a declaration collapses the wire to the single `run_code`
960
964
  // transport and lists the tools from their SDK projection. Where no
961
- // projection can be read at all, declaring would collapse the executor and
962
- // then have to undo it, losing the native wire on the way out. Stay native
963
- // instead.
965
+ // projection can be read at all, declaring would collapse the wire and
966
+ // then have to undo it, losing the native surface on the way out. Stay
967
+ // native instead.
964
968
  const projectable = publicSchemas(agent)
965
969
  if (presentation === 'ptc' && (projectable === undefined || projectable.length === 0)) {
966
970
  warnOnce('runtime', 'no tool schema projection available — keeping the native tool surface')
@@ -1001,7 +1005,6 @@ export function apply(ctx, config) {
1001
1005
  const assembled = await next()
1002
1006
 
1003
1007
  const assembledTools = Array.isArray(assembled?.tools) ? assembled.tools : undefined
1004
- const wireHasRunCode = (assembledTools ?? []).some(t => t?.name === 'run_code')
1005
1008
  const wireOnlyRunCode = assembledTools !== undefined && assembledTools.length > 0 && assembledTools.every(t => t?.name === 'run_code')
1006
1009
 
1007
1010
  // The paging restriction was installed OUTSIDE this waterfall (see