@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
@@ -4326,6 +4326,12 @@ function normalizeVault(raw) {
4326
4326
  if (typeof raw.posthogPersonalApiKey === "string" && raw.posthogPersonalApiKey.trim()) {
4327
4327
  out.posthogPersonalApiKey = raw.posthogPersonalApiKey.trim();
4328
4328
  }
4329
+ if (typeof raw.posthogAccessToken === "string" && raw.posthogAccessToken.trim()) {
4330
+ out.posthogAccessToken = raw.posthogAccessToken.trim();
4331
+ }
4332
+ if (typeof raw.posthogRefreshToken === "string" && raw.posthogRefreshToken.trim()) {
4333
+ out.posthogRefreshToken = raw.posthogRefreshToken.trim();
4334
+ }
4329
4335
  if (typeof raw.sentryAuthToken === "string" && raw.sentryAuthToken.trim()) {
4330
4336
  out.sentryAuthToken = raw.sentryAuthToken.trim();
4331
4337
  }
@@ -4968,6 +4974,7 @@ __export(app_settings_exports, {
4968
4974
  saveAbleTimeConnection: () => saveAbleTimeConnection,
4969
4975
  saveAppSettings: () => saveAppSettings,
4970
4976
  saveLinearOAuth: () => saveLinearOAuth,
4977
+ savePosthogOAuth: () => savePosthogOAuth,
4971
4978
  selectManagedAccount: () => selectManagedAccount,
4972
4979
  showCostEnabled: () => showCostEnabled,
4973
4980
  slackAppLevelToken: () => slackAppLevelToken,
@@ -5040,7 +5047,7 @@ function toPublicAppSettings(settings) {
5040
5047
  hasAbleTimeOAuth: Boolean(settings.integrations.abletimeRefreshToken?.trim()),
5041
5048
  hasVercelToken: Boolean(settings.integrations.vercelToken?.trim()),
5042
5049
  hasSupabaseToken: Boolean(settings.integrations.supabaseAccessToken?.trim()),
5043
- hasPosthogToken: Boolean(settings.integrations.posthogPersonalApiKey?.trim()),
5050
+ hasPosthogToken: hasPosthogCredentials(settings.integrations),
5044
5051
  hasSentryToken: Boolean(settings.integrations.sentryAuthToken?.trim()),
5045
5052
  hasRemoteAccount: Boolean(settings.integrations.remoteAccountToken?.trim())
5046
5053
  }
@@ -5236,6 +5243,12 @@ function normalizeIntegrations(raw) {
5236
5243
  const key = source.posthogPersonalApiKey.trim();
5237
5244
  if (key) out.posthogPersonalApiKey = key;
5238
5245
  }
5246
+ for (const key of ["posthogAccessToken", "posthogRefreshToken"]) {
5247
+ const token = typeof source[key] === "string" ? source[key].trim() : "";
5248
+ if (token) out[key] = token;
5249
+ }
5250
+ const posthogExp = Number(source.posthogTokenExpiresAt);
5251
+ if (Number.isFinite(posthogExp)) out.posthogTokenExpiresAt = posthogExp;
5239
5252
  if (typeof source.posthogHost === "string") {
5240
5253
  const host = source.posthogHost.trim();
5241
5254
  if (host) out.posthogHost = host;
@@ -6154,8 +6167,26 @@ function disconnectLinearConnection() {
6154
6167
  delete integrations.linearOrganizationName;
6155
6168
  return saveAppSettings({ ...current, integrations });
6156
6169
  }
6170
+ function hasPosthogCredentials(integrations) {
6171
+ return Boolean(
6172
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
6173
+ );
6174
+ }
6157
6175
  function isPosthogConnected(settings = loadAppSettings()) {
6158
- return Boolean(settings.integrations.posthogPersonalApiKey?.trim());
6176
+ return hasPosthogCredentials(settings.integrations);
6177
+ }
6178
+ function savePosthogOAuth(input) {
6179
+ const current = loadAppSettings();
6180
+ const integrations = { ...current.integrations };
6181
+ integrations.posthogAccessToken = input.accessToken.trim();
6182
+ if (input.refreshToken?.trim()) integrations.posthogRefreshToken = input.refreshToken.trim();
6183
+ if (typeof input.expiresIn === "number" && Number.isFinite(input.expiresIn)) {
6184
+ integrations.posthogTokenExpiresAt = Date.now() + Math.max(0, input.expiresIn) * 1e3;
6185
+ }
6186
+ if (input.host?.trim()) integrations.posthogHost = input.host.trim();
6187
+ if (input.viewerName?.trim()) integrations.posthogViewerName = input.viewerName.trim().slice(0, 120);
6188
+ delete integrations.posthogPersonalApiKey;
6189
+ return saveAppSettings({ ...current, integrations });
6159
6190
  }
6160
6191
  function isAbleTimeConnected(settings = loadAppSettings()) {
6161
6192
  return Boolean(
@@ -6606,6 +6637,8 @@ var init_app_settings = __esm({
6606
6637
  "vercelToken",
6607
6638
  "supabaseAccessToken",
6608
6639
  "posthogPersonalApiKey",
6640
+ "posthogAccessToken",
6641
+ "posthogRefreshToken",
6609
6642
  "sentryAuthToken"
6610
6643
  ];
6611
6644
  CLOUD_CONNECT_AGENTS = /* @__PURE__ */ new Set([
@@ -8702,14 +8735,14 @@ function fileMtimeMs(path) {
8702
8735
  }
8703
8736
  }
8704
8737
  function rememberThread(thread, mtimeMs) {
8705
- const cache = cacheForDir();
8706
- cache.byId.set(thread.id, thread);
8707
- if (mtimeMs != null) cache.mtimeMs.set(thread.id, mtimeMs);
8738
+ const cache2 = cacheForDir();
8739
+ cache2.byId.set(thread.id, thread);
8740
+ if (mtimeMs != null) cache2.mtimeMs.set(thread.id, mtimeMs);
8708
8741
  }
8709
8742
  function forgetThread(id) {
8710
- const cache = cacheForDir();
8711
- cache.byId.delete(id);
8712
- cache.mtimeMs.delete(id);
8743
+ const cache2 = cacheForDir();
8744
+ cache2.byId.delete(id);
8745
+ cache2.mtimeMs.delete(id);
8713
8746
  selfWriteMtimes.delete(id);
8714
8747
  }
8715
8748
  function invalidateThreadListCache() {
@@ -8726,9 +8759,9 @@ function readThread(id) {
8726
8759
  forgetThread(id);
8727
8760
  return null;
8728
8761
  }
8729
- const cache = cacheForDir();
8730
- const cached = cache.byId.get(id);
8731
- if (cached && cache.mtimeMs.get(id) === mtimeMs) return cached;
8762
+ const cache2 = cacheForDir();
8763
+ const cached = cache2.byId.get(id);
8764
+ if (cached && cache2.mtimeMs.get(id) === mtimeMs) return cached;
8732
8765
  const raw = (0, import_node_fs17.readFileSync)(path, "utf8");
8733
8766
  const thread = normalizeThread(JSON.parse(raw));
8734
8767
  rememberThread(thread, mtimeMs);
@@ -8757,7 +8790,7 @@ function isThreadRecordFile(nameOrPath) {
8757
8790
  return name.endsWith(".json") && !name.endsWith(".live.json") && !name.endsWith(".setup.log.json");
8758
8791
  }
8759
8792
  function listThreads(opts) {
8760
- const cache = cacheForDir();
8793
+ const cache2 = cacheForDir();
8761
8794
  const files = (0, import_node_fs17.readdirSync)(threadsDir()).filter(isThreadRecordFile);
8762
8795
  const seen = /* @__PURE__ */ new Set();
8763
8796
  for (const f of files) {
@@ -8769,10 +8802,10 @@ function listThreads(opts) {
8769
8802
  } catch {
8770
8803
  }
8771
8804
  }
8772
- for (const id of [...cache.byId.keys()]) {
8805
+ for (const id of [...cache2.byId.keys()]) {
8773
8806
  if (!seen.has(id)) forgetThread(id);
8774
8807
  }
8775
- const threads = [...cache.byId.values()].sort(
8808
+ const threads = [...cache2.byId.values()].sort(
8776
8809
  (a, b) => b.updatedAt.localeCompare(a.updatedAt)
8777
8810
  );
8778
8811
  if (opts?.includeArchived) return threads;
@@ -11221,7 +11254,7 @@ var init_coordinator_prompt = __esm({
11221
11254
  "- linear_* (when Linear is connected) \u2014 list_teams for team key/states; linear_list_projects for project names; get/search include the project a ticket is on; get/create/update/comment with ENG-123. Worktree agents have the same Account tools \u2014 prefer they comment, update status, and create spin-offs (parent=) on their own ticket when they were asked to do the work. When reviewing a PR or ticket, do not comment or update until the user types a next step \u2014 they should work through the feedback in chat first. Do not tell the child to ask_user after the review. Scope errors: reconnect Linear in Account settings. Prefer these over any Linear MCP the CLI may still list. Worktree agents use the Claude Linear connector only when Account Linear is not set or the Sideboard call fails, and they do not mention that connector startup failure when Sideboard works.",
11222
11255
  "- github_* \u2014 get/comment/update/create GitHub issues via Account `gh` (#123). github_list_projects and get/search include GitHub Projects. projectsError or a missing read:project scope \u2192 `gh auth refresh -s read:project`. Worktree agents have these too. Prefer Sideboard `github_*` while Account `gh` works. A failed Claude GitHub connector (`mcp_github_github`) is not a Sideboard outage \u2014 do not mention it. Use that connector only when `gh` is not set up or the Sideboard call fails. Pass parent= for spin-offs. When reviewing a PR or ticket, do not comment, submit `gh pr review`, or update the PR/ticket until the user types a next step.",
11223
11256
  "- abletime_* (when AbleTime is connected) \u2014 orientation first; abletime_list_projects lists projects; get/list include the project a task is on; get/comment/update/create (parent= for spin-offs); ensure_task when work has no ticket (or create_workspace from the default branch auto-creates one). Worktree agents have the same Account tools. Same review-write gate as Linear/GitHub.",
11224
- "- Optional connectors (Vercel, Supabase, Sentry) in Settings \u2192 Connectors inject tokens into worktree agent env when connected. Prefer official CLIs (`vercel`, `supabase`, `sentry-cli`). When Settings \u2192 Connectors has a PostHog personal API key, PostHog is the Sideboard tool `posthog_api` (GET by default; POST `/api/projects/:id/query/` or `/api/environments/:id/query/` is a read and does not need write=true; other POST and PATCH need write=true only when the user asked to change data). The PostHog key stays in the vault \u2014 do not read it from the environment, and do not sign in to a PostHog MCP. When no PostHog API key is set, use the Claude PostHog connector. When a key is set, ignore a failed Claude PostHog connector and do not sign in to a PostHog MCP. If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized while that Sideboard token is set, do not sign in \u2014 use the native CLI. When that token is not set or the CLI call fails, the Claude connector is the fallback. Do not mention a Claude connector startup failure when the Sideboard connection works. Tell any worktree agent (Claude / Cursor / Codex / OpenCode) to write CLI output to `.context/cli/` and read a slice. If a CLI is missing, the user presses Install CLI on that row. Do not add vendor MCPs. Git (`gh`) stays Settings \u2192 Git; issue tracking stays Settings \u2192 Issues. The phone remote is Settings \u2192 Remote \u2014 do not look up Slack users.",
11257
+ "- Optional connectors (Vercel, Supabase, Sentry) in Settings \u2192 Connectors inject tokens into worktree agent env when connected. Prefer official CLIs (`vercel`, `supabase`, `sentry-cli`). When Settings \u2192 Connectors is signed in to PostHog, PostHog is the Sideboard tool `posthog_api` (GET by default; POST `/api/projects/:id/query/` or `/api/environments/:id/query/` is a read and does not need write=true; other POST and PATCH need write=true only when the user asked to change data). The PostHog token stays in the vault \u2014 do not read it from the environment, and do not sign in to a PostHog MCP. When PostHog is not signed in, Claude worktree turns load the signed-in PostHog connector as server claude.ai PostHog (tools mcp__claude_ai_PostHog__*) inside --mcp-config. --strict-mcp-config does not load claude.ai connectors, and --allowedTools only skips prompts. Cursor, Codex, and OpenCode do not have those tools. When PostHog is signed in, ignore a failed Claude PostHog connector and do not sign in to a PostHog MCP. If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized while that Sideboard token is set, do not sign in \u2014 use the native CLI. When that token is not set or the CLI call fails, the Claude connector is the fallback. Do not mention a Claude connector startup failure when the Sideboard connection works. Tell any worktree agent (Claude / Cursor / Codex / OpenCode) to write CLI output to `.context/cli/` and read a slice. If a CLI is missing, the user presses Install CLI on that row. Do not add vendor MCPs. Git (`gh`) stays Settings \u2192 Git; issue tracking stays Settings \u2192 Issues. The phone remote is Settings \u2192 Remote \u2014 do not look up Slack users.",
11225
11258
  "- get_pr_stack / open_pr_stack_layers / add_stack_layer / create_pr_stack \u2014 GitHub stacked PRs (`gh stack`); one worktree per layer",
11226
11259
  "- list_models \u2014 only when you need a specific model (rare); otherwise omit model so Account defaults apply",
11227
11260
  "- list_chats / get_chat \u2014 live thread list (parent id + last message preview). get_chat on this orchestration chat lists child worktree agents (status + lastText). blockedReason is why that agent is waiting on a person. Also includes usage / lastTurnUsage. Archived workspaces and agents are list_archive, not this list.",
@@ -14403,6 +14436,173 @@ ${JSON.stringify(launch)}`;
14403
14436
  }
14404
14437
  });
14405
14438
 
14439
+ // src/agents/claude-usage.ts
14440
+ var init_claude_usage = __esm({
14441
+ "src/agents/claude-usage.ts"() {
14442
+ "use strict";
14443
+ }
14444
+ });
14445
+
14446
+ // src/agents/claude-usage-client.ts
14447
+ function accessTokenFromCredentialsJson(raw) {
14448
+ const trimmed = raw.trim();
14449
+ if (!trimmed) return null;
14450
+ if (trimmed.startsWith("sk-ant-")) {
14451
+ const token = trimmed.split(/\s+/)[0];
14452
+ return token || null;
14453
+ }
14454
+ try {
14455
+ const parsed = JSON.parse(trimmed);
14456
+ const oauth = parsed.claudeAiOauth && typeof parsed.claudeAiOauth === "object" ? parsed.claudeAiOauth : parsed;
14457
+ const token = oauth.accessToken ?? oauth.access_token;
14458
+ return typeof token === "string" && token.trim() ? token.trim() : null;
14459
+ } catch {
14460
+ return null;
14461
+ }
14462
+ }
14463
+ function claudeCredentialsPath(configDir) {
14464
+ const root = configDir?.trim() || process.env.CLAUDE_CONFIG_DIR?.trim() || (0, import_node_path36.join)((0, import_node_os16.homedir)(), ".claude");
14465
+ return (0, import_node_path36.join)(root, ".credentials.json");
14466
+ }
14467
+ async function readFileAccessToken(configDir) {
14468
+ const path = claudeCredentialsPath(configDir);
14469
+ if (!(0, import_node_fs34.existsSync)(path)) return null;
14470
+ try {
14471
+ return accessTokenFromCredentialsJson((0, import_node_fs34.readFileSync)(path, "utf8"));
14472
+ } catch {
14473
+ return null;
14474
+ }
14475
+ }
14476
+ async function readKeychainAccessToken(configDir) {
14477
+ if (process.platform !== "darwin") return null;
14478
+ const root = configDir?.trim();
14479
+ const accounts = root ? [root, void 0] : [void 0];
14480
+ for (const service of KEYCHAIN_SERVICES) {
14481
+ for (const account of accounts) {
14482
+ const args = ["find-generic-password", "-s", service, "-w"];
14483
+ if (account) args.splice(3, 0, "-a", account);
14484
+ const result = await run("security", args, {
14485
+ reject: false,
14486
+ timeoutMs: 4e3
14487
+ });
14488
+ if (result.exitCode !== 0 || !result.stdout.trim()) continue;
14489
+ const token = accessTokenFromCredentialsJson(result.stdout);
14490
+ if (token) return token;
14491
+ }
14492
+ }
14493
+ return null;
14494
+ }
14495
+ async function readClaudeAccessToken(configDir) {
14496
+ const envToken = process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim();
14497
+ if (envToken) return envToken;
14498
+ const fromFile = await readFileAccessToken(configDir);
14499
+ if (fromFile) return fromFile;
14500
+ return readKeychainAccessToken(configDir);
14501
+ }
14502
+ var import_node_fs34, import_node_os16, import_node_path36, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS, KEYCHAIN_SERVICES;
14503
+ var init_claude_usage_client = __esm({
14504
+ "src/agents/claude-usage-client.ts"() {
14505
+ "use strict";
14506
+ import_node_fs34 = require("fs");
14507
+ import_node_os16 = require("os");
14508
+ import_node_path36 = require("path");
14509
+ init_run();
14510
+ init_fetch();
14511
+ init_app_settings();
14512
+ init_claude_usage();
14513
+ CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
14514
+ CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
14515
+ KEYCHAIN_SERVICES = ["Claude Code-credentials", "Claude Code"];
14516
+ }
14517
+ });
14518
+
14519
+ // src/agents/claude-posthog-connector.ts
14520
+ function asRecord5(value) {
14521
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
14522
+ return value;
14523
+ }
14524
+ function rowsFrom(body) {
14525
+ if (Array.isArray(body)) {
14526
+ return body.filter((row) => asRecord5(row) !== null);
14527
+ }
14528
+ const record = asRecord5(body);
14529
+ const data = record?.data;
14530
+ if (!Array.isArray(data)) return [];
14531
+ return data.filter((row) => asRecord5(row) !== null);
14532
+ }
14533
+ function isPosthogName(value) {
14534
+ if (typeof value !== "string") return false;
14535
+ const head = value.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)[0];
14536
+ return head === "posthog";
14537
+ }
14538
+ function rowId(row) {
14539
+ const id = row.id;
14540
+ return typeof id === "string" && ID_RE.test(id) ? id : null;
14541
+ }
14542
+ function posthogConnectorFromList(body) {
14543
+ const matches = rowsFrom(body).filter(
14544
+ (row2) => row2.eligible !== false && rowId(row2) !== null && (isPosthogName(row2.display_name) || isPosthogName(row2.displayName) || isPosthogName(row2.name))
14545
+ );
14546
+ const row = matches.find((item) => item.additional_install !== true && item.additionalInstall !== true) ?? matches[0];
14547
+ const id = row ? rowId(row) : null;
14548
+ if (!id) return null;
14549
+ return {
14550
+ type: "claudeai-proxy",
14551
+ id,
14552
+ url: `${PROXY_ORIGIN}/v1/mcp/${id}`,
14553
+ displayName: "PostHog",
14554
+ alwaysLoad: true
14555
+ };
14556
+ }
14557
+ async function loadClaudePosthogConnector(now = Date.now()) {
14558
+ if (cache && now - cache.at < (cache.value ? SUCCESS_TTL_MS : MISS_TTL_MS)) return cache.value;
14559
+ const token = await readClaudeAccessToken();
14560
+ if (!token) {
14561
+ cache = { at: now, value: null };
14562
+ return null;
14563
+ }
14564
+ try {
14565
+ const res = await httpFetch(LIST_URL, {
14566
+ headers: {
14567
+ Authorization: `Bearer ${token}`,
14568
+ "anthropic-version": "2023-06-01",
14569
+ "anthropic-beta": "mcp-servers-2025-12-04"
14570
+ },
14571
+ signal: AbortSignal.timeout(4e3)
14572
+ });
14573
+ if (!res.ok) {
14574
+ cache = { at: now, value: null };
14575
+ return null;
14576
+ }
14577
+ const value = posthogConnectorFromList(await res.json());
14578
+ cache = { at: now, value };
14579
+ return value;
14580
+ } catch {
14581
+ cache = { at: now, value: null };
14582
+ return null;
14583
+ }
14584
+ }
14585
+ async function claudePosthogConnectorForTurn() {
14586
+ if (turnOverride) return turnOverride();
14587
+ if (process.env.VITEST) return null;
14588
+ return loadClaudePosthogConnector();
14589
+ }
14590
+ var CLAUDE_POSTHOG_CONNECTOR_SERVER, LIST_URL, PROXY_ORIGIN, ID_RE, SUCCESS_TTL_MS, MISS_TTL_MS, cache, turnOverride;
14591
+ var init_claude_posthog_connector = __esm({
14592
+ "src/agents/claude-posthog-connector.ts"() {
14593
+ "use strict";
14594
+ init_fetch();
14595
+ init_claude_usage_client();
14596
+ CLAUDE_POSTHOG_CONNECTOR_SERVER = "claude.ai PostHog";
14597
+ LIST_URL = "https://api.anthropic.com/v1/mcp_servers?limit=1000&include_additional_installs=true";
14598
+ PROXY_ORIGIN = "https://mcp-proxy.anthropic.com";
14599
+ ID_RE = /^[A-Za-z0-9_-]+$/;
14600
+ SUCCESS_TTL_MS = 5 * 6e4;
14601
+ MISS_TTL_MS = 3e4;
14602
+ cache = null;
14603
+ }
14604
+ });
14605
+
14406
14606
  // src/agents/types.ts
14407
14607
  function planModeTurnInstruction(planMode) {
14408
14608
  return planMode ? PLAN_MODE_INSTRUCTION : PLAN_MODE_OFF_INSTRUCTION;
@@ -14455,11 +14655,11 @@ var init_types = __esm({
14455
14655
 
14456
14656
  // src/agent-rpc/metadata.ts
14457
14657
  function agentRuntimeMetadataPath() {
14458
- return (0, import_node_path36.join)(appDataDir(), "agent-runtime.json");
14658
+ return (0, import_node_path37.join)(appDataDir(), "agent-runtime.json");
14459
14659
  }
14460
14660
  function readAgentRuntimeMetadata() {
14461
14661
  try {
14462
- const raw = JSON.parse((0, import_node_fs34.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
14662
+ const raw = JSON.parse((0, import_node_fs35.readFileSync)(agentRuntimeMetadataPath(), "utf8"));
14463
14663
  if (!raw || typeof raw !== "object") return null;
14464
14664
  const rec = raw;
14465
14665
  if (typeof rec.runtimeId !== "string" || !rec.runtimeId.trim()) return null;
@@ -14507,12 +14707,12 @@ function agentRuntimeLooksLive(meta = readAgentRuntimeMetadata()) {
14507
14707
  if (!meta) return false;
14508
14708
  return pidAlive(meta.pid);
14509
14709
  }
14510
- var import_node_fs34, import_node_path36;
14710
+ var import_node_fs35, import_node_path37;
14511
14711
  var init_metadata = __esm({
14512
14712
  "src/agent-rpc/metadata.ts"() {
14513
14713
  "use strict";
14514
- import_node_fs34 = require("fs");
14515
- import_node_path36 = require("path");
14714
+ import_node_fs35 = require("fs");
14715
+ import_node_path37 = require("path");
14516
14716
  init_paths();
14517
14717
  init_protocol2();
14518
14718
  }
@@ -14582,11 +14782,11 @@ function entryDir() {
14582
14782
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
14583
14783
  if (cjsDir) return cjsDir;
14584
14784
  try {
14585
- return (0, import_node_path37.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
14785
+ return (0, import_node_path38.dirname)((0, import_node_url2.fileURLToPath)(import_meta5.url));
14586
14786
  } catch {
14587
14787
  try {
14588
14788
  const req = (0, import_node_module2.createRequire)(process.cwd() + "/");
14589
- return (0, import_node_path37.dirname)(req.resolve("@sideboard-ai/core"));
14789
+ return (0, import_node_path38.dirname)(req.resolve("@sideboard-ai/core"));
14590
14790
  } catch {
14591
14791
  return process.cwd();
14592
14792
  }
@@ -14595,20 +14795,20 @@ function entryDir() {
14595
14795
  function claudeRunnerPath() {
14596
14796
  const packagedDir = packagedCursorRuntimeDir();
14597
14797
  if (packagedDir) {
14598
- const packaged = (0, import_node_path37.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
14599
- if ((0, import_node_fs35.existsSync)(packaged)) return packaged;
14798
+ const packaged = (0, import_node_path38.join)(packagedDir, "core-dist", "agents", "claude-runner.js");
14799
+ if ((0, import_node_fs36.existsSync)(packaged)) return packaged;
14600
14800
  }
14601
14801
  const root = entryDir();
14602
14802
  const candidates = [
14603
- (0, import_node_path37.join)(root, "agents", "claude-runner.js"),
14604
- (0, import_node_path37.join)(root, "agents", "claude-runner.cjs"),
14605
- (0, import_node_path37.join)(root, "dist", "agents", "claude-runner.js"),
14606
- (0, import_node_path37.join)(root, "dist", "agents", "claude-runner.cjs"),
14607
- (0, import_node_path37.join)(root, "claude-runner.ts"),
14608
- (0, import_node_path37.join)(root, "src", "agents", "claude-runner.ts")
14803
+ (0, import_node_path38.join)(root, "agents", "claude-runner.js"),
14804
+ (0, import_node_path38.join)(root, "agents", "claude-runner.cjs"),
14805
+ (0, import_node_path38.join)(root, "dist", "agents", "claude-runner.js"),
14806
+ (0, import_node_path38.join)(root, "dist", "agents", "claude-runner.cjs"),
14807
+ (0, import_node_path38.join)(root, "claude-runner.ts"),
14808
+ (0, import_node_path38.join)(root, "src", "agents", "claude-runner.ts")
14609
14809
  ];
14610
14810
  for (const candidate of candidates) {
14611
- if ((0, import_node_fs35.existsSync)(candidate)) return candidate;
14811
+ if ((0, import_node_fs36.existsSync)(candidate)) return candidate;
14612
14812
  }
14613
14813
  return candidates[0];
14614
14814
  }
@@ -14632,13 +14832,13 @@ async function buildClaudeRpcTurnCommand(req) {
14632
14832
  }
14633
14833
  };
14634
14834
  }
14635
- var import_node_fs35, import_node_module2, import_node_path37, import_node_url2, import_meta5;
14835
+ var import_node_fs36, import_node_module2, import_node_path38, import_node_url2, import_meta5;
14636
14836
  var init_claude_host = __esm({
14637
14837
  "src/agents/claude-host.ts"() {
14638
14838
  "use strict";
14639
- import_node_fs35 = require("fs");
14839
+ import_node_fs36 = require("fs");
14640
14840
  import_node_module2 = require("module");
14641
- import_node_path37 = require("path");
14841
+ import_node_path38 = require("path");
14642
14842
  import_node_url2 = require("url");
14643
14843
  init_protocol2();
14644
14844
  init_pilot_tools();
@@ -14730,11 +14930,11 @@ function issueAttachmentWorktreePath(repoPath) {
14730
14930
  return raw || process.cwd();
14731
14931
  }
14732
14932
  function ensureIssueAttachmentsDir(worktreePath) {
14733
- const dir = (0, import_node_path38.join)(worktreePath, ATTACHMENTS_DIR);
14734
- (0, import_node_fs36.mkdirSync)(dir, { recursive: true });
14735
- const gi = (0, import_node_path38.join)(dir, ".gitignore");
14736
- if (!(0, import_node_fs36.existsSync)(gi)) {
14737
- (0, import_node_fs36.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
14933
+ const dir = (0, import_node_path39.join)(worktreePath, ATTACHMENTS_DIR);
14934
+ (0, import_node_fs37.mkdirSync)(dir, { recursive: true });
14935
+ const gi = (0, import_node_path39.join)(dir, ".gitignore");
14936
+ if (!(0, import_node_fs37.existsSync)(gi)) {
14937
+ (0, import_node_fs37.writeFileSync)(gi, attachmentsGitignoreBody(), "utf8");
14738
14938
  }
14739
14939
  return dir;
14740
14940
  }
@@ -14764,7 +14964,7 @@ function looksLikeFileUrl(url) {
14764
14964
  function filenameFromUrl(url, fallback = "attachment") {
14765
14965
  try {
14766
14966
  const parsed = new URL(url);
14767
- const last = decodeURIComponent((0, import_node_path38.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
14967
+ const last = decodeURIComponent((0, import_node_path39.basename)(parsed.pathname)).replace(/[/\\]/g, "_");
14768
14968
  if (last && last !== "/" && last !== ".") return last;
14769
14969
  } catch {
14770
14970
  }
@@ -14786,12 +14986,12 @@ function filenameFromContentDisposition(header) {
14786
14986
  }
14787
14987
  function uniqueAttachmentFileName(dir, originalName) {
14788
14988
  const safe = originalName.replace(/[/\\]/g, "_").replace(/^\.+/, "") || "file";
14789
- if (!(0, import_node_fs36.existsSync)((0, import_node_path38.join)(dir, safe))) return safe;
14790
- const ext = (0, import_node_path38.extname)(safe);
14989
+ if (!(0, import_node_fs37.existsSync)((0, import_node_path39.join)(dir, safe))) return safe;
14990
+ const ext = (0, import_node_path39.extname)(safe);
14791
14991
  const stem = ext ? safe.slice(0, -ext.length) : safe;
14792
14992
  for (let i = 1; i < 1e4; i++) {
14793
14993
  const candidate = `${stem}-${i}${ext}`;
14794
- if (!(0, import_node_fs36.existsSync)((0, import_node_path38.join)(dir, candidate))) return candidate;
14994
+ if (!(0, import_node_fs37.existsSync)((0, import_node_path39.join)(dir, candidate))) return candidate;
14795
14995
  }
14796
14996
  return `${stem}-${(0, import_node_crypto9.randomUUID)()}${ext}`;
14797
14997
  }
@@ -14839,7 +15039,7 @@ function mergeIssueAttachments(items) {
14839
15039
  return out;
14840
15040
  }
14841
15041
  function extensionForContentType(contentType, name) {
14842
- if ((0, import_node_path38.extname)(name)) return name;
15042
+ if ((0, import_node_path39.extname)(name)) return name;
14843
15043
  const mime = (contentType ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
14844
15044
  const ext = EXT_BY_MIME[mime];
14845
15045
  return ext ? `${name}${ext}` : name;
@@ -14891,7 +15091,7 @@ async function downloadAuthenticatedFile(opts) {
14891
15091
  const dir = ensureIssueAttachmentsDir(opts.worktreePath);
14892
15092
  const hinted = opts.name?.trim() || filenameFromContentDisposition(res.headers.get("content-disposition")) || filenameFromUrl(url);
14893
15093
  const name = uniqueAttachmentFileName(dir, extensionForContentType(contentType, hinted));
14894
- (0, import_node_fs36.writeFileSync)((0, import_node_path38.join)(dir, name), buf);
15094
+ (0, import_node_fs37.writeFileSync)((0, import_node_path39.join)(dir, name), buf);
14895
15095
  return {
14896
15096
  name,
14897
15097
  path: `${ATTACHMENTS_DIR}/${name}`,
@@ -14899,12 +15099,12 @@ async function downloadAuthenticatedFile(opts) {
14899
15099
  ...contentType ? { contentType } : {}
14900
15100
  };
14901
15101
  }
14902
- var import_node_fs36, import_node_path38, import_node_crypto9, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
15102
+ var import_node_fs37, import_node_path39, import_node_crypto9, ISSUE_ATTACHMENT_MAX_BYTES, MARKDOWN_IMAGE_RE, MARKDOWN_LINK_RE, HTML_SRC_RE, BARE_URL_RE, EXT_BY_MIME;
14903
15103
  var init_issue_attachments = __esm({
14904
15104
  "src/integrations/issue-attachments.ts"() {
14905
15105
  "use strict";
14906
- import_node_fs36 = require("fs");
14907
- import_node_path38 = require("path");
15106
+ import_node_fs37 = require("fs");
15107
+ import_node_path39 = require("path");
14908
15108
  import_node_crypto9 = require("crypto");
14909
15109
  init_fetch();
14910
15110
  init_workspace_scratch();
@@ -16557,17 +16757,18 @@ function compactMetadataFromClaude(obj) {
16557
16757
  const postTokens = typeof post === "number" && Number.isFinite(post) && post > 0 ? Math.round(post) : void 0;
16558
16758
  return { trigger, postTokens };
16559
16759
  }
16560
- var import_node_fs37, import_node_path39, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
16760
+ var import_node_fs38, import_node_path40, CLAUDE_PROMPT_ARG_MAX, claudeAdapter;
16561
16761
  var init_claude = __esm({
16562
16762
  "src/agents/claude.ts"() {
16563
16763
  "use strict";
16564
- import_node_fs37 = require("fs");
16565
- import_node_path39 = require("path");
16764
+ import_node_fs38 = require("fs");
16765
+ import_node_path40 = require("path");
16566
16766
  init_run();
16567
16767
  init_app_settings();
16568
16768
  init_claude_mcp_status();
16569
16769
  init_claude_mcp();
16570
16770
  init_host();
16771
+ init_claude_posthog_connector();
16571
16772
  init_error_detail();
16572
16773
  init_message_parts();
16573
16774
  init_injected_mcp();
@@ -16581,7 +16782,7 @@ var init_claude = __esm({
16581
16782
  async detect() {
16582
16783
  const claude = resolveClaudeExecutable();
16583
16784
  if (claude !== "claude") {
16584
- if (!(0, import_node_fs37.existsSync)(claude)) {
16785
+ if (!(0, import_node_fs38.existsSync)(claude)) {
16585
16786
  return {
16586
16787
  agent: "claude",
16587
16788
  installed: false,
@@ -16622,7 +16823,7 @@ var init_claude = __esm({
16622
16823
  const claude = resolveClaudeExecutable();
16623
16824
  const sessionId = await this.resolveSessionId(thread.worktreePath, thread.sessionId);
16624
16825
  const effective = dropCachedPrefixOnResume(input, sessionId);
16625
- const { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
16826
+ let { promptText, systemPrompt } = splitTurnInputForSystemPrompt(effective);
16626
16827
  const useStdin = promptText.length > CLAUDE_PROMPT_ARG_MAX;
16627
16828
  if (process.env.SIDEBOARD_DEBUG_CLAUDE_TURN === "1") {
16628
16829
  console.error(
@@ -16645,6 +16846,15 @@ var init_claude = __esm({
16645
16846
  const injectedBrightsyNames = injectedServers.filter((s) => s.name === "brightsy" || s.name.startsWith("brightsy_")).map((s) => s.name);
16646
16847
  const chromeOn = claudeChromeEnabled();
16647
16848
  const userMcpEntries = await proxyClaudeUserMcp(isOrchestrator, [thread.repoPath, thread.worktreePath]);
16849
+ const posthogConnector = !isOrchestrator && !isPosthogConnected() ? await claudePosthogConnectorForTurn() : null;
16850
+ if (posthogConnector && !Object.prototype.hasOwnProperty.call(userMcpEntries, CLAUDE_POSTHOG_CONNECTOR_SERVER)) {
16851
+ userMcpEntries[CLAUDE_POSTHOG_CONNECTOR_SERVER] = { ...posthogConnector };
16852
+ const hint = "PostHog: Settings \u2192 Connectors is not signed in. This turn loads the claude.ai PostHog connector (`claude.ai PostHog`, tools `mcp__claude_ai_PostHog__*`). Use those tools. Do not say PostHog is unavailable.";
16853
+ systemPrompt = systemPrompt ? `${systemPrompt}
16854
+
16855
+ ${hint}` : hint;
16856
+ }
16857
+ const isolateClaudeAiMcp = isOrchestrator || isLocalDevAppDataDir() && !posthogConnector;
16648
16858
  let allowedTools;
16649
16859
  if (isOrchestrator) {
16650
16860
  allowedTools = [
@@ -16685,7 +16895,7 @@ var init_claude = __esm({
16685
16895
  mcpServers: mcpServersRecord(injectedServers, userMcpEntries),
16686
16896
  allowedTools: withClaudePilotRpcTools(allowedTools),
16687
16897
  agentRpc: rpc,
16688
- isolateClaudeAiMcp: isOrchestrator || isLocalDevAppDataDir()
16898
+ isolateClaudeAiMcp
16689
16899
  });
16690
16900
  }
16691
16901
  const args = [
@@ -16730,18 +16940,19 @@ var init_claude = __esm({
16730
16940
  cwd: thread.worktreePath,
16731
16941
  stdin: useStdin ? `${promptText}
16732
16942
  ` : void 0,
16733
- ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path39.dirname)(mcpConfigPath)] } : {},
16943
+ ...mcpConfigPath ? { cleanupDirs: [(0, import_node_path40.dirname)(mcpConfigPath)] } : {},
16734
16944
  // Nested Task/Agent thinking+text in stream-json (Claude Code 2.1.211+).
16735
16945
  // Raise the -p background-agent wait so long TaskOutput polls are not
16736
16946
  // abandoned at Claude Code’s 10-minute default.
16737
16947
  env: {
16738
16948
  CLAUDE_CODE_FORWARD_SUBAGENT_TEXT: "1",
16739
16949
  CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS: process.env.CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS ?? String(CLAUDE_PRINT_BG_WAIT_CEILING_MS),
16740
- // `--strict-mcp-config` still fetches claude.ai connectors on some CLI
16741
- // builds (anthropics/claude-code#60252). Coordinators never need them.
16742
- // Local `pnpm dev` also disables them: those HTTP connectors hang the
16743
- // first worktree turn when Electron's cwd is this Sideboard repo.
16744
- ...isOrchestrator || isLocalDevAppDataDir() ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
16950
+ // Current Claude Code does not fetch claude.ai connectors under
16951
+ // `--strict-mcp-config`. The env is the off switch for older builds
16952
+ // that still fetched the whole account list, and it also refuses an
16953
+ // explicit claudeai-proxy. Orchestrators always set it. Local dev sets
16954
+ // it only when this turn is not passing the PostHog connector.
16955
+ ...isolateClaudeAiMcp ? { ENABLE_CLAUDEAI_MCP_SERVERS: "false" } : {}
16745
16956
  }
16746
16957
  };
16747
16958
  },
@@ -16909,7 +17120,7 @@ async function listCodexModels() {
16909
17120
  if (codex === "codex") {
16910
17121
  const which = await run("which", ["codex"], { reject: false });
16911
17122
  if (which.exitCode !== 0) return FALLBACK_CODEX_MODELS;
16912
- } else if (!(0, import_node_fs38.existsSync)(codex)) {
17123
+ } else if (!(0, import_node_fs39.existsSync)(codex)) {
16913
17124
  return FALLBACK_CODEX_MODELS;
16914
17125
  }
16915
17126
  const listed = await run(codex, ["debug", "models"], { reject: false });
@@ -16946,7 +17157,7 @@ function usageFromCodex(usage, asContext = false) {
16946
17157
  return occ > 0 ? { ...mapped, lastRequestTokens: occ } : mapped;
16947
17158
  }
16948
17159
  function codexHomeDir() {
16949
- return process.env.CODEX_HOME?.trim() || (0, import_node_path40.join)((0, import_node_os16.homedir)(), ".codex");
17160
+ return process.env.CODEX_HOME?.trim() || (0, import_node_path41.join)((0, import_node_os17.homedir)(), ".codex");
16950
17161
  }
16951
17162
  function unwrapCodexMcpResult(result) {
16952
17163
  if (result == null) return void 0;
@@ -16968,28 +17179,28 @@ function unwrapCodexMcpResult(result) {
16968
17179
  return String(result);
16969
17180
  }
16970
17181
  }
16971
- function asRecord5(value) {
17182
+ function asRecord6(value) {
16972
17183
  if (value && typeof value === "object" && !Array.isArray(value)) {
16973
17184
  return value;
16974
17185
  }
16975
17186
  return void 0;
16976
17187
  }
16977
17188
  function codexLooksAuthenticated() {
16978
- const authPath = (0, import_node_path40.join)(codexHomeDir(), "auth.json");
16979
- if (!(0, import_node_fs38.existsSync)(authPath)) return false;
17189
+ const authPath = (0, import_node_path41.join)(codexHomeDir(), "auth.json");
17190
+ if (!(0, import_node_fs39.existsSync)(authPath)) return false;
16980
17191
  try {
16981
- return (0, import_node_fs38.statSync)(authPath).size > 2;
17192
+ return (0, import_node_fs39.statSync)(authPath).size > 2;
16982
17193
  } catch {
16983
17194
  return false;
16984
17195
  }
16985
17196
  }
16986
- var import_node_fs38, import_node_os16, import_node_path40, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
17197
+ var import_node_fs39, import_node_os17, import_node_path41, CODEX_PROMPT_ARG_MAX, FALLBACK_CODEX_MODELS, cachedCodexModels, CODEX_MODEL_CACHE_MS, codexAdapter;
16987
17198
  var init_codex = __esm({
16988
17199
  "src/agents/codex.ts"() {
16989
17200
  "use strict";
16990
- import_node_fs38 = require("fs");
16991
- import_node_os16 = require("os");
16992
- import_node_path40 = require("path");
17201
+ import_node_fs39 = require("fs");
17202
+ import_node_os17 = require("os");
17203
+ import_node_path41 = require("path");
16993
17204
  init_run();
16994
17205
  init_app_settings();
16995
17206
  init_global_workspace();
@@ -17018,7 +17229,7 @@ var init_codex = __esm({
17018
17229
  async detect() {
17019
17230
  const codex = resolveAgentExecutable("codex");
17020
17231
  if (codex !== "codex") {
17021
- if (!(0, import_node_fs38.existsSync)(codex)) {
17232
+ if (!(0, import_node_fs39.existsSync)(codex)) {
17022
17233
  return {
17023
17234
  agent: "codex",
17024
17235
  installed: false,
@@ -17050,7 +17261,7 @@ var init_codex = __esm({
17050
17261
  authenticated,
17051
17262
  linearMcp,
17052
17263
  warnings,
17053
- reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path40.join)(codexHomeDir(), "auth.json")})`
17264
+ reason: authenticated ? void 0 : `Codex auth not found \u2014 run \`codex login\` (expected ${(0, import_node_path41.join)(codexHomeDir(), "auth.json")})`
17054
17265
  };
17055
17266
  },
17056
17267
  async buildTurn(thread, input) {
@@ -17158,7 +17369,7 @@ var init_codex = __esm({
17158
17369
  }
17159
17370
  if (itemType === "mcp_tool_call" && item.id && item.server && item.tool) {
17160
17371
  const name = `mcp__${item.server}__${item.tool}`;
17161
- const input = asRecord5(item.arguments);
17372
+ const input = asRecord6(item.arguments);
17162
17373
  const events = [
17163
17374
  { type: "tool_use", id: item.id, name, input }
17164
17375
  ];
@@ -17282,18 +17493,18 @@ var init_codex = __esm({
17282
17493
  // src/agents/cursor-sdk-resolve.ts
17283
17494
  function thisModuleFile() {
17284
17495
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
17285
- if (cjsDir) return (0, import_node_path41.join)(cjsDir, "cursor-sdk-resolve.js");
17496
+ if (cjsDir) return (0, import_node_path42.join)(cjsDir, "cursor-sdk-resolve.js");
17286
17497
  try {
17287
17498
  return (0, import_node_url3.fileURLToPath)(import_meta6.url);
17288
17499
  } catch {
17289
- return (0, import_node_path41.join)(process.cwd(), "package.json");
17500
+ return (0, import_node_path42.join)(process.cwd(), "package.json");
17290
17501
  }
17291
17502
  }
17292
17503
  function packageRootLooksLikeSdk(dir) {
17293
17504
  try {
17294
- const raw = (0, import_node_fs39.readFileSync)((0, import_node_path41.join)(dir, "package.json"), "utf8");
17505
+ const raw = (0, import_node_fs40.readFileSync)((0, import_node_path42.join)(dir, "package.json"), "utf8");
17295
17506
  const pkg = JSON.parse(raw);
17296
- return pkg.name === "@cursor/sdk" && (0, import_node_fs39.existsSync)(dir);
17507
+ return pkg.name === "@cursor/sdk" && (0, import_node_fs40.existsSync)(dir);
17297
17508
  } catch {
17298
17509
  return false;
17299
17510
  }
@@ -17302,7 +17513,7 @@ function resolvedPackageRoot(fromFile) {
17302
17513
  try {
17303
17514
  const req = (0, import_node_module3.createRequire)(fromFile);
17304
17515
  const pkgJson = req.resolve("@cursor/sdk/package.json");
17305
- const root = (0, import_node_path41.dirname)(pkgJson);
17516
+ const root = (0, import_node_path42.dirname)(pkgJson);
17306
17517
  return packageRootLooksLikeSdk(root) ? root : null;
17307
17518
  } catch {
17308
17519
  return null;
@@ -17316,10 +17527,10 @@ function resolveCursorSdkRoot(opts) {
17316
17527
  }
17317
17528
  const globalNm = npmGlobalNodeModules(env);
17318
17529
  if (globalNm) {
17319
- const globalRoot = (0, import_node_path41.join)(globalNm, "@cursor/sdk");
17530
+ const globalRoot = (0, import_node_path42.join)(globalNm, "@cursor/sdk");
17320
17531
  if (packageRootLooksLikeSdk(globalRoot)) return globalRoot;
17321
17532
  }
17322
- const cwdPkg = (0, import_node_path41.join)(process.cwd(), "package.json");
17533
+ const cwdPkg = (0, import_node_path42.join)(process.cwd(), "package.json");
17323
17534
  return resolvedPackageRoot(thisModuleFile()) ?? resolvedPackageRoot(cwdPkg);
17324
17535
  }
17325
17536
  function isCursorSdkInstalled(opts) {
@@ -17335,13 +17546,13 @@ function exportTarget(value) {
17335
17546
  }
17336
17547
  function cursorSdkEsmEntry(root) {
17337
17548
  try {
17338
- const pkg = JSON.parse((0, import_node_fs39.readFileSync)((0, import_node_path41.join)(root, "package.json"), "utf8"));
17549
+ const pkg = JSON.parse((0, import_node_fs40.readFileSync)((0, import_node_path42.join)(root, "package.json"), "utf8"));
17339
17550
  const exp = pkg.exports;
17340
17551
  const dot = exp && typeof exp === "object" && !Array.isArray(exp) && "." in exp ? exp["."] : exp;
17341
17552
  const rel = exportTarget(dot) ?? (typeof pkg.module === "string" ? pkg.module : null);
17342
17553
  if (!rel) return null;
17343
- const entry = (0, import_node_path41.join)(root, rel);
17344
- return (0, import_node_fs39.existsSync)(entry) ? entry : null;
17554
+ const entry = (0, import_node_path42.join)(root, rel);
17555
+ return (0, import_node_fs40.existsSync)(entry) ? entry : null;
17345
17556
  } catch {
17346
17557
  return null;
17347
17558
  }
@@ -17357,7 +17568,7 @@ async function importCursorSdk(opts) {
17357
17568
  try {
17358
17569
  let entry = cursorSdkEsmEntry(root);
17359
17570
  if (!entry) {
17360
- const req = (0, import_node_module3.createRequire)((0, import_node_path41.join)(root, "package.json"));
17571
+ const req = (0, import_node_module3.createRequire)((0, import_node_path42.join)(root, "package.json"));
17361
17572
  entry = req.resolve("@cursor/sdk");
17362
17573
  }
17363
17574
  return unwrapCursorSdkModule(await import((0, import_node_url3.pathToFileURL)(entry).href));
@@ -17369,8 +17580,8 @@ function cursorSdkPlatformRipgrepPackage() {
17369
17580
  return `@cursor/sdk-${process.platform}-${process.arch}`;
17370
17581
  }
17371
17582
  function nodeModulesDirForPackageRoot(packageRoot) {
17372
- const parent = (0, import_node_path41.dirname)(packageRoot);
17373
- return (0, import_node_path41.basename)(parent).startsWith("@") ? (0, import_node_path41.dirname)(parent) : parent;
17583
+ const parent = (0, import_node_path42.dirname)(packageRoot);
17584
+ return (0, import_node_path42.basename)(parent).startsWith("@") ? (0, import_node_path42.dirname)(parent) : parent;
17374
17585
  }
17375
17586
  function cursorSdkRipgrepCandidate(opts) {
17376
17587
  const root = resolveCursorSdkRoot(opts);
@@ -17378,18 +17589,18 @@ function cursorSdkRipgrepCandidate(opts) {
17378
17589
  const nm = nodeModulesDirForPackageRoot(root);
17379
17590
  const pkg = cursorSdkPlatformRipgrepPackage();
17380
17591
  const bin = process.platform === "win32" ? "rg.exe" : "rg";
17381
- const sibling = (0, import_node_path41.join)(nm, pkg, "bin", bin);
17382
- if ((0, import_node_fs39.existsSync)(sibling)) return sibling;
17383
- const nested = (0, import_node_path41.join)(root, "node_modules", pkg, "bin", bin);
17384
- return (0, import_node_fs39.existsSync)(nested) ? nested : null;
17592
+ const sibling = (0, import_node_path42.join)(nm, pkg, "bin", bin);
17593
+ if ((0, import_node_fs40.existsSync)(sibling)) return sibling;
17594
+ const nested = (0, import_node_path42.join)(root, "node_modules", pkg, "bin", bin);
17595
+ return (0, import_node_fs40.existsSync)(nested) ? nested : null;
17385
17596
  }
17386
- var import_node_fs39, import_node_module3, import_node_path41, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
17597
+ var import_node_fs40, import_node_module3, import_node_path42, import_node_url3, import_meta6, CURSOR_SDK_INSTALL_HINT;
17387
17598
  var init_cursor_sdk_resolve = __esm({
17388
17599
  "src/agents/cursor-sdk-resolve.ts"() {
17389
17600
  "use strict";
17390
- import_node_fs39 = require("fs");
17601
+ import_node_fs40 = require("fs");
17391
17602
  import_node_module3 = require("module");
17392
- import_node_path41 = require("path");
17603
+ import_node_path42 = require("path");
17393
17604
  import_node_url3 = require("url");
17394
17605
  init_path();
17395
17606
  import_meta6 = {};
@@ -17431,21 +17642,21 @@ function platformRipgrepPackage() {
17431
17642
  }
17432
17643
  function usableRipgrepPath(candidate) {
17433
17644
  const raw = candidate?.trim();
17434
- if (!raw || !(0, import_node_path42.isAbsolute)(raw)) return null;
17645
+ if (!raw || !(0, import_node_path43.isAbsolute)(raw)) return null;
17435
17646
  const readable = nodeReadableScriptPath(raw);
17436
- if (!(0, import_node_fs40.existsSync)(readable) || isAsarPath(readable)) return null;
17647
+ if (!(0, import_node_fs41.existsSync)(readable) || isAsarPath(readable)) return null;
17437
17648
  return readable;
17438
17649
  }
17439
17650
  function walkForBundledRipgrep(startFile) {
17440
17651
  if (!startFile) return null;
17441
17652
  const pkg = platformRipgrepPackage();
17442
17653
  const name = rgBinaryName();
17443
- let dir = (0, import_node_path42.dirname)((0, import_node_path42.resolve)(startFile));
17444
- const root = (0, import_node_path42.parse)(dir).root;
17654
+ let dir = (0, import_node_path43.dirname)((0, import_node_path43.resolve)(startFile));
17655
+ const root = (0, import_node_path43.parse)(dir).root;
17445
17656
  while (dir !== root) {
17446
- const hit = usableRipgrepPath((0, import_node_path42.join)(dir, "node_modules", pkg, "bin", name));
17657
+ const hit = usableRipgrepPath((0, import_node_path43.join)(dir, "node_modules", pkg, "bin", name));
17447
17658
  if (hit) return hit;
17448
- const next = (0, import_node_path42.dirname)(dir);
17659
+ const next = (0, import_node_path43.dirname)(dir);
17449
17660
  if (next === dir) break;
17450
17661
  dir = next;
17451
17662
  }
@@ -17455,7 +17666,7 @@ function requireResolveBundledRipgrep(fromFile) {
17455
17666
  try {
17456
17667
  const req = (0, import_node_module4.createRequire)(fromFile);
17457
17668
  const pkgJson = req.resolve(`${platformRipgrepPackage()}/package.json`);
17458
- return usableRipgrepPath((0, import_node_path42.join)((0, import_node_path42.dirname)(pkgJson), "bin", rgBinaryName()));
17669
+ return usableRipgrepPath((0, import_node_path43.join)((0, import_node_path43.dirname)(pkgJson), "bin", rgBinaryName()));
17459
17670
  } catch {
17460
17671
  return null;
17461
17672
  }
@@ -17477,13 +17688,13 @@ function cursorRipgrepEnv(opts) {
17477
17688
  const path = resolveCursorRipgrepPath(opts);
17478
17689
  return path ? { [RIPGREP_ENV]: path } : {};
17479
17690
  }
17480
- var import_node_fs40, import_node_module4, import_node_path42, RIPGREP_ENV;
17691
+ var import_node_fs41, import_node_module4, import_node_path43, RIPGREP_ENV;
17481
17692
  var init_cursor_ripgrep = __esm({
17482
17693
  "src/agents/cursor-ripgrep.ts"() {
17483
17694
  "use strict";
17484
- import_node_fs40 = require("fs");
17695
+ import_node_fs41 = require("fs");
17485
17696
  import_node_module4 = require("module");
17486
- import_node_path42 = require("path");
17697
+ import_node_path43 = require("path");
17487
17698
  init_cursor_sdk_resolve();
17488
17699
  init_node_launch();
17489
17700
  init_packaged_runtime();
@@ -17527,11 +17738,11 @@ function entryDir2() {
17527
17738
  const cjsDir = typeof __dirname !== "undefined" ? __dirname : "";
17528
17739
  if (cjsDir) return cjsDir;
17529
17740
  try {
17530
- return (0, import_node_path43.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
17741
+ return (0, import_node_path44.dirname)((0, import_node_url4.fileURLToPath)(import_meta7.url));
17531
17742
  } catch {
17532
17743
  try {
17533
17744
  const req = (0, import_node_module5.createRequire)(process.cwd() + "/");
17534
- return (0, import_node_path43.dirname)(req.resolve("@sideboard-ai/core"));
17745
+ return (0, import_node_path44.dirname)(req.resolve("@sideboard-ai/core"));
17535
17746
  } catch {
17536
17747
  return process.cwd();
17537
17748
  }
@@ -17542,27 +17753,27 @@ function cursorRunnerPath() {
17542
17753
  if (packaged) return packaged;
17543
17754
  const root = entryDir2();
17544
17755
  const candidates = [
17545
- (0, import_node_path43.join)(root, "agents", "cursor-runner.js"),
17546
- (0, import_node_path43.join)(root, "agents", "cursor-runner.cjs"),
17756
+ (0, import_node_path44.join)(root, "agents", "cursor-runner.js"),
17757
+ (0, import_node_path44.join)(root, "agents", "cursor-runner.cjs"),
17547
17758
  // If somehow resolved from package root instead of dist/
17548
- (0, import_node_path43.join)(root, "dist", "agents", "cursor-runner.js"),
17549
- (0, import_node_path43.join)(root, "dist", "agents", "cursor-runner.cjs"),
17759
+ (0, import_node_path44.join)(root, "dist", "agents", "cursor-runner.js"),
17760
+ (0, import_node_path44.join)(root, "dist", "agents", "cursor-runner.cjs"),
17550
17761
  // Source tree (dev): packages/core/src/agents/cursor-runner.ts
17551
- (0, import_node_path43.join)(root, "cursor-runner.ts"),
17552
- (0, import_node_path43.join)(root, "src", "agents", "cursor-runner.ts")
17762
+ (0, import_node_path44.join)(root, "cursor-runner.ts"),
17763
+ (0, import_node_path44.join)(root, "src", "agents", "cursor-runner.ts")
17553
17764
  ];
17554
17765
  for (const candidate of candidates) {
17555
- if ((0, import_node_fs41.existsSync)(candidate)) return candidate;
17766
+ if ((0, import_node_fs42.existsSync)(candidate)) return candidate;
17556
17767
  }
17557
17768
  return candidates[0];
17558
17769
  }
17559
- var import_node_fs41, import_node_module5, import_node_path43, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
17770
+ var import_node_fs42, import_node_module5, import_node_path44, import_node_url4, import_meta7, FALLBACK_CURSOR_MODELS, cachedModels, MODEL_CACHE_MS, cursorAdapter;
17560
17771
  var init_cursor = __esm({
17561
17772
  "src/agents/cursor.ts"() {
17562
17773
  "use strict";
17563
- import_node_fs41 = require("fs");
17774
+ import_node_fs42 = require("fs");
17564
17775
  import_node_module5 = require("module");
17565
- import_node_path43 = require("path");
17776
+ import_node_path44 = require("path");
17566
17777
  import_node_url4 = require("url");
17567
17778
  init_run();
17568
17779
  init_app_settings();
@@ -17689,26 +17900,26 @@ var init_cursor = __esm({
17689
17900
 
17690
17901
  // src/agent-rpc/opencode-hook.ts
17691
17902
  function writeOpencodeRpcPlugin() {
17692
- const pluginDir = (0, import_node_path44.join)(appDataDir(), "agent-rpc", "opencode");
17693
- (0, import_node_fs42.mkdirSync)(pluginDir, { recursive: true });
17694
- const pluginFile = (0, import_node_path44.join)(pluginDir, "sideboard-rpc.js");
17695
- if ((0, import_node_fs42.existsSync)(pluginFile)) {
17903
+ const pluginDir = (0, import_node_path45.join)(appDataDir(), "agent-rpc", "opencode");
17904
+ (0, import_node_fs43.mkdirSync)(pluginDir, { recursive: true });
17905
+ const pluginFile = (0, import_node_path45.join)(pluginDir, "sideboard-rpc.js");
17906
+ if ((0, import_node_fs43.existsSync)(pluginFile)) {
17696
17907
  try {
17697
- if ((0, import_node_fs42.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
17908
+ if ((0, import_node_fs43.readFileSync)(pluginFile, "utf8") === OPENCODE_PLUGIN_SOURCE) return pluginFile;
17698
17909
  } catch {
17699
17910
  }
17700
17911
  }
17701
17912
  const tmp = `${pluginFile}.${process.pid}.tmp`;
17702
- (0, import_node_fs42.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
17703
- (0, import_node_fs42.renameSync)(tmp, pluginFile);
17913
+ (0, import_node_fs43.writeFileSync)(tmp, OPENCODE_PLUGIN_SOURCE);
17914
+ (0, import_node_fs43.renameSync)(tmp, pluginFile);
17704
17915
  return pluginFile;
17705
17916
  }
17706
- var import_node_fs42, import_node_path44, OPENCODE_PLUGIN_SOURCE;
17917
+ var import_node_fs43, import_node_path45, OPENCODE_PLUGIN_SOURCE;
17707
17918
  var init_opencode_hook = __esm({
17708
17919
  "src/agent-rpc/opencode-hook.ts"() {
17709
17920
  "use strict";
17710
- import_node_fs42 = require("fs");
17711
- import_node_path44 = require("path");
17921
+ import_node_fs43 = require("fs");
17922
+ import_node_path45 = require("path");
17712
17923
  init_paths();
17713
17924
  init_pilot_tools();
17714
17925
  init_protocol2();
@@ -17866,7 +18077,7 @@ var init_opencode_host = __esm({
17866
18077
  });
17867
18078
 
17868
18079
  // src/agents/opencode.ts
17869
- function asRecord6(value) {
18080
+ function asRecord7(value) {
17870
18081
  if (value && typeof value === "object" && !Array.isArray(value)) {
17871
18082
  return value;
17872
18083
  }
@@ -17911,7 +18122,7 @@ async function listOpencodeModels() {
17911
18122
  if (opencode === "opencode") {
17912
18123
  const which = await run("which", ["opencode"], { reject: false });
17913
18124
  if (which.exitCode !== 0) return FALLBACK_OPENCODE_MODELS;
17914
- } else if (!(0, import_node_fs43.existsSync)(opencode)) {
18125
+ } else if (!(0, import_node_fs44.existsSync)(opencode)) {
17915
18126
  return FALLBACK_OPENCODE_MODELS;
17916
18127
  }
17917
18128
  const listed = await run(opencode, ["models"], { reject: false });
@@ -17941,11 +18152,11 @@ function usageFromOpencode(tokens) {
17941
18152
  cacheWriteTokens: tokens.cache?.write ? Number(tokens.cache.write) : void 0
17942
18153
  };
17943
18154
  }
17944
- var import_node_fs43, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
18155
+ var import_node_fs44, FALLBACK_OPENCODE_MODELS, cachedOpencodeModels, OPENCODE_MODEL_CACHE_MS, opencodeAdapter;
17945
18156
  var init_opencode = __esm({
17946
18157
  "src/agents/opencode.ts"() {
17947
18158
  "use strict";
17948
- import_node_fs43 = require("fs");
18159
+ import_node_fs44 = require("fs");
17949
18160
  init_run();
17950
18161
  init_app_settings();
17951
18162
  init_error_detail();
@@ -17971,7 +18182,7 @@ var init_opencode = __esm({
17971
18182
  async detect() {
17972
18183
  const opencode = resolveAgentExecutable("opencode");
17973
18184
  if (opencode !== "opencode") {
17974
- if (!(0, import_node_fs43.existsSync)(opencode)) {
18185
+ if (!(0, import_node_fs44.existsSync)(opencode)) {
17975
18186
  return {
17976
18187
  agent: "opencode",
17977
18188
  installed: false,
@@ -18071,7 +18282,7 @@ var init_opencode = __esm({
18071
18282
  const name = part?.tool ?? part?.name ?? obj.tool ?? obj.name ?? "tool";
18072
18283
  const state = part?.state;
18073
18284
  const input = (state?.input && typeof state.input === "object" ? state.input : void 0) ?? part?.input ?? obj.input;
18074
- const metadata = asRecord6(state?.metadata);
18285
+ const metadata = asRecord7(state?.metadata);
18075
18286
  const id = opencodeToolId(
18076
18287
  name,
18077
18288
  part?.callID ?? part?.id ?? obj.id,
@@ -18106,7 +18317,7 @@ var init_opencode = __esm({
18106
18317
  }
18107
18318
  if (obj.type === "subtask_event") {
18108
18319
  const parentId = str3(obj.childSessionID) ?? str3(obj.childSessionId);
18109
- const part = asRecord6(obj.part);
18320
+ const part = asRecord7(obj.part);
18110
18321
  if (!parentId || !part) return null;
18111
18322
  if (part.type === "text" && str3(part.text)) {
18112
18323
  return withTaskParent(
@@ -18117,8 +18328,8 @@ var init_opencode = __esm({
18117
18328
  if (part.type === "tool" || str3(part.tool)) {
18118
18329
  const name = str3(part.tool) ?? str3(part.name) ?? "tool";
18119
18330
  const id = str3(part.callID) ?? str3(part.id) ?? `${parentId}-${name}`;
18120
- const state = asRecord6(part.state);
18121
- const input = asRecord6(state?.input) ?? asRecord6(part.input);
18331
+ const state = asRecord7(part.state);
18332
+ const input = asRecord7(state?.input) ?? asRecord7(part.input);
18122
18333
  const nested = [
18123
18334
  withEventParentId({ type: "tool_use", id, name, input }, parentId)
18124
18335
  ];
@@ -18424,30 +18635,6 @@ var init_session_quota = __esm({
18424
18635
  }
18425
18636
  });
18426
18637
 
18427
- // src/agents/claude-usage.ts
18428
- var init_claude_usage = __esm({
18429
- "src/agents/claude-usage.ts"() {
18430
- "use strict";
18431
- }
18432
- });
18433
-
18434
- // src/agents/claude-usage-client.ts
18435
- var import_node_fs44, import_node_os17, import_node_path45, CLAUDE_USAGE_ERROR_TTL_MS, CLAUDE_USAGE_STALE_OK_MS;
18436
- var init_claude_usage_client = __esm({
18437
- "src/agents/claude-usage-client.ts"() {
18438
- "use strict";
18439
- import_node_fs44 = require("fs");
18440
- import_node_os17 = require("os");
18441
- import_node_path45 = require("path");
18442
- init_run();
18443
- init_fetch();
18444
- init_app_settings();
18445
- init_claude_usage();
18446
- CLAUDE_USAGE_ERROR_TTL_MS = 5 * 6e4;
18447
- CLAUDE_USAGE_STALE_OK_MS = 30 * 6e4;
18448
- }
18449
- });
18450
-
18451
18638
  // src/agents/install-native.ts
18452
18639
  var init_install_native = __esm({
18453
18640
  "src/agents/install-native.ts"() {
@@ -22436,7 +22623,7 @@ var init_agent_block_view = __esm({
22436
22623
  });
22437
22624
 
22438
22625
  // src/plan/plan-present.ts
22439
- function asRecord7(v) {
22626
+ function asRecord8(v) {
22440
22627
  return v != null && typeof v === "object" && !Array.isArray(v) ? v : null;
22441
22628
  }
22442
22629
  function isPresentPlanToolName(name) {
@@ -22455,7 +22642,7 @@ function extractPresentedPlan(parts) {
22455
22642
  for (let i = parts.length - 1; i >= 0; i--) {
22456
22643
  const p = parts[i];
22457
22644
  if (p.type !== "tool" || !isPresentPlanToolName(p.name)) continue;
22458
- const input = asRecord7(p.input) ?? {};
22645
+ const input = asRecord8(p.input) ?? {};
22459
22646
  const content = typeof input.content === "string" ? input.content : typeof input.plan === "string" ? input.plan : typeof input.markdown === "string" ? input.markdown : "";
22460
22647
  if (!content.trim()) continue;
22461
22648
  const title = typeof input.title === "string" && input.title.trim() ? input.title.trim() : "Plan";
@@ -23007,6 +23194,10 @@ function resolveStopReason(opts) {
23007
23194
  if (opts?.clearQueue === false) return "Stopped by the user";
23008
23195
  return "Stopped (queue cleared)";
23009
23196
  }
23197
+ function isRoutineStopNote(err) {
23198
+ const text7 = err?.trim() ?? "";
23199
+ return text7 === "Stopped" || text7 === "Stopped by the user" || text7 === "Stopped (queue cleared)" || text7 === "Stopped to send the next prompt";
23200
+ }
23010
23201
  function reasonToKeepOnStop(existing, incoming) {
23011
23202
  const next = incoming?.trim();
23012
23203
  if (next) return next.slice(0, STOP_REASON_MAX);
@@ -23014,6 +23205,16 @@ function reasonToKeepOnStop(existing, incoming) {
23014
23205
  if (prior) return prior.slice(0, STOP_REASON_MAX);
23015
23206
  return "Stopped";
23016
23207
  }
23208
+ function turnFinishedEvent(threadId, exitCode, userStopped, lastError) {
23209
+ const note = lastError?.trim() ?? "";
23210
+ const routineStop = userStopped && (note.length === 0 || isRoutineStopNote(note));
23211
+ return {
23212
+ type: "turn_finished",
23213
+ threadId,
23214
+ exitCode,
23215
+ ...routineStop ? { routineStop: true } : {}
23216
+ };
23217
+ }
23017
23218
  function writeStoppedStatus(threadId, reason) {
23018
23219
  const latest = readThread(threadId);
23019
23220
  if (!latest || latest.status === "archived") return latest;
@@ -24170,7 +24371,7 @@ __export(abletime_rest_exports, {
24170
24371
  looksLikeAbleTimeUlid: () => looksLikeAbleTimeUlid,
24171
24372
  textFromAbleTimeDoc: () => textFromAbleTimeDoc
24172
24373
  });
24173
- function asRecord8(value) {
24374
+ function asRecord9(value) {
24174
24375
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24175
24376
  }
24176
24377
  function asString(value) {
@@ -24178,7 +24379,7 @@ function asString(value) {
24178
24379
  }
24179
24380
  function asList(value) {
24180
24381
  if (Array.isArray(value)) return value;
24181
- const record = asRecord8(value);
24382
+ const record = asRecord9(value);
24182
24383
  if (!record) return [];
24183
24384
  for (const key of ["data", "tasks", "projects", "users", "items", "results"]) {
24184
24385
  if (Array.isArray(record[key])) return record[key];
@@ -24195,12 +24396,12 @@ function ableTimeDocFromText(text7) {
24195
24396
  }
24196
24397
  function textFromAbleTimeDoc(value) {
24197
24398
  if (typeof value === "string") return value.trim();
24198
- const record = asRecord8(value);
24399
+ const record = asRecord9(value);
24199
24400
  if (!record) return "";
24200
24401
  if (typeof record.text === "string" && record.text.trim()) return record.text.trim();
24201
24402
  const chunks = [];
24202
24403
  const walk = (node) => {
24203
- const rec = asRecord8(node);
24404
+ const rec = asRecord9(node);
24204
24405
  if (!rec) return;
24205
24406
  if (typeof rec.text === "string" && rec.text) chunks.push(rec.text);
24206
24407
  if (Array.isArray(rec.content)) rec.content.forEach(walk);
@@ -24262,7 +24463,7 @@ async function restPages(path, opts, maxPages = 20) {
24262
24463
  query: { ...opts.query, ...cursor ? { cursor } : {} }
24263
24464
  });
24264
24465
  items.push(...asList(raw));
24265
- const page = asRecord8(asRecord8(raw)?.page);
24466
+ const page = asRecord9(asRecord9(raw)?.page);
24266
24467
  const next = page ? asString(page.nextCursor) : "";
24267
24468
  if (!next) break;
24268
24469
  cursor = next;
@@ -24270,7 +24471,7 @@ async function restPages(path, opts, maxPages = 20) {
24270
24471
  return items;
24271
24472
  }
24272
24473
  function userDisplayName(raw) {
24273
- const rec = asRecord8(raw);
24474
+ const rec = asRecord9(raw);
24274
24475
  if (!rec) return null;
24275
24476
  const id = asString(rec.userId) || asString(rec.id);
24276
24477
  const name = [asString(rec.firstName), asString(rec.lastName)].filter(Boolean).join(" ") || asString(rec.username) || asString(rec.email) || asString(rec.name);
@@ -24278,7 +24479,7 @@ function userDisplayName(raw) {
24278
24479
  return { id: id || void 0, name };
24279
24480
  }
24280
24481
  function restTaskToRaw(raw, users) {
24281
- const rec = asRecord8(raw);
24482
+ const rec = asRecord9(raw);
24282
24483
  if (!rec) return null;
24283
24484
  const id = asString(rec.timeflowTaskId) || asString(rec.taskId) || asString(rec.id);
24284
24485
  const identifier = asString(rec.taskRef) || asString(rec.reference) || id;
@@ -24286,7 +24487,7 @@ function restTaskToRaw(raw, users) {
24286
24487
  if (!id && !identifier && !title) return null;
24287
24488
  const assignee = users.get(asString(rec.assignedUserId));
24288
24489
  const comments = asList(rec.comments).map((item) => {
24289
- const comment = asRecord8(item) ?? {};
24490
+ const comment = asRecord9(item) ?? {};
24290
24491
  const user = userDisplayName(comment);
24291
24492
  return {
24292
24493
  id: asString(comment.commentId) || asString(comment.id),
@@ -24317,13 +24518,13 @@ function restTaskToRaw(raw, users) {
24317
24518
  };
24318
24519
  }
24319
24520
  function restProjectToRaw(raw) {
24320
- const rec = asRecord8(raw);
24521
+ const rec = asRecord9(raw);
24321
24522
  if (!rec) return null;
24322
24523
  const id = asString(rec.projectId) || asString(rec.id);
24323
24524
  const name = asString(rec.projectName) || asString(rec.name);
24324
24525
  if (!id && !name) return null;
24325
24526
  const categories = asList(rec.categories).map((item) => {
24326
- const cat = asRecord8(item) ?? {};
24527
+ const cat = asRecord9(item) ?? {};
24327
24528
  return {
24328
24529
  id: asString(cat.projectCategoryId) || asString(cat.categoryId) || asString(cat.id),
24329
24530
  name: asString(cat.categoryName) || asString(cat.name)
@@ -24335,7 +24536,7 @@ async function listUsers(opts) {
24335
24536
  const users = /* @__PURE__ */ new Map();
24336
24537
  for (const item of await restPages("/users", opts).catch(() => [])) {
24337
24538
  const user = userDisplayName(item);
24338
- const rec = asRecord8(item);
24539
+ const rec = asRecord9(item);
24339
24540
  const id = user?.id || (rec ? asString(rec.userId) : "");
24340
24541
  if (user && id) users.set(id, user);
24341
24542
  }
@@ -24461,10 +24662,10 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24461
24662
  if (!project) throw new Error("AbleTime has no projects to create a task in");
24462
24663
  const categories = asList(project.categories);
24463
24664
  const wantedCategory = firstStringArg(args, ["category_id", "categoryId", "category"]);
24464
- const category = categories.map((item) => asRecord8(item)).find((item) => {
24665
+ const category = categories.map((item) => asRecord9(item)).find((item) => {
24465
24666
  if (!item || !wantedCategory) return false;
24466
24667
  return asString(item.id).toLowerCase() === wantedCategory.toLowerCase() || asString(item.name).toLowerCase() === wantedCategory.toLowerCase();
24467
- }) ?? asRecord8(categories[0]);
24668
+ }) ?? asRecord9(categories[0]);
24468
24669
  const parentArg = firstStringArg(args, ["parent", "parent_id", "parentId", "related_task_id"]);
24469
24670
  const parentTaskId = parentArg ? await resolveRestParentTaskId(parentArg, requestOpts) : void 0;
24470
24671
  const created = await abletimeRestRequest("/tasks", {
@@ -24478,7 +24679,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24478
24679
  }
24479
24680
  });
24480
24681
  const state = firstStringArg(args, ["state"]);
24481
- const createdId = asString(asRecord8(created)?.timeflowTaskId);
24682
+ const createdId = asString(asRecord9(created)?.timeflowTaskId);
24482
24683
  const description = asString(args.description);
24483
24684
  if (createdId && description) {
24484
24685
  await abletimeRestRequest(`/tasks/${encodeURIComponent(createdId)}`, {
@@ -24551,7 +24752,7 @@ async function callAbleTimeRestTool(name, args = {}, opts) {
24551
24752
  method: "POST",
24552
24753
  body: { content: ableTimeDocFromText(body) }
24553
24754
  });
24554
- const rec = asRecord8(created) ?? {};
24755
+ const rec = asRecord9(created) ?? {};
24555
24756
  return {
24556
24757
  id: asString(rec.commentId) || void 0,
24557
24758
  body: textFromAbleTimeDoc(rec.content) || body
@@ -24646,7 +24847,7 @@ function rewriteAbleTimeError(message) {
24646
24847
  }
24647
24848
  return message;
24648
24849
  }
24649
- function asRecord9(value) {
24850
+ function asRecord10(value) {
24650
24851
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24651
24852
  }
24652
24853
  function parseSseJson(body) {
@@ -24668,12 +24869,12 @@ function parseSseJson(body) {
24668
24869
  }
24669
24870
  }
24670
24871
  function unwrapToolResult(result) {
24671
- const record = asRecord9(result);
24872
+ const record = asRecord10(result);
24672
24873
  if (!record) return result;
24673
24874
  const content = record.content;
24674
24875
  if (Array.isArray(content)) {
24675
24876
  const texts = content.map((part) => {
24676
- const item = asRecord9(part);
24877
+ const item = asRecord10(part);
24677
24878
  if (!item) return "";
24678
24879
  return typeof item.text === "string" ? item.text : "";
24679
24880
  }).filter(Boolean);
@@ -24695,7 +24896,7 @@ function unwrapToolResult(result) {
24695
24896
  return result;
24696
24897
  }
24697
24898
  function textsFromUnknown(value) {
24698
- const record = asRecord9(value);
24899
+ const record = asRecord10(value);
24699
24900
  if (!record) return "";
24700
24901
  if (typeof record.message === "string") return record.message;
24701
24902
  if (typeof record.error === "string") return record.error;
@@ -24742,7 +24943,7 @@ async function abletimeMcpRequest(method, params, opts) {
24742
24943
  return parseSseJson(body);
24743
24944
  }
24744
24945
  })();
24745
- const rpc = asRecord9(parsed);
24946
+ const rpc = asRecord10(parsed);
24746
24947
  if (rpc?.error) {
24747
24948
  const detail = typeof rpc.error.message === "string" && rpc.error.message.trim() ? rpc.error.message : `AbleTime MCP error ${rpc.error.code ?? ""}`.trim();
24748
24949
  throw new Error(rewriteAbleTimeError(detail));
@@ -24829,7 +25030,7 @@ var init_abletime_mcp = __esm({
24829
25030
  });
24830
25031
 
24831
25032
  // src/integrations/abletime-attachments.ts
24832
- function asRecord10(value) {
25033
+ function asRecord11(value) {
24833
25034
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24834
25035
  }
24835
25036
  function asString2(value) {
@@ -24837,7 +25038,7 @@ function asString2(value) {
24837
25038
  }
24838
25039
  function asList2(value) {
24839
25040
  if (Array.isArray(value)) return value;
24840
- const record = asRecord10(value);
25041
+ const record = asRecord11(value);
24841
25042
  if (!record) return [];
24842
25043
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
24843
25044
  if (Array.isArray(record[key])) return record[key];
@@ -24856,9 +25057,9 @@ function filesFromAbleTimeDoc(value) {
24856
25057
  const out = [];
24857
25058
  const seen = /* @__PURE__ */ new Set();
24858
25059
  const walk = (node) => {
24859
- const rec = asRecord10(node);
25060
+ const rec = asRecord11(node);
24860
25061
  if (!rec) return;
24861
- const attrs = asRecord10(rec.attrs) ?? rec;
25062
+ const attrs = asRecord11(rec.attrs) ?? rec;
24862
25063
  const url = asString2(attrs.src) || asString2(attrs.href) || asString2(attrs.url) || asString2(attrs.fileUrl) || asString2(attrs.downloadUrl);
24863
25064
  if (url && !seen.has(url)) {
24864
25065
  seen.add(url);
@@ -24876,7 +25077,7 @@ function filesFromAbleTimeDoc(value) {
24876
25077
  function listedAbleTimeFiles(raw) {
24877
25078
  const out = [];
24878
25079
  for (const item of asList2(raw)) {
24879
- const rec = asRecord10(item);
25080
+ const rec = asRecord11(item);
24880
25081
  if (!rec) continue;
24881
25082
  const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl", "permalink"]);
24882
25083
  if (!url) continue;
@@ -24896,7 +25097,7 @@ function mapAbleTimeAttachments(record) {
24896
25097
  ...filesFromAbleTimeDoc(record.description),
24897
25098
  ...filesFromAbleTimeDoc(record.content),
24898
25099
  ...asList2(record.comments).flatMap((item) => {
24899
- const rec = asRecord10(item);
25100
+ const rec = asRecord11(item);
24900
25101
  return rec ? filesFromAbleTimeDoc(rec.content ?? rec.body) : [];
24901
25102
  })
24902
25103
  ].map((file) => ({
@@ -24938,7 +25139,7 @@ async function resolveAbleTimeAttachmentUrl(id, opts) {
24938
25139
  const json = await res.json().catch(() => null);
24939
25140
  const rec = json && typeof json === "object" && !Array.isArray(json) ? json.data && typeof json.data === "object" ? json.data : json : null;
24940
25141
  if (!rec) continue;
24941
- const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord10(rec.file), ["url", "href"]);
25142
+ const url = firstString(rec, ["url", "href", "src", "fileUrl", "downloadUrl"]) || firstString(asRecord11(rec.file), ["url", "href"]);
24942
25143
  if (url) {
24943
25144
  return {
24944
25145
  url,
@@ -24980,7 +25181,7 @@ var init_abletime_attachments = __esm({
24980
25181
  });
24981
25182
 
24982
25183
  // src/integrations/abletime-projects.ts
24983
- function asRecord11(value) {
25184
+ function asRecord12(value) {
24984
25185
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
24985
25186
  }
24986
25187
  function firstString2(record, keys) {
@@ -24993,7 +25194,7 @@ function firstString2(record, keys) {
24993
25194
  }
24994
25195
  function asList3(value) {
24995
25196
  if (Array.isArray(value)) return value;
24996
- const record = asRecord11(value);
25197
+ const record = asRecord12(value);
24997
25198
  if (!record) return [];
24998
25199
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
24999
25200
  if (Array.isArray(record[key])) return record[key];
@@ -25001,7 +25202,7 @@ function asList3(value) {
25001
25202
  return [];
25002
25203
  }
25003
25204
  function ableTimeProjectFields(nested) {
25004
- const projectRecord = asRecord11(nested.project);
25205
+ const projectRecord = asRecord12(nested.project);
25005
25206
  const projectId = firstString2(nested, ["project_id", "projectId"]) || firstString2(projectRecord, ["id"]) || void 0;
25006
25207
  const projectName = firstString2(nested, ["project_name", "projectName"]) || firstString2(projectRecord, ["name", "title"]) || void 0;
25007
25208
  if (!projectId && !projectName) return {};
@@ -25014,13 +25215,13 @@ function ableTimeProjectFields(nested) {
25014
25215
  };
25015
25216
  }
25016
25217
  function mapAbleTimeProject(raw) {
25017
- const record = asRecord11(raw);
25218
+ const record = asRecord12(raw);
25018
25219
  if (!record) return null;
25019
25220
  const id = firstString2(record, ["id", "project_id", "projectId"]);
25020
25221
  const name = firstString2(record, ["name", "title", "projectName"]);
25021
25222
  if (!id && !name) return null;
25022
25223
  const categories = asList3(record.categories ?? record.category).map((item) => {
25023
- const rec = asRecord11(item);
25224
+ const rec = asRecord12(item);
25024
25225
  if (!rec) return null;
25025
25226
  const categoryId = firstString2(rec, ["id", "category_id", "projectCategoryId", "categoryId"]);
25026
25227
  const categoryName = firstString2(rec, ["name", "title", "categoryName"]);
@@ -25057,7 +25258,7 @@ __export(abletime_exports, {
25057
25258
  updateAbleTimeTask: () => updateAbleTimeTask,
25058
25259
  verifyAbleTimeConnection: () => verifyAbleTimeConnection
25059
25260
  });
25060
- function asRecord12(value) {
25261
+ function asRecord13(value) {
25061
25262
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
25062
25263
  }
25063
25264
  function asString3(value) {
@@ -25074,14 +25275,14 @@ function firstString3(record, keys) {
25074
25275
  function firstRecord(record, keys) {
25075
25276
  if (!record) return null;
25076
25277
  for (const key of keys) {
25077
- const value = asRecord12(record[key]);
25278
+ const value = asRecord13(record[key]);
25078
25279
  if (value) return value;
25079
25280
  }
25080
25281
  return null;
25081
25282
  }
25082
25283
  function asList4(value) {
25083
25284
  if (Array.isArray(value)) return value;
25084
- const record = asRecord12(value);
25285
+ const record = asRecord13(value);
25085
25286
  if (!record) return [];
25086
25287
  for (const key of ["data", "tasks", "projects", "items", "results", "nodes"]) {
25087
25288
  if (Array.isArray(record[key])) return record[key];
@@ -25093,18 +25294,18 @@ function labelsOf(record) {
25093
25294
  if (!Array.isArray(raw)) return [];
25094
25295
  return raw.map((item) => {
25095
25296
  if (typeof item === "string") return item.trim();
25096
- const rec = asRecord12(item);
25297
+ const rec = asRecord13(item);
25097
25298
  return rec ? firstString3(rec, ["name", "title", "label"]) : "";
25098
25299
  }).filter(Boolean);
25099
25300
  }
25100
25301
  function commentsOf(record) {
25101
25302
  const out = [];
25102
25303
  for (const item of asList4(record.comments ?? record.notes ?? record.discussion)) {
25103
- const rec = asRecord12(item);
25304
+ const rec = asRecord13(item);
25104
25305
  if (!rec) continue;
25105
25306
  const body = firstString3(rec, ["body", "text", "comment", "message", "contentSanitized"]) || textFromAbleTimeDoc(rec.content);
25106
25307
  if (!body) continue;
25107
- const user = firstString3(asRecord12(rec.user) ?? asRecord12(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
25308
+ const user = firstString3(asRecord13(rec.user) ?? asRecord13(rec.author), ["name", "display_name", "username"]) || firstString3(rec, ["user_name", "author", "username"]);
25108
25309
  const id = firstString3(rec, ["id", "comment_id", "commentId"]);
25109
25310
  const url = firstString3(rec, ["url", "permalink"]);
25110
25311
  const createdAt = firstString3(rec, ["created_at", "createdAt", "created"]);
@@ -25131,7 +25332,7 @@ function taskUrl(task, host) {
25131
25332
  return `${base}/tasks/${slug}`;
25132
25333
  }
25133
25334
  function mapAbleTimeTask(raw, host) {
25134
- const record = asRecord12(raw);
25335
+ const record = asRecord13(raw);
25135
25336
  if (!record) return null;
25136
25337
  const nested = firstRecord(record, ["task", "data"]) ?? record;
25137
25338
  const id = firstString3(nested, ["id", "task_id", "taskId", "timeflowTaskId"]);
@@ -25149,7 +25350,7 @@ function mapAbleTimeTask(raw, host) {
25149
25350
  description: firstString3(nested, ["description", "body", "details", "descriptionSanitized"]) || textFromAbleTimeDoc(nested.description) || void 0,
25150
25351
  state: firstString3(nested, ["state", "board_state", "boardState", "status", "taskState"]) || void 0,
25151
25352
  ...ableTimeProjectFields(nested),
25152
- categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord12(nested.category), ["id"]) || void 0,
25353
+ categoryId: firstString3(nested, ["category_id", "categoryId", "projectCategoryId"]) || firstString3(asRecord13(nested.category), ["id"]) || void 0,
25153
25354
  assignee: assigneeOf(nested),
25154
25355
  labels: labelsOf(nested),
25155
25356
  comments: commentsOf(nested),
@@ -25202,7 +25403,7 @@ function isOpenTask(task) {
25202
25403
  }
25203
25404
  async function getAbleTimeOrientation(opts) {
25204
25405
  const raw = await callAbleTimeTool("orientation", {}, opts);
25205
- const record = asRecord12(raw);
25406
+ const record = asRecord13(raw);
25206
25407
  const viewerRec = firstRecord(record, ["viewer", "principal", "user", "actor", "me", "person"]) ?? record;
25207
25408
  const viewer = {
25208
25409
  id: firstString3(viewerRec, ["id", "user_id"]) || void 0,
@@ -25281,7 +25482,7 @@ async function commentAbleTimeTask(input, opts) {
25281
25482
  { id, task_id: id, task: id, body, comment: body, text: body },
25282
25483
  opts
25283
25484
  );
25284
- const rec = asRecord12(raw);
25485
+ const rec = asRecord13(raw);
25285
25486
  return {
25286
25487
  id: rec ? firstString3(rec, ["id", "comment_id"]) || void 0 : void 0,
25287
25488
  body: rec ? firstString3(rec, ["body", "text", "comment"]) || body : body
@@ -29439,7 +29640,11 @@ function normalizeServiceOrigin(raw, fallback) {
29439
29640
  function optionalServiceConnected(id, integrations) {
29440
29641
  if (id === "vercel") return Boolean(integrations.vercelToken?.trim());
29441
29642
  if (id === "supabase") return Boolean(integrations.supabaseAccessToken?.trim());
29442
- if (id === "posthog") return Boolean(integrations.posthogPersonalApiKey?.trim());
29643
+ if (id === "posthog") {
29644
+ return Boolean(
29645
+ integrations.posthogAccessToken?.trim() || integrations.posthogRefreshToken?.trim() || integrations.posthogPersonalApiKey?.trim()
29646
+ );
29647
+ }
29443
29648
  return Boolean(integrations.sentryAuthToken?.trim());
29444
29649
  }
29445
29650
  function connectedOptionalServices(integrations) {
@@ -29454,12 +29659,12 @@ function connectorDirectiveLine(spec, cli) {
29454
29659
  if (spec.cli) {
29455
29660
  return `- ${spec.label}: use \`${spec.cli}\` (\`${spec.envKey}\`${extras})${cliPresencePhrase(spec, cli)}. Do not add a ${spec.label} MCP.`;
29456
29661
  }
29457
- return `- ${spec.label}: call \`posthog_api\`. Path must start with \`/api/\`. GET is the default. POST \`/api/projects/:id/query/\` or \`/api/environments/:id/query/\` is a read and does not need \`write=true\`. Other POST and PATCH require \`write=true\` only when the user asked to change data. Do not read the API key from the environment. Do not add a ${spec.label} MCP.`;
29662
+ return `- ${spec.label}: call \`posthog_api\`. Path must start with \`/api/\`. GET is the default. POST \`/api/projects/:id/query/\` or \`/api/environments/:id/query/\` is a read and does not need \`write=true\`. Other POST and PATCH require \`write=true\` only when the user asked to change data. Do not read the token from the environment. Do not add a ${spec.label} MCP.`;
29458
29663
  }
29459
29664
  function connectorAuthCaution(posthog, cliConnected) {
29460
29665
  const signIn = posthog ? "If a connector MCP is listed but needsAuth or returns unauthorized, do not sign in to that MCP." : "If a Vercel, Supabase, or Sentry MCP is listed but needsAuth or returns unauthorized, do not sign in to that MCP.";
29461
29666
  const token = cliConnected ? " CLI tokens are already in this process." : "";
29462
- const key = posthog ? " Do not read a PostHog key from the environment." : "";
29667
+ const key = posthog ? " Do not read a PostHog token from the environment." : "";
29463
29668
  return `${signIn}${token}${key} When this Sideboard connection works, ignore a Claude connector that failed to start. Use the Claude connector only when this connection is not set or the CLI call fails.`;
29464
29669
  }
29465
29670
  function connectorReminderBit(spec, cli) {
@@ -29487,7 +29692,7 @@ function formatOptionalServicesReminder(integrations, cli) {
29487
29692
  const bits = connected.map((spec) => connectorReminderBit(spec, cli)).join(". ");
29488
29693
  const tokenBit = connected.some((spec) => spec.cli) ? "CLI tokens are already in this process. " : "";
29489
29694
  const posthog = connected.some((spec) => spec.id === "posthog");
29490
- const auth = posthog ? "If a connector MCP needsAuth or is unauthorized, ignore it and use the CLI or `posthog_api` while this Sideboard connection works. Use the Claude connector only when it is not set or the call fails. Do not read a PostHog key from the environment." : "If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized, ignore it and use the CLI while this Sideboard connection works. Use the Claude connector only when it is not set or the CLI call fails.";
29695
+ const auth = posthog ? "If a connector MCP needsAuth or is unauthorized, ignore it and use the CLI or `posthog_api` while this Sideboard connection works. Use the Claude connector only when it is not set or the call fails. Do not read a PostHog token from the environment." : "If a Vercel, Supabase, or Sentry MCP needsAuth or is unauthorized, ignore it and use the CLI while this Sideboard connection works. Use the Claude connector only when it is not set or the CLI call fails.";
29491
29696
  return `Settings \u2192 Connectors: ${tokenBit}${bits}. ${auth} Do not add vendor MCPs. Shell dumps from those CLIs go in \`.context/cli/\` \u2014 read a slice.`;
29492
29697
  }
29493
29698
  async function connectedCliPresence(integrations) {
@@ -29537,13 +29742,12 @@ var init_optional_services = __esm({
29537
29742
  {
29538
29743
  id: "posthog",
29539
29744
  label: "PostHog",
29540
- hint: "Product analytics. Agents call `posthog_api` on the Sideboard MCP server.",
29745
+ hint: "Product analytics. Sign in with your browser. Agents call `posthog_api`.",
29541
29746
  tokenPlaceholder: "phx_\u2026",
29542
- tokenDocs: "https://app.posthog.com/settings/user-api-keys",
29747
+ tokenDocs: "https://posthog.com/docs/api/oauth",
29543
29748
  envKey: "POSTHOG_PERSONAL_API_KEY",
29544
29749
  hostEnvKey: "POSTHOG_HOST",
29545
- defaultHost: "https://us.posthog.com",
29546
- hostPlaceholder: "https://us.posthog.com"
29750
+ defaultHost: "https://us.posthog.com"
29547
29751
  },
29548
29752
  {
29549
29753
  id: "sentry",
@@ -31556,7 +31760,7 @@ var init_orchestrator = __esm({
31556
31760
  if (!this.shouldReclaimRunningThread(thread)) continue;
31557
31761
  setStatus(thread.id, "stopped", "Process died (agent exited)");
31558
31762
  this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
31559
- this.emit({ type: "turn_finished", threadId: thread.id, exitCode: 1 });
31763
+ this.emit(turnFinishedEvent(thread.id, 1, this.stoppedTurns.has(thread.id), readThread(thread.id)?.lastError));
31560
31764
  const latest = readThread(thread.id);
31561
31765
  if (latest) {
31562
31766
  notifyParentOfChildHalt(latest, "stopped", (id, prompt) => this.send(id, prompt));
@@ -32121,7 +32325,7 @@ var init_orchestrator = __esm({
32121
32325
  if (stopped?.status === "stopped") {
32122
32326
  this.emit({ type: "status_changed", threadId, status: "stopped" });
32123
32327
  }
32124
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
32328
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
32125
32329
  return;
32126
32330
  }
32127
32331
  thread = this.requireThread(threadId);
@@ -32529,7 +32733,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32529
32733
  if (stopped?.status === "stopped") {
32530
32734
  this.emit({ type: "status_changed", threadId, status: "stopped" });
32531
32735
  }
32532
- this.emit({ type: "turn_finished", threadId, exitCode });
32736
+ this.emit(turnFinishedEvent(threadId, exitCode, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
32533
32737
  } else {
32534
32738
  const failDetail = formatTurnExitError(exitCode, detail);
32535
32739
  const explainedInChat = exitCode !== 0 && Boolean(chatText) && (looksLikeAgentFailureMessage(chatText) || failDetail && chatText.includes(failDetail.replace(/^exit\s*\d+:\s*/i, "").trim()));
@@ -32546,7 +32750,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32546
32750
  status: written.status
32547
32751
  });
32548
32752
  }
32549
- this.emit({ type: "turn_finished", threadId, exitCode });
32753
+ this.emit(turnFinishedEvent(threadId, exitCode, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
32550
32754
  if (exitCode === 0) {
32551
32755
  this.crashContinued.delete(threadId);
32552
32756
  this.maybeEnqueueJobContinue(threadId, chatText, parts);
@@ -32581,14 +32785,14 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32581
32785
  if (stopped?.status === "stopped") {
32582
32786
  this.emit({ type: "status_changed", threadId, status: "stopped" });
32583
32787
  }
32584
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
32788
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
32585
32789
  } else {
32586
32790
  const written = writeLiveStatus(threadId, "error", message);
32587
32791
  if (written?.status === "error") {
32588
32792
  this.emit({ type: "error", threadId, message });
32589
32793
  this.emit({ type: "status_changed", threadId, status: "error" });
32590
32794
  }
32591
- this.emit({ type: "turn_finished", threadId, exitCode: 1 });
32795
+ this.emit(turnFinishedEvent(threadId, 1, this.stoppedTurns.has(threadId), readThread(threadId)?.lastError));
32592
32796
  const failedOver = await isolateQuotaFailover(
32593
32797
  () => this.maybeHandleOrchestrationQuotaFailover(threadId, message)
32594
32798
  );
@@ -32636,9 +32840,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32636
32840
  const continueQueue = opts?.continueQueue === true;
32637
32841
  const thread = this.requireThread(threadRef);
32638
32842
  const inFlight = this.activeTurns.has(thread.id) || this.startingTurns.has(thread.id);
32639
- if (inFlight) {
32640
- this.stoppedTurns.add(thread.id);
32641
- }
32843
+ if (inFlight) this.stoppedTurns.add(thread.id);
32642
32844
  if (clearQueue && thread.queue.length > 0) {
32643
32845
  this.haltDrain.delete(thread.id);
32644
32846
  updateThread(thread.id, { queue: [], queueAttachments: [] });
@@ -32648,6 +32850,7 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32648
32850
  } else if (continueQueue) {
32649
32851
  this.haltDrain.delete(thread.id);
32650
32852
  }
32853
+ let stopped = writeStoppedStatus(thread.id, resolveStopReason(opts)) ?? readThread(thread.id) ?? thread;
32651
32854
  const handle = this.activeTurns.get(thread.id);
32652
32855
  if (handle) handle.kill();
32653
32856
  const proc = this.processes.get(`${thread.id}:agent`);
@@ -32666,10 +32869,10 @@ ${formatEnvReminder(projectNameForRepoPath(thread.repoPath || thread.worktreePat
32666
32869
  }
32667
32870
  }
32668
32871
  }
32669
- const stopped = writeStoppedStatus(thread.id, resolveStopReason(opts)) ?? readThread(thread.id) ?? thread;
32872
+ stopped = readThread(thread.id) ?? stopped;
32670
32873
  if (stopped.status === "stopped") {
32671
32874
  this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
32672
- if (inFlight && opts?.notifyParent !== false) {
32875
+ if (inFlight && opts?.notifyParent !== false && !continueQueue) {
32673
32876
  notifyParentOfChildHalt(stopped, "stopped", (id, prompt) => this.send(id, prompt));
32674
32877
  }
32675
32878
  }
@@ -34089,7 +34292,7 @@ function createClippedMcpServer() {
34089
34292
 
34090
34293
  // src/mcp/server.ts
34091
34294
  var import_zod12 = require("zod");
34092
- var import_node_crypto24 = require("crypto");
34295
+ var import_node_crypto25 = require("crypto");
34093
34296
  var import_node_path74 = require("path");
34094
34297
  init_orchestrator();
34095
34298
  init_task_state();
@@ -36002,6 +36205,85 @@ function registerConnectedIssueVendorTools(server, settings = loadAppSettings())
36002
36205
  var import_zod8 = require("zod");
36003
36206
  init_fetch();
36004
36207
  init_optional_services();
36208
+
36209
+ // src/integrations/posthog-oauth.ts
36210
+ var import_node_crypto21 = require("crypto");
36211
+ var import_node_http4 = require("http");
36212
+ init_fetch();
36213
+ init_app_settings();
36214
+ var BAKED_POSTHOG_OAUTH_CLIENT_ID = "https://www.sideboard.build/oauth/posthog-client.json";
36215
+ var POSTHOG_TOKEN = "https://oauth.posthog.com/oauth/token/";
36216
+ var REFRESH_SKEW_MS4 = 6e4;
36217
+ function posthogOAuthClientId() {
36218
+ return process.env.SIDEBOARD_POSTHOG_OAUTH_CLIENT_ID?.trim() || BAKED_POSTHOG_OAUTH_CLIENT_ID;
36219
+ }
36220
+ async function exchangePosthogToken(body) {
36221
+ const res = await httpFetch(POSTHOG_TOKEN, {
36222
+ method: "POST",
36223
+ headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
36224
+ body
36225
+ });
36226
+ const data = await res.json().catch(() => ({}));
36227
+ if (!res.ok || data.error || !data.access_token?.trim()) {
36228
+ const detail = data.error_description || data.error || `HTTP ${res.status}`;
36229
+ throw new Error(`PostHog sign-in failed: ${detail}`);
36230
+ }
36231
+ return data;
36232
+ }
36233
+ var refreshInFlight4 = null;
36234
+ async function refreshPosthogAccessToken(refresh, host, viewerName, legacy) {
36235
+ try {
36236
+ const data = await exchangePosthogToken(
36237
+ new URLSearchParams({
36238
+ grant_type: "refresh_token",
36239
+ refresh_token: refresh,
36240
+ client_id: posthogOAuthClientId()
36241
+ })
36242
+ );
36243
+ const saved = savePosthogOAuth({
36244
+ accessToken: data.access_token.trim(),
36245
+ refreshToken: data.refresh_token?.trim() || refresh,
36246
+ expiresIn: data.expires_in,
36247
+ host,
36248
+ viewerName
36249
+ });
36250
+ return {
36251
+ token: saved.integrations.posthogAccessToken.trim(),
36252
+ host: saved.integrations.posthogHost?.trim() || host
36253
+ };
36254
+ } catch (err) {
36255
+ if (legacy) return { token: legacy, host };
36256
+ throw err;
36257
+ }
36258
+ }
36259
+ async function getPosthogAccessToken() {
36260
+ const integrations = loadAppSettings().integrations;
36261
+ const host = integrations.posthogHost?.trim() || "https://us.posthog.com";
36262
+ const access = integrations.posthogAccessToken?.trim() || "";
36263
+ const refresh = integrations.posthogRefreshToken?.trim() || "";
36264
+ const legacy = integrations.posthogPersonalApiKey?.trim() || "";
36265
+ const exp = integrations.posthogTokenExpiresAt;
36266
+ const accessFresh = Boolean(access) && (exp == null || exp - Date.now() > REFRESH_SKEW_MS4);
36267
+ if (accessFresh) return { token: access, host };
36268
+ if (refresh) {
36269
+ if (!refreshInFlight4) {
36270
+ refreshInFlight4 = refreshPosthogAccessToken(
36271
+ refresh,
36272
+ host,
36273
+ integrations.posthogViewerName,
36274
+ legacy
36275
+ ).finally(() => {
36276
+ refreshInFlight4 = null;
36277
+ });
36278
+ }
36279
+ return refreshInFlight4;
36280
+ }
36281
+ if (access) return { token: access, host };
36282
+ if (legacy) return { token: legacy, host };
36283
+ return null;
36284
+ }
36285
+
36286
+ // src/mcp/posthog-tools.ts
36005
36287
  init_app_settings();
36006
36288
  init_issue_list();
36007
36289
  var POSTHOG_METHODS = ["GET", "POST", "PATCH"];
@@ -36057,9 +36339,16 @@ async function runPosthogApi(input) {
36057
36339
  if (method === "GET" && input.body !== void 0) {
36058
36340
  return mcpJson({ ok: false, error: "GET does not take a body" }, true);
36059
36341
  }
36060
- const integrations = loadAppSettings().integrations;
36061
- const token = integrations.posthogPersonalApiKey?.trim();
36062
- if (!token) {
36342
+ let session;
36343
+ try {
36344
+ session = await getPosthogAccessToken();
36345
+ } catch (err) {
36346
+ return mcpJson(
36347
+ { ok: false, error: err instanceof Error ? err.message : String(err) },
36348
+ true
36349
+ );
36350
+ }
36351
+ if (!session) {
36063
36352
  return mcpJson(
36064
36353
  { ok: false, error: "PostHog is not connected (Settings \u2192 Connectors)." },
36065
36354
  true
@@ -36068,7 +36357,7 @@ async function runPosthogApi(input) {
36068
36357
  let url;
36069
36358
  try {
36070
36359
  url = posthogApiUrl(
36071
- integrations.posthogHost || "https://us.posthog.com",
36360
+ session.host,
36072
36361
  withPosthogSlash(method, input.path),
36073
36362
  input.query
36074
36363
  );
@@ -36079,7 +36368,7 @@ async function runPosthogApi(input) {
36079
36368
  );
36080
36369
  }
36081
36370
  const headers = {
36082
- Authorization: `Bearer ${token}`,
36371
+ Authorization: `Bearer ${session.token}`,
36083
36372
  Accept: "application/json"
36084
36373
  };
36085
36374
  let body;
@@ -36562,7 +36851,7 @@ function registerScheduleTools(server) {
36562
36851
  var import_zod11 = require("zod");
36563
36852
 
36564
36853
  // src/order/order.ts
36565
- var import_node_crypto21 = require("crypto");
36854
+ var import_node_crypto22 = require("crypto");
36566
36855
  var import_node_fs72 = require("fs");
36567
36856
  var import_node_path70 = require("path");
36568
36857
  init_paths();
@@ -37266,7 +37555,7 @@ function setOrderPlan(input) {
37266
37555
  const owner = input.ownerThreadId?.trim() ?? "";
37267
37556
  const existing = file.plans.find((plan2) => plan2.ownerThreadId === owner);
37268
37557
  const plan = {
37269
- id: existing?.id ?? (0, import_node_crypto21.randomUUID)(),
37558
+ id: existing?.id ?? (0, import_node_crypto22.randomUUID)(),
37270
37559
  ownerThreadId: owner,
37271
37560
  title,
37272
37561
  summary: input.summary?.trim().slice(0, 600) ?? existing?.summary ?? "",
@@ -37333,7 +37622,7 @@ function selectPlan(file, input) {
37333
37622
  if (file.plans.length === 1) return file.plans[0];
37334
37623
  if (file.plans.length === 0) {
37335
37624
  const plan = {
37336
- id: (0, import_node_crypto21.randomUUID)(),
37625
+ id: (0, import_node_crypto22.randomUUID)(),
37337
37626
  ownerThreadId: "",
37338
37627
  title: "Planner",
37339
37628
  summary: "",
@@ -37367,7 +37656,7 @@ function setOrderDependency(input) {
37367
37656
  }
37368
37657
  const loop = dependencyWouldCycle(scoped, draft);
37369
37658
  const edge = {
37370
- id: (0, import_node_crypto21.randomUUID)(),
37659
+ id: (0, import_node_crypto22.randomUUID)(),
37371
37660
  planId: plan.id,
37372
37661
  waitsOn,
37373
37662
  gate,
@@ -37704,7 +37993,7 @@ function registerOrderTools(server) {
37704
37993
  }
37705
37994
 
37706
37995
  // src/agent-rpc/handlers.ts
37707
- var import_node_crypto22 = require("crypto");
37996
+ var import_node_crypto23 = require("crypto");
37708
37997
  var import_node_path71 = require("path");
37709
37998
  init_wait_for_job();
37710
37999
  init_wait_for_turn();
@@ -37751,7 +38040,7 @@ setToolPermissionPublisher({
37751
38040
  // src/agent-rpc/handlers.ts
37752
38041
  init_protocol2();
37753
38042
  function presentArtifactResult(input) {
37754
- const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto22.randomUUID)().slice(0, 8)}`;
38043
+ const id = input.artifact_id?.trim() || `artifact_${Date.now().toString(36)}_${(0, import_node_crypto23.randomUUID)().slice(0, 8)}`;
37755
38044
  return {
37756
38045
  ok: true,
37757
38046
  artifact_id: id,
@@ -37776,7 +38065,7 @@ init_worktree();
37776
38065
  init_paths();
37777
38066
 
37778
38067
  // src/board/board-pins.ts
37779
- var import_node_crypto23 = require("crypto");
38068
+ var import_node_crypto24 = require("crypto");
37780
38069
  var import_node_fs73 = require("fs");
37781
38070
  var import_node_path72 = require("path");
37782
38071
  init_paths();
@@ -38757,7 +39046,7 @@ async function startMcpServer() {
38757
39046
  const ident = issue?.identifier ?? ref.trim();
38758
39047
  const attachments = issue ? [
38759
39048
  {
38760
- id: (0, import_node_crypto24.randomUUID)(),
39049
+ id: (0, import_node_crypto25.randomUUID)(),
38761
39050
  name: issue.identifier,
38762
39051
  kind: "issue",
38763
39052
  content: [