@linxin666/dsh-liangshen 0.4.14 → 0.4.16

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.
@@ -1,22 +1,25 @@
1
1
  /**
2
- * tool-catalog — the model-visible tool surface for LiangShen mode: one
3
- * presentation declaration per session, gentle tool paging for high-fan-out
2
+ * tool-catalog — the model-visible tool surface for LiangShen mode: the
3
+ * presentation this composition renders, gentle tool paging for high-fan-out
4
4
  * namespaces, and the durable catalog message.
5
5
  *
6
- * PRESENTATION: the `presentation` config picks how this session's tools sit
7
- * on the wire, matching the SDK's ToolPresentationMode:
8
- * - `native`: the assembled native roster, no code transport;
6
+ * PRESENTATION: the `presentation` config names the transport the session
7
+ * carries, matching the SDK's tool presentation modes:
8
+ * - `native`: the native roster, no code transport;
9
9
  * - `ptc` (default): the wire collapses to the single `run_code` transport
10
10
  * and every other tool is reached from inside the program through the
11
11
  * generated SDK.
12
12
  *
13
- * The declaration happens once per agent scope (agent.ctx.tools.presentAs) as
14
- * early as the scope exists — there is no turn-boundary staging: the retired
15
- * anchor-turn mechanism is gone, and the legacy `anchorTools` key is accepted
16
- * but ignored with a one-time warning. The legacy boolean `ptcPresentation`
17
- * maps onto the enum (true -> 'ptc', false -> 'native') with a one-time
18
- * deprecation warning. A missing code runtime or a declined declaration keeps
19
- * the native surface with a one-time warning.
13
+ * The preset composition is what actually selects it: `src/composition.ts`
14
+ * enables or disables the `tool-executor-ptc` row from the same setting, and
15
+ * that row is what installs the executor whose `describe()` decides the wire
16
+ * (0.2.2 retired `ctx.tools.presentAs`, the old per-scope declaration, so this
17
+ * plugin no longer declares anything). A deployment with no code runtime keeps
18
+ * the native surface, and the catalog says so. There is no turn-boundary
19
+ * staging: the retired anchor-turn mechanism is gone, and the legacy
20
+ * `anchorTools` key is accepted but ignored with a one-time warning. The legacy
21
+ * boolean `ptcPresentation` maps onto the enum (true -> 'ptc', false ->
22
+ * 'native') with a one-time deprecation warning.
20
23
  *
21
24
  * TOOL PAGING: tools whose names match `pagedToolPatterns` (default
22
25
  * `['mcp__*']`) stay off the wire until their namespace is activated through
@@ -26,25 +29,27 @@
26
29
  * process-memory state. At most a few namespaces stay active; the LRU
27
30
  * eviction falls out of the same replay.
28
31
  *
29
- * Paging is enforced in TWO places, because the wire is not the only surface a
30
- * tool can be reached through:
31
- * - the wire partition below (resident tools returned, paged tools lifted) and
32
- * - a per-scope registry restriction (agent.ctx.tools.restrict) that removes
33
- * the paged names exactly as the wire does.
34
- * The second one is what makes paging real under the `ptc` presentation,
35
- * where the wire has already collapsed to the single `run_code` transport and
36
- * every other tool is reached from inside a program. Under a collapsed wire
37
- * the visible set is the whole surface: it renders the `tools:sdk` prompt
38
- * section and it is what a program may dispatch to, so filtering the assembled
39
- * `tools` array alone would withhold nothing the model can observe. The
40
- * restriction is derived from the same pattern match as the partition
41
- * (`withheldToolNames`) and is lifted before a new one is applied, so repeated
42
- * collections do not accumulate filters.
32
+ * Paging is enforced in ONE place: a per-scope registry restriction
33
+ * (agent.ctx.tools.restrict) that removes the paged names from every scoped
34
+ * reader, the request's own wire included.
43
35
  *
44
- * WHICH PRESENTATION PAGES WHAT: the registry restriction is installed for
45
- * `ptc` alone, because a collapsed wire is the one presentation where the
46
- * scope's registry IS the whole reachable surface. `native` carries no
47
- * program at all, so the wire partition is the whole of paging there.
36
+ * The wire cannot be filtered by a listener any more. Since 0.2.2 the
37
+ * `system-prompt/assemble` waterfall transforms a `PromptPresentation` that
38
+ * carries no tool array at all: the harness collects the tool providers BEFORE
39
+ * the waterfall runs and merges the authoritative `tools` back AFTER it, so a
40
+ * listener can neither observe nor rewrite what the request carries. The
41
+ * registry is the surface every tool declaration is projected from — the
42
+ * native roster the executor renders and the set a program may dispatch to —
43
+ * so one restriction pages both presentations, and the wire partition that
44
+ * used to page the `native` roster is gone with the array it filtered.
45
+ *
46
+ * READING THE SURFACE: the catalog describes the request's own tool set, read
47
+ * as `tools.schemas(agent, context.toolSet)` while assembling. The assemble
48
+ * context's `toolSet` is the step's admitted selection — the fact a listener
49
+ * cannot recover from the assembly value — and `schemas()` reads through the
50
+ * scope's restriction, so the catalog lists exactly what the wire carries. An
51
+ * unreadable projection is NOT an empty one: the catalog keeps its last
52
+ * published state rather than announcing a session with no tools.
48
53
  *
49
54
  * TIMING: that restriction is installed from OUTSIDE the assembly waterfall.
50
55
  * `SystemPrompt.assemble()` collects the tool providers and calls every
@@ -83,7 +88,6 @@ import {
83
88
  inactiveNamespaces,
84
89
  integerAtLeast,
85
90
  namespaceOf,
86
- partitionWireTools,
87
91
  replayActivations,
88
92
  summarizeInactive,
89
93
  validatePagedToolPatterns,
@@ -115,7 +119,7 @@ const pagedSurfaceBySession = new WeakMap()
115
119
  /**
116
120
  * Publish (or, with `undefined`, retract) one scope's paged namespaces.
117
121
  * @param agent - agent scope the partition belongs to.
118
- * @param surface - namespace-keyed namespaces, as `partitionWireTools` returns.
122
+ * @param surface - namespace-keyed namespaces, as `inactiveNamespaces` returns.
119
123
  */
