dsh-think-effort 0.3.0 → 0.5.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/cordis.patch.yml CHANGED
@@ -42,4 +42,8 @@
42
42
  # Which models offer Auto: all | declared | off.
43
43
  autoScope: all
44
44
  # Subagent calls: inherit | auto | low/high/max. Applies immediately.
45
- subagentLevel: inherit
45
+ subagentLevel: inherit
46
+ # Record every effort decision for the conversation's floating debug
47
+ # log (Settings -> Automatic thinking depth -> Debug). Off by default;
48
+ # turning it on never changes a request.
49
+ debugOverlay: false
package/docs/DETAIL.en.md CHANGED
@@ -8,15 +8,34 @@ Declarative thinking-depth control for DeepSeek (and other) reasoning models: th
8
8
  2. **Offers `Auto`.** One `Auto` entry is prepended to the model's depth list.
9
9
  3. **Resolves per request.** At the adapter boundary `auto` becomes the declared default; a request whose `purpose` is a cheap host-owned call becomes `low` when the model declares it — regardless of the session's own choice, because those bounded calls never inherit it; a manually picked depth passes through untouched and is validated by DSH itself.
10
10
  4. **Subagent depth.** A subagent effort can be pinned (`inherit` / `auto` / `low`…`max`). `inherit` keeps DSH's native inheritance; a fixed depth overrides the child's own or inherited pick, while a cheap-call downgrade still wins.
11
+ 5. **Live debug log.** An optional floating window shows every request's effort decision (requested → sent), subagent sessions included. It records only; it never changes a request.
11
12
 
12
13
  ## Usage
13
14
 
14
15
  - Pick `Auto` in the model selector to state "use the default depth", or a concrete depth to pin it.
15
16
  - Leaving the depth unset (the native "provider default" row) behaves like `Auto` on ordinary steps — both land on the declared default; `Auto` only records the intent in the session. The cheap-call downgrade applies either way.
16
17
  - The recognized models, default depth and cheap-call list live in the plugin row's config (`think-effort` in `cordis.patch.yml`).
17
- - The visual settings page is preferred: **Plugins → Automatic thinking depth → Configure**. Every field is `volatile`, so Save applies immediately without a restart.
18
+ - The visual settings page has **two entries**, both editing the same form: **Settings → Automatic thinking depth** (recommended), or **Plugins → Automatic thinking depth → Configure** on the row. Every field is `volatile`, so Save applies immediately without a restart.
18
19
 
19
- ![Settings page](settings.png)
20
+ ![The Settings entry](settings-section.png)
21
+
22
+ ## Live debug log
23
+
24
+ Turn on **Debug → Show the live effort-switch log in the conversation** and a movable window (the `shell.overlay` seat) appears at the conversation's bottom-right corner, showing:
25
+
26
+ - each model request's time, purpose, requested depth, the depth actually sent, and the model;
27
+ - subagent sessions' decisions (with a `Sub` badge) — a subagent runs in the same Host process and therefore shares the one journal;
28
+ - `Settings update` and `Capability declared` events, so a save's effect is visible;
29
+ - filters for this session, all sessions, and switches only, plus one-click copy.
30
+
31
+ Two halves: the Host half appends each decision, at the adapter boundary, to an **in-memory ring buffer** (300 records at most, never written to the session log or disk) and serves it through two `webServer` routes — a cursor-based read and a clear; the browser half polls only while the switch is on, and keeps the window's position and open state in browser storage. With the switch off the routes answer `enabled: false`, the window disappears, and recording stops.
32
+
33
+ ## Where the settings page comes from
34
+
35
+ - The row page registers into the plugin manager's `plugins.row.config`, keyed `dsh-think-effort#think-effort`.
36
+ - The Settings page registers into the settings panel's `settings.section` (same `id` `think-effort`, `order: 16`, right after the built-in Plugins section at 15); its glyph registers into `settings.section.icon` with the matching `id`.
37
+ - A Settings section receives no form from its owner, so the page reads the **row's settings namespace** (the profile entry id, `think-effort`) through the `configForms` service. `whileServed(['think-effort'])` registers the entry only while the Host serves that namespace, so a deployment without the row never shows an empty page.
38
+ - Both entries share one form controller inside `configForms`, so a save from either place is the same profile write.
20
39
 
