dshgo-context-panel 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dshgo-context-panel contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,112 @@
1
+ # Context panel · `dshgo-context-panel`
2
+
3
+ A standalone DSH plugin that shows context occupancy, breakdown, trends, tool/file activity, events, compaction history, and the live session fleet in both dsh-Go's native UI and DSH Web. Both routes share `lib/collect.js` and `contextData()`; the read-only `dsh-Go` reference repository is not modified.
4
+
5
+ ## Features
6
+
7
+ - Composer strip: a compact status line such as `Context 63% · 632k/1M`, clipped to 24 Unicode code points.
8
+ - Native V2 panel: Overview, Trend, and More (tools/files/events/compaction/fleet) keep all seven content pages; the occupancy card leads and low-frequency details/settings start collapsed; old clients receive a V1 long-list fallback.
9
+ - Web panel: classic script client with the plugin-owned `/api/DSHgo-context-panel/data` and `/sessions` routes; narrow layouts support scrolling tabs, keyboard navigation, and ARIA tab semantics.
10
+ - Data fallback order: `sessionProjections` → `tokenMeter` → the latest complete model call. Incomplete or unproven usage is reported as unknown rather than invented zeroes.
11
+ - Optional prompt prefix/suffix: registered through the host's `systemPrompt.section`, disabled by default, ordered beside the deployment prefix/suffix, and kept literal.
12
+ - Optional numeric archive: stores only hashed session/sequence identifiers, timestamps, input/output/cache numbers, and committed flags. It never stores conversation text, tool arguments, or file contents, and exposes observed 7-day/30-day summaries.
13
+
14
+ ## Install
15
+
16
+ ```powershell
17
+ dsh plugin --profile web add "F:\编程\dsh\dshgo\hub\dshgo-context-panel"
18
+ dsh --profile web --port 6993 --no-open
19
+ ```
20
+
21
+ The native entry appears in chat details and All features. The Web entry is the `Go Context` / `Go 上下文` sidebar row.
22
+
23
+ ## Configuration
24
+
25
+ `apply(ctx, options)` accepts these plugin-side options. Every limit bounds what this plugin reads, displays, or stores; **it never deletes or trims engine context**.
26
+
27
+ | Option | Default | Range / meaning |
28
+ | --- | ---: | --- |
29
+ | `maxNodes` | 2000 | 0–20000; plugin event scan/display bound; 0 skips event reads |
30
+ | `maxKeptTurns` | 12 | 0–60; retained turn trend/model-call bound |
31
+ | `maxRequestSteps` | 12 | 0–60; step-granularity trend bound |
32
+ | `maxEvents` | 20 | 0–20; event feed bound |
33
+ | `maxFileOps` | 12 | 0–12; file activity bound |
34
+ | `maxArchiveNodes` | 5000 | archive record bound, 0–20000 |
35
+ | `maxCommandChars` | 160 | 16–240; Unicode code-point bound for names, paths, and copy |
36
+ | `maxSessions` | 128 | 1–256; in-memory session preference/compaction bound |
37
+ | `archiveEnabled` | `false` | must be explicitly `true` to write files |
38
+ | `archivePath` | `''` | required absolute path when archive is enabled; no default location |
39
+ | `promptPrefix` / `promptSuffix` | `''` | blank values register nothing; nonblank values stay literal |
40
+
41
+ Native sorting and granularity are session-scoped. Web query choices are request-scoped and cannot mutate native defaults or leak between chats.
42
+
43
+ ### Archive concurrency and recovery
44
+
45
+ The archive uses an absolute path, an 8 MiB read bound, temporary-file + `rename` replacement, and a short `.lock` lease. A writer waits for other locks; if it sees a live lock or an abandoned lock it **never unlinks it automatically**. It preserves the lock and reports `ARCHIVE_BUSY` or `ARCHIVE_ABANDONED`. After all writers have stopped, an operator can remove the lock file and retry. This conservative recovery avoids a check-then-unlink race that could admit two writers.
46
+
47
+ ## Data boundaries
48
+
49
+ - `assistant/message` and `assistant/attempt` enter trends only when input/output are proven non-negative safe integers; stream chunks are provisional and terminal samples take precedence.
50
+ - Missing `contextBreakdown` buckets remain unknown; a computable pressure difference is shown separately as unclassified rather than falsely labelled free space.
51
+ - File ranking keeps only recognized path summaries and line counts; displayed text is clipped by `maxCommandChars`.
52
+ - Archive summaries are explicitly “observed calls”, not a full historical ledger; cache totals include only cache fields actually supplied by the source.
53
+
54
+ ## Layout
55
+
56
+ ```text
57
+ lib/config.js defaults, integer bounds, Unicode clipping, bounded preferences
58
+ lib/collect.js host adapters, usage de-duplication, trends/events/files/compaction
59
+ lib/view.js V2/V1 views, contextData, strip copy
60
+ lib/index.js native panel/strip, refresh, session isolation, archive/prompt wiring
61
+ lib/archive.js numeric archive, 7/30-day insights, atomic writes
62
+ lib/archive-lock.js .lock ownership and conservative recovery
63
+ lib/prompts.js optional systemPrompt.section prefix/suffix
64
+ lib/web-panel.js Web routes, same-origin fence, request-local switches
65
+ web/client.js classic no-build Web client
66
+ preview/ reproducible inputs and verification artifacts
67
+ test/ unit, bounds, concurrency, Web, and client-contract tests
68
+ ```
69
+
70
+ ## Verification
71
+
72
+ Run from the plugin directory:
73
+
74
+ ```powershell
75
+ node ..\dsh-Go\sdk\plugin-kit\bin\check.mjs . --load
76
+ node --test test/*.test.js
77
+ node --check web\client.js
78
+ ```
79
+
80
+ The browser harness is `preview/browser-verify.mjs`. With Playwright and an installed Edge channel it uses fixture data from `contextData()` and the actual `web/client.js`, covering 320/390/768/1280 widths, zh/en, light/dark themes, all seven tabs, keyboard navigation, response races, and request-local preferences. It is not a live-host route test or a physical-device test. Write each run to a new timestamped `preview/round-YYYYMMDD-<timestamp>/` directory; do not overwrite existing screenshots.
81
+
82
+ The file is input for the Playwright skill runner, not a standalone ESM entry. Run:
83
+
84
+ ```powershell
85
+ node "$env:USERPROFILE/.agents/skills/playwright/run.js" ./preview/browser-verify.mjs
86
+ ```
87
+
88
+ This requires installed Playwright/Edge and network access to the test-only React 18.3.1 UMD files; these are not plugin runtime dependencies. See the [verification report](docs/verification-2026-12-01.md) for evidence and unverified scope.
89
+
90
+ Native Flutter layout previews use the current plugin's `contextView()` / `contextData()` and the prepared App parser. They render both themes for all seven pages, plus a 320px large-text trend and an English overview:
91
+
92
+ ```powershell
93
+ node ./preview/native-verify.mjs
94
+ ```
95
+
96
+ Override `DSHGO_PREVIEW_CHECKOUT`, `DSHGO_PREVIEW_FLUTTER`, and `DSH_TEST_FONT_DIR` for the prepared local renderer environment. The defaults use the existing ASCII checkout. This does not execute plugin actions, simulate a physical phone, or render real composer strip chrome.
97
+
98
+ For real-engine loading, use an isolated `DSH_HOME` and leave user profiles untouched:
99
+
100
+ ```powershell
101
+ $env:ELECTRON_RUN_AS_NODE='1'; $env:DSH_HOME='E:\dev\DSHgo-webcheck'
102
+ dsh --profile webcheck --from-default-profile web --dump-config
103
+ dsh plugin --profile webcheck add <this directory> --offline
104
+ dsh --profile webcheck --port 6997 --no-open
105
+ ```
106
+
107
+ ## Known scope
108
+
109
+ - This round does not modify `dsh-Go`, and does not claim that a physical phone install or a real-host browser screenshot has been completed.
110
+ - Native host components may still crop the fourth narrow trend column or draw negative line-chart ticks. The plugin changes the trend detail to list rows, but host chart behavior remains a host-side issue.
111
+ - The SDK treats strips as data-only; `preview/view-strip-*.json` is a proxy for preview output, not the real strip chrome.
112
+ - `maxNodes`, `maxArchiveNodes`, and the other limits belong to this plugin; they are not context-trimming controls.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # 上下文面板 · `dshgo-context-panel`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 独立的 DSH 插件:在 dsh-Go 原生界面和 DSH Web 中展示当前会话的上下文占用、分区、趋势、工具/文件活动、事件、压缩历史和多会话编队。两条界面路线共用 `lib/collect.js` 与 `contextData()`,不修改只读参考仓库 `dsh-Go`。
4
+
5
+ ## 能力
6
+
7
+ - composer strip:短状态条,例如 `上下文 63% · 632k/1M`,最多 24 个 Unicode 码点。
8
+ - 原生 v2 面板:概览、趋势、更多(内含工具/文件/事件/压缩/编队)七页;主占用卡优先,低频详情和趋势设置默认收起;旧客户端自动回退 v1 长列表。
9
+ - Web 面板:经典脚本客户端,同源路由 `/api/DSHgo-context-panel/data` 与 `/sessions`,窄屏支持横向标签滚动、键盘切页、ARIA tab 语义。
10
+ - 数据退化顺序:`sessionProjections` → `tokenMeter` → 最近一次完整模型调用;不完整或无法证明的 usage 显示为未知,不伪造为零。
11
+ - 可选提示词前后缀:通过宿主 `systemPrompt.section` 注册,默认关闭,按宿主部署前缀/后缀顺序排列,文本按字面量处理。
12
+ - 可选数值归档:只保存哈希会话/序号、时间、输入/输出/cache 数值和 committed 标记,不保存对话、工具参数或文件内容;提供 7 天/30 天观察统计。
13
+
14
+ ## 安装
15
+
16
+ ```powershell
17
+ dsh plugin --profile web add "F:\编程\dsh\dshgo\hub\dshgo-context-panel"
18
+ dsh --profile web --port 6993 --no-open
19
+ ```
20
+
21
+ 原生入口位于会话详情的插件页和「全部功能」;Web 入口是侧栏的「Go 上下文 / Go Context」。
22
+
23
+ ## 配置
24
+
25
+ `apply(ctx, options)` 接受以下插件侧配置。所有上限只限制本插件读取、展示或存储的数量,**不会删除或裁剪引擎上下文**。
26
+
27
+ | 配置 | 默认值 | 范围/说明 |
28
+ | --- | ---: | --- |
29
+ | `maxNodes` | 2000 | 0–20000;插件扫描/展示的事件上限,0 跳过事件读取 |
30
+ | `maxKeptTurns` | 12 | 0–60;保留的 turn 趋势与模型调用数 |
31
+ | `maxRequestSteps` | 12 | 0–60;step 粒度趋势点上限 |
32
+ | `maxEvents` | 20 | 0–20;事件流上限 |
33
+ | `maxFileOps` | 12 | 0–12;文件活动上限 |
34
+ | `maxArchiveNodes` | 5000 | 归档记录上限,范围 0–20000 |
35
+ | `maxCommandChars` | 160 | 16–240;工具名、路径和文案的 Unicode 码点上限 |
36
+ | `maxSessions` | 128 | 1–256;内存中的会话偏好/压缩状态上限 |
37
+ | `archiveEnabled` | `false` | 必须显式为 `true` 才落盘 |
38
+ | `archivePath` | `''` | 归档启用时必须是绝对路径;没有默认落点 |
39
+ | `promptPrefix` / `promptSuffix` | `''` | 空白不注册;非空按字面量注入 |
40
+
41
+ 原生排序和粒度偏好按 session 隔离;Web 查询参数是请求级的,不会改写原生偏好,也不会泄漏到其他会话。
42
+
43
+ ### 归档并发恢复
44
+
45
+ 归档使用绝对路径、8 MiB 读取上限、临时文件 + `rename` 原子替换和短时 `.lock`。归档写者遇到其他锁会等待;遇到存活锁或检测到已废弃锁时**不会自动删除**,而是保留锁并报告 `ARCHIVE_BUSY` 或 `ARCHIVE_ABANDONED`。确认没有其他写者后,再由运维手工删除对应 `.lock` 并重试,避免检查后删除造成双写者。
46
+
47
+ ## 数据边界
48
+
49
+ - `assistant/message` 和 `assistant/attempt` 只有在 input/output 可证明为非负安全整数时进入趋势;流式 chunk 只作为未结算样本,终态样本优先。
50
+ - `contextBreakdown` 缺失桶显示未知;可计算的压力差额单列为「未分类」,不能误报成空闲。
51
+ - 文件排行只保留识别到的路径摘要和行数;显示文案按 `maxCommandChars` 裁剪。
52
+ - 归档洞察写明「观察到的调用」,不是全历史账本;缓存值仅统计数据中实际提供的 cache 字段。
53
+
54
+ ## 目录与职责
55
+
56
+ ```text
57
+ lib/config.js 配置默认值、整数边界、Unicode 裁剪、有界偏好
58
+ lib/collect.js 宿主服务适配、usage 去重、趋势/事件/文件/压缩采集
59
+ lib/view.js v2/v1 视图、contextData、strip 文案
60
+ lib/index.js 原生 panel/strip、事件刷新、会话隔离、归档/提示词接线
61
+ lib/archive.js 数值归档、7/30 天洞察、原子写入
62
+ lib/archive-lock.js .lock 所有权与保守恢复
63
+ lib/prompts.js systemPrompt.section 的可选前后缀
64
+ lib/web-panel.js Web 路由、同源栅栏、请求级开关
65
+ web/client.js 无构建经典脚本 Web 客户端
66
+ preview/ 可复现输入与截图/JSON 验证产物
67
+ test/ 单元、边界、并发、Web 和客户端契约测试
68
+ ```
69
+
70
+ ## 校验
71
+
72
+ 在插件目录执行:
73
+
74
+ ```powershell
75
+ node ..\dsh-Go\sdk\plugin-kit\bin\check.mjs . --load
76
+ node --test test/*.test.js
77
+ node --check web\client.js
78
+ ```
79
+
80
+ 浏览器版可用 `preview/browser-verify.mjs` 通过 Playwright + 已安装 Edge 运行;它使用 `contextData()` fixture 和实际 `web/client.js`,覆盖 320/390/768/1280 宽度、zh/en、明暗主题、七页、键盘切页、请求竞态和请求级偏好。该验证不等同于真实宿主 Web 路由或实体手机验证。输出默认写入带时间戳的新目录 `preview/round-YYYYMMDD-<timestamp>/`,不能覆盖既有截图。
81
+
82
+ 该文件是 Playwright skill runner 的输入,不能直接当作 ESM 执行。运行方式:
83
+
84
+ ```powershell
85
+ node "$env:USERPROFILE/.agents/skills/playwright/run.js" ./preview/browser-verify.mjs
86
+ ```
87
+
88
+ 需要已安装 Playwright/Edge,以及测试用 React 18.3.1 UMD 的网络访问;不是插件运行时依赖。验收与未验证范围见 [本轮报告](docs/verification-2026-12-01.md)。
89
+
90
+ 原生 Flutter 排版预览使用当前插件的 `contextView()` / `contextData()` 与准备好的 App 解析器,按紧凑主导航逐页输出明暗主题,额外覆盖 320px 大字号趋势和英文概览:
91
+
92
+ ```powershell
93
+ node ./preview/native-verify.mjs
94
+ ```
95
+
96
+ 可用 `DSHGO_PREVIEW_CHECKOUT`、`DSHGO_PREVIEW_FLUTTER`、`DSH_TEST_FONT_DIR` 覆盖本机渲染环境;默认使用已有 ASCII 路径副本。它不执行插件动作,不模拟实体手机,也不把 strip 数据代理当实际输入框状态条。
97
+
98
+ 真实引擎加载应使用独立 `DSH_HOME`,不要触碰用户 profile:
99
+
100
+ ```powershell
101
+ $env:ELECTRON_RUN_AS_NODE='1'; $env:DSH_HOME='E:\dev\DSHgo-webcheck'
102
+ dsh --profile webcheck --from-default-profile web --dump-config
103
+ dsh plugin --profile webcheck add <本目录> --offline
104
+ dsh --profile webcheck --port 6997 --no-open
105
+ ```
106
+
107
+ ## 已知范围
108
+
109
+ - 本轮未修改 `dsh-Go`,也未宣称实体手机安装或真实宿主浏览器截图已完成。
110
+ - 原生宿主仍可能在窄屏裁剪表格第 4 列、折线图 y 轴负刻度;这是宿主组件行为,插件已把趋势明细改成窄屏更稳的列表行。
111
+ - strip 在 SDK 中是纯数据,`preview/view-strip-*.json` 只是代理出图,不是真实 strip 视图。
112
+ - `maxNodes`、`maxArchiveNodes` 等是插件自有边界,不是上下文裁剪旋钮。
@@ -0,0 +1,6 @@
1
+ # Applied when a profile selects this bundle:
2
+ # dsh plugin --profile web add /path/to/dshgo-context-panel
3
+ # A plain insert (id + name) mounts without a restart.
4
+ - insert:
5
+ - id: dshgo-context-panel
6
+ name: dshgo-context-panel
@@ -0,0 +1,47 @@
1
+ // Short filesystem leases for numeric archives. No dependency on a host profile.
2
+ import { open, unlink } from 'node:fs/promises'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { setTimeout as delay } from 'node:timers/promises'
5
+
6
+ async function owner(path) {
7
+ let file
8
+ try {
9
+ file = await open(path, 'r')
10
+ const buffer = Buffer.alloc(1024)
11
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0)
12
+ return JSON.parse(buffer.toString('utf8', 0, bytesRead))
13
+ } catch { return null } finally { await file?.close() }
14
+ }
15
+ function dead(pid) {
16
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
17
+ try { process.kill(pid, 0); return false } catch (error) { return error.code === 'ESRCH' }
18
+ }
19
+
20
+ export async function acquireArchiveLock(path) {
21
+ const lockPath = path + '.lock'
22
+ const deadline = Date.now() + 4000
23
+ while (true) {
24
+ let file
25
+ try {
26
+ file = await open(lockPath, 'wx', 0o600)
27
+ const token = randomUUID()
28
+ await file.writeFile(JSON.stringify({ pid: process.pid, token }))
29
+ await file.sync()
30
+ return async () => {
31
+ await file.close()
32
+ if ((await owner(lockPath))?.token === token) await unlink(lockPath).catch(() => {})
33
+ }
34
+ } catch (error) {
35
+ if (file) { await file.close(); await unlink(lockPath).catch(() => {}); throw error }
36
+ if (error.code !== 'EEXIST') throw error
37
+ const previous = await owner(lockPath)
38
+ // Never reclaim locks automatically: checking ownership then unlinking
39
+ // cannot be atomic, and another writer may already have replaced the file.
40
+ if (previous?.token && dead(previous.pid)) {
41
+ throw Object.assign(new Error('archive lock is abandoned; stop archive writers before removing its .lock file'), { code: 'ARCHIVE_ABANDONED' })
42
+ }
43
+ if (Date.now() >= deadline) throw Object.assign(new Error('archive writer remains busy'), { code: 'ARCHIVE_BUSY' })
44
+ await delay(25)
45
+ }
46
+ }
47
+ }
package/lib/archive.js ADDED
@@ -0,0 +1,97 @@
1
+ // Opt-in local numeric summaries. Atomic writes, bounded reads, no conversation text.
2
+ import { open, mkdir, rename, unlink } from 'node:fs/promises'
3
+ import { dirname, isAbsolute } from 'node:path'
4
+ import { createHash, randomUUID } from 'node:crypto'
5
+ import { normalizeConfig } from './config.js'
6
+ import { usagePoints } from './collect.js'
7
+ import { acquireArchiveLock } from './archive-lock.js'
8
+ const DAY = 86400000
9
+ const MAX_BYTES = 8 * 1024 * 1024
10
+ const hash = (text) => createHash('sha256').update(text).digest('hex')
11
+ const numeric = (n) => Number.isSafeInteger(n) && n >= 0
12
+ function valid(row) {
13
+ return row && /^[a-f0-9]{64}$/.test(row.key) && /^[a-f0-9]{64}$/.test(row.session) && Number.isSafeInteger(row.at) && row.at > 0 && ['input', 'output', 'cacheRead'].every((k) => numeric(row[k])) && typeof row.committed === 'boolean'
14
+ }
15
+ async function load(path) {
16
+ let file
17
+ try {
18
+ file = await open(path, 'r')
19
+ const buffer = Buffer.alloc(MAX_BYTES + 1)
20
+ let bytes = 0
21
+ while (bytes < buffer.length) {
22
+ const read = await file.read(buffer, bytes, buffer.length - bytes, null)
23
+ if (read.bytesRead === 0) break
24
+ bytes += read.bytesRead
25
+ }
26
+ if (bytes > MAX_BYTES) throw new Error('archive exceeds 8 MiB')
27
+ const value = JSON.parse(buffer.toString('utf8', 0, bytes))
28
+ if (value?.version !== 1 || !Array.isArray(value.records) || value.records.length > 20000 || !value.records.every(valid)) throw new Error('invalid archive schema')
29
+ // Copy only allowlisted fields, even from an externally edited archive.
30
+ return value.records.map(({ key, session, at, input, output, cacheRead, committed }) => ({ key, session, at, input, output, cacheRead, committed }))
31
+ } catch (e) { if (e.code === 'ENOENT') return []; throw e } finally { await file?.close() }
32
+ }
33
+ export function createArchive(options = {}, { now = Date.now } = {}) {
34
+ const config = normalizeConfig(options)
35
+ const enabled = config.archiveEnabled
36
+ const path = config.archivePath
37
+ let error = null
38
+ let fatal = false
39
+ let dirty = false
40
+ let revision = 0
41
+ let records = new Map()
42
+ let serial = Promise.resolve()
43
+ const fail = (e, permanent = false) => { error = e?.code ?? e?.message ?? 'archive unavailable'; fatal ||= permanent }
44
+ function prune() {
45
+ records = new Map([...records.values()].filter((r) => r.at <= now() && r.at >= now() - 30 * DAY).sort((a, b) => b.at - a.at || a.key.localeCompare(b.key)).slice(0, config.maxArchiveNodes).map((r) => [r.key, r]))
46
+ }
47
+ const ready = (async () => {
48
+ if (!enabled) return
49
+ if (!path || !isAbsolute(path)) { fail(new Error('an absolute archivePath is required'), true); return }
50
+ try {
51
+ for (const row of await load(path)) if (!records.has(row.key)) records.set(row.key, row)
52
+ prune(); dirty = true
53
+ } catch (e) { fail(e, true) }
54
+ })()
55
+ function record(sessionId, event) {
56
+ if (!enabled || fatal || typeof sessionId !== 'string' || !Number.isSafeInteger(event?.seq) || !['assistant/message', 'assistant/attempt'].includes(event.type)) return false
57
+ const point = usagePoints({ snapshotEvents: () => [event] })[0]
58
+ if (!point || !Number.isSafeInteger(point.at) || point.at > now() || point.at < now() - 30 * DAY) return false
59
+ const row = { key: hash(`${sessionId}\0${event.seq}`), session: hash(sessionId), at: point.at, input: point.input, output: point.output, cacheRead: point.cacheRead, committed: point.committed }
60
+ if (!valid(row) || records.has(row.key)) return false
61
+ records.set(row.key, row); prune(); dirty = true; revision++
62
+ return true
63
+ }
64
+ function flush() {
65
+ serial = serial.then(async () => {
66
+ await ready
67
+ if (!enabled || fatal || !dirty) return
68
+ let lock; let temp
69
+ try {
70
+ await mkdir(dirname(path), { recursive: true })
71
+ // Wait for concurrent writes; active or abandoned owners are never
72
+ // auto-reclaimed because check-then-unlink is not an atomic lease.
73
+ lock = await acquireArchiveLock(path)
74
+ for (const row of await load(path)) if (!records.has(row.key)) records.set(row.key, row)
75
+ prune()
76
+ const json = JSON.stringify({ version: 1, records: [...records.values()] })
77
+ const writtenRevision = revision
78
+ if (Buffer.byteLength(json) > MAX_BYTES) throw new Error('archive exceeds 8 MiB')
79
+ temp = path + '.' + randomUUID() + '.tmp'
80
+ const file = await open(temp, 'wx', 0o600)
81
+ try { await file.writeFile(json); await file.sync() } finally { await file.close() }
82
+ await rename(temp, path); temp = undefined
83
+ dirty = revision !== writtenRevision; error = null
84
+ } catch (e) { fail(e) } finally {
85
+ if (temp) await unlink(temp).catch(() => {})
86
+ if (lock) await lock()
87
+ }
88
+ }).catch((e) => fail(e))
89
+ return serial
90
+ }
91
+ function insights() {
92
+ prune()
93
+ const aggregate = (days) => [...records.values()].filter((r) => r.at >= now() - days * DAY).reduce((a, r) => ({ calls: a.calls + 1, partial: a.partial + Number(!r.committed), input: a.input + r.input, output: a.output + r.output, cacheRead: a.cacheRead + r.cacheRead }), { calls: 0, partial: 0, input: 0, output: 0, cacheRead: 0 })
94
+ return { enabled, error, records: records.size, limit: config.maxArchiveNodes, seven: aggregate(7), thirty: aggregate(30) }
95
+ }
96
+ return { ready, record, flush, insights }
97
+ }