120
124
  function publishPagedSurface(agent, surface) {
121
125
  if (agent === undefined || agent === null) return
@@ -558,38 +562,6 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
558
562
  ].join('\n')
559
563
  }
560
564
 
561
- /**
562
- * Overlay the registry projection onto each wire entry, keyed by name, so the
563
- * catalog describes complete argument semantics even when the assembly's own
564
- * tool object carries a thinner definition.
565
- *
566
- * A tool the projection NAMES is authoritative for the parameter field,
567
- * including its absence: a projected entry that declares no parameters means
568
- * the tool takes no declared arguments, and the wire's placeholder object
569
- * (`{ type: 'object', properties: {} }`) would otherwise render the misleading
570
- * `Record<string, JsonValue>` signature. A tool the projection does not name
571
- * keeps the wire's own definition, and so does every entry when no projection
572
- * is readable at all.
573
- */
574
- export function mergeProjectedSchemas(wireTools, projection) {
575
- if (!Array.isArray(projection) || projection.length === 0) return wireTools
576
- const byName = new Map()
577
- for (const schema of projection) {
578
- if (typeof schema?.name === 'string' && schema.name !== '') byName.set(schema.name, schema)
579
- }
580
- return wireTools.map((tool) => {
581
- const projected = byName.get(tool?.name)
582
- if (projected === undefined) return tool
583
- const merged = { ...tool }
584
- if (projected.parameters === undefined) delete merged.parameters
585
- else merged.parameters = projected.parameters
586
- if (typeof projected.description === 'string' && projected.description.length > 0) {
587
- merged.description = projected.description
588
- }
589
- return merged
590
- })
591
- }
592
-
593
565
  /** Build the durable catalog message for one entry list. */
594
566
  export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
