dsh-context-compression-improved 0.7.0-beta.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.ja.md +217 -220
  3. package/CHANGELOG.ko.md +211 -214
  4. package/CHANGELOG.md +401 -376
  5. package/CHANGELOG.zh.md +196 -199
  6. package/README.md +97 -97
  7. package/README.zh.md +86 -86
  8. package/package.json +1 -1
  9. package/packages/selector/dsh.plugin.json +1 -1
  10. package/packages/selector/lib/client.d.ts +44 -0
  11. package/packages/selector/lib/client.js +1733 -6
  12. package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
  13. package/packages/selector/lib/index.d.ts +13 -1
  14. package/packages/selector/lib/index.js +204 -3
  15. package/packages/selector/lib/profiles.d.ts +6 -0
  16. package/packages/selector/lib/pruner.d.ts +6 -0
  17. package/packages/selector/lib/pruner.js +90 -258
  18. package/packages/selector/lib/style.css +88 -46
  19. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
  20. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  21. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
  22. package/packages/selector/src/client/decode.ts +57 -53
  23. package/packages/selector/src/client/index.ts +307 -213
  24. package/packages/selector/src/client/locales/de.ts +141 -0
  25. package/packages/selector/src/client/locales/es.ts +141 -0
  26. package/packages/selector/src/client/locales/fr.ts +141 -0
  27. package/packages/selector/src/client/locales/it.ts +141 -0
  28. package/packages/selector/src/client/locales/ja.ts +141 -0
  29. package/packages/selector/src/client/locales/ko.ts +141 -0
  30. package/packages/selector/src/client/locales/ru.ts +141 -0
  31. package/packages/selector/src/client/locales.ts +282 -196
  32. package/packages/selector/src/client/monitor-fab.ts +336 -0
  33. package/packages/selector/src/client/savings-card.tsx +150 -0
  34. package/packages/selector/src/client/settings-section.tsx +140 -124
  35. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  36. package/packages/selector/src/index.ts +207 -5
  37. package/packages/selector/src/preset-overlay.ts +629 -629
  38. package/packages/selector/src/profiles.ts +431 -414
  39. package/packages/selector/src/pruner/content.ts +198 -198
  40. package/packages/selector/src/pruner/state.ts +57 -57
  41. package/packages/selector/src/pruner.ts +2759 -2665
  42. package/packages/selector/src/runtime/audit.ts +303 -303
  43. package/packages/selector/src/runtime/config.ts +756 -731
  44. package/packages/selector/src/runtime/monitor.ts +235 -0
  45. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  46. package/packages/selector/src/runtime/retrieve.ts +479 -457
  47. package/packages/selector/src/runtime/savings.ts +337 -0
  48. package/packages/selector/src/runtime/summary-command.ts +133 -133
  49. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -233
  50. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -204
  51. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -53
  52. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -65
  53. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -125
  54. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -37
  55. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  56. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +306 -306
  57. package/packages/selector/src/runtime/types.ts +365 -358
  58. package/packages/selector/tests/built/client-artifact.spec.ts +61 -61
  59. package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
  60. package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
  61. package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
  62. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
  63. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  64. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  65. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  66. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  67. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  68. package/packages/selector/tests/host-preset-overlay.host.spec.ts +203 -203
  69. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  70. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  71. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  72. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -62
  73. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -156
  74. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  75. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  76. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -154
  77. package/packages/selector/tests/settings-seat.client.spec.ts +177 -165
  78. package/scripts/packed-components-smoke.mjs +734 -734
  79. package/scripts/packed-install-e2e.mjs +1 -1
  80. package/scripts/verify-release.mjs +1 -1
  81. package/tests/TEST_INVENTORY.md +41 -41
  82. package/tsconfig.tests.json +17 -17
  83. package/vitest.config.ts +57 -57
