@linxin666/dsh-liangshen 0.4.17 → 0.4.19
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 +4 -4
- package/README.zh.md +4 -4
- package/lib/client.js +52 -9
- package/lib/client.js.map +1 -1
- package/lib/index.js +28 -6
- package/lib/types/client/lever-controller.d.ts +26 -2
- package/lib/types/client/settings-entry-form.d.ts +1 -1
- package/package.json +15 -15
- package/presets/liangshen/dispatcher-rules.mjs +87 -62
- package/presets/liangshen/fact-ledger.mjs +42 -26
- package/presets/liangshen/minimal-prompt.mjs +35 -16
- package/presets/liangshen/paging.mjs +140 -7
- package/presets/liangshen/subagent-routes.mjs +11 -22
- package/presets/liangshen/tool-activate.mjs +1 -8
- package/presets/liangshen/tool-catalog.mjs +141 -100
- package/presets/liangshen/working-context.mjs +81 -95
- package/src/announce.test.ts +58 -0
- package/src/client/lever-controller.ts +57 -15
- package/src/client/settings-entry-form.ts +1 -1
- package/src/composition.test.ts +26 -0
- package/src/composition.ts +9 -1
- package/src/index.ts +22 -4
- package/tools/benchmark-driver.mjs +1 -1
- package/tools/benchmark-live-run.mjs +0 -1
- package/tools/benchmark-report.mjs +1 -2
- package/tools/check-dispatcher-rules.mjs +1 -1
- package/tools/probe-selftest.mjs +1 -1
|
@@ -88,14 +88,16 @@
|
|
|
88
88
|
|
|
89
89
|
import {
|
|
90
90
|
DEFAULT_MAX_ACTIVE_NAMESPACES,
|
|
91
|
-
|
|
92
|
-
inactiveNamespaces,
|
|
91
|
+
TOOL_ACTIVATE_NAME,
|
|
93
92
|
integerAtLeast,
|
|
93
|
+
latestVisiblePluginMessage,
|
|
94
94
|
namespaceOf,
|
|
95
|
+
partitionWireTools,
|
|
96
|
+
reconcileStepMessage,
|
|
95
97
|
replayActivations,
|
|
98
|
+
sessionEvents,
|
|
96
99
|
summarizeInactive,
|
|
97
100
|
validatePagedToolPatterns,
|
|
98
|
-
withheldToolNames,
|
|
99
101
|
} from './paging.mjs'
|
|
100
102
|
|
|
101
103
|
/** Cordis plugin name used by loader diagnostics. */
|
|
@@ -123,7 +125,8 @@ const pagedSurfaceBySession = new WeakMap()
|
|
|
123
125
|
/**
|
|
124
126
|
* Publish (or, with `undefined`, retract) one scope's paged namespaces.
|
|
125
127
|
* @param agent - agent scope the partition belongs to.
|
|
126
|
-
* @param surface - namespace-keyed namespaces, as
|
|
128
|
+
* @param surface - namespace-keyed namespaces, as one pre-activation partition
|
|
129
|
+
* (`partitionWireTools` with an empty active set) reports them.
|
|
127
130
|
*/
|
|
128
131
|
function publishPagedSurface(agent, surface) {
|
|
129
132
|
if (agent === undefined || agent === null) return
|
|
@@ -199,6 +202,18 @@ export const DEFAULT_PRESENTATION = 'ptc'
|
|
|
199
202
|
*/
|
|
200
203
|
export const DEFAULT_MAX_RESIDENT_TOKENS = 8000
|
|
201
204
|
|
|
205
|
+
/**
|
|
206
|
+
* The serialized character count one schema contributes, or 0 when it cannot be
|
|
207
|
+
* serialized at all (a hostile or circular definition).
|
|
208
|
+
*/
|
|
209
|
+
function schemaCharacters(schema) {
|
|
210
|
+
try {
|
|
211
|
+
return JSON.stringify(schema)?.length ?? 0
|
|
212
|
+
} catch {
|
|
213
|
+
return 0
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
202
217
|
/**
|
|
203
218
|
* Rough token estimate for one tool surface: the serialized schema is the
|
|
204
219
|
* payload the request actually carries, and four characters per token is the
|
|
@@ -211,15 +226,40 @@ export function estimateSurfaceTokens(schemas) {
|
|
|
211
226
|
let characters = 0
|
|
212
227
|
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
213
228
|
if (schema === null || schema === undefined) continue
|
|
214
|
-
|
|
215
|
-
characters += JSON.stringify(schema)?.length ?? 0
|
|
216
|
-
} catch {
|
|
217
|
-
// A hostile or circular schema contributes nothing rather than throwing.
|
|
218
|
-
}
|
|
229
|
+
characters += schemaCharacters(schema)
|
|
219
230
|
}
|
|
220
231
|
return Math.ceil(characters / 4)
|
|
221
232
|
}
|
|
222
233
|
|
|
234
|
+
/**
|
|
235
|
+
* One pass over one tool surface: its estimated token cost AND its heaviest
|
|
236
|
+
* tools, so the budget diagnostic never serializes the surface twice.
|
|
237
|
+
*
|
|
238
|
+
* The named tools are the ones a remedy should look at, and their order is a
|
|
239
|
+
* stable descending sort by their own estimate: the insertion below keeps the
|
|
240
|
+
* log order of equally heavy tools, exactly like sorting the whole list would.
|
|
241
|
+
* @param schemas - the tool schemas on the wire.
|
|
242
|
+
* @param count - how many heavy tools to name.
|
|
243
|
+
* @returns the estimated tokens plus the heaviest tools, heaviest first.
|
|
244
|
+
*/
|
|
245
|
+
function measureSurface(schemas, count = 3) {
|
|
246
|
+
let characters = 0
|
|
247
|
+
const heaviest = []
|
|
248
|
+
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
249
|
+
if (schema === null || schema === undefined) continue
|
|
250
|
+
const own = schemaCharacters(schema)
|
|
251
|
+
characters += own
|
|
252
|
+
const tokens = Math.ceil(own / 4)
|
|
253
|
+
const entry = { name: typeof schema?.name === 'string' ? schema.name : '(unnamed)', tokens }
|
|
254
|
+
let index = 0
|
|
255
|
+
while (index < heaviest.length && heaviest[index].tokens >= tokens) index += 1
|
|
256
|
+
if (index >= count) continue
|
|
257
|
+
heaviest.splice(index, 0, entry)
|
|
258
|
+
if (heaviest.length > count) heaviest.length = count
|
|
259
|
+
}
|
|
260
|
+
return { tokens: Math.ceil(characters / 4), heaviest }
|
|
261
|
+
}
|
|
262
|
+
|
|
223
263
|
/**
|
|
224
264
|
* Nesting depth beyond which an inline signature degrades to JsonValue. The
|
|
225
265
|
* rendering stays one line per tool, so deeply nested argument objects are
|
|
@@ -360,9 +400,10 @@ export const CURATED_TOOL_SUMMARIES = new Map([
|
|
|
360
400
|
['subagent', 'Delegate a self-contained task to a subagent that works in its own context and returns its result, not its steps (`description`, `prompt`, optional `provider` / `model` / `reasoning_effort`).'],
|
|
361
401
|
['subagent_fork', 'Delegate a task to a subagent seeded with this conversation (`description`, `prompt`); it inherits the parent route, so route fields are not accepted.'],
|
|
362
402
|
['list_subagent_models', 'Discover the subagent routes this session authorizes (`provider`, optional `model`); the returned ids feed the delegation tools.'],
|
|
363
|
-
['send_message', 'Send a message to
|
|
364
|
-
['list_agents', 'List the
|
|
365
|
-
['
|
|
403
|
+
['send_message', 'Send a message to an agent in the subagent tree (`agent`, `message`); a working agent receives it at its next step, an idle one starts a new turn.'],
|
|
404
|
+
['list_agents', 'List the entire subagent tree, the caller included, as rows of name, status and description; it takes no arguments.'],
|
|
405
|
+
['wait_agent', 'Wait for input at the next step: agent messages, completion notifications and user steering (`timeout_ms`, 10000 to 3600000, default 30000).'],
|
|
406
|
+
['interrupt_agent', 'Ask a subagent to stop its current work (`agent`); the call returns without waiting for it to settle.'],
|
|
366
407
|
['ask_user_question', 'Ask the user a concise question and wait for the answer (`questions`: id, question, optional header, options, and custom input).'],
|
|
367
408
|
['web_search', 'Search the web for current information (one to four `queries`); returns a merged summary and its source URLs.'],
|
|
368
409
|
['skill', 'Load the full instructions of one session skill (`name`); call it before acting on a task that names or matches a skill.'],
|
|
@@ -567,23 +608,19 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
|
|
|
567
608
|
].join('\n')
|
|
568
609
|
}
|
|
569
610
|
|
|
570
|
-
/** Build the durable catalog message for one
|
|
571
|
-
|
|
611
|
+
/** Build the durable catalog message for one already-rendered text. */
|
|
612
|
+
function catalogMessageFor(text) {
|
|
572
613
|
return {
|
|
573
614
|
id: globalThis.crypto.randomUUID(),
|
|
574
615
|
role: 'user',
|
|
575
|
-
content: [{ type: 'text', text
|
|
616
|
+
content: [{ type: 'text', text }],
|
|
576
617
|
source: { kind: name },
|
|
577
618
|
}
|
|
578
619
|
}
|
|
579
620
|
|
|
580
|
-
/**
|
|
581
|
-
function
|
|
582
|
-
|
|
583
|
-
return blocks
|
|
584
|
-
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
585
|
-
.map(block => block.text)
|
|
586
|
-
.join('\n')
|
|
621
|
+
/** Build the durable catalog message for one entry list. */
|
|
622
|
+
export function createCatalogMessage(entries, presentation = 'native', inactive = []) {
|
|
623
|
+
return catalogMessageFor(renderCatalogText(entries, presentation, inactive))
|
|
587
624
|
}
|
|
588
625
|
|
|
589
626
|
/** Whether one message is this plugin's catalog. */
|
|
@@ -593,50 +630,16 @@ function isCatalogMessage(message) {
|
|
|
593
630
|
}
|
|
594
631
|
|
|
595
632
|
/**
|
|
596
|
-
*
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
/** Visible surface positions, or undefined when the session exposes none. */
|
|
605
|
-
function visibleSeqSet(session) {
|
|
606
|
-
const nodes = session?.surface?.nodes
|
|
607
|
-
return Array.isArray(nodes) ? new Set(nodes) : undefined
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
/**
|
|
611
|
-
* Published catalog state read back from durable log.
|
|
633
|
+
* The catalog text for one assembly state, rendered once per state object.
|
|
634
|
+
*
|
|
635
|
+
* The state object is replaced by every assembly, so this memo only ever answers
|
|
636
|
+
* for one assembly: repeated pre-step reads against an unchanged surface re-render
|
|
637
|
+
* nothing, and a new assembly memoizes afresh. The text is appended here so the
|
|
638
|
+
* publish path builds its message from the same rendering.
|
|
612
639
|
*/
|
|
613
|
-
function
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
const visible = visibleSeqSet(session)
|
|
617
|
-
let published = false
|
|
618
|
-
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
619
|
-
const event = events[index]
|
|
620
|
-
if (event?.type !== 'user/message' || !isCatalogMessage(event.data)) continue
|
|
621
|
-
published = true
|
|
622
|
-
if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
|
|
623
|
-
return { published, text: textOf(event.data) }
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
return { published }
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
/** This plugin's catalog message inside one step's admitted batch, if any. */
|
|
630
|
-
function catalogMessage(messages) {
|
|
631
|
-
for (const message of messages) {
|
|
632
|
-
if (isCatalogMessage(message)) return { message, text: textOf(message) }
|
|
633
|
-
}
|
|
634
|
-
return undefined
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
/** Drop one message from a step's admitted batch. */
|
|
638
|
-
function withoutMessage(decision, id) {
|
|
639
|
-
return { ...decision, messages: decision.messages.filter(message => message.id !== id) }
|
|
640
|
+
function stateCatalogText(state) {
|
|
641
|
+
if (typeof state.text !== 'string') state.text = renderCatalogText(state.entries, state.presentation, state.inactive)
|
|
642
|
+
return state.text
|
|
640
643
|
}
|
|
641
644
|
|
|
642
645
|
/** Register the registry paging and the per-step catalog injection. */
|
|
@@ -682,7 +685,9 @@ export function apply(ctx, config) {
|
|
|
682
685
|
}
|
|
683
686
|
const presentation = resolvePresentation(config, detail => warnOnce(`presentation:${detail}`, detail))
|
|
684
687
|
|
|
685
|
-
// Per-agent fresh state evaluated on every assembly (never stale across
|
|
688
|
+
// Per-agent fresh state evaluated on every assembly (never stale across
|
|
689
|
+
// steps/turns). The catalog text is memoized on the state object itself, so the
|
|
690
|
+
// pre-step reads of one assembly render it once instead of once per read.
|
|
686
691
|
const agentCatalogState = new WeakMap()
|
|
687
692
|
|
|
688
693
|
// Session to agent mapping for lifecycle events
|
|
@@ -745,13 +750,33 @@ export function apply(ctx, config) {
|
|
|
745
750
|
// assembly-path emergency that warning describes.
|
|
746
751
|
const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
|
|
747
752
|
if (fullSurface.length === 0) return undefined
|
|
753
|
+
// ONE partition of the full surface, with the empty active set: it is both
|
|
754
|
+
// the publication the activation tool reads back (every paged namespace,
|
|
755
|
+
// active or not) and the basis the withhold list and the catalog summary are
|
|
756
|
+
// derived from, so the two halves of paging cannot disagree about which
|
|
757
|
+
// tools a namespace carries.
|
|
758
|
+
const allPaged = partitionWireTools(fullSurface, pagedToolPatterns, [])
|
|
748
759
|
// Publish before the withhold decision: with every namespace already active
|
|
749
760
|
// there is nothing to restrict, and the activation tool must still know the
|
|
750
761
|
// namespace exists to report it as active instead of unknown.
|
|
751
|
-
publishPagedSurface(agent,
|
|
762
|
+
publishPagedSurface(agent, allPaged.inactive)
|
|
752
763
|
const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active
|
|
753
|
-
const
|
|
764
|
+
const activeNames = new Set(active)
|
|
765
|
+
const withheld = []
|
|
766
|
+
const inactive = new Map()
|
|
767
|
+
for (const [namespace, group] of allPaged.inactive) {
|
|
768
|
+
if (activeNames.has(namespace)) continue
|
|
769
|
+
inactive.set(namespace, group)
|
|
770
|
+
for (const tool of group) {
|
|
771
|
+
if (typeof tool?.name !== 'string' || tool.name === '') continue
|
|
772
|
+
// The reserved transport cannot be named by a restriction, so paging
|
|
773
|
+
// must never be the reason a session loses it.
|
|
774
|
+
if (tool.name === 'run_code') continue
|
|
775
|
+
withheld.push(tool.name)
|
|
776
|
+
}
|
|
777
|
+
}
|
|
754
778
|
if (withheld.length === 0) return undefined
|
|
779
|
+
withheld.sort()
|
|
755
780
|
|
|
756
781
|
try {
|
|
757
782
|
const dispose = tools.restrict({ deny: withheld })
|
|
@@ -759,7 +784,7 @@ export function apply(ctx, config) {
|
|
|
759
784
|
warnOnce('paging-runtime', 'the tool registry did not confirm the paging restriction — the paged namespaces stay reachable through a program in this session')
|
|
760
785
|
return undefined
|
|
761
786
|
}
|
|
762
|
-
const state = { active, inactive
|
|
787
|
+
const state = { active, inactive, dispose }
|
|
763
788
|
agentPaging.set(agent, state)
|
|
764
789
|
return state
|
|
765
790
|
} catch (err) {
|
|
@@ -897,6 +922,24 @@ export function apply(ctx, config) {
|
|
|
897
922
|
clearScopePaging(agent)
|
|
898
923
|
})
|
|
899
924
|
|
|
925
|
+
/**
|
|
926
|
+
* Whether one completed call can move the active set at all.
|
|
927
|
+
*
|
|
928
|
+
* The paging replay reads exactly two shapes: an activation, and a call into a
|
|
929
|
+
* family that is ALREADY active (which only refreshes its recency). A call
|
|
930
|
+
* into a resident host builtin — the shell, the filesystem tools, the catalog's
|
|
931
|
+
* own readers — is neither, and a paged family that is still paged out cannot
|
|
932
|
+
* be reached at all, so a paged scope skips the resync for it and keeps the page
|
|
933
|
+
* it already installed. Deliberately conservative: a scope with no live
|
|
934
|
+
* restriction, a call that names no tool, and the transport itself keep the old
|
|
935
|
+
* path.
|
|
936
|
+
*/
|
|
937
|
+
const mayMovePaging = (agent, toolName) => !agentPaging.has(agent)
|
|
938
|
+
|| typeof toolName !== 'string'
|
|
939
|
+
|| toolName === TOOL_ACTIVATE_NAME
|
|
940
|
+
|| toolName === 'run_code'
|
|
941
|
+
|| namespaceOf(toolName, pagedToolPatterns) !== undefined
|
|
942
|
+
|
|
900
943
|
/**
|
|
901
944
|
* Re-sync after a call that can move the active set.
|
|
902
945
|
*
|
|
@@ -908,7 +951,8 @@ export function apply(ctx, config) {
|
|
|
908
951
|
* serializes independent read-only calls.
|
|
909
952
|
*/
|
|
910
953
|
ctx.on('tools/post-execute', (exec, _result, next) => {
|
|
911
|
-
|
|
954
|
+
const agent = exec?.agent
|
|
955
|
+
if (mayMovePaging(agent, exec?.name)) syncBeforeAssembly(agent)
|
|
912
956
|
return next()
|
|
913
957
|
}, { prepend: true })
|
|
914
958
|
|
|
@@ -956,24 +1000,25 @@ export function apply(ctx, config) {
|
|
|
956
1000
|
if (surface === undefined) {
|
|
957
1001
|
const previous = agentCatalogState.get(agent)
|
|
958
1002
|
if (previous !== undefined && previous.presentation !== effectivePresentation) {
|
|
959
|
-
|
|
1003
|
+
// A fresh state object on purpose: the memoized text belongs to the
|
|
1004
|
+
// presentation it was rendered for, so it must not travel along.
|
|
1005
|
+
agentCatalogState.set(agent, {
|
|
1006
|
+
entries: previous.entries,
|
|
1007
|
+
presentation: effectivePresentation,
|
|
1008
|
+
inactive: previous.inactive,
|
|
1009
|
+
})
|
|
960
1010
|
}
|
|
961
1011
|
return assembled
|
|
962
1012
|
}
|
|
963
1013
|
|
|
964
|
-
// Diagnostic guard on the always-on-wire surface
|
|
1014
|
+
// Diagnostic guard on the always-on-wire surface: ONE pass yields both the
|
|
1015
|
+
// total and the heaviest tools the remedy should name. It warns rather than
|
|
965
1016
|
// truncates: silently dropping a tool the session needs would trade a
|
|
966
1017
|
// measurable context cost for an unmeasurable capability loss.
|
|
967
|
-
const residentTokens =
|
|
1018
|
+
const { tokens: residentTokens, heaviest } = measureSurface(surface)
|
|
968
1019
|
if (residentTokens > maxResidentTokens) {
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
.map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
|
|
972
|
-
.sort((left, right) => right.tokens - left.tokens)
|
|
973
|
-
.slice(0, 3)
|
|
974
|
-
.map(entry => `${entry.name} (${entry.tokens})`)
|
|
975
|
-
.join(', ')
|
|
976
|
-
warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${surface.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${heaviest} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
|
|
1020
|
+
const named = heaviest.map(entry => `${entry.name} (${entry.tokens})`).join(', ')
|
|
1021
|
+
warnOnce('resident-budget', `the resident tool surface is about ${residentTokens} tokens across ${surface.length} tools, over the ${maxResidentTokens}-token budget; heaviest: ${named} — add matching families to pagedToolPatterns so they are held off the wire until activated`)
|
|
977
1022
|
}
|
|
978
1023
|
|
|
979
1024
|
// The page the registry enforces IS this request's page: the restriction was
|
|
@@ -1001,24 +1046,20 @@ export function apply(ctx, config) {
|
|
|
1001
1046
|
const state = agent === undefined ? undefined : agentCatalogState.get(agent)
|
|
1002
1047
|
if (state === undefined) return decision
|
|
1003
1048
|
|
|
1004
|
-
const
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
return {
|
|
1020
|
-
...decision,
|
|
1021
|
-
messages: decision.messages.map(message => (message.id === existing.message.id ? catalog : message)),
|
|
1022
|
-
}
|
|
1049
|
+
const candidate = stateCatalogText(state)
|
|
1050
|
+
const history = latestVisiblePluginMessage(agent, isCatalogMessage)
|
|
1051
|
+
// A surface that is empty AND was never published has nothing to announce:
|
|
1052
|
+
// publishing "no tools" for it is what made a seeded child session deny the
|
|
1053
|
+
// tools its own request carries (issue #2016). A surface that replaced a
|
|
1054
|
+
// published one does announce it, which is why the published flag is part of
|
|
1055
|
+
// the condition.
|
|
1056
|
+
const silent = !history.published && state.entries.length === 0 && state.inactive.length === 0
|
|
1057
|
+
return reconcileStepMessage(
|
|
1058
|
+
decision,
|
|
1059
|
+
history,
|
|
1060
|
+
candidate,
|
|
1061
|
+
() => (silent ? undefined : catalogMessageFor(candidate)),
|
|
1062
|
+
isCatalogMessage,
|
|
1063
|
+
)
|
|
1023
1064
|
}, { prepend: true })
|
|
1024
1065
|
}
|
|
@@ -20,21 +20,31 @@
|
|
|
20
20
|
* todos projection.
|
|
21
21
|
*
|
|
22
22
|
* When no field has anything to say the step is left untouched. The injection
|
|
23
|
-
* and dedup discipline
|
|
24
|
-
* persistent, carries the plugin source shape, and a
|
|
25
|
-
* only when the rendered line changed or the published
|
|
26
|
-
* surface.
|
|
23
|
+
* and dedup discipline is shared with tool-catalog's pre-step (paging.mjs owns
|
|
24
|
+
* it): the message is persistent, carries the plugin source shape, and a
|
|
25
|
+
* replacement is published only when the rendered line changed or the published
|
|
26
|
+
* copy left the visible surface.
|
|
27
|
+
*
|
|
28
|
+
* Every field folds in ONE pass over the durable stream: the plan-mode and todo
|
|
29
|
+
* projections, the register, and the failed-call index the activation replay
|
|
30
|
+
* needs are read event by event, and the replay itself only runs when the log
|
|
31
|
+
* holds an activation at all.
|
|
27
32
|
*/
|
|
28
33
|
|
|
29
34
|
import {
|
|
30
35
|
DEFAULT_MAX_ACTIVE_NAMESPACES,
|
|
31
36
|
DEFAULT_PAGED_TOOL_PATTERNS,
|
|
37
|
+
TOOL_ACTIVATE_NAME,
|
|
38
|
+
erroredCallId,
|
|
32
39
|
integerAtLeast,
|
|
40
|
+
latestVisiblePluginMessage,
|
|
41
|
+
reconcileStepMessage,
|
|
33
42
|
replayActivations,
|
|
43
|
+
sessionEvents,
|
|
34
44
|
validatePagedToolPatterns,
|
|
35
45
|
} from './paging.mjs'
|
|
36
46
|
|
|
37
|
-
import {
|
|
47
|
+
import { applyFactLedgerEvent, renderLedgerField } from './fact-ledger.mjs'
|
|
38
48
|
|
|
39
49
|
/** Cordis plugin name used by loader diagnostics. */
|
|
40
50
|
export const name = 'liangshen-working-context'
|
|
@@ -45,23 +55,33 @@ const MAX_TITLE_CHARS = 80
|
|
|
45
55
|
/** At most this many in-progress titles render; the rest collapse to a count. */
|
|
46
56
|
const MAX_TITLES = 3
|
|
47
57
|
|
|
48
|
-
/**
|
|
49
|
-
function
|
|
50
|
-
if (
|
|
51
|
-
|
|
52
|
-
|
|
58
|
+
/** Fold one event into the plan-mode projection: the last plan/mode event wins. */
|
|
59
|
+
function foldPlanMode(projection, event) {
|
|
60
|
+
if (event?.type !== 'plan/mode' || typeof event.data?.active !== 'boolean') return projection
|
|
61
|
+
projection.seen = true
|
|
62
|
+
projection.active = event.data.active
|
|
63
|
+
return projection
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Fold one event into the todo projection: the latest list, cleared by the next turn/start. */
|
|
67
|
+
function foldTodos(current, event) {
|
|
68
|
+
if (event?.type === 'turn/start') return undefined
|
|
69
|
+
if (event?.type === 'todo/write' && Array.isArray(event.data?.todos)) return event.data.todos
|
|
70
|
+
return current
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The in-progress titles of one folded todo list, in list order. */
|
|
74
|
+
function inProgressTitles(todos) {
|
|
75
|
+
return (todos ?? [])
|
|
76
|
+
.filter(item => item?.status === 'in_progress' && typeof item?.content === 'string' && item.content.trim() !== '')
|
|
77
|
+
.map(item => item.content.trim())
|
|
53
78
|
}
|
|
54
79
|
|
|
55
80
|
/** The latest plan/mode state in the log: seen flag plus active value. */
|
|
56
81
|
export function planModeState(events) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (event?.type !== 'plan/mode' || typeof event.data?.active !== 'boolean') continue
|
|
61
|
-
seen = true
|
|
62
|
-
active = event.data.active
|
|
63
|
-
}
|
|
64
|
-
return { seen, active }
|
|
82
|
+
const projection = { seen: false, active: false }
|
|
83
|
+
for (const event of Array.isArray(events) ? events : []) foldPlanMode(projection, event)
|
|
84
|
+
return projection
|
|
65
85
|
}
|
|
66
86
|
|
|
67
87
|
/**
|
|
@@ -70,18 +90,8 @@ export function planModeState(events) {
|
|
|
70
90
|
*/
|
|
71
91
|
export function inProgressTodos(events) {
|
|
72
92
|
let todos
|
|
73
|
-
for (const event of Array.isArray(events) ? events : [])
|
|
74
|
-
|
|
75
|
-
todos = undefined
|
|
76
|
-
continue
|
|
77
|
-
}
|
|
78
|
-
if (event?.type === 'todo/write' && Array.isArray(event.data?.todos)) {
|
|
79
|
-
todos = event.data.todos
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
return (todos ?? [])
|
|
83
|
-
.filter(item => item?.status === 'in_progress' && typeof item?.content === 'string' && item.content.trim() !== '')
|
|
84
|
-
.map(item => item.content.trim())
|
|
93
|
+
for (const event of Array.isArray(events) ? events : []) todos = foldTodos(todos, event)
|
|
94
|
+
return inProgressTitles(todos)
|
|
85
95
|
}
|
|
86
96
|
|
|
87
97
|
/** Clip one title to the per-title budget at a word-ish boundary. */
|
|
@@ -93,19 +103,43 @@ function clipTitle(title) {
|
|
|
93
103
|
/**
|
|
94
104
|
* Render the working-context line for one session's events, or undefined when
|
|
95
105
|
* no field has anything objective to say.
|
|
106
|
+
*
|
|
107
|
+
* One pass over the stream folds everything this line renders plus the two
|
|
108
|
+
* facts the activation replay needs — the failed callIds and whether any
|
|
109
|
+
* activation was recorded at all. Without an activation the replay cannot find
|
|
110
|
+
* an active namespace (it reads activations, plus the recency of families one of
|
|
111
|
+
* them already lifted), so the second pass is skipped instead of walking the
|
|
112
|
+
* whole log again to derive an empty set.
|
|
96
113
|
*/
|
|
97
114
|
export function renderWorkingContext(events, options) {
|
|
98
115
|
const patterns = options?.pagedToolPatterns ?? DEFAULT_PAGED_TOOL_PATTERNS
|
|
99
116
|
const maxActive = options?.maxActiveNamespaces ?? DEFAULT_MAX_ACTIVE_NAMESPACES
|
|
100
|
-
const
|
|
117
|
+
const list = Array.isArray(events) ? events : []
|
|
118
|
+
const plan = { seen: false, active: false }
|
|
119
|
+
const facts = []
|
|
120
|
+
const errored = new Set()
|
|
121
|
+
let todos
|
|
122
|
+
let sawActivation = false
|
|
123
|
+
for (const event of list) {
|
|
124
|
+
foldPlanMode(plan, event)
|
|
125
|
+
todos = foldTodos(todos, event)
|
|
126
|
+
applyFactLedgerEvent(facts, event)
|
|
127
|
+
const failedCallId = erroredCallId(event)
|
|
128
|
+
if (failedCallId !== undefined) errored.add(failedCallId)
|
|
129
|
+
if ((event?.type === 'tool/call' || event?.type === 'tool/ptc-dispatch') && event.data?.name === TOOL_ACTIVATE_NAME) {
|
|
130
|
+
sawActivation = true
|
|
131
|
+
}
|
|
132
|
+
}
|
|
101
133
|
|
|
102
|
-
const
|
|
134
|
+
const fields = []
|
|
103
135
|
if (plan.seen) fields.push(`plan mode: ${plan.active ? 'on' : 'off'}`)
|
|
104
136
|
|
|
105
|
-
|
|
106
|
-
|
|
137
|
+
if (sawActivation) {
|
|
138
|
+
const { active } = replayActivations(list, maxActive, patterns, errored)
|
|
139
|
+
if (active.length > 0) fields.push(`active namespaces: ${[...active].sort().join(', ')}`)
|
|
140
|
+
}
|
|
107
141
|
|
|
108
|
-
const titles =
|
|
142
|
+
const titles = inProgressTitles(todos)
|
|
109
143
|
if (titles.length > 0) {
|
|
110
144
|
const shown = titles.slice(0, MAX_TITLES).map(clipTitle)
|
|
111
145
|
const rest = titles.length - shown.length
|
|
@@ -115,53 +149,18 @@ export function renderWorkingContext(events, options) {
|
|
|
115
149
|
// The key-fact register: facts the model pinned with fact_register, folded
|
|
116
150
|
// from the same event stream, ride this line so they land inside the local
|
|
117
151
|
// attention window every step.
|
|
118
|
-
const ledgerField = renderLedgerField(
|
|
152
|
+
const ledgerField = renderLedgerField(facts)
|
|
119
153
|
if (ledgerField !== undefined) fields.push(ledgerField)
|
|
120
154
|
|
|
121
155
|
return fields.length === 0 ? undefined : `[Working Context: ${fields.join(' | ')}]`
|
|
122
156
|
}
|
|
123
157
|
|
|
124
|
-
/** The text one message contributes, joined across its text blocks. */
|
|
125
|
-
function textOf(message) {
|
|
126
|
-
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
127
|
-
return blocks
|
|
128
|
-
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
129
|
-
.map(block => block.text)
|
|
130
|
-
.join('\n')
|
|
131
|
-
}
|
|
132
|
-
|
|
133
158
|
/** Whether one message is this plugin's working-context line. */
|
|
134
159
|
function isContextMessage(message) {
|
|
135
160
|
const source = message?.source
|
|
136
161
|
return source?.kind === name || (source?.kind === 'plugin' && source?.plugin === name)
|
|
137
162
|
}
|
|
138
163
|
|
|
139
|
-
/** Visible surface positions, or undefined when the session exposes none. */
|
|
140
|
-
function visibleSeqSet(session) {
|
|
141
|
-
const nodes = session?.surface?.nodes
|
|
142
|
-
return Array.isArray(nodes) ? new Set(nodes) : undefined
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/**
|
|
146
|
-
* Published working-context state read back from the durable log: the latest
|
|
147
|
-
* visible line's text, or just the published flag when every copy was shadowed.
|
|
148
|
-
*/
|
|
149
|
-
function contextHistory(agent) {
|
|
150
|
-
const session = agent?.session
|
|
151
|
-
const events = sessionEvents(session)
|
|
152
|
-
const visible = visibleSeqSet(session)
|
|
153
|
-
let published = false
|
|
154
|
-
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
155
|
-
const event = events[index]
|
|
156
|
-
if (event?.type !== 'user/message' || !isContextMessage(event.data)) continue
|
|
157
|
-
published = true
|
|
158
|
-
if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
|
|
159
|
-
return { published, text: textOf(event.data) }
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
return { published }
|
|
163
|
-
}
|
|
164
|
-
|
|
165
164
|
/** Build the durable working-context message for one rendered line. */
|
|
166
165
|
export function createContextMessage(line) {
|
|
167
166
|
return {
|
|
@@ -194,29 +193,16 @@ export function apply(ctx, config) {
|
|
|
194
193
|
maxActiveNamespaces,
|
|
195
194
|
})
|
|
196
195
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
//
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
if (existing === undefined) return decision
|
|
209
|
-
return { ...decision, messages: decision.messages.filter(message => message.id !== existing.id) }
|
|
210
|
-
}
|
|
211
|
-
if (existing !== undefined && textOf(existing) === line) return decision
|
|
212
|
-
|
|
213
|
-
const message = createContextMessage(line)
|
|
214
|
-
if (existing === undefined) {
|
|
215
|
-
return { ...decision, messages: [...decision.messages, message] }
|
|
216
|
-
}
|
|
217
|
-
return {
|
|
218
|
-
...decision,
|
|
219
|
-
messages: decision.messages.map(item => (item.id === existing.id ? message : item)),
|
|
220
|
-
}
|
|
196
|
+
// Nothing objective to say: inject nothing (a stale published line is left
|
|
197
|
+
// for compaction to age out rather than replaced with an empty marker). The
|
|
198
|
+
// reconciliation is shared with tool-catalog's pre-step, so the two durable
|
|
199
|
+
// messages republish under exactly the same rules.
|
|
200
|
+
return reconcileStepMessage(
|
|
201
|
+
decision,
|
|
202
|
+
latestVisiblePluginMessage(agent, isContextMessage),
|
|
203
|
+
line,
|
|
204
|
+
() => createContextMessage(line),
|
|
205
|
+
isContextMessage,
|
|
206
|
+
)
|
|
221
207
|
}, { prepend: true })
|
|
222
208
|
}
|