@linxin666/dsh-liangshen 0.3.23 → 0.4.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.
Files changed (59) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +55 -41
  3. package/README.zh.md +54 -40
  4. package/cordis.patch.yml +3 -2
  5. package/icon.svg +3 -0
  6. package/lib/client.js +1380 -29
  7. package/lib/client.js.map +1 -1
  8. package/lib/index.js +616 -367
  9. package/lib/types/announce.test.d.ts +10 -0
  10. package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
  11. package/lib/types/client/PluginSettingsCard.d.ts +137 -0
  12. package/lib/types/client/index.d.ts +57 -4
  13. package/lib/types/client/lever-controller.d.ts +16 -2
  14. package/lib/types/client/locales.d.ts +40 -1
  15. package/lib/types/client/main-session.d.ts +32 -0
  16. package/lib/types/client/plugin-card-seat.d.ts +103 -0
  17. package/lib/types/client/settings-form.d.ts +197 -0
  18. package/lib/types/composition.d.ts +116 -0
  19. package/lib/types/composition.test.d.ts +7 -0
  20. package/lib/types/core/lever.d.ts +6 -3
  21. package/lib/types/index.d.ts +160 -33
  22. package/lib/types/index.test.d.ts +5 -0
  23. package/package.json +27 -18
  24. package/presets/liangshen/NOTICE +4 -4
  25. package/presets/liangshen/agent.cordis.yml +168 -123
  26. package/presets/liangshen/fact-ledger.mjs +141 -0
  27. package/presets/liangshen/guard.mjs +426 -0
  28. package/presets/liangshen/minimal-prompt.mjs +73 -38
  29. package/presets/liangshen/paging.mjs +232 -0
  30. package/presets/liangshen/tool-activate.mjs +176 -0
  31. package/presets/liangshen/tool-catalog.mjs +615 -219
  32. package/presets/liangshen/working-context.mjs +222 -0
  33. package/src/announce.test.ts +248 -55
  34. package/src/client/LiangShenLever.module.css +2 -0
  35. package/src/client/LiangShenLever.tsx +41 -10
  36. package/src/client/LiangShenSettingsCard.tsx +233 -0
  37. package/src/client/PluginSettingsCard.tsx +555 -0
  38. package/src/client/index.ts +102 -5
  39. package/src/client/lever-controller.ts +76 -9
  40. package/src/client/locales.ts +79 -1
  41. package/src/client/main-session.ts +43 -0
  42. package/src/client/plugin-card-seat.ts +192 -0
  43. package/src/client/settings-card.module.css +418 -0
  44. package/src/client/settings-form.ts +442 -0
  45. package/src/composition.test.ts +294 -0
  46. package/src/composition.ts +554 -0
  47. package/src/core/lever.ts +7 -4
  48. package/src/index.test.ts +68 -1
  49. package/src/index.ts +293 -101
  50. package/tools/benchmark-live-run.mjs +193 -63
  51. package/lib/types/schema.d.ts +0 -18
  52. package/lib/types/schema.test.d.ts +0 -1
  53. package/lib/types/sync.d.ts +0 -47
  54. package/lib/types/sync.test.d.ts +0 -1
  55. package/presets/liangshen/custom-bash.mjs +0 -213
  56. package/src/schema.test.ts +0 -64
  57. package/src/schema.ts +0 -110
  58. package/src/sync.test.ts +0 -224
  59. package/src/sync.ts +0 -222
