cyrus-edge-worker 0.2.75 → 0.2.77

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.
@@ -1,7 +1,7 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { execSync } from "node:child_process";
3
3
  import { EventEmitter } from "node:events";
4
- import { existsSync, readFileSync } from "node:fs";
4
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
6
6
  import { basename, join } from "node:path";
7
7
  import { LinearClient } from "@linear/sdk";
@@ -12,11 +12,12 @@ import { ConfigUpdater, ensureGhTokenResolver, ensureGitHubCredentialHelper, } f
12
12
  import { CLIIssueTrackerService, CLIRPCServer, createLogger, DEFAULT_PROXY_URL, GitHubTokenStore, isAgentSessionCreatedWebhook, isAgentSessionPromptedWebhook, isContentUpdateMessage, isIssueAssignedWebhook, isIssueCommentMentionWebhook, isIssueDeletedWebhook, isIssueNewCommentWebhook, isIssueStateChangeMessage, isIssueStateChangeWebhook, isIssueStateIdUpdateWebhook, isIssueTitleOrDescriptionUpdateWebhook, isIssueUnassignedWebhook, isSessionStartMessage, isStopSignalMessage, isUnassignMessage, isUserPromptMessage, PersistenceManager, requireLinearWorkspaceId, resolvePath, WebhookIpValidator, } from "cyrus-core";
13
13
  import { CursorRunner } from "cyrus-cursor-runner";
14
14
  import { GeminiRunner } from "cyrus-gemini-runner";
15
- import { extractCommentAuthor, extractCommentBody, extractCommentId, extractCommentUrl, extractPRBaseBranchRef, extractPRBranchRef, extractPRNumber, extractPRTitle, extractRepoFullName, extractRepoName, extractRepoOwner, extractSessionKey, GitHubAppTokenProvider, GitHubCommentService, GitHubEventTransport, isCommentOnPullRequest, isIssueCommentPayload, isPullRequestReviewCommentPayload, isPullRequestReviewPayload, stripMention, } from "cyrus-github-event-transport";
15
+ import { allowedReviewAppIds, extractCommentAuthor, extractCommentBody, extractCommentId, extractCommentUrl, extractPRBaseBranchRef, extractPRBranchRef, extractPRNumber, extractPRTitle, extractRepoFullName, extractRepoName, extractRepoOwner, extractSessionKey, formatReviewFindings, GitHubAppTokenProvider, GitHubCommentService, GitHubEventTransport, isCommentOnPullRequest, isIssueCommentPayload, isPullRequestReviewCommentPayload, isPullRequestReviewPayload, loadReviewFindings, resolveReviewAppId, stripMention, } from "cyrus-github-event-transport";
16
16
  import { extractDiscussionId, extractSessionKey as extractGitLabSessionKey, extractMRBaseBranchRef, extractMRBranchRef, extractMRIid, extractMRTitle, extractNoteAuthor, extractNoteBody, extractNoteId, extractNoteUrl, extractProjectId, extractProjectPath, GitLabCommentService, GitLabEventTransport, isNoteOnMergeRequest, stripMention as stripGitLabMention, } from "cyrus-gitlab-event-transport";
17
17
  import { LinearEventTransport, LinearIssueTrackerService, } from "cyrus-linear-event-transport";
18
18
  import { createCodexMessagePublisher, createCyrusToolsServer, createFetchFailureModesClient, } from "cyrus-mcp-tools";
19
19
  import { OpenCodeRunner } from "cyrus-opencode-runner";
20
+ import { PlaneAgentRunCoordinator, PlaneApiClient, PlaneEventTransport, PlaneIssueTrackerService, } from "cyrus-plane-event-transport";
20
21
  import { SlackEventTransport, } from "cyrus-slack-event-transport";
21
22
  import { ZulipEventTransport, } from "cyrus-zulip-event-transport";
22
23
  import { Sessions, streamableHttp } from "fastify-mcp";
