cyrus-edge-worker 0.2.76 → 0.2.78-staging.0

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.
@@ -12,7 +12,7 @@ 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";
@@ -30,6 +30,7 @@ import { ChatSessionHandler } from "./ChatSessionHandler.js";
30
30
  import { ConfigManager } from "./ConfigManager.js";
31
31
  import { DefaultSkillsDeployer } from "./DefaultSkillsDeployer.js";
32
32
  import { EgressProxy } from "./EgressProxy.js";
33
+ import { GitHubCiRouter } from "./GitHubCiRouter.js";
33
34
  import { GitService } from "./GitService.js";
34
35
  import { GlobalSessionRegistry } from "./GlobalSessionRegistry.js";
35
36
  import { McpConfigService } from "./McpConfigService.js";
@@ -133,6 +134,8 @@ export class EdgeWorker extends EventEmitter {
133
134
  * Key format: `${createdAt}:${issueId}`
134
135
  */
135
136
  processedIssueUpdateKeys = new Set();
137
+ /** Bounded review-level deduplication, including concurrent and queued suggestions. */
138
+ processedGitHubSuggestionKeys = new Set();
136
139
  /**
137
140
  * Sessions parked due to blocked-by dependencies.
138
141
  * Key: Linear issue ID (the blocked issue)
@@ -397,29 +400,7 @@ export class EdgeWorker extends EventEmitter {
397
400
  this.logger.warn("Session warmup failed (non-fatal):", err);
398
401
  });
399
402
  }
400
- // Start config file watcher via ConfigManager
401
- this.configManager.on("configChanged", async (changes) => {
402
- const strictMcpConfigChanged = (this.config.strictMcpConfig ?? true) !==
403
- (changes.newConfig.strictMcpConfig ?? true);
404
- if (strictMcpConfigChanged) {
405
- for (const warmSession of this.warmInstances.values()) {
406
- warmSession.close();
407
- }
408
- this.warmInstances.clear();
409
- }
410
- this.updateLinearWorkspaceTokens(changes.newConfig);
411
- await this.removeDeletedRepositories(changes.removed);
412
- await this.updateModifiedRepositories(changes.modified);
413
- await this.addNewRepositories(changes.added);
414
- // Live-update sandbox / egress proxy settings
415
- await this.applySandboxConfigChanges(changes.newConfig);
416
- this.config = EdgeWorker.normalizeConfigPaths(changes.newConfig);
417
- this.configManager.setConfig(changes.newConfig);
418
- this.runnerSelectionService.setConfig(changes.newConfig);
419
- this.toolPermissionResolver.setConfig(changes.newConfig);
420
- this.runnerSlots.setLimit(changes.newConfig.maxConcurrentSessions ?? Number.POSITIVE_INFINITY);
421
- });
422
- this.configManager.startConfigWatcher();
403
+ this.startConfigWatcher();
423
404
  // Start egress proxy if sandbox is enabled.
424
405
  // The proxy intercepts Bash-spawned subprocess traffic only (git, gh, npm, etc.).
425
406
  // Claude's inference API, MCP servers, and built-in file tools bypass the proxy.
@@ -599,6 +580,53 @@ export class EdgeWorker extends EventEmitter {
599
580
  * Register the GitHub event transport for receiving forwarded GitHub webhooks from CYHOST.
600
581
  * This creates a /github-webhook endpoint that handles @cyrusagent mentions on GitHub PRs.
601
582
  */
583
+ async prepareCiPrompt(session, repository, prompt) {
584
+ if (this.agentSessionManager.getSession(session.id) !== session) {
585
+ throw new Error("CI continuation unavailable for this session origin");
586
+ }
587
+ if (session.status === "error")
588
+ throw new Error("CI cannot resume an errored or stopped session automatically");
589
+ const runner = session.agentRunner;
590
+ if (runner?.isRunning()) {
591
+ if (!runner.supportsStreamingInput || !runner.addStreamMessage) {
592
+ throw new Error("CI session is busy; redeliver after its turn completes");
593
+ }
594
+ return async () => {
595
+ runner.addStreamMessage(prompt);
596
+ };
597
+ }
598
+ const resumeId = session.claudeSessionId ??
599
+ session.geminiSessionId ??
600
+ session.codexSessionId ??
601
+ session.cursorSessionId ??
602
+ session.opencodeSessionId;
603
+ if (!resumeId)
604
+ throw new Error("CI session has no resumable runner");
605
+ if (!existsSync(session.workspace.path))
606
+ throw new Error("CI workspace no longer exists");
607
+ if (session.issueContext?.trackerId !== "github" &&
608
+ !session.id.startsWith("github-")) {
609
+ const workspaceId = requireLinearWorkspaceId(repository);
610
+ return async () => {
611
+ // A user may have resumed the session during GitHub validation.
612
+ if (session.agentRunner?.isRunning())
613
+ throw new Error("CI session became busy");
614
+ await this.resumeAgentSession(session, repository, session.id, this.agentSessionManager, prompt, "", false, [], workspaceId, 50);
615
+ };
616
+ }
617
+ const { config, runnerType } = await this.buildAgentRunnerConfig(session, repository, session.id, undefined, this.toolPermissionResolver.buildGithubAllowedTools(repository), [
618
+ repository.repositoryPath,
619
+ ...Object.values(session.workspace.repoPaths ?? {}),
620
+ ], this.buildDisallowedTools(repository), resumeId, undefined, undefined, 50, undefined, this.buildSkillSessionContext(repository, undefined, session), "github");
621
+ return async () => {
622
+ if (session.agentRunner?.isRunning())
623
+ throw new Error("CI session became busy");
624
+ const resumed = this.createRunnerForType(runnerType, config);
625
+ this.agentSessionManager.addAgentRunner(session.id, resumed);
626
+ await this.savePersistedState();
627
+ await resumed.start(prompt);
628
+ };
629
+ }
602
630
  registerGitHubEventTransport() {
603
631
  // Use direct GitHub signature verification only when BOTH:
604
632
  // 1. GITHUB_WEBHOOK_SECRET is set (we have the secret to verify)
@@ -613,7 +641,17 @@ export class EdgeWorker extends EventEmitter {
613
641
  const secret = useSignatureVerification
614
642
  ? process.env.GITHUB_WEBHOOK_SECRET
615
643
  : process.env.CYRUS_API_KEY || "";
644
+ const ciRouter = new GitHubCiRouter({
645
+ enabled: () => this.config.ciFailureTrigger === true,
646
+ home: this.cyrusHome,
647
+ repositories: () => [...this.repositories.values()],
648
+ sessions: () => this.getAllKnownSessions(),
649
+ token: (repository, installationToken) => this.resolveGitHubToken({ installationToken }, repository),
650
+ prepare: (session, repository, prompt) => this.prepareCiPrompt(session, repository, prompt),
651
+ onDispatchError: (sessionId) => this.logger.error(`CI dispatch failed for session ${sessionId}; inspect ci-dispatch journal before redelivery`),
652
+ });
616
653
  this.gitHubEventTransport = new GitHubEventTransport({
654
+ handleCiFailure: (failure, context) => ciRouter.handle(failure, context.installationToken),
617
655
  fastifyServer: this.sharedApplicationServer.getFastifyInstance(),
618
656
  verificationMode,
619
657
  secret,
@@ -901,7 +939,11 @@ export class EdgeWorker extends EventEmitter {
901
939
  const cyrusAppBaseUrl = process.env.CYRUS_API_KEY
902
940
  ? getCyrusAppUrl()
903
941
  : undefined;
904
- const slackAdapter = new SlackChatAdapter(chatRepositoryProvider, this.logger, { repositoryRoutingContext: routingContext, cyrusAppBaseUrl });
942
+ const slackAdapter = new SlackChatAdapter(chatRepositoryProvider, this.logger, {
943
+ repositoryRoutingContext: routingContext,
944
+ cyrusAppBaseUrl,
945
+ userAccessControl: this.userAccessControl,
946
+ });
905
947
  if (!chatRepositoryProvider.getDefaultLinearWorkspaceId() ||
906
948
  !chatRepositoryProvider.getDefaultRepository()) {
907
949
  this.logger.warn("No repositories or workspaces configured — Slack sessions will not have access to MCP tools");
@@ -982,6 +1024,8 @@ export class EdgeWorker extends EventEmitter {
982
1024
  let githubPrQueueKey;
983
1025
  let hasReservedGitHubPrSlot = reservedGitHubPrSlot;
984
1026
  let githubPrSlotReleased = false;
1027
+ let suggestionKey;
1028
+ let suggestionAccepted = false;
985
1029
  try {
986
1030
  // Only handle comments on pull requests
987
1031
  if (!isCommentOnPullRequest(event)) {
@@ -990,22 +1034,30 @@ export class EdgeWorker extends EventEmitter {
990
1034
  }
991
1035
  const repoFullName = extractRepoFullName(event);
992
1036
  const prNumber = extractPRNumber(event);
993
- const commentBody = extractCommentBody(event);
1037
+ let commentBody = extractCommentBody(event);
994
1038
  const commentAuthor = extractCommentAuthor(event);
995
1039
  const prTitle = extractPRTitle(event);
996
1040
  const sessionKey = extractSessionKey(event);
997
1041
  githubPrQueueKey = sessionKey;
998
1042
  const isPullRequestReview = isPullRequestReviewPayload(event.payload);
1043
+ const isSuggestion = isPullRequestReviewPayload(event.payload) &&
1044
+ event.payload.review.state === "commented" &&
1045
+ event.payload.review.user.type === "Bot" &&
1046
+ Boolean(event.payload.review.commit_id) &&
1047
+ event.payload.review.commit_id === event.payload.pull_request.head.sha;
999
1048
  // Skip comments from the bot itself to prevent infinite loops
1000
1049
  const botUsername = process.env.GITHUB_BOT_USERNAME;
1001
- if (botUsername && commentAuthor === botUsername) {
1050
+ if (botUsername &&
1051
+ (commentAuthor === botUsername ||
1052
+ commentAuthor === `${botUsername}[bot]`)) {
1002
1053
  this.logger.debug(`Ignoring comment from bot user @${botUsername} on ${repoFullName}#${prNumber}`);
1003
1054
  return;
1004
1055
  }
1005
1056
  // For pull_request_review events, defensively check review state
1006
1057
  // (must happen before the mention check — reviews don't contain @mentions)
1007
1058
  if (isPullRequestReviewPayload(event.payload)) {
1008
- if (event.payload.review.state !== "changes_requested") {
1059
+ if (event.payload.action !== "submitted" ||
1060
+ (event.payload.review.state !== "changes_requested" && !isSuggestion)) {
1009
1061
  this.logger.debug(`Ignoring pull_request_review with state: ${event.payload.review.state}`);
1010
1062
  return;
1011
1063
  }
@@ -1017,6 +1069,52 @@ export class EdgeWorker extends EventEmitter {
1017
1069
  this.logger.debug(`PR review trigger is disabled, ignoring pull_request_review on ${repoFullName}#${prNumber}`);
1018
1070
  return;
1019
1071
  }
1072
+ // App reviews default to denied, including direct signed deliveries.
1073
+ // Resolve identity again here; forwarding headers are not covered by GitHub's signature.
1074
+ if (isPullRequestReviewPayload(event.payload) &&
1075
+ event.payload.review.user.type === "Bot") {
1076
+ if (event.payload.review.user.id === event.payload.pull_request.user.id)
1077
+ return;
1078
+ const ids = allowedReviewAppIds(this.config.githubReviewAppPolicies, event.payload.installation?.id.toString(), event.payload.repository.owner, isSuggestion);
1079
+ if (ids.length === 0)
1080
+ return;
1081
+ try {
1082
+ const token = await this.resolveGitHubToken(event);
1083
+ const appId = token
1084
+ ? await resolveReviewAppId(event.payload.review.user, token)
1085
+ : null;
1086
+ if (!appId || !ids.includes(appId))
1087
+ return;
1088
+ // Never accept reviews from the app used to run Cyrus itself.
1089
+ const selfLogin = process.env.GITHUB_APP_SLUG;
1090
+ if (selfLogin && commentAuthor === `${selfLogin}[bot]`)
1091
+ return;
1092
+ if (isSuggestion) {
1093
+ // Do not double-enqueue a review delivered under different webhook IDs.
1094
+ const key = `${event.payload.installation?.id}:${repoFullName}:${prNumber}:${event.payload.review.id}`;
1095
+ if (!reservedGitHubPrSlot &&
1096
+ this.processedGitHubSuggestionKeys.has(key))
1097
+ return;
1098
+ suggestionKey = key;
1099
+ this.processedGitHubSuggestionKeys.add(key);
1100
+ const findings = await loadReviewFindings({
1101
+ owner: extractRepoOwner(event),
1102
+ repo: extractRepoName(event),
1103
+ pullNumber: prNumber,
1104
+ reviewId: event.payload.review.id,
1105
+ authorId: event.payload.review.user.id,
1106
+ commitId: event.payload.review.commit_id,
1107
+ }, token);
1108
+ if (!findings.length)
1109
+ return;
1110
+ commentBody = `Review suggestions from @${commentAuthor}:\n\n${formatReviewFindings(findings)}`;
1111
+ }
1112
+ }
1113
+ catch (error) {
1114
+ this.logger.warn("Could not verify GitHub review app; ignoring review", error instanceof Error ? error : new Error(String(error)));
1115
+ return;
1116
+ }
1117
+ }
1020
1118
  // Only trigger on comments that mention the bot (when configured)
1021
1119
  // Skip this check for pull_request_review events — reviews don't @mention the bot
1022
1120
  if (!isPullRequestReview &&
@@ -1089,6 +1187,7 @@ export class EdgeWorker extends EventEmitter {
1089
1187
  if (this.activeGitHubPrSessions.has(sessionKey)) {
1090
1188
  const queue = this.queuedGitHubPrEvents.get(sessionKey) ?? [];
1091
1189
  queue.push(event);
1190
+ suggestionAccepted = true;
1092
1191
  this.queuedGitHubPrEvents.set(sessionKey, queue);
1093
1192
  this.logger.info(`Queued GitHub webhook for ${repoFullName}#${prNumber}; ${queue.length} event(s) waiting`);
1094
1193
  if (reactionToken && prNumber) {
@@ -1117,7 +1216,9 @@ export class EdgeWorker extends EventEmitter {
1117
1216
  owner: extractRepoOwner(event),
1118
1217
  repo: extractRepoName(event),
1119
1218
  issueNumber: prNumber,
1120
- body: "Received your change request. Getting started on those changes now.",
1219
+ body: isSuggestion
1220
+ ? "Received the review suggestions. Getting started on those findings now."
1221
+ : "Received your change request. Getting started on those changes now.",
1121
1222
  })
1122
1223
  .catch((err) => {
1123
1224
  this.logger.warn(`Failed to post acknowledgement comment: ${err instanceof Error ? err.message : err}`);
@@ -1257,6 +1358,7 @@ export class EdgeWorker extends EventEmitter {
1257
1358
  this.logger.info(`Starting ${runnerType} runner for GitHub PR ${repoFullName}#${prNumber}`);
1258
1359
  // Start the session and handle completion
1259
1360
  try {
1361
+ suggestionAccepted = true;
1260
1362
  const sessionInfo = await runner.start(taskInstructions);
1261
1363
  this.logger.info(`GitHub session started: ${sessionInfo.sessionId}`);
1262
1364
  // A runner that exits before emitting a result still needs a reply.
@@ -1281,6 +1383,12 @@ export class EdgeWorker extends EventEmitter {
1281
1383
  !githubPrSlotReleased) {
1282
1384
  this.advanceGitHubPrQueue(githubPrQueueKey);
1283
1385
  }
1386
+ if (suggestionKey && !suggestionAccepted)
1387
+ this.processedGitHubSuggestionKeys.delete(suggestionKey);
1388
+ if (this.processedGitHubSuggestionKeys.size > 1000) {
1389
+ for (const key of [...this.processedGitHubSuggestionKeys].slice(0, 500))
1390
+ this.processedGitHubSuggestionKeys.delete(key);
1391
+ }
1284
1392
  this.activeWebhookCount--;
1285
1393
  }
1286
1394
  }
@@ -1529,7 +1637,7 @@ ${reviewBody}
1529
1637
  - Address all the reviewer's feedback and make the necessary changes
1530
1638
  - After making changes, commit and push them to the branch
1531
1639
  - Respond with a concise summary of the changes you made`;
1532
- return `You are working on a GitHub Pull Request that has received a change request review.
1640
+ 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"}.
1533
1641
 
1534
1642
  ## Context
1535
1643
  - **Repository**: ${repoFullName}
@@ -2200,6 +2308,32 @@ ${taskSection}`;
2200
2308
  return false;
2201
2309
  }
2202
2310
  }
2311
+ /** Register live configuration updates before watching the file. */
2312
+ startConfigWatcher() {
2313
+ // Start config file watcher via ConfigManager
2314
+ this.configManager.on("configChanged", async (changes) => {
2315
+ const strictMcpConfigChanged = (this.config.strictMcpConfig ?? true) !==
2316
+ (changes.newConfig.strictMcpConfig ?? true);
2317
+ if (strictMcpConfigChanged) {
2318
+ for (const warmSession of this.warmInstances.values()) {
2319
+ warmSession.close();
2320
+ }
2321
+ this.warmInstances.clear();
2322
+ }
2323
+ this.updateLinearWorkspaceTokens(changes.newConfig);
2324
+ await this.removeDeletedRepositories(changes.removed);
2325
+ await this.updateModifiedRepositories(changes.modified);
2326
+ await this.addNewRepositories(changes.added);
2327
+ // Live-update sandbox / egress proxy settings
2328
+ await this.applySandboxConfigChanges(changes.newConfig);
2329
+ this.config = EdgeWorker.normalizeConfigPaths(changes.newConfig);
2330
+ this.configManager.setConfig(changes.newConfig);
2331
+ this.runnerSelectionService.setConfig(changes.newConfig);
2332
+ this.toolPermissionResolver.setConfig(changes.newConfig);
2333
+ this.runnerSlots.setLimit(changes.newConfig.maxConcurrentSessions ?? Number.POSITIVE_INFINITY);
2334
+ });
2335
+ this.configManager.startConfigWatcher();
2336
+ }
2203
2337
  /**
2204
2338
  * Set the config file path for dynamic reloading
2205
2339
  */