@linxin666/dsh-liangshen 0.3.22 → 0.3.24

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 (37) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -38
  3. package/README.zh.md +44 -37
  4. package/lib/client.js +1058 -11
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +105 -22
  7. package/lib/types/client/LiangShenSettingsCard.d.ts +61 -0
  8. package/lib/types/client/PluginSettingsCard.d.ts +133 -0
  9. package/lib/types/client/index.d.ts +34 -0
  10. package/lib/types/client/locales.d.ts +27 -1
  11. package/lib/types/client/plugin-card-seat.d.ts +96 -0
  12. package/lib/types/client/settings-form.d.ts +197 -0
  13. package/lib/types/core/lever.d.ts +6 -3
  14. package/lib/types/index.d.ts +23 -11
  15. package/lib/types/sync.d.ts +29 -2
  16. package/package.json +6 -2
  17. package/presets/liangshen/NOTICE +4 -4
  18. package/presets/liangshen/agent.cordis.yml +130 -119
  19. package/presets/liangshen/minimal-prompt.mjs +71 -36
  20. package/presets/liangshen/paging.mjs +232 -0
  21. package/presets/liangshen/tool-activate.mjs +176 -0
  22. package/presets/liangshen/tool-catalog.mjs +610 -218
  23. package/presets/liangshen/working-context.mjs +214 -0
  24. package/src/client/LiangShenLever.tsx +4 -1
  25. package/src/client/LiangShenSettingsCard.tsx +149 -0
  26. package/src/client/PluginSettingsCard.tsx +550 -0
  27. package/src/client/index.ts +60 -1
  28. package/src/client/locales.ts +53 -1
  29. package/src/client/plugin-card-seat.ts +185 -0
  30. package/src/client/settings-card.module.css +418 -0
  31. package/src/client/settings-form.ts +439 -0
  32. package/src/core/lever.ts +7 -4
  33. package/src/index.ts +35 -14
  34. package/src/sync.test.ts +86 -7
  35. package/src/sync.ts +108 -6
  36. package/tools/benchmark-live-run.mjs +24 -33
  37. package/presets/liangshen/custom-bash.mjs +0 -213
