@laoyuehanni/dsh-token-usage 0.4.12 → 0.4.14
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 +19 -9
- package/README.zh.md +19 -9
- package/lib/aux-request.d.ts +4 -0
- package/lib/aux-request.d.ts.map +1 -1
- package/lib/aux-request.js +1 -0
- package/lib/aux-request.js.map +1 -1
- package/lib/client/DashboardCards.d.ts +18 -10
- package/lib/client/DashboardCards.d.ts.map +1 -1
- package/lib/client/DashboardCards.js +14 -8
- package/lib/client/DashboardCards.js.map +1 -1
- package/lib/client/QuotaButton.d.ts +3 -1
- package/lib/client/QuotaButton.d.ts.map +1 -1
- package/lib/client/QuotaButton.js +23 -9
- package/lib/client/QuotaButton.js.map +1 -1
- package/lib/client/RequestPool.d.ts.map +1 -1
- package/lib/client/RequestPool.js +111 -32
- package/lib/client/RequestPool.js.map +1 -1
- package/lib/client/StatCard.d.ts +8 -10
- package/lib/client/StatCard.d.ts.map +1 -1
- package/lib/client/StatCard.js +10 -13
- package/lib/client/StatCard.js.map +1 -1
- package/lib/client/TokenUsageSection.d.ts.map +1 -1
- package/lib/client/TokenUsageSection.js +25 -14
- package/lib/client/TokenUsageSection.js.map +1 -1
- package/lib/client/UsageRows.d.ts +19 -11
- package/lib/client/UsageRows.d.ts.map +1 -1
- package/lib/client/UsageRows.js +59 -16
- package/lib/client/UsageRows.js.map +1 -1
- package/lib/client/UsageView.js +2 -2
- package/lib/client/UsageView.js.map +1 -1
- package/lib/client/format.d.ts +5 -0
- package/lib/client/format.d.ts.map +1 -1
- package/lib/client/format.js +5 -0
- package/lib/client/format.js.map +1 -1
- package/lib/client/locales.d.ts +17 -2
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/locales.js +34 -4
- package/lib/client/locales.js.map +1 -1
- package/lib/client/quota-format.d.ts +55 -1
- package/lib/client/quota-format.d.ts.map +1 -1
- package/lib/client/quota-format.js +99 -0
- package/lib/client/quota-format.js.map +1 -1
- package/lib/client.js +426 -141
- package/lib/client.js.map +1 -1
- package/lib/compaction-attribution.d.ts +72 -0
- package/lib/compaction-attribution.d.ts.map +1 -0
- package/lib/compaction-attribution.js +82 -0
- package/lib/compaction-attribution.js.map +1 -0
- package/lib/field-completion.d.ts +46 -0
- package/lib/field-completion.d.ts.map +1 -0
- package/lib/field-completion.js +71 -0
- package/lib/field-completion.js.map +1 -0
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +145 -15
- package/lib/index.js.map +1 -1
- package/lib/migrate.d.ts +2 -1
- package/lib/migrate.d.ts.map +1 -1
- package/lib/migrate.js +13 -1
- package/lib/migrate.js.map +1 -1
- package/lib/provider-label.d.ts +20 -0
- package/lib/provider-label.d.ts.map +1 -0
- package/lib/provider-label.js +21 -0
- package/lib/provider-label.js.map +1 -0
- package/lib/provider-names.d.ts +60 -0
- package/lib/provider-names.d.ts.map +1 -0
- package/lib/provider-names.js +156 -0
- package/lib/provider-names.js.map +1 -0
- package/lib/quota/adapters/magpie.d.ts.map +1 -1
- package/lib/quota/adapters/magpie.js +25 -0
- package/lib/quota/adapters/magpie.js.map +1 -1
- package/lib/request-observe.d.ts +16 -1
- package/lib/request-observe.d.ts.map +1 -1
- package/lib/request-observe.js +82 -1
- package/lib/request-observe.js.map +1 -1
- package/lib/rollup.d.ts +10 -4
- package/lib/rollup.d.ts.map +1 -1
- package/lib/rollup.js +21 -4
- package/lib/rollup.js.map +1 -1
- package/lib/session-request-details.d.ts +2 -1
- package/lib/session-request-details.d.ts.map +1 -1
- package/lib/session-request-details.js +8 -0
- package/lib/session-request-details.js.map +1 -1
- package/lib/stats-route.d.ts +4 -0
- package/lib/stats-route.d.ts.map +1 -1
- package/lib/stats-route.js +14 -1
- package/lib/stats-route.js.map +1 -1
- package/lib/stats.d.ts.map +1 -1
- package/lib/stats.js +86 -19
- package/lib/stats.js.map +1 -1
- package/lib/sync-state.d.ts +43 -0
- package/lib/sync-state.d.ts.map +1 -1
- package/lib/sync-state.js +106 -0
- package/lib/sync-state.js.map +1 -1
- package/lib/sync.d.ts.map +1 -1
- package/lib/sync.js +26 -5
- package/lib/sync.js.map +1 -1
- package/lib/usage-log.d.ts +31 -0
- package/lib/usage-log.d.ts.map +1 -1
- package/lib/usage-log.js +172 -8
- package/lib/usage-log.js.map +1 -1
- package/lib/usage-record.d.ts +33 -8
- package/lib/usage-record.d.ts.map +1 -1
- package/lib/usage-record.js +79 -12
- package/lib/usage-record.js.map +1 -1
- package/lib/wire.d.ts +85 -1
- package/lib/wire.d.ts.map +1 -1
- package/lib/wire.js.map +1 -1
- package/package.json +1 -1
package/lib/sync-state.d.ts
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* later sync is the user's decision (the manual command). A missing or
|
|
7
7
|
* malformed marker reads as unmet: the next startup re-runs the gated
|
|
8
8
|
* work, whose dedupe and idempotent upserts make the repetition a no-op.
|
|
9
|
+
* `completedFields` is the field-completion registry's done-set: each id
|
|
10
|
+
* is stamped once every candidate session was readable, or once the
|
|
11
|
+
* completer exhausted its `fieldCompletionAttempts` retry budget for
|
|
12
|
+
* sessions that stay unreadable.
|
|
9
13
|
*
|
|
10
14
|
* @module token-usage/sync-state
|
|
11
15
|
*/
|
|
@@ -23,7 +27,27 @@ export interface SyncState {
|
|
|
23
27
|
/** Epoch milliseconds when timing figures (latencyMs, firstTokenLatencyMs)
|
|
24
28
|
* were backfilled into day files; absent on pre-timing installs. */
|
|
25
29
|
timingSyncedAt?: number;
|
|
30
|
+
/** Field-completer ids whose candidate sessions were all readable on a
|
|
31
|
+
* finished pass, or whose retry budget for unreadable sessions ran out.
|
|
32
|
+
* Absent means none of them have completed. */
|
|
33
|
+
completedFields?: readonly string[];
|
|
34
|
+
/** Consecutive field-completion passes that ended with unreadable
|
|
35
|
+
* candidate sessions, per completer id. Reset by a clean pass; a
|
|
36
|
+
* completer that reaches {@link FIELD_COMPLETION_MAX_ATTEMPTS} is
|
|
37
|
+
* stamped done instead of retried. Absent when nothing is pending. */
|
|
38
|
+
fieldCompletionAttempts?: Readonly<Record<string, number>>;
|
|
26
39
|
}
|
|
40
|
+
/**
|
|
41
|
+
* Retry budget for one field completer: startup passes that each end with
|
|
42
|
+
* unreadable candidate sessions. The pass after the last retry stamps the
|
|
43
|
+
* completer done — a session log that stayed unreadable for this many
|
|
44
|
+
* startups is treated as permanently gone.
|
|
45
|
+
*/
|
|
46
|
+
export declare const FIELD_COMPLETION_MAX_ATTEMPTS = 3;
|
|
47
|
+
/** Completer ids already stamped, ignoring a malformed `completedFields`. */
|
|
48
|
+
export declare function completedFieldIds(state: Pick<SyncState, 'completedFields'> | null): readonly string[];
|
|
49
|
+
/** Completer ids that still owe a pass. */
|
|
50
|
+
export declare function pendingCompleterIds(state: SyncState | null, ids: readonly string[]): string[];
|
|
27
51
|
/**
|
|
28
52
|
* Read the marker file. A missing or malformed file reads as null — the
|
|
29
53
|
* caller treats that as unmet and re-runs the gated work idempotently.
|
|
@@ -68,4 +92,23 @@ export declare function markMetaSynced(dir: string, now?: () => Date): Promise<v
|
|
|
68
92
|
* @param now - clock source (test seam).
|
|
69
93
|
*/
|
|
70
94
|
export declare function markTimingSynced(dir: string, now?: () => Date): Promise<void>;
|
|
95
|
+
/**
|
|
96
|
+
* Fold one field-completion pass into the marker: clean completers are
|
|
97
|
+
* stamped done and their retry counter cleared; completers that still had
|
|
98
|
+
* unreadable candidate sessions advance theirs, and a counter that reaches
|
|
99
|
+
* {@link FIELD_COMPLETION_MAX_ATTEMPTS} stamps the completer done instead —
|
|
100
|
+
* the dead sessions are abandoned, not retried forever. Other markers are
|
|
101
|
+
* preserved. A missing marker is left missing: inventing `initializedAt`
|
|
102
|
+
* would make the first-run sync look finished. The startup pass only calls
|
|
103
|
+
* this after that sync has already stamped the file.
|
|
104
|
+
* @param dir - the data directory holding the marker.
|
|
105
|
+
* @param outcome - what the pass proved, per completer id.
|
|
106
|
+
* @returns the completer ids this call newly stamped done (including
|
|
107
|
+
* retry-budget exhaustions); empty when the marker was missing or nothing
|
|
108
|
+
* settled.
|
|
109
|
+
*/
|
|
110
|
+
export declare function markFieldCompletionOutcome(dir: string, outcome: {
|
|
111
|
+
cleanIds: readonly string[];
|
|
112
|
+
retriedIds: readonly string[];
|
|
113
|
+
}): Promise<readonly string[]>;
|
|
71
114
|
//# sourceMappingURL=sync-state.d.ts.map
|
package/lib/sync-state.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync-state.d.ts","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"sync-state.d.ts","sourceRoot":"","sources":["../src/sync-state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAiB,KAAK,UAAU,EAAE,MAAM,UAAU,CAAA;AAKzD;;;mEAGmE;AACnE,MAAM,WAAW,SAAS;IACxB,kEAAkE;IAClE,aAAa,EAAE,MAAM,CAAA;IACrB;gEAC4D;IAC5D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB;wEACoE;IACpE,cAAc,CAAC,EAAE,MAAM,CAAA;IACvB;;mDAE+C;IAC/C,eAAe,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACnC;;;0EAGsE;IACtE,uBAAuB,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;CAC3D;AAED;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,IAAI,CAAA;AAQ9C,6EAA6E;AAC7E,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,IAAI,CAAC,SAAS,EAAE,iBAAiB,CAAC,GAAG,IAAI,GAAG,SAAS,MAAM,EAAE,CAIrG;AA8BD,2CAA2C;AAC3C,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,EAAE,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAG7F;AAED;;;;GAIG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,UAA0B,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAiB9G;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,GAAE,UAA0B,GAAG,OAAO,CAAC,OAAO,CAAC,CAErG;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC,CAKjF;AAED;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,MAAM,EACX,GAAG,GAAE,MAAM,IAAuB,EAClC,QAAQ,UAAQ,EAChB,UAAU,UAAQ,GACjB,OAAO,CAAC,IAAI,CAAC,CAaf;AAED;;;;GAIG;AACH,wBAAsB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAM,IAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAUnG;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAM,IAAuB,GAAG,OAAO,CAAC,IAAI,CAAC,CAUrG;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,0BAA0B,CAC9C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE;IAAE,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GACtE,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC,CA6B5B"}
|
package/lib/sync-state.js
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
* later sync is the user's decision (the manual command). A missing or
|
|
7
7
|
* malformed marker reads as unmet: the next startup re-runs the gated
|
|
8
8
|
* work, whose dedupe and idempotent upserts make the repetition a no-op.
|
|
9
|
+
* `completedFields` is the field-completion registry's done-set: each id
|
|
10
|
+
* is stamped once every candidate session was readable, or once the
|
|
11
|
+
* completer exhausted its `fieldCompletionAttempts` retry budget for
|
|
12
|
+
* sessions that stay unreadable.
|
|
9
13
|
*
|
|
10
14
|
* @module token-usage/sync-state
|
|
11
15
|
*/
|
|
@@ -14,12 +18,59 @@ import { join } from 'node:path';
|
|
|
14
18
|
import { consoleLogger } from "./log.js";
|
|
15
19
|
const STATE_FILE = 'state.json';
|
|
16
20
|
const TMP_FILE = 'state.json.tmp';
|
|
21
|
+
/**
|
|
22
|
+
* Retry budget for one field completer: startup passes that each end with
|
|
23
|
+
* unreadable candidate sessions. The pass after the last retry stamps the
|
|
24
|
+
* completer done — a session log that stayed unreadable for this many
|
|
25
|
+
* startups is treated as permanently gone.
|
|
26
|
+
*/
|
|
27
|
+
export const FIELD_COMPLETION_MAX_ATTEMPTS = 3;
|
|
17
28
|
function isSyncState(value) {
|
|
18
29
|
if (typeof value !== 'object' || value === null)
|
|
19
30
|
return false;
|
|
20
31
|
const state = value;
|
|
21
32
|
return typeof state.initializedAt === 'number' && Number.isFinite(state.initializedAt);
|
|
22
33
|
}
|
|
34
|
+
/** Completer ids already stamped, ignoring a malformed `completedFields`. */
|
|
35
|
+
export function completedFieldIds(state) {
|
|
36
|
+
const raw = state?.completedFields;
|
|
37
|
+
if (!Array.isArray(raw))
|
|
38
|
+
return [];
|
|
39
|
+
return raw.filter((id) => typeof id === 'string' && id !== '');
|
|
40
|
+
}
|
|
41
|
+
/** The done-set as a writable field, omitted when empty so older markers stay unchanged. */
|
|
42
|
+
function completedFieldsOf(state) {
|
|
43
|
+
const ids = completedFieldIds(state);
|
|
44
|
+
return ids.length > 0 ? { completedFields: [...ids] } : {};
|
|
45
|
+
}
|
|
46
|
+
/** Consecutive-failure counters as a plain record, ignoring a malformed map
|
|
47
|
+
* and clamping out-of-range values to a fresh count. */
|
|
48
|
+
function fieldAttemptsOf(state) {
|
|
49
|
+
const raw = state?.fieldCompletionAttempts;
|
|
50
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
|
|
51
|
+
return {};
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const [id, count] of Object.entries(raw)) {
|
|
54
|
+
if (id === '' || typeof count !== 'number' || !Number.isFinite(count) || count < 1)
|
|
55
|
+
continue;
|
|
56
|
+
out[id] = Math.floor(count);
|
|
57
|
+
}
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
/** The attempt map as a writable field, omitted when empty. */
|
|
61
|
+
function fieldAttemptsField(attempts) {
|
|
62
|
+
const kept = {};
|
|
63
|
+
for (const [id, count] of Object.entries(attempts)) {
|
|
64
|
+
if (count > 0)
|
|
65
|
+
kept[id] = count;
|
|
66
|
+
}
|
|
67
|
+
return Object.keys(kept).length > 0 ? { fieldCompletionAttempts: kept } : {};
|
|
68
|
+
}
|
|
69
|
+
/** Completer ids that still owe a pass. */
|
|
70
|
+
export function pendingCompleterIds(state, ids) {
|
|
71
|
+
const done = new Set(completedFieldIds(state));
|
|
72
|
+
return ids.filter(id => !done.has(id));
|
|
73
|
+
}
|
|
23
74
|
/**
|
|
24
75
|
* Read the marker file. A missing or malformed file reads as null — the
|
|
25
76
|
* caller treats that as unmet and re-runs the gated work idempotently.
|
|
@@ -88,6 +139,8 @@ export async function markInitialized(dir, now = () => new Date(), withMeta = fa
|
|
|
88
139
|
...(existing?.timingSyncedAt !== undefined
|
|
89
140
|
? { timingSyncedAt: existing.timingSyncedAt }
|
|
90
141
|
: withTiming ? { timingSyncedAt: now().getTime() } : {}),
|
|
142
|
+
...completedFieldsOf(existing),
|
|
143
|
+
...fieldAttemptsField(fieldAttemptsOf(existing)),
|
|
91
144
|
});
|
|
92
145
|
}
|
|
93
146
|
/**
|
|
@@ -102,6 +155,8 @@ export async function markMetaSynced(dir, now = () => new Date()) {
|
|
|
102
155
|
initializedAt,
|
|
103
156
|
metaSyncedAt: now().getTime(),
|
|
104
157
|
...(existing?.timingSyncedAt !== undefined ? { timingSyncedAt: existing.timingSyncedAt } : {}),
|
|
158
|
+
...completedFieldsOf(existing),
|
|
159
|
+
...fieldAttemptsField(fieldAttemptsOf(existing)),
|
|
105
160
|
});
|
|
106
161
|
}
|
|
107
162
|
/**
|
|
@@ -116,6 +171,57 @@ export async function markTimingSynced(dir, now = () => new Date()) {
|
|
|
116
171
|
initializedAt,
|
|
117
172
|
...(existing?.metaSyncedAt !== undefined ? { metaSyncedAt: existing.metaSyncedAt } : {}),
|
|
118
173
|
timingSyncedAt: now().getTime(),
|
|
174
|
+
...completedFieldsOf(existing),
|
|
175
|
+
...fieldAttemptsField(fieldAttemptsOf(existing)),
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Fold one field-completion pass into the marker: clean completers are
|
|
180
|
+
* stamped done and their retry counter cleared; completers that still had
|
|
181
|
+
* unreadable candidate sessions advance theirs, and a counter that reaches
|
|
182
|
+
* {@link FIELD_COMPLETION_MAX_ATTEMPTS} stamps the completer done instead —
|
|
183
|
+
* the dead sessions are abandoned, not retried forever. Other markers are
|
|
184
|
+
* preserved. A missing marker is left missing: inventing `initializedAt`
|
|
185
|
+
* would make the first-run sync look finished. The startup pass only calls
|
|
186
|
+
* this after that sync has already stamped the file.
|
|
187
|
+
* @param dir - the data directory holding the marker.
|
|
188
|
+
* @param outcome - what the pass proved, per completer id.
|
|
189
|
+
* @returns the completer ids this call newly stamped done (including
|
|
190
|
+
* retry-budget exhaustions); empty when the marker was missing or nothing
|
|
191
|
+
* settled.
|
|
192
|
+
*/
|
|
193
|
+
export async function markFieldCompletionOutcome(dir, outcome) {
|
|
194
|
+
const existing = await readSyncState(dir);
|
|
195
|
+
if (existing === null)
|
|
196
|
+
return [];
|
|
197
|
+
const stamped = new Set(completedFieldIds(existing));
|
|
198
|
+
const attempts = fieldAttemptsOf(existing);
|
|
199
|
+
const newlyStamped = [];
|
|
200
|
+
for (const id of outcome.cleanIds) {
|
|
201
|
+
if (id === '')
|
|
202
|
+
continue;
|
|
203
|
+
if (!stamped.has(id))
|
|
204
|
+
newlyStamped.push(id);
|
|
205
|
+
stamped.add(id);
|
|
206
|
+
delete attempts[id];
|
|
207
|
+
}
|
|
208
|
+
for (const id of outcome.retriedIds) {
|
|
209
|
+
if (id === '' || stamped.has(id))
|
|
210
|
+
continue;
|
|
211
|
+
attempts[id] = (attempts[id] ?? 0) + 1;
|
|
212
|
+
if (attempts[id] >= FIELD_COMPLETION_MAX_ATTEMPTS) {
|
|
213
|
+
stamped.add(id);
|
|
214
|
+
newlyStamped.push(id);
|
|
215
|
+
delete attempts[id];
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
await writeSyncState(dir, {
|
|
219
|
+
initializedAt: existing.initializedAt,
|
|
220
|
+
...(existing.metaSyncedAt !== undefined ? { metaSyncedAt: existing.metaSyncedAt } : {}),
|
|
221
|
+
...(existing.timingSyncedAt !== undefined ? { timingSyncedAt: existing.timingSyncedAt } : {}),
|
|
222
|
+
...completedFieldsOf({ completedFields: [...stamped] }),
|
|
223
|
+
...fieldAttemptsField(attempts),
|
|
119
224
|
});
|
|
225
|
+
return newlyStamped;
|
|
120
226
|
}
|
|
121
227
|
//# 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;;;;;;;;;;;;;;GAcG;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;AA0BjC;;;;;GAK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AAC"}
|
package/lib/sync.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;
|
|
1
|
+
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AASvE,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,WAAW,gBAAgB;IAC/B,uCAAuC;IACvC,SAAS,EAAE,MAAM,CAAA;IACjB,qEAAqE;IACrE,KAAK,EAAE,MAAM,CAAA;IACb,uCAAuC;IACvC,KAAK,EAAE,MAAM,CAAA;IACb,qCAAqC;IACrC,OAAO,EAAE,MAAM,CAAA;IACf;8EAC0E;IAC1E,OAAO,EAAE,MAAM,CAAA;IACf;iEAC6D;IAC7D,cAAc,EAAE,MAAM,CAAA;CACvB;AAED;;;;;GAKG;AACH,MAAM,WAAW,kBAAkB;IACjC,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,aAAa,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;yDACyD;AACzD,MAAM,WAAW,YAAY;IAC3B,MAAM,CAAC,EAAE,EAAE,MAA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ANGED
|
@@ -18,7 +18,8 @@
|
|
|
18
18
|
* @module token-usage/sync
|
|
19
19
|
*/
|
|
20
20
|
import { markInitialized, markMetaSynced, readSyncState } from "./sync-state.js";
|
|
21
|
-
import {
|
|
21
|
+
import { CompactionAttributionWindow } from "./compaction-attribution.js";
|
|
22
|
+
import { extractFirstTokenTimeFromStream, modelOfEvent, providerOfEvent, recordOfEvent } from "./usage-record.js";
|
|
22
23
|
/**
|
|
23
24
|
* Normalize the handle persistence seam into the generation-free read surface
|
|
24
25
|
* {@link syncHistory} walks.
|
|
@@ -116,15 +117,21 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
116
117
|
// The session was read in full: this walk is now the authority for what
|
|
117
118
|
// the ledger must hold, so its stale coordinates become droppable.
|
|
118
119
|
readable.add(id);
|
|
119
|
-
// Last-known route
|
|
120
|
-
//
|
|
121
|
-
//
|
|
120
|
+
// Last-known route of this session: a turn/end error names neither a
|
|
121
|
+
// model nor a provider, so the walk follows the same request/context +
|
|
122
|
+
// assistant/message events the live recorder does. Compaction and
|
|
123
|
+
// llm/retry carry their own route on the event and do not move this.
|
|
122
124
|
let model = '';
|
|
125
|
+
let provider = '';
|
|
123
126
|
// Latest-wins title: title events append in seq order, so the LAST one
|
|
124
127
|
// seen is the current title — a rename, an auto-generated title, and a
|
|
125
128
|
// fallback all land as the same append, one fold covers every source.
|
|
126
129
|
let title;
|
|
127
130
|
let openStep = null;
|
|
131
|
+
// The compaction attribution window of this session — the SAME
|
|
132
|
+
// implementation the live recorder drives, so a rescan attributes rows
|
|
133
|
+
// exactly like a live observation would.
|
|
134
|
+
const attributionWindow = new CompactionAttributionWindow();
|
|
128
135
|
for (const event of inspection.events) {
|
|
129
136
|
signal?.throwIfAborted();
|
|
130
137
|
if (event.type === 'step/start') {
|
|
@@ -137,6 +144,9 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
137
144
|
const revealed = modelOfEvent(event);
|
|
138
145
|
if (revealed !== undefined)
|
|
139
146
|
model = revealed;
|
|
147
|
+
const revealedProvider = providerOfEvent(event);
|
|
148
|
+
if (revealedProvider !== undefined)
|
|
149
|
+
provider = revealedProvider;
|
|
140
150
|
const revealedTitle = titleOfEvent(event);
|
|
141
151
|
if (revealedTitle !== undefined)
|
|
142
152
|
title = revealedTitle;
|
|
@@ -162,9 +172,20 @@ export async function syncHistory(deps, onTick, signal) {
|
|
|
162
172
|
else if (event.type === 'step/end' || event.type === 'turn/end') {
|
|
163
173
|
openStep = null;
|
|
164
174
|
}
|
|
165
|
-
|
|
175
|
+
attributionWindow.observe(event);
|
|
176
|
+
const record = recordOfEvent(event, id, model, deps.recordCompaction !== false, timing, provider);
|
|
166
177
|
if (record === null)
|
|
167
178
|
continue;
|
|
179
|
+
// Attribution attaches to plain-request rows only (same rule as the
|
|
180
|
+
// live recorder): the compaction row is the rewrite's own billing row,
|
|
181
|
+
// a failure row has no cache figures to explain. Rows already saved
|
|
182
|
+
// dedupe below — the attribution lands on the first write, and rows
|
|
183
|
+
// persisted before this field stay unattributed (never rewritten).
|
|
184
|
+
if (record.kind === undefined || record.kind === 'request') {
|
|
185
|
+
const attribution = attributionWindow.consumeForRequest();
|
|
186
|
+
if (attribution !== undefined)
|
|
187
|
+
record.compactionAttribution = attribution;
|
|
188
|
+
}
|
|
168
189
|
// Keep the id whether the row was already saved or lands now: the
|
|
169
190
|
// reconcile pass keeps exactly the ids this walk produced.
|
|
170
191
|
reproduced.add(record.requestId);
|
package/lib/sync.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAQH,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAChF,OAAO,EAAE,+BAA+B,EAAE,YAAY,EAAE,aAAa,EAAsB,MAAM,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"sync.js","sourceR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OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,CAAA;AACpD,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,IAAc,EAAE,GAAW;IAChE,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,GAAG,CAAC,CAAA;IACtC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,CAAC,YAAY,KAAK,SAAS;QAAE,OAAO,IAAI,CAAA;IACnE,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,EAAE,GAAG,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAA;IAC/D,IAAI,KAAK,KAAK,IAAI;QAAE,MAAM,eAAe,CAAC,GAAG,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,CAAC,CAAA;;QAChE,MAAM,cAAc,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,MAAM,CAAA;AACf,CAAC"}
|
package/lib/usage-log.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { type LoggerLike } from './log.ts';
|
|
11
11
|
import { type UsageRecord } from './usage-record.ts';
|
|
12
12
|
import { type SyncPersistence } from './sync.ts';
|
|
13
|
+
import type { FieldCompleter } from './field-completion.ts';
|
|
13
14
|
declare const DAY_FILE: RegExp;
|
|
14
15
|
/** Test for this store's per-day file names; the migration shares the naming contract. */
|
|
15
16
|
export { DAY_FILE };
|
|
@@ -81,6 +82,14 @@ export declare class UsageLog {
|
|
|
81
82
|
* @returns the number of rows that were backfilled with timing.
|
|
82
83
|
*/
|
|
83
84
|
backfillTiming(persistence: SyncPersistence): Promise<number>;
|
|
85
|
+
/**
|
|
86
|
+
* Fill absent fields declared by `completers` from the session logs.
|
|
87
|
+
* Runs on the append queue. A thrown walk reports nothing settled, so
|
|
88
|
+
* the caller does not stamp the pass and the next startup retries it.
|
|
89
|
+
* @param persistence - host session persistence.
|
|
90
|
+
* @param completers - the still-pending completers.
|
|
91
|
+
*/
|
|
92
|
+
completeFields(persistence: SyncPersistence, completers: readonly FieldCompleter[]): Promise<FieldCompletionResult>;
|
|
84
93
|
/**
|
|
85
94
|
* Drop every saved row that the authoritative session walk did not
|
|
86
95
|
* reproduce. A row whose request id no longer appears in any session log is
|
|
@@ -125,4 +134,26 @@ export declare class UsageLog {
|
|
|
125
134
|
* from session persistence events, and rewrite touched day files atomically.
|
|
126
135
|
*/
|
|
127
136
|
export declare function backfillDayFilesTiming(dir: string, persistence: SyncPersistence, logger?: LoggerLike): Promise<number>;
|
|
137
|
+
/** What one field-completion pass did, per completer: `cleanIds` settled
|
|
138
|
+
* with every candidate session readable; `retriedIds` still had unreadable
|
|
139
|
+
* candidate sessions, so the caller decides via its retry budget whether
|
|
140
|
+
* to stamp or re-run them. */
|
|
141
|
+
export interface FieldCompletionResult {
|
|
142
|
+
/** Rows that gained at least one field. */
|
|
143
|
+
patched: number;
|
|
144
|
+
/** Completer ids whose every candidate session was readable. */
|
|
145
|
+
cleanIds: readonly string[];
|
|
146
|
+
/** Completer ids with at least one unreadable candidate session. */
|
|
147
|
+
retriedIds: readonly string[];
|
|
148
|
+
/** Candidate sessions whose log could not be read. */
|
|
149
|
+
failedSessions: number;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Fill absent fields from session logs. A day file is rewritten only when a
|
|
153
|
+
* row changed. An unreadable session does not block the others; it moves
|
|
154
|
+
* the completer from `cleanIds` to `retriedIds` so the caller's retry
|
|
155
|
+
* budget, not this walk, decides when the completer settles. Rows the
|
|
156
|
+
* walk cannot prove stay blank; that does not block settlement.
|
|
157
|
+
*/
|
|
158
|
+
export declare function completeDayFiles(dir: string, persistence: SyncPersistence, completers: readonly FieldCompleter[], logger?: LoggerLike): Promise<FieldCompletionResult>;
|
|
128
159
|
//# sourceMappingURL=usage-log.d.ts.map
|
package/lib/usage-log.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-log.d.ts","sourceRoot":"","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EAAE,MAAM,EACX,WAAW,EAAE,eAAe,EAC5B,UAAU,EAAE,SAAS,cAAc,EAAE,EACrC,MAAM,GAAE,UAA0B,GACjC,OAAO,CAAC,qBAAqB,CAAC,CAoGhC"}
|
package/lib/usage-log.js
CHANGED
|
@@ -175,6 +175,25 @@ export class UsageLog {
|
|
|
175
175
|
return 0;
|
|
176
176
|
});
|
|
177
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Fill absent fields declared by `completers` from the session logs.
|
|
180
|
+
* Runs on the append queue. A thrown walk reports nothing settled, so
|
|
181
|
+
* the caller does not stamp the pass and the next startup retries it.
|
|
182
|
+
* @param persistence - host session persistence.
|
|
183
|
+
* @param completers - the still-pending completers.
|
|
184
|
+
*/
|
|
185
|
+
completeFields(persistence, completers) {
|
|
186
|
+
let result = { patched: 0, cleanIds: [], retriedIds: [], failedSessions: 0 };
|
|
187
|
+
const task = this.queue.then(async () => {
|
|
188
|
+
await this.ensureDir();
|
|
189
|
+
result = await completeDayFiles(this.dir, persistence, completers, this.logger);
|
|
190
|
+
});
|
|
191
|
+
this.queue = task.catch(() => { });
|
|
192
|
+
return task.then(() => result).catch((error) => {
|
|
193
|
+
this.logger.error('[token-usage] field completion failed:', error);
|
|
194
|
+
return { patched: 0, cleanIds: [], retriedIds: [], failedSessions: 0 };
|
|
195
|
+
});
|
|
196
|
+
}
|
|
178
197
|
/**
|
|
179
198
|
* Drop every saved row that the authoritative session walk did not
|
|
180
199
|
* reproduce. A row whose request id no longer appears in any session log is
|
|
@@ -262,6 +281,29 @@ async function readDayLines(dir, name, logger) {
|
|
|
262
281
|
}
|
|
263
282
|
return lines;
|
|
264
283
|
}
|
|
284
|
+
/**
|
|
285
|
+
* Replace a file with new content, atomically for the reader: the new bytes
|
|
286
|
+
* land in a sibling temp file, and the rename swaps it in. `rename` replaces
|
|
287
|
+
* an existing target on Windows (MoveFileEx + REPLACE_EXISTING), so no window
|
|
288
|
+
* exists in which the day file is missing — unlinking the target first would
|
|
289
|
+
* drop every row of that day should the process die between the two calls.
|
|
290
|
+
* The unlink survives only as a fallback for filesystems that refuse to
|
|
291
|
+
* overwrite.
|
|
292
|
+
* @param tmp - the temp file holding the new content.
|
|
293
|
+
* @param target - the file to replace.
|
|
294
|
+
*/
|
|
295
|
+
async function replaceFile(tmp, target) {
|
|
296
|
+
try {
|
|
297
|
+
await rename(tmp, target);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
const code = error.code;
|
|
301
|
+
if (code !== 'EPERM' && code !== 'EEXIST' && code !== 'EACCES')
|
|
302
|
+
throw error;
|
|
303
|
+
await unlink(target).catch(() => undefined);
|
|
304
|
+
await rename(tmp, target);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
265
307
|
async function rewriteDayFile(dir, name, records) {
|
|
266
308
|
const target = join(dir, name);
|
|
267
309
|
if (records.length === 0) {
|
|
@@ -270,8 +312,7 @@ async function rewriteDayFile(dir, name, records) {
|
|
|
270
312
|
}
|
|
271
313
|
const tmp = join(dir, `${name}.tmp`);
|
|
272
314
|
await writeFile(tmp, `${records.map(serializeRecord).join('\n')}\n`, 'utf8');
|
|
273
|
-
await
|
|
274
|
-
await rename(tmp, target);
|
|
315
|
+
await replaceFile(tmp, target);
|
|
275
316
|
}
|
|
276
317
|
/**
|
|
277
318
|
* Redistribute parsed rows onto the day file their event time names.
|
|
@@ -322,8 +363,7 @@ async function refileDayFiles(dir, logger) {
|
|
|
322
363
|
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
323
364
|
const tmp = join(dir, `${source}.tmp`);
|
|
324
365
|
await writeFile(tmp, body, 'utf8');
|
|
325
|
-
await
|
|
326
|
-
await rename(tmp, target);
|
|
366
|
+
await replaceFile(tmp, target);
|
|
327
367
|
}
|
|
328
368
|
else {
|
|
329
369
|
await rewriteDayFile(dir, source, stay);
|
|
@@ -375,8 +415,7 @@ async function reconcileDayFiles(dir, sets, logger) {
|
|
|
375
415
|
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
376
416
|
const tmp = join(dir, `${name}.tmp`);
|
|
377
417
|
await writeFile(tmp, body, 'utf8');
|
|
378
|
-
await
|
|
379
|
-
await rename(tmp, target);
|
|
418
|
+
await replaceFile(tmp, target);
|
|
380
419
|
}
|
|
381
420
|
else {
|
|
382
421
|
await rewriteDayFile(dir, name, stay);
|
|
@@ -481,8 +520,7 @@ export async function backfillDayFilesTiming(dir, persistence, logger = consoleL
|
|
|
481
520
|
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
482
521
|
const tmp = join(dir, `${name}.tmp`);
|
|
483
522
|
await writeFile(tmp, body, 'utf8');
|
|
484
|
-
await
|
|
485
|
-
await rename(tmp, target);
|
|
523
|
+
await replaceFile(tmp, target);
|
|
486
524
|
}
|
|
487
525
|
else {
|
|
488
526
|
await rewriteDayFile(dir, name, stay);
|
|
@@ -490,4 +528,130 @@ export async function backfillDayFilesTiming(dir, persistence, logger = consoleL
|
|
|
490
528
|
}
|
|
491
529
|
return patchedCount;
|
|
492
530
|
}
|
|
531
|
+
/**
|
|
532
|
+
* Fill absent fields from session logs. A day file is rewritten only when a
|
|
533
|
+
* row changed. An unreadable session does not block the others; it moves
|
|
534
|
+
* the completer from `cleanIds` to `retriedIds` so the caller's retry
|
|
535
|
+
* budget, not this walk, decides when the completer settles. Rows the
|
|
536
|
+
* walk cannot prove stay blank; that does not block settlement.
|
|
537
|
+
*/
|
|
538
|
+
export async function completeDayFiles(dir, persistence, completers, logger = consoleLogger) {
|
|
539
|
+
const none = { patched: 0, cleanIds: [], retriedIds: [], failedSessions: 0 };
|
|
540
|
+
if (completers.length === 0)
|
|
541
|
+
return none;
|
|
542
|
+
let names;
|
|
543
|
+
try {
|
|
544
|
+
names = (await readdir(dir)).filter(name => DAY_FILE.test(name)).sort();
|
|
545
|
+
}
|
|
546
|
+
catch (error) {
|
|
547
|
+
logger.error('[token-usage] cannot list data dir ' + dir + ':', error);
|
|
548
|
+
return none;
|
|
549
|
+
}
|
|
550
|
+
const fileLines = new Map();
|
|
551
|
+
const candidates = new Map();
|
|
552
|
+
for (const name of names) {
|
|
553
|
+
const lines = await readDayLines(dir, name, logger);
|
|
554
|
+
let fileHasCandidate = false;
|
|
555
|
+
for (const line of lines) {
|
|
556
|
+
const record = line.record;
|
|
557
|
+
if (record === null)
|
|
558
|
+
continue;
|
|
559
|
+
for (const completer of completers) {
|
|
560
|
+
if (!completer.needs(record))
|
|
561
|
+
continue;
|
|
562
|
+
fileHasCandidate = true;
|
|
563
|
+
let sessions = candidates.get(completer.id);
|
|
564
|
+
if (sessions === undefined) {
|
|
565
|
+
sessions = new Set();
|
|
566
|
+
candidates.set(completer.id, sessions);
|
|
567
|
+
}
|
|
568
|
+
sessions.add(record.sessionId);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
if (fileHasCandidate)
|
|
572
|
+
fileLines.set(name, lines);
|
|
573
|
+
}
|
|
574
|
+
if (fileLines.size === 0) {
|
|
575
|
+
return { patched: 0, cleanIds: completers.map(completer => completer.id), retriedIds: [], failedSessions: 0 };
|
|
576
|
+
}
|
|
577
|
+
const reader = readerOf(persistence);
|
|
578
|
+
const sessions = new Set();
|
|
579
|
+
for (const ids of candidates.values())
|
|
580
|
+
for (const id of ids)
|
|
581
|
+
sessions.add(id);
|
|
582
|
+
const failed = new Set();
|
|
583
|
+
const changedFiles = new Set();
|
|
584
|
+
let patched = 0;
|
|
585
|
+
for (const sessionId of sessions) {
|
|
586
|
+
let events;
|
|
587
|
+
try {
|
|
588
|
+
events = (await reader.read(sessionId)).events;
|
|
589
|
+
}
|
|
590
|
+
catch (error) {
|
|
591
|
+
failed.add(sessionId);
|
|
592
|
+
logger.warn(`[token-usage] session ${sessionId} unreadable during field completion, skipped:`, error instanceof Error ? error.message : String(error));
|
|
593
|
+
continue;
|
|
594
|
+
}
|
|
595
|
+
const proofs = new Map();
|
|
596
|
+
for (const completer of completers) {
|
|
597
|
+
if (!candidates.get(completer.id)?.has(sessionId))
|
|
598
|
+
continue;
|
|
599
|
+
proofs.set(completer.id, completer.prove(sessionId, events));
|
|
600
|
+
}
|
|
601
|
+
for (const [name, lines] of fileLines) {
|
|
602
|
+
let fileChanged = false;
|
|
603
|
+
for (const line of lines) {
|
|
604
|
+
const record = line.record;
|
|
605
|
+
if (record === null || record.sessionId !== sessionId)
|
|
606
|
+
continue;
|
|
607
|
+
let rowChanged = false;
|
|
608
|
+
for (const completer of completers) {
|
|
609
|
+
if (!completer.needs(record))
|
|
610
|
+
continue;
|
|
611
|
+
const proof = proofs.get(completer.id)?.get(record.requestId);
|
|
612
|
+
if (proof === undefined)
|
|
613
|
+
continue;
|
|
614
|
+
if (completer.fill(record, proof))
|
|
615
|
+
rowChanged = true;
|
|
616
|
+
}
|
|
617
|
+
if (rowChanged) {
|
|
618
|
+
patched += 1;
|
|
619
|
+
fileChanged = true;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (fileChanged)
|
|
623
|
+
changedFiles.add(name);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
for (const name of changedFiles) {
|
|
627
|
+
const lines = fileLines.get(name);
|
|
628
|
+
if (lines === undefined)
|
|
629
|
+
continue;
|
|
630
|
+
const stay = [];
|
|
631
|
+
const stray = [];
|
|
632
|
+
for (const line of lines) {
|
|
633
|
+
if (line.record === null)
|
|
634
|
+
stray.push(line.raw);
|
|
635
|
+
else
|
|
636
|
+
stay.push(line.record);
|
|
637
|
+
}
|
|
638
|
+
if (stray.length > 0) {
|
|
639
|
+
const target = join(dir, name);
|
|
640
|
+
const body = `${stay.map(serializeRecord).join('\n')}${stay.length > 0 ? '\n' : ''}${stray.join('\n')}\n`;
|
|
641
|
+
const tmp = join(dir, `${name}.tmp`);
|
|
642
|
+
await writeFile(tmp, body, 'utf8');
|
|
643
|
+
await replaceFile(tmp, target);
|
|
644
|
+
}
|
|
645
|
+
else {
|
|
646
|
+
await rewriteDayFile(dir, name, stay);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
const cleanIds = [];
|
|
650
|
+
const retriedIds = [];
|
|
651
|
+
for (const completer of completers) {
|
|
652
|
+
const hasFailedCandidate = [...(candidates.get(completer.id) ?? [])].some(id => failed.has(id));
|
|
653
|
+
(hasFailedCandidate ? retriedIds : cleanIds).push(completer.id);
|
|
654
|
+
}
|
|
655
|
+
return { patched, cleanIds, retriedIds, failedSessions: failed.size };
|
|
656
|
+
}
|
|
493
657
|
//# sourceMappingURL=usage-log.js.map
|