gipity 1.1.13 → 1.1.15

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/api.js CHANGED
@@ -22,7 +22,11 @@ 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;
28
32
  // Media generation (music/video/image/speech, `service call` POSTs) can
@@ -48,6 +52,56 @@ async function fetchWithTimeout(url, init, timeoutMs, label) {
48
52
  throw e;
49
53
  }
50
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
+ }
51
105
  /** Resolve the Bearer token value. A GIPITY_TOKEN env var (a long-lived agent
52
106
  * API token) takes precedence over the saved session — the persistent,
53
107
  * login-free path for headless agents and CI. Falls back to the refreshed
@@ -149,21 +203,27 @@ export function post(path, body, opts) {
149
203
  export async function postForTarEntries(path, body, retried = false) {
150
204
  const headers = await getHeaders();
151
205
  const url = `${baseUrl()}${path}`;
152
- const res = await fetch(url, {
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, {
153
210
  method: 'POST',
154
211
  headers,
155
212
  body: body ? JSON.stringify(body) : undefined,
156
- });
213
+ }, LONG_REQUEST_TIMEOUT_MS, `POST ${path}`);
157
214
  if (await shouldRetryAfter401(res.status, retried)) {
215
+ await read(r => r.arrayBuffer().catch(() => null)); // drain + clear the body timer
158
216
  return postForTarEntries(path, body, true);
159
217
  }
160
218
  if (!res.ok) {
161
- const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
219
+ const json = await read(r => r.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } })));
162
220
  const err = json.error || { code: 'UNKNOWN', message: res.statusText };
163
221
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
164
222
  }
165
- if (!res.body)
223
+ if (!res.body) {
224
+ await read(async () => null); // clear the body timer before bailing out
166
225
  throw new ApiError(500, 'EMPTY_RESPONSE', 'Server returned no body');
226
+ }
167
227
  const extract = tar.extract();
168
228
  const entries = [];
169
229
  const done = new Promise((resolve, reject) => {
@@ -180,9 +240,11 @@ export async function postForTarEntries(path, body, retried = false) {
180
240
  extract.on('finish', () => resolve());
181
241
  extract.on('error', reject);
182
242
  });
183
- Readable.fromWeb(res.body).pipe(extract);
184
- await done;
185
- return entries;
243
+ return read(async () => {
244
+ Readable.fromWeb(res.body).pipe(extract);
245
+ await done;
246
+ return entries;
247
+ });
186
248
  }
187
249
  export function put(path, body) {
188
250
  return request('PUT', path, body);
@@ -219,16 +281,18 @@ export async function sendMessage(message) {
219
281
  /** Download a file as raw bytes (no JSON parsing) */
220
282
  export async function download(path, retried = false) {
221
283
  const url = `${baseUrl()}${path}`;
222
- const res = await fetch(url, {
284
+ const { res, read } = await fetchWithStagedTimeout(url, {
223
285
  headers: { ...clientHeaders(), 'Authorization': `Bearer ${await bearerToken()}` },
224
- });
286
+ }, DOWNLOAD_HEADER_TIMEOUT_MS, `GET ${path}`);
225
287
  if (await shouldRetryAfter401(res.status, retried)) {
288
+ await read(r => r.arrayBuffer().catch(() => null));
226
289
  return download(path, true);
227
290
  }
228
291
  if (!res.ok) {
292
+ await read(async () => null);
229
293
  throw new ApiError(res.status, 'DOWNLOAD_ERROR', with401Hint(res.status, `Download failed: ${res.statusText}`));
230
294
  }
231
- return Buffer.from(await res.arrayBuffer());
295
+ return read(async (r) => Buffer.from(await r.arrayBuffer()));
232
296
  }
233
297
  /** Download raw bytes plus the response headers - for binary endpoints whose
234
298
  * metadata rides headers (e.g. `GET /projects/:guid/export`, where
@@ -236,18 +300,21 @@ export async function download(path, retried = false) {
236
300
  * Non-2xx responses are parsed as standard JSON errors. */
237
301
  export async function downloadWithHeaders(path, retried = false) {
238
302
  const url = `${baseUrl()}${path}`;
239
- const res = await fetch(url, {
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, {
240
306
  headers: { ...clientHeaders(), 'Authorization': `Bearer ${await bearerToken()}` },
241
- });
307
+ }, LONG_REQUEST_TIMEOUT_MS, `GET ${path}`);
242
308
  if (await shouldRetryAfter401(res.status, retried)) {
309
+ await read(r => r.arrayBuffer().catch(() => null));
243
310
  return downloadWithHeaders(path, true);
244
311
  }
