@andorra-labs/code 0.1.15 → 0.1.16

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 (100) hide show
  1. package/dist/src/agent-definitions.js +29 -6
  2. package/dist/src/agent-execution.js +4 -2
  3. package/dist/src/agent-mcp.d.ts +1 -1
  4. package/dist/src/agent-mcp.js +13 -9
  5. package/dist/src/app-server/protocol.d.ts +4 -1
  6. package/dist/src/app-server/protocol.js +1 -1
  7. package/dist/src/app-server.d.ts +107 -0
  8. package/dist/src/app-server.js +893 -22
  9. package/dist/src/auth/deployment.js +2 -2
  10. package/dist/src/browser-runner.js +1 -0
  11. package/dist/src/browser-ui/style.css +3 -3
  12. package/dist/src/browser-ui/tokens.css +27 -16
  13. package/dist/src/claude-provider.js +3 -1
  14. package/dist/src/cli.js +22 -8
  15. package/dist/src/codex-errors.js +4 -1
  16. package/dist/src/command-screens.js +5 -3
  17. package/dist/src/commands.d.ts +2 -1
  18. package/dist/src/compaction-phrases.d.ts +4 -0
  19. package/dist/src/compaction-phrases.js +20 -0
  20. package/dist/src/context-compaction.js +2 -1
  21. package/dist/src/decision/DecisionManager.js +3 -2
  22. package/dist/src/decision/requestPhrases.d.ts +4 -0
  23. package/dist/src/decision/requestPhrases.js +23 -0
  24. package/dist/src/github-inbox.d.ts +55 -0
  25. package/dist/src/github-inbox.js +153 -0
  26. package/dist/src/graph-health.js +7 -3
  27. package/dist/src/graph-provider-portability.js +32 -10
  28. package/dist/src/graph-quota.d.ts +29 -2
  29. package/dist/src/graph-quota.js +68 -10
  30. package/dist/src/graph-runner.js +24 -7
  31. package/dist/src/graph-server.d.ts +1 -1
  32. package/dist/src/graph-server.js +9 -7
  33. package/dist/src/graph-ui/app.js +110 -33
  34. package/dist/src/graph-ui/controls.css +1 -0
  35. package/dist/src/graph-ui/embed.js +2 -2
  36. package/dist/src/graph-ui/icons.js +1 -0
  37. package/dist/src/graph-ui/index.html +1 -1
  38. package/dist/src/graph-ui/manager.css +1 -1
  39. package/dist/src/graph-ui/manager.js +2 -2
  40. package/dist/src/graph-ui/sidebar.js +30 -0
  41. package/dist/src/graph-ui/studio-canvas.js +26 -13
  42. package/dist/src/graph-ui/studio.css +15 -7
  43. package/dist/src/graph-ui/studio.js +11 -4
  44. package/dist/src/graph-ui/style.css +77 -45
  45. package/dist/src/graph-ui/theme.js +3 -36
  46. package/dist/src/graph-ui/tokens.css +27 -19
  47. package/dist/src/graphs.js +4 -3
  48. package/dist/src/membership.d.ts +20 -1
  49. package/dist/src/membership.js +29 -4
  50. package/dist/src/model-metadata.d.ts +1 -1
  51. package/dist/src/model-metadata.js +4 -2
  52. package/dist/src/plan-pass.d.ts +59 -0
  53. package/dist/src/plan-pass.js +165 -0
  54. package/dist/src/provider-engine.js +3 -0
  55. package/dist/src/providers.d.ts +17 -0
  56. package/dist/src/providers.js +68 -19
  57. package/dist/src/pull-request-checks.d.ts +26 -0
  58. package/dist/src/pull-request-checks.js +56 -0
  59. package/dist/src/pull-request-conversation.d.ts +134 -0
  60. package/dist/src/pull-request-conversation.js +221 -0
  61. package/dist/src/pull-request-create.d.ts +175 -0
  62. package/dist/src/pull-request-create.js +392 -0
  63. package/dist/src/pull-request-details.d.ts +242 -0
  64. package/dist/src/pull-request-details.js +614 -0
  65. package/dist/src/pull-request-edit.d.ts +23 -0
  66. package/dist/src/pull-request-edit.js +91 -0
  67. package/dist/src/pull-request-logs.d.ts +76 -0
  68. package/dist/src/pull-request-logs.js +172 -0
  69. package/dist/src/pull-request-merge.d.ts +112 -0
  70. package/dist/src/pull-request-merge.js +258 -0
  71. package/dist/src/pull-request-review.d.ts +137 -0
  72. package/dist/src/pull-request-review.js +401 -0
  73. package/dist/src/pull-requests.d.ts +43 -2
  74. package/dist/src/pull-requests.js +112 -21
  75. package/dist/src/react-runtime.js +37 -4
  76. package/dist/src/remote/engine-pool.js +16 -4
  77. package/dist/src/run-control.d.ts +10 -0
  78. package/dist/src/run-control.js +24 -0
  79. package/dist/src/run-progress.d.ts +10 -0
  80. package/dist/src/run-progress.js +122 -0
  81. package/dist/src/run-records.d.ts +2 -2
  82. package/dist/src/runtime.d.ts +5 -1
  83. package/dist/src/runtime.js +14 -2
  84. package/dist/src/subagent-run.js +1 -0
  85. package/dist/src/telemetry/capture-core.d.ts +17 -0
  86. package/dist/src/telemetry/capture-core.js +59 -1
  87. package/dist/src/telemetry/classify.d.ts +3 -1
  88. package/dist/src/telemetry/classify.js +37 -0
  89. package/dist/src/telemetry/emitter.d.ts +2 -0
  90. package/dist/src/telemetry/emitter.js +42 -5
  91. package/dist/src/telemetry/schema.d.ts +22 -0
  92. package/dist/src/telemetry/schema.js +68 -1
  93. package/dist/src/telemetry/surface.d.ts +1 -0
  94. package/dist/src/telemetry/uploader.d.ts +6 -1
  95. package/dist/src/telemetry/uploader.js +22 -3
  96. package/dist/src/terminal-ui.js +1 -1
  97. package/dist/src/transcript.js +8 -2
  98. package/dist/src/types.d.ts +7 -0
  99. package/dist/src/usage-analytics.js +18 -10
  100. package/package.json +1 -1
@@ -12,7 +12,7 @@ import { changeConfigFile, configDirectory, ConfigConflictError, isProjectExtens
12
12
  import { isUnlimitedAlias } from './limits.js';
13
13
  import { isPermissionMode, permissionMode as livePermissionMode, workspacePermissionKey } from './permissions.js';
14
14
  import { RunControl } from './run-control.js';
15
- import { allocateCodexAccountSlots, createAdapter, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS } from './providers.js';
15
+ import { allocateCodexAccountSlots, createAdapter, findProviderById, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS } from './providers.js';
16
16
  import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
17
17
  import { testProviderConnection } from './provider-connection.js';
18
18
  import { CodexAccountAuth } from './codex-browser-auth.js';
@@ -31,8 +31,8 @@ import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.
31
31
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
32
32
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
33
33
  import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
34
- import { freeTierGraphViolation, readGraphQuota } from './graph-quota.js';
35
- import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, currentGraphSelection, getMembership, loadAccessibleGraph } from './membership.js';
34
+ import { freeTierGraphViolation, notePremiumGraphAccount, readGraphQuota } from './graph-quota.js';
35
+ import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph } from './membership.js';
36
36
  import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
37
37
  import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
38
38
  import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
@@ -47,7 +47,15 @@ import { writePendingAgentInteraction, removePendingAgentInteraction } from './s
47
47
  import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
48
48
  import { createTools } from './tools.js';
49
49
  import { TimerRegistry, WAKE_RETRY_MS } from './timers.js';
50
- import { confirmAutoFixWake, isFinishedPullRequest, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, noAccountMessage, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
50
+ import { checksRollup, classifyGhError, classifyWriteError, PullRequestReader, runAsAccount, sameChecksRollup, PullRequestRefusal } from './pull-request-details.js';
51
+ import { commitBody, commitTitle, deleteBranch, dequeue, enableAutoMerge, enqueue, headCommit, mergeMethod, mergePullRequest, setReadyForReview, updateBranch, updateMethod } from './pull-request-merge.js';
52
+ import { accountToken, branchName, createFromFolder, githubHttpsUrl, githubRepositoryOf, gitIn, PullRequestCreateBlocked, pullRequestTitle, readCreateDraft, repositoryName, tokenCredentials } from './pull-request-create.js';
53
+ import { addComment, applySuggestionText, commitFile, coAuthorTrailer, deleteComment, editComment, reactionContent, readFileAt, setReaction, suggestionOf, uniformLineEndings } from './pull-request-conversation.js';
54
+ import { changeAssignees, changeLabels, currentText, editBody, editTitle, nodeIds, setOpen, updateText } from './pull-request-edit.js';
55
+ import { actionsJobOf, fixChecksPrompt, jobId } from './pull-request-logs.js';
56
+ import { issueNamedIn, readRepositoryIssues, readReviewRequests } from './github-inbox.js';
57
+ import { changeReviewers, commentBody, draftComments, failedRunIds, githubLogin, nodeId, replyToThread, rerunFailedJobs, reviewerEntries, reviewerLogins, reviewEvent, reviewPath, runIds, setFileViewed, setThreadResolved, submitReview, teamSlugs, } from './pull-request-review.js';
58
+ import { confirmAutoFixWake, handedOver, isFinishedPullRequest, settleFinishedPullRequest, withChecks, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, noAccountMessage, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
51
59
  import { AutomationStore } from './automations.js';
52
60
  import { executeAutomation } from './automation-runner.js';
53
61
  import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
@@ -62,7 +70,7 @@ import { pricingFor } from './model-tiers.js';
62
70
  import { purgeOutbox } from './telemetry/outbox.js';
63
71
  import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
64
72
  import { ArtifactStore } from './artifacts.js';
65
- import { mergeRunProgress, replayRunJournal } from './run-progress.js';
73
+ import { coverUnsavedToolCalls, mergeRunProgress, replayRunJournal, toolBoundaryOpen } from './run-progress.js';
66
74
  import { compactHistory, compactedContextEstimate } from './commands.js';
67
75
  import { readFavicon } from './favicons.js';
68
76
  import { attachmentReferenceBlock, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, relinkAttachmentPath, resolveAttachments, attachmentReadRoots } from './attachments.js';
@@ -124,6 +132,17 @@ const RELAY_LONG_DEADLINE_MS = 1_260_000;
124
132
  const MAX_RESUME_LINEAGE = 32;
125
133
  const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'projectMemory', 'limits', 'workspacePermissions', 'projectExtensions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch'];
126
134
  function message(error) { return error instanceof Error ? error.message : String(error); }
135
+ const MERGE_METHOD_WORD = { merge: 'A merge commit', squash: 'Squash and merge', rebase: 'Rebase and merge' };
136
+ const NEW_COMMITS = 'This pull request has new commits since you read it. Look at them before merging or updating it.';
137
+ /** A PR-tab write's parameters, checked before anything reaches gh; a bad one is the caller's error. */
138
+ function writeParams(parse) {
139
+ try {
140
+ return parse();
141
+ }
142
+ catch (error) {
143
+ throw new AppServerError('invalid-params', message(error));
144
+ }
145
+ }
127
146
  function providerAuthView(view, includeUrl) {
128
147
  if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
129
148
  throw new Error('Invalid authentication state');
@@ -613,8 +632,12 @@ function freshAllowance(state) {
613
632
  const { remainingToolCalls: _tools, remainingWallTimeMs: _wall, ...rest } = state;
614
633
  return { ...rest, iterations: 0, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: freshAllowance(copy.state) })) }) };
