@linxin666/dsh-liangshen 0.4.15 → 0.4.17

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,50 +1,59 @@
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
- * TOOL PAGING: tools whose names match `pagedToolPatterns` (default
22
- * `['mcp__*']`) stay off the wire until their namespace is activated through
23
- * the `tool_activate` tool (registered by the sibling tool-activate plugin).
24
+ * TOOL PAGING: tools whose names match `pagedToolPatterns` — by default the
25
+ * MCP bridge plus the plugin families `browser_*`, `task_board_*`, `team_*`,
26
+ * `squad*`, `ui_*` and `ssh_*` — stay off the wire until their namespace is
27
+ * activated through the `tool_activate` tool (registered by the sibling
28
+ * tool-activate plugin). Every host builtin stays resident: no shipped pattern
29
+ * names one, so the session keeps its shell, filesystem, job, skill, delegation,
30
+ * plan, goal and web tools on the wire for its whole lifetime.
24
31
  * The active set replays from the durable session event stream on every
25
32
  * assembly, so resume, reload, and compaction rebuild it without any
26
33
  * process-memory state. At most a few namespaces stay active; the LRU
27
34
  * eviction falls out of the same replay.
28
35
  *
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.
36
+ * Paging is enforced in ONE place: a per-scope registry restriction
37
+ * (agent.ctx.tools.restrict) that removes the paged names from every scoped
38
+ * reader, the request's own wire included.
43
39
  *
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.
40
+ * The wire cannot be filtered by a listener any more. Since 0.2.2 the
41
+ * `system-prompt/assemble` waterfall transforms a `PromptPresentation` that
42
+ * carries no tool array at all: the harness collects the tool providers BEFORE
43
+ * the waterfall runs and merges the authoritative `tools` back AFTER it, so a
44
+ * listener can neither observe nor rewrite what the request carries. The
45
+ * registry is the surface every tool declaration is projected from — the
46
+ * native roster the executor renders and the set a program may dispatch to —
47
+ * so one restriction pages both presentations, and the wire partition that
48
+ * used to page the `native` roster is gone with the array it filtered.
49
+ *
50
+ * READING THE SURFACE: the catalog describes the request's own tool set, read
51
+ * as `tools.schemas(agent, context.toolSet)` while assembling. The assemble
52
+ * context's `toolSet` is the step's admitted selection — the fact a listener
53
+ * cannot recover from the assembly value — and `schemas()` reads through the
54
+ * scope's restriction, so the catalog lists exactly what the wire carries. An
55
+ * unreadable projection is NOT an empty one: the catalog keeps its last
56
+ * published state rather than announcing a session with no tools.
48
57
  *
49
58
  * TIMING: that restriction is installed from OUTSIDE the assembly waterfall.
50
59
  * `SystemPrompt.assemble()` collects the tool providers and calls every