21
40
  ## Limitations
22
41
 
@@ -41,6 +60,7 @@ Declarative thinking-depth control for DeepSeek (and other) reasoning models: th
41
60
  | `auxLevel` | `low` | Depth those calls request |
42
61
  | `autoScope` | `all` | `all` / `declared` / `off` |
43
62
  | `subagentLevel` | `inherit` | Subagent depth: `inherit` / `auto` / a fixed depth; a fixed depth overrides the child's own or inherited pick |
63
+ | `debugOverlay` | `false` | Live effort-switch log over the conversation (records only, never rewrites; 300 records in Host memory) |
44
64
  | `trace` | `false` | Write decisions to stderr for diagnosis |
45
65
 
46
66
  ## Diagnostic tool
package/docs/DETAIL.zh.md CHANGED
@@ -8,15 +8,34 @@
8
8
  2. **提供 `Auto`**:在模型目录的档位列表最前面补一个 `Auto`。
9
9
  3. **逐请求解析**:在适配器边界把 `auto` 换成声明默认档;`purpose` 属于廉价调用时换成 `low`(仅当模型声明了它,且**与会话选了什么都无关**——会话标题/图片摘要本来就不继承会话档位);手动选的档位一律原样透传,由 DSH 自己校验。
10
10
  4. **子代理档位**:可给子代理统一指定强度(`inherit` / `auto` / `low`…`max`)。`inherit` 保持 DSH 原生继承;固定档会覆盖子代理自身或从父代理继承的选择,廉价调用的降档仍然优先。
11
+ 5. **实时调试日志**:可选的悬浮窗,展示每次请求的档位决策(请求档位 → 实际档位),包括子代理会话;只记录,不改变任何请求。
11
12
 
12
13
  ## 使用
13
14
 
14
15
  - 在模型选择器里选 `Auto` 即声明「按默认档走」;选具体档位即固定该档位。
15
16
  - 不选任何档位(原生“提供方默认”)在普通步骤上与 `Auto` 等效,都会落到声明默认档;差别只是 `Auto` 把意图记录进会话。廉价调用的降档在任何情况下都生效。
16
17
  - 识别范围、默认档、廉价调用清单都在插件配置里(`cordis.patch.yml` 的 `think-effort` 行)。
17
- - 更推荐用可视化设置:**插件 → 自动思考档位 → 配置**,字段全部是 `volatile` 配置,保存后立即生效(无需重启)。
18
+ - 可视化设置有**两个入口**,表单与写入相同:**设置 → 自动思考档位**(推荐),或**插件 → 自动思考档位 → 行「配置」**。字段全部是 `volatile` 配置,保存后立即生效(无需重启)。
18
19
 