245
312
  if (!res.ok) {
246
- const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
313
+ const json = await read(r => r.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } })));
247
314
  const err = json.error || { code: 'UNKNOWN', message: res.statusText };
248
315
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
249
316
  }
250
- return { buffer: Buffer.from(await res.arrayBuffer()), headers: res.headers };
317
+ return read(async (r) => ({ buffer: Buffer.from(await r.arrayBuffer()), headers: r.headers }));
251
318
  }
252
319
  /** POST raw bytes (e.g. a .gip bundle) and parse the JSON response, returning
253
320
  * the HTTP status alongside it so callers can tell a clean 201 from a 207
@@ -377,11 +444,11 @@ export async function getAccountSlug() {
377
444
  * X-App-Token; no Authorization header is ever sent. */
378
445
  export async function publicRequest(method, path, body, extraHeaders) {
379
446
  const url = `${baseUrl()}${path}`;
380
- const res = await fetch(url, {
447
+ const res = await fetchWithTimeout(url, {
381
448
  method,
382
449
  headers: { ...clientHeaders(), 'Content-Type': 'application/json', ...extraHeaders },
383
450
  body: body === undefined ? undefined : JSON.stringify(body),
384
- });
451
+ }, REQUEST_TIMEOUT_MS, `${method} ${path}`);
385
452
  if (!res.ok) {
386
453
  const json = await res.json().catch(() => ({ error: { code: 'UNKNOWN', message: res.statusText } }));
387
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; // network blip - retry
226
+ continue;
214
227
  }
215
228
  if (res.ok) {
216
229
  const json = await res.json().catch(() => null);
@@ -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
- * NOTE: on macOS the OAuth token can live in the Keychain, which we can't read
38
- * non-interactively — so a `false` here may be a false-negative. Callers should
39
- * treat `false` as "offer the login step" rather than "definitely logged out."
40
- * (Tracked as an open question in the desktop onboarding spec.)
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
@@ -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. Headless
921
- // `-p` runs skip the dialog already, so this is only needed interactively.
922
- if (!nonInteractive)
923
- markFolderTrusted(process.cwd());
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(),
@@ -1138,6 +1152,20 @@ async function launchNonClaudeAgent(adapter, ctx) {
1138
1152
  const childEnv = { ...process.env };
1139
1153
  if (convGuid)
1140
1154
  childEnv.GIPITY_CONVERSATION_GUID = convGuid;
1155
+ // Pin project attribution for the agent's own model calls. opencode's
1156
+ // Gipity provider sends this as X-Gipity-Project so per-project cost
1157
+ // reporting sees the spend; without it every llm_agent ledger row lands
1158
+ // unattributed (project_id NULL), which is what happened to the first
1159
+ // cloud devbox sessions.
1160
+ //
1161
+ // The plugin's fallback is to read .gipity.json from the directory OPENCODE
1162
+ // reports, which is not reliably the linked project dir - the plugin has
1163
+ // always documented that a runner which knows the project should pin it
1164
+ // here, but nothing ever did. We do know it: this is the launch that just
1165
+ // resolved the config.
1166
+ const projectGuidForAgent = getConfig()?.projectGuid;
1167
+ if (projectGuidForAgent)
1168
+ childEnv.GIPITY_PROJECT = projectGuidForAgent;
1141
1169
  const agentCmd = resolveCommand(adapter.binary);
1142
1170
  const child = spawnCommand(agentCmd, agentArgs, {
1143
1171
  stdio: 'inherit',
@@ -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, isClaudeAuthenticated, probeClaudeAuthenticated } from '../claude-setup.js';
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
- // Default: cheap heuristic (poll-safe). With --probe-claude: a real (billed)
116
- // `claude -p` ping for a definitive answer.
117
- claude.authenticated = claude.installed && (opts.probeClaude ? probeClaudeAuthenticated() : isClaudeAuthenticated());
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
- console.log(`${muted('claude code ')} installed ${yn(env.claude.installed)} · authenticated ${yn(env.claude.authenticated)}`);
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
@@ -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 DEFAULT_TOOLS;
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 into the agent CLIs found on this machine (${AGENT_ADAPTERS.map(a => a.displayName).join(', ')}).`)
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: all except aider (opt-in - it also writes .aider.conf.yml). Choices: ${TOOL_KEYS.join(', ')}, all`)
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
- if (opts.capture === false) {
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
- cfg.captureHooks = false;
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 opt out of */ }
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