@linxin666/dsh-liangshen 0.3.23 → 0.4.0
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.
- package/README.i18n.yaml +2 -2
- package/README.md +55 -41
- package/README.zh.md +54 -40
- package/cordis.patch.yml +3 -2
- package/icon.svg +3 -0
- package/lib/client.js +1380 -29
- package/lib/client.js.map +1 -1
- package/lib/index.js +616 -367
- package/lib/types/announce.test.d.ts +10 -0
- package/lib/types/client/LiangShenSettingsCard.d.ts +78 -0
- package/lib/types/client/PluginSettingsCard.d.ts +137 -0
- package/lib/types/client/index.d.ts +57 -4
- package/lib/types/client/lever-controller.d.ts +16 -2
- package/lib/types/client/locales.d.ts +40 -1
- package/lib/types/client/main-session.d.ts +32 -0
- package/lib/types/client/plugin-card-seat.d.ts +103 -0
- package/lib/types/client/settings-form.d.ts +197 -0
- package/lib/types/composition.d.ts +116 -0
- package/lib/types/composition.test.d.ts +7 -0
- package/lib/types/core/lever.d.ts +6 -3
- package/lib/types/index.d.ts +160 -33
- package/lib/types/index.test.d.ts +5 -0
- package/package.json +27 -18
- package/presets/liangshen/NOTICE +4 -4
- package/presets/liangshen/agent.cordis.yml +168 -123
- package/presets/liangshen/fact-ledger.mjs +141 -0
- package/presets/liangshen/guard.mjs +426 -0
- package/presets/liangshen/minimal-prompt.mjs +73 -38
- package/presets/liangshen/paging.mjs +232 -0
- package/presets/liangshen/tool-activate.mjs +176 -0
- package/presets/liangshen/tool-catalog.mjs +615 -219
- package/presets/liangshen/working-context.mjs +222 -0
- package/src/announce.test.ts +248 -55
- package/src/client/LiangShenLever.module.css +2 -0
- package/src/client/LiangShenLever.tsx +41 -10
- package/src/client/LiangShenSettingsCard.tsx +233 -0
- package/src/client/PluginSettingsCard.tsx +555 -0
- package/src/client/index.ts +102 -5
- package/src/client/lever-controller.ts +76 -9
- package/src/client/locales.ts +79 -1
- package/src/client/main-session.ts +43 -0
- package/src/client/plugin-card-seat.ts +192 -0
- package/src/client/settings-card.module.css +418 -0
- package/src/client/settings-form.ts +442 -0
- package/src/composition.test.ts +294 -0
- package/src/composition.ts +554 -0
- package/src/core/lever.ts +7 -4
- package/src/index.test.ts +68 -1
- package/src/index.ts +293 -101
- package/tools/benchmark-live-run.mjs +193 -63
- package/lib/types/schema.d.ts +0 -18
- package/lib/types/schema.test.d.ts +0 -1
- package/lib/types/sync.d.ts +0 -47
- package/lib/types/sync.test.d.ts +0 -1
- package/presets/liangshen/custom-bash.mjs +0 -213
- package/src/schema.test.ts +0 -64
- package/src/schema.ts +0 -110
- package/src/sync.test.ts +0 -224
- package/src/sync.ts +0 -222
|
@@ -1,22 +1,86 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* tool-catalog —
|
|
3
|
-
*
|
|
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
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
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,70 @@ 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. The budget was re-estimated for DeepSeek-V4.1:
|
|
129
|
+
* its KV cache is a quarter of V4-Flash's (890 bytes/token), so the same schema
|
|
130
|
+
* load occupies a quarter of the sparse-index slots and the threshold moved from
|
|
131
|
+
* 6000 to 8000 — still calibrated above the shipped roster so only real growth
|
|
132
|
+
* trips it.
|
|
133
|
+
*/
|
|
134
|
+
export const DEFAULT_MAX_RESIDENT_TOKENS = 8000
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Rough token estimate for one tool surface: the serialized schema is the
|
|
138
|
+
* payload the request actually carries, and four characters per token is the
|
|
139
|
+
* conventional English-and-JSON approximation. Deliberately coarse — this
|
|
140
|
+
* drives a warning threshold, not a billing figure.
|
|
141
|
+
* @param schemas - the tool schemas on the wire.
|
|
142
|
+
* @returns estimated tokens, or 0 when nothing is measurable.
|
|
143
|
+
*/
|
|
144
|
+
export function estimateSurfaceTokens(schemas) {
|
|
145
|
+
let characters = 0
|
|
146
|
+
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
147
|
+
if (schema === null || schema === undefined) continue
|
|
148
|
+
try {
|
|
149
|
+
characters += JSON.stringify(schema)?.length ?? 0
|
|
150
|
+
} catch {
|
|
151
|
+
// A hostile or circular schema contributes nothing rather than throwing.
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return Math.ceil(characters / 4)
|
|
155
|
+
}
|
|
156
|
+
|
|
29
157
|
/**
|
|
30
158
|
* Nesting depth beyond which an inline signature degrades to JsonValue. The
|
|
31
159
|
* rendering stays one line per tool, so deeply nested argument objects are
|
|
@@ -36,14 +164,6 @@ const MAX_SIGNATURE_DEPTH = 4
|
|
|
36
164
|
/** Types the compact signature renders exactly; everything else degrades. */
|
|
37
165
|
const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null'])
|
|
38
166
|
|
|
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
167
|
function optionalBoolean(value, field, fallback) {
|
|
48
168
|
if (value === undefined) return fallback
|
|
49
169
|
if (typeof value !== 'boolean') {
|
|
@@ -52,41 +172,42 @@ function optionalBoolean(value, field, fallback) {
|
|
|
52
172
|
return value
|
|
53
173
|
}
|
|
54
174
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
175
|
+
/**
|
|
176
|
+
* Resolve the presentation config: the explicit `presentation` enum wins; the
|
|
177
|
+
* legacy boolean `ptcPresentation` maps onto it (true -> 'ptc', false ->
|
|
178
|
+
* 'native') with a one-time deprecation warning; neither means the default.
|
|
179
|
+
*/
|
|
180
|
+
function resolvePresentation(config, warn) {
|
|
181
|
+
const explicit = config?.presentation
|
|
182
|
+
if (explicit !== undefined) {
|
|
183
|
+
if (!PRESENTATION_MODES.includes(explicit)) {
|
|
184
|
+
throw new TypeError(`${name}: presentation must be one of ${JSON.stringify(PRESENTATION_MODES)}`)
|
|
185
|
+
}
|
|
186
|
+
if (config?.ptcPresentation !== undefined) {
|
|
187
|
+
optionalBoolean(config.ptcPresentation, 'ptcPresentation', true)
|
|
188
|
+
warn('the ptcPresentation key is deprecated — presentation takes precedence over it')
|
|
189
|
+
}
|
|
190
|
+
return explicit
|
|
191
|
+
}
|
|
192
|
+
if (config?.ptcPresentation !== undefined) {
|
|
193
|
+
const legacy = optionalBoolean(config.ptcPresentation, 'ptcPresentation', true)
|
|
194
|
+
warn(`the ptcPresentation key is deprecated; use presentation instead (mapping ${legacy ? "true -> 'ptc'" : "false -> 'native'"})`)
|
|
195
|
+
return legacy ? 'ptc' : 'native'
|
|
196
|
+
}
|
|
197
|
+
return DEFAULT_PRESENTATION
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Validate the retired anchorTools key's shape before ignoring it. */
|
|
201
|
+
function validateRetiredAnchorTools(value) {
|
|
202
|
+
if (value === undefined) return
|
|
58
203
|
if (!Array.isArray(value)) {
|
|
59
204
|
throw new TypeError(`${name}: anchorTools must be an array of tool names`)
|
|
60
205
|
}
|
|
61
|
-
|
|
206
|
+
for (const entry of value) {
|
|
62
207
|
if (typeof entry !== 'string' || entry.trim() === '') {
|
|
63
208
|
throw new TypeError(`${name}: anchorTools entries must be non-empty tool names`)
|
|
64
209
|
}
|
|
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
210
|
}
|
|
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
211
|
}
|
|
91
212
|
|
|
92
213
|
/**
|
|
@@ -155,25 +276,35 @@ export function renderSignature(parameters) {
|
|
|
155
276
|
|
|
156
277
|
/**
|
|
157
278
|
* Catalog entries for one tool surface, sorted by name so an unchanged surface
|
|
158
|
-
* renders byte-identical text across assemblies. Nameless definitions
|
|
159
|
-
* the run_code transport
|
|
279
|
+
* renders byte-identical text across assemblies. Nameless definitions are
|
|
280
|
+
* skipped; the `run_code` transport is listed only when the presentation puts
|
|
281
|
+
* it on the wire beside the native tools ('both').
|
|
160
282
|
*/
|
|
161
|
-
export function catalogEntries(schemas, maxLength) {
|
|
283
|
+
export function catalogEntries(schemas, maxLength, options) {
|
|
284
|
+
const includeRunCode = options?.includeRunCode === true
|
|
285
|
+
const patterns = Array.isArray(options?.patterns) ? options.patterns : []
|
|
162
286
|
const entries = []
|
|
163
287
|
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
164
288
|
const toolName = schema?.name
|
|
165
|
-
if (typeof toolName !== 'string' || toolName === ''
|
|
289
|
+
if (typeof toolName !== 'string' || toolName === '') continue
|
|
290
|
+
if (toolName === 'run_code' && !includeRunCode) continue
|
|
291
|
+
// A tool from a paged family carries its namespace so the catalog can group
|
|
292
|
+
// it the way the model calls it, instead of scattering one server's tools
|
|
293
|
+
// through an alphabetical list.
|
|
294
|
+
const namespace = namespaceOf(toolName, patterns)
|
|
166
295
|
entries.push({
|
|
167
296
|
name: toolName,
|
|
168
297
|
signature: renderSignature(schema.parameters),
|
|
169
298
|
description: catalogDescription(schema.description, maxLength),
|
|
299
|
+
...(namespace === undefined ? {} : { namespace }),
|
|
170
300
|
})
|
|
171
301
|
}
|
|
172
302
|
return entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
173
303
|
}
|
|
174
304
|
|
|
175
305
|
/**
|
|
176
|
-
* The program contract the injected message carries
|
|
306
|
+
* The program contract the injected message carries when the wire collapsed to
|
|
307
|
+
* the PTC transport: `run_code` is then the only directly callable tool.
|
|
177
308
|
*/
|
|
178
309
|
const PTC_PROGRAM_LINES = [
|
|
179
310
|
'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 +314,68 @@ const PTC_PROGRAM_LINES = [
|
|
|
183
314
|
'- a failed call rejects with `ToolCallError`, whose `toolName` and human-readable message identify it — `try/catch` it to continue;',
|
|
184
315
|
'- 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
316
|
'',
|
|
186
|
-
|
|
317
|
+
'`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.',
|
|
318
|
+
'',
|
|
319
|
+
'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.',
|
|
320
|
+
]
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The short note the catalog carries when `run_code` sits on the wire beside
|
|
324
|
+
* the native roster ('both'): native calls are the primary surface, and the
|
|
325
|
+
* transport covers programmatic batch work. Paged-out namespaces stay reachable
|
|
326
|
+
* through the SDK inside a program even before activation.
|
|
327
|
+
*/
|
|
328
|
+
const BOTH_PROGRAM_LINES = [
|
|
329
|
+
'Prefer calling the tools above directly by name: ordinary single-step work (read, edit, bash, one search) goes through the native call, never through `run_code`. Reserve `run_code` for what a direct call cannot do — 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: programmatic batch computation, wide fan-out, or multi-step data shaping. Routing everyday calls through a program adds a wrapping layer with no payoff.',
|
|
330
|
+
'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
331
|
]
|
|
188
332
|
|
|
189
333
|
/**
|
|
190
334
|
* Model-facing catalog text.
|
|
191
|
-
* -
|
|
192
|
-
* -
|
|
193
|
-
*
|
|
194
|
-
* -
|
|
335
|
+
* - Native presentation: the on-wire tool list plus the paged-out namespace summary.
|
|
336
|
+
* - 'both': the on-wire list INCLUDING `run_code`, the namespace summary, and
|
|
337
|
+
* the short programmatic-escape note.
|
|
338
|
+
* - 'ptc' (wire collapsed to `run_code`): the SDK-reachable list plus the full
|
|
339
|
+
* program contract naming `run_code` the one direct transport.
|
|
195
340
|
*/
|
|
196
|
-
export function renderCatalogText(entries,
|
|
341
|
+
export function renderCatalogText(entries, presentation = 'native', inactive = []) {
|
|
342
|
+
// Activated paged families are listed under their namespace heading; every
|
|
343
|
+
// other tool stays in the flat alphabetical list, so an unchanged surface
|
|
344
|
+
// still renders byte-identical text.
|
|
345
|
+
const resident = entries.filter(entry => entry.namespace === undefined)
|
|
346
|
+
const byNamespace = new Map()
|
|
347
|
+
for (const entry of entries) {
|
|
348
|
+
if (entry.namespace === undefined) continue
|
|
349
|
+
if (!byNamespace.has(entry.namespace)) byNamespace.set(entry.namespace, [])
|
|
350
|
+
byNamespace.get(entry.namespace).push(entry)
|
|
351
|
+
}
|
|
352
|
+
const lineOf = entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`
|
|
197
353
|
const available = entries.length === 0
|
|
198
354
|
? ['No tools are currently available in this session.']
|
|
199
355
|
: [
|
|
200
356
|
'<available_tools>',
|
|
201
|
-
...
|
|
357
|
+
...resident.map(lineOf),
|
|
358
|
+
...[...byNamespace.entries()].flatMap(([namespace, group]) => [
|
|
359
|
+
`- namespace \`${namespace}\` (activated):`,
|
|
360
|
+
...group.map(entry => ` ${lineOf(entry)}`),
|
|
361
|
+
]),
|
|
202
362
|
'</available_tools>',
|
|
203
363
|
]
|
|
204
|
-
const footer =
|
|
364
|
+
const footer = inactive.length === 0
|
|
365
|
+
? 'This is the complete current list and replaces any earlier available-tools list in this session.'
|
|
366
|
+
: 'This is the current on-wire list and replaces any earlier available-tools list in this session.'
|
|
367
|
+
const inactiveBlock = inactive.length === 0 ? [] : [
|
|
368
|
+
'',
|
|
369
|
+
'These tool namespaces are registered but currently paged out of the wire:',
|
|
370
|
+
'<inactive_namespaces>',
|
|
371
|
+
...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.`),
|
|
372
|
+
'</inactive_namespaces>',
|
|
373
|
+
]
|
|
374
|
+
const presentationLines = presentation === 'ptc'
|
|
375
|
+
? ['', ...PTC_PROGRAM_LINES]
|
|
376
|
+
: presentation === 'both'
|
|
377
|
+
? ['', ...BOTH_PROGRAM_LINES]
|
|
378
|
+
: []
|
|
205
379
|
return [
|
|
206
380
|
'<system-reminder>',
|
|
207
381
|
'The following tools are available in this session:',
|
|
@@ -209,16 +383,24 @@ export function renderCatalogText(entries, ptc) {
|
|
|
209
383
|
...available,
|
|
210
384
|
'',
|
|
211
385
|
footer,
|
|
212
|
-
...
|
|
386
|
+
...inactiveBlock,
|
|
387
|
+
...presentationLines,
|
|
213
388
|
'</system-reminder>',
|
|
214
389
|
].join('\n')
|
|
215
390
|
}
|
|
216
391
|
|
|
217
392
|
/**
|
|
218
|
-
* Overlay the registry projection
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
393
|
+
* Overlay the registry projection onto each wire entry, keyed by name, so the
|
|
394
|
+
* catalog describes complete argument semantics even when the assembly's own
|
|
395
|
+
* tool object carries a thinner definition.
|
|
396
|
+
*
|
|
397
|
+
* A tool the projection NAMES is authoritative for the parameter field,
|
|
398
|
+
* including its absence: a projected entry that declares no parameters means
|
|
399
|
+
* the tool takes no declared arguments, and the wire's placeholder object
|
|
400
|
+
* (`{ type: 'object', properties: {} }`) would otherwise render the misleading
|
|
401
|
+
* `Record<string, JsonValue>` signature. A tool the projection does not name
|
|
402
|
+
* keeps the wire's own definition, and so does every entry when no projection
|
|
403
|
+
* is readable at all.
|
|
222
404
|
*/
|
|
223
405
|
export function mergeProjectedSchemas(wireTools, projection) {
|
|
224
406
|
if (!Array.isArray(projection) || projection.length === 0) return wireTools
|
|
@@ -230,7 +412,8 @@ export function mergeProjectedSchemas(wireTools, projection) {
|
|
|
230
412
|
const projected = byName.get(tool?.name)
|
|
231
413
|
if (projected === undefined) return tool
|
|
232
414
|
const merged = { ...tool }
|
|
233
|
-
if (projected.parameters
|
|
415
|
+
if (projected.parameters === undefined) delete merged.parameters
|
|
416
|
+
else merged.parameters = projected.parameters
|
|
234
417
|
if (typeof projected.description === 'string' && projected.description.length > 0) {
|
|
235
418
|
merged.description = projected.description
|
|
236
419
|
}
|
|
@@ -239,12 +422,12 @@ export function mergeProjectedSchemas(wireTools, projection) {
|
|
|
239
422
|
}
|
|
240
423
|
|
|
241
424
|
/** Build the durable catalog message for one entry list. */
|
|
242
|
-
export function createCatalogMessage(entries,
|
|
425
|
+
export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
|
|
243
426
|
return {
|
|
244
427
|
id: globalThis.crypto.randomUUID(),
|
|
245
428
|
role: 'user',
|
|
246
|
-
content: [{ type: 'text', text: renderCatalogText(entries,
|
|
247
|
-
source: { kind:
|
|
429
|
+
content: [{ type: 'text', text: renderCatalogText(entries, presentation, inactive) }],
|
|
430
|
+
source: { kind: name },
|
|
248
431
|
}
|
|
249
432
|
}
|
|
250
433
|
|
|
@@ -260,7 +443,7 @@ function textOf(message) {
|
|
|
260
443
|
/** Whether one message is this plugin's catalog. */
|
|
261
444
|
function isCatalogMessage(message) {
|
|
262
445
|
const source = message?.source
|
|
263
|
-
return source?.kind === 'plugin' && source?.plugin === name
|
|
446
|
+
return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
|
|
264
447
|
}
|
|
265
448
|
|
|
266
449
|
/**
|
|
@@ -310,98 +493,226 @@ function withoutMessage(decision, id) {
|
|
|
310
493
|
return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
|
|
311
494
|
}
|
|
312
495
|
|
|
313
|
-
/** Register the
|
|
496
|
+
/** Register the presentation declaration, the wire paging, and the per-step catalog injection. */
|
|
314
497
|
export function apply(ctx, config) {
|
|
315
498
|
const descriptionMaxLength = integerAtLeast(
|
|
499
|
+
name,
|
|
316
500
|
config?.descriptionMaxLength,
|
|
317
501
|
'descriptionMaxLength',
|
|
318
502
|
1,
|
|
319
503
|
DEFAULT_DESCRIPTION_MAX_LENGTH,
|
|
320
504
|
)
|
|
321
|
-
const
|
|
322
|
-
const
|
|
505
|
+
const pagedToolPatterns = validatePagedToolPatterns(name, config?.pagedToolPatterns)
|
|
506
|
+
const maxActiveNamespaces = integerAtLeast(
|
|
507
|
+
name,
|
|
508
|
+
config?.maxActiveNamespaces,
|
|
509
|
+
'maxActiveNamespaces',
|
|
510
|
+
1,
|
|
511
|
+
DEFAULT_MAX_ACTIVE_NAMESPACES,
|
|
512
|
+
)
|
|
513
|
+
const maxResidentTokens = integerAtLeast(
|
|
514
|
+
name,
|
|
515
|
+
config?.maxResidentTokens,
|
|
516
|
+
'maxResidentTokens',
|
|
517
|
+
1,
|
|
518
|
+
DEFAULT_MAX_RESIDENT_TOKENS,
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
// One-time warnings, per concern so each retired/legacy key reports itself.
|
|
522
|
+
const warned = new Set()
|
|
523
|
+
const warnOnce = (key, detail) => {
|
|
524
|
+
if (warned.has(key)) return
|
|
525
|
+
warned.add(key)
|
|
526
|
+
try {
|
|
527
|
+
ctx.logger?.warn?.(`${name}: ${detail}`)
|
|
528
|
+
} catch {
|
|
529
|
+
// Logger unavailable
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
validateRetiredAnchorTools(config?.anchorTools)
|
|
534
|
+
if (config?.anchorTools !== undefined) {
|
|
535
|
+
warnOnce('anchor', 'anchor-turn staging is retired — the anchorTools key is accepted but no longer narrows the wire')
|
|
536
|
+
}
|
|
537
|
+
const presentation = resolvePresentation(config, detail => warnOnce('ptcPresentation', detail))
|
|
323
538
|
|
|
324
539
|
// Per-agent fresh state evaluated on every assembly (never stale across steps/turns)
|
|
325
540
|
const agentCatalogState = new WeakMap()
|
|
326
541
|
|
|
327
|
-
// Session to agent mapping for
|
|
542
|
+
// Session to agent mapping for lifecycle events
|
|
328
543
|
const agentBySession = new WeakMap()
|
|
329
544
|
|
|
330
|
-
// Presentation
|
|
331
|
-
const
|
|
332
|
-
const
|
|
333
|
-
const
|
|
545
|
+
// Presentation declaration tracking per agent scope (one declaration each)
|
|
546
|
+
const agentDeclared = new WeakSet()
|
|
547
|
+
const agentDeclareFailed = new WeakSet()
|
|
548
|
+
const agentDisposers = new WeakMap()
|
|
334
549
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
550
|
+
// Registry-level paging state, one entry per agent scope: the names the live
|
|
551
|
+
// restriction withholds and the exact disposer that lifts it. Keyed by agent
|
|
552
|
+
// so two sessions assembling at once cannot lift each other's filter, and
|
|
553
|
+
// released with the agent so a departed scope leaves no filter behind.
|
|
554
|
+
const agentPaging = new WeakMap()
|
|
555
|
+
|
|
556
|
+
/** Lift one agent scope's live restriction, if it has one. */
|
|
557
|
+
const clearScopePaging = (agent) => {
|
|
558
|
+
const state = agentPaging.get(agent)
|
|
559
|
+
if (state === undefined) return
|
|
560
|
+
agentPaging.delete(agent)
|
|
339
561
|
try {
|
|
340
|
-
|
|
341
|
-
} catch {
|
|
342
|
-
|
|
562
|
+
state.dispose()
|
|
563
|
+
} catch (err) {
|
|
564
|
+
warnOnce('paging-dispose', `lifting an earlier tool restriction failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
343
565
|
}
|
|
344
566
|
}
|
|
345
567
|
|
|
346
|
-
|
|
568
|
+
/**
|
|
569
|
+
* Recompute one agent scope's page from the durable session event stream and
|
|
570
|
+
* make the registry match it: `deny` masks exactly the names the wire
|
|
571
|
+
* partition would withhold, so the scope still inherits everything else.
|
|
572
|
+
* Scoped registrations are exempt by the registry's own rule, so
|
|
573
|
+
* preset-owned tools can never be filtered away by this.
|
|
574
|
+
*
|
|
575
|
+
* The restriction is what paging MEANS under a collapsed `ptc` wire, where
|
|
576
|
+
* filtering the assembled `tools` array changes nothing a program can reach.
|
|
577
|
+
* It also stores the namespaces it withheld, so the catalog and the live
|
|
578
|
+
* restriction are read from ONE fact instead of two computations.
|
|
579
|
+
*
|
|
580
|
+
* Called OUTSIDE the assembly waterfall, deliberately: see
|
|
581
|
+
* {@link syncBeforeAssembly} for why an in-waterfall sync cannot fix the
|
|
582
|
+
* request it runs in. Returns the stored state, or undefined when the scope
|
|
583
|
+
* needs none — nothing paged, an unusable scoped view, or a refused filter.
|
|
584
|
+
*/
|
|
585
|
+
const syncScopePaging = (agent) => {
|
|
586
|
+
clearScopePaging(agent)
|
|
347
587
|
|
|
348
|
-
|
|
349
|
-
|
|
588
|
+
const tools = agent?.ctx?.tools
|
|
589
|
+
if (tools === undefined || typeof tools.restrict !== 'function') {
|
|
590
|
+
warnOnce('paging-runtime', 'no scoped tools view to page through — the paged namespaces stay reachable through a program in this session')
|
|
591
|
+
return undefined
|
|
592
|
+
}
|
|
350
593
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
594
|
+
// Read with the restriction lifted (clearScopePaging above), or the
|
|
595
|
+
// withheld names would already be missing and the next sync would find
|
|
596
|
+
// nothing left to withhold. Silent on an unreadable surface: a sync may
|
|
597
|
+
// run before the registry is populated, and "no tools yet" is not the
|
|
598
|
+
// assembly-path emergency that warning describes.
|
|
599
|
+
const fullSurface = quietSchemas(agent) ?? []
|
|
600
|
+
if (fullSurface.length === 0) return undefined
|
|
601
|
+
const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active
|
|
602
|
+
const withheld = withheldToolNames(fullSurface, pagedToolPatterns, active)
|
|
603
|
+
if (withheld.length === 0) return undefined
|
|
604
|
+
|
|
605
|
+
try {
|
|
606
|
+
const dispose = tools.restrict({ deny: withheld })
|
|
607
|
+
if (typeof dispose !== 'function') {
|
|
608
|
+
warnOnce('paging-runtime', 'the tool registry did not confirm the paging restriction — the paged namespaces stay reachable through a program in this session')
|
|
609
|
+
return undefined
|
|
610
|
+
}
|
|
611
|
+
const state = { active, inactive: inactiveNamespaces(fullSurface, pagedToolPatterns, active), dispose }
|
|
612
|
+
agentPaging.set(agent, state)
|
|
613
|
+
return state
|
|
614
|
+
} catch (err) {
|
|
615
|
+
// A registry that refuses the filter (a name that vanished mid-assembly,
|
|
616
|
+
// a scope that is not scoped after all) must not cost the session its
|
|
617
|
+
// tools: the refused restriction simply does not apply.
|
|
618
|
+
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`)
|
|
619
|
+
return undefined
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Bring a scope's page up to date from OUTSIDE the assembly waterfall.
|
|
625
|
+
*
|
|
626
|
+
* `SystemPrompt.assemble()` collects the tool providers AND calls every
|
|
627
|
+
* section's `text(context)` before it runs the `system-prompt/assemble`
|
|
628
|
+
* waterfall, so a restriction installed inside that waterfall cannot change
|
|
629
|
+
* the request it runs for: the `tools:sdk` section has already been rendered
|
|
630
|
+
* from the unrestricted registry. It would take effect one assembly later,
|
|
631
|
+
* leaving a request whose catalog claims a namespace is paged while that
|
|
632
|
+
* request's own SDK section still lists it. Syncing before the providers are
|
|
633
|
+
* collected is what keeps the two consistent from the FIRST `ptc` request.
|
|
634
|
+
*
|
|
635
|
+
* GATED ON THE WIRE ACTUALLY COLLAPSING, not on the configuration asking for
|
|
636
|
+
* it. Both halves of that gate matter, and each covers a deployment where
|
|
637
|
+
* paging at the registry would be wrong:
|
|
638
|
+
* - `presentation === 'ptc'` is what the operator configured, and it excludes
|
|
639
|
+
* `both`, whose documented contract is that a paged-out namespace stays
|
|
640
|
+
* reachable through the SDK inside a program before activation. Installing
|
|
641
|
+
* the restriction there would break that contract for the first request;
|
|
642
|
+
* - `agentDeclared.has(agent)` is the scope's own declaration actually
|
|
643
|
+
* landing, which is NOT the same as `transportReady()`. A deployment with
|
|
644
|
+
* no mounted code runtime (and one whose host declines the declaration)
|
|
645
|
+
* keeps the native wire: the assembled array carries paging by itself, and
|
|
646
|
+
* a registry restriction installed anyway would strip the paged families
|
|
647
|
+
* from that request's native wire — the first request would lose tools it
|
|
648
|
+
* is supposed to have, and the catalog would announce namespaces as
|
|
649
|
+
* withheld that nothing withheld.
|
|
650
|
+
*/
|
|
651
|
+
const syncBeforeAssembly = (agent) => {
|
|
652
|
+
if (agent === undefined || presentation !== 'ptc') return undefined
|
|
653
|
+
if (!agentDeclared.has(agent)) return undefined
|
|
654
|
+
return syncScopePaging(agent)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
const registry = () => ctx.get('tools')
|
|
659
|
+
// The 0.1.6 cohort renamed the service face from `codeRuntime` to
|
|
660
|
+
// `ptcRuntime` (package `@deepseek-ai/dsh-code-runtime` became
|
|
661
|
+
// `@deepseek-ai/dsh-ptc-runtime`); the old key is gone, so reading it would
|
|
662
|
+
// silently disable PTC staging for every session.
|
|
663
|
+
const transportReady = () => presentation !== 'native' && ctx.get('ptcRuntime') !== undefined
|
|
355
664
|
|
|
356
665
|
/**
|
|
357
|
-
* Declare
|
|
666
|
+
* Declare this agent scope's presentation through the public
|
|
667
|
+
* agent.ctx.tools.presentAs(mode). One declaration per scope; a refusal is
|
|
668
|
+
* permanent for the agent, a wire miss is retryable.
|
|
358
669
|
*/
|
|
359
|
-
const
|
|
360
|
-
if (!
|
|
361
|
-
if (
|
|
362
|
-
if (
|
|
670
|
+
const declarePresentation = (agent) => {
|
|
671
|
+
if (!transportReady() || agent === undefined) return false
|
|
672
|
+
if (agentDeclared.has(agent)) return true
|
|
673
|
+
if (agentDeclareFailed.has(agent)) return false
|
|
363
674
|
|
|
364
675
|
const tools = agent?.ctx?.tools
|
|
365
676
|
if (tools === undefined || typeof tools.presentAs !== 'function') {
|
|
366
|
-
|
|
367
|
-
warnOnce('no scoped tools view to declare
|
|
677
|
+
agentDeclareFailed.add(agent)
|
|
678
|
+
warnOnce('runtime', 'no scoped tools view to declare the presentation through — keeping the native tool surface')
|
|
368
679
|
return false
|
|
369
680
|
}
|
|
370
681
|
|
|
371
682
|
try {
|
|
372
|
-
const disposer = tools.presentAs(
|
|
373
|
-
|
|
683
|
+
const disposer = tools.presentAs(presentation)
|
|
684
|
+
agentDeclared.add(agent)
|
|
374
685
|
if (typeof disposer === 'function') {
|
|
375
|
-
|
|
686
|
+
agentDisposers.set(agent, disposer)
|
|
376
687
|
}
|
|
377
688
|
return true
|
|
378
689
|
} catch (err) {
|
|
379
|
-
|
|
380
|
-
warnOnce(`
|
|
690
|
+
agentDeclareFailed.add(agent)
|
|
691
|
+
warnOnce('runtime', `the "${presentation}" presentation was declined: ${err instanceof Error ? err.message : String(err)} — keeping the native tool surface`)
|
|
381
692
|
return false
|
|
382
693
|
}
|
|
383
694
|
}
|
|
384
695
|
|
|
385
696
|
/**
|
|
386
|
-
* Abort/revert
|
|
697
|
+
* Abort/revert the declaration if active, restoring the native presentation.
|
|
387
698
|
*/
|
|
388
|
-
const
|
|
699
|
+
const revertPresentation = (agent, reason, retryable = false) => {
|
|
389
700
|
if (agent === undefined) return
|
|
390
|
-
const disposer =
|
|
701
|
+
const disposer = agentDisposers.get(agent)
|
|
391
702
|
if (typeof disposer === 'function') {
|
|
392
703
|
try {
|
|
393
704
|
disposer()
|
|
394
705
|
} catch {
|
|
395
706
|
// Ignore disposer error
|
|
396
707
|
}
|
|
397
|
-
|
|
708
|
+
agentDisposers.delete(agent)
|
|
398
709
|
}
|
|
399
|
-
|
|
710
|
+
agentDeclared.delete(agent)
|
|
400
711
|
// A declaration the host itself refused is permanent for this agent. One that
|
|
401
|
-
// merely failed to reach a wire is not: the next
|
|
402
|
-
//
|
|
403
|
-
if (!retryable)
|
|
404
|
-
warnOnce(reason)
|
|
712
|
+
// merely failed to reach a wire is not: the next assembly may declare again,
|
|
713
|
+
// and latching it would strand the session on the native surface.
|
|
714
|
+
if (!retryable) agentDeclareFailed.add(agent)
|
|
715
|
+
warnOnce('runtime', `${reason} — keeping the native tool surface`)
|
|
405
716
|
}
|
|
406
717
|
|
|
407
718
|
/**
|
|
@@ -420,6 +731,25 @@ export function apply(ctx, config) {
|
|
|
420
731
|
return scoped ?? reg
|
|
421
732
|
}
|
|
422
733
|
|
|
734
|
+
/**
|
|
735
|
+
* Read the scope's model-facing surface without the assembly path's warning.
|
|
736
|
+
* Returns undefined when no projection is readable at all.
|
|
737
|
+
*/
|
|
738
|
+
const quietSchemas = (agent) => {
|
|
739
|
+
const tools = resolveToolsService(agent)
|
|
740
|
+
if (tools === undefined) return undefined
|
|
741
|
+
for (const method of ['schemas', 'sdkSchemas']) {
|
|
742
|
+
if (typeof tools[method] !== 'function') continue
|
|
743
|
+
try {
|
|
744
|
+
const schemas = tools[method](agent)
|
|
745
|
+
if (Array.isArray(schemas)) return schemas.filter(entry => entry?.name && entry.name !== 'run_code')
|
|
746
|
+
} catch {
|
|
747
|
+
// Try the next source; an unreadable registry is not fatal here.
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
return undefined
|
|
751
|
+
}
|
|
752
|
+
|
|
423
753
|
const publicSchemas = (agent) => {
|
|
424
754
|
const tools = resolveToolsService(agent)
|
|
425
755
|
if (tools === undefined) return undefined
|
|
@@ -432,7 +762,7 @@ export function apply(ctx, config) {
|
|
|
432
762
|
}
|
|
433
763
|
return undefined
|
|
434
764
|
} catch {
|
|
435
|
-
warnOnce('no tool schemas available')
|
|
765
|
+
warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
|
|
436
766
|
return undefined
|
|
437
767
|
}
|
|
438
768
|
}
|
|
@@ -445,181 +775,247 @@ export function apply(ctx, config) {
|
|
|
445
775
|
return filtered.length > 0 ? filtered : undefined
|
|
446
776
|
}
|
|
447
777
|
} catch {
|
|
448
|
-
warnOnce('no tool schemas available')
|
|
778
|
+
warnOnce('runtime', 'no tool schemas available — keeping the native tool surface')
|
|
449
779
|
return undefined
|
|
450
780
|
}
|
|
451
781
|
}
|
|
452
782
|
return undefined
|
|
453
783
|
}
|
|
454
784
|
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
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) => {
|
|
785
|
+
// Early lifecycle hook: declare the presentation and page the scope as soon
|
|
786
|
+
// as it exists.
|
|
787
|
+
//
|
|
788
|
+
// The 0.1.6 cohort folded the former `agent/session-start` into the async
|
|
789
|
+
// serial `agent/created`, which carries the same payload object and runs
|
|
790
|
+
// before the first prompt assembly; the host waits for this listener, so the
|
|
791
|
+
// declaration is already in place when that assembly reads the presentation.
|
|
792
|
+
//
|
|
793
|
+
// The payload is destructured ON PURPOSE: `agent/created` passes its payload
|
|
794
|
+
// OBJECT as the first argument, not the agent itself. Reading that parameter
|
|
795
|
+
// as the agent yields an object with no `session` and no `ctx`, so the
|
|
796
|
+
// declaration is skipped and paging silently never engages.
|
|
797
|
+
ctx.on('agent/created', ({ agent }) => {
|
|
477
798
|
if (agent?.session !== undefined) agentBySession.set(agent.session, agent)
|
|
478
|
-
if (
|
|
479
|
-
|
|
480
|
-
|
|
799
|
+
if (transportReady()) declarePresentation(agent)
|
|
800
|
+
// The session log is readable here, and this runs before the first turn
|
|
801
|
+
// assembles a prompt, so a scope created over an existing (resumed)
|
|
802
|
+
// session is paged before its FIRST assembly rather than one request late.
|
|
803
|
+
syncBeforeAssembly(agent)
|
|
481
804
|
})
|
|
482
805
|
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
806
|
+
// A departed scope must not keep a registry restriction behind: the layer is
|
|
807
|
+
// keyed by the agent, and a recycled key would inherit a stale filter.
|
|
808
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
809
|
+
agentCatalogState.delete(agent)
|
|
810
|
+
clearScopePaging(agent)
|
|
488
811
|
})
|
|
489
812
|
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
813
|
+
/**
|
|
814
|
+
* Re-sync after a call that can move the active set.
|
|
815
|
+
*
|
|
816
|
+
* Every window between assemblies is the right one to fix the NEXT one, and
|
|
817
|
+
* this fires at the end of each tool call: a `tool_activate` and the calls
|
|
818
|
+
* that refresh a namespace's recency are exactly the events the paging
|
|
819
|
+
* replay reads, so the restriction and the catalog are back in step long
|
|
820
|
+
* before the next prompt is assembled. Declared concurrency-safe so it never
|
|
821
|
+
* serializes independent read-only calls.
|
|
822
|
+
*/
|
|
823
|
+
ctx.on('tools/post-execute', (exec, _result, next) => {
|
|
824
|
+
syncBeforeAssembly(exec?.agent)
|
|
825
|
+
return next()
|
|
826
|
+
}, { prepend: true })
|
|
497
827
|
|
|
498
828
|
// Per-agent, not one process-wide flag: two sessions assembling at once would
|
|
499
|
-
// otherwise let one skip the
|
|
829
|
+
// otherwise let one skip the re-assembly the other is running.
|
|
500
830
|
const reassembling = new WeakSet()
|
|
501
831
|
|
|
502
832
|
ctx.on('system-prompt/assemble', async (assembly, context, next) => {
|
|
503
833
|
const agent = context?.agent
|
|
504
|
-
const staged = anchoring(agent)
|
|
505
834
|
|
|
506
835
|
if (agent !== undefined && agent.session !== undefined) {
|
|
507
836
|
agentBySession.set(agent.session, agent)
|
|
508
837
|
}
|
|
509
838
|
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
ptcDeclared = presentPtc(agent)
|
|
523
|
-
}
|
|
839
|
+
if (agent !== undefined && !agentDeclared.has(agent) && transportReady()) {
|
|
840
|
+
// Under 'ptc' a declaration collapses the wire to the single `run_code`
|
|
841
|
+
// transport and lists the tools from their SDK projection. Where no
|
|
842
|
+
// projection can be read at all, declaring would collapse the executor and
|
|
843
|
+
// then have to undo it, losing the native wire on the way out. Stay native
|
|
844
|
+
// instead. Under 'both' the native roster stays on the wire either way, so
|
|
845
|
+
// the declaration needs no projection guard.
|
|
846
|
+
const projectable = publicSchemas(agent)
|
|
847
|
+
if (presentation === 'ptc' && (projectable === undefined || projectable.length === 0)) {
|
|
848
|
+
warnOnce('runtime', 'no tool schema projection available — keeping the native tool surface')
|
|
849
|
+
} else {
|
|
850
|
+
const declaredNow = declarePresentation(agent)
|
|
524
851
|
// A declaration made here cannot reach THIS assembly: the harness collects
|
|
525
|
-
// the tool providers before the waterfall runs. Re-assemble so the
|
|
526
|
-
//
|
|
527
|
-
if (
|
|
852
|
+
// the tool providers before the waterfall runs. Re-assemble so the
|
|
853
|
+
// presentation lands on the assembly the model actually receives.
|
|
854
|
+
if (declaredNow && !reassembling.has(agent)) {
|
|
528
855
|
const sp = ctx.get('systemPrompt')
|
|
529
856
|
if (typeof sp?.assemble === 'function') {
|
|
530
857
|
reassembling.add(agent)
|
|
531
858
|
try {
|
|
532
859
|
return await sp.assemble(context)
|
|
533
860
|
} catch (error) {
|
|
534
|
-
warnOnce(`re-assembling after the
|
|
861
|
+
warnOnce('runtime', `re-assembling after the presentation declaration failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
535
862
|
} finally {
|
|
536
863
|
reassembling.delete(agent)
|
|
537
864
|
}
|
|
538
865
|
}
|
|
539
|
-
// Nothing re-assembled, so this wire stays native.
|
|
540
|
-
//
|
|
541
|
-
//
|
|
542
|
-
|
|
543
|
-
ptcDeclared = false
|
|
866
|
+
// Nothing re-assembled, so this wire stays native. Presenting a transport
|
|
867
|
+
// the request never names would lie to the model, so drop back to native
|
|
868
|
+
// for this assembly and let the next assembly declare again.
|
|
869
|
+
revertPresentation(agent, `the "${presentation}" declaration did not reach this assembly wire`, true)
|
|
544
870
|
}
|
|
545
|
-
} else {
|
|
546
|
-
ptcDeclared = true
|
|
547
871
|
}
|
|
548
872
|
}
|
|
549
873
|
|
|
550
|
-
//
|
|
551
|
-
//
|
|
552
|
-
//
|
|
553
|
-
//
|
|
554
|
-
|
|
874
|
+
// A declaration that just landed here (a scope no lifecycle hook could
|
|
875
|
+
// reach) pages the scope before the re-assembly collects its providers, so
|
|
876
|
+
// that request renders a page-consistent SDK section too. Idempotent: a
|
|
877
|
+
// scope already paged by its lifecycle hook re-derives the same state.
|
|
878
|
+
if (agent !== undefined && agentDeclared.has(agent)) syncBeforeAssembly(agent)
|
|
555
879
|
|
|
880
|
+
// Delegate first: the assembled value stays authoritative for the wire (a
|
|
881
|
+
// presentation declared inside this waterfall reaches the NEXT assembly,
|
|
882
|
+
// which is why a declaration is followed by a re-assembly).
|
|
556
883
|
const assembled = await next()
|
|
557
884
|
|
|
558
|
-
const
|
|
559
|
-
const wireHasRunCode =
|
|
560
|
-
const wireOnlyRunCode =
|
|
885
|
+
const assembledTools = Array.isArray(assembled?.tools) ? assembled.tools : undefined
|
|
886
|
+
const wireHasRunCode = (assembledTools ?? []).some(t => t?.name === 'run_code')
|
|
887
|
+
const wireOnlyRunCode = assembledTools !== undefined && assembledTools.length > 0 && assembledTools.every(t => t?.name === 'run_code')
|
|
888
|
+
|
|
889
|
+
// The paging restriction was installed OUTSIDE this waterfall (see
|
|
890
|
+
// {@link syncBeforeAssembly}) because `assemble()` renders the sections and
|
|
891
|
+
// collects the providers before the waterfall runs: installing it here
|
|
892
|
+
// would leave the request it runs for with a catalog that claims a
|
|
893
|
+
// namespace is paged and a `tools:sdk` section that still lists it. What
|
|
894
|
+
// this waterfall does with it is read the SAME state the restriction was
|
|
895
|
+
// built from, so the catalog never describes a different page than the one
|
|
896
|
+
// the registry enforces.
|
|
897
|
+
const pagingState = agent === undefined ? undefined : agentPaging.get(agent)
|
|
561
898
|
|
|
562
|
-
//
|
|
563
|
-
//
|
|
564
|
-
//
|
|
565
|
-
//
|
|
566
|
-
//
|
|
899
|
+
// Under a collapsed `ptc` wire the registry is the ONLY surface a tool can
|
|
900
|
+
// be reached through, so the page is expressed as a registry restriction.
|
|
901
|
+
// Every other wire still carries paging by itself on the assembled array,
|
|
902
|
+
// and `both` deliberately stays unrestricted: that is what keeps its
|
|
903
|
+
// documented "paged namespaces stay reachable through the SDK inside a
|
|
904
|
+
// program" behavior intact. A wire that carries the native roster again (a
|
|
905
|
+
// reverted declaration) must also drop a page left over from a collapsed
|
|
906
|
+
// assembly, or the filter would keep hiding tools that wire just handed
|
|
907
|
+
// back.
|
|
908
|
+
let surface = agent !== undefined ? publicSchemas(agent) : undefined
|
|
909
|
+
// The wire partition replays the durable log itself: `pagingState` exists
|
|
910
|
+
// only where a restriction was installed (the collapsed ptc wire), and
|
|
911
|
+
// native/both still page the assembled array from the same event stream.
|
|
912
|
+
const activeNamespaces = new Set(
|
|
913
|
+
replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active,
|
|
914
|
+
)
|
|
915
|
+
if (agent !== undefined && !wireOnlyRunCode && pagingState !== undefined) clearScopePaging(agent)
|
|
916
|
+
|
|
917
|
+
// If the wire carries only run_code but no projection is readable, revert to
|
|
918
|
+
// native and restore the native wire. The replacement travels in the RETURNED
|
|
919
|
+
// assembly: the waterfall's returned value is the authoritative one, and
|
|
920
|
+
// mutating the object the harness handed downstream would be a side effect no
|
|
921
|
+
// other listener can see.
|
|
567
922
|
let correctedWire
|
|
568
923
|
if (wireOnlyRunCode && (surface === undefined || surface.length === 0)) {
|
|
569
|
-
|
|
570
|
-
ptcDeclared = false
|
|
924
|
+
revertPresentation(agent, 'no tool schema projection available under PTC')
|
|
571
925
|
const nativeSchemas = publicSchemas(agent) ?? []
|
|
572
926
|
surface = nativeSchemas
|
|
573
927
|
correctedWire = nativeSchemas
|
|
574
928
|
}
|
|
575
929
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
930
|
+
const effectiveWire = correctedWire ?? assembledTools
|
|
931
|
+
const effectiveHasRunCode = (effectiveWire ?? []).some(t => t?.name === 'run_code')
|
|
932
|
+
const effectiveOnlyRunCode = effectiveWire !== undefined && effectiveWire.length > 0 && effectiveWire.every(t => t?.name === 'run_code')
|
|
933
|
+
|
|
934
|
+
// The catalog describes the transport this request actually carries, never
|
|
935
|
+
// the configuration's intent: a collapsed wire is 'ptc', run_code beside the
|
|
936
|
+
// native roster is 'both', and anything else is native.
|
|
937
|
+
const effectivePresentation = effectiveOnlyRunCode ? 'ptc' : (effectiveHasRunCode ? 'both' : 'native')
|
|
938
|
+
|
|
939
|
+
// Gentle paging: the active namespaces were replayed from the durable event
|
|
940
|
+
// stream above; here the paged-but-inactive tools come off the wire itself.
|
|
941
|
+
// run_code and the resident roster never match the paging patterns.
|
|
942
|
+
const { resident, inactive } = partitionWireTools(effectiveWire, pagedToolPatterns, activeNamespaces)
|
|
580
943
|
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
//
|
|
584
|
-
const
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
944
|
+
// Diagnostic guard on the always-on-wire surface. It warns rather than
|
|
945
|
+
// truncates: silently dropping a tool the session needs would trade a
|
|
946
|
+
// measurable context cost for an unmeasurable capability loss.
|
|
947
|
+
const residentTokens = estimateSurfaceTokens(resident)
|
|
948
|
+
if (residentTokens > maxResidentTokens) {
|
|
949
|
+
// Name the heaviest tools so the remedy is actionable rather than a bare number.
|
|
950
|
+
const heaviest = [...resident]
|
|
951
|
+
.map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
|
|
952
|
+
.sort((left, right) => right.tokens - left.tokens)
|
|
953
|
+
.slice(0, 3)
|
|
954
|
+
.map(entry => `${entry.name} (${entry.tokens})`)
|
|
955
|
+
.join(', ')
|
|
956
|
+
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`)
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
// The catalog describes this request's ACTUAL surface: with a live page it
|
|
960
|
+
// summarizes exactly the namespaces that page withholds (the same fact the
|
|
961
|
+
// restriction was built from), and otherwise the namespaces the WIRE
|
|
962
|
+
// partition found — which under `both` stay reachable through the SDK
|
|
963
|
+
// inside a program, as the programmatic-escape note below states.
|
|
964
|
+
const catalogInactive = summarizeInactive(
|
|
965
|
+
pagingState?.inactive ?? inactive,
|
|
966
|
+
describe => catalogDescription(describe, descriptionMaxLength),
|
|
967
|
+
)
|
|
589
968
|
|
|
590
|
-
|
|
969
|
+
let entries
|
|
970
|
+
if (effectivePresentation === 'ptc') {
|
|
971
|
+
// Under the collapsed transport the request opens only run_code, so the
|
|
972
|
+
// catalog lists the SDK-reachable projection instead of the wire.
|
|
973
|
+
entries = catalogEntries(surface ?? [], descriptionMaxLength, { patterns: pagedToolPatterns })
|
|
974
|
+
} else {
|
|
975
|
+
const merged = mergeProjectedSchemas(resident, surface)
|
|
976
|
+
entries = catalogEntries(merged, descriptionMaxLength, {
|
|
977
|
+
includeRunCode: effectivePresentation === 'both',
|
|
978
|
+
patterns: pagedToolPatterns,
|
|
979
|
+
})
|
|
980
|
+
}
|
|
981
|
+
const inactiveSummary = catalogInactive
|
|
591
982
|
|
|
592
983
|
// Store fresh state on agent
|
|
593
984
|
if (agent !== undefined) {
|
|
594
985
|
agentCatalogState.set(agent, {
|
|
595
986
|
entries,
|
|
596
|
-
|
|
987
|
+
presentation: effectivePresentation,
|
|
988
|
+
inactive: inactiveSummary,
|
|
597
989
|
})
|
|
598
990
|
}
|
|
599
991
|
|
|
600
|
-
if (
|
|
601
|
-
|
|
992
|
+
if (assembledTools === undefined) return assembled
|
|
993
|
+
// Keep the caller's own assembly object whenever this pass neither corrected
|
|
994
|
+
// a collapsed wire nor lifted a paged tool off it: a needless copy would hand
|
|
995
|
+
// downstream listeners a different object for no behavioral reason.
|
|
996
|
+
const unchanged = correctedWire === undefined && resident.length === assembledTools.length
|
|
997
|
+
return unchanged ? assembled : { ...assembled, tools: resident }
|
|
602
998
|
}, { prepend: true })
|
|
603
999
|
|
|
604
1000
|
ctx.on('agent/pre-step', async (payload, next) => {
|
|
605
1001
|
const decision = await next()
|
|
606
1002
|
if (decision.kind !== 'enter') return decision
|
|
607
1003
|
const agent = payload?.agent
|
|
608
|
-
const state =
|
|
1004
|
+
const state = agent === undefined ? undefined : agentCatalogState.get(agent)
|
|
609
1005
|
if (state === undefined) return decision
|
|
610
1006
|
|
|
611
|
-
const { entries,
|
|
612
|
-
const candidate = renderCatalogText(entries,
|
|
1007
|
+
const { entries, presentation: statePresentation, inactive } = state
|
|
1008
|
+
const candidate = renderCatalogText(entries, statePresentation, inactive)
|
|
613
1009
|
const history = catalogHistory(agent)
|
|
614
1010
|
const existing = catalogMessage(decision.messages)
|
|
615
1011
|
if (history.text === candidate) {
|
|
616
1012
|
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
617
1013
|
}
|
|
618
1014
|
if (existing !== undefined && existing.text === candidate) return decision
|
|
619
|
-
if (!history.published && entries.length === 0) {
|
|
1015
|
+
if (!history.published && entries.length === 0 && inactive.length === 0) {
|
|
620
1016
|
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
621
1017
|
}
|
|
622
|
-
const catalog = createCatalogMessage(entries,
|
|
1018
|
+
const catalog = createCatalogMessage(entries, statePresentation, inactive)
|
|
623
1019
|
if (existing === undefined) {
|
|
624
1020
|
return { ...decision, messages: [...decision.messages, catalog] }
|
|
625
1021
|
}
|