19
- ![设置页](settings.png)
20
+ ![设置面板里的入口](settings-section.png)
21
+
22
+ ## 实时调试日志
23
+
24
+ 设置页「调试 → 在会话界面显示实时档位切换日志」打开后,会话右下角出现一个可拖动的悬浮窗(`shell.overlay` 槽位),实时显示:
25
+
26
+ - 每次模型请求的时间、用途、请求档位与实际发送档位、模型;
27
+ - 子代理会话的决策(带「子」标记)——子代理与主会话在同一个 Host 进程里,共用同一份日志;
28
+ - `设置更新` 与 `能力声明` 事件,便于确认保存是否生效;
29
+ - 「当前会话 / 全部会话 / 仅切换」筛选与一键复制。
30
+
31
+ 实现分两半:Host 半边在适配器边界把每条决策写入一个**内存环形缓冲**(最多 300 条,不写会话日志、不落盘),并通过两条 `webServer` 路由提供增量读取与清空;浏览器半边按开关状态轮询,只在打开时请求,窗口位置与展开状态存在浏览器本地。关掉开关后路由返回 `enabled: false`,窗口消失、记录停止。
32
+
33
+ ## 设置页从哪里来
34
+
35
+ - 插件行页面注册进插件管理器的 `plugins.row.config`,键为 `dsh-think-effort#think-effort`;
36
+ - 设置页注册进设置面板的 `settings.section`(`id` 同为 `think-effort`,`order: 16`,紧跟 order 15 的内置插件),图标注册进 `settings.section.icon` 且 `id` 必须与之一致;
37
+ - 设置页没有 owner 传入的表单,所以它从 `configForms` 服务读取**行设置命名空间**(即 profile 条目 id `think-effort`)。`whileServed(['think-effort'])` 保证只有 Host 正在提供该命名空间时才注册,页面不会在没有这一行的部署里留下空壳;
38
+ - 两个入口共用 `configForms` 里同一个表单控制器,因此任一入口的保存都是同一次 profile 写入。
20
39
 
21
40
  ## 限制
22
41
 
@@ -41,6 +60,7 @@
41
60
  | `auxLevel` | `low` | 廉价调用用的档位 |
42
61
  | `autoScope` | `all` | `all` / `declared` / `off` |
43
62
  | `subagentLevel` | `inherit` | 子代理档位:`inherit` / `auto` / 固定档;固定档覆盖子代理自身或继承的选择 |
63
+ | `debugOverlay` | `false` | 会话界面的实时档位切换日志(只记录,不改请求;Host 内存最多 300 条) |
44
64
  | `trace` | `false` | 把决策写到 stderr(排查用) |
45
65
 
46
66
  ## 诊断工具
Binary file
Binary file
Binary file
package/index.js CHANGED
@@ -49,6 +49,7 @@ import {
49
49
  shouldDeclare,
50
50
  withAutoEffort,
51
51
  } from './src/policy.js';
52
+ import { createDebugJournal, registerDebugRoutes } from './src/debug.js';
52
53
 
53
54
  /** The llm-pi-ai settings entry id in a composed profile. */
54
55
  const PI_AI_NAMESPACE = 'llm-pi-ai';
@@ -88,6 +89,12 @@ export const Config = z.object({
88
89
  auxLevel: z.string().default(DEFAULT_CONFIG.auxLevel).volatile(),
89
90
  /** Subagent-owned calls: `inherit`, `auto`, or a fixed level. */
90
91
  subagentLevel: z.string().default(DEFAULT_CONFIG.subagentLevel).volatile(),
92
+ /**
93
+ * Record every effort decision in a bounded in-memory journal and serve it to
94
+ * the conversation's floating debug log. Off by default; when off the journal
95
+ * stays empty and the routes answer `enabled: false`.
96
+ */
97
+ debugOverlay: z.boolean().default(DEFAULT_CONFIG.debugOverlay).volatile(),
91
98
  /** Diagnostic stderr trace of each decision. */
92
99
  trace: z.boolean().default(false).volatile(),
93
100
  });
