@linxin666/dsh-liangshen 0.3.21 → 0.3.23

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,69 +1,20 @@
1
1
  /**
2
- * tool-catalog — this preset's staged model-visible tool surface: the anchor
3
- * turn's wire, the PTC handoff at the turn boundary, and the durable catalog
4
- * message that names the surface.
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.
5
4
  *
6
- * WHY: the preset's system prompt stays on the builtin Minimal preset's
7
- * one-line persona, so the tool-guidance sections the Standard prompt carries
8
- * are absent, and `minimal-prompt` narrows every assembly down to the persona
9
- * section — including the harness's own `tools:sdk` and `tools:ptc-only`
10
- * sections. The capability facts therefore travel as a user message at the
11
- * prompt tail (Layer 3), the way `dsh-tool-skill` injects the skill catalog,
12
- * and that message is the model's only source for the SDK bindings, for the
13
- * rule that only `run_code` may be called directly, and for the program contract
14
- * the harness states in those same filtered sections: one program per intent,
15
- * overlapping independent reads under `Promise.all`, `ToolCallError` handling,
16
- * and curated program output.
17
- *
18
- * ANCHOR TURN: the assembled wire tool list is narrowed to `anchorTools`
19
- * before the request carries it, and the session still presents tools natively.
20
- * The shipped preset anchors on `bash` alone — the builtin Minimal surface —
21
- * so the first request carries the shell schema and nothing else.
22
- *
23
- * PTC HANDOFF: from the session's second turn on, this plugin declares PTC
24
- * presentation for that agent alone (`agent.ctx.tools.presentAs('ptc')`), so
25
- * the wire carries the single reserved `run_code` transport and every other
26
- * tool is reached from inside the program through the generated SDK. The
27
- * harness collects the tool providers BEFORE it runs the `system-prompt/
28
- * assemble` waterfall, so a declaration made inside that waterfall cannot
29
- * affect the assembly it is made in: the plugin declares on the boundary
30
- * session events instead — the anchor turn's `turn/end` and the second turn's
31
- * `turn/start` — which are emitted before the promoted turn's first assembly
32
- * reads the wire, and the assembly listener re-asserts the declaration for a
33
- * session whose boundary was crossed while this plugin was not observing
34
- * events (a host restart mid-turn). There the collapse lands one assembly
35
- * later, and the catalog text does not depend on it. Reading the boundary from
36
- * the durable log (not memory) keeps it stable across resume, reload, and
37
- * compaction. The switch needs a mounted code runtime, and the SDK section it
38
- * registers is evaluated during every assembly: without a runtime the plugin
39
- * stays native instead of failing the session, and a failed switch degrades
40
- * the same way with a one-time warning.
41
- *
42
- * CATALOG CONTENT: the entries are the PTC surface — the registry's visible
43
- * tools minus `run_code`, each named with its compact argument signature and a
44
- * one-line description — read from the registry (`ctx.tools.sdkSchemas`) so the
45
- * list does not depend on which surface the current request happens to carry.
46
- * The first turn therefore already names every tool the promoted turn reaches,
47
- * the way the skill catalog names skills the model loads on demand. When the
48
- * registry or its SDK projection is unavailable the entries fall back to the
49
- * assembled wire schemas, so the mode still publishes a truthful list.
50
- *
51
- * DEDUPE: the message is durable, so publishing it every step would append a
52
- * copy per step. The rendering is a pure function of the entry list and the
53
- * presentation plan, and the published copy is read back from the durable log,
54
- * so a step republishes only when the rendered text actually differs from the
55
- * last catalog message still on the session's visible surface (a changed tool
56
- * set, or a copy a compaction shadowed). Nothing is kept in memory across
57
- * steps, so resume and reload reconstruct the same decision.
58
- *
59
- * SOURCE SHAPE: the message source carries ONLY `{ kind: 'plugin', plugin }`.
60
- * That is the same shape the instruction hint uses, and it stays inside the
61
- * durable validator's `plugin` field set (`kind`, `plugin`, `form`, `sections`,
62
- * `summary`) — an extra field would be rejected the moment the harness applies
63
- * that whitelist to V3 user messages the way it already does to V3
64
- * `system/message` events. `plugin` is also the only injected kind the v2->v3
65
- * migration whitelist and the v3 MessageSourceMap both classify (#1455), and
66
- * the message text itself is what identifies a stale catalog.
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.
67
18
  */
