@linxin666/dsh-liangshen 0.3.22 → 0.3.24

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.
Files changed (37) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +45 -38
  3. package/README.zh.md +44 -37
  4. package/lib/client.js +1058 -11
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +105 -22
  7. package/lib/types/client/LiangShenSettingsCard.d.ts +61 -0
  8. package/lib/types/client/PluginSettingsCard.d.ts +133 -0
  9. package/lib/types/client/index.d.ts +34 -0
  10. package/lib/types/client/locales.d.ts +27 -1
  11. package/lib/types/client/plugin-card-seat.d.ts +96 -0
  12. package/lib/types/client/settings-form.d.ts +197 -0
  13. package/lib/types/core/lever.d.ts +6 -3
  14. package/lib/types/index.d.ts +23 -11
  15. package/lib/types/sync.d.ts +29 -2
  16. package/package.json +6 -2
  17. package/presets/liangshen/NOTICE +4 -4
  18. package/presets/liangshen/agent.cordis.yml +130 -119
  19. package/presets/liangshen/minimal-prompt.mjs +71 -36
  20. package/presets/liangshen/paging.mjs +232 -0
  21. package/presets/liangshen/tool-activate.mjs +176 -0
  22. package/presets/liangshen/tool-catalog.mjs +610 -218
  23. package/presets/liangshen/working-context.mjs +214 -0
  24. package/src/client/LiangShenLever.tsx +4 -1
  25. package/src/client/LiangShenSettingsCard.tsx +149 -0
  26. package/src/client/PluginSettingsCard.tsx +550 -0
  27. package/src/client/index.ts +60 -1
  28. package/src/client/locales.ts +53 -1
  29. package/src/client/plugin-card-seat.ts +185 -0
  30. package/src/client/settings-card.module.css +418 -0
  31. package/src/client/settings-form.ts +439 -0
  32. package/src/core/lever.ts +7 -4
  33. package/src/index.ts +35 -14
  34. package/src/sync.test.ts +86 -7
  35. package/src/sync.ts +108 -6
  36. package/tools/benchmark-live-run.mjs +24 -33
  37. package/presets/liangshen/custom-bash.mjs +0 -213
@@ -1,22 +1,86 @@
1
1
  /**
2
- * tool-catalog — staged model-visible tool surface for LiangShen mode:
3
- * anchor turn's native wire, PTC handoff at turn boundary, and durable catalog message.
2
+ * tool-catalog — the model-visible tool surface for LiangShen mode: one
3
+ * presentation declaration per session, gentle tool paging for high-fan-out
4
+ * namespaces, and the durable catalog message.
4
5
  *
5
- * Minimal-prompt retains official host tools:sdk and tools:ptc-only sections
6
- * in the system prompt. This plugin:
7
- * 1. Separates PTC plan from actual presentation state.
8
- * 2. Uses only public APIs (tools.schemas, tools.presentAs).
9
- * 3. Does not duplicate the giant TypeScript SDK into durable messages.
10
- * 4. Staging: anchor turn narrows to anchorTools (bash or 4 tools) natively.
11
- * 5. Turn boundary session events / lifecycle hooks declare PTC before assemble.
12
- * 6. If SDK/tools are unavailable, reverts PTC and synchronizes wire to native.
13
- * 7. Removes the false statement about schemas traveling with tool definition.
14
- * 8. Maintains deduplication and compaction recovery.
15
- * 9. Native presentation lists exactly the tools this request's wire carries; under
16
- * PTC the list is the SDK-reachable registry projection and the program contract
17
- * marks `run_code` as the only directly callable transport.
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;
9
+ * - `ptc`: the wire collapses to the single `run_code` transport and every
10
+ * other tool is reached from inside the program through the generated SDK;
11
+ * - `both` (default): the full native roster plus the `run_code` transport
12
+ * co-resident on the wire — native calls carry ordinary work, `run_code`
13
+ * covers programmatic batch computation and overlapped fan-out.
14
+ *
15
+ * The declaration happens once per agent scope (agent.ctx.tools.presentAs) as
16
+ * early as the scope exists — there is no turn-boundary staging: the retired
17
+ * anchor-turn mechanism is gone, and the legacy `anchorTools` key is accepted
18
+ * but ignored with a one-time warning. The legacy boolean `ptcPresentation`
19
+ * maps onto the enum (true -> 'ptc', false -> 'native') with a one-time
20
+ * deprecation warning. A missing code runtime or a declined declaration keeps
21
+ * the native surface with a one-time warning.
22
+ *
23
+ * TOOL PAGING: tools whose names match `pagedToolPatterns` (default
24
+ * `['mcp__*']`) stay off the wire until their namespace is activated through
25
+ * the `tool_activate` tool (registered by the sibling tool-activate plugin).
26
+ * The active set replays from the durable session event stream on every
27
+ * assembly, so resume, reload, and compaction rebuild it without any
28
+ * process-memory state. At most a few namespaces stay active; the LRU
29
+ * eviction falls out of the same replay.
30
+ *
31
+ * Paging is enforced in TWO places, because the wire is not the only surface a
32
+ * tool can be reached through:
33
+ * - the wire partition below (resident tools returned, paged tools lifted) and
34
+ * - a per-scope registry restriction (agent.ctx.tools.restrict) that removes
35
+ * the paged names exactly as the wire does.
36
+ * The second one is what makes paging real under the `ptc` presentation,
37
+ * where the wire has already collapsed to the single `run_code` transport and
38
+ * every other tool is reached from inside a program. Under a collapsed wire
39
+ * the visible set is the whole surface: it renders the `tools:sdk` prompt
40
+ * section and it is what a program may dispatch to, so filtering the assembled
41
+ * `tools` array alone would withhold nothing the model can observe. The
42
+ * restriction is derived from the same pattern match as the partition
43
+ * (`withheldToolNames`) and is lifted before a new one is applied, so repeated
44
+ * collections do not accumulate filters.
45
+ *
46
+ * TIMING: that restriction is installed from OUTSIDE the assembly waterfall.
47
+ * `SystemPrompt.assemble()` collects the tool providers and calls every
48
+ * section's `text(context)` BEFORE it runs the `system-prompt/assemble`
49
+ * waterfall, so a restriction installed inside that waterfall could only take
50
+ * effect one assembly later — leaving a request whose catalog claims a
51
+ * namespace is paged while that request's own `tools:sdk` section still lists
52
+ * it. `syncBeforeAssembly` therefore runs at scope creation, session start,
53
+ * and after each tool call that can move the active set, so the FIRST `ptc`
54
+ * request already renders a page-consistent SDK section.
55
+ *
56
+ * CATALOG: the durable user message appended after the user's own message
57
+ * names exactly the tools the current request's wire carries (each tool's
58
+ * argument signature plus a one-line summary), then summarizes the paged-out
59
+ * namespaces with their activation pointer. Under 'both' the catalog lists
60
+ * `run_code` like any other tool and notes the programmatic-escape hatch; the
61
+ * 'ptc' program contract only ships when the wire actually collapsed to it.
62
+ * The catalog republishes only when its content changes or the published copy
63
+ * left the visible surface (compaction, resume).
64
+ *
65
+ * RESIDENT BUDGET: `maxResidentTokens` (default 1500) estimates the
66
+ * always-on-wire surface and warns once when it is crossed. The guard is a
67
+ * diagnostic, never a truncation: silently dropping a tool the session needs
68
+ * would trade a measurable context cost for an unmeasurable capability loss.
18
69
  */
