@linxin666/dsh-liangshen 0.4.18 → 0.4.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.
@@ -33,6 +33,11 @@
33
33
  * process-memory state. At most a few namespaces stay active; the LRU
34
34
  * eviction falls out of the same replay.
35
35
  *
36
+ * `idleReclaimSteps` (default 0 = off) adds deferred idle reclaim: a namespace
37
+ * idle for N steps expires, but the replay applies the expiry only at the next
38
+ * activation touch or a `compaction/end` boundary — moments the prompt prefix
39
+ * changes anyway — so reclaim adds no prefix-cache rebuild (issue #2066).
40
+ *
36
41
  * Paging is enforced in ONE place: a per-scope registry restriction
37
42
  * (agent.ctx.tools.restrict) that removes the paged names from every scoped
38
43
  * reader, the request's own wire included.
@@ -87,15 +92,20 @@
87
92
  */
88
93
 
89
94
  import {
95
+ DEFAULT_IDLE_RECLAIM_STEPS,
90
96
  DEFAULT_MAX_ACTIVE_NAMESPACES,
91
- inactiveNamespaces,
97
+ TOOL_ACTIVATE_NAME,
92
98
  integerAtLeast,
99
+ latestVisiblePluginMessage,
93
100
  namespaceOf,
101
+ partitionWireTools,
102
+ reconcileStepMessage,
94
103
  replayActivations,
104
+ sessionEvents,
95
105
  summarizeInactive,
96
106
  validatePagedToolPatterns,
97
- withheldToolNames,
98
107
  } from './paging.mjs'
108
+ import { publishWirePresentation } from './wire-presentation.mjs'
99
109
 
100
110
  /** Cordis plugin name used by loader diagnostics. */
101
111
  export const name = 'liangshen-tool-catalog'
@@ -122,7 +132,8 @@ const pagedSurfaceBySession = new WeakMap()
122
132
  /**
123
133
  * Publish (or, with `undefined`, retract) one scope's paged namespaces.
124
134
  * @param agent - agent scope the partition belongs to.
125
- * @param surface - namespace-keyed namespaces, as `inactiveNamespaces` returns.
135
+ * @param surface - namespace-keyed namespaces, as one pre-activation partition
136
+ * (`partitionWireTools` with an empty active set) reports them.
126
137
  */
127
138
  function publishPagedSurface(agent, surface) {
128
139
  if (agent === undefined || agent === null) return
@@ -198,6 +209,18 @@ export const DEFAULT_PRESENTATION = 'ptc'
198
209
  */
199
210
  export const DEFAULT_MAX_RESIDENT_TOKENS = 8000
200
211
 
212
+ /**
213
+ * The serialized character count one schema contributes, or 0 when it cannot be
214
+ * serialized at all (a hostile or circular definition).
215
+ */
216
+ function schemaCharacters(schema) {
217
+ try {
218
+ return JSON.stringify(schema)?.length ?? 0
219
+ } catch {
220
+ return 0
221
+ }
222
+ }
223
+
201
224
  /**
202
225
  * Rough token estimate for one tool surface: the serialized schema is the
203
226
  * payload the request actually carries, and four characters per token is the
@@ -210,15 +233,40 @@ export function estimateSurfaceTokens(schemas) {
210
233
  let characters = 0
211
234
  for (const schema of Array.isArray(schemas) ? schemas : []) {
212
235
  if (schema === null || schema === undefined) continue
213
- try {
214
- characters += JSON.stringify(schema)?.length ?? 0
215
- } catch {
216
- // A hostile or circular schema contributes nothing rather than throwing.
217
- }
236
+ characters += schemaCharacters(schema)
218
237
  }
219
238
  return Math.ceil(characters / 4)
220
239
  }
221
240
 
241
+ /**
242
+ * One pass over one tool surface: its estimated token cost AND its heaviest
243
+ * tools, so the budget diagnostic never serializes the surface twice.
244
+ *
245
+ * The named tools are the ones a remedy should look at, and their order is a
246
+ * stable descending sort by their own estimate: the insertion below keeps the
247
+ * log order of equally heavy tools, exactly like sorting the whole list would.
248
+ * @param schemas - the tool schemas on the wire.
249
+ * @param count - how many heavy tools to name.
250
+ * @returns the estimated tokens plus the heaviest tools, heaviest first.
251
+ */
252
+ function measureSurface(schemas, count = 3) {
253
+ let characters = 0
254
+ const heaviest = []
255
+ for (const schema of Array.isArray(schemas) ? schemas : []) {
256
+ if (schema === null || schema === undefined) continue
257
+ const own = schemaCharacters(schema)
258
+ characters += own
259
+ const tokens = Math.ceil(own / 4)
260
+ const entry = { name: typeof schema?.name === 'string' ? schema.name : '(unnamed)', tokens }
261
+ let index = 0
262
+ while (index < heaviest.length && heaviest[index].tokens >= tokens) index += 1
263
+ if (index >= count) continue
264
+ heaviest.splice(index, 0, entry)
265
+ if (heaviest.length > count) heaviest.length = count
266
+ }
267
+ return { tokens: Math.ceil(characters / 4), heaviest }
268
+ }
269
+
222
270
  /**
223
271
  * Nesting depth beyond which an inline signature degrades to JsonValue. The
224
272
  * rendering stays one line per tool, so deeply nested argument objects are
@@ -359,9 +407,10 @@ export const CURATED_TOOL_SUMMARIES = new Map([
359
407
  ['subagent', 'Delegate a self-contained task to a subagent that works in its own context and returns its result, not its steps (`description`, `prompt`, optional `provider` / `model` / `reasoning_effort`).'],
360
408
  ['subagent_fork', 'Delegate a task to a subagent seeded with this conversation (`description`, `prompt`); it inherits the parent route, so route fields are not accepted.'],
361
409
  ['list_subagent_models', 'Discover the subagent routes this session authorizes (`provider`, optional `model`); the returned ids feed the delegation tools.'],
362
- ['send_message', 'Send a message to a subagent started from this session (`agent_id`, `message`); the call confirms delivery, not the answer.'],
363
- ['list_agents', 'List the subagents started from this session with their ids, labels, and status (`scope`).'],
364
- ['interrupt_agent', 'Ask a subagent to stop its current work (`agent_id`); the call returns without waiting for it to settle.'],
410
+ ['send_message', 'Send a message to an agent in the subagent tree (`agent`, `message`); a working agent receives it at its next step, an idle one starts a new turn.'],
411
+ ['list_agents', 'List the entire subagent tree, the caller included, as rows of name, status and description; it takes no arguments.'],
412
+ ['wait_agent', 'Wait for input at the next step: agent messages, completion notifications and user steering (`timeout_ms`, 10000 to 3600000, default 30000).'],
413
+ ['interrupt_agent', 'Ask a subagent to stop its current work (`agent`); the call returns without waiting for it to settle.'],
365
414
  ['ask_user_question', 'Ask the user a concise question and wait for the answer (`questions`: id, question, optional header, options, and custom input).'],
366
415
  ['web_search', 'Search the web for current information (one to four `queries`); returns a merged summary and its source URLs.'],
367
416
  ['skill', 'Load the full instructions of one session skill (`name`); call it before acting on a task that names or matches a skill.'],
@@ -566,23 +615,19 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
566
615
  ].join('\n')
567
616
  }
568
617
 
569
- /** Build the durable catalog message for one entry list. */
570
- export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
618
+ /** Build the durable catalog message for one already-rendered text. */
619
+ function catalogMessageFor(text) {
571
620
  return {
572
621
  id: globalThis.crypto.randomUUID(),
573
622
  role: 'user',
574
- content: [{ type: 'text', text: renderCatalogText(entries, presentation, inactive) }],
623
+ content: [{ type: 'text', text }],
575
624
  source: { kind: name },
576
625
  }
577
626
  }
578
627
 
579
- /** The text one message contributes, joined across its text blocks. */
580
- function textOf(message) {
581
- const blocks = Array.isArray(message?.content) ? message.content : []
582
- return blocks
583
- .filter(block => block?.type === 'text' && typeof block.text === 'string')
584
- .map(block => block.text)
585
- .join('\n')
628
+ /** Build the durable catalog message for one entry list. */
629
+ export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
630
+ return catalogMessageFor(renderCatalogText(entries, presentation, inactive))
586
631
  }
587
632
 
588
633
  /** Whether one message is this plugin's catalog. */
@@ -592,50 +637,16 @@ function isCatalogMessage(message) {
592
637
  }
593
638
 
594
639
  /**
595
- * Session events, tolerating both snapshotEvents() and events array.
596
- */
597
- function sessionEvents(session) {
598
- if (Array.isArray(session?.events)) return session.events
599
- if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
600
- return []
601
- }
602
-
603
- /** Visible surface positions, or undefined when the session exposes none. */
604
- function visibleSeqSet(session) {
605
- const nodes = session?.surface?.nodes
606
- return Array.isArray(nodes) ? new Set(nodes) : undefined
607
- }
608
-
609
- /**
610
- * Published catalog state read back from durable log.
640
+ * The catalog text for one assembly state, rendered once per state object.
641
+ *
642
+ * The state object is replaced by every assembly, so this memo only ever answers
643
+ * for one assembly: repeated pre-step reads against an unchanged surface re-render
644
+ * nothing, and a new assembly memoizes afresh. The text is appended here so the
645
+ * publish path builds its message from the same rendering.
611
646
  */
612
- function catalogHistory(agent) {
613
- const session = agent?.session
614
- const events = sessionEvents(session)
615
- const visible = visibleSeqSet(session)
616
- let published = false
617
- for (let index = events.length - 1; index >= 0; index -= 1) {
618
- const event = events[index]
619
- if (event?.type !== 'user/message' || !isCatalogMessage(event.data)) continue
620
- published = true
621
- if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
622
- return { published, text: textOf(event.data) }
623
- }
624
- }
625
- return { published }
626
- }
627
-
628
- /** This plugin's catalog message inside one step's admitted batch, if any. */
629
- function catalogMessage(messages) {
630
- for (const message of messages) {
631
- if (isCatalogMessage(message)) return { message, text: textOf(message) }
632
- }
633
- return undefined
634
- }
635
-
636
- /** Drop one message from a step's admitted batch. */
637
- function withoutMessage(decision, id) {
638
- return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
647
+ function stateCatalogText(state) {
648
+ if (typeof state.text !== 'string') state.text = renderCatalogText(state.entries, state.presentation, state.inactive)
649
+ return state.text
639
650
  }
640
651
 
641
652
  /** Register the registry paging and the per-step catalog injection. */
@@ -662,6 +673,13 @@ export function apply(ctx, config) {
662
673
  1,
663
674
  DEFAULT_MAX_RESIDENT_TOKENS,
664
675
  )
676
+ const idleReclaimSteps = integerAtLeast(
677
+ name,
678
+ config?.idleReclaimSteps,
679
+ 'idleReclaimSteps',
680
+ 0,
681
+ DEFAULT_IDLE_RECLAIM_STEPS,
682
+ )
665
683
 
666
684
  // One-time warnings, per concern so each retired/legacy key reports itself.
667
685
  const warned = new Set()
@@ -681,7 +699,9 @@ export function apply(ctx, config) {
681
699
  }
682
700
  const presentation = resolvePresentation(config, detail => warnOnce(`presentation:${detail}`, detail))
683
701
 
684
- // Per-agent fresh state evaluated on every assembly (never stale across steps/turns)
702
+ // Per-agent fresh state evaluated on every assembly (never stale across
703
+ // steps/turns). The catalog text is memoized on the state object itself, so the
704
+ // pre-step reads of one assembly render it once instead of once per read.
685
705
  const agentCatalogState = new WeakMap()
686
706
 
687
707
  // Session to agent mapping for lifecycle events
@@ -744,13 +764,33 @@ export function apply(ctx, config) {
744
764
  // assembly-path emergency that warning describes.
745
765
  const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
746
766
  if (fullSurface.length === 0) return undefined
767
+ // ONE partition of the full surface, with the empty active set: it is both
768
+ // the publication the activation tool reads back (every paged namespace,
769
+ // active or not) and the basis the withhold list and the catalog summary are
770
+ // derived from, so the two halves of paging cannot disagree about which
771
+ // tools a namespace carries.
772
+ const allPaged = partitionWireTools(fullSurface, pagedToolPatterns, [])
747
773
  // Publish before the withhold decision: with every namespace already active
748
774
  // there is nothing to restrict, and the activation tool must still know the
749
775
  // namespace exists to report it as active instead of unknown.
750
- publishPagedSurface(agent, inactiveNamespaces(fullSurface, pagedToolPatterns, []))
751
- const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active
752
- const withheld = withheldToolNames(fullSurface, pagedToolPatterns, active)
776
+ publishPagedSurface(agent, allPaged.inactive)
777
+ const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns, undefined, idleReclaimSteps).active
778
+ const activeNames = new Set(active)
779
+ const withheld = []
780
+ const inactive = new Map()
781
+ for (const [namespace, group] of allPaged.inactive) {
782
+ if (activeNames.has(namespace)) continue
783
+ inactive.set(namespace, group)
784
+ for (const tool of group) {
785
+ if (typeof tool?.name !== 'string' || tool.name === '') continue
786
+ // The reserved transport cannot be named by a restriction, so paging
787
+ // must never be the reason a session loses it.
788
+ if (tool.name === 'run_code') continue
789
+ withheld.push(tool.name)
790
+ }
791
+ }
753
792
  if (withheld.length === 0) return undefined
793
+ withheld.sort()
754
794
 
755
795
  try {
756
796
  const dispose = tools.restrict({ deny: withheld })
@@ -758,7 +798,7 @@ export function apply(ctx, config) {
758
798
  warnOnce('paging-runtime', 'the tool registry did not confirm the paging restriction — the paged namespaces stay reachable through a program in this session')
759
799
  return undefined
760
800
  }
761
- const state = { active, inactive: inactiveNamespaces(fullSurface, pagedToolPatterns, active), dispose }
801
+ const state = { active, inactive, dispose }
762
802
  agentPaging.set(agent, state)
763
803
  return state
764
804
  } catch (err) {
@@ -896,6 +936,24 @@ export function apply(ctx, config) {
896
936
  clearScopePaging(agent)
897
937
  })
898
938
 
939
+ /**
940
+ * Whether one completed call can move the active set at all.
941
+ *
942
+ * The paging replay reads exactly two shapes: an activation, and a call into a
943
+ * family that is ALREADY active (which only refreshes its recency). A call
944
+ * into a resident host builtin — the shell, the filesystem tools, the catalog's
945
+ * own readers — is neither, and a paged family that is still paged out cannot
946
+ * be reached at all, so a paged scope skips the resync for it and keeps the page
947
+ * it already installed. Deliberately conservative: a scope with no live
948
+ * restriction, a call that names no tool, and the transport itself keep the old
949
+ * path.
950
+ */
951
+ const mayMovePaging = (agent, toolName) => !agentPaging.has(agent)
952
+ || typeof toolName !== 'string'
953
+ || toolName === TOOL_ACTIVATE_NAME
954
+ || toolName === 'run_code'
955
+ || namespaceOf(toolName, pagedToolPatterns) !== undefined
956
+
899
957
  /**
900
958
  * Re-sync after a call that can move the active set.
901
959
  *
@@ -907,7 +965,8 @@ export function apply(ctx, config) {
907
965
  * serializes independent read-only calls.
908
966
  */
909
967
  ctx.on('tools/post-execute', (exec, _result, next) => {
910
- syncBeforeAssembly(exec?.agent)
968
+ const agent = exec?.agent
969
+ if (mayMovePaging(agent, exec?.name)) syncBeforeAssembly(agent)
911
970
  return next()
912
971
  }, { prepend: true })
913
972
 
@@ -923,6 +982,12 @@ export function apply(ctx, config) {
923
982
  agentBySession.set(agent.session, agent)
924
983
  }
925
984
 
985
+ // The presentation is knowable before the rest of the waterfall runs. Publish
986
+ // it now so minimal-prompt reads THIS request's transport after its own next()
987
+ // regardless of which prepended listener wraps the other.
988
+ const effectivePresentation = collapsedTransport() ? 'ptc' : 'native'
989
+ publishWirePresentation(agent, effectivePresentation)
990
+
926
991
  // Page the scope before the providers are collected; a scope the lifecycle
927
992
  // hooks already paged re-derives the same state, so this is idempotent.
928
993
  syncBeforeAssembly(agent)
@@ -944,7 +1009,6 @@ export function apply(ctx, config) {
944
1009
  // under both, so the configured mode plus a mounted runtime is the answer -
945
1010
  // and a mode whose runtime is missing keeps the native wording, because
946
1011
  // that is the wire an executor-less deployment renders.
947
- const effectivePresentation = collapsedTransport() ? 'ptc' : 'native'
948
1012
 
949
1013
  // An unreadable projection is NOT an empty one. Keep the catalog this scope
950
1014
  // last published instead of rewriting it: recording "this session has no
@@ -955,24 +1019,25 @@ export function apply(ctx, config) {
955
1019
  if (surface === undefined) {
956
1020
  const previous = agentCatalogState.get(agent)
957
1021
  if (previous !== undefined && previous.presentation !== effectivePresentation) {
958
- agentCatalogState.set(agent, { ...previous, presentation: effectivePresentation })
1022
+ // A fresh state object on purpose: the memoized text belongs to the
1023
+ // presentation it was rendered for, so it must not travel along.
1024
+ agentCatalogState.set(agent, {
1025
+ entries: previous.entries,
1026
+ presentation: effectivePresentation,
1027
+ inactive: previous.inactive,
1028
+ })
959
1029
  }
960
1030
  return assembled
961
1031
  }
962
1032
 
963
- // Diagnostic guard on the always-on-wire surface. It warns rather than
1033
+ // Diagnostic guard on the always-on-wire surface: ONE pass yields both the
1034
+ // total and the heaviest tools the remedy should name. It warns rather than
964
1035
  // truncates: silently dropping a tool the session needs would trade a
965
1036
  // measurable context cost for an unmeasurable capability loss.
966
- const residentTokens = estimateSurfaceTokens(surface)
1037
+ const { tokens: residentTokens, heaviest } = measureSurface(surface)
967
1038
  if (residentTokens > maxResidentTokens) {
968
- // Name the heaviest tools so the remedy is actionable rather than a bare number.
969
- const heaviest = [...surface]
970
- .map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
971
- .sort((left, right) => right.tokens - left.tokens)
972
- .slice(0, 3)
973
- .map(entry => `${entry.name} (${entry.tokens})`)
974
- .join(', ')
975
- warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${surface.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${heaviest} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
1039
+ const named = heaviest.map(entry => `${entry.name} (${entry.tokens})`).join(', ')
1040
+ warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${surface.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${named} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
976
1041
  }
977
1042
 
978
1043
  // The page the registry enforces IS this request's page: the restriction was
@@ -1000,24 +1065,20 @@ export function apply(ctx, config) {
1000
1065
  const state = agent === undefined ? undefined : agentCatalogState.get(agent)
1001
1066
  if (state === undefined) return decision
1002
1067
 
1003
- const { entries, presentation: statePresentation, inactive } = state
1004
- const candidate = renderCatalogText(entries, statePresentation, inactive)
1005
- const history = catalogHistory(agent)
1006
- const existing = catalogMessage(decision.messages)
1007
- if (history.text === candidate) {
1008
- return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
1009
- }
1010
- if (existing !== undefined && existing.text === candidate) return decision
1011
- if (!history.published && entries.length === 0 && inactive.length === 0) {
1012
- return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
1013
- }
1014
- const catalog = createCatalogMessage(entries, statePresentation, inactive)
1015
- if (existing === undefined) {
1016
- return { ...decision, messages: [...decision.messages, catalog] }
1017
- }
1018
- return {
1019
- ...decision,
1020
- messages: decision.messages.map(message => (message.id === existing.message.id ? catalog : message)),
1021
- }
1068
+ const candidate = stateCatalogText(state)
1069
+ const history = latestVisiblePluginMessage(agent, isCatalogMessage)
1070
+ // A surface that is empty AND was never published has nothing to announce:
1071
+ // publishing "no tools" for it is what made a seeded child session deny the
1072
+ // tools its own request carries (issue #2016). A surface that replaced a
1073
+ // published one does announce it, which is why the published flag is part of
1074
+ // the condition.
1075
+ const silent = !history.published && state.entries.length === 0 && state.inactive.length === 0
1076
+ return reconcileStepMessage(
1077
+ decision,
1078
+ history,
1079
+ candidate,
1080
+ () => (silent ? undefined : catalogMessageFor(candidate)),
1081
+ isCatalogMessage,
1082
+ )
1022
1083
  }, { prepend: true })
1023
1084
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Per-session wire presentation shared by the sibling tool-catalog and
3
+ * minimal-prompt rows. The Host's assembly waterfall carries sections only;
4
+ * tool-catalog owns the configured mode plus runtime probe and publishes it
5
+ * before calling the next assembly listener.
6
+ */
7
+
8
+ const presentationByAgent = new WeakMap()
9
+ const presentationBySession = new WeakMap()
10
+
11
+ /** Publish or retract the effective native/ptc transport for one agent scope. */
12
+ export function publishWirePresentation(agent, presentation) {
13
+ if (agent === undefined || agent === null || (typeof agent !== 'object' && typeof agent !== 'function')) return
14
+ const session = agent.session
15
+ const sessionKey = session !== null && (typeof session === 'object' || typeof session === 'function') ? session : undefined
16
+ if (presentation === undefined) {
17
+ presentationByAgent.delete(agent)
18
+ if (sessionKey !== undefined) presentationBySession.delete(sessionKey)
19
+ return
20
+ }
21
+ presentationByAgent.set(agent, presentation)
22
+ if (sessionKey !== undefined) presentationBySession.set(sessionKey, presentation)
23
+ }
24
+
25
+ /** Read the transport published for this scope, or undefined when unavailable. */
26
+ export function wirePresentationFor(agent) {
27
+ if (agent === undefined || agent === null || (typeof agent !== 'object' && typeof agent !== 'function')) return undefined
28
+ const direct = presentationByAgent.get(agent)
29
+ if (direct !== undefined) return direct
30
+ const session = agent.session
31
+ if (session === null || (typeof session !== 'object' && typeof session !== 'function')) return undefined
32
+ return presentationBySession.get(session)
33
+ }