@@ -66,6 +67,8 @@ export class EdgeWorker extends EventEmitter {
66
67
  gitLabEventTransport = null; // GitLab event transport for forwarded GitLab webhooks
67
68
  slackEventTransport = null;
68
69
  zulipEventTransport = null;
70
+ planeIssueTracker = null; // Plane agent runs (PLANE_* env vars)
71
+ planeEventTransport = null;
69
72
  zulipChatSessionHandler = null;
70
73
  chatSessionHandler = null;
71
74
  gitHubCommentService; // Service for posting comments back to GitHub PRs
@@ -130,6 +133,8 @@ export class EdgeWorker extends EventEmitter {
130
133
  * Key format: `${createdAt}:${issueId}`
131
134
  */
132
135
  processedIssueUpdateKeys = new Set();
136
+ /** Bounded review-level deduplication, including concurrent and queued suggestions. */
137
+ processedGitHubSuggestionKeys = new Set();
133
138
  /**
134
139
  * Sessions parked due to blocked-by dependencies.
135
140
  * Key: Linear issue ID (the blocked issue)
@@ -317,6 +322,12 @@ export class EdgeWorker extends EventEmitter {
317
322
  this.issueTrackers.set(linearWorkspaceId, issueTracker);
318
323
  }
319
324
  }
325
+ // Plane is configured by env vars; its repositories use the tracker's
326
+ // workspace key as their linearWorkspaceId.
327
+ this.planeIssueTracker = this.createPlaneIssueTracker();
328
+ if (this.planeIssueTracker) {
329
+ this.issueTrackers.set(this.planeIssueTracker.workspaceKey, this.planeIssueTracker);
330
+ }
320
331
  // Create activity sinks per workspace (one per workspace, mirrors issueTrackers)
321
332
  for (const [workspaceId, issueTracker] of this.issueTrackers) {
322
333
  this.activitySinks.set(workspaceId, new LinearActivitySink(issueTracker, workspaceId));
@@ -339,6 +350,9 @@ export class EdgeWorker extends EventEmitter {
339
350
  getIssueTracker: (workspaceId) => this.issueTrackers.get(workspaceId),
340
351
  getCyrusToolsMcpUrl: () => this.getCyrusToolsMcpUrl(),
341
352
  createCyrusToolsOptions: (parentSessionId) => this.createCyrusToolsOptions(parentSessionId),
353
+ getTrackerMcpServers: (workspaceId) => this.planeIssueTracker?.workspaceKey === workspaceId
354
+ ? { plane: this.planeIssueTracker.toolsMcpServerConfig() }
355
+ : undefined,
342
356
  });
343
357
  this.runnerConfigBuilder = new RunnerConfigBuilder(this.toolPermissionResolver, this.mcpConfigService, this.runnerSelectionService);
344
358
  this.activityPoster = new ActivityPoster(this.issueTrackers, this.repositories, this.logger);
@@ -541,6 +555,7 @@ export class EdgeWorker extends EventEmitter {
541
555
  this.registerGitLabEventTransport();
542
556
  this.registerSlackEventTransport();
543
557
  this.registerZulipEventTransport();
558
+ this.registerPlaneEventTransport();
544
559
  // 3. Create and register ConfigUpdater (both platforms)
545
560
  this.configUpdater = new ConfigUpdater(this.sharedApplicationServer.getFastifyInstance(), this.cyrusHome, () => process.env.CYRUS_API_KEY || "");
546
561
  // Register config update routes
@@ -754,6 +769,85 @@ export class EdgeWorker extends EventEmitter {
754
769
  get activeChatSessionHandlers() {
755
770
  return [this.chatSessionHandler, this.zulipChatSessionHandler].filter((handler) => handler !== null);
756
771
  }
772
+ /**
773
+ * Plane (self-hosted or cloud) agent runs. Enabled when PLANE_BASE_URL,
774
+ * PLANE_WORKSPACE_SLUG, PLANE_CLIENT_ID and PLANE_CLIENT_SECRET are set.
775
+ * The app installation id comes from PLANE_APP_INSTALLATION_ID, or from
776
+ * the OAuth install redirect (saved to <cyrusHome>/plane-installation.json).
777
+ */
778
+ createPlaneIssueTracker() {
779
+ const baseUrl = process.env.PLANE_BASE_URL?.trim().replace(/\/+$/, "");
780
+ const workspaceSlug = process.env.PLANE_WORKSPACE_SLUG?.trim();
781
+ const clientId = process.env.PLANE_CLIENT_ID?.trim();
782
+ const clientSecret = process.env.PLANE_CLIENT_SECRET?.trim();
783
+ if (!baseUrl || !workspaceSlug || !clientId || !clientSecret) {
784
+ return null;
785
+ }
786
+ const appInstallationId = process.env.PLANE_APP_INSTALLATION_ID?.trim() ||
787
+ this.readPlaneInstallations()[workspaceSlug] ||
788
+ "";
789
+ const api = new PlaneApiClient({
790
+ baseUrl,
791
+ workspaceSlug,
792
+ clientId,
793
+ clientSecret,
794
+ appInstallationId,
795
+ });
796
+ return new PlaneIssueTrackerService(api, `plane-${workspaceSlug}`);
797
+ }
798
+ planeInstallationsPath() {
799
+ return join(this.cyrusHome, "plane-installation.json");
800
+ }
801
+ readPlaneInstallations() {
802
+ try {
803
+ return JSON.parse(readFileSync(this.planeInstallationsPath(), "utf8"));
804
+ }
805
+ catch {
806
+ return {};
807
+ }
808
+ }
809
+ /**
810
+ * Register the Plane webhook (agent runs) and OAuth install routes, if
811
+ * Plane is configured. Plane's agent events become Linear-shaped agent
812
+ * session webhooks, so they go through the same handling as Linear's.
813
+ */
814
+ registerPlaneEventTransport() {
815
+ const tracker = this.planeIssueTracker;
816
+ if (!tracker) {
817
+ return;
818
+ }
819
+ const webhookSecret = process.env.PLANE_WEBHOOK_SECRET?.trim() || "";
820
+ if (!webhookSecret) {
821
+ this.logger.warn("PLANE_WEBHOOK_SECRET is not set: Plane webhooks are accepted unsigned. Only do this on a local test instance.");
822
+ }
823
+ const coordinator = new PlaneAgentRunCoordinator({
824
+ tracker,
825
+ isKnownSession: (runId) => Boolean(this.agentSessionManager.getSession(runId)) ||
826
+ this.repositoryRouter.hasPendingSelection(runId),
827
+ dispatch: (webhook) => this.handleWebhook(webhook, Array.from(this.repositories.values())),
828
+ });
829
+ this.planeEventTransport = new PlaneEventTransport({
830
+ fastifyServer: this.sharedApplicationServer.getFastifyInstance(),
831
+ webhookSecret,
832
+ onInstall: (query) => {
833
+ const installationId = query.app_installation_id;
834
+ tracker.api.setAppInstallationId(installationId);
835
+ const installations = this.readPlaneInstallations();
836
+ installations[tracker.api.workspaceSlug] = installationId;
837
+ writeFileSync(this.planeInstallationsPath(), JSON.stringify(installations, null, 2), { mode: 0o600 });
838
+ this.logger.info(`Plane app installed in ${tracker.api.workspaceSlug} (installation ${installationId})`);
839
+ return `Cyrus is installed in the Plane workspace "${tracker.api.workspaceSlug}". You can close this tab.`;
840
+ },
841
+ });
842
+ this.planeEventTransport.on("event", (payload) => {
843
+ void coordinator.handle(payload);
844
+ });
845
+ this.planeEventTransport.on("error", (error) => {
846
+ this.handleError(error);
847
+ });
848
+ this.planeEventTransport.register();
849
+ this.logger.info(`✅ Plane event transport registered for ${tracker.api.baseUrl} (workspace ${tracker.api.workspaceSlug}, key ${tracker.workspaceKey})${tracker.api.isInstalled ? "" : " — app not installed yet"}`);
850
+ }
757
851
  /**
758
852
  * Register the Zulip event transport, if Zulip is configured.
759
853
  *
@@ -809,7 +903,11 @@ export class EdgeWorker extends EventEmitter {
809
903
  const cyrusAppBaseUrl = process.env.CYRUS_API_KEY
810
904
  ? getCyrusAppUrl()
811
905
  : undefined;
812
- const slackAdapter = new SlackChatAdapter(chatRepositoryProvider, this.logger, { repositoryRoutingContext: routingContext, cyrusAppBaseUrl });
906
+ const slackAdapter = new SlackChatAdapter(chatRepositoryProvider, this.logger, {
907
+ repositoryRoutingContext: routingContext,
908
+ cyrusAppBaseUrl,
909
+ userAccessControl: this.userAccessControl,
910
+ });
813
911
  if (!chatRepositoryProvider.getDefaultLinearWorkspaceId() ||
814
912
  !chatRepositoryProvider.getDefaultRepository()) {
815
913
  this.logger.warn("No repositories or workspaces configured — Slack sessions will not have access to MCP tools");
@@ -890,6 +988,8 @@ export class EdgeWorker extends EventEmitter {
890
988
  let githubPrQueueKey;
891
989
  let hasReservedGitHubPrSlot = reservedGitHubPrSlot;
892
990
  let githubPrSlotReleased = false;
991
+ let suggestionKey;
992
+ let suggestionAccepted = false;
893
993
  try {
894
994
  // Only handle comments on pull requests
895
995
  if (!isCommentOnPullRequest(event)) {
@@ -898,22 +998,30 @@ export class EdgeWorker extends EventEmitter {
898
998
  }
899
999
  const repoFullName = extractRepoFullName(event);
900
1000
  const prNumber = extractPRNumber(event);
901
- const commentBody = extractCommentBody(event);
1001
+ let commentBody = extractCommentBody(event);
902
1002
  const commentAuthor = extractCommentAuthor(event);
903
1003
  const prTitle = extractPRTitle(event);
904
1004
  const sessionKey = extractSessionKey(event);
905
1005
  githubPrQueueKey = sessionKey;
906
1006
  const isPullRequestReview = isPullRequestReviewPayload(event.payload);
1007
+ const isSuggestion = isPullRequestReviewPayload(event.payload) &&
1008
+ event.payload.review.state === "commented" &&
1009
+ event.payload.review.user.type === "Bot" &&
1010
+ Boolean(event.payload.review.commit_id) &&
1011
+ event.payload.review.commit_id === event.payload.pull_request.head.sha;
907
1012
  // Skip comments from the bot itself to prevent infinite loops
908
1013
  const botUsername = process.env.GITHUB_BOT_USERNAME;
909
- if (botUsername && commentAuthor === botUsername) {
1014
+ if (botUsername &&
1015
+ (commentAuthor === botUsername ||
1016
+ commentAuthor === `${botUsername}[bot]`)) {
910
1017
  this.logger.debug(`Ignoring comment from bot user @${botUsername} on ${repoFullName}#${prNumber}`);
911
1018
  return;
912
1019
  }
913
1020
  // For pull_request_review events, defensively check review state
914
1021
  // (must happen before the mention check — reviews don't contain @mentions)
915
1022
  if (isPullRequestReviewPayload(event.payload)) {
916
- if (event.payload.review.state !== "changes_requested") {
1023
+ if (event.payload.action !== "submitted" ||
1024
+ (event.payload.review.state !== "changes_requested" && !isSuggestion)) {
917
1025
  this.logger.debug(`Ignoring pull_request_review with state: ${event.payload.review.state}`);
918
1026
  return;
919
1027
  }
@@ -925,6 +1033,52 @@ export class EdgeWorker extends EventEmitter {
925
1033
  this.logger.debug(`PR review trigger is disabled, ignoring pull_request_review on ${repoFullName}#${prNumber}`);
926
1034
  return;
927
1035
  }
1036
+ // App reviews default to denied, including direct signed deliveries.
1037
+ // Resolve identity again here; forwarding headers are not covered by GitHub's signature.
1038
+ if (isPullRequestReviewPayload(event.payload) &&
1039
+ event.payload.review.user.type === "Bot") {
1040
+ if (event.payload.review.user.id === event.payload.pull_request.user.id)
1041
+ return;
1042
+ const ids = allowedReviewAppIds(this.config.githubReviewAppPolicies, event.payload.installation?.id.toString(), event.payload.repository.owner, isSuggestion);
1043
+ if (ids.length === 0)
1044
+ return;
1045
+ try {
1046
+ const token = await this.resolveGitHubToken(event);
1047
+ const appId = token
1048
+ ? await resolveReviewAppId(event.payload.review.user, token)
1049
+ : null;
1050
+ if (!appId || !ids.includes(appId))
1051
+ return;
1052
+ // Never accept reviews from the app used to run Cyrus itself.
1053
+ const selfLogin = process.env.GITHUB_APP_SLUG;
1054
+ if (selfLogin && commentAuthor === `${selfLogin}[bot]`)
1055
+ return;
1056
+ if (isSuggestion) {
1057
+ // Do not double-enqueue a review delivered under different webhook IDs.
1058
+ const key = `${event.payload.installation?.id}:${repoFullName}:${prNumber}:${event.payload.review.id}`;
1059
+ if (!reservedGitHubPrSlot &&
1060
+ this.processedGitHubSuggestionKeys.has(key))
1061
+ return;
1062
+ suggestionKey = key;
1063
+ this.processedGitHubSuggestionKeys.add(key);
1064
+ const findings = await loadReviewFindings({
1065
+ owner: extractRepoOwner(event),
1066
+ repo: extractRepoName(event),
1067
+ pullNumber: prNumber,
1068
+ reviewId: event.payload.review.id,
1069
+ authorId: event.payload.review.user.id,
1070
+ commitId: event.payload.review.commit_id,
1071
+ }, token);
1072
+ if (!findings.length)
1073
+ return;
1074
+ commentBody = `Review suggestions from @${commentAuthor}:\n\n${formatReviewFindings(findings)}`;
1075
+ }
1076
+ }
1077
+ catch (error) {
1078
+ this.logger.warn("Could not verify GitHub review app; ignoring review", error instanceof Error ? error : new Error(String(error)));
1079
+ return;
1080
+ }
1081
+ }
928
1082
  // Only trigger on comments that mention the bot (when configured)
929
1083
  // Skip this check for pull_request_review events — reviews don't @mention the bot
930
1084
  if (!isPullRequestReview &&
@@ -997,6 +1151,7 @@ export class EdgeWorker extends EventEmitter {
997
1151
  if (this.activeGitHubPrSessions.has(sessionKey)) {
998
1152
  const queue = this.queuedGitHubPrEvents.get(sessionKey) ?? [];
999
1153
  queue.push(event);
1154
+ suggestionAccepted = true;
1000
1155
  this.queuedGitHubPrEvents.set(sessionKey, queue);
1001
1156
  this.logger.info(`Queued GitHub webhook for ${repoFullName}#${prNumber}; ${queue.length} event(s) waiting`);
1002
1157
  if (reactionToken && prNumber) {
@@ -1025,7 +1180,9 @@ export class EdgeWorker extends EventEmitter {
1025
1180
  owner: extractRepoOwner(event),
1026
1181
  repo: extractRepoName(event),
1027
1182
  issueNumber: prNumber,
1028
- body: "Received your change request. Getting started on those changes now.",
1183
+ body: isSuggestion
1184
+ ? "Received the review suggestions. Getting started on those findings now."
1185
+ : "Received your change request. Getting started on those changes now.",
1029
1186
  })
1030
1187
  .catch((err) => {
1031
1188
  this.logger.warn(`Failed to post acknowledgement comment: ${err instanceof Error ? err.message : err}`);
@@ -1165,6 +1322,7 @@ export class EdgeWorker extends EventEmitter {
1165
1322
  this.logger.info(`Starting ${runnerType} runner for GitHub PR ${repoFullName}#${prNumber}`);
1166
1323
  // Start the session and handle completion
1167
1324
  try {
1325
+ suggestionAccepted = true;
1168
1326
  const sessionInfo = await runner.start(taskInstructions);
1169
1327
  this.logger.info(`GitHub session started: ${sessionInfo.sessionId}`);
1170
1328
  // A runner that exits before emitting a result still needs a reply.
@@ -1189,6 +1347,12 @@ export class EdgeWorker extends EventEmitter {
1189
1347
  !githubPrSlotReleased) {
1190
1348
  this.advanceGitHubPrQueue(githubPrQueueKey);
1191
1349
  }
1350
+ if (suggestionKey && !suggestionAccepted)
1351
+ this.processedGitHubSuggestionKeys.delete(suggestionKey);
1352
+ if (this.processedGitHubSuggestionKeys.size > 1000) {
1353
+ for (const key of [...this.processedGitHubSuggestionKeys].slice(0, 500))
1354
+ this.processedGitHubSuggestionKeys.delete(key);
1355
+ }
1192
1356
  this.activeWebhookCount--;
1193
1357
  }
1194
1358
  }
@@ -1437,7 +1601,7 @@ ${reviewBody}
1437
1601
  - Address all the reviewer's feedback and make the necessary changes
1438
1602
  - After making changes, commit and push them to the branch
1439
1603
  - Respond with a concise summary of the changes you made`;
1440
- return `You are working on a GitHub Pull Request that has received a change request review.
1604
+ return `You are working on a GitHub Pull Request that has received ${isPullRequestReviewPayload(event.payload) && event.payload.review.state === "commented" ? "review suggestions from an explicitly allowed app" : "a change request review"}.
1441
1605
 
1442
1606
  ## Context
1443
1607
  - **Repository**: ${repoFullName}
@@ -1961,6 +2125,7 @@ ${taskSection}`;
1961
2125
  async stop() {
1962
2126
  // Stop config file watcher
1963
2127
  await this.configManager.stop();
2128
+ this.planeIssueTracker?.dispose();
1964
2129
  try {
1965
2130
  await this.savePersistedState();
1966
2131
  this.logger.info("✅ EdgeWorker state saved successfully");
@@ -4964,9 +5129,9 @@ ${input.userComment}
4964
5129
  repoConfig.claudeDefaultModel ||
4965
5130
  repoConfig.model ||
4966
5131
  "claude-opus-4-6";
4967
- // Build allowed/disallowed tools — same as what buildAgentRunnerConfig() uses.
4968
- // Without these, startup() inherits the user's defaultMode ("default"),
4969
- // which causes macOS permission prompts for file writes.
5132
+ // Build the same permission policy that the live runner uses. WarmQuery
5133
+ // handles the first prompt directly, so these startup options cannot rely
5134
+ // on ClaudeRunner.start() to override loaded settings.defaultMode.
4970
5135
  const allowedTools = this.buildAllowedTools(repo);
4971
5136
  const disallowedTools = this.buildDisallowedTools(repo);
4972
5137
  const warm = await startup({
@@ -4978,6 +5143,7 @@ ${input.userComment}
4978
5143
  ...(allowedTools.length > 0 && { allowedTools }),
4979
5144
  ...(disallowedTools.length > 0 && { disallowedTools }),
4980
5145
  settingSources: ["user", "project", "local"],
5146
+ permissionMode: "default",
4981
5147
  strictMcpConfig: this.config.strictMcpConfig ?? true,
4982
5148
  // CLAUDE_CODE_SUBPROCESS_ENV_SCRUB is intentionally not set here;
4983
5149
  // see CYPACK-1108 and ClaudeRunner.start() for context.