@@ -1,42 +1,56 @@
1
1
  /**
2
2
  * minimal-prompt — keep this preset's system prompt on the builtin Minimal
3
3
  * preset's one-line persona (plus the session's workspace directory) while the
4
- * tool surface is staged behind the anchor turn and handed to PTC presentation
5
- * after it.
4
+ * sibling tool-catalog plugin owns the wire: one presentation declaration per
5
+ * session ('native' | 'ptc' | 'both') and gentle paging for high-fan-out
6
+ * namespaces.
6
7
  *
7
8
  * The assembled prompt is filtered down to the persona section, plus the plan
8
- * policy when plan mode is active and the official PTC tool SDK sections
9
- * (`tools:sdk` and `tools:ptc-only`) when PTC mode is active: the harness
9
+ * policy when plan mode is active, plus the official PTC tool SDK sections
10
+ * (`tools:sdk` and `tools:ptc-only`) exactly when the assembled wire carries
11
+ * the `run_code` transport (presentations 'ptc' and 'both'; an unreadable wire
12
+ * keeps them, matching the harness's own empty-section drop): the harness
10
13
  * identity, web-surface, tool-guidance, file-reference, and structured-output
11
- * sections never reach the model. Under PTC presentation, keeping the official
12
- * `tools:sdk` and `tools:ptc-only` sections ensures the model receives the
13
- * complete generated tool signatures, argument types, output schemas, and
14
- * parameter comments without private SDK schemas or renderer duplication.
14
+ * sections never reach the model. Keeping the official SDK sections when the
15
+ * transport is present ensures the model receives the complete generated tool
16
+ * signatures, argument types, output schemas, and parameter comments without
17
+ * private SDK schemas or renderer duplication.
15
18
  *
16
19
  * WORKSPACE LINE: the bare persona says nothing about where the session
17
20
  * operates, so the selected workspace directory is appended to the persona at
18
21
  * assembly time (`Your working directory is <cwd>.`), read from the session
19
22
  * header. This is the only orientation fact the persona block carries.
20
23
  *
21
- * WORKSPACE INSTRUCTIONS (default `instructionSource: 'system-prompt'`): the
22
- * AGENTS.md-style instruction files the harness would inject as user-role
23
- * context are instead read at assembly time and become part of the system
24
- * prompt itself, as one `workspace-instructions` section appended after the
25
- * persona block and plan mode's policy. Discovery mirrors the harness's
26
- * baseline chain — `$DSH_HOME/AGENTS.md`, then `AGENTS.md` / `CLAUDE.md` and
27
- * their `.local` overlays from the project root (the nearest ancestor holding
28
- * a `.git` marker) down to the session cwd, broadest first, with the harness's
29
- * per-directory duplicate suppression and byte budget — so the content rides
30
- * the prompt on every request: it survives compaction, needs no durable
31
- * message, and picks up file edits on the next assembly. The section is
32
- * appended after the stable prefix, so the anchor's KV-cache prefix stays
33
- * intact. Because the harness's prompt renderer interpolates every section
34
- * strictly, the section text is only a `{{workspace_instructions}}` reference
35
- * and the rendered content travels as that assembly variable's value —
36
- * variable values are inserted verbatim and never re-scanned, so instruction
37
- * files may contain `{{...}}` examples without breaking every request.
24
+ * WORKSPACE INSTRUCTIONS (`instructionSource`, default `'host'`): where the
25
+ * AGENTS.md-style instruction files reach the model.
38
26
  *
39
- * DYNAMIC RECONCILIATION & HOST CONTRACT:
27
+ * - `'host'` (default): the plugin appends no prompt section and leaves
28
+ * `decision.messages` byte-for-byte untouched, so the preset's own mounted
29
+ * `@deepseek-ai/dsh-agent-instructions` row delivers the baseline and the
30
+ * dynamic subdirectory instructions as ordinary user-role messages, exactly
31
+ * as the upstream presets do. The system prompt stays the bare persona (plus
32
+ * plan mode's policy), and the durability cost is the harness's: the baseline
33
+ * is a message the host re-derives on every step, not prompt text that
34
+ * survives compaction for free.
35
+ * - `'system-prompt'`: the files are instead read at assembly time and become
36
+ * part of the system prompt itself, as one `workspace-instructions` section
37
+ * appended after the persona block and plan mode's policy, while the
38
+ * harness's own injections are condensed or dropped so nothing duplicates.
39
+ * Discovery mirrors the harness's baseline chain — `$DSH_HOME/AGENTS.md`,
40
+ * then `AGENTS.md` / `CLAUDE.md` and their `.local` overlays from the
41
+ * project root (the nearest ancestor holding a `.git` marker) down to the
42
+ * session cwd, broadest first, with the harness's per-directory duplicate
43
+ * suppression and byte budget — so the content rides the prompt on every
44
+ * request: it survives compaction, needs no durable message, and picks up
45
+ * file edits on the next assembly. The section is appended after the stable
46
+ * prefix, so the anchor's KV-cache prefix stays intact. Because the harness's
47
+ * prompt renderer interpolates every section strictly, the section text is
48
+ * only a `{{workspace_instructions}}` reference and the rendered content
49
+ * travels as that assembly variable's value — variable values are inserted
50
+ * verbatim and never re-scanned, so instruction files may contain `{{...}}`
51
+ * examples without breaking every request.
52
+ *
53
+ * DYNAMIC RECONCILIATION & HOST CONTRACT (`'system-prompt'` only):
40
54
  * - Baseline instructions are resident in the system prompt. When the host's
41
55
  * agent-instructions emits a pure baseline message (`source.baseline === true`),
42
56
  * if the baseline was successfully loaded in the system prompt for this session,
@@ -59,10 +73,12 @@
59
73
  * instructions triggered by an inner read/edit are projected on the NEXT step;
60
74
  * same-program writes execute before that next-step projection reaches model context.
61
75
  *
62
- * `instructionSource: 'hint'` restores hint behavior: the first injection
76
+ * `instructionSource: 'hint'` is the third source: the first injection
63
77
  * becomes a single non-imperative pointer to the reference files (issue #388,
64
78
  * upstream dsh-anchored-standard #49) and every later injection is dropped; the
65
- * model reaches the knowledge through read / skill_load.
79
+ * model reaches the knowledge through read / skill_load. Like `'host'` it
80
+ * appends no prompt section, but unlike `'host'` it rewrites the host's
81
+ * messages.
66
82
  *
67
83
  * PLAN MODE is kept by default. `dsh-plan-mode` enforces its rules through
68
84
  * the `plan:policy` prompt section alone. `keepPlanPolicy: false` restores the
@@ -106,8 +122,13 @@ export const PTC_SECTION_NAMES = ['tools:ptc-only', 'tools:sdk']
106
122
  export const WORKSPACE_INSTRUCTIONS_SECTION_NAME = 'workspace-instructions'
107
123
  export const WORKSPACE_INSTRUCTIONS_VARIABLE = 'workspace_instructions'
108
124
 
109
- /** Accepted `instructionSource` values, default first. */
110
- export const INSTRUCTION_SOURCES = ['system-prompt', 'hint']
125
+ /**
126
+ * Accepted `instructionSource` values, default first: `'host'` hands the
127
+ * instructions back to the harness's own user-role injection, `'system-prompt'`
128
+ * lifts them into the system prompt, `'hint'` replaces them with a one-time
129
+ * pointer.
130
+ */
131
+ export const INSTRUCTION_SOURCES = ['host', 'system-prompt', 'hint']
111
132
 
