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/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
 
@@ -6765,6 +6888,10 @@ function parseTranscript(content, afterUuid) {
6765
6888
  let lastUuid = afterUuid;
6766
6889
  const out = [];
6767
6890
  const toolNames = /* @__PURE__ */ new Map();
6891
+ const countedUsage = /* @__PURE__ */ new Set();
6892
+ let tokensIn = 0;
6893
+ let tokensOut = 0;
6894
+ const num = (v7) => typeof v7 === "number" && v7 > 0 ? v7 : 0;
6768
6895
  for (const raw of content.split("\n")) {
6769
6896
  const line = raw.trim();
6770
6897
  if (!line) continue;
@@ -6785,6 +6912,16 @@ function parseTranscript(content, afterUuid) {
6785
6912
  if (parsed?.uuid === afterUuid) seenWatermark = true;
6786
6913
  continue;
6787
6914
  }
6915
+ if (parsed?.type === "assistant" && parsed?.isSidechain !== true) {
6916
+ const m = parsed.message;
6917
+ const u = m?.usage;
6918
+ const key = typeof m?.id === "string" && m.id ? m.id : parsed.uuid;
6919
+ if (u && typeof key === "string" && !countedUsage.has(key)) {
6920
+ countedUsage.add(key);
6921
+ tokensIn += num(u.input_tokens) + num(u.cache_read_input_tokens) + num(u.cache_creation_input_tokens);
6922
+ tokensOut += num(u.output_tokens);
6923
+ }
6924
+ }
6788
6925
  const entries = transcriptLineToEntries(parsed, toolNames);
6789
6926
  if (entries.length) {
6790
6927
  for (const e of entries) out.push(e);
@@ -6796,7 +6933,8 @@ function parseTranscript(content, afterUuid) {
6796
6933
  return {
6797
6934
  entries: out,
6798
6935
  lastUuid,
6799
- foundWatermark: seenWatermark
6936
+ foundWatermark: seenWatermark,
6937
+ usage: { tokensIn, tokensOut }
6800
6938
  };
6801
6939
  }
6802
6940
  var init_claude_code = __esm({
@@ -6805,54 +6943,6 @@ var init_claude_code = __esm({
6805
6943
  }
6806
6944
  });
6807
6945
 
6808
- // src/platform.ts
6809
- var platform_exports = {};
6810
- __export(platform_exports, {
6811
- isBatchShim: () => isBatchShim,
6812
- resolveCommand: () => resolveCommand,
6813
- spawnCommand: () => spawnCommand,
6814
- spawnSyncCommand: () => spawnSyncCommand,
6815
- winBatchInvocation: () => winBatchInvocation
6816
- });
6817
- import { execSync as execSync3, spawn, spawnSync } from "child_process";
6818
- function resolveCommand(cmd) {
6819
- if (process.platform !== "win32") return cmd;
6820
- try {
6821
- const lines = execSync3(`where ${cmd}`, { encoding: "utf-8", windowsHide: true }).split(/\r?\n/).map((l7) => l7.trim()).filter(Boolean);
6822
- return lines.find((l7) => l7.endsWith(".exe")) || lines.find((l7) => l7.endsWith(".cmd")) || cmd;
6823
- } catch {
6824
- return `${cmd}.cmd`;
6825
- }
6826
- }
6827
- function isBatchShim(cmd) {
6828
- return process.platform === "win32" && /\.(cmd|bat)$/i.test(cmd);
6829
- }
6830
- function winBatchInvocation(cmd, args) {
6831
- const comspec = process.env.ComSpec || "cmd.exe";
6832
- const quote = (t) => `"${String(t).replace(/"/g, '""')}"`;
6833
- const line = [cmd, ...args].map(quote).join(" ");
6834
- return { file: comspec, args: ["/d", "/s", "/c", `"${line}"`] };
6835
- }
6836
- function spawnCommand(cmd, args = [], options = {}) {
6837
- if (isBatchShim(cmd)) {
6838
- const inv = winBatchInvocation(cmd, args);
6839
- return spawn(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6840
- }
6841
- return spawn(cmd, [...args], { windowsHide: true, ...options });
6842
- }
6843
- function spawnSyncCommand(cmd, args = [], options = {}) {
6844
- if (isBatchShim(cmd)) {
6845
- const inv = winBatchInvocation(cmd, args);
6846
- return spawnSync(inv.file, inv.args, { windowsHide: true, ...options, windowsVerbatimArguments: true });
6847
- }
6848
- return spawnSync(cmd, [...args], { windowsHide: true, ...options });
6849
- }
6850
- var init_platform = __esm({
6851
- "src/platform.ts"() {
6852
- "use strict";
6853
- }
6854
- });
6855
-
6856
6946
  // src/knowledge.ts
6857
6947
  var BUILD_VS_NON_BUILD_RULE, SKILLS_CONTENT, DEFINITION_OF_DONE, GIPITY_TAGLINE;
6858
6948
  var init_knowledge = __esm({
@@ -7104,7 +7194,15 @@ function ensureOpencodeInstalled(opts = {}) {
7104
7194
  }
7105
7195
  function ensureOpencodePluginInstalled() {
7106
7196
  const src = stagedPluginPath();
7107
- if (!existsSync4(src)) return existsSync4(opencodePluginDest());
7197
+ if (!existsSync4(src)) {
7198
+ const installed = existsSync4(opencodePluginDest());
7199
+ if (!installed) {
7200
+ console.warn(
7201
+ "Gipity opencode plugin is not staged (skills install incomplete?) - session capture is off. Re-run `gipity init` with network access to fix."
7202
+ );
7203
+ }
7204
+ return installed;
7205
+ }
7108
7206
  const dest = opencodePluginDest();
7109
7207
  try {
7110
7208
  if (existsSync4(dest) && readFileSync3(dest, "utf-8") === readFileSync3(src, "utf-8")) return true;
@@ -7412,7 +7510,10 @@ function installSkillsAndHooks(skillsDir, manifestPath, harnessLabel) {
7412
7510
  ["clone", "--depth", "1", `https://github.com/${GIPITY_MARKETPLACE_REPO}.git`, join6(tmp, "repo")],
7413
7511
  { stdio: "ignore", timeout: 12e4 }
7414
7512
  );
7415
- 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
+ }
7416
7517
  const repo = join6(tmp, "repo");
7417
7518
  let version = GIPITY_PLUGIN_VERSION;
7418
7519
  try {
@@ -7438,7 +7539,8 @@ function installSkillsAndHooks(skillsDir, manifestPath, harnessLabel) {
7438
7539
  }
7439
7540
  writeFileSync3(manifestPath, JSON.stringify({ version, skills: names }, null, 2) + "\n");
7440
7541
  console.log(`Installed ${names.length} Gipity skills for ${harnessLabel} (${skillsDir}).`);
7441
- } catch {
7542
+ } catch (e) {
7543
+ console.warn(`Skills install for ${harnessLabel} failed midway: ${e instanceof Error ? e.message : String(e)} - re-run \`gipity init\`.`);
7442
7544
  } finally {
7443
7545
  rmSync(tmp, { recursive: true, force: true });
7444
7546
  }
@@ -7511,7 +7613,7 @@ function setupCodexIntegration() {
7511
7613
  setupCodexHooks();
7512
7614
  }
7513
7615
  function ensureOpencodeSkillsInstalled() {
7514
- if (agentSkillsState().current) return;
7616
+ if (agentSkillsState().current && existsSync5(stagedPluginPath())) return;
7515
7617
  if (!binaryOnPath("opencode")) return;
7516
7618
  installSkillsAndHooks(AGENTS_SKILLS_DIR, AGENT_SKILLS_MANIFEST, "opencode");
7517
7619
  }
@@ -7683,7 +7785,33 @@ alwaysApply: true
7683
7785
  ${block}`
7684
7786
  );
7685
7787
  }
7686
- 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()) {
7687
7815
  for (const t of tools) {
7688
7816
  t.setup();
7689
7817
  t.integrate?.();
@@ -7799,7 +7927,7 @@ var init_setup = __esm({
7799
7927
  GIPITY_MARKETPLACE_NAME = "gipity";
7800
7928
  GIPITY_MARKETPLACE_REPO = "GipityAI/skills";
7801
7929
  LEGACY_MARKETPLACE_REPO = "GipityAI/claude-plugin";
7802
- GIPITY_PLUGIN_VERSION = "0.7.0";
7930
+ GIPITY_PLUGIN_VERSION = "0.8.0";
7803
7931
  AGENTS_SKILLS_DIR = join6(homedir4(), ".agents", "skills");
7804
7932
  AGENT_HOOKS_DIR = join6(homedir4(), ".gipity", "agent-hooks");
7805
7933
  AGENT_SKILLS_MANIFEST = join6(homedir4(), ".gipity", "agent-skills.json");
@@ -7861,15 +7989,19 @@ main();
7861
7989
  GIPITY_BLOCK_BEGIN = "<!-- BEGIN GIPITY INTEGRATION - auto-generated by gipity, do not edit this block -->";
7862
7990
  GIPITY_BLOCK_END = "<!-- END GIPITY INTEGRATION -->";
7863
7991
  SUPPORTED_TOOLS = [
7864
- { key: "claude", label: "Claude Code (CLAUDE.md + Gipity plugin)", setup: setupClaudeMd, integrate: setupClaudeHooks },
7865
- { key: "codex", label: "OpenAI Codex (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupCodexIntegration },
7866
- { key: "grok", label: "Grok Build (AGENTS.md + Gipity plugin)", setup: setupAgentsMd, integrate: ensureGrokPluginInstalled },
7867
- { key: "agy", label: "Antigravity (AGENTS.md + skills + sync hooks)", setup: setupAgentsMd, integrate: setupAgyIntegration },
7868
- { key: "opencode", label: "opencode (AGENTS.md + skills + Gipity plugin)", setup: setupAgentsMd, integrate: setupOpencodeIntegration },
7869
- { key: "aider", label: "Aider (AGENTS.md + .aider.conf.yml)", setup: setupAiderMd, optIn: true },
7870
- { key: "gemini", label: "Gemini CLI (GEMINI.md)", setup: setupGeminiMd },
7871
- { key: "copilot", label: "GitHub Copilot (.github/copilot-instructions.md)", setup: setupCopilotMd },
7872
- { 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" }
7873
8005
  ];
7874
8006
  DEFAULT_TOOLS = SUPPORTED_TOOLS.filter((t) => !t.optIn);
7875
8007
  MAX_SLUG_LENGTH = 40;
@@ -8046,6 +8178,12 @@ function lineToEntries(parsed, sessionId, idx, toolNames) {
8046
8178
  }
8047
8179
  return [];
8048
8180
  }
8181
+ function tokenTotals(payload) {
8182
+ const t = payload?.info?.total_token_usage;
8183
+ if (!t || typeof t !== "object") return null;
8184
+ const num = (v7) => typeof v7 === "number" && v7 > 0 ? v7 : 0;
8185
+ return { input: num(t.input_tokens), output: num(t.output_tokens) };
8186
+ }
8049
8187
  function parseTranscript2(content, afterUuid) {
8050
8188
  const lines = content.split("\n");
8051
8189
  let sessionId = "";
@@ -8067,6 +8205,8 @@ function parseTranscript2(content, afterUuid) {
8067
8205
  const out = [];
8068
8206
  const toolNames = /* @__PURE__ */ new Map();
8069
8207
  let lastIdx = startAfter;
8208
+ let baseUsage = null;
8209
+ let lastUsage = null;
8070
8210
  for (let i = 0; i < lines.length; i++) {
8071
8211
  const line = lines[i].trim();
8072
8212
  if (!line) continue;
@@ -8076,13 +8216,16 @@ function parseTranscript2(content, afterUuid) {
8076
8216
  } catch {
8077
8217
  continue;
8078
8218
  }
8219
+ const isTokenCount = parsed?.type === "event_msg" && parsed?.payload?.type === "token_count";
8079
8220
  if (startAfter !== null && i <= startAfter) {
8080
8221
  const p = parsed?.payload;
8081
8222
  if (parsed?.type === "response_item" && p && (p.type === "custom_tool_call" || p.type === "function_call") && typeof p.call_id === "string") {
8082
8223
  toolNames.set(p.call_id, typeof p.name === "string" && p.name ? p.name : "tool");
8083
8224
  }
8225
+ if (isTokenCount) baseUsage = tokenTotals(parsed.payload) ?? baseUsage;
8084
8226
  continue;
8085
8227
  }
8228
+ if (isTokenCount) lastUsage = tokenTotals(parsed.payload) ?? lastUsage;
8086
8229
  const entries = lineToEntries(parsed, sessionId, i, toolNames);
8087
8230
  for (const e of entries) out.push(e);
8088
8231
  lastIdx = i;
@@ -8090,7 +8233,11 @@ function parseTranscript2(content, afterUuid) {
8090
8233
  return {
8091
8234
  entries: out,
8092
8235
  lastUuid: lastIdx === null ? afterUuid : positional(sessionId, lastIdx),
8093
- foundWatermark
8236
+ foundWatermark,
8237
+ usage: lastUsage === null ? { tokensIn: 0, tokensOut: 0 } : {
8238
+ tokensIn: Math.max(0, lastUsage.input - (baseUsage?.input ?? 0)),
8239
+ tokensOut: Math.max(0, lastUsage.output - (baseUsage?.output ?? 0))
8240
+ }
8094
8241
  };
8095
8242
  }
8096
8243
  var init_codex = __esm({
@@ -8647,6 +8794,9 @@ function parseTranscript5(content, afterUuid) {
8647
8794
  const foundWatermark = afterUuid === null || watermarkLine !== -1;
8648
8795
  const out = [];
8649
8796
  let lastUuid = foundWatermark ? afterUuid : null;
8797
+ let tokensIn = 0;
8798
+ let tokensOut = 0;
8799
+ const num = (v7) => typeof v7 === "number" && v7 > 0 ? v7 : 0;
8650
8800
  for (let i = 0; i < lines.length; i++) {
8651
8801
  if (watermarkLine !== -1 && i <= watermarkLine) continue;
8652
8802
  const line = lines[i].trim();
@@ -8657,12 +8807,17 @@ function parseTranscript5(content, afterUuid) {
8657
8807
  } catch {
8658
8808
  continue;
8659
8809
  }
8660
- const entries = messageToEntries(parsed?.info, Array.isArray(parsed?.parts) ? parsed.parts : []);
8810
+ const info2 = parsed?.info;
8811
+ const entries = messageToEntries(info2, Array.isArray(parsed?.parts) ? parsed.parts : []);
8661
8812
  if (!entries.length) continue;
8813
+ if (info2?.role === "assistant" && info2?.tokens) {
8814
+ tokensIn += num(info2.tokens.input) + num(info2.tokens.cache?.read) + num(info2.tokens.cache?.write);
8815
+ tokensOut += num(info2.tokens.output);
8816
+ }
8662
8817
  for (const e of entries) out.push(e);
8663
- if (typeof parsed?.info?.id === "string") lastUuid = parsed.info.id;
8818
+ if (typeof info2?.id === "string") lastUuid = info2.id;
8664
8819
  }
8665
- return { entries: out, lastUuid, foundWatermark };
8820
+ return { entries: out, lastUuid, foundWatermark, usage: { tokensIn, tokensOut } };
8666
8821
  }
8667
8822
  var init_opencode = __esm({
8668
8823
  "src/capture/sources/opencode.ts"() {
@@ -8881,6 +9036,7 @@ var init_client_context = __esm({
8881
9036
  var api_exports = {};
8882
9037
  __export(api_exports, {
8883
9038
  ApiError: () => ApiError,
9039
+ LONG_REQUEST_TIMEOUT_MS: () => LONG_REQUEST_TIMEOUT_MS,
8884
9040
  del: () => del,
8885
9041
  download: () => download,
8886
9042
  downloadStream: () => downloadStream,
@@ -8913,6 +9069,47 @@ async function fetchWithTimeout(url, init, timeoutMs, label2) {
8913
9069
  throw e;
8914
9070
  }
8915
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
+ }
8916
9113
  async function bearerToken() {
8917
9114
  const envToken = process.env.GIPITY_TOKEN?.trim();
8918
9115
  if (envToken) return envToken;
@@ -8948,16 +9145,16 @@ async function getAuthHeader() {
8948
9145
  const headers = await getHeaders();
8949
9146
  return headers.Authorization;
8950
9147
  }
8951
- async function request(method, path5, body, retrying = false) {
9148
+ async function request(method, path5, body, retrying = false, timeoutMs = REQUEST_TIMEOUT_MS) {
8952
9149
  const headers = await getHeaders();
8953
9150
  const url = `${baseUrl()}${path5}`;
8954
9151
  const res = await fetchWithTimeout(url, {
8955
9152
  method,
8956
9153
  headers,
8957
9154
  body: body ? JSON.stringify(body) : void 0
8958
- }, REQUEST_TIMEOUT_MS, `${method} ${path5}`);
9155
+ }, timeoutMs, `${method} ${path5}`);
8959
9156
  if (await shouldRetryAfter401(res.status, retrying)) {
8960
- return request(method, path5, body, true);
9157
+ return request(method, path5, body, true, timeoutMs);
8961
9158
  }
8962
9159
  if (!res.ok) {
8963
9160
  const json = await res.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } }));
@@ -8969,26 +9166,30 @@ async function request(method, path5, body, retrying = false) {
8969
9166
  function get(path5) {
8970
9167
  return request("GET", path5);
8971
9168
  }
8972
- function post(path5, body) {
8973
- return request("POST", path5, body);
9169
+ function post(path5, body, opts) {
9170
+ return request("POST", path5, body, false, opts?.timeoutMs);
8974
9171
  }
8975
9172
  async function postForTarEntries(path5, body, retried = false) {
8976
9173
  const headers = await getHeaders();
8977
9174
  const url = `${baseUrl()}${path5}`;
8978
- const res = await fetch(url, {
9175
+ const { res, read } = await fetchWithStagedTimeout(url, {
8979
9176
  method: "POST",
8980
9177
  headers,
8981
9178
  body: body ? JSON.stringify(body) : void 0
8982
- });
9179
+ }, LONG_REQUEST_TIMEOUT_MS, `POST ${path5}`);
8983
9180
  if (await shouldRetryAfter401(res.status, retried)) {
9181
+ await read((r) => r.arrayBuffer().catch(() => null));
8984
9182
  return postForTarEntries(path5, body, true);
8985
9183
  }
8986
9184
  if (!res.ok) {
8987
- 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 } })));
8988
9186
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
8989
9187
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
8990
9188
  }
8991
- 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
+ }
8992
9193
  const extract3 = tar.extract();
8993
9194
  const entries = [];
8994
9195
  const done = new Promise((resolve19, reject) => {
@@ -9005,9 +9206,11 @@ async function postForTarEntries(path5, body, retried = false) {
9005
9206
  extract3.on("finish", () => resolve19());
9006
9207
  extract3.on("error", reject);
9007
9208
  });
9008
- Readable.fromWeb(res.body).pipe(extract3);
9009
- await done;
9010
- return entries;
9209
+ return read(async () => {
9210
+ Readable.fromWeb(res.body).pipe(extract3);
9211
+ await done;
9212
+ return entries;
9213
+ });
9011
9214
  }
9012
9215
  function put(path5, body) {
9013
9216
  return request("PUT", path5, body);
@@ -9034,31 +9237,34 @@ async function sendMessage(message) {
9034
9237
  }
9035
9238
  async function download(path5, retried = false) {
9036
9239
  const url = `${baseUrl()}${path5}`;
9037
- const res = await fetch(url, {
9240
+ const { res, read } = await fetchWithStagedTimeout(url, {
9038
9241
  headers: { ...clientHeaders(), "Authorization": `Bearer ${await bearerToken()}` }
9039
- });
9242
+ }, DOWNLOAD_HEADER_TIMEOUT_MS, `GET ${path5}`);
9040
9243
  if (await shouldRetryAfter401(res.status, retried)) {
9244
+ await read((r) => r.arrayBuffer().catch(() => null));
9041
9245
  return download(path5, true);
9042
9246
  }
9043
9247
  if (!res.ok) {
9248
+ await read(async () => null);
9044
9249
  throw new ApiError(res.status, "DOWNLOAD_ERROR", with401Hint(res.status, `Download failed: ${res.statusText}`));
9045
9250
  }
9046
- return Buffer.from(await res.arrayBuffer());
9251
+ return read(async (r) => Buffer.from(await r.arrayBuffer()));
9047
9252
  }
9048
9253
  async function downloadWithHeaders(path5, retried = false) {
9049
9254
  const url = `${baseUrl()}${path5}`;
9050
- const res = await fetch(url, {
9255
+ const { res, read } = await fetchWithStagedTimeout(url, {
9051
9256
  headers: { ...clientHeaders(), "Authorization": `Bearer ${await bearerToken()}` }
9052
- });
9257
+ }, LONG_REQUEST_TIMEOUT_MS, `GET ${path5}`);
9053
9258
  if (await shouldRetryAfter401(res.status, retried)) {
9259
+ await read((r) => r.arrayBuffer().catch(() => null));
9054
9260
  return downloadWithHeaders(path5, true);
9055
9261
  }
9056
9262
  if (!res.ok) {
9057
- 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 } })));
9058
9264
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
9059
9265
  throw new ApiError(res.status, err.code, with401Hint(res.status, err.message), json.data);
9060
9266
  }
9061
- return { buffer: Buffer.from(await res.arrayBuffer()), headers: res.headers };
9267
+ return read(async (r) => ({ buffer: Buffer.from(await r.arrayBuffer()), headers: r.headers }));
9062
9268
  }
9063
9269
  async function postBinary(path5, body, contentType = "application/zip", retried = false) {
9064
9270
  const url = `${baseUrl()}${path5}`;
@@ -9153,11 +9359,11 @@ async function getAccountSlug() {
9153
9359
  }
9154
9360
  async function publicRequest(method, path5, body, extraHeaders) {
9155
9361
  const url = `${baseUrl()}${path5}`;
9156
- const res = await fetch(url, {
9362
+ const res = await fetchWithTimeout(url, {
9157
9363
  method,
9158
9364
  headers: { ...clientHeaders(), "Content-Type": "application/json", ...extraHeaders },
9159
9365
  body: body === void 0 ? void 0 : JSON.stringify(body)
9160
- });
9366
+ }, REQUEST_TIMEOUT_MS, `${method} ${path5}`);
9161
9367
  if (!res.ok) {
9162
9368
  const json = await res.json().catch(() => ({ error: { code: "UNKNOWN", message: res.statusText } }));
9163
9369
  const err = json.error || { code: "UNKNOWN", message: res.statusText };
@@ -9176,7 +9382,7 @@ async function mintAppToken(projectGuid2) {
9176
9382
  return void 0;
9177
9383
  }
9178
9384
  }
9179
- var tar, ApiError, REQUEST_TIMEOUT_MS, DOWNLOAD_HEADER_TIMEOUT_MS, PUT_TIMEOUT_FLOOR_MS, PUT_MIN_BYTES_PER_SEC, accountSlugCache;
9385
+ var tar, ApiError, REQUEST_TIMEOUT_MS, DOWNLOAD_HEADER_TIMEOUT_MS, LONG_REQUEST_TIMEOUT_MS, PUT_TIMEOUT_FLOOR_MS, PUT_MIN_BYTES_PER_SEC, accountSlugCache;
9180
9386
  var init_api = __esm({
9181
9387
  "src/api.ts"() {
9182
9388
  "use strict";
@@ -9198,6 +9404,7 @@ var init_api = __esm({
9198
9404
  };
9199
9405
  REQUEST_TIMEOUT_MS = 6e4;
9200
9406
  DOWNLOAD_HEADER_TIMEOUT_MS = 3e4;
9407
+ LONG_REQUEST_TIMEOUT_MS = 31e4;
9201
9408
  PUT_TIMEOUT_FLOOR_MS = 12e4;
9202
9409
  PUT_MIN_BYTES_PER_SEC = 256 * 1024;
9203
9410
  accountSlugCache = null;
@@ -36078,14 +36285,14 @@ init_agents();
36078
36285
  init_colors();
36079
36286
  init_utils();
36080
36287
  import { basename as basename2, resolve as resolve7, dirname as dirname7 } from "path";
36081
- import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
36288
+ import { existsSync as existsSync10, readFileSync as readFileSync11 } from "fs";
36082
36289
 
36083
36290
  // src/adopt-cwd.ts
36084
36291
  init_api();
36085
36292
  init_setup();
36086
36293
  import { readdirSync as readdirSync6, statSync as statSync4 } from "fs";
36087
- import { join as join14, resolve as resolve6, sep as sep3, parse as parsePath } from "path";
36088
- import { homedir as homedir10 } from "os";
36294
+ import { join as join13, resolve as resolve6, sep as sep3, parse as parsePath } from "path";
36295
+ import { homedir as homedir9 } from "os";
36089
36296
 
36090
36297
  // src/project-setup.ts
36091
36298
  init_config();
@@ -36328,7 +36535,7 @@ async function finalizeLocalProject(opts) {
36328
36535
  } catch (err) {
36329
36536
  if (opts.sync === "strict") throw err;
36330
36537
  }
36331
- setupProjectTools(opts.tools ?? DEFAULT_TOOLS);
36538
+ setupProjectTools(opts.tools);
36332
36539
  return { applied };
36333
36540
  }
36334
36541
 
@@ -36352,165 +36559,6 @@ function getProjectsRoot() {
36352
36559
  return defaultDir;
36353
36560
  }
36354
36561
 
36355
- // src/relay/state.ts
36356
- import { readFileSync as readFileSync11, writeFileSync as writeFileSync8, mkdirSync as mkdirSync7, existsSync as existsSync10, chmodSync as chmodSync3, unlinkSync as unlinkSync5 } from "fs";
36357
- import { join as join13 } from "path";
36358
- import { homedir as homedir9 } from "os";
36359
- var RELAY_DIR = process.env.GIPITY_DIR || join13(homedir9(), ".gipity");
36360
- var RELAY_FILE = join13(RELAY_DIR, "relay.json");
36361
- var FILE_MODE = 384;
36362
- function emptyState() {
36363
- return { device: null, paused: false };
36364
- }
36365
- function loadState() {
36366
- if (!existsSync10(RELAY_FILE)) return emptyState();
36367
- try {
36368
- const raw = JSON.parse(readFileSync11(RELAY_FILE, "utf-8"));
36369
- return {
36370
- device: raw.device ?? null,
36371
- paused: Boolean(raw.paused),
36372
- relay_enabled: typeof raw.relay_enabled === "boolean" ? raw.relay_enabled : void 0,
36373
- onboard_shown: Boolean(raw.onboard_shown),
36374
- diagnostics_consent: typeof raw.diagnostics_consent === "boolean" ? raw.diagnostics_consent : void 0,
36375
- agent_updates: typeof raw.agent_updates === "boolean" ? raw.agent_updates : void 0,
36376
- agent_token: typeof raw.agent_token === "string" ? raw.agent_token : null,
36377
- agent_token_guid: typeof raw.agent_token_guid === "string" ? raw.agent_token_guid : null
36378
- };
36379
- } catch {
36380
- return emptyState();
36381
- }
36382
- }
36383
- function saveState(state) {
36384
- mkdirSync7(RELAY_DIR, { recursive: true });
36385
- writeFileSync8(RELAY_FILE, JSON.stringify(state, null, 2) + "\n", { mode: FILE_MODE });
36386
- try {
36387
- chmodSync3(RELAY_FILE, FILE_MODE);
36388
- } catch {
36389
- }
36390
- }
36391
- function mutate(fn) {
36392
- const s = loadState();
36393
- fn(s);
36394
- saveState(s);
36395
- }
36396
- function getDevice() {
36397
- return loadState().device;
36398
- }
36399
- function setDevice(device) {
36400
- mutate((s) => {
36401
- s.device = device;
36402
- });
36403
- }
36404
- function clearDevice() {
36405
- mutate((s) => {
36406
- s.device = null;
36407
- s.paused = false;
36408
- s.agent_token = null;
36409
- s.agent_token_guid = null;
36410
- });
36411
- }
36412
- function getAgentToken() {
36413
- const s = loadState();
36414
- return s.agent_token ? { token: s.agent_token, guid: s.agent_token_guid ?? null } : null;
36415
- }
36416
- function setAgentToken(token, guid) {
36417
- mutate((s) => {
36418
- s.agent_token = token;
36419
- s.agent_token_guid = guid;
36420
- });
36421
- }
36422
- function isPaused() {
36423
- return loadState().paused;
36424
- }
36425
- function setPaused(paused) {
36426
- mutate((s) => {
36427
- s.paused = paused;
36428
- });
36429
- }
36430
- function getRelayEnabled() {
36431
- return loadState().relay_enabled;
36432
- }
36433
- function isRelayEnabled() {
36434
- return loadState().relay_enabled === true;
36435
- }
36436
- function setRelayEnabled(enabled) {
36437
- mutate((s) => {
36438
- s.relay_enabled = enabled;
36439
- });
36440
- }
36441
- function getDiagnosticsConsent() {
36442
- return loadState().diagnostics_consent;
36443
- }
36444
- function setDiagnosticsConsent(consent) {
36445
- mutate((s) => {
36446
- s.diagnostics_consent = consent;
36447
- });
36448
- }
36449
- function diagnosticsConsented() {
36450
- const env = process.env.GIPITY_NO_DIAGNOSTICS ?? process.env.DO_NOT_TRACK;
36451
- if (env && env !== "0" && env.toLowerCase() !== "false") return false;
36452
- return loadState().diagnostics_consent !== false;
36453
- }
36454
- function getAgentUpdatesPref() {
36455
- return loadState().agent_updates;
36456
- }
36457
- function setAgentUpdatesPref(on2) {
36458
- mutate((s) => {
36459
- s.agent_updates = on2;
36460
- });
36461
- }
36462
- function agentUpdatesEnabled() {
36463
- if (process.env.DISABLE_AUTOUPDATER === "1") return false;
36464
- const env = (process.env.GIPITY_RELAY_AGENT_UPDATES || "").toLowerCase();
36465
- if (["0", "off", "false", "no"].includes(env)) return false;
36466
- if (["1", "on", "true", "yes"].includes(env)) return true;
36467
- if (process.env.CI || process.env.NODE_ENV === "test") return false;
36468
- return loadState().agent_updates !== false;
36469
- }
36470
- var RELAY_PID_FILE = join13(RELAY_DIR, "relay.pid");
36471
- function getDaemonPidPath() {
36472
- return RELAY_PID_FILE;
36473
- }
36474
- function writeDaemonPid(pid) {
36475
- mkdirSync7(RELAY_DIR, { recursive: true });
36476
- writeFileSync8(RELAY_PID_FILE, String(pid), { flag: "wx" });
36477
- }
36478
- function clearDaemonPid() {
36479
- try {
36480
- unlinkSync5(RELAY_PID_FILE);
36481
- } catch {
36482
- }
36483
- }
36484
- function isDaemonRunning() {
36485
- if (!existsSync10(RELAY_PID_FILE)) return false;
36486
- try {
36487
- const raw = readFileSync11(RELAY_PID_FILE, "utf-8").trim();
36488
- const pid = parseInt(raw, 10);
36489
- if (!pid || isNaN(pid)) {
36490
- try {
36491
- unlinkSync5(RELAY_PID_FILE);
36492
- } catch {
36493
- }
36494
- return false;
36495
- }
36496
- if (pid === process.pid) {
36497
- try {
36498
- unlinkSync5(RELAY_PID_FILE);
36499
- } catch {
36500
- }
36501
- return false;
36502
- }
36503
- process.kill(pid, 0);
36504
- return true;
36505
- } catch {
36506
- try {
36507
- unlinkSync5(RELAY_PID_FILE);
36508
- } catch {
36509
- }
36510
- return false;
36511
- }
36512
- }
36513
-
36514
36562
  // src/adopt-cwd.ts
36515
36563
  var EASY_FILES = 200;
36516
36564
  var EASY_BYTES = 100 * 1024 * 1024;
@@ -36531,7 +36579,7 @@ function scanForAdoption(cwd) {
36531
36579
  for (const name of entries) {
36532
36580
  if (truncated) return;
36533
36581
  if (isSyncIgnored(name)) continue;
36534
- const full = join14(dir, name);
36582
+ const full = join13(dir, name);
36535
36583
  let st2;
36536
36584
  try {
36537
36585
  st2 = statSync4(full);
@@ -36568,7 +36616,7 @@ function isLikelyEmpty(cwd) {
36568
36616
  }
36569
36617
  function canAdoptCwd(cwd) {
36570
36618
  const norm = resolve6(cwd);
36571
- const home = resolve6(homedir10());
36619
+ const home = resolve6(homedir9());
36572
36620
  const blocked = /* @__PURE__ */ new Set([
36573
36621
  sep3,
36574
36622
  home,
@@ -36605,10 +36653,10 @@ function countGitRepoChildren(dir) {
36605
36653
  let count = 0;
36606
36654
  for (const name of entries.slice(0, 50)) {
36607
36655
  if (name.startsWith(".")) continue;
36608
- const child = join14(dir, name);
36656
+ const child = join13(dir, name);
36609
36657
  try {
36610
36658
  if (!statSync4(child).isDirectory()) continue;
36611
- const gitPath = join14(child, ".git");
36659
+ const gitPath = join13(child, ".git");
36612
36660
  if (statSync4(gitPath)) count++;
36613
36661
  } catch {
36614
36662
  }
@@ -36618,7 +36666,7 @@ function countGitRepoChildren(dir) {
36618
36666
  }
36619
36667
  function formatCwdLabel(cwd) {
36620
36668
  const norm = resolve6(cwd);
36621
- const home = resolve6(homedir10());
36669
+ const home = resolve6(homedir9());
36622
36670
  if (norm === home) return "~";
36623
36671
  if (norm.startsWith(home + sep3)) {
36624
36672
  const tail2 = norm.slice(home.length + 1).split(sep3);
@@ -36645,15 +36693,10 @@ async function adoptCurrentDir(opts) {
36645
36693
  }
36646
36694
  let isNew = false;
36647
36695
  if (!project) {
36648
- const device = getDevice();
36649
36696
  const body = {
36650
36697
  name: opts.projectName,
36651
36698
  slug: opts.projectSlug
36652
36699
  };
36653
- if (device) {
36654
- body.autoChat = "claude_code";
36655
- body.deviceGuid = device.guid;
36656
- }
36657
36700
  try {
36658
36701
  const res = await post("/projects", body);
36659
36702
  project = res.data;
@@ -36699,8 +36742,11 @@ var ADOPT_THRESHOLDS = {
36699
36742
 
36700
36743
  // src/commands/init.ts
36701
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
+ }
36702
36748
  function resolveTools(forFlag) {
36703
- if (!forFlag) return DEFAULT_TOOLS;
36749
+ if (!forFlag) return resolveProjectTools();
36704
36750
  const requested = forFlag.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
36705
36751
  const unknown = requested.filter((k7) => !TOOL_KEYS.includes(k7) && k7 !== "all");
36706
36752
  if (unknown.length) {
@@ -36711,13 +36757,17 @@ function resolveTools(forFlag) {
36711
36757
  );
36712
36758
  }
36713
36759
  var initCommand = new Command("init").description("Link this directory to a project").addHelpText("after", `
36714
- 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(
36715
36761
  "--for <tools>",
36716
- `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`
36717
36763
  ).addHelpText("after", `
36718
36764
  Examples:
36719
- $ 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.
36720
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.
36721
36771
  $ gipity init --for codex AGENTS.md + Codex skills/sync hooks only.
36722
36772
  $ gipity init --for grok AGENTS.md + the Gipity plugin in Grok only.
36723
36773
  $ gipity init --for cursor,gemini Write only the Cursor + Gemini primers.
@@ -36741,6 +36791,8 @@ Working with an existing Gipity project:
36741
36791
  }
36742
36792
  const wantsClaude = tools.some((t) => t.key === "claude");
36743
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;
36744
36796
  try {
36745
36797
  const auth = getAuth();
36746
36798
  if (!auth) {
@@ -36748,7 +36800,7 @@ Working with an existing Gipity project:
36748
36800
  process.exit(1);
36749
36801
  }
36750
36802
  const cwd = process.cwd();
36751
- if (existsSync11(resolve7(cwd, ".gipity.json"))) {
36803
+ if (existsSync10(resolve7(cwd, ".gipity.json"))) {
36752
36804
  const existing = getConfig();
36753
36805
  console.log(`Already linked to ${info(`"${existing?.projectSlug ?? ""}"`)} ${muted(`(${existing?.projectGuid ?? ""})`)}`);
36754
36806
  setupProjectTools(tools);
@@ -36764,9 +36816,15 @@ Working with an existing Gipity project:
36764
36816
  existing.captureHooks = false;
36765
36817
  changed = true;
36766
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
+ }
36767
36824
  if (changed) saveConfigAt(cwd, existing);
36768
36825
  }
36769
36826
  console.log(success(`Refreshed primer files: ${primerSummary}.`));
36827
+ if (skippedNote) console.log(skippedNote);
36770
36828
  if (opts.capture === false) {
36771
36829
  console.log(success("Session recording disabled for this project (captureHooks: false in .gipity.json)."));
36772
36830
  }
@@ -36829,15 +36887,18 @@ Working with an existing Gipity project:
36829
36887
  console.log(`Found existing project ${info(`"${adopted.project.name}"`)} ${muted(`(${adopted.project.slug})`)}`);
36830
36888
  }
36831
36889
  if (adopted.applied > 0) console.log(`Synced ${adopted.applied} change${adopted.applied > 1 ? "s" : ""} with Gipity.`);
36832
- if (opts.capture === false) {
36890
+ const pinnedFresh = pinnedToolKeys(opts.for, tools);
36891
+ if (opts.capture === false || pinnedFresh) {
36833
36892
  try {
36834
- const cfg = JSON.parse(readFileSync12(resolve7(cwd, ".gipity.json"), "utf-8"));
36835
- cfg.captureHooks = false;
36893
+ const cfg = JSON.parse(readFileSync11(resolve7(cwd, ".gipity.json"), "utf-8"));
36894
+ if (opts.capture === false) cfg.captureHooks = false;
36895
+ if (pinnedFresh) cfg.tools = pinnedFresh;
36836
36896
  saveConfigAt(cwd, cfg);
36837
36897
  } catch {
36838
36898
  }
36839
36899
  }
36840
36900
  console.log(success(`Wrote primer files: ${primerSummary}.`));
36901
+ if (skippedNote) console.log(skippedNote);
36841
36902
  if (wantsClaude) {
36842
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.`));
36843
36904
  if (opts.capture === false) {
@@ -36866,15 +36927,15 @@ init_api();
36866
36927
  init_config();
36867
36928
  init_colors();
36868
36929
  init_setup();
36869
- import { existsSync as existsSync12, readFileSync as readFileSync13 } from "fs";
36870
- import { join as join15, resolve as resolve8 } from "path";
36871
- import { homedir as homedir11 } from "os";
36930
+ import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
36931
+ import { join as join14, resolve as resolve8 } from "path";
36932
+ import { homedir as homedir10 } from "os";
36872
36933
  function checkGipityPlugin() {
36873
- const path5 = join15(homedir11(), ".claude", "settings.json");
36934
+ const path5 = join14(homedir10(), ".claude", "settings.json");
36874
36935
  let settings = {};
36875
- if (existsSync12(path5)) {
36936
+ if (existsSync11(path5)) {
36876
36937
  try {
36877
- settings = JSON.parse(readFileSync13(path5, "utf-8"));
36938
+ settings = JSON.parse(readFileSync12(path5, "utf-8"));
36878
36939
  } catch {
36879
36940
  }
36880
36941
  }
@@ -37126,7 +37187,7 @@ init_colors();
37126
37187
  init_auth();
37127
37188
 
37128
37189
  // src/commands/page-eval.ts
37129
- import { readFileSync as readFileSync15 } from "node:fs";
37190
+ import { readFileSync as readFileSync14 } from "node:fs";
37130
37191
  init_api();
37131
37192
  init_colors();
37132
37193
  init_auth();
@@ -37159,8 +37220,8 @@ function dropCheckpoint(projectGuid2, database) {
37159
37220
  // src/page-fixtures.ts
37160
37221
  init_api();
37161
37222
  init_config();
37162
- import { readFileSync as readFileSync14, statSync as statSync6, existsSync as existsSync13, readdirSync as readdirSync7 } from "node:fs";
37163
- import { basename as basename4, resolve as resolve10, relative as relative3, join as join16 } from "node:path";
37223
+ import { readFileSync as readFileSync13, statSync as statSync6, existsSync as existsSync12, readdirSync as readdirSync7 } from "node:fs";
37224
+ import { basename as basename4, resolve as resolve10, relative as relative3, join as join15 } from "node:path";
37164
37225
  var FIND_SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", ".gipity", "dist", "build", ".next", "coverage"]);
37165
37226
  function findByBasename(root, name, limit = 3) {
37166
37227
  const hits = [];
@@ -37177,9 +37238,9 @@ function findByBasename(root, name, limit = 3) {
37177
37238
  }
37178
37239
  for (const e of entries) {
37179
37240
  if (e.isDirectory()) {
37180
- if (!FIND_SKIP.has(e.name)) queue.push(join16(dir, e.name));
37241
+ if (!FIND_SKIP.has(e.name)) queue.push(join15(dir, e.name));
37181
37242
  } else if (e.name === name && hits.length < limit) {
37182
- hits.push(join16(dir, e.name));
37243
+ hits.push(join15(dir, e.name));
37183
37244
  }
37184
37245
  }
37185
37246
  }
@@ -37187,7 +37248,7 @@ function findByBasename(root, name, limit = 3) {
37187
37248
  }
37188
37249
  function assertLocalAsset(flag, localPath) {
37189
37250
  const abs = resolve10(localPath);
37190
- if (existsSync13(abs)) return;
37251
+ if (existsSync12(abs)) return;
37191
37252
  const root = getProjectRoot() ?? process.cwd();
37192
37253
  const elsewhere = findByBasename(root, basename4(localPath)).filter((p) => p !== abs);
37193
37254
  const found = elsewhere.length ? `
@@ -37213,7 +37274,7 @@ async function uploadPublicFixture(projectGuid2, localPath, flag = "--fixture")
37213
37274
  const res = await fetch(init.data.url, {
37214
37275
  method: "PUT",
37215
37276
  headers: { "Content-Type": contentType },
37216
- body: readFileSync14(localPath)
37277
+ body: readFileSync13(localPath)
37217
37278
  });
37218
37279
  if (!res.ok) {
37219
37280
  throw new Error(`upload of fixture "${name}" failed: ${res.status} ${res.statusText}`);
@@ -37313,7 +37374,7 @@ function capWaitForTimeoutMs(raw) {
37313
37374
  return WAIT_FOR_MAX_MS;
37314
37375
  }
37315
37376
  function readScriptFile(pathArg) {
37316
- return readFileSync15(pathArg === "-" ? 0 : pathArg, "utf8");
37377
+ return readFileSync14(pathArg === "-" ? 0 : pathArg, "utf8");
37317
37378
  }
37318
37379
  function parsesAsExpression(s) {
37319
37380
  try {
@@ -37757,8 +37818,8 @@ init_config();
37757
37818
  init_auth();
37758
37819
  init_colors();
37759
37820
  init_utils();
37760
- import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync9 } from "fs";
37761
- import { dirname as dirname9, extname as extname4, join as join17, resolve as resolvePath } from "path";
37821
+ import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "fs";
37822
+ import { dirname as dirname9, extname as extname4, join as join16, resolve as resolvePath } from "path";
37762
37823
  var DEVICE_PRESETS = {
37763
37824
  default: { width: 1280, height: 720 },
37764
37825
  desktop: { width: 1920, height: 1080 },
@@ -37822,7 +37883,7 @@ function dimSuffix(vp2) {
37822
37883
  }
37823
37884
  function defaultScreenshotDir() {
37824
37885
  const root = getProjectRoot();
37825
- return join17(root ?? ".", "screenshots");
37886
+ return join16(root ?? ".", "screenshots");
37826
37887
  }
37827
37888
  function timestampSlug(d = /* @__PURE__ */ new Date()) {
37828
37889
  const p = (n) => String(n).padStart(2, "0");
@@ -38034,9 +38095,9 @@ var pageScreenshotCommand = new Command("screenshot").description("Screenshot a
38034
38095
  return stemPath(opts.output, suffix);
38035
38096
  };
38036
38097
  for (let i = 0; i < pngs.length; i++) {
38037
- const target = opts.output ? outputPath(i) : join17(dir, names[i] ?? shotName(meta.screenshots[i].viewport));
38038
- mkdirSync8(dirname9(target), { recursive: true });
38039
- writeFileSync9(target, pngs[i].buffer);
38098
+ const target = opts.output ? outputPath(i) : join16(dir, names[i] ?? shotName(meta.screenshots[i].viewport));
38099
+ mkdirSync7(dirname9(target), { recursive: true });
38100
+ writeFileSync8(target, pngs[i].buffer);
38040
38101
  savedFiles.push(resolvePath(target));
38041
38102
  }
38042
38103
  if (opts.json) {
@@ -38678,7 +38739,7 @@ memoryCommand.command("delete <topic>").description("Delete a topic").option("--
38678
38739
  init_api();
38679
38740
  init_config();
38680
38741
  init_setup();
38681
- import { readFileSync as readFileSync16, existsSync as existsSync14, statSync as statSync7, mkdirSync as mkdirSync9, writeFileSync as writeFileSync10 } from "fs";
38742
+ import { readFileSync as readFileSync15, existsSync as existsSync13, statSync as statSync7, mkdirSync as mkdirSync8, writeFileSync as writeFileSync9 } from "fs";
38682
38743
  import { dirname as dirname10, extname as extname5, relative as relative4, resolve as resolve11, sep as sep4 } from "path";
38683
38744
  init_colors();
38684
38745
  var LANG_MAP = {
@@ -38899,7 +38960,7 @@ GCC/Rust).
38899
38960
  if (args.length >= 2 && INTERPRETERS[args[0].toLowerCase()] !== void 0) {
38900
38961
  langFromInterp = INTERPRETERS[args[0].toLowerCase()];
38901
38962
  const rest = args.slice(1).join(" ");
38902
- if (existsSync14(rest) && statSync7(rest).isFile()) filePath = rest;
38963
+ if (existsSync13(rest) && statSync7(rest).isFile()) filePath = rest;
38903
38964
  else inlineCode = rest;
38904
38965
  } else if (args.length === 1) {
38905
38966
  inlineCode = args[0];
@@ -38920,7 +38981,7 @@ GCC/Rust).
38920
38981
  let source = inlineCode;
38921
38982
  if (filePath) {
38922
38983
  try {
38923
- source = readFileSync16(filePath, "utf8");
38984
+ source = readFileSync15(filePath, "utf8");
38924
38985
  } catch {
38925
38986
  console.error(error(`Cannot read file: ${filePath}`));
38926
38987
  process.exit(1);
@@ -38947,7 +39008,7 @@ GCC/Rust).
38947
39008
  }
38948
39009
  if (source) {
38949
39010
  const scratchReads = scratchRefsInCode(source).filter(
38950
- (p) => shouldIgnore(p, SCRATCH_IGNORE) && existsSync14(resolve11(process.cwd(), p)) && !isWriteTarget(source, p)
39011
+ (p) => shouldIgnore(p, SCRATCH_IGNORE) && existsSync13(resolve11(process.cwd(), p)) && !isWriteTarget(source, p)
38951
39012
  );
38952
39013
  if (scratchReads.length) {
38953
39014
  console.error(error(`Scratch files are never mirrored into the sandbox, so it can't read: ${scratchReads.join(", ")}`));
@@ -38984,8 +39045,8 @@ GCC/Rust).
38984
39045
  const rel2 = f.path.replace(/\\/g, "/");
38985
39046
  const abs = resolve11(base, rel2);
38986
39047
  if (abs !== base && !abs.startsWith(base + sep4)) continue;
38987
- mkdirSync9(dirname10(abs), { recursive: true });
38988
- writeFileSync10(abs, Buffer.from(f.contentBase64, "base64"));
39048
+ mkdirSync8(dirname10(abs), { recursive: true });
39049
+ writeFileSync9(abs, Buffer.from(f.contentBase64, "base64"));
38989
39050
  scratchWritten.push(rel2);
38990
39051
  }
38991
39052
  }
@@ -39008,7 +39069,7 @@ GCC/Rust).
39008
39069
  }
39009
39070
  if (res.data.outputFiles && res.data.outputFiles.length > 0) {
39010
39071
  const projectRoot = getProjectRoot();
39011
- const landed = (f) => pulledLocal && !!projectRoot && existsSync14(resolve11(projectRoot, f));
39072
+ const landed = (f) => pulledLocal && !!projectRoot && existsSync13(resolve11(projectRoot, f));
39012
39073
  const onDisk = res.data.outputFiles.filter(landed);
39013
39074
  const notOnDisk = res.data.outputFiles.filter((f) => !landed(f));
39014
39075
  if (onDisk.length > 0) {
@@ -39162,6 +39223,167 @@ init_colors();
39162
39223
  init_utils();
39163
39224
  import { join as join18 } from "path";
39164
39225
  import { mkdirSync as mkdirSync10 } from "fs";
39226
+
39227
+ // src/relay/state.ts
39228
+ import { readFileSync as readFileSync16, writeFileSync as writeFileSync10, mkdirSync as mkdirSync9, existsSync as existsSync14, chmodSync as chmodSync3, unlinkSync as unlinkSync5 } from "fs";
39229
+ import { join as join17 } from "path";
39230
+ import { homedir as homedir11 } from "os";
39231
+ var RELAY_DIR = process.env.GIPITY_DIR || join17(homedir11(), ".gipity");
39232
+ var RELAY_FILE = join17(RELAY_DIR, "relay.json");
39233
+ var FILE_MODE = 384;
39234
+ function emptyState() {
39235
+ return { device: null, paused: false };
39236
+ }
39237
+ function loadState() {
39238
+ if (!existsSync14(RELAY_FILE)) return emptyState();
39239
+ try {
39240
+ const raw = JSON.parse(readFileSync16(RELAY_FILE, "utf-8"));
39241
+ return {
39242
+ device: raw.device ?? null,
39243
+ paused: Boolean(raw.paused),
39244
+ relay_enabled: typeof raw.relay_enabled === "boolean" ? raw.relay_enabled : void 0,
39245
+ onboard_shown: Boolean(raw.onboard_shown),
39246
+ diagnostics_consent: typeof raw.diagnostics_consent === "boolean" ? raw.diagnostics_consent : void 0,
39247
+ agent_updates: typeof raw.agent_updates === "boolean" ? raw.agent_updates : void 0,
39248
+ agent_token: typeof raw.agent_token === "string" ? raw.agent_token : null,
39249
+ agent_token_guid: typeof raw.agent_token_guid === "string" ? raw.agent_token_guid : null
39250
+ };
39251
+ } catch {
39252
+ return emptyState();
39253
+ }
39254
+ }
39255
+ function saveState(state) {
39256
+ mkdirSync9(RELAY_DIR, { recursive: true });
39257
+ writeFileSync10(RELAY_FILE, JSON.stringify(state, null, 2) + "\n", { mode: FILE_MODE });
39258
+ try {
39259
+ chmodSync3(RELAY_FILE, FILE_MODE);
39260
+ } catch {
39261
+ }
39262
+ }
39263
+ function mutate(fn) {
39264
+ const s = loadState();
39265
+ fn(s);
39266
+ saveState(s);
39267
+ }
39268
+ function getDevice() {
39269
+ return loadState().device;
39270
+ }
39271
+ function setDevice(device) {
39272
+ mutate((s) => {
39273
+ s.device = device;
39274
+ });
39275
+ }
39276
+ function clearDevice() {
39277
+ mutate((s) => {
39278
+ s.device = null;
39279
+ s.paused = false;
39280
+ s.agent_token = null;
39281
+ s.agent_token_guid = null;
39282
+ });
39283
+ }
39284
+ function getAgentToken() {
39285
+ const s = loadState();
39286
+ return s.agent_token ? { token: s.agent_token, guid: s.agent_token_guid ?? null } : null;
39287
+ }
39288
+ function setAgentToken(token, guid) {
39289
+ mutate((s) => {
39290
+ s.agent_token = token;
39291
+ s.agent_token_guid = guid;
39292
+ });
39293
+ }
39294
+ function isPaused() {
39295
+ return loadState().paused;
39296
+ }
39297
+ function setPaused(paused) {
39298
+ mutate((s) => {
39299
+ s.paused = paused;
39300
+ });
39301
+ }
39302
+ function getRelayEnabled() {
39303
+ return loadState().relay_enabled;
39304
+ }
39305
+ function isRelayEnabled() {
39306
+ return loadState().relay_enabled === true;
39307
+ }
39308
+ function setRelayEnabled(enabled) {
39309
+ mutate((s) => {
39310
+ s.relay_enabled = enabled;
39311
+ });
39312
+ }
39313
+ function getDiagnosticsConsent() {
39314
+ return loadState().diagnostics_consent;
39315
+ }
39316
+ function setDiagnosticsConsent(consent) {
39317
+ mutate((s) => {
39318
+ s.diagnostics_consent = consent;
39319
+ });
39320
+ }
39321
+ function diagnosticsConsented() {
39322
+ const env = process.env.GIPITY_NO_DIAGNOSTICS ?? process.env.DO_NOT_TRACK;
39323
+ if (env && env !== "0" && env.toLowerCase() !== "false") return false;
39324
+ return loadState().diagnostics_consent !== false;
39325
+ }
39326
+ function getAgentUpdatesPref() {
39327
+ return loadState().agent_updates;
39328
+ }
39329
+ function setAgentUpdatesPref(on2) {
39330
+ mutate((s) => {
39331
+ s.agent_updates = on2;
39332
+ });
39333
+ }
39334
+ function agentUpdatesEnabled() {
39335
+ if (process.env.DISABLE_AUTOUPDATER === "1") return false;
39336
+ const env = (process.env.GIPITY_RELAY_AGENT_UPDATES || "").toLowerCase();
39337
+ if (["0", "off", "false", "no"].includes(env)) return false;
39338
+ if (["1", "on", "true", "yes"].includes(env)) return true;
39339
+ if (process.env.CI || process.env.NODE_ENV === "test") return false;
39340
+ return loadState().agent_updates !== false;
39341
+ }
39342
+ var RELAY_PID_FILE = join17(RELAY_DIR, "relay.pid");
39343
+ function getDaemonPidPath() {
39344
+ return RELAY_PID_FILE;
39345
+ }
39346
+ function writeDaemonPid(pid) {
39347
+ mkdirSync9(RELAY_DIR, { recursive: true });
39348
+ writeFileSync10(RELAY_PID_FILE, String(pid), { flag: "wx" });
39349
+ }
39350
+ function clearDaemonPid() {
39351
+ try {
39352
+ unlinkSync5(RELAY_PID_FILE);
39353
+ } catch {
39354
+ }
39355
+ }
39356
+ function isDaemonRunning() {
39357
+ if (!existsSync14(RELAY_PID_FILE)) return false;
39358
+ try {
39359
+ const raw = readFileSync16(RELAY_PID_FILE, "utf-8").trim();
39360
+ const pid = parseInt(raw, 10);
39361
+ if (!pid || isNaN(pid)) {
39362
+ try {
39363
+ unlinkSync5(RELAY_PID_FILE);
39364
+ } catch {
39365
+ }
39366
+ return false;
39367
+ }
39368
+ if (pid === process.pid) {
39369
+ try {
39370
+ unlinkSync5(RELAY_PID_FILE);
39371
+ } catch {
39372
+ }
39373
+ return false;
39374
+ }
39375
+ process.kill(pid, 0);
39376
+ return true;
39377
+ } catch {
39378
+ try {
39379
+ unlinkSync5(RELAY_PID_FILE);
39380
+ } catch {
39381
+ }
39382
+ return false;
39383
+ }
39384
+ }
39385
+
39386
+ // src/commands/project.ts
39165
39387
  var projectCommand = new Command("project").description("Manage projects").argument("[name]", "Switch to project by name/slug").option("--json", "Output as JSON").action((name, opts) => run("Project", async () => {
39166
39388
  const config = requireConfig();
39167
39389
  if (name) {
@@ -41429,6 +41651,7 @@ async function runLaunch(cmdName, cmdCfg, opts) {
41429
41651
  }
41430
41652
  }
41431
41653
  const adapter = getAdapter(agentKey);
41654
+ setupToolForAgent(adapter.key);
41432
41655
  if (!nonInteractive && !cmdCfg.presetAgent) {
41433
41656
  writePrefs({ lastAgent: adapter.key });
41434
41657
  }
@@ -41566,7 +41789,7 @@ Sending to Claude Code: ${userMsg}
41566
41789
  } else if (convGuidForHooks) {
41567
41790
  childEnv2.GIPITY_CONVERSATION_GUID = convGuidForHooks;
41568
41791
  }
41569
- if (!nonInteractive) markFolderTrusted(process.cwd());
41792
+ markFolderTrusted(process.cwd());
41570
41793
  const child = spawnCommand(claudeCmd, allArgs, {
41571
41794
  stdio: "inherit",
41572
41795
  cwd: process.cwd(),
@@ -41949,12 +42172,7 @@ async function createNewProject(existingSlugs, preset) {
41949
42172
  continue;
41950
42173
  }
41951
42174
  try {
41952
- const device = getDevice();
41953
42175
  const body = { name: projectName, slug: projectSlug };
41954
- if (device) {
41955
- body.autoChat = "claude_code";
41956
- body.deviceGuid = device.guid;
41957
- }
41958
42176
  const res = await post("/projects", body);
41959
42177
  console.log(` ${info(`Creating "${projectName}"...`)} ${success("Created.")}`);
41960
42178
  return res.data;
@@ -43364,7 +43582,7 @@ serviceCommand.command("call <name> [body]").description("Call an app service by
43364
43582
  }
43365
43583
  res = await publicRequest(opts.get ? "GET" : "POST", url, opts.get ? void 0 : body, headers);
43366
43584
  } else {
43367
- res = opts.get ? await get(url) : await post(url, body);
43585
+ res = opts.get ? await get(url) : await post(url, body, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
43368
43586
  }
43369
43587
  } catch (err) {
43370
43588
  const hint = opts.anon ? anonBillingHint(name, err) : null;
@@ -44334,7 +44552,7 @@ Examples:
44334
44552
  image_size: opts.imageSize,
44335
44553
  seed: Number.isFinite(opts.seed) ? opts.seed : void 0,
44336
44554
  input_images: inputImages
44337
- });
44555
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
44338
44556
  const verb = inputImages ? "Editing image..." : "Generating image...";
44339
44557
  const started = Date.now();
44340
44558
  const result = opts.json ? await doGenerate() : await withSpinner(verb, doGenerate, { done: null });
@@ -44383,7 +44601,7 @@ Examples:
44383
44601
  aspect_ratio: opts.aspect,
44384
44602
  resolution: opts.resolution,
44385
44603
  duration_seconds: opts.duration ? Number(opts.duration) : void 0
44386
- });
44604
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
44387
44605
  const started = Date.now();
44388
44606
  const result = opts.json ? await doGenerate() : await withSpinner("Generating video...", doGenerate, { done: null });
44389
44607
  const elapsed = (Date.now() - started) / 1e3;
@@ -44438,7 +44656,7 @@ Examples:
44438
44656
  voice: opts.voice,
44439
44657
  language: opts.language,
44440
44658
  speakers
44441
- });
44659
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
44442
44660
  const started = Date.now();
44443
44661
  const result = opts.json ? await doGenerate() : await withSpinner("Generating speech...", doGenerate, { done: null });
44444
44662
  const elapsed = (Date.now() - started) / 1e3;
@@ -44490,7 +44708,7 @@ Examples:
44490
44708
  // Lyrics imply vocals; otherwise instrumental unless --vocals.
44491
44709
  instrumental: lyrics ? false : !opts.vocals,
44492
44710
  lyrics: lyrics || void 0
44493
- });
44711
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
44494
44712
  const started = Date.now();
44495
44713
  const result = opts.json ? await doGenerate() : await withSpinner("Generating music...", doGenerate, { done: null });
44496
44714
  const elapsed = (Date.now() - started) / 1e3;
@@ -44530,7 +44748,7 @@ Examples:
44530
44748
  text,
44531
44749
  duration_seconds: opts.duration,
44532
44750
  prompt_influence: opts.influence
44533
- });
44751
+ }, { timeoutMs: LONG_REQUEST_TIMEOUT_MS });
44534
44752
  const started = Date.now();
44535
44753
  const result = opts.json ? await doGenerate() : await withSpinner("Generating sound effect...", doGenerate, { done: null });
44536
44754
  const elapsed = (Date.now() - started) / 1e3;
@@ -45378,7 +45596,12 @@ function gatherEnv(opts = {}) {
45378
45596
  session_expired: expired
45379
45597
  };
45380
45598
  const claude = { installed: isClaudeInstalled(), authenticated: false };
45381
- claude.authenticated = claude.installed && (opts.probeClaude ? probeClaudeAuthenticated() : isClaudeAuthenticated());
45599
+ if (claude.installed) {
45600
+ const status = opts.probeClaude ? null : claudeAuthStatus();
45601
+ claude.authenticated = opts.probeClaude ? probeClaudeAuthenticated() : status?.loggedIn ?? claudeCredentialHeuristic();
45602
+ claude.account = status?.email ?? null;
45603
+ claude.method = status?.authMethod ?? null;
45604
+ }
45382
45605
  const relay = {
45383
45606
  paired: !!device,
45384
45607
  running: isDaemonRunning(),
@@ -45418,7 +45641,11 @@ var doctorCommand = new Command("doctor").description("Check install + environme
45418
45641
  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.`)}`);
45419
45642
  }
45420
45643
  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")}`);
45421
- console.log(`${muted("claude code ")} installed ${yn(env.claude.installed)} \xB7 authenticated ${yn(env.claude.authenticated)}`);
45644
+ const claudeAccount = env.claude.account ? muted(` (${env.claude.account}${env.claude.method ? ` via ${env.claude.method}` : ""})`) : "";
45645
+ console.log(`${muted("claude code ")} installed ${yn(env.claude.installed)} \xB7 authenticated ${yn(env.claude.authenticated)}${claudeAccount}`);
45646
+ if (env.claude.installed && !env.claude.authenticated) {
45647
+ console.log(`${muted(" ")} ${warning(claudeLoginHint())}`);
45648
+ }
45422
45649
  const autostartLabel = env.relay.autostart === null ? muted("n/a") : yn(env.relay.autostart);
45423
45650
  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})`) : ""}`);