615
634
  }
635
+ /** Marks a checkpoint (and its modifier copies) so the resumed agent summarizes its earlier messages before its first request. */
636
+ function requestCompaction(state) {
637
+ return { ...state, compactRequested: true, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: requestCompaction(copy.state) })) }) };
638
+ }
616
639
  function wakeProvenance(wake, node) {
617
- if (wake !== 'timer' && wake !== 'auto-fix')
640
+ if (wake !== 'timer' && wake !== 'auto-fix' && wake !== 'fix-checks')
618
641
  return {};
619
642
  return { wake, ...(typeof node === 'string' && node ? { node } : {}) };
620
643
  }
@@ -712,9 +735,13 @@ export class AppServer {
712
735
  detectedSignIns = new Map();
713
736
  retireCodexAccount;
714
737
  gh;
738
+ git;
715
739
  pullRequestWatcher;
740
+ pullRequestReader;
716
741
  sessionChanges;
717
742
  autoFixWakes = new Set();
743
+ /** Wakes the PR tab's Fix with Agent armed: delivered as the person's request, not as a timer. */
744
+ fixWakes = new Set();
718
745
  reviewWaiters = new Map();
719
746
  reviewWaitsStarting = new Set();
720
747
  graphSync = new GraphAccessSync(undefined, undefined, () => this.emit('graphs.changed', {}));
@@ -791,6 +818,10 @@ export class AppServer {
791
818
  this.signInProbes = options.signInProbes;
792
819
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
793
820
  this.gh = options.gh ?? runGh;
821
+ this.git = options.git ?? gitIn;
822
+ this.pullRequestReader = new PullRequestReader(this.gh, Date.now, (sessionId, read, details) => {
823
+ void this.syncPullRequestRecord(sessionId, read, details).catch(error => this.log('warn', `Could not record ${read.url}'s checks: ${message(error)}`));
824
+ });
794
825
  this.pullRequestWatcher = new PullRequestWatcher({
795
826
  home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
796
827
  onUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
@@ -1217,8 +1248,8 @@ export class AppServer {
1217
1248
  case 'sessions.stats': return { stats: await this.sessionStats() };
1218
1249
  case 'sessions.usage': {
1219
1250
  const days = params.days === undefined ? 7 : params.days;
1220
- if (days !== 7 && days !== 30 && days !== 365)
1221
- throw new AppServerError('invalid-params', 'days must be 7, 30, or 365');
1251
+ if (days !== 1 && days !== 7 && days !== 30 && days !== 365)
1252
+ throw new AppServerError('invalid-params', 'days must be 1, 7, 30, or 365');
1222
1253
  return { usage: await readUsageAnalytics(this.directory, days) };
1223
1254
  }
1224
1255
  case 'sessions.get': {
@@ -1253,6 +1284,32 @@ export class AppServer {
1253
1284
  case 'sessions.pullRequest.dismiss':
1254
1285
  await this.dismissPullRequest(identifier(params.id, 'id'));
1255
1286
  return {};
1287
+ case 'sessions.pullRequest.details': return this.pullRequestDetails(identifier(params.id, 'id'), params.refresh === true);
1288
+ case 'sessions.pullRequest.files':
1289
+ return this.pullRequestFiles(identifier(params.id, 'id'), params.refresh === true, typeof params.headSha === 'string' && /^[0-9a-f]{7,64}$/i.test(params.headSha) ? params.headSha : undefined);
1290
+ case 'sessions.pullRequest.review': return this.pullRequestReview(identifier(params.id, 'id'), params.refresh === true);
1291
+ case 'sessions.pullRequest.submitReview': return this.submitPullRequestReview(params);
1292
+ case 'sessions.pullRequest.thread': return this.pullRequestThread(params);
1293
+ case 'sessions.pullRequest.markViewed': return this.markPullRequestFileViewed(params);
1294
+ case 'sessions.pullRequest.rerunChecks': return this.rerunPullRequestChecks(params);
1295
+ case 'sessions.pullRequest.requestReviewers': return this.requestPullRequestReviewers(params);
1296
+ case 'sessions.pullRequest.mergeState': return this.pullRequestReader.readMerge(identifier(params.id, 'id'), await this.storedPullRequest(identifier(params.id, 'id')), { refresh: params.refresh === true });
1297
+ case 'sessions.pullRequest.merge': return this.mergeSessionPullRequest(params);
1298
+ case 'sessions.pullRequest.updateBranch': return this.updateSessionPullRequestBranch(params);
1299
+ case 'sessions.pullRequest.ready': return this.readySessionPullRequest(params);
1300
+ case 'sessions.pullRequest.draft': return this.sessionPullRequestDraft(params);
1301
+ case 'sessions.pullRequest.create': return this.createSessionPullRequest(params);
1302
+ case 'sessions.pullRequest.comment': return this.pullRequestComment(params);
1303
+ case 'sessions.pullRequest.react': return this.pullRequestReact(params);
1304
+ case 'sessions.pullRequest.applySuggestion': return this.applyPullRequestSuggestion(params);
1305
+ case 'sessions.pullRequest.checkLog': return this.pullRequestCheckLog(params);
1306
+ case 'sessions.pullRequest.fixChecks': return this.fixPullRequestChecks(params);
1307
+ case 'sessions.pullRequest.edit': return this.editSessionPullRequest(params);
1308
+ case 'sessions.pullRequest.setState': return this.setSessionPullRequestState(params);
1309
+ case 'sessions.pullRequest.dequeue': return this.dequeueSessionPullRequest(params);
1310
+ case 'sessions.pullRequest.attach': return this.attachSessionPullRequest(params);
1311
+ case 'pullRequests.reviewRequests': return this.pullRequestReviewRequests(params.refresh === true);
1312
+ case 'issues.list': return this.listWorkspaceIssues(params);
1256
1313
  case 'sessions.changes.list': return this.sessionChanges.list(changesSessionId(params.id), diffLines(params.maxLines, LIST_DIFF_LINES));
1257
1314
  case 'sessions.changes.get': {
1258
1315
  const id = changesSessionId(params.id);
@@ -2046,6 +2103,10 @@ export class AppServer {
2046
2103
  }
2047
2104
  const [entry] = mergeProviderSecrets(current.providers, [upsert]);
2048
2105
  const index = current.providers.findIndex(item => item.id === entry.id);
2106
+ // Ids are matched without regard to case, so two that differ only in case would name one provider.
2107
+ const clash = index < 0 ? current.providers.find(item => item.id.toLowerCase() === entry.id.toLowerCase()) : undefined;
2108
+ if (clash)
2109
+ throw new AppServerError('invalid-params', `A provider named ${clash.id} already exists; provider identifiers ignore case. Choose another identifier.`);
2049
2110
  providers = index < 0 ? [...current.providers, entry] : current.providers.map((item, at) => at === index ? entry : item);
2050
2111
  providers = allocateCodexAccountSlots(current.providers, providers);
2051
2112
  removedSlots.length = 0;
@@ -2679,6 +2740,7 @@ export class AppServer {
2679
2740
  this.emitTimers(id);
2680
2741
  await this.browserViews.release(id, 'That session was deleted.');
2681
2742
  await removePullRequest(this.directory, id).catch(() => { });
2743
+ this.pullRequestReader.forget(id);
2682
2744
  await removeSessionSkill(this.directory, id).catch(() => { });
2683
2745
  if (/^[A-Za-z0-9_-]{1,128}$/.test(id))
2684
2746
  await this.sessionChanges.remove(id).catch(() => { });
@@ -2815,7 +2877,7 @@ export class AppServer {
2815
2877
  ...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
2816
2878
  ...(params.permissions === undefined ? {} : { permissions: params.permissions }),
2817
2879
  ...(sentAttachments === undefined ? {} : { attachments: sentAttachments }),
2818
- }, { sameSession: sessionId, resumedFrom: originalRunId, ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }), ...(ownWake === undefined ? {} : { wake: ownWake }), ...(ownWakeNode === undefined ? {} : { wakeNode: ownWakeNode }), ...(internal?.freshAllowance === true ? { freshAllowance: true } : {}) });
2880
+ }, { sameSession: sessionId, resumedFrom: originalRunId, ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }), ...(ownWake === undefined ? {} : { wake: ownWake }), ...(ownWakeNode === undefined ? {} : { wakeNode: ownWakeNode }), ...(internal?.freshAllowance === true ? { freshAllowance: true } : {}), ...(params.compact === true ? { compact: true } : {}) });
2819
2881
  }
2820
2882
  catch (error) {
2821
2883
  await releaseRunResumeClaim(this.directory, originalRunId);
@@ -2935,7 +2997,7 @@ export class AppServer {
2935
2997
  if (!config.providers.length)
2936
2998
  throw new AppServerError('invalid-params', 'Add a model provider in Settings before starting a task.');
2937
2999
  const providerId = params.provider === undefined ? config.provider : identifier(params.provider, 'provider');
2938
- const provider = config.providers.find(item => item.id === providerId);
3000
+ const provider = findProviderById(config.providers, providerId);
2939
3001
  if (!provider)
2940
3002
  throw new AppServerError('invalid-params', `Unknown provider: ${providerId}`);
2941
3003
  const carriedModel = internal?.carriedModel;
@@ -3085,6 +3147,10 @@ export class AppServer {
3085
3147
  for (const [nodeId, checkpoint] of collected)
3086
3148
  collected.set(nodeId, { ...checkpoint, state: freshAllowance(checkpoint.state) });
3087
3149
  }
3150
+ if (internal?.compact === true) {
3151
+ for (const [nodeId, checkpoint] of collected)
3152
+ collected.set(nodeId, { ...checkpoint, state: requestCompaction(checkpoint.state) });
3153
+ }
3088
3154
  const warnings = [];
3089
3155
  if (journalGaps.length > 0) {
3090
3156
  warnings.push('Part of this task\'s journal could not be saved while it ran (the disk may have been full), so this resume may repeat a step that had already finished.');
@@ -3175,14 +3241,19 @@ export class AppServer {
3175
3241
  seededIdentities.add(`${activation.generation ?? 0}:${activation.nodeId}`);
3176
3242
  seededGenerations.add(activation.nodeId);
3177
3243
  }
3178
- const toolBoundary = (checkpoint) => {
3179
- const toolEvent = progress.lastEffectfulToolEvent?.[checkpoint.nodeId];
3180
- return toolEvent !== undefined && Date.parse(checkpoint.savedAt) < Date.parse(toolEvent);
3181
- };
3244
+ const toolBoundary = (checkpoint) => toolBoundaryOpen(checkpoint, progress);
3182
3245
  const reenterable = [...collected.values()].filter(checkpoint => graph.nodes[checkpoint.nodeId] !== undefined
3183
3246
  && !(Object.hasOwn(progress.nodeResults, checkpoint.nodeId) && !interruptedFrontier.has(checkpoint.nodeId))
3184
3247
  && (checkpoint.generation === undefined || seededIdentities.has(`${checkpoint.generation}:${checkpoint.nodeId}`) || !seededGenerations.has(checkpoint.nodeId))
3185
3248
  && continuableByThisRun(checkpoint.nodeId, checkpoint));
3249
+ if (reenterable.some(toolBoundary)) {
3250
+ const journalLines = chain.flatMap(attempt => (lineageJournals.get(attempt) ?? '').split('\n').filter(Boolean));
3251
+ for (const checkpoint of reenterable.filter(toolBoundary)) {
3252
+ const covered = coverUnsavedToolCalls(checkpoint, journalLines);
3253
+ if (covered !== undefined)
3254
+ Object.assign(checkpoint, covered);
3255
+ }
3256
+ }
3186
3257
  if (reenterable.some(toolBoundary)) {
3187
3258
  throw new AppServerError('nothing-to-continue', 'That attempt ran a tool call after the conversation its checkpoint saved, so a resume could repeat effects the checkpoint does not cover. Check what the call changed, then send this as a new task.');
3188
3259
  }
@@ -3599,6 +3670,7 @@ export class AppServer {
3599
3670
  status, reason,
3600
3671
  ...(result?.providerRequestFailed || healthProviderFailed ? { providerRequestFailed: true } : {}),
3601
3672
  ...(result?.providerOverflow ? { providerOverflow: true } : {}),
3673
+ ...(result?.failureCode === undefined ? {} : { errorCode: result.failureCode }),
3602
3674
  ...(result?.telemetry !== undefined || probeModels.size > 0 ? { telemetry: finishedTelemetry } : {}),
3603
3675
  ...(result?.toolCalls === undefined ? {} : { toolCalls: result.toolCalls }),
3604
3676
  })));
@@ -4705,22 +4777,28 @@ export class AppServer {
4705
4777
  return { directory: access.directory, subject };
4706
4778
  }
4707
4779
  async currentAccountIsConfirmed(subject) {
4708
- const membership = await getMembership(undefined, this.directory).catch(() => ({ paid: false }));
4780
+ const membership = await getGraphMembership(undefined, this.directory).catch(() => ({ paid: false }));
4709
4781
  return membership.subject === subject;
4710
4782
  }
4711
4783
  async listGraphs(params) {
4712
4784
  void params;
4713
4785
  const { directory, subject } = await this.graphDirectory(true);
4714
- const [saved, status, membership] = await Promise.all([listGraphs(directory), getAuthStatus().catch(() => ({ signedIn: false, subject: undefined })), getMembership(undefined, directory).catch(() => ({ paid: false }))]);
4786
+ const [saved, status, membership] = await Promise.all([listGraphs(directory), getAuthStatus().catch(() => ({ signedIn: false, subject: undefined })), // The plan check and its stored pass belong to the application home, not to the account's graph folder.
4787
+ getGraphMembership(undefined, this.directory).catch(() => ({ paid: false }))]);
4715
4788
  const graphs = [{ id: 'default', name: SOFTWARE_ENGINEER_HARNESS.name, revision: SOFTWARE_ENGINEER_HARNESS.revision, preset: true }];
4716
4789
  const free = membership.paid !== true;
4717
4790
  const confirmed = free && subject !== undefined && membership.subject === subject && !membership.unavailable;
4718
- const kept = confirmed ? (await readGraphQuota(directory, saved)).freeGraphId : undefined;
4791
+ if (!free && subject !== undefined && membership.subject === subject)
4792
+ await notePremiumGraphAccount(directory).catch(() => { });
4793
+ const kept = confirmed ? (await readGraphQuota(directory, saved, { adopt: true })).freeGraphId : undefined;
4719
4794
  for (const graph of withoutDeletedGraphs(saved)) {
4720
- if (graph.id === 'default' || (free && (graph.id !== kept || freeTierGraphViolation(graph) !== undefined)))
4795
+ // Without a confirmed account this folder's graphs belong to whoever signed out: list none of them.
4796
+ if (graph.id === 'default' || (free && !confirmed))
4721
4797
  continue;
4798
+ // A confirmed free account sees every saved graph; all but its own are view only and cannot start a task.
4799
+ const locked = free && (graph.id !== kept || freeTierGraphViolation(graph) !== undefined);
4722
4800
  const info = await stat(join(directory, 'graphs', graph.id, 'latest.json')).catch(() => undefined);
4723
- graphs.push({ id: graph.id, name: graph.name, revision: graph.revision, preset: false, ...(info ? { updatedAt: info.mtime.toISOString() } : {}) });
4801
+ graphs.push({ id: graph.id, name: graph.name, revision: graph.revision, preset: false, ...(locked ? { locked: true } : {}), ...(info ? { updatedAt: info.mtime.toISOString() } : {}) });
4724
4802
  }
4725
4803
  const config = await loadConfig(this.directory);
4726
4804
  const configured = configuredGraphSelection(config, subject);
@@ -5658,8 +5736,7 @@ export class AppServer {
5658
5736
  return undefined;
5659
5737
  if (this.autoFixWakes.has(pending.wakeId))
5660
5738
  this.cancelAutoFixWake(sessionId, pending.wakeId);
5661
- const { pendingFix: _pending, ...rest } = current;
5662
- const next = { ...rest, handledThrough: pending.through, updatedAt: new Date().toISOString() };
5739
+ const next = { ...handedOver(current, pending), updatedAt: new Date().toISOString() };
5663
5740
  await writePullRequest(this.directory, sessionId, next);
5664
5741
  return next;
5665
5742
  });
@@ -5741,8 +5818,800 @@ export class AppServer {
5741
5818
  this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
5742
5819
  await removePullRequest(this.directory, sessionId);
5743
5820
  });
