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/adopt-cwd.js
CHANGED
|
@@ -17,7 +17,6 @@ import { get, post, ApiError } from './api.js';
|
|
|
17
17
|
import { isSyncIgnored } from './setup.js';
|
|
18
18
|
import { finalizeLocalProject } from './project-setup.js';
|
|
19
19
|
import { getProjectsRoot } from './relay/paths.js';
|
|
20
|
-
import * as relayState from './relay/state.js';
|
|
21
20
|
const EASY_FILES = 200;
|
|
22
21
|
const EASY_BYTES = 100 * 1024 * 1024; // 100 MB
|
|
23
22
|
const REFUSE_FILES = 2000;
|
|
@@ -210,15 +209,15 @@ export async function adoptCurrentDir(opts) {
|
|
|
210
209
|
}
|
|
211
210
|
let isNew = false;
|
|
212
211
|
if (!project) {
|
|
213
|
-
|
|
212
|
+
// No autoChat: which agent will run here isn't known (init wires them
|
|
213
|
+
// all up; build's picker runs later), so a pre-created chat would guess
|
|
214
|
+
// `claude_code` and sit empty forever when another agent is used. The
|
|
215
|
+
// first captured session creates/reuses a conversation with the right
|
|
216
|
+
// source via the launch path or the capture runner's self-arm resolve.
|
|
214
217
|
const body = {
|
|
215
218
|
name: opts.projectName,
|
|
216
219
|
slug: opts.projectSlug,
|
|
217
220
|
};
|
|
218
|
-
if (device) {
|
|
219
|
-
body.autoChat = 'claude_code';
|
|
220
|
-
body.deviceGuid = device.guid;
|
|
221
|
-
}
|
|
222
221
|
try {
|
|
223
222
|
const res = await post('/projects', body);
|
|
224
223
|
project = res.data;
|
package/dist/api.js
CHANGED
|
@@ -22,9 +22,22 @@ export class ApiError extends Error {
|
|
|
22
22
|
// finish well within REQUEST_TIMEOUT_MS; the S3 PUT path keeps its own
|
|
23
23
|
// size-based timeout. Streaming downloads can't use a single total cap (a large
|
|
24
24
|
// but healthy tree would be cut off mid-stream), so downloadStream bounds only
|
|
25
|
-
// the time-to-first-byte here and an idle watchdog in sync.ts guards the body
|
|
25
|
+
// the time-to-first-byte here and an idle watchdog in sync.ts guards the body;
|
|
26
|
+
// the buffered large-body paths (download, downloadWithHeaders,
|
|
27
|
+
// postForTarEntries) use fetchWithStagedTimeout for the same two-phase reason.
|
|
28
|
+
// "Every" is literal: a raw fetch() here has no deadline at all, and one
|
|
29
|
+
// unbounded call is enough to hang a whole deploy while it holds the lock.
|
|
26
30
|
const REQUEST_TIMEOUT_MS = 60_000;
|
|
27
31
|
const DOWNLOAD_HEADER_TIMEOUT_MS = 30_000;
|
|
32
|
+
// Media generation (music/video/image/speech, `service call` POSTs) can
|
|
33
|
+
// legitimately run minutes in ONE request/response: a GPU-backed music model
|
|
34
|
+
// waking from scale-to-zero spends 1-3 min booting + loading weights before it
|
|
35
|
+
// renders a note, and Veo video runs 30-120s. The server bounds all of these at
|
|
36
|
+
// 300s (its provider fetch budget and the ALB idle timeout are both 300s), so
|
|
37
|
+
// the long-call cap sits just above that ceiling - the server's clearer error
|
|
38
|
+
// always arrives before the CLI gives up. Callers opt in per request; plain
|
|
39
|
+
// JSON calls keep the tight default so a wedged connection still fails fast.
|
|
40
|
+
export const LONG_REQUEST_TIMEOUT_MS = 310_000;
|
|
28
41
|
/** fetch() that rejects with a clean 408 ApiError if the whole exchange (headers
|
|
29
42
|
* + body) doesn't complete within timeoutMs, instead of hanging forever. For
|
|
30
43
|
* request/response JSON calls only - never wrap a long streaming body in this. */
|
|
@@ -39,6 +52,56 @@ async function fetchWithTimeout(url, init, timeoutMs, label) {
|
|
|
39
52
|
throw e;
|
|
40
53
|
}
|
|
41
54
|
}
|
|
55
|
+
/** fetch() for responses whose BODY may be large or slow to produce (a project
|
|
56
|
+
* export, a screenshot tar). A single total cap is wrong here (it would cut
|
|
57
|
+
* off a healthy large transfer), but NO cap lets a wedged socket hang forever,
|
|
58
|
+
* which is the stall that leaves a command silent, unkillable by any deadline,
|
|
59
|
+
* and still holding the project lock. So bound the two phases separately:
|
|
60
|
+
* `headerMs` for time-to-first-byte (the server does its work before it
|
|
61
|
+
* responds), then a size-aware body budget once the headers land.
|
|
62
|
+
*
|
|
63
|
+
* Callers MUST consume the response through the returned `read()` so the body
|
|
64
|
+
* deadline is cleared and an abort surfaces as a clean 408 rather than a bare
|
|
65
|
+
* AbortError. Every exit path, including parsing a non-2xx error body, has
|
|
66
|
+
* to go through it, or the timer outlives the request. */
|
|
67
|
+
async function fetchWithStagedTimeout(url, init, headerMs, label) {
|
|
68
|
+
const ac = new AbortController();
|
|
69
|
+
let timer = setTimeout(() => ac.abort(), headerMs);
|
|
70
|
+
let res;
|
|
71
|
+
try {
|
|
72
|
+
res = await fetch(url, { ...init, signal: ac.signal });
|
|
73
|
+
}
|
|
74
|
+
catch (e) {
|
|
75
|
+
clearTimeout(timer);
|
|
76
|
+
if (ac.signal.aborted) {
|
|
77
|
+
throw new ApiError(408, 'REQUEST_TIMEOUT', `${label} timed out after ${Math.round(headerMs / 1000)}s (no response from the server)`);
|
|
78
|
+
}
|
|
79
|
+
throw e;
|
|
80
|
+
}
|
|
81
|
+
// Headers are in: re-arm the same controller with a budget for the body,
|
|
82
|
+
// scaled by the declared length on the same throughput policy as the PUT path.
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
const declared = Number(res.headers.get('content-length') ?? 0);
|
|
85
|
+
const bodyMs = putTimeoutMs(Number.isFinite(declared) ? declared : 0);
|
|
86
|
+
timer = setTimeout(() => ac.abort(), bodyMs);
|
|
87
|
+
return {
|
|
88
|
+
res,
|
|
89
|
+
async read(fn) {
|
|
90
|
+
try {
|
|
91
|
+
return await fn(res);
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
if (ac.signal.aborted) {
|
|
95
|
+
throw new ApiError(408, 'REQUEST_TIMEOUT', `${label} stalled mid-body (no completion in ${Math.round(bodyMs / 1000)}s)`);
|
|
96
|
+
}
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
}
|
|
42
105
|
/** Resolve the Bearer token value. A GIPITY_TOKEN env var (a long-lived agent
|
|
43
106
|
* API token) takes precedence over the saved session — the persistent,
|
|
44
107
|
* login-free path for headless agents and CI. Falls back to the refreshed
|
|
@@ -111,16 +174,16 @@ export async function getAuthHeader() {
|
|
|
111
174
|
const headers = await getHeaders();
|
|
112
175
|
return headers.Authorization;
|
|
113
176
|
}
|
|
114
|
-
async function request(method, path, body, retrying = false) {
|
|
177
|
+
async function request(method, path, body, retrying = false, timeoutMs = REQUEST_TIMEOUT_MS) {
|
|
115
178
|
const headers = await getHeaders();
|
|
116
179
|
const url = `${baseUrl()}${path}`;
|
|
117
180
|
const res = await fetchWithTimeout(url, {
|
|
118
181
|
method,
|
|
119
182
|
headers,
|
|
120
183
|
body: body ? JSON.stringify(body) : undefined,
|
|
121
|
-
},
|
|
184
|
+
}, timeoutMs, `${method} ${path}`);
|
|
122
185
|
if (await shouldRetryAfter401(res.status, retrying)) {
|
|
123
|
-
return request(method, path, body, true);
|
|
186
|
+
return request(method, path, body, true, timeoutMs);
|
|
124
187
|
}
|
|
125
188
|
if (!res.ok) {
|
|
126
189
|
const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
|
|
@@ -132,29 +195,35 @@ async function request(method, path, body, retrying = false) {
|
|
|
132
195
|
export function get(path) {
|
|
133
196
|
return request('GET', path);
|
|
134
197
|
}
|
|
135
|
-
export function post(path, body) {
|
|
136
|
-
return request('POST', path, body);
|
|
198
|
+
export function post(path, body, opts) {
|
|
199
|
+
return request('POST', path, body, false, opts?.timeoutMs);
|
|
137
200
|
}
|
|
138
201
|
/** POST JSON and consume the response as a tar stream, returning each entry as
|
|
139
202
|
* { name, buffer } in arrival order. Non-2xx responses are parsed as JSON errors. */
|
|
140
203
|
export async function postForTarEntries(path, body, retried = false) {
|
|
141
204
|
const headers = await getHeaders();
|
|
142
205
|
const url = `${baseUrl()}${path}`;
|
|
143
|
-
|
|
206
|
+
// The capture (load + render across viewports) runs server-side BEFORE the
|
|
207
|
+
// first byte, so time-to-first-byte gets the long budget; the server bounds
|
|
208
|
+
// itself at 300s, so its own clearer error always beats this ceiling.
|
|
209
|
+
const { res, read } = await fetchWithStagedTimeout(url, {
|
|
144
210
|
method: 'POST',
|
|
145
211
|
headers,
|
|
146
212
|
body: body ? JSON.stringify(body) : undefined,
|
|
147
|
-
});
|
|
213
|
+
}, LONG_REQUEST_TIMEOUT_MS, `POST ${path}`);
|
|
148
214
|
if (await shouldRetryAfter401(res.status, retried)) {
|
|
215
|
+
await read(r => r.arrayBuffer().catch(() => null)); // drain + clear the body timer
|
|
149
216
|
return postForTarEntries(path, body, true);
|
|
150
217
|
}
|
|
151
218
|
if (!res.ok) {
|
|
152
|
-
const json = await
|
|
219
|
+
const json = await read(r => r.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } })));
|
|
153
220
|
const err = json.error || { code: 'UNKNOWN', message: res.statusText };
|
|
154
221
|
throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
|
|
155
222
|
}
|
|
156
|
-
if (!res.body)
|
|
223
|
+
if (!res.body) {
|
|
224
|
+
await read(async () => null); // clear the body timer before bailing out
|
|
157
225
|
throw new ApiError(500, 'EMPTY_RESPONSE', 'Server returned no body');
|
|
226
|
+
}
|
|
158
227
|
const extract = tar.extract();
|
|
159
228
|
const entries = [];
|
|
160
229
|
const done = new Promise((resolve, reject) => {
|
|
@@ -171,9 +240,11 @@ export async function postForTarEntries(path, body, retried = false) {
|
|
|
171
240
|
extract.on('finish', () => resolve());
|
|
172
241
|
extract.on('error', reject);
|
|
173
242
|
});
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
243
|
+
return read(async () => {
|
|
244
|
+
Readable.fromWeb(res.body).pipe(extract);
|
|
245
|
+
await done;
|
|
246
|
+
return entries;
|
|
247
|
+
});
|
|
177
248
|
}
|
|
178
249
|
export function put(path, body) {
|
|
179
250
|
return request('PUT', path, body);
|
|
@@ -210,16 +281,18 @@ export async function sendMessage(message) {
|
|
|
210
281
|
/** Download a file as raw bytes (no JSON parsing) */
|
|
211
282
|
export async function download(path, retried = false) {
|
|
212
283
|
const url = `${baseUrl()}${path}`;
|
|
213
|
-
const res = await
|
|
284
|
+
const { res, read } = await fetchWithStagedTimeout(url, {
|
|
214
285
|
headers: { ...clientHeaders(), 'Authorization': `Bearer ${await bearerToken()}` },
|
|
215
|
-
});
|
|
286
|
+
}, DOWNLOAD_HEADER_TIMEOUT_MS, `GET ${path}`);
|
|
216
287
|
if (await shouldRetryAfter401(res.status, retried)) {
|
|
288
|
+
await read(r => r.arrayBuffer().catch(() => null));
|
|
217
289
|
return download(path, true);
|
|
218
290
|
}
|
|
219
291
|
if (!res.ok) {
|
|
292
|
+
await read(async () => null);
|
|
220
293
|
throw new ApiError(res.status, 'DOWNLOAD_ERROR', with401Hint(res.status, `Download failed: ${res.statusText}`));
|
|
221
294
|
}
|
|
222
|
-
return Buffer.from(await
|
|
295
|
+
return read(async (r) => Buffer.from(await r.arrayBuffer()));
|
|
223
296
|
}
|
|
224
297
|
/** Download raw bytes plus the response headers - for binary endpoints whose
|
|
225
298
|
* metadata rides headers (e.g. `GET /projects/:guid/export`, where
|
|
@@ -227,18 +300,21 @@ export async function download(path, retried = false) {
|
|
|
227
300
|
* Non-2xx responses are parsed as standard JSON errors. */
|
|
228
301
|
export async function downloadWithHeaders(path, retried = false) {
|
|
229
302
|
const url = `${baseUrl()}${path}`;
|
|
230
|
-
|
|
303
|
+
// The bundle is assembled server-side before the first byte, so a big project
|
|
304
|
+
// legitimately waits; give time-to-first-byte the long budget, not the 30s one.
|
|
305
|
+
const { res, read } = await fetchWithStagedTimeout(url, {
|
|
231
306
|
headers: { ...clientHeaders(), 'Authorization': `Bearer ${await bearerToken()}` },
|
|
232
|
-
});
|
|
307
|
+
}, LONG_REQUEST_TIMEOUT_MS, `GET ${path}`);
|
|
233
308
|
if (await shouldRetryAfter401(res.status, retried)) {
|
|
309
|
+
await read(r => r.arrayBuffer().catch(() => null));
|
|
234
310
|
return downloadWithHeaders(path, true);
|
|
235
311
|
}
|
|
236
312
|
if (!res.ok) {
|
|
237
|
-
const json = await
|
|
313
|
+
const json = await read(r => r.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } })));
|
|
238
314
|
const err = json.error || { code: 'UNKNOWN', message: res.statusText };
|
|
239
315
|
throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
|
|
240
316
|
}
|
|
241
|
-
return { buffer: Buffer.from(await
|
|
317
|
+
return read(async (r) => ({ buffer: Buffer.from(await r.arrayBuffer()), headers: r.headers }));
|
|
242
318
|
}
|
|
243
319
|
/** POST raw bytes (e.g. a .gip bundle) and parse the JSON response, returning
|
|
244
320
|
* the HTTP status alongside it so callers can tell a clean 201 from a 207
|
|
@@ -368,11 +444,11 @@ export async function getAccountSlug() {
|
|
|
368
444
|
* X-App-Token; no Authorization header is ever sent. */
|
|
369
445
|
export async function publicRequest(method, path, body, extraHeaders) {
|
|
370
446
|
const url = `${baseUrl()}${path}`;
|
|
371
|
-
const res = await
|
|
447
|
+
const res = await fetchWithTimeout(url, {
|
|
372
448
|
method,
|
|
373
449
|
headers: { ...clientHeaders(), 'Content-Type': 'application/json', ...extraHeaders },
|
|
374
450
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
375
|
-
});
|
|
451
|
+
}, REQUEST_TIMEOUT_MS, `${method} ${path}`);
|
|
376
452
|
if (!res.ok) {
|
|
377
453
|
const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
|
|
378
454
|
const err = json.error || { code: 'UNKNOWN', message: res.statusText };
|
package/dist/auth.js
CHANGED
|
@@ -99,6 +99,17 @@ const delay = (ms) => new Promise(r => setTimeout(r, ms));
|
|
|
99
99
|
// wait, then re-read and ADOPT the freshly-rotated token instead of refreshing.
|
|
100
100
|
const LOCK_WAIT_MS = 10_000; // refresh is one quick round-trip; cap the wait
|
|
101
101
|
const LOCK_POLL_MS = 100;
|
|
102
|
+
// A refresh is a token lookup plus a signature, sub-second in practice. Without
|
|
103
|
+
// a deadline, though, a wedged socket (connected, then silent: a dropped NAT
|
|
104
|
+
// flow, a black-holed path) hangs this fetch FOREVER, and because every
|
|
105
|
+
// authenticated command resolves its bearer token through here, the whole CLI
|
|
106
|
+
// hangs with it, before any spinner or phase output exists to show it, and
|
|
107
|
+
// while sync already holds .gipity/sync.lock. That is the silent, unbounded
|
|
108
|
+
// "deploy just stalls" stall. Bound each attempt so a dead connection becomes a
|
|
109
|
+
// retry (and then a real error) instead of an infinite wait.
|
|
110
|
+
// (env override exists so the regression test can prove the timer actually
|
|
111
|
+
// fires without burning 3 x 15s of real wall clock).
|
|
112
|
+
const REFRESH_TIMEOUT_MS = Number(process.env.GIPITY_REFRESH_TIMEOUT_MS) || 15_000;
|
|
102
113
|
/** Acquire the global auth-refresh lock. Returns a release fn, or null if we
|
|
103
114
|
* couldn't get it within the wait window (caller then proceeds best-effort —
|
|
104
115
|
* refresh must never block a command indefinitely). Mirrors sync.ts's advisory
|
|
@@ -206,11 +217,13 @@ export async function refreshTokenIfNeeded(force = false) {
|
|
|
206
217
|
method: 'POST',
|
|
207
218
|
headers: { 'Content-Type': 'application/json' },
|
|
208
219
|
body: JSON.stringify({ refreshToken }),
|
|
220
|
+
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
|
|
209
221
|
});
|
|
210
222
|
}
|
|
211
223
|
catch {
|
|
224
|
+
// Network blip OR a timeout we just imposed - both are retryable here.
|
|
212
225
|
await delay(attempt * 300);
|
|
213
|
-
continue;
|
|
226
|
+
continue;
|
|
214
227
|
}
|
|
215
228
|
if (res.ok) {
|
|
216
229
|
const json = await res.json().catch(() => null);
|
|
@@ -176,6 +176,16 @@ export function parseTranscript(content, afterUuid) {
|
|
|
176
176
|
// whole file (including pre-watermark lines) so a result whose tool_use
|
|
177
177
|
// was forwarded in an earlier sweep still resolves its name.
|
|
178
178
|
const toolNames = new Map();
|
|
179
|
+
// Token totals for the newly parsed range. Claude Code splits one API
|
|
180
|
+
// response across several transcript lines (one per content block), each
|
|
181
|
+
// repeating the same `message.usage`, so count each `message.id` once.
|
|
182
|
+
// tokens_in is the full input side (fresh + cache-read + cache-creation)
|
|
183
|
+
// to match the relay result footer's semantics; the per-entry input_tokens
|
|
184
|
+
// stays fresh-input-only, which is why summing entries can't replace this.
|
|
185
|
+
const countedUsage = new Set();
|
|
186
|
+
let tokensIn = 0;
|
|
187
|
+
let tokensOut = 0;
|
|
188
|
+
const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
|
|
179
189
|
for (const raw of content.split('\n')) {
|
|
180
190
|
const line = raw.trim();
|
|
181
191
|
if (!line)
|
|
@@ -201,6 +211,18 @@ export function parseTranscript(content, afterUuid) {
|
|
|
201
211
|
seenWatermark = true;
|
|
202
212
|
continue;
|
|
203
213
|
}
|
|
214
|
+
// Usage is counted independently of entry emission: an assistant line
|
|
215
|
+
// whose content produced no entries still carries real token usage.
|
|
216
|
+
if (parsed?.type === 'assistant' && parsed?.isSidechain !== true) {
|
|
217
|
+
const m = parsed.message;
|
|
218
|
+
const u = m?.usage;
|
|
219
|
+
const key = typeof m?.id === 'string' && m.id ? m.id : parsed.uuid;
|
|
220
|
+
if (u && typeof key === 'string' && !countedUsage.has(key)) {
|
|
221
|
+
countedUsage.add(key);
|
|
222
|
+
tokensIn += num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
|
|
223
|
+
tokensOut += num(u.output_tokens);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
204
226
|
const entries = transcriptLineToEntries(parsed, toolNames);
|
|
205
227
|
if (entries.length) {
|
|
206
228
|
for (const e of entries)
|
|
@@ -218,6 +240,7 @@ export function parseTranscript(content, afterUuid) {
|
|
|
218
240
|
entries: out,
|
|
219
241
|
lastUuid,
|
|
220
242
|
foundWatermark: seenWatermark,
|
|
243
|
+
usage: { tokensIn, tokensOut },
|
|
221
244
|
};
|
|
222
245
|
}
|
|
223
246
|
//# sourceMappingURL=claude-code.js.map
|
|
@@ -149,6 +149,19 @@ function lineToEntries(parsed, sessionId, idx, toolNames) {
|
|
|
149
149
|
* *after* the positional watermark `afterUuid`. Same contract as the
|
|
150
150
|
* claude-code parser: returns entries in order, the new watermark, and
|
|
151
151
|
* whether the old watermark was still valid for this file. */
|
|
152
|
+
/** Cumulative token totals from a `token_count` event_msg, or null. The
|
|
153
|
+
* rollout's `info.total_token_usage` is the session running total and its
|
|
154
|
+
* `input_tokens` already includes cached input (verified against real
|
|
155
|
+
* rollouts: total_tokens = input_tokens + output_tokens), so range usage is
|
|
156
|
+
* a plain delta of totals - never a sum over events, which would re-count
|
|
157
|
+
* the whole session on every event. */
|
|
158
|
+
function tokenTotals(payload) {
|
|
159
|
+
const t = payload?.info?.total_token_usage;
|
|
160
|
+
if (!t || typeof t !== 'object')
|
|
161
|
+
return null;
|
|
162
|
+
const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
|
|
163
|
+
return { input: num(t.input_tokens), output: num(t.output_tokens) };
|
|
164
|
+
}
|
|
152
165
|
export function parseTranscript(content, afterUuid) {
|
|
153
166
|
const lines = content.split('\n');
|
|
154
167
|
// The session id lives in the first session_meta line. Without it we can
|
|
@@ -180,6 +193,10 @@ export function parseTranscript(content, afterUuid) {
|
|
|
180
193
|
const out = [];
|
|
181
194
|
const toolNames = new Map();
|
|
182
195
|
let lastIdx = startAfter;
|
|
196
|
+
// Cumulative token totals at the watermark (baseline) and at the end of
|
|
197
|
+
// the parsed range - their delta is this range's usage.
|
|
198
|
+
let baseUsage = null;
|
|
199
|
+
let lastUsage = null;
|
|
183
200
|
for (let i = 0; i < lines.length; i++) {
|
|
184
201
|
const line = lines[i].trim();
|
|
185
202
|
if (!line)
|
|
@@ -191,17 +208,23 @@ export function parseTranscript(content, afterUuid) {
|
|
|
191
208
|
catch {
|
|
192
209
|
continue;
|
|
193
210
|
}
|
|
211
|
+
const isTokenCount = parsed?.type === 'event_msg' && parsed?.payload?.type === 'token_count';
|
|
194
212
|
if (startAfter !== null && i <= startAfter) {
|
|
195
213
|
// Pre-watermark: record tool names only, so a post-watermark
|
|
196
|
-
// tool_result still resolves the name of an already-forwarded call
|
|
214
|
+
// tool_result still resolves the name of an already-forwarded call
|
|
215
|
+
// (and the running token total, so the range delta starts right).
|
|
197
216
|
const p = parsed?.payload;
|
|
198
217
|
if (parsed?.type === 'response_item' && p &&
|
|
199
218
|
(p.type === 'custom_tool_call' || p.type === 'function_call') &&
|
|
200
219
|
typeof p.call_id === 'string') {
|
|
201
220
|
toolNames.set(p.call_id, typeof p.name === 'string' && p.name ? p.name : 'tool');
|
|
202
221
|
}
|
|
222
|
+
if (isTokenCount)
|
|
223
|
+
baseUsage = tokenTotals(parsed.payload) ?? baseUsage;
|
|
203
224
|
continue;
|
|
204
225
|
}
|
|
226
|
+
if (isTokenCount)
|
|
227
|
+
lastUsage = tokenTotals(parsed.payload) ?? lastUsage;
|
|
205
228
|
const entries = lineToEntries(parsed, sessionId, i, toolNames);
|
|
206
229
|
for (const e of entries)
|
|
207
230
|
out.push(e);
|
|
@@ -211,6 +234,12 @@ export function parseTranscript(content, afterUuid) {
|
|
|
211
234
|
entries: out,
|
|
212
235
|
lastUuid: lastIdx === null ? afterUuid : positional(sessionId, lastIdx),
|
|
213
236
|
foundWatermark,
|
|
237
|
+
usage: lastUsage === null
|
|
238
|
+
? { tokensIn: 0, tokensOut: 0 }
|
|
239
|
+
: {
|
|
240
|
+
tokensIn: Math.max(0, lastUsage.input - (baseUsage?.input ?? 0)),
|
|
241
|
+
tokensOut: Math.max(0, lastUsage.output - (baseUsage?.output ?? 0)),
|
|
242
|
+
},
|
|
214
243
|
};
|
|
215
244
|
}
|
|
216
245
|
//# sourceMappingURL=codex.js.map
|
|
@@ -116,6 +116,12 @@ export function parseTranscript(content, afterUuid) {
|
|
|
116
116
|
const foundWatermark = afterUuid === null || watermarkLine !== -1;
|
|
117
117
|
const out = [];
|
|
118
118
|
let lastUuid = foundWatermark ? afterUuid : null;
|
|
119
|
+
// Token totals for the newly parsed range. tokens_in is the full input side
|
|
120
|
+
// (fresh input + cache read/write) to match the relay result footer's
|
|
121
|
+
// semantics; the per-entry input_tokens stays `tokens.input` only.
|
|
122
|
+
let tokensIn = 0;
|
|
123
|
+
let tokensOut = 0;
|
|
124
|
+
const num = (v) => (typeof v === 'number' && v > 0 ? v : 0);
|
|
119
125
|
for (let i = 0; i < lines.length; i++) {
|
|
120
126
|
if (watermarkLine !== -1 && i <= watermarkLine)
|
|
121
127
|
continue;
|
|
@@ -129,14 +135,22 @@ export function parseTranscript(content, afterUuid) {
|
|
|
129
135
|
catch {
|
|
130
136
|
continue;
|
|
131
137
|
}
|
|
132
|
-
const
|
|
138
|
+
const info = parsed?.info;
|
|
139
|
+
const entries = messageToEntries(info, Array.isArray(parsed?.parts) ? parsed.parts : []);
|
|
133
140
|
if (!entries.length)
|
|
134
141
|
continue;
|
|
142
|
+
// Count usage only for lines that emit entries: entry-less lines don't
|
|
143
|
+
// advance the watermark, so counting them would re-add their tokens on
|
|
144
|
+
// every subsequent flush.
|
|
145
|
+
if (info?.role === 'assistant' && info?.tokens) {
|
|
146
|
+
tokensIn += num(info.tokens.input) + num(info.tokens.cache?.read) + num(info.tokens.cache?.write);
|
|
147
|
+
tokensOut += num(info.tokens.output);
|
|
148
|
+
}
|
|
135
149
|
for (const e of entries)
|
|
136
150
|
out.push(e);
|
|
137
|
-
if (typeof
|
|
138
|
-
lastUuid =
|
|
151
|
+
if (typeof info?.id === 'string')
|
|
152
|
+
lastUuid = info.id;
|
|
139
153
|
}
|
|
140
|
-
return { entries: out, lastUuid, foundWatermark };
|
|
154
|
+
return { entries: out, lastUuid, foundWatermark, usage: { tokensIn, tokensOut } };
|
|
141
155
|
}
|
|
142
156
|
//# sourceMappingURL=opencode.js.map
|
package/dist/claude-setup.js
CHANGED
|
@@ -12,7 +12,12 @@ import { execSync } from 'child_process';
|
|
|
12
12
|
import { existsSync } from 'fs';
|
|
13
13
|
import { homedir } from 'os';
|
|
14
14
|
import { join } from 'path';
|
|
15
|
+
import { resolveCommand, spawnCommand } from './platform.js';
|
|
15
16
|
export const CLAUDE_PACKAGE = '@anthropic-ai/claude-code';
|
|
17
|
+
/** `claude auth status` is a local credential read (no LLM call, not billed),
|
|
18
|
+
* but it is still a process spawn - budget a few seconds and treat an overrun
|
|
19
|
+
* as "unknown". */
|
|
20
|
+
const AUTH_STATUS_TIMEOUT_MS = 15_000;
|
|
16
21
|
/** Pure: the platform-appropriate detect + install commands. Unit-tested. */
|
|
17
22
|
export function claudeInstallPlan(platformOverride) {
|
|
18
23
|
const plat = platformOverride ?? process.platform;
|
|
@@ -31,19 +36,119 @@ export function isClaudeInstalled(platformOverride) {
|
|
|
31
36
|
return false;
|
|
32
37
|
}
|
|
33
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Ask Claude Code itself whether it is logged in.
|
|
41
|
+
*
|
|
42
|
+
* This is the authoritative check: Claude Code reads its OWN credential store,
|
|
43
|
+
* so it works on macOS (Keychain) where an outside file probe cannot, and it
|
|
44
|
+
* reflects a revoked or lapsed token that a file-existence check would happily
|
|
45
|
+
* call "logged in". It is NOT billed (no LLM call) but it does spawn a process
|
|
46
|
+
* and costs ~2s, so call it on the failure path or the periodic heartbeat, not
|
|
47
|
+
* on every dispatch.
|
|
48
|
+
*
|
|
49
|
+
* Returns null when the question can't be answered (Claude Code absent, or too
|
|
50
|
+
* old to have `auth status`) so callers can distinguish "definitely logged out"
|
|
51
|
+
* from "don't know" instead of reporting a confident wrong answer.
|
|
52
|
+
*/
|
|
53
|
+
export function claudeAuthStatus() {
|
|
54
|
+
if (!isClaudeInstalled())
|
|
55
|
+
return null;
|
|
56
|
+
try {
|
|
57
|
+
return parseClaudeAuthStatus(execSync('claude auth status --json', {
|
|
58
|
+
timeout: AUTH_STATUS_TIMEOUT_MS,
|
|
59
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
60
|
+
encoding: 'utf-8',
|
|
61
|
+
windowsHide: true,
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Non-zero exit, timeout, or unparseable output (an older Claude Code with
|
|
66
|
+
// no `auth status` subcommand). Unknown, not "logged out".
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Async twin of {@link claudeAuthStatus}, for callers that share an event loop
|
|
71
|
+
* with other work. The relay daemon runs its heartbeat, dispatch and
|
|
72
|
+
* cancellation loops on ONE loop, so a ~2s execSync there would freeze all of
|
|
73
|
+
* them (the same reason diagnostics probes are async). Never rejects. */
|
|
74
|
+
export function claudeAuthStatusAsync() {
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
let out = '';
|
|
77
|
+
let settled = false;
|
|
78
|
+
const done = (v) => { if (!settled) {
|
|
79
|
+
settled = true;
|
|
80
|
+
resolve(v);
|
|
81
|
+
} };
|
|
82
|
+
let child;
|
|
83
|
+
try {
|
|
84
|
+
child = spawnCommand(resolveCommand('claude'), ['auth', 'status', '--json'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return done(null);
|
|
88
|
+
}
|
|
89
|
+
const timer = setTimeout(() => {
|
|
90
|
+
try {
|
|
91
|
+
child.kill('SIGKILL');
|
|
92
|
+
}
|
|
93
|
+
catch { /* already gone */ }
|
|
94
|
+
done(null);
|
|
95
|
+
}, AUTH_STATUS_TIMEOUT_MS);
|
|
96
|
+
child.stdout?.on('data', (d) => { out += d.toString(); });
|
|
97
|
+
child.on('error', () => { clearTimeout(timer); done(null); });
|
|
98
|
+
child.on('close', () => { clearTimeout(timer); done(parseClaudeAuthStatus(out)); });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** Parse `claude auth status --json`. Returns null on anything unexpected, so
|
|
102
|
+
* "couldn't tell" never masquerades as "logged out". Exported for tests. */
|
|
103
|
+
export function parseClaudeAuthStatus(out) {
|
|
104
|
+
try {
|
|
105
|
+
const parsed = JSON.parse(out);
|
|
106
|
+
if (typeof parsed?.loggedIn !== 'boolean')
|
|
107
|
+
return null;
|
|
108
|
+
return {
|
|
109
|
+
loggedIn: parsed.loggedIn,
|
|
110
|
+
authMethod: parsed.authMethod,
|
|
111
|
+
email: parsed.email,
|
|
112
|
+
subscriptionType: parsed.subscriptionType,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
34
119
|
/**
|
|
35
120
|
* Best-effort, positive-evidence-only check for "Claude Code is logged in."
|
|
36
121
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
122
|
+
* Prefers `claude auth status` (authoritative, sees the Keychain, notices a
|
|
123
|
+
* revoked token) and falls back to the old env/file heuristic only when that
|
|
124
|
+
* can't answer, e.g. a Claude Code too old to have the subcommand. The
|
|
125
|
+
* fallback keeps the original caveat: on macOS the OAuth token can live in the
|
|
126
|
+
* Keychain, which we can't read, so a `false` from the FALLBACK may be a
|
|
127
|
+
* false-negative. Callers wanting certainty should use claudeAuthStatus()
|
|
128
|
+
* directly and treat null as "unknown".
|
|
41
129
|
*/
|
|
42
130
|
export function isClaudeAuthenticated() {
|
|
131
|
+
return claudeAuthStatus()?.loggedIn ?? claudeCredentialHeuristic();
|
|
132
|
+
}
|
|
133
|
+
/** The pre-`auth status` fallback: an env token, or a credentials file on disk.
|
|
134
|
+
* Cheap (no spawn) but blind to the macOS Keychain and to revoked tokens, so
|
|
135
|
+
* it is only correct as a LAST resort. Exported so a caller that has already
|
|
136
|
+
* paid for claudeAuthStatus() can fall back without spawning it a second time. */
|
|
137
|
+
export function claudeCredentialHeuristic() {
|
|
43
138
|
if (process.env.CLAUDE_CODE_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY)
|
|
44
139
|
return true;
|
|
45
140
|
return existsSync(join(homedir(), '.claude', '.credentials.json'));
|
|
46
141
|
}
|
|
142
|
+
/** The actionable "log in to Claude Code" line. `deviceName` names the machine
|
|
143
|
+
* that needs it, because the person reading this is usually in a browser on a
|
|
144
|
+
* DIFFERENT machine: Claude Code's own "run /login" is advice for someone
|
|
145
|
+
* sitting at a Claude Code prompt, which the reader is not. The login is an
|
|
146
|
+
* interactive browser flow, so it has to happen on that machine by hand. */
|
|
147
|
+
export function claudeLoginHint(deviceName) {
|
|
148
|
+
const where = deviceName ? `on ${deviceName}` : 'on that machine';
|
|
149
|
+
return `Claude Code is not logged in ${where}. Run \`claude auth login\` there `
|
|
150
|
+
+ 'and sign in, then send this again.';
|
|
151
|
+
}
|
|
47
152
|
/**
|
|
48
153
|
* Definitive auth check: actually run a tiny headless `claude -p` ping. If it
|
|
49
154
|
* returns output, Claude Code is authenticated. This is the reliable check
|
package/dist/commands/build.js
CHANGED
|
@@ -10,7 +10,7 @@ import { get, post, ApiError, getAccountSlug } from '../api.js';
|
|
|
10
10
|
import { interactiveLogin } from '../login-flow.js';
|
|
11
11
|
import { getConfig, saveConfigAt, clearConfigCache, getApiBaseOverride, DEFAULT_API_BASE, getConfigPath } from '../config.js';
|
|
12
12
|
import { sync } from '../sync.js';
|
|
13
|
-
import { slugify, ensureGipityPluginInstalled, setupProjectTools, DEFAULT_SYNC_IGNORE, isSyncIgnored } from '../setup.js';
|
|
13
|
+
import { slugify, ensureGipityPluginInstalled, setupProjectTools, setupToolForAgent, DEFAULT_SYNC_IGNORE, isSyncIgnored } from '../setup.js';
|
|
14
14
|
import { buildProjectContextBlock as buildProjectContextBlockText, buildNewProjectPrompt, buildResumeWrap, buildFreshWrap, } from '../prompts.js';
|
|
15
15
|
import * as relayState from '../relay/state.js';
|
|
16
16
|
import { maybeOfferRelayOn, ensureDaemonRunning } from '../relay/onboarding.js';
|
|
@@ -700,6 +700,12 @@ async function runLaunch(cmdName, cmdCfg, opts) {
|
|
|
700
700
|
}
|
|
701
701
|
}
|
|
702
702
|
const adapter = getAdapter(agentKey);
|
|
703
|
+
// The project's tool set was resolved above, before we knew which agent
|
|
704
|
+
// the user would pick (the picker runs after). A project pinned to one
|
|
705
|
+
// tool - or set up on a machine where this agent wasn't installed yet -
|
|
706
|
+
// would otherwise launch this agent with no primer and no capture hooks.
|
|
707
|
+
// Idempotent: a no-op when the agent is already part of the project.
|
|
708
|
+
setupToolForAgent(adapter.key);
|
|
703
709
|
// We never ask about the model: an explicit `--model` passes straight
|
|
704
710
|
// through to the agent, and with no flag the agent's own default (and
|
|
705
711
|
// its own model memory) stays authoritative. Only an interactive pick
|
|
@@ -917,10 +923,18 @@ async function runLaunch(cmdName, cmdCfg, opts) {
|
|
|
917
923
|
}
|
|
918
924
|
// A Gipity project directory is trusted by construction - the user
|
|
919
925
|
// created or explicitly chose it. Pre-accept Claude's per-directory
|
|
920
|
-
// trust dialog so an interactive launch doesn't stop to ask.
|
|
921
|
-
//
|
|
922
|
-
|
|
923
|
-
|
|
926
|
+
// trust dialog so an interactive launch doesn't stop to ask.
|
|
927
|
+
//
|
|
928
|
+
// This runs for HEADLESS runs too. It used to be skipped for `-p` on the
|
|
929
|
+
// theory that "headless runs skip the dialog already" - true of the
|
|
930
|
+
// blocking prompt, but NOT of its consequences: an untrusted workspace
|
|
931
|
+
// makes Claude Code discard the project's whole permissions.allow list
|
|
932
|
+
// ("Ignoring 32 permissions.allow entries ... this workspace has not been
|
|
933
|
+
// trusted"). That failure is silent and deferred - the agent just gets
|
|
934
|
+
// denied tools it was configured to have, mid-run, with nothing tying it
|
|
935
|
+
// back to trust. Relay dispatches are the main headless path, so they
|
|
936
|
+
// were the main victims. markFolderTrusted is idempotent and best-effort.
|
|
937
|
+
markFolderTrusted(process.cwd());
|
|
924
938
|
const child = spawnCommand(claudeCmd, allArgs, {
|
|
925
939
|
stdio: 'inherit',
|
|
926
940
|
cwd: process.cwd(),
|
|
@@ -1395,12 +1409,12 @@ async function createNewProject(existingSlugs, preset) {
|
|
|
1395
1409
|
continue;
|
|
1396
1410
|
}
|
|
1397
1411
|
try {
|
|
1398
|
-
|
|
1412
|
+
// No autoChat here: the agent isn't chosen yet (the picker runs after
|
|
1413
|
+
// project setup), so a pre-created chat would guess `claude_code` and
|
|
1414
|
+
// sit empty forever whenever the user picks another agent. The launch
|
|
1415
|
+
// path creates (or the placeholder-reuse logic finds) the conversation
|
|
1416
|
+
// with the RIGHT source moments later.
|
|
1399
1417
|
const body = { name: projectName, slug: projectSlug };
|
|
1400
|
-
if (device) {
|
|
1401
|
-
body.autoChat = 'claude_code';
|
|
1402
|
-
body.deviceGuid = device.guid;
|
|
1403
|
-
}
|
|
1404
1418
|
const res = await post('/projects', body);
|
|
1405
1419
|
// Single console.log keeps the line on the headless stderr stream -
|
|
1406
1420
|
// process.stdout.write would leak the message onto the child's stdout.
|