45424
45651
  if (existsSync20(resolve15(process.cwd(), ".codex", "hooks.json"))) {
@@ -46403,6 +46630,7 @@ async function revokeRelayAgentToken() {
46403
46630
  init_platform();
46404
46631
  init_client_context();
46405
46632
  init_agents();
46633
+ init_claude_setup();
46406
46634
  import { cpus, freemem, totalmem, loadavg, release, uptime, homedir as homedir18 } from "os";
46407
46635
  import { statfsSync, readdirSync as readdirSync9 } from "fs";
46408
46636
  import { join as join26 } from "path";
@@ -46499,10 +46727,11 @@ async function collectDiagnostics() {
46499
46727
  return [];
46500
46728
  }
46501
46729
  })();
46502
- const [versions, cursor, gpu] = await Promise.all([
46730
+ const [versions, cursor, gpu, claudeAuth] = await Promise.all([
46503
46731
  Promise.all(AGENT_ADAPTERS.map((a) => probeVersion(a.binary))),
46504
46732
  probeVersion("cursor"),
46505
- detectGpu()
46733
+ detectGpu(),
46734
+ claudeAuthStatusAsync()
46506
46735
  ]);
46507
46736
  const agents = {};
46508
46737
  AGENT_ADAPTERS.forEach((a, i) => {
@@ -46522,7 +46751,8 @@ async function collectDiagnostics() {
46522
46751
  disk: diskUsage(),
46523
46752
  gpu,
46524
46753
  agents: Object.keys(agents).length ? agents : void 0,
46525
- projects_local: localProjectCount()
46754
+ projects_local: localProjectCount(),
46755
+ claude_auth: claudeAuth ? { logged_in: claudeAuth.loggedIn, method: claudeAuth.authMethod, subscription: claudeAuth.subscriptionType } : void 0
46526
46756
  };
46527
46757
  }
46528
46758
  function safe(fn) {
@@ -46533,6 +46763,9 @@ function safe(fn) {
46533
46763
  }
46534
46764
  }
46535
46765
 
46766
+ // src/relay/daemon.ts
46767
+ init_claude_setup();
46768
+
46536
46769
  // src/relay/agent-updates.ts
46537
46770
  init_agents();
46538
46771
  init_platform();
@@ -46966,7 +47199,15 @@ function mapPlatform2(p) {
46966
47199
  }
46967
47200
  async function registerDevice() {
46968
47201
  const name = (hostname6() || "my-pc").trim().slice(0, 100) || "my-pc";
46969
- const res = await post("/remote-devices", { name, platform: mapPlatform2(osPlatform3()), machine_id: getMachineId() });
47202
+ const deviceKind = process.env.GIPITY_DEVICE_KIND;
47203
+ const agentKind = process.env.GIPITY_AGENT_KIND;
47204
+ const res = await post("/remote-devices", {
47205
+ name,
47206
+ platform: mapPlatform2(osPlatform3()),
47207
+ machine_id: getMachineId(),
47208
+ ...deviceKind ? { device_kind: deviceKind } : {},
47209
+ ...agentKind ? { agent_kind: agentKind } : {}
47210
+ });
46970
47211
  const device = {
46971
47212
  guid: res.data.short_guid,
46972
47213
  name: res.data.name,
@@ -47699,7 +47940,9 @@ async function handleDispatch(claimed) {
47699
47940
  }
47700
47941
  }
47701
47942
  const stderrNote = stderrTail ? `: ${stderrTail.slice(0, 300)}` : "";
47702
- const tail2 = runtimeLimit ? `stopped after ${dur} (runtime limit)` : killed ? `cancelled (${dur})` : spawnErr ? `failed (${dur}: ${spawnErr})` : exitCode === 0 ? `finished (${dur})` : `failed (${dur}, exit ${exitCode}${stderrNote})`;
47943
+ const authHint = exitCode !== 0 && !killed && !runtimeLimit && !spawnErr ? claudeAuthFailureHint(await claudeAuthStatusAsync(), stderrTail, getDevice()?.name) : null;
47944
+ const authNote = authHint ? ` \xB7 ${authHint}` : "";
47945
+ 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}`;
47703
47946
  pushSystem(`Claude Code ${tail2}`);
47704
47947
  await flushQueue();
47705
47948
  const metrics = startupMs !== void 0 ? { startup_ms: startupMs } : void 0;
@@ -47715,10 +47958,16 @@ async function handleDispatch(claimed) {
47715
47958
  log2("info", "dispatch done", { id: d.short_guid, ms: ms2, startupMs });
47716
47959
  await ack(d.short_guid, "done", void 0, metrics);
47717
47960
  } else {
47718
- log2("warn", "dispatch child exited nonzero", { id: d.short_guid, exitCode, ms: ms2 });
47719
- await ack(d.short_guid, "error", `Claude Code exited with code ${exitCode}${stderrNote}`);
47961
+ log2("warn", "dispatch child exited nonzero", { id: d.short_guid, exitCode, ms: ms2, authHint: !!authHint });
47962
+ await ack(d.short_guid, "error", `Claude Code exited with code ${exitCode}${stderrNote}${authNote}`);
47720
47963
  }
47721
47964
  }
47965
+ 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;
47966
+ function claudeAuthFailureHint(status, stderrTail, deviceName) {
47967
+ if (status?.loggedIn === false) return claudeLoginHint(deviceName);
47968
+ if (status === null && CLAUDE_AUTH_ERROR_RE.test(stderrTail)) return claudeLoginHint(deviceName);
47969
+ return null;
47970
+ }
47722
47971
  async function handleNonClaudeDispatch(adapter, d, cwd, queue, pushSystem, flushQueue) {
47723
47972
  const args = ["build", "--agent", adapter.key, "-p", d.message, "--bypass-approvals"];
47724
47973
  if (d.model) args.push("--model", d.model);