@laoyuehanni/dsh-token-usage 0.4.1 → 0.4.3
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/README.md +4 -12
- package/README.zh.md +4 -12
- package/docs/pricing.md +3 -13
- package/lib/client/PricingDialog.d.ts +51 -0
- package/lib/client/PricingDialog.d.ts.map +1 -0
- package/lib/client/PricingDialog.js +127 -0
- package/lib/client/PricingDialog.js.map +1 -0
- package/lib/client/PricingOverviewDialog.d.ts +76 -0
- package/lib/client/PricingOverviewDialog.d.ts.map +1 -0
- package/lib/client/PricingOverviewDialog.js +361 -0
- package/lib/client/PricingOverviewDialog.js.map +1 -0
- package/lib/client/SessionTable.d.ts +39 -0
- package/lib/client/SessionTable.d.ts.map +1 -0
- package/lib/client/SessionTable.js +181 -0
- package/lib/client/SessionTable.js.map +1 -0
- package/lib/client/TokenUsageCard.d.ts.map +1 -1
- package/lib/client/TokenUsageCard.js +4 -1
- package/lib/client/TokenUsageCard.js.map +1 -1
- package/lib/client/TokenUsageSection.d.ts +17 -9
- package/lib/client/TokenUsageSection.d.ts.map +1 -1
- package/lib/client/TokenUsageSection.js +67 -127
- package/lib/client/TokenUsageSection.js.map +1 -1
- package/lib/client/format.d.ts.map +1 -1
- package/lib/client/format.js +12 -4
- package/lib/client/format.js.map +1 -1
- package/lib/client/index.d.ts +3 -2
- package/lib/client/index.d.ts.map +1 -1
- package/lib/client/index.js +23 -3
- package/lib/client/index.js.map +1 -1
- package/lib/client/locales.d.ts +35 -2
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/locales.js +70 -4
- package/lib/client/locales.js.map +1 -1
- package/lib/client.js +1438 -317
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +59 -20
- package/lib/index.js.map +1 -1
- package/lib/migrate.d.ts +3 -2
- package/lib/migrate.d.ts.map +1 -1
- package/lib/migrate.js +4 -2
- package/lib/migrate.js.map +1 -1
- package/lib/pricing.d.ts +63 -21
- package/lib/pricing.d.ts.map +1 -1
- package/lib/pricing.js +82 -53
- package/lib/pricing.js.map +1 -1
- package/lib/rollup.d.ts +7 -1
- package/lib/rollup.d.ts.map +1 -1
- package/lib/rollup.js +15 -0
- package/lib/rollup.js.map +1 -1
- package/lib/session-meta.d.ts +68 -0
- package/lib/session-meta.d.ts.map +1 -0
- package/lib/session-meta.js +174 -0
- package/lib/session-meta.js.map +1 -0
- package/lib/stats-route.d.ts +22 -0
- package/lib/stats-route.d.ts.map +1 -1
- package/lib/stats-route.js +93 -12
- package/lib/stats-route.js.map +1 -1
- package/lib/stats.d.ts +57 -11
- package/lib/stats.d.ts.map +1 -1
- package/lib/stats.js +239 -26
- package/lib/stats.js.map +1 -1
- package/lib/sync-state.d.ts +42 -10
- package/lib/sync-state.d.ts.map +1 -1
- package/lib/sync-state.js +61 -19
- package/lib/sync-state.js.map +1 -1
- package/lib/sync.d.ts +122 -15
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +142 -20
- package/lib/sync.js.map +1 -1
- package/lib/usage-log.d.ts +35 -0
- package/lib/usage-log.d.ts.map +1 -1
- package/lib/usage-log.js +111 -0
- package/lib/usage-log.js.map +1 -1
- package/lib/wire.d.ts +117 -11
- package/lib/wire.d.ts.map +1 -1
- package/lib/wire.js +4 -1
- package/lib/wire.js.map +1 -1
- package/package.json +1 -1
package/lib/sync-state.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* One-shot initialization
|
|
3
|
-
* sync
|
|
4
|
-
*
|
|
2
|
+
* One-shot initialization markers: whether the plugin ever completed a
|
|
3
|
+
* history sync (`initializedAt`) and whether a sync has since folded the
|
|
4
|
+
* session metadata (titles, header facts) into `sessions.json`
|
|
5
|
+
* (`metaSyncedAt`). The markers exist only to gate automatic runs; every
|
|
6
|
+
* later sync is the user's decision (the manual command). A missing or
|
|
7
|
+
* malformed marker reads as unmet: the next startup re-runs the gated
|
|
8
|
+
* work, whose dedupe and idempotent upserts make the repetition a no-op.
|
|
5
9
|
*
|
|
6
10
|
* @module token-usage/sync-state
|
|
7
11
|
*/
|
|
@@ -11,26 +15,26 @@ import { consoleLogger } from "./log.js";
|
|
|
11
15
|
const STATE_FILE = 'state.json';
|
|
12
16
|
const TMP_FILE = 'state.json.tmp';
|
|
13
17
|
function isSyncState(value) {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
if (typeof value !== 'object' || value === null)
|
|
19
|
+
return false;
|
|
20
|
+
const state = value;
|
|
21
|
+
return typeof state.initializedAt === 'number' && Number.isFinite(state.initializedAt);
|
|
17
22
|
}
|
|
18
23
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* dedupe makes the repetition a no-op.
|
|
24
|
+
* Read the marker file. A missing or malformed file reads as null — the
|
|
25
|
+
* caller treats that as unmet and re-runs the gated work idempotently.
|
|
22
26
|
* @param dir - the data directory holding the marker.
|
|
23
27
|
*/
|
|
24
|
-
export async function
|
|
28
|
+
export async function readSyncState(dir, logger = consoleLogger) {
|
|
25
29
|
let text;
|
|
26
30
|
try {
|
|
27
31
|
text = await readFile(join(dir, STATE_FILE), 'utf8');
|
|
28
32
|
}
|
|
29
33
|
catch (error) {
|
|
30
34
|
if (error.code === 'ENOENT')
|
|
31
|
-
return
|
|
35
|
+
return null;
|
|
32
36
|
logger.error('[token-usage] cannot read state:', error);
|
|
33
|
-
return
|
|
37
|
+
return null;
|
|
34
38
|
}
|
|
35
39
|
let value;
|
|
36
40
|
try {
|
|
@@ -38,20 +42,58 @@ export async function isInitialized(dir, logger = consoleLogger) {
|
|
|
38
42
|
}
|
|
39
43
|
catch {
|
|
40
44
|
// Malformed marker: treat as uninitialized (the sync re-runs idempotently).
|
|
41
|
-
return
|
|
45
|
+
return null;
|
|
42
46
|
}
|
|
43
|
-
return isSyncState(value);
|
|
47
|
+
return isSyncState(value) ? value : null;
|
|
44
48
|
}
|
|
45
49
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
50
|
+
* Whether the first automatic sync already completed. A missing or
|
|
51
|
+
* malformed marker reads as uninitialized: the next startup re-runs the
|
|
52
|
+
* sync, whose dedupe makes the repetition a no-op.
|
|
48
53
|
* @param dir - the data directory holding the marker.
|
|
49
|
-
* @param now - clock source (test seam).
|
|
50
54
|
*/
|
|
51
|
-
export async function
|
|
55
|
+
export async function isInitialized(dir, logger = consoleLogger) {
|
|
56
|
+
return (await readSyncState(dir, logger)) !== null;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Persist the marker file atomically (temp file + rename), so a crash
|
|
60
|
+
* mid-write never leaves a torn marker that would misread as settled.
|
|
61
|
+
* Fields absent from `state` are omitted, never null.
|
|
62
|
+
* @param dir - the data directory holding the marker.
|
|
63
|
+
* @param state - the marker contents to write.
|
|
64
|
+
*/
|
|
65
|
+
export async function writeSyncState(dir, state) {
|
|
52
66
|
const target = join(dir, STATE_FILE);
|
|
53
67
|
const tmp = join(dir, TMP_FILE);
|
|
54
|
-
await writeFile(tmp, JSON.stringify(
|
|
68
|
+
await writeFile(tmp, JSON.stringify(state), 'utf8');
|
|
55
69
|
await rename(tmp, target);
|
|
56
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* Persist the initialized marker (and, when the caller says the same run
|
|
73
|
+
* folded the metadata, the meta marker alongside it). An existing
|
|
74
|
+
* `metaSyncedAt` survives: the first-sync write must not revoke a backfill
|
|
75
|
+
* an earlier upgrade already completed.
|
|
76
|
+
* @param dir - the data directory holding the marker.
|
|
77
|
+
* @param now - clock source (test seam).
|
|
78
|
+
* @param withMeta - whether this run also folded session metadata.
|
|
79
|
+
*/
|
|
80
|
+
export async function markInitialized(dir, now = () => new Date(), withMeta = false) {
|
|
81
|
+
const existing = await readSyncState(dir);
|
|
82
|
+
await writeSyncState(dir, {
|
|
83
|
+
initializedAt: now().getTime(),
|
|
84
|
+
...(existing?.metaSyncedAt !== undefined
|
|
85
|
+
? { metaSyncedAt: existing.metaSyncedAt }
|
|
86
|
+
: withMeta ? { metaSyncedAt: now().getTime() } : {}),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Stamp the metadata backfill as done, preserving `initializedAt`.
|
|
91
|
+
* @param dir - the data directory holding the marker.
|
|
92
|
+
* @param now - clock source (test seam).
|
|
93
|
+
*/
|
|
94
|
+
export async function markMetaSynced(dir, now = () => new Date()) {
|
|
95
|
+
const existing = await readSyncState(dir);
|
|
96
|
+
const initializedAt = existing?.initializedAt ?? now().getTime();
|
|
97
|
+
await writeSyncState(dir, { initializedAt, metaSyncedAt: now().getTime() });
|
|
98
|
+
}
|
|
57
99
|
//# sourceMappingURL=sync-state.js.map
|
package/lib/sync-state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-state.js","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sync-state.js","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC9D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,aAAa,EAAmB,MAAM,UAAU,CAAA;AAEzD,MAAM,UAAU,GAAG,YAAY,CAAA;AAC/B,MAAM,QAAQ,GAAG,gBAAgB,CAAA;AAajC,SAAS,WAAW,CAAC,KAAc;IACjC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAA;IAC7D,MAAM,KAAK,GAAG,KAAgC,CAAA;IAC9C,OAAO,OAAO,KAAK,CAAC,aAAa,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,aAAa,CAAC,CAAA;AACxF,CAAC;AAED;;;;GAIG;AACH,MAAM,CAA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;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,GAAW,EACX,MAAkB,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE,EAClC,QAAQ,GAAG,KAAK;IAEhB,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,GAAG,CAAC,CAAA;IACzC,MAAM,cAAc,CAAC,GAAG,EAAE;QACxB,aAAa,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE;QAC9B,GAAG,CAAC,QAAQ,EAAE,YAAY,KAAK,SAAS;YACtC,CAAC,CAAC,EAAE,YAAY,EAAE,QAAQ,CAAC,YAAY,EAAE;YACzC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACvD,CAAC,CAAA;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,GAAW,EAAE,MAAkB,GAAG,EAAE,CAAC,IAAI,IAAI,EAAE;IAClF,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,GAAG,CAAC,CAAA;IACzC,MAAM,aAAa,GAAG,QAAQ,EAAE,aAAa,IAAI,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAChE,MAAM,cAAc,CAAC,GAAG,EAAE,EAAE,aAAa,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAA;AAC7E,CAAC"}
|
package/lib/sync.d.ts
CHANGED
|
@@ -11,6 +11,11 @@
|
|
|
11
11
|
* the run — one unreadable file must not keep the rest of the history
|
|
12
12
|
* out of the ledger.
|
|
13
13
|
*
|
|
14
|
+
* Reads go through whichever persistence seam the running host exposes: the
|
|
15
|
+
* handle generation (`dsh` 0.1.3-alpha.1 and later, `open`/`read`/`close`) or
|
|
16
|
+
* the older inspect generation (`dsh` 0.1.2-rc.1 and earlier, `inspect`). One
|
|
17
|
+
* probe per run picks the seam, so a single build walks history on both.
|
|
18
|
+
*
|
|
14
19
|
* @module token-usage/sync
|
|
15
20
|
*/
|
|
16
21
|
import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session';
|
|
@@ -21,6 +26,10 @@ export interface SyncResult {
|
|
|
21
26
|
added: number;
|
|
22
27
|
/** Requests already present in the log (deduped). */
|
|
23
28
|
skipped: number;
|
|
29
|
+
/** Rows removed because no readable session log reproduced them: relics of
|
|
30
|
+
* an older stored format, whose event coordinates the host rewrote when it
|
|
31
|
+
* migrated the log to the current format generation. */
|
|
32
|
+
removed: number;
|
|
24
33
|
/** Sessions whose stored log failed to load or validate. Their rows are
|
|
25
34
|
* absent from this run; every such session is reported through
|
|
26
35
|
* {@link SyncDeps.onSessionFailure} and counted here. */
|
|
@@ -43,33 +52,124 @@ export interface SyncProgressTick {
|
|
|
43
52
|
added: number;
|
|
44
53
|
/** Rows skipped by dedupe so far. */
|
|
45
54
|
skipped: number;
|
|
55
|
+
/** Rows removed by the closing reconcile pass so far. Stays zero until the
|
|
56
|
+
* walk finishes: the pass needs every readable session to have spoken. */
|
|
57
|
+
removed: number;
|
|
46
58
|
/** Sessions skipped so far because their stored log failed to load or
|
|
47
59
|
* validate; they count as processed for the progress bar. */
|
|
48
60
|
failedSessions: number;
|
|
49
61
|
}
|
|
50
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* The header facts the metadata index captures (the duck-typed projection
|
|
64
|
+
* of the host's `SessionHeader`): the working directory, the subagent
|
|
65
|
+
* classification, and the parent lineage. All three are immutable per
|
|
66
|
+
* session, so one upsert per session per run suffices.
|
|
67
|
+
*/
|
|
68
|
+
export interface SessionHeaderFacts {
|
|
69
|
+
cwd?: string;
|
|
70
|
+
origin?: 'subagent';
|
|
71
|
+
parentSession?: string;
|
|
72
|
+
}
|
|
73
|
+
/** The metadata sink the sync folds identity facts into (duck-typed for
|
|
74
|
+
* tests; the host passes a {@link SessionMetaStore}). */
|
|
75
|
+
export interface SyncMetaSink {
|
|
76
|
+
upsert(id: string, patch: SessionHeaderFacts & {
|
|
77
|
+
title?: string;
|
|
78
|
+
}): Promise<void>;
|
|
79
|
+
}
|
|
80
|
+
/** One stored session as either persistence generation lists it: the handle
|
|
81
|
+
* generation reports `snapshot.header.id`, the older one a bare `header`. */
|
|
82
|
+
export type SyncSessionEntry = {
|
|
83
|
+
readonly id: SessionId;
|
|
84
|
+
} | {
|
|
85
|
+
readonly header: {
|
|
86
|
+
readonly id: SessionId;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
/** One open read handle of the handle-based generation (`dsh` 0.1.3-alpha.1
|
|
90
|
+
* and later). The host's real handle also carries `append`/`flush` and an
|
|
91
|
+
* `eventState` beside `read`'s events; the sync needs only this much. */
|
|
92
|
+
export interface SyncSessionHandle {
|
|
93
|
+
/** The immutable stored header, fixed when the handle was opened. */
|
|
94
|
+
readonly header?: SessionHeaderFacts | undefined;
|
|
95
|
+
/** The log slice; with no arguments, the whole log from seq 0. */
|
|
96
|
+
read(offset?: number, length?: number, options?: {
|
|
97
|
+
signal?: AbortSignal;
|
|
98
|
+
}): Promise<{
|
|
99
|
+
events: readonly SessionEvent[];
|
|
100
|
+
}>;
|
|
101
|
+
/** Release the handle — idempotent. On a read handle this frees local
|
|
102
|
+
* resources only: a read handle never takes write ownership, so it runs
|
|
103
|
+
* beside the host's writer (and beside another process's). */
|
|
104
|
+
close(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The persistence surface the sync needs (duck-typed for tests). The host
|
|
108
|
+
* ships two generations of this seam and {@link readerOf} probes which one is
|
|
109
|
+
* live, so one build serves both:
|
|
110
|
+
*
|
|
111
|
+
* - **handle seam** (`dsh` 0.1.3-alpha.1 and later): `list({ signal })` reports
|
|
112
|
+
* ids under `header.id`, and `open(id, 'read')` yields a handle whose
|
|
113
|
+
* `read()` returns the log while `header` carries the identity facts.
|
|
114
|
+
* - **inspect seam** (`dsh` 0.1.2-rc.1 and earlier): `list(signal)` reports
|
|
115
|
+
* bare headers and `inspect(id, signal)` returns log and header at once.
|
|
116
|
+
*
|
|
117
|
+
* Exactly one of `open`/`inspect` exists per host, hence both are optional; a
|
|
118
|
+
* persistence carrying neither is rejected up front (see {@link readerOf})
|
|
119
|
+
* instead of being reported as one unreadable session after another.
|
|
120
|
+
*/
|
|
51
121
|
export interface SyncPersistence {
|
|
52
|
-
/** Every materialized session, in arbitrary order.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
122
|
+
/** Every materialized session, in arbitrary order. The handle generation
|
|
123
|
+
* takes an options object here, the older one the signal positionally. */
|
|
124
|
+
list(options?: {
|
|
125
|
+
signal?: AbortSignal;
|
|
126
|
+
} | AbortSignal): Promise<readonly SyncSessionEntry[]>;
|
|
127
|
+
/** Handle generation: one read handle onto a stored session. */
|
|
128
|
+
open?(id: SessionId, access: 'read', options?: {
|
|
129
|
+
signal?: AbortSignal;
|
|
130
|
+
}): Promise<SyncSessionHandle>;
|
|
131
|
+
/** Inspect generation: the immutable logical event log of one session,
|
|
132
|
+
* with the header the identity facts are projected from. */
|
|
133
|
+
inspect?(id: SessionId, signal?: AbortSignal): Promise<{
|
|
58
134
|
events: readonly SessionEvent[];
|
|
135
|
+
meta?: SessionHeaderFacts;
|
|
59
136
|
}>;
|
|
60
137
|
}
|
|
138
|
+
/**
|
|
139
|
+
* The ledger surface the sync needs (duck-typed for tests): the host passes
|
|
140
|
+
* the {@link UsageLog}, tests pass an in-memory twin.
|
|
141
|
+
*/
|
|
142
|
+
export type SyncLog = Pick<UsageLog, 'scan' | 'ids' | 'record' | 'reconcile'>;
|
|
61
143
|
/** Dependencies of one sync run. */
|
|
62
144
|
export interface SyncDeps {
|
|
63
145
|
persistence: SyncPersistence;
|
|
64
|
-
log:
|
|
146
|
+
log: SyncLog;
|
|
65
147
|
/** Whether the sync records `compaction/summary` events (default true,
|
|
66
148
|
* mirroring the `recordCompaction` config). */
|
|
67
149
|
recordCompaction?: boolean;
|
|
150
|
+
/** Metadata sink for the session table's identity fields: the walk folds
|
|
151
|
+
* each session's latest-wins `session/title` text and its immutable
|
|
152
|
+
* header facts (cwd, lineage) into it. Absent → no metadata capture
|
|
153
|
+
* (the usage walk still runs). */
|
|
154
|
+
meta?: SyncMetaSink;
|
|
68
155
|
/** Called once per session whose stored log failed to load or validate
|
|
69
156
|
* (the session is then skipped). The host uses this to log which session
|
|
70
157
|
* and why; aborts raised through `signal` are re-thrown, never reported. */
|
|
71
158
|
onSessionFailure?: (id: SessionId, error: unknown) => void;
|
|
159
|
+
/** Whether the closing reconcile pass runs (default true). The boot path
|
|
160
|
+
* passes false: a first-run install has no stale rows to drop, and the
|
|
161
|
+
* pass would delay the marker write that a concurrent data-directory
|
|
162
|
+
* migration waits behind. */
|
|
163
|
+
reconcile?: boolean;
|
|
72
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* The latest-wins `session/title` text of one event, or undefined: the
|
|
167
|
+
* event type is host-merged (`dsh-session-title`), so the plugin reads the
|
|
168
|
+
* payload duck-typed and tolerantly — a non-string or empty title is
|
|
169
|
+
* skipped, never fabricated. Exported for the live recorder, which folds
|
|
170
|
+
* the same event into the same index.
|
|
171
|
+
*/
|
|
172
|
+
export declare function titleOfEvent(event: SessionEvent): string | undefined;
|
|
73
173
|
/**
|
|
74
174
|
* Append every missing request row. The log's dedupe set is rebuilt from the
|
|
75
175
|
* data files first, so a second run is a no-op and rows recorded live in a
|
|
@@ -83,13 +183,20 @@ export interface SyncDeps {
|
|
|
83
183
|
*/
|
|
84
184
|
export declare function syncHistory(deps: SyncDeps, onTick?: (tick: SyncProgressTick) => void, signal?: AbortSignal): Promise<SyncResult>;
|
|
85
185
|
/**
|
|
86
|
-
* Run the
|
|
87
|
-
*
|
|
88
|
-
* the
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
186
|
+
* Run the gated automatic work, then persist the markers:
|
|
187
|
+
* - No `initializedAt` — the first-run backfill: one full sync (which also
|
|
188
|
+
* folds the metadata), then both markers land together.
|
|
189
|
+
* - `initializedAt` present, `metaSyncedAt` absent — a pre-session-table
|
|
190
|
+
* install owes exactly one metadata backfill: run the same sync once
|
|
191
|
+
* more (every usage row dedupes to a no-op write; the walk lands the
|
|
192
|
+
* titles and header facts the old build never stored), then stamp
|
|
193
|
+
* `metaSyncedAt`.
|
|
194
|
+
* - Both markers present — nothing to do.
|
|
195
|
+
* A crash before the marker write leaves the marker absent, so the next
|
|
196
|
+
* startup re-runs — a no-op thanks to dedupe and idempotent upserts.
|
|
197
|
+
* @param deps - persistence and the shared log (with the metadata sink).
|
|
198
|
+
* @param dir - the data directory holding the markers.
|
|
199
|
+
* @returns the sync outcome, or null when both markers were already set.
|
|
93
200
|
*/
|
|
94
201
|
export declare function autoSyncIfNeeded(deps: SyncDeps, dir: string): Promise<SyncResult | null>;
|
|
95
202
|
//# sourceMappingURL=sync.d.ts.map
|
package/lib/sync.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAQvE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAE9C,+BAA+B;AAC/B,MAAM,WAAW,UAAU;IACzB,gCAAgC;IAChC,KAAK,EAAE,MAAM,CAAA;IACb,qDAAqD;IACrD,OAAO,EAAE,MAAM,CAAA;IACf;;4DAEwD;IACxD,OAAO,EAAE,MAAM,CAAA;IACf;;6DAEyD;IACzD,cAAc,EAAE,MAAM,CAAA;CACvB;AAED;;;;;;;GAOG;AACH,MAAM,WA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;;;;;;;GAUG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,QAAQ,EACd,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,gBAAgB,KAAK,IAAI,EACzC,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,UAAU,CAAC,CAsFrB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAO9F"}
|
package/lib/sync.js
CHANGED
|
@@ -11,10 +11,77 @@
|
|
|
11
11
|
* the run — one unreadable file must not keep the rest of the history
|
|
12
12
|
* out of the ledger.
|
|
13
13
|
*
|
|
14
|
+
* Reads go through whichever persistence seam the running host exposes: the
|
|
15
|
+
* handle generation (`dsh` 0.1.3-alpha.1 and later, `open`/`read`/`close`) or
|
|
16
|
+
* the older inspect generation (`dsh` 0.1.2-rc.1 and earlier, `inspect`). One
|
|
17
|
+
* probe per run picks the seam, so a single build walks history on both.
|
|
18
|
+
*
|
|
14
19
|
* @module token-usage/sync
|
|
15
20
|
*/
|
|
16
|
-
import {
|
|
21
|
+
import { markInitialized, markMetaSynced, readSyncState } from "./sync-state.js";
|
|
17
22
|
import { modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
23
|
+
/**
|
|
24
|
+
* Probe which persistence seam the running host exposes and normalize it.
|
|
25
|
+
*
|
|
26
|
+
* The probe runs once per sync, never once per session: a host does not change
|
|
27
|
+
* generation mid-process, and probing per session would report a wholesale
|
|
28
|
+
* mismatch as N individually unreadable sessions — precisely the silent
|
|
29
|
+
* failure the two seams invite.
|
|
30
|
+
* @param persistence - the host's `ctx.sessionPersistence` (or a test twin).
|
|
31
|
+
* @returns the normalized reader.
|
|
32
|
+
* @throws {Error} when the persistence exposes neither seam (a host older or
|
|
33
|
+
* newer than either generation), which must fail loudly rather than report
|
|
34
|
+
* every session as unreadable.
|
|
35
|
+
*/
|
|
36
|
+
function readerOf(persistence) {
|
|
37
|
+
const { open, inspect } = persistence;
|
|
38
|
+
const idOf = (entry) => 'header' in entry ? entry.header.id : entry.id;
|
|
39
|
+
if (typeof open === 'function') {
|
|
40
|
+
return {
|
|
41
|
+
async list(signal) {
|
|
42
|
+
return (await persistence.list(signal === undefined ? {} : { signal })).map(idOf);
|
|
43
|
+
},
|
|
44
|
+
async read(id, signal) {
|
|
45
|
+
const handle = await open.call(persistence, id, 'read', signal === undefined ? {} : { signal });
|
|
46
|
+
try {
|
|
47
|
+
const { events } = await handle.read();
|
|
48
|
+
return { events, meta: handle.header };
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
// Best-effort teardown: the rows are already collected, so a failing
|
|
52
|
+
// close must not turn a good read into an unreadable session. It
|
|
53
|
+
// still has to run on every path — the host counts a leaked read
|
|
54
|
+
// handle as a resource leak.
|
|
55
|
+
await handle.close().catch(() => { });
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
if (typeof inspect === 'function') {
|
|
61
|
+
return {
|
|
62
|
+
async list(signal) {
|
|
63
|
+
return (await persistence.list(signal)).map(idOf);
|
|
64
|
+
},
|
|
65
|
+
async read(id, signal) {
|
|
66
|
+
return await inspect.call(persistence, id, signal);
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
throw new Error('token-usage: sessionPersistence exposes neither open() (dsh 0.1.3-alpha.1+) nor inspect() (dsh <= 0.1.2-rc.1)');
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The latest-wins `session/title` text of one event, or undefined: the
|
|
74
|
+
* event type is host-merged (`dsh-session-title`), so the plugin reads the
|
|
75
|
+
* payload duck-typed and tolerantly — a non-string or empty title is
|
|
76
|
+
* skipped, never fabricated. Exported for the live recorder, which folds
|
|
77
|
+
* the same event into the same index.
|
|
78
|
+
*/
|
|
79
|
+
export function titleOfEvent(event) {
|
|
80
|
+
if (event.type !== 'session/title')
|
|
81
|
+
return undefined;
|
|
82
|
+
const title = event.data?.title;
|
|
83
|
+
return typeof title === 'string' && title !== '' ? title : undefined;
|
|
84
|
+
}
|
|
18
85
|
/**
|
|
19
86
|
* Append every missing request row. The log's dedupe set is rebuilt from the
|
|
20
87
|
* data files first, so a second run is a no-op and rows recorded live in a
|
|
@@ -28,21 +95,32 @@ import { modelOfEvent, recordOfEvent } from "./usage-record.js";
|
|
|
28
95
|
*/
|
|
29
96
|
export async function syncHistory(deps, onTick, signal) {
|
|
30
97
|
await deps.log.scan();
|
|
31
|
-
|
|
98
|
+
// Snapshot before the walk: only rows already saved are reconcile
|
|
99
|
+
// candidates, so a request landing live mid-walk is never deleted.
|
|
100
|
+
const eligible = deps.log.ids();
|
|
101
|
+
const reader = readerOf(deps.persistence);
|
|
102
|
+
const sessions = await reader.list(signal);
|
|
32
103
|
let added = 0;
|
|
33
104
|
let skipped = 0;
|
|
105
|
+
let removed = 0;
|
|
34
106
|
let failedSessions = 0;
|
|
35
107
|
const total = sessions.length;
|
|
36
108
|
let processed = 0;
|
|
37
|
-
|
|
38
|
-
|
|
109
|
+
/** Every id this walk reproduces; the reconcile pass keeps exactly these. */
|
|
110
|
+
const reproduced = new Set();
|
|
111
|
+
/** Sessions this walk read in full. Only their rows may be reconciled: a
|
|
112
|
+
* row whose session is missing from the list (deleted, or hidden behind a
|
|
113
|
+
* header this build cannot read) is never dropped for its absence. */
|
|
114
|
+
const readable = new Set();
|
|
115
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
116
|
+
for (const id of sessions) {
|
|
39
117
|
signal?.throwIfAborted();
|
|
40
118
|
// One unreadable session log (a format the current dsh build rejects,
|
|
41
119
|
// a torn file, …) must not abort the whole walk: skip the session,
|
|
42
120
|
// report it, and let the rest of the history land.
|
|
43
121
|
let inspection;
|
|
44
122
|
try {
|
|
45
|
-
inspection = await
|
|
123
|
+
inspection = await reader.read(id, signal);
|
|
46
124
|
}
|
|
47
125
|
catch (error) {
|
|
48
126
|
// A cancellation is the caller's (or the host read path's) abort —
|
|
@@ -51,46 +129,90 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
51
129
|
throw error;
|
|
52
130
|
failedSessions += 1;
|
|
53
131
|
processed += 1;
|
|
54
|
-
deps.onSessionFailure?.(
|
|
55
|
-
onTick?.({ processed, total, added, skipped, failedSessions });
|
|
132
|
+
deps.onSessionFailure?.(id, error);
|
|
133
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
56
134
|
continue;
|
|
57
135
|
}
|
|
136
|
+
// The session was read in full: this walk is now the authority for what
|
|
137
|
+
// the ledger must hold, so its stale coordinates become droppable.
|
|
138
|
+
readable.add(id);
|
|
58
139
|
// Last-known route model of this session: failure rows need a model to
|
|
59
140
|
// attribute, and turn/end names none, so the walk follows the same
|
|
60
141
|
// request/context + assistant/message events the live recorder does.
|
|
61
142
|
let model = '';
|
|
143
|
+
// Latest-wins title: title events append in seq order, so the LAST one
|
|
144
|
+
// seen is the current title — a rename, an auto-generated title, and a
|
|
145
|
+
// fallback all land as the same append, one fold covers every source.
|
|
146
|
+
let title;
|
|
62
147
|
for (const event of inspection.events) {
|
|
63
148
|
signal?.throwIfAborted();
|
|
64
149
|
const revealed = modelOfEvent(event);
|
|
65
150
|
if (revealed !== undefined)
|
|
66
151
|
model = revealed;
|
|
67
|
-
const
|
|
152
|
+
const revealedTitle = titleOfEvent(event);
|
|
153
|
+
if (revealedTitle !== undefined)
|
|
154
|
+
title = revealedTitle;
|
|
155
|
+
const record = recordOfEvent(event, id, model, deps.recordCompaction !== false);
|
|
68
156
|
if (record === null)
|
|
69
157
|
continue;
|
|
158
|
+
// Keep the id whether the row was already saved or lands now: the
|
|
159
|
+
// reconcile pass keeps exactly the ids this walk produced.
|
|
160
|
+
reproduced.add(record.requestId);
|
|
70
161
|
if (await deps.log.record(record))
|
|
71
162
|
added += 1;
|
|
72
163
|
else
|
|
73
164
|
skipped += 1;
|
|
74
165
|
}
|
|
166
|
+
// One metadata upsert per session: the title fold above plus the
|
|
167
|
+
// immutable header facts. The upsert is a no-op when nothing changed,
|
|
168
|
+
// so repeat syncs never rewrite the index.
|
|
169
|
+
if (deps.meta !== undefined) {
|
|
170
|
+
const header = inspection.meta;
|
|
171
|
+
const patch = {
|
|
172
|
+
...(title !== undefined ? { title } : {}),
|
|
173
|
+
...(header?.cwd !== undefined && header.cwd !== '' ? { cwd: header.cwd } : {}),
|
|
174
|
+
...(header?.origin !== undefined ? { origin: header.origin } : {}),
|
|
175
|
+
...(header?.parentSession !== undefined && header.parentSession !== '' ? { parentSession: header.parentSession } : {}),
|
|
176
|
+
};
|
|
177
|
+
if (Object.keys(patch).length > 0)
|
|
178
|
+
await deps.meta.upsert(id, patch);
|
|
179
|
+
}
|
|
75
180
|
processed += 1;
|
|
76
|
-
onTick?.({ processed, total, added, skipped, failedSessions });
|
|
181
|
+
onTick?.({ processed, total, added, skipped, removed, failedSessions });
|
|
182
|
+
}
|
|
183
|
+
// Reconcile last, once every readable session has spoken for its rows: a
|
|
184
|
+
// saved row no readable session reproduces is a relic of an older stored
|
|
185
|
+
// format. A session that merely failed to load protects its own rows.
|
|
186
|
+
if (deps.reconcile !== false) {
|
|
187
|
+
removed = await deps.log.reconcile(reproduced, readable, eligible);
|
|
77
188
|
}
|
|
78
|
-
return { added, skipped, failedSessions };
|
|
189
|
+
return { added, skipped, removed, failedSessions };
|
|
79
190
|
}
|
|
80
191
|
/**
|
|
81
|
-
* Run the
|
|
82
|
-
*
|
|
83
|
-
* the
|
|
84
|
-
*
|
|
85
|
-
*
|
|
86
|
-
*
|
|
87
|
-
*
|
|
192
|
+
* Run the gated automatic work, then persist the markers:
|
|
193
|
+
* - No `initializedAt` — the first-run backfill: one full sync (which also
|
|
194
|
+
* folds the metadata), then both markers land together.
|
|
195
|
+
* - `initializedAt` present, `metaSyncedAt` absent — a pre-session-table
|
|
196
|
+
* install owes exactly one metadata backfill: run the same sync once
|
|
197
|
+
* more (every usage row dedupes to a no-op write; the walk lands the
|
|
198
|
+
* titles and header facts the old build never stored), then stamp
|
|
199
|
+
* `metaSyncedAt`.
|
|
200
|
+
* - Both markers present — nothing to do.
|
|
201
|
+
* A crash before the marker write leaves the marker absent, so the next
|
|
202
|
+
* startup re-runs — a no-op thanks to dedupe and idempotent upserts.
|
|
203
|
+
* @param deps - persistence and the shared log (with the metadata sink).
|
|
204
|
+
* @param dir - the data directory holding the markers.
|
|
205
|
+
* @returns the sync outcome, or null when both markers were already set.
|
|
88
206
|
*/
|
|
89
207
|
export async function autoSyncIfNeeded(deps, dir) {
|
|
90
|
-
|
|
208
|
+
const state = await readSyncState(dir);
|
|
209
|
+
if (state !== null && state.metaSyncedAt !== undefined)
|
|
91
210
|
return null;
|
|
92
|
-
const result = await syncHistory(deps);
|
|
93
|
-
|
|
211
|
+
const result = await syncHistory({ ...deps, reconcile: false });
|
|
212
|
+
if (state === null)
|
|
213
|
+
await markInitialized(dir, undefined, true);
|
|
214
|
+
else
|
|
215
|
+
await markMetaSynced(dir);
|
|
94
216
|
return result;
|
|
95
217
|
}
|
|
96
218
|
//# sourceMappingURL=sync.js.map
|
package/lib/sync.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAQH,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChF,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAA;AAkJ/D;;;;;;;;;;;;GAYG;AACH,SAAS,QAAQ,CAAC,WAA4B;IAC5C,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,WAAW,CAAA;IACrC,MAAM,IAAI,GAAG,CAAC,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M,cAAc,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,MAAM,CAAA;AACf,CAAC"}
|
package/lib/usage-log.d.ts
CHANGED
|
@@ -28,6 +28,9 @@ export declare class UsageLog {
|
|
|
28
28
|
private readonly dir;
|
|
29
29
|
private readonly logger;
|
|
30
30
|
private readonly seen;
|
|
31
|
+
/** Owning session of every saved id; the reconcile pass uses it to protect
|
|
32
|
+
* the rows of sessions whose log could not be read. */
|
|
33
|
+
private readonly owners;
|
|
31
34
|
private queue;
|
|
32
35
|
private ready;
|
|
33
36
|
/**
|
|
@@ -37,6 +40,12 @@ export declare class UsageLog {
|
|
|
37
40
|
constructor(dir: string, logger?: LoggerLike);
|
|
38
41
|
/** Whether a request id is already known to this log. */
|
|
39
42
|
has(requestId: string): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Snapshot every saved request id. A reconcile pass takes this *before* the
|
|
45
|
+
* session walk so a row appended by a live request while the walk runs is
|
|
46
|
+
* never a deletion candidate.
|
|
47
|
+
*/
|
|
48
|
+
ids(): ReadonlySet<string>;
|
|
40
49
|
/**
|
|
41
50
|
* Settle every queued append. The chain never rejects (each task absorbs
|
|
42
51
|
* its own failure), so this is the quiescence point a data-directory
|
|
@@ -63,6 +72,32 @@ export declare class UsageLog {
|
|
|
63
72
|
* @returns the number of rows that had to move.
|
|
64
73
|
*/
|
|
65
74
|
refileByEventDay(): Promise<number>;
|
|
75
|
+
/**
|
|
76
|
+
* Drop every saved row that the authoritative session walk did not
|
|
77
|
+
* reproduce. A row whose request id no longer appears in any session log is
|
|
78
|
+
* a relic of an older stored format: the host rewrote the event coordinates
|
|
79
|
+
* when it migrated the log to the current format generation, so the walk
|
|
80
|
+
* reproduces the same requests under new ids.
|
|
81
|
+
*
|
|
82
|
+
* Three guards keep this pass from destroying live data:
|
|
83
|
+
* - only ids in `eligible` (the snapshot taken before the walk) are
|
|
84
|
+
* candidates, so a row a live request appended during the walk survives;
|
|
85
|
+
* - a row is dropped only when its owning session was read **in full** by
|
|
86
|
+
* the walk, so "the walk did not see it" is never inferred from a session
|
|
87
|
+
* that failed to load, from a session missing out of the list (deleted,
|
|
88
|
+
* or hidden behind a header this build cannot read), or from a row whose
|
|
89
|
+
* owner is unknown;
|
|
90
|
+
* - malformed lines are never candidates and stay where they are.
|
|
91
|
+
*
|
|
92
|
+
* A day file is rewritten only when it actually loses a row, and the
|
|
93
|
+
* rewrite is atomic. Runs on the append queue so a live write cannot
|
|
94
|
+
* interleave with it.
|
|
95
|
+
* @param keep - request ids the walk reproduced from readable sessions.
|
|
96
|
+
* @param readableSessions - sessions the walk read in full.
|
|
97
|
+
* @param eligible - the pre-walk snapshot of saved request ids.
|
|
98
|
+
* @returns the number of rows removed.
|
|
99
|
+
*/
|
|
100
|
+
reconcile(keep: ReadonlySet<string>, readableSessions: ReadonlySet<string>, eligible: ReadonlySet<string>): Promise<number>;
|
|
66
101
|
/** The directory is created once and remembered; an external deletion
|
|
67
102
|
* forces a rebuild on the next append (see {@link appendOnce}). */
|
|
68
103
|
private ensureDir;
|
package/lib/usage-log.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-log.d.ts","sourceRoot":"","sources":["../src/usage-log.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAIH,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,UAAU,CAAA;AACzD,OAAO,EAAgC,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAElF,QAAA,MAAM,QAAQ,QAAsC,CAAA;AAEpD,0FAA0F;AAC1F,OAAO,EAAE,QAAQ,EAAE,CAAA;AAEnB,0EAA0E;AAC1E,wBAAgB,WAAW,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAK9C;AAED,4EAA4E;AAC5E,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAMD;;;;;;;GAOG;AACH,qBAAa,QAAQ;
|
|
1
|
+
{"version":3,"file":"usage-log.d.ts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