@@ -247,6 +254,132 @@ export function apply(ctx, rawConfig) {
247
254
  /** Log de-duplication for per-request decisions. */
248
255
  const logged = new Set();
249
256
 
257
+ // ── debug journal ────────────────────────────────────────────────────────
258
+ // The browser half renders this as a floating log over the conversation.
259
+ // Recording is gated by the live config reference, so the switch costs
260
+ // nothing while it is off and applies on the next request after a save.
261
+ const debugJournal = createDebugJournal();
262
+ const debugOn = () => config.debugOverlay === true;
263
+ /** Session facts for the journal, cached because headers do not change. */
264
+ const debugSessions = new Map();
265
+ /** Last level served per `session|purpose`, so a record can name the switch. */
266
+ const debugLast = new Map();
267
+
268
+ /** Read one live Session header, when the store still holds it. */
269
+ const headerOf = (sessionId) => {
270
+ try {
271
+ return ctx.get('sessions')?.get?.(sessionId)?.header;
272
+ } catch {
273
+ return undefined;
274
+ }
275
+ };
276
+
277
+ /**
278
+ * Describe one request's session for the journal: whether it belongs to a
279
+ * subagent, the durable parent link, and the title when one is known.
280
+ * @param {string} [sessionId] stamped session identity.
281
+ * @returns {object} JSON-safe identity fields.
282
+ */
283
+ const debugSessionFacts = (sessionId) => {
284
+ if (typeof sessionId !== 'string' || sessionId === '') {
285
+ return { sessionId: null, parentSession: null, rootSessionId: null, subagent: false, title: null };
286
+ }
287
+ const cached = debugSessions.get(sessionId);
288
+ if (cached !== undefined) return cached;
289
+ let agent;
290
+ try {
291
+ agent = ctx.get('agents')?.get?.(sessionId);
292
+ } catch {
293
+ agent = undefined;
294
+ }
295
+ const session = agent?.session ?? (() => {
296
+ try {
297
+ return ctx.get('sessions')?.get?.(sessionId);
298
+ } catch {
299
+ return undefined;
300
+ }
301
+ })();
302
+ const header = session?.header;
303
+ const parentSession = typeof header?.parentSession === 'string' ? header.parentSession : null;
304
+ let rootSessionId = sessionId;
305
+ let cursor = header;
306
+ for (let depth = 0; depth < 8 && cursor !== undefined; depth += 1) {
307
+ if (typeof cursor.parentSession !== 'string') {
308
+ rootSessionId = typeof cursor.id === 'string' ? cursor.id : rootSessionId;
309
+ break;
310
+ }
311
+ rootSessionId = cursor.parentSession;
312
+ cursor = headerOf(cursor.parentSession);
313
+ if (cursor === undefined) break;
314
+ }
315
+ let title = null;
316
+ try {
317
+ const snapshot = ctx.get('sessionTitle')?.get?.(session);
318
+ if (typeof snapshot?.title === 'string' && snapshot.title !== '') title = snapshot.title;
319
+ } catch {
320
+ /* a missing title service only costs the label */
321
+ }
322
+ const facts = {
323
+ sessionId,
324
+ parentSession,
325
+ rootSessionId,
326
+ subagent: isSubagentAgent(agent) || header?.origin === 'subagent' || (typeof header?.delegationDepth === 'number' && header.delegationDepth > 0),
327
+ title,
328
+ };
329
+ if (debugSessions.size > 200) debugSessions.clear();
330
+ debugSessions.set(sessionId, facts);
331
+ return facts;
332
+ };
333
+
334
+ /**
335
+ * Append one journal record while the debug switch is on.
336
+ * @param {string} kind record type.
337
+ * @param {object} [fields] JSON-safe fields.
338
+ */
339
+ const debugRecord = (kind, fields) => {
340
+ if (debugOn() !== true) return;
341
+ try {
342
+ debugJournal.record(kind, fields);
343
+ } catch {
344
+ /* a debug record must never break a model request */
345
+ }
346
+ };
347
+
348
+ /**
349
+ * Record one per-request effort decision: what the selection asked for, what
350
+ * the adapter will send, and whether that differs from the previous call of
351
+ * the same session and purpose (the "switch" a reader is looking for).
352
+ * @param {object} input decision facts.
353
+ * @param {string} input.provider route key.
354
+ * @param {string} input.model model id.
355
+ * @param {object} input.options the request options the adapter receives.
356
+ * @param {string} [input.level] the level the plugin applied, if any.
357
+ */
358
+ const debugRequest = ({ provider, model, options, level }) => {
359
+ if (debugOn() !== true) return;
360
+ // An ordinary agent step usually carries no purpose; name it explicitly so
361
+ // the browser half can label it instead of showing "unknown".
362
+ const purpose = typeof options.purpose === 'string' && options.purpose !== '' ? options.purpose : 'agent';
363
+ const requested = typeof options.reasoningEffort === 'string' ? options.reasoningEffort : null;
364
+ const applied = level ?? requested;
365
+ const facts = debugSessionFacts(options.sessionId);
366
+ const key = `${facts.sessionId ?? '-'}|${purpose ?? '-'}`;
367
+ const previous = debugLast.get(key) ?? null;
368
+ if (debugLast.size > 200) debugLast.clear();
369
+ debugLast.set(key, applied);
370
+ debugRecord('request', {
371
+ ...facts,
372
+ provider,
373
+ model,
374
+ purpose,
375
+ requested,
376
+ applied,
377
+ switched: level !== undefined && level !== requested,
378
+ from: previous,
379
+ changed: previous !== null && previous !== applied,
380
+ });
381
+ };
382
+
250
383
  // ── capability declaration ───────────────────────────────────────────────
251
384
  /** Serialize settings writes; a boot burst must not stack whole-section updates. */
252
385
  let syncTail = Promise.resolve();
@@ -269,6 +402,11 @@ export function apply(ctx, rawConfig) {
269
402
  try {
270
403
  await settings.update(PI_AI_NAMESPACE, { providers: plan.section.providers }, section.revision);
271
404
  trace('capability sync: section written');
405
+ debugRecord('capability', {
406
+ declared: plan.declared.map((entry) => `${entry.provider}/${entry.model}`),
407
+ efforts: [...config.efforts],
408
+ defaultEffort: config.defaultEffort,
409
+ });
272
410
  void selfCheck();
273
411
  ctx.logger?.info?.(
274
412
  '[think-effort] declared DeepSeek effort capabilities in %s: %s',
@@ -306,6 +444,7 @@ export function apply(ctx, rawConfig) {
306
444
  efforts: reasoning !== null && typeof reasoning === 'object' ? reasoning.efforts : undefined,
307
445
  defaultEffort: reasoning !== null && typeof reasoning === 'object' ? reasoning.defaultEffort : undefined,
308
446
  }, config);
447
+ debugRequest({ provider, model, options, level });
309
448
  if (level === undefined || level === options.reasoningEffort) return options;
310
449
  const key = `${provider}/${model}/${String(options.purpose ?? '-')}/${level}`;
311
450
  trace('translate: %s/%s purpose=%s requested=%s -> %s', provider, model, String(options.purpose ?? '-'), String(options.reasoningEffort), level);
@@ -393,6 +532,15 @@ export function apply(ctx, rawConfig) {
393
532
  ctx.on('loader/volatile-update', () => {
394
533
  config = readConfig(rawConfig);
395
534
  trace('volatile update: enabled=%s subagentLevel=%s', config.enabled, config.subagentLevel);
535
+ debugRecord('config', {
536
+ enabled: config.enabled,
537
+ debugOverlay: config.debugOverlay,
538
+ autoLevel: config.autoLevel,
539
+ defaultEffort: config.defaultEffort,
540
+ subagentLevel: config.subagentLevel,
541
+ auxDowngrade: config.auxDowngrade,
542
+ auxLevel: config.auxLevel,
543
+ });
396
544
  if (config.enabled === false) return;
397
545
  syncCapabilities();
398
546
  });
@@ -489,6 +637,16 @@ export function apply(ctx, rawConfig) {
489
637
  scope.effect(() => scope.tools.register(statusTool), 'think-effort: status tool');
490
638
  });
491
639
 
640
+ // ── debug routes ─────────────────────────────────────────────────────────
641
+ // The conversation's floating debug log polls these. One effect owns both
642
+ // route registrations, so unloading the bundle removes the endpoints.
643
+ ctx.inject?.(['webServer'], (scope) => {
644
+ scope.effect(() => registerDebugRoutes(scope, {
645
+ journal: debugJournal,
646
+ enabled: () => config.debugOverlay === true,
647
+ }), 'think-effort: debug routes');
648
+ });
649
+
492
650
  // Unload: put every registry entry we replaced back, then retire a durable
493
651
  // `auto` selection so a session cannot keep a mask that no longer resolves
494
652
  // (DSH validates the selection against the model's efforts on every request).
package/locale/en.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Automatic thinking depth",
4
- "description": "Adds Auto to the model selector for reasoning models and resolves it per request: the declared default for normal steps (high on DeepSeek), Low for cheap host-owned calls, and an optional depth just for subagents — all editable on a live visual settings page.",
4
+ "description": "Adds Auto to the model selector for reasoning models and resolves it per request: the declared default for normal steps (high on DeepSeek), Low for cheap host-owned calls, and an optional depth just for subagents — all editable on a live visual settings page. A debug switch shows every request's effort decision (subagents included) in a floating log over the conversation.",
5
5
  "detail": "docs/DETAIL.en.md"
6
6
  }
7
7
  }
package/locale/zh.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "自动思考档位",
4
- "description": "为推理模型在模型选择器里加上 Auto,并逐请求解析:普通步骤用声明的默认档(DeepSeek 为 high),廉价调用用 low,子代理可单独指定强度;全部规则都能在可视化设置页即时调整。",
4
+ "description": "为推理模型在模型选择器里加上 Auto,并逐请求解析:普通步骤用声明的默认档(DeepSeek 为 high),廉价调用用 low,子代理可单独指定强度;全部规则都能在可视化设置页即时调整。打开调试开关后,每次请求的档位决策(含子代理)会实时显示在会话界面的悬浮窗里。",
5
5
  "detail": "docs/DETAIL.zh.md"
6
6
  }
