gipity 1.1.12 → 1.1.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/dist/adopt-cwd.js +5 -6
- package/dist/api.js +98 -22
- package/dist/auth.js +14 -1
- package/dist/capture/sources/claude-code.js +23 -0
- package/dist/capture/sources/codex.js +30 -1
- package/dist/capture/sources/opencode.js +18 -4
- package/dist/claude-setup.js +109 -4
- package/dist/commands/build.js +24 -10
- package/dist/commands/doctor.js +26 -5
- package/dist/commands/generate.js +6 -6
- package/dist/commands/init.js +53 -9
- package/dist/commands/service.js +7 -2
- package/dist/hooks/capture-runner.js +94 -4
- package/dist/index.js +576 -327
- package/dist/opencode-setup.js +9 -2
- package/dist/project-setup.js +5 -2
- package/dist/relay/daemon.js +54 -4
- package/dist/relay/diagnostics.js +10 -1
- package/dist/setup.js +113 -29
- package/package.json +2 -2
package/dist/commands/doctor.js
CHANGED
|
@@ -5,7 +5,7 @@ import { homedir } from 'os';
|
|
|
5
5
|
import { LOCAL_PKG_DIR, LOCAL_ENTRY, STATE_FILE, SETTINGS_FILE, UPDATE_LOG, readState, readSettings, updatesDisabled } from '../updater/state.js';
|
|
6
6
|
import { bold, dim, success, warning, error as clrError, muted } from '../colors.js';
|
|
7
7
|
import { getAuth, sessionExpired } from '../auth.js';
|
|
8
|
-
import { isClaudeInstalled,
|
|
8
|
+
import { isClaudeInstalled, probeClaudeAuthenticated, claudeAuthStatus, claudeCredentialHeuristic, claudeLoginHint } from '../claude-setup.js';
|
|
9
9
|
import * as relayState from '../relay/state.js';
|
|
10
10
|
import { planFor, UnsupportedPlatformError } from '../relay/installers.js';
|
|
11
11
|
import { resolveCliPath } from '../relay/setup.js';
|
|
@@ -112,9 +112,23 @@ export function gatherEnv(opts = {}) {
|
|
|
112
112
|
session_expired: expired,
|
|
113
113
|
};
|
|
114
114
|
const claude = { installed: isClaudeInstalled(), authenticated: false };
|
|
115
|
-
//
|
|
116
|
-
//
|
|
117
|
-
|
|
115
|
+
// `claude auth status` is authoritative (it reads Claude Code's own store, so
|
|
116
|
+
// it sees the macOS Keychain and notices a revoked token) and NOT billed, but
|
|
117
|
+
// it is a ~2s process spawn - so run it ONCE and derive both the verdict and
|
|
118
|
+
// the account from that single call. --probe-claude remains for the rare case
|
|
119
|
+
// you want proof that a real round-trip works, not just that a credential
|
|
120
|
+
// exists. Naming the signed-in account is the fastest way to spot the classic
|
|
121
|
+
// relay misconfiguration: the daemon running as a different user/HOME than
|
|
122
|
+
// the human who logged in, so it reads a different ~/.claude and is forever
|
|
123
|
+
// "not logged in" no matter how many times they sign in interactively.
|
|
124
|
+
if (claude.installed) {
|
|
125
|
+
const status = opts.probeClaude ? null : claudeAuthStatus();
|
|
126
|
+
claude.authenticated = opts.probeClaude
|
|
127
|
+
? probeClaudeAuthenticated()
|
|
128
|
+
: (status?.loggedIn ?? claudeCredentialHeuristic());
|
|
129
|
+
claude.account = status?.email ?? null;
|
|
130
|
+
claude.method = status?.authMethod ?? null;
|
|
131
|
+
}
|
|
118
132
|
const relay = {
|
|
119
133
|
paired: !!device,
|
|
120
134
|
running: relayState.isDaemonRunning(),
|
|
@@ -159,7 +173,14 @@ export const doctorCommand = new Command('doctor')
|
|
|
159
173
|
console.log(`${muted(' ')} ${dim(`login PATH yet. Ensure ${env.node.version_manager} auto-activates in your shell rc, set it as the default version, or symlink node + gipity onto your base PATH.`)}`);
|
|
160
174
|
}
|
|
161
175
|
console.log(`${muted('gipity login ')} ${env.gipity.logged_in ? success(`logged in as ${env.gipity.email}`) : (env.gipity.session_expired ? warning(`session expired (${env.gipity.email})`) : warning('not logged in'))}`);
|
|
162
|
-
|
|
176
|
+
const claudeAccount = env.claude.account ? muted(` (${env.claude.account}${env.claude.method ? ` via ${env.claude.method}` : ''})`) : '';
|
|
177
|
+
console.log(`${muted('claude code ')} installed ${yn(env.claude.installed)} · authenticated ${yn(env.claude.authenticated)}${claudeAccount}`);
|
|
178
|
+
if (env.claude.installed && !env.claude.authenticated) {
|
|
179
|
+
// The single most common cause of a relay that accepts messages and then
|
|
180
|
+
// fails every one of them. Say the fix here rather than making them find
|
|
181
|
+
// it from a failed dispatch.
|
|
182
|
+
console.log(`${muted(' ')} ${warning(claudeLoginHint())}`);
|
|
183
|
+
}
|
|
163
184
|
const autostartLabel = env.relay.autostart === null ? muted('n/a') : yn(env.relay.autostart);
|
|
164
185
|
console.log(`${muted('relay ')} paired ${yn(env.relay.paired)} · running ${yn(env.relay.running)} · autostart ${autostartLabel}${env.relay.paused ? warning(' · paused') : ''}${env.relay.device ? muted(` (${env.relay.device.name})`) : ''}`);
|
|
165
186
|
// Codex approves project hooks interactively and stores the decision in
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Command, Option } from 'commander';
|
|
2
|
-
import { post } from '../api.js';
|
|
2
|
+
import { post, LONG_REQUEST_TIMEOUT_MS } from '../api.js';
|
|
3
3
|
import { resolveProjectContext, getConfigPath } from '../config.js';
|
|
4
4
|
import { pushFile } from '../sync.js';
|
|
5
5
|
import { mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
@@ -254,7 +254,7 @@ Examples:
|
|
|
254
254
|
image_size: opts.imageSize,
|
|
255
255
|
seed: Number.isFinite(opts.seed) ? opts.seed : undefined,
|
|
256
256
|
input_images: inputImages,
|
|
257
|
-
});
|
|
257
|
+
}, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
258
258
|
const verb = inputImages ? 'Editing image...' : 'Generating image...';
|
|
259
259
|
const started = Date.now();
|
|
260
260
|
const result = opts.json
|
|
@@ -323,7 +323,7 @@ Examples:
|
|
|
323
323
|
aspect_ratio: opts.aspect,
|
|
324
324
|
resolution: opts.resolution,
|
|
325
325
|
duration_seconds: opts.duration ? Number(opts.duration) : undefined,
|
|
326
|
-
});
|
|
326
|
+
}, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
327
327
|
// Veo runs 30-120s; the bouncing bar + timer keeps the wait honest.
|
|
328
328
|
const started = Date.now();
|
|
329
329
|
const result = opts.json
|
|
@@ -396,7 +396,7 @@ Examples:
|
|
|
396
396
|
voice: opts.voice,
|
|
397
397
|
language: opts.language,
|
|
398
398
|
speakers,
|
|
399
|
-
});
|
|
399
|
+
}, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
400
400
|
const started = Date.now();
|
|
401
401
|
const result = opts.json
|
|
402
402
|
? await doGenerate()
|
|
@@ -467,7 +467,7 @@ Examples:
|
|
|
467
467
|
// Lyrics imply vocals; otherwise instrumental unless --vocals.
|
|
468
468
|
instrumental: lyrics ? false : !opts.vocals,
|
|
469
469
|
lyrics: lyrics || undefined,
|
|
470
|
-
});
|
|
470
|
+
}, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
471
471
|
const started = Date.now();
|
|
472
472
|
const result = opts.json
|
|
473
473
|
? await doGenerate()
|
|
@@ -521,7 +521,7 @@ Examples:
|
|
|
521
521
|
text,
|
|
522
522
|
duration_seconds: opts.duration,
|
|
523
523
|
prompt_influence: opts.influence,
|
|
524
|
-
});
|
|
524
|
+
}, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
525
525
|
const started = Date.now();
|
|
526
526
|
const result = opts.json
|
|
527
527
|
? await doGenerate()
|
package/dist/commands/init.js
CHANGED
|
@@ -4,15 +4,31 @@ import { existsSync, readFileSync } from 'fs';
|
|
|
4
4
|
import { getAccountSlug } from '../api.js';
|
|
5
5
|
import { getConfig, getConfigPath, saveConfigAt } from '../config.js';
|
|
6
6
|
import { getAuth } from '../auth.js';
|
|
7
|
-
import { slugify, setupProjectTools, SUPPORTED_TOOLS, DEFAULT_TOOLS, DEFAULT_SYNC_IGNORE } from '../setup.js';
|
|
7
|
+
import { slugify, setupProjectTools, SUPPORTED_TOOLS, DEFAULT_TOOLS, DEFAULT_SYNC_IGNORE, resolveProjectTools } from '../setup.js';
|
|
8
8
|
import { AGENT_ADAPTERS } from '../agents/index.js';
|
|
9
|
-
import { success, error as clrError, info, muted, bold } from '../colors.js';
|
|
9
|
+
import { success, error as clrError, info, muted, bold, brand } from '../colors.js';
|
|
10
10
|
import { confirm } from '../utils.js';
|
|
11
11
|
import { scanForAdoption, adoptCurrentDir, canAdoptCwd, formatBytes, formatCwdLabel, ADOPT_THRESHOLDS, } from '../adopt-cwd.js';
|
|
12
12
|
const TOOL_KEYS = SUPPORTED_TOOLS.map(t => t.key);
|
|
13
|
+
/** The tool keys to pin in .gipity.json, or null to leave the project on
|
|
14
|
+
* auto-detect. Only an explicit `--for` pins: a bare `init` records nothing,
|
|
15
|
+
* so the project keeps tracking whatever the user installs later. `--for all`
|
|
16
|
+
* is an explicit choice too - it pins the full set on purpose. */
|
|
17
|
+
function pinnedToolKeys(forFlag, tools) {
|
|
18
|
+
return forFlag ? tools.map(t => t.key) : null;
|
|
19
|
+
}
|
|
20
|
+
/** Which tools this `init` run sets up.
|
|
21
|
+
*
|
|
22
|
+
* No `--for` defers to the project: its existing pin if it has one, else
|
|
23
|
+
* what's installed here (resolveProjectTools). Falling straight through to
|
|
24
|
+
* detection instead would make a bare re-run of `init` quietly widen a pinned
|
|
25
|
+
* project back out - `--for opencode` today, then a plain `gipity init`
|
|
26
|
+
* tomorrow re-adds every installed agent's primer.
|
|
27
|
+
*
|
|
28
|
+
* On a FRESH init there is no config yet, so this is detection, as intended. */
|
|
13
29
|
function resolveTools(forFlag) {
|
|
14
30
|
if (!forFlag)
|
|
15
|
-
return
|
|
31
|
+
return resolveProjectTools();
|
|
16
32
|
const requested = forFlag.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
|
|
17
33
|
const unknown = requested.filter(k => !TOOL_KEYS.includes(k) && k !== 'all');
|
|
18
34
|
if (unknown.length) {
|
|
@@ -24,15 +40,19 @@ function resolveTools(forFlag) {
|
|
|
24
40
|
}
|
|
25
41
|
export const initCommand = new Command('init')
|
|
26
42
|
.description('Link this directory to a project')
|
|
27
|
-
.addHelpText('after', `\nWrites CLAUDE.md/AGENTS.md primer files so your AI coding tool understands Gipity, and installs the Gipity skills + file-sync hooks
|
|
43
|
+
.addHelpText('after', `\nWrites CLAUDE.md/AGENTS.md primer files so your AI coding tool understands Gipity, and installs the Gipity skills + file-sync hooks. By default it only sets up the tools actually installed here (${AGENT_ADAPTERS.map(a => a.displayName).join(', ')}, …) - use --for to choose explicitly.`)
|
|
28
44
|
.argument('[name]', 'Project name/slug (defaults to current directory name)')
|
|
29
45
|
.option('--agent <guid>', 'Agent GUID to use')
|
|
30
46
|
.option('--no-capture', 'Don\'t record Claude Code sessions in this directory to your Gipity project (sets captureHooks: false in .gipity.json)')
|
|
31
|
-
.option('--for <tools>', `Which AI tool primer files to write (comma-separated). Default:
|
|
47
|
+
.option('--for <tools>', `Which AI tool primer files to write (comma-separated). Default: the tools detected on this machine. An explicit --for is remembered in .gipity.json, so later commands don't re-add the others. Choices: ${TOOL_KEYS.join(', ')}, all`)
|
|
32
48
|
.addHelpText('after', `
|
|
33
49
|
Examples:
|
|
34
|
-
$ gipity init Link cwd as a new project (slug = dir name)
|
|
50
|
+
$ gipity init Link cwd as a new project (slug = dir name);
|
|
51
|
+
sets up the tools installed on this machine.
|
|
35
52
|
$ gipity init my-app Link cwd with an explicit slug.
|
|
53
|
+
$ gipity init --for opencode Only opencode - pinned, so a later
|
|
54
|
+
gipity build won't re-add the others.
|
|
55
|
+
$ gipity init --for all Every tool, whether installed or not.
|
|
36
56
|
$ gipity init --for codex AGENTS.md + Codex skills/sync hooks only.
|
|
37
57
|
$ gipity init --for grok AGENTS.md + the Gipity plugin in Grok only.
|
|
38
58
|
$ gipity init --for cursor,gemini Write only the Cursor + Gemini primers.
|
|
@@ -60,6 +80,14 @@ Working with an existing Gipity project:
|
|
|
60
80
|
}
|
|
61
81
|
const wantsClaude = tools.some(t => t.key === 'claude');
|
|
62
82
|
const primerSummary = tools.map(t => t.label).join(', ');
|
|
83
|
+
// Name what was left out, and how to get it. Silence here is what made the
|
|
84
|
+
// old write-everything default feel arbitrary in the other direction: a
|
|
85
|
+
// user with one agent could not tell whether a missing primer was a
|
|
86
|
+
// decision or a bug.
|
|
87
|
+
const skipped = DEFAULT_TOOLS.filter(d => !tools.some(t => t.key === d.key));
|
|
88
|
+
const skippedNote = skipped.length
|
|
89
|
+
? `${muted(`Skipped (not installed here): ${skipped.map(t => t.key).join(', ')} - add with`)} ${brand(`gipity init --for ${skipped.map(t => t.key).join(',')}`)}${muted('.')}`
|
|
90
|
+
: null;
|
|
63
91
|
try {
|
|
64
92
|
// Check auth
|
|
65
93
|
const auth = getAuth();
|
|
@@ -97,10 +125,20 @@ Working with an existing Gipity project:
|
|
|
97
125
|
existing.captureHooks = false;
|
|
98
126
|
changed = true;
|
|
99
127
|
}
|
|
128
|
+
// An explicit --for re-pins the project. Without persisting it,
|
|
129
|
+
// `gipity build` (which calls setupProjectTools() with no arguments)
|
|
130
|
+
// would re-add every tool's primer on its next run.
|
|
131
|
+
const pinned = pinnedToolKeys(opts.for, tools);
|
|
132
|
+
if (pinned && JSON.stringify(existing.tools ?? null) !== JSON.stringify(pinned)) {
|
|
133
|
+
existing.tools = pinned;
|
|
134
|
+
changed = true;
|
|
135
|
+
}
|
|
100
136
|
if (changed)
|
|
101
137
|
saveConfigAt(cwd, existing);
|
|
102
138
|
}
|
|
103
139
|
console.log(success(`Refreshed primer files: ${primerSummary}.`));
|
|
140
|
+
if (skippedNote)
|
|
141
|
+
console.log(skippedNote);
|
|
104
142
|
if (opts.capture === false) {
|
|
105
143
|
console.log(success('Session recording disabled for this project (captureHooks: false in .gipity.json).'));
|
|
106
144
|
}
|
|
@@ -168,15 +206,21 @@ Working with an existing Gipity project:
|
|
|
168
206
|
console.log(`Synced ${adopted.applied} change${adopted.applied > 1 ? 's' : ''} with Gipity.`);
|
|
169
207
|
// Session recording opt-out. Written after adopt so it lands in the
|
|
170
208
|
// freshly created .gipity.json regardless of how the link happened.
|
|
171
|
-
|
|
209
|
+
const pinnedFresh = pinnedToolKeys(opts.for, tools);
|
|
210
|
+
if (opts.capture === false || pinnedFresh) {
|
|
172
211
|
try {
|
|
173
212
|
const cfg = JSON.parse(readFileSync(resolve(cwd, '.gipity.json'), 'utf-8'));
|
|
174
|
-
|
|
213
|
+
if (opts.capture === false)
|
|
214
|
+
cfg.captureHooks = false;
|
|
215
|
+
if (pinnedFresh)
|
|
216
|
+
cfg.tools = pinnedFresh;
|
|
175
217
|
saveConfigAt(cwd, cfg);
|
|
176
218
|
}
|
|
177
|
-
catch { /* config missing/unreadable - nothing to
|
|
219
|
+
catch { /* config missing/unreadable - nothing to record */ }
|
|
178
220
|
}
|
|
179
221
|
console.log(success(`Wrote primer files: ${primerSummary}.`));
|
|
222
|
+
if (skippedNote)
|
|
223
|
+
console.log(skippedNote);
|
|
180
224
|
if (wantsClaude) {
|
|
181
225
|
console.log(success(`Ready! Run your coding agent here (${AGENT_ADAPTERS.map(a => a.key).join(', ')}), or \`gipity build\` to launch one with a picker.`));
|
|
182
226
|
// Recording happens by default (however Claude Code is launched), so
|
package/dist/commands/service.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
-
import { get, post, publicRequest, mintAppToken, ApiError } from '../api.js';
|
|
2
|
+
import { get, post, publicRequest, mintAppToken, ApiError, LONG_REQUEST_TIMEOUT_MS } from '../api.js';
|
|
3
3
|
import { getAuth } from '../auth.js';
|
|
4
4
|
import { requireConfig } from '../config.js';
|
|
5
5
|
import { bold, muted } from '../colors.js';
|
|
@@ -110,7 +110,12 @@ serviceCommand
|
|
|
110
110
|
res = await publicRequest(opts.get ? 'GET' : 'POST', url, opts.get ? undefined : body, headers);
|
|
111
111
|
}
|
|
112
112
|
else {
|
|
113
|
-
|
|
113
|
+
// Generation services (music, video, image, ...) can hold the request
|
|
114
|
+
// open for minutes - e.g. a GPU music model cold-starting from
|
|
115
|
+
// scale-to-zero renders nothing for 1-3 min first. The server bounds
|
|
116
|
+
// the work at 300s, so give POSTs that full budget instead of the 60s
|
|
117
|
+
// default (which killed every cold-start render at exactly 60s).
|
|
118
|
+
res = opts.get ? await get(url) : await post(url, body, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
|
|
114
119
|
}
|
|
115
120
|
}
|
|
116
121
|
catch (err) {
|
|
@@ -79,10 +79,14 @@ function readState(convGuid) {
|
|
|
79
79
|
try {
|
|
80
80
|
const raw = readFileSync(p, 'utf-8');
|
|
81
81
|
const parsed = JSON.parse(raw);
|
|
82
|
+
const posNum = (v) => (typeof v === 'number' && v >= 0 ? v : undefined);
|
|
82
83
|
return {
|
|
83
84
|
last_uuid: typeof parsed.last_uuid === 'string' ? parsed.last_uuid : null,
|
|
84
85
|
last_flush_ms: typeof parsed.last_flush_ms === 'number' ? parsed.last_flush_ms : undefined,
|
|
85
86
|
attached: typeof parsed.attached === 'boolean' ? parsed.attached : undefined,
|
|
87
|
+
pending_tokens_in: posNum(parsed.pending_tokens_in),
|
|
88
|
+
pending_tokens_out: posNum(parsed.pending_tokens_out),
|
|
89
|
+
pending_active_ms: posNum(parsed.pending_active_ms),
|
|
86
90
|
};
|
|
87
91
|
}
|
|
88
92
|
catch {
|
|
@@ -365,7 +369,51 @@ async function ensureAttached(convGuid, hook) {
|
|
|
365
369
|
if (ok)
|
|
366
370
|
writeState(convGuid, { ...(state ?? { last_uuid: null }), attached: true });
|
|
367
371
|
}
|
|
368
|
-
|
|
372
|
+
// A gap between consecutive transcript timestamps longer than this is idle
|
|
373
|
+
// time (e.g. a replayed range spanning the user's think-time between
|
|
374
|
+
// prompts), not agent work - skip it when estimating active time.
|
|
375
|
+
export const ACTIVE_GAP_MAX_MS = 5 * 60_000;
|
|
376
|
+
/** Estimate the agent's working time over a batch of entries: the sum of
|
|
377
|
+
* gaps between consecutive entry timestamps, skipping idle stretches.
|
|
378
|
+
* Within one prompt run the transcript grows continuously (tool calls,
|
|
379
|
+
* assistant chunks), so this tracks real work closely; the hook path has no
|
|
380
|
+
* agent-reported duration the way the relay's stream `result` footer does. */
|
|
381
|
+
export function activeMsFromEntries(entries) {
|
|
382
|
+
let total = 0;
|
|
383
|
+
let prev = null;
|
|
384
|
+
for (const e of entries) {
|
|
385
|
+
if (!e.ts)
|
|
386
|
+
continue;
|
|
387
|
+
const t = Date.parse(e.ts);
|
|
388
|
+
if (isNaN(t))
|
|
389
|
+
continue;
|
|
390
|
+
if (prev !== null) {
|
|
391
|
+
const gap = t - prev;
|
|
392
|
+
if (gap > 0 && gap <= ACTIVE_GAP_MAX_MS)
|
|
393
|
+
total += gap;
|
|
394
|
+
}
|
|
395
|
+
prev = t;
|
|
396
|
+
}
|
|
397
|
+
return total;
|
|
398
|
+
}
|
|
399
|
+
/** Fallback token totals for parsers that don't report `usage` (Codex, Grok):
|
|
400
|
+
* sum the assistant entries' token fields. Claude/opencode override this via
|
|
401
|
+
* ParseResult.usage - their per-entry fields undercount (no cache tokens)
|
|
402
|
+
* or repeat across lines, which a plain entry sum can't correct. */
|
|
403
|
+
export function entryTokenTotals(entries) {
|
|
404
|
+
let tokensIn = 0;
|
|
405
|
+
let tokensOut = 0;
|
|
406
|
+
for (const e of entries) {
|
|
407
|
+
if (e.kind !== 'assistant')
|
|
408
|
+
continue;
|
|
409
|
+
if (typeof e.input_tokens === 'number' && e.input_tokens > 0)
|
|
410
|
+
tokensIn += e.input_tokens;
|
|
411
|
+
if (typeof e.output_tokens === 'number' && e.output_tokens > 0)
|
|
412
|
+
tokensOut += e.output_tokens;
|
|
413
|
+
}
|
|
414
|
+
return { tokensIn, tokensOut };
|
|
415
|
+
}
|
|
416
|
+
async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs = 0, emitResult = false) {
|
|
369
417
|
void isSubagent;
|
|
370
418
|
if (!hook.transcript_path || !existsSync(hook.transcript_path))
|
|
371
419
|
return;
|
|
@@ -382,11 +430,13 @@ async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs =
|
|
|
382
430
|
try {
|
|
383
431
|
const state = readState(convGuid) ?? { last_uuid: null };
|
|
384
432
|
const content = await readWholeFile(hook.transcript_path);
|
|
433
|
+
let replayed = false;
|
|
385
434
|
let result = src.capture.parse(content, state.last_uuid, hook);
|
|
386
435
|
if (!result.foundWatermark && state.last_uuid !== null) {
|
|
387
436
|
// Transcript rotated (/clear or compact) - watermark isn't present.
|
|
388
437
|
// Replay from top; server dedupes via the source_uuid unique index.
|
|
389
438
|
result = src.capture.parse(content, null, hook);
|
|
439
|
+
replayed = true;
|
|
390
440
|
}
|
|
391
441
|
// Base64 image blocks (Read-of-image tool results) upload to VFS and
|
|
392
442
|
// become image_ref blocks — same no-inline-base64 chokepoint as the
|
|
@@ -395,11 +445,49 @@ async function handleStopFamily(convGuid, src, hook, isSubagent, minIntervalMs =
|
|
|
395
445
|
if (hook.cwd)
|
|
396
446
|
rewriter.setCwd(hook.cwd);
|
|
397
447
|
const entries = await rewriter.rewrite(result.entries);
|
|
448
|
+
// Roll this flush's token usage + working time into the pending
|
|
449
|
+
// counters. A replayed-from-top range re-parses lines whose rows the
|
|
450
|
+
// server already has (and whose tokens an earlier result already
|
|
451
|
+
// counted), so its usage is unknowable without server state - skip it
|
|
452
|
+
// rather than double-count; only the rotation boundary is undercounted.
|
|
453
|
+
const flushUsage = replayed
|
|
454
|
+
? { tokensIn: 0, tokensOut: 0 }
|
|
455
|
+
: result.usage ?? entryTokenTotals(result.entries);
|
|
456
|
+
const flushActive = replayed ? 0 : activeMsFromEntries(result.entries);
|
|
457
|
+
const pendIn = (state.pending_tokens_in ?? 0) + flushUsage.tokensIn;
|
|
458
|
+
const pendOut = (state.pending_tokens_out ?? 0) + flushUsage.tokensOut;
|
|
459
|
+
const pendActive = (state.pending_active_ms ?? 0) + flushActive;
|
|
460
|
+
// On a clean end-of-run event, emit the accumulated metrics as a
|
|
461
|
+
// `result` entry - the same footer the relay's stream path posts, which
|
|
462
|
+
// the server rolls into the conversation counters the projects list
|
|
463
|
+
// reads (tokens_in/tokens_out/active_ms). The source_uuid is
|
|
464
|
+
// deterministic in the watermark so a retried POST dedupes instead of
|
|
465
|
+
// double-counting. No cost here: only the stream footer reports cost.
|
|
466
|
+
let resultEmitted = false;
|
|
467
|
+
if (emitResult && result.lastUuid && (pendIn > 0 || pendOut > 0 || pendActive > 0)) {
|
|
468
|
+
const lastTs = [...entries].reverse().find((e) => e.ts)?.ts;
|
|
469
|
+
entries.push({
|
|
470
|
+
kind: 'result',
|
|
471
|
+
tokens_in: pendIn,
|
|
472
|
+
tokens_out: pendOut,
|
|
473
|
+
duration_ms: pendActive,
|
|
474
|
+
source_uuid: `${hook.session_id ?? convGuid}-result-${result.lastUuid}`,
|
|
475
|
+
...(lastTs ? { ts: lastTs } : {}),
|
|
476
|
+
});
|
|
477
|
+
resultEmitted = true;
|
|
478
|
+
}
|
|
398
479
|
const ok = await postEntries(convGuid, entries);
|
|
399
480
|
if (ok) {
|
|
400
481
|
// Stamp the flush time even when no new lines landed, so the throttle
|
|
401
482
|
// above measures from the last attempt. Keep the watermark if unchanged.
|
|
402
|
-
writeState(convGuid, {
|
|
483
|
+
writeState(convGuid, {
|
|
484
|
+
...state,
|
|
485
|
+
last_uuid: result.lastUuid ?? state.last_uuid,
|
|
486
|
+
last_flush_ms: Date.now(),
|
|
487
|
+
pending_tokens_in: resultEmitted ? 0 : pendIn,
|
|
488
|
+
pending_tokens_out: resultEmitted ? 0 : pendOut,
|
|
489
|
+
pending_active_ms: resultEmitted ? 0 : pendActive,
|
|
490
|
+
});
|
|
403
491
|
}
|
|
404
492
|
}
|
|
405
493
|
finally {
|
|
@@ -411,7 +499,7 @@ async function handleSessionEnd(convGuid, src, hook) {
|
|
|
411
499
|
// Stop, so there's usually nothing new, but a race between Stop and
|
|
412
500
|
// SessionEnd could leave lines behind.
|
|
413
501
|
if (hook.transcript_path && existsSync(hook.transcript_path)) {
|
|
414
|
-
await handleStopFamily(convGuid, src, hook, false);
|
|
502
|
+
await handleStopFamily(convGuid, src, hook, false, 0, true);
|
|
415
503
|
}
|
|
416
504
|
const sessionId = hook.session_id ?? 'unknown';
|
|
417
505
|
const entries = [{
|
|
@@ -518,7 +606,9 @@ async function main() {
|
|
|
518
606
|
case 'session-start':
|
|
519
607
|
break; // ensureAttached above already covers what this event used to do
|
|
520
608
|
case 'stop':
|
|
521
|
-
|
|
609
|
+
// End of a prompt run - flush AND roll the run's accumulated
|
|
610
|
+
// tokens/working time into the conversation via a result entry.
|
|
611
|
+
await handleStopFamily(convGuid, src, hook, false, 0, true);
|
|
522
612
|
break;
|
|
523
613
|
case 'subagent-stop':
|
|
524
614
|
await handleStopFamily(convGuid, src, hook, true);
|