@sideboard-ai/core 0.1.345 → 0.1.347

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.
Files changed (67) hide show
  1. package/dist/{abletime-MSIMJKKQ.js → abletime-3HRWLQZJ.js} +4 -4
  2. package/dist/{abletime-X2TJ6PPK.js → abletime-CGFJZB7L.js} +4 -4
  3. package/dist/{abletime-oauth-DEIENLHC.js → abletime-oauth-JQDSH5OL.js} +3 -3
  4. package/dist/{abletime-oauth-2RUKRZYZ.js → abletime-oauth-QNJQLHR4.js} +3 -3
  5. package/dist/{abletime-rest-UBLSGMSA.js → abletime-rest-TANL5TMY.js} +3 -3
  6. package/dist/{abletime-rest-HWBUPI4R.js → abletime-rest-UQA2CRZN.js} +3 -3
  7. package/dist/{agents-AQM7NLXD.js → agents-5MFGVK7C.js} +7 -7
  8. package/dist/{agents-7CHZO3K3.js → agents-T4XBZZDA.js} +7 -7
  9. package/dist/{app-settings-Q2F57NVK.js → app-settings-PPIMYJKS.js} +3 -1
  10. package/dist/{app-settings-A6JUT2SF.js → app-settings-SNOPJ7P5.js} +3 -1
  11. package/dist/{chunk-5IMXA563.js → chunk-27XWAI7S.js} +22 -22
  12. package/dist/{chunk-RTZO2YJC.js → chunk-2HPVGTHF.js} +2 -2
  13. package/dist/{chunk-GHKJBZW5.js → chunk-4NXGVJA6.js} +2 -2
  14. package/dist/{chunk-O5WRVQFT.js → chunk-5FUAOU3G.js} +1 -1
  15. package/dist/{chunk-3J3XOIHF.js → chunk-62ALWH3T.js} +3 -3
  16. package/dist/{chunk-J3BQHHDZ.js → chunk-6TV6L2DD.js} +4 -4
  17. package/dist/{chunk-4PHOJMZI.js → chunk-6WMNIX2U.js} +35 -2
  18. package/dist/{chunk-4PXHJA5K.js → chunk-7B2OUQON.js} +2 -2
  19. package/dist/{chunk-TD76ORBJ.js → chunk-AJMERXZP.js} +2 -2
  20. package/dist/{chunk-QTDCPMOW.js → chunk-ATS7SYHG.js} +1 -1
  21. package/dist/{chunk-AG2RM3DF.js → chunk-CEQ4Z32M.js} +3 -3
  22. package/dist/{chunk-5TS3KVGI.js → chunk-E77SRVVO.js} +1 -1
  23. package/dist/{chunk-5SJGR3VS.js → chunk-F7WP2U5I.js} +12 -9
  24. package/dist/{chunk-YFPSTG52.js → chunk-FDYMVJFU.js} +5 -5
  25. package/dist/{chunk-IYX53WZY.js → chunk-GAGTEI6B.js} +5 -5
  26. package/dist/{chunk-JZKNRDKF.js → chunk-IJNTTVFH.js} +23 -23
  27. package/dist/{chunk-MB3GOWB3.js → chunk-IVRWRYTH.js} +19 -10
  28. package/dist/{chunk-3DMRQB4Y.js → chunk-JCYGQKER.js} +1 -1
  29. package/dist/{chunk-JHT3CYLT.js → chunk-MOUAM6ZC.js} +1 -1
  30. package/dist/{chunk-Z54FI4VL.js → chunk-NTY5WGRD.js} +2 -2
  31. package/dist/{chunk-LHU6ZBFB.js → chunk-OHUAAX3O.js} +2 -2
  32. package/dist/{chunk-NQHEEGTH.js → chunk-PVCECFJK.js} +1 -1
  33. package/dist/{chunk-MHRU743Z.js → chunk-Q4TZA4MN.js} +2247 -2155
  34. package/dist/{chunk-4SNEW63T.js → chunk-RUIHNWRV.js} +3 -3
  35. package/dist/{chunk-NDBMDHQ5.js → chunk-RYPD7XWV.js} +5 -5
  36. package/dist/{chunk-FNAP6CCS.js → chunk-UJMCTGV7.js} +2 -2
  37. package/dist/{chunk-S3UGLMGE.js → chunk-WWU4SYZR.js} +35 -2
  38. package/dist/{chunk-4YGVJRXY.js → chunk-XNGW4OYD.js} +4 -4
  39. package/dist/{chunk-TW63CYUA.js → chunk-Y6VQX2LY.js} +2679 -2587
  40. package/dist/{chunk-BD7KUYJA.js → chunk-ZJMYCDYQ.js} +5 -5
  41. package/dist/{conductor-DUHRZUQY.js → conductor-EMGMDNHL.js} +5 -5
  42. package/dist/{conductor-3A2TNWUW.js → conductor-LYQKONSA.js} +5 -5
  43. package/dist/{coordinator-prompt-OX6A4MDA.js → coordinator-prompt-DLY3FS2L.js} +4 -4
  44. package/dist/{coordinator-prompt-7QALNDIV.js → coordinator-prompt-WALVMGKI.js} +4 -4
  45. package/dist/{global-workspace-HM2RKBCT.js → global-workspace-7OQ5O6JT.js} +4 -4
  46. package/dist/{global-workspace-6GGS3DWU.js → global-workspace-UG2A3CEM.js} +4 -4
  47. package/dist/index.cjs +1090 -640
  48. package/dist/index.d.cts +62 -8
  49. package/dist/index.d.ts +62 -8
  50. package/dist/index.js +325 -32
  51. package/dist/{linear-WYI64BMX.js → linear-MIJO6DCV.js} +2 -2
  52. package/dist/{linear-JE4WAZ3W.js → linear-PKYJH4WK.js} +2 -2
  53. package/dist/{linear-list-I4NAOWPN.js → linear-list-JPQ27RXG.js} +1 -1
  54. package/dist/{linear-list-CGUCPWTV.js → linear-list-N57PR6JM.js} +1 -1
  55. package/dist/mcp/run-stdio.cjs +500 -224
  56. package/dist/mcp/run-stdio.js +106 -21
  57. package/dist/{optional-cli-7QXXPEN6.js → optional-cli-4GTEDEYJ.js} +3 -3
  58. package/dist/{optional-cli-YHLVTVRK.js → optional-cli-RPJIQBDX.js} +4 -4
  59. package/dist/{orchestrator-OWO6LQ5U.js → orchestrator-AJZNVREM.js} +10 -10
  60. package/dist/{orchestrator-POMFVZLB.js → orchestrator-BUEPWNCF.js} +10 -10
  61. package/dist/{thread-store-HETUMDVA.js → thread-store-MEUWZDVV.js} +2 -2
  62. package/dist/{thread-store-V5IDUJ4L.js → thread-store-R3G5VBII.js} +2 -2
  63. package/dist/{workspaces-DTMPNDPW.js → workspaces-35T6FW57.js} +4 -4
  64. package/dist/{workspaces-V6IIBSKA.js → workspaces-KWGTP7DI.js} +4 -4
  65. package/dist/{worktree-FX5FT6BI.js → worktree-5P7SCST3.js} +3 -3
  66. package/dist/{worktree-BD3EJE24.js → worktree-ROJXGBWS.js} +3 -3
  67. package/package.json +1 -1
