dsh-context-compression-improved 0.2.4 → 0.2.5

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 (127) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +8 -8
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +212 -16
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +1 -19
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +75 -54
  22. package/packages/selector/README.md +7 -12
  23. package/packages/selector/README.zh.md +6 -13
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +16 -16
  27. package/packages/selector/lib/client.d.ts +97 -5
  28. package/packages/selector/lib/client.js +1884 -92
  29. package/packages/selector/lib/config.js +863 -6
  30. package/packages/selector/lib/index.d.ts +29 -21
  31. package/packages/selector/lib/index.js +424 -18
  32. package/packages/selector/lib/invariant.js +4 -4
  33. package/packages/selector/lib/pruner.d.ts +179 -4
  34. package/packages/selector/lib/pruner.js +1406 -371
  35. package/packages/selector/lib/style.css +42 -0
  36. package/packages/selector/lib/tail-trim.js +13 -4
  37. package/packages/selector/package.json +18 -27
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +200 -62
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/profiles.ts +431 -342
  61. package/packages/selector/src/pruner/state.ts +57 -43
  62. package/packages/selector/src/pruner.ts +2736 -2154
  63. package/packages/selector/src/runtime/audit.ts +303 -231
  64. package/packages/selector/src/runtime/config.ts +756 -642
  65. package/packages/selector/src/runtime/measurement.ts +436 -432
  66. package/packages/selector/src/runtime/monitor.ts +235 -0
  67. package/packages/selector/src/runtime/retrieve.ts +479 -457
  68. package/packages/selector/src/runtime/savings.ts +337 -0
  69. package/packages/selector/src/runtime/session-events.ts +30 -17
  70. package/packages/selector/src/runtime/summary-command.ts +127 -0
  71. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  72. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  73. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  74. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  75. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  76. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  77. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  78. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  79. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  80. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  81. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -275
  82. package/packages/selector/src/runtime/types.ts +365 -325
  83. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  84. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  85. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  86. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  87. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  88. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  89. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  90. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  91. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  92. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  93. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  94. package/packages/selector/tests/preset-overlay.host.spec.ts +8 -18
  95. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  96. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  97. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  98. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  99. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  100. package/packages/selector/tests/runtime/audit.spec.ts +275 -172
  101. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  102. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  103. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  104. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  105. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2702
  106. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  107. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  108. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  109. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  110. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  111. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  112. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  113. package/packages/selector/tests/standing-generation.host.spec.ts +142 -87
  114. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  115. package/pnpm-workspace.yaml +66 -19
  116. package/scripts/capture-profile-baseline.mjs +42 -0
  117. package/scripts/generate-tokenizer-fixtures.py +81 -81
  118. package/scripts/generate-vision-fixtures.py +208 -208
  119. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  120. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  121. package/scripts/toolclass-corpus-replay.mjs +281 -273
  122. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  123. package/tests/TEST_INVENTORY.md +41 -42
  124. package/scripts/capture-profile-baseline.ts +0 -80
  125. package/tsconfig.scripts.json +0 -13
  126. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  127. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,275 +1,303 @@
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
- constructor(
53
- private readonly ctx: Context,
54
- private readonly options: PresetOptionsSettings,
55
- ) {}
56
-
57
- get enabled(): boolean {
58
- return this.options.estimatorMode === 'host' || this.options.estimatorMode === 'direct'
59
- }
60
-
61
- async ask(request: SideChannelRequest): Promise<string | undefined> {
62
- const timeoutMs = this.options.estimatorTimeoutMs ?? 3_000
63
- const timeout = AbortSignal.timeout(timeoutMs)
64
- const signal = typeof AbortSignal.any === 'function' ? AbortSignal.any([request.signal, timeout]) : timeout
65
- try {
66
- if (this.options.estimatorMode === 'host') return await this.askHost(request.system, request.user, signal)
67
- if (this.options.estimatorMode === 'direct') return await this.askDirect(request.system, request.user, signal)
68
- return undefined
69
- } catch {
70
- return undefined
71
- }
72
- }
73
-
74
- /** Failure-open wrapper that also records one audit record per call. */
75
- async askAudited(request: SideChannelRequest): Promise<{ text?: string, audit: SideChannelAudit }> {
76
- const now = Date.now()
77
- const text = await this.ask(request)
78
- const audit: SideChannelAudit = {
79
- ok: text !== undefined,
80
- latencyMs: Date.now() - now,
81
- ...this.identity() !== undefined ? { channel: this.identity()! } : {},
82
- ...(text === undefined ? { reason: 'channel returned no content (timeout, non-2xx, parse failure, or reasoning ate the 256-token budget)' } : {}),
83
- }
84
- return { ...(text === undefined ? {} : { text }), audit }
85
- }
86
-
87
- identity(): string | undefined {
88
- if (this.options.estimatorMode === 'direct') {
89
- return `direct:${this.options.estimatorModel ?? ''}`
90
- }
91
- if (this.options.estimatorMode === 'host') {
92
- const route = this.resolveHostRoute()
93
- return route === undefined ? 'host' : `host:${route.provider}/${route.model}`
94
- }
95
- return undefined
96
- }
97
-
98
- /**
99
- * Host-route resolution matching this version line's estimator semantics:
100
- * an explicitly configured provider/model pair, nothing else.
101
- */
102
- private resolveHostRoute(): { provider: string, model: string } | undefined {
103
- const provider = this.options.estimatorProvider ?? ''
104
- const model = this.options.estimatorModel ?? ''
105
- if (provider.length > 0 && model.length > 0) return { provider, model }
106
- return undefined
107
- }
108
-
109
- private async askHost(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
110
- let llm: HostLlmLike | undefined
111
- try {
112
- llm = this.ctx.get('llm' as never) as HostLlmLike | undefined
113
- } catch {
114
- return undefined
115
- }
116
- if (llm?.stream === undefined) return undefined
117
- const route = this.resolveHostRoute()
118
- if (route === undefined) return undefined
119
- let text = ''
120
- const stream = llm.stream({
121
- provider: route.provider,
122
- model: route.model,
123
- messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
124
- system,
125
- temperature: 0,
126
- reasoningEffort: 'off',
127
- maxTokens: 256,
128
- signal,
129
- })
130
- for await (const chunk of stream) {
131
- // reasoningEffort 'off' is a request, not a guarantee: if reasoning still
132
- // eats the 256-token budget, `content` stays empty and the caller falls
133
- // back to the mechanical fold (text.trim() check below).
134
- if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
135
- text += chunk.text
136
- } else if (chunk.type === 'finish' && chunk.text === undefined) {
137
- break
138
- }
139
- }
140
- return text.trim().length > 0 ? text : undefined
141
- }
142
-
143
- private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
144
- const baseUrl = this.options.estimatorBaseUrl
145
- if (baseUrl === undefined || baseUrl.length === 0) return undefined
146
- const headers: Record<string, string> = { 'content-type': 'application/json' }
147
- if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
148
- headers.authorization = `Bearer ${this.options.estimatorApiKey}`
149
- }
150
- const model = this.options.estimatorModel ?? ''
151
- if (model.length === 0) return undefined
152
- const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
153
- method: 'POST',
154
- headers,
155
- body: JSON.stringify({
156
- model,
157
- messages: [
158
- { role: 'system', content: system },
159
- { role: 'user', content: user },
160
- ],
161
- temperature: 0,
162
- max_tokens: 256,
163
- }),
164
- signal,
165
- })
166
- if (!response.ok) return undefined
167
- const payload = (await response.json()) as {
168
- choices?: { message?: { content?: string } }[]
169
- }
170
- const text = payload.choices?.[0]?.message?.content
171
- return typeof text === 'string' && text.trim().length > 0 ? text : undefined
172
- }
173
- }
174
-
175
- /**
176
- * Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
177
- * query, the main LLM's reasoning summary (the intent lives there — AD11),
178
- * and per-node summaries with identifier + count + ONE content sample.
179
- */
180
- export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
181
- const what = kind === 'search' ? 'files' : 'document sections'
182
- return [
183
- 'You rank session artifacts by relevance to an agent query.',
184
- `You are given numbered ${what} with a short sample each.`,
185
- `Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
186
- 'as a comma-separated list. Omit identifiers you consider irrelevant.',
187
- 'Never invent identifiers; never add commentary.',
188
- ].join(' ')
189
- }
190
-
191
- export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
192
- if (text === undefined || text.trim().length === 0) return undefined
193
- const ranked: string[] = []
194
- const seen = new Set<string>()
195
- for (const token of text.split(/[\s,;]+/)) {
196
- const id = token.replace(/[^\w./:#-]/gu, '')
197
- if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
198
- seen.add(id)
199
- ranked.push(id)
200
- }
201
- return ranked.length > 0 ? ranked : undefined
202
- }
203
-
204
- /** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
205
- export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
206
- if (ranking === undefined) return nodes
207
- const byId = new Map(nodes.map(node => [node.id, node]))
208
- const ordered: T[] = []
209
- for (const id of ranking) {
210
- const node = byId.get(id)
211
- if (node !== undefined) ordered.push(node)
212
- }
213
- for (const node of nodes) {
214
- if (!ordered.includes(node)) ordered.push(node)
215
- }
216
- return ordered
217
- }
218
-
219
- /** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
220
- export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
221
- return !fitsBudget && nodeCount > 1
222
- }
223
-
224
- /** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
225
- export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
226
-
227
- export function buildRankUserPrompt(
228
- nodes: readonly RankedNode[],
229
- query: string,
230
- reasoningSummary: string | undefined,
231
- ): string {
232
- const lines = [
233
- ...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
234
- ...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
235
- ? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
236
- ...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
237
- ]
238
- return lines.join('\n')
239
- }
240
-
241
- export interface RankOutcome {
242
- /** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
243
- readonly ranking?: readonly string[]
244
- readonly audit: SideChannelAudit
245
- }
246
-
247
- /**
248
- * S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
249
- * path (gate closed, channel undefined, garbage answer) resolves with
250
- * `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
251
- */
252
- export async function rankNodes(
253
- nodes: readonly RankedNode[],
254
- validIds: ReadonlySet<string>,
255
- query: string,
256
- reasoningSummary: string | undefined,
257
- channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
258
- signal: AbortSignal,
259
- ): Promise<RankOutcome> {
260
- if (nodes.length <= 1 || query.trim().length === 0) {
261
- return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
262
- }
263
- const { text, audit } = await channel.askAudited({
264
- system: buildRankSystemPrompt('search'),
265
- user: buildRankUserPrompt(nodes, query, reasoningSummary),
266
- signal,
267
- })
268
- const ranking = parseRanking(text, validIds)
269
- return {
270
- ...(ranking === undefined ? {} : { ranking }),
271
- audit: ranking === undefined
272
- ? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
273
- : audit,
274
- }
275
- }
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
+ llm = this.ctx.get('llm' as never) as HostLlmLike | undefined
141
+ } catch {
142
+ return undefined
143
+ }
144
+ if (llm?.stream === undefined) return undefined
145
+ const route = this.resolveHostRoute()
146
+ if (route === undefined) return undefined
147
+ let text = ''
148
+ const stream = llm.stream({
149
+ provider: route.provider,
150
+ model: route.model,
151
+ messages: [{ role: 'user', content: [{ type: 'text', text: user }] }],
152
+ system,
153
+ temperature: 0,
154
+ reasoningEffort: 'off',
155
+ maxTokens: this.overrides?.maxTokens ?? 256,
156
+ signal,
157
+ })
158
+ for await (const chunk of stream) {
159
+ // reasoningEffort 'off' is a request, not a guarantee: if reasoning still
160
+ // eats the 256-token budget, `content` stays empty and the caller falls
161
+ // back to the mechanical fold (text.trim() check below).
162
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') {
163
+ text += chunk.text
164
+ } else if (chunk.type === 'finish' && chunk.text === undefined) {
165
+ break
166
+ }
167
+ }
168
+ return text.trim().length > 0 ? text : undefined
169
+ }
170
+
171
+ private async askDirect(system: string, user: string, signal: AbortSignal): Promise<string | undefined> {
172
+ const baseUrl = this.options.estimatorBaseUrl
173
+ if (baseUrl === undefined || baseUrl.length === 0) return undefined
174
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
175
+ if (this.options.estimatorApiKey !== undefined && this.options.estimatorApiKey.length > 0) {
176
+ headers.authorization = `Bearer ${this.options.estimatorApiKey}`
177
+ }
178
+ const model = this.options.estimatorModel ?? ''
179
+ if (model.length === 0) return undefined
180
+ const response = await fetch(`${baseUrl.replace(/\/+$/, '')}/chat/completions`, {
181
+ method: 'POST',
182
+ headers,
183
+ body: JSON.stringify({
184
+ model,
185
+ messages: [
186
+ { role: 'system', content: system },
187
+ { role: 'user', content: user },
188
+ ],
189
+ temperature: 0,
190
+ max_tokens: this.overrides?.maxTokens ?? 256,
191
+ }),
192
+ signal,
193
+ })
194
+ if (!response.ok) return undefined
195
+ const payload = (await response.json()) as {
196
+ choices?: { message?: { content?: string } }[]
197
+ }
198
+ const text = payload.choices?.[0]?.message?.content
199
+ return typeof text === 'string' && text.trim().length > 0 ? text : undefined
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Rank-then-cut (TS4): ONE call sorts and filters. The prompt carries the
205
+ * query, the main LLM's reasoning summary (the intent lives there — AD11),
206
+ * and per-node summaries with identifier + count + ONE content sample.
207
+ */
208
+ export function buildRankSystemPrompt(kind: 'search' | 'document'): string {
209
+ const what = kind === 'search' ? 'files' : 'document sections'
210
+ return [
211
+ 'You rank session artifacts by relevance to an agent query.',
212
+ `You are given numbered ${what} with a short sample each.`,
213
+ `Answer with ONLY the identifiers of the ${what} that matter, most relevant first,`,
214
+ 'as a comma-separated list. Omit identifiers you consider irrelevant.',
215
+ 'Never invent identifiers; never add commentary.',
216
+ ].join(' ')
217
+ }
218
+
219
+ export function parseRanking(text: string | undefined, validIds: ReadonlySet<string>): string[] | undefined {
220
+ if (text === undefined || text.trim().length === 0) return undefined
221
+ const ranked: string[] = []
222
+ const seen = new Set<string>()
223
+ for (const token of text.split(/[\s,;]+/)) {
224
+ const id = token.replace(/[^\w./:#-]/gu, '')
225
+ if (id.length === 0 || !validIds.has(id) || seen.has(id)) continue
226
+ seen.add(id)
227
+ ranked.push(id)
228
+ }
229
+ return ranked.length > 0 ? ranked : undefined
230
+ }
231
+
232
+ /** Nodes mentioned by the LM keep their rank; the rest are appended in order (SC-existence). */
233
+ export function mergeRanking<T extends { readonly id: string }>(nodes: readonly T[], ranking: readonly string[] | undefined): readonly T[] {
234
+ if (ranking === undefined) return nodes
235
+ const byId = new Map(nodes.map(node => [node.id, node]))
236
+ const ordered: T[] = []
237
+ for (const id of ranking) {
238
+ const node = byId.get(id)
239
+ if (node !== undefined) ordered.push(node)
240
+ }
241
+ for (const node of nodes) {
242
+ if (!ordered.includes(node)) ordered.push(node)
243
+ }
244
+ return ordered
245
+ }
246
+
247
+ /** Cost gate (R-10): call only when something must be dropped and there is more than one node. */
248
+ export function sideChannelGate(fitsBudget: boolean, nodeCount: number): boolean {
249
+ return !fitsBudget && nodeCount > 1
250
+ }
251
+
252
+ /** One node face offered to the rank prompt: id + count/mass + ONE content sample. */
253
+ export interface RankedNode { readonly id: string, readonly detail: string, readonly sample: string }
254
+
255
+ export function buildRankUserPrompt(
256
+ nodes: readonly RankedNode[],
257
+ query: string,
258
+ reasoningSummary: string | undefined,
259
+ ): string {
260
+ const lines = [
261
+ ...(query.trim().length > 0 ? [`query: ${query.trim().slice(0, 300)}`] : []),
262
+ ...(reasoningSummary !== undefined && reasoningSummary.trim().length > 0
263
+ ? [`reasoning: ${reasoningSummary.trim().slice(0, 300)}`] : []),
264
+ ...nodes.map(node => `${node.id} | ${node.detail} | ${node.sample.replace(/\s+/gu, ' ')}`),
265
+ ]
266
+ return lines.join('\n')
267
+ }
268
+
269
+ export interface RankOutcome {
270
+ /** Ranked ids the LM returned; `undefined` on any failure (fail-open). */
271
+ readonly ranking?: readonly string[]
272
+ readonly audit: SideChannelAudit
273
+ }
274
+
275
+ /**
276
+ * S1 orchestrator: gate → ONE channel call → parse → merge. Every failure
277
+ * path (gate closed, channel undefined, garbage answer) resolves with
278
+ * `ranking: undefined`, which the mechanical fold reproduces byte-for-byte.
279
+ */
280
+ export async function rankNodes(
281
+ nodes: readonly RankedNode[],
282
+ validIds: ReadonlySet<string>,
283
+ query: string,
284
+ reasoningSummary: string | undefined,
285
+ channel: Pick<SideChannel, 'ask' | 'askAudited' | 'identity'>,
286
+ signal: AbortSignal,
287
+ ): Promise<RankOutcome> {
288
+ if (nodes.length <= 1 || query.trim().length === 0) {
289
+ return { audit: { ok: false, latencyMs: 0, reason: 'gate closed: single node or empty query' } }
290
+ }
291
+ const { text, audit } = await channel.askAudited({
292
+ system: buildRankSystemPrompt('search'),
293
+ user: buildRankUserPrompt(nodes, query, reasoningSummary),
294
+ signal,
295
+ })
296
+ const ranking = parseRanking(text, validIds)
297
+ return {
298
+ ...(ranking === undefined ? {} : { ranking }),
299
+ audit: ranking === undefined
300
+ ? { ...audit, ok: false, reason: 'unparseable or empty ranking; falling back to the mechanical fold' }
301
+ : audit,
302
+ }
303
+ }