68
19
 
69
20
  /** Cordis plugin name used by loader diagnostics. */
@@ -72,13 +23,13 @@ export const name = 'liangshen-tool-catalog'
72
23
  /** Prompt assembly must exist before the wire catalog can be observed. */
73
24
  export const inject = ['systemPrompt']
74
25
 
75
- /** Default cap for one tool's one-line summary in the injected list. */
26
+ /** Default cap for one tool's one-line summary in the injected compact list. */
76
27
  const DEFAULT_DESCRIPTION_MAX_LENGTH = 200
77
28
 
78
29
  /**
79
- * Nesting depth beyond which an inline signature degrades to `JsonValue`. The
30
+ * Nesting depth beyond which an inline signature degrades to JsonValue. The
80
31
  * rendering stays one line per tool, so deeply nested argument objects are
81
- * summarized rather than expanded into a wall of text.
32
+ * summarized in the inline summary rather than expanded into an unreadable line.
82
33
  */
83
34
  const MAX_SIGNATURE_DEPTH = 4
84
35
 
@@ -101,7 +52,7 @@ function optionalBoolean(value, field, fallback) {
101
52
  return value
102
53
  }
103
54
 
104
- /** Parse the `anchorTools` config: absent means staging off, entries must be non-empty names. */
55
+ /** Parse the anchorTools config: absent means staging off, entries must be non-empty names. */
105
56
  function anchorToolNames(value) {
106
57
  if (value === undefined) return []
107
58
  if (!Array.isArray(value)) {
@@ -116,12 +67,8 @@ function anchorToolNames(value) {
116
67
  }
117
68
 
118
69
  /**
119
- * Whether the session is still in its anchor turn: fewer than two `turn/start`
120
- * events and no `turn/end` yet, so the anchor covers the whole first turn even
121
- * when it takes several steps. The count is read from the log on every
122
- * decision, so resume, reload, and compaction cannot lose or revive the
123
- * boundary, and a first turn that ends without a reply still promotes at the
124
- * next one.
70
+ * Whether the session is still in its anchor turn: fewer than two turn/start
71
+ * events and no turn/end yet.
125
72
  */
126
73
  export function inAnchorTurn(events) {
127
74
  let turns = 0
@@ -144,11 +91,11 @@ export function anchorToolsOf(tools, names) {
144
91
 
145
92
  /**
146
93
  * One-line model-facing summary of a tool description: whitespace collapsed,
147
- * truncated with an ellipsis. The full description stays in the tool schema.
94
+ * truncated with an ellipsis when maxLength is specified.
148
95
  */
149
96
  export function catalogDescription(value, maxLength) {
150
97
  const normalized = String(value ?? '').replaceAll(/\s+/g, ' ').trim()
151
- if (normalized.length <= maxLength) return normalized
98
+ if (maxLength === undefined || maxLength <= 0 || normalized.length <= maxLength) return normalized
152
99
  return `${normalized.slice(0, maxLength - 3)}...`
153
100
  }
154
101
 
@@ -159,10 +106,8 @@ function renderLiteral(value) {
159
106
  }
160
107
 
161
108
  /**
162
- * One JSON-Schema node as compact TypeScript-ish text: scalars, `const`/`enum`
163
- * literals, unions (`oneOf` / `anyOf` / array-typed `type`), arrays, and inline
164
- * object literals. Unsupported or malformed nodes degrade to `JsonValue`, so a
165
- * hostile schema can only cost precision, never throw during assembly.
109
+ * One JSON-Schema node as compact TypeScript-ish text for inline signatures.
110
+ * Bounded by MAX_SIGNATURE_DEPTH so inline signatures remain single-line.
166
111
  */
167
112
  export function renderJsonSchemaType(schema, depth = 0) {
168
113
  if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return 'JsonValue'
@@ -199,9 +144,8 @@ export function renderJsonSchemaType(schema, depth = 0) {
199
144
 
200
145
  /**
201
146
  * The parenthesized argument signature of one tool, e.g.
202
- * `({ command: string, timeoutMs?: number })`. Empty when the parameter schema
203
- * carries nothing to say (a typeless schema): the entry then renders as a bare
204
- * name rather than as an argument list the model would have to unlearn.
147
+ * ({ command: string, timeoutMs?: number }). Empty when the parameter schema
148
+ * carries nothing to say.
205
149
  */
206
150
  export function renderSignature(parameters) {
207
151
  if (parameters === null || typeof parameters !== 'object' || Array.isArray(parameters)) return ''
@@ -211,14 +155,14 @@ export function renderSignature(parameters) {
211
155
 
212
156
  /**
213
157
  * Catalog entries for one tool surface, sorted by name so an unchanged surface
214
- * renders byte-identical text across assemblies. Nameless definitions are
215
- * skipped.
158
+ * renders byte-identical text across assemblies. Nameless definitions and
159
+ * the run_code transport tool are skipped.
216
160
  */
217
161
  export function catalogEntries(schemas, maxLength) {
218
162
  const entries = []
219
163
  for (const schema of Array.isArray(schemas) ? schemas : []) {
220
164
  const toolName = schema?.name
221
- if (typeof toolName !== 'string' || toolName === '') continue
165
+ if (typeof toolName !== 'string' || toolName === '' || toolName === 'run_code') continue
222
166
  entries.push({
223
167
  name: toolName,
224
168
  signature: renderSignature(schema.parameters),
@@ -229,14 +173,7 @@ export function catalogEntries(schemas, maxLength) {
229
173
  }
230
174
 
231
175
  /**
232
- * The program contract the injected message carries under PTC: the usage
233
- * instructions the harness renders in its own `tools:sdk` section — which
234
- * `minimal-prompt` filters out of the system prompt along with the SDK
235
- * declarations — restated in our own wording so the injected text is identical
236
- * on both sides of the presentation boundary and the promotion forces no
237
- * republish. `@deepseek-ai/dsh-tools` owns the contract; its parallel cap
238
- * (`maxParallelSubCalls`) defaults to 10, which is what makes the overlap rule
239
- * worth stating.
176
+ * The program contract the injected message carries under PTC.
240
177
  */
241
178
  const PTC_PROGRAM_LINES = [
242
179
  '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:',
@@ -246,15 +183,15 @@ const PTC_PROGRAM_LINES = [
246
183
  '- a failed call rejects with `ToolCallError`, whose `toolName` and human-readable message identify it — `try/catch` it to continue;',
247
184
  '- 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.',
248
185
  '',
249
- "`run_code` is the only tool that can be called directly once it is on the wire; the session's first turn carries the shell alone.",
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.",
250
187
  ]
251
188
 
252
189
  /**
253
- * Model-facing catalog text. Deliberately one stable rendering for both the
254
- * first publication and a replacement: the text is then the complete record of
255
- * what was published, so a republish decision needs no field beyond it. The PTC
256
- * sentence is part of that record because the presentation plan is a deployment
257
- * fact, not a per-step one.
190
+ * 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.
258
195
  */
259
196
  export function renderCatalogText(entries, ptc) {
260
197
  const available = entries.length === 0
@@ -264,8 +201,7 @@ export function renderCatalogText(entries, ptc) {
264
201
  ...entries.map(entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`),
265
202
  '</available_tools>',
266
203
  ]
267
- const footer = "This is the complete current list and replaces any earlier available-tools list in this session. "
268
- + "It carries each tool's argument signature and a one-line summary; the full parameter schema travels with its own tool definition."
204
+ const footer = 'This is the complete current list and replaces any earlier available-tools list in this session.'
269
205
  return [
270
206
  '<system-reminder>',
271
207
  'The following tools are available in this session:',
@@ -278,12 +214,33 @@ export function renderCatalogText(entries, ptc) {
278
214
  ].join('\n')
279
215
  }
280
216
 
217
+ /**
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.
222
+ */
223
+ export function mergeProjectedSchemas(wireTools, projection) {
224
+ if (!Array.isArray(projection) || projection.length === 0) return wireTools
225
+ const byName = new Map()
226
+ for (const schema of projection) {
227
+ if (typeof schema?.name === 'string' && schema.name !== '') byName.set(schema.name, schema)
228
+ }
229
+ return wireTools.map((tool) => {
230
+ const projected = byName.get(tool?.name)
231
+ if (projected === undefined) return tool
232
+ const merged = { ...tool }
233
+ if (projected.parameters !== undefined) merged.parameters = projected.parameters
234
+ if (typeof projected.description === 'string' && projected.description.length > 0) {
235
+ merged.description = projected.description
236
+ }
237
+ return merged
238
+ })
239
+ }
240
+
281
241
  /** Build the durable catalog message for one entry list. */
282
242
  export function createCatalogMessage(entries, ptc) {
283
243
  return {
284
- // Session persistence validates every replayed user/message for a
285
- // non-empty string id; a plugin-built message without one corrupts the
286
- // durable journal (SessionPersistenceCorruptionError on load).
287
244
  id: globalThis.crypto.randomUUID(),
288
245
  role: 'user',
289
246
  content: [{ type: 'text', text: renderCatalogText(entries, ptc) }],
@@ -307,8 +264,7 @@ function isCatalogMessage(message) {
307
264
  }
308
265
 
309
266
  /**
310
- * Session events, tolerating both the current `snapshotEvents()` accessor and
311
- * the older mutable `events` array (SDK 0.1.2-alpha.4 renamed it).
267
+ * Session events, tolerating both snapshotEvents() and events array.
312
268
  */
313
269
  function sessionEvents(session) {
314
270
  if (Array.isArray(session?.events)) return session.events
@@ -323,11 +279,7 @@ function visibleSeqSet(session) {
323
279
  }
324
280
 
325
281
  /**
326
- * Published catalog state read back from the durable log: the text of the most
327
- * recent catalog message still on the visible surface, plus whether any catalog
328
- * was ever published. A resumed, forked, or externally written seed may hold an
329
- * unusable record, so one is skipped rather than throwing inside the step
330
- * listener (which would fail every later turn).
282
+ * Published catalog state read back from durable log.
331
283
  */
332
284
  function catalogHistory(agent) {
333
285
  const session = agent?.session
@@ -367,24 +319,19 @@ export function apply(ctx, config) {
367
319
  DEFAULT_DESCRIPTION_MAX_LENGTH,
368
320
  )
369
321
  const anchorNames = anchorToolNames(config?.anchorTools)
370
- const ptcEnabled = optionalBoolean(config?.ptcPresentation, 'ptcPresentation', true)
322
+ const ptcPlanEnabled = optionalBoolean(config?.ptcPresentation, 'ptcPresentation', true)
371
323
 
372
- // The last observed catalog for each live agent — the registry's SDK surface
373
- // when it publishes one, else the assembled wire schemas. `prepend: true`
374
- // makes this listener outermost, so the anchor narrowing covers what
375
- // `next()` returned.
376
- const catalogByAgent = new WeakMap()
324
+ // Per-agent fresh state evaluated on every assembly (never stale across steps/turns)
325
+ const agentCatalogState = new WeakMap()
377
326
 
378
- // Session to agent, so the boundary events a session emits can reach the
379
- // per-agent presentation declaration. Filled by every assembly.
327
+ // Session to agent mapping for boundary events
380
328
  const agentBySession = new WeakMap()
381
329
 
382
- // Agents whose PTC declaration already ran. Keyed by agent so a resumed or
383
- // reloaded session re-declares it from the durable turn count, and latched
384
- // before the call so a failing declaration warns once instead of per step.
385
- const ptcAgents = new WeakSet()
330
+ // Presentation status tracking per agent
331
+ const agentPtcDeclared = new WeakSet()
332
+ const agentPtcFailed = new WeakSet()
333
+ const agentPtcDisposers = new WeakMap()
386
334
 
387
- // One-time warnings: a broken optional path must degrade, never spam.
388
335
  let warned = false
389
336
  const warnOnce = (detail) => {
390
337
  if (warned) return
@@ -392,110 +339,276 @@ export function apply(ctx, config) {
392
339
  try {
393
340
  ctx.logger?.warn?.(`${name}: ${detail} — keeping the native tool surface`)
394
341
  } catch {
395
- // Logger unavailable — the guard exists only to avoid spamming.
342
+ // Logger unavailable
396
343
  }
397
344
  }
398
345
 
399
- // Read without `inject`: the catalog is the mode's core, so the plugin must
400
- // keep applying (and publishing a truthful fallback list) even when the
401
- // registry or the code runtime is absent.
402
346
  const registry = () => ctx.get('tools')
403
347
 
404
- /** Whether this deployment can present PTC at all: opted in and a runtime mounted. */
405
- const ptcReady = () => ptcEnabled && ctx.get('codeRuntime') !== undefined
348
+ /** Whether PTC is planned and capable in this deployment. */
349
+ const ptcPlanReady = () => ptcPlanEnabled && ctx.get('codeRuntime') !== undefined
406
350
 
407
- /**
408
- * Whether this session is still in its anchor turn. An empty `anchorTools`
409
- * disables staging, so every session reads as promoted.
410
- */
351
+ /** Whether this session is still in its anchor turn. */
411
352
  const anchoring = (agent) => (
412
353
  anchorNames.length > 0 && agent !== undefined && inAnchorTurn(sessionEvents(agent?.session))
413
354
  )
414
355
 
415
356
  /**
416
- * Declare PTC presentation for one agent. The declaration is per scope
417
- * (`agent.ctx`), so it covers this session alone, and it must land BEFORE the
418
- * promoted turn's first assembly: the harness collects the tool providers
419
- * before it runs the `system-prompt/assemble` waterfall, so nothing a
420
- * waterfall listener does can change the assembly it is participating in.
421
- * The turn-boundary events are therefore the primary trigger; the assembly
422
- * listener re-asserts it for a session whose boundary was crossed while this
423
- * plugin was not mounted (a host restart mid-turn), where the collapse then
424
- * lands one assembly later.
357
+ * Declare PTC presentation for one agent using public agent.ctx.tools.presentAs('ptc').
425
358
  */
426
359
  const presentPtc = (agent) => {
427
- if (!ptcReady() || agent === undefined || ptcAgents.has(agent)) return
360
+ if (!ptcPlanReady() || agent === undefined) return false
361
+ if (agentPtcDeclared.has(agent)) return true
362
+ if (agentPtcFailed.has(agent)) return false
363
+
428
364
  const tools = agent?.ctx?.tools
429
365
  if (tools === undefined || typeof tools.presentAs !== 'function') {
366
+ agentPtcFailed.add(agent)
430
367
  warnOnce('no scoped tools view to declare PTC presentation')
431
- return
368
+ return false
432
369
  }
433
- ptcAgents.add(agent)
370
+
434
371
  try {
435
- tools.presentAs('ptc')
436
- } catch {
437
- // A failed declaration must never break the session; the wire stays
438
- // native and the catalog says so.
439
- warnOnce('PTC presentation declined')
372
+ const disposer = tools.presentAs('ptc')
373
+ agentPtcDeclared.add(agent)
374
+ if (typeof disposer === 'function') {
375
+ agentPtcDisposers.set(agent, disposer)
376
+ }
377
+ return true
378
+ } catch (err) {
379
+ agentPtcFailed.add(agent)
380
+ warnOnce(`PTC presentation declined: ${err instanceof Error ? err.message : String(err)}`)
381
+ return false
440
382
  }
441
383
  }
442
384
 
443
385
  /**
444
- * The registry's PTC surface: every visible tool except the reserved
445
- * `run_code` transport (which the projection already excludes). Read on every
446
- * assembly, whatever surface the current request happens to carry, so the
447
- * anchor turn already names what the promoted turn reaches and the rendered
448
- * text does not change at the boundary. Undefined when the registry cannot
449
- * project it, which sends the caller to the assembled wire schemas.
386
+ * Abort/revert PTC declaration if active, restoring presentation back to native.
450
387
  */
451
- const sdkSurface = (agent) => {
452
- const tools = registry()
453
- if (tools === undefined || typeof tools.sdkSchemas !== 'function') return undefined
454
- try {
455
- const schemas = tools.sdkSchemas(agent)
456
- return Array.isArray(schemas) && schemas.length > 0 ? schemas : undefined
457
- } catch {
458
- warnOnce('no SDK tool projection available')
459
- return undefined
388
+ const revertPtc = (agent, reason, retryable = false) => {
389
+ if (agent === undefined) return
390
+ const disposer = agentPtcDisposers.get(agent)
391
+ if (typeof disposer === 'function') {
392
+ try {
393
+ disposer()
394
+ } catch {
395
+ // Ignore disposer error
396
+ }
397
+ agentPtcDisposers.delete(agent)
460
398
  }
399
+ agentPtcDeclared.delete(agent)
400
+ // 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)
461
405
  }
462
406
 
463
- ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
464
- const agent = context?.agent
465
- const staged = anchoring(agent)
466
- if (!staged) presentPtc(agent)
467
- if (agent !== undefined) {
468
- if (agent.session !== undefined) agentBySession.set(agent.session, agent)
469
- const surface = sdkSurface(agent)
470
- if (surface !== undefined) catalogByAgent.set(agent, catalogEntries(surface, descriptionMaxLength))
407
+ /**
408
+ * Read visible tool schemas from the public tools.schemas(agent) API.
409
+ * Excludes run_code. Tolerates test stubs providing sdkSchemas.
410
+ */
411
+ const resolveToolsService = (agent) => {
412
+ const scoped = agent?.ctx?.tools
413
+ if (typeof scoped?.schemas === 'function' || typeof scoped?.sdkSchemas === 'function') {
414
+ return scoped
471
415
  }
472
- // Downstream errors propagate untouched; only this plugin's own logic is
473
- // guarded (a staging bug must never brick every request of a session).
474
- const assembled = await next()
475
- if (agent !== undefined && catalogByAgent.get(agent) === undefined) {
476
- catalogByAgent.set(agent, catalogEntries(assembled.tools, descriptionMaxLength))
416
+ const reg = registry()
417
+ if (typeof reg?.schemas === 'function' || typeof reg?.sdkSchemas === 'function') {
418
+ return reg
477
419
  }
478
- if (!staged) return assembled
479
- return { ...assembled, tools: anchorToolsOf(assembled.tools, anchorNames) }
480
- }, { prepend: true })
420
+ return scoped ?? reg
421
+ }
422
+
423
+ const publicSchemas = (agent) => {
424
+ const tools = resolveToolsService(agent)
425
+ if (tools === undefined) return undefined
426
+ if (typeof tools.schemas === 'function') {
427
+ try {
428
+ const schemas = tools.schemas(agent)
429
+ if (Array.isArray(schemas) && schemas.length > 0) {
430
+ const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
431
+ return filtered.length > 0 ? filtered : undefined
432
+ }
433
+ return undefined
434
+ } catch {
435
+ warnOnce('no tool schemas available')
436
+ return undefined
437
+ }
438
+ }
439
+ // Test harness compatibility stub
440
+ if (typeof tools.sdkSchemas === 'function') {
441
+ try {
442
+ const schemas = tools.sdkSchemas(agent)
443
+ if (Array.isArray(schemas) && schemas.length > 0) {
444
+ const filtered = schemas.filter(t => t?.name && t.name !== 'run_code')
445
+ return filtered.length > 0 ? filtered : undefined
446
+ }
447
+ } catch {
448
+ warnOnce('no tool schemas available')
449
+ return undefined
450
+ }
451
+ }
452
+ return undefined
453
+ }
481
454
 
482
- // The deterministic promotion trigger: the anchor turn's end, and the second
483
- // turn's start. Both are emitted before the next assembly reads the wire.
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) => {
477
+ if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
478
+ if (!anchoring(agent) && ptcPlanReady()) {
479
+ presentPtc(agent)
480
+ }
481
+ })
482
+
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
+ }
488
+ })
489
+
490
+ // Turn boundary session events
484
491
  ctx.on('session/event', (session, event) => {
485
492
  if (event?.type !== 'turn/start' && event?.type !== 'turn/end') return
486
493
  const agent = session === undefined ? undefined : agentBySession.get(session)
487
- if (agent === undefined || anchoring(agent)) return
494
+ if (agent === undefined || anchoring(agent) || !ptcPlanReady()) return
488
495
  presentPtc(agent)
489
496
  })
490
497
 
498
+ // 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.
500
+ const reassembling = new WeakSet()
501
+
502
+ ctx.on('system-prompt/assemble', async (assembly, context, next) => {
503
+ const agent = context?.agent
504
+ const staged = anchoring(agent)
505
+
506
+ if (agent !== undefined && agent.session !== undefined) {
507
+ agentBySession.set(agent.session, agent)
508
+ }
509
+
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
+ }
524
+ // 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)) {
528
+ const sp = ctx.get('systemPrompt')
529
+ if (typeof sp?.assemble === 'function') {
530
+ reassembling.add(agent)
531
+ try {
532
+ return await sp.assemble(context)
533
+ } catch (error) {
534
+ warnOnce(`re-assembling after the PTC declaration failed: ${error instanceof Error ? error.message : String(error)}`)
535
+ } finally {
536
+ reassembling.delete(agent)
537
+ }
538
+ }
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
544
+ }
545
+ } else {
546
+ ptcDeclared = true
547
+ }
548
+ }
549
+
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
555
+
556
+ const assembled = await next()
557
+
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.
567
+ let correctedWire
568
+ if (wireOnlyRunCode && (surface === undefined || surface.length === 0)) {
569
+ revertPtc(agent, 'no tool schema projection available under PTC')
570
+ ptcDeclared = false
571
+ const nativeSchemas = publicSchemas(agent) ?? []
572
+ surface = nativeSchemas
573
+ correctedWire = nativeSchemas
574
+ }
575
+
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)
589
+
590
+ const entries = catalogEntries(catalogTools, descriptionMaxLength)
591
+
592
+ // Store fresh state on agent
593
+ if (agent !== undefined) {
594
+ agentCatalogState.set(agent, {
595
+ entries,
596
+ ptc: isActualPtc,
597
+ })
598
+ }
599
+
600
+ if (!staged) return correctedWire === undefined ? assembled : { ...assembled, tools: correctedWire }
601
+ return { ...assembled, tools: anchorToolsOf(effectiveWire, anchorNames) }
602
+ }, { prepend: true })
603
+
491
604
  ctx.on('agent/pre-step', async (payload, next) => {
492
605
  const decision = await next()
493
606
  if (decision.kind !== 'enter') return decision
494
607
  const agent = payload?.agent
495
- const entries = agent === undefined ? undefined : catalogByAgent.get(agent)
496
- if (entries === undefined) return decision
608
+ const state = catalogStateFor(agent)
609
+ if (state === undefined) return decision
497
610
 
498
- const ptc = ptcReady()
611
+ const { entries, ptc } = state
499
612
  const candidate = renderCatalogText(entries, ptc)
500
613
  const history = catalogHistory(agent)
501
614
  const existing = catalogMessage(decision.messages)