19
70
 
71
+ import {
72
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
73
+ DEFAULT_PAGED_TOOL_PATTERNS,
74
+ inactiveNamespaces,
75
+ integerAtLeast,
76
+ namespaceOf,
77
+ partitionWireTools,
78
+ replayActivations,
79
+ summarizeInactive,
80
+ validatePagedToolPatterns,
81
+ withheldToolNames,
82
+ } from './paging.mjs'
83
+
20
84
  /** Cordis plugin name used by loader diagnostics. */
21
85
  export const name = 'liangshen-tool-catalog'
22
86
 
@@ -26,6 +90,66 @@ export const inject = ['systemPrompt']
26
90
  /** Default cap for one tool's one-line summary in the injected compact list. */
27
91
  const DEFAULT_DESCRIPTION_MAX_LENGTH = 200
28
92
 
93
+ /** The presentation modes the SDK's ToolPresentationMode supports. */
94
+ export const PRESENTATION_MODES = ['native', 'ptc', 'both']
95
+
96
+ /**
97
+ * The default presentation: the wire collapses to the single \`run_code\` transport
98
+ * and every other tool is reached from inside the program through the generated
99
+ * SDK.
100
+ *
101
+ * This is a deliberate trade, not a measured win. Collapsing the wire removes the
102
+ * native roster's schema payload from every request, which is the cheapest static
103
+ * context of the three modes; the official published scaffold comparison, however,
104
+ * places this presentation BELOW the natively presented surface on both code-agent
105
+ * benchmarks (DeepSWE v1.1: 67.6 against 72.6; Terminal-Bench 2.1: 85.8 against
106
+ * 90.6). The default is chosen for its static-context cost on long sessions and is
107
+ * NOT locally measured — the bundled benchmark matrix is how that would be settled.
108
+ * A deployment with no mounted code runtime degrades to the native surface with a
109
+ * one-time warning rather than presenting a transport the request cannot carry.
110
+ */
111
+ export const DEFAULT_PRESENTATION = 'ptc'
112
+
113
+ /**
114
+ * The default ceiling on the resident (always-on-wire) tool surface, in
115
+ * estimated tokens. The model's long-range attention is a bounded sparse
116
+ * budget, so a static schema surface that keeps growing silently evicts the
117
+ * conversation's own constraints from it, and tool paging exists to keep that
118
+ * surface small.
119
+ *
120
+ * The value is calibrated ABOVE this preset's own shipped roster rather than at
121
+ * the theoretical core-set ideal: with gentle paging every non-\`mcp__*\` tool the
122
+ * preset mounts stays resident, and that roster measures in the low thousands of
123
+ * estimated tokens. A ceiling below the factory baseline would fire on every
124
+ * ordinary session and train the reader to ignore it. It therefore flags real
125
+ * growth — a deployment adding tool families of its own — instead of the shipped
126
+ * configuration. The guard warns once per session and never truncates: silently
127
+ * dropping a tool the session needs would trade a measurable context cost for an
128
+ * unmeasurable capability loss.
129
+ */
130
+ export const DEFAULT_MAX_RESIDENT_TOKENS = 6000
131
+
132
+ /**
133
+ * Rough token estimate for one tool surface: the serialized schema is the
134
+ * payload the request actually carries, and four characters per token is the
135
+ * conventional English-and-JSON approximation. Deliberately coarse — this
136
+ * drives a warning threshold, not a billing figure.
137
+ * @param schemas - the tool schemas on the wire.
138
+ * @returns estimated tokens, or 0 when nothing is measurable.
139
+ */
140
+ export function estimateSurfaceTokens(schemas) {
141
+ let characters = 0
142
+ for (const schema of Array.isArray(schemas) ? schemas : []) {
143
+ if (schema === null || schema === undefined) continue
144
+ try {
145
+ characters += JSON.stringify(schema)?.length ?? 0
146
+ } catch {
147
+ // A hostile or circular schema contributes nothing rather than throwing.
148
+ }
149
+ }
150
+ return Math.ceil(characters / 4)
151
+ }
152
+
29
153
  /**
30
154
  * Nesting depth beyond which an inline signature degrades to JsonValue. The
31
155
  * rendering stays one line per tool, so deeply nested argument objects are
@@ -36,14 +160,6 @@ const MAX_SIGNATURE_DEPTH = 4
36
160
  /** Types the compact signature renders exactly; everything else degrades. */
37
161
  const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null'])
38
162
 
