@linxin666/dsh-liangshen 0.4.18 → 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/package.json +15 -15
- package/presets/liangshen/dispatcher-rules.mjs +87 -62
- package/presets/liangshen/fact-ledger.mjs +41 -25
- 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 -7
- package/presets/liangshen/tool-catalog.mjs +141 -99
- 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/composition.test.ts +26 -0
- package/src/composition.ts +9 -1
- package/src/index.ts +22 -4
|
@@ -88,13 +88,16 @@
|
|
|
88
88
|
|
|
89
89
|
import {
|
|
90
90
|
DEFAULT_MAX_ACTIVE_NAMESPACES,
|
|
91
|
-
|
|
91
|
+
TOOL_ACTIVATE_NAME,
|
|
92
92
|
integerAtLeast,
|
|
93
|
+
latestVisiblePluginMessage,
|
|
93
94
|
namespaceOf,
|
|
95
|
+
partitionWireTools,
|
|
96
|
+
reconcileStepMessage,
|
|
94
97
|
replayActivations,
|
|
98
|
+
sessionEvents,
|
|
95
99
|
summarizeInactive,
|
|
96
100
|
validatePagedToolPatterns,
|
|
97
|
-
withheldToolNames,
|
|
98
101
|
} from './paging.mjs'
|
|
99
102
|
|
|
100
103
|
/** Cordis plugin name used by loader diagnostics. */
|
|
@@ -122,7 +125,8 @@ const pagedSurfaceBySession = new WeakMap()
|
|
|
122
125
|
/**
|
|
123
126
|
* Publish (or, with `undefined`, retract) one scope's paged namespaces.
|
|
124
127
|
* @param agent - agent scope the partition belongs to.
|
|
125
|
-
* @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.
|
|
126
130
|
*/
|
|
127
131
|
function publishPagedSurface(agent, surface) {
|
|
128
132
|
if (agent === undefined || agent === null) return
|
|
@@ -198,6 +202,18 @@ export const DEFAULT_PRESENTATION = 'ptc'
|
|
|
198
202
|
*/
|
|
199
203
|
export const DEFAULT_MAX_RESIDENT_TOKENS = 8000
|
|
200
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
|
+
|
|
201
217
|
/**
|
|
202
218
|
* Rough token estimate for one tool surface: the serialized schema is the
|
|
203
219
|
* payload the request actually carries, and four characters per token is the
|
|
@@ -210,15 +226,40 @@ export function estimateSurfaceTokens(schemas) {
|
|
|
210
226
|
let characters = 0
|
|
211
227
|
for (const schema of Array.isArray(schemas) ? schemas : []) {
|
|
212
228
|
if (schema === null || schema === undefined) continue
|
|
213
|
-
|
|
214
|
-
characters += JSON.stringify(schema)?.length ?? 0
|
|
215
|
-
} catch {
|
|
216
|
-
// A hostile or circular schema contributes nothing rather than throwing.
|
|
217
|
-
}
|
|
229
|
+
characters += schemaCharacters(schema)
|
|
218
230
|
}
|
|
219
231
|
return Math.ceil(characters / 4)
|
|
220
232
|
}
|
|
221
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
|
+
|
|
222
263
|
/**
|
|
223
264
|
* Nesting depth beyond which an inline signature degrades to JsonValue. The
|
|
224
265
|
* rendering stays one line per tool, so deeply nested argument objects are
|
|
@@ -359,9 +400,10 @@ export const CURATED_TOOL_SUMMARIES = new Map([
|
|
|
359
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`).'],
|
|
360
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.'],
|
|
361
402
|
['list_subagent_models', 'Discover the subagent routes this session authorizes (`provider`, optional `model`); the returned ids feed the delegation tools.'],
|
|
362
|
-
['send_message', 'Send a message to
|
|
363
|
-
['list_agents', 'List the
|
|
364
|
-
['
|
|
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.'],
|
|
365
407
|
['ask_user_question', 'Ask the user a concise question and wait for the answer (`questions`: id, question, optional header, options, and custom input).'],
|
|
366
408
|
['web_search', 'Search the web for current information (one to four `queries`); returns a merged summary and its source URLs.'],
|
|
367
409
|
['skill', 'Load the full instructions of one session skill (`name`); call it before acting on a task that names or matches a skill.'],
|
|
@@ -566,23 +608,19 @@ export function renderCatalogText(entries, presentation = 'native', inactive = [
|
|
|
566
608
|
].join('\n')
|
|
567
609
|
}
|
|
568
610
|
|
|
569
|
-
/** Build the durable catalog message for one
|
|
570
|
-
|
|
611
|
+
/** Build the durable catalog message for one already-rendered text. */
|
|
612
|
+
function catalogMessageFor(text) {
|
|
571
613
|
return {
|
|
572
614
|
id: globalThis.crypto.randomUUID(),
|
|
573
615
|
role: 'user',
|
|
574
|
-
content: [{ type: 'text', text
|
|
616
|
+
content: [{ type: 'text', text }],
|
|
575
617
|
source: { kind: name },
|
|
576
618
|
}
|
|
577
619
|
}
|
|
578
620
|
|
|
579
|
-
/**
|
|
580
|
-
function
|
|
581
|
-
|
|
582
|
-
return blocks
|
|
583
|
-
.filter(block => block?.type === 'text' && typeof block.text === 'string')
|
|
584
|
-
.map(block => block.text)
|
|
585
|
-
.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))
|
|
586
624
|
}
|
|
587
625
|
|
|
588
626
|
/** Whether one message is this plugin's catalog. */
|
|
@@ -592,50 +630,16 @@ function isCatalogMessage(message) {
|
|
|
592
630
|
}
|
|
593
631
|
|
|
594
632
|
/**
|
|
595
|
-
*
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
/** Visible surface positions, or undefined when the session exposes none. */
|
|
604
|
-
function visibleSeqSet(session) {
|
|
605
|
-
const nodes = session?.surface?.nodes
|
|
606
|
-
return Array.isArray(nodes) ? new Set(nodes) : undefined
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
/**
|
|
610
|
-
* 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.
|
|
611
639
|
*/
|
|
612
|
-
function
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
const visible = visibleSeqSet(session)
|
|
616
|
-
let published = false
|
|
617
|
-
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
618
|
-
const event = events[index]
|
|
619
|
-
if (event?.type !== 'user/message' || !isCatalogMessage(event.data)) continue
|
|
620
|
-
published = true
|
|
621
|
-
if (visible === undefined || typeof event.seq !== 'number' || visible.has(event.seq)) {
|
|
622
|
-
return { published, text: textOf(event.data) }
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
return { published }
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
/** This plugin's catalog message inside one step's admitted batch, if any. */
|
|
629
|
-
function catalogMessage(messages) {
|
|
630
|
-
for (const message of messages) {
|
|
631
|
-
if (isCatalogMessage(message)) return { message, text: textOf(message) }
|
|
632
|
-
}
|
|
633
|
-
return undefined
|
|
634
|
-
}
|
|
635
|
-
|
|
636
|
-
/** Drop one message from a step's admitted batch. */
|
|
637
|
-
function withoutMessage(decision, id) {
|
|
638
|
-
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
|
|
639
643
|
}
|
|
640
644
|
|
|
641
645
|
/** Register the registry paging and the per-step catalog injection. */
|
|
@@ -681,7 +685,9 @@ export function apply(ctx, config) {
|
|
|
681
685
|
}
|
|
682
686
|
const presentation = resolvePresentation(config, detail => warnOnce(`presentation:${detail}`, detail))
|
|
683
687
|
|
|
684
|
-
// 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.
|
|
685
691
|
const agentCatalogState = new WeakMap()
|
|
686
692
|
|
|
687
693
|
// Session to agent mapping for lifecycle events
|
|
@@ -744,13 +750,33 @@ export function apply(ctx, config) {
|
|
|
744
750
|
// assembly-path emergency that warning describes.
|
|
745
751
|
const fullSurface = readSurface(agent, undefined, { quiet: true }) ?? []
|
|
746
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, [])
|
|
747
759
|
// Publish before the withhold decision: with every namespace already active
|
|
748
760
|
// there is nothing to restrict, and the activation tool must still know the
|
|
749
761
|
// namespace exists to report it as active instead of unknown.
|
|
750
|
-
publishPagedSurface(agent,
|
|
762
|
+
publishPagedSurface(agent, allPaged.inactive)
|
|
751
763
|
const active = replayActivations(sessionEvents(agent?.session), maxActiveNamespaces, pagedToolPatterns).active
|
|
752
|
-
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
|
+
}
|
|
753
778
|
if (withheld.length === 0) return undefined
|
|
779
|
+
withheld.sort()
|
|
754
780
|
|
|
755
781
|
try {
|
|
756
782
|
const dispose = tools.restrict({ deny: withheld })
|
|
@@ -758,7 +784,7 @@ export function apply(ctx, config) {
|
|
|
758
784
|
warnOnce('paging-runtime', 'the tool registry did not confirm the paging restriction — the paged namespaces stay reachable through a program in this session')
|
|
759
785
|
return undefined
|
|
760
786
|
}
|
|
761
|
-
const state = { active, inactive
|
|
787
|
+
const state = { active, inactive, dispose }
|
|
762
788
|
agentPaging.set(agent, state)
|
|
763
789
|
return state
|
|
764
790
|
} catch (err) {
|
|
@@ -896,6 +922,24 @@ export function apply(ctx, config) {
|
|
|
896
922
|
clearScopePaging(agent)
|
|
897
923
|
})
|
|
898
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
|
+
|
|
899
943
|
/**
|
|
900
944
|
* Re-sync after a call that can move the active set.
|
|
901
945
|
*
|
|
@@ -907,7 +951,8 @@ export function apply(ctx, config) {
|
|
|
907
951
|
* serializes independent read-only calls.
|
|
908
952
|
*/
|
|
909
953
|
ctx.on('tools/post-execute', (exec, _result, next) => {
|
|
910
|
-
|
|
954
|
+
const agent = exec?.agent
|
|
955
|
+
if (mayMovePaging(agent, exec?.name)) syncBeforeAssembly(agent)
|
|
911
956
|
return next()
|
|
912
957
|
}, { prepend: true })
|
|
913
958
|
|
|
@@ -955,24 +1000,25 @@ export function apply(ctx, config) {
|
|
|
955
1000
|
if (surface === undefined) {
|
|
956
1001
|
const previous = agentCatalogState.get(agent)
|
|
957
1002
|
if (previous !== undefined && previous.presentation !== effectivePresentation) {
|
|
958
|
-
|
|
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
|
+
})
|
|
959
1010
|
}
|
|
960
1011
|
return assembled
|
|
961
1012
|
}
|
|
962
1013
|
|
|
963
|
-
// 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
|
|
964
1016
|
// truncates: silently dropping a tool the session needs would trade a
|
|
965
1017
|
// measurable context cost for an unmeasurable capability loss.
|
|
966
|
-
const residentTokens =
|
|
1018
|
+
const { tokens: residentTokens, heaviest } = measureSurface(surface)
|
|
967
1019
|
if (residentTokens > maxResidentTokens) {
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
.map(tool => ({ name: typeof tool?.name === 'string' ? tool.name : '(unnamed)', tokens: estimateSurfaceTokens([tool]) }))
|
|
971
|
-
.sort((left, right) => right.tokens - left.tokens)
|
|
972
|
-
.slice(0, 3)
|
|
973
|
-
.map(entry => `${entry.name} (${entry.tokens})`)
|
|
974
|
-
.join(', ')
|
|
975
|
-
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`)
|
|
976
1022
|
}
|
|
977
1023
|
|
|
978
1024
|
// The page the registry enforces IS this request's page: the restriction was
|
|
@@ -1000,24 +1046,20 @@ export function apply(ctx, config) {
|
|
|
1000
1046
|
const state = agent === undefined ? undefined : agentCatalogState.get(agent)
|
|
1001
1047
|
if (state === undefined) return decision
|
|
1002
1048
|
|
|
1003
|
-
const
|
|
1004
|
-
const
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
return {
|
|
1019
|
-
...decision,
|
|
1020
|
-
messages: decision.messages.map(message => (message.id === existing.message.id ? catalog : message)),
|
|
1021
|
-
}
|
|
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
|
+
)
|
|
1022
1064
|
}, { prepend: true })
|
|
1023
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
|
}
|