@linxin666/dsh-liangshen 0.1.19 → 0.1.20

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/README.i18n.yaml CHANGED
@@ -2,5 +2,5 @@
2
2
  # side as of the last confirmed-consistent state. Both languages carry equal authority;
3
3
  # after editing either side, bring the other along and re-record with:
4
4
  # node scripts/verify-docs.mjs --write <dir>
5
- README.md: ae227ee20159760120c4b9b6a939be7a86630083
6
- README.zh.md: f801f176e5fa64c68982425b040cd5bd424d5210
5
+ README.md: c92073da251703316c10f0268e8befe94d89d1d5
6
+ README.zh.md: b93cfb8d13c52e9e941219a2664e8439ab9da5c6
package/README.md CHANGED
@@ -14,6 +14,8 @@ DeepSeek V4 Pro conditions strongly on the API tool catalog visible in the FIRST
14
14
 
15
15
  Measured on native Windows (DeepSeek V4 Pro, max, V4.1b task): 98 / 99, mean 98.5, zero `let me` traces in the second run — reproducible, not a lucky draw, and no tool capability sacrificed. Original experiment: [xiaobright/dsh-anchored-standard](https://github.com/xiaobright/dsh-anchored-standard).
16
16
 
17
+ Windows note: DSH's PTY backend is linux/darwin-only, so on win32 the persistent-shell group is disabled and phase-1 `bash` switches to `custom-bash` — the same name and Minimal-compatible schema, spawning Git Bash through the ordinary cross-platform subprocess seam (see `presets/liangshen/custom-bash.mjs`).
18
+
17
19
  ## Stabilization controls
18
20
 
19
21
  The preset ships with extra safeguards on top of the reference mechanism, all configured in `agent.cordis.yml` under `tool-bootstrap`:
package/README.zh.md CHANGED
@@ -14,6 +14,8 @@ DeepSeek V4 Pro 会强烈依赖 API 中可见的**首轮工具目录**选择执
14
14
 
15
15
  Windows 原生环境实测(DeepSeek V4 Pro、max、V4.1b 题面):98 / 99,均值 98.5,第二轮全程无 `let me` 痕迹,证明不是抽卡,也不需要牺牲完整工具能力。原始实验 preset:[xiaobright/dsh-anchored-standard](https://github.com/xiaobright/dsh-anchored-standard)。
16
16
 
17
+ Windows 说明:DSH 的 PTY 后端仅支持 linux/darwin,win32 上持久 shell 组被禁用,phase-1 的 `bash` 切换为 `custom-bash`——同名且 schema 与 Minimal 兼容,经普通跨平台子进程通道调起 Git Bash(见 `presets/liangshen/custom-bash.mjs`)。
18
+
17
19
  ## 稳定化控制
18
20
 
19
21
  preset 在参考机制之上内置了额外保护,全部在 `agent.cordis.yml` 的 `tool-bootstrap` 段配置:
package/lib/index.js CHANGED
@@ -310,6 +310,47 @@ function syncPresetTrees(sourceRoot, targetRoot, retire = []) {
310
310
  return result;
311
311
  }
312
312
  //#endregion
313
+ //#region src/mount-once.ts
314
+ /**
315
+ * Host single-instance guard shared by the plugin family. The family bundle
316
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
317
+ * the loader accepts a standalone install of the same package side by side;
318
+ * without this guard the second instance would still re-register the same
319
+ * webserver routes, tools, settings namespaces, and system-prompt sections
320
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
321
+ * lifetime of the first instance (the browser half is already deduped by
322
+ * package name in the client module host).
323
+ *
324
+ * The registry rides a global symbol so two module instances of the same
325
+ * package (npm copy vs repository link) still share one verdict. cordis
326
+ * `ctx.effect` runs its callback immediately and treats the callback's
327
+ * return value as the fiber disposer, so the unmarker is returned, not run.
328
+ */
329
+ const MOUNTED = Symbol.for("dsh-web-ui.mounted-plugins");
330
+ function mountedSet() {
331
+ const registry = globalThis;
332
+ return registry[MOUNTED] ??= /* @__PURE__ */ new Set();
333
+ }
334
+ /**
335
+ * Wrap a cordis plugin apply so the package runs at most once per process.
336
+ * The first mount registers normally and unmarks when its fiber disposes;
337
+ * any later mount of the same package name is a no-op.
338
+ * @param packageName - npm package identity shared by every install source.
339
+ * @param fn - the original plugin apply.
340
+ * @returns an apply of the same shape.
341
+ */
342
+ function mountOnce(packageName, fn) {
343
+ return ((...args) => {
344
+ const mounted = mountedSet();
345
+ if (mounted.has(packageName)) return;
346
+ mounted.add(packageName);
347
+ args[0]?.effect?.(() => () => {
348
+ mounted.delete(packageName);
349
+ });
350
+ return fn(...args);
351
+ });
352
+ }
353
+ //#endregion
313
354
  //#region src/index.ts
314
355
  /**
315
356
  * dsh-liangshen — LiangShen (梁神) agent preset plugin.
@@ -350,7 +391,8 @@ function bundledPresetsRoot() {
350
391
  * @param ctx - host plugin context carrying systemPrompt.
351
392
  * @param config - resolved plugin config (schema defaults applied by the loader).
352
393
  */
353
- function apply(ctx, config) {
394
+ const apply = mountOnce("@linxin666/dsh-liangshen", applyImpl);
395
+ function applyImpl(ctx, config) {
354
396
  const resolve = () => ({
355
397
  announceToAgent: config?.announceToAgent ?? DEFAULT_ANNOUNCE,
356
398
  enabled: config?.enabled ?? true
@@ -38,4 +38,5 @@ export declare function bundledPresetsRoot(): string;
38
38
  * @param ctx - host plugin context carrying systemPrompt.
39
39
  * @param config - resolved plugin config (schema defaults applied by the loader).
40
40
  */
41
- export declare function apply(ctx: Context, config?: Config): void;
41
+ export declare const apply: typeof applyImpl;
42
+ declare function applyImpl(ctx: Context, config?: Config): void;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Host single-instance guard shared by the plugin family. The family bundle
3
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
4
+ * the loader accepts a standalone install of the same package side by side;
5
+ * without this guard the second instance would still re-register the same
6
+ * webserver routes, tools, settings namespaces, and system-prompt sections
7
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
8
+ * lifetime of the first instance (the browser half is already deduped by
9
+ * package name in the client module host).
10
+ *
11
+ * The registry rides a global symbol so two module instances of the same
12
+ * package (npm copy vs repository link) still share one verdict. cordis
13
+ * `ctx.effect` runs its callback immediately and treats the callback's
14
+ * return value as the fiber disposer, so the unmarker is returned, not run.
15
+ */
16
+ /**
17
+ * Wrap a cordis plugin apply so the package runs at most once per process.
18
+ * The first mount registers normally and unmarks when its fiber disposes;
19
+ * any later mount of the same package name is a no-op.
20
+ * @param packageName - npm package identity shared by every install source.
21
+ * @param fn - the original plugin apply.
22
+ * @returns an apply of the same shape.
23
+ */
24
+ export declare function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@linxin666/dsh-liangshen",
3
3
  "description": "LiangShen (梁神) agent preset for the dsh web GUI: a two-phase anchored-standard preset — the first model request exposes only the builtin Minimal exact two-tool surface (persistent bash plus str_replace_editor) with no runtime contexts or injected instructions (Minimal-aligned trajectory anchor), promotion is gated on the first minimal-like reasoning block with a fallback, and the wire then switches to Code Mode (PTC, a single run_code tool over the full registry) with the ordinary injections returning afterwards. The preset files are synced into ~/.dsh/.agent-presets on host startup. Hot-pluggable — mounted via cordis.patch.yml + a profile node_modules symlink, no dsh source changes.",
4
- "version": "0.1.19",
4
+ "version": "0.1.20",
5
5
  "type": "module",
6
6
  "engines": {
7
7
  "node": "^22.19.0 || >=24.0.0"
@@ -1,4 +1,7 @@
1
1
  agent.cordis.yml 改编自 DeepSeek Harness 内置 Minimal 与 Standard preset(MIT)。
2
2
  tool-bootstrap.mjs 来自 https://github.com/xiaobright/dsh-anchored-standard(MIT),
3
3
  并包含 dsh-liangshen 的两阶段隔离扩展。
4
+ custom-bash.mjs 移植自同一上游(xiaobright/dsh-anchored-standard,MIT)的
5
+ combo-anchored/custom-bash.mjs,用于 win32 上以跨平台子进程通道提供同名
6
+ `bash` 工具(Git Bash)。
4
7
  原始 DeepSeek 版权和 MIT 许可声明见开源仓库。
@@ -99,6 +99,7 @@
99
99
  - id: persistent-shell
100
100
  name: cordis:group
101
101
  group: true
102
+ disabled: !!js process.platform === 'win32'
102
103
  isolate:
103
104
  terminals: true
104
105
  config:
@@ -124,6 +125,19 @@
124
125
  * Please avoid commands that may produce a very large amount of output.
125
126
  * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.
126
127
 
128
+ # Windows-only `bash` tool (custom-bash.mjs): the PTY backend above is
129
+ # linux/darwin-only, so win32 disables the persistent-shell group and
130
+ # registers this `bash` through the ordinary cross-platform subprocess seam
131
+ # (Git Bash). Both platforms end up with exactly one tool named `bash`, so the
132
+ # phase-1 Minimal anchor (shellTools: [bash] + str_replace_editor) is
133
+ # unchanged. Non-zero exit is reported not thrown; state does NOT persist
134
+ # across calls on this path; no OS sandbox confinement on Windows. `bashPath`
135
+ # is optional (defaults to Git Bash inference); set it explicitly when git is
136
+ # not on PATH.
137
+ - id: custom-bash
138
+ name: ./custom-bash.mjs
139
+ disabled: !!js process.platform !== 'win32'
140
+
127
141
  # ── minimal phase-1 filesystem ──────────────────────────────────────────────
128
142
 
129
143
  # Phase-1 editor as a direct top-level row: it reuses the host's sandboxed
@@ -0,0 +1,213 @@
1
+ /**
2
+ * custom-bash — a Windows-capable `bash` tool for the liangshen preset. It
3
+ * registers under the SAME name (`bash`) as the persistent shell so the
4
+ * phase-1 Minimal anchor (bash + str_replace_editor) holds on every platform,
5
+ * but executes through `ctx.subprocess.spawn` instead of a PTY.
6
+ *
7
+ * WHY: DSH's PTY backend is linux/darwin-only — subprocess-local throws
8
+ * "terminal inspection is unsupported on platform win32", so the
9
+ * persistent-shell group (dsh-terminal + dsh-terminal-bash +
10
+ * dsh-tool-bash-persistent) cannot spawn on Windows. agent.cordis.yml disables
11
+ * that group on win32 and enables this tool instead; both platforms end up
12
+ * with exactly one `bash` tool and the byte-exact schema anchor is kept.
13
+ *
14
+ * Executable resolution (config `bashPath`, no hardcoded install path):
15
+ * an explicit non-empty `bashPath` wins unconditionally. Unset, the Git Bash
16
+ * executable is INFERRED in probe order:
17
+ * 1. the `git` executable on PATH — its install root carries `bin\bash.exe`
18
+ * one level up from `cmd\`, beside `bin\`, or two levels up from
19
+ * `mingw64\bin\` (the standard installer, choco, and winget all resolve
20
+ * here);
21
+ * 2. the well-known Git-for-Windows roots derived from environment variables
22
+ * (ProgramFiles, ProgramFiles(x86), LOCALAPPDATA\Programs\Git, scoop's
23
+ * ~\scoop\apps\git\current junction);
24
+ * 3. plain `bash` through `ctx.subprocess.resolveExecutable` (PATH lookup —
25
+ * last resort; on Windows that may pick the WSL shim, which is still true
26
+ * bash even though paths shift to /mnt/…).
27
+ *
28
+ * If NOTHING resolves the tool fails with an actionable error — it never
29
+ * silently executes under pwsh/cmd, which are different command languages.
30
+ *
31
+ * Semantics mirror the official bash tool: `bash -c <command>` in a fresh
32
+ * process, bounded output, non-zero exit reported not thrown. No sandbox
33
+ * confinement on Windows (the sandbox backend is linux-only); the description
34
+ * says so.
35
+ *
36
+ * Ported from xiaobright/dsh-anchored-standard (MIT) — see NOTICE.
37
+ */
38
+
39
+ import { access } from 'node:fs/promises'
40
+ import { dirname, join } from 'node:path'
41
+
42
+ /** Cordis plugin name used by loader diagnostics. */
43
+ export const name = 'custom-bash'
44
+
45
+ /** The subprocess and tools services must exist before this tool can register. */
46
+ export const inject = ['subprocess', 'tools']
47
+
48
+ const DEFAULT_TIMEOUT_MS = 120000
49
+ const DEFAULT_MAX_OUTPUT_BYTES = 64000
50
+
51
+ /**
52
+ * Git Bash candidate paths, in probe order (see the header): the `git`
53
+ * executable's install root first, then the well-known env-derived roots.
54
+ * Exported for tests; pure — existence probing happens at the call site.
55
+ */
56
+ export function bashCandidates(env, gitExe) {
57
+ const candidates = []
58
+ // git at <root>\cmd\git.exe (installer/scoop) or <root>\bin\git.exe →
59
+ // <root>\bin\bash.exe; <root>\mingw64\bin\git.exe (portable) → two up.
60
+ // A bare relative name means `git` did not actually resolve to a path.
61
+ if (typeof gitExe === 'string' && /[/\\]/.test(gitExe)) {
62
+ const dir = dirname(gitExe)
63
+ const root = dirname(dir)
64
+ candidates.push(
65
+ join(root, 'bin', 'bash.exe'),
66
+ join(dir, 'bash.exe'),
67
+ join(dirname(root), 'bin', 'bash.exe'),
68
+ )
69
+ }
70
+ if (env.ProgramFiles) candidates.push(join(env.ProgramFiles, 'Git', 'bin', 'bash.exe'))
71
+ if (env['ProgramFiles(x86)']) candidates.push(join(env['ProgramFiles(x86)'], 'Git', 'bin', 'bash.exe'))
72
+ if (env.LOCALAPPDATA) candidates.push(join(env.LOCALAPPDATA, 'Programs', 'Git', 'bin', 'bash.exe'))
73
+ if (env.USERPROFILE) candidates.push(join(env.USERPROFILE, 'scoop', 'apps', 'git', 'current', 'bin', 'bash.exe'))
74
+ // Layouts overlap (a `bin` git.exe derives the same bash twice) — probe
75
+ // order survives the dedupe, insertion order is preserved.
76
+ return [...new Set(candidates)]
77
+ }
78
+
79
+ /** Tool parameter schema for the model-facing command. */
80
+ const commandSchema = {
81
+ type: 'object',
82
+ properties: {
83
+ command: {
84
+ type: 'string',
85
+ description: 'The bash command to execute (`bash -c` string domain).',
86
+ },
87
+ workdir: {
88
+ type: 'string',
89
+ description: 'Optional working directory; defaults to the session cwd.',
90
+ },
91
+ },
92
+ required: ['command'],
93
+ additionalProperties: false,
94
+ }
95
+
96
+ /** Register the model-facing `bash` tool. */
97
+ export function apply(ctx, config) {
98
+ const explicitBashPath = typeof config?.bashPath === 'string' && config.bashPath.length > 0 ? config.bashPath : undefined
99
+ const timeoutMs = Number.isSafeInteger(config?.timeoutMs) && config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_TIMEOUT_MS
100
+ const maxOutputBytes = Number.isSafeInteger(config?.maxOutputBytes) && config.maxOutputBytes > 0 ? config.maxOutputBytes : DEFAULT_MAX_OUTPUT_BYTES
101
+
102
+ // The inferred executable is memoized per plugin instance: candidate probing
103
+ // walks the filesystem, and the answer cannot change within a mount. A
104
+ // failed inference is NOT memoized — the plain `bash` fallback resolves
105
+ // fresh on every execute until some probe succeeds.
106
+ let inferredShell
107
+ const exists = (path) => access(path).then(() => true, () => false)
108
+ const resolveShell = async (signal) => {
109
+ if (explicitBashPath !== undefined) {
110
+ // A misconfigured explicit path must fail as itself, not as a
111
+ // discovery miss — the raw resolution error says which path failed.
112
+ return ctx.subprocess.resolveExecutable(explicitBashPath, undefined, signal)
113
+ }
114
+ if (inferredShell !== undefined) {
115
+ return ctx.subprocess.resolveExecutable(inferredShell, undefined, signal)
116
+ }
117
+ let gitExe
118
+ try {
119
+ gitExe = await ctx.subprocess.resolveExecutable('git', undefined, signal)
120
+ } catch {
121
+ // git unresolvable → the env-derived candidates below still apply
122
+ }
123
+ for (const candidate of bashCandidates(process.env, gitExe)) {
124
+ if (!(await exists(candidate))) continue
125
+ try {
126
+ inferredShell = await ctx.subprocess.resolveExecutable(candidate, undefined, signal)
127
+ return inferredShell
128
+ } catch {
129
+ // Exists but unresolvable (EPERM, a broken scoop junction): keep
130
+ // probing — one bad root must not block the rest of the chain, and
131
+ // nothing is memoized so later executes can still find a good one.
132
+ continue
133
+ }
134
+ }
135
+ try {
136
+ return await ctx.subprocess.resolveExecutable('bash', undefined, signal)
137
+ } catch (error) {
138
+ // Total discovery failure (no Git Bash root, no env root, no bash on
139
+ // PATH): name the remedies instead of leaking a raw ENOENT. Never
140
+ // fall back to pwsh/cmd here — the schema promises `bash -c`
141
+ // semantics; a different shell would silently break every command.
142
+ throw new Error(`bash executable not found — install Git for Windows, expose a bash on PATH, or set the custom-bash \`bashPath\` config (${String((error && error.message) || error)})`)
143
+ }
144
+ }
145
+
146
+ ctx.tools.register({
147
+ name: 'bash',
148
+ description: [
149
+ 'Run commands in a bash shell (Git Bash on Windows)',
150
+ '* When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.',
151
+ "* You don't have access to the internet via this tool.",
152
+ '* You do have access to a mirror of common linux and python packages via apt and pip.',
153
+ '* State does NOT persist across command calls: each call runs in a fresh shell.',
154
+ "* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.",
155
+ '* Please avoid commands that may produce a very large amount of output.',
156
+ '* NOTE: runs without OS sandbox confinement on Windows (no landlock); treat output as untrusted.',
157
+ ].join('\n'),
158
+ parameters: commandSchema,
159
+ output: {
160
+ schema: {
161
+ type: 'object',
162
+ additionalProperties: false,
163
+ properties: {
164
+ text: { type: 'string' },
165
+ },
166
+ required: ['text'],
167
+ },
168
+ render: (_args, value) => [{ type: 'text', text: value.text }],
169
+ },
170
+ async execute(args, exec) {
171
+ const shell = await resolveShell(exec?.signal)
172
+ const workdir = typeof args.workdir === 'string' && args.workdir.length > 0
173
+ ? args.workdir
174
+ : exec?.agent?.session?.header?.cwd
175
+ const signal = exec?.signal
176
+ const handle = ctx.subprocess.spawn({
177
+ argv: [shell, '-c', args.command],
178
+ ...workdir !== undefined ? { cwd: workdir } : {},
179
+ stdio: {
180
+ stdin: 'ignore',
181
+ stdout: { maxBytes: maxOutputBytes },
182
+ stderr: { maxBytes: maxOutputBytes },
183
+ },
184
+ ...signal !== undefined ? { signal } : {},
185
+ graceMs: 3000,
186
+ })
187
+ let outcome
188
+ try {
189
+ outcome = await handle.done
190
+ } catch (error) {
191
+ // A spawn-level failure (bad executable, EPERM) surfaces as a throw,
192
+ // which the runtime turns into an isError result.
193
+ throw new Error(`bash spawn failed: ${String(error)}`)
194
+ }
195
+ let stdout = ''
196
+ let stderr = ''
197
+ try {
198
+ stdout = handle.collected.stdout.readFrom(0).text
199
+ stderr = handle.collected.stderr.readFrom(0).text
200
+ } catch {
201
+ // Collected readers may be unavailable on some backends; tolerate.
202
+ }
203
+ const text = [stdout, stderr].filter((part) => part.length > 0).join('\n')
204
+ const tail = text.length > 0 ? text : `exit code: ${outcome.exitCode} (no output)`
205
+ if (outcome.exitCode !== 0) {
206
+ // Non-zero exit is a reported failure, not a throw: the model sees the
207
+ // command output plus the exit code.
208
+ throw new Error(tail)
209
+ }
210
+ return { text: tail }
211
+ },
212
+ })
213
+ }
@@ -110,7 +110,7 @@ function integerAtLeast(value, field, minimum) {
110
110
  return value
111
111
  }
112
112
 
113
- function countWord(text, regex) {
113
+ export function countWord(text, regex) {
114
114
  return [...text.matchAll(regex)].length
115
115
  }
116
116
 
@@ -226,13 +226,15 @@ function resetToControlled(state) {
226
226
  */
227
227
  function applyPresentation(agent, state, policy) {
228
228
  if (state.presentationApplied || policy.promotedPresentation !== 'code') return
229
- state.presentationApplied = true
230
229
  const tools = agent.ctx.tools
230
+ // Latch only after the switch really happened: without a tools view there
231
+ // is nothing to present, and latching early would skip Code Mode forever.
231
232
  if (tools === undefined) return
232
233
  // The disposer restores the deployment-default (native) presentation; it is
233
234
  // kept on the state so a post-compaction reset can release Code Mode and
234
235
  // let the phase-1 catalog filter see the native tool list again.
235
236
  state.presentationDisposer = tools.presentAs('code')
237
+ state.presentationApplied = true
236
238
  }
237
239
 
238
240
  /**
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ import type {} from '@deepseek-ai/dsh-system-prompt'
22
22
  import z from 'schemastery'
23
23
  import { dshHome } from './dsh-home.ts'
24
24
  import { syncPresetTrees } from './sync.ts'
25
+ import { mountOnce } from './mount-once.ts'
25
26
 
26
27
  /** Stable cordis plugin name. */
27
28
  export const name = 'liangshen'
@@ -68,7 +69,9 @@ export function bundledPresetsRoot(): string {
68
69
  * @param ctx - host plugin context carrying systemPrompt.
69
70
  * @param config - resolved plugin config (schema defaults applied by the loader).
70
71
  */
71
- export function apply(ctx: Context, config?: Config): void {
72
+ export const apply = mountOnce('@linxin666/dsh-liangshen', applyImpl)
73
+
74
+ function applyImpl(ctx: Context, config?: Config): void {
72
75
  const resolve = (): Config => ({
73
76
  announceToAgent: config?.announceToAgent ?? DEFAULT_ANNOUNCE,
74
77
  enabled: config?.enabled ?? true,
@@ -0,0 +1,48 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/mount-once.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * Host single-instance guard shared by the plugin family. The family bundle
4
+ * (dsh-web-ui-all / dsh-skins) namespaces every child row id (web-ui-*), so
5
+ * the loader accepts a standalone install of the same package side by side;
6
+ * without this guard the second instance would still re-register the same
7
+ * webserver routes, tools, settings namespaces, and system-prompt sections
8
+ * and fail the boot. mountOnce makes the second host apply a no-op for the
9
+ * lifetime of the first instance (the browser half is already deduped by
10
+ * package name in the client module host).
11
+ *
12
+ * The registry rides a global symbol so two module instances of the same
13
+ * package (npm copy vs repository link) still share one verdict. cordis
14
+ * `ctx.effect` runs its callback immediately and treats the callback's
15
+ * return value as the fiber disposer, so the unmarker is returned, not run.
16
+ */
17
+
18
+ const MOUNTED = Symbol.for('dsh-web-ui.mounted-plugins')
19
+
20
+ interface MountRegistry {
21
+ [MOUNTED]?: Set<string>
22
+ }
23
+
24
+ function mountedSet(): Set<string> {
25
+ const registry = globalThis as MountRegistry
26
+ return (registry[MOUNTED] ??= new Set())
27
+ }
28
+
29
+ /**
30
+ * Wrap a cordis plugin apply so the package runs at most once per process.
31
+ * The first mount registers normally and unmarks when its fiber disposes;
32
+ * any later mount of the same package name is a no-op.
33
+ * @param packageName - npm package identity shared by every install source.
34
+ * @param fn - the original plugin apply.
35
+ * @returns an apply of the same shape.
36
+ */
37
+ export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
38
+ return ((...args: unknown[]) => {
39
+ const mounted = mountedSet()
40
+ if (mounted.has(packageName)) return
41
+ mounted.add(packageName)
42
+ const ctx = args[0] as { effect?: (effect: () => unknown) => unknown } | undefined
43
+ ctx?.effect?.(() => () => {
44
+ mounted.delete(packageName)
45
+ })
46
+ return fn(...args)
47
+ }) as T
48
+ }
@@ -11,7 +11,7 @@
11
11
  import { createReadStream } from 'node:fs'
12
12
  import readline from 'node:readline'
13
13
 
14
- import { classifyReasoning } from '../presets/liangshen/tool-bootstrap.mjs'
14
+ import { classifyReasoning, countWord } from '../presets/liangshen/tool-bootstrap.mjs'
15
15
 
16
16
  const WORD = {
17
17
  we: /\bwe\b/gi,
@@ -29,27 +29,6 @@ export function countMarkers(text) {
29
29
  }
30
30
  }
31
31
 
32
- function countWord(text, regex) {
33
- return [...text.matchAll(regex)].length
34
- }
35
-
36
- /** Legacy helper: materialize every parsed event (kept for callers that need the array). */
37
- export async function readEvents(path) {
38
- const events = []
39
- const input = createReadStream(path)
40
- const lines = readline.createInterface({ input, crlfDelay: Infinity })
41
- for await (const line of lines) {
42
- const trimmed = line.trim()
43
- if (trimmed.length === 0) continue
44
- try {
45
- events.push(JSON.parse(trimmed))
46
- } catch {
47
- // Ignore malformed tail lines from a partially flushed export.
48
- }
49
- }
50
- return events
51
- }
52
-
53
32
  /**
54
33
  * Incremental session accumulator shared by the array and streaming paths so
55
34
  * both report exactly the same facts. It never retains parsed events or full