@@ -83,7 +92,6 @@ import {
83
92
  inactiveNamespaces,
84
93
  integerAtLeast,
85
94
  namespaceOf,
86
- partitionWireTools,
87
95
  replayActivations,
88
96
  summarizeInactive,
89
97
  validatePagedToolPatterns,
@@ -115,7 +123,7 @@ const pagedSurfaceBySession = new WeakMap()
115
123
  /**
116
124
  * Publish (or, with `undefined`, retract) one scope's paged namespaces.
117
125
  * @param agent - agent scope the partition belongs to.
118
- * @param surface - namespace-keyed namespaces, as `partitionWireTools` returns.
126
+ * @param surface - namespace-keyed namespaces, as `inactiveNamespaces` returns.
119
127
  */
120
128
  function publishPagedSurface(agent, surface) {
121
129
  if (agent === undefined || agent === null) return
@@ -175,9 +183,10 @@ export const DEFAULT_PRESENTATION = 'ptc'
175
183
  * surface small.
176
184
  *
177
185
  * The value is calibrated ABOVE this preset's own shipped roster rather than at
178
- * the theoretical core-set ideal: with gentle paging every non-\`mcp__*\` tool the
179
- * preset mounts stays resident, and that roster measures in the low thousands of
180
- * estimated tokens. A ceiling below the factory baseline would fire on every
186
+ * the theoretical core-set ideal: with gentle paging the resident surface is the
187
+ * host builtins plus every tool family no shipped pattern claims, and that
188
+ * roster measures in the low thousands of estimated tokens. A ceiling below the
189
+ * factory baseline would fire on every
181
190
  * ordinary session and train the reader to ignore it. It therefore flags real
182
191
  * growth — a deployment adding tool families of its own — instead of the shipped
183
192
  * configuration. The guard warns once per session and never truncates: silently
@@ -293,9 +302,9 @@ function validateRetiredAnchorTools(value) {
293
302
  * line instead.
294
303
  *
295
304
  * SCOPE: exactly the host builtins the preset's own `agent.cordis.yml` rows
296
- * mount for a session, which is the surface the paging wildcard leaves resident
297
- * (`pagedToolPatterns` defaults to `mcp__*`, so no host builtin is ever paged
298
- * out):
305
+ * mount for a session, which is the surface the shipped paging patterns leave
306
+ * resident (they name the MCP bridge and the plugin tool families, and no host
307
+ * builtin matches one):
299
308
  * - the shell (one of bash / pwsh per platform), the filesystem and discovery
300
309
  * tools, the background-job controls, and the editor;
301
310
  * - the prompt/skill surface, the todo list, the user question tool, and
@@ -558,38 +567,6 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
558
567
  ].join('\n')
559
568
  }
560
569
 
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
570
  /** Build the durable catalog message for one entry list. */
594
571
  export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
595
572
  return {
@@ -662,7 +639,7 @@ function withoutMessage(decision, id) {
662
639
  return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
663
640
  }
664
641
 
665
- /** Register the presentation declaration, the wire paging, and the per-step catalog injection. */
642
+ /** Register the registry paging and the per-step catalog injection. */
666
643
  export function apply(ctx, config) {
667
644
  const descriptionMaxLength = integerAtLeast(
668
645
  name,
@@ -711,11 +688,6 @@ export function apply(ctx, config) {
711
688
  // Session to agent mapping for lifecycle events
712
689
  const agentBySession = new WeakMap()
713
690
 
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
691
  // Registry-level paging state, one entry per agent scope: the names the live
720
692
  // restriction withholds and the exact disposer that lifts it. Keyed by agent
721
693
  // so two sessions assembling at once cannot lift each other's filter, and
@@ -736,15 +708,17 @@ export function apply(ctx, config) {
736
708
 
737
709
  /**
738
710
  * 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.
711
+ * make the registry match it: `deny` masks exactly the names the paged
712
+ * namespaces carry, so the scope still inherits everything else.
741
713
  * Scoped registrations are exempt by the registry's own rule, so
742
714
  * preset-owned tools can never be filtered away by this.
743
715
  *
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.
716
+ * The restriction is what paging MEANS in both presentations now that the
717
+ * waterfall carries no tool array: the registry is the surface every tool
718
+ * declaration is projected from, so the native roster and the program
719
+ * bindings lose the paged names together. It also stores the namespaces it
720
+ * withheld, so the catalog and the live restriction are read from ONE fact
721
+ * instead of two computations.
748
722
  *
749
723
  * Called OUTSIDE the assembly waterfall, deliberately: see
750
724
  * {@link syncBeforeAssembly} for why an in-waterfall sync cannot fix the
@@ -769,7 +743,7 @@ export function apply(ctx, config) {
769
743
  // nothing left to withhold. Silent on an unreadable surface: a sync may
770
744
  // run before the registry is populated, and "no tools yet" is not the
771
745
  // assembly-path emergency that warning describes.
772
- const fullSurface = quietSchemas(agent) ?? []
746
+ const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
773
747
  if (fullSurface.length === 0) return undefined
774
748
  // Publish before the withhold decision: with every namespace already active
775
749
  // there is nothing to restrict, and the activation tool must still know the
@@ -809,23 +783,18 @@ export function apply(ctx, config) {
809
783
  * request's own SDK section still lists it. Syncing before the providers are
810
784
  * collected is what keeps the two consistent from the FIRST `ptc` request.
811
785
  *
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.
786
+ * EVERY SCOPE IS PAGED, in both presentations. Before 0.2.2 the native
787
+ * roster was filtered in the waterfall itself — the listener returned a
788
+ * narrowed `tools` array — so a registry restriction there would have been
789
+ * redundant, and a deployment whose wire never collapsed (no code runtime, a
790
+ * declined declaration) had to keep it off entirely. The harness now merges
791
+ * its own provider-owned `tools` back after the waterfall, so that return
792
+ * value is discarded: the registry is the only place a page can exist, and a
793
+ * scope left unpaged would hand the model every paged family it was supposed
794
+ * to activate first.
825
795
  */
826
796
  const syncBeforeAssembly = (agent) => {
827
- if (agent === undefined || presentation !== 'ptc') return undefined
828
- if (!agentDeclared.has(agent)) return undefined
797
+ if (agent === undefined) return undefined
829
798
  return syncScopePaging(agent)
830
799
  }
831
800
 
@@ -834,65 +803,16 @@ export function apply(ctx, config) {
834
803
  // The 0.1.6 cohort renamed the service face from `codeRuntime` to
835
804
  // `ptcRuntime` (package `@deepseek-ai/dsh-code-runtime` became
836
805
  // `@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
- }
806
+ // silently disable program presentation for every session.
807
+ //
808
+ // This is the ONE fact that decides what the request carries, because no
809
+ // reader can observe the collapse itself: the petc executor keeps `run_code`
810
+ // outside the registry (`describe()` returns it, `tools.schemas()` never
811
+ // does), so a `schemas()` read returns the same roster under both
812
+ // presentations. The composition enables the `tool-executor-ptc` row from
813
+ // exactly this setting (see `src/composition.ts`), so the configured
814
+ // presentation plus a mounted runtime IS the wire.
815
+ const collapsedTransport = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
896
816
 
897
817
  /**
898
818
  * Read visible tool schemas from the public tools.schemas(agent) API.
@@ -911,71 +831,59 @@ export function apply(ctx, config) {
911
831
  }
912
832
 
913
833
  /**
914
- * Read the scope's model-facing surface without the assembly path's warning.
915
- * Returns undefined when no projection is readable at all.
834
+ * Read the model-facing surface one scope offers this step, without the
835
+ * reserved transport (the catalog never lists run_code as an entry).
836
+ *
837
+ * `toolSet` is the assemble context's step admission: passing it narrows the
838
+ * read to exactly the tools this request may carry, conditionally registered
839
+ * ones excluded. Omitted, the read covers every registered definition, which
840
+ * is what the paging sync needs to compute its page.
841
+ *
842
+ * An EMPTY list and an UNREADABLE registry are different facts, and the
843
+ * return type keeps them apart: `[]` means this scope really offers no tool,
844
+ * `undefined` means nothing could be read (a deployment without the registry,
845
+ * a projection that threw). A caller that treats the second as the first
846
+ * announces "no tools" to a session that has them — the defect issue #2016
847
+ * reports.
848
+ *
849
+ * @param agent - agent scope the surface is read for.
850
+ * @param toolSet - the step's admitted selection, or undefined for every definition.
851
+ * @param options - `quiet` suppresses the diagnostic of an unreadable registry.
852
+ * @returns the visible schemas minus run_code, or undefined when unreadable.
916
853
  */
917
- const quietSchemas = (agent) => {
854
+ const readSurface = (agent, toolSet, options) => {
918
855
  const tools = resolveToolsService(agent)
919
856
  if (tools === undefined) return undefined
920
857
  for (const method of ['schemas', 'sdkSchemas']) {
921
858
  if (typeof tools[method] !== 'function') continue
922
859
  try {
923
- const schemas = tools[method](agent)
860
+ const schemas = tools[method](agent, toolSet)
924
861
  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
862
+ } catch (err) {
863
+ if (options?.quiet !== true) {
864
+ // Its own key, so an unreadable projection never swallows the
865
+ // declaration warning that explains what replaced it.
866
+ warnOnce('surface', `no tool schemas available (${err instanceof Error ? err.message : String(err)}) — the catalog keeps its last published state`)
955
867
  }
956
- } catch {
957
- warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
958
868
  return undefined
959
869
  }
960
870
  }
961
871
  return undefined
962
872
  }
963
873
 
964
- // Early lifecycle hook: declare the presentation and page the scope as soon
965
- // as it exists.
874
+ // Early lifecycle hook: page the scope as soon as it exists.
966
875
  //
967
876
  // The 0.1.6 cohort folded the former `agent/session-start` into the async
968
877
  // serial `agent/created`, which carries the same payload object and runs
969
878
  // 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.
879
+ // page is already in place when that assembly collects its tool providers.
971
880
  //
972
881
  // The payload is destructured ON PURPOSE: `agent/created` passes its payload
973
882
  // 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.
883
+ // as the agent yields an object with no `session` and no `ctx`, so paging
884
+ // would silently never engage.
976
885
  ctx.on('agent/created', ({ agent }) => {
977
886
  if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
978
- if (transportReady()) declarePresentation(agent)
979
887
  // The session log is readable here, and this runs before the first turn
980
888
  // assembles a prompt, so a scope created over an existing (resumed)
981
889
  // session is paged before its FIRST assembly rather than one request late.
@@ -1004,166 +912,86 @@ export function apply(ctx, config) {
1004
912
  return next()
1005
913
  }, { prepend: true })
1006
914
 
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
915
  ctx.on('system-prompt/assemble', async (assembly, context, next) => {
1012
916
  const agent = context?.agent
917
+ // The step's admitted selection, and the one fact about this request's tool
918
+ // set a listener can still read: since 0.2.2 the assembly value carries no
919
+ // tool array, and the providers it is built from are collected before this
920
+ // waterfall runs.
921
+ const toolSet = context?.toolSet
1013
922
 
1014
923
  if (agent !== undefined && agent.session !== undefined) {
1015
924
  agentBySession.set(agent.session, agent)
1016
925
  }
1017
926
 
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)
927
+ // Page the scope before the providers are collected; a scope the lifecycle
928
+ // hooks already paged re-derives the same state, so this is idempotent.
929
+ syncBeforeAssembly(agent)
1057
930
 
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).
931
+ // The waterfall's transformed value travels on untouched: tool declarations
932
+ // are provider-owned, so there is no array here to filter or restore.
1061
933
  const assembled = await next()
1062
934
 
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
935
+ // The catalog describes THIS request's surface, read from the registry
936
+ // through the step's admission. `schemas()` reads through the scope's
937
+ // restriction, so the result is exactly the list this request carries: the
938
+ // native roster, or - under a collapsed `ptc` wire - the projection every
939
+ // tool is reached through from inside a program (run_code is the transport,
940
+ // never a catalog entry).
941
+ const surface = agent === undefined ? undefined : readSurface(agent, toolSet)
942
+
943
+ // The presentation this request carries is the one the composition mounted.
944
+ // Nothing in the assembly names it and `schemas()` reads the same roster
945
+ // under both, so the configured mode plus a mounted runtime is the answer -
946
+ // and a mode whose runtime is missing keeps the native wording, because
947
+ // that is the wire an executor-less deployment renders.
948
+ const effectivePresentation = collapsedTransport() ? 'ptc' : 'native'
949
+
950
+ // An unreadable projection is NOT an empty one. Keep the catalog this scope
951
+ // last published instead of rewriting it: recording "this session has no
952
+ // tools" over a read that merely failed is what made the model refuse tools
953
+ // the request was carrying (issue #2016). The one fact that still has to
954
+ // follow the request is the transport, so the wording is corrected above.
955
+ if (agent === undefined) return assembled
956
+ if (surface === undefined) {
957
+ const previous = agentCatalogState.get(agent)
958
+ if (previous !== undefined && previous.presentation !== effectivePresentation) {
959
+ agentCatalogState.set(agent, { ...previous, presentation: effectivePresentation })
960
+ }
961
+ return assembled
1102
962
  }
1103
963
 
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
964
  // Diagnostic guard on the always-on-wire surface. It warns rather than
1118
965
  // truncates: silently dropping a tool the session needs would trade a
1119
966
  // measurable context cost for an unmeasurable capability loss.
1120
- const residentTokens = estimateSurfaceTokens(resident)
967
+ const residentTokens = estimateSurfaceTokens(surface)
1121
968
  if (residentTokens > maxResidentTokens) {
1122
969
  // Name the heaviest tools so the remedy is actionable rather than a bare number.
1123
- const heaviest = [...resident]
970
+ const heaviest = [...surface]
1124
971
  .map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
1125
972
  .sort((left, right) => right.tokens - left.tokens)
1126
973
  .slice(0, 3)
1127
974
  .map(entry => `${entry.name} (${entry.tokens})`)
1128
975
  .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`)
976
+ 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
977
  }
1131
978
 
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,
979
+ // The page the registry enforces IS this request's page: the restriction was
980
+ // installed before the providers were collected (see {@link syncBeforeAssembly}),
981
+ // and the surface above already reads through it. A scope whose page could
982
+ // not be installed withholds nothing, so it advertises nothing.
983
+ const pagingState = agentPaging.get(agent)
984
+ const inactiveSummary = summarizeInactive(
985
+ pagingState?.inactive ?? [],
1138
986
  describe => catalogDescription(describe, descriptionMaxLength),
1139
987
  )
1140
988
 
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 }
989
+ agentCatalogState.set(agent, {
990
+ entries: catalogEntries(surface, descriptionMaxLength, { patterns: pagedToolPatterns }),
991
+ presentation: effectivePresentation,
992
+ inactive: inactiveSummary,
993
+ })
994
+ return assembled
1167
995
  }, { prepend: true })
1168
996
 
1169
997
  ctx.on('agent/pre-step', async (payload, next) => {