@sideboard-ai/core 0.1.346 → 0.1.348

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-RTZO2YJC.js → chunk-2HPVGTHF.js} +2 -2
  12. package/dist/{chunk-GHKJBZW5.js → chunk-4NXGVJA6.js} +2 -2
  13. package/dist/{chunk-O5WRVQFT.js → chunk-5FUAOU3G.js} +1 -1
  14. package/dist/{chunk-3J3XOIHF.js → chunk-62ALWH3T.js} +3 -3
  15. package/dist/{chunk-J3BQHHDZ.js → chunk-6TV6L2DD.js} +4 -4
  16. package/dist/{chunk-4PHOJMZI.js → chunk-6WMNIX2U.js} +35 -2
  17. package/dist/{chunk-4PXHJA5K.js → chunk-7B2OUQON.js} +2 -2
  18. package/dist/{chunk-TD76ORBJ.js → chunk-AJMERXZP.js} +2 -2
  19. package/dist/{chunk-QTDCPMOW.js → chunk-ATS7SYHG.js} +1 -1
  20. package/dist/{chunk-AG2RM3DF.js → chunk-CEQ4Z32M.js} +3 -3
  21. package/dist/{chunk-5TS3KVGI.js → chunk-E77SRVVO.js} +1 -1
  22. package/dist/{chunk-5SJGR3VS.js → chunk-F7WP2U5I.js} +12 -9
  23. package/dist/{chunk-YFPSTG52.js → chunk-FDYMVJFU.js} +5 -5
  24. package/dist/{chunk-IYX53WZY.js → chunk-GAGTEI6B.js} +5 -5
  25. package/dist/{chunk-MB3GOWB3.js → chunk-IVRWRYTH.js} +19 -10
  26. package/dist/{chunk-3DMRQB4Y.js → chunk-JCYGQKER.js} +1 -1
  27. package/dist/{chunk-JHT3CYLT.js → chunk-MOUAM6ZC.js} +1 -1
  28. package/dist/{chunk-Z54FI4VL.js → chunk-NTY5WGRD.js} +2 -2
  29. package/dist/{chunk-5IMXA563.js → chunk-OH3BAUMC.js} +46 -33
  30. package/dist/{chunk-LHU6ZBFB.js → chunk-OHUAAX3O.js} +2 -2
  31. package/dist/{chunk-NQHEEGTH.js → chunk-PVCECFJK.js} +1 -1
  32. package/dist/{chunk-MHRU743Z.js → chunk-Q4TZA4MN.js} +2247 -2155
  33. package/dist/{chunk-4SNEW63T.js → chunk-RUIHNWRV.js} +3 -3
  34. package/dist/{chunk-NDBMDHQ5.js → chunk-RYPD7XWV.js} +5 -5
  35. package/dist/{chunk-FNAP6CCS.js → chunk-UJMCTGV7.js} +2 -2
  36. package/dist/{chunk-JZKNRDKF.js → chunk-WMD77UCY.js} +47 -34
  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 +1115 -651
  48. package/dist/index.d.cts +61 -6
  49. package/dist/index.d.ts +61 -6
  50. package/dist/index.js +326 -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 +524 -235
  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-4SXTORD2.js} +10 -10
  60. package/dist/{orchestrator-POMFVZLB.js → orchestrator-KNOMW5CZ.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
package/dist/index.cjs CHANGED
@@ -1699,6 +1699,12 @@ function normalizeVault(raw) {
1699
1699
  if (typeof raw.posthogPersonalApiKey === "string" && raw.posthogPersonalApiKey.trim()) {
1700
1700
  out.posthogPersonalApiKey = raw.posthogPersonalApiKey.trim();
1701
1701
  }
1702
+ if (typeof raw.posthogAccessToken === "string" && raw.posthogAccessToken.trim()) {
1703
+ out.posthogAccessToken = raw.posthogAccessToken.trim();
1704
+ }
1705
+ if (typeof raw.posthogRefreshToken === "string" && raw.posthogRefreshToken.trim()) {
1706
+ out.posthogRefreshToken = raw.posthogRefreshToken.trim();
1707
+ }
1702
1708
  if (typeof raw.sentryAuthToken === "string" && raw.sentryAuthToken.trim()) {
1703
1709
  out.sentryAuthToken = raw.sentryAuthToken.trim();
1704
1710
  }
@@ -2369,6 +2375,7 @@ __export(app_settings_exports, {
2369
2375
  saveAbleTimeConnection: () => saveAbleTimeConnection,
2370
2376
  saveAppSettings: () => saveAppSettings,
2371
2377
  saveLinearOAuth: () => saveLinearOAuth,
2378
+ savePosthogOAuth: () => savePosthogOAuth,
2372
2379
  selectManagedAccount: () => selectManagedAccount,
2373
2380
  showCostEnabled: () => showCostEnabled,
2374
2381
  slackAppLevelToken: () => slackAppLevelToken,
@@ -2441,7 +2448,7 @@ function toPublicAppSettings(settings) {
2441
2448
  hasAbleTimeOAuth: Boolean(settings.integrations.abletimeRefreshToken?.trim()),
2442
2449
  hasVercelToken: Boolean(settings.integrations.vercelToken?.trim()),
2443
2450
  hasSupabaseToken: Boolean(settings.integrations.supabaseAccessToken?.trim()),
2444
- hasPosthogToken: Boolean(settings.integrations.posthogPersonalApiKey?.trim()),
2451
+ hasPosthogToken: hasPosthogCredentials(settings.integrations),
2445
2452
  hasSentryToken: Boolean(settings.integrations.sentryAuthToken?.trim()),
2446
2453
  hasRemoteAccount: Boolean(settings.integrations.remoteAccountToken?.trim())
2447
2454
  }
@@ -2637,6 +2644,12 @@ function normalizeIntegrations(raw) {
2637
2644
  const key = source.posthogPersonalApiKey.trim();
2638
2645
  if (key) out.posthogPersonalApiKey = key;
2639
2646
  }
2647
+ for (const key of ["posthogAccessToken", "posthogRefreshToken"]) {
2648
+ const token = typeof source[key] === "string" ? source[key].trim() : "";
2649
+ if (token) out[key] = token;
2650
+ }
2651
+ const posthogExp = Number(source.posthogTokenExpiresAt);
2652
+ if (Number.isFinite(posthogExp)) out.posthogTokenExpiresAt = posthogExp;
2640
2653
  if (typeof source.posthogHost === "string") {
2641
2654
  const host = source.posthogHost.trim();
2642
2655
  if (host) out.posthogHost = host;
@@ -3555,8 +3568,26 @@ function disconnectLinearConnection() {
3555
3568
  delete integrations.linearOrganizationName;
3556
3569
  return saveAppSettings({ ...current, integrations });
3557
3570
  }
3571
+ function hasPosthogCredentials(integrations) {
3572
+ return Boolean(
3573
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
3574
+ );
3575
+ }
3558
3576
  function isPosthogConnected(settings = loadAppSettings()) {
3559
- return Boolean(settings.integrations.posthogPersonalApiKey?.trim());
3577
+ return hasPosthogCredentials(settings.integrations);
3578
+ }
3579
+ function savePosthogOAuth(input) {
3580
+ const current = loadAppSettings();
3581
+ const integrations = { ...current.integrations };
3582
+ integrations.posthogAccessToken = input.accessToken.trim();
3583
+ if (input.refreshToken?.trim()) integrations.posthogRefreshToken = input.refreshToken.trim();
3584
+ if (typeof input.expiresIn === "number" && Number.isFinite(input.expiresIn)) {
3585
+ integrations.posthogTokenExpiresAt = Date.now() + Math.max(0, input.expiresIn) * 1e3;
3586
+ }
3587
+ if (input.host?.trim()) integrations.posthogHost = input.host.trim();
3588
+ if (input.viewerName?.trim()) integrations.posthogViewerName = input.viewerName.trim().slice(0, 120);
3589
+ delete integrations.posthogPersonalApiKey;
3590
+ return saveAppSettings({ ...current, integrations });
3560
3591
  }
3561
3592
  function isAbleTimeConnected(settings = loadAppSettings()) {
3562
3593
  return Boolean(
@@ -4007,6 +4038,8 @@ var init_app_settings = __esm({
4007
4038
  "vercelToken",
4008
4039
  "supabaseAccessToken",
4009
4040
  "posthogPersonalApiKey",
4041
+ "posthogAccessToken",
4042
+ "posthogRefreshToken",
4010
4043
  "sentryAuthToken"
4011
4044
  ];
4012
4045
  CLOUD_CONNECT_AGENTS = /* @__PURE__ */ new Set([
@@ -5934,14 +5967,14 @@ function fileMtimeMs(path2) {
5934
5967
  }
5935
5968
  }
5936
5969
  function rememberThread(thread, mtimeMs) {
5937
- const cache2 = cacheForDir();
5938
- cache2.byId.set(thread.id, thread);
5939
- if (mtimeMs != null) cache2.mtimeMs.set(thread.id, mtimeMs);
5970
+ const cache3 = cacheForDir();
5971
+ cache3.byId.set(thread.id, thread);
5972
+ if (mtimeMs != null) cache3.mtimeMs.set(thread.id, mtimeMs);
5940
5973
  }
5941
5974
  function forgetThread(id) {
5942
- const cache2 = cacheForDir();
5943
- cache2.byId.delete(id);
5944
- cache2.mtimeMs.delete(id);
5975
+ const cache3 = cacheForDir();
5976
+ cache3.byId.delete(id);
5977
+ cache3.mtimeMs.delete(id);
5945
5978
  selfWriteMtimes.delete(id);
5946
5979
  }
5947
5980
  function invalidateThreadListCache() {
@@ -5958,9 +5991,9 @@ function readThread(id) {
5958
5991
  forgetThread(id);
5959
5992
  return null;
5960
5993
  }
5961
- const cache2 = cacheForDir();
5962
- const cached2 = cache2.byId.get(id);
5963
- if (cached2 && cache2.mtimeMs.get(id) === mtimeMs) return cached2;
5994
+ const cache3 = cacheForDir();
5995
+ const cached2 = cache3.byId.get(id);
5996
+ if (cached2 && cache3.mtimeMs.get(id) === mtimeMs) return cached2;
5964
5997
  const raw = (0, import_node_fs13.readFileSync)(path2, "utf8");
5965
5998
  const thread = normalizeThread(JSON.parse(raw));
5966
5999
  rememberThread(thread, mtimeMs);
@@ -5989,7 +6022,7 @@ function isThreadRecordFile(nameOrPath) {
5989
6022
  return name.endsWith(".json") && !name.endsWith(".live.json") && !name.endsWith(".setup.log.json");
5990
6023
  }
5991
6024
  function listThreads(opts) {
5992
- const cache2 = cacheForDir();
6025
+ const cache3 = cacheForDir();
5993
6026
  const files = (0, import_node_fs13.readdirSync)(threadsDir()).filter(isThreadRecordFile);
5994
6027
  const seen = /* @__PURE__ */ new Set();
5995
6028
  for (const f of files) {
@@ -6001,10 +6034,10 @@ function listThreads(opts) {
6001
6034
  } catch {
6002
6035
  }
6003
6036
  }
6004
- for (const id of [...cache2.byId.keys()]) {
6037
+ for (const id of [...cache3.byId.keys()]) {
6005
6038
  if (!seen.has(id)) forgetThread(id);
6006
6039
  }
6007
- const threads = [...cache2.byId.values()].sort(
6040
+ const threads = [...cache3.byId.values()].sort(
6008
6041
  (a, b) => b.updatedAt.localeCompare(a.updatedAt)
6009
6042
  );
6010
6043
  if (opts?.includeArchived) return threads;
@@ -13330,7 +13363,7 @@ var init_coordinator_prompt = __esm({
13330
13363
  "- 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.",
13331
13364
  "- 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.",
13332
13365
  "- 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.",
13333
- "- 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.",
13366
+ "- 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.",
13334
13367
  "- get_pr_stack / open_pr_stack_layers / add_stack_layer / create_pr_stack \u2014 GitHub stacked PRs (`gh stack`); one worktree per layer",
13335
13368
  "- list_models \u2014 only when you need a specific model (rare); otherwise omit model so Account defaults apply",
13336
13369
  "- 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.",
@@ -17016,6 +17049,487 @@ ${JSON.stringify(launch)}`;
17016
17049
  }
17017
17050
  });
17018
17051
 
17052
+ // src/agents/claude-usage.ts
17053
+ function parseClaudeResetsAt(value) {
17054
+ if (typeof value === "number" && Number.isFinite(value)) {
17055
+ const ms = value > 1e12 ? value : value * 1e3;
17056
+ const d = new Date(ms);
17057
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
17058
+ }
17059
+ if (typeof value === "string") {
17060
+ const trimmed = value.trim();
17061
+ if (!trimmed) return null;
17062
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
17063
+ return parseClaudeResetsAt(Number(trimmed));
17064
+ }
17065
+ const d = new Date(trimmed);
17066
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
17067
+ }
17068
+ return null;
17069
+ }
17070
+ function parseClaudeUtilization(value) {
17071
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
17072
+ return Math.max(0, Math.min(100, value));
17073
+ }
17074
+ function windowFromRaw(id, raw) {
17075
+ if (!raw || typeof raw !== "object") return null;
17076
+ const row2 = raw;
17077
+ const used = parseClaudeUtilization(row2.utilization ?? row2.used_percentage);
17078
+ if (used == null) return null;
17079
+ const meta = WINDOW_META[id];
17080
+ return {
17081
+ id,
17082
+ label: meta.label,
17083
+ shortLabel: meta.shortLabel,
17084
+ detail: meta.detail,
17085
+ usedPercent: used,
17086
+ remainingPercent: Math.max(0, Math.min(100, 100 - used)),
17087
+ resetsAt: parseClaudeResetsAt(row2.resets_at)
17088
+ };
17089
+ }
17090
+ function extraUsageFromRaw(raw) {
17091
+ if (!raw || typeof raw !== "object") return void 0;
17092
+ const row2 = raw;
17093
+ const enabled = row2.is_enabled === true || row2.enabled === true;
17094
+ if (!enabled && row2.is_enabled !== false && row2.enabled !== false) return void 0;
17095
+ const usedCredits = numberOrUndef(row2.used_credits ?? row2.used);
17096
+ const monthlyLimit = numberOrUndef(row2.monthly_limit);
17097
+ const usedPercent = parseClaudeUtilization(row2.utilization) ?? void 0;
17098
+ return {
17099
+ enabled,
17100
+ ...usedCredits != null ? { usedCredits } : {},
17101
+ ...monthlyLimit != null ? { monthlyLimit } : {},
17102
+ ...usedPercent != null ? { usedPercent } : {}
17103
+ };
17104
+ }
17105
+ function numberOrUndef(value) {
17106
+ if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
17107
+ return value;
17108
+ }
17109
+ function parseClaudeUsagePayload(raw, fetchedAt2 = (/* @__PURE__ */ new Date()).toISOString()) {
17110
+ if (!raw || typeof raw !== "object") return null;
17111
+ const obj = raw;
17112
+ const source = obj.rate_limits && typeof obj.rate_limits === "object" ? obj.rate_limits : obj;
17113
+ const windows = [];
17114
+ for (const id of WINDOW_ORDER) {
17115
+ const parsed = windowFromRaw(id, source[id]);
17116
+ if (parsed) windows.push(parsed);
17117
+ }
17118
+ if (windows.length === 0) return null;
17119
+ const extra = extraUsageFromRaw(obj.extra_usage ?? source.extra_usage);
17120
+ return {
17121
+ windows,
17122
+ ...extra ? { extraUsage: extra } : {},
17123
+ fetchedAt: fetchedAt2
17124
+ };
17125
+ }
17126
+ function hottestClaudeWindow(usage) {
17127
+ if (usage.windows.length === 0) return null;
17128
+ return usage.windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);
17129
+ }
17130
+ function formatClaudeUsageReset(resetsAt, now = /* @__PURE__ */ new Date()) {
17131
+ if (!resetsAt) return "";
17132
+ const at = new Date(resetsAt);
17133
+ if (Number.isNaN(at.getTime())) return "";
17134
+ const ms = at.getTime() - now.getTime();
17135
+ if (ms <= 0) return "resets soon";
17136
+ const minutes = Math.round(ms / 6e4);
17137
+ if (minutes < 60) return `resets in ${Math.max(1, minutes)}m`;
17138
+ const hours = Math.round(minutes / 60);
17139
+ if (hours < 36) return `resets in ${hours}h`;
17140
+ try {
17141
+ return `resets ${at.toLocaleString(void 0, {
17142
+ weekday: "short",
17143
+ hour: "numeric",
17144
+ minute: "2-digit"
17145
+ })}`;
17146
+ } catch {
17147
+ return `resets ${at.toISOString()}`;
17148
+ }
17149
+ }
17150
+ function formatClaudeUsageResetClock(resetsAt) {
17151
+ if (!resetsAt) return "";
17152
+ const at = new Date(resetsAt);
17153
+ if (Number.isNaN(at.getTime())) return "";
17154
+ try {
17155
+ return at.toLocaleString(void 0, {
17156
+ weekday: "short",
17157
+ month: "short",
17158
+ day: "numeric",
17159
+ hour: "numeric",
17160
+ minute: "2-digit"
17161
+ });
17162
+ } catch {
17163
+ return at.toISOString();
17164
+ }
17165
+ }
17166
+ function formatClaudeUsageFetchedAt(fetchedAt2, now = /* @__PURE__ */ new Date()) {
17167
+ const at = new Date(fetchedAt2);
17168
+ if (Number.isNaN(at.getTime())) return "";
17169
+ const minutes = Math.max(0, Math.round((now.getTime() - at.getTime()) / 6e4));
17170
+ if (minutes < 1) return "Updated just now";
17171
+ if (minutes < 60) return `Updated ${minutes}m ago`;
17172
+ const hours = Math.round(minutes / 60);
17173
+ if (hours < 36) return `Updated ${hours}h ago`;
17174
+ return `Updated ${formatClaudeUsageResetClock(fetchedAt2)}`;
17175
+ }
17176
+ function formatClaudeExtraUsageDetail(extra) {
17177
+ if (!extra.enabled) return "Extra usage off";
17178
+ const bits = ["Extra usage on"];
17179
+ if (extra.usedCredits != null && extra.monthlyLimit != null) {
17180
+ bits.push(`${extra.usedCredits} / ${extra.monthlyLimit} credits this month`);
17181
+ } else if (extra.usedCredits != null) {
17182
+ bits.push(`${extra.usedCredits} credits used`);
17183
+ }
17184
+ if (extra.usedPercent != null) {
17185
+ bits.push(`${Math.round(extra.usedPercent)}% of extra pool`);
17186
+ }
17187
+ return bits.join(" \xB7 ");
17188
+ }
17189
+ function formatClaudeUsageWindowLine(window, now = /* @__PURE__ */ new Date()) {
17190
+ const reset = formatClaudeUsageReset(window.resetsAt, now);
17191
+ const clock = formatClaudeUsageResetClock(window.resetsAt);
17192
+ const left = `${Math.round(window.remainingPercent)}% left`;
17193
+ const used = `${Math.round(window.usedPercent)}% used`;
17194
+ const resetBit = reset ? clock && !reset.includes(clock) ? `${reset} (${clock})` : reset : "";
17195
+ return resetBit ? `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used} \xB7 ${resetBit}` : `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used}`;
17196
+ }
17197
+ function formatClaudeUsageTooltip(usage, now = /* @__PURE__ */ new Date()) {
17198
+ const lines = [
17199
+ "Claude Code plan",
17200
+ ...usage.windows.map((w) => formatClaudeUsageWindowLine(w, now))
17201
+ ];
17202
+ if (usage.extraUsage) {
17203
+ lines.push(formatClaudeExtraUsageDetail(usage.extraUsage));
17204
+ }
17205
+ const fetched = formatClaudeUsageFetchedAt(usage.fetchedAt, now);
17206
+ if (fetched) lines.push(fetched);
17207
+ return lines.join("\n");
17208
+ }
17209
+ function formatClaudeUsageCompact(window) {
17210
+ return `${window.shortLabel} ${Math.round(window.remainingPercent)}%`;
17211
+ }
17212
+ function claudeUsageWindowOverLimit(window) {
17213
+ return window.remainingPercent <= 0 || window.usedPercent >= 100;
17214
+ }
17215
+ function claudeUsageOverLimitWindows(usage) {
17216
+ if (!usage) return [];
17217
+ return usage.windows.filter(claudeUsageWindowOverLimit);
17218
+ }
17219
+ function formatOverLimitWindowList(windows, now) {
17220
+ const parts = windows.map((w) => {
17221
+ const reset = formatClaudeUsageReset(w.resetsAt, now);
17222
+ return reset ? `${w.label} (${reset})` : w.label;
17223
+ });
17224
+ return {
17225
+ list: parts.join(", "),
17226
+ verb: windows.length === 1 ? "is" : "are"
17227
+ };
17228
+ }
17229
+ function formatClaudeUsageOverLimitConfirm(windows, now = /* @__PURE__ */ new Date()) {
17230
+ if (windows.length === 0) return "";
17231
+ const { list, verb } = formatOverLimitWindowList(windows, now);
17232
+ return `Claude Code ${list} ${verb} at or over the plan limit. Send this message anyway?`;
17233
+ }
17234
+ function formatClaudeUsageOverLimitWait(windows, now = /* @__PURE__ */ new Date()) {
17235
+ if (windows.length === 0) return "";
17236
+ const { list, verb } = formatOverLimitWindowList(windows, now);
17237
+ return `Claude Code ${list} ${verb} at or over the plan limit. Sending is paused until the window resets.`;
17238
+ }
17239
+ var WINDOW_META, WINDOW_ORDER;
17240
+ var init_claude_usage = __esm({
17241
+ "src/agents/claude-usage.ts"() {
17242
+ "use strict";
17243
+ WINDOW_META = {
17244
+ five_hour: {
17245
+ label: "5-hour session",
17246
+ shortLabel: "5h",
17247
+ detail: "Rolling 5-hour limit across all models"
17248
+ },
17249
+ seven_day: {
17250
+ label: "Weekly",
17251
+ shortLabel: "wk",
17252
+ detail: "7-day cap across all models"
17253
+ },
17254
+ seven_day_opus: {
17255
+ label: "Opus",
17256
+ shortLabel: "Opus",
17257
+ detail: "Weekly Opus-only cap"
17258
+ },
17259
+ seven_day_sonnet: {
17260
+ label: "Sonnet",
17261
+ shortLabel: "Sonnet",
17262
+ detail: "Weekly Sonnet-only cap"
17263
+ }
17264
+ };
17265
+ WINDOW_ORDER = [
17266
+ "five_hour",
17267
+ "seven_day",
17268
+ "seven_day_opus",
17269
+ "seven_day_sonnet"
17270
+ ];
17271
+ }
17272
+ });
17273
+
17274
+ // src/agents/claude-usage-client.ts
17275
+ function usageCacheDir(opts) {
17276
+ return opts.configDir?.trim() || "";
17277
+ }
17278
+ function adoptCacheDir(dir) {
17279
+ if (dir === cacheDirKey) return;
17280
+ cache = null;
17281
+ lastGood = null;
17282
+ errorUntil = 0;
17283
+ inflight = null;
17284
+ cacheDirKey = dir;
17285
+ }
17286
+ function accessTokenFromCredentialsJson(raw) {
17287
+ const trimmed = raw.trim();
17288
+ if (!trimmed) return null;
17289
+ if (trimmed.startsWith("sk-ant-")) {
17290
+ const token = trimmed.split(/\s+/)[0];
17291
+ return token || null;
17292
+ }
17293
+ try {
17294
+ const parsed = JSON.parse(trimmed);
17295
+ const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
17296
+ const token = oauth.accessToken ?? oauth.access_token;
17297
+ return typeof token === "string" && token.trim() ? token.trim() : null;
17298
+ } catch {
17299
+ return null;
17300
+ }
17301
+ }
17302
+ function claudeCredentialsPath(configDir) {
17303
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || (0, import_node_path42.join)((0, import_node_os17.homedir)(), ".claude");
17304
+ return (0, import_node_path42.join)(root, ".credentials.json");
17305
+ }
17306
+ async function readFileAccessToken(configDir) {
17307
+ const path2 = claudeCredentialsPath(configDir);
17308
+ if (!(0, import_node_fs39.existsSync)(path2)) return null;
17309
+ try {
17310
+ return accessTokenFromCredentialsJson((0, import_node_fs39.readFileSync)(path2, "utf8"));
17311
+ } catch {
17312
+ return null;
17313
+ }
17314
+ }
17315
+ async function readKeychainAccessToken(configDir) {
17316
+ if (process.platform !== "darwin") return null;
17317
+ const root = configDir?.trim();
17318
+ const accounts = root ? [root, void 0] : [void 0];
17319
+ for (const service of KEYCHAIN_SERVICES) {
17320
+ for (const account of accounts) {
17321
+ const args = ["find-generic-password", "-s", service, "-w"];
17322
+ if (account) args.splice(3, 0, "-a", account);
17323
+ const result = await run("security", args, {
17324
+ reject: false,
17325
+ timeoutMs: 4e3
17326
+ });
17327
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
17328
+ const token = accessTokenFromCredentialsJson(result.stdout);
17329
+ if (token) return token;
17330
+ }
17331
+ }
17332
+ return null;
17333
+ }
17334
+ async function readClaudeAccessToken(configDir) {
17335
+ const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
17336
+ if (envToken) return envToken;
17337
+ const fromFile = await readFileAccessToken(configDir);
17338
+ if (fromFile) return fromFile;
17339
+ return readKeychainAccessToken(configDir);
17340
+ }
17341
+ async function resolveClaudeUserAgent() {
17342
+ if (claudeVersion) return `claude-code/${claudeVersion}`;
17343
+ try {
17344
+ const claude = resolveClaudeExecutable();
17345
+ const result = await run(claude, ["--version"], { reject: false, timeoutMs: 4e3 });
17346
+ const match = `${result.stdout}
17347
+ ${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
17348
+ claudeVersion = match?.[1] ?? "2.1.80";
17349
+ } catch {
17350
+ claudeVersion = "2.1.80";
17351
+ }
17352
+ return `claude-code/${claudeVersion}`;
17353
+ }
17354
+ function staleOk(now) {
17355
+ if (!lastGood) return null;
17356
+ if (now - lastGood.at > CLAUDE_USAGE_STALE_OK_MS) return null;
17357
+ return lastGood.value;
17358
+ }
17359
+ function reuseLast() {
17360
+ return lastGood?.value ?? null;
17361
+ }
17362
+ async function getClaudePlanUsage(opts = {}) {
17363
+ const now = opts.now ?? Date.now();
17364
+ adoptCacheDir(usageCacheDir(opts));
17365
+ if (now < errorUntil) return reuseLast() ?? staleOk(now);
17366
+ if (!opts.force) {
17367
+ if (cache && now - cache.at < CLAUDE_USAGE_TTL_MS) return cache.value;
17368
+ }
17369
+ if (inflight) return inflight;
17370
+ inflight = (async () => {
17371
+ try {
17372
+ const token = await (opts.readAccessToken ?? (() => readClaudeAccessToken(opts.configDir)))();
17373
+ if (!token) {
17374
+ cache = { at: now, dir: cacheDirKey, value: null };
17375
+ return null;
17376
+ }
17377
+ const fetchFn = opts.fetch ?? httpFetch;
17378
+ const userAgent = opts.userAgent ?? await resolveClaudeUserAgent();
17379
+ const ac = new AbortController();
17380
+ const timer2 = setTimeout(() => ac.abort(), 8e3);
17381
+ let res;
17382
+ try {
17383
+ res = await fetchFn(CLAUDE_OAUTH_USAGE_URL, {
17384
+ headers: {
17385
+ Authorization: `Bearer ${token}`,
17386
+ "anthropic-beta": "oauth-2025-04-20",
17387
+ "User-Agent": userAgent
17388
+ },
17389
+ signal: ac.signal
17390
+ });
17391
+ } finally {
17392
+ clearTimeout(timer2);
17393
+ }
17394
+ if (res.status === 401 || res.status === 403) {
17395
+ cache = { at: now, dir: cacheDirKey, value: null };
17396
+ return null;
17397
+ }
17398
+ if (res.status === 429) {
17399
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
17400
+ const last = reuseLast();
17401
+ if (last) cache = { at: now, dir: cacheDirKey, value: last };
17402
+ return last;
17403
+ }
17404
+ if (!res.ok) {
17405
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
17406
+ return staleOk(now);
17407
+ }
17408
+ const usage = parseClaudeUsagePayload(await res.json(), new Date(now).toISOString());
17409
+ cache = { at: now, dir: cacheDirKey, value: usage };
17410
+ if (usage) lastGood = { at: now, dir: cacheDirKey, value: usage };
17411
+ return usage;
17412
+ } catch {
17413
+ errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
17414
+ return staleOk(now);
17415
+ } finally {
17416
+ inflight = null;
17417
+ }
17418
+ })();
17419
+ return inflight;
17420
+ }
17421
+ var import_node_fs39, import_node_os17, import_node_path42, CLAUDE_OAUTH_USAGE_URL, CLAUDE_USAGE_TTL_MS, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS, KEYCHAIN_SERVICES, cache, errorUntil, inflight, lastGood, claudeVersion, cacheDirKey;
17422
+ var init_claude_usage_client = __esm({
17423
+ "src/agents/claude-usage-client.ts"() {
17424
+ "use strict";
17425
+ import_node_fs39 = require("fs");
17426
+ import_node_os17 = require("os");
17427
+ import_node_path42 = require("path");
17428
+ init_run();
17429
+ init_fetch();
17430
+ init_app_settings();
17431
+ init_claude_usage();
17432
+ CLAUDE_OAUTH_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
17433
+ CLAUDE_USAGE_TTL_MS = 9e4;
17434
+ CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
17435
+ CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
17436
+ KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
17437
+ cache = null;
17438
+ errorUntil = 0;
17439
+ inflight = null;
17440
+ lastGood = null;
17441
+ claudeVersion = null;
17442
+ cacheDirKey = "";
17443
+ }
17444
+ });
17445
+
17446
+ // src/agents/claude-posthog-connector.ts
17447
+ function asRecord5(value) {
17448
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
17449
+ return value;
17450
+ }
17451
+ function rowsFrom(body) {
17452
+ if (Array.isArray(body)) {
17453
+ return body.filter((row2) => asRecord5(row2) !== null);
17454
+ }
17455
+ const record = asRecord5(body);
17456
+ const data = record?.data;
17457
+ if (!Array.isArray(data)) return [];
17458
+ return data.filter((row2) => asRecord5(row2) !== null);
17459
+ }
17460
+ function isPosthogName(value) {
17461
+ if (typeof value !== "string") return false;
17462
+ const head = value.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
17463
+ return head === "posthog";
17464
+ }
17465
+ function rowId(row2) {
17466
+ const id = row2.id;
17467
+ return typeof id === "string" && ID_RE.test(id) ? id : null;
17468
+ }
17469
+ function posthogConnectorFromList(body) {
17470
+ const matches = rowsFrom(body).filter(
17471
+ (row3) => row3.eligible !== false && rowId(row3) !== null && (isPosthogName(row3.display_name) || isPosthogName(row3.displayName) || isPosthogName(row3.name))
17472
+ );
17473
+ const row2 = matches.find((item) => item.additional_install !== true && item.additionalInstall !== true) ?? matches[0];
17474
+ const id = row2 ? rowId(row2) : null;
17475
+ if (!id) return null;
17476
+ return {
17477
+ type: "claudeai-proxy",
17478
+ id,
17479
+ url: `${PROXY_ORIGIN}/v1/mcp/${id}`,
17480
+ displayName: "PostHog",
17481
+ alwaysLoad: true
17482
+ };
17483
+ }
17484
+ async function loadClaudePosthogConnector(now = Date.now()) {
17485
+ if (cache2 && now - cache2.at < (cache2.value ? SUCCESS_TTL_MS : MISS_TTL_MS)) return cache2.value;
17486
+ const token = await readClaudeAccessToken();
17487
+ if (!token) {
17488
+ cache2 = { at: now, value: null };
17489
+ return null;
17490
+ }
17491
+ try {
17492
+ const res = await httpFetch(LIST_URL, {
17493
+ headers: {
17494
+ Authorization: `Bearer ${token}`,
17495
+ "anthropic-version": "2023-06-01",
17496
+ "anthropic-beta": "mcp-servers-2025-12-04"
17497
+ },
17498
+ signal: AbortSignal.timeout(4e3)
17499
+ });
17500
+ if (!res.ok) {
17501
+ cache2 = { at: now, value: null };
17502
+ return null;
17503
+ }
17504
+ const value = posthogConnectorFromList(await res.json());
17505
+ cache2 = { at: now, value };
17506
+ return value;
17507
+ } catch {
17508
+ cache2 = { at: now, value: null };
17509
+ return null;
17510
+ }
17511
+ }
17512
+ async function claudePosthogConnectorForTurn() {
17513
+ if (turnOverride) return turnOverride();
17514
+ if (process.env.VITEST) return null;
17515
+ return loadClaudePosthogConnector();
17516
+ }
17517
+ var CLAUDE_POSTHOG_CONNECTOR_SERVER, LIST_URL, PROXY_ORIGIN, ID_RE, SUCCESS_TTL_MS, MISS_TTL_MS, cache2, turnOverride;
17518
+ var init_claude_posthog_connector = __esm({
17519
+ "src/agents/claude-posthog-connector.ts"() {
17520
+ "use strict";
17521
+ init_fetch();
17522
+ init_claude_usage_client();
17523
+ CLAUDE_POSTHOG_CONNECTOR_SERVER = "claude.ai PostHog";
17524
+ LIST_URL = "https://api.anthropic.com/v1/mcp_servers?limit=1000&include_additional_installs=true";
17525
+ PROXY_ORIGIN = "https://mcp-proxy.anthropic.com";
17526
+ ID_RE = /^[A-Za-z0-9_-]+$/;
17527
+ SUCCESS_TTL_MS = 5 * 6e4;
17528
+ MISS_TTL_MS = 3e4;
17529
+ cache2 = null;
17530
+ }
17531
+ });
17532
+
17019
17533
  // src/agents/types.ts
17020
17534
  function planModeTurnInstruction(planMode) {
17021
17535
  return planMode ? PLAN_MODE_INSTRUCTION : PLAN_MODE_OFF_INSTRUCTION;
@@ -17068,10 +17582,10 @@ var init_types = __esm({
17068
17582
 
17069
17583
  // src/agent-rpc/metadata.ts
17070
17584
  function agentRuntimeMetadataPath() {
17071
- return (0, import_node_path42.join)(appDataDir(), "agent-runtime.json");
17585
+ return (0, import_node_path43.join)(appDataDir(), "agent-runtime.json");
17072
17586
  }
17073
17587
  function writeAgentRuntimeMetadata(meta) {
17074
- (0, import_node_fs39.writeFileSync)(agentRuntimeMetadataPath(), `${JSON.stringify(meta)}
17588
+ (0, import_node_fs40.writeFileSync)(agentRuntimeMetadataPath(), `${JSON.stringify(meta)}
17075
17589
  `, {
17076
17590
  encoding: "utf8",
17077
17591
  mode: 384
@@ -17079,7 +17593,7 @@ function writeAgentRuntimeMetadata(meta) {
17079
17593
  }
17080
17594
  function readAgentRuntimeMetadata() {
17081
17595
  try {
17082
- const raw = JSON.parse((0, import_node_fs39.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
17596
+ const raw = JSON.parse((0, import_node_fs40.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
17083
17597
  if (!raw || typeof raw !== "object") return null;
17084
17598
  const rec = raw;
17085
17599
  if (typeof rec.runtimeId !== "string" || !rec.runtimeId.trim()) return null;
@@ -17127,7 +17641,7 @@ function clearAgentRuntimeMetadataIfOwned(pid = process.pid) {
17127
17641
  const current = readAgentRuntimeMetadata();
17128
17642
  if (!current || current.pid !== pid) return;
17129
17643
  try {
17130
- (0, import_node_fs39.unlinkSync)(agentRuntimeMetadataPath());
17644
+ (0, import_node_fs40.unlinkSync)(agentRuntimeMetadataPath());
17131
17645
  } catch {
17132
17646
  }
17133
17647
  }
@@ -17135,12 +17649,12 @@ function agentRuntimeLooksLive(meta = readAgentRuntimeMetadata()) {
17135
17649
  if (!meta) return false;
17136
17650
  return pidAlive2(meta.pid);
17137
17651
  }
17138
- var import_node_fs39, import_node_path42;
17652
+ var import_node_fs40, import_node_path43;
17139
17653
  var init_metadata = __esm({
17140
17654
  "src/agent-rpc/metadata.ts"() {
17141
17655
  "use strict";
17142
- import_node_fs39 = require("fs");
17143
- import_node_path42 = require("path");
17656
+ import_node_fs40 = require("fs");
17657
+ import_node_path43 = require("path");
17144
17658
  init_paths();
17145
17659
  init_protocol2();
17146
17660
  }
@@ -17210,11 +17724,11 @@ function entryDir() {
17210
17724
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
17211
17725
  if (cjsDir) return cjsDir;
17212
17726
  try {
17213
- return (0, import_node_path43.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
17727
+ return (0, import_node_path44.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
17214
17728
  } catch {
17215
17729
  try {
17216
17730
  const req = (0, import_node_module2.createRequire)(process.cwd() + "/");
17217
- return (0, import_node_path43.dirname)(req.resolve("@sideboard-ai/core"));
17731
+ return (0, import_node_path44.dirname)(req.resolve("@sideboard-ai/core"));
17218
17732
  } catch {
17219
17733
  return process.cwd();
17220
17734
  }
@@ -17223,20 +17737,20 @@ function entryDir() {
17223
17737
  function claudeRunnerPath() {
17224
17738
  const packagedDir = packagedCursorRuntimeDir();
17225
17739
  if (packagedDir) {
17226
- const packaged = (0, import_node_path43.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
17227
- if ((0, import_node_fs40.existsSync)(packaged)) return packaged;
17740
+ const packaged = (0, import_node_path44.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
17741
+ if ((0, import_node_fs41.existsSync)(packaged)) return packaged;
17228
17742
  }
17229
17743
  const root = entryDir();
17230
17744
  const candidates = [
17231
- (0, import_node_path43.join)(root, "agents", "claude-runner.js"),
17232
- (0, import_node_path43.join)(root, "agents", "claude-runner.cjs"),
17233
- (0, import_node_path43.join)(root, "dist", "agents", "claude-runner.js"),
17234
- (0, import_node_path43.join)(root, "dist", "agents", "claude-runner.cjs"),
17235
- (0, import_node_path43.join)(root, "claude-runner.ts"),
17236
- (0, import_node_path43.join)(root, "src", "agents", "claude-runner.ts")
17745
+ (0, import_node_path44.join)(root, "agents", "claude-runner.js"),
17746
+ (0, import_node_path44.join)(root, "agents", "claude-runner.cjs"),
17747
+ (0, import_node_path44.join)(root, "dist", "agents", "claude-runner.js"),
17748
+ (0, import_node_path44.join)(root, "dist", "agents", "claude-runner.cjs"),
17749
+ (0, import_node_path44.join)(root, "claude-runner.ts"),
17750
+ (0, import_node_path44.join)(root, "src", "agents", "claude-runner.ts")
17237
17751
  ];
17238
17752
  for (const candidate of candidates) {
17239
- if ((0, import_node_fs40.existsSync)(candidate)) return candidate;
17753
+ if ((0, import_node_fs41.existsSync)(candidate)) return candidate;
17240
17754
  }
17241
17755
  return candidates[0];
17242
17756
  }
@@ -17260,13 +17774,13 @@ async function buildClaudeRpcTurnCommand(req) {
17260
17774
  }
17261
17775
  };
17262
17776
  }
17263
- var import_node_fs40, import_node_module2, import_node_path43, import_node_url2, import_meta5;
17777
+ var import_node_fs41, import_node_module2, import_node_path44, import_node_url2, import_meta5;
17264
17778
  var init_claude_host = __esm({
17265
17779
  "src/agents/claude-host.ts"() {
17266
17780
  "use strict";
17267
- import_node_fs40 = require("fs");
17781
+ import_node_fs41 = require("fs");
17268
17782
  import_node_module2 = require("module");
17269
- import_node_path43 = require("path");
17783
+ import_node_path44 = require("path");
17270
17784
  import_node_url2 = require("url");
17271
17785
  init_protocol2();
17272
17786
  init_pilot_tools();
@@ -17358,11 +17872,11 @@ function issueAttachmentWorktreePath(repoPath) {
17358
17872
  return raw || process.cwd();
17359
17873
  }
17360
17874
  function ensureIssueAttachmentsDir(worktreePath) {
17361
- const dir = (0, import_node_path44.join)(worktreePath, ATTACHMENTS_DIR);
17362
- (0, import_node_fs41.mkdirSync)(dir, { recursive: true });
17363
- const gi = (0, import_node_path44.join)(dir, ".gitignore");
17364
- if (!(0, import_node_fs41.existsSync)(gi)) {
17365
- (0, import_node_fs41.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
17875
+ const dir = (0, import_node_path45.join)(worktreePath, ATTACHMENTS_DIR);
17876
+ (0, import_node_fs42.mkdirSync)(dir, { recursive: true });
17877
+ const gi = (0, import_node_path45.join)(dir, ".gitignore");
17878
+ if (!(0, import_node_fs42.existsSync)(gi)) {
17879
+ (0, import_node_fs42.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
17366
17880
  }
17367
17881
  return dir;
17368
17882
  }
@@ -17392,7 +17906,7 @@ function looksLikeFileUrl(url) {
17392
17906
  function filenameFromUrl(url, fallback = "attachment") {
17393
17907
  try {
17394
17908
  const parsed = new URL(url);
17395
- const last = decodeURIComponent((0, import_node_path44.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
17909
+ const last = decodeURIComponent((0, import_node_path45.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
17396
17910
  if (last && last !== "/" && last !== ".") return last;
17397
17911
  } catch {
17398
17912
  }
@@ -17414,12 +17928,12 @@ function filenameFromContentDisposition(header2) {
17414
17928
  }
17415
17929
  function uniqueAttachmentFileName(dir, originalName) {
17416
17930
  const safe = originalName.replace(/[/\\]/g, "_").replace(/^\.+/, "") || "file";
17417
- if (!(0, import_node_fs41.existsSync)((0, import_node_path44.join)(dir, safe))) return safe;
17418
- const ext = (0, import_node_path44.extname)(safe);
17931
+ if (!(0, import_node_fs42.existsSync)((0, import_node_path45.join)(dir, safe))) return safe;
17932
+ const ext = (0, import_node_path45.extname)(safe);
17419
17933
  const stem = ext ? safe.slice(0, -ext.length) : safe;
17420
17934
  for (let i = 1; i < 1e4; i++) {
17421
17935
  const candidate = `${stem}-${i}${ext}`;
17422
- if (!(0, import_node_fs41.existsSync)((0, import_node_path44.join)(dir, candidate))) return candidate;
17936
+ if (!(0, import_node_fs42.existsSync)((0, import_node_path45.join)(dir, candidate))) return candidate;
17423
17937
  }
17424
17938
  return `${stem}-${(0, import_node_crypto14.randomUUID)()}${ext}`;
17425
17939
  }
@@ -17467,7 +17981,7 @@ function mergeIssueAttachments(items) {
17467
17981
  return out;
17468
17982
  }
17469
17983
  function extensionForContentType(contentType, name) {
17470
- if ((0, import_node_path44.extname)(name)) return name;
17984
+ if ((0, import_node_path45.extname)(name)) return name;
17471
17985
  const mime = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
17472
17986
  const ext = EXT_BY_MIME[mime];
17473
17987
  return ext ? `${name}${ext}` : name;
@@ -17519,7 +18033,7 @@ async function downloadAuthenticatedFile(opts) {
17519
18033
  const dir = ensureIssueAttachmentsDir(opts.worktreePath);
17520
18034
  const hinted = opts.name?.trim() || filenameFromContentDisposition(res.headers.get("content-disposition")) || filenameFromUrl(url);
17521
18035
  const name = uniqueAttachmentFileName(dir, extensionForContentType(contentType, hinted));
17522
- (0, import_node_fs41.writeFileSync)((0, import_node_path44.join)(dir, name), buf);
18036
+ (0, import_node_fs42.writeFileSync)((0, import_node_path45.join)(dir, name), buf);
17523
18037
  return {
17524
18038
  name,
17525
18039
  path: `${ATTACHMENTS_DIR}/${name}`,
@@ -17527,12 +18041,12 @@ async function downloadAuthenticatedFile(opts) {
17527
18041
  ...contentType ? { contentType } : {}
17528
18042
  };
17529
18043
  }
17530
- var import_node_fs41, import_node_path44, import_node_crypto14, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
18044
+ var import_node_fs42, import_node_path45, import_node_crypto14, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
17531
18045
  var init_issue_attachments = __esm({
17532
18046
  "src/integrations/issue-attachments.ts"() {
17533
18047
  "use strict";
17534
- import_node_fs41 = require("fs");
17535
- import_node_path44 = require("path");
18048
+ import_node_fs42 = require("fs");
18049
+ import_node_path45 = require("path");
17536
18050
  import_node_crypto14 = require("crypto");
17537
18051
  init_fetch();
17538
18052
  init_workspace_scratch();
@@ -19359,17 +19873,18 @@ function compactMetadataFromClaude(obj) {
19359
19873
  const postTokens = typeof post === "number" && Number.isFinite(post) && post > 0 ? Math.round(post) : void 0;
19360
19874
  return { trigger, postTokens };
19361
19875
  }
19362
- var import_node_fs42, import_node_path45, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
19876
+ var import_node_fs43, import_node_path46, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
19363
19877
  var init_claude = __esm({
19364
19878
  "src/agents/claude.ts"() {
19365
19879
  "use strict";
19366
- import_node_fs42 = require("fs");
19367
- import_node_path45 = require("path");
19880
+ import_node_fs43 = require("fs");
19881
+ import_node_path46 = require("path");
19368
19882
  init_run();
19369
19883
  init_app_settings();
19370
19884
  init_claude_mcp_status();
19371
19885
  init_claude_mcp();
19372
19886
  init_host();
19887
+ init_claude_posthog_connector();
19373
19888
  init_error_detail();
19374
19889
  init_message_parts();
19375
19890
  init_injected_mcp();
@@ -19383,7 +19898,7 @@ var init_claude = __esm({
19383
19898
  async detect() {
19384
19899
  const claude = resolveClaudeExecutable();
19385
19900
  if (claude !== "claude") {
19386
- if (!(0, import_node_fs42.existsSync)(claude)) {
19901
+ if (!(0, import_node_fs43.existsSync)(claude)) {
19387
19902
  return {
19388
19903
  agent: "claude",
19389
19904
  installed: false,
@@ -19424,7 +19939,7 @@ var init_claude = __esm({
19424
19939
  const claude = resolveClaudeExecutable();
19425
19940
  const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
19426
19941
  const effective = dropCachedPrefixOnResume(input, sessionId);
19427
- const { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
19942
+ let { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
19428
19943
  const useStdin = promptText.length > CLAUDE_PROMPT_ARG_MAX;
19429
19944
  if (process.env.SIDEBOARD_DEBUG_CLAUDE_TURN === "1") {
19430
19945
  console.error(
@@ -19447,6 +19962,15 @@ var init_claude = __esm({
19447
19962
  const injectedBrightsyNames = injectedServers.filter((s) => s.name === "brightsy" || s.name.startsWith("brightsy_")).map((s) => s.name);
19448
19963
  const chromeOn = claudeChromeEnabled();
19449
19964
  const userMcpEntries = await proxyClaudeUserMcp(isOrchestrator, [thread.repoPath, thread.worktreePath]);
19965
+ const posthogConnector = !isOrchestrator && !isPosthogConnected() ? await claudePosthogConnectorForTurn() : null;
19966
+ if (posthogConnector && !Object.prototype.hasOwnProperty.call(userMcpEntries, CLAUDE_POSTHOG_CONNECTOR_SERVER)) {
19967
+ userMcpEntries[CLAUDE_POSTHOG_CONNECTOR_SERVER] = { ...posthogConnector };
19968
+ 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.";
19969
+ systemPrompt = systemPrompt ? `${systemPrompt}
19970
+
19971
+ ${hint}` : hint;
19972
+ }
19973
+ const isolateClaudeAiMcp = isOrchestrator || isLocalDevAppDataDir() && !posthogConnector;
19450
19974
  let allowedTools;
19451
19975
  if (isOrchestrator) {
19452
19976
  allowedTools = [
@@ -19487,7 +20011,7 @@ var init_claude = __esm({
19487
20011
  mcpServers: mcpServersRecord(injectedServers, userMcpEntries),
19488
20012
  allowedTools: withClaudePilotRpcTools(allowedTools),
19489
20013
  agentRpc: rpc,
19490
- isolateClaudeAiMcp: isOrchestrator || isLocalDevAppDataDir()
20014
+ isolateClaudeAiMcp
19491
20015
  });
19492
20016
  }
19493
20017
  const args = [
@@ -19532,18 +20056,19 @@ var init_claude = __esm({
19532
20056
  cwd: thread.worktreePath,
19533
20057
  stdin: useStdin ? `${promptText}
19534
20058
  ` : void 0,
19535
- ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path45.dirname)(mcpConfigPath)] } : {},
20059
+ ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path46.dirname)(mcpConfigPath)] } : {},
19536
20060
  // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
19537
20061
  // Raise the -p background-agent wait so long TaskOutput polls are not
19538
20062
  // abandoned at Claude Code’s 10-minute default.
19539
20063
  env: {
19540
20064
  CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
19541
20065
  CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? String(CLAUDE_PRINT_BG_WAIT_CEILING_MS),
19542
- // `--strict-mcp-config` still fetches claude.ai connectors on some CLI
19543
- // builds (anthropics/claude-code#60252). Coordinators never need them.
19544
- // Local `pnpm dev` also disables them: those HTTP connectors hang the
19545
- // first worktree turn when Electron's cwd is this Sideboard repo.
19546
- ...isOrchestrator || isLocalDevAppDataDir() ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
20066
+ // Current Claude Code does not fetch claude.ai connectors under
20067
+ // `--strict-mcp-config`. The env is the off switch for older builds
20068
+ // that still fetched the whole account list, and it also refuses an
20069
+ // explicit claudeai-proxy. Orchestrators always set it. Local dev sets
20070
+ // it only when this turn is not passing the PostHog connector.
20071
+ ...isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
19547
20072
  }
19548
20073
  };
19549
20074
  },
@@ -19711,7 +20236,7 @@ async function listCodexModels() {
19711
20236
  if (codex === "codex") {
19712
20237
  const which = await run("which", ["codex"], { reject: false });
19713
20238
  if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
19714
- } else if (!(0, import_node_fs43.existsSync)(codex)) {
20239
+ } else if (!(0, import_node_fs44.existsSync)(codex)) {
19715
20240
  return FALLBACK_CODEX_MODELS;
19716
20241
  }
19717
20242
  const listed = await run(codex, ["debug", "models"], { reject: false });
@@ -19748,7 +20273,7 @@ function usageFromCodex(usage, asContext = false) {
19748
20273
  return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
19749
20274
  }
19750
20275
  function codexHomeDir() {
19751
- return process.env.CODEX_HOME?.trim() || (0, import_node_path46.join)((0, import_node_os17.homedir)(), ".codex");
20276
+ return process.env.CODEX_HOME?.trim() || (0, import_node_path47.join)((0, import_node_os18.homedir)(), ".codex");
19752
20277
  }
19753
20278
  function unwrapCodexMcpResult(result) {
19754
20279
  if (result == null) return void 0;
@@ -19770,28 +20295,28 @@ function unwrapCodexMcpResult(result) {
19770
20295
  return String(result);
19771
20296
  }
19772
20297
  }
19773
- function asRecord5(value) {
20298
+ function asRecord6(value) {
19774
20299
  if (value && typeof value === "object" && !Array.isArray(value)) {
19775
20300
  return value;
19776
20301
  }
19777
20302
  return void 0;
19778
20303
  }
19779
20304
  function codexLooksAuthenticated() {
19780
- const authPath = (0, import_node_path46.join)(codexHomeDir(), "auth.json");
19781
- if (!(0, import_node_fs43.existsSync)(authPath)) return false;
20305
+ const authPath = (0, import_node_path47.join)(codexHomeDir(), "auth.json");
20306
+ if (!(0, import_node_fs44.existsSync)(authPath)) return false;
19782
20307
  try {
19783
- return (0, import_node_fs43.statSync)(authPath).size > 2;
20308
+ return (0, import_node_fs44.statSync)(authPath).size > 2;
19784
20309
  } catch {
19785
20310
  return false;
19786
20311
  }
19787
20312
  }
19788
- var import_node_fs43, import_node_os17, import_node_path46, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
20313
+ var import_node_fs44, import_node_os18, import_node_path47, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
19789
20314
  var init_codex = __esm({
19790
20315
  "src/agents/codex.ts"() {
19791
20316
  "use strict";
19792
- import_node_fs43 = require("fs");
19793
- import_node_os17 = require("os");
19794
- import_node_path46 = require("path");
20317
+ import_node_fs44 = require("fs");
20318
+ import_node_os18 = require("os");
20319
+ import_node_path47 = require("path");
19795
20320
  init_run();
19796
20321
  init_app_settings();
19797
20322
  init_global_workspace();
@@ -19820,7 +20345,7 @@ var init_codex = __esm({
19820
20345
  async detect() {
19821
20346
  const codex = resolveAgentExecutable("codex");
19822
20347
  if (codex !== "codex") {
19823
- if (!(0, import_node_fs43.existsSync)(codex)) {
20348
+ if (!(0, import_node_fs44.existsSync)(codex)) {
19824
20349
  return {
19825
20350
  agent: "codex",
19826
20351
  installed: false,
@@ -19852,7 +20377,7 @@ var init_codex = __esm({
19852
20377
  authenticated,
19853
20378
  linearMcp,
19854
20379
  warnings,
19855
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path46.join)(codexHomeDir(), "auth.json")})`
20380
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path47.join)(codexHomeDir(), "auth.json")})`
19856
20381
  };
19857
20382
  },
19858
20383
  async buildTurn(thread, input) {
@@ -19960,7 +20485,7 @@ var init_codex = __esm({
19960
20485
  }
19961
20486
  if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
19962
20487
  const name = `mcp__${item.server}__${item.tool}`;
19963
- const input = asRecord5(item.arguments);
20488
+ const input = asRecord6(item.arguments);
19964
20489
  const events = [
19965
20490
  { type: "tool_use", id: item.id, name, input }
19966
20491
  ];
@@ -20084,18 +20609,18 @@ var init_codex = __esm({
20084
20609
  // src/agents/cursor-sdk-resolve.ts
20085
20610
  function thisModuleFile() {
20086
20611
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
20087
- if (cjsDir) return (0, import_node_path47.join)(cjsDir, "cursor-sdk-resolve.js");
20612
+ if (cjsDir) return (0, import_node_path48.join)(cjsDir, "cursor-sdk-resolve.js");
20088
20613
  try {
20089
20614
  return (0, import_node_url3.fileURLToPath)(import_meta6.url);
20090
20615
  } catch {
20091
- return (0, import_node_path47.join)(process.cwd(), "package.json");
20616
+ return (0, import_node_path48.join)(process.cwd(), "package.json");
20092
20617
  }
20093
20618
  }
20094
20619
  function packageRootLooksLikeSdk(dir) {
20095
20620
  try {
20096
- const raw = (0, import_node_fs44.readFileSync)((0, import_node_path47.join)(dir, "package.json"), "utf8");
20621
+ const raw = (0, import_node_fs45.readFileSync)((0, import_node_path48.join)(dir, "package.json"), "utf8");
20097
20622
  const pkg = JSON.parse(raw);
20098
- return pkg.name === "@cursor/sdk" && (0, import_node_fs44.existsSync)(dir);
20623
+ return pkg.name === "@cursor/sdk" && (0, import_node_fs45.existsSync)(dir);
20099
20624
  } catch {
20100
20625
  return false;
20101
20626
  }
@@ -20104,7 +20629,7 @@ function resolvedPackageRoot(fromFile) {
20104
20629
  try {
20105
20630
  const req = (0, import_node_module3.createRequire)(fromFile);
20106
20631
  const pkgJson = req.resolve("@cursor/sdk/package.json");
20107
- const root = (0, import_node_path47.dirname)(pkgJson);
20632
+ const root = (0, import_node_path48.dirname)(pkgJson);
20108
20633
  return packageRootLooksLikeSdk(root) ? root : null;
20109
20634
  } catch {
20110
20635
  return null;
@@ -20118,10 +20643,10 @@ function resolveCursorSdkRoot(opts) {
20118
20643
  }
20119
20644
  const globalNm = npmGlobalNodeModules(env);
20120
20645
  if (globalNm) {
20121
- const globalRoot = (0, import_node_path47.join)(globalNm, "@cursor/sdk");
20646
+ const globalRoot = (0, import_node_path48.join)(globalNm, "@cursor/sdk");
20122
20647
  if (packageRootLooksLikeSdk(globalRoot)) return globalRoot;
20123
20648
  }
20124
- const cwdPkg = (0, import_node_path47.join)(process.cwd(), "package.json");
20649
+ const cwdPkg = (0, import_node_path48.join)(process.cwd(), "package.json");
20125
20650
  return resolvedPackageRoot(thisModuleFile()) ?? resolvedPackageRoot(cwdPkg);
20126
20651
  }
20127
20652
  function isCursorSdkInstalled(opts) {
@@ -20137,13 +20662,13 @@ function exportTarget(value) {
20137
20662
  }
20138
20663
  function cursorSdkEsmEntry(root) {
20139
20664
  try {
20140
- const pkg = JSON.parse((0, import_node_fs44.readFileSync)((0, import_node_path47.join)(root, "package.json"), "utf8"));
20665
+ const pkg = JSON.parse((0, import_node_fs45.readFileSync)((0, import_node_path48.join)(root, "package.json"), "utf8"));
20141
20666
  const exp = pkg.exports;
20142
20667
  const dot = exp && typeof exp === "object" && !Array.isArray(exp) && "." in exp ? exp["."] : exp;
20143
20668
  const rel = exportTarget(dot) ?? (typeof pkg.module === "string" ? pkg.module : null);
20144
20669
  if (!rel) return null;
20145
- const entry = (0, import_node_path47.join)(root, rel);
20146
- return (0, import_node_fs44.existsSync)(entry) ? entry : null;
20670
+ const entry = (0, import_node_path48.join)(root, rel);
20671
+ return (0, import_node_fs45.existsSync)(entry) ? entry : null;
20147
20672
  } catch {
20148
20673
  return null;
20149
20674
  }
@@ -20159,7 +20684,7 @@ async function importCursorSdk(opts) {
20159
20684
  try {
20160
20685
  let entry = cursorSdkEsmEntry(root);
20161
20686
  if (!entry) {
20162
- const req = (0, import_node_module3.createRequire)((0, import_node_path47.join)(root, "package.json"));
20687
+ const req = (0, import_node_module3.createRequire)((0, import_node_path48.join)(root, "package.json"));
20163
20688
  entry = req.resolve("@cursor/sdk");
20164
20689
  }
20165
20690
  return unwrapCursorSdkModule(await import((0, import_node_url3.pathToFileURL)(entry).href));
@@ -20171,8 +20696,8 @@ function cursorSdkPlatformRipgrepPackage() {
20171
20696
  return `@cursor/sdk-${process.platform}-${process.arch}`;
20172
20697
  }
20173
20698
  function nodeModulesDirForPackageRoot(packageRoot) {
20174
- const parent = (0, import_node_path47.dirname)(packageRoot);
20175
- return (0, import_node_path47.basename)(parent).startsWith("@") ? (0, import_node_path47.dirname)(parent) : parent;
20699
+ const parent = (0, import_node_path48.dirname)(packageRoot);
20700
+ return (0, import_node_path48.basename)(parent).startsWith("@") ? (0, import_node_path48.dirname)(parent) : parent;
20176
20701
  }
20177
20702
  function cursorSdkRipgrepCandidate(opts) {
20178
20703
  const root = resolveCursorSdkRoot(opts);
@@ -20180,18 +20705,18 @@ function cursorSdkRipgrepCandidate(opts) {
20180
20705
  const nm = nodeModulesDirForPackageRoot(root);
20181
20706
  const pkg = cursorSdkPlatformRipgrepPackage();
20182
20707
  const bin = process.platform === "win32" ? "rg.exe" : "rg";
20183
- const sibling = (0, import_node_path47.join)(nm, pkg, "bin", bin);
20184
- if ((0, import_node_fs44.existsSync)(sibling)) return sibling;
20185
- const nested = (0, import_node_path47.join)(root, "node_modules", pkg, "bin", bin);
20186
- return (0, import_node_fs44.existsSync)(nested) ? nested : null;
20708
+ const sibling = (0, import_node_path48.join)(nm, pkg, "bin", bin);
20709
+ if ((0, import_node_fs45.existsSync)(sibling)) return sibling;
20710
+ const nested = (0, import_node_path48.join)(root, "node_modules", pkg, "bin", bin);
20711
+ return (0, import_node_fs45.existsSync)(nested) ? nested : null;
20187
20712
  }
20188
- var import_node_fs44, import_node_module3, import_node_path47, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
20713
+ var import_node_fs45, import_node_module3, import_node_path48, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
20189
20714
  var init_cursor_sdk_resolve = __esm({
20190
20715
  "src/agents/cursor-sdk-resolve.ts"() {
20191
20716
  "use strict";
20192
- import_node_fs44 = require("fs");
20717
+ import_node_fs45 = require("fs");
20193
20718
  import_node_module3 = require("module");
20194
- import_node_path47 = require("path");
20719
+ import_node_path48 = require("path");
20195
20720
  import_node_url3 = require("url");
20196
20721
  init_path();
20197
20722
  import_meta6 = {};
@@ -20244,20 +20769,20 @@ function turnCostUsdFromCursorUsage(before, after) {
20244
20769
  if (!(delta >= 0) || !Number.isFinite(delta)) return void 0;
20245
20770
  return delta / 100;
20246
20771
  }
20247
- function asRecord6(value) {
20772
+ function asRecord7(value) {
20248
20773
  if (value && typeof value === "object" && !Array.isArray(value)) {
20249
20774
  return value;
20250
20775
  }
20251
20776
  return void 0;
20252
20777
  }
20253
20778
  function normalizeCursorToolCall(name, args) {
20254
- const raw = asRecord6(args);
20779
+ const raw = asRecord7(args);
20255
20780
  const toolName = typeof raw?.toolName === "string" && raw.toolName.trim() ? raw.toolName.trim() : null;
20256
- const looksLikeMcp = name === "mcp" || toolName != null && (typeof raw?.providerIdentifier === "string" || asRecord6(raw?.args) != null);
20781
+ const looksLikeMcp = name === "mcp" || toolName != null && (typeof raw?.providerIdentifier === "string" || asRecord7(raw?.args) != null);
20257
20782
  if (looksLikeMcp && toolName) {
20258
20783
  const providerRaw = typeof raw.providerIdentifier === "string" && raw.providerIdentifier.trim() ? raw.providerIdentifier.trim() : "sideboard";
20259
20784
  const provider = providerRaw.replace(/[^a-zA-Z0-9_-]/g, "_");
20260
- const nested = asRecord6(raw.args);
20785
+ const nested = asRecord7(raw.args);
20261
20786
  return {
20262
20787
  name: `mcp__${provider}__${toolName}`,
20263
20788
  input: nested ?? { toolName }
@@ -20268,7 +20793,7 @@ function normalizeCursorToolCall(name, args) {
20268
20793
  function unwrapCursorToolResult(result) {
20269
20794
  if (result == null) return void 0;
20270
20795
  if (typeof result === "string") return result;
20271
- const rec = asRecord6(result);
20796
+ const rec = asRecord7(result);
20272
20797
  if (!rec) {
20273
20798
  try {
20274
20799
  return JSON.stringify(result);
@@ -20279,18 +20804,18 @@ function unwrapCursorToolResult(result) {
20279
20804
  const collectTexts = (items) => {
20280
20805
  const texts = [];
20281
20806
  for (const item of items) {
20282
- const row2 = asRecord6(item);
20807
+ const row2 = asRecord7(item);
20283
20808
  if (!row2) continue;
20284
20809
  if (typeof row2.text === "string") {
20285
20810
  texts.push(row2.text);
20286
20811
  continue;
20287
20812
  }
20288
- const nested = asRecord6(row2.text);
20813
+ const nested = asRecord7(row2.text);
20289
20814
  if (typeof nested?.text === "string") texts.push(nested.text);
20290
20815
  }
20291
20816
  return texts;
20292
20817
  };
20293
- const value = asRecord6(rec.value);
20818
+ const value = asRecord7(rec.value);
20294
20819
  if (value && Array.isArray(value.content)) {
20295
20820
  const texts = collectTexts(value.content);
20296
20821
  if (texts.length) return texts.join("\n");
@@ -20307,10 +20832,10 @@ function unwrapCursorToolResult(result) {
20307
20832
  }
20308
20833
  function cursorToolResultIsError(status, result) {
20309
20834
  if (status === "error") return true;
20310
- const rec = asRecord6(result);
20835
+ const rec = asRecord7(result);
20311
20836
  if (!rec) return false;
20312
20837
  if (rec.status === "error") return true;
20313
- const value = asRecord6(rec.value);
20838
+ const value = asRecord7(rec.value);
20314
20839
  return value?.isError === true;
20315
20840
  }
20316
20841
  function cursorSdkMessageToEvents(msg) {
@@ -20425,21 +20950,21 @@ function platformRipgrepPackage() {
20425
20950
  }
20426
20951
  function usableRipgrepPath(candidate) {
20427
20952
  const raw = candidate?.trim();
20428
- if (!raw || !(0, import_node_path48.isAbsolute)(raw)) return null;
20953
+ if (!raw || !(0, import_node_path49.isAbsolute)(raw)) return null;
20429
20954
  const readable = nodeReadableScriptPath(raw);
20430
- if (!(0, import_node_fs45.existsSync)(readable) || isAsarPath(readable)) return null;
20955
+ if (!(0, import_node_fs46.existsSync)(readable) || isAsarPath(readable)) return null;
20431
20956
  return readable;
20432
20957
  }
20433
20958
  function walkForBundledRipgrep(startFile) {
20434
20959
  if (!startFile) return null;
20435
20960
  const pkg = platformRipgrepPackage();
20436
20961
  const name = rgBinaryName();
20437
- let dir = (0, import_node_path48.dirname)((0, import_node_path48.resolve)(startFile));
20438
- const root = (0, import_node_path48.parse)(dir).root;
20962
+ let dir = (0, import_node_path49.dirname)((0, import_node_path49.resolve)(startFile));
20963
+ const root = (0, import_node_path49.parse)(dir).root;
20439
20964
  while (dir !== root) {
20440
- const hit = usableRipgrepPath((0, import_node_path48.join)(dir, "node_modules", pkg, "bin", name));
20965
+ const hit = usableRipgrepPath((0, import_node_path49.join)(dir, "node_modules", pkg, "bin", name));
20441
20966
  if (hit) return hit;
20442
- const next = (0, import_node_path48.dirname)(dir);
20967
+ const next = (0, import_node_path49.dirname)(dir);
20443
20968
  if (next === dir) break;
20444
20969
  dir = next;
20445
20970
  }
@@ -20449,7 +20974,7 @@ function requireResolveBundledRipgrep(fromFile) {
20449
20974
  try {
20450
20975
  const req = (0, import_node_module4.createRequire)(fromFile);
20451
20976
  const pkgJson = req.resolve(`${platformRipgrepPackage()}/package.json`);
20452
- return usableRipgrepPath((0, import_node_path48.join)((0, import_node_path48.dirname)(pkgJson), "bin", rgBinaryName()));
20977
+ return usableRipgrepPath((0, import_node_path49.join)((0, import_node_path49.dirname)(pkgJson), "bin", rgBinaryName()));
20453
20978
  } catch {
20454
20979
  return null;
20455
20980
  }
@@ -20471,13 +20996,13 @@ function cursorRipgrepEnv(opts) {
20471
20996
  const path2 = resolveCursorRipgrepPath(opts);
20472
20997
  return path2 ? { [RIPGREP_ENV]: path2 } : {};
20473
20998
  }
20474
- var import_node_fs45, import_node_module4, import_node_path48, RIPGREP_ENV;
20999
+ var import_node_fs46, import_node_module4, import_node_path49, RIPGREP_ENV;
20475
21000
  var init_cursor_ripgrep = __esm({
20476
21001
  "src/agents/cursor-ripgrep.ts"() {
20477
21002
  "use strict";
20478
- import_node_fs45 = require("fs");
21003
+ import_node_fs46 = require("fs");
20479
21004
  import_node_module4 = require("module");
20480
- import_node_path48 = require("path");
21005
+ import_node_path49 = require("path");
20481
21006
  init_cursor_sdk_resolve();
20482
21007
  init_node_launch();
20483
21008
  init_packaged_runtime();
@@ -20529,11 +21054,11 @@ function entryDir2() {
20529
21054
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
20530
21055
  if (cjsDir) return cjsDir;
20531
21056
  try {
20532
- return (0, import_node_path49.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
21057
+ return (0, import_node_path50.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
20533
21058
  } catch {
20534
21059
  try {
20535
21060
  const req = (0, import_node_module5.createRequire)(process.cwd() + "/");
20536
- return (0, import_node_path49.dirname)(req.resolve("@sideboard-ai/core"));
21061
+ return (0, import_node_path50.dirname)(req.resolve("@sideboard-ai/core"));
20537
21062
  } catch {
20538
21063
  return process.cwd();
20539
21064
  }
@@ -20544,27 +21069,27 @@ function cursorRunnerPath() {
20544
21069
  if (packaged) return packaged;
20545
21070
  const root = entryDir2();
20546
21071
  const candidates = [
20547
- (0, import_node_path49.join)(root, "agents", "cursor-runner.js"),
20548
- (0, import_node_path49.join)(root, "agents", "cursor-runner.cjs"),
21072
+ (0, import_node_path50.join)(root, "agents", "cursor-runner.js"),
21073
+ (0, import_node_path50.join)(root, "agents", "cursor-runner.cjs"),
20549
21074
  // If somehow resolved from package root instead of dist/
20550
- (0, import_node_path49.join)(root, "dist", "agents", "cursor-runner.js"),
20551
- (0, import_node_path49.join)(root, "dist", "agents", "cursor-runner.cjs"),
21075
+ (0, import_node_path50.join)(root, "dist", "agents", "cursor-runner.js"),
21076
+ (0, import_node_path50.join)(root, "dist", "agents", "cursor-runner.cjs"),
20552
21077
  // Source tree (dev): packages/core/src/agents/cursor-runner.ts
20553
- (0, import_node_path49.join)(root, "cursor-runner.ts"),
20554
- (0, import_node_path49.join)(root, "src", "agents", "cursor-runner.ts")
21078
+ (0, import_node_path50.join)(root, "cursor-runner.ts"),
21079
+ (0, import_node_path50.join)(root, "src", "agents", "cursor-runner.ts")
20555
21080
  ];
20556
21081
  for (const candidate of candidates) {
20557
- if ((0, import_node_fs46.existsSync)(candidate)) return candidate;
21082
+ if ((0, import_node_fs47.existsSync)(candidate)) return candidate;
20558
21083
  }
20559
21084
  return candidates[0];
20560
21085
  }
20561
- var import_node_fs46, import_node_module5, import_node_path49, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
21086
+ var import_node_fs47, import_node_module5, import_node_path50, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
20562
21087
  var init_cursor = __esm({
20563
21088
  "src/agents/cursor.ts"() {
20564
21089
  "use strict";
20565
- import_node_fs46 = require("fs");
21090
+ import_node_fs47 = require("fs");
20566
21091
  import_node_module5 = require("module");
20567
- import_node_path49 = require("path");
21092
+ import_node_path50 = require("path");
20568
21093
  import_node_url4 = require("url");
20569
21094
  init_run();
20570
21095
  init_app_settings();
@@ -20691,26 +21216,26 @@ var init_cursor = __esm({
20691
21216
 
20692
21217
  // src/agent-rpc/opencode-hook.ts
20693
21218
  function writeOpencodeRpcPlugin() {
20694
- const pluginDir = (0, import_node_path50.join)(appDataDir(), "agent-rpc", "opencode");
20695
- (0, import_node_fs47.mkdirSync)(pluginDir, { recursive: true });
20696
- const pluginFile = (0, import_node_path50.join)(pluginDir, "sideboard-rpc.js");
20697
- if ((0, import_node_fs47.existsSync)(pluginFile)) {
21219
+ const pluginDir = (0, import_node_path51.join)(appDataDir(), "agent-rpc", "opencode");
21220
+ (0, import_node_fs48.mkdirSync)(pluginDir, { recursive: true });
21221
+ const pluginFile = (0, import_node_path51.join)(pluginDir, "sideboard-rpc.js");
21222
+ if ((0, import_node_fs48.existsSync)(pluginFile)) {
20698
21223
  try {
20699
- if ((0, import_node_fs47.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
21224
+ if ((0, import_node_fs48.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
20700
21225
  } catch {
20701
21226
  }
20702
21227
  }
20703
21228
  const tmp = `${pluginFile}.${process.pid}.tmp`;
20704
- (0, import_node_fs47.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
20705
- (0, import_node_fs47.renameSync)(tmp, pluginFile);
21229
+ (0, import_node_fs48.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
21230
+ (0, import_node_fs48.renameSync)(tmp, pluginFile);
20706
21231
  return pluginFile;
20707
21232
  }
20708
- var import_node_fs47, import_node_path50, OPENCODE_PLUGIN_SOURCE;
21233
+ var import_node_fs48, import_node_path51, OPENCODE_PLUGIN_SOURCE;
20709
21234
  var init_opencode_hook = __esm({
20710
21235
  "src/agent-rpc/opencode-hook.ts"() {
20711
21236
  "use strict";
20712
- import_node_fs47 = require("fs");
20713
- import_node_path50 = require("path");
21237
+ import_node_fs48 = require("fs");
21238
+ import_node_path51 = require("path");
20714
21239
  init_paths();
20715
21240
  init_pilot_tools();
20716
21241
  init_protocol2();
@@ -20868,7 +21393,7 @@ var init_opencode_host = __esm({
20868
21393
  });
20869
21394
 
20870
21395
  // src/agents/opencode.ts
20871
- function asRecord7(value) {
21396
+ function asRecord8(value) {
20872
21397
  if (value && typeof value === "object" && !Array.isArray(value)) {
20873
21398
  return value;
20874
21399
  }
@@ -20913,7 +21438,7 @@ async function listOpencodeModels() {
20913
21438
  if (opencode === "opencode") {
20914
21439
  const which = await run("which", ["opencode"], { reject: false });
20915
21440
  if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
20916
- } else if (!(0, import_node_fs48.existsSync)(opencode)) {
21441
+ } else if (!(0, import_node_fs49.existsSync)(opencode)) {
20917
21442
  return FALLBACK_OPENCODE_MODELS;
20918
21443
  }
20919
21444
  const listed = await run(opencode, ["models"], { reject: false });
@@ -20943,11 +21468,11 @@ function usageFromOpencode(tokens) {
20943
21468
  cacheWriteTokens: tokens.cache?.write ? Number(tokens.cache.write) : void 0
20944
21469
  };
20945
21470
  }
20946
- var import_node_fs48, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
21471
+ var import_node_fs49, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
20947
21472
  var init_opencode = __esm({
20948
21473
  "src/agents/opencode.ts"() {
20949
21474
  "use strict";
20950
- import_node_fs48 = require("fs");
21475
+ import_node_fs49 = require("fs");
20951
21476
  init_run();
20952
21477
  init_app_settings();
20953
21478
  init_error_detail();
@@ -20973,7 +21498,7 @@ var init_opencode = __esm({
20973
21498
  async detect() {
20974
21499
  const opencode = resolveAgentExecutable("opencode");
20975
21500
  if (opencode !== "opencode") {
20976
- if (!(0, import_node_fs48.existsSync)(opencode)) {
21501
+ if (!(0, import_node_fs49.existsSync)(opencode)) {
20977
21502
  return {
20978
21503
  agent: "opencode",
20979
21504
  installed: false,
@@ -21073,7 +21598,7 @@ var init_opencode = __esm({
21073
21598
  const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
21074
21599
  const state = part?.state;
21075
21600
  const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
21076
- const metadata = asRecord7(state?.metadata);
21601
+ const metadata = asRecord8(state?.metadata);
21077
21602
  const id = opencodeToolId(
21078
21603
  name,
21079
21604
  part?.callID ?? part?.id ?? obj.id,
@@ -21108,7 +21633,7 @@ var init_opencode = __esm({
21108
21633
  }
21109
21634
  if (obj.type === "subtask_event") {
21110
21635
  const parentId = str4(obj.childSessionID) ?? str4(obj.childSessionId);
21111
- const part = asRecord7(obj.part);
21636
+ const part = asRecord8(obj.part);
21112
21637
  if (!parentId || !part) return null;
21113
21638
  if (part.type === "text" && str4(part.text)) {
21114
21639
  return withTaskParent(
@@ -21119,8 +21644,8 @@ var init_opencode = __esm({
21119
21644
  if (part.type === "tool" || str4(part.tool)) {
21120
21645
  const name = str4(part.tool) ?? str4(part.name) ?? "tool";
21121
21646
  const id = str4(part.callID) ?? str4(part.id) ?? `${parentId}-${name}`;
21122
- const state = asRecord7(part.state);
21123
- const input = asRecord7(state?.input) ?? asRecord7(part.input);
21647
+ const state = asRecord8(part.state);
21648
+ const input = asRecord8(state?.input) ?? asRecord8(part.input);
21124
21649
  const nested = [
21125
21650
  withEventParentId({ type: "tool_use", id, name, input }, parentId)
21126
21651
  ];
@@ -21426,400 +21951,6 @@ var init_session_quota = __esm({
21426
21951
  }
21427
21952
  });
21428
21953
 
21429
- // src/agents/claude-usage.ts
21430
- function parseClaudeResetsAt(value) {
21431
- if (typeof value === "number" && Number.isFinite(value)) {
21432
- const ms = value > 1e12 ? value : value * 1e3;
21433
- const d = new Date(ms);
21434
- return Number.isNaN(d.getTime()) ? null : d.toISOString();
21435
- }
21436
- if (typeof value === "string") {
21437
- const trimmed = value.trim();
21438
- if (!trimmed) return null;
21439
- if (/^\d+(\.\d+)?$/.test(trimmed)) {
21440
- return parseClaudeResetsAt(Number(trimmed));
21441
- }
21442
- const d = new Date(trimmed);
21443
- return Number.isNaN(d.getTime()) ? null : d.toISOString();
21444
- }
21445
- return null;
21446
- }
21447
- function parseClaudeUtilization(value) {
21448
- if (typeof value !== "number" || !Number.isFinite(value)) return null;
21449
- return Math.max(0, Math.min(100, value));
21450
- }
21451
- function windowFromRaw(id, raw) {
21452
- if (!raw || typeof raw !== "object") return null;
21453
- const row2 = raw;
21454
- const used = parseClaudeUtilization(row2.utilization ?? row2.used_percentage);
21455
- if (used == null) return null;
21456
- const meta = WINDOW_META[id];
21457
- return {
21458
- id,
21459
- label: meta.label,
21460
- shortLabel: meta.shortLabel,
21461
- detail: meta.detail,
21462
- usedPercent: used,
21463
- remainingPercent: Math.max(0, Math.min(100, 100 - used)),
21464
- resetsAt: parseClaudeResetsAt(row2.resets_at)
21465
- };
21466
- }
21467
- function extraUsageFromRaw(raw) {
21468
- if (!raw || typeof raw !== "object") return void 0;
21469
- const row2 = raw;
21470
- const enabled = row2.is_enabled === true || row2.enabled === true;
21471
- if (!enabled && row2.is_enabled !== false && row2.enabled !== false) return void 0;
21472
- const usedCredits = numberOrUndef(row2.used_credits ?? row2.used);
21473
- const monthlyLimit = numberOrUndef(row2.monthly_limit);
21474
- const usedPercent = parseClaudeUtilization(row2.utilization) ?? void 0;
21475
- return {
21476
- enabled,
21477
- ...usedCredits != null ? { usedCredits } : {},
21478
- ...monthlyLimit != null ? { monthlyLimit } : {},
21479
- ...usedPercent != null ? { usedPercent } : {}
21480
- };
21481
- }
21482
- function numberOrUndef(value) {
21483
- if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
21484
- return value;
21485
- }
21486
- function parseClaudeUsagePayload(raw, fetchedAt2 = (/* @__PURE__ */ new Date()).toISOString()) {
21487
- if (!raw || typeof raw !== "object") return null;
21488
- const obj = raw;
21489
- const source = obj.rate_limits && typeof obj.rate_limits === "object" ? obj.rate_limits : obj;
21490
- const windows = [];
21491
- for (const id of WINDOW_ORDER) {
21492
- const parsed = windowFromRaw(id, source[id]);
21493
- if (parsed) windows.push(parsed);
21494
- }
21495
- if (windows.length === 0) return null;
21496
- const extra = extraUsageFromRaw(obj.extra_usage ?? source.extra_usage);
21497
- return {
21498
- windows,
21499
- ...extra ? { extraUsage: extra } : {},
21500
- fetchedAt: fetchedAt2
21501
- };
21502
- }
21503
- function hottestClaudeWindow(usage) {
21504
- if (usage.windows.length === 0) return null;
21505
- return usage.windows.reduce((a, b) => b.usedPercent > a.usedPercent ? b : a);
21506
- }
21507
- function formatClaudeUsageReset(resetsAt, now = /* @__PURE__ */ new Date()) {
21508
- if (!resetsAt) return "";
21509
- const at = new Date(resetsAt);
21510
- if (Number.isNaN(at.getTime())) return "";
21511
- const ms = at.getTime() - now.getTime();
21512
- if (ms <= 0) return "resets soon";
21513
- const minutes = Math.round(ms / 6e4);
21514
- if (minutes < 60) return `resets in ${Math.max(1, minutes)}m`;
21515
- const hours = Math.round(minutes / 60);
21516
- if (hours < 36) return `resets in ${hours}h`;
21517
- try {
21518
- return `resets ${at.toLocaleString(void 0, {
21519
- weekday: "short",
21520
- hour: "numeric",
21521
- minute: "2-digit"
21522
- })}`;
21523
- } catch {
21524
- return `resets ${at.toISOString()}`;
21525
- }
21526
- }
21527
- function formatClaudeUsageResetClock(resetsAt) {
21528
- if (!resetsAt) return "";
21529
- const at = new Date(resetsAt);
21530
- if (Number.isNaN(at.getTime())) return "";
21531
- try {
21532
- return at.toLocaleString(void 0, {
21533
- weekday: "short",
21534
- month: "short",
21535
- day: "numeric",
21536
- hour: "numeric",
21537
- minute: "2-digit"
21538
- });
21539
- } catch {
21540
- return at.toISOString();
21541
- }
21542
- }
21543
- function formatClaudeUsageFetchedAt(fetchedAt2, now = /* @__PURE__ */ new Date()) {
21544
- const at = new Date(fetchedAt2);
21545
- if (Number.isNaN(at.getTime())) return "";
21546
- const minutes = Math.max(0, Math.round((now.getTime() - at.getTime()) / 6e4));
21547
- if (minutes < 1) return "Updated just now";
21548
- if (minutes < 60) return `Updated ${minutes}m ago`;
21549
- const hours = Math.round(minutes / 60);
21550
- if (hours < 36) return `Updated ${hours}h ago`;
21551
- return `Updated ${formatClaudeUsageResetClock(fetchedAt2)}`;
21552
- }
21553
- function formatClaudeExtraUsageDetail(extra) {
21554
- if (!extra.enabled) return "Extra usage off";
21555
- const bits = ["Extra usage on"];
21556
- if (extra.usedCredits != null && extra.monthlyLimit != null) {
21557
- bits.push(`${extra.usedCredits} / ${extra.monthlyLimit} credits this month`);
21558
- } else if (extra.usedCredits != null) {
21559
- bits.push(`${extra.usedCredits} credits used`);
21560
- }
21561
- if (extra.usedPercent != null) {
21562
- bits.push(`${Math.round(extra.usedPercent)}% of extra pool`);
21563
- }
21564
- return bits.join(" \xB7 ");
21565
- }
21566
- function formatClaudeUsageWindowLine(window, now = /* @__PURE__ */ new Date()) {
21567
- const reset = formatClaudeUsageReset(window.resetsAt, now);
21568
- const clock = formatClaudeUsageResetClock(window.resetsAt);
21569
- const left = `${Math.round(window.remainingPercent)}% left`;
21570
- const used = `${Math.round(window.usedPercent)}% used`;
21571
- const resetBit = reset ? clock && !reset.includes(clock) ? `${reset} (${clock})` : reset : "";
21572
- return resetBit ? `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used} \xB7 ${resetBit}` : `${window.label} \u2014 ${window.detail}. ${left} \xB7 ${used}`;
21573
- }
21574
- function formatClaudeUsageTooltip(usage, now = /* @__PURE__ */ new Date()) {
21575
- const lines = [
21576
- "Claude Code plan",
21577
- ...usage.windows.map((w) => formatClaudeUsageWindowLine(w, now))
21578
- ];
21579
- if (usage.extraUsage) {
21580
- lines.push(formatClaudeExtraUsageDetail(usage.extraUsage));
21581
- }
21582
- const fetched = formatClaudeUsageFetchedAt(usage.fetchedAt, now);
21583
- if (fetched) lines.push(fetched);
21584
- return lines.join("\n");
21585
- }
21586
- function formatClaudeUsageCompact(window) {
21587
- return `${window.shortLabel} ${Math.round(window.remainingPercent)}%`;
21588
- }
21589
- function claudeUsageWindowOverLimit(window) {
21590
- return window.remainingPercent <= 0 || window.usedPercent >= 100;
21591
- }
21592
- function claudeUsageOverLimitWindows(usage) {
21593
- if (!usage) return [];
21594
- return usage.windows.filter(claudeUsageWindowOverLimit);
21595
- }
21596
- function formatOverLimitWindowList(windows, now) {
21597
- const parts = windows.map((w) => {
21598
- const reset = formatClaudeUsageReset(w.resetsAt, now);
21599
- return reset ? `${w.label} (${reset})` : w.label;
21600
- });
21601
- return {
21602
- list: parts.join(", "),
21603
- verb: windows.length === 1 ? "is" : "are"
21604
- };
21605
- }
21606
- function formatClaudeUsageOverLimitConfirm(windows, now = /* @__PURE__ */ new Date()) {
21607
- if (windows.length === 0) return "";
21608
- const { list, verb } = formatOverLimitWindowList(windows, now);
21609
- return `Claude Code ${list} ${verb} at or over the plan limit. Send this message anyway?`;
21610
- }
21611
- function formatClaudeUsageOverLimitWait(windows, now = /* @__PURE__ */ new Date()) {
21612
- if (windows.length === 0) return "";
21613
- const { list, verb } = formatOverLimitWindowList(windows, now);
21614
- return `Claude Code ${list} ${verb} at or over the plan limit. Sending is paused until the window resets.`;
21615
- }
21616
- var WINDOW_META, WINDOW_ORDER;
21617
- var init_claude_usage = __esm({
21618
- "src/agents/claude-usage.ts"() {
21619
- "use strict";
21620
- WINDOW_META = {
21621
- five_hour: {
21622
- label: "5-hour session",
21623
- shortLabel: "5h",
21624
- detail: "Rolling 5-hour limit across all models"
21625
- },
21626
- seven_day: {
21627
- label: "Weekly",
21628
- shortLabel: "wk",
21629
- detail: "7-day cap across all models"
21630
- },
21631
- seven_day_opus: {
21632
- label: "Opus",
21633
- shortLabel: "Opus",
21634
- detail: "Weekly Opus-only cap"
21635
- },
21636
- seven_day_sonnet: {
21637
- label: "Sonnet",
21638
- shortLabel: "Sonnet",
21639
- detail: "Weekly Sonnet-only cap"
21640
- }
21641
- };
21642
- WINDOW_ORDER = [
21643
- "five_hour",
21644
- "seven_day",
21645
- "seven_day_opus",
21646
- "seven_day_sonnet"
21647
- ];
21648
- }
21649
- });
21650
-
21651
- // src/agents/claude-usage-client.ts
21652
- function usageCacheDir(opts) {
21653
- return opts.configDir?.trim() || "";
21654
- }
21655
- function adoptCacheDir(dir) {
21656
- if (dir === cacheDirKey) return;
21657
- cache = null;
21658
- lastGood = null;
21659
- errorUntil = 0;
21660
- inflight = null;
21661
- cacheDirKey = dir;
21662
- }
21663
- function accessTokenFromCredentialsJson(raw) {
21664
- const trimmed = raw.trim();
21665
- if (!trimmed) return null;
21666
- if (trimmed.startsWith("sk-ant-")) {
21667
- const token = trimmed.split(/\s+/)[0];
21668
- return token || null;
21669
- }
21670
- try {
21671
- const parsed = JSON.parse(trimmed);
21672
- const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
21673
- const token = oauth.accessToken ?? oauth.access_token;
21674
- return typeof token === "string" && token.trim() ? token.trim() : null;
21675
- } catch {
21676
- return null;
21677
- }
21678
- }
21679
- function claudeCredentialsPath(configDir) {
21680
- const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || (0, import_node_path51.join)((0, import_node_os18.homedir)(), ".claude");
21681
- return (0, import_node_path51.join)(root, ".credentials.json");
21682
- }
21683
- async function readFileAccessToken(configDir) {
21684
- const path2 = claudeCredentialsPath(configDir);
21685
- if (!(0, import_node_fs49.existsSync)(path2)) return null;
21686
- try {
21687
- return accessTokenFromCredentialsJson((0, import_node_fs49.readFileSync)(path2, "utf8"));
21688
- } catch {
21689
- return null;
21690
- }
21691
- }
21692
- async function readKeychainAccessToken(configDir) {
21693
- if (process.platform !== "darwin") return null;
21694
- const root = configDir?.trim();
21695
- const accounts = root ? [root, void 0] : [void 0];
21696
- for (const service of KEYCHAIN_SERVICES) {
21697
- for (const account of accounts) {
21698
- const args = ["find-generic-password", "-s", service, "-w"];
21699
- if (account) args.splice(3, 0, "-a", account);
21700
- const result = await run("security", args, {
21701
- reject: false,
21702
- timeoutMs: 4e3
21703
- });
21704
- if (result.exitCode !== 0 || !result.stdout.trim()) continue;
21705
- const token = accessTokenFromCredentialsJson(result.stdout);
21706
- if (token) return token;
21707
- }
21708
- }
21709
- return null;
21710
- }
21711
- async function readClaudeAccessToken(configDir) {
21712
- const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
21713
- if (envToken) return envToken;
21714
- const fromFile = await readFileAccessToken(configDir);
21715
- if (fromFile) return fromFile;
21716
- return readKeychainAccessToken(configDir);
21717
- }
21718
- async function resolveClaudeUserAgent() {
21719
- if (claudeVersion) return `claude-code/${claudeVersion}`;
21720
- try {
21721
- const claude = resolveClaudeExecutable();
21722
- const result = await run(claude, ["--version"], { reject: false, timeoutMs: 4e3 });
21723
- const match = `${result.stdout}
21724
- ${result.stderr}`.match(/(\d+\.\d+\.\d+)/);
21725
- claudeVersion = match?.[1] ?? "2.1.80";
21726
- } catch {
21727
- claudeVersion = "2.1.80";
21728
- }
21729
- return `claude-code/${claudeVersion}`;
21730
- }
21731
- function staleOk(now) {
21732
- if (!lastGood) return null;
21733
- if (now - lastGood.at > CLAUDE_USAGE_STALE_OK_MS) return null;
21734
- return lastGood.value;
21735
- }
21736
- function reuseLast() {
21737
- return lastGood?.value ?? null;
21738
- }
21739
- async function getClaudePlanUsage(opts = {}) {
21740
- const now = opts.now ?? Date.now();
21741
- adoptCacheDir(usageCacheDir(opts));
21742
- if (now < errorUntil) return reuseLast() ?? staleOk(now);
21743
- if (!opts.force) {
21744
- if (cache && now - cache.at < CLAUDE_USAGE_TTL_MS) return cache.value;
21745
- }
21746
- if (inflight) return inflight;
21747
- inflight = (async () => {
21748
- try {
21749
- const token = await (opts.readAccessToken ?? (() => readClaudeAccessToken(opts.configDir)))();
21750
- if (!token) {
21751
- cache = { at: now, dir: cacheDirKey, value: null };
21752
- return null;
21753
- }
21754
- const fetchFn = opts.fetch ?? httpFetch;
21755
- const userAgent = opts.userAgent ?? await resolveClaudeUserAgent();
21756
- const ac = new AbortController();
21757
- const timer2 = setTimeout(() => ac.abort(), 8e3);
21758
- let res;
21759
- try {
21760
- res = await fetchFn(CLAUDE_OAUTH_USAGE_URL, {
21761
- headers: {
21762
- Authorization: `Bearer ${token}`,
21763
- "anthropic-beta": "oauth-2025-04-20",
21764
- "User-Agent": userAgent
21765
- },
21766
- signal: ac.signal
21767
- });
21768
- } finally {
21769
- clearTimeout(timer2);
21770
- }
21771
- if (res.status === 401 || res.status === 403) {
21772
- cache = { at: now, dir: cacheDirKey, value: null };
21773
- return null;
21774
- }
21775
- if (res.status === 429) {
21776
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
21777
- const last = reuseLast();
21778
- if (last) cache = { at: now, dir: cacheDirKey, value: last };
21779
- return last;
21780
- }
21781
- if (!res.ok) {
21782
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
21783
- return staleOk(now);
21784
- }
21785
- const usage = parseClaudeUsagePayload(await res.json(), new Date(now).toISOString());
21786
- cache = { at: now, dir: cacheDirKey, value: usage };
21787
- if (usage) lastGood = { at: now, dir: cacheDirKey, value: usage };
21788
- return usage;
21789
- } catch {
21790
- errorUntil = now + CLAUDE_USAGE_ERROR_TTL_MS;
21791
- return staleOk(now);
21792
- } finally {
21793
- inflight = null;
21794
- }
21795
- })();
21796
- return inflight;
21797
- }
21798
- var import_node_fs49, import_node_os18, import_node_path51, CLAUDE_OAUTH_USAGE_URL, CLAUDE_USAGE_TTL_MS, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS, KEYCHAIN_SERVICES, cache, errorUntil, inflight, lastGood, claudeVersion, cacheDirKey;
21799
- var init_claude_usage_client = __esm({
21800
- "src/agents/claude-usage-client.ts"() {
21801
- "use strict";
21802
- import_node_fs49 = require("fs");
21803
- import_node_os18 = require("os");
21804
- import_node_path51 = require("path");
21805
- init_run();
21806
- init_fetch();
21807
- init_app_settings();
21808
- init_claude_usage();
21809
- CLAUDE_OAUTH_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
21810
- CLAUDE_USAGE_TTL_MS = 9e4;
21811
- CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
21812
- CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
21813
- KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
21814
- cache = null;
21815
- errorUntil = 0;
21816
- inflight = null;
21817
- lastGood = null;
21818
- claudeVersion = null;
21819
- cacheDirKey = "";
21820
- }
21821
- });
21822
-
21823
21954
  // src/agents/install-native.ts
21824
21955
  async function installCurlScript(opts) {
21825
21956
  const result = await run("bash", ["-c", opts.command], {
@@ -25747,7 +25878,7 @@ var init_model_context = __esm({
25747
25878
  });
25748
25879
 
25749
25880
  // src/plan/plan-present.ts
25750
- function asRecord8(v) {
25881
+ function asRecord9(v) {
25751
25882
  return v != null && typeof v === "object" && !Array.isArray(v) ? v : null;
25752
25883
  }
25753
25884
  function isPresentPlanToolName(name) {
@@ -25766,7 +25897,7 @@ function extractPresentedPlan(parts) {
25766
25897
  for (let i = parts.length - 1; i >= 0; i--) {
25767
25898
  const p = parts[i];
25768
25899
  if (p.type !== "tool" || !isPresentPlanToolName(p.name)) continue;
25769
- const input = asRecord8(p.input) ?? {};
25900
+ const input = asRecord9(p.input) ?? {};
25770
25901
  const content = typeof input.content === "string" ? input.content : typeof input.plan === "string" ? input.plan : typeof input.markdown === "string" ? input.markdown : "";
25771
25902
  if (!content.trim()) continue;
25772
25903
  const title = typeof input.title === "string" && input.title.trim() ? input.title.trim() : "Plan";
@@ -26318,6 +26449,10 @@ function resolveStopReason(opts) {
26318
26449
  if (opts?.clearQueue === false) return "Stopped by the user";
26319
26450
  return "Stopped (queue cleared)";
26320
26451
  }
26452
+ function isRoutineStopNote(err) {
26453
+ const text7 = err?.trim() ?? "";
26454
+ return text7 === "Stopped" || text7 === "Stopped by the user" || text7 === "Stopped (queue cleared)" || text7 === "Stopped to send the next prompt";
26455
+ }
26321
26456
  function reasonToKeepOnStop(existing, incoming) {
26322
26457
  const next = incoming?.trim();
26323
26458
  if (next) return next.slice(0, STOP_REASON_MAX);
@@ -26325,6 +26460,16 @@ function reasonToKeepOnStop(existing, incoming) {
26325
26460
  if (prior) return prior.slice(0, STOP_REASON_MAX);
26326
26461
  return "Stopped";
26327
26462
  }
26463
+ function turnFinishedEvent(threadId, exitCode, userStopped, lastError) {
26464
+ const note = lastError?.trim() ?? "";
26465
+ const routineStop = userStopped && (note.length === 0 || isRoutineStopNote(note));
26466
+ return {
26467
+ type: "turn_finished",
26468
+ threadId,
26469
+ exitCode,
26470
+ ...routineStop ? { routineStop: true } : {}
26471
+ };
26472
+ }
26328
26473
  function writeStoppedStatus(threadId, reason) {
26329
26474
  const latest = readThread(threadId);
26330
26475
  if (!latest || latest.status === "archived") return latest;
@@ -26929,7 +27074,7 @@ __export(abletime_rest_exports, {
26929
27074
  looksLikeAbleTimeUlid: () => looksLikeAbleTimeUlid,
26930
27075
  textFromAbleTimeDoc: () => textFromAbleTimeDoc
26931
27076
  });
26932
- function asRecord9(value) {
27077
+ function asRecord10(value) {
26933
27078
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
26934
27079
  }
26935
27080
  function asString(value) {
@@ -26937,7 +27082,7 @@ function asString(value) {
26937
27082
  }
26938
27083
  function asList(value) {
26939
27084
  if (Array.isArray(value)) return value;
26940
- const record = asRecord9(value);
27085
+ const record = asRecord10(value);
26941
27086
  if (!record) return [];
26942
27087
  for (const key of ["data", "tasks", "projects", "users", "items", "results"]) {
26943
27088
  if (Array.isArray(record[key])) return record[key];
@@ -26954,12 +27099,12 @@ function ableTimeDocFromText(text7) {
26954
27099
  }
26955
27100
  function textFromAbleTimeDoc(value) {
26956
27101
  if (typeof value === "string") return value.trim();
26957
- const record = asRecord9(value);
27102
+ const record = asRecord10(value);
26958
27103
  if (!record) return "";
26959
27104
  if (typeof record.text === "string" && record.text.trim()) return record.text.trim();
26960
27105
  const chunks = [];
26961
27106
  const walk = (node) => {
26962
- const rec = asRecord9(node);
27107
+ const rec = asRecord10(node);
26963
27108
  if (!rec) return;
26964
27109
  if (typeof rec.text === "string" && rec.text) chunks.push(rec.text);
26965
27110
  if (Array.isArray(rec.content)) rec.content.forEach(walk);
@@ -27021,7 +27166,7 @@ async function restPages(path2, opts, maxPages = 20) {
27021
27166
  query: { ...opts.query, ...cursor ? { cursor } : {} }
27022
27167
  });
27023
27168
  items.push(...asList(raw));
27024
- const page = asRecord9(asRecord9(raw)?.page);
27169
+ const page = asRecord10(asRecord10(raw)?.page);
27025
27170
  const next = page ? asString(page.nextCursor) : "";
27026
27171
  if (!next) break;
27027
27172
  cursor = next;
@@ -27029,7 +27174,7 @@ async function restPages(path2, opts, maxPages = 20) {
27029
27174
  return items;
27030
27175
  }
27031
27176
  function userDisplayName(raw) {
27032
- const rec = asRecord9(raw);
27177
+ const rec = asRecord10(raw);
27033
27178
  if (!rec) return null;
27034
27179
  const id = asString(rec.userId) || asString(rec.id);
27035
27180
  const name = [asString(rec.firstName), asString(rec.lastName)].filter(Boolean).join(" ") || asString(rec.username) || asString(rec.email) || asString(rec.name);
@@ -27037,7 +27182,7 @@ function userDisplayName(raw) {
27037
27182
  return { id: id || void 0, name };
27038
27183
  }
27039
27184
  function restTaskToRaw(raw, users) {
27040
- const rec = asRecord9(raw);
27185
+ const rec = asRecord10(raw);
27041
27186
  if (!rec) return null;
27042
27187
  const id = asString(rec.timeflowTaskId) || asString(rec.taskId) || asString(rec.id);
27043
27188
  const identifier = asString(rec.taskRef) || asString(rec.reference) || id;
@@ -27045,7 +27190,7 @@ function restTaskToRaw(raw, users) {
27045
27190
  if (!id && !identifier && !title) return null;
27046
27191
  const assignee = users.get(asString(rec.assignedUserId));
27047
27192
  const comments = asList(rec.comments).map((item) => {
27048
- const comment = asRecord9(item) ?? {};
27193
+ const comment = asRecord10(item) ?? {};
27049
27194
  const user = userDisplayName(comment);
27050
27195
  return {
27051
27196
  id: asString(comment.commentId) || asString(comment.id),
@@ -27076,13 +27221,13 @@ function restTaskToRaw(raw, users) {
27076
27221
  };
27077
27222
  }
27078
27223
  function restProjectToRaw(raw) {
27079
- const rec = asRecord9(raw);
27224
+ const rec = asRecord10(raw);
27080
27225
  if (!rec) return null;
27081
27226
  const id = asString(rec.projectId) || asString(rec.id);
27082
27227
  const name = asString(rec.projectName) || asString(rec.name);
27083
27228
  if (!id && !name) return null;
27084
27229
  const categories = asList(rec.categories).map((item) => {
27085
- const cat = asRecord9(item) ?? {};
27230
+ const cat = asRecord10(item) ?? {};
27086
27231
  return {
27087
27232
  id: asString(cat.projectCategoryId) || asString(cat.categoryId) || asString(cat.id),
27088
27233
  name: asString(cat.categoryName) || asString(cat.name)
@@ -27094,7 +27239,7 @@ async function listUsers(opts) {
27094
27239
  const users = /* @__PURE__ */ new Map();
27095
27240
  for (const item of await restPages("/users", opts).catch(() => [])) {
27096
27241
  const user = userDisplayName(item);
27097
- const rec = asRecord9(item);
27242
+ const rec = asRecord10(item);
27098
27243
  const id = user?.id || (rec ? asString(rec.userId) : "");
27099
27244
  if (user && id) users.set(id, user);
27100
27245
  }
@@ -27220,10 +27365,10 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
27220
27365
  if (!project) throw new Error("AbleTime has no projects to create a task in");
27221
27366
  const categories = asList(project.categories);
27222
27367
  const wantedCategory = firstStringArg(args, ["category_id", "categoryId", "category"]);
27223
- const category = categories.map((item) => asRecord9(item)).find((item) => {
27368
+ const category = categories.map((item) => asRecord10(item)).find((item) => {
27224
27369
  if (!item || !wantedCategory) return false;
27225
27370
  return asString(item.id).toLowerCase() === wantedCategory.toLowerCase() || asString(item.name).toLowerCase() === wantedCategory.toLowerCase();
27226
- }) ?? asRecord9(categories[0]);
27371
+ }) ?? asRecord10(categories[0]);
27227
27372
  const parentArg = firstStringArg(args, ["parent", "parent_id", "parentId", "related_task_id"]);
27228
27373
  const parentTaskId = parentArg ? await resolveRestParentTaskId(parentArg, requestOpts) : void 0;
27229
27374
  const created = await abletimeRestRequest("/tasks", {
@@ -27237,7 +27382,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
27237
27382
  }
27238
27383
  });
27239
27384
  const state = firstStringArg(args, ["state"]);
27240
- const createdId = asString(asRecord9(created)?.timeflowTaskId);
27385
+ const createdId = asString(asRecord10(created)?.timeflowTaskId);
27241
27386
  const description = asString(args.description);
27242
27387
  if (createdId && description) {
27243
27388
  await abletimeRestRequest(`/tasks/${encodeURIComponent(createdId)}`, {
@@ -27310,7 +27455,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
27310
27455
  method: "POST",
27311
27456
  body: { content: ableTimeDocFromText(body) }
27312
27457
  });
27313
- const rec = asRecord9(created) ?? {};
27458
+ const rec = asRecord10(created) ?? {};
27314
27459
  return {
27315
27460
  id: asString(rec.commentId) || void 0,
27316
27461
  body: textFromAbleTimeDoc(rec.content) || body
@@ -27405,7 +27550,7 @@ function rewriteAbleTimeError(message) {
27405
27550
  }
27406
27551
  return message;
27407
27552
  }
27408
- function asRecord10(value) {
27553
+ function asRecord11(value) {
27409
27554
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
27410
27555
  }
27411
27556
  function parseSseJson(body) {
@@ -27427,12 +27572,12 @@ function parseSseJson(body) {
27427
27572
  }
27428
27573
  }
27429
27574
  function unwrapToolResult(result) {
27430
- const record = asRecord10(result);
27575
+ const record = asRecord11(result);
27431
27576
  if (!record) return result;
27432
27577
  const content = record.content;
27433
27578
  if (Array.isArray(content)) {
27434
27579
  const texts = content.map((part) => {
27435
- const item = asRecord10(part);
27580
+ const item = asRecord11(part);
27436
27581
  if (!item) return "";
27437
27582
  return typeof item.text === "string" ? item.text : "";
27438
27583
  }).filter(Boolean);
@@ -27454,7 +27599,7 @@ function unwrapToolResult(result) {
27454
27599
  return result;
27455
27600
  }
27456
27601
  function textsFromUnknown(value) {
27457
- const record = asRecord10(value);
27602
+ const record = asRecord11(value);
27458
27603
  if (!record) return "";
27459
27604
  if (typeof record.message === "string") return record.message;
27460
27605
  if (typeof record.error === "string") return record.error;
@@ -27501,7 +27646,7 @@ async function abletimeMcpRequest(method, params, opts) {
27501
27646
  return parseSseJson(body);
27502
27647
  }
27503
27648
  })();
27504
- const rpc = asRecord10(parsed);
27649
+ const rpc = asRecord11(parsed);
27505
27650
  if (rpc?.error) {
27506
27651
  const detail = typeof rpc.error.message === "string" && rpc.error.message.trim() ? rpc.error.message : `AbleTime MCP error ${rpc.error.code ?? ""}`.trim();
27507
27652
  throw new Error(rewriteAbleTimeError(detail));
@@ -27588,7 +27733,7 @@ var init_abletime_mcp = __esm({
27588
27733
  });
27589
27734
 
27590
27735
  // src/integrations/abletime-attachments.ts
27591
- function asRecord11(value) {
27736
+ function asRecord12(value) {
27592
27737
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
27593
27738
  }
27594
27739
  function asString2(value) {
@@ -27596,7 +27741,7 @@ function asString2(value) {
27596
27741
  }
27597
27742
  function asList2(value) {
27598
27743
  if (Array.isArray(value)) return value;
27599
- const record = asRecord11(value);
27744
+ const record = asRecord12(value);
27600
27745
  if (!record) return [];
27601
27746
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
27602
27747
  if (Array.isArray(record[key])) return record[key];
@@ -27615,9 +27760,9 @@ function filesFromAbleTimeDoc(value) {
27615
27760
  const out = [];
27616
27761
  const seen = /* @__PURE__ */ new Set();
27617
27762
  const walk = (node) => {
27618
- const rec = asRecord11(node);
27763
+ const rec = asRecord12(node);
27619
27764
  if (!rec) return;
27620
- const attrs = asRecord11(rec.attrs) ?? rec;
27765
+ const attrs = asRecord12(rec.attrs) ?? rec;
27621
27766
  const url = asString2(attrs.src) || asString2(attrs.href) || asString2(attrs.url) || asString2(attrs.fileUrl) || asString2(attrs.downloadUrl);
27622
27767
  if (url && !seen.has(url)) {
27623
27768
  seen.add(url);
@@ -27635,7 +27780,7 @@ function filesFromAbleTimeDoc(value) {
27635
27780
  function listedAbleTimeFiles(raw) {
27636
27781
  const out = [];
27637
27782
  for (const item of asList2(raw)) {
27638
- const rec = asRecord11(item);
27783
+ const rec = asRecord12(item);
27639
27784
  if (!rec) continue;
27640
27785
  const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl", "permalink"]);
27641
27786
  if (!url) continue;
@@ -27655,7 +27800,7 @@ function mapAbleTimeAttachments(record) {
27655
27800
  ...filesFromAbleTimeDoc(record.description),
27656
27801
  ...filesFromAbleTimeDoc(record.content),
27657
27802
  ...asList2(record.comments).flatMap((item) => {
27658
- const rec = asRecord11(item);
27803
+ const rec = asRecord12(item);
27659
27804
  return rec ? filesFromAbleTimeDoc(rec.content ?? rec.body) : [];
27660
27805
  })
27661
27806
  ].map((file) => ({
@@ -27697,7 +27842,7 @@ async function resolveAbleTimeAttachmentUrl(id, opts) {
27697
27842
  const json = await res.json().catch(() => null);
27698
27843
  const rec = json && typeof json === "object" && !Array.isArray(json) ? json.data && typeof json.data === "object" ? json.data : json : null;
27699
27844
  if (!rec) continue;
27700
- const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord11(rec.file), ["url", "href"]);
27845
+ const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord12(rec.file), ["url", "href"]);
27701
27846
  if (url) {
27702
27847
  return {
27703
27848
  url,
@@ -27739,7 +27884,7 @@ var init_abletime_attachments = __esm({
27739
27884
  });
27740
27885
 
27741
27886
  // src/integrations/abletime-projects.ts
27742
- function asRecord12(value) {
27887
+ function asRecord13(value) {
27743
27888
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
27744
27889
  }
27745
27890
  function firstString2(record, keys) {
@@ -27752,7 +27897,7 @@ function firstString2(record, keys) {
27752
27897
  }
27753
27898
  function asList3(value) {
27754
27899
  if (Array.isArray(value)) return value;
27755
- const record = asRecord12(value);
27900
+ const record = asRecord13(value);
27756
27901
  if (!record) return [];
27757
27902
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
27758
27903
  if (Array.isArray(record[key])) return record[key];
@@ -27760,7 +27905,7 @@ function asList3(value) {
27760
27905
  return [];
27761
27906
  }
27762
27907
  function ableTimeProjectFields(nested) {
27763
- const projectRecord = asRecord12(nested.project);
27908
+ const projectRecord = asRecord13(nested.project);
27764
27909
  const projectId = firstString2(nested, ["project_id", "projectId"]) || firstString2(projectRecord, ["id"]) || void 0;
27765
27910
  const projectName = firstString2(nested, ["project_name", "projectName"]) || firstString2(projectRecord, ["name", "title"]) || void 0;
27766
27911
  if (!projectId && !projectName) return {};
@@ -27773,13 +27918,13 @@ function ableTimeProjectFields(nested) {
27773
27918
  };
27774
27919
  }
27775
27920
  function mapAbleTimeProject(raw) {
27776
- const record = asRecord12(raw);
27921
+ const record = asRecord13(raw);
27777
27922
  if (!record) return null;
27778
27923
  const id = firstString2(record, ["id", "project_id", "projectId"]);
27779
27924
  const name = firstString2(record, ["name", "title", "projectName"]);
27780
27925
  if (!id && !name) return null;
27781
27926
  const categories = asList3(record.categories ?? record.category).map((item) => {
27782
- const rec = asRecord12(item);
27927
+ const rec = asRecord13(item);
27783
27928
  if (!rec) return null;
27784
27929
  const categoryId = firstString2(rec, ["id", "category_id", "projectCategoryId", "categoryId"]);
27785
27930
  const categoryName = firstString2(rec, ["name", "title", "categoryName"]);
@@ -27816,7 +27961,7 @@ __export(abletime_exports, {
27816
27961
  updateAbleTimeTask: () => updateAbleTimeTask,
27817
27962
  verifyAbleTimeConnection: () => verifyAbleTimeConnection
27818
27963
  });
27819
- function asRecord13(value) {
27964
+ function asRecord14(value) {
27820
27965
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
27821
27966
  }
27822
27967
  function asString3(value) {
@@ -27833,14 +27978,14 @@ function firstString3(record, keys) {
27833
27978
  function firstRecord(record, keys) {
27834
27979
  if (!record) return null;
27835
27980
  for (const key of keys) {
27836
- const value = asRecord13(record[key]);
27981
+ const value = asRecord14(record[key]);
27837
27982
  if (value) return value;
27838
27983
  }
27839
27984
  return null;
27840
27985
  }
27841
27986
  function asList4(value) {
27842
27987
  if (Array.isArray(value)) return value;
27843
- const record = asRecord13(value);
27988
+ const record = asRecord14(value);
27844
27989
  if (!record) return [];
27845
27990
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
27846
27991
  if (Array.isArray(record[key])) return record[key];
@@ -27852,18 +27997,18 @@ function labelsOf(record) {
27852
27997
  if (!Array.isArray(raw)) return [];
27853
27998
  return raw.map((item) => {
27854
27999
  if (typeof item === "string") return item.trim();
27855
- const rec = asRecord13(item);
28000
+ const rec = asRecord14(item);
27856
28001
  return rec ? firstString3(rec, ["name", "title", "label"]) : "";
27857
28002
  }).filter(Boolean);
27858
28003
  }
27859
28004
  function commentsOf(record) {
27860
28005
  const out = [];
27861
28006
  for (const item of asList4(record.comments ?? record.notes ?? record.discussion)) {
27862
- const rec = asRecord13(item);
28007
+ const rec = asRecord14(item);
27863
28008
  if (!rec) continue;
27864
28009
  const body = firstString3(rec, ["body", "text", "comment", "message", "contentSanitized"]) || textFromAbleTimeDoc(rec.content);
27865
28010
  if (!body) continue;
27866
- const user = firstString3(asRecord13(rec.user) ?? asRecord13(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
28011
+ const user = firstString3(asRecord14(rec.user) ?? asRecord14(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
27867
28012
  const id = firstString3(rec, ["id", "comment_id", "commentId"]);
27868
28013
  const url = firstString3(rec, ["url", "permalink"]);
27869
28014
  const createdAt = firstString3(rec, ["created_at", "createdAt", "created"]);
@@ -27890,7 +28035,7 @@ function taskUrl(task, host) {
27890
28035
  return `${base}/tasks/${slug}`;
27891
28036
  }
27892
28037
  function mapAbleTimeTask(raw, host) {
27893
- const record = asRecord13(raw);
28038
+ const record = asRecord14(raw);
27894
28039
  if (!record) return null;
27895
28040
  const nested = firstRecord(record, ["task", "data"]) ?? record;
27896
28041
  const id = firstString3(nested, ["id", "task_id", "taskId", "timeflowTaskId"]);
@@ -27908,7 +28053,7 @@ function mapAbleTimeTask(raw, host) {
27908
28053
  description: firstString3(nested, ["description", "body", "details", "descriptionSanitized"]) || textFromAbleTimeDoc(nested.description) || void 0,
27909
28054
  state: firstString3(nested, ["state", "board_state", "boardState", "status", "taskState"]) || void 0,
27910
28055
  ...ableTimeProjectFields(nested),
27911
- categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord13(nested.category), ["id"]) || void 0,
28056
+ categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord14(nested.category), ["id"]) || void 0,
27912
28057
  assignee: assigneeOf(nested),
27913
28058
  labels: labelsOf(nested),
27914
28059
  comments: commentsOf(nested),
@@ -27961,7 +28106,7 @@ function isOpenTask(task) {
27961
28106
  }
27962
28107
  async function getAbleTimeOrientation(opts) {
27963
28108
  const raw = await callAbleTimeTool("orientation", {}, opts);
27964
- const record = asRecord13(raw);
28109
+ const record = asRecord14(raw);
27965
28110
  const viewerRec = firstRecord(record, ["viewer", "principal", "user", "actor", "me", "person"]) ?? record;
27966
28111
  const viewer = {
27967
28112
  id: firstString3(viewerRec, ["id", "user_id"]) || void 0,
@@ -28040,7 +28185,7 @@ async function commentAbleTimeTask(input, opts) {
28040
28185
  { id, task_id: id, task: id, body, comment: body, text: body },
28041
28186
  opts
28042
28187
  );
28043
- const rec = asRecord13(raw);
28188
+ const rec = asRecord14(raw);
28044
28189
  return {
28045
28190
  id: rec ? firstString3(rec, ["id", "comment_id"]) || void 0 : void 0,
28046
28191
  body: rec ? firstString3(rec, ["body", "text", "comment"]) || body : body
@@ -32242,7 +32387,7 @@ function normalizeServiceOrigin(raw, fallback) {
32242
32387
  return fallback;
32243
32388
  }
32244
32389
  }
32245
- function asRecord14(value) {
32390
+ function asRecord15(value) {
32246
32391
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
32247
32392
  }
32248
32393
  function asString4(value) {
@@ -32275,7 +32420,7 @@ async function authorizedGet(url, token) {
32275
32420
  });
32276
32421
  const body = await readJson2(res);
32277
32422
  if (!res.ok) {
32278
- const record = asRecord14(body);
32423
+ const record = asRecord15(body);
32279
32424
  const message = firstString4(record, ["message", "error", "error_description", "detail"]) || (typeof body === "string" ? body.trim().slice(0, 160) : "");
32280
32425
  throw new Error(
32281
32426
  message ? `${res.status}: ${message}` : `Request failed (${res.status})`
@@ -32289,28 +32434,28 @@ async function verifyOptionalService(input) {
32289
32434
  const spec = optionalServiceSpec(input.id);
32290
32435
  try {
32291
32436
  if (input.id === "vercel") {
32292
- const body2 = asRecord14(await authorizedGet("https://api.vercel.com/v2/user", token));
32293
- const user = asRecord14(body2?.user) ?? body2;
32437
+ const body2 = asRecord15(await authorizedGet("https://api.vercel.com/v2/user", token));
32438
+ const user = asRecord15(body2?.user) ?? body2;
32294
32439
  const name2 = firstString4(user, ["username", "name", "email"]) || "Vercel user";
32295
32440
  return { viewerName: name2 };
32296
32441
  }
32297
32442
  if (input.id === "supabase") {
32298
32443
  const body2 = await authorizedGet("https://api.supabase.com/v1/organizations", token);
32299
32444
  const list2 = Array.isArray(body2) ? body2 : [];
32300
- const first2 = asRecord14(list2[0]);
32445
+ const first2 = asRecord15(list2[0]);
32301
32446
  const name2 = firstString4(first2, ["name", "slug"]) || "Supabase";
32302
32447
  return { viewerName: list2.length > 1 ? `${name2} +${list2.length - 1}` : name2 };
32303
32448
  }
32304
32449
  if (input.id === "posthog") {
32305
32450
  const host2 = normalizeServiceOrigin(input.host, spec.defaultHost ?? "https://us.posthog.com");
32306
- const body2 = asRecord14(await authorizedGet(`${host2}/api/users/@me/`, token));
32451
+ const body2 = asRecord15(await authorizedGet(`${host2}/api/users/@me/`, token));
32307
32452
  const name2 = firstString4(body2, ["email", "distinct_id"]) || [firstString4(body2, ["first_name"]), firstString4(body2, ["last_name"])].filter(Boolean).join(" ") || "PostHog user";
32308
32453
  return { viewerName: name2, host: host2 };
32309
32454
  }
32310
32455
  const host = normalizeServiceOrigin(input.host, spec.defaultHost ?? "https://sentry.io");
32311
32456
  const body = await authorizedGet(`${host}/api/0/organizations/`, token);
32312
32457
  const list = Array.isArray(body) ? body : [];
32313
- const first = asRecord14(list[0]);
32458
+ const first = asRecord15(list[0]);
32314
32459
  const name = firstString4(first, ["slug", "name"]) || "Sentry";
32315
32460
  return { viewerName: list.length > 1 ? `${name} +${list.length - 1}` : name, host };
32316
32461
  } catch (err) {
@@ -32354,6 +32499,9 @@ function clearConnection(integrations, id) {
32354
32499
  }
32355
32500
  if (id === "posthog") {
32356
32501
  delete integrations.posthogPersonalApiKey;
32502
+ delete integrations.posthogAccessToken;
32503
+ delete integrations.posthogRefreshToken;
32504
+ delete integrations.posthogTokenExpiresAt;
32357
32505
  delete integrations.posthogViewerName;
32358
32506
  delete integrations.posthogHost;
32359
32507
  return;
@@ -32366,6 +32514,9 @@ async function connectOptionalService(input) {
32366
32514
  if (!isOptionalServiceId(input.id)) {
32367
32515
  throw new Error("Unknown optional service");
32368
32516
  }
32517
+ if (input.id === "posthog") {
32518
+ throw new Error("PostHog connects with Sign in, not an API key.");
32519
+ }
32369
32520
  const verified = await verifyOptionalService(input);
32370
32521
  const current = loadAppSettings();
32371
32522
  const integrations = { ...current.integrations };
@@ -32388,7 +32539,11 @@ function disconnectOptionalService(id) {
32388
32539
  function optionalServiceConnected(id, integrations) {
32389
32540
  if (id === "vercel") return Boolean(integrations.vercelToken?.trim());
32390
32541
  if (id === "supabase") return Boolean(integrations.supabaseAccessToken?.trim());
32391
- if (id === "posthog") return Boolean(integrations.posthogPersonalApiKey?.trim());
32542
+ if (id === "posthog") {
32543
+ return Boolean(
32544
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
32545
+ );
32546
+ }
32392
32547
  return Boolean(integrations.sentryAuthToken?.trim());
32393
32548
  }
32394
32549
  function connectedOptionalServices(integrations) {
@@ -32403,12 +32558,12 @@ function connectorDirectiveLine(spec, cli) {
32403
32558
  if (spec.cli) {
32404
32559
  return `- ${spec.label}: use \`${spec.cli}\` (\`${spec.envKey}\`${extras})${cliPresencePhrase(spec, cli)}. Do not add a ${spec.label} MCP.`;
32405
32560
  }
32406
- 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.`;
32561
+ 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.`;
32407
32562
  }
32408
32563
  function connectorAuthCaution(posthog, cliConnected) {
32409
32564
  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.";
32410
32565
  const token = cliConnected ? " CLI tokens are already in this process." : "";
32411
- const key = posthog ? " Do not read a PostHog key from the environment." : "";
32566
+ const key = posthog ? " Do not read a PostHog token from the environment." : "";
32412
32567
  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.`;
32413
32568
  }
32414
32569
  function connectorReminderBit(spec, cli) {
@@ -32436,7 +32591,7 @@ function formatOptionalServicesReminder(integrations, cli) {
32436
32591
  const bits = connected.map((spec) => connectorReminderBit(spec, cli)).join(". ");
32437
32592
  const tokenBit = connected.some((spec) => spec.cli) ? "CLI tokens are already in this process. " : "";
32438
32593
  const posthog = connected.some((spec) => spec.id === "posthog");
32439
- 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.";
32594
+ 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.";
32440
32595
  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.`;
32441
32596
  }
32442
32597
  async function connectedCliPresence(integrations) {
@@ -32486,13 +32641,12 @@ var init_optional_services = __esm({
32486
32641
  {
32487
32642
  id: "posthog",
32488
32643
  label: "PostHog",
32489
- hint: "Product analytics. Agents call `posthog_api` on the Sideboard MCP server.",
32644
+ hint: "Product analytics. Sign in with your browser. Agents call `posthog_api`.",
32490
32645
  tokenPlaceholder: "phx_\u2026",
32491
- tokenDocs: "https://app.posthog.com/settings/user-api-keys",
32646
+ tokenDocs: "https://posthog.com/docs/api/oauth",
32492
32647
  envKey: "POSTHOG_PERSONAL_API_KEY",
32493
32648
  hostEnvKey: "POSTHOG_HOST",
32494
- defaultHost: "https://us.posthog.com",
32495
- hostPlaceholder: "https://us.posthog.com"
32649
+ defaultHost: "https://us.posthog.com"
32496
32650
  },
32497
32651
  {
32498
32652
  id: "sentry",
@@ -34166,7 +34320,7 @@ var init_orchestrator = __esm({
34166
34320
  if (!this.shouldReclaimRunningThread(thread)) continue;
34167
34321
  setStatus(thread.id, "stopped", "Process died (agent exited)");
34168
34322
  this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
34169
- this.emit({ type: "turn_finished", threadId: thread.id, exitCode: 1 });
34323
+ this.emit(turnFinishedEvent(thread.id, 1, this.stoppedTurns.has(thread.id), readThread(thread.id)?.lastError));
34170
34324
  const latest = readThread(thread.id);
34171
34325
  if (latest) {
34172
34326
  notifyParentOfChildHalt(latest, "stopped", (id, prompt) => this.send(id, prompt));
@@ -34731,7 +34885,7 @@ var init_orchestrator = __esm({
34731
34885
  if (stopped?.status === "stopped") {
34732
34886
  this.emit({ type: "status_changed", threadId, status: "stopped" });
34733
34887
  }
34734
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
34888
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
34735
34889
  return;
34736
34890
  }
34737
34891
  thread = this.requireThread(threadId);
@@ -35139,7 +35293,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35139
35293
  if (stopped?.status === "stopped") {
35140
35294
  this.emit({ type: "status_changed", threadId, status: "stopped" });
35141
35295
  }
35142
- this.emit({ type: "turn_finished", threadId, exitCode });
35296
+ this.emit(turnFinishedEvent(threadId, exitCode, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
35143
35297
  } else {
35144
35298
  const failDetail = formatTurnExitError(exitCode, detail);
35145
35299
  const explainedInChat = exitCode !== 0 && Boolean(chatText) && (looksLikeAgentFailureMessage(chatText) || failDetail && chatText.includes(failDetail.replace(/^exit\s*\d+:\s*/i, "").trim()));
@@ -35156,7 +35310,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35156
35310
  status: written.status
35157
35311
  });
35158
35312
  }
35159
- this.emit({ type: "turn_finished", threadId, exitCode });
35313
+ this.emit(turnFinishedEvent(threadId, exitCode, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
35160
35314
  if (exitCode === 0) {
35161
35315
  this.crashContinued.delete(threadId);
35162
35316
  this.maybeEnqueueJobContinue(threadId, chatText, parts);
@@ -35191,14 +35345,14 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35191
35345
  if (stopped?.status === "stopped") {
35192
35346
  this.emit({ type: "status_changed", threadId, status: "stopped" });
35193
35347
  }
35194
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
35348
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
35195
35349
  } else {
35196
35350
  const written = writeLiveStatus(threadId, "error", message);
35197
35351
  if (written?.status === "error") {
35198
35352
  this.emit({ type: "error", threadId, message });
35199
35353
  this.emit({ type: "status_changed", threadId, status: "error" });
35200
35354
  }
35201
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
35355
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
35202
35356
  const failedOver = await isolateQuotaFailover(
35203
35357
  () => this.maybeHandleOrchestrationQuotaFailover(threadId, message)
35204
35358
  );
@@ -35246,9 +35400,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35246
35400
  const continueQueue = opts?.continueQueue === true;
35247
35401
  const thread = this.requireThread(threadRef);
35248
35402
  const inFlight = this.activeTurns.has(thread.id) || this.startingTurns.has(thread.id);
35249
- if (inFlight) {
35250
- this.stoppedTurns.add(thread.id);
35251
- }
35403
+ if (inFlight) this.stoppedTurns.add(thread.id);
35252
35404
  if (clearQueue && thread.queue.length > 0) {
35253
35405
  this.haltDrain.delete(thread.id);
35254
35406
  updateThread(thread.id, { queue: [], queueAttachments: [] });
@@ -35258,6 +35410,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35258
35410
  } else if (continueQueue) {
35259
35411
  this.haltDrain.delete(thread.id);
35260
35412
  }
35413
+ let stopped = writeStoppedStatus(thread.id, resolveStopReason(opts)) ?? readThread(thread.id) ?? thread;
35261
35414
  const handle = this.activeTurns.get(thread.id);
35262
35415
  if (handle) handle.kill();
35263
35416
  const proc = this.processes.get(`${thread.id}:agent`);
@@ -35276,10 +35429,10 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
35276
35429
  }
35277
35430
  }
35278
35431
  }
35279
- const stopped = writeStoppedStatus(thread.id, resolveStopReason(opts)) ?? readThread(thread.id) ?? thread;
35432
+ stopped = readThread(thread.id) ?? stopped;
35280
35433
  if (stopped.status === "stopped") {
35281
35434
  this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
35282
- if (inFlight && opts?.notifyParent !== false) {
35435
+ if (inFlight && opts?.notifyParent !== false && !continueQueue) {
35283
35436
  notifyParentOfChildHalt(stopped, "stopped", (id, prompt) => this.send(id, prompt));
35284
35437
  }
35285
35438
  }
@@ -36777,6 +36930,7 @@ __export(index_exports, {
36777
36930
  ATTACHMENTS_DIR: () => ATTACHMENTS_DIR,
36778
36931
  AbleTimeOAuthCancelledError: () => AbleTimeOAuthCancelledError,
36779
36932
  BAKED_ABLETIME_OAUTH_CLIENT_ID: () => BAKED_ABLETIME_OAUTH_CLIENT_ID,
36933
+ BAKED_POSTHOG_OAUTH_CLIENT_ID: () => BAKED_POSTHOG_OAUTH_CLIENT_ID,
36780
36934
  BAKED_REMOTE_RELAY_URL: () => BAKED_REMOTE_RELAY_URL,
36781
36935
  BAKED_SLACK_CLIENT_ID: () => BAKED_SLACK_CLIENT_ID,
36782
36936
  BAKED_SLACK_RELAY_URL: () => BAKED_SLACK_RELAY_URL,
@@ -36864,10 +37018,14 @@ __export(index_exports, {
36864
37018
  PLAN_MODE_OFF_INSTRUCTION: () => PLAN_MODE_OFF_INSTRUCTION,
36865
37019
  PLAN_QUESTION_ANSWERS_PREFIX: () => PLAN_QUESTION_ANSWERS_PREFIX,
36866
37020
  PORT_RANGE_SIZE: () => PORT_RANGE_SIZE,
37021
+ POSTHOG_OAUTH_OPTIONAL_SCOPES: () => POSTHOG_OAUTH_OPTIONAL_SCOPES,
37022
+ POSTHOG_OAUTH_REGISTERED_REDIRECT: () => POSTHOG_OAUTH_REGISTERED_REDIRECT,
37023
+ POSTHOG_OAUTH_SCOPES: () => POSTHOG_OAUTH_SCOPES,
36867
37024
  PRESENT_PLAN_REQUIRES_PLAN_MODE: () => PRESENT_PLAN_REQUIRES_PLAN_MODE,
36868
37025
  PRESENT_PLAN_TOOL_DESCRIPTION: () => PRESENT_PLAN_TOOL_DESCRIPTION,
36869
37026
  PROFILE_NOTES_MAX: () => PROFILE_NOTES_MAX,
36870
37027
  PR_DETAILS_JSON_FIELDS: () => PR_DETAILS_JSON_FIELDS,
37028
+ PosthogOAuthCancelledError: () => PosthogOAuthCancelledError,
36871
37029
  READ_ALOUD_RATE_DEFAULT: () => READ_ALOUD_RATE_DEFAULT,
36872
37030
  READ_ALOUD_RATE_MAX: () => READ_ALOUD_RATE_MAX,
36873
37031
  READ_ALOUD_RATE_MIN: () => READ_ALOUD_RATE_MIN,
@@ -37090,6 +37248,7 @@ __export(index_exports, {
37090
37248
  createLinearIssue: () => createLinearIssue,
37091
37249
  createLinearPkce: () => createLinearPkce,
37092
37250
  createOrUpdatePr: () => createOrUpdatePr,
37251
+ createPosthogPkce: () => createPosthogPkce,
37093
37252
  createPrStack: () => createPrStack,
37094
37253
  createSchedule: () => createSchedule,
37095
37254
  createSlackOrgApp: () => createSlackOrgApp,
@@ -37119,6 +37278,7 @@ __export(index_exports, {
37119
37278
  disconnectOptionalService: () => disconnectOptionalService,
37120
37279
  disconnectRemoteAccount: () => disconnectRemoteAccount,
37121
37280
  disconnectSlackWorkspace: () => disconnectSlackWorkspace,
37281
+ discoverPosthogHost: () => discoverPosthogHost,
37122
37282
  discoverSkills: () => discoverSkills,
37123
37283
  downloadAbleTimeAttachment: () => downloadAbleTimeAttachment,
37124
37284
  downloadGitHubIssueAttachment: () => downloadGitHubIssueAttachment,
@@ -37289,6 +37449,7 @@ __export(index_exports, {
37289
37449
  getMcpUiHost: () => getMcpUiHost,
37290
37450
  getOrchestrator: () => getOrchestrator,
37291
37451
  getOrderPlan: () => getOrderPlan,
37452
+ getPosthogAccessToken: () => getPosthogAccessToken,
37292
37453
  getPr: () => getPr,
37293
37454
  getPrChecks: () => getPrChecks,
37294
37455
  getPrCiChecks: () => getPrCiChecks,
@@ -37397,6 +37558,7 @@ __export(index_exports, {
37397
37558
  isPlanQuestionAnswersMessage: () => isPlanQuestionAnswersMessage,
37398
37559
  isPollWrapperToolName: () => isPollWrapperToolName,
37399
37560
  isPosthogConnected: () => isPosthogConnected,
37561
+ isPosthogOAuthCancelled: () => isPosthogOAuthCancelled,
37400
37562
  isPrNotMergeableError: () => isPrNotMergeableError,
37401
37563
  isPresentPlanToolName: () => isPresentPlanToolName,
37402
37564
  isPrimaryCheckoutThread: () => isPrimaryCheckoutThread,
@@ -37625,6 +37787,9 @@ __export(index_exports, {
37625
37787
  pnpmFilterPackage: () => pnpmFilterPackage,
37626
37788
  pollSlackOutboundWatches: () => pollSlackOutboundWatches,
37627
37789
  posixShellSingleQuote: () => posixShellSingleQuote,
37790
+ posthogOAuthAuthorizeUrl: () => posthogOAuthAuthorizeUrl,
37791
+ posthogOAuthClientId: () => posthogOAuthClientId,
37792
+ posthogOAuthScopeParam: () => posthogOAuthScopeParam,
37628
37793
  preferredCursorCostCents: () => preferredCursorCostCents,
37629
37794
  prepareTerminalCommand: () => prepareTerminalCommand,
37630
37795
  prependQueuedItem: () => prependQueuedItem,
@@ -37752,6 +37917,7 @@ __export(index_exports, {
37752
37917
  saveAbleTimeConnection: () => saveAbleTimeConnection,
37753
37918
  saveAppSettings: () => saveAppSettings,
37754
37919
  saveLinearOAuth: () => saveLinearOAuth,
37920
+ savePosthogOAuth: () => savePosthogOAuth,
37755
37921
  saveRemotePhoneToken: () => saveRemotePhoneToken,
37756
37922
  saveSlackOrgCredentials: () => saveSlackOrgCredentials,
37757
37923
  saveWorktreeRunPorts: () => saveWorktreeRunPorts,
@@ -37820,6 +37986,7 @@ __export(index_exports, {
37820
37986
  startLinearOAuth: () => startLinearOAuth,
37821
37987
  startMcpServer: () => startMcpServer,
37822
37988
  startOrchestration: () => startOrchestration,
37989
+ startPosthogOAuth: () => startPosthogOAuth,
37823
37990
  startRelayServer: () => startRelayServer,
37824
37991
  startRemoteAccountLogin: () => startRemoteAccountLogin,
37825
37992
  startSlackOAuth: () => startSlackOAuth,
@@ -39566,10 +39733,10 @@ var MIN_MD_CHARS = 120;
39566
39733
  function oneLine2(value, max) {
39567
39734
  return value.replace(/[`\r\n]/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
39568
39735
  }
39569
- function asRecord15(value) {
39736
+ function asRecord16(value) {
39570
39737
  if (typeof value === "string") {
39571
39738
  try {
39572
- return asRecord15(JSON.parse(value));
39739
+ return asRecord16(JSON.parse(value));
39573
39740
  } catch {
39574
39741
  return void 0;
39575
39742
  }
@@ -39644,7 +39811,7 @@ function toolContent(input) {
39644
39811
  if (!input) return "";
39645
39812
  const direct = input.content;
39646
39813
  if (typeof direct === "string") return direct;
39647
- const nested = asRecord15(direct);
39814
+ const nested = asRecord16(direct);
39648
39815
  if (!nested) return "";
39649
39816
  for (const key of ["html", "markup", "text", "source", "content", "code"]) {
39650
39817
  if (typeof nested[key] === "string") return nested[key];
@@ -39667,7 +39834,7 @@ function phoneArtifactText(text7, parts, limit = Number.POSITIVE_INFINITY) {
39667
39834
  const extras = [];
39668
39835
  for (const part of parts ?? []) {
39669
39836
  if (part.type !== "tool" || part.parentId || !isArtifactTool(part.name)) continue;
39670
- const input = asRecord15(part.input);
39837
+ const input = asRecord16(part.input);
39671
39838
  const content = toolContent(input);
39672
39839
  const hint = artifactHint(content);
39673
39840
  if (hint && hints.has(hint)) continue;
@@ -39686,7 +39853,7 @@ function phoneArtifactText(text7, parts, limit = Number.POSITIVE_INFINITY) {
39686
39853
  ${tail}` : tail;
39687
39854
  }
39688
39855
  function parseOpenArtifact(value, chatId) {
39689
- const record = asRecord15(value);
39856
+ const record = asRecord16(value);
39690
39857
  if (!record) return "invalid";
39691
39858
  const title = oneLine2(str5(record.title), 200);
39692
39859
  if (!title) return "invalid";
@@ -39709,7 +39876,7 @@ function phoneArtifactDocuments(sources) {
39709
39876
  }
39710
39877
  for (const part of source.parts ?? []) {
39711
39878
  if (part.type !== "tool" || part.parentId || !isArtifactTool(part.name)) continue;
39712
- const input = asRecord15(part.input);
39879
+ const input = asRecord16(part.input);
39713
39880
  const content = toolContent(input);
39714
39881
  const hint = artifactHint(content);
39715
39882
  if (hint && hints.has(hint)) continue;
@@ -42852,6 +43019,7 @@ function pushNotes(input) {
42852
43019
  }
42853
43020
  const event = input.event;
42854
43021
  if (!event || event.type !== "turn_finished" && event.type !== "error") return notes;
43022
+ if (event.type === "turn_finished" && event.routineStop) return notes;
42855
43023
  if (fresh.has(event.threadId)) return notes;
42856
43024
  const finished = event.type === "turn_finished" && (event.exitCode === 0 || event.exitCode == null);
42857
43025
  notes.push({ chatId: event.threadId, kind: finished ? "finished" : "failed" });
@@ -47089,6 +47257,281 @@ init_abletime();
47089
47257
  init_abletime_mcp();
47090
47258
  init_abletime_oauth();
47091
47259
  init_optional_services();
47260
+
47261
+ // src/integrations/posthog-oauth.ts
47262
+ var import_node_crypto35 = require("crypto");
47263
+ var import_node_http6 = require("http");
47264
+ init_fetch();
47265
+ init_app_settings();
47266
+ var BAKED_POSTHOG_OAUTH_CLIENT_ID = "https://www.sideboard.build/oauth/posthog-client.json";
47267
+ var POSTHOG_OAUTH_REGISTERED_REDIRECT = "http://127.0.0.1/callback";
47268
+ var POSTHOG_AUTHORIZE = "https://oauth.posthog.com/oauth/authorize/";
47269
+ var POSTHOG_TOKEN = "https://oauth.posthog.com/oauth/token/";
47270
+ var POSTHOG_API_HOSTS = ["https://us.posthog.com", "https://eu.posthog.com"];
47271
+ var POSTHOG_OAUTH_SCOPES = [
47272
+ "project:read",
47273
+ "organization:read",
47274
+ "query:read",
47275
+ "insight:read",
47276
+ "feature_flag:read",
47277
+ "experiment:read",
47278
+ "error_tracking:read",
47279
+ "dashboard:read",
47280
+ "event_definition:read",
47281
+ "property_definition:read",
47282
+ "user:read",
47283
+ "person:read"
47284
+ ];
47285
+ var POSTHOG_OAUTH_OPTIONAL_SCOPES = [
47286
+ "query:write",
47287
+ "insight:write",
47288
+ "feature_flag:write",
47289
+ "experiment:write",
47290
+ "error_tracking:write",
47291
+ "dashboard:write",
47292
+ "person:write",
47293
+ "cohort:read",
47294
+ "cohort:write",
47295
+ "survey:read",
47296
+ "survey:write",
47297
+ "annotation:read",
47298
+ "annotation:write",
47299
+ "session_recording:read",
47300
+ "logs:read"
47301
+ ];
47302
+ var REFRESH_SKEW_MS4 = 6e4;
47303
+ var PosthogOAuthCancelledError = class extends Error {
47304
+ constructor(message = "PostHog sign-in cancelled") {
47305
+ super(message);
47306
+ this.name = "PosthogOAuthCancelledError";
47307
+ }
47308
+ };
47309
+ function isPosthogOAuthCancelled(err) {
47310
+ return err instanceof PosthogOAuthCancelledError;
47311
+ }
47312
+ function posthogOAuthClientId() {
47313
+ return process.env.SIDEBOARD_POSTHOG_OAUTH_CLIENT_ID?.trim() || BAKED_POSTHOG_OAUTH_CLIENT_ID;
47314
+ }
47315
+ function posthogOAuthScopeParam() {
47316
+ return [...POSTHOG_OAUTH_SCOPES, ...POSTHOG_OAUTH_OPTIONAL_SCOPES].join(" ");
47317
+ }
47318
+ function createPosthogPkce() {
47319
+ const verifier = (0, import_node_crypto35.randomBytes)(32).toString("base64url");
47320
+ const challenge = (0, import_node_crypto35.createHash)("sha256").update(verifier).digest("base64url");
47321
+ return { verifier, challenge };
47322
+ }
47323
+ function posthogOAuthAuthorizeUrl(clientId, state, codeChallenge, redirectUri) {
47324
+ const params = new URLSearchParams({
47325
+ client_id: clientId,
47326
+ redirect_uri: redirectUri,
47327
+ response_type: "code",
47328
+ scope: posthogOAuthScopeParam(),
47329
+ state,
47330
+ code_challenge: codeChallenge,
47331
+ code_challenge_method: "S256"
47332
+ });
47333
+ return `${POSTHOG_AUTHORIZE}?${params.toString()}`;
47334
+ }
47335
+ function htmlPage3(title, body) {
47336
+ return `<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>
47337
+ <style>body{font-family:ui-sans-serif,system-ui,sans-serif;padding:48px 24px;max-width:36rem;margin:0 auto;color:#1a1a1a}
47338
+ h1{font-size:1.25rem}p{line-height:1.5;color:#444}</style></head><body>${body}</body></html>`;
47339
+ }
47340
+ async function exchangePosthogToken(body) {
47341
+ const res = await httpFetch(POSTHOG_TOKEN, {
47342
+ method: "POST",
47343
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
47344
+ body
47345
+ });
47346
+ const data = await res.json().catch(() => ({}));
47347
+ if (!res.ok || data.error || !data.access_token?.trim()) {
47348
+ const detail = data.error_description || data.error || `HTTP ${res.status}`;
47349
+ throw new Error(`PostHog sign-in failed: ${detail}`);
47350
+ }
47351
+ return data;
47352
+ }
47353
+ function viewerNameFromMe(body) {
47354
+ const record = body && typeof body === "object" ? body : {};
47355
+ const email = typeof record.email === "string" ? record.email.trim() : "";
47356
+ if (email) return email.slice(0, 120);
47357
+ const first = typeof record.first_name === "string" ? record.first_name.trim() : "";
47358
+ const last = typeof record.last_name === "string" ? record.last_name.trim() : "";
47359
+ const name = [first, last].filter(Boolean).join(" ");
47360
+ return (name || "PostHog user").slice(0, 120);
47361
+ }
47362
+ async function discoverPosthogHost(token) {
47363
+ let last = "PostHog rejected the sign-in";
47364
+ for (const host of POSTHOG_API_HOSTS) {
47365
+ const res = await httpFetch(`${host}/api/users/@me/`, {
47366
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" }
47367
+ });
47368
+ if (res.status === 401 || res.status === 403) {
47369
+ last = `${host} rejected the token`;
47370
+ continue;
47371
+ }
47372
+ if (!res.ok) {
47373
+ last = `${host} returned HTTP ${res.status}`;
47374
+ continue;
47375
+ }
47376
+ const body = await res.json().catch(() => ({}));
47377
+ return { host, viewerName: viewerNameFromMe(body) };
47378
+ }
47379
+ throw new Error(last);
47380
+ }
47381
+ var refreshInFlight4 = null;
47382
+ async function refreshPosthogAccessToken(refresh, host, viewerName, legacy) {
47383
+ try {
47384
+ const data = await exchangePosthogToken(
47385
+ new URLSearchParams({
47386
+ grant_type: "refresh_token",
47387
+ refresh_token: refresh,
47388
+ client_id: posthogOAuthClientId()
47389
+ })
47390
+ );
47391
+ const saved = savePosthogOAuth({
47392
+ accessToken: data.access_token.trim(),
47393
+ refreshToken: data.refresh_token?.trim() || refresh,
47394
+ expiresIn: data.expires_in,
47395
+ host,
47396
+ viewerName
47397
+ });
47398
+ return {
47399
+ token: saved.integrations.posthogAccessToken.trim(),
47400
+ host: saved.integrations.posthogHost?.trim() || host
47401
+ };
47402
+ } catch (err) {
47403
+ if (legacy) return { token: legacy, host };
47404
+ throw err;
47405
+ }
47406
+ }
47407
+ async function getPosthogAccessToken() {
47408
+ const integrations = loadAppSettings().integrations;
47409
+ const host = integrations.posthogHost?.trim() || "https://us.posthog.com";
47410
+ const access = integrations.posthogAccessToken?.trim() || "";
47411
+ const refresh = integrations.posthogRefreshToken?.trim() || "";
47412
+ const legacy = integrations.posthogPersonalApiKey?.trim() || "";
47413
+ const exp = integrations.posthogTokenExpiresAt;
47414
+ const accessFresh = Boolean(access) && (exp == null || exp - Date.now() > REFRESH_SKEW_MS4);
47415
+ if (accessFresh) return { token: access, host };
47416
+ if (refresh) {
47417
+ if (!refreshInFlight4) {
47418
+ refreshInFlight4 = refreshPosthogAccessToken(
47419
+ refresh,
47420
+ host,
47421
+ integrations.posthogViewerName,
47422
+ legacy
47423
+ ).finally(() => {
47424
+ refreshInFlight4 = null;
47425
+ });
47426
+ }
47427
+ return refreshInFlight4;
47428
+ }
47429
+ if (access) return { token: access, host };
47430
+ if (legacy) return { token: legacy, host };
47431
+ return null;
47432
+ }
47433
+ async function startPosthogOAuth(opts) {
47434
+ if (opts?.signal?.aborted) throw new PosthogOAuthCancelledError();
47435
+ const clientId = posthogOAuthClientId();
47436
+ const state = (0, import_node_crypto35.randomBytes)(16).toString("hex");
47437
+ const pkce = createPosthogPkce();
47438
+ const timeoutMs = opts?.timeoutMs ?? 5 * 6e4;
47439
+ const code = await new Promise((resolve3, reject) => {
47440
+ let settled = false;
47441
+ const finish2 = (err, value) => {
47442
+ if (settled) return;
47443
+ settled = true;
47444
+ cleanup();
47445
+ if (err) reject(err);
47446
+ else resolve3(value);
47447
+ };
47448
+ const server = (0, import_node_http6.createServer)((req, res) => {
47449
+ try {
47450
+ const url = new URL(req.url || "/", "http://127.0.0.1");
47451
+ if (url.pathname !== "/callback") {
47452
+ res.writeHead(404);
47453
+ res.end("Not found");
47454
+ return;
47455
+ }
47456
+ const err = url.searchParams.get("error");
47457
+ const gotState = url.searchParams.get("state");
47458
+ const gotCode = url.searchParams.get("code");
47459
+ if (err) {
47460
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
47461
+ res.end(htmlPage3("PostHog", "<h1>Authorization cancelled</h1><p>You can close this tab.</p>"));
47462
+ finish2(new PosthogOAuthCancelledError());
47463
+ return;
47464
+ }
47465
+ if (gotState !== state || !gotCode) {
47466
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
47467
+ res.end(htmlPage3("PostHog", "<h1>Invalid callback</h1><p>State or code missing.</p>"));
47468
+ finish2(new Error("PostHog sign-in callback was invalid"));
47469
+ return;
47470
+ }
47471
+ const addr = server.address();
47472
+ const port = addr && typeof addr !== "string" ? addr.port : 0;
47473
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
47474
+ res.end(
47475
+ htmlPage3(
47476
+ "PostHog connected",
47477
+ "<h1>PostHog connected</h1><p>You can close this tab and return to Sideboard.</p>"
47478
+ )
47479
+ );
47480
+ finish2(void 0, { code: gotCode, redirectUri: `http://127.0.0.1:${port}/callback` });
47481
+ } catch (e) {
47482
+ finish2(e instanceof Error ? e : new Error(String(e)));
47483
+ }
47484
+ });
47485
+ const timer2 = setTimeout(() => finish2(new Error("PostHog sign-in timed out \u2014 try again")), timeoutMs);
47486
+ const onAbort = () => finish2(new PosthogOAuthCancelledError());
47487
+ const cleanup = () => {
47488
+ clearTimeout(timer2);
47489
+ opts?.signal?.removeEventListener("abort", onAbort);
47490
+ server.close();
47491
+ };
47492
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
47493
+ if (opts?.signal?.aborted) {
47494
+ onAbort();
47495
+ return;
47496
+ }
47497
+ server.on("error", (e) => {
47498
+ finish2(e instanceof Error ? e : new Error(String(e)));
47499
+ });
47500
+ server.listen(0, "127.0.0.1", () => {
47501
+ const addr = server.address();
47502
+ const port = addr && typeof addr !== "string" ? addr.port : 0;
47503
+ if (!port) {
47504
+ finish2(new Error("PostHog sign-in could not bind a local port"));
47505
+ return;
47506
+ }
47507
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
47508
+ const authorizeUrl = posthogOAuthAuthorizeUrl(clientId, state, pkce.challenge, redirectUri);
47509
+ void Promise.resolve(opts?.openUrl?.(authorizeUrl)).catch((e) => {
47510
+ finish2(e instanceof Error ? e : new Error(String(e)));
47511
+ });
47512
+ });
47513
+ });
47514
+ const data = await exchangePosthogToken(
47515
+ new URLSearchParams({
47516
+ grant_type: "authorization_code",
47517
+ code: code.code,
47518
+ redirect_uri: code.redirectUri,
47519
+ client_id: clientId,
47520
+ code_verifier: pkce.verifier
47521
+ })
47522
+ );
47523
+ const token = data.access_token.trim();
47524
+ const discovered = await discoverPosthogHost(token);
47525
+ return savePosthogOAuth({
47526
+ accessToken: token,
47527
+ refreshToken: data.refresh_token?.trim(),
47528
+ expiresIn: data.expires_in,
47529
+ host: discovered.host,
47530
+ viewerName: discovered.viewerName
47531
+ });
47532
+ }
47533
+
47534
+ // src/index.ts
47092
47535
  init_optional_cli();
47093
47536
  init_fetch();
47094
47537
  init_system_ca();
@@ -47165,7 +47608,7 @@ init_stage_files();
47165
47608
  init_consume_attachments();
47166
47609
 
47167
47610
  // src/composer/pasted-text.ts
47168
- var import_node_crypto35 = require("crypto");
47611
+ var import_node_crypto36 = require("crypto");
47169
47612
  var PASTE_ATTACH_MIN_CHARS = 1200;
47170
47613
  var PASTE_ATTACH_MIN_LINES = 15;
47171
47614
  var PASTED_NAME_RE = /^Pasted text #(\d+)\.txt$/i;
@@ -47192,7 +47635,7 @@ function nextPastedTextName(existing) {
47192
47635
  }
47193
47636
  function buildPastedTextAttachment(text7, opts) {
47194
47637
  return {
47195
- id: opts?.id ?? (0, import_node_crypto35.randomUUID)(),
47638
+ id: opts?.id ?? (0, import_node_crypto36.randomUUID)(),
47196
47639
  name: opts?.name ?? "Pasted text #1.txt",
47197
47640
  kind: "file",
47198
47641
  path: opts?.path,
@@ -47368,7 +47811,7 @@ function createClippedMcpServer() {
47368
47811
 
47369
47812
  // src/mcp/server.ts
47370
47813
  var import_zod12 = require("zod");
47371
- var import_node_crypto38 = require("crypto");
47814
+ var import_node_crypto39 = require("crypto");
47372
47815
  var import_node_path82 = require("path");
47373
47816
  init_orchestrator();
47374
47817
  init_task_state();
@@ -48565,9 +49008,16 @@ async function runPosthogApi(input) {
48565
49008
  if (method === "GET" && input.body !== void 0) {
48566
49009
  return mcpJson({ ok: false, error: "GET does not take a body" }, true);
48567
49010
  }
48568
- const integrations = loadAppSettings().integrations;
48569
- const token = integrations.posthogPersonalApiKey?.trim();
48570
- if (!token) {
49011
+ let session;
49012
+ try {
49013
+ session = await getPosthogAccessToken();
49014
+ } catch (err) {
49015
+ return mcpJson(
49016
+ { ok: false, error: err instanceof Error ? err.message : String(err) },
49017
+ true
49018
+ );
49019
+ }
49020
+ if (!session) {
48571
49021
  return mcpJson(
48572
49022
  { ok: false, error: "PostHog is not connected (Settings \u2192 Connectors)." },
48573
49023
  true
@@ -48576,7 +49026,7 @@ async function runPosthogApi(input) {
48576
49026
  let url;
48577
49027
  try {
48578
49028
  url = posthogApiUrl(
48579
- integrations.posthogHost || "https://us.posthog.com",
49029
+ session.host,
48580
49030
  withPosthogSlash(method, input.path),
48581
49031
  input.query
48582
49032
  );
@@ -48587,7 +49037,7 @@ async function runPosthogApi(input) {
48587
49037
  );
48588
49038
  }
48589
49039
  const headers = {
48590
- Authorization: `Bearer ${token}`,
49040
+ Authorization: `Bearer ${session.token}`,
48591
49041
  Accept: "application/json"
48592
49042
  };
48593
49043
  let body;
@@ -49361,7 +49811,7 @@ function registerOrderTools(server) {
49361
49811
  }
49362
49812
 
49363
49813
  // src/agent-rpc/handlers.ts
49364
- var import_node_crypto36 = require("crypto");
49814
+ var import_node_crypto37 = require("crypto");
49365
49815
  var import_node_path79 = require("path");
49366
49816
  init_wait_for_job();
49367
49817
  init_wait_for_turn();
@@ -49392,7 +49842,7 @@ setToolPermissionPublisher({
49392
49842
  }
49393
49843
  }
49394
49844
  });
49395
- function asRecord16(value) {
49845
+ function asRecord17(value) {
49396
49846
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
49397
49847
  return value;
49398
49848
  }
@@ -49403,12 +49853,12 @@ function invalidParams(message) {
49403
49853
  return Object.assign(new Error(message), { rpcCode: -32602 });
49404
49854
  }
49405
49855
  var handlePermissionAsk = async (params, _ctx) => {
49406
- const rec = asRecord16(params);
49856
+ const rec = asRecord17(params);
49407
49857
  const threadId = str6(rec.threadId).trim();
49408
49858
  const toolName = str6(rec.toolName).trim();
49409
49859
  if (!threadId) throw invalidParams("threadId is required");
49410
49860
  if (!toolName) throw invalidParams("toolName is required");
49411
- const input = asRecord16(rec.input);
49861
+ const input = asRecord17(rec.input);
49412
49862
  const ask = {
49413
49863
  threadId,
49414
49864
  toolName,
@@ -49444,7 +49894,7 @@ var handlePermissionAsk = async (params, _ctx) => {
49444
49894
  // src/agent-rpc/handlers.ts
49445
49895
  init_protocol2();
49446
49896
  function presentArtifactResult(input) {
49447
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto36.randomUUID)().slice(0, 8)}`;
49897
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto37.randomUUID)().slice(0, 8)}`;
49448
49898
  return {
49449
49899
  ok: true,
49450
49900
  artifact_id: id,
@@ -49456,7 +49906,7 @@ function presentArtifactResult(input) {
49456
49906
  message: input.type === "log" ? "Log accepted. Same artifact_id appends; send only new lines next time." : "Artifact accepted. Sideboard desktop opens it in the side column beside chat."
49457
49907
  };
49458
49908
  }
49459
- function asRecord17(value) {
49909
+ function asRecord18(value) {
49460
49910
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
49461
49911
  return value;
49462
49912
  }
@@ -49480,7 +49930,7 @@ async function handleRuntimePing(_params, _ctx) {
49480
49930
  };
49481
49931
  }
49482
49932
  async function handlePresentArtifact(params, _ctx) {
49483
- const rec = asRecord17(params);
49933
+ const rec = asRecord18(params);
49484
49934
  const title = str7(rec.title).trim();
49485
49935
  const type = str7(rec.type).trim();
49486
49936
  const allowed = ["html", "svg", "markdown", "react", "log"];
@@ -49504,7 +49954,7 @@ async function handlePresentArtifact(params, _ctx) {
49504
49954
  });
49505
49955
  }
49506
49956
  async function handleJobWait(params, ctx, waitFn = waitForDetachedJob) {
49507
- const rec = asRecord17(params);
49957
+ const rec = asRecord18(params);
49508
49958
  const id = str7(rec.id).trim();
49509
49959
  if (!id) throw invalidParams2("id is required");
49510
49960
  const cwd = jobCwd(rec);
@@ -49528,7 +49978,7 @@ async function handleJobWait(params, ctx, waitFn = waitForDetachedJob) {
49528
49978
  };
49529
49979
  }
49530
49980
  async function handleJobStop(params, _ctx) {
49531
- const rec = asRecord17(params);
49981
+ const rec = asRecord18(params);
49532
49982
  const id = str7(rec.id).trim();
49533
49983
  if (!id) throw invalidParams2("id is required");
49534
49984
  const reason = str7(rec.reason).trim() || void 0;
@@ -49556,7 +50006,7 @@ async function defaultTurnWait(ref, timeoutMs) {
49556
50006
  });
49557
50007
  }
49558
50008
  async function handleTurnWait(params, ctx, waitFn = defaultTurnWait) {
49559
- const rec = asRecord17(params);
50009
+ const rec = asRecord18(params);
49560
50010
  const ref = str7(rec.ref).trim();
49561
50011
  if (!ref) throw invalidParams2("ref is required");
49562
50012
  const requested = typeof rec.timeoutMs === "number" && Number.isFinite(rec.timeoutMs) ? rec.timeoutMs : void 0;
@@ -49608,7 +50058,7 @@ init_worktree();
49608
50058
  init_paths();
49609
50059
 
49610
50060
  // src/board/board-pins.ts
49611
- var import_node_crypto37 = require("crypto");
50061
+ var import_node_crypto38 = require("crypto");
49612
50062
  var import_node_fs79 = require("fs");
49613
50063
  var import_node_path80 = require("path");
49614
50064
  init_paths();
@@ -49640,7 +50090,7 @@ function addBoardPin(input) {
49640
50090
  const ref = input.ref.trim();
49641
50091
  if (!ref) throw new Error("Board item needs a ref");
49642
50092
  const pin = {
49643
- id: (0, import_node_crypto37.randomUUID)(),
50093
+ id: (0, import_node_crypto38.randomUUID)(),
49644
50094
  kind: input.kind,
49645
50095
  ref,
49646
50096
  repoPath: input.repoPath.trim(),
@@ -50604,7 +51054,7 @@ async function startMcpServer() {
50604
51054
  const ident = issue?.identifier ?? ref.trim();
50605
51055
  const attachments = issue ? [
50606
51056
  {
50607
- id: (0, import_node_crypto38.randomUUID)(),
51057
+ id: (0, import_node_crypto39.randomUUID)(),
50608
51058
  name: issue.identifier,
50609
51059
  kind: "issue",
50610
51060
  content: [
@@ -51166,8 +51616,8 @@ init_protocol2();
51166
51616
  init_metadata();
51167
51617
 
51168
51618
  // src/agent-rpc/server.ts
51169
- var import_node_crypto39 = require("crypto");
51170
- var import_node_http6 = require("http");
51619
+ var import_node_crypto40 = require("crypto");
51620
+ var import_node_http7 = require("http");
51171
51621
  var import_ws5 = require("ws");
51172
51622
  init_protocol2();
51173
51623
  init_metadata();
@@ -51175,7 +51625,7 @@ function tokensEqual(a, b) {
51175
51625
  const left = Buffer.from(a);
51176
51626
  const right = Buffer.from(b);
51177
51627
  if (left.length !== right.length) return false;
51178
- return (0, import_node_crypto39.timingSafeEqual)(left, right);
51628
+ return (0, import_node_crypto40.timingSafeEqual)(left, right);
51179
51629
  }
51180
51630
  function authTokenFromUpgrade(req) {
51181
51631
  try {
@@ -51208,16 +51658,16 @@ var AgentRpcServer = class {
51208
51658
  async listen(opts = {}) {
51209
51659
  const host = opts.host ?? "127.0.0.1";
51210
51660
  const port = opts.port ?? 0;
51211
- const authToken = (0, import_node_crypto39.randomBytes)(24).toString("base64url");
51661
+ const authToken = (0, import_node_crypto40.randomBytes)(24).toString("base64url");
51212
51662
  this.meta = {
51213
- runtimeId: (0, import_node_crypto39.randomUUID)(),
51663
+ runtimeId: (0, import_node_crypto40.randomUUID)(),
51214
51664
  pid: process.pid,
51215
51665
  protocolVersion: AGENT_RPC_PROTOCOL_VERSION,
51216
51666
  authToken,
51217
51667
  startedAt: Date.now(),
51218
51668
  transports: []
51219
51669
  };
51220
- const http = (0, import_node_http6.createServer)((_req, res) => {
51670
+ const http = (0, import_node_http7.createServer)((_req, res) => {
51221
51671
  res.statusCode = 404;
51222
51672
  res.end();
51223
51673
  });
@@ -51359,7 +51809,7 @@ init_home_board();
51359
51809
  init_abletime();
51360
51810
  init_abletime_mcp();
51361
51811
  init_abletime_rest();
51362
- function asRecord18(value) {
51812
+ function asRecord19(value) {
51363
51813
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
51364
51814
  }
51365
51815
  function asString5(value) {
@@ -51376,7 +51826,7 @@ function firstString5(record, keys) {
51376
51826
  function firstRecord2(record, keys) {
51377
51827
  if (!record) return null;
51378
51828
  for (const key of keys) {
51379
- const value = asRecord18(record[key]);
51829
+ const value = asRecord19(record[key]);
51380
51830
  if (value) return value;
51381
51831
  }
51382
51832
  return null;
@@ -51390,7 +51840,7 @@ function identifierFromUnknown(value) {
51390
51840
  return id2 ? [id2] : [];
51391
51841
  }
51392
51842
  if (Array.isArray(value)) return value.flatMap(identifierFromUnknown);
51393
- const rec = asRecord18(value);
51843
+ const rec = asRecord19(value);
51394
51844
  if (!rec) return [];
51395
51845
  for (const key of ["nodes", "data", "tasks", "items"]) {
51396
51846
  if (Array.isArray(rec[key])) return identifierFromUnknown(rec[key]);
@@ -51400,7 +51850,7 @@ function identifierFromUnknown(value) {
51400
51850
  return id ? [id] : [];
51401
51851
  }
51402
51852
  function ableTimeBlockedByIdentifiers(raw) {
51403
- const record = asRecord18(raw);
51853
+ const record = asRecord19(raw);
51404
51854
  const nested = firstRecord2(record, ["task", "data"]) ?? record;
51405
51855
  if (!nested) return [];
51406
51856
  const value = nested.blocked_by ?? nested.blockedBy ?? nested.depends_on ?? nested.dependsOn ?? nested.dependencyParentTimeflowTaskId ?? nested.wait_on ?? nested.waitOn;
@@ -51415,7 +51865,7 @@ function ableTimeBlockedByIdentifiers(raw) {
51415
51865
  return out;
51416
51866
  }
51417
51867
  function taskReference(raw) {
51418
- const record = asRecord18(raw);
51868
+ const record = asRecord19(raw);
51419
51869
  const nested = firstRecord2(record, ["task", "data"]) ?? record;
51420
51870
  return firstString5(nested, ["taskRef", "reference", "identifier"]);
51421
51871
  }
@@ -51430,7 +51880,7 @@ async function getAbleTimeIssueBlockedBy(id, opts) {
51430
51880
  continue;
51431
51881
  }
51432
51882
  const parent = await callAbleTimeTool("get_task", { id: blockerId, task_id: blockerId }, opts);
51433
- const parentRecord = firstRecord2(asRecord18(parent), ["task", "data"]) ?? asRecord18(parent);
51883
+ const parentRecord = firstRecord2(asRecord19(parent), ["task", "data"]) ?? asRecord19(parent);
51434
51884
  if (ableTimeStateIsClosed(taskState(parentRecord))) continue;
51435
51885
  const ref = taskReference(parent);
51436
51886
  if (!ref || looksLikeAbleTimeUlid(ref)) {
@@ -52989,7 +53439,7 @@ function resolveSlackListenMode(opts) {
52989
53439
  init_protocol();
52990
53440
 
52991
53441
  // src/relay/account-login.ts
52992
- var import_node_crypto40 = require("crypto");
53442
+ var import_node_crypto41 = require("crypto");
52993
53443
  init_fetch();
52994
53444
  init_protocol();
52995
53445
  var RemoteAccountLoginCancelled = class extends Error {
@@ -53057,7 +53507,7 @@ async function readJson6(res, url) {
53057
53507
  async function startRemoteAccountLogin(opts) {
53058
53508
  if (opts.signal?.aborted) throw new RemoteAccountLoginCancelled();
53059
53509
  const origin = (opts.origin ?? remoteAccountHttpOrigin()).replace(/\/+$/, "");
53060
- const state = (0, import_node_crypto40.randomBytes)(16).toString("hex");
53510
+ const state = (0, import_node_crypto41.randomBytes)(16).toString("hex");
53061
53511
  const timeoutMs = opts.timeoutMs ?? 5 * 6e4;
53062
53512
  const pollIntervalMs = opts.pollIntervalMs ?? 400;
53063
53513
  const linkToken = opts.linkToken?.trim() ?? "";
@@ -53482,6 +53932,7 @@ async function pollSlackOutboundWatches(opts) {
53482
53932
  ATTACHMENTS_DIR,
53483
53933
  AbleTimeOAuthCancelledError,
53484
53934
  BAKED_ABLETIME_OAUTH_CLIENT_ID,
53935
+ BAKED_POSTHOG_OAUTH_CLIENT_ID,
53485
53936
  BAKED_REMOTE_RELAY_URL,
53486
53937
  BAKED_SLACK_CLIENT_ID,
53487
53938
  BAKED_SLACK_RELAY_URL,
@@ -53569,10 +54020,14 @@ async function pollSlackOutboundWatches(opts) {
53569
54020
  PLAN_MODE_OFF_INSTRUCTION,
53570
54021
  PLAN_QUESTION_ANSWERS_PREFIX,
53571
54022
  PORT_RANGE_SIZE,
54023
+ POSTHOG_OAUTH_OPTIONAL_SCOPES,
54024
+ POSTHOG_OAUTH_REGISTERED_REDIRECT,
54025
+ POSTHOG_OAUTH_SCOPES,
53572
54026
  PRESENT_PLAN_REQUIRES_PLAN_MODE,
53573
54027
  PRESENT_PLAN_TOOL_DESCRIPTION,
53574
54028
  PROFILE_NOTES_MAX,
53575
54029
  PR_DETAILS_JSON_FIELDS,
54030
+ PosthogOAuthCancelledError,
53576
54031
  READ_ALOUD_RATE_DEFAULT,
53577
54032
  READ_ALOUD_RATE_MAX,
53578
54033
  READ_ALOUD_RATE_MIN,
@@ -53795,6 +54250,7 @@ async function pollSlackOutboundWatches(opts) {
53795
54250
  createLinearIssue,
53796
54251
  createLinearPkce,
53797
54252
  createOrUpdatePr,
54253
+ createPosthogPkce,
53798
54254
  createPrStack,
53799
54255
  createSchedule,
53800
54256
  createSlackOrgApp,
@@ -53824,6 +54280,7 @@ async function pollSlackOutboundWatches(opts) {
53824
54280
  disconnectOptionalService,
53825
54281
  disconnectRemoteAccount,
53826
54282
  disconnectSlackWorkspace,
54283
+ discoverPosthogHost,
53827
54284
  discoverSkills,
53828
54285
  downloadAbleTimeAttachment,
53829
54286
  downloadGitHubIssueAttachment,
@@ -53994,6 +54451,7 @@ async function pollSlackOutboundWatches(opts) {
53994
54451
  getMcpUiHost,
53995
54452
  getOrchestrator,
53996
54453
  getOrderPlan,
54454
+ getPosthogAccessToken,
53997
54455
  getPr,
53998
54456
  getPrChecks,
53999
54457
  getPrCiChecks,
@@ -54102,6 +54560,7 @@ async function pollSlackOutboundWatches(opts) {
54102
54560
  isPlanQuestionAnswersMessage,
54103
54561
  isPollWrapperToolName,
54104
54562
  isPosthogConnected,
54563
+ isPosthogOAuthCancelled,
54105
54564
  isPrNotMergeableError,
54106
54565
  isPresentPlanToolName,
54107
54566
  isPrimaryCheckoutThread,
@@ -54330,6 +54789,9 @@ async function pollSlackOutboundWatches(opts) {
54330
54789
  pnpmFilterPackage,
54331
54790
  pollSlackOutboundWatches,
54332
54791
  posixShellSingleQuote,
54792
+ posthogOAuthAuthorizeUrl,
54793
+ posthogOAuthClientId,
54794
+ posthogOAuthScopeParam,
54333
54795
  preferredCursorCostCents,
54334
54796
  prepareTerminalCommand,
54335
54797
  prependQueuedItem,
@@ -54457,6 +54919,7 @@ async function pollSlackOutboundWatches(opts) {
54457
54919
  saveAbleTimeConnection,
54458
54920
  saveAppSettings,
54459
54921
  saveLinearOAuth,
54922
+ savePosthogOAuth,
54460
54923
  saveRemotePhoneToken,
54461
54924
  saveSlackOrgCredentials,
54462
54925
  saveWorktreeRunPorts,
@@ -54525,6 +54988,7 @@ async function pollSlackOutboundWatches(opts) {
54525
54988
  startLinearOAuth,
54526
54989
  startMcpServer,
54527
54990
  startOrchestration,
54991
+ startPosthogOAuth,
54528
54992
  startRelayServer,
54529
54993
  startRemoteAccountLogin,
54530
54994
  startSlackOAuth,