@linxin666/dsh-liangshen 0.3.19 → 0.3.21
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 +51 -35
- package/README.zh.md +53 -37
- package/lib/client.js +640 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +10 -6
- package/lib/types/announce.test.d.ts +1 -0
- package/lib/types/client/LiangShenLever.d.ts +17 -0
- package/lib/types/client/index.d.ts +45 -0
- package/lib/types/client/lever-controller.d.ts +133 -0
- package/lib/types/client/locales.d.ts +27 -0
- package/lib/types/core/lever.d.ts +50 -0
- package/lib/types/index.d.ts +10 -6
- package/lib/types/index.test.d.ts +1 -0
- package/lib/types/schema.test.d.ts +1 -0
- package/lib/types/sync.test.d.ts +1 -0
- package/package.json +32 -5
- package/presets/liangshen/NOTICE +4 -3
- package/presets/liangshen/agent.cordis.yml +122 -86
- package/presets/liangshen/custom-bash.mjs +4 -4
- package/presets/liangshen/minimal-prompt.mjs +534 -0
- package/presets/liangshen/tool-catalog.mjs +518 -0
- package/src/client/LiangShenLever.module.css +314 -0
- package/src/client/LiangShenLever.tsx +176 -0
- package/src/client/css-modules.d.ts +5 -0
- package/src/client/index.ts +89 -0
- package/src/client/lever-controller.ts +331 -0
- package/src/client/locales.ts +46 -0
- package/src/core/lever.ts +68 -0
- package/src/index.ts +10 -6
- package/src/schema.test.ts +1 -1
- package/src/sync.test.ts +4 -4
- package/tools/analyze-session.mjs +25 -5
- package/presets/liangshen/tool-bootstrap.mjs +0 -601
|
@@ -0,0 +1,518 @@
|
|
|
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.
|
|
5
|
+
*
|
|
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.
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
70
|
+
export const name = 'liangshen-tool-catalog'
|
|
71
|
+
|
|
72
|
+
/** Prompt assembly must exist before the wire catalog can be observed. */
|
|
73
|
+
export const inject = ['systemPrompt']
|
|
74
|
+
|
|
75
|
+
/** Default cap for one tool's one-line summary in the injected list. */
|
|
76
|
+
const DEFAULT_DESCRIPTION_MAX_LENGTH = 200
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Nesting depth beyond which an inline signature degrades to `JsonValue`. The
|
|
80
|
+
* rendering stays one line per tool, so deeply nested argument objects are
|
|
81
|
+
* summarized rather than expanded into a wall of text.
|
|
82
|
+
*/
|
|
83
|
+
const MAX_SIGNATURE_DEPTH = 4
|
|
84
|
+
|
|
85
|
+
/** Types the compact signature renders exactly; everything else degrades. */
|
|
86
|
+
const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null'])
|
|
87
|
+
|
|
88
|
+
function integerAtLeast(value, field, minimum, fallback) {
|
|
89
|
+
if (value === undefined) return fallback
|
|
90
|
+
if (!Number.isInteger(value) || value < minimum) {
|
|
91
|
+
throw new TypeError(`${name}: ${field} must be an integer >= ${minimum}`)
|
|
92
|
+
}
|
|
93
|
+
return value
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function optionalBoolean(value, field, fallback) {
|
|
97
|
+
if (value === undefined) return fallback
|
|
98
|
+
if (typeof value !== 'boolean') {
|
|
99
|
+
throw new TypeError(`${name}: ${field} must be a boolean`)
|
|
100
|
+
}
|
|
101
|
+
return value
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Parse the `anchorTools` config: absent means staging off, entries must be non-empty names. */
|
|
105
|
+
function anchorToolNames(value) {
|
|
106
|
+
if (value === undefined) return []
|
|
107
|
+
if (!Array.isArray(value)) {
|
|
108
|
+
throw new TypeError(`${name}: anchorTools must be an array of tool names`)
|
|
109
|
+
}
|
|
110
|
+
return value.map((entry) => {
|
|
111
|
+
if (typeof entry !== 'string' || entry.trim() === '') {
|
|
112
|
+
throw new TypeError(`${name}: anchorTools entries must be non-empty tool names`)
|
|
113
|
+
}
|
|
114
|
+
return entry
|
|
115
|
+
})
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
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.
|
|
125
|
+
*/
|
|
126
|
+
export function inAnchorTurn(events) {
|
|
127
|
+
let turns = 0
|
|
128
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
129
|
+
if (event?.type === 'turn/end') return false
|
|
130
|
+
if (event?.type !== 'turn/start') continue
|
|
131
|
+
turns += 1
|
|
132
|
+
if (turns >= 2) return false
|
|
133
|
+
}
|
|
134
|
+
return true
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Narrow one assembled wire tool list to the anchor names, preserving wire order. */
|
|
138
|
+
export function anchorToolsOf(tools, names) {
|
|
139
|
+
const wire = Array.isArray(tools) ? tools : []
|
|
140
|
+
if (names.length === 0) return wire
|
|
141
|
+
const keep = new Set(names)
|
|
142
|
+
return wire.filter(tool => keep.has(tool?.name))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* One-line model-facing summary of a tool description: whitespace collapsed,
|
|
147
|
+
* truncated with an ellipsis. The full description stays in the tool schema.
|
|
148
|
+
*/
|
|
149
|
+
export function catalogDescription(value, maxLength) {
|
|
150
|
+
const normalized = String(value ?? '').replaceAll(/\s+/g, ' ').trim()
|
|
151
|
+
if (normalized.length <= maxLength) return normalized
|
|
152
|
+
return `${normalized.slice(0, maxLength - 3)}...`
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** One scalar literal as TypeScript-ish text; non-JSON scalars degrade to the broad type. */
|
|
156
|
+
function renderLiteral(value) {
|
|
157
|
+
const json = JSON.stringify(value)
|
|
158
|
+
return json === undefined ? 'JsonValue' : json
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
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.
|
|
166
|
+
*/
|
|
167
|
+
export function renderJsonSchemaType(schema, depth = 0) {
|
|
168
|
+
if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return 'JsonValue'
|
|
169
|
+
const union = Array.isArray(schema.oneOf) ? schema.oneOf : Array.isArray(schema.anyOf) ? schema.anyOf : undefined
|
|
170
|
+
if (union !== undefined && union.length > 0) {
|
|
171
|
+
const parts = union.map(node => renderJsonSchemaType(node, depth))
|
|
172
|
+
return [...new Set(parts)].join(' | ')
|
|
173
|
+
}
|
|
174
|
+
if (Object.hasOwn(schema, 'const')) return renderLiteral(schema.const)
|
|
175
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum.map(renderLiteral).join(' | ')
|
|
176
|
+
if (Array.isArray(schema.type)) {
|
|
177
|
+
const parts = schema.type.map(type => (typeof type === 'string' ? type : 'JsonValue'))
|
|
178
|
+
return [...new Set(parts)].join(' | ')
|
|
179
|
+
}
|
|
180
|
+
if (SCALAR_TYPES.has(schema.type)) return schema.type === 'integer' ? 'number' : schema.type
|
|
181
|
+
if (schema.type === 'array') {
|
|
182
|
+
const items = schema.items === undefined ? 'JsonValue' : renderJsonSchemaType(schema.items, depth + 1)
|
|
183
|
+
return items.includes('|') ? `(${items})[]` : `${items}[]`
|
|
184
|
+
}
|
|
185
|
+
if (schema.type === 'object' || schema.properties !== undefined) {
|
|
186
|
+
if (depth >= MAX_SIGNATURE_DEPTH) return 'JsonValue'
|
|
187
|
+
const properties = schema.properties !== undefined && typeof schema.properties === 'object' && !Array.isArray(schema.properties)
|
|
188
|
+
? Object.entries(schema.properties)
|
|
189
|
+
: []
|
|
190
|
+
if (properties.length === 0) return 'Record<string, JsonValue>'
|
|
191
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : [])
|
|
192
|
+
const fields = properties.map(([field, child]) => (
|
|
193
|
+
`${field}${required.has(field) ? '' : '?'}: ${renderJsonSchemaType(child, depth + 1)}`
|
|
194
|
+
))
|
|
195
|
+
return `{ ${fields.join(', ')} }`
|
|
196
|
+
}
|
|
197
|
+
return 'JsonValue'
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* 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.
|
|
205
|
+
*/
|
|
206
|
+
export function renderSignature(parameters) {
|
|
207
|
+
if (parameters === null || typeof parameters !== 'object' || Array.isArray(parameters)) return ''
|
|
208
|
+
const type = renderJsonSchemaType(parameters)
|
|
209
|
+
return type === 'JsonValue' ? '' : `(${type})`
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 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.
|
|
216
|
+
*/
|
|
217
|
+
export function catalogEntries(schemas, maxLength) {
|
|
218
|
+
const entries = []
|
|
219
|
+
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
220
|
+
const toolName = schema?.name
|
|
221
|
+
if (typeof toolName !== 'string' || toolName === '') continue
|
|
222
|
+
entries.push({
|
|
223
|
+
name: toolName,
|
|
224
|
+
signature: renderSignature(schema.parameters),
|
|
225
|
+
description: catalogDescription(schema.description, maxLength),
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
return entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
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.
|
|
240
|
+
*/
|
|
241
|
+
const PTC_PROGRAM_LINES = [
|
|
242
|
+
'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:',
|
|
243
|
+
'',
|
|
244
|
+
'- reach a tool as `await tools.<name>({ ... })` — quoted access for exotic names, `tools["my-tool"]({ ... })`;',
|
|
245
|
+
'- overlap independent read-only calls under `Promise.all` (safe calls run concurrently, mutating calls run alone in submission order) and sequence dependent work with `await`;',
|
|
246
|
+
'- a failed call rejects with `ToolCallError`, whose `toolName` and human-readable message identify it — `try/catch` it to continue;',
|
|
247
|
+
'- 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
|
+
'',
|
|
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.",
|
|
250
|
+
]
|
|
251
|
+
|
|
252
|
+
/**
|
|
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.
|
|
258
|
+
*/
|
|
259
|
+
export function renderCatalogText(entries, ptc) {
|
|
260
|
+
const available = entries.length === 0
|
|
261
|
+
? ['No tools are currently available in this session.']
|
|
262
|
+
: [
|
|
263
|
+
'<available_tools>',
|
|
264
|
+
...entries.map(entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`),
|
|
265
|
+
'</available_tools>',
|
|
266
|
+
]
|
|
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."
|
|
269
|
+
return [
|
|
270
|
+
'<system-reminder>',
|
|
271
|
+
'The following tools are available in this session:',
|
|
272
|
+
'',
|
|
273
|
+
...available,
|
|
274
|
+
'',
|
|
275
|
+
footer,
|
|
276
|
+
...(ptc ? ['', ...PTC_PROGRAM_LINES] : []),
|
|
277
|
+
'</system-reminder>',
|
|
278
|
+
].join('\n')
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Build the durable catalog message for one entry list. */
|
|
282
|
+
export function createCatalogMessage(entries, ptc) {
|
|
283
|
+
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
|
+
id: globalThis.crypto.randomUUID(),
|
|
288
|
+
role: 'user',
|
|
289
|
+
content: [{ type: 'text', text: renderCatalogText(entries, ptc) }],
|
|
290
|
+
source: { kind: 'plugin', plugin: name },
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** The text one message contributes, joined across its text blocks. */
|
|
295
|
+
function textOf(message) {
|
|
296
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
297
|
+
return blocks
|
|
298
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
299
|
+
.map(block => block.text)
|
|
300
|
+
.join('\n')
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Whether one message is this plugin's catalog. */
|
|
304
|
+
function isCatalogMessage(message) {
|
|
305
|
+
const source = message?.source
|
|
306
|
+
return source?.kind === 'plugin' && source?.plugin === name
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Session events, tolerating both the current `snapshotEvents()` accessor and
|
|
311
|
+
* the older mutable `events` array (SDK 0.1.2-alpha.4 renamed it).
|
|
312
|
+
*/
|
|
313
|
+
function sessionEvents(session) {
|
|
314
|
+
if (Array.isArray(session?.events)) return session.events
|
|
315
|
+
if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
|
|
316
|
+
return []
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Visible surface positions, or undefined when the session exposes none. */
|
|
320
|
+
function visibleSeqSet(session) {
|
|
321
|
+
const nodes = session?.surface?.nodes
|
|
322
|
+
return Array.isArray(nodes) ? new Set(nodes) : undefined
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
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).
|
|
331
|
+
*/
|
|
332
|
+
function catalogHistory(agent) {
|
|
333
|
+
const session = agent?.session
|
|
334
|
+
const events = sessionEvents(session)
|
|
335
|
+
const visible = visibleSeqSet(session)
|
|
336
|
+
let published = false
|
|
337
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
338
|
+
const event = events[index]
|
|
339
|
+
if (event?.type !== 'user/message' || !isCatalogMessage(event.data)) continue
|
|
340
|
+
published = true
|
|
341
|
+
if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
|
|
342
|
+
return { published, text: textOf(event.data) }
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return { published }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** This plugin's catalog message inside one step's admitted batch, if any. */
|
|
349
|
+
function catalogMessage(messages) {
|
|
350
|
+
for (const message of messages) {
|
|
351
|
+
if (isCatalogMessage(message)) return { message, text: textOf(message) }
|
|
352
|
+
}
|
|
353
|
+
return undefined
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Drop one message from a step's admitted batch. */
|
|
357
|
+
function withoutMessage(decision, id) {
|
|
358
|
+
return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Register the surface staging, the PTC handoff, and the per-step catalog injection. */
|
|
362
|
+
export function apply(ctx, config) {
|
|
363
|
+
const descriptionMaxLength = integerAtLeast(
|
|
364
|
+
config?.descriptionMaxLength,
|
|
365
|
+
'descriptionMaxLength',
|
|
366
|
+
1,
|
|
367
|
+
DEFAULT_DESCRIPTION_MAX_LENGTH,
|
|
368
|
+
)
|
|
369
|
+
const anchorNames = anchorToolNames(config?.anchorTools)
|
|
370
|
+
const ptcEnabled = optionalBoolean(config?.ptcPresentation, 'ptcPresentation', true)
|
|
371
|
+
|
|
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()
|
|
377
|
+
|
|
378
|
+
// Session to agent, so the boundary events a session emits can reach the
|
|
379
|
+
// per-agent presentation declaration. Filled by every assembly.
|
|
380
|
+
const agentBySession = new WeakMap()
|
|
381
|
+
|
|
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()
|
|
386
|
+
|
|
387
|
+
// One-time warnings: a broken optional path must degrade, never spam.
|
|
388
|
+
let warned = false
|
|
389
|
+
const warnOnce = (detail) => {
|
|
390
|
+
if (warned) return
|
|
391
|
+
warned = true
|
|
392
|
+
try {
|
|
393
|
+
ctx.logger?.warn?.(`${name}: ${detail} — keeping the native tool surface`)
|
|
394
|
+
} catch {
|
|
395
|
+
// Logger unavailable — the guard exists only to avoid spamming.
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
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
|
+
const registry = () => ctx.get('tools')
|
|
403
|
+
|
|
404
|
+
/** Whether this deployment can present PTC at all: opted in and a runtime mounted. */
|
|
405
|
+
const ptcReady = () => ptcEnabled && ctx.get('codeRuntime') !== undefined
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Whether this session is still in its anchor turn. An empty `anchorTools`
|
|
409
|
+
* disables staging, so every session reads as promoted.
|
|
410
|
+
*/
|
|
411
|
+
const anchoring = (agent) => (
|
|
412
|
+
anchorNames.length > 0 && agent !== undefined && inAnchorTurn(sessionEvents(agent?.session))
|
|
413
|
+
)
|
|
414
|
+
|
|
415
|
+
/**
|
|
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.
|
|
425
|
+
*/
|
|
426
|
+
const presentPtc = (agent) => {
|
|
427
|
+
if (!ptcReady() || agent === undefined || ptcAgents.has(agent)) return
|
|
428
|
+
const tools = agent?.ctx?.tools
|
|
429
|
+
if (tools === undefined || typeof tools.presentAs !== 'function') {
|
|
430
|
+
warnOnce('no scoped tools view to declare PTC presentation')
|
|
431
|
+
return
|
|
432
|
+
}
|
|
433
|
+
ptcAgents.add(agent)
|
|
434
|
+
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')
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
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.
|
|
450
|
+
*/
|
|
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
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
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))
|
|
471
|
+
}
|
|
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))
|
|
477
|
+
}
|
|
478
|
+
if (!staged) return assembled
|
|
479
|
+
return { ...assembled, tools: anchorToolsOf(assembled.tools, anchorNames) }
|
|
480
|
+
}, { prepend: true })
|
|
481
|
+
|
|
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.
|
|
484
|
+
ctx.on('session/event', (session, event) => {
|
|
485
|
+
if (event?.type !== 'turn/start' && event?.type !== 'turn/end') return
|
|
486
|
+
const agent = session === undefined ? undefined : agentBySession.get(session)
|
|
487
|
+
if (agent === undefined || anchoring(agent)) return
|
|
488
|
+
presentPtc(agent)
|
|
489
|
+
})
|
|
490
|
+
|
|
491
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
492
|
+
const decision = await next()
|
|
493
|
+
if (decision.kind !== 'enter') return decision
|
|
494
|
+
const agent = payload?.agent
|
|
495
|
+
const entries = agent === undefined ? undefined : catalogByAgent.get(agent)
|
|
496
|
+
if (entries === undefined) return decision
|
|
497
|
+
|
|
498
|
+
const ptc = ptcReady()
|
|
499
|
+
const candidate = renderCatalogText(entries, ptc)
|
|
500
|
+
const history = catalogHistory(agent)
|
|
501
|
+
const existing = catalogMessage(decision.messages)
|
|
502
|
+
if (history.text === candidate) {
|
|
503
|
+
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
504
|
+
}
|
|
505
|
+
if (existing !== undefined && existing.text === candidate) return decision
|
|
506
|
+
if (!history.published && entries.length === 0) {
|
|
507
|
+
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
508
|
+
}
|
|
509
|
+
const catalog = createCatalogMessage(entries, ptc)
|
|
510
|
+
if (existing === undefined) {
|
|
511
|
+
return { ...decision, messages: [...decision.messages, catalog] }
|
|
512
|
+
}
|
|
513
|
+
return {
|
|
514
|
+
...decision,
|
|
515
|
+
messages: decision.messages.map(message => (message.id === existing.message.id ? catalog : message)),
|
|
516
|
+
}
|
|
517
|
+
}, { prepend: true })
|
|
518
|
+
}
|