7
7
  }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "dsh-think-effort",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
- "description": "Automatic thinking depth for DeepSeek routes in DeepSeek Harness: declare the model's effort vocabulary, add Auto to the model selector, resolve it to the declared default, give subagents their own depth, drop cheap host-owned calls to Low, and edit every rule on a live visual settings page.",
5
+ "description": "Automatic thinking depth for DeepSeek routes in DeepSeek Harness: declare the model's effort vocabulary, add Auto to the model selector, resolve it to the declared default, give subagents their own depth, drop cheap host-owned calls to Low, edit every rule on a live visual settings page, and watch each request's effort decision live in a floating debug log over the conversation.",
6
6
  "icon": "./icon.svg",
7
7
  "license": "MIT",
8
8
  "author": "mhlywxl",
@@ -14,7 +14,9 @@
14
14
  "thinking-level",
15
15
  "deepseek",
16
16
  "subagent",
17
- "settings-page"
17
+ "settings-page",
18
+ "debug-overlay",
19
+ "live-log"
18
20
  ],
19
21
  "exports": {
20
22
  ".": "./index.js",
package/src/debug.js ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Opt-in debug journal and the Host routes that serve it to the browser half.
3
+ *
4
+ * <h2>Why a journal instead of a log line</h2>
5
+ *
6
+ * The plugin already writes each decision to the Host log (`trace`). A person
7
+ * watching the conversation cannot see that log, and the interesting event —
8
+ * "this request asked for `auto` and went out as `max`" — is produced per model
9
+ * request inside the adapter facade. So the Host half appends every decision to
10
+ * a small in-memory ring buffer while the debug switch is on, and the browser
11
+ * half polls these routes and renders the buffer as a floating log over the
12
+ * conversation (including subagent sessions, which share the one Host process).
13
+ *
14
+ * <h2>Contract</h2>
15
+ *
16
+ * - The journal is a bounded ring buffer of JSON-safe records; it lives only in
17
+ * Host memory and never touches the session log, so turning the switch off
18
+ * leaves no trace and no migration behind.
19
+ * - Every route answers `enabled: false` while the switch is off. The switch is
20
+ * the live config reference, so the browser half notices a save immediately.
21
+ * - Reads are `GET …?since=<seq>`; the answer is a delta plus the buffer's
22
+ * current bounds, so a client that fell behind can discard its view instead of
23
+ * showing a gap. `POST …/clear` empties the buffer (guarded by a header, so a
24
+ * cross-site form post cannot reach it).
25
+ *
26
+ * @module dsh-think-effort/debug
27
+ */
28
+
29
+ /** Exact route the browser half polls. */
30
+ export const DEBUG_PATH = '/think-effort/debug';
31
+ /** Exact route that empties the journal. */
32
+ export const DEBUG_CLEAR_PATH = '/think-effort/debug/clear';
33
+ /** Header a clear request must carry, so a cross-site form post cannot reach it. */
34
+ export const DEBUG_CLEAR_HEADER = 'x-think-effort-debug';
35
+ /** Records kept before the oldest ones are dropped. */
36
+ export const DEBUG_LIMIT = 300;
37
+
38
+ /** JSON response helper for a raw Node route handler. */
39
+ function sendJson(response, status, body) {
40
+ const text = JSON.stringify(body);
41
+ const headers = {
42
+ 'content-type': 'application/json; charset=utf-8',
43
+ 'cache-control': 'no-store',
44
+ 'content-length': String(Buffer.byteLength(text)),
45
+ };
46
+ if (typeof response.writeHead === 'function') response.writeHead(status, headers);
47
+ response.end(text);
48
+ }
49
+
50
+ /**
51
+ * Whether a request comes from this application's own page.
52
+ *
53
+ * The custom route sits outside the `/api` bridge, so it has no cookie
54
+ * authentication of its own. Browsers send `Sec-Fetch-Site` on every request
55
+ * they make; a cross-site request is refused, while a missing header (an older
56
+ * engine, or the desktop page's own transport) is admitted — the Host binds to
57
+ * loopback in every shipped composition.
58
+ * @param {object} request Node request.
59
+ * @returns {boolean} true when the request may read the journal.
60
+ */
61
+ function sameOrigin(request) {
62
+ const site = request?.headers?.['sec-fetch-site'];
63
+ return typeof site !== 'string' || site === 'same-origin' || site === 'none';
64
+ }
65
+
66
+ /**
67
+ * Create the bounded in-memory journal.
68
+ * @param {object} [options] overrides for tests.
69
+ * @param {number} [options.limit] records to keep.
70
+ * @param {() => number} [options.now] clock, so records are deterministic in tests.
71
+ * @returns {object} the journal.
72
+ */
73
+ export function createDebugJournal({ limit = DEBUG_LIMIT, now = () => Date.now() } = {}) {
74
+ /** @type {Array<object>} */
75
+ const records = [];
76
+ /** Monotone sequence; survives `clear()` so a client's cursor never replays. */
77
+ let seq = 0;
78
+
79
+ return {
80
+ /** Highest sequence ever appended. */
81
+ get latest() {
82
+ return seq;
83
+ },
84
+ /** Records currently buffered. */
85
+ get size() {
86
+ return records.length;
87
+ },
88
+ /**
89
+ * Append one record.
90
+ * @param {string} kind record type: `request`, `config` or `capability`.
91
+ * @param {object} [fields] JSON-safe fields of the record.
92
+ * @returns {number} the record's sequence number.
93
+ */
94
+ record(kind, fields = {}) {
95
+ seq += 1;
96
+ records.push({ seq, at: now(), kind, ...fields });
97
+ if (records.length > limit) records.splice(0, records.length - limit);
98
+ return seq;
99
+ },
100
+ /**
101
+ * Read the records after a cursor.
102
+ * @param {number} [since] last sequence the caller already has.
103
+ * @returns {{latest: number, oldest: number|null, reset: boolean, entries: object[]}} the delta.
104
+ */
105
+ snapshot(since = 0) {
106
+ const cursor = Number.isFinite(since) && since > 0 ? Math.floor(since) : 0;
107
+ const oldest = records.length > 0 ? records[0].seq : null;
108
+ // The cursor names a record the buffer no longer holds: the caller must
109
+ // replace its view instead of appending a delta with a hole in it.
110
+ const reset = cursor > 0 && oldest !== null && cursor + 1 < oldest;
111
+ return {
112
+ latest: seq,
113
+ oldest,
114
+ reset,
115
+ entries: records.filter((entry) => entry.seq > cursor),
116
+ };
117
+ },
118
+ /** Empty the buffer; the sequence keeps counting so clients stay consistent. */
119
+ clear() {
120
+ records.length = 0;
121
+ return seq;
122
+ },
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Register the debug routes on the Host web server.
128
+ *
129
+ * The plugin owns both routes through one Cordis effect, so disabling the bundle
130
+ * removes the endpoints instead of leaving live handlers behind.
131
+ *
132
+ * @param {object} webCtx context providing `webServer`.
133
+ * @param {object} options wiring.
134
+ * @param {object} options.journal the journal to serve.
135
+ * @param {() => boolean} options.enabled live debug switch.
136
+ * @returns {() => void} disposer removing both routes.
137
+ */
138
+ export function registerDebugRoutes(webCtx, { journal, enabled }) {
139
+ const disposers = [];
140
+ try {
141
+ disposers.push(webCtx.webServer.register({
142
+ kind: 'exact',
143
+ path: DEBUG_PATH,
144
+ handler(request, response) {
145
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
146
+ sendJson(response, 405, { ok: false, error: 'method' });
147
+ return;
148
+ }
149
+ if (!sameOrigin(request)) {
150
+ sendJson(response, 403, { ok: false, error: 'origin' });
151
+ return;
152
+ }
153
+ if (enabled() !== true) {
154
+ sendJson(response, 200, { ok: true, enabled: false, latest: journal.latest, oldest: null, reset: false, entries: [] });
155
+ return;
156
+ }
157
+ let since = 0;
158
+ try {
159
+ const url = new URL(String(request.url ?? '/'), 'http://dsh.invalid');
160
+ since = Number(url.searchParams.get('since') ?? '0');
161
+ } catch {
162
+ /* an unparseable URL reads from the beginning */
163
+ }
164
+ sendJson(response, 200, { ok: true, enabled: true, ...journal.snapshot(since) });
165
+ },
166
+ }));
167
+ disposers.push(webCtx.webServer.register({
168
+ kind: 'exact',
169
+ path: DEBUG_CLEAR_PATH,
170
+ handler(request, response) {
171
+ if (request.method !== 'POST') {
172
+ sendJson(response, 405, { ok: false, error: 'method' });
173
+ return;
174
+ }
175
+ if (!sameOrigin(request) || request.headers?.[DEBUG_CLEAR_HEADER] !== '1') {
176
+ sendJson(response, 403, { ok: false, error: 'origin' });
177
+ return;
178
+ }
179
+ sendJson(response, 200, { ok: true, latest: journal.clear() });
180
+ },
181
+ }));
182
+ } catch (error) {
183
+ for (const dispose of disposers) dispose?.();
184
+ throw error;
185
+ }
186
+ return () => {
187
+ for (const dispose of disposers) dispose?.();
188
+ };
189
+ }
package/src/policy.js CHANGED
@@ -92,6 +92,8 @@ export const DEFAULT_CONFIG = {
92
92
  * id forces that depth (clamped to the model's declared vocabulary).
93
93
  */
94
94
  subagentLevel: 'inherit',
95
+ /** Record every effort decision for the conversation's floating debug log. */
96
+ debugOverlay: false,
95
97
  /** Diagnostic stderr trace of each decision. */
96
98
  trace: false,
97
99
  };