@@ -4326,6 +4326,12 @@ function normalizeVault(raw) {
4326
4326
  if (typeof raw.posthogPersonalApiKey === "string" && raw.posthogPersonalApiKey.trim()) {
4327
4327
  out.posthogPersonalApiKey = raw.posthogPersonalApiKey.trim();
4328
4328
  }
4329
+ if (typeof raw.posthogAccessToken === "string" && raw.posthogAccessToken.trim()) {
4330
+ out.posthogAccessToken = raw.posthogAccessToken.trim();
4331
+ }
4332
+ if (typeof raw.posthogRefreshToken === "string" && raw.posthogRefreshToken.trim()) {
4333
+ out.posthogRefreshToken = raw.posthogRefreshToken.trim();
4334
+ }
4329
4335
  if (typeof raw.sentryAuthToken === "string" && raw.sentryAuthToken.trim()) {
4330
4336
  out.sentryAuthToken = raw.sentryAuthToken.trim();
4331
4337
  }
@@ -4968,6 +4974,7 @@ __export(app_settings_exports, {
4968
4974
  saveAbleTimeConnection: () => saveAbleTimeConnection,
4969
4975
  saveAppSettings: () => saveAppSettings,
4970
4976
  saveLinearOAuth: () => saveLinearOAuth,
4977
+ savePosthogOAuth: () => savePosthogOAuth,
4971
4978
  selectManagedAccount: () => selectManagedAccount,
4972
4979
  showCostEnabled: () => showCostEnabled,
4973
4980
  slackAppLevelToken: () => slackAppLevelToken,
@@ -5040,7 +5047,7 @@ function toPublicAppSettings(settings) {
5040
5047
  hasAbleTimeOAuth: Boolean(settings.integrations.abletimeRefreshToken?.trim()),
5041
5048
  hasVercelToken: Boolean(settings.integrations.vercelToken?.trim()),
5042
5049
  hasSupabaseToken: Boolean(settings.integrations.supabaseAccessToken?.trim()),
5043
- hasPosthogToken: Boolean(settings.integrations.posthogPersonalApiKey?.trim()),
5050
+ hasPosthogToken: hasPosthogCredentials(settings.integrations),
5044
5051
  hasSentryToken: Boolean(settings.integrations.sentryAuthToken?.trim()),
5045
5052
  hasRemoteAccount: Boolean(settings.integrations.remoteAccountToken?.trim())
5046
5053
  }
@@ -5236,6 +5243,12 @@ function normalizeIntegrations(raw) {
5236
5243
  const key = source.posthogPersonalApiKey.trim();
5237
5244
  if (key) out.posthogPersonalApiKey = key;
5238
5245
  }
5246
+ for (const key of ["posthogAccessToken", "posthogRefreshToken"]) {
5247
+ const token = typeof source[key] === "string" ? source[key].trim() : "";
5248
+ if (token) out[key] = token;
5249
+ }
5250
+ const posthogExp = Number(source.posthogTokenExpiresAt);
5251
+ if (Number.isFinite(posthogExp)) out.posthogTokenExpiresAt = posthogExp;
5239
5252
  if (typeof source.posthogHost === "string") {
5240
5253
  const host = source.posthogHost.trim();
5241
5254
  if (host) out.posthogHost = host;
@@ -6154,8 +6167,26 @@ function disconnectLinearConnection() {
6154
6167
  delete integrations.linearOrganizationName;
6155
6168
  return saveAppSettings({ ...current, integrations });
6156
6169
  }
6170
+ function hasPosthogCredentials(integrations) {
6171
+ return Boolean(
6172
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
6173
+ );
6174
+ }
6157
6175
  function isPosthogConnected(settings = loadAppSettings()) {
6158
- return Boolean(settings.integrations.posthogPersonalApiKey?.trim());
6176
+ return hasPosthogCredentials(settings.integrations);
6177
+ }
6178
+ function savePosthogOAuth(input) {
6179
+ const current = loadAppSettings();
6180
+ const integrations = { ...current.integrations };
6181
+ integrations.posthogAccessToken = input.accessToken.trim();
6182
+ if (input.refreshToken?.trim()) integrations.posthogRefreshToken = input.refreshToken.trim();
6183
+ if (typeof input.expiresIn === "number" && Number.isFinite(input.expiresIn)) {
6184
+ integrations.posthogTokenExpiresAt = Date.now() + Math.max(0, input.expiresIn) * 1e3;
6185
+ }
6186
+ if (input.host?.trim()) integrations.posthogHost = input.host.trim();
6187
+ if (input.viewerName?.trim()) integrations.posthogViewerName = input.viewerName.trim().slice(0, 120);
6188
+ delete integrations.posthogPersonalApiKey;
6189
+ return saveAppSettings({ ...current, integrations });
6159
6190
  }
6160
6191
  function isAbleTimeConnected(settings = loadAppSettings()) {
6161
6192
  return Boolean(
@@ -6606,6 +6637,8 @@ var init_app_settings = __esm({
6606
6637
  "vercelToken",
6607
6638
  "supabaseAccessToken",
6608
6639
  "posthogPersonalApiKey",
6640
+ "posthogAccessToken",
6641
+ "posthogRefreshToken",
6609
6642
  "sentryAuthToken"
6610
6643
  ];
6611
6644
  CLOUD_CONNECT_AGENTS = /* @__PURE__ */ new Set([
@@ -8702,14 +8735,14 @@ function fileMtimeMs(path) {
8702
8735
  }
8703
8736
  }
8704
8737
  function rememberThread(thread, mtimeMs) {
8705
- const cache = cacheForDir();
8706
- cache.byId.set(thread.id, thread);
8707
- if (mtimeMs != null) cache.mtimeMs.set(thread.id, mtimeMs);
8738
+ const cache2 = cacheForDir();
8739
+ cache2.byId.set(thread.id, thread);
8740
+ if (mtimeMs != null) cache2.mtimeMs.set(thread.id, mtimeMs);
8708
8741
  }
8709
8742
  function forgetThread(id) {
8710
- const cache = cacheForDir();
8711
- cache.byId.delete(id);
8712
- cache.mtimeMs.delete(id);
8743
+ const cache2 = cacheForDir();
8744
+ cache2.byId.delete(id);
8745
+ cache2.mtimeMs.delete(id);
8713
8746
  selfWriteMtimes.delete(id);
8714
8747
  }
8715
8748
  function invalidateThreadListCache() {
@@ -8726,9 +8759,9 @@ function readThread(id) {
8726
8759
  forgetThread(id);
8727
8760
  return null;
8728
8761
  }
8729
- const cache = cacheForDir();
8730
- const cached = cache.byId.get(id);
8731
- if (cached && cache.mtimeMs.get(id) === mtimeMs) return cached;
8762
+ const cache2 = cacheForDir();
8763
+ const cached = cache2.byId.get(id);
8764
+ if (cached && cache2.mtimeMs.get(id) === mtimeMs) return cached;
8732
8765
  const raw = (0, import_node_fs17.readFileSync)(path, "utf8");
8733
8766
  const thread = normalizeThread(JSON.parse(raw));
8734
8767
  rememberThread(thread, mtimeMs);
@@ -8757,7 +8790,7 @@ function isThreadRecordFile(nameOrPath) {
8757
8790
  return name.endsWith(".json") && !name.endsWith(".live.json") && !name.endsWith(".setup.log.json");
8758
8791
  }
8759
8792
  function listThreads(opts) {
8760
- const cache = cacheForDir();
8793
+ const cache2 = cacheForDir();
8761
8794
  const files = (0, import_node_fs17.readdirSync)(threadsDir()).filter(isThreadRecordFile);
8762
8795
  const seen = /* @__PURE__ */ new Set();
8763
8796
  for (const f of files) {
@@ -8769,10 +8802,10 @@ function listThreads(opts) {
8769
8802
  } catch {
8770
8803
  }
8771
8804
  }
8772
- for (const id of [...cache.byId.keys()]) {
8805
+ for (const id of [...cache2.byId.keys()]) {
8773
8806
  if (!seen.has(id)) forgetThread(id);
8774
8807
  }
8775
- const threads = [...cache.byId.values()].sort(
8808
+ const threads = [...cache2.byId.values()].sort(
8776
8809
  (a, b) => b.updatedAt.localeCompare(a.updatedAt)
8777
8810
  );
8778
8811
  if (opts?.includeArchived) return threads;
@@ -11221,7 +11254,7 @@ var init_coordinator_prompt = __esm({
11221
11254
  "- linear_* (when Linear is connected) \u2014 list_teams for team key/states; linear_list_projects for project names; get/search include the project a ticket is on; get/create/update/comment with ENG-123. Worktree agents have the same Account tools \u2014 prefer they comment, update status, and create spin-offs (parent=) on their own ticket when they were asked to do the work. When reviewing a PR or ticket, do not comment or update until the user types a next step \u2014 they should work through the feedback in chat first. Do not tell the child to ask_user after the review. Scope errors: reconnect Linear in Account settings. Prefer these over any Linear MCP the CLI may still list. Worktree agents use the Claude Linear connector only when Account Linear is not set or the Sideboard call fails, and they do not mention that connector startup failure when Sideboard works.",
11222
11255
  "- github_* \u2014 get/comment/update/create GitHub issues via Account `gh` (#123). github_list_projects and get/search include GitHub Projects. projectsError or a missing read:project scope \u2192 `gh auth refresh -s read:project`. Worktree agents have these too. Prefer Sideboard `github_*` while Account `gh` works. A failed Claude GitHub connector (`mcp_github_github`) is not a Sideboard outage \u2014 do not mention it. Use that connector only when `gh` is not set up or the Sideboard call fails. Pass parent= for spin-offs. When reviewing a PR or ticket, do not comment, submit `gh pr review`, or update the PR/ticket until the user types a next step.",
11223
11256
  "- abletime_* (when AbleTime is connected) \u2014 orientation first; abletime_list_projects lists projects; get/list include the project a task is on; get/comment/update/create (parent= for spin-offs); ensure_task when work has no ticket (or create_workspace from the default branch auto-creates one). Worktree agents have the same Account tools. Same review-write gate as Linear/GitHub.",
11224
- "- Optional connectors (Vercel, Supabase, Sentry) in Settings \u2192 Connectors inject tokens into worktree agent env when connected. Prefer official CLIs (`vercel`, `supabase`, `sentry-cli`). When Settings \u2192 Connectors has a PostHog personal API key, PostHog is the Sideboard tool `posthog_api` (GET by default; POST `/api/projects/:id/query/` or `/api/environments/:id/query/` is a read and does not need write=true; other POST and PATCH need write=true only when the user asked to change data). The PostHog key stays in the vault \u2014 do not read it from the environment, and do not sign in to a PostHog MCP. When no PostHog API key is set, use the Claude PostHog connector. When a key is set, ignore a failed Claude PostHog connector and do not sign in to a PostHog MCP. If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized while that Sideboard token is set, do not sign in \u2014 use the native CLI. When that token is not set or the CLI call fails, the Claude connector is the fallback. Do not mention a Claude connector startup failure when the Sideboard connection works. Tell any worktree agent (Claude / Cursor / Codex / OpenCode) to write CLI output to `.context/cli/` and read a slice. If a CLI is missing, the user presses Install CLI on that row. Do not add vendor MCPs. Git (`gh`) stays Settings \u2192 Git; issue tracking stays Settings \u2192 Issues. The phone remote is Settings \u2192 Remote \u2014 do not look up Slack users.",
11257
+ "- Optional connectors (Vercel, Supabase, Sentry) in Settings \u2192 Connectors inject tokens into worktree agent env when connected. Prefer official CLIs (`vercel`, `supabase`, `sentry-cli`). When Settings \u2192 Connectors is signed in to PostHog, PostHog is the Sideboard tool `posthog_api` (GET by default; POST `/api/projects/:id/query/` or `/api/environments/:id/query/` is a read and does not need write=true; other POST and PATCH need write=true only when the user asked to change data). The PostHog token stays in the vault \u2014 do not read it from the environment, and do not sign in to a PostHog MCP. When PostHog is not signed in, Claude worktree turns load the signed-in PostHog connector as server claude.ai PostHog (tools mcp__claude_ai_PostHog__*) inside --mcp-config. --strict-mcp-config does not load claude.ai connectors, and --allowedTools only skips prompts. Cursor, Codex, and OpenCode do not have those tools. When PostHog is signed in, ignore a failed Claude PostHog connector and do not sign in to a PostHog MCP. If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized while that Sideboard token is set, do not sign in \u2014 use the native CLI. When that token is not set or the CLI call fails, the Claude connector is the fallback. Do not mention a Claude connector startup failure when the Sideboard connection works. Tell any worktree agent (Claude / Cursor / Codex / OpenCode) to write CLI output to `.context/cli/` and read a slice. If a CLI is missing, the user presses Install CLI on that row. Do not add vendor MCPs. Git (`gh`) stays Settings \u2192 Git; issue tracking stays Settings \u2192 Issues. The phone remote is Settings \u2192 Remote \u2014 do not look up Slack users.",
11225
11258
  "- get_pr_stack / open_pr_stack_layers / add_stack_layer / create_pr_stack \u2014 GitHub stacked PRs (`gh stack`); one worktree per layer",
11226
11259
  "- list_models \u2014 only when you need a specific model (rare); otherwise omit model so Account defaults apply",
11227
11260
  "- list_chats / get_chat \u2014 live thread list (parent id + last message preview). get_chat on this orchestration chat lists child worktree agents (status + lastText). blockedReason is why that agent is waiting on a person. Also includes usage / lastTurnUsage. Archived workspaces and agents are list_archive, not this list.",
@@ -14403,6 +14436,173 @@ ${JSON.stringify(launch)}`;
14403
14436
  }
14404
14437
  });
14405
14438
 
14439
+ // src/agents/claude-usage.ts
14440
+ var init_claude_usage = __esm({
14441
+ "src/agents/claude-usage.ts"() {
14442
+ "use strict";
14443
+ }
14444
+ });
14445
+
14446
+ // src/agents/claude-usage-client.ts
14447
+ function accessTokenFromCredentialsJson(raw) {
14448
+ const trimmed = raw.trim();
14449
+ if (!trimmed) return null;
14450
+ if (trimmed.startsWith("sk-ant-")) {
14451
+ const token = trimmed.split(/\s+/)[0];
14452
+ return token || null;
14453
+ }
14454
+ try {
14455
+ const parsed = JSON.parse(trimmed);
14456
+ const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
14457
+ const token = oauth.accessToken ?? oauth.access_token;
14458
+ return typeof token === "string" && token.trim() ? token.trim() : null;
14459
+ } catch {
14460
+ return null;
14461
+ }
14462
+ }
14463
+ function claudeCredentialsPath(configDir) {
14464
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || (0, import_node_path36.join)((0, import_node_os16.homedir)(), ".claude");
14465
+ return (0, import_node_path36.join)(root, ".credentials.json");
14466
+ }
14467
+ async function readFileAccessToken(configDir) {
14468
+ const path = claudeCredentialsPath(configDir);
14469
+ if (!(0, import_node_fs34.existsSync)(path)) return null;
14470
+ try {
14471
+ return accessTokenFromCredentialsJson((0, import_node_fs34.readFileSync)(path, "utf8"));
14472
+ } catch {
14473
+ return null;
14474
+ }
14475
+ }
14476
+ async function readKeychainAccessToken(configDir) {
14477
+ if (process.platform !== "darwin") return null;
14478
+ const root = configDir?.trim();
14479
+ const accounts = root ? [root, void 0] : [void 0];
14480
+ for (const service of KEYCHAIN_SERVICES) {
14481
+ for (const account of accounts) {
14482
+ const args = ["find-generic-password", "-s", service, "-w"];
14483
+ if (account) args.splice(3, 0, "-a", account);
14484
+ const result = await run("security", args, {
14485
+ reject: false,
14486
+ timeoutMs: 4e3
14487
+ });
14488
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
14489
+ const token = accessTokenFromCredentialsJson(result.stdout);
14490
+ if (token) return token;
14491
+ }
14492
+ }
14493
+ return null;
14494
+ }
14495
+ async function readClaudeAccessToken(configDir) {
14496
+ const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
14497
+ if (envToken) return envToken;
14498
+ const fromFile = await readFileAccessToken(configDir);
14499
+ if (fromFile) return fromFile;
14500
+ return readKeychainAccessToken(configDir);
14501
+ }
14502
+ var import_node_fs34, import_node_os16, import_node_path36, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS, KEYCHAIN_SERVICES;
14503
+ var init_claude_usage_client = __esm({
14504
+ "src/agents/claude-usage-client.ts"() {
14505
+ "use strict";
14506
+ import_node_fs34 = require("fs");
14507
+ import_node_os16 = require("os");
14508
+ import_node_path36 = require("path");
14509
+ init_run();
14510
+ init_fetch();
14511
+ init_app_settings();
14512
+ init_claude_usage();
14513
+ CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
14514
+ CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
14515
+ KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
14516
+ }
14517
+ });
14518
+
14519
+ // src/agents/claude-posthog-connector.ts
14520
+ function asRecord5(value) {
14521
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
14522
+ return value;
14523
+ }
14524
+ function rowsFrom(body) {
14525
+ if (Array.isArray(body)) {
14526
+ return body.filter((row) => asRecord5(row) !== null);
14527
+ }
14528
+ const record = asRecord5(body);
14529
+ const data = record?.data;
14530
+ if (!Array.isArray(data)) return [];
14531
+ return data.filter((row) => asRecord5(row) !== null);
14532
+ }
14533
+ function isPosthogName(value) {
14534
+ if (typeof value !== "string") return false;
14535
+ const head = value.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
14536
+ return head === "posthog";
14537
+ }
14538
+ function rowId(row) {
14539
+ const id = row.id;
14540
+ return typeof id === "string" && ID_RE.test(id) ? id : null;
14541
+ }
14542
+ function posthogConnectorFromList(body) {
14543
+ const matches = rowsFrom(body).filter(
14544
+ (row2) => row2.eligible !== false && rowId(row2) !== null && (isPosthogName(row2.display_name) || isPosthogName(row2.displayName) || isPosthogName(row2.name))
14545
+ );
14546
+ const row = matches.find((item) => item.additional_install !== true && item.additionalInstall !== true) ?? matches[0];
14547
+ const id = row ? rowId(row) : null;
14548
+ if (!id) return null;
14549
+ return {
14550
+ type: "claudeai-proxy",
14551
+ id,
14552
+ url: `${PROXY_ORIGIN}/v1/mcp/${id}`,
14553
+ displayName: "PostHog",
14554
+ alwaysLoad: true
14555
+ };
14556
+ }
14557
+ async function loadClaudePosthogConnector(now = Date.now()) {
14558
+ if (cache && now - cache.at < (cache.value ? SUCCESS_TTL_MS : MISS_TTL_MS)) return cache.value;
14559
+ const token = await readClaudeAccessToken();
14560
+ if (!token) {
14561
+ cache = { at: now, value: null };
14562
+ return null;
14563
+ }
14564
+ try {
14565
+ const res = await httpFetch(LIST_URL, {
14566
+ headers: {
14567
+ Authorization: `Bearer ${token}`,
14568
+ "anthropic-version": "2023-06-01",
14569
+ "anthropic-beta": "mcp-servers-2025-12-04"
14570
+ },
14571
+ signal: AbortSignal.timeout(4e3)
14572
+ });
14573
+ if (!res.ok) {
14574
+ cache = { at: now, value: null };
14575
+ return null;
14576
+ }
14577
+ const value = posthogConnectorFromList(await res.json());
14578
+ cache = { at: now, value };
14579
+ return value;
14580
+ } catch {
14581
+ cache = { at: now, value: null };
14582
+ return null;
14583
+ }
14584
+ }
14585
+ async function claudePosthogConnectorForTurn() {
14586
+ if (turnOverride) return turnOverride();
14587
+ if (process.env.VITEST) return null;
14588
+ return loadClaudePosthogConnector();
14589
+ }
14590
+ var CLAUDE_POSTHOG_CONNECTOR_SERVER, LIST_URL, PROXY_ORIGIN, ID_RE, SUCCESS_TTL_MS, MISS_TTL_MS, cache, turnOverride;
14591
+ var init_claude_posthog_connector = __esm({
14592
+ "src/agents/claude-posthog-connector.ts"() {
14593
+ "use strict";
14594
+ init_fetch();
14595
+ init_claude_usage_client();
14596
+ CLAUDE_POSTHOG_CONNECTOR_SERVER = "claude.ai PostHog";
14597
+ LIST_URL = "https://api.anthropic.com/v1/mcp_servers?limit=1000&include_additional_installs=true";
14598
+ PROXY_ORIGIN = "https://mcp-proxy.anthropic.com";
14599
+ ID_RE = /^[A-Za-z0-9_-]+$/;
14600
+ SUCCESS_TTL_MS = 5 * 6e4;
14601
+ MISS_TTL_MS = 3e4;
14602
+ cache = null;
14603
+ }
14604
+ });
14605
+
14406
14606
  // src/agents/types.ts
14407
14607
  function planModeTurnInstruction(planMode) {
14408
14608
  return planMode ? PLAN_MODE_INSTRUCTION : PLAN_MODE_OFF_INSTRUCTION;
@@ -14455,11 +14655,11 @@ var init_types = __esm({
14455
14655
 
14456
14656
  // src/agent-rpc/metadata.ts
14457
14657
  function agentRuntimeMetadataPath() {
14458
- return (0, import_node_path36.join)(appDataDir(), "agent-runtime.json");
14658
+ return (0, import_node_path37.join)(appDataDir(), "agent-runtime.json");
14459
14659
  }
14460
14660
  function readAgentRuntimeMetadata() {
14461
14661
  try {
14462
- const raw = JSON.parse((0, import_node_fs34.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
14662
+ const raw = JSON.parse((0, import_node_fs35.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
14463
14663
  if (!raw || typeof raw !== "object") return null;
14464
14664
  const rec = raw;
14465
14665
  if (typeof rec.runtimeId !== "string" || !rec.runtimeId.trim()) return null;
@@ -14507,12 +14707,12 @@ function agentRuntimeLooksLive(meta = readAgentRuntimeMetadata()) {
14507
14707
  if (!meta) return false;
14508
14708
  return pidAlive(meta.pid);
14509
14709
  }
14510
- var import_node_fs34, import_node_path36;
14710
+ var import_node_fs35, import_node_path37;
14511
14711
  var init_metadata = __esm({
14512
14712
  "src/agent-rpc/metadata.ts"() {
14513
14713
  "use strict";
14514
- import_node_fs34 = require("fs");
14515
- import_node_path36 = require("path");
14714
+ import_node_fs35 = require("fs");
14715
+ import_node_path37 = require("path");
14516
14716
  init_paths();
14517
14717
  init_protocol2();
14518
14718
  }
@@ -14582,11 +14782,11 @@ function entryDir() {
14582
14782
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
14583
14783
  if (cjsDir) return cjsDir;
14584
14784
  try {
14585
- return (0, import_node_path37.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
14785
+ return (0, import_node_path38.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
14586
14786
  } catch {
14587
14787
  try {
14588
14788
  const req = (0, import_node_module2.createRequire)(process.cwd() + "/");
14589
- return (0, import_node_path37.dirname)(req.resolve("@sideboard-ai/core"));
14789
+ return (0, import_node_path38.dirname)(req.resolve("@sideboard-ai/core"));
14590
14790
  } catch {
14591
14791
  return process.cwd();
14592
14792
  }
@@ -14595,20 +14795,20 @@ function entryDir() {
14595
14795
  function claudeRunnerPath() {
14596
14796
  const packagedDir = packagedCursorRuntimeDir();
14597
14797
  if (packagedDir) {
14598
- const packaged = (0, import_node_path37.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
14599
- if ((0, import_node_fs35.existsSync)(packaged)) return packaged;
14798
+ const packaged = (0, import_node_path38.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
14799
+ if ((0, import_node_fs36.existsSync)(packaged)) return packaged;
14600
14800
  }
14601
14801
  const root = entryDir();
14602
14802
  const candidates = [
14603
- (0, import_node_path37.join)(root, "agents", "claude-runner.js"),
14604
- (0, import_node_path37.join)(root, "agents", "claude-runner.cjs"),
14605
- (0, import_node_path37.join)(root, "dist", "agents", "claude-runner.js"),
14606
- (0, import_node_path37.join)(root, "dist", "agents", "claude-runner.cjs"),
14607
- (0, import_node_path37.join)(root, "claude-runner.ts"),
14608
- (0, import_node_path37.join)(root, "src", "agents", "claude-runner.ts")
14803
+ (0, import_node_path38.join)(root, "agents", "claude-runner.js"),
14804
+ (0, import_node_path38.join)(root, "agents", "claude-runner.cjs"),
14805
+ (0, import_node_path38.join)(root, "dist", "agents", "claude-runner.js"),
14806
+ (0, import_node_path38.join)(root, "dist", "agents", "claude-runner.cjs"),
14807
+ (0, import_node_path38.join)(root, "claude-runner.ts"),
14808
+ (0, import_node_path38.join)(root, "src", "agents", "claude-runner.ts")
14609
14809
  ];
14610
14810
  for (const candidate of candidates) {
14611
- if ((0, import_node_fs35.existsSync)(candidate)) return candidate;
14811
+ if ((0, import_node_fs36.existsSync)(candidate)) return candidate;
14612
14812
  }
14613
14813
  return candidates[0];
14614
14814
  }
@@ -14632,13 +14832,13 @@ async function buildClaudeRpcTurnCommand(req) {
14632
14832
  }
14633
14833
  };
14634
14834
  }
14635
- var import_node_fs35, import_node_module2, import_node_path37, import_node_url2, import_meta5;
14835
+ var import_node_fs36, import_node_module2, import_node_path38, import_node_url2, import_meta5;
14636
14836
  var init_claude_host = __esm({
14637
14837
  "src/agents/claude-host.ts"() {
14638
14838
  "use strict";
14639
- import_node_fs35 = require("fs");
14839
+ import_node_fs36 = require("fs");
14640
14840
  import_node_module2 = require("module");
14641
- import_node_path37 = require("path");
14841
+ import_node_path38 = require("path");
14642
14842
  import_node_url2 = require("url");
14643
14843
  init_protocol2();
14644
14844
  init_pilot_tools();
@@ -14730,11 +14930,11 @@ function issueAttachmentWorktreePath(repoPath) {
14730
14930
  return raw || process.cwd();
14731
14931
  }
14732
14932
  function ensureIssueAttachmentsDir(worktreePath) {
14733
- const dir = (0, import_node_path38.join)(worktreePath, ATTACHMENTS_DIR);
14734
- (0, import_node_fs36.mkdirSync)(dir, { recursive: true });
14735
- const gi = (0, import_node_path38.join)(dir, ".gitignore");
14736
- if (!(0, import_node_fs36.existsSync)(gi)) {
14737
- (0, import_node_fs36.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
14933
+ const dir = (0, import_node_path39.join)(worktreePath, ATTACHMENTS_DIR);
14934
+ (0, import_node_fs37.mkdirSync)(dir, { recursive: true });
14935
+ const gi = (0, import_node_path39.join)(dir, ".gitignore");
14936
+ if (!(0, import_node_fs37.existsSync)(gi)) {
14937
+ (0, import_node_fs37.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
14738
14938
  }
14739
14939
  return dir;
14740
14940
  }
@@ -14764,7 +14964,7 @@ function looksLikeFileUrl(url) {
14764
14964
  function filenameFromUrl(url, fallback = "attachment") {
14765
14965
  try {
14766
14966
  const parsed = new URL(url);
14767
- const last = decodeURIComponent((0, import_node_path38.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
14967
+ const last = decodeURIComponent((0, import_node_path39.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
14768
14968
  if (last && last !== "/" && last !== ".") return last;
14769
14969
  } catch {
14770
14970
  }
@@ -14786,12 +14986,12 @@ function filenameFromContentDisposition(header) {
14786
14986
  }
14787
14987
  function uniqueAttachmentFileName(dir, originalName) {
14788
14988
  const safe = originalName.replace(/[/\\]/g, "_").replace(/^\.+/, "") || "file";
14789
- if (!(0, import_node_fs36.existsSync)((0, import_node_path38.join)(dir, safe))) return safe;
14790
- const ext = (0, import_node_path38.extname)(safe);
14989
+ if (!(0, import_node_fs37.existsSync)((0, import_node_path39.join)(dir, safe))) return safe;
14990
+ const ext = (0, import_node_path39.extname)(safe);
14791
14991
  const stem = ext ? safe.slice(0, -ext.length) : safe;
14792
14992
  for (let i = 1; i < 1e4; i++) {
14793
14993
  const candidate = `${stem}-${i}${ext}`;
14794
- if (!(0, import_node_fs36.existsSync)((0, import_node_path38.join)(dir, candidate))) return candidate;
14994
+ if (!(0, import_node_fs37.existsSync)((0, import_node_path39.join)(dir, candidate))) return candidate;
14795
14995
  }
14796
14996
  return `${stem}-${(0, import_node_crypto9.randomUUID)()}${ext}`;
14797
14997
  }
@@ -14839,7 +15039,7 @@ function mergeIssueAttachments(items) {
14839
15039
  return out;
14840
15040
  }
14841
15041
  function extensionForContentType(contentType, name) {
14842
- if ((0, import_node_path38.extname)(name)) return name;
15042
+ if ((0, import_node_path39.extname)(name)) return name;
14843
15043
  const mime = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
14844
15044
  const ext = EXT_BY_MIME[mime];
14845
15045
  return ext ? `${name}${ext}` : name;
@@ -14891,7 +15091,7 @@ async function downloadAuthenticatedFile(opts) {
14891
15091
  const dir = ensureIssueAttachmentsDir(opts.worktreePath);
14892
15092
  const hinted = opts.name?.trim() || filenameFromContentDisposition(res.headers.get("content-disposition")) || filenameFromUrl(url);
14893
15093
  const name = uniqueAttachmentFileName(dir, extensionForContentType(contentType, hinted));
14894
- (0, import_node_fs36.writeFileSync)((0, import_node_path38.join)(dir, name), buf);
15094
+ (0, import_node_fs37.writeFileSync)((0, import_node_path39.join)(dir, name), buf);
14895
15095
  return {
14896
15096
  name,
14897
15097
  path: `${ATTACHMENTS_DIR}/${name}`,
@@ -14899,12 +15099,12 @@ async function downloadAuthenticatedFile(opts) {
14899
15099
  ...contentType ? { contentType } : {}
14900
15100
  };
14901
15101
  }
14902
- var import_node_fs36, import_node_path38, import_node_crypto9, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
15102
+ var import_node_fs37, import_node_path39, import_node_crypto9, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
14903
15103
  var init_issue_attachments = __esm({
14904
15104
  "src/integrations/issue-attachments.ts"() {
14905
15105
  "use strict";
14906
- import_node_fs36 = require("fs");
14907
- import_node_path38 = require("path");
15106
+ import_node_fs37 = require("fs");
15107
+ import_node_path39 = require("path");
14908
15108
  import_node_crypto9 = require("crypto");
14909
15109
  init_fetch();
14910
15110
  init_workspace_scratch();
@@ -16557,17 +16757,18 @@ function compactMetadataFromClaude(obj) {
16557
16757
  const postTokens = typeof post === "number" && Number.isFinite(post) && post > 0 ? Math.round(post) : void 0;
16558
16758
  return { trigger, postTokens };
16559
16759
  }
16560
- var import_node_fs37, import_node_path39, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
16760
+ var import_node_fs38, import_node_path40, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
16561
16761
  var init_claude = __esm({
16562
16762
  "src/agents/claude.ts"() {
16563
16763
  "use strict";
16564
- import_node_fs37 = require("fs");
16565
- import_node_path39 = require("path");
16764
+ import_node_fs38 = require("fs");
16765
+ import_node_path40 = require("path");
16566
16766
  init_run();
16567
16767
  init_app_settings();
16568
16768
  init_claude_mcp_status();
16569
16769
  init_claude_mcp();
16570
16770
  init_host();
16771
+ init_claude_posthog_connector();
16571
16772
  init_error_detail();
16572
16773
  init_message_parts();
16573
16774
  init_injected_mcp();
@@ -16581,7 +16782,7 @@ var init_claude = __esm({
16581
16782
  async detect() {
16582
16783
  const claude = resolveClaudeExecutable();
16583
16784
  if (claude !== "claude") {
16584
- if (!(0, import_node_fs37.existsSync)(claude)) {
16785
+ if (!(0, import_node_fs38.existsSync)(claude)) {
16585
16786
  return {
16586
16787
  agent: "claude",
16587
16788
  installed: false,
@@ -16622,7 +16823,7 @@ var init_claude = __esm({
16622
16823
  const claude = resolveClaudeExecutable();
16623
16824
  const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
16624
16825
  const effective = dropCachedPrefixOnResume(input, sessionId);
16625
- const { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
16826
+ let { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
16626
16827
  const useStdin = promptText.length > CLAUDE_PROMPT_ARG_MAX;
16627
16828
  if (process.env.SIDEBOARD_DEBUG_CLAUDE_TURN === "1") {
16628
16829
  console.error(
@@ -16645,6 +16846,15 @@ var init_claude = __esm({
16645
16846
  const injectedBrightsyNames = injectedServers.filter((s) => s.name === "brightsy" || s.name.startsWith("brightsy_")).map((s) => s.name);
16646
16847
  const chromeOn = claudeChromeEnabled();
16647
16848
  const userMcpEntries = await proxyClaudeUserMcp(isOrchestrator, [thread.repoPath, thread.worktreePath]);
16849
+ const posthogConnector = !isOrchestrator && !isPosthogConnected() ? await claudePosthogConnectorForTurn() : null;
16850
+ if (posthogConnector && !Object.prototype.hasOwnProperty.call(userMcpEntries, CLAUDE_POSTHOG_CONNECTOR_SERVER)) {
16851
+ userMcpEntries[CLAUDE_POSTHOG_CONNECTOR_SERVER] = { ...posthogConnector };
16852
+ const hint = "PostHog: Settings \u2192 Connectors is not signed in. This turn loads the claude.ai PostHog connector (`claude.ai PostHog`, tools `mcp__claude_ai_PostHog__*`). Use those tools. Do not say PostHog is unavailable.";
16853
+ systemPrompt = systemPrompt ? `${systemPrompt}
16854
+
16855
+ ${hint}` : hint;
16856
+ }
16857
+ const isolateClaudeAiMcp = isOrchestrator || isLocalDevAppDataDir() && !posthogConnector;
16648
16858
  let allowedTools;
16649
16859
  if (isOrchestrator) {
16650
16860
  allowedTools = [
@@ -16685,7 +16895,7 @@ var init_claude = __esm({
16685
16895
  mcpServers: mcpServersRecord(injectedServers, userMcpEntries),
16686
16896
  allowedTools: withClaudePilotRpcTools(allowedTools),
16687
16897
  agentRpc: rpc,
16688
- isolateClaudeAiMcp: isOrchestrator || isLocalDevAppDataDir()
16898
+ isolateClaudeAiMcp
16689
16899
  });
16690
16900
  }
16691
16901
  const args = [
@@ -16730,18 +16940,19 @@ var init_claude = __esm({
16730
16940
  cwd: thread.worktreePath,
16731
16941
  stdin: useStdin ? `${promptText}
16732
16942
  ` : void 0,
16733
- ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path39.dirname)(mcpConfigPath)] } : {},
16943
+ ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path40.dirname)(mcpConfigPath)] } : {},
16734
16944
  // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
16735
16945
  // Raise the -p background-agent wait so long TaskOutput polls are not
16736
16946
  // abandoned at Claude Code’s 10-minute default.
16737
16947
  env: {
16738
16948
  CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
16739
16949
  CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? String(CLAUDE_PRINT_BG_WAIT_CEILING_MS),
16740
- // `--strict-mcp-config` still fetches claude.ai connectors on some CLI
16741
- // builds (anthropics/claude-code#60252). Coordinators never need them.
16742
- // Local `pnpm dev` also disables them: those HTTP connectors hang the
16743
- // first worktree turn when Electron's cwd is this Sideboard repo.
16744
- ...isOrchestrator || isLocalDevAppDataDir() ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
16950
+ // Current Claude Code does not fetch claude.ai connectors under
16951
+ // `--strict-mcp-config`. The env is the off switch for older builds
16952
+ // that still fetched the whole account list, and it also refuses an
16953
+ // explicit claudeai-proxy. Orchestrators always set it. Local dev sets
16954
+ // it only when this turn is not passing the PostHog connector.
16955
+ ...isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
16745
16956
  }
16746
16957
  };
16747
16958
  },
@@ -16909,7 +17120,7 @@ async function listCodexModels() {
16909
17120
  if (codex === "codex") {
16910
17121
  const which = await run("which", ["codex"], { reject: false });
16911
17122
  if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
16912
- } else if (!(0, import_node_fs38.existsSync)(codex)) {
17123
+ } else if (!(0, import_node_fs39.existsSync)(codex)) {
16913
17124
  return FALLBACK_CODEX_MODELS;
16914
17125
  }
16915
17126
  const listed = await run(codex, ["debug", "models"], { reject: false });
@@ -16946,7 +17157,7 @@ function usageFromCodex(usage, asContext = false) {
16946
17157
  return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
16947
17158
  }
16948
17159
  function codexHomeDir() {
16949
- return process.env.CODEX_HOME?.trim() || (0, import_node_path40.join)((0, import_node_os16.homedir)(), ".codex");
17160
+ return process.env.CODEX_HOME?.trim() || (0, import_node_path41.join)((0, import_node_os17.homedir)(), ".codex");
16950
17161
  }
16951
17162
  function unwrapCodexMcpResult(result) {
16952
17163
  if (result == null) return void 0;
@@ -16968,28 +17179,28 @@ function unwrapCodexMcpResult(result) {
16968
17179
  return String(result);
16969
17180
  }
16970
17181
  }
16971
- function asRecord5(value) {
17182
+ function asRecord6(value) {
16972
17183
  if (value && typeof value === "object" && !Array.isArray(value)) {
16973
17184
  return value;
16974
17185
  }
16975
17186
  return void 0;
16976
17187
  }
16977
17188
  function codexLooksAuthenticated() {
16978
- const authPath = (0, import_node_path40.join)(codexHomeDir(), "auth.json");
16979
- if (!(0, import_node_fs38.existsSync)(authPath)) return false;
17189
+ const authPath = (0, import_node_path41.join)(codexHomeDir(), "auth.json");
17190
+ if (!(0, import_node_fs39.existsSync)(authPath)) return false;
16980
17191
  try {
16981
- return (0, import_node_fs38.statSync)(authPath).size > 2;
17192
+ return (0, import_node_fs39.statSync)(authPath).size > 2;
16982
17193
  } catch {
16983
17194
  return false;
16984
17195
  }
16985
17196
  }
16986
- var import_node_fs38, import_node_os16, import_node_path40, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
17197
+ var import_node_fs39, import_node_os17, import_node_path41, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
16987
17198
  var init_codex = __esm({
16988
17199
  "src/agents/codex.ts"() {
16989
17200
  "use strict";
16990
- import_node_fs38 = require("fs");
16991
- import_node_os16 = require("os");
16992
- import_node_path40 = require("path");
17201
+ import_node_fs39 = require("fs");
17202
+ import_node_os17 = require("os");
17203
+ import_node_path41 = require("path");
16993
17204
  init_run();
16994
17205
  init_app_settings();
16995
17206
  init_global_workspace();
@@ -17018,7 +17229,7 @@ var init_codex = __esm({
17018
17229
  async detect() {
17019
17230
  const codex = resolveAgentExecutable("codex");
17020
17231
  if (codex !== "codex") {
17021
- if (!(0, import_node_fs38.existsSync)(codex)) {
17232
+ if (!(0, import_node_fs39.existsSync)(codex)) {
17022
17233
  return {
17023
17234
  agent: "codex",
17024
17235
  installed: false,
@@ -17050,7 +17261,7 @@ var init_codex = __esm({
17050
17261
  authenticated,
17051
17262
  linearMcp,
17052
17263
  warnings,
17053
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path40.join)(codexHomeDir(), "auth.json")})`
17264
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path41.join)(codexHomeDir(), "auth.json")})`
17054
17265
  };
17055
17266
  },
17056
17267
  async buildTurn(thread, input) {
@@ -17158,7 +17369,7 @@ var init_codex = __esm({
17158
17369
  }
17159
17370
  if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
17160
17371
  const name = `mcp__${item.server}__${item.tool}`;
17161
- const input = asRecord5(item.arguments);
17372
+ const input = asRecord6(item.arguments);
17162
17373
  const events = [
17163
17374
  { type: "tool_use", id: item.id, name, input }
17164
17375
  ];
@@ -17282,18 +17493,18 @@ var init_codex = __esm({
17282
17493
  // src/agents/cursor-sdk-resolve.ts
17283
17494
  function thisModuleFile() {
17284
17495
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
17285
- if (cjsDir) return (0, import_node_path41.join)(cjsDir, "cursor-sdk-resolve.js");
17496
+ if (cjsDir) return (0, import_node_path42.join)(cjsDir, "cursor-sdk-resolve.js");
17286
17497
  try {
17287
17498
  return (0, import_node_url3.fileURLToPath)(import_meta6.url);
17288
17499
  } catch {
17289
- return (0, import_node_path41.join)(process.cwd(), "package.json");
17500
+ return (0, import_node_path42.join)(process.cwd(), "package.json");
17290
17501
  }
17291
17502
  }
17292
17503
  function packageRootLooksLikeSdk(dir) {
17293
17504
  try {
17294
- const raw = (0, import_node_fs39.readFileSync)((0, import_node_path41.join)(dir, "package.json"), "utf8");
17505
+ const raw = (0, import_node_fs40.readFileSync)((0, import_node_path42.join)(dir, "package.json"), "utf8");
17295
17506
  const pkg = JSON.parse(raw);
17296
- return pkg.name === "@cursor/sdk" && (0, import_node_fs39.existsSync)(dir);
17507
+ return pkg.name === "@cursor/sdk" && (0, import_node_fs40.existsSync)(dir);
17297
17508
  } catch {
17298
17509
  return false;
17299
17510
  }
@@ -17302,7 +17513,7 @@ function resolvedPackageRoot(fromFile) {
17302
17513
  try {
17303
17514
  const req = (0, import_node_module3.createRequire)(fromFile);
17304
17515
  const pkgJson = req.resolve("@cursor/sdk/package.json");
17305
- const root = (0, import_node_path41.dirname)(pkgJson);
17516
+ const root = (0, import_node_path42.dirname)(pkgJson);
17306
17517
  return packageRootLooksLikeSdk(root) ? root : null;
17307
17518
  } catch {
17308
17519
  return null;
@@ -17316,10 +17527,10 @@ function resolveCursorSdkRoot(opts) {
17316
17527
  }
17317
17528
  const globalNm = npmGlobalNodeModules(env);
17318
17529
  if (globalNm) {
17319
- const globalRoot = (0, import_node_path41.join)(globalNm, "@cursor/sdk");
17530
+ const globalRoot = (0, import_node_path42.join)(globalNm, "@cursor/sdk");
17320
17531
  if (packageRootLooksLikeSdk(globalRoot)) return globalRoot;
17321
17532
  }
17322
- const cwdPkg = (0, import_node_path41.join)(process.cwd(), "package.json");
17533
+ const cwdPkg = (0, import_node_path42.join)(process.cwd(), "package.json");
17323
17534
  return resolvedPackageRoot(thisModuleFile()) ?? resolvedPackageRoot(cwdPkg);
17324
17535
  }
17325
17536
  function isCursorSdkInstalled(opts) {
@@ -17335,13 +17546,13 @@ function exportTarget(value) {
17335
17546
  }
17336
17547
  function cursorSdkEsmEntry(root) {
17337
17548
  try {
17338
- const pkg = JSON.parse((0, import_node_fs39.readFileSync)((0, import_node_path41.join)(root, "package.json"), "utf8"));
17549
+ const pkg = JSON.parse((0, import_node_fs40.readFileSync)((0, import_node_path42.join)(root, "package.json"), "utf8"));
17339
17550
  const exp = pkg.exports;
17340
17551
  const dot = exp && typeof exp === "object" && !Array.isArray(exp) && "." in exp ? exp["."] : exp;
17341
17552
  const rel = exportTarget(dot) ?? (typeof pkg.module === "string" ? pkg.module : null);
17342
17553
  if (!rel) return null;
17343
- const entry = (0, import_node_path41.join)(root, rel);
17344
- return (0, import_node_fs39.existsSync)(entry) ? entry : null;
17554
+ const entry = (0, import_node_path42.join)(root, rel);
17555
+ return (0, import_node_fs40.existsSync)(entry) ? entry : null;
17345
17556
  } catch {
17346
17557
  return null;
17347
17558
  }
@@ -17357,7 +17568,7 @@ async function importCursorSdk(opts) {
17357
17568
  try {
17358
17569
  let entry = cursorSdkEsmEntry(root);
17359
17570
  if (!entry) {
17360
- const req = (0, import_node_module3.createRequire)((0, import_node_path41.join)(root, "package.json"));
17571
+ const req = (0, import_node_module3.createRequire)((0, import_node_path42.join)(root, "package.json"));
17361
17572
  entry = req.resolve("@cursor/sdk");
17362
17573
  }
17363
17574
  return unwrapCursorSdkModule(await import((0, import_node_url3.pathToFileURL)(entry).href));
@@ -17369,8 +17580,8 @@ function cursorSdkPlatformRipgrepPackage() {
17369
17580
  return `@cursor/sdk-${process.platform}-${process.arch}`;
17370
17581
  }
17371
17582
  function nodeModulesDirForPackageRoot(packageRoot) {
17372
- const parent = (0, import_node_path41.dirname)(packageRoot);
17373
- return (0, import_node_path41.basename)(parent).startsWith("@") ? (0, import_node_path41.dirname)(parent) : parent;
17583
+ const parent = (0, import_node_path42.dirname)(packageRoot);
17584
+ return (0, import_node_path42.basename)(parent).startsWith("@") ? (0, import_node_path42.dirname)(parent) : parent;
17374
17585
  }
17375
17586
  function cursorSdkRipgrepCandidate(opts) {
17376
17587
  const root = resolveCursorSdkRoot(opts);
@@ -17378,18 +17589,18 @@ function cursorSdkRipgrepCandidate(opts) {
17378
17589
  const nm = nodeModulesDirForPackageRoot(root);
17379
17590
  const pkg = cursorSdkPlatformRipgrepPackage();
17380
17591
  const bin = process.platform === "win32" ? "rg.exe" : "rg";
17381
- const sibling = (0, import_node_path41.join)(nm, pkg, "bin", bin);
17382
- if ((0, import_node_fs39.existsSync)(sibling)) return sibling;
17383
- const nested = (0, import_node_path41.join)(root, "node_modules", pkg, "bin", bin);
17384
- return (0, import_node_fs39.existsSync)(nested) ? nested : null;
17592
+ const sibling = (0, import_node_path42.join)(nm, pkg, "bin", bin);
17593
+ if ((0, import_node_fs40.existsSync)(sibling)) return sibling;
17594
+ const nested = (0, import_node_path42.join)(root, "node_modules", pkg, "bin", bin);
17595
+ return (0, import_node_fs40.existsSync)(nested) ? nested : null;
17385
17596
  }
17386
- var import_node_fs39, import_node_module3, import_node_path41, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
17597
+ var import_node_fs40, import_node_module3, import_node_path42, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
17387
17598
  var init_cursor_sdk_resolve = __esm({
17388
17599
  "src/agents/cursor-sdk-resolve.ts"() {
17389
17600
  "use strict";
17390
- import_node_fs39 = require("fs");
17601
+ import_node_fs40 = require("fs");
17391
17602
  import_node_module3 = require("module");
17392
- import_node_path41 = require("path");
17603
+ import_node_path42 = require("path");
17393
17604
  import_node_url3 = require("url");
17394
17605
  init_path();
17395
17606
  import_meta6 = {};
@@ -17431,21 +17642,21 @@ function platformRipgrepPackage() {
17431
17642
  }
17432
17643
  function usableRipgrepPath(candidate) {
17433
17644
  const raw = candidate?.trim();
17434
- if (!raw || !(0, import_node_path42.isAbsolute)(raw)) return null;
17645
+ if (!raw || !(0, import_node_path43.isAbsolute)(raw)) return null;
17435
17646
  const readable = nodeReadableScriptPath(raw);
17436
- if (!(0, import_node_fs40.existsSync)(readable) || isAsarPath(readable)) return null;
17647
+ if (!(0, import_node_fs41.existsSync)(readable) || isAsarPath(readable)) return null;
17437
17648
  return readable;
17438
17649
  }
17439
17650
  function walkForBundledRipgrep(startFile) {
17440
17651
  if (!startFile) return null;
17441
17652
  const pkg = platformRipgrepPackage();
17442
17653
  const name = rgBinaryName();
17443
- let dir = (0, import_node_path42.dirname)((0, import_node_path42.resolve)(startFile));
17444
- const root = (0, import_node_path42.parse)(dir).root;
17654
+ let dir = (0, import_node_path43.dirname)((0, import_node_path43.resolve)(startFile));
17655
+ const root = (0, import_node_path43.parse)(dir).root;
17445
17656
  while (dir !== root) {
17446
- const hit = usableRipgrepPath((0, import_node_path42.join)(dir, "node_modules", pkg, "bin", name));
17657
+ const hit = usableRipgrepPath((0, import_node_path43.join)(dir, "node_modules", pkg, "bin", name));
17447
17658
  if (hit) return hit;
17448
- const next = (0, import_node_path42.dirname)(dir);
17659
+ const next = (0, import_node_path43.dirname)(dir);
17449
17660
  if (next === dir) break;
17450
17661
  dir = next;
17451
17662
  }
@@ -17455,7 +17666,7 @@ function requireResolveBundledRipgrep(fromFile) {
17455
17666
  try {
17456
17667
  const req = (0, import_node_module4.createRequire)(fromFile);
17457
17668
  const pkgJson = req.resolve(`${platformRipgrepPackage()}/package.json`);
17458
- return usableRipgrepPath((0, import_node_path42.join)((0, import_node_path42.dirname)(pkgJson), "bin", rgBinaryName()));
17669
+ return usableRipgrepPath((0, import_node_path43.join)((0, import_node_path43.dirname)(pkgJson), "bin", rgBinaryName()));
17459
17670
  } catch {
17460
17671
  return null;
17461
17672
  }
@@ -17477,13 +17688,13 @@ function cursorRipgrepEnv(opts) {
17477
17688
  const path = resolveCursorRipgrepPath(opts);
17478
17689
  return path ? { [RIPGREP_ENV]: path } : {};
17479
17690
  }
17480
- var import_node_fs40, import_node_module4, import_node_path42, RIPGREP_ENV;
17691
+ var import_node_fs41, import_node_module4, import_node_path43, RIPGREP_ENV;
17481
17692
  var init_cursor_ripgrep = __esm({
17482
17693
  "src/agents/cursor-ripgrep.ts"() {
17483
17694
  "use strict";
17484
- import_node_fs40 = require("fs");
17695
+ import_node_fs41 = require("fs");
17485
17696
  import_node_module4 = require("module");
17486
- import_node_path42 = require("path");
17697
+ import_node_path43 = require("path");
17487
17698
  init_cursor_sdk_resolve();
17488
17699
  init_node_launch();
17489
17700
  init_packaged_runtime();
@@ -17527,11 +17738,11 @@ function entryDir2() {
17527
17738
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
17528
17739
  if (cjsDir) return cjsDir;
17529
17740
  try {
17530
- return (0, import_node_path43.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
17741
+ return (0, import_node_path44.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
17531
17742
  } catch {
17532
17743
  try {
17533
17744
  const req = (0, import_node_module5.createRequire)(process.cwd() + "/");
17534
- return (0, import_node_path43.dirname)(req.resolve("@sideboard-ai/core"));
17745
+ return (0, import_node_path44.dirname)(req.resolve("@sideboard-ai/core"));
17535
17746
  } catch {
17536
17747
  return process.cwd();
17537
17748
  }
@@ -17542,27 +17753,27 @@ function cursorRunnerPath() {
17542
17753
  if (packaged) return packaged;
17543
17754
  const root = entryDir2();
17544
17755
  const candidates = [
17545
- (0, import_node_path43.join)(root, "agents", "cursor-runner.js"),
17546
- (0, import_node_path43.join)(root, "agents", "cursor-runner.cjs"),
17756
+ (0, import_node_path44.join)(root, "agents", "cursor-runner.js"),
17757
+ (0, import_node_path44.join)(root, "agents", "cursor-runner.cjs"),
17547
17758
  // If somehow resolved from package root instead of dist/
17548
- (0, import_node_path43.join)(root, "dist", "agents", "cursor-runner.js"),
17549
- (0, import_node_path43.join)(root, "dist", "agents", "cursor-runner.cjs"),
17759
+ (0, import_node_path44.join)(root, "dist", "agents", "cursor-runner.js"),
17760
+ (0, import_node_path44.join)(root, "dist", "agents", "cursor-runner.cjs"),
17550
17761
  // Source tree (dev): packages/core/src/agents/cursor-runner.ts
17551
- (0, import_node_path43.join)(root, "cursor-runner.ts"),
17552
- (0, import_node_path43.join)(root, "src", "agents", "cursor-runner.ts")
17762
+ (0, import_node_path44.join)(root, "cursor-runner.ts"),
17763
+ (0, import_node_path44.join)(root, "src", "agents", "cursor-runner.ts")
17553
17764
  ];
17554
17765
  for (const candidate of candidates) {
17555
- if ((0, import_node_fs41.existsSync)(candidate)) return candidate;
17766
+ if ((0, import_node_fs42.existsSync)(candidate)) return candidate;
17556
17767
  }
17557
17768
  return candidates[0];
17558
17769
  }
17559
- var import_node_fs41, import_node_module5, import_node_path43, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
17770
+ var import_node_fs42, import_node_module5, import_node_path44, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
17560
17771
  var init_cursor = __esm({
17561
17772
  "src/agents/cursor.ts"() {
17562
17773
  "use strict";
17563
- import_node_fs41 = require("fs");
17774
+ import_node_fs42 = require("fs");
17564
17775
  import_node_module5 = require("module");
17565
- import_node_path43 = require("path");
17776
+ import_node_path44 = require("path");
17566
17777
  import_node_url4 = require("url");
17567
17778
  init_run();
17568
17779
  init_app_settings();
@@ -17689,26 +17900,26 @@ var init_cursor = __esm({
17689
17900
 
17690
17901
  // src/agent-rpc/opencode-hook.ts
17691
17902
  function writeOpencodeRpcPlugin() {
17692
- const pluginDir = (0, import_node_path44.join)(appDataDir(), "agent-rpc", "opencode");
17693
- (0, import_node_fs42.mkdirSync)(pluginDir, { recursive: true });
17694
- const pluginFile = (0, import_node_path44.join)(pluginDir, "sideboard-rpc.js");
17695
- if ((0, import_node_fs42.existsSync)(pluginFile)) {
17903
+ const pluginDir = (0, import_node_path45.join)(appDataDir(), "agent-rpc", "opencode");
17904
+ (0, import_node_fs43.mkdirSync)(pluginDir, { recursive: true });
17905
+ const pluginFile = (0, import_node_path45.join)(pluginDir, "sideboard-rpc.js");
17906
+ if ((0, import_node_fs43.existsSync)(pluginFile)) {
17696
17907
  try {
17697
- if ((0, import_node_fs42.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
17908
+ if ((0, import_node_fs43.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
17698
17909
  } catch {
17699
17910
  }
17700
17911
  }
17701
17912
  const tmp = `${pluginFile}.${process.pid}.tmp`;
17702
- (0, import_node_fs42.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
17703
- (0, import_node_fs42.renameSync)(tmp, pluginFile);
17913
+ (0, import_node_fs43.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
17914
+ (0, import_node_fs43.renameSync)(tmp, pluginFile);
17704
17915
  return pluginFile;
17705
17916
  }
17706
- var import_node_fs42, import_node_path44, OPENCODE_PLUGIN_SOURCE;
17917
+ var import_node_fs43, import_node_path45, OPENCODE_PLUGIN_SOURCE;
17707
17918
  var init_opencode_hook = __esm({
17708
17919
  "src/agent-rpc/opencode-hook.ts"() {
17709
17920
  "use strict";
17710
- import_node_fs42 = require("fs");
17711
- import_node_path44 = require("path");
17921
+ import_node_fs43 = require("fs");
17922
+ import_node_path45 = require("path");
17712
17923
  init_paths();
17713
17924
  init_pilot_tools();
17714
17925
  init_protocol2();
@@ -17866,7 +18077,7 @@ var init_opencode_host = __esm({
17866
18077
  });
17867
18078
 
17868
18079
  // src/agents/opencode.ts
17869
- function asRecord6(value) {
18080
+ function asRecord7(value) {
17870
18081
  if (value && typeof value === "object" && !Array.isArray(value)) {
17871
18082
  return value;
17872
18083
  }
@@ -17911,7 +18122,7 @@ async function listOpencodeModels() {
17911
18122
  if (opencode === "opencode") {
17912
18123
  const which = await run("which", ["opencode"], { reject: false });
17913
18124
  if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
17914
- } else if (!(0, import_node_fs43.existsSync)(opencode)) {
18125
+ } else if (!(0, import_node_fs44.existsSync)(opencode)) {
17915
18126
  return FALLBACK_OPENCODE_MODELS;
17916
18127
  }
17917
18128
  const listed = await run(opencode, ["models"], { reject: false });
@@ -17941,11 +18152,11 @@ function usageFromOpencode(tokens) {
17941
18152
  cacheWriteTokens: tokens.cache?.write ? Number(tokens.cache.write) : void 0
17942
18153
  };
17943
18154
  }
17944
- var import_node_fs43, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
18155
+ var import_node_fs44, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
17945
18156
  var init_opencode = __esm({
17946
18157
  "src/agents/opencode.ts"() {
17947
18158
  "use strict";
17948
- import_node_fs43 = require("fs");
18159
+ import_node_fs44 = require("fs");
17949
18160
  init_run();
17950
18161
  init_app_settings();
17951
18162
  init_error_detail();
@@ -17971,7 +18182,7 @@ var init_opencode = __esm({
17971
18182
  async detect() {
17972
18183
  const opencode = resolveAgentExecutable("opencode");
17973
18184
  if (opencode !== "opencode") {
17974
- if (!(0, import_node_fs43.existsSync)(opencode)) {
18185
+ if (!(0, import_node_fs44.existsSync)(opencode)) {
17975
18186
  return {
17976
18187
  agent: "opencode",
17977
18188
  installed: false,
@@ -18071,7 +18282,7 @@ var init_opencode = __esm({
18071
18282
  const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
18072
18283
  const state = part?.state;
18073
18284
  const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
18074
- const metadata = asRecord6(state?.metadata);
18285
+ const metadata = asRecord7(state?.metadata);
18075
18286
  const id = opencodeToolId(
18076
18287
  name,
18077
18288
  part?.callID ?? part?.id ?? obj.id,
@@ -18106,7 +18317,7 @@ var init_opencode = __esm({
18106
18317
  }
18107
18318
  if (obj.type === "subtask_event") {
18108
18319
  const parentId = str3(obj.childSessionID) ?? str3(obj.childSessionId);
18109
- const part = asRecord6(obj.part);
18320
+ const part = asRecord7(obj.part);
18110
18321
  if (!parentId || !part) return null;
18111
18322
  if (part.type === "text" && str3(part.text)) {
18112
18323
  return withTaskParent(
@@ -18117,8 +18328,8 @@ var init_opencode = __esm({
18117
18328
  if (part.type === "tool" || str3(part.tool)) {
18118
18329
  const name = str3(part.tool) ?? str3(part.name) ?? "tool";
18119
18330
  const id = str3(part.callID) ?? str3(part.id) ?? `${parentId}-${name}`;
18120
- const state = asRecord6(part.state);
18121
- const input = asRecord6(state?.input) ?? asRecord6(part.input);
18331
+ const state = asRecord7(part.state);
18332
+ const input = asRecord7(state?.input) ?? asRecord7(part.input);
18122
18333
  const nested = [
18123
18334
  withEventParentId({ type: "tool_use", id, name, input }, parentId)
18124
18335
  ];
@@ -18424,30 +18635,6 @@ var init_session_quota = __esm({
18424
18635
  }
18425
18636
  });
18426
18637
 
18427
- // src/agents/claude-usage.ts
18428
- var init_claude_usage = __esm({
18429
- "src/agents/claude-usage.ts"() {
18430
- "use strict";
18431
- }
18432
- });
18433
-
18434
- // src/agents/claude-usage-client.ts
18435
- var import_node_fs44, import_node_os17, import_node_path45, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS;
18436
- var init_claude_usage_client = __esm({
18437
- "src/agents/claude-usage-client.ts"() {
18438
- "use strict";
18439
- import_node_fs44 = require("fs");
18440
- import_node_os17 = require("os");
18441
- import_node_path45 = require("path");
18442
- init_run();
18443
- init_fetch();
18444
- init_app_settings();
18445
- init_claude_usage();
18446
- CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
18447
- CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
18448
- }
18449
- });
18450
-
18451
18638
  // src/agents/install-native.ts
18452
18639
  var init_install_native = __esm({
18453
18640
  "src/agents/install-native.ts"() {
@@ -22436,7 +22623,7 @@ var init_agent_block_view = __esm({
22436
22623
  });
22437
22624
 
22438
22625
  // src/plan/plan-present.ts
22439
- function asRecord7(v) {
22626
+ function asRecord8(v) {
22440
22627
  return v != null && typeof v === "object" && !Array.isArray(v) ? v : null;
22441
22628
  }
22442
22629
  function isPresentPlanToolName(name) {
@@ -22455,7 +22642,7 @@ function extractPresentedPlan(parts) {
22455
22642
  for (let i = parts.length - 1; i >= 0; i--) {
22456
22643
  const p = parts[i];
22457
22644
  if (p.type !== "tool" || !isPresentPlanToolName(p.name)) continue;
22458
- const input = asRecord7(p.input) ?? {};
22645
+ const input = asRecord8(p.input) ?? {};
22459
22646
  const content = typeof input.content === "string" ? input.content : typeof input.plan === "string" ? input.plan : typeof input.markdown === "string" ? input.markdown : "";
22460
22647
  if (!content.trim()) continue;
22461
22648
  const title = typeof input.title === "string" && input.title.trim() ? input.title.trim() : "Plan";
@@ -24170,7 +24357,7 @@ __export(abletime_rest_exports, {
24170
24357
  looksLikeAbleTimeUlid: () => looksLikeAbleTimeUlid,
24171
24358
  textFromAbleTimeDoc: () => textFromAbleTimeDoc
24172
24359
  });
24173
- function asRecord8(value) {
24360
+ function asRecord9(value) {
24174
24361
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24175
24362
  }
24176
24363
  function asString(value) {
@@ -24178,7 +24365,7 @@ function asString(value) {
24178
24365
  }
24179
24366
  function asList(value) {
24180
24367
  if (Array.isArray(value)) return value;
24181
- const record = asRecord8(value);
24368
+ const record = asRecord9(value);
24182
24369
  if (!record) return [];
24183
24370
  for (const key of ["data", "tasks", "projects", "users", "items", "results"]) {
24184
24371
  if (Array.isArray(record[key])) return record[key];
@@ -24195,12 +24382,12 @@ function ableTimeDocFromText(text7) {
24195
24382
  }
24196
24383
  function textFromAbleTimeDoc(value) {
24197
24384
  if (typeof value === "string") return value.trim();
24198
- const record = asRecord8(value);
24385
+ const record = asRecord9(value);
24199
24386
  if (!record) return "";
24200
24387
  if (typeof record.text === "string" && record.text.trim()) return record.text.trim();
24201
24388
  const chunks = [];
24202
24389
  const walk = (node) => {
24203
- const rec = asRecord8(node);
24390
+ const rec = asRecord9(node);
24204
24391
  if (!rec) return;
24205
24392
  if (typeof rec.text === "string" && rec.text) chunks.push(rec.text);
24206
24393
  if (Array.isArray(rec.content)) rec.content.forEach(walk);
@@ -24262,7 +24449,7 @@ async function restPages(path, opts, maxPages = 20) {
24262
24449
  query: { ...opts.query, ...cursor ? { cursor } : {} }
24263
24450
  });
24264
24451
  items.push(...asList(raw));
24265
- const page = asRecord8(asRecord8(raw)?.page);
24452
+ const page = asRecord9(asRecord9(raw)?.page);
24266
24453
  const next = page ? asString(page.nextCursor) : "";
24267
24454
  if (!next) break;
24268
24455
  cursor = next;
@@ -24270,7 +24457,7 @@ async function restPages(path, opts, maxPages = 20) {
24270
24457
  return items;
24271
24458
  }
24272
24459
  function userDisplayName(raw) {
24273
- const rec = asRecord8(raw);
24460
+ const rec = asRecord9(raw);
24274
24461
  if (!rec) return null;
24275
24462
  const id = asString(rec.userId) || asString(rec.id);
24276
24463
  const name = [asString(rec.firstName), asString(rec.lastName)].filter(Boolean).join(" ") || asString(rec.username) || asString(rec.email) || asString(rec.name);
@@ -24278,7 +24465,7 @@ function userDisplayName(raw) {
24278
24465
  return { id: id || void 0, name };
24279
24466
  }
24280
24467
  function restTaskToRaw(raw, users) {
24281
- const rec = asRecord8(raw);
24468
+ const rec = asRecord9(raw);
24282
24469
  if (!rec) return null;
24283
24470
  const id = asString(rec.timeflowTaskId) || asString(rec.taskId) || asString(rec.id);
24284
24471
  const identifier = asString(rec.taskRef) || asString(rec.reference) || id;
@@ -24286,7 +24473,7 @@ function restTaskToRaw(raw, users) {
24286
24473
  if (!id && !identifier && !title) return null;
24287
24474
  const assignee = users.get(asString(rec.assignedUserId));
24288
24475
  const comments = asList(rec.comments).map((item) => {
24289
- const comment = asRecord8(item) ?? {};
24476
+ const comment = asRecord9(item) ?? {};
24290
24477
  const user = userDisplayName(comment);
24291
24478
  return {
24292
24479
  id: asString(comment.commentId) || asString(comment.id),
@@ -24317,13 +24504,13 @@ function restTaskToRaw(raw, users) {
24317
24504
  };
24318
24505
  }
24319
24506
  function restProjectToRaw(raw) {
24320
- const rec = asRecord8(raw);
24507
+ const rec = asRecord9(raw);
24321
24508
  if (!rec) return null;
24322
24509
  const id = asString(rec.projectId) || asString(rec.id);
24323
24510
  const name = asString(rec.projectName) || asString(rec.name);
24324
24511
  if (!id && !name) return null;
24325
24512
  const categories = asList(rec.categories).map((item) => {
24326
- const cat = asRecord8(item) ?? {};
24513
+ const cat = asRecord9(item) ?? {};
24327
24514
  return {
24328
24515
  id: asString(cat.projectCategoryId) || asString(cat.categoryId) || asString(cat.id),
24329
24516
  name: asString(cat.categoryName) || asString(cat.name)
@@ -24335,7 +24522,7 @@ async function listUsers(opts) {
24335
24522
  const users = /* @__PURE__ */ new Map();
24336
24523
  for (const item of await restPages("/users", opts).catch(() => [])) {
24337
24524
  const user = userDisplayName(item);
24338
- const rec = asRecord8(item);
24525
+ const rec = asRecord9(item);
24339
24526
  const id = user?.id || (rec ? asString(rec.userId) : "");
24340
24527
  if (user && id) users.set(id, user);
24341
24528
  }
@@ -24461,10 +24648,10 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24461
24648
  if (!project) throw new Error("AbleTime has no projects to create a task in");
24462
24649
  const categories = asList(project.categories);
24463
24650
  const wantedCategory = firstStringArg(args, ["category_id", "categoryId", "category"]);
24464
- const category = categories.map((item) => asRecord8(item)).find((item) => {
24651
+ const category = categories.map((item) => asRecord9(item)).find((item) => {
24465
24652
  if (!item || !wantedCategory) return false;
24466
24653
  return asString(item.id).toLowerCase() === wantedCategory.toLowerCase() || asString(item.name).toLowerCase() === wantedCategory.toLowerCase();
24467
- }) ?? asRecord8(categories[0]);
24654
+ }) ?? asRecord9(categories[0]);
24468
24655
  const parentArg = firstStringArg(args, ["parent", "parent_id", "parentId", "related_task_id"]);
24469
24656
  const parentTaskId = parentArg ? await resolveRestParentTaskId(parentArg, requestOpts) : void 0;
24470
24657
  const created = await abletimeRestRequest("/tasks", {
@@ -24478,7 +24665,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24478
24665
  }
24479
24666
  });
24480
24667
  const state = firstStringArg(args, ["state"]);
24481
- const createdId = asString(asRecord8(created)?.timeflowTaskId);
24668
+ const createdId = asString(asRecord9(created)?.timeflowTaskId);
24482
24669
  const description = asString(args.description);
24483
24670
  if (createdId && description) {
24484
24671
  await abletimeRestRequest(`/tasks/${encodeURIComponent(createdId)}`, {
@@ -24551,7 +24738,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24551
24738
  method: "POST",
24552
24739
  body: { content: ableTimeDocFromText(body) }
24553
24740
  });
24554
- const rec = asRecord8(created) ?? {};
24741
+ const rec = asRecord9(created) ?? {};
24555
24742
  return {
24556
24743
  id: asString(rec.commentId) || void 0,
24557
24744
  body: textFromAbleTimeDoc(rec.content) || body
@@ -24646,7 +24833,7 @@ function rewriteAbleTimeError(message) {
24646
24833
  }
24647
24834
  return message;
24648
24835
  }
24649
- function asRecord9(value) {
24836
+ function asRecord10(value) {
24650
24837
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24651
24838
  }
24652
24839
  function parseSseJson(body) {
@@ -24668,12 +24855,12 @@ function parseSseJson(body) {
24668
24855
  }
24669
24856
  }
24670
24857
  function unwrapToolResult(result) {
24671
- const record = asRecord9(result);
24858
+ const record = asRecord10(result);
24672
24859
  if (!record) return result;
24673
24860
  const content = record.content;
24674
24861
  if (Array.isArray(content)) {
24675
24862
  const texts = content.map((part) => {
24676
- const item = asRecord9(part);
24863
+ const item = asRecord10(part);
24677
24864
  if (!item) return "";
24678
24865
  return typeof item.text === "string" ? item.text : "";
24679
24866
  }).filter(Boolean);
@@ -24695,7 +24882,7 @@ function unwrapToolResult(result) {
24695
24882
  return result;
24696
24883
  }
24697
24884
  function textsFromUnknown(value) {
24698
- const record = asRecord9(value);
24885
+ const record = asRecord10(value);
24699
24886
  if (!record) return "";
24700
24887
  if (typeof record.message === "string") return record.message;
24701
24888
  if (typeof record.error === "string") return record.error;
@@ -24742,7 +24929,7 @@ async function abletimeMcpRequest(method, params, opts) {
24742
24929
  return parseSseJson(body);
24743
24930
  }
24744
24931
  })();
24745
- const rpc = asRecord9(parsed);
24932
+ const rpc = asRecord10(parsed);
24746
24933
  if (rpc?.error) {
24747
24934
  const detail = typeof rpc.error.message === "string" && rpc.error.message.trim() ? rpc.error.message : `AbleTime MCP error ${rpc.error.code ?? ""}`.trim();
24748
24935
  throw new Error(rewriteAbleTimeError(detail));
@@ -24829,7 +25016,7 @@ var init_abletime_mcp = __esm({
24829
25016
  });
24830
25017
 
24831
25018
  // src/integrations/abletime-attachments.ts
24832
- function asRecord10(value) {
25019
+ function asRecord11(value) {
24833
25020
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24834
25021
  }
24835
25022
  function asString2(value) {
@@ -24837,7 +25024,7 @@ function asString2(value) {
24837
25024
  }
24838
25025
  function asList2(value) {
24839
25026
  if (Array.isArray(value)) return value;
24840
- const record = asRecord10(value);
25027
+ const record = asRecord11(value);
24841
25028
  if (!record) return [];
24842
25029
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
24843
25030
  if (Array.isArray(record[key])) return record[key];
@@ -24856,9 +25043,9 @@ function filesFromAbleTimeDoc(value) {
24856
25043
  const out = [];
24857
25044
  const seen = /* @__PURE__ */ new Set();
24858
25045
  const walk = (node) => {
24859
- const rec = asRecord10(node);
25046
+ const rec = asRecord11(node);
24860
25047
  if (!rec) return;
24861
- const attrs = asRecord10(rec.attrs) ?? rec;
25048
+ const attrs = asRecord11(rec.attrs) ?? rec;
24862
25049
  const url = asString2(attrs.src) || asString2(attrs.href) || asString2(attrs.url) || asString2(attrs.fileUrl) || asString2(attrs.downloadUrl);
24863
25050
  if (url && !seen.has(url)) {
24864
25051
  seen.add(url);
@@ -24876,7 +25063,7 @@ function filesFromAbleTimeDoc(value) {
24876
25063
  function listedAbleTimeFiles(raw) {
24877
25064
  const out = [];
24878
25065
  for (const item of asList2(raw)) {
24879
- const rec = asRecord10(item);
25066
+ const rec = asRecord11(item);
24880
25067
  if (!rec) continue;
24881
25068
  const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl", "permalink"]);
24882
25069
  if (!url) continue;
@@ -24896,7 +25083,7 @@ function mapAbleTimeAttachments(record) {
24896
25083
  ...filesFromAbleTimeDoc(record.description),
24897
25084
  ...filesFromAbleTimeDoc(record.content),
24898
25085
  ...asList2(record.comments).flatMap((item) => {
24899
- const rec = asRecord10(item);
25086
+ const rec = asRecord11(item);
24900
25087
  return rec ? filesFromAbleTimeDoc(rec.content ?? rec.body) : [];
24901
25088
  })
24902
25089
  ].map((file) => ({
@@ -24938,7 +25125,7 @@ async function resolveAbleTimeAttachmentUrl(id, opts) {
24938
25125
  const json = await res.json().catch(() => null);
24939
25126
  const rec = json && typeof json === "object" && !Array.isArray(json) ? json.data && typeof json.data === "object" ? json.data : json : null;
24940
25127
  if (!rec) continue;
24941
- const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord10(rec.file), ["url", "href"]);
25128
+ const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord11(rec.file), ["url", "href"]);
24942
25129
  if (url) {
24943
25130
  return {
24944
25131
  url,
@@ -24980,7 +25167,7 @@ var init_abletime_attachments = __esm({
24980
25167
  });
24981
25168
 
24982
25169
  // src/integrations/abletime-projects.ts
24983
- function asRecord11(value) {
25170
+ function asRecord12(value) {
24984
25171
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24985
25172
  }
24986
25173
  function firstString2(record, keys) {
@@ -24993,7 +25180,7 @@ function firstString2(record, keys) {
24993
25180
  }
24994
25181
  function asList3(value) {
24995
25182
  if (Array.isArray(value)) return value;
24996
- const record = asRecord11(value);
25183
+ const record = asRecord12(value);
24997
25184
  if (!record) return [];
24998
25185
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
24999
25186
  if (Array.isArray(record[key])) return record[key];
@@ -25001,7 +25188,7 @@ function asList3(value) {
25001
25188
  return [];
25002
25189
  }
25003
25190
  function ableTimeProjectFields(nested) {
25004
- const projectRecord = asRecord11(nested.project);
25191
+ const projectRecord = asRecord12(nested.project);
25005
25192
  const projectId = firstString2(nested, ["project_id", "projectId"]) || firstString2(projectRecord, ["id"]) || void 0;
25006
25193
  const projectName = firstString2(nested, ["project_name", "projectName"]) || firstString2(projectRecord, ["name", "title"]) || void 0;
25007
25194
  if (!projectId && !projectName) return {};
@@ -25014,13 +25201,13 @@ function ableTimeProjectFields(nested) {
25014
25201
  };
25015
25202
  }
25016
25203
  function mapAbleTimeProject(raw) {
25017
- const record = asRecord11(raw);
25204
+ const record = asRecord12(raw);
25018
25205
  if (!record) return null;
25019
25206
  const id = firstString2(record, ["id", "project_id", "projectId"]);
25020
25207
  const name = firstString2(record, ["name", "title", "projectName"]);
25021
25208
  if (!id && !name) return null;
25022
25209
  const categories = asList3(record.categories ?? record.category).map((item) => {
25023
- const rec = asRecord11(item);
25210
+ const rec = asRecord12(item);
25024
25211
  if (!rec) return null;
25025
25212
  const categoryId = firstString2(rec, ["id", "category_id", "projectCategoryId", "categoryId"]);
25026
25213
  const categoryName = firstString2(rec, ["name", "title", "categoryName"]);
@@ -25057,7 +25244,7 @@ __export(abletime_exports, {
25057
25244
  updateAbleTimeTask: () => updateAbleTimeTask,
25058
25245
  verifyAbleTimeConnection: () => verifyAbleTimeConnection
25059
25246
  });
25060
- function asRecord12(value) {
25247
+ function asRecord13(value) {
25061
25248
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
25062
25249
  }
25063
25250
  function asString3(value) {
@@ -25074,14 +25261,14 @@ function firstString3(record, keys) {
25074
25261
  function firstRecord(record, keys) {
25075
25262
  if (!record) return null;
25076
25263
  for (const key of keys) {
25077
- const value = asRecord12(record[key]);
25264
+ const value = asRecord13(record[key]);
25078
25265
  if (value) return value;
25079
25266
  }
25080
25267
  return null;
25081
25268
  }
25082
25269
  function asList4(value) {
25083
25270
  if (Array.isArray(value)) return value;
25084
- const record = asRecord12(value);
25271
+ const record = asRecord13(value);
25085
25272
  if (!record) return [];
25086
25273
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
25087
25274
  if (Array.isArray(record[key])) return record[key];
@@ -25093,18 +25280,18 @@ function labelsOf(record) {
25093
25280
  if (!Array.isArray(raw)) return [];
25094
25281
  return raw.map((item) => {
25095
25282
  if (typeof item === "string") return item.trim();
25096
- const rec = asRecord12(item);
25283
+ const rec = asRecord13(item);
25097
25284
  return rec ? firstString3(rec, ["name", "title", "label"]) : "";
25098
25285
  }).filter(Boolean);
25099
25286
  }
25100
25287
  function commentsOf(record) {
25101
25288
  const out = [];
25102
25289
  for (const item of asList4(record.comments ?? record.notes ?? record.discussion)) {
25103
- const rec = asRecord12(item);
25290
+ const rec = asRecord13(item);
25104
25291
  if (!rec) continue;
25105
25292
  const body = firstString3(rec, ["body", "text", "comment", "message", "contentSanitized"]) || textFromAbleTimeDoc(rec.content);
25106
25293
  if (!body) continue;
25107
- const user = firstString3(asRecord12(rec.user) ?? asRecord12(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
25294
+ const user = firstString3(asRecord13(rec.user) ?? asRecord13(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
25108
25295
  const id = firstString3(rec, ["id", "comment_id", "commentId"]);
25109
25296
  const url = firstString3(rec, ["url", "permalink"]);
25110
25297
  const createdAt = firstString3(rec, ["created_at", "createdAt", "created"]);
@@ -25131,7 +25318,7 @@ function taskUrl(task, host) {
25131
25318
  return `${base}/tasks/${slug}`;
25132
25319
  }
25133
25320
  function mapAbleTimeTask(raw, host) {
25134
- const record = asRecord12(raw);
25321
+ const record = asRecord13(raw);
25135
25322
  if (!record) return null;
25136
25323
  const nested = firstRecord(record, ["task", "data"]) ?? record;
25137
25324
  const id = firstString3(nested, ["id", "task_id", "taskId", "timeflowTaskId"]);
@@ -25149,7 +25336,7 @@ function mapAbleTimeTask(raw, host) {
25149
25336
  description: firstString3(nested, ["description", "body", "details", "descriptionSanitized"]) || textFromAbleTimeDoc(nested.description) || void 0,
25150
25337
  state: firstString3(nested, ["state", "board_state", "boardState", "status", "taskState"]) || void 0,
25151
25338
  ...ableTimeProjectFields(nested),
25152
- categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord12(nested.category), ["id"]) || void 0,
25339
+ categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord13(nested.category), ["id"]) || void 0,
25153
25340
  assignee: assigneeOf(nested),
25154
25341
  labels: labelsOf(nested),
25155
25342
  comments: commentsOf(nested),
@@ -25202,7 +25389,7 @@ function isOpenTask(task) {
25202
25389
  }
25203
25390
  async function getAbleTimeOrientation(opts) {
25204
25391
  const raw = await callAbleTimeTool("orientation", {}, opts);
25205
- const record = asRecord12(raw);
25392
+ const record = asRecord13(raw);
25206
25393
  const viewerRec = firstRecord(record, ["viewer", "principal", "user", "actor", "me", "person"]) ?? record;
25207
25394
  const viewer = {
25208
25395
  id: firstString3(viewerRec, ["id", "user_id"]) || void 0,
@@ -25281,7 +25468,7 @@ async function commentAbleTimeTask(input, opts) {
25281
25468
  { id, task_id: id, task: id, body, comment: body, text: body },
25282
25469
  opts
25283
25470
  );
25284
- const rec = asRecord12(raw);
25471
+ const rec = asRecord13(raw);
25285
25472
  return {
25286
25473
  id: rec ? firstString3(rec, ["id", "comment_id"]) || void 0 : void 0,
25287
25474
  body: rec ? firstString3(rec, ["body", "text", "comment"]) || body : body
@@ -29439,7 +29626,11 @@ function normalizeServiceOrigin(raw, fallback) {
29439
29626
  function optionalServiceConnected(id, integrations) {
29440
29627
  if (id === "vercel") return Boolean(integrations.vercelToken?.trim());
29441
29628
  if (id === "supabase") return Boolean(integrations.supabaseAccessToken?.trim());
29442
- if (id === "posthog") return Boolean(integrations.posthogPersonalApiKey?.trim());
29629
+ if (id === "posthog") {
29630
+ return Boolean(
29631
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
29632
+ );
29633
+ }
29443
29634
  return Boolean(integrations.sentryAuthToken?.trim());
29444
29635
  }
29445
29636
  function connectedOptionalServices(integrations) {
@@ -29454,12 +29645,12 @@ function connectorDirectiveLine(spec, cli) {
29454
29645
  if (spec.cli) {
29455
29646
  return `- ${spec.label}: use \`${spec.cli}\` (\`${spec.envKey}\`${extras})${cliPresencePhrase(spec, cli)}. Do not add a ${spec.label} MCP.`;
29456
29647
  }
29457
- return `- ${spec.label}: call \`posthog_api\`. Path must start with \`/api/\`. GET is the default. POST \`/api/projects/:id/query/\` or \`/api/environments/:id/query/\` is a read and does not need \`write=true\`. Other POST and PATCH require \`write=true\` only when the user asked to change data. Do not read the API key from the environment. Do not add a ${spec.label} MCP.`;
29648
+ return `- ${spec.label}: call \`posthog_api\`. Path must start with \`/api/\`. GET is the default. POST \`/api/projects/:id/query/\` or \`/api/environments/:id/query/\` is a read and does not need \`write=true\`. Other POST and PATCH require \`write=true\` only when the user asked to change data. Do not read the token from the environment. Do not add a ${spec.label} MCP.`;
29458
29649
  }
29459
29650
  function connectorAuthCaution(posthog, cliConnected) {
29460
29651
  const signIn = posthog ? "If a connector MCP is listed but needsAuth or returns unauthorized, do not sign in to that MCP." : "If a Vercel, Supabase, or Sentry MCP is listed but needsAuth or returns unauthorized, do not sign in to that MCP.";
29461
29652
  const token = cliConnected ? " CLI tokens are already in this process." : "";
29462
- const key = posthog ? " Do not read a PostHog key from the environment." : "";
29653
+ const key = posthog ? " Do not read a PostHog token from the environment." : "";
29463
29654
  return `${signIn}${token}${key} When this Sideboard connection works, ignore a Claude connector that failed to start. Use the Claude connector only when this connection is not set or the CLI call fails.`;
29464
29655
  }
29465
29656
  function connectorReminderBit(spec, cli) {
@@ -29487,7 +29678,7 @@ function formatOptionalServicesReminder(integrations, cli) {
29487
29678
  const bits = connected.map((spec) => connectorReminderBit(spec, cli)).join(". ");
29488
29679
  const tokenBit = connected.some((spec) => spec.cli) ? "CLI tokens are already in this process. " : "";
29489
29680
  const posthog = connected.some((spec) => spec.id === "posthog");
29490
- const auth = posthog ? "If a connector MCP needsAuth or is unauthorized, ignore it and use the CLI or `posthog_api` while this Sideboard connection works. Use the Claude connector only when it is not set or the call fails. Do not read a PostHog key from the environment." : "If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized, ignore it and use the CLI while this Sideboard connection works. Use the Claude connector only when it is not set or the CLI call fails.";
29681
+ const auth = posthog ? "If a connector MCP needsAuth or is unauthorized, ignore it and use the CLI or `posthog_api` while this Sideboard connection works. Use the Claude connector only when it is not set or the call fails. Do not read a PostHog token from the environment." : "If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized, ignore it and use the CLI while this Sideboard connection works. Use the Claude connector only when it is not set or the CLI call fails.";
29491
29682
  return `Settings \u2192 Connectors: ${tokenBit}${bits}. ${auth} Do not add vendor MCPs. Shell dumps from those CLIs go in \`.context/cli/\` \u2014 read a slice.`;
29492
29683
  }
29493
29684
  async function connectedCliPresence(integrations) {
@@ -29537,13 +29728,12 @@ var init_optional_services = __esm({
29537
29728
  {
29538
29729
  id: "posthog",
29539
29730
  label: "PostHog",
29540
- hint: "Product analytics. Agents call `posthog_api` on the Sideboard MCP server.",
29731
+ hint: "Product analytics. Sign in with your browser. Agents call `posthog_api`.",
29541
29732
  tokenPlaceholder: "phx_\u2026",
29542
- tokenDocs: "https://app.posthog.com/settings/user-api-keys",
29733
+ tokenDocs: "https://posthog.com/docs/api/oauth",
29543
29734
  envKey: "POSTHOG_PERSONAL_API_KEY",
29544
29735
  hostEnvKey: "POSTHOG_HOST",
29545
- defaultHost: "https://us.posthog.com",
29546
- hostPlaceholder: "https://us.posthog.com"
29736
+ defaultHost: "https://us.posthog.com"
29547
29737
  },
29548
29738
  {
29549
29739
  id: "sentry",
@@ -34089,7 +34279,7 @@ function createClippedMcpServer() {
34089
34279
 
34090
34280
  // src/mcp/server.ts
34091
34281
  var import_zod12 = require("zod");
34092
- var import_node_crypto24 = require("crypto");
34282
+ var import_node_crypto25 = require("crypto");
34093
34283
  var import_node_path74 = require("path");
34094
34284
  init_orchestrator();
34095
34285
  init_task_state();
@@ -36002,6 +36192,85 @@ function registerConnectedIssueVendorTools(server, settings = loadAppSettings())
36002
36192
  var import_zod8 = require("zod");
36003
36193
  init_fetch();
36004
36194
  init_optional_services();
36195
+
36196
+ // src/integrations/posthog-oauth.ts
36197
+ var import_node_crypto21 = require("crypto");
36198
+ var import_node_http4 = require("http");
36199
+ init_fetch();
36200
+ init_app_settings();
36201
+ var BAKED_POSTHOG_OAUTH_CLIENT_ID = "https://www.sideboard.build/oauth/posthog-client.json";
36202
+ var POSTHOG_TOKEN = "https://oauth.posthog.com/oauth/token/";
36203
+ var REFRESH_SKEW_MS4 = 6e4;
36204
+ function posthogOAuthClientId() {
36205
+ return process.env.SIDEBOARD_POSTHOG_OAUTH_CLIENT_ID?.trim() || BAKED_POSTHOG_OAUTH_CLIENT_ID;
36206
+ }
36207
+ async function exchangePosthogToken(body) {
36208
+ const res = await httpFetch(POSTHOG_TOKEN, {
36209
+ method: "POST",
36210
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
36211
+ body
36212
+ });
36213
+ const data = await res.json().catch(() => ({}));
36214
+ if (!res.ok || data.error || !data.access_token?.trim()) {
36215
+ const detail = data.error_description || data.error || `HTTP ${res.status}`;
36216
+ throw new Error(`PostHog sign-in failed: ${detail}`);
36217
+ }
36218
+ return data;
36219
+ }
36220
+ var refreshInFlight4 = null;
36221
+ async function refreshPosthogAccessToken(refresh, host, viewerName, legacy) {
36222
+ try {
36223
+ const data = await exchangePosthogToken(
36224
+ new URLSearchParams({
36225
+ grant_type: "refresh_token",
36226
+ refresh_token: refresh,
36227
+ client_id: posthogOAuthClientId()
36228
+ })
36229
+ );
36230
+ const saved = savePosthogOAuth({
36231
+ accessToken: data.access_token.trim(),
36232
+ refreshToken: data.refresh_token?.trim() || refresh,
36233
+ expiresIn: data.expires_in,
36234
+ host,
36235
+ viewerName
36236
+ });
36237
+ return {
36238
+ token: saved.integrations.posthogAccessToken.trim(),
36239
+ host: saved.integrations.posthogHost?.trim() || host
36240
+ };
36241
+ } catch (err) {
36242
+ if (legacy) return { token: legacy, host };
36243
+ throw err;
36244
+ }
36245
+ }
36246
+ async function getPosthogAccessToken() {
36247
+ const integrations = loadAppSettings().integrations;
36248
+ const host = integrations.posthogHost?.trim() || "https://us.posthog.com";
36249
+ const access = integrations.posthogAccessToken?.trim() || "";
36250
+ const refresh = integrations.posthogRefreshToken?.trim() || "";
36251
+ const legacy = integrations.posthogPersonalApiKey?.trim() || "";
36252
+ const exp = integrations.posthogTokenExpiresAt;
36253
+ const accessFresh = Boolean(access) && (exp == null || exp - Date.now() > REFRESH_SKEW_MS4);
36254
+ if (accessFresh) return { token: access, host };
36255
+ if (refresh) {
36256
+ if (!refreshInFlight4) {
36257
+ refreshInFlight4 = refreshPosthogAccessToken(
36258
+ refresh,
36259
+ host,
36260
+ integrations.posthogViewerName,
36261
+ legacy
36262
+ ).finally(() => {
36263
+ refreshInFlight4 = null;
36264
+ });
36265
+ }
36266
+ return refreshInFlight4;
36267
+ }
36268
+ if (access) return { token: access, host };
36269
+ if (legacy) return { token: legacy, host };
36270
+ return null;
36271
+ }
36272
+
36273
+ // src/mcp/posthog-tools.ts
36005
36274
  init_app_settings();
36006
36275
  init_issue_list();
36007
36276
  var POSTHOG_METHODS = ["GET", "POST", "PATCH"];
@@ -36057,9 +36326,16 @@ async function runPosthogApi(input) {
36057
36326
  if (method === "GET" && input.body !== void 0) {
36058
36327
  return mcpJson({ ok: false, error: "GET does not take a body" }, true);
36059
36328
  }
36060
- const integrations = loadAppSettings().integrations;
36061
- const token = integrations.posthogPersonalApiKey?.trim();
36062
- if (!token) {
36329
+ let session;
36330
+ try {
36331
+ session = await getPosthogAccessToken();
36332
+ } catch (err) {
36333
+ return mcpJson(
36334
+ { ok: false, error: err instanceof Error ? err.message : String(err) },
36335
+ true
36336
+ );
36337
+ }
36338
+ if (!session) {
36063
36339
  return mcpJson(
36064
36340
  { ok: false, error: "PostHog is not connected (Settings \u2192 Connectors)." },
36065
36341
  true
@@ -36068,7 +36344,7 @@ async function runPosthogApi(input) {
36068
36344
  let url;
36069
36345
  try {
36070
36346
  url = posthogApiUrl(
36071
- integrations.posthogHost || "https://us.posthog.com",
36347
+ session.host,
36072
36348
  withPosthogSlash(method, input.path),
36073
36349
  input.query
36074
36350
  );
@@ -36079,7 +36355,7 @@ async function runPosthogApi(input) {
36079
36355
  );
36080
36356
  }
36081
36357
  const headers = {
36082
- Authorization: `Bearer ${token}`,
36358
+ Authorization: `Bearer ${session.token}`,
36083
36359
  Accept: "application/json"
36084
36360
  };
36085
36361
  let body;
@@ -36562,7 +36838,7 @@ function registerScheduleTools(server) {
36562
36838
  var import_zod11 = require("zod");
36563
36839
 
36564
36840
  // src/order/order.ts
36565
- var import_node_crypto21 = require("crypto");
36841
+ var import_node_crypto22 = require("crypto");
36566
36842
  var import_node_fs72 = require("fs");
36567
36843
  var import_node_path70 = require("path");
36568
36844
  init_paths();
@@ -37266,7 +37542,7 @@ function setOrderPlan(input) {
37266
37542
  const owner = input.ownerThreadId?.trim() ?? "";
37267
37543
  const existing = file.plans.find((plan2) => plan2.ownerThreadId === owner);
37268
37544
  const plan = {
37269
- id: existing?.id ?? (0, import_node_crypto21.randomUUID)(),
37545
+ id: existing?.id ?? (0, import_node_crypto22.randomUUID)(),
37270
37546
  ownerThreadId: owner,
37271
37547
  title,
37272
37548
  summary: input.summary?.trim().slice(0, 600) ?? existing?.summary ?? "",
@@ -37333,7 +37609,7 @@ function selectPlan(file, input) {
37333
37609
  if (file.plans.length === 1) return file.plans[0];
37334
37610
  if (file.plans.length === 0) {
37335
37611
  const plan = {
37336
- id: (0, import_node_crypto21.randomUUID)(),
37612
+ id: (0, import_node_crypto22.randomUUID)(),
37337
37613
  ownerThreadId: "",
37338
37614
  title: "Planner",
37339
37615
  summary: "",
@@ -37367,7 +37643,7 @@ function setOrderDependency(input) {
37367
37643
  }
37368
37644
  const loop = dependencyWouldCycle(scoped, draft);
37369
37645
  const edge = {
37370
- id: (0, import_node_crypto21.randomUUID)(),
37646
+ id: (0, import_node_crypto22.randomUUID)(),
37371
37647
  planId: plan.id,
37372
37648
  waitsOn,
37373
37649
  gate,
@@ -37704,7 +37980,7 @@ function registerOrderTools(server) {
37704
37980
  }
37705
37981
 
37706
37982
  // src/agent-rpc/handlers.ts
37707
- var import_node_crypto22 = require("crypto");
37983
+ var import_node_crypto23 = require("crypto");
37708
37984
  var import_node_path71 = require("path");
37709
37985
  init_wait_for_job();
37710
37986
  init_wait_for_turn();
@@ -37751,7 +38027,7 @@ setToolPermissionPublisher({
37751
38027
  // src/agent-rpc/handlers.ts
37752
38028
  init_protocol2();
37753
38029
  function presentArtifactResult(input) {
37754
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto22.randomUUID)().slice(0, 8)}`;
38030
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto23.randomUUID)().slice(0, 8)}`;
37755
38031
  return {
37756
38032
  ok: true,
37757
38033
  artifact_id: id,
@@ -37776,7 +38052,7 @@ init_worktree();
37776
38052
  init_paths();
37777
38053
 
37778
38054
  // src/board/board-pins.ts
37779
- var import_node_crypto23 = require("crypto");
38055
+ var import_node_crypto24 = require("crypto");
37780
38056
  var import_node_fs73 = require("fs");
37781
38057
  var import_node_path72 = require("path");
37782
38058
  init_paths();
@@ -38757,7 +39033,7 @@ async function startMcpServer() {
38757
39033
  const ident = issue?.identifier ?? ref.trim();
38758
39034
  const attachments = issue ? [
38759
39035
  {
38760
- id: (0, import_node_crypto24.randomUUID)(),
39036
+ id: (0, import_node_crypto25.randomUUID)(),
38761
39037
  name: issue.identifier,
38762
39038
  kind: "issue",
38763
39039
  content: [