5821
+ this.pullRequestReader.forget(sessionId);
5744
5822
  this.emitPullRequest(sessionId, null);
5745
5823
  }
5824
+ /**
5825
+ * The PR tab's read of a task's pull request: branches, author, mergeability, description, commits,
5826
+ * checks and reviews, through the account that can read it. Answers come from a short cache (see
5827
+ * PullRequestReader); a failed read keeps the last good answer and says why it is not current.
5828
+ */
5829
+ async pullRequestDetails(sessionId, refresh) {
5830
+ const pullRequest = await readPullRequest(this.directory, sessionId);
5831
+ if (!pullRequest)
5832
+ throw new AppServerError('not-found', 'This session has no pull request.');
5833
+ return this.pullRequestReader.readDetails(sessionId, pullRequest, { refresh });
5834
+ }
5835
+ async pullRequestFiles(sessionId, refresh, headSha) {
5836
+ const pullRequest = await readPullRequest(this.directory, sessionId);
5837
+ if (!pullRequest)
5838
+ throw new AppServerError('not-found', 'This session has no pull request.');
5839
+ return this.pullRequestReader.readFiles(sessionId, pullRequest, { refresh, ...(headSha === undefined ? {} : { headSha }) });
5840
+ }
5841
+ async storedPullRequest(sessionId) {
5842
+ const pullRequest = await readPullRequest(this.directory, sessionId);
5843
+ if (!pullRequest)
5844
+ throw new AppServerError('not-found', 'This session has no pull request.');
5845
+ return pullRequest;
5846
+ }
5847
+ /**
5848
+ * The task's pull request for a write. `url`, when the tab sends it, is the PR the person looked at;
5849
+ * a write for a PR the task no longer has is refused rather than applied to its new one.
5850
+ */
5851
+ async pullRequestToWrite(sessionId, url, required = false) {
5852
+ if (required && typeof url !== 'string')
5853
+ throw new AppServerError('invalid-params', 'url must name the pull request the person looked at');
5854
+ const pullRequest = await this.storedPullRequest(sessionId);
5855
+ if (url !== undefined && url !== pullRequest.url) {
5856
+ return { refused: { ok: false, error: { kind: 'refused', message: 'This task’s pull request changed since you read it. Look again before writing.' } } };
5857
+ }
5858
+ return pullRequest;
5859
+ }
5860
+ /** The PR tab's review state: unresolved and resolved threads, which files the person viewed, and who is asked to review. */
5861
+ async pullRequestReview(sessionId, refresh) {
5862
+ return this.pullRequestReader.readReview(sessionId, await this.storedPullRequest(sessionId), { refresh });
5863
+ }
5864
+ /** A write's answer, with the review state read again at once so the tab shows what GitHub now holds. */
5865
+ async afterReviewWrite(sessionId, pullRequest, answer) {
5866
+ if (!answer.ok)
5867
+ return { ok: false, error: answer.error };
5868
+ return { ok: true, ...answer.value, ...await this.pullRequestReader.readReview(sessionId, pullRequest, { force: true }) };
5869
+ }
5870
+ /** Posts a review (comment, approve or request changes) with its line comments, as the account the person confirmed. */
5871
+ async submitPullRequestReview(params) {
5872
+ const sessionId = identifier(params.id, 'id');
5873
+ const input = writeParams(() => {
5874
+ const as = githubLogin(params.as, 'as');
5875
+ const event = reviewEvent(params.event);
5876
+ const body = commentBody(params.body, 'body', false);
5877
+ const comments = draftComments(params.comments);
5878
+ const headSha = typeof params.headSha === 'string' && /^[0-9a-f]{40}$/i.test(params.headSha) ? params.headSha : undefined;
5879
+ return { as, event, body, comments, headSha };
5880
+ });
5881
+ const target = await this.pullRequestToWrite(sessionId, params.url);
5882
+ if ('refused' in target)
5883
+ return target.refused;
5884
+ const pullRequest = target;
5885
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
5886
+ if (state.viewerIsAuthor && input.event !== 'comment')
5887
+ throw new PullRequestRefusal('You opened this pull request, so GitHub lets you comment on it but not approve it or request changes.');
5888
+ // A review left pending on github.com may carry the line comments on its own.
5889
+ if (input.event !== 'approve' && input.body === undefined && input.comments.length === 0 && (state.pendingReview?.comments ?? 0) === 0) {
5890
+ throw new PullRequestRefusal(input.event === 'comment' ? 'A comment needs text or a line comment.' : 'Requesting changes needs text or a line comment.');
5891
+ }
5892
+ return submitReview(gh, state, { event: input.event, comments: input.comments, ...(input.body === undefined ? {} : { body: input.body }), ...(input.headSha === undefined ? {} : { commitOid: input.headSha }) });
5893
+ }, { details: true });
5894
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
5895
+ }
5896
+ /** Replies to a review thread, or resolves or reopens it. */
5897
+ async pullRequestThread(params) {
5898
+ const sessionId = identifier(params.id, 'id');
5899
+ const input = writeParams(() => {
5900
+ const action = params.action;
5901
+ if (action !== 'reply' && action !== 'resolve' && action !== 'unresolve')
5902
+ throw new Error('action must be reply, resolve or unresolve');
5903
+ return { as: githubLogin(params.as, 'as'), threadId: nodeId(params.threadId, 'threadId'), action, body: action === 'reply' ? commentBody(params.body, 'body', true) : undefined };
5904
+ });
5905
+ const target = await this.pullRequestToWrite(sessionId, params.url);
5906
+ if ('refused' in target)
5907
+ return target.refused;
5908
+ const pullRequest = target;
5909
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
5910
+ const thread = state.threads.find(entry => entry.id === input.threadId);
5911
+ if (thread === undefined)
5912
+ throw new PullRequestRefusal('That conversation is no longer on this pull request.');
5913
+ if (input.action === 'reply')
5914
+ await replyToThread(gh, thread.id, input.body);
5915
+ else
5916
+ await setThreadResolved(gh, thread.id, input.action === 'resolve');
5917
+ return {};
5918
+ });
5919
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
5920
+ }
5921
+ /** Marks a file viewed or not viewed for the person, as on github.com. Nobody is notified, so the state is not read again. */
5922
+ async markPullRequestFileViewed(params) {
5923
+ const sessionId = identifier(params.id, 'id');
5924
+ const input = writeParams(() => {
5925
+ if (typeof params.viewed !== 'boolean')
5926
+ throw new Error('viewed must be true or false');
5927
+ return { as: githubLogin(params.as, 'as'), path: reviewPath(params.path), viewed: params.viewed };
5928
+ });
5929
+ const target = await this.pullRequestToWrite(sessionId, params.url);
5930
+ if ('refused' in target)
5931
+ return target.refused;
5932
+ const pullRequest = target;
5933
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
5934
+ await setFileViewed(gh, state.pullRequestId, input.path, input.viewed);
5935
+ if (input.viewed)
5936
+ state.viewed[input.path] = 'viewed';
5937
+ else
5938
+ delete state.viewed[input.path];
5939
+ return {};
5940
+ });
5941
+ return answer.ok ? { ok: true } : { ok: false, error: answer.error };
5942
+ }
5943
+ /** Re-runs the failed jobs of GitHub Actions runs behind this PR's failed checks, as read last. */
5944
+ async rerunPullRequestChecks(params) {
5945
+ const sessionId = identifier(params.id, 'id');
5946
+ const input = writeParams(() => ({ as: githubLogin(params.as, 'as'), runIds: runIds(params.runIds) }));
5947
+ const target = await this.pullRequestToWrite(sessionId, params.url);
5948
+ if ('refused' in target)
5949
+ return target.refused;
5950
+ const pullRequest = target;
5951
+ const read = await this.pullRequestReader.readDetails(sessionId, pullRequest);
5952
+ // Without the checks there is nothing to check the runs against; say why rather than "no longer failing".
5953
+ if (read.details === null)
5954
+ return { ok: false, error: read.error ?? { kind: 'failed', message: 'GitHub did not answer.' } };
5955
+ const failed = new Set(failedRunIds(read.details.checks, pullRequest));
5956
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh) => {
5957
+ const stale = input.runIds.filter(runId => !failed.has(runId));
5958
+ if (stale.length > 0)
5959
+ throw new PullRequestRefusal(stale.length === input.runIds.length ? 'Those checks are no longer failing on this pull request.' : 'Some of those checks are no longer failing on this pull request.');
5960
+ for (const runId of input.runIds)
5961
+ await rerunFailedJobs(gh, pullRequest, runId);
5962
+ return { reran: input.runIds.length };
5963
+ }, { details: true });
5964
+ return answer.ok ? { ok: true, ...answer.value } : { ok: false, error: answer.error };
5965
+ }
5966
+ /** Asks people to review the PR, or withdraws requests. */
5967
+ async requestPullRequestReviewers(params) {
5968
+ const sessionId = identifier(params.id, 'id');
5969
+ const input = writeParams(() => {
5970
+ const add = reviewerLogins(params.add, 'add');
5971
+ const addTeams = teamSlugs(params.addTeams, 'addTeams');
5972
+ const remove = reviewerEntries(params.remove, 'remove');
5973
+ if (add.length + addTeams.length + remove.length === 0)
5974
+ throw new Error('Name someone to add or remove.');
5975
+ return { as: githubLogin(params.as, 'as'), add, addTeams, remove };
5976
+ });
5977
+ const target = await this.pullRequestToWrite(sessionId, params.url);
5978
+ if ('refused' in target)
5979
+ return target.refused;
5980
+ const pullRequest = target;
5981
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh) => {
5982
+ await changeReviewers(gh, pullRequest, { add: input.add, addTeams: input.addTeams, remove: input.remove });
5983
+ return {};
5984
+ }, { details: true });
5985
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
5986
+ }
5987
+ /** Puts what a merge-side write changed on the stored record at once, so the sidebar and the tab show it; the watcher then confirms it. */
5988
+ async recordPullRequestChange(sessionId, url, change) {
5989
+ const written = await withPullRequest(this.directory, sessionId, async () => {
5990
+ const current = await readPullRequest(this.directory, sessionId);
5991
+ if (current?.url !== url)
5992
+ return undefined;
5993
+ const next = settleFinishedPullRequest({ ...current, ...change, updatedAt: new Date().toISOString() });
5994
+ if (next.pendingFix === undefined && current.pendingFix !== undefined)
5995
+ this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
5996
+ await writePullRequest(this.directory, sessionId, next);
5997
+ return next;
5998
+ }).catch(error => { this.log('warn', `Could not record the change to ${url}: ${message(error)}`); return undefined; });
5999
+ if (written) {
6000
+ this.emitPullRequest(sessionId, written);
6001
+ if (pullRequestNeedsWatch(written))
6002
+ void this.pullRequestWatcher.poll();
6003
+ }
6004
+ }
6005
+ /** A merge-side write's answer, with the merge state read again so the tab shows what GitHub now holds. */
6006
+ async afterMergeWrite(sessionId, pullRequest, answer) {
6007
+ if (!answer.ok)
6008
+ return { ok: false, error: answer.error };
6009
+ const read = await this.pullRequestReader.readMerge(sessionId, pullRequest, { force: true });
6010
+ const stored = await readPullRequest(this.directory, sessionId);
6011
+ return { ok: true, ...answer.value, ...read, ...(stored?.url === pullRequest.url ? { pullRequest: pullRequestForClients(stored) } : {}) };
6012
+ }
6013
+ /**
6014
+ * Merges the task's PR now, or sets it to merge when ready (GitHub's auto-merge), with the method and
6015
+ * commit message the person chose, at the head commit they read. Deleting the head branch afterwards
6016
+ * is said separately: the merge has happened even when that fails.
6017
+ */
6018
+ async mergeSessionPullRequest(params) {
6019
+ const sessionId = identifier(params.id, 'id');
6020
+ const input = writeParams(() => {
6021
+ const when = params.when ?? 'now';
6022
+ if (when !== 'now' && when !== 'ready' && when !== 'queue')
6023
+ throw new Error('when must be now, ready or queue');
6024
+ if (params.deleteBranch !== undefined && typeof params.deleteBranch !== 'boolean')
6025
+ throw new Error('deleteBranch must be true or false');
6026
+ if (params.bypass !== undefined && typeof params.bypass !== 'boolean')
6027
+ throw new Error('bypass must be true or false');
6028
+ const bypass = params.bypass === true;
6029
+ if (bypass && when !== 'now')
6030
+ throw new Error('bypass merges now; it cannot wait or queue');
6031
+ return { as: githubLogin(params.as, 'as'), method: when === 'queue' ? 'merge' : mergeMethod(params.method), headSha: headCommit(params.headSha), title: commitTitle(params.title), body: commitBody(params.body), deleteBranch: params.deleteBranch === true, when, bypass };
6032
+ });
6033
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6034
+ if ('refused' in target)
6035
+ return target.refused;
6036
+ const pullRequest = target;
6037
+ const answer = await this.pullRequestReader.writeMerge(sessionId, pullRequest, input.as, async (gh, state) => {
6038
+ if (state.state === 'merged' || state.state === 'closed')
6039
+ throw new PullRequestRefusal(`This pull request is already ${state.state}.`);
6040
+ if (state.state === 'draft')
6041
+ throw new PullRequestRefusal('This pull request is a draft. Mark it ready for review before merging.');
6042
+ if (state.headSha !== input.headSha)
6043
+ throw new PullRequestRefusal(NEW_COMMITS);
6044
+ if (input.when === 'queue') {
6045
+ if (!state.mergeQueue)
6046
+ throw new PullRequestRefusal(`${state.baseRefName} has no merge queue. Merge the pull request instead.`);
6047
+ if (state.queued !== undefined)
6048
+ throw new PullRequestRefusal(`This pull request is already in ${state.baseRefName}’s merge queue.`);
6049
+ if (state.mergeable === 'conflicting' || state.mergeState === 'dirty')
6050
+ throw new PullRequestRefusal(`This pull request has conflicts with ${state.baseRefName}.`);
6051
+ return { queued: true, ...await enqueue(gh, state.pullRequestId, input.headSha) };
6052
+ }
6053
+ if (!state.methods.includes(input.method))
6054
+ throw new PullRequestRefusal(`${MERGE_METHOD_WORD[input.method]} is not allowed on this repository.`);
6055
+ if (input.bypass && !state.canBypass)
6056
+ throw new PullRequestRefusal(`${state.viewer} cannot merge without waiting for ${state.baseRefName}’s requirements.`);
6057
+ if (state.mergeQueue && !input.bypass)
6058
+ throw new PullRequestRefusal(`${state.baseRefName} merges through a merge queue. Add this pull request to the queue instead.`);
6059
+ // GitHub lets an admin merge past what holds a pull request back; the tab does so only when the person
6060
+ // ticked the bypass, and never past conflicts.
6061
+ if (input.when === 'now') {
6062
+ if (state.mergeable === 'conflicting' || state.mergeState === 'dirty')
6063
+ throw new PullRequestRefusal(`This pull request has conflicts with ${state.baseRefName}.`);
6064
+ if (state.mergeState === 'unknown' || state.mergeable === 'unknown')
6065
+ throw new PullRequestRefusal('GitHub is still working out whether this pull request can merge. Try again in a moment.');
6066
+ const allowed = input.bypass ? ['clean', 'unstable', 'has-hooks', 'blocked', 'behind'] : ['clean', 'unstable', 'has-hooks'];
6067
+ if (!allowed.includes(state.mergeState))
6068
+ throw new PullRequestRefusal(`GitHub holds this pull request back (${state.mergeState}). Read what holds it in the panel.`);
6069
+ }
6070
+ const commit = { method: input.method, headSha: input.headSha, ...(input.title === undefined ? {} : { title: input.title }), ...(input.body === undefined ? {} : { body: input.body }) };
6071
+ if (input.when === 'ready') {
6072
+ if (!state.autoMergeAllowed)
6073
+ throw new PullRequestRefusal('This repository does not allow auto-merge, so the pull request cannot merge itself when ready.');
6074
+ await enableAutoMerge(gh, state.pullRequestId, commit);
6075
+ return { autoMerge: true };
6076
+ }
6077
+ const merged = await mergePullRequest(gh, state.pullRequestId, commit);
6078
+ if (!input.deleteBranch || state.deletesBranch)
6079
+ return { merged: true, ...merged };
6080
+ if (state.headRefId === undefined || !state.canDeleteBranch)
6081
+ return { merged: true, ...merged, branchError: `You can’t delete ${state.headRefName}.` };
6082
+ try {
6083
+ await deleteBranch(gh, state.headRefId);
6084
+ return { merged: true, ...merged, branchDeleted: true };
6085
+ }
6086
+ catch (error) {
6087
+ return { merged: true, ...merged, branchError: classifyWriteError(error).message };
6088
+ }
6089
+ });
6090
+ if (answer.ok && answer.value.queued !== true)
6091
+ await this.recordPullRequestChange(sessionId, pullRequest.url, answer.value.merged === true ? { state: 'merged', mergeWhenReady: false } : { mergeWhenReady: true });
6092
+ return this.afterMergeWrite(sessionId, pullRequest, answer);
6093
+ }
6094
+ /** Brings the PR's branch up to date with its base on GitHub (GitHub's "Update branch"), by a merge commit or a rebase. */
6095
+ async updateSessionPullRequestBranch(params) {
6096
+ const sessionId = identifier(params.id, 'id');
6097
+ const input = writeParams(() => ({ as: githubLogin(params.as, 'as'), method: updateMethod(params.method), headSha: headCommit(params.headSha) }));
6098
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6099
+ if ('refused' in target)
6100
+ return target.refused;
6101
+ const pullRequest = target;
6102
+ const answer = await this.pullRequestReader.writeMerge(sessionId, pullRequest, input.as, async (gh, state) => {
6103
+ if (state.state === 'merged' || state.state === 'closed')
6104
+ throw new PullRequestRefusal(`This pull request is already ${state.state}.`);
6105
+ if (state.headSha !== input.headSha)
6106
+ throw new PullRequestRefusal(NEW_COMMITS);
6107
+ if (!state.canUpdateBranch)
6108
+ throw new PullRequestRefusal(`GitHub does not offer to update ${state.headRefName}: it is up to date with ${state.baseRefName}, or ${state.viewer} cannot push to it.`);
6109
+ // GitHub answers with the head before the update lands; the tab reads it again shortly instead.
6110
+ await updateBranch(gh, state.pullRequestId, { method: input.method, headSha: input.headSha });
6111
+ return { updated: true };
6112
+ });
6113
+ return this.afterMergeWrite(sessionId, pullRequest, answer);
6114
+ }
6115
+ /** Marks a draft ready for review (GitHub then asks its reviewers), or converts the PR back to a draft. */
6116
+ async readySessionPullRequest(params) {
6117
+ const sessionId = identifier(params.id, 'id');
6118
+ const input = writeParams(() => {
6119
+ if (typeof params.ready !== 'boolean')
6120
+ throw new Error('ready must be true or false');
6121
+ return { as: githubLogin(params.as, 'as'), ready: params.ready };
6122
+ });
6123
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6124
+ if ('refused' in target)
6125
+ return target.refused;
6126
+ const pullRequest = target;
6127
+ const answer = await this.pullRequestReader.writeMerge(sessionId, pullRequest, input.as, async (gh, state) => {
6128
+ if (state.state === 'merged' || state.state === 'closed')
6129
+ throw new PullRequestRefusal(`This pull request is already ${state.state}.`);
6130
+ if ((state.state === 'draft') !== input.ready)
6131
+ return {};
6132
+ await setReadyForReview(gh, state.pullRequestId, input.ready);
6133
+ return {};
6134
+ });
6135
+ if (answer.ok)
6136
+ await this.recordPullRequestChange(sessionId, pullRequest.url, { state: input.ready ? 'open' : 'draft' });
6137
+ return this.afterMergeWrite(sessionId, pullRequest, answer);
6138
+ }
6139
+ /**
6140
+ * What Create Pull Request would open from the task's folder: its branch, commits and repository, the
6141
+ * account that can push, and a drafted title and body; or why there is nothing to open (`blocked`).
6142
+ */
6143
+ async sessionPullRequestDraft(params) {
6144
+ const sessionId = identifier(params.id, 'id');
6145
+ const base = params.base === undefined ? undefined : writeParams(() => branchName(params.base, 'base'));
6146
+ const record = await this.readSession(sessionId);
6147
+ if (await readPullRequest(this.directory, sessionId))
6148
+ return { draft: null, blocked: { kind: 'has-pull-request', message: 'This task already has a pull request.' } };
6149
+ try {
6150
+ const prompt = record.history[0]?.task;
6151
+ return { draft: await readCreateDraft(this.gh, this.git(record.workspace), record.workspace, { taskName: record.name, ...(base === undefined ? {} : { base }), closesIssue: (owner, repo) => issueNamedIn(prompt, owner, repo) }) };
6152
+ }
6153
+ catch (error) {
6154
+ if (error instanceof PullRequestCreateBlocked)
6155
+ return { draft: null, blocked: error.block };
6156
+ return { draft: null, error: classifyGhError(error) };
6157
+ }
6158
+ }
6159
+ /**
6160
+ * Opens a pull request from the task's folder as the account the person confirmed, pushing the branch
6161
+ * first when GitHub lacks it, and attaches it to the task (or attaches the one already open for the
6162
+ * branch, with `attach`). The watcher then follows it like any other.
6163
+ */
6164
+ async createSessionPullRequest(params) {
6165
+ const sessionId = identifier(params.id, 'id');
6166
+ const input = writeParams(() => {
6167
+ if (params.draft !== undefined && typeof params.draft !== 'boolean')
6168
+ throw new Error('draft must be true or false');
6169
+ if (params.attach !== undefined && typeof params.attach !== 'boolean')
6170
+ throw new Error('attach must be true or false');
6171
+ const attach = params.attach === true;
6172
+ return {
6173
+ as: githubLogin(params.as, 'as'), owner: githubLogin(params.owner, 'owner'), repo: repositoryName(params.repo, 'repo'),
6174
+ head: branchName(params.head, 'head'), base: branchName(params.base, 'base'), headSha: headCommit(params.headSha),
6175
+ title: attach ? '' : pullRequestTitle(params.title), ...(commitBody(params.body) === undefined ? {} : { body: commitBody(params.body) }),
6176
+ draft: params.draft === true, attach,
6177
+ ...(params.into === undefined || params.into === null ? {} : { into: { owner: githubLogin(params.into.owner, 'into.owner'), repo: repositoryName(params.into.repo, 'into.repo') } }),
6178
+ };
6179
+ });
6180
+ const record = await this.readSession(sessionId);
6181
+ if (await readPullRequest(this.directory, sessionId))
6182
+ return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
6183
+ let opened;
6184
+ try {
6185
+ opened = await runAsAccount(this.gh, input.as, gh => createFromFolder(gh, this.git(record.workspace), input));
6186
+ }
6187
+ catch (error) {
6188
+ const failure = classifyWriteError(error);
6189
+ const pushed = error.pushedBranch;
6190
+ return { ok: false, error: typeof pushed === 'string' ? { ...failure, message: `${failure.message.replace(/\.?$/, '.')} ${pushed} was pushed to GitHub; no pull request was opened.` } : failure };
6191
+ }
6192
+ const ref = parsePullRequestUrl(opened.url);
6193
+ if (!ref)
6194
+ return { ok: false, error: { kind: 'failed', message: `GitHub answered with ${opened.url}, which is not a pull request link.` } };
6195
+ // A pull request the task picked up meanwhile (its agent opened one) is kept, not replaced.
6196
+ const meanwhile = await readPullRequest(this.directory, sessionId);
6197
+ if (meanwhile !== undefined && meanwhile.url !== ref.url)
6198
+ return { ok: true, url: opened.url, pushed: opened.pushed, pullRequest: pullRequestForClients(meanwhile) };
6199
+ const attached = await this.attachPullRequest(sessionId, ref);
6200
+ return { ok: true, url: opened.url, pushed: opened.pushed, ...(opened.attached ? { attached: true } : {}), pullRequest: pullRequestForClients(attached) };
6201
+ }
6202
+ /** Where a comment the tab may change sits in the review read: a timeline comment, a review's text, or a comment in a thread. */
6203
+ static commentIn(state, commentId) {
6204
+ const issue = state.comments?.find(entry => entry.id === commentId);
6205
+ if (issue)
6206
+ return { kind: 'issue', canEdit: issue.canEdit, canDelete: issue.canDelete };
6207
+ const review = state.reviewBodies?.find(entry => entry.id === commentId);
6208
+ if (review)
6209
+ return { kind: 'review', canEdit: review.canEdit, canDelete: false };
6210
+ for (const thread of state.threads) {
6211
+ const comment = thread.comments.find(entry => entry.id === commentId);
6212
+ if (comment)
6213
+ return { kind: 'thread', canEdit: comment.canEdit === true, canDelete: comment.canDelete === true };
6214
+ }
6215
+ return undefined;
6216
+ }
6217
+ /** Posts a comment on the PR's conversation, or edits or deletes one of the person's comments. */
6218
+ async pullRequestComment(params) {
6219
+ const sessionId = identifier(params.id, 'id');
6220
+ const input = writeParams(() => {
6221
+ const action = params.action;
6222
+ if (action !== 'add' && action !== 'edit' && action !== 'delete')
6223
+ throw new Error('action must be add, edit or delete');
6224
+ return {
6225
+ as: githubLogin(params.as, 'as'), action,
6226
+ ...(action === 'add' ? {} : { commentId: nodeId(params.commentId, 'commentId') }),
6227
+ ...(action === 'delete' ? {} : { body: commentBody(params.body, 'body', true) }),
6228
+ };
6229
+ });
6230
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6231
+ if ('refused' in target)
6232
+ return target.refused;
6233
+ const pullRequest = target;
6234
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
6235
+ if (input.action === 'add')
6236
+ return { comment: await addComment(gh, state.pullRequestId, input.body) };
6237
+ const found = AppServer.commentIn(state, input.commentId);
6238
+ if (found === undefined)
6239
+ throw new PullRequestRefusal('That comment is no longer on this pull request.');
6240
+ if (input.action === 'edit') {
6241
+ if (!found.canEdit)
6242
+ throw new PullRequestRefusal(`${state.viewer} cannot edit that comment.`);
6243
+ await editComment(gh, found.kind, input.commentId, input.body);
6244
+ return {};
6245
+ }
6246
+ if (!found.canDelete || found.kind === 'review')
6247
+ throw new PullRequestRefusal(found.kind === 'review' ? 'GitHub does not delete a submitted review; edit its text instead.' : `${state.viewer} cannot delete that comment.`);
6248
+ await deleteComment(gh, found.kind, input.commentId);
6249
+ return {};
6250
+ }, { details: true });
6251
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
6252
+ }
6253
+ /** Adds or takes back one of GitHub's reactions on the PR, a comment or a review. Nobody is notified, so it acts at once. */
6254
+ async pullRequestReact(params) {
6255
+ const sessionId = identifier(params.id, 'id');
6256
+ const input = writeParams(() => {
6257
+ if (typeof params.add !== 'boolean')
6258
+ throw new Error('add must be true or false');
6259
+ return { as: githubLogin(params.as, 'as'), subjectId: nodeId(params.subjectId, 'subjectId'), content: reactionContent(params.content), add: params.add };
6260
+ });
6261
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6262
+ if ('refused' in target)
6263
+ return target.refused;
6264
+ const pullRequest = target;
6265
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
6266
+ const known = input.subjectId === state.pullRequestId
6267
+ || state.comments?.some(entry => entry.id === input.subjectId && entry.canReact)
6268
+ || state.reviewBodies?.some(entry => entry.id === input.subjectId && entry.canReact)
6269
+ || state.threads.some(thread => thread.comments.some(entry => entry.id === input.subjectId && entry.canReact !== false));
6270
+ if (!known)
6271
+ throw new PullRequestRefusal('That comment is no longer on this pull request, or it takes no reactions.');
6272
+ await setReaction(gh, input.subjectId, input.content, input.add);
6273
+ return {};
6274
+ });
6275
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
6276
+ }
6277
+ /**
6278
+ * Commits a reviewer's suggestion to the PR's branch on GitHub, as GitHub's "Commit suggestion" does,
6279
+ * at the head the person read (GitHub refuses when the file changed since). The task's folder is then
6280
+ * brought up to the new commit when it sits on that branch at the old head; otherwise the answer says
6281
+ * it is behind.
6282
+ */
6283
+ async applyPullRequestSuggestion(params) {
6284
+ const sessionId = identifier(params.id, 'id');
6285
+ const input = writeParams(() => ({ as: githubLogin(params.as, 'as'), threadId: nodeId(params.threadId, 'threadId'), commentId: nodeId(params.commentId, 'commentId'), headSha: headCommit(params.headSha) }));
6286
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6287
+ if ('refused' in target)
6288
+ return target.refused;
6289
+ const pullRequest = target;
6290
+ const record = await this.readSession(sessionId).catch(() => undefined);
6291
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state, details) => {
6292
+ const thread = state.threads.find(entry => entry.id === input.threadId);
6293
+ const comment = thread?.comments.find(entry => entry.id === input.commentId);
6294
+ if (thread === undefined || comment === undefined)
6295
+ throw new PullRequestRefusal('That suggestion is no longer on this pull request.');
6296
+ const suggestion = suggestionOf(comment.body);
6297
+ if (suggestion === undefined)
6298
+ throw new PullRequestRefusal('That comment does not hold one suggestion to commit.');
6299
+ if (thread.outdated || thread.line === undefined || thread.side !== 'right' || thread.onFile)
6300
+ throw new PullRequestRefusal('That suggestion is on lines the pull request no longer has. Apply it by hand.');
6301
+ if (isFinishedPullRequest(pullRequest.state) || details?.state === 'merged' || details?.state === 'closed')
6302
+ throw new PullRequestRefusal(`This pull request is ${details?.state === 'closed' || pullRequest.state === 'closed' ? 'closed' : 'merged'}; a suggestion is not committed to its branch from here.`);
6303
+ const meta = state.meta;
6304
+ if (meta === undefined || meta.headRefName === '')
6305
+ throw new PullRequestRefusal('GitHub did not say which branch the pull request is on.');
6306
+ // Never the base repository in its place: a head branch of the same name there is another branch (review P1).
6307
+ if (meta.headRepository === undefined)
6308
+ throw new PullRequestRefusal('GitHub no longer has this pull request’s head repository, so the suggestion cannot be committed to it.');
6309
+ if (meta.headSha.toLowerCase() !== input.headSha)
6310
+ throw new PullRequestRefusal(NEW_COMMITS);
6311
+ const repository = meta.headRepository;
6312
+ const file = await readFileAt(gh, repository, thread.path, input.headSha);
6313
+ if (!file.utf8)
6314
+ throw new PullRequestRefusal(`${thread.path} is not UTF-8 text, so the suggestion is not committed from here. Commit it on GitHub.`);
6315
+ if (!uniformLineEndings(file.text))
6316
+ throw new PullRequestRefusal(`${thread.path} mixes line endings, so the suggestion is not committed from here. Commit it on GitHub.`);
6317
+ const changed = applySuggestionText(file.text, thread.startLine ?? thread.line, thread.line, suggestion);
6318
+ if (changed === undefined)
6319
+ throw new PullRequestRefusal(`${thread.path} no longer has those lines.`);
6320
+ if (changed === file.text)
6321
+ throw new PullRequestRefusal('The suggestion is already in the file.');
6322
+ const trailer = coAuthorTrailer(comment.author, comment.authorId);
6323
+ let committed;
6324
+ try {
6325
+ committed = await commitFile(gh, repository, { path: thread.path, branch: meta.headRefName, sha: file.sha, content: changed, message: `Apply suggestion from @${comment.author}${trailer === undefined ? '' : `\n\n${trailer}`}` });
6326
+ }
6327
+ catch (error) {
6328
+ // GitHub's 409: the file on the branch is no longer the one the suggestion was read against (seen on the sandbox, 2026-11-24).
6329
+ if (/\bHTTP 409\b/.test(error instanceof Error ? error.message : String(error)))
6330
+ throw new PullRequestRefusal(`${thread.path} changed on ${meta.headRefName} since you read it, so the suggestion was not committed. Look again.`);
6331
+ throw error;
6332
+ }
6333
+ const folder = record === undefined || committed.commit === undefined ? undefined
6334
+ : await this.catchUpFolder(record.workspace, { repository, branch: meta.headRefName, from: input.headSha, to: committed.commit }, () => accountToken(gh, input.as));
6335
+ return { ...committed, ...(folder === undefined ? {} : { folder }) };
6336
+ }, { details: true });
6337
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
6338
+ }
6339
+ /**
6340
+ * Brings the task's folder up to a commit made on GitHub from the tab, when the folder sits on that
6341
+ * branch at the commit before it: a fetch as the confirmed account and a fast-forward, never a merge
6342
+ * of anything else. `behind` when it cannot (other commits, or local changes in the way).
6343
+ */
6344
+ async catchUpFolder(folder, change, token) {
6345
+ const git = this.git(folder);
6346
+ const branch = await git(['symbolic-ref', '--quiet', '--short', 'HEAD']);
6347
+ if (branch.code !== 0)
6348
+ return undefined;
6349
+ if (branch.stdout.trim() !== change.branch)
6350
+ return 'other-branch';
6351
+ const head = await git(['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
6352
+ if (head.code !== 0 || head.stdout.trim().toLowerCase() !== change.from)
6353
+ return 'behind';
6354
+ const [owner = '', repo = ''] = change.repository.split('/');
6355
+ try {
6356
+ const fetched = await git(['fetch', '--no-tags', '--quiet', githubHttpsUrl(owner, repo), `refs/heads/${change.branch}`], { timeoutMs: 120_000, env: tokenCredentials(await token()) });
6357
+ if (fetched.code !== 0)
6358
+ return 'behind';
6359
+ const moved = await git(['merge', '--ff-only', '--quiet', change.to]);
6360
+ return moved.code === 0 ? 'updated' : 'behind';
6361
+ }
6362
+ catch {
6363
+ return 'behind';
6364
+ }
6365
+ }
6366
+ /** An excerpt of a failed GitHub Actions job's log, for a check of this PR's head. */
6367
+ async pullRequestCheckLog(params) {
6368
+ const sessionId = identifier(params.id, 'id');
6369
+ const job = writeParams(() => jobId(params.jobId));
6370
+ const pullRequest = await this.storedPullRequest(sessionId);
6371
+ const read = await this.pullRequestReader.readDetails(sessionId, pullRequest);
6372
+ if (read.details === null)
6373
+ return { log: null, error: read.error ?? { kind: 'failed', message: 'GitHub did not answer.' } };
6374
+ // Only a job behind one of this PR's checks is read, never one the tab was merely told about.
6375
+ if (!read.details.checks.some(check => actionsJobOf(check.url, pullRequest)?.jobId === job)) {
6376
+ return { log: null, error: { kind: 'failed', message: 'That job is not one of this pull request’s checks.' } };
6377
+ }
6378
+ return this.pullRequestReader.readCheckLog(sessionId, pullRequest, job);
6379
+ }
6380
+ /**
6381
+ * Hands the PR's failed checks to the task's agent ("Fix with Agent"): a prompt naming them and how to
6382
+ * read their logs, delivered like a self-wake (into the running turn, or as the next one). The checks
6383
+ * come from the engine's own read, never from text the tab sends.
6384
+ */
6385
+ async fixPullRequestChecks(params) {
6386
+ const sessionId = identifier(params.id, 'id');
6387
+ const names = writeParams(() => {
6388
+ if (params.names === undefined || params.names === null)
6389
+ return undefined;
6390
+ if (!Array.isArray(params.names) || params.names.length > 50 || params.names.some(name => typeof name !== 'string'))
6391
+ throw new Error('names must list check names');
6392
+ return new Set(params.names);
6393
+ });
6394
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6395
+ if ('refused' in target)
6396
+ return target.refused;
6397
+ const pullRequest = target;
6398
+ if (isFinishedPullRequest(pullRequest.state))
6399
+ return { ok: false, error: { kind: 'refused', message: `This pull request is ${pullRequest.state}; there is nothing left to fix.` } };
6400
+ const read = await this.pullRequestReader.readDetails(sessionId, pullRequest);
6401
+ if (read.details === null)
6402
+ return { ok: false, error: read.error ?? { kind: 'failed', message: 'GitHub did not answer.' } };
6403
+ const failed = read.details.checks.filter(check => check.state === 'failed' && (names === undefined || names.has(check.name)));
6404
+ if (failed.length === 0)
6405
+ return { ok: false, error: { kind: 'refused', message: 'None of those checks is failing on this pull request now.' } };
6406
+ const prompt = fixChecksPrompt(pullRequest, {
6407
+ checks: failed.map(check => ({ name: check.name, ...(check.workflow === undefined ? {} : { workflow: check.workflow }), ...(check.url === undefined ? {} : { url: check.url }) })),
6408
+ ...(read.details.headSha === undefined ? {} : { headSha: read.details.headSha }), branch: read.details.headRefName, source: 'person',
6409
+ });
6410
+ const waiter = this.reviewWaiters.get(sessionId);
6411
+ if (waiter) {
6412
+ waiter({ kind: 'comments', prompt });
6413
+ return { ok: true, delivered: 'waiting', prompt };
6414
+ }
6415
+ // A second press while the first is still waiting to be delivered does not ask the agent twice.
6416
+ const armed = [...this.fixWakes].find(id => this.timers.get(id)?.owner === sessionId);
6417
+ if (armed !== undefined)
6418
+ return { ok: true, delivered: 'queued', wakeId: armed, prompt: this.timers.get(armed).prompt, already: true };
6419
+ const timer = this.timers.arm(1, prompt, sessionId, pullRequest.carry, undefined);
6420
+ this.fixWakes.add(timer.id);
6421
+ this.emitTimers(sessionId);
6422
+ this.armTimerCheck();
6423
+ return { ok: true, delivered: this.run?.sessionId === sessionId ? 'running' : 'queued', wakeId: timer.id, prompt };
6424
+ }
6425
+ /** Changes the PR's title, description, labels or assignees, as the account the person confirmed. */
6426
+ async editSessionPullRequest(params) {
6427
+ const sessionId = identifier(params.id, 'id');
6428
+ const input = writeParams(() => {
6429
+ const change = {
6430
+ as: githubLogin(params.as, 'as'), title: editTitle(params.title), body: editBody(params.body), previousTitle: editBody(params.previousTitle, 'previousTitle'), previousBody: editBody(params.previousBody, 'previousBody'),
6431
+ addLabels: nodeIds(params.addLabels, 'addLabels'), removeLabels: nodeIds(params.removeLabels, 'removeLabels'),
6432
+ addAssignees: nodeIds(params.addAssignees, 'addAssignees'), removeAssignees: nodeIds(params.removeAssignees, 'removeAssignees'),
6433
+ };
6434
+ if (change.title === undefined && change.body === undefined && change.addLabels.length + change.removeLabels.length + change.addAssignees.length + change.removeAssignees.length === 0)
6435
+ throw new Error('Name something to change.');
6436
+ return change;
6437
+ });
6438
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6439
+ if ('refused' in target)
6440
+ return target.refused;
6441
+ const pullRequest = target;
6442
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state) => {
6443
+ const meta = state.meta;
6444
+ if (meta === undefined)
6445
+ throw new PullRequestRefusal('GitHub did not say what this pull request holds. Look again.');
6446
+ if (!meta.canUpdate)
6447
+ throw new PullRequestRefusal(`${state.viewer} cannot change this pull request.`);
6448
+ const labels = new Set([...meta.repositoryLabels, ...meta.labels].map(label => label.id));
6449
+ const people = new Set([...meta.assignable, ...meta.assignees].map(person => person.id));
6450
+ if ([...input.addLabels, ...input.removeLabels].some(id => !labels.has(id)))
6451
+ throw new PullRequestRefusal('One of those labels is no longer on this repository. Look again.');
6452
+ if ([...input.addAssignees, ...input.removeAssignees].some(id => !people.has(id)))
6453
+ throw new PullRequestRefusal('One of those people can no longer be assigned. Look again.');
6454
+ if (input.title !== undefined || input.body !== undefined) {
6455
+ // An edit made on GitHub since the person began is not overwritten.
6456
+ const now = await currentText(gh, state.pullRequestId);
6457
+ if (input.body !== undefined && input.previousBody !== undefined && now.body.replace(/\r\n/g, '\n') !== input.previousBody.replace(/\r\n/g, '\n'))
6458
+ throw new PullRequestRefusal('The description changed on GitHub since you began editing it. Copy your text, look again, and edit it once more.');
6459
+ if (input.title !== undefined && input.previousTitle !== undefined && now.title !== input.previousTitle)
6460
+ throw new PullRequestRefusal('The title changed on GitHub since you began editing it. Look again.');
6461
+ await updateText(gh, state.pullRequestId, { ...(input.title === undefined ? {} : { title: input.title }), ...(input.body === undefined ? {} : { body: input.body }) });
6462
+ }
6463
+ await changeLabels(gh, state.pullRequestId, { add: input.addLabels, remove: input.removeLabels });
6464
+ await changeAssignees(gh, state.pullRequestId, { add: input.addAssignees, remove: input.removeAssignees });
6465
+ return {};
6466
+ }, { details: true });
6467
+ if (answer.ok && input.title !== undefined)
6468
+ await this.recordPullRequestChange(sessionId, pullRequest.url, { title: input.title });
6469
+ return this.afterReviewWrite(sessionId, pullRequest, answer);
6470
+ }
6471
+ /** Closes the PR (with a comment first, when the person wrote one) or reopens it. Its branch stays. */
6472
+ async setSessionPullRequestState(params) {
6473
+ const sessionId = identifier(params.id, 'id');
6474
+ const input = writeParams(() => {
6475
+ if (params.state !== 'open' && params.state !== 'closed')
6476
+ throw new Error('state must be open or closed');
6477
+ return { as: githubLogin(params.as, 'as'), open: params.state === 'open', body: commentBody(params.body, 'body', false) };
6478
+ });
6479
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6480
+ if ('refused' in target)
6481
+ return target.refused;
6482
+ const pullRequest = target;
6483
+ const answer = await this.pullRequestReader.write(sessionId, pullRequest, input.as, async (gh, state, details) => {
6484
+ if (details?.state === 'merged' || pullRequest.state === 'merged')
6485
+ throw new PullRequestRefusal('This pull request is merged; it cannot be closed or reopened.');
6486
+ const meta = state.meta;
6487
+ if (input.open ? meta?.canReopen === false : meta?.canClose === false)
6488
+ throw new PullRequestRefusal(`${state.viewer} cannot ${input.open ? 'reopen' : 'close'} this pull request.`);
6489
+ if (input.body !== undefined)
6490
+ await addComment(gh, state.pullRequestId, input.body);
6491
+ try {
6492
+ await setOpen(gh, state.pullRequestId, input.open);
6493
+ }
6494
+ catch (error) {
6495
+ // The comment stands; the tab must not post it again on a retry (review P3).
6496
+ if (input.body !== undefined)
6497
+ throw Object.assign(error instanceof Error ? error : new Error(String(error)), { commentPosted: true });
6498
+ throw error;
6499
+ }
6500
+ return { state: input.open ? 'open' : 'closed' };
6501
+ }, { details: true });
6502
+ if (answer.ok)
6503
+ await this.recordPullRequestChange(sessionId, pullRequest.url, { state: input.open ? (pullRequest.state === 'draft' ? 'draft' : 'open') : 'closed' });
6504
+ const after = await this.afterReviewWrite(sessionId, pullRequest, answer);
6505
+ const stored = await readPullRequest(this.directory, sessionId);
6506
+ return stored?.url === pullRequest.url ? { ...after, pullRequest: pullRequestForClients(stored) } : after;
6507
+ }
6508
+ /** Takes the PR out of its base's merge queue. */
6509
+ async dequeueSessionPullRequest(params) {
6510
+ const sessionId = identifier(params.id, 'id');
6511
+ const input = writeParams(() => ({ as: githubLogin(params.as, 'as') }));
6512
+ const target = await this.pullRequestToWrite(sessionId, params.url, true);
6513
+ if ('refused' in target)
6514
+ return target.refused;
6515
+ const pullRequest = target;
6516
+ const answer = await this.pullRequestReader.writeMerge(sessionId, pullRequest, input.as, async (gh, state) => {
6517
+ if (state.queued === undefined)
6518
+ throw new PullRequestRefusal(`This pull request is not in ${state.baseRefName}’s merge queue.`);
6519
+ await dequeue(gh, state.pullRequestId);
6520
+ return { dequeued: true };
6521
+ });
6522
+ return this.afterMergeWrite(sessionId, pullRequest, answer);
6523
+ }
6524
+ /** Attaches a GitHub pull request to a task (Review Requests' "Review in New Task"); the watcher then follows it. */
6525
+ async attachSessionPullRequest(params) {
6526
+ const sessionId = identifier(params.id, 'id');
6527
+ const ref = typeof params.url === 'string' ? parsePullRequestUrl(params.url) : undefined;
6528
+ if (!ref)
6529
+ throw new AppServerError('invalid-params', 'url must be a GitHub pull request URL, https://github.com/<owner>/<repo>/pull/<number>');
6530
+ await this.readSession(sessionId);
6531
+ const current = await readPullRequest(this.directory, sessionId);
6532
+ if (current !== undefined && current.url !== ref.url)
6533
+ return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
6534
+ return { ok: true, pullRequest: pullRequestForClients(await this.attachPullRequest(sessionId, ref)) };
6535
+ }
6536
+ reviewRequestsRead = { failures: 0 };
6537
+ /**
6538
+ * The open pull requests that ask a signed-in account for its review, each with the task it is attached
6539
+ * to, if one. Read at most once a minute (a refresh: every 5 seconds), backed off on a rate limit.
6540
+ */
6541
+ async pullRequestReviewRequests(refresh) {
6542
+ const held = this.reviewRequestsRead;
6543
+ const now = Date.now();
6544
+ if (held.inflight)
6545
+ await held.inflight;
6546
+ else if ((held.retryAt === undefined || now >= held.retryAt) && (held.attemptedAt === undefined || now - held.attemptedAt >= (refresh ? 5_000 : 60_000))) {
6547
+ held.attemptedAt = now;
6548
+ held.inflight = (async () => {
6549
+ try {
6550
+ held.value = await readReviewRequests(this.gh);
6551
+ held.at = Date.now();
6552
+ held.failures = 0;
6553
+ delete held.error;
6554
+ delete held.retryAt;
6555
+ }
6556
+ catch (error) {
6557
+ const failure = classifyGhError(error);
6558
+ if (failure.kind === 'rate-limited') {
6559
+ held.failures++;
6560
+ held.retryAt = Date.now() + Math.min(15 * 60_000, 60_000 * 2 ** (held.failures - 1));
6561
+ failure.retryAt = new Date(held.retryAt).toISOString();
6562
+ }
6563
+ held.error = failure;
6564
+ }
6565
+ finally {
6566
+ held.inflight = undefined;
6567
+ }
6568
+ })();
6569
+ await held.inflight;
6570
+ }
6571
+ const attached = new Map((await listPullRequests(this.directory).catch(() => [])).map(entry => [entry.pullRequest.url, entry.sessionId]));
6572
+ return {
6573
+ requests: held.value === undefined ? null : held.value.requests.map(request => ({ ...request, ...(attached.has(request.url) ? { sessionId: attached.get(request.url) } : {}) })),
6574
+ accounts: held.value?.accounts ?? [],
6575
+ ...(held.at === undefined ? {} : { fetchedAt: new Date(held.at).toISOString() }),
6576
+ ...(held.error === undefined ? {} : { error: { ...held.error } }),
6577
+ };
6578
+ }
6579
+ /** The open issues of a project folder's GitHub repository (its `origin`), to start a task from one. */
6580
+ async listWorkspaceIssues(params) {
6581
+ const root = await workspaceRoot(params.workspace);
6582
+ const remote = await this.git(root)(['remote', 'get-url', 'origin']);
6583
+ const repository = remote.code === 0 ? githubRepositoryOf(remote.stdout) : undefined;
6584
+ if (repository === undefined)
6585
+ return { issues: null, blocked: { kind: 'no-github-remote', message: 'This folder has no GitHub remote named origin.' } };
6586
+ try {
6587
+ const read = await readRepositoryIssues(this.gh, repository.owner, repository.repo);
6588
+ return { repository, issues: read.issues, enabled: read.enabled, ...(read.viewer === undefined ? {} : { viewer: read.viewer }) };
6589
+ }
6590
+ catch (error) {
6591
+ return { repository, issues: null, error: classifyGhError(error) };
6592
+ }
6593
+ }
6594
+ /**
6595
+ * Keeps the sidebar's checks mark in step with what the tab just read from GitHub (never a cached
6596
+ * answer), and asks the watcher to catch up on a state it has not seen.
6597
+ */
6598
+ async syncPullRequestRecord(sessionId, read, details) {
6599
+ const rollup = checksRollup(details.checks);
6600
+ if (details.state !== read.state && pullRequestNeedsWatch(read))
6601
+ void this.pullRequestWatcher.poll();
6602
+ if (sameChecksRollup(rollup, read.checks))
6603
+ return;
6604
+ const written = await withPullRequest(this.directory, sessionId, async () => {
6605
+ const current = await readPullRequest(this.directory, sessionId);
6606
+ if (current?.url !== read.url || sameChecksRollup(rollup, current.checks))
6607
+ return undefined;
6608
+ const next = { ...withChecks(current, rollup), updatedAt: new Date().toISOString() };
6609
+ await writePullRequest(this.directory, sessionId, next);
6610
+ return next;
6611
+ });
6612
+ if (written)
6613
+ this.emitPullRequest(sessionId, written);
6614
+ }
5746
6615
  cancelAutoFixWake(sessionId, wakeId) {
5747
6616
  this.autoFixWakes.delete(wakeId);
5748
6617
  if (!this.timers.cancel(wakeId))
@@ -5818,6 +6687,7 @@ export class AppServer {
5818
6687
  spendWake(timer, reason) {
5819
6688
  this.timers.settle(timer.id);
5820
6689
  this.autoFixWakes.delete(timer.id);
6690
+ this.fixWakes.delete(timer.id);
5821
6691
  this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
5822
6692
  const sessionId = timer.owner;
5823
6693
  if (sessionId === undefined)
@@ -6021,10 +6891,11 @@ export class AppServer {
6021
6891
  ...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
6022
6892
  ...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
6023
6893
  ...(carry?.input === undefined ? {} : { input: carry.input }),
6024
- ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: autoFix ? 'auto-fix' : 'timer', ...(startNode === undefined ? {} : { startNode }) });
6894
+ ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: autoFix ? 'auto-fix' : this.fixWakes.has(timer.id) ? 'fix-checks' : 'timer', ...(startNode === undefined ? {} : { startNode }) });
6025
6895
  }
6026
6896
  this.timers.settle(timer.id);
6027
6897
  this.autoFixWakes.delete(timer.id);
6898
+ this.fixWakes.delete(timer.id);
6028
6899
  void markAutoFixDelivered(this.directory, sessionId, timer.id)
6029
6900
  .then(pullRequest => { if (pullRequest)
6030
6901
  this.emitPullRequest(sessionId, pullRequest); })