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/index.js CHANGED
@@ -4218,7 +4218,8 @@ async function refreshTokenIfNeeded(force = false) {
4218
4218
  res = await fetch(`${apiBase2}/auth/refresh`, {
4219
4219
  method: "POST",
4220
4220
  headers: { "Content-Type": "application/json" },
4221
- body: JSON.stringify({ refreshToken })
4221
+ body: JSON.stringify({ refreshToken }),
4222
+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS)
4222
4223
  });
4223
4224
  } catch {
4224
4225
  await delay(attempt * 300);
@@ -4252,7 +4253,7 @@ async function forceRefreshAccessToken() {
4252
4253
  await refreshTokenIfNeeded(true);
4253
4254
  return !accessTokenExpired();
4254
4255
  }
4255
- var AUTH_DIR, AUTH_FILE, AUTH_LOCK_FILE, cached, delay, LOCK_WAIT_MS, LOCK_POLL_MS;
4256
+ var AUTH_DIR, AUTH_FILE, AUTH_LOCK_FILE, cached, delay, LOCK_WAIT_MS, LOCK_POLL_MS, REFRESH_TIMEOUT_MS;
4256
4257
  var init_auth = __esm({
4257
4258
  "src/auth.ts"() {
4258
4259
  "use strict";
@@ -4264,6 +4265,7 @@ var init_auth = __esm({
4264
4265
  delay = (ms2) => new Promise((r) => setTimeout(r, ms2));
4265
4266
  LOCK_WAIT_MS = 1e4;
4266
4267
  LOCK_POLL_MS = 100;
4268
+ REFRESH_TIMEOUT_MS = Number(process.env.GIPITY_REFRESH_TIMEOUT_MS) || 15e3;
4267
4269
  }
4268
4270
  });
4269
4271
 
@@ -6621,8 +6623,56 @@ var init_self_update = __esm({
6621
6623
  }
6622
6624
  });
6623
6625
 
6626
+ // src/platform.ts
6627
+ var platform_exports = {};
6628
+ __export(platform_exports, {
6629
+ isBatchShim: () => isBatchShim,
6630
+ resolveCommand: () => resolveCommand,
6631
+ spawnCommand: () => spawnCommand,
6632
+ spawnSyncCommand: () => spawnSyncCommand,
6633
+ winBatchInvocation: () => winBatchInvocation
6634
+ });
6635
+ import { execSync as execSync2, spawn, spawnSync } from "child_process";
6636
+ function resolveCommand(cmd) {
6637
+ if (process.platform !== "win32") return cmd;
6638
+ try {
6639
+ const lines = execSync2(`where ${cmd}`, { encoding: "utf-8", windowsHide: true }).split(/\r?\n/).map((l7) => l7.trim()).filter(Boolean);
6640
+ return lines.find((l7) => l7.endsWith(".exe")) || lines.find((l7) => l7.endsWith(".cmd")) || cmd;
6641
+ } catch {
6642
+ return `${cmd}.cmd`;
6643
+ }
6644
+ }
6645
+ function isBatchShim(cmd) {
6646
+ return process.platform === "win32" && /\.(cmd|bat)$/i.test(cmd);
6647
+ }
6648
+ function winBatchInvocation(cmd, args) {
6649
+ const comspec = process.env.ComSpec || "cmd.exe";
6650
+ const quote = (t) => `"${String(t).replace(/"/g, '""')}"`;
6651
+ const line = [cmd, ...args].map(quote).join(" ");
6652
+ return { file: comspec, args: ["/d", "/s", "/c", `"${line}"`] };
6653
+ }
6654
+ function spawnCommand(cmd, args = [], options = {}) {
6655
+ if (isBatchShim(cmd)) {
6656
+ const inv = winBatchInvocation(cmd, args);
6657
+ return spawn(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6658
+ }
6659
+ return spawn(cmd, [...args], { windowsHide: true, ...options });
6660
+ }
6661
+ function spawnSyncCommand(cmd, args = [], options = {}) {
6662
+ if (isBatchShim(cmd)) {
6663
+ const inv = winBatchInvocation(cmd, args);
6664
+ return spawnSync(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6665
+ }
6666
+ return spawnSync(cmd, [...args], { windowsHide: true, ...options });
6667
+ }
6668
+ var init_platform = __esm({
6669
+ "src/platform.ts"() {
6670
+ "use strict";
6671
+ }
6672
+ });
6673
+
6624
6674
  // src/claude-setup.ts
6625
- import { execSync as execSync2 } from "child_process";
6675
+ import { execSync as execSync3 } from "child_process";
6626
6676
  import { existsSync as existsSync3 } from "fs";
6627
6677
  import { homedir as homedir2 } from "os";
6628
6678
  import { join as join4 } from "path";
@@ -6635,20 +6685,91 @@ function claudeInstallPlan(platformOverride) {
6635
6685
  }
6636
6686
  function isClaudeInstalled(platformOverride) {
6637
6687
  try {
6638
- execSync2(claudeInstallPlan(platformOverride).checkCmd, { stdio: "ignore", windowsHide: true });
6688
+ execSync3(claudeInstallPlan(platformOverride).checkCmd, { stdio: "ignore", windowsHide: true });
6639
6689
  return true;
6640
6690
  } catch {
6641
6691
  return false;
6642
6692
  }
6643
6693
  }
6644
- function isClaudeAuthenticated() {
6694
+ function claudeAuthStatus() {
6695
+ if (!isClaudeInstalled()) return null;
6696
+ try {
6697
+ return parseClaudeAuthStatus(execSync3("claude auth status --json", {
6698
+ timeout: AUTH_STATUS_TIMEOUT_MS,
6699
+ stdio: ["ignore", "pipe", "ignore"],
6700
+ encoding: "utf-8",
6701
+ windowsHide: true
6702
+ }));
6703
+ } catch {
6704
+ return null;
6705
+ }
6706
+ }
6707
+ function claudeAuthStatusAsync() {
6708
+ return new Promise((resolve19) => {
6709
+ let out = "";
6710
+ let settled = false;
6711
+ const done = (v7) => {
6712
+ if (!settled) {
6713
+ settled = true;
6714
+ resolve19(v7);
6715
+ }
6716
+ };
6717
+ let child;
6718
+ try {
6719
+ child = spawnCommand(
6720
+ resolveCommand("claude"),
6721
+ ["auth", "status", "--json"],
6722
+ { stdio: ["ignore", "pipe", "ignore"] }
6723
+ );
6724
+ } catch {
6725
+ return done(null);
6726
+ }
6727
+ const timer = setTimeout(() => {
6728
+ try {
6729
+ child.kill("SIGKILL");
6730
+ } catch {
6731
+ }
6732
+ done(null);
6733
+ }, AUTH_STATUS_TIMEOUT_MS);
6734
+ child.stdout?.on("data", (d) => {
6735
+ out += d.toString();
6736
+ });
6737
+ child.on("error", () => {
6738
+ clearTimeout(timer);
6739
+ done(null);
6740
+ });
6741
+ child.on("close", () => {
6742
+ clearTimeout(timer);
6743
+ done(parseClaudeAuthStatus(out));
6744
+ });
6745
+ });
6746
+ }
6747
+ function parseClaudeAuthStatus(out) {
6748
+ try {
6749
+ const parsed = JSON.parse(out);
6750
+ if (typeof parsed?.loggedIn !== "boolean") return null;
6751
+ return {
6752
+ loggedIn: parsed.loggedIn,
6753
+ authMethod: parsed.authMethod,
6754
+ email: parsed.email,
6755
+ subscriptionType: parsed.subscriptionType
6756
+ };
6757
+ } catch {
6758
+ return null;
6759
+ }
6760
+ }
6761
+ function claudeCredentialHeuristic() {
6645
6762
  if (process.env.CLAUDE_CODE_OAUTH_TOKEN || process.env.ANTHROPIC_API_KEY) return true;
6646
6763
  return existsSync3(join4(homedir2(), ".claude", ".credentials.json"));
6647
6764
  }
6765
+ function claudeLoginHint(deviceName) {
6766
+ const where = deviceName ? `on ${deviceName}` : "on that machine";
6767
+ return `Claude Code is not logged in ${where}. Run \`claude auth login\` there and sign in, then send this again.`;
6768
+ }
6648
6769
  function probeClaudeAuthenticated() {
6649
6770
  if (!isClaudeInstalled()) return false;
6650
6771
  try {
6651
- const out = execSync2('claude -p "Reply with the single word: PONG"', {
6772
+ const out = execSync3('claude -p "Reply with the single word: PONG"', {
6652
6773
  timeout: 6e4,
6653
6774
  stdio: ["ignore", "pipe", "ignore"],
6654
6775
  encoding: "utf-8",
@@ -6663,16 +6784,18 @@ function ensureClaudeInstalled(opts = {}) {
6663
6784
  if (!opts.force && isClaudeInstalled()) return { installed: true, alreadyPresent: true };
6664
6785
  const { installArgv } = claudeInstallPlan();
6665
6786
  try {
6666
- execSync2(installArgv.join(" "), { stdio: opts.quiet ? "ignore" : "inherit", windowsHide: true });
6787
+ execSync3(installArgv.join(" "), { stdio: opts.quiet ? "ignore" : "inherit", windowsHide: true });
6667
6788
  } catch {
6668
6789
  }
6669
6790
  return { installed: isClaudeInstalled(), alreadyPresent: false };
6670
6791
  }
6671
- var CLAUDE_PACKAGE;
6792
+ var CLAUDE_PACKAGE, AUTH_STATUS_TIMEOUT_MS;
6672
6793
  var init_claude_setup = __esm({
6673
6794
  "src/claude-setup.ts"() {
6674
6795
  "use strict";
6796
+ init_platform();
6675
6797
  CLAUDE_PACKAGE = "@anthropic-ai/claude-code";
6798
+ AUTH_STATUS_TIMEOUT_MS = 15e3;
6676
6799
  }
6677
6800
  });
6678
6801
 
@@ -6820,54 +6943,6 @@ var init_claude_code = __esm({
6820
6943
  }
6821
6944
  });
6822
6945
 
6823
- // src/platform.ts
6824
- var platform_exports = {};
6825
- __export(platform_exports, {
6826
- isBatchShim: () => isBatchShim,
6827
- resolveCommand: () => resolveCommand,
6828
- spawnCommand: () => spawnCommand,
6829
- spawnSyncCommand: () => spawnSyncCommand,
6830
- winBatchInvocation: () => winBatchInvocation
6831
- });
6832
- import { execSync as execSync3, spawn, spawnSync } from "child_process";
6833
- function resolveCommand(cmd) {
6834
- if (process.platform !== "win32") return cmd;
6835
- try {
6836
- const lines = execSync3(`where ${cmd}`, { encoding: "utf-8", windowsHide: true }).split(/\r?\n/).map((l7) => l7.trim()).filter(Boolean);
6837
- return lines.find((l7) => l7.endsWith(".exe")) || lines.find((l7) => l7.endsWith(".cmd")) || cmd;
6838
- } catch {
6839
- return `${cmd}.cmd`;
6840
- }
6841
- }
6842
- function isBatchShim(cmd) {
6843
- return process.platform === "win32" && /\.(cmd|bat)$/i.test(cmd);
6844
- }
6845
- function winBatchInvocation(cmd, args) {
6846
- const comspec = process.env.ComSpec || "cmd.exe";
6847
- const quote = (t) => `"${String(t).replace(/"/g, '""')}"`;
6848
- const line = [cmd, ...args].map(quote).join(" ");
6849
- return { file: comspec, args: ["/d", "/s", "/c", `"${line}"`] };
6850
- }
6851
- function spawnCommand(cmd, args = [], options = {}) {
6852
- if (isBatchShim(cmd)) {
6853
- const inv = winBatchInvocation(cmd, args);
6854
- return spawn(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6855
- }
6856
- return spawn(cmd, [...args], { windowsHide: true, ...options });
6857
- }
6858
- function spawnSyncCommand(cmd, args = [], options = {}) {
6859
- if (isBatchShim(cmd)) {
6860
- const inv = winBatchInvocation(cmd, args);
6861
- return spawnSync(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6862
- }
6863
- return spawnSync(cmd, [...args], { windowsHide: true, ...options });
6864
- }
6865
- var init_platform = __esm({
6866
- "src/platform.ts"() {
6867
- "use strict";
6868
- }
6869
- });
6870
-
6871
6946
  // src/knowledge.ts
6872
6947
  var BUILD_VS_NON_BUILD_RULE, SKILLS_CONTENT, DEFINITION_OF_DONE, GIPITY_TAGLINE;
6873
6948
  var init_knowledge = __esm({
@@ -7435,7 +7510,10 @@ function installSkillsAndHooks(skillsDir, manifestPath, harnessLabel) {
7435
7510
  ["clone", "--depth", "1", `https://github.com/${GIPITY_MARKETPLACE_REPO}.git`, join6(tmp, "repo")],
7436
7511
  { stdio: "ignore", timeout: 12e4 }
7437
7512
  );
7438
- if (clone.status !== 0) return;
7513
+ if (clone.status !== 0) {
7514
+ console.warn(`Skills install for ${harnessLabel}: git clone of ${GIPITY_MARKETPLACE_REPO} failed (exit ${clone.status}) - hooks/skills not refreshed; re-run \`gipity init\` with network access.`);
7515
+ return;
7516
+ }
7439
7517
  const repo = join6(tmp, "repo");
7440
7518
  let version = GIPITY_PLUGIN_VERSION;
7441
7519
  try {
@@ -7461,7 +7539,8 @@ function installSkillsAndHooks(skillsDir, manifestPath, harnessLabel) {
7461
7539
  }
7462
7540
  writeFileSync3(manifestPath, JSON.stringify({ version, skills: names }, null, 2) + "\n");
7463
7541
  console.log(`Installed ${names.length} Gipity skills for ${harnessLabel} (${skillsDir}).`);
7464
- } catch {
7542
+ } catch (e) {
7543
+ console.warn(`Skills install for ${harnessLabel} failed midway: ${e instanceof Error ? e.message : String(e)} - re-run \`gipity init\`.`);
7465
7544
  } finally {
7466
7545
  rmSync(tmp, { recursive: true, force: true });
7467
7546
  }
@@ -7706,7 +7785,33 @@ alwaysApply: true
7706
7785
  ${block}`
7707
7786
  );
7708
7787
  }
7709
- function setupProjectTools(tools = DEFAULT_TOOLS) {
7788
+ function hasExistingPrimer(root, key) {
7789
+ const primer = PRIMER_FILES[key];
7790
+ return !!primer && existsSync5(join6(root, primer));
7791
+ }
7792
+ function detectedTools() {
7793
+ const root = resolve(process.cwd());
7794
+ const found = DEFAULT_TOOLS.filter(
7795
+ (t) => hasExistingPrimer(root, t.key) || !!t.binary && binaryOnPath(t.binary)
7796
+ );
7797
+ return found.length ? found : DEFAULT_TOOLS;
7798
+ }
7799
+ function resolveProjectTools() {
7800
+ const pinned = getConfig()?.tools;
7801
+ if (pinned?.length) {
7802
+ const chosen = SUPPORTED_TOOLS.filter((t) => pinned.includes(t.key));
7803
+ if (chosen.length) return chosen;
7804
+ }
7805
+ return detectedTools();
7806
+ }
7807
+ function setupToolForAgent(key) {
7808
+ const tool = SUPPORTED_TOOLS.find((t) => t.key === key);
7809
+ if (!tool) return false;
7810
+ tool.setup();
7811
+ tool.integrate?.();
7812
+ return true;
7813
+ }
7814
+ function setupProjectTools(tools = resolveProjectTools()) {
7710
7815
  for (const t of tools) {
7711
7816
  t.setup();
7712
7817
  t.integrate?.();
@@ -7884,15 +7989,19 @@ main();
7884
7989
  GIPITY_BLOCK_BEGIN = "<!-- BEGIN GIPITY INTEGRATION - auto-generated by gipity, do not edit this block -->";
7885
7990
  GIPITY_BLOCK_END = "<!-- END GIPITY INTEGRATION -->";
7886
7991
  SUPPORTED_TOOLS = [
7887
- { key: "claude", label: "Claude Code (CLAUDE.md + Gipity plugin)", setup: setupClaudeMd, integrate: setupClaudeHooks },
7888
- { key: "codex", label: "OpenAI Codex (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupCodexIntegration },
7889
- { key: "grok", label: "Grok Build (AGENTS.md + Gipity plugin)", setup: setupAgentsMd, integrate: ensureGrokPluginInstalled },
7890
- { key: "agy", label: "Antigravity (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupAgyIntegration },
7891
- { key: "opencode", label: "opencode (AGENTS.md + skills + Gipity plugin)", setup: setupAgentsMd, integrate: setupOpencodeIntegration },
7892
- { key: "aider", label: "Aider (AGENTS.md + .aider.conf.yml)", setup: setupAiderMd, optIn: true },
7893
- { key: "gemini", label: "Gemini CLI (GEMINI.md)", setup: setupGeminiMd },
7894
- { key: "copilot", label: "GitHub Copilot (.github/copilot-instructions.md)", setup: setupCopilotMd },
7895
- { key: "cursor", label: "Cursor (.cursor/rules/gipity.mdc)", setup: setupCursorMd }
7992
+ { key: "claude", label: "Claude Code (CLAUDE.md + Gipity plugin)", setup: setupClaudeMd, integrate: setupClaudeHooks, binary: "claude" },
7993
+ { key: "codex", label: "OpenAI Codex (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupCodexIntegration, binary: "codex" },
7994
+ { key: "grok", label: "Grok Build (AGENTS.md + Gipity plugin)", setup: setupAgentsMd, integrate: ensureGrokPluginInstalled, binary: "grok" },
7995
+ { key: "agy", label: "Antigravity (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupAgyIntegration, binary: "agy" },
7996
+ { key: "opencode", label: "opencode (AGENTS.md + skills + Gipity plugin)", setup: setupAgentsMd, integrate: setupOpencodeIntegration, binary: "opencode" },
7997
+ { key: "aider", label: "Aider (AGENTS.md + .aider.conf.yml)", setup: setupAiderMd, optIn: true, binary: "aider" },
7998
+ { key: "gemini", label: "Gemini CLI (GEMINI.md)", setup: setupGeminiMd, binary: "gemini" },
7999
+ // Copilot and Cursor are primarily IDE extensions - a user can rely on either
8000
+ // daily with no CLI on PATH, so a binary probe would wrongly say "absent".
8001
+ // Both ship an optional shell command, so probe it, but ALSO honor a project
8002
+ // that already has their config directory (see detectedTools).
8003
+ { key: "copilot", label: "GitHub Copilot (.github/copilot-instructions.md)", setup: setupCopilotMd, binary: "copilot" },
8004
+ { key: "cursor", label: "Cursor (.cursor/rules/gipity.mdc)", setup: setupCursorMd, binary: "cursor" }
7896
8005
  ];
7897
8006
  DEFAULT_TOOLS = SUPPORTED_TOOLS.filter((t) => !t.optIn);
7898
8007
  MAX_SLUG_LENGTH = 40;
@@ -8960,6 +9069,47 @@ async function fetchWithTimeout(url, init, timeoutMs, label2) {
8960
9069
  throw e;
8961
9070
  }
8962
9071
  }
9072
+ async function fetchWithStagedTimeout(url, init, headerMs, label2) {
9073
+ const ac2 = new AbortController();
9074
+ let timer = setTimeout(() => ac2.abort(), headerMs);
9075
+ let res;
9076
+ try {
9077
+ res = await fetch(url, { ...init, signal: ac2.signal });
9078
+ } catch (e) {
9079
+ clearTimeout(timer);
9080
+ if (ac2.signal.aborted) {
9081
+ throw new ApiError(
9082
+ 408,
9083
+ "REQUEST_TIMEOUT",
9084
+ `${label2} timed out after ${Math.round(headerMs / 1e3)}s (no response from the server)`
9085
+ );
9086
+ }
9087
+ throw e;
9088
+ }
9089
+ clearTimeout(timer);
9090
+ const declared = Number(res.headers.get("content-length") ?? 0);
9091
+ const bodyMs = putTimeoutMs(Number.isFinite(declared) ? declared : 0);
9092
+ timer = setTimeout(() => ac2.abort(), bodyMs);
9093
+ return {
9094
+ res,
9095
+ async read(fn) {
9096
+ try {
9097
+ return await fn(res);
9098
+ } catch (e) {
9099
+ if (ac2.signal.aborted) {
9100
+ throw new ApiError(
9101
+ 408,
9102
+ "REQUEST_TIMEOUT",
9103
+ `${label2} stalled mid-body (no completion in ${Math.round(bodyMs / 1e3)}s)`
9104
+ );
9105
+ }
9106
+ throw e;
9107
+ } finally {
9108
+ clearTimeout(timer);
9109
+ }
9110
+ }
9111
+ };
9112
+ }
8963
9113
  async function bearerToken() {
8964
9114
  const envToken = process.env.GIPITY_TOKEN?.trim();
8965
9115
  if (envToken) return envToken;
@@ -9022,20 +9172,24 @@ function post(path5, body, opts) {
9022
9172
  async function postForTarEntries(path5, body, retried = false) {
9023
9173
  const headers = await getHeaders();
9024
9174
  const url = `${baseUrl()}${path5}`;
9025
- const res = await fetch(url, {
9175
+ const { res, read } = await fetchWithStagedTimeout(url, {
9026
9176
  method: "POST",
9027
9177
  headers,
9028
9178
  body: body ? JSON.stringify(body) : void 0
9029
- });
9179
+ }, LONG_REQUEST_TIMEOUT_MS, `POST ${path5}`);
9030
9180
  if (await shouldRetryAfter401(res.status, retried)) {
9181
+ await read((r) => r.arrayBuffer().catch(() => null));
9031
9182
  return postForTarEntries(path5, body, true);
9032
9183
  }
9033
9184
  if (!res.ok) {
9034
- const json = await res.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } }));
9185
+ const json = await read((r) => r.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } })));
9035
9186
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
9036
9187
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
9037
9188
  }
9038
- if (!res.body) throw new ApiError(500, "EMPTY_RESPONSE", "Server returned no body");
9189
+ if (!res.body) {
9190
+ await read(async () => null);
9191
+ throw new ApiError(500, "EMPTY_RESPONSE", "Server returned no body");
9192
+ }
9039
9193
  const extract3 = tar.extract();
9040
9194
  const entries = [];
9041
9195
  const done = new Promise((resolve19, reject) => {
@@ -9052,9 +9206,11 @@ async function postForTarEntries(path5, body, retried = false) {
9052
9206
  extract3.on("finish", () => resolve19());
9053
9207
  extract3.on("error", reject);
9054
9208
  });
9055
- Readable.fromWeb(res.body).pipe(extract3);
9056
- await done;
9057
- return entries;
9209
+ return read(async () => {
9210
+ Readable.fromWeb(res.body).pipe(extract3);
9211
+ await done;
9212
+ return entries;
9213
+ });
9058
9214
  }
9059
9215
  function put(path5, body) {
9060
9216
  return request("PUT", path5, body);
@@ -9081,31 +9237,34 @@ async function sendMessage(message) {
9081
9237
  }
9082
9238
  async function download(path5, retried = false) {
9083
9239
  const url = `${baseUrl()}${path5}`;
9084
- const res = await fetch(url, {
9240
+ const { res, read } = await fetchWithStagedTimeout(url, {
9085
9241
  headers: { ...clientHeaders(), "Authorization": `Bearer ${await bearerToken()}` }
9086
- });
9242
+ }, DOWNLOAD_HEADER_TIMEOUT_MS, `GET ${path5}`);
9087
9243
  if (await shouldRetryAfter401(res.status, retried)) {
9244
+ await read((r) => r.arrayBuffer().catch(() => null));
9088
9245
  return download(path5, true);
9089
9246
  }
9090
9247
  if (!res.ok) {
9248
+ await read(async () => null);
9091
9249
  throw new ApiError(res.status, "DOWNLOAD_ERROR", with401Hint(res.status, `Download failed: ${res.statusText}`));
9092
9250
  }
9093
- return Buffer.from(await res.arrayBuffer());
9251
+ return read(async (r) => Buffer.from(await r.arrayBuffer()));
9094
9252
  }
9095
9253
  async function downloadWithHeaders(path5, retried = false) {
9096
9254
  const url = `${baseUrl()}${path5}`;
9097
- const res = await fetch(url, {
9255
+ const { res, read } = await fetchWithStagedTimeout(url, {
9098
9256
  headers: { ...clientHeaders(), "Authorization": `Bearer ${await bearerToken()}` }
9099
- });
9257
+ }, LONG_REQUEST_TIMEOUT_MS, `GET ${path5}`);
9100
9258
  if (await shouldRetryAfter401(res.status, retried)) {
9259
+ await read((r) => r.arrayBuffer().catch(() => null));
9101
9260
  return downloadWithHeaders(path5, true);
9102
9261
  }
9103
9262
  if (!res.ok) {
9104
- const json = await res.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } }));
9263
+ const json = await read((r) => r.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } })));
9105
9264
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
9106
9265
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
9107
9266
  }
9108
- return { buffer: Buffer.from(await res.arrayBuffer()), headers: res.headers };
9267
+ return read(async (r) => ({ buffer: Buffer.from(await r.arrayBuffer()), headers: r.headers }));
9109
9268
  }
9110
9269
  async function postBinary(path5, body, contentType = "application/zip", retried = false) {
9111
9270
  const url = `${baseUrl()}${path5}`;
@@ -9200,11 +9359,11 @@ async function getAccountSlug() {
9200
9359
  }
9201
9360
  async function publicRequest(method, path5, body, extraHeaders) {
9202
9361
  const url = `${baseUrl()}${path5}`;
9203
- const res = await fetch(url, {
9362
+ const res = await fetchWithTimeout(url, {
9204
9363
  method,
9205
9364
  headers: { ...clientHeaders(), "Content-Type": "application/json", ...extraHeaders },
9206
9365
  body: body === void 0 ? void 0 : JSON.stringify(body)
9207
- });
9366
+ }, REQUEST_TIMEOUT_MS, `${method} ${path5}`);
9208
9367
  if (!res.ok) {
9209
9368
  const json = await res.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } }));
9210
9369
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
@@ -36376,7 +36535,7 @@ async function finalizeLocalProject(opts) {
36376
36535
  } catch (err) {
36377
36536
  if (opts.sync === "strict") throw err;
36378
36537
  }
36379
- setupProjectTools(opts.tools ?? DEFAULT_TOOLS);
36538
+ setupProjectTools(opts.tools);
36380
36539
  return { applied };
36381
36540
  }
36382
36541
 
@@ -36583,8 +36742,11 @@ var ADOPT_THRESHOLDS = {
36583
36742
 
36584
36743
  // src/commands/init.ts
36585
36744
  var TOOL_KEYS = SUPPORTED_TOOLS.map((t) => t.key);
36745
+ function pinnedToolKeys(forFlag, tools) {
36746
+ return forFlag ? tools.map((t) => t.key) : null;
36747
+ }
36586
36748
  function resolveTools(forFlag) {
36587
- if (!forFlag) return DEFAULT_TOOLS;
36749
+ if (!forFlag) return resolveProjectTools();
36588
36750
  const requested = forFlag.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
36589
36751
  const unknown = requested.filter((k7) => !TOOL_KEYS.includes(k7) && k7 !== "all");
36590
36752
  if (unknown.length) {
@@ -36595,13 +36757,17 @@ function resolveTools(forFlag) {
36595
36757
  );
36596
36758
  }
36597
36759
  var initCommand = new Command("init").description("Link this directory to a project").addHelpText("after", `
36598
- Writes 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(", ")}).`).argument("[name]", "Project name/slug (defaults to current directory name)").option("--agent <guid>", "Agent GUID to use").option("--no-capture", "Don't record Claude Code sessions in this directory to your Gipity project (sets captureHooks: false in .gipity.json)").option(
36760
+ Writes 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(", ")}, \u2026) - use --for to choose explicitly.`).argument("[name]", "Project name/slug (defaults to current directory name)").option("--agent <guid>", "Agent GUID to use").option("--no-capture", "Don't record Claude Code sessions in this directory to your Gipity project (sets captureHooks: false in .gipity.json)").option(
36599
36761
  "--for <tools>",
36600
- `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`
36762
+ `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`
36601
36763
  ).addHelpText("after", `
36602
36764
  Examples:
36603
- $ gipity init Link cwd as a new project (slug = dir name).
36765
+ $ gipity init Link cwd as a new project (slug = dir name);
36766
+ sets up the tools installed on this machine.
36604
36767
  $ gipity init my-app Link cwd with an explicit slug.
36768
+ $ gipity init --for opencode Only opencode - pinned, so a later
36769
+ gipity build won't re-add the others.
36770
+ $ gipity init --for all Every tool, whether installed or not.
36605
36771
  $ gipity init --for codex AGENTS.md + Codex skills/sync hooks only.
36606
36772
  $ gipity init --for grok AGENTS.md + the Gipity plugin in Grok only.
36607
36773
  $ gipity init --for cursor,gemini Write only the Cursor + Gemini primers.
@@ -36625,6 +36791,8 @@ Working with an existing Gipity project:
36625
36791
  }
36626
36792
  const wantsClaude = tools.some((t) => t.key === "claude");
36627
36793
  const primerSummary = tools.map((t) => t.label).join(", ");
36794
+ const skipped = DEFAULT_TOOLS.filter((d) => !tools.some((t) => t.key === d.key));
36795
+ const skippedNote = skipped.length ? `${muted(`Skipped (not installed here): ${skipped.map((t) => t.key).join(", ")} - add with`)} ${brand(`gipity init --for ${skipped.map((t) => t.key).join(",")}`)}${muted(".")}` : null;
36628
36796
  try {
36629
36797
  const auth = getAuth();
36630
36798
  if (!auth) {
@@ -36648,9 +36816,15 @@ Working with an existing Gipity project:
36648
36816
  existing.captureHooks = false;
36649
36817
  changed = true;
36650
36818
  }
36819
+ const pinned = pinnedToolKeys(opts.for, tools);
36820
+ if (pinned && JSON.stringify(existing.tools ?? null) !== JSON.stringify(pinned)) {
36821
+ existing.tools = pinned;
36822
+ changed = true;
36823
+ }
36651
36824
  if (changed) saveConfigAt(cwd, existing);
36652
36825
  }
36653
36826
  console.log(success(`Refreshed primer files: ${primerSummary}.`));
36827
+ if (skippedNote) console.log(skippedNote);
36654
36828
  if (opts.capture === false) {
36655
36829
  console.log(success("Session recording disabled for this project (captureHooks: false in .gipity.json)."));
36656
36830
  }
@@ -36713,15 +36887,18 @@ Working with an existing Gipity project:
36713
36887
  console.log(`Found existing project ${info(`"${adopted.project.name}"`)} ${muted(`(${adopted.project.slug})`)}`);
36714
36888
  }
36715
36889
  if (adopted.applied > 0) console.log(`Synced ${adopted.applied} change${adopted.applied > 1 ? "s" : ""} with Gipity.`);
36716
- if (opts.capture === false) {
36890
+ const pinnedFresh = pinnedToolKeys(opts.for, tools);
36891
+ if (opts.capture === false || pinnedFresh) {
36717
36892
  try {
36718
36893
  const cfg = JSON.parse(readFileSync11(resolve7(cwd, ".gipity.json"), "utf-8"));
36719
- cfg.captureHooks = false;
36894
+ if (opts.capture === false) cfg.captureHooks = false;
36895
+ if (pinnedFresh) cfg.tools = pinnedFresh;
36720
36896
  saveConfigAt(cwd, cfg);
36721
36897
  } catch {
36722
36898
  }
36723
36899
  }
36724
36900
  console.log(success(`Wrote primer files: ${primerSummary}.`));
36901
+ if (skippedNote) console.log(skippedNote);
36725
36902
  if (wantsClaude) {
36726
36903
  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.`));
36727
36904
  if (opts.capture === false) {
@@ -41474,6 +41651,7 @@ async function runLaunch(cmdName, cmdCfg, opts) {
41474
41651
  }
41475
41652
  }
41476
41653
  const adapter = getAdapter(agentKey);
41654
+ setupToolForAgent(adapter.key);
41477
41655
  if (!nonInteractive && !cmdCfg.presetAgent) {
41478
41656
  writePrefs({ lastAgent: adapter.key });
41479
41657
  }
@@ -41611,7 +41789,7 @@ Sending to Claude Code: ${userMsg}
41611
41789
  } else if (convGuidForHooks) {
41612
41790
  childEnv2.GIPITY_CONVERSATION_GUID = convGuidForHooks;
41613
41791
  }
41614
- if (!nonInteractive) markFolderTrusted(process.cwd());
41792
+ markFolderTrusted(process.cwd());
41615
41793
  const child = spawnCommand(claudeCmd, allArgs, {
41616
41794
  stdio: "inherit",
41617
41795
  cwd: process.cwd(),
@@ -41787,6 +41965,8 @@ Sending to ${adapter.displayName}: ${message}
41787
41965
  }
41788
41966
  const childEnv2 = { ...process.env };
41789
41967
  if (convGuid) childEnv2.GIPITY_CONVERSATION_GUID = convGuid;
41968
+ const projectGuidForAgent = getConfig()?.projectGuid;
41969
+ if (projectGuidForAgent) childEnv2.GIPITY_PROJECT = projectGuidForAgent;
41790
41970
  const agentCmd = resolveCommand(adapter.binary);
41791
41971
  const child = spawnCommand(agentCmd, agentArgs, {
41792
41972
  stdio: "inherit",
@@ -45418,7 +45598,12 @@ function gatherEnv(opts = {}) {
45418
45598
  session_expired: expired
45419
45599
  };
45420
45600
  const claude = { installed: isClaudeInstalled(), authenticated: false };
45421
- claude.authenticated = claude.installed && (opts.probeClaude ? probeClaudeAuthenticated() : isClaudeAuthenticated());
45601
+ if (claude.installed) {
45602
+ const status = opts.probeClaude ? null : claudeAuthStatus();
45603
+ claude.authenticated = opts.probeClaude ? probeClaudeAuthenticated() : status?.loggedIn ?? claudeCredentialHeuristic();
45604
+ claude.account = status?.email ?? null;
45605
+ claude.method = status?.authMethod ?? null;
45606
+ }
45422
45607
  const relay = {
45423
45608
  paired: !!device,
45424
45609
  running: isDaemonRunning(),
@@ -45458,7 +45643,11 @@ var doctorCommand = new Command("doctor").description("Check install + environme
45458
45643
  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.`)}`);
45459
45644
  }
45460
45645
  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")}`);
45461
- console.log(`${muted("claude code ")} installed ${yn(env.claude.installed)} \xB7 authenticated ${yn(env.claude.authenticated)}`);
45646
+ const claudeAccount = env.claude.account ? muted(` (${env.claude.account}${env.claude.method ? ` via ${env.claude.method}` : ""})`) : "";
45647
+ console.log(`${muted("claude code ")} installed ${yn(env.claude.installed)} \xB7 authenticated ${yn(env.claude.authenticated)}${claudeAccount}`);
45648
+ if (env.claude.installed && !env.claude.authenticated) {
45649
+ console.log(`${muted(" ")} ${warning(claudeLoginHint())}`);
45650
+ }
45462
45651
  const autostartLabel = env.relay.autostart === null ? muted("n/a") : yn(env.relay.autostart);
45463
45652
  console.log(`${muted("relay ")} paired ${yn(env.relay.paired)} \xB7 running ${yn(env.relay.running)} \xB7 autostart ${autostartLabel}${env.relay.paused ? warning(" \xB7 paused") : ""}${env.relay.device ? muted(` (${env.relay.device.name})`) : ""}`);
45464
45653
  if (existsSync20(resolve15(process.cwd(), ".codex", "hooks.json"))) {
@@ -46443,6 +46632,7 @@ async function revokeRelayAgentToken() {
46443
46632
  init_platform();
46444
46633
  init_client_context();
46445
46634
  init_agents();
46635
+ init_claude_setup();
46446
46636
  import { cpus, freemem, totalmem, loadavg, release, uptime, homedir as homedir18 } from "os";
46447
46637
  import { statfsSync, readdirSync as readdirSync9 } from "fs";
46448
46638
  import { join as join26 } from "path";
@@ -46539,10 +46729,11 @@ async function collectDiagnostics() {
46539
46729
  return [];
46540
46730
  }
46541
46731
  })();
46542
- const [versions, cursor, gpu] = await Promise.all([
46732
+ const [versions, cursor, gpu, claudeAuth] = await Promise.all([
46543
46733
  Promise.all(AGENT_ADAPTERS.map((a) => probeVersion(a.binary))),
46544
46734
  probeVersion("cursor"),
46545
- detectGpu()
46735
+ detectGpu(),
46736
+ claudeAuthStatusAsync()
46546
46737
  ]);
46547
46738
  const agents = {};
46548
46739
  AGENT_ADAPTERS.forEach((a, i) => {
@@ -46562,7 +46753,8 @@ async function collectDiagnostics() {
46562
46753
  disk: diskUsage(),
46563
46754
  gpu,
46564
46755
  agents: Object.keys(agents).length ? agents : void 0,
46565
- projects_local: localProjectCount()
46756
+ projects_local: localProjectCount(),
46757
+ claude_auth: claudeAuth ? { logged_in: claudeAuth.loggedIn, method: claudeAuth.authMethod, subscription: claudeAuth.subscriptionType } : void 0
46566
46758
  };
46567
46759
  }
46568
46760
  function safe(fn) {
@@ -46573,6 +46765,9 @@ function safe(fn) {
46573
46765
  }
46574
46766
  }
46575
46767
 
46768
+ // src/relay/daemon.ts
46769
+ init_claude_setup();
46770
+
46576
46771
  // src/relay/agent-updates.ts
46577
46772
  init_agents();
46578
46773
  init_platform();
@@ -47006,7 +47201,15 @@ function mapPlatform2(p) {
47006
47201
  }
47007
47202
  async function registerDevice() {
47008
47203
  const name = (hostname6() || "my-pc").trim().slice(0, 100) || "my-pc";
47009
- const res = await post("/remote-devices", { name, platform: mapPlatform2(osPlatform3()), machine_id: getMachineId() });
47204
+ const deviceKind = process.env.GIPITY_DEVICE_KIND;
47205
+ const agentKind = process.env.GIPITY_AGENT_KIND;
47206
+ const res = await post("/remote-devices", {
47207
+ name,
47208
+ platform: mapPlatform2(osPlatform3()),
47209
+ machine_id: getMachineId(),
47210
+ ...deviceKind ? { device_kind: deviceKind } : {},
47211
+ ...agentKind ? { agent_kind: agentKind } : {}
47212
+ });
47010
47213
  const device = {
47011
47214
  guid: res.data.short_guid,
47012
47215
  name: res.data.name,
@@ -47717,6 +47920,7 @@ async function handleDispatch(claimed) {
47717
47920
  let killed = false;
47718
47921
  let runtimeLimit = false;
47719
47922
  let stderrTail = "";
47923
+ let assistantTail = "";
47720
47924
  let startupMs;
47721
47925
  try {
47722
47926
  const result = await spawnGipityClaude(args, cwd, d, queue, { resumeWords: transcript?.words });
@@ -47724,6 +47928,7 @@ async function handleDispatch(claimed) {
47724
47928
  killed = result.killed;
47725
47929
  runtimeLimit = result.runtimeLimit ?? false;
47726
47930
  stderrTail = result.stderrTail ?? "";
47931
+ assistantTail = result.assistantTail ?? "";
47727
47932
  startupMs = result.startupMs;
47728
47933
  } catch (err) {
47729
47934
  spawnErr = err?.message || String(err);
@@ -47739,7 +47944,9 @@ async function handleDispatch(claimed) {
47739
47944
  }
47740
47945
  }
47741
47946
  const stderrNote = stderrTail ? `: ${stderrTail.slice(0, 300)}` : "";
47742
- const tail2 = runtimeLimit ? `stopped after ${dur} (runtime limit)` : killed ? `cancelled (${dur})` : spawnErr ? `failed (${dur}: ${spawnErr})` : exitCode === 0 ? `finished (${dur})` : `failed (${dur}, exit ${exitCode}${stderrNote})`;
47947
+ const authHint = exitCode !== 0 && !killed && !runtimeLimit && !spawnErr ? claudeAuthFailureHint(await claudeAuthStatusAsync(), `${stderrTail} ${assistantTail}`, getDevice()?.name) : null;
47948
+ const authNote = authHint ? ` \xB7 ${authHint}` : "";
47949
+ const tail2 = runtimeLimit ? `stopped after ${dur} (runtime limit)` : killed ? `cancelled (${dur})` : spawnErr ? `failed (${dur}: ${spawnErr})` : exitCode === 0 ? `finished (${dur})` : `failed (${dur}, exit ${exitCode}${stderrNote})${authNote}`;
47743
47950
  pushSystem(`Claude Code ${tail2}`);
47744
47951
  await flushQueue();
47745
47952
  const metrics = startupMs !== void 0 ? { startup_ms: startupMs } : void 0;
@@ -47755,10 +47962,16 @@ async function handleDispatch(claimed) {
47755
47962
  log2("info", "dispatch done", { id: d.short_guid, ms: ms2, startupMs });
47756
47963
  await ack(d.short_guid, "done", void 0, metrics);
47757
47964
  } else {
47758
- log2("warn", "dispatch child exited nonzero", { id: d.short_guid, exitCode, ms: ms2 });
47759
- await ack(d.short_guid, "error", `Claude Code exited with code ${exitCode}${stderrNote}`);
47965
+ log2("warn", "dispatch child exited nonzero", { id: d.short_guid, exitCode, ms: ms2, authHint: !!authHint });
47966
+ await ack(d.short_guid, "error", `Claude Code exited with code ${exitCode}${stderrNote}${authNote}`);
47760
47967
  }
47761
47968
  }
47969
+ var CLAUDE_AUTH_ERROR_RE = /not logged in|please run \/login|claude auth login|invalid api key|authentication_error|oauth token (?:has )?(?:expired|been revoked)/i;
47970
+ function claudeAuthFailureHint(status, outputTail, deviceName) {
47971
+ if (status?.loggedIn === false) return claudeLoginHint(deviceName);
47972
+ if (status === null && CLAUDE_AUTH_ERROR_RE.test(outputTail)) return claudeLoginHint(deviceName);
47973
+ return null;
47974
+ }
47762
47975
  async function handleNonClaudeDispatch(adapter, d, cwd, queue, pushSystem, flushQueue) {
47763
47976
  const args = ["build", "--agent", adapter.key, "-p", d.message, "--bypass-approvals"];
47764
47977
  if (d.model) args.push("--model", d.model);
@@ -48170,6 +48383,7 @@ async function spawnGipityClaude(args, cwd, d, queue, meta) {
48170
48383
  const ownQueue = !queue;
48171
48384
  const dispatchStartedAt = Date.now();
48172
48385
  let stdoutBytesTotal = 0;
48386
+ const assistantTail = [];
48173
48387
  let lastStdoutByteAt = dispatchStartedAt;
48174
48388
  let stdoutBytesAtLastTick = 0;
48175
48389
  const phases = new PhaseTracker();
@@ -48279,6 +48493,12 @@ async function spawnGipityClaude(args, cwd, d, queue, meta) {
48279
48493
  e.ts = ts2;
48280
48494
  if (!e.source_uuid) e.source_uuid = randomUUID2();
48281
48495
  }
48496
+ for (const e of entries) {
48497
+ if (e.kind === "assistant" && typeof e.text === "string") {
48498
+ assistantTail.push(e.text.trim());
48499
+ if (assistantTail.length > 3) assistantTail.shift();
48500
+ }
48501
+ }
48282
48502
  q.push(...entries);
48283
48503
  });
48284
48504
  child.stdout?.on("data", (chunk) => {
@@ -48333,6 +48553,7 @@ async function spawnGipityClaude(args, cwd, d, queue, meta) {
48333
48553
  killed,
48334
48554
  runtimeLimit,
48335
48555
  stderrTail: stderrTail.join(" | "),
48556
+ assistantTail: assistantTail.join(" | "),
48336
48557
  startupMs: firstEventAt !== void 0 ? Math.max(0, firstEventAt - dispatchStartedAt) : void 0
48337
48558
  });
48338
48559
  });