dsh-context-truth 0.1.3 → 0.3.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.
- package/CHANGELOG.md +233 -0
- package/README-en.md +94 -7
- package/README.md +163 -7
- package/lib/client.js +154 -0
- package/lib/index.js +1839 -46
- package/package.json +14 -1
- package/test/client.test.js +59 -0
- package/test/index.test.js +1352 -26
package/lib/index.js
CHANGED
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
* "established background", and the false belief survives every later
|
|
12
12
|
* compaction. The model never gets a correction because no correction exists.
|
|
13
13
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
14
|
+
* THREE CAPABILITIES, ONE BELIEF TO KILL
|
|
15
|
+
* --------------------------------------
|
|
16
16
|
* 1. MEASUREMENT IN (default on). One dynamic runtime-context line, refreshed
|
|
17
17
|
* from the host's own token meter, re-injected only when the reading moves a
|
|
18
18
|
* display step. It adds no tool, no message, and no per-step noise — one
|
|
@@ -20,6 +20,13 @@
|
|
|
20
20
|
* 2. CLAIM FILTERING (default on). The compaction summarizer is told not to
|
|
21
21
|
* record the assistant's own guesses about its remaining budget, so the
|
|
22
22
|
* false belief stops being re-injected as established background.
|
|
23
|
+
* 3. FOLD POLICY (`foldMode`, default idle). Who folds, and what the model knows
|
|
24
|
+
* before it happens. `idle` keeps the legacy turn-boundary fold; `handoff`
|
|
25
|
+
* asks the model for a handoff note at 85% of the fold point, folds at that
|
|
26
|
+
* round's end, and activates exactly one follow-up turn whose first job is to
|
|
27
|
+
* read the note back. The point of `handoff` is the cost `idle` leaves on the
|
|
28
|
+
* table: a fold the model did not see coming makes it rebuild its own
|
|
29
|
+
* picture from a summary, and long tasks pay for that in repeated work.
|
|
23
30
|
*
|
|
24
31
|
* HOW IT PLUGS IN
|
|
25
32
|
* ---------------
|
|
@@ -53,10 +60,21 @@
|
|
|
53
60
|
* point is derived the way `dsh-compaction-basic` derives it:
|
|
54
61
|
* `min(window * thresholdRatio, window - reservedCompletion - headroom)`.
|
|
55
62
|
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* It is
|
|
63
|
+
* ONE PEER IMPORT, STILL NO BUILD: the sole import is
|
|
64
|
+
* `@deepseek-ai/schemastery` — the host's own schema package, declared as a peer
|
|
65
|
+
* dependency. It is published on npm, so npm installs it with the plugin, and
|
|
66
|
+
* the host that runs the plugin already ships it. It exists only so the settings
|
|
67
|
+
* page can render a form for the options below: the host reads a plugin's form
|
|
68
|
+
* from `fiber.runtime.Config`, and only a real schema (something with `toJSON`)
|
|
69
|
+
* is accepted. Everything else stays dependency-free ESM, and this file is both
|
|
70
|
+
* the source and the runtime artifact (`lib/index.js`).
|
|
59
71
|
*/
|
|
72
|
+
import { randomUUID } from 'node:crypto'
|
|
73
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
74
|
+
import { homedir } from 'node:os'
|
|
75
|
+
import { isAbsolute, join, resolve as resolvePath } from 'node:path'
|
|
76
|
+
|
|
77
|
+
import z from '@deepseek-ai/schemastery'
|
|
60
78
|
|
|
61
79
|
/** Stable cordis plugin name (loader diagnostics, and the runtime-context section name). */
|
|
62
80
|
export const name = 'context-truth'
|
|
@@ -67,8 +85,22 @@ export const CONTEXT_NAME = 'context-truth'
|
|
|
67
85
|
/** Prompt variable carrying the rendered line. */
|
|
68
86
|
export const VARIABLE_NAME = 'context_occupancy'
|
|
69
87
|
|
|
70
|
-
/**
|
|
71
|
-
|
|
88
|
+
/**
|
|
89
|
+
* Services that must be wired before this plugin can act.
|
|
90
|
+
*
|
|
91
|
+
* `systemPrompt` carries the line and `tokenMeter` supplies the authoritative
|
|
92
|
+
* reading; both resolve in a plugin context.
|
|
93
|
+
*
|
|
94
|
+
* `compaction` IS DELIBERATELY ABSENT. Declaring it left this entry `pending
|
|
95
|
+
* (waiting for service: compaction)` forever — the plugin stopped loading
|
|
96
|
+
* entirely, taking the occupancy line with it — because in this build the
|
|
97
|
+
* compaction engine is provided inside a scope no plugin context can reach.
|
|
98
|
+
* Probed live: `ctx.get`, `ctx.reflect.get(name, false)`, `ctx.compaction` and
|
|
99
|
+
* even a running `agent.ctx` all return nothing for `compaction`, while
|
|
100
|
+
* `tokenMeter` resolves on all of them. See `installIdleFold` for what that means
|
|
101
|
+
* for capability 3.
|
|
102
|
+
*/
|
|
103
|
+
export const inject = ['systemPrompt', 'tokenMeter']
|
|
72
104
|
|
|
73
105
|
/** Orders the line first inside the runtime-context block (sandbox is 110, approval 115). */
|
|
74
106
|
const DEFAULT_ORDER = 100
|
|
@@ -99,10 +131,17 @@ const DEFAULT_OPTIONS = {
|
|
|
99
131
|
/** Emit the auto-compaction point and the headroom left before it. */
|
|
100
132
|
showAutoCompactionPoint: true,
|
|
101
133
|
/**
|
|
102
|
-
* Mirror of
|
|
103
|
-
* compaction config; the line only reports the point, it never
|
|
134
|
+
* Mirror of the mounted compaction backend's policy. Keep these equal to the
|
|
135
|
+
* profile's compaction config; the line only reports the point, it never
|
|
136
|
+
* enforces it.
|
|
137
|
+
*
|
|
138
|
+
* 0.7 rather than upstream's 0.8 because this profile runs `@aiwayds/dsh-dcp`,
|
|
139
|
+
* whose bundle sets `thresholdRatio: 0.7` (verified against the live engine:
|
|
140
|
+
* thresholdRatio=0.7, headroomTokens=65536, retainRatio=0.16). The displayed
|
|
141
|
+
* point is unchanged either way — the budget term binds at 678,464 — but the
|
|
142
|
+
* mirror must match for the case where it does not.
|
|
104
143
|
*/
|
|
105
|
-
thresholdRatio: 0.
|
|
144
|
+
thresholdRatio: 0.7,
|
|
106
145
|
headroomTokens: 65536,
|
|
107
146
|
/** Reserved completion tokens; `null` reads the routed request's own maxTokens. */
|
|
108
147
|
reservedCompletionTokens: null,
|
|
@@ -111,6 +150,13 @@ const DEFAULT_OPTIONS = {
|
|
|
111
150
|
tightAt: 0.85,
|
|
112
151
|
/** Fraction of the compaction point a reading must fall back below to leave a band. */
|
|
113
152
|
hysteresis: 0.05,
|
|
153
|
+
/**
|
|
154
|
+
* Closing sentence of the `tight` band. `none` (default) lets the numbers speak
|
|
155
|
+
* and leaves the decision to the model; `inform` states what the fold costs;
|
|
156
|
+
* `stop` restores the 0.1.3 imperative that told it to finish the step and
|
|
157
|
+
* hand off.
|
|
158
|
+
*/
|
|
159
|
+
tightAdvice: 'none',
|
|
114
160
|
/**
|
|
115
161
|
* Display quantum as a percentage of the window. The rendered text changes
|
|
116
162
|
* only when the reading crosses a quantum, which is what keeps re-injection
|
|
@@ -118,27 +164,251 @@ const DEFAULT_OPTIONS = {
|
|
|
118
164
|
* snapshot would then be re-committed on every single step.
|
|
119
165
|
*/
|
|
120
166
|
quantumPercent: 5,
|
|
167
|
+
/**
|
|
168
|
+
* Translate the remaining headroom into this session's own pace ("~6 more
|
|
169
|
+
* steps"). Display-only: it never moves a band edge, the threshold, or the
|
|
170
|
+
* decision to fold. It needs the host's per-step counter (`agent.phase`); when
|
|
171
|
+
* that is absent the clause is omitted rather than guessed.
|
|
172
|
+
*/
|
|
173
|
+
paceEstimate: true,
|
|
174
|
+
/** Recent per-step deltas the estimate takes the median of. */
|
|
175
|
+
paceSamples: 16,
|
|
176
|
+
/** Samples required before any estimate is shown. */
|
|
177
|
+
paceMinSamples: 3,
|
|
178
|
+
/** Margin a higher rung must clear before the line promises more steps. */
|
|
179
|
+
paceMargin: 0.25,
|
|
121
180
|
/** Append the "this line is the only authority" clause. */
|
|
122
181
|
authoritative: true,
|
|
123
182
|
/** Add the explicit "earlier claims are stale" clause to the calm band. */
|
|
124
183
|
staleClaimClause: true,
|
|
184
|
+
/**
|
|
185
|
+
* Report how much of the window is still unused. This is the figure that
|
|
186
|
+
* answers "how much context do I have left" — the headroom figure answers
|
|
187
|
+
* "how far to the fold", and conflating them is what produced "Very low
|
|
188
|
+
* context" next to 350K of free window.
|
|
189
|
+
*/
|
|
190
|
+
freeClause: true,
|
|
191
|
+
/**
|
|
192
|
+
* Define what the fold is in the `tight` and `critical` bands. Without it the
|
|
193
|
+
* remaining-room figure reads as "context left" rather than "room before a
|
|
194
|
+
* routine reorganization", which is what a live model acted on.
|
|
195
|
+
*/
|
|
196
|
+
foldClause: true,
|
|
125
197
|
/** Log each band change through ctx.logger, when a logger is present. */
|
|
126
198
|
logBandChanges: true,
|
|
127
199
|
/** Append `compactionRules` to the summarizer directive. */
|
|
128
200
|
patchCompactionPrompt: true,
|
|
129
201
|
/** Rules appended to the summarizer directive; `[]` disables the append. */
|
|
130
202
|
compactionRules: DEFAULT_COMPACTION_RULES,
|
|
203
|
+
/**
|
|
204
|
+
* Fold at the idle boundary once the reading is within `foldAtIdleMarginPercent`
|
|
205
|
+
* of the compaction point.
|
|
206
|
+
*
|
|
207
|
+
* The host's automatic compaction is a *crossing* trigger, and the behaviour it
|
|
208
|
+
* produces near the point — batching, avoiding risky edits, stopping
|
|
209
|
+
* mid-iteration to commit WIP — is exactly what keeps the reading just below it.
|
|
210
|
+
* Measured on a live session: four hours with no fold, every turn two to eight
|
|
211
|
+
* steps long, and three consecutive "continue" instructions unable to finish one
|
|
212
|
+
* task. Folding at the model's own turn boundary breaks that loop, and the
|
|
213
|
+
* official engine only accepts `compactNow` while the agent is idle, which is
|
|
214
|
+
* precisely when this fires.
|
|
215
|
+
*
|
|
216
|
+
* Off by default: it spends a summarizer call and rewrites the window, which is
|
|
217
|
+
* a policy decision rather than telemetry.
|
|
218
|
+
*/
|
|
219
|
+
foldAtIdle: false,
|
|
220
|
+
/** Headroom, as a percent of the window, at or below which the idle fold fires. */
|
|
221
|
+
foldAtIdleMarginPercent: 5,
|
|
222
|
+
/**
|
|
223
|
+
* How the fold is requested.
|
|
224
|
+
*
|
|
225
|
+
* `command` (the preferred half of `auto`) runs the session's own `/compact`
|
|
226
|
+
* through the **agent's** command view, so the fold is executed by whichever
|
|
227
|
+
* backend that agent's realm mounts — the same engine a human's `/compact`
|
|
228
|
+
* reaches. That matters twice over: it is the only path that works on a stock
|
|
229
|
+
* deployment (upstream discussion 9425: a profile-scope plugin cannot inject a
|
|
230
|
+
* preset realm's `compaction` service), and it keeps the summary style
|
|
231
|
+
* consistent with the folds the session would get on its own.
|
|
232
|
+
*
|
|
233
|
+
* `service` calls `ctx.compaction.compactNow()` directly, which is all a
|
|
234
|
+
* same-scope provider needs (e.g. `@aiwayds/dsh-dcp`) and is the only option
|
|
235
|
+
* when the realm registers no `compact` command.
|
|
236
|
+
*
|
|
237
|
+
* `auto` tries the command first and falls back to the service.
|
|
238
|
+
*/
|
|
239
|
+
foldAtIdleMethod: 'auto',
|
|
240
|
+
/** Minimum gap between idle-fold attempts, so a failure cannot hammer the engine. */
|
|
241
|
+
foldAtIdleCooldownMs: 60000,
|
|
242
|
+
/**
|
|
243
|
+
* Which fold policy owns the session. Capability 3, and the only option here
|
|
244
|
+
* that changes *behaviour* rather than reporting.
|
|
245
|
+
*
|
|
246
|
+
* `off` — another plugin (or the host's own pressure trigger) owns it.
|
|
247
|
+
* Folding spends a summarizer call and rewrites the window, so this
|
|
248
|
+
* is the opt-out for deployments that do not want it.
|
|
249
|
+
* `idle` — the legacy turn-boundary fold, and the DEFAULT. Folds when the
|
|
250
|
+
* idle reading is within `foldAtIdleMarginPercent` of the fold point.
|
|
251
|
+
* `handoff` — EXPERIMENTAL. Handoff-first. The model is reminded at `handoffAt` ×
|
|
252
|
+
* the fold point, writes its own handoff note, registers it with
|
|
253
|
+
* `handoff_ready`, and the fold runs at that round's end. Exactly
|
|
254
|
+
* one follow-up turn is activated, and its first instruction is to
|
|
255
|
+
* read that note back before touching the task.
|
|
256
|
+
*/
|
|
257
|
+
foldMode: 'idle',
|
|
258
|
+
/**
|
|
259
|
+
* Prep point as a fraction of the FOLD POINT (not of the window): at
|
|
260
|
+
* `handoffAt` × fold point the handoff reminder is injected. 0.85 leaves the
|
|
261
|
+
* model roughly one turn's worth of steps before the host's own pressure fold
|
|
262
|
+
* would take the decision away from it.
|
|
263
|
+
*/
|
|
264
|
+
handoffAt: 0.85,
|
|
265
|
+
/**
|
|
266
|
+
* Where handoff notes live. `''` means `$DSH_HOME/handoffs`, and a relative
|
|
267
|
+
* value resolves under `$DSH_HOME`. Never the workspace: a note that lives in
|
|
268
|
+
* the repo becomes project state, and it is recycled.
|
|
269
|
+
*/
|
|
270
|
+
handoffDir: '',
|
|
271
|
+
/**
|
|
272
|
+
* How many prep reminders one fold cycle may inject (each lands at most once
|
|
273
|
+
* per turn). After the budget is spent the host's pressure fold takes over,
|
|
274
|
+
* which is the behaviour this mode exists to improve on — so keep it above 1.
|
|
275
|
+
*/
|
|
276
|
+
handoffReminders: 3,
|
|
131
277
|
}
|
|
132
278
|
|
|
279
|
+
/**
|
|
280
|
+
* Settings schema. The host turns a plugin's `Config` into a form on the settings
|
|
281
|
+
* page and writes edits back into the profile patch, so every option is
|
|
282
|
+
* switchable without editing YAML. Defaults here mirror `DEFAULT_OPTIONS`;
|
|
283
|
+
* `resolveOptions` stays the only place that interprets them, so a value the form
|
|
284
|
+
* never writes behaves exactly like one it does.
|
|
285
|
+
*
|
|
286
|
+
* `.volatile()` ON EVERY FIELD (EXCEPT `enabled`) IS LOAD-BEARING. The settings
|
|
287
|
+
* service builds its form with `volatileForm(schema)`, which keeps only nodes
|
|
288
|
+
* marked volatile and drops the whole entry when nothing survives — a schema
|
|
289
|
+
* without a single marker renders **no form at all**, silently. Volatile is also
|
|
290
|
+
* the truth: the loader commits such a change straight into the running
|
|
291
|
+
* reference (`_commitVolatile`) instead of reloading the plugin, which is why
|
|
292
|
+
* `apply` reads its options through a resolver rather than a snapshot. `enabled`
|
|
293
|
+
* is deliberately left out: it decides whether the context line is registered at
|
|
294
|
+
* all, and the plugin list already carries an on/off switch for that.
|
|
295
|
+
*/
|
|
296
|
+
export const Config = z.object({
|
|
297
|
+
enabled: z.boolean().default(true),
|
|
298
|
+
order: z.number().default(DEFAULT_ORDER).volatile(),
|
|
299
|
+
language: z.string().default('en').volatile(),
|
|
300
|
+
showAutoCompactionPoint: z.boolean().default(true).volatile(),
|
|
301
|
+
thresholdRatio: z.number().default(0.7).volatile(),
|
|
302
|
+
headroomTokens: z.number().step(1).min(0).default(65536).volatile(),
|
|
303
|
+
reservedCompletionTokens: z.number().step(1).min(0).volatile(),
|
|
304
|
+
moderateAt: z.number().default(0.5).volatile(),
|
|
305
|
+
tightAt: z.number().default(0.85).volatile(),
|
|
306
|
+
hysteresis: z.number().min(0).default(0.05).volatile(),
|
|
307
|
+
tightAdvice: z.string().default('none').volatile(),
|
|
308
|
+
quantumPercent: z.number().min(0).default(5).volatile(),
|
|
309
|
+
paceEstimate: z.boolean().default(true).volatile(),
|
|
310
|
+
paceSamples: z.number().step(1).min(2).default(16).volatile(),
|
|
311
|
+
paceMinSamples: z.number().step(1).min(1).default(3).volatile(),
|
|
312
|
+
paceMargin: z.number().min(0).default(0.25).volatile(),
|
|
313
|
+
authoritative: z.boolean().default(true).volatile(),
|
|
314
|
+
staleClaimClause: z.boolean().default(true).volatile(),
|
|
315
|
+
freeClause: z.boolean().default(true).volatile(),
|
|
316
|
+
foldClause: z.boolean().default(true).volatile(),
|
|
317
|
+
logBandChanges: z.boolean().default(true).volatile(),
|
|
318
|
+
patchCompactionPrompt: z.boolean().default(true).volatile(),
|
|
319
|
+
// A field with no schema default is materialized as `[]`, and `[]` means "append
|
|
320
|
+
// nothing" here — so the default must carry the real rules, or merely adding the
|
|
321
|
+
// schema switches capability 2 off. Found live: the running config read
|
|
322
|
+
// `compactionRules: []` and the summarizer directive went unpatched.
|
|
323
|
+
compactionRules: z.array(z.string()).default(DEFAULT_COMPACTION_RULES).volatile(),
|
|
324
|
+
/**
|
|
325
|
+
* Legacy switch, read only by `resolveFoldMode`. NO `.default()` on purpose: a
|
|
326
|
+
* materialized `false` would make every untouched config look like an explicit
|
|
327
|
+
* opt-out, and the resolver could no longer tell "never set" (→ `idle`) from
|
|
328
|
+
* "set to false" (→ `off`).
|
|
329
|
+
*/
|
|
330
|
+
foldAtIdle: z.boolean().volatile(),
|
|
331
|
+
foldAtIdleMarginPercent: z.number().min(0.1).max(50).default(5).volatile(),
|
|
332
|
+
foldAtIdleMethod: z.string().default('auto').volatile(),
|
|
333
|
+
foldAtIdleCooldownMs: z.number().step(1).min(0).default(60000).volatile(),
|
|
334
|
+
/**
|
|
335
|
+
* NO `.default()` HERE, AND THAT IS LOAD-BEARING. An absent key is the only way
|
|
336
|
+
* this plugin can tell "the user never chose a mode" apart from "the user chose
|
|
337
|
+
* a mode", and that distinction is what makes the compatibility rules safe: a
|
|
338
|
+
* config written before `foldMode` existed resolves to `idle` (folding at the
|
|
339
|
+
* model's own turn boundary is what it already did), a config that explicitly
|
|
340
|
+
* set `foldAtIdle: false` keeps opting out, and a config the settings form has
|
|
341
|
+
* touched stays exactly where it was put. `resolveOptions` is the only reader,
|
|
342
|
+
* so an absent key never reaches runtime.
|
|
343
|
+
*/
|
|
344
|
+
foldMode: z.union([z.const('off'), z.const('idle'), z.const('handoff')]).volatile(),
|
|
345
|
+
handoffAt: z.number().min(0.5).max(0.95).default(0.85).volatile(),
|
|
346
|
+
handoffDir: z.string().default('').volatile(),
|
|
347
|
+
handoffReminders: z.number().step(1).min(0).default(3).volatile(),
|
|
348
|
+
})
|
|
349
|
+
|
|
133
350
|
/** Clamp a numeric option, falling back when it is not a finite number. */
|
|
134
351
|
function num(value, fallback) {
|
|
135
352
|
return typeof value === 'number' && Number.isFinite(value) ? value : fallback
|
|
136
353
|
}
|
|
137
354
|
|
|
355
|
+
/** The marker `cosmokit` puts on a volatile config reference. */
|
|
356
|
+
const VOLATILE_WRITE = Symbol.for('cosmokit.volatile.write')
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Materialize one config value.
|
|
360
|
+
*
|
|
361
|
+
* A field declared `.volatile()` is stored by the host as a live *reference*, not
|
|
362
|
+
* a plain value — that is the mechanism that lets the settings page change an
|
|
363
|
+
* option without reloading the plugin (`loader._commitVolatile` writes into the
|
|
364
|
+
* running reference). So `ctx.config` hands this plugin reference objects, and
|
|
365
|
+
* the host's own adapters unwrap them the same way (`plainOptions`). Detection is
|
|
366
|
+
* structural and matches `cosmokit.isVolatile`.
|
|
367
|
+
*/
|
|
368
|
+
function plainValue(value) {
|
|
369
|
+
if (
|
|
370
|
+
value !== null &&
|
|
371
|
+
typeof value === 'object' &&
|
|
372
|
+
VOLATILE_WRITE in value &&
|
|
373
|
+
typeof value.get === 'function'
|
|
374
|
+
) {
|
|
375
|
+
return plainValue(value.get())
|
|
376
|
+
}
|
|
377
|
+
return value
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Materialize a whole config object, one level deep, as the host does. */
|
|
381
|
+
function plainConfig(config) {
|
|
382
|
+
if (config === null || typeof config !== 'object') return config
|
|
383
|
+
const out = {}
|
|
384
|
+
for (const [key, value] of Object.entries(config)) out[key] = plainValue(value)
|
|
385
|
+
return out
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Resolve the fold mode, with `foldAtIdle` as the deprecated spelling of `idle`.
|
|
390
|
+
*
|
|
391
|
+
* `raw` is the validated config, not the merged defaults: the schema leaves
|
|
392
|
+
* `foldMode` defaultless on purpose so that a missing key is observable here.
|
|
393
|
+
*
|
|
394
|
+
* DEFAULT = `idle`: folding at the model's own turn boundary is what this plugin
|
|
395
|
+
* did before `foldMode` existed (behind `foldAtIdle: true`), and a config that
|
|
396
|
+
* never touched either key must keep that behaviour. `foldAtIdle: false` is the
|
|
397
|
+
* explicit opt-out that predates the mode selector, so it still resolves to `off`.
|
|
398
|
+
* An explicit `foldMode` always wins, because the settings form writes one the
|
|
399
|
+
* moment a human picks a mode.
|
|
400
|
+
*/
|
|
401
|
+
function resolveFoldMode(raw) {
|
|
402
|
+
const explicit = raw !== null && typeof raw === 'object' ? raw.foldMode : undefined
|
|
403
|
+
if (explicit === 'off' || explicit === 'idle' || explicit === 'handoff') return explicit
|
|
404
|
+
const legacy = raw !== null && typeof raw === 'object' ? raw.foldAtIdle : undefined
|
|
405
|
+
return legacy === false ? 'off' : 'idle'
|
|
406
|
+
}
|
|
407
|
+
|
|
138
408
|
/** Merge user config over the defaults with light validation. */
|
|
139
409
|
function resolveOptions(config) {
|
|
140
|
-
const raw = config
|
|
141
|
-
const merged = { ...DEFAULT_OPTIONS, ...raw }
|
|
410
|
+
const raw = plainConfig(config)
|
|
411
|
+
const merged = raw !== null && typeof raw === 'object' ? { ...DEFAULT_OPTIONS, ...raw } : DEFAULT_OPTIONS
|
|
142
412
|
const rules = Array.isArray(merged.compactionRules)
|
|
143
413
|
? merged.compactionRules.filter((rule) => typeof rule === 'string' && rule.trim().length > 0)
|
|
144
414
|
: DEFAULT_COMPACTION_RULES
|
|
@@ -155,8 +425,38 @@ function resolveOptions(config) {
|
|
|
155
425
|
moderateAt: num(merged.moderateAt, DEFAULT_OPTIONS.moderateAt),
|
|
156
426
|
tightAt: num(merged.tightAt, DEFAULT_OPTIONS.tightAt),
|
|
157
427
|
hysteresis: Math.max(0, num(merged.hysteresis, DEFAULT_OPTIONS.hysteresis)),
|
|
428
|
+
tightAdvice:
|
|
429
|
+
merged.tightAdvice === 'stop' ? 'stop' : merged.tightAdvice === 'inform' ? 'inform' : 'none',
|
|
430
|
+
foldClause: merged.foldClause === true,
|
|
431
|
+
freeClause: merged.freeClause === true,
|
|
158
432
|
quantumPercent: Math.max(0, num(merged.quantumPercent, DEFAULT_OPTIONS.quantumPercent)),
|
|
433
|
+
paceEstimate: merged.paceEstimate === true,
|
|
434
|
+
paceSamples: Math.max(2, Math.round(num(merged.paceSamples, DEFAULT_OPTIONS.paceSamples))),
|
|
435
|
+
paceMinSamples: Math.max(1, Math.round(num(merged.paceMinSamples, DEFAULT_OPTIONS.paceMinSamples))),
|
|
436
|
+
paceMargin: Math.max(0, num(merged.paceMargin, DEFAULT_OPTIONS.paceMargin)),
|
|
159
437
|
compactionRules: rules,
|
|
438
|
+
foldAtIdle: merged.foldAtIdle === true,
|
|
439
|
+
foldAtIdleMarginPercent: Math.min(
|
|
440
|
+
50,
|
|
441
|
+
Math.max(0.1, num(merged.foldAtIdleMarginPercent, DEFAULT_OPTIONS.foldAtIdleMarginPercent)),
|
|
442
|
+
),
|
|
443
|
+
foldAtIdleMethod:
|
|
444
|
+
merged.foldAtIdleMethod === 'command' || merged.foldAtIdleMethod === 'service'
|
|
445
|
+
? merged.foldAtIdleMethod
|
|
446
|
+
: 'auto',
|
|
447
|
+
foldAtIdleCooldownMs: Math.max(
|
|
448
|
+
0,
|
|
449
|
+
num(merged.foldAtIdleCooldownMs, DEFAULT_OPTIONS.foldAtIdleCooldownMs),
|
|
450
|
+
),
|
|
451
|
+
// Already resolved from `raw`, so a legacy `foldAtIdle: true` and an explicit
|
|
452
|
+
// `foldMode` can never disagree downstream.
|
|
453
|
+
foldMode: resolveFoldMode(raw),
|
|
454
|
+
handoffAt: Math.min(0.95, Math.max(0.5, num(merged.handoffAt, DEFAULT_OPTIONS.handoffAt))),
|
|
455
|
+
handoffDir: typeof merged.handoffDir === 'string' ? merged.handoffDir.trim() : '',
|
|
456
|
+
handoffReminders: Math.max(
|
|
457
|
+
0,
|
|
458
|
+
Math.round(num(merged.handoffReminders, DEFAULT_OPTIONS.handoffReminders)),
|
|
459
|
+
),
|
|
160
460
|
}
|
|
161
461
|
}
|
|
162
462
|
|
|
@@ -174,25 +474,93 @@ function percentOf(value, total) {
|
|
|
174
474
|
return Math.round((value / total) * 100)
|
|
175
475
|
}
|
|
176
476
|
|
|
477
|
+
/** Read a wired service by property for diagnostics; never throws. */
|
|
478
|
+
function serviceOr(ctx, key) {
|
|
479
|
+
try {
|
|
480
|
+
return ctx[key]
|
|
481
|
+
} catch {
|
|
482
|
+
return undefined
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Name the mounted compaction backend by its prototype chain, for diagnostics.
|
|
488
|
+
*
|
|
489
|
+
* Which backend owns the seam decides two things this plugin cares about: whether
|
|
490
|
+
* a fold can be requested at all (`compactNow` reachable from a plugin context —
|
|
491
|
+
* the stock backend is not, see upstream discussion 9425), and whether capability
|
|
492
|
+
* 2 has anything to patch (a deterministic backend makes no summarizer call, so
|
|
493
|
+
* the directive rules never apply).
|
|
494
|
+
*
|
|
495
|
+
* @returns the chain, or `none` when no service is reachable.
|
|
496
|
+
*/
|
|
497
|
+
function backendIdentity(service) {
|
|
498
|
+
try {
|
|
499
|
+
if (!isService(service)) return 'none'
|
|
500
|
+
const chain = []
|
|
501
|
+
let proto = Object.getPrototypeOf(service)
|
|
502
|
+
while (proto !== null && proto.constructor !== undefined && chain.length < 5) {
|
|
503
|
+
if (proto.constructor.name === 'Object') break
|
|
504
|
+
chain.push(proto.constructor.name)
|
|
505
|
+
proto = Object.getPrototypeOf(proto)
|
|
506
|
+
}
|
|
507
|
+
return chain.length === 0 ? 'anonymous' : chain.join('>')
|
|
508
|
+
} catch {
|
|
509
|
+
return 'unknown'
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
177
513
|
/** Resolve a service that may or may not be mounted, without ever throwing. */
|
|
178
514
|
function safeGet(ctx, key) {
|
|
515
|
+
let viaMethod
|
|
179
516
|
try {
|
|
180
|
-
|
|
517
|
+
viaMethod = ctx.get(key)
|
|
181
518
|
} catch {
|
|
182
|
-
|
|
519
|
+
viaMethod = undefined
|
|
520
|
+
}
|
|
521
|
+
if (isService(viaMethod)) return viaMethod
|
|
522
|
+
let viaProperty
|
|
523
|
+
try {
|
|
524
|
+
viaProperty = ctx[key]
|
|
525
|
+
} catch {
|
|
526
|
+
viaProperty = undefined
|
|
183
527
|
}
|
|
528
|
+
return isService(viaProperty) ? viaProperty : undefined
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* Whether a value is a reachable service.
|
|
533
|
+
*
|
|
534
|
+
* Load-bearing: cordis answers a property read for a service this fiber does not
|
|
535
|
+
* have with a **string** ("not injected" style diagnostics), not `undefined`. An
|
|
536
|
+
* earlier revision accepted anything non-undefined, so the idle fold concluded it
|
|
537
|
+
* had a service and then failed the `compactNow` shape check — and the "no service
|
|
538
|
+
* mounted" warning fired on every trigger while the real reason stayed invisible.
|
|
539
|
+
*/
|
|
540
|
+
function isService(value) {
|
|
541
|
+
return value !== null && (typeof value === 'object' || typeof value === 'function')
|
|
184
542
|
}
|
|
185
543
|
|
|
186
544
|
/**
|
|
187
545
|
* Read the host's own occupancy figure for one session.
|
|
188
546
|
* @returns `{ used, window, reserved, threshold }`; any field may be `undefined`.
|
|
189
547
|
*/
|
|
190
|
-
function readOccupancy(ctx, session, options) {
|
|
548
|
+
function readOccupancy(ctx, session, options, injectedMeter) {
|
|
191
549
|
const result = {}
|
|
192
550
|
let used
|
|
193
551
|
let window_
|
|
194
552
|
|
|
195
|
-
|
|
553
|
+
// `injectedMeter` is a resolver (see `apply`), not a value: reading it per use
|
|
554
|
+
// follows a host that swaps the service.
|
|
555
|
+
let meter
|
|
556
|
+
if (injectedMeter !== undefined) {
|
|
557
|
+
try {
|
|
558
|
+
meter = injectedMeter()
|
|
559
|
+
} catch {
|
|
560
|
+
meter = undefined
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
if (meter === undefined) meter = safeGet(ctx, 'tokenMeter')
|
|
196
564
|
if (meter !== undefined && typeof meter.measure === 'function') {
|
|
197
565
|
try {
|
|
198
566
|
const measured = meter.measure(session)
|
|
@@ -312,14 +680,21 @@ function quantize(used, window_, options) {
|
|
|
312
680
|
/**
|
|
313
681
|
* Display step for the remaining-headroom figure. Every step is a function of the
|
|
314
682
|
* reading, so a whole bucket renders to one identical string.
|
|
683
|
+
*
|
|
684
|
+
* The floor is deliberately coarse. An earlier build shrank the step to 2K as the
|
|
685
|
+
* room ran out, which re-injected the line on nearly every step in exactly the
|
|
686
|
+
* band that was already talking about the fold: over one long session the tight
|
|
687
|
+
* band was committed 333 times at a median gap of 45s, with runs of 4–20s. Within
|
|
688
|
+
* a few tens of thousands of tokens of the point, the pace estimate is the useful
|
|
689
|
+
* signal, not the exact remainder — and the sub-step rendering ("Under 10K") keeps
|
|
690
|
+
* a remainder smaller than one step honest.
|
|
315
691
|
*/
|
|
316
692
|
function headroomDisplayStep(headroom, window_, options) {
|
|
317
693
|
const coarse = displayStep(window_, options)
|
|
318
694
|
const tiers = [
|
|
319
695
|
coarse,
|
|
320
696
|
Math.max(1000, Math.round(coarse * 0.4)),
|
|
321
|
-
Math.max(1000, Math.round(coarse * 0.
|
|
322
|
-
2000,
|
|
697
|
+
Math.max(1000, Math.round(coarse * 0.2)),
|
|
323
698
|
]
|
|
324
699
|
for (const tier of tiers) {
|
|
325
700
|
if (headroom >= 4 * tier) return tier
|
|
@@ -339,11 +714,22 @@ function quantizeHeadroom(headroom, window_, options) {
|
|
|
339
714
|
return Math.floor(headroom / step) * step
|
|
340
715
|
}
|
|
341
716
|
|
|
342
|
-
/**
|
|
717
|
+
/**
|
|
718
|
+
* The clause that closes every variant.
|
|
719
|
+
*
|
|
720
|
+
* The "do not count it down yourself" half is not decoration. A live session
|
|
721
|
+
* showed the model reading the figure correctly and then spending it in its head
|
|
722
|
+
* across the steps that followed — `30K → 28K → 16K → 10K → 7K → 5K` — while the
|
|
723
|
+
* host's own number sat still at `About 10K` (it is restated only when it changes,
|
|
724
|
+
* which is what keeps this line from re-injecting every step). Twelve minutes
|
|
725
|
+
* later it announced "Context is nearly exhausted (~5K)", a figure the host never
|
|
726
|
+
* reported. The measured number has to be labelled a measurement, not an
|
|
727
|
+
* allowance to draw down.
|
|
728
|
+
*/
|
|
343
729
|
function authorityClause(language) {
|
|
344
730
|
return language === 'zh'
|
|
345
|
-
? '
|
|
346
|
-
:
|
|
731
|
+
? '本行是宿主的后台遥测,也是上下文压力的唯一权威——不要提起它、不要凭对话长度或轮数估计压力、不要自行倒计时(读数变化时它会自动重述),也不要对压缩采取任何动作:折叠由宿主在步与步之间自动完成。'
|
|
732
|
+
: 'Background telemetry from the host, and the only authority on context pressure: do not mention it, do not estimate or count it down yourself — it is restated whenever it changes — and take no action about compaction; the host folds between steps automatically.'
|
|
347
733
|
}
|
|
348
734
|
|
|
349
735
|
/** The clause that retires claims inherited from earlier turns and checkpoints. */
|
|
@@ -353,6 +739,56 @@ function staleClause(language) {
|
|
|
353
739
|
: 'Earlier claims that context is nearly exhausted — including ones inside compacted checkpoints — are stale.'
|
|
354
740
|
}
|
|
355
741
|
|
|
742
|
+
/**
|
|
743
|
+
* The `tight` band's closing sentence, when one is configured.
|
|
744
|
+
*
|
|
745
|
+
* `none` is the default and adds nothing: the numbers are the message. The 0.1.4
|
|
746
|
+
* build described the coming fold here, and a live session showed what that
|
|
747
|
+
* costs — the band re-injects most often, so the model read a fresh fold notice
|
|
748
|
+
* every step or two, began narrating "I should compact" in its own replies, and
|
|
749
|
+
* lost momentum. A sentence about an automatic, host-owned event turned into a
|
|
750
|
+
* task the model thought it owned.
|
|
751
|
+
*
|
|
752
|
+
* `inform` restores the 0.1.4 factual sentence, `stop` the 0.1.3 imperative.
|
|
753
|
+
*/
|
|
754
|
+
function tightClause(zh, options) {
|
|
755
|
+
if (options.tightAdvice === 'stop') {
|
|
756
|
+
return zh
|
|
757
|
+
? ' 余量确实不多了——收完当前这一步、把状态落到磁盘,再考虑交接。'
|
|
758
|
+
: ' Headroom is genuinely small — finish the current step, land durable state, then hand off.'
|
|
759
|
+
}
|
|
760
|
+
if (options.tightAdvice === 'inform') {
|
|
761
|
+
return zh
|
|
762
|
+
? ' 到那时较早的对话会被折成一段 LLM 摘要、本窗口被重写——别让关键状态只存在于对话里。'
|
|
763
|
+
: ' At that point the older turns are folded into an LLM-written summary and this window is rewritten — keep nothing critical only in the conversation.'
|
|
764
|
+
}
|
|
765
|
+
return ''
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
/**
|
|
769
|
+
* What the fold *is*, for the two bands whose remaining room is small.
|
|
770
|
+
*
|
|
771
|
+
* The numbers alone left a gap a live session walked straight into: eleven
|
|
772
|
+
* seconds after the line said `Under 10K tokens of headroom remain before it`, the
|
|
773
|
+
* model wrote "Very low context. I must do this in as few commands as possible."
|
|
774
|
+
* It had read the figure correctly — it simply took "room before the fold" to mean
|
|
775
|
+
* "context left", when the window still held 350K and the fold only reorganizes
|
|
776
|
+
* it. This clause is that missing definition, stated as a fact: it orders nothing,
|
|
777
|
+
* so it cannot become the "finish the step and hand off" nudge of 0.1.3.
|
|
778
|
+
*
|
|
779
|
+
* `brief` is for the `critical` band, which already says a fold is expected and
|
|
780
|
+
* only needs the part that defuses "exhausted".
|
|
781
|
+
*/
|
|
782
|
+
function foldClause(zh, options, brief = false) {
|
|
783
|
+
if (options.foldClause !== true) return ''
|
|
784
|
+
if (brief) {
|
|
785
|
+
return zh ? ' 窗口并未耗尽——折叠之后工作照常继续。' : ' The window is not exhausted — work continues after the fold.'
|
|
786
|
+
}
|
|
787
|
+
return zh
|
|
788
|
+
? ' 折叠是例行操作,不是窗口的终点:较早的对话会被折成摘要,之后工作照常继续。'
|
|
789
|
+
: ' The fold is routine, not the end of the window: older turns become a summary and work continues after it.'
|
|
790
|
+
}
|
|
791
|
+
|
|
356
792
|
/** "under 50K" / "不足 50K" — the honest form of a figure below one display step. */
|
|
357
793
|
function underStep(step, zh) {
|
|
358
794
|
return zh ? `不足 ${formatTokens(step)}` : `under ${formatTokens(step)}`
|
|
@@ -364,6 +800,151 @@ function underPercent(step, window_, zh) {
|
|
|
364
800
|
return zh ? `不足 ${value}` : `under ${value}`
|
|
365
801
|
}
|
|
366
802
|
|
|
803
|
+
/**
|
|
804
|
+
* Step-count ladder for the pace estimate. Coarse on purpose: the runtime
|
|
805
|
+
* snapshot is re-committed only when its bytes change, so a figure that drifts
|
|
806
|
+
* every step would cost more in re-injection than it explains. The rendered rung
|
|
807
|
+
* moves only when the estimate crosses it.
|
|
808
|
+
*
|
|
809
|
+
* The top rung is open-ended (`20+`) because that is where the estimate is both
|
|
810
|
+
* least useful and most volatile: a live session's raw count ranged 23–38 across
|
|
811
|
+
* consecutive steps, which straddled a `21 / 34` boundary and flipped the line
|
|
812
|
+
* five times in 90 seconds. Above ~20 steps the exact figure changes no decision.
|
|
813
|
+
*/
|
|
814
|
+
const PACE_LADDER = [1, 2, 3, 5, 8, 13, 20]
|
|
815
|
+
|
|
816
|
+
/** Median of a small numeric array; does not mutate the input. */
|
|
817
|
+
function median(values) {
|
|
818
|
+
if (!Array.isArray(values) || values.length === 0) return undefined
|
|
819
|
+
const sorted = [...values].sort((left, right) => left - right)
|
|
820
|
+
const middle = sorted.length >> 1
|
|
821
|
+
return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Fold one prompt assembly into the per-session pace state.
|
|
826
|
+
*
|
|
827
|
+
* Sampling happens ONLY when the host's `(turn, step)` pair advances. One step
|
|
828
|
+
* can assemble more than once — retries, the compaction summarizer, session
|
|
829
|
+
* titling — and those extra assemblies are not work and must not enter the
|
|
830
|
+
* average as if they were.
|
|
831
|
+
*
|
|
832
|
+
* A negative delta means the meter re-based because a fold landed (measured in
|
|
833
|
+
* this deployment: 200K -> under 50K within three seconds). The history is
|
|
834
|
+
* dropped instead of being averaged against it, otherwise a single fold poisons
|
|
835
|
+
* the estimate for many steps afterwards. The estimate is the median of the
|
|
836
|
+
* recent positive deltas, so one 30K tool dump cannot drag it; a step that added
|
|
837
|
+
* nothing is not evidence about pace and is ignored.
|
|
838
|
+
*
|
|
839
|
+
* @returns `{ state, perStep, samples }`; `perStep` stays undefined until
|
|
840
|
+
* `paceMinSamples` samples exist, and stays undefined when the host exposes no
|
|
841
|
+
* step counter at all.
|
|
842
|
+
*/
|
|
843
|
+
function nextPaceState(previous, sample, options) {
|
|
844
|
+
const turn = sample === undefined || sample === null ? undefined : sample.turn
|
|
845
|
+
const step = sample === undefined || sample === null ? undefined : sample.step
|
|
846
|
+
const used = sample === undefined || sample === null ? undefined : sample.used
|
|
847
|
+
const observed = previous === undefined || previous === null ? undefined : previous
|
|
848
|
+
|
|
849
|
+
// No usable counter: keep whatever state we already have.
|
|
850
|
+
if (!Number.isFinite(turn) || !Number.isFinite(step) || !Number.isFinite(used)) {
|
|
851
|
+
return { state: observed, perStep: observed?.perStep, samples: observed?.recent.length ?? 0 }
|
|
852
|
+
}
|
|
853
|
+
if (observed === undefined) return { state: { turn, step, used, recent: [] }, perStep: undefined, samples: 0 }
|
|
854
|
+
|
|
855
|
+
// Same step assembled again: no new work, so nothing is sampled.
|
|
856
|
+
if (observed.turn === turn && observed.step === step) {
|
|
857
|
+
return { state: observed, perStep: observed.perStep, samples: observed.recent.length }
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const delta = used - observed.used
|
|
861
|
+
const recent =
|
|
862
|
+
delta < 0
|
|
863
|
+
? []
|
|
864
|
+
: delta === 0
|
|
865
|
+
? observed.recent
|
|
866
|
+
: [...observed.recent, delta].slice(-options.paceSamples)
|
|
867
|
+
const perStep = recent.length >= options.paceMinSamples ? median(recent) : undefined
|
|
868
|
+
return { state: { turn, step, used, recent, perStep }, perStep, samples: recent.length }
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* The estimate for one assembly, keeping per-session state in `store`.
|
|
873
|
+
* Undefined whenever the feature is off, the host has no step counter, or the
|
|
874
|
+
* session is too young — in which case the clause is absent, not zero.
|
|
875
|
+
*/
|
|
876
|
+
function samplePace(store, session, assembly, used, options) {
|
|
877
|
+
if (options.paceEstimate !== true || !Number.isFinite(used)) return undefined
|
|
878
|
+
const agent = assembly === undefined || assembly === null ? undefined : assembly.agent
|
|
879
|
+
const phase = agent === undefined || agent === null ? undefined : agent.phase
|
|
880
|
+
const next = nextPaceState(store.get(session), { turn: phase?.turn, step: phase?.step, used }, options)
|
|
881
|
+
if (next.state !== undefined) store.set(session, next.state)
|
|
882
|
+
return next.perStep
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** Whole steps the remaining headroom covers at the observed rate. */
|
|
886
|
+
function paceSteps(headroom, perStep) {
|
|
887
|
+
if (!Number.isFinite(headroom) || headroom < 0) return undefined
|
|
888
|
+
if (!Number.isFinite(perStep) || perStep <= 0) return undefined
|
|
889
|
+
return Math.floor(headroom / perStep)
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
/** Index of the largest ladder rung a step count still reaches, or undefined. */
|
|
893
|
+
function paceRung(steps) {
|
|
894
|
+
if (!Number.isFinite(steps) || steps < 1) return undefined
|
|
895
|
+
let index = 0
|
|
896
|
+
for (let i = 0; i < PACE_LADDER.length; i += 1) if (steps >= PACE_LADDER[i]) index = i
|
|
897
|
+
return index
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Settle the rung the line publishes.
|
|
902
|
+
*
|
|
903
|
+
* The estimate's own wobble is wider than one rung, so publishing it raw made the
|
|
904
|
+
* line flip: measured in a live session, `13 -> 21 -> 34+ -> 21 -> 34+` inside 90
|
|
905
|
+
* seconds, where one snapshot re-commit was caused by nothing but the flip (the
|
|
906
|
+
* headroom and the band were both unchanged). The rung therefore settles the way
|
|
907
|
+
* a band does, and asymmetrically:
|
|
908
|
+
*
|
|
909
|
+
* - downward — fewer remaining steps, i.e. less room promised — takes effect at
|
|
910
|
+
* once, the same direction the headroom itself rounds;
|
|
911
|
+
* - upward — promising more room — must clear the higher rung by `paceMargin`,
|
|
912
|
+
* so a straddling estimate cannot flip the line, while a genuinely slower
|
|
913
|
+
* session still gets the higher figure (the rule cannot freeze).
|
|
914
|
+
*
|
|
915
|
+
* @returns `{ state, steps }`, where `steps` re-derives the rung to render.
|
|
916
|
+
*/
|
|
917
|
+
function settlePace(steps, previous, options) {
|
|
918
|
+
const index = paceRung(steps)
|
|
919
|
+
if (index === undefined) return { state: previous, steps: undefined }
|
|
920
|
+
if (previous === undefined || previous === null || !Number.isFinite(previous.published)) {
|
|
921
|
+
return { state: { published: index }, steps: PACE_LADDER[index] }
|
|
922
|
+
}
|
|
923
|
+
if (index <= previous.published) return { state: { published: index }, steps: PACE_LADDER[index] }
|
|
924
|
+
const required = PACE_LADDER[index] * (1 + Math.max(0, options.paceMargin))
|
|
925
|
+
if (steps >= required) return { state: { published: index }, steps: PACE_LADDER[index] }
|
|
926
|
+
return { state: previous, steps: PACE_LADDER[previous.published] }
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* The pace clause, bucketed onto {@link PACE_LADDER}.
|
|
931
|
+
*
|
|
932
|
+
* The rung is the largest one the estimate still reaches, so the figure rounds
|
|
933
|
+
* DOWN like the headroom does: the line must never promise more remaining steps
|
|
934
|
+
* than the session's own rate supports. The top rung renders as "34+".
|
|
935
|
+
*/
|
|
936
|
+
function paceSentence(steps, zh) {
|
|
937
|
+
if (!Number.isFinite(steps) || steps < 1) return ''
|
|
938
|
+
let rung = PACE_LADDER[0]
|
|
939
|
+
for (const edge of PACE_LADDER) if (steps >= edge) rung = edge
|
|
940
|
+
const open = rung === PACE_LADDER[PACE_LADDER.length - 1]
|
|
941
|
+
const label = open ? `${rung}+` : String(rung)
|
|
942
|
+
const plural = rung === 1 ? '' : 's'
|
|
943
|
+
return zh
|
|
944
|
+
? ` 按本会话近期节奏,这点余量约合 ${label} 步。`
|
|
945
|
+
: ` At this session's recent rate that is roughly ${label} more step${plural}.`
|
|
946
|
+
}
|
|
947
|
+
|
|
367
948
|
/** Render the reading for one band. Pure: same inputs, same bytes. */
|
|
368
949
|
function render(band, reading, options) {
|
|
369
950
|
const zh = options.language === 'zh'
|
|
@@ -372,6 +953,18 @@ function render(band, reading, options) {
|
|
|
372
953
|
if (band === 'ample' && options.staleClaimClause) parts.push(staleClause(options.language))
|
|
373
954
|
const tail = parts.length === 0 ? '' : ` ${parts.join(' ')}`
|
|
374
955
|
|
|
956
|
+
// The estimate qualifies the remaining headroom, so it rides only on the two
|
|
957
|
+
// bands where that headroom is the decision at hand — together with the
|
|
958
|
+
// definition of what the fold is, without which the figure reads as "context
|
|
959
|
+
// left" rather than "room before a routine reorganization".
|
|
960
|
+
const pace = band === 'tight' || band === 'critical' ? paceSentence(reading.steps, zh) : ''
|
|
961
|
+
const fold =
|
|
962
|
+
band === 'tight'
|
|
963
|
+
? foldClause(zh, options)
|
|
964
|
+
: band === 'critical'
|
|
965
|
+
? foldClause(zh, options, true)
|
|
966
|
+
: ''
|
|
967
|
+
|
|
375
968
|
if (band === 'unknown') {
|
|
376
969
|
return zh
|
|
377
970
|
? `上下文实况:本会话尚未取到用量读数。不要据此声称上下文紧张。${tail}`
|
|
@@ -396,8 +989,28 @@ function render(band, reading, options) {
|
|
|
396
989
|
? ` 自动压缩阈值 ${formatTokens(reading.threshold)}(窗口的 ${percentOf(reading.threshold, reading.window)}%)。`
|
|
397
990
|
: ` Automatic compaction fires at ${formatTokens(reading.threshold)} (${percentOf(reading.threshold, reading.window)}% of the window).`
|
|
398
991
|
: ''
|
|
992
|
+
// How much of the window is still unused — the figure that actually answers
|
|
993
|
+
// "how much context do I have left?". The headroom above answers a different
|
|
994
|
+
// question ("how far to the fold"), and a live model answered the first with
|
|
995
|
+
// the second: "Very low context" at 10K of headroom, while 350K of the window
|
|
996
|
+
// was free. Quantized onto the same step as `used`, so it moves on exactly the
|
|
997
|
+
// same crossings and costs no extra re-injection.
|
|
998
|
+
const freeRaw = reading.freeRaw
|
|
999
|
+
const flooredFree = reading.free === 0 && Number.isFinite(freeRaw) && freeRaw > 0
|
|
1000
|
+
const free =
|
|
1001
|
+
options.freeClause !== true || !Number.isFinite(reading.free)
|
|
1002
|
+
? ''
|
|
1003
|
+
: flooredFree && step !== undefined
|
|
1004
|
+
? zh
|
|
1005
|
+
? ` 窗口还有${underStep(step, zh)} 未使用。`
|
|
1006
|
+
: ` Under ${formatTokens(step)} of the window is still free.`
|
|
1007
|
+
: zh
|
|
1008
|
+
? ` 窗口还有约 ${formatTokens(reading.free)} 未使用。`
|
|
1009
|
+
: ` About ${formatTokens(reading.free)} of the window is still free.`
|
|
1010
|
+
// Nothing left to report once the reading has reached the point: "About 0
|
|
1011
|
+
// tokens of headroom remain" is noise on the one line that should stay calm.
|
|
399
1012
|
const remaining =
|
|
400
|
-
head === undefined
|
|
1013
|
+
head === undefined || reading.headroomRaw === 0
|
|
401
1014
|
? ''
|
|
402
1015
|
: flooredHead && headStep !== undefined
|
|
403
1016
|
? zh
|
|
@@ -413,20 +1026,18 @@ function render(band, reading, options) {
|
|
|
413
1026
|
switch (band) {
|
|
414
1027
|
case 'ample':
|
|
415
1028
|
return zh
|
|
416
|
-
? `${head0}${point}${remaining} 上下文不紧张——不要因为"上下文不够"而收尾、交接子代理或缩小范围。${tail}`
|
|
417
|
-
: `${head0}${point}${remaining} Context is NOT scarce — do not wrap up, hand off to a subagent, or narrow scope for context reasons.${tail}`
|
|
1029
|
+
? `${head0}${free}${point}${remaining} 上下文不紧张——不要因为"上下文不够"而收尾、交接子代理或缩小范围。${tail}`
|
|
1030
|
+
: `${head0}${free}${point}${remaining} Context is NOT scarce — do not wrap up, hand off to a subagent, or narrow scope for context reasons.${tail}`
|
|
418
1031
|
case 'moderate':
|
|
419
1032
|
return zh
|
|
420
|
-
? `${head0}${point}${remaining} 仍有充足余量,继续推进即可,顺手把关键状态写进文档或提交。${tail}`
|
|
421
|
-
: `${head0}${point}${remaining} There is still real headroom — keep going, and keep durable notes or commits current as you work.${tail}`
|
|
1033
|
+
? `${head0}${free}${point}${remaining} 仍有充足余量,继续推进即可,顺手把关键状态写进文档或提交。${tail}`
|
|
1034
|
+
: `${head0}${free}${point}${remaining} There is still real headroom — keep going, and keep durable notes or commits current as you work.${tail}`
|
|
422
1035
|
case 'tight':
|
|
423
|
-
return zh
|
|
424
|
-
? `${head0}${point}${remaining} 余量确实不多了——收完当前这一步、把状态落到磁盘,再考虑交接。${tail}`
|
|
425
|
-
: `${head0}${point}${remaining} Headroom is genuinely small — finish the current step, land durable state, then hand off.${tail}`
|
|
1036
|
+
return `${head0}${free}${point}${remaining}${pace}${fold}${tightClause(zh, options)}${tail}`
|
|
426
1037
|
default:
|
|
427
1038
|
return zh
|
|
428
|
-
? `${head0}${point} 已到或越过自动压缩点——接下来可能发生压缩折叠,别让关键状态只存在于本窗口。${tail}`
|
|
429
|
-
: `${head0}${point} At or past the automatic compaction point — expect earlier turns to be folded; keep nothing critical only in this window.${tail}`
|
|
1039
|
+
? `${head0}${free}${point}${remaining}${pace}${fold} 已到或越过自动压缩点——接下来可能发生压缩折叠,别让关键状态只存在于本窗口。${tail}`
|
|
1040
|
+
: `${head0}${free}${point}${remaining}${pace}${fold} At or past the automatic compaction point — expect earlier turns to be folded; keep nothing critical only in this window.${tail}`
|
|
430
1041
|
}
|
|
431
1042
|
}
|
|
432
1043
|
|
|
@@ -525,11 +1136,44 @@ function patchCompactionRequest(options, rules) {
|
|
|
525
1136
|
* @param config - optional overrides of the defaults documented above.
|
|
526
1137
|
*/
|
|
527
1138
|
export function apply(ctx, config) {
|
|
528
|
-
|
|
1139
|
+
// Read options through this on every use. A field declared `.volatile()` is a
|
|
1140
|
+
// live reference, so a settings change lands here without reloading the plugin
|
|
1141
|
+
// — a snapshot taken once at apply time would silently ignore every later
|
|
1142
|
+
// toggle. The listeners below are therefore installed unconditionally and gate
|
|
1143
|
+
// themselves per event instead of at install time.
|
|
1144
|
+
const resolve = () => resolveOptions(config)
|
|
1145
|
+
|
|
1146
|
+
// Services are acquired through `ctx.inject`, not `ctx.get`. `get` resolves
|
|
1147
|
+
// through `ctx.reflect` and returned nothing for `compaction` in a live
|
|
1148
|
+
// deployment: the idle fold's first real trigger (22:44, inside the margin, at
|
|
1149
|
+
// an idle boundary) logged "no compaction service is mounted" and folded
|
|
1150
|
+
// nothing. Injecting also keeps this plugin loading on deployments that mount
|
|
1151
|
+
// no compaction service at all, since the callback simply never runs.
|
|
1152
|
+
// Services are read per use through the proxy cordis wires for the declared
|
|
1153
|
+
// injections, never snapshotted: a host that swaps an implementation (or
|
|
1154
|
+
// provides one only later) must be followed. `readOccupancy` and the fold also
|
|
1155
|
+
// fall back to `safeGet`, which costs nothing and keeps the plugin usable if a
|
|
1156
|
+
// deployment resolves the names differently.
|
|
1157
|
+
const services = {
|
|
1158
|
+
meter: () => ctx.tokenMeter,
|
|
1159
|
+
// `ctx.compaction` answers with a diagnostic string when the service is not
|
|
1160
|
+
// reachable, which `isService` rejects; the fold therefore stays inactive and
|
|
1161
|
+
// logs why, once, instead of failing per trigger.
|
|
1162
|
+
compaction: () => ctx.compaction,
|
|
1163
|
+
}
|
|
1164
|
+
const compactionService = serviceOr(ctx, 'compaction')
|
|
1165
|
+
logLine(
|
|
1166
|
+
ctx,
|
|
1167
|
+
'info',
|
|
1168
|
+
'context-truth: services wired (tokenMeter=%s compaction=%s/%s)',
|
|
1169
|
+
typeof serviceOr(ctx, 'tokenMeter'),
|
|
1170
|
+
typeof compactionService,
|
|
1171
|
+
backendIdentity(compactionService),
|
|
1172
|
+
)
|
|
529
1173
|
|
|
530
|
-
if (
|
|
1174
|
+
if (resolve().enabled) {
|
|
531
1175
|
try {
|
|
532
|
-
installContextLine(ctx,
|
|
1176
|
+
installContextLine(ctx, resolve, services)
|
|
533
1177
|
} catch (error) {
|
|
534
1178
|
if (isAlreadyRegistered(error)) {
|
|
535
1179
|
const logger = ctx.logger
|
|
@@ -542,7 +1186,9 @@ export function apply(ctx, config) {
|
|
|
542
1186
|
}
|
|
543
1187
|
}
|
|
544
1188
|
|
|
545
|
-
installCompactionPatch(ctx,
|
|
1189
|
+
installCompactionPatch(ctx, resolve)
|
|
1190
|
+
installIdleFold(ctx, resolve, services)
|
|
1191
|
+
installHandoffFold(ctx, resolve, services)
|
|
546
1192
|
}
|
|
547
1193
|
|
|
548
1194
|
/** Whether a registration failed because the name is already taken in this layer. */
|
|
@@ -551,11 +1197,12 @@ function isAlreadyRegistered(error) {
|
|
|
551
1197
|
}
|
|
552
1198
|
|
|
553
1199
|
/** Install the `llm/stream` listener that extends the summarizer directive. */
|
|
554
|
-
function installCompactionPatch(ctx,
|
|
555
|
-
if (!options.patchCompactionPrompt || options.compactionRules.length === 0) return
|
|
1200
|
+
function installCompactionPatch(ctx, resolve) {
|
|
556
1201
|
let warned = false
|
|
557
1202
|
ctx.on('llm/stream', (request, next) => {
|
|
558
1203
|
try {
|
|
1204
|
+
const options = resolve()
|
|
1205
|
+
if (!options.patchCompactionPrompt || options.compactionRules.length === 0) return next()
|
|
559
1206
|
const applied = patchCompactionRequest(request, options.compactionRules)
|
|
560
1207
|
// Only a request its own caller tagged as compaction may spend the one-shot
|
|
561
1208
|
// warning. Warning on a heuristic match let an ordinary turn — one whose
|
|
@@ -575,19 +1222,1092 @@ function installCompactionPatch(ctx, options) {
|
|
|
575
1222
|
})
|
|
576
1223
|
}
|
|
577
1224
|
|
|
1225
|
+
/** Log through the host logger when present; logging must never break a turn. */
|
|
1226
|
+
function logLine(ctx, level, format, ...args) {
|
|
1227
|
+
try {
|
|
1228
|
+
const logger = ctx.logger
|
|
1229
|
+
if (logger !== undefined && typeof logger[level] === 'function') logger[level](format, ...args)
|
|
1230
|
+
} catch {
|
|
1231
|
+
// A logger that throws is the logger's problem, not the turn's.
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/**
|
|
1236
|
+
* Whether an idle session is close enough to the compaction point that its next
|
|
1237
|
+
* turns would be short sprints. Pure, so the decision is testable without stubs.
|
|
1238
|
+
*
|
|
1239
|
+
* @param reading - `{ used, threshold, window }` as returned by `readOccupancy`.
|
|
1240
|
+
* @param options - resolved plugin options.
|
|
1241
|
+
* @returns `{ fold }` plus the numbers behind the decision, for the log line.
|
|
1242
|
+
*/
|
|
1243
|
+
function shouldFoldAtIdle(reading, options) {
|
|
1244
|
+
// The mode is the authority, not the legacy flag: `resolveOptions` has already
|
|
1245
|
+
// mapped `foldAtIdle: true` onto `foldMode: 'idle'`, so a single gate keeps the
|
|
1246
|
+
// two spellings from ever disagreeing (`handoff` mode must not also fold here).
|
|
1247
|
+
if (options.foldMode !== 'idle') return { fold: false }
|
|
1248
|
+
const used = reading === null || reading === undefined ? undefined : reading.used
|
|
1249
|
+
const threshold = reading === null || reading === undefined ? undefined : reading.threshold
|
|
1250
|
+
const window_ = reading === null || reading === undefined ? undefined : reading.window
|
|
1251
|
+
if (!Number.isFinite(used) || !Number.isFinite(threshold) || threshold <= 0) return { fold: false }
|
|
1252
|
+
if (!Number.isFinite(window_) || window_ <= 0) return { fold: false }
|
|
1253
|
+
const margin = Math.round((window_ * options.foldAtIdleMarginPercent) / 100)
|
|
1254
|
+
const headroom = Math.round(threshold - used)
|
|
1255
|
+
return { fold: headroom <= margin, headroom, margin }
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* Fold at the idle boundary when the session is nearly out of room. See
|
|
1260
|
+
* `foldAtIdle` in DEFAULT_OPTIONS for why the host's crossing trigger is not
|
|
1261
|
+
* enough on its own. Every failure is logged and swallowed, and an attempt is
|
|
1262
|
+
* rate-limited: a trigger must never break a turn or hammer the engine.
|
|
1263
|
+
*/
|
|
1264
|
+
function installIdleFold(ctx, resolve, services) {
|
|
1265
|
+
let inFlight = false
|
|
1266
|
+
let attemptedAt = 0
|
|
1267
|
+
let warnedNoService = false
|
|
1268
|
+
ctx.on('agent/status', ({ agent, status } = {}) => {
|
|
1269
|
+
if (status !== 'idle' || agent === null || agent === undefined) return
|
|
1270
|
+
const options = resolve()
|
|
1271
|
+
if (options.foldMode !== 'idle') return
|
|
1272
|
+
if (inFlight || Date.now() - attemptedAt < options.foldAtIdleCooldownMs) return
|
|
1273
|
+
let decision
|
|
1274
|
+
try {
|
|
1275
|
+
const session = agent.session
|
|
1276
|
+
if (session === null || session === undefined) return
|
|
1277
|
+
decision = shouldFoldAtIdle(readOccupancy(ctx, session, options), options)
|
|
1278
|
+
} catch {
|
|
1279
|
+
return
|
|
1280
|
+
}
|
|
1281
|
+
if (!decision.fold) return
|
|
1282
|
+
inFlight = true
|
|
1283
|
+
attemptedAt = Date.now()
|
|
1284
|
+
const signal = new AbortController().signal
|
|
1285
|
+
Promise.resolve()
|
|
1286
|
+
.then(() => requestFold(ctx, agent, options, services, signal))
|
|
1287
|
+
.then(
|
|
1288
|
+
(outcome) => {
|
|
1289
|
+
if (outcome === undefined) {
|
|
1290
|
+
if (!warnedNoService) {
|
|
1291
|
+
warnedNoService = true
|
|
1292
|
+
logLine(
|
|
1293
|
+
ctx,
|
|
1294
|
+
'warn',
|
|
1295
|
+
'context-truth: foldAtIdle is enabled, but neither the realm /compact command nor a reachable compaction service answered (upstream discussion 9425); the idle fold stays inactive',
|
|
1296
|
+
)
|
|
1297
|
+
}
|
|
1298
|
+
return
|
|
1299
|
+
}
|
|
1300
|
+
logLine(
|
|
1301
|
+
ctx,
|
|
1302
|
+
'info',
|
|
1303
|
+
'context-truth: folded at idle via %s (headroom=%s margin=%s folded=%s)',
|
|
1304
|
+
outcome.how,
|
|
1305
|
+
decision.headroom,
|
|
1306
|
+
decision.margin,
|
|
1307
|
+
outcome.folded,
|
|
1308
|
+
)
|
|
1309
|
+
},
|
|
1310
|
+
(error) =>
|
|
1311
|
+
logLine(
|
|
1312
|
+
ctx,
|
|
1313
|
+
'warn',
|
|
1314
|
+
'context-truth: idle fold failed: %s',
|
|
1315
|
+
error === null || error === undefined ? 'unknown error' : (error.message ?? error),
|
|
1316
|
+
),
|
|
1317
|
+
)
|
|
1318
|
+
.finally(() => {
|
|
1319
|
+
inFlight = false
|
|
1320
|
+
})
|
|
1321
|
+
})
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
/**
|
|
1325
|
+
* Ask for one fold, at the agent's own idle boundary.
|
|
1326
|
+
*
|
|
1327
|
+
* Two channels, in this order, and the order is the point:
|
|
1328
|
+
*
|
|
1329
|
+
* 1. `commands.execute(agent, '/compact', …)` runs the session's own slash
|
|
1330
|
+
* command **through the agent's realm view**, so the fold lands on whichever
|
|
1331
|
+
* backend that agent mounts — the same engine a human's `/compact` reaches.
|
|
1332
|
+
* This is the only channel that works on a stock deployment: a plugin entry
|
|
1333
|
+
* lives at profile scope and cannot inject a preset realm's `compaction`
|
|
1334
|
+
* service (upstream discussion 9425). It is also the channel that keeps the
|
|
1335
|
+
* summary style consistent with the session's own folds.
|
|
1336
|
+
* 2. `ctx.compaction.compactNow()` on a provider reachable from the plugin's own
|
|
1337
|
+
* scope — the direct path, and the only one available when the realm registers
|
|
1338
|
+
* no `compact` command (e.g. a preset that drops `command-compact`).
|
|
1339
|
+
*
|
|
1340
|
+
* @returns `{ how, folded }` — which channel answered and whether a summary was
|
|
1341
|
+
* actually committed — or `undefined` when neither channel could be reached.
|
|
1342
|
+
* The two are separate answers on purpose: a `/compact` that finds no compactable
|
|
1343
|
+
* range answers successfully without folding, and capability 3 must not activate
|
|
1344
|
+
* a follow-up turn on the strength of a fold that never happened.
|
|
1345
|
+
*/
|
|
1346
|
+
async function requestFold(ctx, agent, options, services, signal) {
|
|
1347
|
+
if (options.foldAtIdleMethod !== 'service') {
|
|
1348
|
+
const commands = safeGet(ctx, 'commands')
|
|
1349
|
+
if (commands !== undefined && typeof commands.execute === 'function') {
|
|
1350
|
+
try {
|
|
1351
|
+
const result = await commands.execute(agent, '/compact', [], signal)
|
|
1352
|
+
// `sourceEventSeq` correlates the committed summary with `compaction/summary`
|
|
1353
|
+
// and is absent on the "No compactable history yet" success.
|
|
1354
|
+
return {
|
|
1355
|
+
how: 'command',
|
|
1356
|
+
folded: result !== null && result !== undefined && result.sourceEventSeq !== undefined,
|
|
1357
|
+
}
|
|
1358
|
+
} catch (error) {
|
|
1359
|
+
// A realm without the command, or a refusal, is not fatal: the service
|
|
1360
|
+
// channel below is still worth trying.
|
|
1361
|
+
logLine(
|
|
1362
|
+
ctx,
|
|
1363
|
+
'info',
|
|
1364
|
+
'context-truth: /compact request did not fold (%s); trying the compaction service',
|
|
1365
|
+
error === null || error === undefined ? 'unknown error' : (error.message ?? error),
|
|
1366
|
+
)
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
if (options.foldAtIdleMethod === 'command') return undefined
|
|
1371
|
+
// Ranked candidates, and the winner is the first that actually carries
|
|
1372
|
+
// `compactNow` — never "the first that is not undefined".
|
|
1373
|
+
//
|
|
1374
|
+
// That distinction is load-bearing: a property read for a service this fiber
|
|
1375
|
+
// does not have answers with a **diagnostic string**, not `undefined` (the foot
|
|
1376
|
+
// gun reported in upstream discussion 9425). An earlier revision took that
|
|
1377
|
+
// string as "found", skipped the `ctx.get` candidate that would have worked,
|
|
1378
|
+
// and then failed its own shape check — so the fold silently never fired while
|
|
1379
|
+
// the service was reachable the whole time.
|
|
1380
|
+
const candidates = []
|
|
1381
|
+
try {
|
|
1382
|
+
candidates.push(safeGet(agent.ctx, 'compaction'))
|
|
1383
|
+
} catch {
|
|
1384
|
+
// an agent without its own context is expected
|
|
1385
|
+
}
|
|
1386
|
+
try {
|
|
1387
|
+
candidates.push(safeGet(ctx, 'compaction'))
|
|
1388
|
+
} catch {
|
|
1389
|
+
// a context without `get` is expected on some harnesses
|
|
1390
|
+
}
|
|
1391
|
+
if (services.compaction !== undefined) {
|
|
1392
|
+
try {
|
|
1393
|
+
candidates.push(services.compaction())
|
|
1394
|
+
} catch {
|
|
1395
|
+
// a wired property that throws is simply not a candidate
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
const compaction = candidates.find(
|
|
1399
|
+
(candidate) => isService(candidate) && typeof candidate.compactNow === 'function',
|
|
1400
|
+
)
|
|
1401
|
+
if (compaction === undefined) return undefined
|
|
1402
|
+
const result = await compaction.compactNow(agent, signal)
|
|
1403
|
+
// `null` is the engine's documented "no safe useful range" answer.
|
|
1404
|
+
return { how: 'service', folded: result !== null && result !== undefined }
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
// ---------------------------------------------------------------------------
|
|
1408
|
+
// Capability 3 (`foldMode: 'handoff'`): fold behind the model's own handoff note.
|
|
1409
|
+
//
|
|
1410
|
+
// What `idle` mode leaves on the table is not the fold, it is the surprise. The
|
|
1411
|
+
// host folds on pressure, between steps, without telling the model; the model then
|
|
1412
|
+
// rebuilds its picture of a long task from a summary, and the rebuild is where
|
|
1413
|
+
// repeated work comes from (measured over 143 folds: 81 were followed by the model
|
|
1414
|
+
// re-reading files it had written itself before the fold).
|
|
1415
|
+
//
|
|
1416
|
+
// This mode moves the decision to where the model can still act on it:
|
|
1417
|
+
//
|
|
1418
|
+
// 1. PREP at `handoffAt` × the fold point (default 85%) a reminder is
|
|
1419
|
+
// injected into the running turn. The model writes a note to a path
|
|
1420
|
+
// this plugin chose, then calls `handoff_ready`.
|
|
1421
|
+
// 2. FOLD at that round's end (idle), `compactNow` runs — the same engine
|
|
1422
|
+
// `/compact` and the legacy idle fold reach.
|
|
1423
|
+
// 3. ACTIVATE exactly one follow-up turn whose first instruction is to read the
|
|
1424
|
+
// note back before touching the task. One, not a loop: a chain of
|
|
1425
|
+
// self-activated turns is how a plugin takes a session over.
|
|
1426
|
+
//
|
|
1427
|
+
// Everything here is fail-open. A missing service, an unreadable state file, a
|
|
1428
|
+
// full disk, an engine that throws — each is logged and leaves the turn alive. The
|
|
1429
|
+
// worst outcome must be "no fold", never "the session is stuck".
|
|
1430
|
+
// ---------------------------------------------------------------------------
|
|
1431
|
+
|
|
1432
|
+
/** Tool the model calls to register the note it just wrote. */
|
|
1433
|
+
const HANDOFF_TOOL_NAME = 'handoff_ready'
|
|
1434
|
+
/** State file kept beside the notes, one per session directory. */
|
|
1435
|
+
const HANDOFF_STATE_FILE = 'state.json'
|
|
1436
|
+
/** A note shorter than this cannot carry a task across a fold. */
|
|
1437
|
+
const HANDOFF_MIN_CHARS = 200
|
|
1438
|
+
/** Backstop: a note no later cycle referenced again is recycled after a week. */
|
|
1439
|
+
const HANDOFF_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
|
|
1440
|
+
/** How often the backstop sweep runs while the plugin is mounted. */
|
|
1441
|
+
const HANDOFF_SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000
|
|
1442
|
+
/** Activation deliveries attempted per fold before giving up (crash recovery). */
|
|
1443
|
+
const HANDOFF_MAX_ACTIVATION_ATTEMPTS = 2
|
|
1444
|
+
|
|
1445
|
+
/** Path segment that cannot escape its directory; session ids are already safe, but never trust that. */
|
|
1446
|
+
function safeSegment(value) {
|
|
1447
|
+
const text = String(value === null || value === undefined ? '' : value)
|
|
1448
|
+
.replace(/[^A-Za-z0-9._-]+/g, '_')
|
|
1449
|
+
.replace(/^\.+/, '')
|
|
1450
|
+
const trimmed = text.slice(0, 120)
|
|
1451
|
+
return trimmed === '' ? 'unknown-session' : trimmed
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
/** `$DSH_HOME`, or `~/.dsh` when the host exports nothing. `env` is a parameter so this is testable. */
|
|
1455
|
+
function dshHome(env) {
|
|
1456
|
+
const exported = env !== null && typeof env === 'object' ? env.DSH_HOME : undefined
|
|
1457
|
+
if (typeof exported === 'string' && exported.trim() !== '') return exported.trim()
|
|
1458
|
+
return join(homedir(), '.dsh')
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* Root that owns every session's notes. Empty `handoffDir` means
|
|
1463
|
+
* `$DSH_HOME/handoffs`; a relative value resolves under `$DSH_HOME`, so a profile
|
|
1464
|
+
* patch can say `handoffs-test` without hard-coding an absolute path.
|
|
1465
|
+
*/
|
|
1466
|
+
function handoffRoot(options, env) {
|
|
1467
|
+
const configured = typeof options.handoffDir === 'string' ? options.handoffDir.trim() : ''
|
|
1468
|
+
const home = dshHome(env === undefined ? process.env : env)
|
|
1469
|
+
if (configured === '') return join(home, 'handoffs')
|
|
1470
|
+
return isAbsolute(configured) ? configured : resolvePath(home, configured)
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/** `<root>/<sessionId>/<fold#>.handoff.md` — one directory per session, never the workspace. */
|
|
1474
|
+
function handoffPathFor(root, sessionId, foldNo) {
|
|
1475
|
+
const label = String(Math.max(1, Math.round(Number.isFinite(foldNo) ? foldNo : 1))).padStart(3, '0')
|
|
1476
|
+
return join(root, safeSegment(sessionId), `${label}.handoff.md`)
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
/** Session identity, header first: that is the id the store and the UI use. */
|
|
1480
|
+
function sessionIdOf(session) {
|
|
1481
|
+
if (session === null || session === undefined) return ''
|
|
1482
|
+
const header = session.header
|
|
1483
|
+
const candidates = [header === null || header === undefined ? undefined : header.id, session.id]
|
|
1484
|
+
for (const candidate of candidates) {
|
|
1485
|
+
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate.trim()
|
|
1486
|
+
}
|
|
1487
|
+
return ''
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/**
|
|
1491
|
+
* Whether this session is a delegate of another one.
|
|
1492
|
+
*
|
|
1493
|
+
* Measured on this host: the session header carries no `origin` field, so
|
|
1494
|
+
* `delegationDepth` is the authoritative signal — 0 for a root session, > 0 for
|
|
1495
|
+
* anything a delegation created. Folding a delegate would activate a turn nobody
|
|
1496
|
+
* is watching, so handoff mode stays out of those sessions entirely.
|
|
1497
|
+
*/
|
|
1498
|
+
function isDelegate(session) {
|
|
1499
|
+
const header = session === null || session === undefined ? undefined : session.header
|
|
1500
|
+
const depth = header === null || header === undefined ? undefined : header.delegationDepth
|
|
1501
|
+
return Number.isFinite(depth) && depth > 0
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
/** The prep point: `handoffAt` of the FOLD POINT, plus the numbers behind the decision. */
|
|
1505
|
+
function handoffTrigger(reading, options) {
|
|
1506
|
+
if (options.foldMode !== 'handoff') return { prepare: false }
|
|
1507
|
+
const used = reading === null || reading === undefined ? undefined : reading.used
|
|
1508
|
+
const threshold = reading === null || reading === undefined ? undefined : reading.threshold
|
|
1509
|
+
if (!Number.isFinite(used) || !Number.isFinite(threshold) || threshold <= 0) return { prepare: false }
|
|
1510
|
+
const ratio = Math.min(0.95, Math.max(0.5, num(options.handoffAt, DEFAULT_OPTIONS.handoffAt)))
|
|
1511
|
+
const point = Math.round(threshold * ratio)
|
|
1512
|
+
return { prepare: used >= point, point, used, threshold, headroom: Math.round(threshold - used) }
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
/** The reading as a percentage of the fold point, for message text. */
|
|
1516
|
+
function foldPointPercent(used, threshold) {
|
|
1517
|
+
if (!Number.isFinite(used) || !Number.isFinite(threshold) || threshold <= 0) return '?'
|
|
1518
|
+
return String(Math.round((used / threshold) * 100))
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/** Same file, however it was spelled. Windows compares case-insensitively. */
|
|
1522
|
+
function samePath(left, right) {
|
|
1523
|
+
if (typeof left !== 'string' || typeof right !== 'string') return false
|
|
1524
|
+
if (left === '' || right === '') return false
|
|
1525
|
+
try {
|
|
1526
|
+
const a = resolvePath(left)
|
|
1527
|
+
const b = resolvePath(right)
|
|
1528
|
+
return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b
|
|
1529
|
+
} catch {
|
|
1530
|
+
return false
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
/** The message shape the agent loop accepts from a plugin (`followup` / `inject`). */
|
|
1535
|
+
function handoffMessage(text) {
|
|
1536
|
+
return { id: randomUUID(), role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } }
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
/** Prep reminder: what to write, exactly where, and why it is worth the steps. */
|
|
1540
|
+
function handoffPrepMessage({ path, trigger, recycled, options }) {
|
|
1541
|
+
const percent = foldPointPercent(trigger.used, trigger.threshold)
|
|
1542
|
+
const used = formatTokens(trigger.used)
|
|
1543
|
+
const point = formatTokens(trigger.threshold)
|
|
1544
|
+
const recycledNote =
|
|
1545
|
+
recycled > 0
|
|
1546
|
+
? options.language === 'zh'
|
|
1547
|
+
? `(按回收策略删掉了上一份 ${recycled} 个档文件。)`
|
|
1548
|
+
: ` (recycled ${recycled} older note file(s) per the recycling rule.)`
|
|
1549
|
+
: ''
|
|
1550
|
+
if (options.language === 'zh') {
|
|
1551
|
+
return [
|
|
1552
|
+
`[交接式折叠 · 准备] 本会话已用到折叠点的 ${percent}%(${used} / ${point})。宿主的自动折叠会在折叠点直接发生,不看你的进度;折叠后你只能靠摘要重建认知,长任务里那正是重复劳动的来源。`,
|
|
1553
|
+
'',
|
|
1554
|
+
'现在写一份交接档给折叠后的你自己,然后继续手头的活(不要为写档中断任务):',
|
|
1555
|
+
`1) 路径必须是这个,不要改:${path}`,
|
|
1556
|
+
'2) 按这几节写,标准是「不看对话历史也能立刻接上」:',
|
|
1557
|
+
' - 当前目标(一句话)',
|
|
1558
|
+
' - 已定案(拍过板的决定,注明勿再复议)',
|
|
1559
|
+
' - 已验证的事实与证据(命令输出、file:line)',
|
|
1560
|
+
' - 待办(按序,标出下一步的第一个动作)',
|
|
1561
|
+
' - 关键路径',
|
|
1562
|
+
' - 坑(试过并失败的路线,避免重试)',
|
|
1563
|
+
'3) 写完调用工具 handoff_ready 登记(它只认上面这个路径)。',
|
|
1564
|
+
`4) 这是临时文件:下一次交接生成时它会被回收${recycledNote}。要长期保留的内容写进项目里,不要留在这里。`,
|
|
1565
|
+
'',
|
|
1566
|
+
'本轮结束时才会折叠,之后会自动开一轮(仅一轮)让你读档接着做。',
|
|
1567
|
+
].join('\n')
|
|
1568
|
+
}
|
|
1569
|
+
return [
|
|
1570
|
+
`[handoff fold · prepare] This session is at ${percent}% of its fold point (${used} / ${point}). The host's automatic fold happens at the fold point regardless of where you are in your work; after it you would rebuild your picture from a summary, which is where long tasks pay for repeated work.`,
|
|
1571
|
+
'',
|
|
1572
|
+
'Write a handoff note for the post-fold you, then continue your work (do not interrupt the task to do this):',
|
|
1573
|
+
`1) The path must be exactly this one, do not change it: ${path}`,
|
|
1574
|
+
'2) Use these sections; the bar is "a reader with no conversation history can continue":',
|
|
1575
|
+
' - current goal (one line)',
|
|
1576
|
+
' - decisions already made (note that they are settled)',
|
|
1577
|
+
' - verified facts and their evidence (command output, file:line)',
|
|
1578
|
+
' - next steps in order, with the very next action marked',
|
|
1579
|
+
' - key paths',
|
|
1580
|
+
' - dead ends already tried, so they are not retried',
|
|
1581
|
+
'3) Then call the handoff_ready tool to register it; it only accepts the path above.',
|
|
1582
|
+
`4) This is a temporary file: it is recycled when the next handoff is created${recycledNote}. Anything that must outlive it belongs in the project.`,
|
|
1583
|
+
'',
|
|
1584
|
+
'The fold runs at the end of this round, and exactly one follow-up turn is activated to read the note back.',
|
|
1585
|
+
].join('\n')
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
/** Activation message: read the note first, then finish the interrupted work. */
|
|
1589
|
+
function handoffActivationMessage({ path, foldNo, options }) {
|
|
1590
|
+
if (options.language === 'zh') {
|
|
1591
|
+
return [
|
|
1592
|
+
`[交接式折叠 · 激活] 你刚才那一轮被折叠了(本会话第 ${foldNo} 次)。折叠前你自己写了交接档:`,
|
|
1593
|
+
path,
|
|
1594
|
+
'',
|
|
1595
|
+
'这是唯一一次自动激活的轮次,不会连续自动开轮。按顺序做:',
|
|
1596
|
+
'1) 先 read 这个文件,再动手。它是你对折叠前状态的第一手记录,比摘要可靠。',
|
|
1597
|
+
'2) 按「待办」继续,把因折叠被打断的那件事做完。不要重新推导档里已经写明的结论——省掉那段时间正是这套机制的目的。',
|
|
1598
|
+
'3) 这一轮内文件还在:你记得、但档里没写的关键事实,补进去。',
|
|
1599
|
+
'4) 如果档里的描述和你现在看到的实际情况冲突,以实际情况为准,并在最后说明冲突在哪。',
|
|
1600
|
+
'5) 结束时简短交代:从档里接上了什么、这一轮推进了什么。',
|
|
1601
|
+
].join('\n')
|
|
1602
|
+
}
|
|
1603
|
+
return [
|
|
1604
|
+
`[handoff fold · activate] Your previous round was folded (fold #${foldNo} of this session). Before it happened you wrote yourself a handoff note:`,
|
|
1605
|
+
path,
|
|
1606
|
+
'',
|
|
1607
|
+
'This is the only auto-activated turn; nothing will auto-activate again until the next fold. In order:',
|
|
1608
|
+
'1) Read that file first, before doing anything else. It is your own first-hand record of the state, more reliable than the summary.',
|
|
1609
|
+
'2) Continue from its "next steps" and finish what the fold interrupted. Do not re-derive conclusions the note already states — not paying that cost is the point of this mechanism.',
|
|
1610
|
+
'3) The file still exists this round: add any key fact you remember that it is missing.',
|
|
1611
|
+
'4) Where the note disagrees with what you observe now, trust the observation and say where they diverged.',
|
|
1612
|
+
'5) End with a short account of what you picked up from the note and what this round advanced.',
|
|
1613
|
+
].join('\n')
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/** A fresh state record for one session. */
|
|
1617
|
+
function emptyHandoffState(sessionId) {
|
|
1618
|
+
return { version: 1, sessionId, foldNo: 0, reminders: 0, reminderTurn: null, ready: null, pending: null, wokenAt: null }
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/** A registered note, or `null` when the record is unusable. */
|
|
1622
|
+
function normalizeReady(value) {
|
|
1623
|
+
if (value === null || typeof value !== 'object') return null
|
|
1624
|
+
if (typeof value.path !== 'string' || value.path === '') return null
|
|
1625
|
+
return {
|
|
1626
|
+
path: value.path,
|
|
1627
|
+
chars: Number.isFinite(value.chars) ? value.chars : 0,
|
|
1628
|
+
at: Number.isFinite(value.at) ? value.at : 0,
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
|
|
1632
|
+
/** A queued activation, or `null`. */
|
|
1633
|
+
function normalizePending(value) {
|
|
1634
|
+
if (value === null || typeof value !== 'object') return null
|
|
1635
|
+
if (typeof value.path !== 'string' || value.path === '') return null
|
|
1636
|
+
return {
|
|
1637
|
+
id: typeof value.id === 'string' && value.id !== '' ? value.id : randomUUID(),
|
|
1638
|
+
path: value.path,
|
|
1639
|
+
foldNo: Number.isFinite(value.foldNo) ? Math.round(value.foldNo) : 0,
|
|
1640
|
+
createdAt: Number.isFinite(value.createdAt) ? value.createdAt : 0,
|
|
1641
|
+
attempts: Number.isFinite(value.attempts) && value.attempts >= 0 ? Math.round(value.attempts) : 0,
|
|
1642
|
+
deliveredAt: Number.isFinite(value.deliveredAt) ? value.deliveredAt : null,
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
/**
|
|
1647
|
+
* Load one session's state, or a fresh record.
|
|
1648
|
+
*
|
|
1649
|
+
* Synchronous on purpose: the prep decision runs inside the `agent/request`
|
|
1650
|
+
* waterfall, where an await would delay the model call, and this is a few hundred
|
|
1651
|
+
* bytes read at most once per turn. A corrupt or unreadable file degrades to "no
|
|
1652
|
+
* state" instead of throwing — the worst case is one duplicate reminder, not a
|
|
1653
|
+
* broken session.
|
|
1654
|
+
*/
|
|
1655
|
+
function readHandoffState(dir, sessionId) {
|
|
1656
|
+
try {
|
|
1657
|
+
const parsed = JSON.parse(readFileSync(join(dir, HANDOFF_STATE_FILE), 'utf8'))
|
|
1658
|
+
if (parsed === null || typeof parsed !== 'object') return emptyHandoffState(sessionId)
|
|
1659
|
+
const state = emptyHandoffState(sessionId)
|
|
1660
|
+
if (Number.isFinite(parsed.foldNo) && parsed.foldNo >= 0) state.foldNo = Math.round(parsed.foldNo)
|
|
1661
|
+
if (Number.isFinite(parsed.reminders) && parsed.reminders >= 0) state.reminders = Math.round(parsed.reminders)
|
|
1662
|
+
if (Number.isFinite(parsed.reminderTurn)) state.reminderTurn = Math.round(parsed.reminderTurn)
|
|
1663
|
+
if (Number.isFinite(parsed.wokenAt)) state.wokenAt = Math.round(parsed.wokenAt)
|
|
1664
|
+
state.ready = normalizeReady(parsed.ready)
|
|
1665
|
+
state.pending = normalizePending(parsed.pending)
|
|
1666
|
+
return state
|
|
1667
|
+
} catch {
|
|
1668
|
+
return emptyHandoffState(sessionId)
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
|
|
1672
|
+
/** Mirror one session's state to disk. Returns whether it landed. */
|
|
1673
|
+
function writeHandoffState(dir, state) {
|
|
1674
|
+
try {
|
|
1675
|
+
mkdirSync(dir, { recursive: true })
|
|
1676
|
+
writeFileSync(join(dir, HANDOFF_STATE_FILE), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
|
1677
|
+
return true
|
|
1678
|
+
} catch {
|
|
1679
|
+
return false
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
/** Character count of a note, or `null` when the file is missing or not a file. */
|
|
1684
|
+
function handoffFileChars(path) {
|
|
1685
|
+
try {
|
|
1686
|
+
if (!statSync(path).isFile()) return null
|
|
1687
|
+
return readFileSync(path, 'utf8').length
|
|
1688
|
+
} catch {
|
|
1689
|
+
return null
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
/**
|
|
1694
|
+
* Notes this prep should recycle: everything in the session directory except the
|
|
1695
|
+
* paths it must survive and the state file.
|
|
1696
|
+
*
|
|
1697
|
+
* Decision: recycling happens when the NEXT handoff is handed out, and the next
|
|
1698
|
+
* note's number is always `foldNo + 1`, so the ONLY note that must survive is the
|
|
1699
|
+
* one the last fold activated — `foldNo`'s own note. Keeping it is not a nicety:
|
|
1700
|
+
* the prep for note N+1 runs at the head of the activation turn for note N, so a
|
|
1701
|
+
* recycle that ignored this deleted the activation target 4.5s after it was
|
|
1702
|
+
* activated and the turn's first `read` failed with FS_NOT_FOUND (live drill,
|
|
1703
|
+
* 2026-11-16: activated 18:39:58.877, prep 18:40:03.431, read 18:40:04.983).
|
|
1704
|
+
* The older reasoning — "an undelivered activation is protected upstream" — ✗ was
|
|
1705
|
+
* wrong, because delivery happens before the round starts, not after it ends.
|
|
1706
|
+
*/
|
|
1707
|
+
function handoffReapable(root, sessionId, keepPaths) {
|
|
1708
|
+
const dir = join(root, safeSegment(sessionId))
|
|
1709
|
+
let names
|
|
1710
|
+
try {
|
|
1711
|
+
names = readdirSync(dir)
|
|
1712
|
+
} catch {
|
|
1713
|
+
return []
|
|
1714
|
+
}
|
|
1715
|
+
const keep = Array.isArray(keepPaths) ? keepPaths : [keepPaths]
|
|
1716
|
+
const doomed = []
|
|
1717
|
+
for (const entry of names) {
|
|
1718
|
+
if (!entry.toLowerCase().endsWith('.md')) continue
|
|
1719
|
+
const full = join(dir, entry)
|
|
1720
|
+
if (keep.some((keepPath) => samePath(full, keepPath))) continue
|
|
1721
|
+
doomed.push(full)
|
|
1722
|
+
}
|
|
1723
|
+
return doomed
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
/** Delete files, tolerating a locked one (it is swept next pass). */
|
|
1727
|
+
function deleteFiles(files) {
|
|
1728
|
+
let removed = 0
|
|
1729
|
+
for (const file of files) {
|
|
1730
|
+
try {
|
|
1731
|
+
unlinkSync(file)
|
|
1732
|
+
removed += 1
|
|
1733
|
+
} catch {
|
|
1734
|
+
// A locked or already-gone file is not an error worth failing a prep for.
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
return removed
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
/**
|
|
1741
|
+
* Backstop sweep: notes older than `maxAgeMs` go, then directories left holding
|
|
1742
|
+
* nothing but their state file. A directory with an undelivered activation is left
|
|
1743
|
+
* alone — its note is about to be read.
|
|
1744
|
+
*/
|
|
1745
|
+
function sweepHandoffs(root, nowMs, maxAgeMs) {
|
|
1746
|
+
let removed = 0
|
|
1747
|
+
let entries
|
|
1748
|
+
try {
|
|
1749
|
+
entries = readdirSync(root, { withFileTypes: true })
|
|
1750
|
+
} catch {
|
|
1751
|
+
return 0
|
|
1752
|
+
}
|
|
1753
|
+
for (const entry of entries) {
|
|
1754
|
+
if (entry === null || entry === undefined || !entry.isDirectory()) continue
|
|
1755
|
+
const dir = join(root, entry.name)
|
|
1756
|
+
const state = readHandoffState(dir, entry.name)
|
|
1757
|
+
const spare = state.pending !== null && state.pending.deliveredAt === null ? state.pending.path : null
|
|
1758
|
+
let names
|
|
1759
|
+
try {
|
|
1760
|
+
names = readdirSync(dir)
|
|
1761
|
+
} catch {
|
|
1762
|
+
continue
|
|
1763
|
+
}
|
|
1764
|
+
for (const name of names) {
|
|
1765
|
+
if (!name.toLowerCase().endsWith('.md')) continue
|
|
1766
|
+
const file = join(dir, name)
|
|
1767
|
+
if (spare !== null && samePath(file, spare)) continue
|
|
1768
|
+
let info
|
|
1769
|
+
try {
|
|
1770
|
+
info = statSync(file)
|
|
1771
|
+
} catch {
|
|
1772
|
+
continue
|
|
1773
|
+
}
|
|
1774
|
+
if (nowMs - info.mtimeMs <= maxAgeMs) continue
|
|
1775
|
+
try {
|
|
1776
|
+
unlinkSync(file)
|
|
1777
|
+
removed += 1
|
|
1778
|
+
} catch {
|
|
1779
|
+
// Swept next time.
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
try {
|
|
1783
|
+
const left = readdirSync(dir).filter((name) => name !== HANDOFF_STATE_FILE)
|
|
1784
|
+
// Pruning takes the state file with the directory, so it must be as
|
|
1785
|
+
// conservative as the note sweep: only when nothing but the state remains
|
|
1786
|
+
// AND the state itself has not been touched for the same week. Getting this
|
|
1787
|
+
// wrong is not cosmetic — the sweep runs at every plugin load, and the state
|
|
1788
|
+
// it would have deleted is exactly the pending activation that restart
|
|
1789
|
+
// recovery depends on (found by a unit test that lost its fixture).
|
|
1790
|
+
let stateStale = true
|
|
1791
|
+
try {
|
|
1792
|
+
stateStale = nowMs - statSync(join(dir, HANDOFF_STATE_FILE)).mtimeMs > maxAgeMs
|
|
1793
|
+
} catch {
|
|
1794
|
+
stateStale = true
|
|
1795
|
+
}
|
|
1796
|
+
if (left.length === 0 && stateStale) rmSync(dir, { recursive: true, force: true })
|
|
1797
|
+
} catch {
|
|
1798
|
+
// A directory that cannot be pruned now is pruned later.
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
return removed
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
/**
|
|
1805
|
+
* Install the handoff fold: prep reminder, `handoff_ready`, the round-end fold, the
|
|
1806
|
+
* single activation turn, and the recycling that keeps the directory bounded.
|
|
1807
|
+
*/
|
|
1808
|
+
function installHandoffFold(ctx, resolve, services) {
|
|
1809
|
+
/** Per-session state, hydrated from disk on first use and mirrored back on change. */
|
|
1810
|
+
const states = new Map()
|
|
1811
|
+
/** One-shot log keys: a condition that recurs every step is reported once. */
|
|
1812
|
+
const noted = new Set()
|
|
1813
|
+
/** A fold is an engine call; never run two at once from this closure. */
|
|
1814
|
+
let folding = false
|
|
1815
|
+
|
|
1816
|
+
const dirFor = (options, sessionId) => join(handoffRoot(options), safeSegment(sessionId))
|
|
1817
|
+
|
|
1818
|
+
const messageOf = (error) =>
|
|
1819
|
+
error === null || error === undefined ? 'unknown error' : (error.message ?? String(error))
|
|
1820
|
+
|
|
1821
|
+
function noteOnce(key, level, format, ...args) {
|
|
1822
|
+
if (noted.has(key)) return
|
|
1823
|
+
noted.add(key)
|
|
1824
|
+
logLine(ctx, level, format, ...args)
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
function stateFor(options, sessionId) {
|
|
1828
|
+
const cached = states.get(sessionId)
|
|
1829
|
+
if (cached !== undefined) return cached
|
|
1830
|
+
const loaded = readHandoffState(dirFor(options, sessionId), sessionId)
|
|
1831
|
+
states.set(sessionId, loaded)
|
|
1832
|
+
return loaded
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
function persist(options, sessionId, state) {
|
|
1836
|
+
if (writeHandoffState(dirFor(options, sessionId), state)) return
|
|
1837
|
+
noteOnce(
|
|
1838
|
+
`state-write:${sessionId}`,
|
|
1839
|
+
'warn',
|
|
1840
|
+
'context-truth: could not write the handoff state for %s; this fold still works, restart recovery will not',
|
|
1841
|
+
sessionId,
|
|
1842
|
+
)
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/**
|
|
1846
|
+
* Step 1: remind the model while it can still act. Runs inside the
|
|
1847
|
+
* `agent/request` waterfall, so it stays synchronous and swallows everything —
|
|
1848
|
+
* the return value is the model call's configuration.
|
|
1849
|
+
*/
|
|
1850
|
+
function prepare(agent, turn) {
|
|
1851
|
+
const options = resolve()
|
|
1852
|
+
if (options.foldMode !== 'handoff') return
|
|
1853
|
+
const session = agent === null || agent === undefined ? undefined : agent.session
|
|
1854
|
+
if (session === null || session === undefined) return
|
|
1855
|
+
if (isDelegate(session)) return
|
|
1856
|
+
const sessionId = sessionIdOf(session)
|
|
1857
|
+
if (sessionId === '') return
|
|
1858
|
+
const state = stateFor(options, sessionId)
|
|
1859
|
+
// A wake already carries this round's reminder as its first user message; a
|
|
1860
|
+
// second inject would stack two copies of it in the same round.
|
|
1861
|
+
if (state.wokenAt !== null) {
|
|
1862
|
+
state.wokenAt = null
|
|
1863
|
+
// 唤醒轮的第一条消息就是提醒,把它记成“本轮已提醒”,否则同一轮第二个
|
|
1864
|
+
// request 会再注入一条(实机 01:39:07 唤醒 2/3,01:39:17 又注入 3/3)。
|
|
1865
|
+
state.reminderTurn = turn === undefined ? null : turn
|
|
1866
|
+
persist(options, sessionId, state)
|
|
1867
|
+
return
|
|
1868
|
+
}
|
|
1869
|
+
// A queued activation owns the next round: never remind on top of it.
|
|
1870
|
+
if (state.pending !== null && state.pending.deliveredAt === null) return
|
|
1871
|
+
if (state.ready !== null) return
|
|
1872
|
+
if (state.reminders >= options.handoffReminders) {
|
|
1873
|
+
noteOnce(
|
|
1874
|
+
`budget:${sessionId}`,
|
|
1875
|
+
'info',
|
|
1876
|
+
'context-truth: handoff reminder budget spent for %s (%s in this cycle); the host pressure fold takes this one',
|
|
1877
|
+
sessionId,
|
|
1878
|
+
options.handoffReminders,
|
|
1879
|
+
)
|
|
1880
|
+
return
|
|
1881
|
+
}
|
|
1882
|
+
if (turn !== undefined && state.reminderTurn === turn) return
|
|
1883
|
+
const reading = readOccupancy(ctx, session, options, services.meter)
|
|
1884
|
+
const trigger = handoffTrigger(reading, options)
|
|
1885
|
+
if (!trigger.prepare) return
|
|
1886
|
+
|
|
1887
|
+
const root = handoffRoot(options)
|
|
1888
|
+
const path = handoffPathFor(root, sessionId, state.foldNo + 1)
|
|
1889
|
+
// 交接档 N 是当前折叠的激活目标,必须活到激活轮读完它;准备轮 N+1 就发生在激活轮
|
|
1890
|
+
// 里,所以这里按编号把它排除掉(✗ 旧实现只排除“未投递的激活”,而投递发生在轮次开始
|
|
1891
|
+
// 之前,等于没排除)。不额外按 pending.path 排除:一次折叠后 pending.foldNo 恒等于
|
|
1892
|
+
// state.foldNo,两者指向同一份文件 —— 两套守卫互为冗余时,变异测试抓不住任何一套
|
|
1893
|
+
// (实测:删掉编号守卫,67/67 仍全绿,因为 pending 守卫替它挡了)。
|
|
1894
|
+
const keep = [path, handoffPathFor(root, sessionId, state.foldNo)]
|
|
1895
|
+
const doomed = handoffReapable(root, sessionId, keep)
|
|
1896
|
+
try {
|
|
1897
|
+
// Reap after the reminder lands, so a failed inject does not cost the model
|
|
1898
|
+
// its previous note for nothing.
|
|
1899
|
+
agent.inject(handoffMessage(handoffPrepMessage({ path, trigger, recycled: doomed.length, options })))
|
|
1900
|
+
} catch (error) {
|
|
1901
|
+
logLine(ctx, 'warn', 'context-truth: could not inject the handoff reminder for %s: %s', sessionId, messageOf(error))
|
|
1902
|
+
return
|
|
1903
|
+
}
|
|
1904
|
+
const recycled = deleteFiles(doomed)
|
|
1905
|
+
state.reminders += 1
|
|
1906
|
+
state.reminderTurn = turn === undefined ? null : turn
|
|
1907
|
+
persist(options, sessionId, state)
|
|
1908
|
+
logLine(
|
|
1909
|
+
ctx,
|
|
1910
|
+
'info',
|
|
1911
|
+
'context-truth: handoff prep %s/%s for %s (used=%s of the %s fold point, recycled=%s) -> %s',
|
|
1912
|
+
state.reminders,
|
|
1913
|
+
options.handoffReminders,
|
|
1914
|
+
sessionId,
|
|
1915
|
+
trigger.used,
|
|
1916
|
+
trigger.threshold,
|
|
1917
|
+
recycled,
|
|
1918
|
+
path,
|
|
1919
|
+
)
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
/**
|
|
1923
|
+
* Step 1b: wake a round with the reminder.
|
|
1924
|
+
*
|
|
1925
|
+
* `agent.inject` only queues for the next REQUEST of a running round. When the
|
|
1926
|
+
* reminder trips on the model's last step of a round, the message waits for
|
|
1927
|
+
* something to start a new round — observed live: injected 18:48:04.482, read
|
|
1928
|
+
* only after the human's next message. A round end is the one moment a wake is
|
|
1929
|
+
* both safe (nothing is running) and bounded (the same reminder budget).
|
|
1930
|
+
*/
|
|
1931
|
+
function remind(agent, options, sessionId, state) {
|
|
1932
|
+
if (state.wokenAt !== null) return
|
|
1933
|
+
const trigger = handoffTrigger(readOccupancy(ctx, agent.session, options, services.meter), options)
|
|
1934
|
+
if (!trigger.prepare) {
|
|
1935
|
+
noteOnce(
|
|
1936
|
+
`no-note:${sessionId}`,
|
|
1937
|
+
'info',
|
|
1938
|
+
'context-truth: %s ended a round without handoff_ready and below the prep point; leaving this fold to the host pressure trigger',
|
|
1939
|
+
sessionId,
|
|
1940
|
+
)
|
|
1941
|
+
return
|
|
1942
|
+
}
|
|
1943
|
+
if (state.reminders >= options.handoffReminders) {
|
|
1944
|
+
noteOnce(
|
|
1945
|
+
`budget:${sessionId}`,
|
|
1946
|
+
'info',
|
|
1947
|
+
'context-truth: handoff reminder budget spent for %s (%s in this cycle); leaving this fold to the host pressure trigger',
|
|
1948
|
+
sessionId,
|
|
1949
|
+
options.handoffReminders,
|
|
1950
|
+
)
|
|
1951
|
+
return
|
|
1952
|
+
}
|
|
1953
|
+
const root = handoffRoot(options)
|
|
1954
|
+
const path = handoffPathFor(root, sessionId, state.foldNo + 1)
|
|
1955
|
+
const doomed = handoffReapable(root, sessionId, [path, handoffPathFor(root, sessionId, state.foldNo)])
|
|
1956
|
+
try {
|
|
1957
|
+
agent.followup(handoffMessage(handoffPrepMessage({ path, trigger, recycled: doomed.length, options })))
|
|
1958
|
+
} catch (error) {
|
|
1959
|
+
logLine(ctx, 'warn', 'context-truth: could not wake %s with the handoff reminder: %s', sessionId, messageOf(error))
|
|
1960
|
+
return
|
|
1961
|
+
}
|
|
1962
|
+
const recycled = deleteFiles(doomed)
|
|
1963
|
+
state.reminders += 1
|
|
1964
|
+
state.wokenAt = Date.now()
|
|
1965
|
+
state.reminderTurn = null
|
|
1966
|
+
persist(options, sessionId, state)
|
|
1967
|
+
logLine(
|
|
1968
|
+
ctx,
|
|
1969
|
+
'info',
|
|
1970
|
+
'context-truth: handoff reminder %s/%s for %s woke the round (used=%s of the %s fold point, recycled=%s) -> %s',
|
|
1971
|
+
state.reminders,
|
|
1972
|
+
options.handoffReminders,
|
|
1973
|
+
sessionId,
|
|
1974
|
+
trigger.used,
|
|
1975
|
+
trigger.threshold,
|
|
1976
|
+
recycled,
|
|
1977
|
+
path,
|
|
1978
|
+
)
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
/** Step 3: deliver the one activation turn, at most twice across restarts. */
|
|
1982
|
+
function deliver(agent, options, sessionId, state) {
|
|
1983
|
+
const pending = state.pending
|
|
1984
|
+
if (pending === null || pending.deliveredAt !== null) return
|
|
1985
|
+
if (pending.attempts >= HANDOFF_MAX_ACTIVATION_ATTEMPTS) {
|
|
1986
|
+
logLine(
|
|
1987
|
+
ctx,
|
|
1988
|
+
'warn',
|
|
1989
|
+
'context-truth: activation for fold #%s of %s failed %s times; leaving the session to the human (note: %s)',
|
|
1990
|
+
pending.foldNo,
|
|
1991
|
+
sessionId,
|
|
1992
|
+
pending.attempts,
|
|
1993
|
+
pending.path,
|
|
1994
|
+
)
|
|
1995
|
+
return
|
|
1996
|
+
}
|
|
1997
|
+
// The activation message names a file; a turn whose first step is a read of a
|
|
1998
|
+
// missing file is worse than no activation at all. The recycle rule below no
|
|
1999
|
+
// longer deletes this note, so this is the backstop for the other ways it can
|
|
2000
|
+
// vanish (a human, a sweep, another instance).
|
|
2001
|
+
try {
|
|
2002
|
+
if (!statSync(pending.path).isFile()) throw new Error('not a regular file')
|
|
2003
|
+
} catch (error) {
|
|
2004
|
+
logLine(
|
|
2005
|
+
ctx,
|
|
2006
|
+
'warn',
|
|
2007
|
+
'context-truth: the note for fold #%s of %s is gone (%s); releasing the activation instead of pointing a turn at a missing file',
|
|
2008
|
+
pending.foldNo,
|
|
2009
|
+
sessionId,
|
|
2010
|
+
messageOf(error),
|
|
2011
|
+
)
|
|
2012
|
+
state.pending = null
|
|
2013
|
+
persist(options, sessionId, state)
|
|
2014
|
+
return
|
|
2015
|
+
}
|
|
2016
|
+
// Persist the attempt BEFORE sending. A crash between the two can duplicate one
|
|
2017
|
+
// message at worst (bounded by the cap above); it can never loop.
|
|
2018
|
+
pending.attempts += 1
|
|
2019
|
+
persist(options, sessionId, state)
|
|
2020
|
+
try {
|
|
2021
|
+
agent.followup(
|
|
2022
|
+
handoffMessage(handoffActivationMessage({ path: pending.path, foldNo: pending.foldNo, options })),
|
|
2023
|
+
)
|
|
2024
|
+
} catch (error) {
|
|
2025
|
+
logLine(ctx, 'warn', 'context-truth: could not activate the post-fold turn for %s: %s', sessionId, messageOf(error))
|
|
2026
|
+
return
|
|
2027
|
+
}
|
|
2028
|
+
pending.deliveredAt = Date.now()
|
|
2029
|
+
persist(options, sessionId, state)
|
|
2030
|
+
logLine(ctx, 'info', 'context-truth: activated fold #%s of %s -> %s', pending.foldNo, sessionId, pending.path)
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
/** Step 2: at the round's end, fold if the model registered a note. */
|
|
2034
|
+
function foldAtRoundEnd(agent) {
|
|
2035
|
+
const options = resolve()
|
|
2036
|
+
if (options.foldMode !== 'handoff') return
|
|
2037
|
+
const session = agent === null || agent === undefined ? undefined : agent.session
|
|
2038
|
+
if (session === null || session === undefined) return
|
|
2039
|
+
if (isDelegate(session)) return
|
|
2040
|
+
const sessionId = sessionIdOf(session)
|
|
2041
|
+
if (sessionId === '') return
|
|
2042
|
+
const state = stateFor(options, sessionId)
|
|
2043
|
+
|
|
2044
|
+
// An activation that never left the building comes first: the fold already
|
|
2045
|
+
// happened, and the missing piece is the round that was supposed to read it.
|
|
2046
|
+
if (state.pending !== null && state.pending.deliveredAt === null) {
|
|
2047
|
+
deliver(agent, options, sessionId, state)
|
|
2048
|
+
return
|
|
2049
|
+
}
|
|
2050
|
+
if (state.ready === null) {
|
|
2051
|
+
remind(agent, options, sessionId, state)
|
|
2052
|
+
return
|
|
2053
|
+
}
|
|
2054
|
+
if (folding) return
|
|
2055
|
+
const reading = readOccupancy(ctx, session, options, services.meter)
|
|
2056
|
+
const trigger = handoffTrigger(reading, options)
|
|
2057
|
+
if (!trigger.prepare) {
|
|
2058
|
+
// A reading far below the prep point means somebody else folded first (the
|
|
2059
|
+
// host at pressure, or a human running /compact). The note was not used.
|
|
2060
|
+
const foldedElsewhere = Number.isFinite(trigger.point) && trigger.used < trigger.point * 0.75
|
|
2061
|
+
if (foldedElsewhere) {
|
|
2062
|
+
logLine(
|
|
2063
|
+
ctx,
|
|
2064
|
+
'info',
|
|
2065
|
+
'context-truth: %s was folded by something else (used=%s, prep point=%s); the note at %s went unused and is released',
|
|
2066
|
+
sessionId,
|
|
2067
|
+
trigger.used,
|
|
2068
|
+
trigger.point,
|
|
2069
|
+
state.ready.path,
|
|
2070
|
+
)
|
|
2071
|
+
state.ready = null
|
|
2072
|
+
state.reminders = 0
|
|
2073
|
+
state.reminderTurn = null
|
|
2074
|
+
state.wokenAt = null
|
|
2075
|
+
persist(options, sessionId, state)
|
|
2076
|
+
return
|
|
2077
|
+
}
|
|
2078
|
+
noteOnce(
|
|
2079
|
+
`below-point:${sessionId}`,
|
|
2080
|
+
'info',
|
|
2081
|
+
'context-truth: %s registered a handoff but the reading (%s) is below the prep point (%s); keeping it for the next round end',
|
|
2082
|
+
sessionId,
|
|
2083
|
+
trigger.used,
|
|
2084
|
+
trigger.point,
|
|
2085
|
+
)
|
|
2086
|
+
return
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
const note = state.ready
|
|
2090
|
+
folding = true
|
|
2091
|
+
Promise.resolve()
|
|
2092
|
+
.then(() => requestFold(ctx, agent, options, services, new AbortController().signal))
|
|
2093
|
+
.then(
|
|
2094
|
+
(outcome) => {
|
|
2095
|
+
if (outcome === undefined) {
|
|
2096
|
+
noteOnce(
|
|
2097
|
+
`no-service:${sessionId}`,
|
|
2098
|
+
'warn',
|
|
2099
|
+
'context-truth: handoff mode found neither the realm /compact command nor a reachable compaction service (upstream discussion 9425); the note at %s is kept',
|
|
2100
|
+
note.path,
|
|
2101
|
+
)
|
|
2102
|
+
return
|
|
2103
|
+
}
|
|
2104
|
+
if (!outcome.folded) {
|
|
2105
|
+
logLine(
|
|
2106
|
+
ctx,
|
|
2107
|
+
'info',
|
|
2108
|
+
'context-truth: the fold reported no compactable range for %s; the note at %s is kept for the next round end',
|
|
2109
|
+
sessionId,
|
|
2110
|
+
note.path,
|
|
2111
|
+
)
|
|
2112
|
+
return
|
|
2113
|
+
}
|
|
2114
|
+
const foldNo = state.foldNo + 1
|
|
2115
|
+
state.foldNo = foldNo
|
|
2116
|
+
state.ready = null
|
|
2117
|
+
state.reminders = 0
|
|
2118
|
+
state.reminderTurn = null
|
|
2119
|
+
state.wokenAt = null
|
|
2120
|
+
// The activation is durable before it is sent, which is the one thing the
|
|
2121
|
+
// reference implementation this was modelled on does not do.
|
|
2122
|
+
state.pending = {
|
|
2123
|
+
id: randomUUID(),
|
|
2124
|
+
path: note.path,
|
|
2125
|
+
foldNo,
|
|
2126
|
+
createdAt: Date.now(),
|
|
2127
|
+
attempts: 0,
|
|
2128
|
+
deliveredAt: null,
|
|
2129
|
+
}
|
|
2130
|
+
persist(options, sessionId, state)
|
|
2131
|
+
logLine(
|
|
2132
|
+
ctx,
|
|
2133
|
+
'info',
|
|
2134
|
+
'context-truth: folded %s at the round end via %s (fold #%s, note %s)',
|
|
2135
|
+
sessionId,
|
|
2136
|
+
outcome.how,
|
|
2137
|
+
foldNo,
|
|
2138
|
+
note.path,
|
|
2139
|
+
)
|
|
2140
|
+
deliver(agent, options, sessionId, state)
|
|
2141
|
+
},
|
|
2142
|
+
(error) => logLine(ctx, 'warn', 'context-truth: handoff fold failed: %s', messageOf(error)),
|
|
2143
|
+
)
|
|
2144
|
+
.finally(() => {
|
|
2145
|
+
folding = false
|
|
2146
|
+
})
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
/**
|
|
2150
|
+
* The tool the model calls once the note exists.
|
|
2151
|
+
*
|
|
2152
|
+
* Registered as a plain definition rather than through `defineTool`, because
|
|
2153
|
+
* `@deepseek-ai/dsh-tools` is not resolvable from this package's own directory
|
|
2154
|
+
* (verified here: ERR_MODULE_NOT_FOUND) and a plugin that cannot load is worse
|
|
2155
|
+
* than a plugin that builds a four-field object itself. The registry only
|
|
2156
|
+
* requires `output: { schema, render }`, so this is the whole contract.
|
|
2157
|
+
*/
|
|
2158
|
+
function toolDefinition() {
|
|
2159
|
+
return {
|
|
2160
|
+
name: HANDOFF_TOOL_NAME,
|
|
2161
|
+
description:
|
|
2162
|
+
'Register the handoff note you just wrote to the path context-truth named, so this round is folded and exactly one follow-up turn is activated to read it back. Only meaningful in handoff fold mode, and only for that exact path.',
|
|
2163
|
+
parameters: {
|
|
2164
|
+
type: 'object',
|
|
2165
|
+
properties: {
|
|
2166
|
+
path: {
|
|
2167
|
+
type: 'string',
|
|
2168
|
+
description: 'The handoff path context-truth named. Omit to use the path it chose for this session.',
|
|
2169
|
+
},
|
|
2170
|
+
},
|
|
2171
|
+
},
|
|
2172
|
+
output: {
|
|
2173
|
+
schema: { type: 'string' },
|
|
2174
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
2175
|
+
},
|
|
2176
|
+
execute: (args, exec) => {
|
|
2177
|
+
const options = resolve()
|
|
2178
|
+
const zh = options.language === 'zh'
|
|
2179
|
+
const agent = exec === null || exec === undefined ? undefined : exec.agent
|
|
2180
|
+
const session = agent === null || agent === undefined ? undefined : agent.session
|
|
2181
|
+
if (options.foldMode !== 'handoff') {
|
|
2182
|
+
return zh
|
|
2183
|
+
? `✗ handoff_ready 只在 handoff 折叠模式下有效(当前:${options.foldMode}),没有登记任何东西。`
|
|
2184
|
+
: `✗ handoff_ready only applies in handoff fold mode (current mode: ${options.foldMode}); nothing was registered.`
|
|
2185
|
+
}
|
|
2186
|
+
if (session === null || session === undefined) {
|
|
2187
|
+
return zh ? '✗ handoff_ready 需要一个活着的会话,没有登记任何东西。' : '✗ handoff_ready needs a live session; nothing was registered.'
|
|
2188
|
+
}
|
|
2189
|
+
if (isDelegate(session)) {
|
|
2190
|
+
return zh
|
|
2191
|
+
? '✗ 当前是委派会话,交接式折叠只在根会话上生效;没有登记任何东西。'
|
|
2192
|
+
: '✗ this is a delegated session, and handoff folding only applies to a root session; nothing was registered.'
|
|
2193
|
+
}
|
|
2194
|
+
const sessionId = sessionIdOf(session)
|
|
2195
|
+
if (sessionId === '') {
|
|
2196
|
+
return zh ? '✗ 无法识别当前会话,没有登记任何东西。' : '✗ could not identify this session; nothing was registered.'
|
|
2197
|
+
}
|
|
2198
|
+
const state = stateFor(options, sessionId)
|
|
2199
|
+
if (state.pending !== null && state.pending.deliveredAt === null) {
|
|
2200
|
+
return zh
|
|
2201
|
+
? '✗ 本会话已经排了一次折叠,激活轮还没投递;这次不重复登记。'
|
|
2202
|
+
: '✗ a fold for this session is already queued and not yet activated; nothing was registered.'
|
|
2203
|
+
}
|
|
2204
|
+
const root = handoffRoot(options)
|
|
2205
|
+
const expected = handoffPathFor(root, sessionId, state.foldNo + 1)
|
|
2206
|
+
const given = args !== null && typeof args === 'object' && typeof args.path === 'string' ? args.path.trim() : ''
|
|
2207
|
+
if (given !== '' && !samePath(given, expected)) {
|
|
2208
|
+
return zh
|
|
2209
|
+
? `✗ 这个路径不属于本会话的交接目录。\n 期望:${expected}\n 收到:${given}\n交接档只能放在插件管理的目录里,不能写进工作区。写到期望路径后再调用。`
|
|
2210
|
+
: `✗ that path is not the one this session owns.\n expected: ${expected}\n given: ${given}\nHandoff notes stay in the plugin's own directory, never in the workspace. Write to the expected path and call again.`
|
|
2211
|
+
}
|
|
2212
|
+
const chars = handoffFileChars(expected)
|
|
2213
|
+
if (chars === null) {
|
|
2214
|
+
return zh
|
|
2215
|
+
? `✗ 这个路径还没有文件:${expected}\n先把档写到这里(必须是这个路径),再调用 handoff_ready。`
|
|
2216
|
+
: `✗ there is no handoff note at ${expected}\nWrite it there first (that exact path), then call handoff_ready.`
|
|
2217
|
+
}
|
|
2218
|
+
if (chars < HANDOFF_MIN_CHARS) {
|
|
2219
|
+
return zh
|
|
2220
|
+
? `✗ 交接档只有 ${chars} 字符(最少 ${HANDOFF_MIN_CHARS})。它要能让折叠后的会话不看对话历史就接上:补上目标、已定案、证据、下一步,再调用。`
|
|
2221
|
+
: `✗ the note is only ${chars} characters (minimum ${HANDOFF_MIN_CHARS}). It has to let the folded session continue without this conversation: add the goal, the decisions, the evidence, the next action, then call again.`
|
|
2222
|
+
}
|
|
2223
|
+
state.ready = { path: expected, chars, at: Date.now() }
|
|
2224
|
+
persist(options, sessionId, state)
|
|
2225
|
+
logLine(ctx, 'info', 'context-truth: handoff registered for %s (%s chars) at %s', sessionId, chars, expected)
|
|
2226
|
+
return zh
|
|
2227
|
+
? `✓ 交接档已登记(${chars} 字符):${expected}\n本轮结束时会执行折叠,然后自动开一轮(仅一轮)让你读档。现在结束本轮:收尾正在写的文件,不要再开新任务。`
|
|
2228
|
+
: `✓ handoff registered (${chars} chars): ${expected}\nThis round is folded when it ends, and exactly one turn is activated to read it back. End this round now: finish the file you are writing, do not start a new task.`
|
|
2229
|
+
},
|
|
2230
|
+
}
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
// The tool exists in every mode: the settings form toggles `foldMode` live, and a
|
|
2234
|
+
// tool that only appears after a reload would leave handoff mode unrunnable on the
|
|
2235
|
+
// very session that just turned it on. Its description is one line for that reason.
|
|
2236
|
+
const tools = safeGet(ctx, 'tools')
|
|
2237
|
+
if (tools === undefined || typeof tools.register !== 'function' || typeof ctx.effect !== 'function') {
|
|
2238
|
+
logLine(
|
|
2239
|
+
ctx,
|
|
2240
|
+
'warn',
|
|
2241
|
+
'context-truth: no tools service is reachable from this scope; handoff mode cannot register %s and will stay inert',
|
|
2242
|
+
HANDOFF_TOOL_NAME,
|
|
2243
|
+
)
|
|
2244
|
+
} else {
|
|
2245
|
+
try {
|
|
2246
|
+
ctx.effect(() => tools.register(toolDefinition()), `context-truth: ${HANDOFF_TOOL_NAME}`)
|
|
2247
|
+
} catch (error) {
|
|
2248
|
+
logLine(ctx, 'warn', 'context-truth: could not register %s: %s', HANDOFF_TOOL_NAME, messageOf(error))
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
// Prep runs inside a waterfall: synchronous, and it must never throw — its return
|
|
2253
|
+
// value is the model call's configuration.
|
|
2254
|
+
ctx.on('agent/request', (payload, next) => {
|
|
2255
|
+
try {
|
|
2256
|
+
prepare(payload === null || payload === undefined ? undefined : payload.agent, payload === null || payload === undefined ? undefined : payload.turn)
|
|
2257
|
+
} catch (error) {
|
|
2258
|
+
noteOnce('prep-error', 'warn', 'context-truth: handoff prep failed: %s', messageOf(error))
|
|
2259
|
+
}
|
|
2260
|
+
return next()
|
|
2261
|
+
})
|
|
2262
|
+
|
|
2263
|
+
// The fold itself is async and runs after the emitting stack unwinds, so the
|
|
2264
|
+
// `followup` that activates the next round never re-enters the agent loop.
|
|
2265
|
+
ctx.on('agent/status', ({ agent, status } = {}) => {
|
|
2266
|
+
if (status !== 'idle' || agent === null || agent === undefined) return
|
|
2267
|
+
Promise.resolve()
|
|
2268
|
+
.then(() => foldAtRoundEnd(agent))
|
|
2269
|
+
.catch((error) => logLine(ctx, 'warn', 'context-truth: handoff fold failed: %s', messageOf(error)))
|
|
2270
|
+
})
|
|
2271
|
+
|
|
2272
|
+
function sweep() {
|
|
2273
|
+
const options = resolve()
|
|
2274
|
+
if (options.foldMode !== 'handoff') return
|
|
2275
|
+
try {
|
|
2276
|
+
const removed = sweepHandoffs(handoffRoot(options), Date.now(), HANDOFF_MAX_AGE_MS)
|
|
2277
|
+
if (removed > 0) {
|
|
2278
|
+
logLine(ctx, 'info', 'context-truth: recycled %s stale handoff note(s) older than %s days', removed, Math.round(HANDOFF_MAX_AGE_MS / 86400000))
|
|
2279
|
+
}
|
|
2280
|
+
} catch (error) {
|
|
2281
|
+
logLine(ctx, 'warn', 'context-truth: handoff sweep failed: %s', messageOf(error))
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// Backstop only: the primary recycling happens when the next note is handed out.
|
|
2286
|
+
try {
|
|
2287
|
+
Promise.resolve().then(sweep).catch(() => {})
|
|
2288
|
+
if (typeof ctx.setInterval === 'function') ctx.setInterval(sweep, HANDOFF_SWEEP_INTERVAL_MS)
|
|
2289
|
+
} catch {
|
|
2290
|
+
// A timer is a convenience, never a requirement.
|
|
2291
|
+
}
|
|
2292
|
+
}
|
|
2293
|
+
|
|
578
2294
|
/** Install the dynamic runtime-context line. */
|
|
579
|
-
function installContextLine(ctx,
|
|
2295
|
+
function installContextLine(ctx, resolve, services) {
|
|
580
2296
|
/** Last band published per session (hysteresis memory); never rendered. */
|
|
581
2297
|
const bands = new WeakMap()
|
|
2298
|
+
/** Per-session pace state for the headroom estimate; never rendered raw. */
|
|
2299
|
+
const paces = new WeakMap()
|
|
582
2300
|
/** Last text handed out, so a failed read degrades to the previous line. */
|
|
583
|
-
let lastText = renderUnknown(
|
|
2301
|
+
let lastText = renderUnknown(resolve())
|
|
584
2302
|
|
|
585
2303
|
const line = (assembly) => {
|
|
2304
|
+
// Resolved per assembly, so a settings change shows up on the next prompt.
|
|
2305
|
+
const options = resolve()
|
|
586
2306
|
try {
|
|
587
2307
|
const session = assembly?.agent?.session
|
|
588
2308
|
if (session === undefined || session === null) return lastText
|
|
589
2309
|
|
|
590
|
-
const reading = readOccupancy(ctx, session, options)
|
|
2310
|
+
const reading = readOccupancy(ctx, session, options, services.meter)
|
|
591
2311
|
const window_ = reading.window
|
|
592
2312
|
const ratio =
|
|
593
2313
|
Number.isFinite(reading.used) && Number.isFinite(window_) && window_ > 0
|
|
@@ -629,6 +2349,22 @@ function installContextLine(ctx, options) {
|
|
|
629
2349
|
band === 'unknown' || headroomRaw === undefined
|
|
630
2350
|
? undefined
|
|
631
2351
|
: quantizeHeadroom(headroomRaw, window_, options)
|
|
2352
|
+
// Sampled on every assembly so the state stays current even in bands that
|
|
2353
|
+
// do not render it; the rung settles before it is rendered.
|
|
2354
|
+
const perStep = samplePace(paces, session, assembly, reading.used, options)
|
|
2355
|
+
const settled = settlePace(paceSteps(headroomRaw, perStep), paces.get(session)?.pace, options)
|
|
2356
|
+
const sampled = paces.get(session)
|
|
2357
|
+
if (sampled !== undefined && settled.state !== undefined) {
|
|
2358
|
+
paces.set(session, { ...sampled, pace: settled.state })
|
|
2359
|
+
}
|
|
2360
|
+
const steps = settled.steps
|
|
2361
|
+
// Window still unused, on the same display step as `used` (floored, so it
|
|
2362
|
+
// never promises more room than the window has).
|
|
2363
|
+
const freeRaw =
|
|
2364
|
+
Number.isFinite(window_) && Number.isFinite(reading.used)
|
|
2365
|
+
? Math.max(0, window_ - reading.used)
|
|
2366
|
+
: undefined
|
|
2367
|
+
const free = band === 'unknown' || freeRaw === undefined ? undefined : quantize(freeRaw, window_, options)
|
|
632
2368
|
lastText = render(
|
|
633
2369
|
band,
|
|
634
2370
|
{
|
|
@@ -638,6 +2374,9 @@ function installContextLine(ctx, options) {
|
|
|
638
2374
|
headroomStep:
|
|
639
2375
|
headroomRaw === undefined ? undefined : headroomDisplayStep(headroomRaw, window_, options),
|
|
640
2376
|
headroomRaw,
|
|
2377
|
+
free,
|
|
2378
|
+
freeRaw,
|
|
2379
|
+
steps,
|
|
641
2380
|
used: reading.used,
|
|
642
2381
|
window: window_,
|
|
643
2382
|
threshold: reading.threshold,
|
|
@@ -652,12 +2391,34 @@ function installContextLine(ctx, options) {
|
|
|
652
2391
|
}
|
|
653
2392
|
}
|
|
654
2393
|
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
2394
|
+
// Bind both registrations to THIS plugin's fiber.
|
|
2395
|
+
//
|
|
2396
|
+
// The service returns a disposer, but it is created through `layers.effect` on
|
|
2397
|
+
// the *service's* context, so ignoring it leaves the variable registered for the
|
|
2398
|
+
// lifetime of the service — i.e. forever. The consequence is not cosmetic: after
|
|
2399
|
+
// one reload the name is taken, every later instance throws "already registered",
|
|
2400
|
+
// and this plugin's `apply` deliberately goes inert on that error, so the plugin
|
|
2401
|
+
// can never be reloaded into a new version again (observed live 2026-11-16: every
|
|
2402
|
+
// reload logged "another instance already owns the context line" while no other
|
|
2403
|
+
// instance existed). `ctx.effect` puts the disposer on our own fiber, which is
|
|
2404
|
+
// what a reload actually disposes.
|
|
2405
|
+
const bind = typeof ctx.effect === 'function' ? (fn, label) => ctx.effect(fn, label) : (fn) => fn()
|
|
2406
|
+
bind(
|
|
2407
|
+
() => ctx.systemPrompt.variable(VARIABLE_NAME, (assembly) => line(assembly)),
|
|
2408
|
+
'context-truth: runtime-context variable',
|
|
2409
|
+
)
|
|
2410
|
+
bind(
|
|
2411
|
+
() =>
|
|
2412
|
+
ctx.systemPrompt.context({
|
|
2413
|
+
name: CONTEXT_NAME,
|
|
2414
|
+
// `order` is fixed at registration: the host snapshots the contribution list
|
|
2415
|
+
// per assembly, and moving it live would reshuffle the cached prefix for a
|
|
2416
|
+
// change nobody asked to see mid-turn.
|
|
2417
|
+
order: resolve().order,
|
|
2418
|
+
text: `{{${VARIABLE_NAME}}}`,
|
|
2419
|
+
}),
|
|
2420
|
+
'context-truth: runtime-context section',
|
|
2421
|
+
)
|
|
661
2422
|
}
|
|
662
2423
|
|
|
663
2424
|
/** Test-only surface: the pure helpers, so the suite can exercise them directly. */
|
|
@@ -674,6 +2435,38 @@ export const internals = {
|
|
|
674
2435
|
quantizeHeadroom,
|
|
675
2436
|
headroomDisplayStep,
|
|
676
2437
|
displayStep,
|
|
2438
|
+
PACE_LADDER,
|
|
2439
|
+
median,
|
|
2440
|
+
nextPaceState,
|
|
2441
|
+
samplePace,
|
|
2442
|
+
paceSteps,
|
|
2443
|
+
paceRung,
|
|
2444
|
+
settlePace,
|
|
2445
|
+
paceSentence,
|
|
2446
|
+
tightClause,
|
|
2447
|
+
foldClause,
|
|
2448
|
+
shouldFoldAtIdle,
|
|
2449
|
+
resolveFoldMode,
|
|
2450
|
+
handoffTrigger,
|
|
2451
|
+
handoffRoot,
|
|
2452
|
+
handoffPathFor,
|
|
2453
|
+
handoffPrepMessage,
|
|
2454
|
+
handoffActivationMessage,
|
|
2455
|
+
handoffReapable,
|
|
2456
|
+
sweepHandoffs,
|
|
2457
|
+
readHandoffState,
|
|
2458
|
+
writeHandoffState,
|
|
2459
|
+
handoffFileChars,
|
|
2460
|
+
emptyHandoffState,
|
|
2461
|
+
safeSegment,
|
|
2462
|
+
sessionIdOf,
|
|
2463
|
+
isDelegate,
|
|
2464
|
+
samePath,
|
|
2465
|
+
HANDOFF_TOOL_NAME,
|
|
2466
|
+
HANDOFF_MIN_CHARS,
|
|
2467
|
+
HANDOFF_MAX_AGE_MS,
|
|
2468
|
+
HANDOFF_STATE_FILE,
|
|
2469
|
+
backendIdentity,
|
|
677
2470
|
render,
|
|
678
2471
|
renderUnknown,
|
|
679
2472
|
messageText,
|