@agent-watch-ai/edge 0.7.0 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/README.md +4 -1
- package/dist/billing/session-billing.d.ts +5 -2
- package/dist/billing/session-billing.js +27 -6
- package/dist/capture/capture-env.d.ts +3 -3
- package/dist/capture/capture-env.js +5 -5
- package/dist/capture/captured-step.js +24 -0
- package/dist/capture/constants/capture.constants.d.ts +15 -0
- package/dist/capture/constants/capture.constants.js +15 -0
- package/dist/capture/launched-runs.d.ts +27 -0
- package/dist/capture/launched-runs.js +15 -9
- package/dist/capture/python/sitecustomize.py +11 -2
- package/dist/capture/venv-loader.d.ts +68 -0
- package/dist/capture/venv-loader.js +189 -0
- package/dist/cli/constants/cli.constants.d.ts +21 -0
- package/dist/cli/constants/cli.constants.js +22 -1
- package/dist/cli/doctor-run-capture.d.ts +8 -0
- package/dist/cli/doctor-run-capture.js +14 -0
- package/dist/cli/doctor.js +6 -2
- package/dist/cli/hook-check.d.ts +7 -2
- package/dist/cli/hook-check.js +30 -15
- package/dist/cli/hook.js +44 -3
- package/dist/cli/npm-global.d.ts +24 -0
- package/dist/cli/npm-global.js +77 -0
- package/dist/cli/npx-install.js +22 -6
- package/dist/cli/replay.js +42 -7
- package/dist/cli/setup.js +71 -7
- package/dist/cli/types/cli.types.d.ts +2 -0
- package/dist/cli/uninstall.js +34 -1
- package/dist/cli/update.js +3 -2
- package/dist/cli.js +4 -1
- package/dist/config/config-store.d.ts +15 -4
- package/dist/config/config-store.js +31 -7
- package/dist/config/config.d.ts +8 -0
- package/dist/config/config.js +10 -0
- package/dist/config/constants/config.constants.d.ts +13 -1
- package/dist/config/constants/config.constants.js +13 -1
- package/dist/config/repo-config.js +7 -2
- package/dist/config/schemas/config.schema.d.ts +6 -2
- package/dist/config/schemas/config.schema.js +17 -3
- package/dist/credentials/cloud-claim.d.ts +2 -0
- package/dist/credentials/cloud-claim.js +21 -2
- package/dist/credentials/constants/credentials.constants.d.ts +8 -0
- package/dist/credentials/constants/credentials.constants.js +8 -0
- package/dist/credentials/credential-status.js +1 -1
- package/dist/credentials/credentials.d.ts +3 -3
- package/dist/credentials/credentials.js +26 -12
- package/dist/credentials/identity.d.ts +2 -2
- package/dist/credentials/identity.js +2 -2
- package/dist/credentials/install-key.d.ts +31 -0
- package/dist/credentials/install-key.js +58 -0
- package/dist/credentials/migration.d.ts +9 -7
- package/dist/credentials/migration.js +58 -18
- package/dist/credentials/secret-store.d.ts +12 -0
- package/dist/credentials/secret-store.js +18 -1
- package/dist/enforcement/enforcement.js +1 -1
- package/dist/events/enrich.d.ts +14 -0
- package/dist/events/enrich.js +1 -1
- package/dist/git/constants/git.constants.d.ts +2 -0
- package/dist/git/constants/git.constants.js +9 -0
- package/dist/git/repo-snapshot.js +8 -2
- package/dist/git/types/snapshot.types.d.ts +4 -0
- package/dist/pipeline/hook-pipeline.js +5 -2
- package/dist/providers/antigravity/antigravity.adapter.d.ts +14 -0
- package/dist/providers/antigravity/antigravity.adapter.js +86 -18
- package/dist/providers/antigravity/antigravity.provider.js +7 -4
- package/dist/providers/antigravity/constants/antigravity.constants.d.ts +10 -0
- package/dist/providers/antigravity/constants/antigravity.constants.js +10 -0
- package/dist/providers/antigravity/schemas/antigravity.schema.js +7 -13
- package/dist/providers/claude/claude.otel.d.ts +33 -1
- package/dist/providers/claude/claude.otel.js +81 -12
- package/dist/providers/claude/claude.provider.js +12 -6
- package/dist/providers/codex/codex.capture.d.ts +1 -1
- package/dist/providers/codex/codex.capture.js +3 -3
- package/dist/providers/codex/codex.otel.js +2 -2
- package/dist/providers/codex/codex.provider.js +2 -1
- package/dist/providers/gemini/gemini.capture.js +2 -2
- package/dist/providers/gemini/gemini.otel.js +2 -2
- package/dist/providers/gemini/gemini.provider.js +2 -1
- package/dist/providers/shared/terminal-capture.js +3 -3
- package/dist/providers/types/provider.types.d.ts +5 -5
- package/dist/replay/checkout-resolver.d.ts +41 -14
- package/dist/replay/checkout-resolver.js +134 -30
- package/dist/replay/replay-runner.d.ts +3 -1
- package/dist/replay/replay-runner.js +74 -22
- package/dist/replay/replay-scan.d.ts +2 -1
- package/dist/replay/replay-scan.js +14 -2
- package/dist/replay/throttle.d.ts +2 -1
- package/dist/replay/throttle.js +4 -1
- package/dist/replay/transcript-turns.js +29 -3
- package/dist/replay/turn-event.d.ts +4 -2
- package/dist/replay/turn-event.js +22 -11
- package/dist/replay/types/replay.types.d.ts +39 -3
- package/dist/replay/worktree-map.d.ts +42 -0
- package/dist/replay/worktree-map.js +134 -0
- package/dist/snapshot/snapshot-pipeline.js +15 -4
- package/dist/snapshot/types/snapshot.types.d.ts +2 -0
- package/dist/turns/antigravity-transcript.d.ts +40 -0
- package/dist/turns/antigravity-transcript.js +102 -0
- package/dist/turns/claude-transcript.d.ts +35 -1
- package/dist/turns/claude-transcript.js +185 -2
- package/dist/turns/codex-transcript.d.ts +22 -1
- package/dist/turns/codex-transcript.js +161 -2
- package/dist/turns/constants/turns.constants.d.ts +67 -0
- package/dist/turns/constants/turns.constants.js +67 -0
- package/dist/turns/gemini-transcript.d.ts +17 -1
- package/dist/turns/gemini-transcript.js +36 -2
- package/dist/turns/transcript.d.ts +31 -1
- package/dist/turns/transcript.js +74 -0
- package/dist/turns/turn-state.d.ts +51 -1
- package/dist/turns/turn-state.js +124 -10
- package/dist/turns/turn-tracker.js +156 -18
- package/dist/turns/types/transcript.types.d.ts +25 -0
- package/dist/turns/types/turn-provider.types.d.ts +18 -1
- package/dist/turns/types/turn-state.types.d.ts +10 -0
- package/docs/DATA_HANDLING.md +11 -6
- package/docs/ENTERPRISE_DEPLOYMENT.md +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ReadTurnUsageRetry, TranscriptUsageEntry, TurnUsage, WindowedTail } from './types/transcript.types.js';
|
|
1
|
+
import type { ReadTurnUsageRetry, TailSnapshot, TranscriptUsageEntry, TurnUsage, WindowedTail } from './types/transcript.types.js';
|
|
2
2
|
/** One read pass over a transcript. */
|
|
3
3
|
type TranscriptPass = () => Promise<TurnUsage | undefined>;
|
|
4
4
|
/**
|
|
@@ -26,6 +26,16 @@ export declare function readUntilSettled(pass: TranscriptPass, retry?: ReadTurnU
|
|
|
26
26
|
* @returns The tail text, or undefined when the file cannot be read.
|
|
27
27
|
*/
|
|
28
28
|
export declare function readTranscriptTail(transcriptPath: string): Promise<string | undefined>;
|
|
29
|
+
/**
|
|
30
|
+
* A transcript's tail as of one size, and the byte offset it starts at.
|
|
31
|
+
*
|
|
32
|
+
* One `stat` for both: a file still being appended to gives the tail and a
|
|
33
|
+
* read of what precedes it the same cut, so nothing falls between them.
|
|
34
|
+
*
|
|
35
|
+
* @param file - Transcript file.
|
|
36
|
+
* @returns The tail (partial first line dropped) and where it starts, or undefined when the file cannot be read.
|
|
37
|
+
*/
|
|
38
|
+
export declare function readTailSnapshot(file: string): Promise<TailSnapshot | undefined>;
|
|
29
39
|
/**
|
|
30
40
|
* A transcript tail with its turn window parsed: the start of every usage pass.
|
|
31
41
|
*
|
|
@@ -39,6 +49,16 @@ export declare function readTranscriptTail(transcriptPath: string): Promise<stri
|
|
|
39
49
|
* @returns The tail and both bounds, or undefined when a bound is not a date or the file cannot be read.
|
|
40
50
|
*/
|
|
41
51
|
export declare function readWindowedTail(transcriptPath: string, sinceIso: string, untilIso?: string): Promise<WindowedTail | undefined>;
|
|
52
|
+
/**
|
|
53
|
+
* The files in one folder whose names pass a test and that were written at or
|
|
54
|
+
* after a moment: the subagent transcripts a turn may hold usage in.
|
|
55
|
+
*
|
|
56
|
+
* @param dir - The folder.
|
|
57
|
+
* @param name - Test for a file name.
|
|
58
|
+
* @param since - Epoch ms; NaN keeps every file.
|
|
59
|
+
* @returns Absolute paths; empty when the folder cannot be read.
|
|
60
|
+
*/
|
|
61
|
+
export declare function filesWrittenSince(dir: string, name: RegExp, since: number): Promise<string[]>;
|
|
42
62
|
/**
|
|
43
63
|
* Stable identity for a transcript entry.
|
|
44
64
|
*
|
|
@@ -63,6 +83,16 @@ export declare function messageIdFor(rawId: string | undefined, line: string): s
|
|
|
63
83
|
* @returns The turn's usage, or undefined when there is nothing to report.
|
|
64
84
|
*/
|
|
65
85
|
export declare function accumulateUsage(entries: ReadonlyMap<string, TranscriptUsageEntry>): TurnUsage | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* One turn's usage out of two disjoint reads, summed: the parent's transcript
|
|
88
|
+
* and its subagents'. The model stays the parent's, the agent the developer
|
|
89
|
+
* talked to; a subagent's names the turn only when the parent read named none.
|
|
90
|
+
*
|
|
91
|
+
* @param parent - Usage of the parent transcript.
|
|
92
|
+
* @param subagents - Usage of the subagents' transcripts, none of it in `parent`.
|
|
93
|
+
* @returns The sum, or whichever one exists.
|
|
94
|
+
*/
|
|
95
|
+
export declare function mergeUsage(parent: TurnUsage | undefined, subagents: TurnUsage | undefined): TurnUsage | undefined;
|
|
66
96
|
/**
|
|
67
97
|
* Decode one JSONL line.
|
|
68
98
|
*
|
package/dist/turns/transcript.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
2
3
|
import { add, finiteOrZero } from '../core/number.js';
|
|
3
4
|
import { asRecord } from '../core/object.js';
|
|
4
5
|
import { sleep } from '../core/async.js';
|
|
@@ -54,6 +55,36 @@ export async function readTranscriptTail(transcriptPath) {
|
|
|
54
55
|
return undefined;
|
|
55
56
|
}
|
|
56
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* A transcript's tail as of one size, and the byte offset it starts at.
|
|
60
|
+
*
|
|
61
|
+
* One `stat` for both: a file still being appended to gives the tail and a
|
|
62
|
+
* read of what precedes it the same cut, so nothing falls between them.
|
|
63
|
+
*
|
|
64
|
+
* @param file - Transcript file.
|
|
65
|
+
* @returns The tail (partial first line dropped) and where it starts, or undefined when the file cannot be read.
|
|
66
|
+
*/
|
|
67
|
+
export async function readTailSnapshot(file) {
|
|
68
|
+
try {
|
|
69
|
+
const { size } = await fs.stat(file);
|
|
70
|
+
const handle = await fs.open(file, 'r');
|
|
71
|
+
try {
|
|
72
|
+
const start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES);
|
|
73
|
+
const buffer = Buffer.allocUnsafe(size - start);
|
|
74
|
+
const { bytesRead } = await handle.read(buffer, 0, size - start, start);
|
|
75
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
76
|
+
// A cut tail starts mid-line: drop up to the first newline, counted in bytes.
|
|
77
|
+
const skip = start === 0 ? 0 : bytes.indexOf(0x0a) + 1;
|
|
78
|
+
return { raw: bytes.subarray(skip).toString('utf8'), start: start + skip };
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
await handle.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return undefined;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
57
88
|
/**
|
|
58
89
|
* A transcript tail with its turn window parsed: the start of every usage pass.
|
|
59
90
|
*
|
|
@@ -76,6 +107,28 @@ export async function readWindowedTail(transcriptPath, sinceIso, untilIso) {
|
|
|
76
107
|
return undefined;
|
|
77
108
|
return { raw, since, until };
|
|
78
109
|
}
|
|
110
|
+
/**
|
|
111
|
+
* The files in one folder whose names pass a test and that were written at or
|
|
112
|
+
* after a moment: the subagent transcripts a turn may hold usage in.
|
|
113
|
+
*
|
|
114
|
+
* @param dir - The folder.
|
|
115
|
+
* @param name - Test for a file name.
|
|
116
|
+
* @param since - Epoch ms; NaN keeps every file.
|
|
117
|
+
* @returns Absolute paths; empty when the folder cannot be read.
|
|
118
|
+
*/
|
|
119
|
+
export async function filesWrittenSince(dir, name, since) {
|
|
120
|
+
const names = await fs.readdir(dir).catch(() => []);
|
|
121
|
+
const files = [];
|
|
122
|
+
for (const entry of names) {
|
|
123
|
+
if (!name.test(entry))
|
|
124
|
+
continue;
|
|
125
|
+
const file = path.join(dir, entry);
|
|
126
|
+
const stat = await fs.stat(file).catch(() => undefined);
|
|
127
|
+
if (stat && !(stat.mtimeMs < since))
|
|
128
|
+
files.push(file);
|
|
129
|
+
}
|
|
130
|
+
return files;
|
|
131
|
+
}
|
|
79
132
|
/**
|
|
80
133
|
* Stable identity for a transcript entry.
|
|
81
134
|
*
|
|
@@ -128,6 +181,27 @@ export function accumulateUsage(entries) {
|
|
|
128
181
|
messageIds: [...entries.keys()]
|
|
129
182
|
};
|
|
130
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* One turn's usage out of two disjoint reads, summed: the parent's transcript
|
|
186
|
+
* and its subagents'. The model stays the parent's, the agent the developer
|
|
187
|
+
* talked to; a subagent's names the turn only when the parent read named none.
|
|
188
|
+
*
|
|
189
|
+
* @param parent - Usage of the parent transcript.
|
|
190
|
+
* @param subagents - Usage of the subagents' transcripts, none of it in `parent`.
|
|
191
|
+
* @returns The sum, or whichever one exists.
|
|
192
|
+
*/
|
|
193
|
+
export function mergeUsage(parent, subagents) {
|
|
194
|
+
if (!parent || !subagents)
|
|
195
|
+
return parent ?? subagents;
|
|
196
|
+
return {
|
|
197
|
+
model: parent.model ?? subagents.model,
|
|
198
|
+
inputTokens: add(parent.inputTokens, subagents.inputTokens),
|
|
199
|
+
outputTokens: add(parent.outputTokens, subagents.outputTokens),
|
|
200
|
+
cachedInputTokens: add(parent.cachedInputTokens, subagents.cachedInputTokens),
|
|
201
|
+
cacheCreationInputTokens: add(parent.cacheCreationInputTokens, subagents.cacheCreationInputTokens),
|
|
202
|
+
messageIds: [...(parent.messageIds ?? []), ...(subagents.messageIds ?? [])]
|
|
203
|
+
};
|
|
204
|
+
}
|
|
131
205
|
/**
|
|
132
206
|
* Read the last TRANSCRIPT_TAIL_BYTES of a file, dropping the partial first
|
|
133
207
|
* line.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SessionTitles } from './types/transcript.types.js';
|
|
2
|
-
import type { AgentProcessRecord, InheritedCheckoutMemo, SessionActivity, SessionModeRecord, TurnRecord, TurnStateEntry, WorkCheckoutMemo } from './types/turn-state.types.js';
|
|
2
|
+
import type { AgentProcessRecord, InheritedCheckoutMemo, SentTurn, SessionActivity, SessionModeRecord, TurnRecord, TurnStateEntry, WorkCheckoutMemo } from './types/turn-state.types.js';
|
|
3
3
|
export type { CheckoutRecord, PromptRecord, ResponseRecord, SessionModelRecord, ToolRecord, TurnRecord, TurnStateEntry } from './types/turn-state.types.js';
|
|
4
4
|
/**
|
|
5
5
|
* The well-formed part of a session mode, from the start event's session or
|
|
@@ -71,6 +71,38 @@ export declare class TurnStateStore {
|
|
|
71
71
|
* @returns A test for a turn id; false for every id when nothing has closed.
|
|
72
72
|
*/
|
|
73
73
|
closedTurns(sessionId: string): Promise<(turnId: string) => boolean>;
|
|
74
|
+
/**
|
|
75
|
+
* Note that a turn close was handed to a detached process and has not run yet.
|
|
76
|
+
*
|
|
77
|
+
* Written before the agent is answered: the `SessionEnd` that may follow at
|
|
78
|
+
* once must find it, or it clears the records the close still has to read.
|
|
79
|
+
*
|
|
80
|
+
* @param sessionId - Provider session id.
|
|
81
|
+
* @param payload - The handed-off payload as JSON text; its hash names the marker.
|
|
82
|
+
*/
|
|
83
|
+
markClosing(sessionId: string, payload: string): Promise<void>;
|
|
84
|
+
/**
|
|
85
|
+
* Take a handed-off close's marker away, and clear the session when it ended
|
|
86
|
+
* meanwhile and no other close is pending.
|
|
87
|
+
*
|
|
88
|
+
* @param sessionId - Provider session id.
|
|
89
|
+
* @param payload - The payload the marker was written for.
|
|
90
|
+
*/
|
|
91
|
+
finishClosing(sessionId: string, payload: string): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Take back a `SessionEnd` that left its clear to a pending close: the same
|
|
94
|
+
* session id started again (`--resume`), and a close finishing now must not
|
|
95
|
+
* clear what the resumed session writes.
|
|
96
|
+
*
|
|
97
|
+
* @param sessionId - Provider session id.
|
|
98
|
+
*/
|
|
99
|
+
forgetEnded(sessionId: string): Promise<void>;
|
|
100
|
+
/**
|
|
101
|
+
* End a session: clear it now, or leave that to a detached close still pending.
|
|
102
|
+
*
|
|
103
|
+
* @param sessionId - Provider session id.
|
|
104
|
+
*/
|
|
105
|
+
endSession(sessionId: string): Promise<void>;
|
|
74
106
|
/**
|
|
75
107
|
* Record which transcript messages a closed turn has counted.
|
|
76
108
|
*
|
|
@@ -83,6 +115,23 @@ export declare class TurnStateStore {
|
|
|
83
115
|
* @param messageIds - Transcript message ids counted into that turn.
|
|
84
116
|
*/
|
|
85
117
|
claimUsage(sessionId: string, turnId: string, messageIds: readonly string[]): Promise<void>;
|
|
118
|
+
/**
|
|
119
|
+
* Keep the summary a turn closed with, for a background subagent of that
|
|
120
|
+
* turn finishing later to re-send with its usage added. Cleared with the session.
|
|
121
|
+
*
|
|
122
|
+
* @param sessionId - Provider session id.
|
|
123
|
+
* @param turnId - The turn.
|
|
124
|
+
* @param sent - The summary as built, with the checkout it routed by.
|
|
125
|
+
*/
|
|
126
|
+
rememberSentTurn(sessionId: string, turnId: string, sent: SentTurn): Promise<void>;
|
|
127
|
+
/**
|
|
128
|
+
* The summary a turn last went out with.
|
|
129
|
+
*
|
|
130
|
+
* @param sessionId - Provider session id.
|
|
131
|
+
* @param turnId - The turn.
|
|
132
|
+
* @returns It, or undefined when none was kept or it cannot be read.
|
|
133
|
+
*/
|
|
134
|
+
readSentTurn(sessionId: string, turnId: string): Promise<SentTurn | undefined>;
|
|
86
135
|
/**
|
|
87
136
|
* Every transcript message id already claimed in this session.
|
|
88
137
|
*
|
|
@@ -344,6 +393,7 @@ export declare class TurnStateStore {
|
|
|
344
393
|
*/
|
|
345
394
|
private pruneAgentPids;
|
|
346
395
|
private pidFile;
|
|
396
|
+
private closingFile;
|
|
347
397
|
/**
|
|
348
398
|
* Directory holding one session's state.
|
|
349
399
|
*
|
package/dist/turns/turn-state.js
CHANGED
|
@@ -7,7 +7,7 @@ import { writeFileAtomic } from '../storage/atomic-file.js';
|
|
|
7
7
|
import { readJsonFile } from '../storage/json-file.js';
|
|
8
8
|
import { SECRET_FILE_MODE, SWEEP_MARKER_FILE } from '../storage/constants/storage.constants.js';
|
|
9
9
|
import { claimSweep } from '../storage/sweep-marker.js';
|
|
10
|
-
import { AGENT_PIDS_DIR, AGENT_PROCESS_FILE, BILLING_SENT_FILE, CLOSED_TURN_PREFIX, INHERITED_CHECKOUT_FILE, LIVENESS_IGNORED_FILES, PROMPT_TICKETS_FILE, RE_UNSAFE_NAME_CHARS, SESSION_DIR_HASH_LENGTH, SESSION_FILES, SESSION_MODEL_FILE, SESSION_MODE_FILE, SESSION_RESUME_FILES, SESSION_START_FILE, SESSION_TITLE_FILE, TURN_RECORD_KINDS, TURN_STATE_SWEEP_INTERVAL_MS, UNTRACED_MARKER_PREFIX, USAGE_CLAIM_PREFIX, WORK_CHECKOUT_FILE } from './constants/turns.constants.js';
|
|
10
|
+
import { AGENT_PIDS_DIR, AGENT_PROCESS_FILE, BILLING_SENT_FILE, CLOSED_TURN_PREFIX, CLOSING_TURN_PREFIX, DETACHED_CLOSE_MAX_AGE_MS, INHERITED_CHECKOUT_FILE, LIVENESS_IGNORED_FILES, PROMPT_TICKETS_FILE, RE_UNSAFE_NAME_CHARS, SENT_TURN_PREFIX, SESSION_DIR_HASH_LENGTH, SESSION_ENDED_FILE, SESSION_FILES, SESSION_MODEL_FILE, SESSION_MODE_FILE, SESSION_RESUME_FILES, SESSION_START_FILE, SESSION_TITLE_FILE, TURN_RECORD_KINDS, TURN_STATE_SWEEP_INTERVAL_MS, UNTRACED_MARKER_PREFIX, USAGE_CLAIM_PREFIX, WORK_CHECKOUT_FILE } from './constants/turns.constants.js';
|
|
11
11
|
/**
|
|
12
12
|
* The well-formed part of a session mode, from the start event's session or
|
|
13
13
|
* the memo read back: what is written and what is read pass the same check.
|
|
@@ -103,6 +103,60 @@ export class TurnStateStore {
|
|
|
103
103
|
const names = new Set(await readSessionDirSafely(this.sessionDir(sessionId)));
|
|
104
104
|
return (turnId) => names.has(`${CLOSED_TURN_PREFIX}${safeName(turnId)}`);
|
|
105
105
|
}
|
|
106
|
+
/**
|
|
107
|
+
* Note that a turn close was handed to a detached process and has not run yet.
|
|
108
|
+
*
|
|
109
|
+
* Written before the agent is answered: the `SessionEnd` that may follow at
|
|
110
|
+
* once must find it, or it clears the records the close still has to read.
|
|
111
|
+
*
|
|
112
|
+
* @param sessionId - Provider session id.
|
|
113
|
+
* @param payload - The handed-off payload as JSON text; its hash names the marker.
|
|
114
|
+
*/
|
|
115
|
+
async markClosing(sessionId, payload) {
|
|
116
|
+
// Empty, so it cannot be half written: no temp file and no fsync on the Stop the agent waits for.
|
|
117
|
+
await fs.mkdir(this.sessionDir(sessionId), { recursive: true });
|
|
118
|
+
await fs.writeFile(this.closingFile(sessionId, payload), '', { mode: SECRET_FILE_MODE });
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Take a handed-off close's marker away, and clear the session when it ended
|
|
122
|
+
* meanwhile and no other close is pending.
|
|
123
|
+
*
|
|
124
|
+
* @param sessionId - Provider session id.
|
|
125
|
+
* @param payload - The payload the marker was written for.
|
|
126
|
+
*/
|
|
127
|
+
async finishClosing(sessionId, payload) {
|
|
128
|
+
await fs.rm(this.closingFile(sessionId, payload), { force: true });
|
|
129
|
+
const names = await freshMarkers(this.sessionDir(sessionId));
|
|
130
|
+
if (names.includes(SESSION_ENDED_FILE) && !names.some(isClosingMarker))
|
|
131
|
+
await this.clear(sessionId);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Take back a `SessionEnd` that left its clear to a pending close: the same
|
|
135
|
+
* session id started again (`--resume`), and a close finishing now must not
|
|
136
|
+
* clear what the resumed session writes.
|
|
137
|
+
*
|
|
138
|
+
* @param sessionId - Provider session id.
|
|
139
|
+
*/
|
|
140
|
+
async forgetEnded(sessionId) {
|
|
141
|
+
await fs.rm(path.join(this.sessionDir(sessionId), SESSION_ENDED_FILE), { force: true });
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* End a session: clear it now, or leave that to a detached close still pending.
|
|
145
|
+
*
|
|
146
|
+
* @param sessionId - Provider session id.
|
|
147
|
+
*/
|
|
148
|
+
async endSession(sessionId) {
|
|
149
|
+
const dir = this.sessionDir(sessionId);
|
|
150
|
+
if ((await freshMarkers(dir)).some(isClosingMarker)) {
|
|
151
|
+
// A close that cleared the whole folder meanwhile leaves nothing to mark: clear below.
|
|
152
|
+
const marked = await fs.writeFile(path.join(dir, SESSION_ENDED_FILE), '', { mode: SECRET_FILE_MODE }).then(() => true, () => false);
|
|
153
|
+
// Looked at again after the mark: a close that finished in between did
|
|
154
|
+
// not see it, and would leave the session to the expiry sweep.
|
|
155
|
+
if (marked && (await freshMarkers(dir)).some(isClosingMarker))
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
await this.clear(sessionId);
|
|
159
|
+
}
|
|
106
160
|
/**
|
|
107
161
|
* Record which transcript messages a closed turn has counted.
|
|
108
162
|
*
|
|
@@ -118,7 +172,35 @@ export class TurnStateStore {
|
|
|
118
172
|
if (messageIds.length === 0)
|
|
119
173
|
return;
|
|
120
174
|
const file = path.join(this.sessionDir(sessionId), `${USAGE_CLAIM_PREFIX}${safeName(turnId)}.json`);
|
|
121
|
-
|
|
175
|
+
// Added to, never replaced: a background subagent claims onto a turn that already closed.
|
|
176
|
+
const earlier = await idsIn(file);
|
|
177
|
+
await writeFileAtomic(file, JSON.stringify({ messageIds: [...new Set([...earlier, ...messageIds])] }), SECRET_FILE_MODE);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Keep the summary a turn closed with, for a background subagent of that
|
|
181
|
+
* turn finishing later to re-send with its usage added. Cleared with the session.
|
|
182
|
+
*
|
|
183
|
+
* @param sessionId - Provider session id.
|
|
184
|
+
* @param turnId - The turn.
|
|
185
|
+
* @param sent - The summary as built, with the checkout it routed by.
|
|
186
|
+
*/
|
|
187
|
+
async rememberSentTurn(sessionId, turnId, sent) {
|
|
188
|
+
await writeFileAtomic(path.join(this.sessionDir(sessionId), `${SENT_TURN_PREFIX}${safeName(turnId)}`), JSON.stringify(sent), SECRET_FILE_MODE);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* The summary a turn last went out with.
|
|
192
|
+
*
|
|
193
|
+
* @param sessionId - Provider session id.
|
|
194
|
+
* @param turnId - The turn.
|
|
195
|
+
* @returns It, or undefined when none was kept or it cannot be read.
|
|
196
|
+
*/
|
|
197
|
+
async readSentTurn(sessionId, turnId) {
|
|
198
|
+
const read = await readJsonFile(path.join(this.sessionDir(sessionId), `${SENT_TURN_PREFIX}${safeName(turnId)}`));
|
|
199
|
+
const sent = asRecord(read.state === 'ok' ? read.value : undefined);
|
|
200
|
+
const summary = asRecord(sent?.['summary']);
|
|
201
|
+
if (!summary || summary['turn_id'] !== turnId || typeof summary['id'] !== 'string')
|
|
202
|
+
return undefined;
|
|
203
|
+
return { ...sent, summary: summary };
|
|
122
204
|
}
|
|
123
205
|
/**
|
|
124
206
|
* Every transcript message id already claimed in this session.
|
|
@@ -133,14 +215,8 @@ export class TurnStateStore {
|
|
|
133
215
|
for (const name of names) {
|
|
134
216
|
if (!name.startsWith(USAGE_CLAIM_PREFIX) || !name.endsWith('.json'))
|
|
135
217
|
continue;
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
if (!Array.isArray(ids))
|
|
139
|
-
continue;
|
|
140
|
-
for (const id of ids) {
|
|
141
|
-
if (typeof id === 'string')
|
|
142
|
-
claimed.add(id);
|
|
143
|
-
}
|
|
218
|
+
for (const id of await idsIn(path.join(dir, name)))
|
|
219
|
+
claimed.add(id);
|
|
144
220
|
}
|
|
145
221
|
return claimed;
|
|
146
222
|
}
|
|
@@ -538,6 +614,9 @@ export class TurnStateStore {
|
|
|
538
614
|
pidFile(pid) {
|
|
539
615
|
return path.join(this.turnsDir, AGENT_PIDS_DIR, `${Math.trunc(pid)}.json`);
|
|
540
616
|
}
|
|
617
|
+
closingFile(sessionId, payload) {
|
|
618
|
+
return path.join(this.sessionDir(sessionId), `${CLOSING_TURN_PREFIX}${sha256Hex(payload).slice(0, SESSION_DIR_HASH_LENGTH)}`);
|
|
619
|
+
}
|
|
541
620
|
/**
|
|
542
621
|
* Directory holding one session's state.
|
|
543
622
|
*
|
|
@@ -551,6 +630,19 @@ export class TurnStateStore {
|
|
|
551
630
|
return path.join(this.turnsDir, sha256Hex(sessionId).slice(0, SESSION_DIR_HASH_LENGTH));
|
|
552
631
|
}
|
|
553
632
|
}
|
|
633
|
+
/**
|
|
634
|
+
* The message ids one claim file holds.
|
|
635
|
+
*
|
|
636
|
+
* @param file - A usage-claim file.
|
|
637
|
+
* @returns Its ids; empty when it is missing, unreadable or the wrong shape.
|
|
638
|
+
*/
|
|
639
|
+
async function idsIn(file) {
|
|
640
|
+
const read = await readJsonFile(file);
|
|
641
|
+
const ids = asRecord(read.state === 'ok' ? read.value : undefined)?.['messageIds'];
|
|
642
|
+
if (!Array.isArray(ids))
|
|
643
|
+
return [];
|
|
644
|
+
return ids.filter((id) => typeof id === 'string');
|
|
645
|
+
}
|
|
554
646
|
/**
|
|
555
647
|
* Every turn record in one session directory, oldest first.
|
|
556
648
|
*
|
|
@@ -714,6 +806,28 @@ async function newestMtime(dir, ignored = new Set()) {
|
|
|
714
806
|
}
|
|
715
807
|
return newest;
|
|
716
808
|
}
|
|
809
|
+
/**
|
|
810
|
+
* The pending-close and session-ended markers of a session written within
|
|
811
|
+
* {@link DETACHED_CLOSE_MAX_AGE_MS}: an older one belongs to a close that died.
|
|
812
|
+
*
|
|
813
|
+
* @param dir - Session directory.
|
|
814
|
+
* @returns The fresh markers' names.
|
|
815
|
+
*/
|
|
816
|
+
async function freshMarkers(dir) {
|
|
817
|
+
const cutoff = Date.now() - DETACHED_CLOSE_MAX_AGE_MS;
|
|
818
|
+
const fresh = [];
|
|
819
|
+
for (const name of await readSessionDirSafely(dir)) {
|
|
820
|
+
if (name !== SESSION_ENDED_FILE && !isClosingMarker(name))
|
|
821
|
+
continue;
|
|
822
|
+
const stat = await fs.stat(path.join(dir, name)).catch(() => undefined);
|
|
823
|
+
if (stat && stat.mtimeMs > cutoff)
|
|
824
|
+
fresh.push(name);
|
|
825
|
+
}
|
|
826
|
+
return fresh;
|
|
827
|
+
}
|
|
828
|
+
function isClosingMarker(name) {
|
|
829
|
+
return name.startsWith(CLOSING_TURN_PREFIX);
|
|
830
|
+
}
|
|
717
831
|
/**
|
|
718
832
|
* Filesystem-safe form of an untrusted record id.
|
|
719
833
|
*
|
|
@@ -2,8 +2,9 @@ import path from 'node:path';
|
|
|
2
2
|
import { pollUntil } from '../core/async.js';
|
|
3
3
|
import { debugLog } from '../core/logger.js';
|
|
4
4
|
import { asRecord, compact } from '../core/object.js';
|
|
5
|
+
import { add } from '../core/number.js';
|
|
5
6
|
import { billingModeOf } from '../billing/billing-mode.js';
|
|
6
|
-
import { sha256Hex } from '../events/event-id.js';
|
|
7
|
+
import { deriveEventId, sha256Hex } from '../events/event-id.js';
|
|
7
8
|
import { REPOSITORY_PATH_METADATA_KEY } from '../events/constants/enrich.constants.js';
|
|
8
9
|
import { codeStateAt } from '../git/code-state.js';
|
|
9
10
|
import { developerDisplayName, developerIdentity } from '../git/git-context.js';
|
|
@@ -15,6 +16,7 @@ import { MAX_WORK_CHANGED_FILES } from '../git/constants/git.constants.js';
|
|
|
15
16
|
import { PARENT_SESSION_VAR, RE_PARENT_SESSION_ID, CLOUD_SURFACE, DEFAULT_SURFACE, EXTERNAL_PATH_KEY, FILE_PATH_KEY, LOCK_KEY_HASH_LENGTH, MAX_PROMPT_TEXT_LENGTH, MAX_TOOL_INPUT_LENGTH, PROMPT_EVIDENCE_KEY, PROMPT_JIRA_IDS_KEY, PROMPT_TEXT_KEY, RESPONSE_EVIDENCE_KEY, INT32_MAX, INT32_MIN, RE_SHA256_HEX, TOOL_CALL_KEY, TOOL_COMPLETION_TYPES, TOOL_START_TYPES, TRANSCRIPT_PATH_KEY, TURN_STATE_TTL_MS, USAGE_LOCK_POLL_MS, USAGE_LOCK_WAIT_MS, USAGE_RETRY } from './constants/turns.constants.js';
|
|
16
17
|
import { resolveFileIdentity } from './file-identity.js';
|
|
17
18
|
import { toSessionMode, TurnStateStore } from './turn-state.js';
|
|
19
|
+
import { mergeUsage } from './transcript.js';
|
|
18
20
|
import { buildToolEvents, callKey } from './tool-events.js';
|
|
19
21
|
import { buildTurnSummary } from './turn-summary.js';
|
|
20
22
|
import { rememberInheritance, retryInheritance } from './inherited-checkout.js';
|
|
@@ -81,7 +83,7 @@ async function processEvent(store, sessionId, event, options) {
|
|
|
81
83
|
// `generation.completed` would degrade the turn to a fallback summary, and one
|
|
82
84
|
// on `session.ended` would leave a session's raw prompt text undeleted.
|
|
83
85
|
if (type === 'session.started')
|
|
84
|
-
await Promise.all([rememberModelSafely(store, sessionId, event), rememberModeSafely(store, sessionId, event, options.provider)]);
|
|
86
|
+
await Promise.all([rememberModelSafely(store, sessionId, event), rememberModeSafely(store, sessionId, event, options.provider), store.forgetEnded(sessionId).catch(() => undefined)]);
|
|
85
87
|
// The first hook walks; a later one walks again only when the deadline cut
|
|
86
88
|
// the last walk, so a busy first hook does not cost the whole session. Not
|
|
87
89
|
// at the session's end, which clears the answer straight after.
|
|
@@ -101,8 +103,10 @@ async function processEvent(store, sessionId, event, options) {
|
|
|
101
103
|
await store.sweep(TURN_STATE_TTL_MS);
|
|
102
104
|
return outcome;
|
|
103
105
|
}
|
|
106
|
+
if (type === 'subagent.completed')
|
|
107
|
+
return lateSubagentUsage(store, sessionId, event, options);
|
|
104
108
|
if (type === 'session.ended') {
|
|
105
|
-
await store.
|
|
109
|
+
await store.endSession(sessionId);
|
|
106
110
|
await store.sweep(TURN_STATE_TTL_MS);
|
|
107
111
|
}
|
|
108
112
|
return undefined;
|
|
@@ -422,6 +426,20 @@ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly =
|
|
|
422
426
|
await store.remove(consumable([...mine, ...late], collected).map((entry) => entry.file));
|
|
423
427
|
if (!readOnly && stopTurnId !== undefined)
|
|
424
428
|
await store.markTurnClosed(sessionId, stopTurnId);
|
|
429
|
+
const outcome = { summary: sanitizeValue(summary), workRoot: work.root, capture: work.capture };
|
|
430
|
+
// Kept for a background subagent of this turn that is still running (a
|
|
431
|
+
// provider that reads none keeps nothing); its own catch, as below. Not for a
|
|
432
|
+
// turn whose usage was never read (lock timeout): adding a subagent's tokens
|
|
433
|
+
// alone would state a provisional total the parent's are missing from.
|
|
434
|
+
// Nor for a turn whose summary was never sent (`emit.turnSummaries` off).
|
|
435
|
+
if (!readOnly && stopTurnId !== undefined && usage && options.config.emit.turnSummaries && options.provider.readSubagentUsage) {
|
|
436
|
+
// Without the transient fields: core relays a turn's prompt text and tool
|
|
437
|
+
// inputs to an LLM read, which a re-send must not pay for twice, and stores neither.
|
|
438
|
+
const kept = { ...outcome, untilIso: window.untilIso, summary: compact({ ...outcome.summary, prompt_text: undefined, tool_inputs: undefined }) };
|
|
439
|
+
await store.rememberSentTurn(sessionId, stopTurnId, kept).catch((error) => {
|
|
440
|
+
debugLog('could not keep the turn summary:', error);
|
|
441
|
+
});
|
|
442
|
+
}
|
|
425
443
|
// The next turn that changes nothing carries this one; the prompt gate asks it too.
|
|
426
444
|
if (!readOnly && work.evidence === 'changed' && work.root && work.git?.repository) {
|
|
427
445
|
// After the records are consumed, so a failure here must not cost the summary.
|
|
@@ -429,7 +447,7 @@ async function closeTurnLocked(store, sessionId, stopEvent, options, readOnly =
|
|
|
429
447
|
debugLog('could not record the work checkout:', error);
|
|
430
448
|
});
|
|
431
449
|
}
|
|
432
|
-
return
|
|
450
|
+
return outcome;
|
|
433
451
|
}
|
|
434
452
|
/**
|
|
435
453
|
* Remember the checkout this turn changed, with its branch and the files the
|
|
@@ -559,22 +577,22 @@ function resolveWindow(all, mine, stopAt) {
|
|
|
559
577
|
async function resolveAndClaimUsage(store, sessionId, stopEvent, options, window, readOnly) {
|
|
560
578
|
if (!options.provider.readTurnUsage || window.startedAt === undefined)
|
|
561
579
|
return undefined;
|
|
580
|
+
const turnId = stopEvent.session.turnId;
|
|
562
581
|
if (readOnly) {
|
|
563
|
-
return readTranscriptUsage(options, window, await store.claimedMessageIds(sessionId));
|
|
582
|
+
return readTranscriptUsage(options, window, await store.claimedMessageIds(sessionId), turnId);
|
|
564
583
|
}
|
|
565
|
-
const
|
|
566
|
-
const release = await waitForUsageLock(options, lockName);
|
|
584
|
+
const release = await waitForUsageLock(options, sessionId);
|
|
567
585
|
if (!release) {
|
|
568
586
|
debugLog('turn usage lock timed out; omitting transcript usage');
|
|
569
587
|
return undefined;
|
|
570
588
|
}
|
|
571
589
|
try {
|
|
572
590
|
const claimed = await store.claimedMessageIds(sessionId);
|
|
573
|
-
const usage = await readTranscriptUsage(options, window, claimed);
|
|
591
|
+
const usage = await readTranscriptUsage(options, window, claimed, turnId);
|
|
574
592
|
if (usage?.messageIds && usage.messageIds.length > 0) {
|
|
575
593
|
// Old Claude versions have no prompt id; the Stop event id still gives
|
|
576
594
|
// every completed turn a distinct ledger file.
|
|
577
|
-
await store.claimUsage(sessionId,
|
|
595
|
+
await store.claimUsage(sessionId, turnId ?? stopEvent.id, usage.messageIds);
|
|
578
596
|
}
|
|
579
597
|
return usage;
|
|
580
598
|
}
|
|
@@ -586,26 +604,146 @@ async function resolveAndClaimUsage(store, sessionId, stopEvent, options, window
|
|
|
586
604
|
* Acquire the session usage lock, waiting a bounded time.
|
|
587
605
|
*
|
|
588
606
|
* @param options - Tracking options supplying the locks directory and clock.
|
|
589
|
-
* @param
|
|
607
|
+
* @param sessionId - The session the lock serializes claims for.
|
|
590
608
|
* @returns The release function, or undefined on timeout.
|
|
591
609
|
*/
|
|
592
|
-
function waitForUsageLock(options,
|
|
610
|
+
function waitForUsageLock(options, sessionId) {
|
|
611
|
+
const lockName = `turn-usage-${sha256Hex(sessionId).slice(0, LOCK_KEY_HASH_LENGTH)}`;
|
|
593
612
|
return pollUntil(() => acquireLock(options.locksDir, lockName, options.env.now), USAGE_LOCK_WAIT_MS, USAGE_LOCK_POLL_MS);
|
|
594
613
|
}
|
|
595
614
|
/**
|
|
596
|
-
* Run this provider's transcript
|
|
615
|
+
* Run this provider's transcript readers over the turn: its own transcript in
|
|
616
|
+
* the window, then its subagents' by turn id, excluding what the first counted.
|
|
597
617
|
*
|
|
598
618
|
* @param options - Tracking options carrying the raw payload.
|
|
599
619
|
* @param window - Bounds this turn may claim from.
|
|
600
620
|
* @param excludeMessageIds - Messages other turns already claimed.
|
|
621
|
+
* @param turnId - The turn's id, when it has one.
|
|
601
622
|
* @returns The usage, or undefined when the provider reports none.
|
|
602
623
|
*/
|
|
603
|
-
async function readTranscriptUsage(options, window, excludeMessageIds) {
|
|
604
|
-
const
|
|
605
|
-
const transcriptPath =
|
|
606
|
-
if (!
|
|
624
|
+
async function readTranscriptUsage(options, window, excludeMessageIds, turnId) {
|
|
625
|
+
const { readTurnUsage, readSubagentUsage } = options.provider;
|
|
626
|
+
const transcriptPath = transcriptPathOf(options);
|
|
627
|
+
if (!readTurnUsage || window.startedAt === undefined || typeof transcriptPath !== 'string')
|
|
628
|
+
return undefined;
|
|
629
|
+
const parent = await readTurnUsage(transcriptPath, window.startedAt, USAGE_RETRY, window.untilIso, excludeMessageIds);
|
|
630
|
+
if (!readSubagentUsage)
|
|
631
|
+
return parent;
|
|
632
|
+
const turn = { turnId, startedAt: window.startedAt, untilIso: window.untilIso };
|
|
633
|
+
const subagents = await readSubagentUsage(options.rawPayload, turn, new Set([...excludeMessageIds, ...(parent?.messageIds ?? [])]));
|
|
634
|
+
return mergeUsage(parent, subagents);
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* The transcript this hook names: the provider's own reading, else the
|
|
638
|
+
* top-level `transcript_path` every other agent uses.
|
|
639
|
+
*
|
|
640
|
+
* @param options - Tracking options carrying the provider and raw payload.
|
|
641
|
+
* @returns The path, or undefined when the payload names none.
|
|
642
|
+
*/
|
|
643
|
+
function transcriptPathOf(options) {
|
|
644
|
+
return options.provider.transcriptPath?.(options.rawPayload, options.env) ?? asRecord(options.rawPayload)?.[TRANSCRIPT_PATH_KEY];
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* A subagent's own stop, for a turn that already closed: claim what that
|
|
648
|
+
* subagent recorded since the turn's read and send the turn again with it added.
|
|
649
|
+
* The turn is the one the subagent's lines name, which need not be the one its
|
|
650
|
+
* stop names (Claude names the current prompt).
|
|
651
|
+
*
|
|
652
|
+
* A background subagent keeps running after the prompt that launched it has
|
|
653
|
+
* its Stop, and its usage would otherwise be no turn's. Core restates a turn
|
|
654
|
+
* on a resend with the same turn id (tokens replaced, every other field kept
|
|
655
|
+
* when the resend states it too), so the resend is the summary the turn went
|
|
656
|
+
* out with, totals raised, under a new event id. A turn still open reads its
|
|
657
|
+
* subagents at its own Stop, so a foreground subagent's stop sends nothing.
|
|
658
|
+
*
|
|
659
|
+
* ponytail: a subagent stopping between the turn's claim and the summary being
|
|
660
|
+
* kept finds nothing to add to, and what it wrote after the turn's read stays
|
|
661
|
+
* unclaimed; native OTel still counts it. Keep the summary under the usage
|
|
662
|
+
* lock if that window shows up.
|
|
663
|
+
*
|
|
664
|
+
* @param store - Per-session state store.
|
|
665
|
+
* @param sessionId - Provider session id.
|
|
666
|
+
* @param event - The subagent's stop.
|
|
667
|
+
* @param options - Tracking options carrying the raw payload.
|
|
668
|
+
* @returns The re-sent summary, or undefined when there is nothing late to add.
|
|
669
|
+
*/
|
|
670
|
+
async function lateSubagentUsage(store, sessionId, event, options) {
|
|
671
|
+
const { readSubagentUsage, readSubagentTurnIds } = options.provider;
|
|
672
|
+
if (!readSubagentUsage)
|
|
673
|
+
return undefined;
|
|
674
|
+
const candidates = readSubagentTurnIds ? await readSubagentTurnIds(options.rawPayload) : [event.session.turnId];
|
|
675
|
+
// ponytail: one summary per hook, so a subagent resumed across two closed
|
|
676
|
+
// turns re-sends the first with late lines; the other's stay unclaimed.
|
|
677
|
+
for (const turnId of candidates) {
|
|
678
|
+
const resent = turnId === undefined ? undefined : await resendWithLateUsage(store, sessionId, turnId, readSubagentUsage, options);
|
|
679
|
+
if (resent)
|
|
680
|
+
return resent;
|
|
681
|
+
}
|
|
682
|
+
return undefined;
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Claim one closed turn's late subagent usage and build its re-send.
|
|
686
|
+
*
|
|
687
|
+
* @param store - Per-session state store.
|
|
688
|
+
* @param sessionId - Provider session id.
|
|
689
|
+
* @param turnId - A turn the subagent's lines name.
|
|
690
|
+
* @param read - The provider's subagent reader.
|
|
691
|
+
* @param options - Tracking options carrying the raw payload.
|
|
692
|
+
* @returns The re-send, or undefined when the turn is open, kept nothing, or has nothing late.
|
|
693
|
+
*/
|
|
694
|
+
async function resendWithLateUsage(store, sessionId, turnId, read, options) {
|
|
695
|
+
// Checked before the lock: most subagents stop inside their turn.
|
|
696
|
+
if (!(await store.readSentTurn(sessionId, turnId)))
|
|
697
|
+
return undefined;
|
|
698
|
+
const release = await waitForUsageLock(options, sessionId);
|
|
699
|
+
if (!release)
|
|
607
700
|
return undefined;
|
|
608
|
-
|
|
701
|
+
try {
|
|
702
|
+
const sent = await store.readSentTurn(sessionId, turnId);
|
|
703
|
+
if (!sent)
|
|
704
|
+
return undefined;
|
|
705
|
+
// Bounded where the turn's own window was: a window reader must not take a later turn's rows.
|
|
706
|
+
const turn = { turnId, startedAt: sent.summary.started_at ?? sent.summary.ended_at, untilIso: sent.untilIso ?? sent.summary.ended_at };
|
|
707
|
+
const usage = await read(options.rawPayload, turn, await store.claimedMessageIds(sessionId));
|
|
708
|
+
if (!usage?.messageIds?.length)
|
|
709
|
+
return undefined;
|
|
710
|
+
const resent = { ...sent, summary: withLateUsage(sent.summary, usage) };
|
|
711
|
+
await store.claimUsage(sessionId, turnId, usage.messageIds);
|
|
712
|
+
// Its own catch: the claim is written, so the re-send must still go out.
|
|
713
|
+
await store.rememberSentTurn(sessionId, turnId, resent).catch((error) => {
|
|
714
|
+
debugLog('could not keep the re-sent turn summary:', error);
|
|
715
|
+
});
|
|
716
|
+
return resent;
|
|
717
|
+
}
|
|
718
|
+
finally {
|
|
719
|
+
await release();
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* A sent summary with late subagent usage added to its totals.
|
|
724
|
+
*
|
|
725
|
+
* @param summary - The summary the turn last went out with.
|
|
726
|
+
* @param usage - Usage no turn has claimed yet.
|
|
727
|
+
* @returns The summary to re-send, under an id of its own.
|
|
728
|
+
*/
|
|
729
|
+
function withLateUsage(summary, usage) {
|
|
730
|
+
return compact({
|
|
731
|
+
...summary,
|
|
732
|
+
id: deriveEventId({
|
|
733
|
+
provider: summary.provider,
|
|
734
|
+
providerEventType: 'turn.summary',
|
|
735
|
+
sessionId: summary.session_id,
|
|
736
|
+
turnId: summary.turn_id,
|
|
737
|
+
timestamp: summary.ended_at,
|
|
738
|
+
payloadFingerprint: sha256Hex(JSON.stringify([summary.id, ...(usage.messageIds ?? [])]))
|
|
739
|
+
}),
|
|
740
|
+
model: summary.model ?? usage.model,
|
|
741
|
+
input_tokens: add(summary.input_tokens, usage.inputTokens),
|
|
742
|
+
cached_input_tokens: add(summary.cached_input_tokens, usage.cachedInputTokens),
|
|
743
|
+
cache_creation_input_tokens: add(summary.cache_creation_input_tokens, usage.cacheCreationInputTokens),
|
|
744
|
+
output_tokens: add(summary.output_tokens, usage.outputTokens),
|
|
745
|
+
usage_status: 'provisional'
|
|
746
|
+
});
|
|
609
747
|
}
|
|
610
748
|
/**
|
|
611
749
|
* The session's name and generated title, when the config lets them leave the machine.
|
|
@@ -633,7 +771,7 @@ async function resolveSessionTitles(store, sessionId, options, readOnly) {
|
|
|
633
771
|
const { readSessionTitles, readTranscriptTitles } = options.provider;
|
|
634
772
|
if (readSessionTitles)
|
|
635
773
|
return safeNativeTitles(() => readSessionTitles(options.env, sessionId));
|
|
636
|
-
const transcriptPath =
|
|
774
|
+
const transcriptPath = transcriptPathOf(options);
|
|
637
775
|
if (!readTranscriptTitles || typeof transcriptPath !== 'string')
|
|
638
776
|
return {};
|
|
639
777
|
try {
|