@linxin666/dsh-liangshen 0.4.1 → 0.4.3

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.
@@ -0,0 +1,142 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-entry-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ // Generated by scripts/sync-shared.mjs from shared/client/settings/settings-entry-form.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
3
+ /**
4
+ * Family settings form bound to the profile entry id a Host actually serves.
5
+ *
6
+ * Under the 0.1.7 settings model a form is addressed by PROFILE ENTRY ID, while
7
+ * a family card knows only its own settings namespace. The family binder
8
+ * (`ctx.get('webUiSettings')`, published by dsh-web-settings) resolves one onto
9
+ * the other and is the preferred transport; this module is the fallback for a
10
+ * page that serves no binder — the group plugin is not installed, or its client
11
+ * half has not applied yet (the aggregate mounts its children in order, and a
12
+ * child still waiting on its own injects publishes nothing).
13
+ *
14
+ * The shared describe mirror is the only local evidence of which row id this
15
+ * profile serves, but it answers asynchronously: at plugin activation it usually
16
+ * holds nothing yet. A one-shot guess therefore cannot be right for every
17
+ * deployment, and the form is bound once per session:
18
+ *
19
+ * - binding the bare namespace made every save answer `No configurable plugin
20
+ * entry "<namespace>"` on an aggregate install (the namespace is not an entry
21
+ * id there), which the card reported as "the deployment did not accept these
22
+ * values";
23
+ * - binding the aggregate row id would break a standalone install, whose row id
24
+ * is the namespace or the package's own `ui-*` row.
25
+ *
26
+ * So the fallback starts on the most likely row and REBINDS the moment the
27
+ * mirror names one of this package's rows. Until the mirror answers, the form
28
+ * reports the binding it holds (usually `loading`), which the card renders as an
29
+ * unavailable form rather than a doomed one.
30
+ */
31
+ import type { ConfigForm, ConfigFormSnapshot, ConfigForms } from '@deepseek-ai/dsh-client-ui-settings/client'
32
+
33
+ /** Options of {@link createServedEntryForm}. */
34
+ export interface ServedEntryFormOptions<T> {
35
+ /** The shared configuration forms service (`ctx.configForms`). */
36
+ forms: ConfigForms
37
+ /**
38
+ * Profile entry ids this package's rows carry, most likely first: the
39
+ * aggregate's generated row, the package's own standalone row, then the bare
40
+ * namespace. The first is the fallback while the mirror has no answer; the
41
+ * last is the answer when the mirror serves none of them.
42
+ */
43
+ entryIds: readonly string[]
44
+ }
45
+
46
+ /** The snapshot a form reports before the Host has answered with this entry. */
47
+ function pendingSnapshot<T>(): ConfigFormSnapshot<T> {
48
+ return {
49
+ status: 'loading',
50
+ value: undefined,
51
+ base: undefined,
52
+ user: undefined,
53
+ revision: undefined,
54
+ writable: false,
55
+ mode: 'host',
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Create a settings form bound to the profile entry id this Host serves, and
61
+ * rebound whenever the shared describe mirror names a different one of this
62
+ * package's rows.
63
+ * @param options - the shared forms service and this package's candidate row ids.
64
+ * @returns a form delegating to the currently resolved entry's own form.
65
+ */
66
+ export function createServedEntryForm<T>(options: ServedEntryFormOptions<T>): ConfigForm<T> {
67
+ const { forms, entryIds } = options
68
+ const fallbackId = entryIds[0]
69
+ const namespaceId = entryIds[entryIds.length - 1]
70
+ const listeners = new Set<() => void>()
71
+ let boundId: string | undefined
72
+ let bound: ConfigForm<T> | undefined
73
+ let offBound: (() => void) | undefined
74
+ let snapshot: ConfigFormSnapshot<T> = pendingSnapshot<T>()
75
+
76
+ /** Republish: the delegated snapshot when one is bound, the pending one otherwise. */
77
+ const publish = (): void => {
78
+ if (bound !== undefined) snapshot = bound.getSnapshot()
79
+ for (const listener of [...listeners]) listener()
80
+ }
81
+
82
+ /**
83
+ * The entry id the mirror currently justifies. An unanswered or empty mirror
84
+ * is not evidence of absence, so it keeps the first candidate; a mirror that
85
+ * answers without any of this package's rows leaves the namespace itself.
86
+ * @returns the entry id to bind.
87
+ */
88
+ const resolve = (): string => {
89
+ let served: readonly string[] | undefined
90
+ try {
91
+ served = forms.describe().getSnapshot().view?.namespaces.map(row => row.ns)
92
+ } catch {
93
+ // A mirror that refuses the read is unanswered too, not absent.
94
+ served = undefined
95
+ }
96
+ if (served === undefined || served.length === 0) return fallbackId
97
+ return entryIds.find(id => served.includes(id)) ?? namespaceId
98
+ }
99
+
100
+ /** Bind (or rebind) the resolved entry's form; a no-op while it is unchanged. */
101
+ const bind = (): void => {
102
+ const target = resolve()
103
+ if (target === boundId) return
104
+ offBound?.()
105
+ offBound = undefined
106
+ let form: ConfigForm<T>
107
+ try {
108
+ form = forms.get<T>(target)
109
+ } catch {
110
+ // A service that refuses the id stays unbound; the next mirror answer
111
+ // retries rather than pinning a wrong entry for the session.
112
+ boundId = undefined
113
+ return
114
+ }
115
+ boundId = target
116
+ bound = form
117
+ offBound = form.subscribe(() => { publish() })
118
+ publish()
119
+ }
120
+
121
+ // The mirror subscription lives for the page: the card owns its form for the
122
+ // session, and the ConfigForm contract carries no disposer to hang it on. The
123
+ // callback is cheap (a resolve plus a no-op while the id is unchanged). A
124
+ // mirror without a subscription seat keeps the initial binding.
125
+ try {
126
+ forms.describe().subscribe(() => { bind() })
127
+ } catch {
128
+ // A describe face that refuses the subscription: the initial binding stands.
129
+ }
130
+ bind()
131
+
132
+ return {
133
+ getSnapshot: () => snapshot,
134
+ subscribe: (listener) => {
135
+ listeners.add(listener)
136
+ return () => { listeners.delete(listener) }
137
+ },
138
+ set: (field, value) => bound?.set(field, value) ?? Promise.resolve(false),
139
+ unset: (field) => bound?.unset(field) ?? Promise.resolve(false),
140
+ mutate: (ops, expectedRevision) => bound?.mutate(ops, expectedRevision) ?? Promise.resolve(false),
141
+ }
142
+ }
package/src/index.ts CHANGED
@@ -250,6 +250,12 @@ function applyImpl(ctx: Context, config?: Config): void {
250
250
  let closed = false
251
251
  /** Serializes declaration work, so a settings write cannot interleave with an in-flight activation. */
252
252
  let queue: Promise<void> = Promise.resolve()
253
+ /**
254
+ * True when the last declaration attempt found no registry. It is the ONLY
255
+ * state the late-registry recovery below acts on, so a registry that was
256
+ * already present at activation is never re-declared.
257
+ */
258
+ let registryMissing = false
253
259
 
254
260
  const warn = (message: string): void => { ctx.logger?.warn?.(`dsh-liangshen: ${message}`) }
255
261
 
@@ -277,14 +283,19 @@ function applyImpl(ctx: Context, config?: Config): void {
277
283
  if (closed || target !== generation) return
278
284
  await undeclare()
279
285
  const values = resolveConfig(config)
280
- if (!values.enabled) return
286
+ if (!values.enabled) {
287
+ registryMissing = false
288
+ return
289
+ }
281
290
  const registry = registryOf()
282
291
  if (registry === undefined) {
292
+ registryMissing = true
283
293
  warn('the agent-preset registry is unavailable; the preset is not declared')
284
294
  return
285
295
  }
286
296
  try {
287
297
  release = await registry.register(declaration(values))
298
+ registryMissing = false
288
299
  ctx.logger?.info?.(`liangshen: preset ${LIANGSHEN_PRESET_ID} declared`)
289
300
  } catch (error) {
290
301
  warn(`declaring the preset failed: ${error instanceof Error ? error.message : String(error)}`)
@@ -319,6 +330,35 @@ function applyImpl(ctx: Context, config?: Config): void {
319
330
 
320
331
  ctx.on('loader/volatile-update', () => { rearm() })
321
332
 
333
+ /**
334
+ * Recover the declaration when the agent-preset registry appears.
335
+ *
336
+ * The registry is deliberately NOT a hard inject: a deployment may compose no
337
+ * preset registry at all, and waiting on it would then pend this row forever
338
+ * -- which under the host's boot gate fails the entire web boot, not just this
339
+ * plugin (issue #1712). But the registry's own publication is decided by its
340
+ * dependency chain (the official registry injects `loader` and
341
+ * `sessionProjections`, and reaches `settings` through `ctx.inject`), so this
342
+ * row's single activation can land BEFORE the service exists. Without this
343
+ * edge the one declaration attempt was simply lost until an unrelated settings
344
+ * write happened to re-arm -- exactly the "toggle any switch and the preset
345
+ * appears, and only then" report (issue #1721).
346
+ *
347
+ * `registryMissing` is the gate rather than a plain `rearm()`: the registry is
348
+ * normally already present at activation, and this callback fires
349
+ * asynchronously even then, so re-arming unconditionally would release and
350
+ * re-declare the preset the activation had just registered (and swap the
351
+ * announcement section for nothing). The callback only repairs the missed
352
+ * case -- the one where the earlier attempt warned and gave up -- and `declare`
353
+ * is idempotent (it undeclares first and carries a generation guard), so a
354
+ * recovery racing an in-flight declaration still settles on one live
355
+ * registration. The fiber's `closed` flag keeps a late arrival from declaring
356
+ * after this row unloads.
357
+ */
358
+ ctx.inject(['agentPresets'], () => {
359
+ if (registryMissing) rearm()
360
+ })
361
+
322
362
  ctx.effect(() => {
323
363
  rearm()
324
364
  return async () => {
package/src/mount-once.ts CHANGED
@@ -5,44 +5,138 @@
5
5
  * the loader accepts a standalone install of the same package side by side;
6
6
  * without this guard the second instance would still re-register the same
7
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).
8
+ * and fail the boot. mountOnce makes a mount of an already-mounted package a
9
+ * no-op for as long as the first instance lives (the browser half is already
10
+ * deduped by package name in the client module host).
11
+ *
12
+ * A no-op is only safe while the holder is ALIVE. The holder can be disposed
13
+ * long after the refused mount ran its course: the Host reloads a profile by
14
+ * creating the new loader entries before the old ones are torn down (a
15
+ * plugin-manager enable/disable/install write, a settings-driven row reload,
16
+ * HMR), so the new aggregate shell entry mounts its family plugin while the
17
+ * previous entry still owns the name. Dropping that refused mount lost the
18
+ * plugin for good - the previous entry then disposed its own mount, releasing
19
+ * the name with nobody left to take it, and the family row stayed listed as
20
+ * active while its host routes 404ed (the task-board panel showed
21
+ * "board.hostError.notMounted", no degraded record appeared, and only a Host
22
+ * restart recovered it).
23
+ *
24
+ * The refused mount is therefore QUEUED, not dropped, and replayed the moment
25
+ * the holder releases the name - if the waiting fiber is still alive then. The
26
+ * single-instance guarantee is unchanged: exactly one mount is live per
27
+ * package name, and the replay re-enters the guard so a later mount still
28
+ * dedupes against it.
11
29
  *
12
30
  * 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
31
+ * package (npm copy vs repository link) still share one verdict. That symbol
32
+ * is a CROSS-REPOSITORY contract, not this file's private state: the four
33
+ * satellite packages (dsh-skins / dsh-pet / dsh-presets /
34
+ * dsh-community-plugins) are separate repositories carrying their own copy of
35
+ * this guard, rebuilt on their own schedule, so the value under `MOUNTED`
36
+ * must keep the shape every published copy reads (a `Set` of package names
37
+ * with `has`/`add`/`delete`). The wait queues this guard added therefore live
38
+ * under their own additive key, and the registry reads back a `Set` even when
39
+ * some other build left a different value there. Changing `MOUNTED`'s shape
40
+ * in place broke that contract once: a satellite's legacy copy created a
41
+ * `Set`, the family's new copy read it as a `Map`, and every family row
42
+ * mounted after it failed with "claims.get is not a function".
43
+ *
44
+ * cordis `ctx.effect` runs its callback immediately and treats the callback's
15
45
  * return value as the fiber disposer, so the unmarker is returned, not run.
16
46
  */
17
47
 
48
+ /** Published cross-repository contract: package names currently mounted. */
18
49
  const MOUNTED = Symbol.for('dsh-web.mounted-plugins')
19
50
 
51
+ /** Additive key this guard owns: refused mounts waiting for the name. */
52
+ const WAITERS = Symbol.for('dsh-web.mounted-plugins.waiters')
53
+
54
+ /** The slice of a cordis context this guard touches. */
55
+ interface MountContext {
56
+ effect?: (effect: () => unknown) => unknown
57
+ }
58
+
59
+ /** One mount that was refused while another fiber owned the package name. */
60
+ interface PendingMount {
61
+ /** Replay the refused mount; a no-op once its own fiber has been disposed. */
62
+ run(): void
63
+ }
64
+
20
65
  interface MountRegistry {
21
- [MOUNTED]?: Set<string>
66
+ [MOUNTED]?: unknown
67
+ [WAITERS]?: Map<string, PendingMount[]>
22
68
  }
23
69
 
70
+ /**
71
+ * The shared name registry, always a `Set` whatever another build stored here:
72
+ * a foreign value (an interim shape, a hand-written global) must not take every
73
+ * family plugin down with it.
74
+ * @returns the process-wide set of mounted package names.
75
+ */
24
76
  function mountedSet(): Set<string> {
25
77
  const registry = globalThis as MountRegistry
26
- return (registry[MOUNTED] ??= new Set())
78
+ const existing = registry[MOUNTED]
79
+ if (existing instanceof Set) return existing as Set<string>
80
+ const created = new Set<string>()
81
+ registry[MOUNTED] = created
82
+ return created
83
+ }
84
+
85
+ /** Queue per package name for mounts refused while a holder was alive. */
86
+ function mountWaiters(): Map<string, PendingMount[]> {
87
+ const registry = globalThis as MountRegistry
88
+ return (registry[WAITERS] ??= new Map())
27
89
  }
28
90
 
29
91
  /**
30
92
  * 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.
93
+ * The first mount registers normally and releases the name when its fiber
94
+ * disposes; a mount refused while that name is held waits for the release and
95
+ * then runs, unless its own fiber disposes first.
33
96
  * @param packageName - npm package identity shared by every install source.
34
97
  * @param fn - the original plugin apply.
35
98
  * @returns an apply of the same shape.
36
99
  */
37
100
  export function mountOnce<T extends (...args: any[]) => unknown>(packageName: string, fn: T): T {
38
- return ((...args: unknown[]) => {
101
+ const mount = (...args: unknown[]): unknown => {
39
102
  const mounted = mountedSet()
40
- if (mounted.has(packageName)) return
103
+ const ctx = args[0] as MountContext | undefined
104
+ if (mounted.has(packageName)) {
105
+ // Another fiber (the aggregate row, a standalone install, or a copy built
106
+ // from an older revision of this guard) owns the name. Queue instead of
107
+ // dropping: dropping lost the plugin for the rest of the process when the
108
+ // holder was disposed by a reload.
109
+ const waiters = mountWaiters()
110
+ const queue = waiters.get(packageName) ?? []
111
+ let alive = true
112
+ const pending: PendingMount = {
113
+ run: () => {
114
+ if (alive) mount(...args)
115
+ },
116
+ }
117
+ // A fiber that dies while it waits must not be replayed afterwards: its
118
+ // context is disposed and registering effects on it would throw.
119
+ ctx?.effect?.(() => () => {
120
+ alive = false
121
+ const index = queue.indexOf(pending)
122
+ if (index >= 0) queue.splice(index, 1)
123
+ })
124
+ queue.push(pending)
125
+ waiters.set(packageName, queue)
126
+ return
127
+ }
41
128
  mounted.add(packageName)
42
- const ctx = args[0] as { effect?: (effect: () => unknown) => unknown } | undefined
43
129
  ctx?.effect?.(() => () => {
44
130
  mounted.delete(packageName)
131
+ const waiters = mountWaiters()
132
+ const queue = waiters.get(packageName)
133
+ if (queue === undefined) return
134
+ waiters.delete(packageName)
135
+ // Defer the handover one microtask so the disposing mount's own effects
136
+ // (routes, ledger, timers) are torn down before the next one registers.
137
+ for (const waiter of queue.splice(0)) queueMicrotask(() => { waiter.run() })
45
138
  })
46
139
  return fn(...args)
47
- }) as T
140
+ }
141
+ return mount as T
48
142
  }
@@ -55,6 +55,13 @@ export function countMarkers(text) {
55
55
  * reasoning text: only the first session/header event, one-line header
56
56
  * summaries, per-step counters/first lines, marker totals, and the first
57
57
  * reasoning line plus its classification are kept.
58
+ *
59
+ * The durable session log does not always carry reasoning TEXT: a provider can
60
+ * persist a signed reasoning block with its signature and an empty string, and
61
+ * whether it does varies by provider and by response. A report therefore states
62
+ * which of the two it measured (`reasoningText`: `present`, `absent`, or
63
+ * `none` for a session with no reasoning block) instead of showing a counter of
64
+ * zero that reads like a measured zero.
58
65
  */
59
66
  function createSessionAccumulator() {
60
67
  return {
@@ -71,6 +78,7 @@ function createSessionAccumulator() {
71
78
  steps: new Map(),
72
79
  current: null,
73
80
  reasoningBlocks: 0,
81
+ reasoningTextBlocks: 0,
74
82
  markers: zeroMarkers(),
75
83
  hasFirstReasoning: false,
76
84
  firstReasoningLine: null,
@@ -121,6 +129,7 @@ function accumulateSessionEvent(acc, event) {
121
129
  const text = String(block.text ?? '')
122
130
  const markers = countMarkers(text)
123
131
  acc.reasoningBlocks += 1
132
+ if (text.trim().length > 0) acc.reasoningTextBlocks += 1
124
133
  for (const key of markerKeys()) acc.markers[key] += markers[key]
125
134
  if (!acc.hasFirstReasoning) {
126
135
  acc.hasFirstReasoning = true
@@ -178,6 +187,11 @@ function finalizeSessionReport(acc, droppedLines) {
178
187
  },
179
188
  headers: acc.headers,
180
189
  reasoningBlocks: acc.reasoningBlocks,
190
+ // `absent` means the provider persisted signed blocks without their text, so
191
+ // every marker below is a floor of zero rather than a measured zero.
192
+ reasoningText: acc.reasoningBlocks === 0
193
+ ? 'none'
194
+ : acc.reasoningTextBlocks > 0 ? 'present' : 'absent',
181
195
  markers,
182
196
  ratio: totalMarkers === 0 ? null : markers.we / totalMarkers,
183
197
  firstReasoningLine: acc.firstReasoningLine,
@@ -250,6 +264,11 @@ export function renderSessionReport(report) {
250
264
  }
251
265
  lines.push(` reasoning blocks=${report.reasoningBlocks} we=${report.markers.we} let_me=${report.markers.letMe} let's=${report.markers.lets} I=${report.markers.i}`)
252
266
  lines.push(` we/(we+let_me)=${report.ratio === null ? 'n/a' : report.ratio.toFixed(2)} visible replies=${report.visibleReplies}`)
267
+ if (report.reasoningText === 'absent') {
268
+ lines.push(' reasoning text: absent - the log persisted signed reasoning blocks without their text, so every marker above counts zero because there was nothing to count')
269
+ } else if (report.reasoningText === 'none') {
270
+ lines.push(' reasoning text: none - this session produced no reasoning block')
271
+ }
253
272
  if (report.firstReasoningLine !== null) {
254
273
  lines.push(` first reasoning: ${report.firstReasoningLine}`)
255
274
  lines.push(` first block label: ${report.firstClassification?.label ?? 'n/a'} (score ${report.firstClassification?.score ?? '-'})`)