@linxin666/dsh-liangshen 0.3.20 → 0.3.22
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 +69 -39
- package/README.zh.md +70 -40
- package/lib/client.js +640 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +11 -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 +11 -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 +29 -2
- package/presets/liangshen/NOTICE +4 -3
- package/presets/liangshen/agent.cordis.yml +129 -86
- package/presets/liangshen/custom-bash.mjs +4 -4
- package/presets/liangshen/minimal-prompt.mjs +835 -0
- package/presets/liangshen/tool-catalog.mjs +631 -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 +11 -6
- package/src/schema.test.ts +1 -1
- package/src/sync.test.ts +4 -4
- package/tools/analyze-session.mjs +25 -5
- package/tools/benchmark-driver.mjs +124 -0
- package/tools/benchmark-live-run.mjs +771 -0
- package/tools/benchmark-report.mjs +354 -0
- package/tools/tasks/liangshen-v41-flash.json +127 -0
- package/presets/liangshen/tool-bootstrap.mjs +0 -601
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tool-catalog — staged model-visible tool surface for LiangShen mode:
|
|
3
|
+
* anchor turn's native wire, PTC handoff at turn boundary, and durable catalog message.
|
|
4
|
+
*
|
|
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.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Cordis plugin name used by loader diagnostics. */
|
|
21
|
+
export const name = 'liangshen-tool-catalog'
|
|
22
|
+
|
|
23
|
+
/** Prompt assembly must exist before the wire catalog can be observed. */
|
|
24
|
+
export const inject = ['systemPrompt']
|
|
25
|
+
|
|
26
|
+
/** Default cap for one tool's one-line summary in the injected compact list. */
|
|
27
|
+
const DEFAULT_DESCRIPTION_MAX_LENGTH = 200
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Nesting depth beyond which an inline signature degrades to JsonValue. The
|
|
31
|
+
* rendering stays one line per tool, so deeply nested argument objects are
|
|
32
|
+
* summarized in the inline summary rather than expanded into an unreadable line.
|
|
33
|
+
*/
|
|
34
|
+
const MAX_SIGNATURE_DEPTH = 4
|
|
35
|
+
|
|
36
|
+
/** Types the compact signature renders exactly; everything else degrades. */
|
|
37
|
+
const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean', 'null'])
|
|
38
|
+
|
|
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
|
+
function optionalBoolean(value, field, fallback) {
|
|
48
|
+
if (value === undefined) return fallback
|
|
49
|
+
if (typeof value !== 'boolean') {
|
|
50
|
+
throw new TypeError(`${name}: ${field} must be a boolean`)
|
|
51
|
+
}
|
|
52
|
+
return value
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Parse the anchorTools config: absent means staging off, entries must be non-empty names. */
|
|
56
|
+
function anchorToolNames(value) {
|
|
57
|
+
if (value === undefined) return []
|
|
58
|
+
if (!Array.isArray(value)) {
|
|
59
|
+
throw new TypeError(`${name}: anchorTools must be an array of tool names`)
|
|
60
|
+
}
|
|
61
|
+
return value.map((entry) => {
|
|
62
|
+
if (typeof entry !== 'string' || entry.trim() === '') {
|
|
63
|
+
throw new TypeError(`${name}: anchorTools entries must be non-empty tool names`)
|
|
64
|
+
}
|
|
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
|
+
}
|
|
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
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* One-line model-facing summary of a tool description: whitespace collapsed,
|
|
94
|
+
* truncated with an ellipsis when maxLength is specified.
|
|
95
|
+
*/
|
|
96
|
+
export function catalogDescription(value, maxLength) {
|
|
97
|
+
const normalized = String(value ?? '').replaceAll(/\s+/g, ' ').trim()
|
|
98
|
+
if (maxLength === undefined || maxLength <= 0 || normalized.length <= maxLength) return normalized
|
|
99
|
+
return `${normalized.slice(0, maxLength - 3)}...`
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** One scalar literal as TypeScript-ish text; non-JSON scalars degrade to the broad type. */
|
|
103
|
+
function renderLiteral(value) {
|
|
104
|
+
const json = JSON.stringify(value)
|
|
105
|
+
return json === undefined ? 'JsonValue' : json
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
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.
|
|
111
|
+
*/
|
|
112
|
+
export function renderJsonSchemaType(schema, depth = 0) {
|
|
113
|
+
if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return 'JsonValue'
|
|
114
|
+
const union = Array.isArray(schema.oneOf) ? schema.oneOf : Array.isArray(schema.anyOf) ? schema.anyOf : undefined
|
|
115
|
+
if (union !== undefined && union.length > 0) {
|
|
116
|
+
const parts = union.map(node => renderJsonSchemaType(node, depth))
|
|
117
|
+
return [...new Set(parts)].join(' | ')
|
|
118
|
+
}
|
|
119
|
+
if (Object.hasOwn(schema, 'const')) return renderLiteral(schema.const)
|
|
120
|
+
if (Array.isArray(schema.enum) && schema.enum.length > 0) return schema.enum.map(renderLiteral).join(' | ')
|
|
121
|
+
if (Array.isArray(schema.type)) {
|
|
122
|
+
const parts = schema.type.map(type => (typeof type === 'string' ? type : 'JsonValue'))
|
|
123
|
+
return [...new Set(parts)].join(' | ')
|
|
124
|
+
}
|
|
125
|
+
if (SCALAR_TYPES.has(schema.type)) return schema.type === 'integer' ? 'number' : schema.type
|
|
126
|
+
if (schema.type === 'array') {
|
|
127
|
+
const items = schema.items === undefined ? 'JsonValue' : renderJsonSchemaType(schema.items, depth + 1)
|
|
128
|
+
return items.includes('|') ? `(${items})[]` : `${items}[]`
|
|
129
|
+
}
|
|
130
|
+
if (schema.type === 'object' || schema.properties !== undefined) {
|
|
131
|
+
if (depth >= MAX_SIGNATURE_DEPTH) return 'JsonValue'
|
|
132
|
+
const properties = schema.properties !== undefined && typeof schema.properties === 'object' && !Array.isArray(schema.properties)
|
|
133
|
+
? Object.entries(schema.properties)
|
|
134
|
+
: []
|
|
135
|
+
if (properties.length === 0) return 'Record<string, JsonValue>'
|
|
136
|
+
const required = new Set(Array.isArray(schema.required) ? schema.required : [])
|
|
137
|
+
const fields = properties.map(([field, child]) => (
|
|
138
|
+
`${field}${required.has(field) ? '' : '?'}: ${renderJsonSchemaType(child, depth + 1)}`
|
|
139
|
+
))
|
|
140
|
+
return `{ ${fields.join(', ')} }`
|
|
141
|
+
}
|
|
142
|
+
return 'JsonValue'
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The parenthesized argument signature of one tool, e.g.
|
|
147
|
+
* ({ command: string, timeoutMs?: number }). Empty when the parameter schema
|
|
148
|
+
* carries nothing to say.
|
|
149
|
+
*/
|
|
150
|
+
export function renderSignature(parameters) {
|
|
151
|
+
if (parameters === null || typeof parameters !== 'object' || Array.isArray(parameters)) return ''
|
|
152
|
+
const type = renderJsonSchemaType(parameters)
|
|
153
|
+
return type === 'JsonValue' ? '' : `(${type})`
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Catalog entries for one tool surface, sorted by name so an unchanged surface
|
|
158
|
+
* renders byte-identical text across assemblies. Nameless definitions and
|
|
159
|
+
* the run_code transport tool are skipped.
|
|
160
|
+
*/
|
|
161
|
+
export function catalogEntries(schemas, maxLength) {
|
|
162
|
+
const entries = []
|
|
163
|
+
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
164
|
+
const toolName = schema?.name
|
|
165
|
+
if (typeof toolName !== 'string' || toolName === '' || toolName === 'run_code') continue
|
|
166
|
+
entries.push({
|
|
167
|
+
name: toolName,
|
|
168
|
+
signature: renderSignature(schema.parameters),
|
|
169
|
+
description: catalogDescription(schema.description, maxLength),
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
return entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* The program contract the injected message carries under PTC.
|
|
177
|
+
*/
|
|
178
|
+
const PTC_PROGRAM_LINES = [
|
|
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:',
|
|
180
|
+
'',
|
|
181
|
+
'- reach a tool as `await tools.<name>({ ... })` — quoted access for exotic names, `tools["my-tool"]({ ... })`;',
|
|
182
|
+
'- 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`;',
|
|
183
|
+
'- a failed call rejects with `ToolCallError`, whose `toolName` and human-readable message identify it — `try/catch` it to continue;',
|
|
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.',
|
|
185
|
+
'',
|
|
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.",
|
|
187
|
+
]
|
|
188
|
+
|
|
189
|
+
/**
|
|
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.
|
|
195
|
+
*/
|
|
196
|
+
export function renderCatalogText(entries, ptc) {
|
|
197
|
+
const available = entries.length === 0
|
|
198
|
+
? ['No tools are currently available in this session.']
|
|
199
|
+
: [
|
|
200
|
+
'<available_tools>',
|
|
201
|
+
...entries.map(entry => `- \`${entry.name}${entry.signature}\`: ${entry.description}`),
|
|
202
|
+
'</available_tools>',
|
|
203
|
+
]
|
|
204
|
+
const footer = 'This is the complete current list and replaces any earlier available-tools list in this session.'
|
|
205
|
+
return [
|
|
206
|
+
'<system-reminder>',
|
|
207
|
+
'The following tools are available in this session:',
|
|
208
|
+
'',
|
|
209
|
+
...available,
|
|
210
|
+
'',
|
|
211
|
+
footer,
|
|
212
|
+
...(ptc ? ['', ...PTC_PROGRAM_LINES] : []),
|
|
213
|
+
'</system-reminder>',
|
|
214
|
+
].join('\n')
|
|
215
|
+
}
|
|
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
|
+
|
|
241
|
+
/** Build the durable catalog message for one entry list. */
|
|
242
|
+
export function createCatalogMessage(entries, ptc) {
|
|
243
|
+
return {
|
|
244
|
+
id: globalThis.crypto.randomUUID(),
|
|
245
|
+
role: 'user',
|
|
246
|
+
content: [{ type: 'text', text: renderCatalogText(entries, ptc) }],
|
|
247
|
+
source: { kind: 'plugin', plugin: name },
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** The text one message contributes, joined across its text blocks. */
|
|
252
|
+
function textOf(message) {
|
|
253
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
254
|
+
return blocks
|
|
255
|
+
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
256
|
+
.map(block => block.text)
|
|
257
|
+
.join('\n')
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Whether one message is this plugin's catalog. */
|
|
261
|
+
function isCatalogMessage(message) {
|
|
262
|
+
const source = message?.source
|
|
263
|
+
return source?.kind === 'plugin' && source?.plugin === name
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Session events, tolerating both snapshotEvents() and events array.
|
|
268
|
+
*/
|
|
269
|
+
function sessionEvents(session) {
|
|
270
|
+
if (Array.isArray(session?.events)) return session.events
|
|
271
|
+
if (typeof session?.snapshotEvents === 'function') return session.snapshotEvents()
|
|
272
|
+
return []
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Visible surface positions, or undefined when the session exposes none. */
|
|
276
|
+
function visibleSeqSet(session) {
|
|
277
|
+
const nodes = session?.surface?.nodes
|
|
278
|
+
return Array.isArray(nodes) ? new Set(nodes) : undefined
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Published catalog state read back from durable log.
|
|
283
|
+
*/
|
|
284
|
+
function catalogHistory(agent) {
|
|
285
|
+
const session = agent?.session
|
|
286
|
+
const events = sessionEvents(session)
|
|
287
|
+
const visible = visibleSeqSet(session)
|
|
288
|
+
let published = false
|
|
289
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
290
|
+
const event = events[index]
|
|
291
|
+
if (event?.type !== 'user/message' || !isCatalogMessage(event.data)) continue
|
|
292
|
+
published = true
|
|
293
|
+
if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
|
|
294
|
+
return { published, text: textOf(event.data) }
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return { published }
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** This plugin's catalog message inside one step's admitted batch, if any. */
|
|
301
|
+
function catalogMessage(messages) {
|
|
302
|
+
for (const message of messages) {
|
|
303
|
+
if (isCatalogMessage(message)) return { message, text: textOf(message) }
|
|
304
|
+
}
|
|
305
|
+
return undefined
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Drop one message from a step's admitted batch. */
|
|
309
|
+
function withoutMessage(decision, id) {
|
|
310
|
+
return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Register the surface staging, the PTC handoff, and the per-step catalog injection. */
|
|
314
|
+
export function apply(ctx, config) {
|
|
315
|
+
const descriptionMaxLength = integerAtLeast(
|
|
316
|
+
config?.descriptionMaxLength,
|
|
317
|
+
'descriptionMaxLength',
|
|
318
|
+
1,
|
|
319
|
+
DEFAULT_DESCRIPTION_MAX_LENGTH,
|
|
320
|
+
)
|
|
321
|
+
const anchorNames = anchorToolNames(config?.anchorTools)
|
|
322
|
+
const ptcPlanEnabled = optionalBoolean(config?.ptcPresentation, 'ptcPresentation', true)
|
|
323
|
+
|
|
324
|
+
// Per-agent fresh state evaluated on every assembly (never stale across steps/turns)
|
|
325
|
+
const agentCatalogState = new WeakMap()
|
|
326
|
+
|
|
327
|
+
// Session to agent mapping for boundary events
|
|
328
|
+
const agentBySession = new WeakMap()
|
|
329
|
+
|
|
330
|
+
// Presentation status tracking per agent
|
|
331
|
+
const agentPtcDeclared = new WeakSet()
|
|
332
|
+
const agentPtcFailed = new WeakSet()
|
|
333
|
+
const agentPtcDisposers = new WeakMap()
|
|
334
|
+
|
|
335
|
+
let warned = false
|
|
336
|
+
const warnOnce = (detail) => {
|
|
337
|
+
if (warned) return
|
|
338
|
+
warned = true
|
|
339
|
+
try {
|
|
340
|
+
ctx.logger?.warn?.(`${name}: ${detail} — keeping the native tool surface`)
|
|
341
|
+
} catch {
|
|
342
|
+
// Logger unavailable
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const registry = () => ctx.get('tools')
|
|
347
|
+
|
|
348
|
+
/** Whether PTC is planned and capable in this deployment. */
|
|
349
|
+
const ptcPlanReady = () => ptcPlanEnabled && ctx.get('codeRuntime') !== undefined
|
|
350
|
+
|
|
351
|
+
/** Whether this session is still in its anchor turn. */
|
|
352
|
+
const anchoring = (agent) => (
|
|
353
|
+
anchorNames.length > 0 && agent !== undefined && inAnchorTurn(sessionEvents(agent?.session))
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Declare PTC presentation for one agent using public agent.ctx.tools.presentAs('ptc').
|
|
358
|
+
*/
|
|
359
|
+
const presentPtc = (agent) => {
|
|
360
|
+
if (!ptcPlanReady() || agent === undefined) return false
|
|
361
|
+
if (agentPtcDeclared.has(agent)) return true
|
|
362
|
+
if (agentPtcFailed.has(agent)) return false
|
|
363
|
+
|
|
364
|
+
const tools = agent?.ctx?.tools
|
|
365
|
+
if (tools === undefined || typeof tools.presentAs !== 'function') {
|
|
366
|
+
agentPtcFailed.add(agent)
|
|
367
|
+
warnOnce('no scoped tools view to declare PTC presentation')
|
|
368
|
+
return false
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
try {
|
|
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
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Abort/revert PTC declaration if active, restoring presentation back to native.
|
|
387
|
+
*/
|
|
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)
|
|
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)
|
|
405
|
+
}
|
|
406
|
+
|
|
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
|
|
415
|
+
}
|
|
416
|
+
const reg = registry()
|
|
417
|
+
if (typeof reg?.schemas === 'function' || typeof reg?.sdkSchemas === 'function') {
|
|
418
|
+
return reg
|
|
419
|
+
}
|
|
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
|
+
}
|
|
454
|
+
|
|
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
|
|
491
|
+
ctx.on('session/event', (session, event) => {
|
|
492
|
+
if (event?.type !== 'turn/start' && event?.type !== 'turn/end') return
|
|
493
|
+
const agent = session === undefined ? undefined : agentBySession.get(session)
|
|
494
|
+
if (agent === undefined || anchoring(agent) || !ptcPlanReady()) return
|
|
495
|
+
presentPtc(agent)
|
|
496
|
+
})
|
|
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
|
+
|
|
604
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
605
|
+
const decision = await next()
|
|
606
|
+
if (decision.kind !== 'enter') return decision
|
|
607
|
+
const agent = payload?.agent
|
|
608
|
+
const state = catalogStateFor(agent)
|
|
609
|
+
if (state === undefined) return decision
|
|
610
|
+
|
|
611
|
+
const { entries, ptc } = state
|
|
612
|
+
const candidate = renderCatalogText(entries, ptc)
|
|
613
|
+
const history = catalogHistory(agent)
|
|
614
|
+
const existing = catalogMessage(decision.messages)
|
|
615
|
+
if (history.text === candidate) {
|
|
616
|
+
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
617
|
+
}
|
|
618
|
+
if (existing !== undefined && existing.text === candidate) return decision
|
|
619
|
+
if (!history.published && entries.length === 0) {
|
|
620
|
+
return existing === undefined ? decision : withoutMessage(decision, existing.message.id)
|
|
621
|
+
}
|
|
622
|
+
const catalog = createCatalogMessage(entries, ptc)
|
|
623
|
+
if (existing === undefined) {
|
|
624
|
+
return { ...decision, messages: [...decision.messages, catalog] }
|
|
625
|
+
}
|
|
626
|
+
return {
|
|
627
|
+
...decision,
|
|
628
|
+
messages: decision.messages.map(message => (message.id === existing.message.id ? catalog : message)),
|
|
629
|
+
}
|
|
630
|
+
}, { prepend: true })
|
|
631
|
+
}
|