595
567
  return {
@@ -662,7 +634,7 @@ function withoutMessage(decision, id) {
662
634
  return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
663
635
  }
664
636
 
665
- /** Register the presentation declaration, the wire paging, and the per-step catalog injection. */
637
+ /** Register the registry paging and the per-step catalog injection. */
666
638
  export function apply(ctx, config) {
667
639
  const descriptionMaxLength = integerAtLeast(
668
640
  name,
@@ -711,11 +683,6 @@ export function apply(ctx, config) {
711
683
  // Session to agent mapping for lifecycle events
712
684
  const agentBySession = new WeakMap()
713
685
 
714
- // Presentation declaration tracking per agent scope (one declaration each)
715
- const agentDeclared = new WeakSet()
716
- const agentDeclareFailed = new WeakSet()
717
- const agentDisposers = new WeakMap()
718
-
719
686
  // Registry-level paging state, one entry per agent scope: the names the live
720
687
  // restriction withholds and the exact disposer that lifts it. Keyed by agent
721
688
  // so two sessions assembling at once cannot lift each other's filter, and
@@ -736,15 +703,17 @@ export function apply(ctx, config) {
736
703
 
737
704
  /**
738
705
  * Recompute one agent scope's page from the durable session event stream and
739
- * make the registry match it: `deny` masks exactly the names the wire
740
- * partition would withhold, so the scope still inherits everything else.
706
+ * make the registry match it: `deny` masks exactly the names the paged
707
+ * namespaces carry, so the scope still inherits everything else.
741
708
  * Scoped registrations are exempt by the registry's own rule, so
742
709
  * preset-owned tools can never be filtered away by this.
743
710
  *
744
- * The restriction is what paging MEANS under a collapsed `ptc` wire, where
745
- * filtering the assembled `tools` array changes nothing a program can reach.
746
- * It also stores the namespaces it withheld, so the catalog and the live
747
- * restriction are read from ONE fact instead of two computations.
711
+ * The restriction is what paging MEANS in both presentations now that the
712
+ * waterfall carries no tool array: the registry is the surface every tool
713
+ * declaration is projected from, so the native roster and the program
714
+ * bindings lose the paged names together. It also stores the namespaces it
715
+ * withheld, so the catalog and the live restriction are read from ONE fact
716
+ * instead of two computations.
748
717
  *
749
718
  * Called OUTSIDE the assembly waterfall, deliberately: see
750
719
  * {@link syncBeforeAssembly} for why an in-waterfall sync cannot fix the
@@ -769,7 +738,7 @@ export function apply(ctx, config) {
769
738
  // nothing left to withhold. Silent on an unreadable surface: a sync may
770
739
  // run before the registry is populated, and "no tools yet" is not the
771
740
  // assembly-path emergency that warning describes.
772
- const fullSurface = quietSchemas(agent) ?? []
741
+ const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
773
742
  if (fullSurface.length === 0) return undefined
774
743
  // Publish before the withhold decision: with every namespace already active
775
744
  // there is nothing to restrict, and the activation tool must still know the
@@ -809,23 +778,18 @@ export function apply(ctx, config) {
809
778
  * request's own SDK section still lists it. Syncing before the providers are
810
779
  * collected is what keeps the two consistent from the FIRST `ptc` request.
811
780
  *
812
- * GATED ON THE WIRE ACTUALLY COLLAPSING, not on the configuration asking for
813
- * it. Both halves of that gate matter, and each covers a deployment where
814
- * paging at the registry would be wrong:
815
- * - `presentation === 'ptc'` is what the operator configured, and it is the
816
- * only presentation whose registry is the whole reachable surface;
817
- * - `agentDeclared.has(agent)` is the scope's own declaration actually
818
- * landing, which is NOT the same as `transportReady()`. A deployment with
819
- * no mounted code runtime (and one whose host declines the declaration)
820
- * keeps the native wire: the assembled array carries paging by itself, and
821
- * a registry restriction installed anyway would strip the paged families
822
- * from that request's native wire — the first request would lose tools it
823
- * is supposed to have, and the catalog would announce namespaces as
824
- * withheld that nothing withheld.
781
+ * EVERY SCOPE IS PAGED, in both presentations. Before 0.2.2 the native
782
+ * roster was filtered in the waterfall itself — the listener returned a
783
+ * narrowed `tools` array — so a registry restriction there would have been
784
+ * redundant, and a deployment whose wire never collapsed (no code runtime, a
785
+ * declined declaration) had to keep it off entirely. The harness now merges
786
+ * its own provider-owned `tools` back after the waterfall, so that return
787
+ * value is discarded: the registry is the only place a page can exist, and a
788
+ * scope left unpaged would hand the model every paged family it was supposed
789
+ * to activate first.
825
790
  */
826
791
  const syncBeforeAssembly = (agent) => {
827
- if (agent === undefined || presentation !== 'ptc') return undefined
828
- if (!agentDeclared.has(agent)) return undefined
792
+ if (agent === undefined) return undefined
829
793
  return syncScopePaging(agent)
830
794
  }
831
795
 
@@ -834,65 +798,16 @@ export function apply(ctx, config) {
834
798
  // The 0.1.6 cohort renamed the service face from `codeRuntime` to
835
799
  // `ptcRuntime` (package `@deepseek-ai/dsh-code-runtime` became
836
800
  // `@deepseek-ai/dsh-ptc-runtime`); the old key is gone, so reading it would
837
- // silently disable PTC staging for every session.
838
- const transportReady = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
839
-
840
- /**
841
- * Declare this agent scope's presentation through the public
842
- * agent.ctx.tools.presentAs(mode). One declaration per scope; a refusal is
843
- * permanent for the agent, a wire miss is retryable.
844
- */
845
- const declarePresentation = (agent) => {
846
- if (!transportReady() || agent === undefined) return false
847
- if (agentDeclared.has(agent)) return true
848
- if (agentDeclareFailed.has(agent)) return false
849
-
850
- const tools = agent?.ctx?.tools
851
- if (tools === undefined || typeof tools.presentAs !== 'function') {
852
- // No composition row replaces this declaration: `presentAs` is how a
853
- // preset selects its wire, so a scope that cannot reach it runs the
854
- // native surface no matter what `presentation` says. Report it once
855
- // instead of leaving the operator's setting silently unapplied.
856
- agentDeclareFailed.add(agent)
857
- warnOnce('runtime', 'no scoped tools view to declare the presentation through — keeping the native tool surface')
858
- return false
859
- }
860
-
861
- try {
862
- const disposer = tools.presentAs(presentation)
863
- agentDeclared.add(agent)
864
- if (typeof disposer === 'function') {
865
- agentDisposers.set(agent, disposer)
866
- }
867
- return true
868
- } catch (err) {
869
- agentDeclareFailed.add(agent)
870
- warnOnce('runtime', `the "${presentation}" presentation was declined: ${err instanceof Error ? err.message : String(err)} — keeping the native tool surface`)
871
- return false
872
- }
873
- }
874
-
875
- /**
876
- * Abort/revert the declaration if active, restoring the native presentation.
877
- */
878
- const revertPresentation = (agent, reason, retryable = false) => {
879
- if (agent === undefined) return
880
- const disposer = agentDisposers.get(agent)
881
- if (typeof disposer === 'function') {
882
- try {
883
- disposer()
884
- } catch {
885
- // Ignore disposer error
886
- }
887
- agentDisposers.delete(agent)
888
- }
889
- agentDeclared.delete(agent)
890
- // A declaration the host itself refused is permanent for this agent. One that
891
- // merely failed to reach a wire is not: the next assembly may declare again,
892
- // and latching it would strand the session on the native surface.
893
- if (!retryable) agentDeclareFailed.add(agent)
894
- warnOnce('runtime', `${reason} — keeping the native tool surface`)
895
- }
801
+ // silently disable program presentation for every session.
802
+ //
803
+ // This is the ONE fact that decides what the request carries, because no
804
+ // reader can observe the collapse itself: the petc executor keeps `run_code`
805
+ // outside the registry (`describe()` returns it, `tools.schemas()` never
806
+ // does), so a `schemas()` read returns the same roster under both
807
+ // presentations. The composition enables the `tool-executor-ptc` row from
808
+ // exactly this setting (see `src/composition.ts`), so the configured
809
+ // presentation plus a mounted runtime IS the wire.
810
+ const collapsedTransport = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
896
811
 
897
812
  /**
898
813
  * Read visible tool schemas from the public tools.schemas(agent) API.
@@ -911,71 +826,59 @@ export function apply(ctx, config) {
911
826
  }
912
827
 
913
828
  /**
914
- * Read the scope's model-facing surface without the assembly path's warning.
915
- * Returns undefined when no projection is readable at all.
829
+ * Read the model-facing surface one scope offers this step, without the
830
+ * reserved transport (the catalog never lists run_code as an entry).
831
+ *
832
+ * `toolSet` is the assemble context's step admission: passing it narrows the
833
+ * read to exactly the tools this request may carry, conditionally registered
834
+ * ones excluded. Omitted, the read covers every registered definition, which
835
+ * is what the paging sync needs to compute its page.
836
+ *
837
+ * An EMPTY list and an UNREADABLE registry are different facts, and the
838
+ * return type keeps them apart: `[]` means this scope really offers no tool,
839
+ * `undefined` means nothing could be read (a deployment without the registry,
840
+ * a projection that threw). A caller that treats the second as the first
841
+ * announces "no tools" to a session that has them — the defect issue #2016
842
+ * reports.
843
+ *
844
+ * @param agent - agent scope the surface is read for.
845
+ * @param toolSet - the step's admitted selection, or undefined for every definition.
846
+ * @param options - `quiet` suppresses the diagnostic of an unreadable registry.
847
+ * @returns the visible schemas minus run_code, or undefined when unreadable.
916
848
  */
917
- const quietSchemas = (agent) => {
849
+ const readSurface = (agent, toolSet, options) => {
918
850
  const tools = resolveToolsService(agent)
919
851
  if (tools === undefined) return undefined
920
852
  for (const method of ['schemas', 'sdkSchemas']) {
921
853
  if (typeof tools[method] !== 'function') continue
922
854
  try {
923
- const schemas = tools[method](agent)
855
+ const schemas = tools[method](agent, toolSet)
924
856
  if (Array.isArray(schemas)) return schemas.filter(entry => entry?.name && entry.name !== 'run_code')
925
- } catch {
926
- // Try the next source; an unreadable registry is not fatal here.
927
- }
928
- }
929
- return undefined
930
- }
931
-
932
- const publicSchemas = (agent) => {
933
- const tools = resolveToolsService(agent)
934
- if (tools === undefined) return undefined
935
- if (typeof tools.schemas === 'function') {
936
- try {
937
- const schemas = tools.schemas(agent)
938
- if (Array.isArray(schemas) && schemas.length > 0) {
939
- const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
940
- return filtered.length > 0 ? filtered : undefined
941
- }
942
- return undefined
943
- } catch {
944
- warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
945
- return undefined
946
- }
947
- }
948
- // Test harness compatibility stub
949
- if (typeof tools.sdkSchemas === 'function') {
950
- try {
951
- const schemas = tools.sdkSchemas(agent)
952
- if (Array.isArray(schemas) && schemas.length > 0) {
953
- const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
954
- return filtered.length > 0 ? filtered : undefined
857
+ } catch (err) {
858
+ if (options?.quiet !== true) {
859
+ // Its own key, so an unreadable projection never swallows the
860
+ // declaration warning that explains what replaced it.
861
+ warnOnce('surface', `no tool schemas available (${err instanceof Error ? err.message : String(err)}) — the catalog keeps its last published state`)
955
862
  }
956
- } catch {
957
- warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
958
863
  return undefined
959
864
  }
960
865
  }
961
866
  return undefined
962
867
  }
963
868
 
964
- // Early lifecycle hook: declare the presentation and page the scope as soon
965
- // as it exists.
869
+ // Early lifecycle hook: page the scope as soon as it exists.
966
870
  //
967
871
  // The 0.1.6 cohort folded the former `agent/session-start` into the async
968
872
  // serial `agent/created`, which carries the same payload object and runs
969
873
  // before the first prompt assembly; the host waits for this listener, so the
970
- // declaration is already in place when that assembly reads the presentation.
874
+ // page is already in place when that assembly collects its tool providers.
971
875
  //
972
876
  // The payload is destructured ON PURPOSE: `agent/created` passes its payload
973
877
  // OBJECT as the first argument, not the agent itself. Reading that parameter
974
- // as the agent yields an object with no `session` and no `ctx`, so the
975
- // declaration is skipped and paging silently never engages.
878
+ // as the agent yields an object with no `session` and no `ctx`, so paging
879
+ // would silently never engage.
976
880
  ctx.on('agent/created', ({ agent }) => {
977
881
  if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
978
- if (transportReady()) declarePresentation(agent)
979
882
  // The session log is readable here, and this runs before the first turn
980
883
  // assembles a prompt, so a scope created over an existing (resumed)
981
884
  // session is paged before its FIRST assembly rather than one request late.
@@ -1004,166 +907,86 @@ export function apply(ctx, config) {
1004
907
  return next()
1005
908
  }, { prepend: true })
1006
909
 
1007
- // Per-agent, not one process-wide flag: two sessions assembling at once would
1008
- // otherwise let one skip the re-assembly the other is running.
1009
- const reassembling = new WeakSet()
1010
-
1011
910
  ctx.on('system-prompt/assemble', async (assembly, context, next) => {
1012
911
  const agent = context?.agent
912
+ // The step's admitted selection, and the one fact about this request's tool
913
+ // set a listener can still read: since 0.2.2 the assembly value carries no
914
+ // tool array, and the providers it is built from are collected before this
915
+ // waterfall runs.
916
+ const toolSet = context?.toolSet
1013
917
 
1014
918
  if (agent !== undefined && agent.session !== undefined) {
1015
919
  agentBySession.set(agent.session, agent)
1016
920
  }
1017
921
 
1018
- if (agent !== undefined && !agentDeclared.has(agent) && transportReady()) {
1019
- // Under 'ptc' a declaration collapses the wire to the single `run_code`
1020
- // transport and lists the tools from their SDK projection. Where no
1021
- // projection can be read at all, declaring would collapse the wire and
1022
- // then have to undo it, losing the native surface on the way out. Stay
1023
- // native instead.
1024
- const projectable = publicSchemas(agent)
1025
- if (presentation === 'ptc' && (projectable === undefined || projectable.length === 0)) {
1026
- warnOnce('runtime', 'no tool schema projection available — keeping the native tool surface')
1027
- } else {
1028
- const declaredNow = declarePresentation(agent)
1029
- // A declaration made here cannot reach THIS assembly: the harness collects
1030
- // the tool providers before the waterfall runs. Re-assemble so the
1031
- // presentation lands on the assembly the model actually receives.
1032
- if (declaredNow && !reassembling.has(agent)) {
1033
- const sp = ctx.get('systemPrompt')
1034
- if (typeof sp?.assemble === 'function') {
1035
- reassembling.add(agent)
1036
- try {
1037
- return await sp.assemble(context)
1038
- } catch (error) {
1039
- warnOnce('runtime', `re-assembling after the presentation declaration failed: ${error instanceof Error ? error.message : String(error)}`)
1040
- } finally {
1041
- reassembling.delete(agent)
1042
- }
1043
- }
1044
- // Nothing re-assembled, so this wire stays native. Presenting a transport
1045
- // the request never names would lie to the model, so drop back to native
1046
- // for this assembly and let the next assembly declare again.
1047
- revertPresentation(agent, `the "${presentation}" declaration did not reach this assembly wire`, true)
1048
- }
1049
- }
1050
- }
1051
-
1052
- // A declaration that just landed here (a scope no lifecycle hook could
1053
- // reach) pages the scope before the re-assembly collects its providers, so
1054
- // that request renders a page-consistent SDK section too. Idempotent: a
1055
- // scope already paged by its lifecycle hook re-derives the same state.
1056
- if (agent !== undefined && agentDeclared.has(agent)) syncBeforeAssembly(agent)
922
+ // Page the scope before the providers are collected; a scope the lifecycle
923
+ // hooks already paged re-derives the same state, so this is idempotent.
924
+ syncBeforeAssembly(agent)
1057
925
 
1058
- // Delegate first: the assembled value stays authoritative for the wire (a
1059
- // presentation declared inside this waterfall reaches the NEXT assembly,
1060
- // which is why a declaration is followed by a re-assembly).
926
+ // The waterfall's transformed value travels on untouched: tool declarations
927
+ // are provider-owned, so there is no array here to filter or restore.
1061
928
  const assembled = await next()
1062
929
 
1063
- const assembledTools = Array.isArray(assembled?.tools) ? assembled.tools : undefined
1064
- const wireOnlyRunCode = assembledTools !== undefined && assembledTools.length > 0 && assembledTools.every(t => t?.name === 'run_code')
1065
-
1066
- // The paging restriction was installed OUTSIDE this waterfall (see
1067
- // {@link syncBeforeAssembly}) because `assemble()` renders the sections and
1068
- // collects the providers before the waterfall runs: installing it here
1069
- // would leave the request it runs for with a catalog that claims a
1070
- // namespace is paged and a `tools:sdk` section that still lists it. What
1071
- // this waterfall does with it is read the SAME state the restriction was
1072
- // built from, so the catalog never describes a different page than the one
1073
- // the registry enforces.
1074
- const pagingState = agent === undefined ? undefined : agentPaging.get(agent)
1075
-
1076
- // Under a collapsed `ptc` wire the registry is the ONLY surface a tool can
1077
- // be reached through, so the page is expressed as a registry restriction.
1078
- // The native wire carries paging by itself on the assembled array. A wire
1079
- // that carries the native roster again (a reverted declaration) must also
1080
- // drop a page left over from a collapsed assembly, or the filter would keep
1081
- // hiding tools that wire just handed back.
1082
- let surface = agent !== undefined ? publicSchemas(agent) : undefined
1083
- // The wire partition replays the durable log itself: `pagingState` exists
1084
- // only where a restriction was installed (the collapsed ptc wire), and the
1085
- // native wire still pages the assembled array from the same event stream.
1086
- const activeNamespaces = new Set(
1087
- replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active,
1088
- )
1089
- if (agent !== undefined && !wireOnlyRunCode && pagingState !== undefined) clearScopePaging(agent)
1090
-
1091
- // If the wire carries only run_code but no projection is readable, revert to
1092
- // native and restore the native wire. The replacement travels in the RETURNED
1093
- // assembly: the waterfall's returned value is the authoritative one, and
1094
- // mutating the object the harness handed downstream would be a side effect no
1095
- // other listener can see.
1096
- let correctedWire
1097
- if (wireOnlyRunCode && (surface === undefined || surface.length === 0)) {
1098
- revertPresentation(agent, 'no tool schema projection available under PTC')
1099
- const nativeSchemas = publicSchemas(agent) ?? []
1100
- surface = nativeSchemas
1101
- correctedWire = nativeSchemas
930
+ // The catalog describes THIS request's surface, read from the registry
931
+ // through the step's admission. `schemas()` reads through the scope's
932
+ // restriction, so the result is exactly the list this request carries: the
933
+ // native roster, or - under a collapsed `ptc` wire - the projection every
934
+ // tool is reached through from inside a program (run_code is the transport,
935
+ // never a catalog entry).
936
+ const surface = agent === undefined ? undefined : readSurface(agent, toolSet)
937
+
938
+ // The presentation this request carries is the one the composition mounted.
939
+ // Nothing in the assembly names it and `schemas()` reads the same roster
940
+ // under both, so the configured mode plus a mounted runtime is the answer -
941
+ // and a mode whose runtime is missing keeps the native wording, because
942
+ // that is the wire an executor-less deployment renders.
943
+ const effectivePresentation = collapsedTransport() ? 'ptc' : 'native'
944
+
945
+ // An unreadable projection is NOT an empty one. Keep the catalog this scope
946
+ // last published instead of rewriting it: recording "this session has no
947
+ // tools" over a read that merely failed is what made the model refuse tools
948
+ // the request was carrying (issue #2016). The one fact that still has to
949
+ // follow the request is the transport, so the wording is corrected above.
950
+ if (agent === undefined) return assembled
951
+ if (surface === undefined) {
952
+ const previous = agentCatalogState.get(agent)
953
+ if (previous !== undefined && previous.presentation !== effectivePresentation) {
954
+ agentCatalogState.set(agent, { ...previous, presentation: effectivePresentation })
955
+ }
956
+ return assembled
1102
957
  }
1103
958
 
1104
- const effectiveWire = correctedWire ?? assembledTools
1105
- const effectiveOnlyRunCode = effectiveWire !== undefined && effectiveWire.length > 0 && effectiveWire.every(t => t?.name === 'run_code')
1106
-
1107
- // The catalog describes the transport this request actually carries, never
1108
- // the configuration's intent: a collapsed wire is 'ptc', and anything else
1109
- // is native.
1110
- const effectivePresentation = effectiveOnlyRunCode ? 'ptc' : 'native'
1111
-
1112
- // Gentle paging: the active namespaces were replayed from the durable event
1113
- // stream above; here the paged-but-inactive tools come off the wire itself.
1114
- // run_code and the resident roster never match the paging patterns.
1115
- const { resident, inactive } = partitionWireTools(effectiveWire, pagedToolPatterns, activeNamespaces)
1116
-
1117
959
  // Diagnostic guard on the always-on-wire surface. It warns rather than
1118
960
  // truncates: silently dropping a tool the session needs would trade a
1119
961
  // measurable context cost for an unmeasurable capability loss.
1120
- const residentTokens = estimateSurfaceTokens(resident)
962
+ const residentTokens = estimateSurfaceTokens(surface)
1121
963
  if (residentTokens > maxResidentTokens) {
1122
964
  // Name the heaviest tools so the remedy is actionable rather than a bare number.
1123
- const heaviest = [...resident]
965
+ const heaviest = [...surface]
1124
966
  .map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
1125
967
  .sort((left, right) => right.tokens - left.tokens)
1126
968
  .slice(0, 3)
1127
969
  .map(entry => `${entry.name} (${entry.tokens})`)
1128
970
  .join(', ')
1129
- warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${resident.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${heaviest} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
971
+ 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`)
1130
972
  }
1131
973
 
1132
- // The catalog describes this request's ACTUAL surface: with a live page it
1133
- // summarizes exactly the namespaces that page withholds (the same fact the
1134
- // restriction was built from), and otherwise the namespaces the WIRE
1135
- // partition found.
1136
- const catalogInactive = summarizeInactive(
1137
- pagingState?.inactive ?? inactive,
974
+ // The page the registry enforces IS this request's page: the restriction was
975
+ // installed before the providers were collected (see {@link syncBeforeAssembly}),
976
+ // and the surface above already reads through it. A scope whose page could
977
+ // not be installed withholds nothing, so it advertises nothing.
978
+ const pagingState = agentPaging.get(agent)
979
+ const inactiveSummary = summarizeInactive(
980
+ pagingState?.inactive ?? [],
1138
981
  describe => catalogDescription(describe, descriptionMaxLength),
1139
982
  )
1140
983
 
1141
- let entries
1142
- if (effectivePresentation === 'ptc') {
1143
- // Under the collapsed transport the request opens only run_code, so the
1144
- // catalog lists the SDK-reachable projection instead of the wire.
1145
- entries = catalogEntries(surface ?? [], descriptionMaxLength, { patterns: pagedToolPatterns })
1146
- } else {
1147
- const merged = mergeProjectedSchemas(resident, surface)
1148
- entries = catalogEntries(merged, descriptionMaxLength, { patterns: pagedToolPatterns })
1149
- }
1150
- const inactiveSummary = catalogInactive
1151
-
1152
- // Store fresh state on agent
1153
- if (agent !== undefined) {
1154
- agentCatalogState.set(agent, {
1155
- entries,
1156
- presentation: effectivePresentation,
1157
- inactive: inactiveSummary,
1158
- })
1159
- }
1160
-
1161
- if (assembledTools === undefined) return assembled
1162
- // Keep the caller's own assembly object whenever this pass neither corrected
1163
- // a collapsed wire nor lifted a paged tool off it: a needless copy would hand
1164
- // downstream listeners a different object for no behavioral reason.
1165
- const unchanged = correctedWire === undefined && resident.length === assembledTools.length
1166
- return unchanged ? assembled : { ...assembled, tools: resident }
984
+ agentCatalogState.set(agent, {
985
+ entries: catalogEntries(surface, descriptionMaxLength, { patterns: pagedToolPatterns }),
986
+ presentation: effectivePresentation,
987
+ inactive: inactiveSummary,
988
+ })
989
+ return assembled
1167
990
  }, { prepend: true })
1168
991
 
1169
992
  ctx.on('agent/pre-step', async (payload, next) => {