112
133
  /** Tools whose executions touch workspace files and may trigger dynamic instruction discovery. */
113
134
  export const FILE_TOUCH_TOOL_NAMES = new Set(['read', 'write', 'edit', 'str_replace_editor'])
@@ -664,13 +685,8 @@ export function withWorkspaceLine(sections, agent) {
664
685
  /** Register the section filter, workspace-instruction source, and dynamic discovery hooks. */
665
686
  export function apply(ctx, config) {
666
687
  const keepPlanPolicy = optionalBoolean(config?.keepPlanPolicy, 'keepPlanPolicy', true)
667
- const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'system-prompt')
688
+ const instructionSource = optionalSource(config?.instructionSource, 'instructionSource', 'host')
668
689
  const instructionMaxBytes = optionalByteSize(config?.instructionMaxBytes, 'instructionMaxBytes', DEFAULT_INSTRUCTION_MAX_BYTES)
669
- const keep = new Set([
670
- ...PERSONA_SECTION_NAMES,
671
- ...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
672
- ...PTC_SECTION_NAMES,
673
- ])
674
690
 
675
691
  // Per-session state tracking (durable across steps, recoverable on replay)
676
692
  const sessionStateMap = new WeakMap()
@@ -724,6 +740,17 @@ export function apply(ctx, config) {
724
740
  ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
725
741
  const assembled = await next()
726
742
  if (!Array.isArray(assembled.sections)) return assembled
743
+ // The official SDK sections belong to the run_code transport: keep them
744
+ // exactly when this assembly's wire carries it ('ptc' and 'both'), drop
745
+ // them from a native wire they would only confuse. An unreadable wire keeps
746
+ // them, matching the harness's own empty-section drop under 'native'.
747
+ const wire = Array.isArray(assembled?.tools) ? assembled.tools : undefined
748
+ const wireHasRunCode = wire === undefined ? true : wire.some(tool => tool?.name === 'run_code')
749
+ const keep = new Set([
750
+ ...PERSONA_SECTION_NAMES,
751
+ ...(keepPlanPolicy ? [PLAN_POLICY_SECTION_NAME] : []),
752
+ ...(wireHasRunCode ? PTC_SECTION_NAMES : []),
753
+ ])
727
754
  const sections = assembled.sections.filter(section => keep.has(section?.name))
728
755
  if (sections.length === 0) {
729
756
  warnOnce(`${name}: no section matched ${JSON.stringify([...keep])} — `
@@ -731,6 +758,8 @@ export function apply(ctx, config) {
731
758
  return assembled
732
759
  }
733
760
  const narrowed = withWorkspaceLine(sections, context?.agent)
761
+ // 'host' and 'hint' append no workspace-instructions section: the harness's
762
+ // own agent-instructions row carries the content (or the hint replaces it).
734
763
  if (instructionSource !== 'system-prompt') return { ...assembled, sections: narrowed }
735
764
 
736
765
  let text
@@ -788,6 +817,12 @@ export function apply(ctx, config) {
788
817
  return { ...decision, messages: instructionHintMessages(decision.messages, state) }
789
818
  }
790
819
 
820
+ // Host mode: the harness's agent-instructions row owns the channel, so every
821
+ // message it queued — baseline and dynamic alike — passes through verbatim:
822
+ // no filterInstructionMessages, no dynamic subdirectory discovery, no
823
+ // plugin-authored message. Handing the decision back unchanged is the point.
824
+ if (instructionSource === 'host') return decision
825
+
791
826
  // System-prompt mode:
792
827
  const cwd = session?.header?.cwd
793
828
  const baselineLoaded = state?.baselineLoaded ?? false
@@ -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
+ }