@@ -0,0 +1,232 @@
1
+ /**
2
+ * paging — pure helpers for the LiangShen preset's gentle tool paging.
3
+ *
4
+ * Paging keeps high-fan-out tool families (MCP servers and similar plugins)
5
+ * off the wire until the session actually needs them: a tool whose name
6
+ * matches one of the configured prefix patterns is PAGED, everything else is
7
+ * RESIDENT and stays on the wire. A paged tool returns to the wire once its
8
+ * namespace is activated through the `tool_activate` tool.
9
+ *
10
+ * The activation state is derived from the durable session event stream, never
11
+ * from process memory: replaying the `tool_activate` tool calls (and the tool
12
+ * calls that refresh a namespace's recency) rebuilds the same active set after
13
+ * a resume, a reload, or a compaction. Failed activations (errored tool
14
+ * results) never take effect.
15
+ *
16
+ * Least-recently-used eviction keeps at most MAX active namespaces: activating
17
+ * beyond the cap evicts the namespace whose latest activation or use is the
18
+ * oldest, returning its tools to the paged summary.
19
+ */
20
+
21
+ /** The default paging pattern: every MCP-bridged tool (`mcp__<server>__<fn>`). */
22
+ export const DEFAULT_PAGED_TOOL_PATTERNS = ['mcp__*']
23
+
24
+ /** The LRU cap on simultaneously active paged namespaces. */
25
+ export const DEFAULT_MAX_ACTIVE_NAMESPACES = 3
26
+
27
+ /** The activation tool this preset registers. */
28
+ export const TOOL_ACTIVATE_NAME = 'tool_activate'
29
+
30
+ /** Validate a positive-integer config value, or fall back when absent. */
31
+ export function integerAtLeast(plugin, value, field, minimum, fallback) {
32
+ if (value === undefined) return fallback
33
+ if (!Number.isInteger(value) || value < minimum) {
34
+ throw new TypeError(`${plugin}: ${field} must be an integer >= ${minimum}`)
35
+ }
36
+ return value
37
+ }
38
+
39
+ /**
40
+ * Validate the pagedToolPatterns config: an array of prefix globs, each a
41
+ * non-empty literal prefix ending in exactly one trailing `*`.
42
+ */
43
+ export function validatePagedToolPatterns(plugin, value, fallback = DEFAULT_PAGED_TOOL_PATTERNS) {
44
+ if (value === undefined) return fallback
45
+ if (!Array.isArray(value)) {
46
+ throw new TypeError(`${plugin}: pagedToolPatterns must be an array of prefix patterns`)
47
+ }
48
+ return value.map((entry) => {
49
+ if (typeof entry !== 'string' || entry.trim() === '') {
50
+ throw new TypeError(`${plugin}: pagedToolPatterns entries must be non-empty strings`)
51
+ }
52
+ if (!entry.endsWith('*') || entry.slice(0, -1).includes('*')) {
53
+ throw new TypeError(`${plugin}: pagedToolPatterns entries must be prefix patterns ending in one trailing "*"`)
54
+ }
55
+ return entry
56
+ })
57
+ }
58
+
59
+ /**
60
+ * The namespace one tool name belongs to under one pattern, or undefined when
61
+ * the pattern does not match. The prefix strips the pattern's literal head and
62
+ * the namespace is the first `__`-delimited segment of the remainder
63
+ * (`mcp__codegraph__codegraph_explore` under `mcp__*` is `codegraph`); a
64
+ * remainder without `__` is the namespace as a whole.
65
+ */
66
+ export function patternNamespace(name, pattern) {
67
+ if (typeof name !== 'string' || typeof pattern !== 'string' || !pattern.endsWith('*')) return undefined
68
+ const prefix = pattern.slice(0, -1)
69
+ if (!name.startsWith(prefix)) return undefined
70
+ const rest = name.slice(prefix.length)
71
+ if (rest === '') return undefined
72
+ const namespace = rest.split('__')[0]
73
+ return namespace === '' ? undefined : namespace
74
+ }
75
+
76
+ /** The namespace one tool name belongs to under any pattern, or undefined. */
77
+ export function namespaceOf(name, patterns) {
78
+ for (const pattern of Array.isArray(patterns) ? patterns : []) {
79
+ const namespace = patternNamespace(name, pattern)
80
+ if (namespace !== undefined) return namespace
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ /**
86
+ * Partition one wire tool list into resident tools and paged-but-inactive
87
+ * namespaces. A paged tool whose namespace is active stays resident. The
88
+ * inactive map is keyed by namespace in sorted order so one surface renders
89
+ * byte-identical text across assemblies.
90
+ */
91
+ export function partitionWireTools(tools, patterns, activeNamespaces) {
92
+ const resident = []
93
+ const inactive = new Map()
94
+ const active = activeNamespaces instanceof Set ? activeNamespaces : new Set(activeNamespaces ?? [])
95
+ for (const tool of Array.isArray(tools) ? tools : []) {
96
+ const namespace = namespaceOf(tool?.name, patterns)
97
+ if (namespace === undefined || active.has(namespace)) {
98
+ resident.push(tool)
99
+ continue
100
+ }
101
+ let group = inactive.get(namespace)
102
+ if (group === undefined) {
103
+ group = []
104
+ inactive.set(namespace, group)
105
+ }
106
+ group.push(tool)
107
+ }
108
+ const sorted = new Map([...inactive.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)))
109
+ return { resident, inactive: sorted }
110
+ }
111
+
112
+ /**
113
+ * The tool names one full (pre-restriction) surface must withhold at the
114
+ * REGISTRY for a given active set: every paged tool whose namespace is not
115
+ * active. Reserved names are never returned — the official transport cannot
116
+ * be named by a restriction, and paging must not be the reason a session
117
+ * loses it.
118
+ *
119
+ * Deliberately the same partition the wire uses, so the two halves of paging
120
+ * cannot disagree about which tools are resident.
121
+ */
122
+ export function withheldToolNames(tools, patterns, activeNamespaces, reserved = ['run_code']) {
123
+ const blocked = new Set(reserved)
124
+ const names = []
125
+ for (const group of partitionWireTools(tools, patterns, activeNamespaces).inactive.values()) {
126
+ for (const tool of group) {
127
+ if (typeof tool?.name !== 'string' || tool.name === '') continue
128
+ if (blocked.has(tool.name)) continue
129
+ names.push(tool.name)
130
+ }
131
+ }
132
+ return names.sort()
133
+ }
134
+
135
+ /**
136
+ * The paged namespaces of one full (pre-restriction) surface, keyed like
137
+ * {@link partitionWireTools} does and sorted the same way, so a catalog can
138
+ * summarize what a restriction withheld without a second matching rule.
139
+ */
140
+ export function inactiveNamespaces(tools, patterns, activeNamespaces) {
141
+ return partitionWireTools(tools, patterns, activeNamespaces).inactive
142
+ }
143
+
144
+ /** Parse one tool/call event's arguments, tolerating the JSON-string form. */
145
+ function callArguments(data) {
146
+ let args = data?.arguments
147
+ if (typeof args === 'string') {
148
+ try {
149
+ args = JSON.parse(args)
150
+ } catch {
151
+ return undefined
152
+ }
153
+ }
154
+ return args !== null && typeof args === 'object' ? args : undefined
155
+ }
156
+
157
+ /**
158
+ * Whether one tool/result event reports a failure.
159
+ *
160
+ * Exported because the phase logic reads the same signal: a failed dispatch opens
161
+ * the review stretch, and one definition of "failed" keeps the two mechanisms
162
+ * from disagreeing about what a failure is.
163
+ */
164
+ export function resultIsError(data) {
165
+ if (data?.error !== undefined && data?.error !== null) return true
166
+ const message = data?.message
167
+ if (message?.isError === true) return true
168
+ const blocks = Array.isArray(message?.content) ? message.content : []
169
+ return blocks.some(block => block?.isError === true)
170
+ }
171
+
172
+ /**
173
+ * Replay the durable session event stream into the active namespace set.
174
+ *
175
+ * Events are the source of truth: a `tool_activate` call whose result did not
176
+ * error activates its namespace (or refreshes its recency), and any other
177
+ * successful call into a paged tool refreshes the namespace it belongs to.
178
+ * Activating beyond the capacity evicts the least recently used namespace.
179
+ * Returns the active namespaces oldest-first and every evicted namespace in
180
+ * eviction order.
181
+ */
182
+ export function replayActivations(events, capacity = DEFAULT_MAX_ACTIVE_NAMESPACES, patterns = DEFAULT_PAGED_TOOL_PATTERNS) {
183
+ const list = Array.isArray(events) ? events : []
184
+ const errored = new Set()
185
+ for (const event of list) {
186
+ if (event?.type !== 'tool/result') continue
187
+ const callId = event.data?.message?.source?.callId ?? event.data?.callId
188
+ if (callId !== undefined && resultIsError(event.data)) errored.add(String(callId))
189
+ }
190
+
191
+ const active = []
192
+ const evicted = []
193
+ const touch = (namespace) => {
194
+ const index = active.indexOf(namespace)
195
+ if (index >= 0) active.splice(index, 1)
196
+ active.push(namespace)
197
+ while (active.length > capacity) evicted.push(active.shift())
198
+ }
199
+ for (const event of list) {
200
+ if (event?.type !== 'tool/call') continue
201
+ const data = event.data
202
+ if (data?.callId !== undefined && errored.has(String(data.callId))) continue
203
+ if (data?.name === TOOL_ACTIVATE_NAME) {
204
+ const namespace = callArguments(data)?.namespace
205
+ if (typeof namespace === 'string' && namespace !== '') touch(namespace)
206
+ continue
207
+ }
208
+ const namespace = namespaceOf(data?.name, patterns)
209
+ if (namespace !== undefined && active.includes(namespace)) touch(namespace)
210
+ }
211
+ return { active, evicted }
212
+ }
213
+
214
+ /**
215
+ * One-line catalog summary per inactive namespace: the namespace, its tool
216
+ * count, a sample tool name, and the first tool's one-line description as the
217
+ * namespace's summary.
218
+ */
219
+ export function summarizeInactive(inactive, describe) {
220
+ const summaries = []
221
+ for (const [namespace, tools] of inactive instanceof Map ? inactive : []) {
222
+ const sorted = [...tools].sort((a, b) => (a?.name < b?.name ? -1 : a?.name > b?.name ? 1 : 0))
223
+ const first = sorted[0]
224
+ summaries.push({
225
+ namespace,
226
+ count: sorted.length,
227
+ sample: typeof first?.name === 'string' ? first.name : '',
228
+ description: typeof describe === 'function' ? describe(first?.description) : '',
229
+ })
230
+ }
231
+ return summaries
232
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * tool-activate — the LiangShen preset's `tool_activate` tool: the activation
3
+ * handle for the gentle tool paging the sibling tool-catalog plugin applies.
4
+ *
5
+ * Tools whose names match the paging patterns (default `mcp__*`) stay out of
6
+ * reach until their namespace is activated here: off the wire, and — under a
7
+ * presentation whose wire has already collapsed to the single `run_code`
8
+ * transport, where the wire carries nothing left to filter — also out of the
9
+ * scope's registry view, which is what the generated SDK and every program
10
+ * dispatch resolve against. The activation itself is the durable `tool/call`
11
+ * event this call appends to the session log: the catalog plugin re-pages the
12
+ * scope at the end of the call (its `tools/post-execute` hook) and the wire
13
+ * partition replays the same event stream at the next assembly, so both halves
14
+ * of paging follow the log — the namespace's tools come back from the next
15
+ * request on, and a resume or compaction rebuilds the same state without any
16
+ * process memory.
17
+ *
18
+ * At most MAX namespaces stay active at once (LRU): activating beyond the cap
19
+ * evicts the least recently used namespace back to the paged summary, and the
20
+ * eviction is named in this tool's result so the catalog's next publication
21
+ * reflects it.
22
+ *
23
+ * Validation: the target must name a namespace that currently has paged,
24
+ * inactive tools — an unknown namespace fails with the list of available ones,
25
+ * and an already-active namespace is a no-op error instead of a silent success.
26
+ */
27
+
28
+ import {
29
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
30
+ DEFAULT_PAGED_TOOL_PATTERNS,
31
+ integerAtLeast,
32
+ namespaceOf,
33
+ replayActivations,
34
+ validatePagedToolPatterns,
35
+ } from './paging.mjs'
36
+
37
+ /** Cordis plugin name used by loader diagnostics. */
38
+ export const name = 'liangshen-tool-activate'
39
+
40
+ /** The tools registry must exist before the activation tool can register. */
41
+ export const inject = ['tools']
42
+
43
+ /** Session events, tolerating both snapshotEvents() and events array. */
44
+ function sessionEvents(session) {
45
+ if (Array.isArray(session?.events)) return session.events
46
+ if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
47
+ return []
48
+ }
49
+
50
+ /** Register the model-facing `tool_activate` tool. */
51
+ export function apply(ctx, config) {
52
+ const pagedToolPatterns = validatePagedToolPatterns(name, config?.pagedToolPatterns)
53
+ const maxActiveNamespaces = integerAtLeast(
54
+ name,
55
+ config?.maxActiveNamespaces,
56
+ 'maxActiveNamespaces',
57
+ 1,
58
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
59
+ )
60
+
61
+ /**
62
+ * Read the session's visible tool schemas from the public API, tolerating
63
+ * test stubs that only provide sdkSchemas.
64
+ */
65
+ const schemasFor = (agent) => {
66
+ const candidates = [agent?.ctx?.tools, ctx.tools, ctx.get('tools')]
67
+ for (const tools of candidates) {
68
+ if (tools === undefined) continue
69
+ for (const method of ['schemas', 'sdkSchemas']) {
70
+ if (typeof tools?.[method] !== 'function') continue
71
+ try {
72
+ const schemas = tools[method](agent)
73
+ if (Array.isArray(schemas)) return schemas
74
+ } catch {
75
+ // A hostile or unavailable projection falls through to the next source.
76
+ }
77
+ }
78
+ }
79
+ return []
80
+ }
81
+
82
+ ctx.tools.register({
83
+ name: 'tool_activate',
84
+ description: [
85
+ `Load one paged tool namespace back into this session's reach — onto the wire, and the generated SDK along with it. The session catalog summarizes the paged namespaces; activating one makes its tools callable from the next request on.`,
86
+ `At most ${maxActiveNamespaces} namespaces stay active at once: activating beyond the cap evicts the least recently used namespace back to the catalog summary.`,
87
+ 'The target must be a paged, currently inactive namespace exactly as the catalog names it.',
88
+ ].join('\n'),
89
+ parameters: {
90
+ type: 'object',
91
+ properties: {
92
+ namespace: {
93
+ type: 'string',
94
+ description: 'The paged namespace to activate, exactly as the catalog names it (for example "codegraph" for mcp__codegraph__* tools).',
95
+ },
96
+ },
97
+ required: ['namespace'],
98
+ additionalProperties: false,
99
+ },
100
+ output: {
101
+ schema: {
102
+ type: 'object',
103
+ additionalProperties: false,
104
+ properties: {
105
+ text: { type: 'string' },
106
+ },
107
+ required: ['text'],
108
+ },
109
+ render: (_args, value) => [{ type: 'text', text: value.text }],
110
+ },
111
+ /**
112
+ * Activation is concurrency-safe: the handler only reads the session's event
113
+ * stream and returns a report. The activation itself is the durable tool/call
114
+ * event the runtime appends for this call, so overlapping activations of
115
+ * different namespaces cannot corrupt shared state — the next assembly simply
116
+ * replays whatever the log holds. Declaring it lets independent activations
117
+ * (and any other read-only sibling) overlap instead of forming a barrier.
118
+ */
119
+ isConcurrencySafe: () => true,
120
+ async execute(args, exec) {
121
+ const namespace = args.namespace
122
+ const agent = exec?.agent
123
+ const schemas = schemasFor(agent)
124
+
125
+ // The paged namespaces the session actually carries, with their tools in
126
+ // stable name order for deterministic reporting.
127
+ const paged = new Map()
128
+ for (const schema of schemas) {
129
+ const toolName = schema?.name
130
+ if (typeof toolName !== 'string' || toolName === 'tool_activate') continue
131
+ const owner = namespaceOf(toolName, pagedToolPatterns)
132
+ if (owner === undefined) continue
133
+ let group = paged.get(owner)
134
+ if (group === undefined) {
135
+ group = []
136
+ paged.set(owner, group)
137
+ }
138
+ group.push(toolName)
139
+ }
140
+ for (const group of paged.values()) group.sort()
141
+
142
+ if (!paged.has(namespace)) {
143
+ const available = [...paged.keys()].sort()
144
+ throw new Error(`unknown paged namespace "${namespace}" — paged namespaces in this session: ${available.map(ns => `"${ns}"`).join(', ') || '(none)'}`)
145
+ }
146
+
147
+ // Replay the activation state from the durable log, EXCLUDING this very
148
+ // call: the harness appends the tool/call event before executing, so the
149
+ // stream may already carry it, and counting it would misreport the target
150
+ // as already active.
151
+ const selfCallId = exec?.callId
152
+ const events = sessionEvents(agent?.session).filter(event => !(
153
+ event?.type === 'tool/call'
154
+ && selfCallId !== undefined
155
+ && event.data?.name === 'tool_activate'
156
+ && String(event.data?.callId) === String(selfCallId)
157
+ ))
158
+ const { active } = replayActivations(events, maxActiveNamespaces, pagedToolPatterns)
159
+ if (active.includes(namespace)) {
160
+ throw new Error(`namespace "${namespace}" is already active; its tools are on the wire`)
161
+ }
162
+
163
+ const next = [...active, namespace]
164
+ const evicted = next.length > maxActiveNamespaces ? next.shift() : undefined
165
+ const tools = paged.get(namespace)
166
+ const lines = [
167
+ `Activated namespace "${namespace}" (${tools.length} tool${tools.length === 1 ? '' : 's'}): ${tools.join(', ')}.`,
168
+ 'Its tools are on the wire from the next request; call them directly by name.',
169
+ ]
170
+ if (evicted !== undefined) {
171
+ lines.push(`Least recently used namespace "${evicted}" was paged out (capacity ${maxActiveNamespaces}); its summary stays in the catalog and tool_activate can reload it.`)
172
+ }
173
+ return { text: lines.join(' ') }
174
+ },
175
+ })
176
+ }