@@ -1,306 +1,306 @@
1
- /**
2
- * TokenPilot-inspired side channel (Phases 10–13).
3
- *
4
- * The S1 relevance filters (S1a search nodes, S1b document sections) ride the
5
- * SAME transports the estimator uses — `host` (the Harness `llm` service) or
6
- * `direct` (OpenAI-compatible HTTP) — with `maxTokens: 256`,
7
- * `temperature: 0`, `reasoningEffort: 'off'`. No second provider/model
8
- * configuration surface exists; failures are fail-open (`undefined`, never a
9
- * throw) and the mechanical fold is always the fallback.
10
- *
11
- * Layer rules: the side channel only changes SELECTION and ORDER; it never
12
- * rewrites content and never removes a node's existence (L1 locators and
13
- * section headings always survive). Every call is cost-gated: if everything
14
- * fits the budget the channel is not called at all.
15
- */
16
- import type { Context } from '@deepseek-ai/cordis'
17
- import type { PresetOptionsSettings } from '../types.ts'
18
-
19
- /** The minimal face of the Harness `llm` service this module consumes. */
20
- export interface HostLlmLike {
21
- stream(request: {
22
- provider: string
23
- model: string
24
- messages: readonly { readonly role: 'user', readonly content: readonly { readonly type: 'text', readonly text: string }[] }[]
25
- system?: string
26
- temperature?: number
27
- reasoningEffort?: string
28
- maxTokens?: number
29
- signal?: AbortSignal
30
- }): AsyncIterable<{ readonly type: string, readonly text?: string }>
31
- }
32
-
33
- /** Audit record of one side-channel call (Phase 13). All fields optional-safe. */
34
- export interface SideChannelAudit {
35
- readonly ok: boolean
36
- readonly latencyMs: number
37
- /** host|direct plus the resolved provider/model identity. */
38
- readonly channel?: string
39
- /** L2 coverage: content shown N of node content total M. */
40
- readonly coverage?: { readonly shown: number, readonly total: number }
41
- readonly reason?: string
42
- }
43
-
44
- export interface SideChannelRequest {
45
- readonly system: string
46
- readonly user: string
47
- readonly signal: AbortSignal
48
- }
49
-
50
- /** One bound side channel. `ask` resolves `undefined` on ANY failure. */
51
- export class SideChannel {
52
- /**
53
- * @param overrides - per-consumer overrides of the estimator-named options.
54
- * The estimator itself never passes them (byte-identical behavior); the
55
- * advisory advisor passes its own mode/timeout/output budget so both
56
- * consumers share one transport without sharing one configuration.
57
- */
58
- constructor(
59
- private readonly ctx: Context,
60
- private readonly options: PresetOptionsSettings,
61
- private readonly overrides?: {
62
- readonly mode?: '' | 'host' | 'direct'
63
- readonly timeoutMs?: number
64
- readonly maxTokens?: number
65
- },
66
- ) {}
67
-
68
- private get mode(): '' | 'host' | 'direct' {
69
- return this.overrides?.mode ?? this.options.estimatorMode ?? ''
70
- }
71
-
72
- get enabled(): boolean {
73
- return this.mode === 'host' || this.mode === 'direct'
74
- }
75
-
76
- async ask(request: SideChannelRequest): Promise<string | undefined> {
77
- const timeoutMs = this.overrides?.timeoutMs ?? this.options.estimatorTimeoutMs ?? 3_000
78
- const timeout = AbortSignal.timeout(timeoutMs)
79
- const signal = typeof AbortSignal.any === 'function' ? AbortSignal.any([request.signal, timeout]) : timeout
80
- try {
81
- if (this.mode === 'host') return await this.askHost(request.system, request.user, signal)
82
- if (this.mode === 'direct') return await this.askDirect(request.system, request.user, signal)
83
- return undefined
84
- } catch {
85
- return undefined
86
- }
87
- }
88
-
89
- /** Failure-open wrapper that also records one audit record per call. */
90
- async askAudited(request: SideChannelRequest): Promise<{ text?: string, audit: SideChannelAudit }> {
91
- const now = Date.now()
92
- const text = await this.ask(request)
93
- const audit: SideChannelAudit = {
94
- ok: text !== undefined,
95
- latencyMs: Date.now() - now,
96
- ...this.identity() !== undefined ? { channel: this.identity()! } : {},
97
- ...(text === undefined ? { reason: 'channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the output-token budget)' } : {}),
98
- }
99
- return { ...(text === undefined ? {} : { text }), audit }
100
- }
101
-
102
- identity(): string | undefined {
103
- if (this.mode === 'direct') {
104
- return `direct:${this.options.estimatorModel ?? ''}`
105
- }
106
- if (this.mode === 'host') {
107
- const route = this.resolveHostRoute()
108
- return route === undefined ? 'host' : `host:${route.provider}/${route.model}`
109
- }
110
- return undefined
111
- }
112
-
113
- /** Same host-route resolution as the estimator: explicit, then host default. */
114
- private resolveHostRoute(): { provider: string, model: string } | undefined {
115
- const provider = this.options.estimatorProvider ?? ''
116
- const model = this.options.estimatorModel ?? ''
117
- if (provider.length > 0 && model.length > 0) return { provider, model }
118
- try {
119
- const defaults = this.ctx.get('agentDefaultModel' as never) as
120
- | { currentSelection?: () => { provider?: string, model?: string } | undefined }
121
- | undefined
122
- const selected = defaults?.currentSelection?.()
123
- const selectedProvider = selected?.provider ?? ''
124
- const selectedModel = selected?.model ?? ''
125
- if (selectedProvider.length > 0 && selectedModel.length > 0) {
126
- return {
127
- provider: provider.length > 0 ? provider : selectedProvider,
128
- model: model.length > 0 ? model : selectedModel,
129
- }
130
- }
131
- } catch {
132
- // optional service; absence must not throw
133
- }
134
- return undefined
135
- }
136
-
137
- private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
138
- let llm: HostLlmLike | undefined
139
- try {
140
- // The standalone checkout has no typed registry entry for the host `llm`
141
- // service (`ctx.get` narrows to `never`); read it through an untyped face
142
- // and restate the minimal shape this module consumes.
143
- llm = (this.ctx as { get(key: string): unknown }).get('llm') as HostLlmLike | undefined
144
- } catch {
145
- return undefined
146
- }
147
- if (llm?.stream === undefined) return undefined
148
- const route = this.resolveHostRoute()
149
- if (route === undefined) return undefined
150
- let text = ''
151
- const stream = llm.stream({
152
- provider: route.provider,
153
- model: route.model,
154
- messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
155
- system,
156
- temperature: 0,
157
- reasoningEffort: 'off',
158
- maxTokens: this.overrides?.maxTokens ?? 256,
159
- signal,
160
- })
161
- for await (const chunk of stream) {
162
- // reasoningEffort 'off' is a request, not a guarantee: if reasoning still
163
- // eats the 256-token budget, `content` stays empty and the caller falls
164
- // back to the mechanical fold (text.trim() check below).
165
- if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
166
- text += chunk.text
167
- } else if (chunk.type === 'finish' && chunk.text === undefined) {
168
- break
169
- }
170
- }
171
- return text.trim().length > 0 ? text : undefined
172
- }
173
-
174
- private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
175
- const baseUrl = this.options.estimatorBaseUrl
176
- if (baseUrl === undefined || baseUrl.length === 0) return undefined
177
- const headers: Record<string, string> = { 'content-type': 'application/json' }
178
- if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
179
- headers.authorization = `Bearer ${this.options.estimatorApiKey}`
180
- }
181
- const model = this.options.estimatorModel ?? ''
182
- if (model.length === 0) return undefined
183
- const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
184
- method: 'POST',
185
- headers,
186
- body: JSON.stringify({
187
- model,
188
- messages: [
189
- { role: 'system', content: system },
190
- { role: 'user', content: user },
191
- ],
192
- temperature: 0,
193
- max_tokens: this.overrides?.maxTokens ?? 256,
194
- }),
195
- signal,
196
- })
197
- if (!response.ok) return undefined
198
- const payload = (await response.json()) as {
199
- choices?: { message?: { content?: string } }[]
200
- }
201
- const text = payload.choices?.[0]?.message?.content
202
- return typeof text === 'string' && text.trim().length > 0 ? text : undefined
203
- }
204
- }
205
-
206
- /**
207
- * Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
208
- * query, the main LLM's reasoning summary (the intent lives there — AD11),
209
- * and per-node summaries with identifier + count + ONE content sample.
210
- */
211
- export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
212
- const what = kind === 'search' ? 'files' : 'document sections'
213
- return [
214
- 'You rank session artifacts by relevance to an agent query.',
215
- `You are given numbered ${what} with a short sample each.`,
216
- `Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
217
- 'as a comma-separated list. Omit identifiers you consider irrelevant.',
218
- 'Never invent identifiers; never add commentary.',
219
- ].join(' ')
220
- }
221
-
222
- export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
223
- if (text === undefined || text.trim().length === 0) return undefined
224
- const ranked: string[] = []
225
- const seen = new Set<string>()
226
- for (const token of text.split(/[\s,;]+/)) {
227
- const id = token.replace(/[^\w./:#-]/gu, '')
228
- if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
229
- seen.add(id)
230
- ranked.push(id)
231
- }
232
- return ranked.length > 0 ? ranked : undefined
233
- }
234
-
235
- /** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
236
- export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
237
- if (ranking === undefined) return nodes
238
- const byId = new Map(nodes.map(node => [node.id, node]))
239
- const ordered: T[] = []
240
- for (const id of ranking) {
241
- const node = byId.get(id)
242
- if (node !== undefined) ordered.push(node)
243
- }
244
- for (const node of nodes) {
245
- if (!ordered.includes(node)) ordered.push(node)
246
- }
247
- return ordered
248
- }
249
-
250
- /** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
251
- export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
252
- return !fitsBudget && nodeCount > 1
253
- }
254
-
255
- /** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
256
- export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
257
-
258
- export function buildRankUserPrompt(
259
- nodes: readonly RankedNode[],
260
- query: string,
261
- reasoningSummary: string | undefined,
262
- ): string {
263
- const lines = [
264
- ...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
265
- ...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
266
- ? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
267
- ...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
268
- ]
269
- return lines.join('\n')
270
- }
271
-
272
- export interface RankOutcome {
273
- /** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
274
- readonly ranking?: readonly string[]
275
- readonly audit: SideChannelAudit
276
- }
277
-
278
- /**
279
- * S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
280
- * path (gate closed, channel undefined, garbage answer) resolves with
281
- * `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
282
- */
283
- export async function rankNodes(
284
- nodes: readonly RankedNode[],
285
- validIds: ReadonlySet<string>,
286
- query: string,
287
- reasoningSummary: string | undefined,
288
- channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
289
- signal: AbortSignal,
290
- ): Promise<RankOutcome> {
291
- if (nodes.length <= 1 || query.trim().length === 0) {
292
- return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
293
- }
294
- const { text, audit } = await channel.askAudited({
295
- system: buildRankSystemPrompt('search'),
296
- user: buildRankUserPrompt(nodes, query, reasoningSummary),
297
- signal,
298
- })
299
- const ranking = parseRanking(text, validIds)
300
- return {
301
- ...(ranking === undefined ? {} : { ranking }),
302
- audit: ranking === undefined
303
- ? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
304
- : audit,
305
- }
306
- }
1
+ /**
2
+ * TokenPilot-inspired side channel (Phases 10–13).
3
+ *
4
+ * The S1 relevance filters (S1a search nodes, S1b document sections) ride the
5
+ * SAME transports the estimator uses — `host` (the Harness `llm` service) or
6
+ * `direct` (OpenAI-compatible HTTP) — with `maxTokens: 256`,
7
+ * `temperature: 0`, `reasoningEffort: 'off'`. No second provider/model
8
+ * configuration surface exists; failures are fail-open (`undefined`, never a
9
+ * throw) and the mechanical fold is always the fallback.
10
+ *
11
+ * Layer rules: the side channel only changes SELECTION and ORDER; it never
12
+ * rewrites content and never removes a node's existence (L1 locators and
13
+ * section headings always survive). Every call is cost-gated: if everything
14
+ * fits the budget the channel is not called at all.
15
+ */
16
+ import type { Context } from '@deepseek-ai/cordis'
17
+ import type { PresetOptionsSettings } from '../types.ts'
18
+
19
+ /** The minimal face of the Harness `llm` service this module consumes. */
20
+ export interface HostLlmLike {
21
+ stream(request: {
22
+ provider: string
23
+ model: string
24
+ messages: readonly { readonly role: 'user', readonly content: readonly { readonly type: 'text', readonly text: string }[] }[]
25
+ system?: string
26
+ temperature?: number
27
+ reasoningEffort?: string
28
+ maxTokens?: number
29
+ signal?: AbortSignal
30
+ }): AsyncIterable<{ readonly type: string, readonly text?: string }>
31
+ }
32
+
33
+ /** Audit record of one side-channel call (Phase 13). All fields optional-safe. */
34
+ export interface SideChannelAudit {
35
+ readonly ok: boolean
36
+ readonly latencyMs: number
37
+ /** host|direct plus the resolved provider/model identity. */
38
+ readonly channel?: string
39
+ /** L2 coverage: content shown N of node content total M. */
40
+ readonly coverage?: { readonly shown: number, readonly total: number }
41
+ readonly reason?: string
42
+ }
43
+
44
+ export interface SideChannelRequest {
45
+ readonly system: string
46
+ readonly user: string
47
+ readonly signal: AbortSignal
48
+ }
49
+
50
+ /** One bound side channel. `ask` resolves `undefined` on ANY failure. */
51
+ export class SideChannel {
52
+ /**
53
+ * @param overrides - per-consumer overrides of the estimator-named options.
54
+ * The estimator itself never passes them (byte-identical behavior); the
55
+ * advisory advisor passes its own mode/timeout/output budget so both
56
+ * consumers share one transport without sharing one configuration.
57
+ */
58
+ constructor(
59
+ private readonly ctx: Context,
60
+ private readonly options: PresetOptionsSettings,
61
+ private readonly overrides?: {
62
+ readonly mode?: '' | 'host' | 'direct'
63
+ readonly timeoutMs?: number
64
+ readonly maxTokens?: number
65
+ },
66
+ ) {}
67
+
68
+ private get mode(): '' | 'host' | 'direct' {
69
+ return this.overrides?.mode ?? this.options.estimatorMode ?? ''
70
+ }
71
+
72
+ get enabled(): boolean {
73
+ return this.mode === 'host' || this.mode === 'direct'
74
+ }
75
+
76
+ async ask(request: SideChannelRequest): Promise<string | undefined> {
77
+ const timeoutMs = this.overrides?.timeoutMs ?? this.options.estimatorTimeoutMs ?? 3_000
78
+ const timeout = AbortSignal.timeout(timeoutMs)
79
+ const signal = typeof AbortSignal.any === 'function' ? AbortSignal.any([request.signal, timeout]) : timeout
80
+ try {
81
+ if (this.mode === 'host') return await this.askHost(request.system, request.user, signal)
82
+ if (this.mode === 'direct') return await this.askDirect(request.system, request.user, signal)
83
+ return undefined
84
+ } catch {
85
+ return undefined
86
+ }
87
+ }
88
+
89
+ /** Failure-open wrapper that also records one audit record per call. */
90
+ async askAudited(request: SideChannelRequest): Promise<{ text?: string, audit: SideChannelAudit }> {
91
+ const now = Date.now()
92
+ const text = await this.ask(request)
93
+ const audit: SideChannelAudit = {
94
+ ok: text !== undefined,
95
+ latencyMs: Date.now() - now,
96
+ ...this.identity() !== undefined ? { channel: this.identity()! } : {},
97
+ ...(text === undefined ? { reason: 'channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the output-token budget)' } : {}),
98
+ }
99
+ return { ...(text === undefined ? {} : { text }), audit }
100
+ }
101
+
102
+ identity(): string | undefined {
103
+ if (this.mode === 'direct') {
104
+ return `direct:${this.options.estimatorModel ?? ''}`
105
+ }
106
+ if (this.mode === 'host') {
107
+ const route = this.resolveHostRoute()
108
+ return route === undefined ? 'host' : `host:${route.provider}/${route.model}`
109
+ }
110
+ return undefined
111
+ }
112
+
113
+ /** Same host-route resolution as the estimator: explicit, then host default. */
114
+ private resolveHostRoute(): { provider: string, model: string } | undefined {
115
+ const provider = this.options.estimatorProvider ?? ''
116
+ const model = this.options.estimatorModel ?? ''
117
+ if (provider.length > 0 && model.length > 0) return { provider, model }
118
+ try {
119
+ const defaults = this.ctx.get('agentDefaultModel' as never) as
120
+ | { currentSelection?: () => { provider?: string, model?: string } | undefined }
121
+ | undefined
122
+ const selected = defaults?.currentSelection?.()
123
+ const selectedProvider = selected?.provider ?? ''
124
+ const selectedModel = selected?.model ?? ''
125
+ if (selectedProvider.length > 0 && selectedModel.length > 0) {
126
+ return {
127
+ provider: provider.length > 0 ? provider : selectedProvider,
128
+ model: model.length > 0 ? model : selectedModel,
129
+ }
130
+ }
131
+ } catch {
132
+ // optional service; absence must not throw
133
+ }
134
+ return undefined
135
+ }
136
+
137
+ private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
138
+ let llm: HostLlmLike | undefined
139
+ try {
140
+ // The standalone checkout has no typed registry entry for the host `llm`
141
+ // service (`ctx.get` narrows to `never`); read it through an untyped face
142
+ // and restate the minimal shape this module consumes.
143
+ llm = (this.ctx as { get(key: string): unknown }).get('llm') as HostLlmLike | undefined
144
+ } catch {
145
+ return undefined
146
+ }
147
+ if (llm?.stream === undefined) return undefined
148
+ const route = this.resolveHostRoute()
149
+ if (route === undefined) return undefined
150
+ let text = ''
151
+ const stream = llm.stream({
152
+ provider: route.provider,
153
+ model: route.model,
154
+ messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
155
+ system,
156
+ temperature: 0,
157
+ reasoningEffort: 'off',
158
+ maxTokens: this.overrides?.maxTokens ?? 256,
159
+ signal,
160
+ })
161
+ for await (const chunk of stream) {
162
+ // reasoningEffort 'off' is a request, not a guarantee: if reasoning still
163
+ // eats the 256-token budget, `content` stays empty and the caller falls
164
+ // back to the mechanical fold (text.trim() check below).
165
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
166
+ text += chunk.text
167
+ } else if (chunk.type === 'finish' && chunk.text === undefined) {
168
+ break
169
+ }
170
+ }
171
+ return text.trim().length > 0 ? text : undefined
172
+ }
173
+
174
+ private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
175
+ const baseUrl = this.options.estimatorBaseUrl
176
+ if (baseUrl === undefined || baseUrl.length === 0) return undefined
177
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
178
+ if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
179
+ headers.authorization = `Bearer ${this.options.estimatorApiKey}`
180
+ }
181
+ const model = this.options.estimatorModel ?? ''
182
+ if (model.length === 0) return undefined
183
+ const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
184
+ method: 'POST',
185
+ headers,
186
+ body: JSON.stringify({
187
+ model,
188
+ messages: [
189
+ { role: 'system', content: system },
190
+ { role: 'user', content: user },
191
+ ],
192
+ temperature: 0,
193
+ max_tokens: this.overrides?.maxTokens ?? 256,
194
+ }),
195
+ signal,
196
+ })
197
+ if (!response.ok) return undefined
198
+ const payload = (await response.json()) as {
199
+ choices?: { message?: { content?: string } }[]
200
+ }
201
+ const text = payload.choices?.[0]?.message?.content
202
+ return typeof text === 'string' && text.trim().length > 0 ? text : undefined
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
208
+ * query, the main LLM's reasoning summary (the intent lives there — AD11),
209
+ * and per-node summaries with identifier + count + ONE content sample.
210
+ */
211
+ export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
212
+ const what = kind === 'search' ? 'files' : 'document sections'
213
+ return [
214
+ 'You rank session artifacts by relevance to an agent query.',
215
+ `You are given numbered ${what} with a short sample each.`,
216
+ `Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
217
+ 'as a comma-separated list. Omit identifiers you consider irrelevant.',
218
+ 'Never invent identifiers; never add commentary.',
219
+ ].join(' ')
220
+ }
221
+
222
+ export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
223
+ if (text === undefined || text.trim().length === 0) return undefined
224
+ const ranked: string[] = []
225
+ const seen = new Set<string>()
226
+ for (const token of text.split(/[\s,;]+/)) {
227
+ const id = token.replace(/[^\w./:#-]/gu, '')
228
+ if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
229
+ seen.add(id)
230
+ ranked.push(id)
231
+ }
232
+ return ranked.length > 0 ? ranked : undefined
233
+ }
234
+
235
+ /** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
236
+ export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
237
+ if (ranking === undefined) return nodes
238
+ const byId = new Map(nodes.map(node => [node.id, node]))
239
+ const ordered: T[] = []
240
+ for (const id of ranking) {
241
+ const node = byId.get(id)
242
+ if (node !== undefined) ordered.push(node)
243
+ }
244
+ for (const node of nodes) {
245
+ if (!ordered.includes(node)) ordered.push(node)
246
+ }
247
+ return ordered
248
+ }
249
+
250
+ /** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
251
+ export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
252
+ return !fitsBudget && nodeCount > 1
253
+ }
254
+
255
+ /** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
256
+ export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
257
+
258
+ export function buildRankUserPrompt(
259
+ nodes: readonly RankedNode[],
260
+ query: string,
261
+ reasoningSummary: string | undefined,
262
+ ): string {
263
+ const lines = [
264
+ ...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
265
+ ...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
266
+ ? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
267
+ ...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
268
+ ]
269
+ return lines.join('\n')
270
+ }
271
+
272
+ export interface RankOutcome {
273
+ /** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
274
+ readonly ranking?: readonly string[]
275
+ readonly audit: SideChannelAudit
276
+ }
277
+
278
+ /**
279
+ * S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
280
+ * path (gate closed, channel undefined, garbage answer) resolves with
281
+ * `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
282
+ */
283
+ export async function rankNodes(
284
+ nodes: readonly RankedNode[],
285
+ validIds: ReadonlySet<string>,
286
+ query: string,
287
+ reasoningSummary: string | undefined,
288
+ channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
289
+ signal: AbortSignal,
290
+ ): Promise<RankOutcome> {
291
+ if (nodes.length <= 1 || query.trim().length === 0) {
292
+ return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
293
+ }
294
+ const { text, audit } = await channel.askAudited({
295
+ system: buildRankSystemPrompt('search'),
296
+ user: buildRankUserPrompt(nodes, query, reasoningSummary),
297
+ signal,
298
+ })
299
+ const ranking = parseRanking(text, validIds)
300
+ return {
301
+ ...(ranking === undefined ? {} : { ranking }),
302
+ audit: ranking === undefined
303
+ ? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
304
+ : audit,
305
+ }
306
+ }