39
- function integerAtLeast(value, field, minimum, fallback) {
40
- if (value === undefined) return fallback
41
- if (!Number.isInteger(value) || value < minimum) {
42
- throw new TypeError(`${name}: ${field} must be an integer >= ${minimum}`)
43
- }
44
- return value
45
- }
46
-
47
163
  function optionalBoolean(value, field, fallback) {
48
164
  if (value === undefined) return fallback
49
165
  if (typeof value !== 'boolean') {
@@ -52,41 +168,42 @@ function optionalBoolean(value, field, fallback) {
52
168
  return value
53
169
  }
54
170
 
55
- /** Parse the anchorTools config: absent means staging off, entries must be non-empty names. */
56
- function anchorToolNames(value) {
57
- if (value === undefined) return []
171
+ /**
172
+ * Resolve the presentation config: the explicit `presentation` enum wins; the
173
+ * legacy boolean `ptcPresentation` maps onto it (true -> 'ptc', false ->
174
+ * 'native') with a one-time deprecation warning; neither means the default.
175
+ */
176
+ function resolvePresentation(config, warn) {
177
+ const explicit = config?.presentation
178
+ if (explicit !== undefined) {
179
+ if (!PRESENTATION_MODES.includes(explicit)) {
180
+ throw new TypeError(`${name}: presentation must be one of ${JSON.stringify(PRESENTATION_MODES)}`)
181
+ }
182
+ if (config?.ptcPresentation !== undefined) {
183
+ optionalBoolean(config.ptcPresentation, 'ptcPresentation', true)
184
+ warn('the ptcPresentation key is deprecated — presentation takes precedence over it')
185
+ }
186
+ return explicit
187
+ }
188
+ if (config?.ptcPresentation !== undefined) {
189
+ const legacy = optionalBoolean(config.ptcPresentation, 'ptcPresentation', true)
190
+ warn(`the ptcPresentation key is deprecated; use presentation instead (mapping ${legacy ? "true -> 'ptc'" : "false -> 'native'"})`)
191
+ return legacy ? 'ptc' : 'native'
192
+ }
193
+ return DEFAULT_PRESENTATION
194
+ }
195
+
196
+ /** Validate the retired anchorTools key's shape before ignoring it. */
197
+ function validateRetiredAnchorTools(value) {
198
+ if (value === undefined) return
58
199
  if (!Array.isArray(value)) {
59
200
  throw new TypeError(`${name}: anchorTools must be an array of tool names`)
60
201
  }
61
- return value.map((entry) => {
202
+ for (const entry of value) {
62
203
  if (typeof entry !== 'string' || entry.trim() === '') {
63
204
  throw new TypeError(`${name}: anchorTools entries must be non-empty tool names`)
64
205
  }
65
- return entry
66
- })
67
- }
68
-
69
- /**
70
- * Whether the session is still in its anchor turn: fewer than two turn/start
71
- * events and no turn/end yet.
72
- */
73
- export function inAnchorTurn(events) {
74
- let turns = 0
75
- for (const event of Array.isArray(events) ? events : []) {
76
- if (event?.type === 'turn/end') return false
77
- if (event?.type !== 'turn/start') continue
78
- turns += 1
79
- if (turns >= 2) return false
80
206
  }
81
- return true
82
- }
83
-
84
- /** Narrow one assembled wire tool list to the anchor names, preserving wire order. */
85
- export function anchorToolsOf(tools, names) {
86
- const wire = Array.isArray(tools) ? tools : []
87
- if (names.length === 0) return wire
88
- const keep = new Set(names)
89
- return wire.filter(tool => keep.has(tool?.name))
90
207
  }
91
208
 
92
209
  /**
@@ -155,25 +272,35 @@ export function renderSignature(parameters) {
155
272
 
156
273
  /**
157
274
  * Catalog entries for one tool surface, sorted by name so an unchanged surface
158
- * renders byte-identical text across assemblies. Nameless definitions and
159
- * the run_code transport tool are skipped.
275
+ * renders byte-identical text across assemblies. Nameless definitions are
276
+ * skipped; the `run_code` transport is listed only when the presentation puts
277
+ * it on the wire beside the native tools ('both').
160
278
  */
161
- export function catalogEntries(schemas, maxLength) {
279
+ export function catalogEntries(schemas, maxLength, options) {
280
+ const includeRunCode = options?.includeRunCode === true
281
+ const patterns = Array.isArray(options?.patterns) ? options.patterns : []
162
282
  const entries = []
163
283
  for (const schema of Array.isArray(schemas) ? schemas : []) {
164
284
  const toolName = schema?.name
165
- if (typeof toolName !== 'string' || toolName === '' || toolName === 'run_code') continue
285
+ if (typeof toolName !== 'string' || toolName === '') continue
286
+ if (toolName === 'run_code' && !includeRunCode) continue
287
+ // A tool from a paged family carries its namespace so the catalog can group
288
+ // it the way the model calls it, instead of scattering one server's tools
289
+ // through an alphabetical list.
290
+ const namespace = namespaceOf(toolName, patterns)
166
291
  entries.push({
167
292
  name: toolName,
168
293
  signature: renderSignature(schema.parameters),
169
294
  description: catalogDescription(schema.description, maxLength),
295
+ ...(namespace === undefined ? {} : { namespace }),
170
296
  })
171
297
  }
172
298
  return entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
173
299
  }
174
300
 
175
301
  /**
176
- * The program contract the injected message carries under PTC.
302
+ * The program contract the injected message carries when the wire collapsed to
303
+ * the PTC transport: `run_code` is then the only directly callable tool.
177
304
  */
178
305
  const PTC_PROGRAM_LINES = [
179
306
  'The session presents these tools through `run_code`, which takes `code` — the body of an async TypeScript function (top-level `await` and `return` both work; only erasable syntax runs, no `enum` or namespaces) — and `description`, a short summary of the program. Compose one program per intent instead of one tool call per step:',
@@ -183,25 +310,68 @@ const PTC_PROGRAM_LINES = [
183
310
  '- a failed call rejects with `ToolCallError`, whose `toolName` and human-readable message identify it — `try/catch` it to continue;',
184
311
  '- only what you `return` or `console.log` becomes program output; every other intermediate result stays out of the conversation, so extract just what the next decision needs, and an image a tool returns is attached after the run.',
185
312
  '',
186
- "`run_code` is the only tool that can be called directly once it is on the wire: every tool listed above is reached from inside the program.",
313
+ '`run_code` is the only tool that can be called directly once it is on the wire: every tool listed above is reached from inside the program.',
314
+ '',
315
+ 'A namespace this session has not activated with `tool_activate({ namespace: "..." })` is not listed above and cannot be reached from inside a program either: the page is a page on the whole surface, not only on the wire, and the paged-out list below names exactly what is withheld. Activating one puts its tools back into this list and back into a program from the next request on.',
316
+ ]
317
+
318
+ /**
319
+ * The short note the catalog carries when `run_code` sits on the wire beside
320
+ * the native roster ('both'): native calls are the primary surface, and the
321
+ * transport covers programmatic batch work. Paged-out namespaces stay reachable
322
+ * through the SDK inside a program even before activation.
323
+ */
324
+ const BOTH_PROGRAM_LINES = [
325
+ 'Call the tools above directly by name for ordinary work. `run_code` is also on the wire for the cases one intent is easier as a program: an async TypeScript body (`code`, with a short `description`) that reaches tools as `await tools.<name>({ ... })`, overlaps independent read-only calls under `Promise.all`, and catches `ToolCallError` to continue — use it for programmatic batch computation or wide fan-out, not for single ordinary calls.',
326
+ 'Paged-out namespaces below stay off the NATIVE wire but stay reachable through the SDK inside a program even before activation; activating one also puts its tools back on the direct surface.',
187
327
  ]
188
328
 
189
329
  /**
190
330
  * Model-facing catalog text.
191
- * - Under native presentation (anchor turn or PTC declined/disabled): carries available_tools list.
192
- * - Under PTC presentation: carries available_tools list and PTC program contract.
193
- * - The false statement that 'the full parameter schema travels with its own tool definition' is removed.
194
- * - Complete SDK definitions are retained in the official host tools:sdk prompt section.
331
+ * - Native presentation: the on-wire tool list plus the paged-out namespace summary.
332
+ * - 'both': the on-wire list INCLUDING `run_code`, the namespace summary, and
333
+ * the short programmatic-escape note.
334
+ * - 'ptc' (wire collapsed to `run_code`): the SDK-reachable list plus the full
335
+ * program contract naming `run_code` the one direct transport.
195
336
  */
196
- export function renderCatalogText(entries, ptc) {
337
+ export function renderCatalogText(entries, presentation = 'native', inactive = []) {
338
+ // Activated paged families are listed under their namespace heading; every
339
+ // other tool stays in the flat alphabetical list, so an unchanged surface
340
+ // still renders byte-identical text.
341
+ const resident = entries.filter(entry => entry.namespace === undefined)
342
+ const byNamespace = new Map()
343
+ for (const entry of entries) {
344
+ if (entry.namespace === undefined) continue
345
+ if (!byNamespace.has(entry.namespace)) byNamespace.set(entry.namespace, [])
346
+ byNamespace.get(entry.namespace).push(entry)
347
+ }
348
+ const lineOf = entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`
197
349
  const available = entries.length === 0
198
350
  ? ['No tools are currently available in this session.']
199
351
  : [
200
352
  '<available_tools>',
201
- ...entries.map(entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`),
353
+ ...resident.map(lineOf),
354
+ ...[...byNamespace.entries()].flatMap(([namespace, group]) => [
355
+ `- namespace \`${namespace}\` (activated):`,
356
+ ...group.map(entry => ` ${lineOf(entry)}`),
357
+ ]),
202
358
  '</available_tools>',
203
359
  ]
204
- const footer = 'This is the complete current list and replaces any earlier available-tools list in this session.'
360
+ const footer = inactive.length === 0
361
+ ? 'This is the complete current list and replaces any earlier available-tools list in this session.'
362
+ : 'This is the current on-wire list and replaces any earlier available-tools list in this session.'
363
+ const inactiveBlock = inactive.length === 0 ? [] : [
364
+ '',
365
+ 'These tool namespaces are registered but currently paged out of the wire:',
366
+ '<inactive_namespaces>',
367
+ ...inactive.map(ns => `- \`${ns.namespace}\` (${ns.count} tool${ns.count === 1 ? '' : 's'}${ns.sample === '' ? '' : `, e.g. \`${ns.sample}\``}): ${ns.description} Call \`tool_activate({ namespace: "${ns.namespace}" })\` to load them onto the wire.`),
368
+ '</inactive_namespaces>',
369
+ ]
370
+ const presentationLines = presentation === 'ptc'
371
+ ? ['', ...PTC_PROGRAM_LINES]
372
+ : presentation === 'both'
373
+ ? ['', ...BOTH_PROGRAM_LINES]
374
+ : []
205
375
  return [
206
376
  '<system-reminder>',
207
377
  'The following tools are available in this session:',
@@ -209,16 +379,24 @@ export function renderCatalogText(entries, ptc) {
209
379
  ...available,
210
380
  '',
211
381
  footer,
212
- ...(ptc ? ['', ...PTC_PROGRAM_LINES] : []),
382
+ ...inactiveBlock,
383
+ ...presentationLines,
213
384
  '</system-reminder>',
214
385
  ].join('\n')
215
386
  }
216
387
 
217
388
  /**
218
- * Overlay the registry projection's fuller schema onto each wire entry, keyed by
219
- * name, so a narrowed native list keeps complete argument semantics even when the
220
- * assembly's own tool object carries a thinner definition. Entries the projection
221
- * does not name, and every entry when no projection is readable, stay untouched.
389
+ * Overlay the registry projection onto each wire entry, keyed by name, so the
390
+ * catalog describes complete argument semantics even when the assembly's own
391
+ * tool object carries a thinner definition.
392
+ *
393
+ * A tool the projection NAMES is authoritative for the parameter field,
394
+ * including its absence: a projected entry that declares no parameters means
395
+ * the tool takes no declared arguments, and the wire's placeholder object
396
+ * (`{ type: 'object', properties: {} }`) would otherwise render the misleading
397
+ * `Record<string, JsonValue>` signature. A tool the projection does not name
398
+ * keeps the wire's own definition, and so does every entry when no projection
399
+ * is readable at all.
222
400
  */
223
401
  export function mergeProjectedSchemas(wireTools, projection) {
224
402
  if (!Array.isArray(projection) || projection.length === 0) return wireTools
@@ -230,7 +408,8 @@ export function mergeProjectedSchemas(wireTools, projection) {
230
408
  const projected = byName.get(tool?.name)
231
409
  if (projected === undefined) return tool
232
410
  const merged = { ...tool }
233
- if (projected.parameters !== undefined) merged.parameters = projected.parameters
411
+ if (projected.parameters === undefined) delete merged.parameters
412
+ else merged.parameters = projected.parameters
234
413
  if (typeof projected.description === 'string' && projected.description.length > 0) {
235
414
  merged.description = projected.description
236
415
  }
@@ -239,11 +418,11 @@ export function mergeProjectedSchemas(wireTools, projection) {
239
418
  }
240
419
 
241
420
  /** Build the durable catalog message for one entry list. */
242
- export function createCatalogMessage(entries, ptc) {
421
+ export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
243
422
  return {
244
423
  id: globalThis.crypto.randomUUID(),
245
424
  role: 'user',
246
- content: [{ type: 'text', text: renderCatalogText(entries, ptc) }],
425
+ content: [{ type: 'text', text: renderCatalogText(entries, presentation, inactive) }],
247
426
  source: { kind: 'plugin', plugin: name },
248
427
  }
249
428
  }
@@ -310,98 +489,222 @@ function withoutMessage(decision, id) {
310
489
  return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
311
490
  }
312
491
 
313
- /** Register the surface staging, the PTC handoff, and the per-step catalog injection. */
492
+ /** Register the presentation declaration, the wire paging, and the per-step catalog injection. */
314
493
  export function apply(ctx, config) {
315
494
  const descriptionMaxLength = integerAtLeast(
495
+ name,
316
496
  config?.descriptionMaxLength,
317
497
  'descriptionMaxLength',
318
498
  1,
319
499
  DEFAULT_DESCRIPTION_MAX_LENGTH,
320
500
  )
321
- const anchorNames = anchorToolNames(config?.anchorTools)
322
- const ptcPlanEnabled = optionalBoolean(config?.ptcPresentation, 'ptcPresentation', true)
501
+ const pagedToolPatterns = validatePagedToolPatterns(name, config?.pagedToolPatterns)
502
+ const maxActiveNamespaces = integerAtLeast(
503
+ name,
504
+ config?.maxActiveNamespaces,
505
+ 'maxActiveNamespaces',
506
+ 1,
507
+ DEFAULT_MAX_ACTIVE_NAMESPACES,
508
+ )
509
+ const maxResidentTokens = integerAtLeast(
510
+ name,
511
+ config?.maxResidentTokens,
512
+ 'maxResidentTokens',
513
+ 1,
514
+ DEFAULT_MAX_RESIDENT_TOKENS,
515
+ )
516
+
517
+ // One-time warnings, per concern so each retired/legacy key reports itself.
518
+ const warned = new Set()
519
+ const warnOnce = (key, detail) => {
520
+ if (warned.has(key)) return
521
+ warned.add(key)
522
+ try {
523
+ ctx.logger?.warn?.(`${name}: ${detail}`)
524
+ } catch {
525
+ // Logger unavailable
526
+ }
527
+ }
528
+
529
+ validateRetiredAnchorTools(config?.anchorTools)
530
+ if (config?.anchorTools !== undefined) {
531
+ warnOnce('anchor', 'anchor-turn staging is retired — the anchorTools key is accepted but no longer narrows the wire')
532
+ }
533
+ const presentation = resolvePresentation(config, detail => warnOnce('ptcPresentation', detail))
323
534
 
324
535
  // Per-agent fresh state evaluated on every assembly (never stale across steps/turns)
325
536
  const agentCatalogState = new WeakMap()
326
537
 
327
- // Session to agent mapping for boundary events
538
+ // Session to agent mapping for lifecycle events
328
539
  const agentBySession = new WeakMap()
329
540
 
330
- // Presentation status tracking per agent
331
- const agentPtcDeclared = new WeakSet()
332
- const agentPtcFailed = new WeakSet()
333
- const agentPtcDisposers = new WeakMap()
541
+ // Presentation declaration tracking per agent scope (one declaration each)
542
+ const agentDeclared = new WeakSet()
543
+ const agentDeclareFailed = new WeakSet()
544
+ const agentDisposers = new WeakMap()
545
+
546
+ // Registry-level paging state, one entry per agent scope: the names the live
547
+ // restriction withholds and the exact disposer that lifts it. Keyed by agent
548
+ // so two sessions assembling at once cannot lift each other's filter, and
549
+ // released with the agent so a departed scope leaves no filter behind.
550
+ const agentPaging = new WeakMap()
551
+
552
+ /** Lift one agent scope's live restriction, if it has one. */
553
+ const clearScopePaging = (agent) => {
554
+ const state = agentPaging.get(agent)
555
+ if (state === undefined) return
556
+ agentPaging.delete(agent)
557
+ try {
558
+ state.dispose()
559
+ } catch (err) {
560
+ warnOnce('paging-dispose', `lifting an earlier tool restriction failed: ${err instanceof Error ? err.message : String(err)}`)
561
+ }
562
+ }
563
+
564
+ /**
565
+ * Recompute one agent scope's page from the durable session event stream and
566
+ * make the registry match it: `deny` masks exactly the names the wire
567
+ * partition would withhold, so the scope still inherits everything else.
568
+ * Scoped registrations are exempt by the registry's own rule, so
569
+ * preset-owned tools can never be filtered away by this.
570
+ *
571
+ * The restriction is what paging MEANS under a collapsed `ptc` wire, where
572
+ * filtering the assembled `tools` array changes nothing a program can reach.
573
+ * It also stores the namespaces it withheld, so the catalog and the live
574
+ * restriction are read from ONE fact instead of two computations.
575
+ *
576
+ * Called OUTSIDE the assembly waterfall, deliberately: see
577
+ * {@link syncBeforeAssembly} for why an in-waterfall sync cannot fix the
578
+ * request it runs in. Returns the stored state, or undefined when the scope
579
+ * needs none — nothing paged, an unusable scoped view, or a refused filter.
580
+ */
581
+ const syncScopePaging = (agent) => {
582
+ clearScopePaging(agent)
583
+
584
+ const tools = agent?.ctx?.tools
585
+ if (tools === undefined || typeof tools.restrict !== 'function') {
586
+ warnOnce('paging-runtime', 'no scoped tools view to page through — the paged namespaces stay reachable through a program in this session')
587
+ return undefined
588
+ }
589
+
590
+ // Read with the restriction lifted (clearScopePaging above), or the
591
+ // withheld names would already be missing and the next sync would find
592
+ // nothing left to withhold. Silent on an unreadable surface: a sync may
593
+ // run before the registry is populated, and "no tools yet" is not the
594
+ // assembly-path emergency that warning describes.
595
+ const fullSurface = quietSchemas(agent) ?? []
596
+ if (fullSurface.length === 0) return undefined
597
+ const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active
598
+ const withheld = withheldToolNames(fullSurface, pagedToolPatterns, active)
599
+ if (withheld.length === 0) return undefined
334
600
 
335
- let warned = false
336
- const warnOnce = (detail) => {
337
- if (warned) return
338
- warned = true
339
601
  try {
340
- ctx.logger?.warn?.(`${name}: ${detail} — keeping the native tool surface`)
341
- } catch {
342
- // Logger unavailable
602
+ const dispose = tools.restrict({ deny: withheld })
603
+ if (typeof dispose !== 'function') {
604
+ warnOnce('paging-runtime', 'the tool registry did not confirm the paging restriction — the paged namespaces stay reachable through a program in this session')
605
+ return undefined
606
+ }
607
+ const state = { active, inactive: inactiveNamespaces(fullSurface, pagedToolPatterns, active), dispose }
608
+ agentPaging.set(agent, state)
609
+ return state
610
+ } catch (err) {
611
+ // A registry that refuses the filter (a name that vanished mid-assembly,
612
+ // a scope that is not scoped after all) must not cost the session its
613
+ // tools: the refused restriction simply does not apply.
614
+ warnOnce('paging-runtime', `paging could not restrict this scope's tools: ${err instanceof Error ? err.message : String(err)} — the paged namespaces stay reachable through a program in this session`)
615
+ return undefined
343
616
  }
344
617
  }
345
618
 
346
- const registry = () => ctx.get('tools')
619
+ /**
620
+ * Bring a scope's page up to date from OUTSIDE the assembly waterfall.
621
+ *
622
+ * `SystemPrompt.assemble()` collects the tool providers AND calls every
623
+ * section's `text(context)` before it runs the `system-prompt/assemble`
624
+ * waterfall, so a restriction installed inside that waterfall cannot change
625
+ * the request it runs for: the `tools:sdk` section has already been rendered
626
+ * from the unrestricted registry. It would take effect one assembly later,
627
+ * leaving a request whose catalog claims a namespace is paged while that
628
+ * request's own SDK section still lists it. Syncing before the providers are
629
+ * collected is what keeps the two consistent from the FIRST `ptc` request.
630
+ *
631
+ * GATED ON THE WIRE ACTUALLY COLLAPSING, not on the configuration asking for
632
+ * it. Both halves of that gate matter, and each covers a deployment where
633
+ * paging at the registry would be wrong:
634
+ * - `presentation === 'ptc'` is what the operator configured, and it excludes
635
+ * `both`, whose documented contract is that a paged-out namespace stays
636
+ * reachable through the SDK inside a program before activation. Installing
637
+ * the restriction there would break that contract for the first request;
638
+ * - `agentDeclared.has(agent)` is the scope's own declaration actually
639
+ * landing, which is NOT the same as `transportReady()`. A deployment with
640
+ * no mounted code runtime (and one whose host declines the declaration)
641
+ * keeps the native wire: the assembled array carries paging by itself, and
642
+ * a registry restriction installed anyway would strip the paged families
643
+ * from that request's native wire — the first request would lose tools it
644
+ * is supposed to have, and the catalog would announce namespaces as
645
+ * withheld that nothing withheld.
646
+ */
647
+ const syncBeforeAssembly = (agent) => {
648
+ if (agent === undefined || presentation !== 'ptc') return undefined
649
+ if (!agentDeclared.has(agent)) return undefined
650
+ return syncScopePaging(agent)
651
+ }
347
652
 
348
- /** Whether PTC is planned and capable in this deployment. */
349
- const ptcPlanReady = () => ptcPlanEnabled && ctx.get('codeRuntime') !== undefined
350
653
 
351
- /** Whether this session is still in its anchor turn. */
352
- const anchoring = (agent) => (
353
- anchorNames.length > 0 && agent !== undefined && inAnchorTurn(sessionEvents(agent?.session))
354
- )
654
+ const registry = () => ctx.get('tools')
655
+ const transportReady = () => presentation !== 'native' && ctx.get('codeRuntime') !== undefined
355
656
 
356
657
  /**
357
- * Declare PTC presentation for one agent using public agent.ctx.tools.presentAs('ptc').
658
+ * Declare this agent scope's presentation through the public
659
+ * agent.ctx.tools.presentAs(mode). One declaration per scope; a refusal is
660
+ * permanent for the agent, a wire miss is retryable.
358
661
  */
359
- const presentPtc = (agent) => {
360
- if (!ptcPlanReady() || agent === undefined) return false
361
- if (agentPtcDeclared.has(agent)) return true
362
- if (agentPtcFailed.has(agent)) return false
662
+ const declarePresentation = (agent) => {
663
+ if (!transportReady() || agent === undefined) return false
664
+ if (agentDeclared.has(agent)) return true
665
+ if (agentDeclareFailed.has(agent)) return false
363
666
 
364
667
  const tools = agent?.ctx?.tools
365
668
  if (tools === undefined || typeof tools.presentAs !== 'function') {
366
- agentPtcFailed.add(agent)
367
- warnOnce('no scoped tools view to declare PTC presentation')
669
+ agentDeclareFailed.add(agent)
670
+ warnOnce('runtime', 'no scoped tools view to declare the presentation through — keeping the native tool surface')
368
671
  return false
369
672
  }
370
673
 
371
674
  try {
372
- const disposer = tools.presentAs('ptc')
373
- agentPtcDeclared.add(agent)
675
+ const disposer = tools.presentAs(presentation)
676
+ agentDeclared.add(agent)
374
677
  if (typeof disposer === 'function') {
375
- agentPtcDisposers.set(agent, disposer)
678
+ agentDisposers.set(agent, disposer)
376
679
  }
377
680
  return true
378
681
  } catch (err) {
379
- agentPtcFailed.add(agent)
380
- warnOnce(`PTC presentation declined: ${err instanceof Error ? err.message : String(err)}`)
682
+ agentDeclareFailed.add(agent)
683
+ warnOnce('runtime', `the "${presentation}" presentation was declined: ${err instanceof Error ? err.message : String(err)} — keeping the native tool surface`)
381
684
  return false
382
685
  }
383
686
  }
384
687
 
385
688
  /**
386
- * Abort/revert PTC declaration if active, restoring presentation back to native.
689
+ * Abort/revert the declaration if active, restoring the native presentation.
387
690
  */
388
- const revertPtc = (agent, reason, retryable = false) => {
691
+ const revertPresentation = (agent, reason, retryable = false) => {
389
692
  if (agent === undefined) return
390
- const disposer = agentPtcDisposers.get(agent)
693
+ const disposer = agentDisposers.get(agent)
391
694
  if (typeof disposer === 'function') {
392
695
  try {
393
696
  disposer()
394
697
  } catch {
395
698
  // Ignore disposer error
396
699
  }
397
- agentPtcDisposers.delete(agent)
700
+ agentDisposers.delete(agent)
398
701
  }
399
- agentPtcDeclared.delete(agent)
702
+ agentDeclared.delete(agent)
400
703
  // A declaration the host itself refused is permanent for this agent. One that
401
- // merely failed to reach a wire is not: the next turn boundary may declare
402
- // again, and latching it would strand the session on the native surface.
403
- if (!retryable) agentPtcFailed.add(agent)
404
- warnOnce(reason)
704
+ // merely failed to reach a wire is not: the next assembly may declare again,
705
+ // and latching it would strand the session on the native surface.
706
+ if (!retryable) agentDeclareFailed.add(agent)
707
+ warnOnce('runtime', `${reason} — keeping the native tool surface`)
405
708
  }
406
709
 
407
710
  /**
@@ -420,6 +723,25 @@ export function apply(ctx, config) {
420
723
  return scoped ?? reg
421
724
  }
422
725
 
726
+ /**
727
+ * Read the scope's model-facing surface without the assembly path's warning.
728
+ * Returns undefined when no projection is readable at all.
729
+ */
730
+ const quietSchemas = (agent) => {
731
+ const tools = resolveToolsService(agent)
732
+ if (tools === undefined) return undefined
733
+ for (const method of ['schemas', 'sdkSchemas']) {
734
+ if (typeof tools[method] !== 'function') continue
735
+ try {
736
+ const schemas = tools[method](agent)
737
+ if (Array.isArray(schemas)) return schemas.filter(entry => entry?.name && entry.name !== 'run_code')
738
+ } catch {
739
+ // Try the next source; an unreadable registry is not fatal here.
740
+ }
741
+ }
742
+ return undefined
743
+ }
744
+
423
745
  const publicSchemas = (agent) => {
424
746
  const tools = resolveToolsService(agent)
425
747
  if (tools === undefined) return undefined
@@ -432,7 +754,7 @@ export function apply(ctx, config) {
432
754
  }
433
755
  return undefined
434
756
  } catch {
435
- warnOnce('no tool schemas available')
757
+ warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
436
758
  return undefined
437
759
  }
438
760
  }
@@ -445,181 +767,251 @@ export function apply(ctx, config) {
445
767
  return filtered.length > 0 ? filtered : undefined
446
768
  }
447
769
  } catch {
448
- warnOnce('no tool schemas available')
770
+ warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
449
771
  return undefined
450
772
  }
451
773
  }
452
774
  return undefined
453
775
  }
454
776
 
455
- /**
456
- * The catalog the NEXT request will expose, resolved from the current
457
- * presentation state rather than from the previous assembly.
458
- *
459
- * A turn boundary declares PTC before the promoted turn's first step, but that
460
- * turn's assembly has not run yet, so the stored state would still describe the
461
- * anchor wire. Resolving the projection here keeps the published catalog in step
462
- * with the transport the request is about to carry.
463
- */
464
- const catalogStateFor = (agent) => {
465
- if (agent === undefined) return undefined
466
- if (!anchoring(agent) && ptcPlanReady() && agentPtcDeclared.has(agent)) {
467
- const schemas = publicSchemas(agent)
468
- if (schemas !== undefined && schemas.length > 0) {
469
- return { entries: catalogEntries(schemas, descriptionMaxLength), ptc: true }
470
- }
471
- }
472
- return agentCatalogState.get(agent)
473
- }
474
-
475
- // Early lifecycle hooks: declare PTC ahead of prompt assembly
476
- ctx.on('agent/created', (agent) => {
777
+ // Early lifecycle hooks: declare the presentation and page the scope as soon
778
+ // as it exists.
779
+ //
780
+ // The payload is destructured ON PURPOSE: `agent/created` and
781
+ // `agent/session-start` pass their payload OBJECT as the first argument, not
782
+ // the agent itself. Reading that parameter as the agent yields an object
783
+ // with no `session` and no `ctx`, so the declaration is skipped and paging
784
+ // silently never engages.
785
+ ctx.on('agent/created', ({ agent }) => {
477
786
  if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
478
- if (!anchoring(agent) && ptcPlanReady()) {
479
- presentPtc(agent)
480
- }
787
+ if (transportReady()) declarePresentation(agent)
788
+ // The session log is readable here, and this runs before the first turn
789
+ // assembles a prompt, so a scope created over an existing (resumed)
790
+ // session is paged before its FIRST assembly rather than one request late.
791
+ syncBeforeAssembly(agent)
481
792
  })
482
793
 
483
- ctx.on('agent/session-start', (agent, session) => {
484
- if (session !== undefined && agent !== undefined) agentBySession.set(session, agent)
485
- if (!anchoring(agent) && ptcPlanReady()) {
486
- presentPtc(agent)
487
- }
794
+ // A departed scope must not keep a registry restriction behind: the layer is
795
+ // keyed by the agent, and a recycled key would inherit a stale filter.
796
+ ctx.on('agent/disposed', ({ agent }) => {
797
+ agentCatalogState.delete(agent)
798
+ clearScopePaging(agent)
488
799
  })
489
800
 
490
- // Turn boundary session events
491
- ctx.on('session/event', (session, event) => {
492
- if (event?.type !== 'turn/start' && event?.type !== 'turn/end') return
493
- const agent = session === undefined ? undefined : agentBySession.get(session)
494
- if (agent === undefined || anchoring(agent) || !ptcPlanReady()) return
495
- presentPtc(agent)
801
+ /**
802
+ * Re-sync after a call that can move the active set.
803
+ *
804
+ * Every window between assemblies is the right one to fix the NEXT one, and
805
+ * this fires at the end of each tool call: a `tool_activate` and the calls
806
+ * that refresh a namespace's recency are exactly the events the paging
807
+ * replay reads, so the restriction and the catalog are back in step long
808
+ * before the next prompt is assembled. Declared concurrency-safe so it never
809
+ * serializes independent read-only calls.
810
+ */
811
+ ctx.on('tools/post-execute', (exec, _result, next) => {
812
+ syncBeforeAssembly(exec?.agent)
813
+ return next()
814
+ }, { prepend: true })
815
+
816
+ ctx.on('agent/session-start', ({ agent }) => {
817
+ if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
818
+ if (transportReady()) declarePresentation(agent)
819
+ // The last point before the first turn assembles a prompt: a resumed
820
+ // session starts its first request already paged.
821
+ syncBeforeAssembly(agent)
496
822
  })
497
823
 
498
824
  // Per-agent, not one process-wide flag: two sessions assembling at once would
499
- // otherwise let one skip the promotion re-assembly the other is running.
825
+ // otherwise let one skip the re-assembly the other is running.
500
826
  const reassembling = new WeakSet()
501
827
 
502
828
  ctx.on('system-prompt/assemble', async (assembly, context, next) => {
503
829
  const agent = context?.agent
504
- const staged = anchoring(agent)
505
830
 
506
831
  if (agent !== undefined && agent.session !== undefined) {
507
832
  agentBySession.set(agent.session, agent)
508
833
  }
509
834
 
510
- let ptcDeclared = false
511
- if (!staged && ptcPlanReady()) {
512
- if (!agentPtcDeclared.has(agent)) {
513
- // A promotion collapses the wire to the single `run_code` transport and
514
- // lists the tools from their SDK projection. Where no projection can be read
515
- // at all, declaring would collapse the executor and then have to undo it,
516
- // losing the native wire on the way out. Stay native instead.
517
- const projectable = publicSchemas(agent)
518
- if (projectable === undefined || projectable.length === 0) {
519
- warnOnce('no tool schema projection available; keeping the native tool surface')
520
- ptcDeclared = false
521
- } else {
522
- ptcDeclared = presentPtc(agent)
523
- }
835
+ if (agent !== undefined && !agentDeclared.has(agent) && transportReady()) {
836
+ // Under 'ptc' a declaration collapses the wire to the single `run_code`
837
+ // transport and lists the tools from their SDK projection. Where no
838
+ // projection can be read at all, declaring would collapse the executor and
839
+ // then have to undo it, losing the native wire on the way out. Stay native
840
+ // instead. Under 'both' the native roster stays on the wire either way, so
841
+ // the declaration needs no projection guard.
842
+ const projectable = publicSchemas(agent)
843
+ if (presentation === 'ptc' && (projectable === undefined || projectable.length === 0)) {
844
+ warnOnce('runtime', 'no tool schema projection available — keeping the native tool surface')
845
+ } else {
846
+ const declaredNow = declarePresentation(agent)
524
847
  // A declaration made here cannot reach THIS assembly: the harness collects
525
- // the tool providers before the waterfall runs. Re-assemble so the collapse
526
- // and the generated SDK land on the assembly the model actually receives.
527
- if (ptcDeclared && !reassembling.has(agent)) {
848
+ // the tool providers before the waterfall runs. Re-assemble so the
849
+ // presentation lands on the assembly the model actually receives.
850
+ if (declaredNow && !reassembling.has(agent)) {
528
851
  const sp = ctx.get('systemPrompt')
529
852
  if (typeof sp?.assemble === 'function') {
530
853
  reassembling.add(agent)
531
854
  try {
532
855
  return await sp.assemble(context)
533
856
  } catch (error) {
534
- warnOnce(`re-assembling after the PTC declaration failed: ${error instanceof Error ? error.message : String(error)}`)
857
+ warnOnce('runtime', `re-assembling after the presentation declaration failed: ${error instanceof Error ? error.message : String(error)}`)
535
858
  } finally {
536
859
  reassembling.delete(agent)
537
860
  }
538
861
  }
539
- // Nothing re-assembled, so this wire stays native. Collapsing the executor
540
- // under it would announce a transport the request never names, so drop back
541
- // to native for this assembly and let the next turn boundary declare again.
542
- revertPtc(agent, 'the PTC declaration did not reach this assembly wire', true)
543
- ptcDeclared = false
862
+ // Nothing re-assembled, so this wire stays native. Presenting a transport
863
+ // the request never names would lie to the model, so drop back to native
864
+ // for this assembly and let the next assembly declare again.
865
+ revertPresentation(agent, `the "${presentation}" declaration did not reach this assembly wire`, true)
544
866
  }
545
- } else {
546
- ptcDeclared = true
547
867
  }
548
868
  }
549
869
 
550
- // The registry projection names every tool the session can reach. Under PTC the
551
- // request opens only `run_code`, so the projection is what the catalog lists;
552
- // under native presentation the catalog must name exactly the tools this request
553
- // carries, or the model is told about a surface it cannot call.
554
- let surface = agent !== undefined ? publicSchemas(agent) : undefined
870
+ // A declaration that just landed here (a scope no lifecycle hook could
871
+ // reach) pages the scope before the re-assembly collects its providers, so
872
+ // that request renders a page-consistent SDK section too. Idempotent: a
873
+ // scope already paged by its lifecycle hook re-derives the same state.
874
+ if (agent !== undefined && agentDeclared.has(agent)) syncBeforeAssembly(agent)
555
875
 
876
+ // Delegate first: the assembled value stays authoritative for the wire (a
877
+ // presentation declared inside this waterfall reaches the NEXT assembly,
878
+ // which is why a declaration is followed by a re-assembly).
556
879
  const assembled = await next()
557
880
 
558
- const wireTools = Array.isArray(assembled?.tools) ? assembled.tools : []
559
- const wireHasRunCode = wireTools.some(t => t?.name === 'run_code')
560
- const wireOnlyRunCode = wireTools.length > 0 && wireTools.every(t => t?.name === 'run_code')
561
-
562
- // If wire carries only run_code but public schemas are unavailable or empty:
563
- // Revert PTC to native and restore wire to native schemas.
564
- // The replacement travels in the RETURNED assembly: the waterfall's returned
565
- // value is the authoritative one, and mutating the object the harness handed
566
- // downstream would be a side effect no other listener can see.
881
+ const assembledTools = Array.isArray(assembled?.tools) ? assembled.tools : undefined
882
+ const wireHasRunCode = (assembledTools ?? []).some(t => t?.name === 'run_code')
883
+ const wireOnlyRunCode = assembledTools !== undefined && assembledTools.length > 0 && assembledTools.every(t => t?.name === 'run_code')
884
+
885
+ // The paging restriction was installed OUTSIDE this waterfall (see
886
+ // {@link syncBeforeAssembly}) because `assemble()` renders the sections and
887
+ // collects the providers before the waterfall runs: installing it here
888
+ // would leave the request it runs for with a catalog that claims a
889
+ // namespace is paged and a `tools:sdk` section that still lists it. What
890
+ // this waterfall does with it is read the SAME state the restriction was
891
+ // built from, so the catalog never describes a different page than the one
892
+ // the registry enforces.
893
+ const pagingState = agent === undefined ? undefined : agentPaging.get(agent)
894
+
895
+ // Under a collapsed `ptc` wire the registry is the ONLY surface a tool can
896
+ // be reached through, so the page is expressed as a registry restriction.
897
+ // Every other wire still carries paging by itself on the assembled array,
898
+ // and `both` deliberately stays unrestricted: that is what keeps its
899
+ // documented "paged namespaces stay reachable through the SDK inside a
900
+ // program" behavior intact. A wire that carries the native roster again (a
901
+ // reverted declaration) must also drop a page left over from a collapsed
902
+ // assembly, or the filter would keep hiding tools that wire just handed
903
+ // back.
904
+ let surface = agent !== undefined ? publicSchemas(agent) : undefined
905
+ // The wire partition replays the durable log itself: `pagingState` exists
906
+ // only where a restriction was installed (the collapsed ptc wire), and
907
+ // native/both still page the assembled array from the same event stream.
908
+ const activeNamespaces = new Set(
909
+ replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active,
910
+ )
911
+ if (agent !== undefined && !wireOnlyRunCode && pagingState !== undefined) clearScopePaging(agent)
912
+
913
+ // If the wire carries only run_code but no projection is readable, revert to
914
+ // native and restore the native wire. The replacement travels in the RETURNED
915
+ // assembly: the waterfall's returned value is the authoritative one, and
916
+ // mutating the object the harness handed downstream would be a side effect no
917
+ // other listener can see.
567
918
  let correctedWire
568
919
  if (wireOnlyRunCode && (surface === undefined || surface.length === 0)) {
569
- revertPtc(agent, 'no tool schema projection available under PTC')
570
- ptcDeclared = false
920
+ revertPresentation(agent, 'no tool schema projection available under PTC')
571
921
  const nativeSchemas = publicSchemas(agent) ?? []
572
922
  surface = nativeSchemas
573
923
  correctedWire = nativeSchemas
574
924
  }
575
925
 
576
- // PTC is what the WIRE carries, not what the configuration intends: the catalog
577
- // must describe the transport this request actually names, or the model is told
578
- // to call `run_code` on a request that offers only native tools.
579
- const isActualPtc = !staged && wireHasRunCode && surface !== undefined && surface.length > 0
580
-
581
- // The effective wire of THIS request includes the anchor narrowing, so the native
582
- // catalog narrows with the schemas the model can actually call instead of
583
- // advertising the promoted roster the anchor turn does not expose.
584
- const effectiveWire = correctedWire ?? assembled.tools
585
- const nativeTools = (Array.isArray(effectiveWire) ? effectiveWire : [])
586
- .filter(t => t?.name && t.name !== 'run_code')
587
- const anchoredTools = staged ? anchorToolsOf(nativeTools, anchorNames) : nativeTools
588
- const catalogTools = isActualPtc ? surface : mergeProjectedSchemas(anchoredTools, surface)
926
+ const effectiveWire = correctedWire ?? assembledTools
927
+ const effectiveHasRunCode = (effectiveWire ?? []).some(t => t?.name === 'run_code')
928
+ const effectiveOnlyRunCode = effectiveWire !== undefined && effectiveWire.length > 0 && effectiveWire.every(t => t?.name === 'run_code')
929
+
930
+ // The catalog describes the transport this request actually carries, never
931
+ // the configuration's intent: a collapsed wire is 'ptc', run_code beside the
932
+ // native roster is 'both', and anything else is native.
933
+ const effectivePresentation = effectiveOnlyRunCode ? 'ptc' : (effectiveHasRunCode ? 'both' : 'native')
934
+
935
+ // Gentle paging: the active namespaces were replayed from the durable event
936
+ // stream above; here the paged-but-inactive tools come off the wire itself.
937
+ // run_code and the resident roster never match the paging patterns.
938
+ const { resident, inactive } = partitionWireTools(effectiveWire, pagedToolPatterns, activeNamespaces)
939
+
940
+ // Diagnostic guard on the always-on-wire surface. It warns rather than
941
+ // truncates: silently dropping a tool the session needs would trade a
942
+ // measurable context cost for an unmeasurable capability loss.
943
+ const residentTokens = estimateSurfaceTokens(resident)
944
+ if (residentTokens > maxResidentTokens) {
945
+ // Name the heaviest tools so the remedy is actionable rather than a bare number.
946
+ const heaviest = [...resident]
947
+ .map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
948
+ .sort((left, right) => right.tokens - left.tokens)
949
+ .slice(0, 3)
950
+ .map(entry => `${entry.name} (${entry.tokens})`)
951
+ .join(', ')
952
+ 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`)
953
+ }
589
954
 
590
- const entries = catalogEntries(catalogTools, descriptionMaxLength)
955
+ // The catalog describes this request's ACTUAL surface: with a live page it
956
+ // summarizes exactly the namespaces that page withholds (the same fact the
957
+ // restriction was built from), and otherwise the namespaces the WIRE
958
+ // partition found — which under `both` stay reachable through the SDK
959
+ // inside a program, as the programmatic-escape note below states.
960
+ const catalogInactive = summarizeInactive(
961
+ pagingState?.inactive ?? inactive,
962
+ describe => catalogDescription(describe, descriptionMaxLength),
963
+ )
964
+
965
+ let entries
966
+ if (effectivePresentation === 'ptc') {
967
+ // Under the collapsed transport the request opens only run_code, so the
968
+ // catalog lists the SDK-reachable projection instead of the wire.
969
+ entries = catalogEntries(surface ?? [], descriptionMaxLength, { patterns: pagedToolPatterns })
970
+ } else {
971
+ const merged = mergeProjectedSchemas(resident, surface)
972
+ entries = catalogEntries(merged, descriptionMaxLength, {
973
+ includeRunCode: effectivePresentation === 'both',
974
+ patterns: pagedToolPatterns,
975
+ })
976
+ }
977
+ const inactiveSummary = catalogInactive
591
978
 
592
979
  // Store fresh state on agent
593
980
  if (agent !== undefined) {
594
981
  agentCatalogState.set(agent, {
595
982
  entries,
596
- ptc: isActualPtc,
983
+ presentation: effectivePresentation,
984
+ inactive: inactiveSummary,
597
985
  })
598
986
  }
599
987
 
600
- if (!staged) return correctedWire === undefined ? assembled : { ...assembled, tools: correctedWire }
601
- return { ...assembled, tools: anchorToolsOf(effectiveWire, anchorNames) }
988
+ if (assembledTools === undefined) return assembled
989
+ // Keep the caller's own assembly object whenever this pass neither corrected
990
+ // a collapsed wire nor lifted a paged tool off it: a needless copy would hand
991
+ // downstream listeners a different object for no behavioral reason.
992
+ const unchanged = correctedWire === undefined && resident.length === assembledTools.length
993
+ return unchanged ? assembled : { ...assembled, tools: resident }
602
994
  }, { prepend: true })
603
995
 
604
996
  ctx.on('agent/pre-step', async (payload, next) => {
605
997
  const decision = await next()
606
998
  if (decision.kind !== 'enter') return decision
607
999
  const agent = payload?.agent
608
- const state = catalogStateFor(agent)
1000
+ const state = agent === undefined ? undefined : agentCatalogState.get(agent)
609
1001
  if (state === undefined) return decision
610
1002
 
611
- const { entries, ptc } = state
612
- const candidate = renderCatalogText(entries, ptc)
1003
+ const { entries, presentation: statePresentation, inactive } = state
1004
+ const candidate = renderCatalogText(entries, statePresentation, inactive)
613
1005
  const history = catalogHistory(agent)
614
1006
  const existing = catalogMessage(decision.messages)
615
1007
  if (history.text === candidate) {
616
1008
  return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
617
1009
  }
618
1010
  if (existing !== undefined && existing.text === candidate) return decision
619
- if (!history.published && entries.length === 0) {
1011
+ if (!history.published && entries.length === 0 && inactive.length === 0) {
620
1012
  return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
621
1013
  }
622
- const catalog = createCatalogMessage(entries, ptc)
1014
+ const catalog = createCatalogMessage(entries, statePresentation, inactive)
623
1015
  if (existing === undefined) {
624
1016
  return { ...decision, messages: [...decision.messages, catalog] }
625
1017
  }