@andorra-labs/code 0.1.16 → 0.1.17

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 (188) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-execution.js +11 -8
  4. package/dist/src/agent-mcp-catalog.js +1 -0
  5. package/dist/src/agent-mcp.d.ts +3 -0
  6. package/dist/src/agent-mcp.js +33 -1
  7. package/dist/src/andorra/entry.d.ts +10 -0
  8. package/dist/src/andorra/entry.js +18 -4
  9. package/dist/src/andorra/hosted.d.ts +2 -1
  10. package/dist/src/andorra/hosted.js +2 -1
  11. package/dist/src/andorra/notices.d.ts +5 -0
  12. package/dist/src/andorra/notices.js +7 -0
  13. package/dist/src/andorra/state.d.ts +3 -2
  14. package/dist/src/andorra/state.js +4 -4
  15. package/dist/src/andorra/terminal.js +7 -2
  16. package/dist/src/anthropic-credentials.js +2 -0
  17. package/dist/src/app-server/error.d.ts +5 -0
  18. package/dist/src/app-server/error.js +7 -0
  19. package/dist/src/app-server/protocol.d.ts +19 -44
  20. package/dist/src/app-server/protocol.js +5 -1
  21. package/dist/src/app-server/workspace.d.ts +89 -0
  22. package/dist/src/app-server/workspace.js +457 -11
  23. package/dist/src/app-server.d.ts +358 -32
  24. package/dist/src/app-server.js +2429 -509
  25. package/dist/src/bridge/cloud.d.ts +27 -0
  26. package/dist/src/bridge/cloud.js +187 -0
  27. package/dist/src/bridge/command.d.ts +30 -0
  28. package/dist/src/bridge/command.js +347 -0
  29. package/dist/src/bridge/control.d.ts +68 -0
  30. package/dist/src/bridge/control.js +233 -0
  31. package/dist/src/bridge/engines.d.ts +90 -0
  32. package/dist/src/bridge/engines.js +601 -0
  33. package/dist/src/bridge/host-ops.d.ts +9 -0
  34. package/dist/src/bridge/host-ops.js +129 -0
  35. package/dist/src/bridge/host.d.ts +47 -0
  36. package/dist/src/bridge/host.js +540 -0
  37. package/dist/src/bridge/link.d.ts +38 -0
  38. package/dist/src/bridge/link.js +508 -0
  39. package/dist/src/bridge/login-link.d.ts +29 -0
  40. package/dist/src/bridge/login-link.js +54 -0
  41. package/dist/src/bridge/protocol.d.ts +136 -0
  42. package/dist/src/bridge/protocol.js +11 -0
  43. package/dist/src/bridge/store.d.ts +12 -0
  44. package/dist/src/bridge/store.js +61 -0
  45. package/dist/src/bridge/wording.d.ts +6 -0
  46. package/dist/src/bridge/wording.js +10 -0
  47. package/dist/src/browser-server.js +7 -1
  48. package/dist/src/browser-ui/tokens.css +1 -1
  49. package/dist/src/change-authors.d.ts +41 -0
  50. package/dist/src/change-authors.js +146 -0
  51. package/dist/src/cli.js +182 -32
  52. package/dist/src/coding-tools.js +15 -15
  53. package/dist/src/command-screens.d.ts +6 -0
  54. package/dist/src/command-screens.js +14 -11
  55. package/dist/src/commands.d.ts +14 -2
  56. package/dist/src/compaction-phrases.js +1 -1
  57. package/dist/src/completion.js +82 -5
  58. package/dist/src/config.d.ts +71 -3
  59. package/dist/src/config.js +202 -77
  60. package/dist/src/deadline.js +13 -1
  61. package/dist/src/decision/checks.js +1 -1
  62. package/dist/src/decision/requestPhrases.js +0 -1
  63. package/dist/src/default-graph.js +1 -1
  64. package/dist/src/file-diff.d.ts +4 -0
  65. package/dist/src/file-diff.js +2 -1
  66. package/dist/src/github-app/agent-writes.d.ts +102 -0
  67. package/dist/src/github-app/agent-writes.js +320 -0
  68. package/dist/src/github-app/client.d.ts +349 -0
  69. package/dist/src/github-app/client.js +810 -0
  70. package/dist/src/github-app/event-source.d.ts +208 -0
  71. package/dist/src/github-app/event-source.js +684 -0
  72. package/dist/src/github-app/metrics.d.ts +32 -0
  73. package/dist/src/github-app/metrics.js +49 -0
  74. package/dist/src/github-app/review-loop.d.ts +274 -0
  75. package/dist/src/github-app/review-loop.js +1177 -0
  76. package/dist/src/github-app/review-node.d.ts +81 -0
  77. package/dist/src/github-app/review-node.js +205 -0
  78. package/dist/src/github-app/review-post.d.ts +73 -0
  79. package/dist/src/github-app/review-post.js +139 -0
  80. package/dist/src/github-app/review-text.d.ts +107 -0
  81. package/dist/src/github-app/review-text.js +1133 -0
  82. package/dist/src/github-app/review-threads.d.ts +47 -0
  83. package/dist/src/github-app/review-threads.js +107 -0
  84. package/dist/src/github-app/reviewer.d.ts +121 -0
  85. package/dist/src/github-app/reviewer.js +598 -0
  86. package/dist/src/github-app/store.d.ts +59 -0
  87. package/dist/src/github-app/store.js +148 -0
  88. package/dist/src/github-app/triggers.d.ts +141 -0
  89. package/dist/src/github-app/triggers.js +441 -0
  90. package/dist/src/github-names.d.ts +8 -0
  91. package/dist/src/github-names.js +8 -0
  92. package/dist/src/glob-search.d.ts +61 -0
  93. package/dist/src/glob-search.js +180 -0
  94. package/dist/src/graph-health.js +6 -1
  95. package/dist/src/graph-manager-chat.js +1 -1
  96. package/dist/src/graph-preview.d.ts +46 -0
  97. package/dist/src/graph-preview.js +55 -0
  98. package/dist/src/graph-provider-portability.js +2 -1
  99. package/dist/src/graph-runner.js +64 -3
  100. package/dist/src/graph-server.js +3 -3
  101. package/dist/src/graph-sync.js +3 -3
  102. package/dist/src/graph-ui/app.js +91 -7
  103. package/dist/src/graph-ui/icons.js +2 -1
  104. package/dist/src/graph-ui/studio.js +15 -1
  105. package/dist/src/graph-ui/tokens.css +1 -1
  106. package/dist/src/graphs.d.ts +34 -1
  107. package/dist/src/graphs.js +158 -14
  108. package/dist/src/image-input.d.ts +16 -0
  109. package/dist/src/image-input.js +41 -0
  110. package/dist/src/membership.d.ts +10 -0
  111. package/dist/src/membership.js +19 -4
  112. package/dist/src/model-health-cache.js +1 -1
  113. package/dist/src/model-metadata.d.ts +6 -0
  114. package/dist/src/model-metadata.js +35 -15
  115. package/dist/src/model-relay/local.d.ts +116 -0
  116. package/dist/src/model-relay/local.js +468 -0
  117. package/dist/src/model-relay/remote.d.ts +129 -0
  118. package/dist/src/model-relay/remote.js +252 -0
  119. package/dist/src/model-relay/runs.d.ts +34 -0
  120. package/dist/src/model-relay/runs.js +146 -0
  121. package/dist/src/model-relay/wire.d.ts +5 -0
  122. package/dist/src/model-relay/wire.js +5 -0
  123. package/dist/src/project-registry.d.ts +21 -0
  124. package/dist/src/project-registry.js +74 -0
  125. package/dist/src/provider-import.d.ts +0 -12
  126. package/dist/src/provider-import.js +7 -195
  127. package/dist/src/providers.d.ts +23 -2
  128. package/dist/src/providers.js +25 -4
  129. package/dist/src/pull-request-logs.d.ts +12 -1
  130. package/dist/src/pull-request-logs.js +14 -3
  131. package/dist/src/pull-requests.d.ts +327 -7
  132. package/dist/src/pull-requests.js +429 -51
  133. package/dist/src/react-runtime.js +1 -1
  134. package/dist/src/remote/engine-pool.d.ts +88 -4
  135. package/dist/src/remote/engine-pool.js +366 -89
  136. package/dist/src/remote/roots.d.ts +19 -0
  137. package/dist/src/remote/roots.js +45 -7
  138. package/dist/src/remote/types.d.ts +0 -44
  139. package/dist/src/run-control.d.ts +7 -0
  140. package/dist/src/run-control.js +23 -0
  141. package/dist/src/run-records.d.ts +7 -2
  142. package/dist/src/run-records.js +71 -6
  143. package/dist/src/runtime.d.ts +5 -1
  144. package/dist/src/runtime.js +10 -2
  145. package/dist/src/session-changes.d.ts +35 -0
  146. package/dist/src/session-changes.js +194 -6
  147. package/dist/src/session-monitor.js +2 -1
  148. package/dist/src/session-reaper.d.ts +1 -1
  149. package/dist/src/session-reaper.js +6 -1
  150. package/dist/src/session-summary.d.ts +2 -1
  151. package/dist/src/session-summary.js +2 -1
  152. package/dist/src/sessions.d.ts +11 -1
  153. package/dist/src/sessions.js +17 -4
  154. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  155. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  156. package/dist/src/skills/bundled/provenance.json +2 -2
  157. package/dist/src/skills/runtime-skills.js +1 -1
  158. package/dist/src/telemetry/emitter.d.ts +15 -0
  159. package/dist/src/telemetry/emitter.js +35 -1
  160. package/dist/src/telemetry/schema.d.ts +25 -2
  161. package/dist/src/telemetry/schema.js +52 -4
  162. package/dist/src/telemetry/surface.d.ts +2 -1
  163. package/dist/src/telemetry/surface.js +4 -1
  164. package/dist/src/terminal-ui.d.ts +1 -0
  165. package/dist/src/terminal-ui.js +10 -3
  166. package/dist/src/test-edit-guard.d.ts +7 -0
  167. package/dist/src/test-edit-guard.js +49 -1
  168. package/dist/src/timers.d.ts +2 -0
  169. package/dist/src/tools.js +59 -9
  170. package/package.json +6 -1
  171. package/dist/src/remote/cert.d.ts +0 -11
  172. package/dist/src/remote/cert.js +0 -87
  173. package/dist/src/remote/client.d.ts +0 -119
  174. package/dist/src/remote/client.js +0 -544
  175. package/dist/src/remote/command.d.ts +0 -4
  176. package/dist/src/remote/command.js +0 -194
  177. package/dist/src/remote/errors.d.ts +0 -11
  178. package/dist/src/remote/errors.js +0 -14
  179. package/dist/src/remote/network.d.ts +0 -22
  180. package/dist/src/remote/network.js +0 -102
  181. package/dist/src/remote/pairing.d.ts +0 -63
  182. package/dist/src/remote/pairing.js +0 -299
  183. package/dist/src/remote/pem.d.ts +0 -2
  184. package/dist/src/remote/pem.js +0 -7
  185. package/dist/src/remote/serve.d.ts +0 -68
  186. package/dist/src/remote/serve.js +0 -244
  187. package/dist/src/remote/server.d.ts +0 -21
  188. package/dist/src/remote/server.js +0 -406
@@ -1,18 +1,22 @@
1
1
  import { createInterface } from 'node:readline';
2
2
  import { createRequire } from 'node:module';
3
3
  import { readFileSync } from 'node:fs';
4
- import { randomUUID } from 'node:crypto';
4
+ import { randomBytes, randomUUID } from 'node:crypto';
5
5
  import { bootMark } from './boot-trace.js';
6
6
  import { ModelHealthCache } from './model-health-cache.js';
7
7
  import { mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
8
8
  import { homedir } from 'node:os';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
11
- import { changeConfigFile, configDirectory, ConfigConflictError, isProjectExtensionOverride, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
11
+ import { changeConfigFile, configDirectory, ConfigConflictError, readGitHubAgentWrites, readGitHubAppEventsEnabled, readGitHubAppReviewNewPullRequests, readGitHubAppReviewsEnabled, readGitHubAppTriggersEnabled, GITHUB_AGENT_WRITES, modelRelayAllowedFor, withModelRelayEntry, isProjectExtensionOverride, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
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, findProviderById, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS } from './providers.js';
15
+ import { allocateCodexAccountSlots, createAdapter, findProviderById, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS, supportsReasoningEffort } from './providers.js';
16
+ import { ModelRelayBroker, RELAY_FAILURE_CODE } from './model-relay/remote.js';
17
+ import { LocalModelRelay, relayedModelIds } from './model-relay/local.js';
18
+ import { ModelRelayRunStore } from './model-relay/runs.js';
19
+ import { MODEL_RELAY_CONNECTION_PREFIX } from './model-relay/wire.js';
16
20
  import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
17
21
  import { testProviderConnection } from './provider-connection.js';
18
22
  import { CodexAccountAuth } from './codex-browser-auth.js';
@@ -24,24 +28,24 @@ import { GOOGLE_BASE_URL } from './google-provider.js';
24
28
  import { GROK_BASE_URL } from './grok-provider.js';
25
29
  import { anthropicAccountHome } from './anthropic-credentials.js';
26
30
  import { codexAccountHome } from './codex-rpc.js';
27
- import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext } from './model-metadata.js';
31
+ import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext, resolveModelContextWindows } from './model-metadata.js';
28
32
  import { liveModelTarget } from './live-model.js';
29
- import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
33
+ import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
30
34
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
31
35
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
32
36
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
33
37
  import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
34
38
  import { freeTierGraphViolation, notePremiumGraphAccount, readGraphQuota } from './graph-quota.js';
35
- import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph } from './membership.js';
39
+ import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph } from './membership.js';
36
40
  import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
37
41
  import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
38
42
  import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
39
- import { getAuthStatus, login, logout, setAuthSignOutReporter } from './auth/index.js';
43
+ import { getAccessToken, getAuthStatus, login, logout, setAuthSignOutReporter } from './auth/index.js';
40
44
  import { configuredGraphSelection, currentGraphSubject, identityStillHolds } from './graph-selection.js';
41
45
  import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
42
46
  import { graphStorageAccess } from './graph-account.js';
43
47
  import { GraphAccessSync } from './graph-sync.js';
44
- import { canExtendLineage, displayHistory, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
48
+ import { canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
45
49
  import { folderChangeBusy, folderChangeHeld, reserveFolderChange } from './project-reservation.js';
46
50
  import { writePendingAgentInteraction, removePendingAgentInteraction } from './session-monitor.js';
47
51
  import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
@@ -55,20 +59,28 @@ import { changeAssignees, changeLabels, currentText, editBody, editTitle, nodeId
55
59
  import { actionsJobOf, fixChecksPrompt, jobId } from './pull-request-logs.js';
56
60
  import { issueNamedIn, readRepositoryIssues, readReviewRequests } from './github-inbox.js';
57
61
  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';
62
+ import { chatReviewLoopActive, parseReviewModel, reviewLoopActive, reviewLoopSettings, REVIEW_SETTING_KEYS } from './pull-requests.js';
63
+ import { confirmAutoFixWake, handedOver, isFinishedPullRequest, settleFinishedPullRequest, withChecks, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, codexReviewsRepository, ghFor, newReviewComments, noAccountMessage, readReviewSignals, REVIEW_BUMP_COMMENT, REVIEW_BUMP_DELAY_MS, REVIEW_SIGNAL_INTERVAL_MS, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
59
64
  import { AutomationStore } from './automations.js';
60
65
  import { executeAutomation } from './automation-runner.js';
61
66
  import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
62
67
  import { runGraph, stopReasonPhrase, timerReminderText, wakeMessageText } from './runtime.js';
63
- import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
68
+ import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportGitHubWatch, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
64
69
  import { telemetryGate } from './telemetry/gate.js';
70
+ import { accountApiTarget, defaultGitHubAppClient, GitHubAppError } from './github-app/client.js';
71
+ import { GitHubEventSource } from './github-app/event-source.js';
72
+ import { MentionTriggers } from './github-app/triggers.js';
73
+ import { applyReviewSettings, coverageAllowsReview, coverageRefusal, ReviewLoopController } from './github-app/review-loop.js';
74
+ import { newRequestId as newReviewLoopId } from './github-app/agent-writes.js';
75
+ import { asksBot, performAgentWrite } from './github-app/agent-writes.js';
76
+ import { createReviewNodeService, endGraphLoops } from './github-app/review-node.js';
65
77
  import { analyticsGenerationFor, resolveAnalyticsConfig } from './analytics.js';
66
78
  import { telemetryDirectory } from './telemetry/identity.js';
67
79
  import { recordPreference } from './telemetry/state.js';
68
80
  import { createRunTelemetry, recordModelUse } from './telemetry/capture.js';
69
81
  import { pricingFor } from './model-tiers.js';
70
82
  import { purgeOutbox } from './telemetry/outbox.js';
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';
83
+ import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runIsOpen, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
72
84
  import { ArtifactStore } from './artifacts.js';
73
85
  import { coverUnsavedToolCalls, mergeRunProgress, replayRunJournal, toolBoundaryOpen } from './run-progress.js';
74
86
  import { compactHistory, compactedContextEstimate } from './commands.js';
@@ -100,10 +112,24 @@ import { createBrowserIncognitoTool, createBrowserPanelTool, createPanelBrowserH
100
112
  import { createBrowserExtensionsTool, EXTENSIONS_OPERATION, relayExtensionSteps, validateExtensionStep } from './browser-extensions-tool.js';
101
113
  import { resolveCapsolverKey } from './capsolver.js';
102
114
  import { resolveWebSearchProvider } from './web-search.js';
103
- import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, readTree, readWorkspaceFile, summarizeMcpServer, workspaceRoot } from './app-server/workspace.js';
115
+ import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, gitLinkBase, listWorkspaceFiles, readTree, readWorkspaceFile, searchOptions, searchWorkspace, summarizeMcpServer, workspaceRoot, writeTarget } from './app-server/workspace.js';
116
+ import { andorraGetToolPath } from '../vendor/engine/runtime/coding-agent/utils/tools-manager.js';
117
+ /** Where ripgrep is, looked up once a minute: the lookup can run `rg --version`, which should not happen per keystroke. */
118
+ let ripgrepLookup;
119
+ function ripgrepPath() {
120
+ if (!ripgrepLookup || Date.now() - ripgrepLookup.at > 60_000)
121
+ ripgrepLookup = { path: andorraGetToolPath('rg'), at: Date.now() };
122
+ return ripgrepLookup.path;
123
+ }
104
124
  import { withReasoningEvents } from './app-server/reasoning.js';
105
125
  import { APP_SERVER_PROTOCOL_VERSION, APP_SERVER_CAPABILITIES, } from './app-server/protocol.js';
106
- import { RemotePeerError } from './remote/errors.js';
126
+ import { AppServerError } from './app-server/error.js';
127
+ import { AUTH_DEPLOYMENT } from './auth/deployment.js';
128
+ import { AuthError } from './auth/types.js';
129
+ import { claimEnvironment, cloudDelete, cloudGet, cloudStart, cloudStop, ControlError, listEnvironments, removeEnvironment, renameEnvironment } from './bridge/control.js';
130
+ import { relayUrlFromEnvironment } from './bridge/host.js';
131
+ import { RelayClosedError, RelayLink } from './bridge/link.js';
132
+ import { bothBridgeCommands, bridgeCommand } from './bridge/wording.js';
107
133
  import { fallbackProviderId, hasAndorraEntry, virtualAndorraEntry } from './andorra/entry.js';
108
134
  import { ANDORRA_CHANGED_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
109
135
  import { andorraAnnouncement } from './andorra/notices.js';
@@ -112,18 +138,83 @@ import { addAndorraEntry, saveAndorraAnswer } from './andorra/opt-in.js';
112
138
  import { HostedMonitor } from './andorra/monitor.js';
113
139
  import { watchRequests } from './andorra/request-watch.js';
114
140
  const SELECTION_HEALTH_TIMEOUT_MS = 60_000;
115
- class AppServerError extends Error {
116
- code;
117
- constructor(code, message) {
118
- super(message);
119
- this.code = code;
120
- }
121
- }
122
141
  const SESSION_HISTORY_TURNS = 6;
123
142
  const MAX_TASK_CHARS = 100_000;
143
+ /** A note the desktop sends with a message for the agent only (`run.note`), such as the person's hand edits. */
144
+ const MAX_NOTE_CHARS = 8_000;
145
+ /** A note longer than the cap is cut, not refused: refusing would block every message until the edits were cleared. */
146
+ const noteParam = (value) => {
147
+ if (value === undefined)
148
+ return undefined;
149
+ if (typeof value !== 'string')
150
+ throw new AppServerError('invalid-params', 'note must be a string');
151
+ const trimmed = value.trim();
152
+ if (!trimmed)
153
+ return undefined;
154
+ return trimmed.length > MAX_NOTE_CHARS ? `${trimmed.slice(0, MAX_NOTE_CHARS - 1)}…` : trimmed;
155
+ };
124
156
  const AUTOMATION_CONTEXT_CHARS = 4_000;
125
- const REMOTE_PROBE_DEADLINE_MS = 180_000;
126
157
  const REMOTE_LINK_ENGINE = 'remote-link';
158
+ /** How often a link whose machine or relay went away is reopened, until it succeeds or the desktop disconnects. */
159
+ const ENGINE_LINK_RETRY_MS = 5_000;
160
+ /** How long the account's environment ids are trusted before the control list is asked again. */
161
+ const ENVIRONMENT_IDS_TTL_MS = 30_000;
162
+ /** While any machine may use this computer's models, the account's list is read this often, so a removed machine's link ends without a window. */
163
+ const MODEL_RELAY_REFRESH_MS = 300_000;
164
+ /** A failed save of `environments.modelRelay` is tried once more after this long; until then the change holds in memory. */
165
+ const MODEL_RELAY_SAVE_RETRY_MS = 30_000;
166
+ /**
167
+ * How long the engine's own link waits before trying an offline machine again: 5 s in its first minute away, 30 s
168
+ * until its fifth minute, then 60 s. An open resets it.
169
+ */
170
+ /** The providers this computer offers a machine: its own (never a relayed entry), by a safe id, at most 64. */
171
+ function relayOfferedProviders(config) {
172
+ return config.providers.filter(provider => provider.type !== 'relayed' && /^[\w-]{1,128}$/.test(provider.id)).slice(0, 64);
173
+ }
174
+ function modelRelayRetryMs(awayMs) {
175
+ return awayMs < 60_000 ? 5_000 : awayMs < 300_000 ? 30_000 : 60_000;
176
+ }
177
+ const MACHINE_OFFLINE = `That machine is offline. Start the bridge on it: ${bothBridgeCommands('run')}.`;
178
+ const REMOTE_HOST_DEADLINE_MS = 30_000;
179
+ const RELAY_TRANSPORT_SLACK_MS = 15_000;
180
+ const RELEASE_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
181
+ const ENVIRONMENT_ID = /^env_[A-Za-z0-9_-]{22}$/;
182
+ const SIGN_IN_FOR_ENVIRONMENTS = 'Sign in to your Andorra account to use other machines.';
183
+ const MACHINE_NAME_RULE = 'A machine name is 1 to 64 characters with no control characters.';
184
+ /** How many times a reopened link asks again for the machine's identity when `whoami` failed, ENGINE_LINK_RETRY_MS apart. */
185
+ const IDENTITY_RETRIES = 3;
186
+ /** `workspaceId` in the remote.* methods and `id` in environments.* name an environment of the signed-in account. */
187
+ function environmentId(value) {
188
+ if (typeof value !== 'string' || !ENVIRONMENT_ID.test(value))
189
+ throw new AppServerError('not-found', 'No linked machine has that id.');
190
+ return value;
191
+ }
192
+ /** The optional Cloud environment a delete is limited to; a value that is not an environment id is refused. */
193
+ function cloudEnvironmentId(value) {
194
+ if (value === undefined)
195
+ return undefined;
196
+ if (typeof value !== 'string' || !ENVIRONMENT_ID.test(value))
197
+ throw new AppServerError('invalid-params', 'environmentId must be a Cloud environment id.');
198
+ return value;
199
+ }
200
+ function machineName(value) {
201
+ const name = typeof value === 'string' ? value.trim() : '';
202
+ if (!name || name.length > 64 || /[\u0000-\u001f\u007f-\u009f]/.test(name))
203
+ throw new AppServerError('invalid-params', MACHINE_NAME_RULE);
204
+ return name;
205
+ }
206
+ async function defaultEnvironmentAccessToken() {
207
+ try {
208
+ return await getAccessToken();
209
+ }
210
+ catch (error) {
211
+ if (error instanceof AuthError && error.code === 'login_required')
212
+ throw new AppServerError('login-required', SIGN_IN_FOR_ENVIRONMENTS);
213
+ if (error instanceof AuthError && error.code === 'network')
214
+ throw new AppServerError('network', error.message);
215
+ throw new AppServerError('auth', message(error));
216
+ }
217
+ }
127
218
  const RELAY_ERROR_CODES = new Set(['invalid-request', 'unknown-method', 'invalid-params', 'busy', 'engine-busy', 'not-found',
128
219
  'login-required', 'auth', 'storage', 'network', 'cancelled', 'internal', 'remote', 'nothing-to-continue']);
129
220
  const RELAY_DEADLINE_MS = 290_000;
@@ -399,6 +490,7 @@ function providerView(provider, providers) {
399
490
  ...(provider.type !== 'andorra' || provider.modelNames === undefined ? {} : { modelNames: { ...provider.modelNames } }),
400
491
  ...(provider.type !== 'andorra' || provider.modelParameters === undefined ? {} : { modelParameters: { ...provider.modelParameters } }),
401
492
  ...(provider.type !== 'andorra' || provider.freeModels === undefined ? {} : { freeModels: [...provider.freeModels] }),
493
+ ...(provider.textOnlyModels === undefined ? {} : { textOnlyModels: [...provider.textOnlyModels] }),
402
494
  ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }),
403
495
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
404
496
  ...(provider.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: provider.requestTimeoutMs }),
@@ -510,6 +602,21 @@ function mergeWebSearchConfig(current, patch) {
510
602
  }
511
603
  return Object.keys(next).length ? next : undefined;
512
604
  }
605
+ /** The text-only ids that still name one of the entry's models (case-folded, as requests match them), without repeats. */
606
+ function retainedTextOnlyModels(listed, offered) {
607
+ const known = new Set(offered.filter((model) => typeof model === 'string').map(model => model.toLowerCase()));
608
+ const seen = new Set();
609
+ return listed.filter(model => {
610
+ // Anything that is not a model id is kept for the config validation to refuse.
611
+ if (typeof model !== 'string')
612
+ return true;
613
+ const folded = model.toLowerCase();
614
+ if (!known.has(folded) || seen.has(folded))
615
+ return false;
616
+ seen.add(folded);
617
+ return true;
618
+ });
619
+ }
513
620
  export function mergeProviderSecrets(stored, incoming) {
514
621
  const previous = new Map(stored.map(provider => [provider.id, provider]));
515
622
  const fields = ['id', 'type', 'baseUrl', 'apiKeyEnv', 'model', 'models', 'modelContextWindows', 'contextWindow', 'reasoningEffort', 'requestTimeoutMs'];
@@ -517,6 +624,8 @@ export function mergeProviderSecrets(stored, incoming) {
517
624
  if (!entry || typeof entry !== 'object' || Array.isArray(entry))
518
625
  throw new AppServerError('invalid-params', 'Each provider must be an object');
519
626
  const source = entry;
627
+ if (source.type === 'relayed')
628
+ throw new AppServerError('invalid-params', 'Relayed providers cannot be saved.');
520
629
  const provider = {};
521
630
  for (const field of fields)
522
631
  if (source[field] !== undefined)
@@ -550,6 +659,16 @@ export function mergeProviderSecrets(stored, incoming) {
550
659
  provider.modelParameters = { ...previousEntry.modelParameters };
551
660
  if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.freeModels !== undefined)
552
661
  provider.freeModels = [...previousEntry.freeModels];
662
+ // Which models are text-only: a client sets it for its own providers (null clears, absent keeps), the router for Andorra.
663
+ const textOnly = provider.type === 'andorra' ? (previousEntry?.type === 'andorra' ? previousEntry.textOnlyModels : undefined)
664
+ : source.textOnlyModels === null ? undefined : source.textOnlyModels === undefined ? previousEntry?.textOnlyModels : source.textOnlyModels;
665
+ if (Array.isArray(textOnly)) {
666
+ const kept = retainedTextOnlyModels(textOnly, [provider.model, ...(Array.isArray(provider.models) ? provider.models : [])]);
667
+ if (kept.length)
668
+ provider.textOnlyModels = kept;
669
+ }
670
+ else if (textOnly !== undefined)
671
+ provider.textOnlyModels = textOnly;
553
672
  if (source.name === null)
554
673
  delete provider.name;
555
674
  else if (source.name === undefined) {
@@ -620,6 +739,7 @@ function sessionSummary(record) {
620
739
  ...(record.parentId === undefined ? {} : { parentId: record.parentId }),
621
740
  ...(record.projectId === undefined ? {} : { projectId: record.projectId }),
622
741
  ...(record.archived === undefined ? {} : { archived: record.archived }),
742
+ ...(record.pinned === true ? { pinned: true } : {}),
623
743
  ...(record.jevEnabled === undefined ? {} : { jevEnabled: record.jevEnabled }),
624
744
  ...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
625
745
  ...(finished === undefined ? {} : { lastTurnStatus: finished }),
@@ -628,16 +748,35 @@ function sessionSummary(record) {
628
748
  ...(record.usage.localCacheReadTokens === undefined ? {} : { localCacheReadTokens: record.usage.localCacheReadTokens }) },
629
749
  };
630
750
  }
631
- function freshAllowance(state) {
751
+ /**
752
+ * Gives a restored checkpoint the allowance a new attempt would have. `loopAttempts` also restarts a
753
+ * Loop modifier's attempt count: a loop that stopped on its last attempt otherwise resumes on that
754
+ * same attempt, so the message that continued it gets one cycle and the run ends on the limit again.
755
+ */
756
+ function freshAllowance(state, loopAttempts) {
632
757
  const { remainingToolCalls: _tools, remainingWallTimeMs: _wall, ...rest } = state;
633
- return { ...rest, iterations: 0, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: freshAllowance(copy.state) })) }) };
758
+ if (loopAttempts)
759
+ delete rest.modifierIteration;
760
+ return { ...rest, iterations: 0, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: freshAllowance(copy.state, loopAttempts) })) }) };
634
761
  }
635
762
  /** Marks a checkpoint (and its modifier copies) so the resumed agent summarizes its earlier messages before its first request. */
636
763
  function requestCompaction(state) {
637
764
  return { ...state, compactRequested: true, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: requestCompaction(copy.state) })) }) };
638
765
  }
766
+ /** The gh-backed PR settings and the Andorra review loop's, apart: the first change the PR on GitHub, the second never. */
767
+ function splitPullRequestSettings(settings) {
768
+ const gh = {};
769
+ const review = {};
770
+ for (const key of ['autoFix', 'mergeWhenReady', 'draft'])
771
+ if (settings[key] !== undefined)
772
+ gh[key] = settings[key];
773
+ for (const key of REVIEW_SETTING_KEYS)
774
+ if (settings[key] !== undefined)
775
+ Object.assign(review, { [key]: settings[key] });
776
+ return { gh, review };
777
+ }
639
778
  function wakeProvenance(wake, node) {
640
- if (wake !== 'timer' && wake !== 'auto-fix' && wake !== 'fix-checks')
779
+ if (wake !== 'timer' && wake !== 'auto-fix' && wake !== 'fix-checks' && wake !== 'mention' && wake !== 'andorra-review')
641
780
  return {};
642
781
  return { wake, ...(typeof node === 'string' && node ? { node } : {}) };
643
782
  }
@@ -647,6 +786,7 @@ export function isFinalWakeRefusal(error) {
647
786
  && (error.code === 'invalid-params' || error.code === 'not-found' || error.code === 'remote'
648
787
  || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue');
649
788
  }
789
+ const keptPullRequestMessage = (pullRequest) => `${pullRequest.url} is ${pullRequest.state}, so it stays on this task: it is how the user sees what became of the work. Nothing was changed, and there is nothing to clean up here. Only the user removes a ${pullRequest.state} pull request, with Dismiss in its menu.`;
650
790
  function outcomeCompletion(status, reason, limits) {
651
791
  return { summary: status === 'cancelled'
652
792
  ? 'This attempt was cancelled before it finished; its work may be incomplete.'
@@ -711,6 +851,104 @@ function readNodeModelOverrides(value) {
711
851
  }
712
852
  return read;
713
853
  }
854
+ const RELAYED_PROVIDER_FIELDS = new Set(['id', 'model', 'models', 'modelContextWindows', 'reasoningEffort']);
855
+ const MAX_RELAYED_PROVIDERS = 64;
856
+ const RELAYED_RESUME_NEEDS_DESKTOP = 'This task uses your computer\'s models. Resume it from Andorra Code on your computer.';
857
+ const RELAYED_GRAPH_NEEDS_DESKTOP = 'This task uses a graph from your computer. Resume it from Andorra Code on your computer.';
858
+ /** The capability a machine advertises when its engine can have its model calls answered by this computer. */
859
+ const MODEL_RELAY_CAPABILITY = 'model.relay';
860
+ const PROVIDER_NOT_HERE = 'That provider is not set up on this computer.';
861
+ /** Resolving the context windows of the relayed providers' models may take this long in all; what is not known by then is left out. */
862
+ const RELAY_WINDOWS_DEADLINE_MS = 5_000;
863
+ /** A provider's resolved model list and context windows are reused this long for the relay blocks of later starts. */
864
+ const RELAY_WINDOWS_CACHE_MS = 300_000;
865
+ const MODEL_NOT_HERE = 'That model is not on this computer\'s list for that provider.';
866
+ /** The deadline of a model.relay call or a runs.get this engine sends a machine itself. */
867
+ const MODEL_RELAY_CALL_MS = 30_000;
868
+ const REMOTE_PRIMARY = 'remote-primary';
869
+ /** A graph every engine has: it is named, never sent. */
870
+ function builtInGraph(id) {
871
+ return currentGraphSelection(id) === 'default' || isReservedGraphId(id);
872
+ }
873
+ /**
874
+ * The `relay` block of run.start and run.resume: the desktop's providers by id and model only (never an address,
875
+ * a key or a sign-in), and optionally the graph to run. Only an engine started for the bridge takes it.
876
+ */
877
+ function readRelay(value, options = {}) {
878
+ if (value === undefined)
879
+ return undefined;
880
+ if (process.env.ANDORRA_SURFACE !== 'remote')
881
+ throw new AppServerError('invalid-params', 'This engine does not take relayed providers.');
882
+ if (!value || typeof value !== 'object' || Array.isArray(value))
883
+ throw new AppServerError('invalid-params', 'relay must be an object with providers and an optional graph.');
884
+ const { providers, graph, ...rest } = value;
885
+ if (Object.keys(rest).length)
886
+ throw new AppServerError('invalid-params', 'relay takes only providers and graph.');
887
+ if (!Array.isArray(providers) || providers.length === 0)
888
+ throw new AppServerError('invalid-params', 'A relayed run needs at least one provider.');
889
+ if (providers.length > MAX_RELAYED_PROVIDERS)
890
+ throw new AppServerError('invalid-params', `A relayed run takes at most ${MAX_RELAYED_PROVIDERS} providers.`);
891
+ const seen = new Set();
892
+ const list = providers.map((entry) => {
893
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
894
+ throw new AppServerError('invalid-params', 'Each relayed provider must be an object.');
895
+ const source = entry;
896
+ if (Object.keys(source).some(key => !RELAYED_PROVIDER_FIELDS.has(key))) {
897
+ throw new AppServerError('invalid-params', 'A relayed provider carries only id, model, models, modelContextWindows and reasoningEffort.');
898
+ }
899
+ if (typeof source.id !== 'string' || !/^[\w-]{1,128}$/.test(source.id))
900
+ throw new AppServerError('invalid-params', 'A relayed provider id must be up to 128 word characters and dashes.');
901
+ if (seen.has(source.id.toLowerCase()))
902
+ throw new AppServerError('invalid-params', `Relayed provider ${source.id} is listed twice.`);
903
+ seen.add(source.id.toLowerCase());
904
+ const model = text(source.model, 'relay.providers model', 500);
905
+ const provider = { id: source.id, type: 'relayed', baseUrl: '', model };
906
+ if (source.models !== undefined) {
907
+ if (!Array.isArray(source.models) || source.models.length > 1_000
908
+ || source.models.some(item => typeof item !== 'string' || !item.trim() || item.length > 500)) {
909
+ throw new AppServerError('invalid-params', 'relay.providers models must be a list of model ids.');
910
+ }
911
+ provider.models = [...new Set([...source.models, model])];
912
+ }
913
+ if (source.modelContextWindows !== undefined) {
914
+ const windows = source.modelContextWindows;
915
+ if (!windows || typeof windows !== 'object' || Array.isArray(windows)
916
+ || Object.entries(windows).some(([key, window]) => !key.trim() || key.length > 500 || ['__proto__', 'constructor', 'prototype'].includes(key) || !Number.isSafeInteger(window) || window <= 0)) {
917
+ throw new AppServerError('invalid-params', 'relay.providers modelContextWindows must map model ids to positive integer context windows.');
918
+ }
919
+ provider.modelContextWindows = Object.fromEntries(Object.entries(windows));
920
+ }
921
+ if (source.reasoningEffort !== undefined)
922
+ provider.reasoningEffort = reasoningEffort(source.reasoningEffort);
923
+ return provider;
924
+ });
925
+ if (graph === undefined)
926
+ return { providers: list };
927
+ try {
928
+ return { providers: list, graph: relayedGraph(graph, { allowDeleted: options.resume === true }) };
929
+ }
930
+ catch (error) {
931
+ throw new AppServerError('invalid-params', `relay.graph: ${message(error)}`);
932
+ }
933
+ }
934
+ /** The configuration a relayed run sees: the desktop's providers in place of this machine's, for this run only. */
935
+ function withRelayedProviders(config, providers) {
936
+ const { externalSubagent: _externalSubagent, ...rest } = config;
937
+ return { ...rest, providers, provider: providers[0].id };
938
+ }
939
+ const RELAY_ERROR_KINDS = ['retryable', 'provider-request', 'other'];
940
+ function readRelayFailure(value) {
941
+ if (!value || typeof value !== 'object' || Array.isArray(value))
942
+ return undefined;
943
+ const source = value;
944
+ const kind = RELAY_ERROR_KINDS.includes(source.kind) ? source.kind : 'other';
945
+ return {
946
+ message: typeof source.message === 'string' ? source.message.slice(0, 4_000) : '', kind,
947
+ ...(source.contextOverflow === true ? { contextOverflow: true } : {}),
948
+ ...(typeof source.code === 'string' && RELAY_FAILURE_CODE.test(source.code) ? { code: source.code } : {}),
949
+ };
950
+ }
951
+ const GITHUB_INSTALL_HINT = (owner, repo) => `Install Andorra Code on ${owner}/${repo} for instant updates`;
714
952
  export class AppServer {
715
953
  automationCheck;
716
954
  autoArchiveCheck;
@@ -737,13 +975,34 @@ export class AppServer {
737
975
  gh;
738
976
  git;
739
977
  pullRequestWatcher;
978
+ githubClient;
979
+ githubSignedIn;
980
+ /** The signed-in account's subject, for gating the `github.watch` telemetry on its plan and opt-out. */
981
+ githubAccount;
982
+ githubEvents;
983
+ /** "@andorra-code" mentions on a task's PR (phase 3): the access check, the 👀 and the wake. */
984
+ mentions;
985
+ /** The App's bot login (`bot` from `GET /v1/github`, or `as` from a bot write), for the Auto-fix prompt. */
986
+ githubBot;
740
987
  pullRequestReader;
741
988
  sessionChanges;
742
989
  autoFixWakes = new Set();
743
990
  /** Wakes the PR tab's Fix with Agent armed: delivered as the person's request, not as a timer. */
744
991
  fixWakes = new Set();
992
+ /** Wakes a mention of the App's bot on the task's PR armed: delivered as "Mentioned on GitHub", not as a timer. */
993
+ mentionWakes = new Set();
745
994
  reviewWaiters = new Map();
746
995
  reviewWaitsStarting = new Set();
996
+ /** The Andorra review loop's fixer wakes, beside Auto-fix's: delivered as "Andorra review", routed like Auto-fix's. */
997
+ reviewWakes = new Set();
998
+ /** Each review wait's run, when it started, and the review loop it watches (the one running when it started, or after). */
999
+ reviewWaitRuns = new Map();
1000
+ reviewLoop;
1001
+ githubMembership;
1002
+ reviewSignalMs;
1003
+ reviewBumpDelayMs;
1004
+ /** Repositories (lower-case owner/name) where Codex was seen on a recent PR, so the question is asked once. */
1005
+ codexRepositories = new Set();
747
1006
  graphSync = new GraphAccessSync(undefined, undefined, () => this.emit('graphs.changed', {}));
748
1007
  // A visibility change made in this process, by a client or by the graph manager's tool in a run, reloads every client's list.
749
1008
  stopGraphVisibilityWatch = onGraphVisibilityChange(() => this.emit('graphs.changed', {}));
@@ -754,11 +1013,41 @@ export class AppServer {
754
1013
  browserViews;
755
1014
  browserExtensions;
756
1015
  extensionStatus = {};
1016
+ /** The Files tab's search in flight per channel, so a newer query cancels the older one. */
1017
+ workspaceSearches = new Map();
757
1018
  pending = new Map();
758
1019
  // Questions and approvals this engine is still waiting on, kept so a window that reloaded
759
1020
  // and re-adopted the engine can show them again (`run.current`).
760
1021
  waiting = new Map();
761
1022
  panelRelays = new Map();
1023
+ modelRelay;
1024
+ /** Answers the model calls of relayed runs on linked machines with this computer's providers. */
1025
+ localRelay;
1026
+ /** Machines being removed: refused at once, before the config file drops them from `environments.modelRelay`. */
1027
+ modelRelayRevoked = new Set();
1028
+ /** Machines allowed here whose save to `environments.modelRelay` failed, as `subject\0env`: allowed for this engine's lifetime. */
1029
+ modelRelayUnsaved = new Set();
1030
+ /** The runs this computer started or resumed on each machine: only their model requests are answered. */
1031
+ modelRelayRuns;
1032
+ /** Runs whose record failed to save, as `subject\0env\0runId`: answered for this engine's lifetime, saved again at 30 s. */
1033
+ modelRelayRunsUnsaved = new Set();
1034
+ /**
1035
+ * Allowed machines a fresh account listing did not name, as `subject\0env`, with when that was first seen. Only a
1036
+ * machine missing from two fresh listings a refresh apart is forgotten.
1037
+ */
1038
+ modelRelayMissing = new Map();
1039
+ /** Each provider's resolved context windows for the relay block, by the fields that determine them. */
1040
+ relayWindowsCache = new Map();
1041
+ /** Reconciliations of the engine's own links in flight; close waits for them. */
1042
+ modelRelayChores = new Set();
1043
+ /** Machines whose removal is in flight: a run they take meanwhile does not allow them again. */
1044
+ modelRelayRemoving = new Map();
1045
+ /** This engine's own links to the machines allowed to use this computer's models, apart from the window's. */
1046
+ modelRelayLinks = new Map();
1047
+ modelRelayRefresh;
1048
+ modelRelaySaveRetries = new Set();
1049
+ /** Bumped by every reconciliation of the engine's links, so only the latest one acts. */
1050
+ modelRelaySync = 0;
762
1051
  panelOperations = new Map();
763
1052
  panelOperationRuns = new Map();
764
1053
  requests = new Set();
@@ -790,10 +1079,17 @@ export class AppServer {
790
1079
  editorTask;
791
1080
  codeIntel;
792
1081
  codeIntelOpening = Promise.resolve();
793
- remoteServe;
794
1082
  engineLinks = new Map();
795
- lastKnownGrants = new Map();
796
- remoteOps = Promise.resolve();
1083
+ environmentOptions;
1084
+ relay;
1085
+ environmentIds;
1086
+ environmentIdsLoading;
1087
+ /** The id of the account's Cloud environment, once a list or a Cloud answer has named it. */
1088
+ cloudEnvironmentId;
1089
+ /** The last failed read of the account's list: within ENVIRONMENT_IDS_TTL_MS, reads fail with it without asking again. */
1090
+ environmentIdsFailure;
1091
+ /** Bumped when the account changes, so an answer fetched for the previous account is never cached. */
1092
+ accountGeneration = 0;
797
1093
  closed = false;
798
1094
  emitsStopped = false;
799
1095
  hosted;
@@ -809,8 +1105,27 @@ export class AppServer {
809
1105
  this.modelHealth = new ModelHealthCache(this.directory, options.modelHealthTtlMs === undefined ? {} : { ttlMs: options.modelHealthTtlMs });
810
1106
  this.createCodeIntelligence = options.createCodeIntelligence ?? (managerOptions => CodeIntelligenceManager.create(managerOptions));
811
1107
  this.loadGraph = options.loadGraph ?? loadAccessibleGraph;
1108
+ this.modelRelay = new ModelRelayBroker({
1109
+ emit: (event, data) => this.emit(event, data),
1110
+ // A desktop's return does not say running over an approval or a question the run still waits on.
1111
+ setRunState: (runId, state) => { if (this.run?.runId === runId && (state === 'awaiting-desktop' || this.pending.size === 0))
1112
+ this.emit('run.state', { runId, state }); },
1113
+ suspendBudget: runId => this.run?.runId === runId ? this.run.permissionControl.holdBudgets() : () => { },
1114
+ ...(options.modelRelayTimers === undefined ? {} : { timers: options.modelRelayTimers }),
1115
+ });
1116
+ this.modelRelayRuns = new ModelRelayRunStore(this.directory);
1117
+ this.localRelay = new LocalModelRelay({
1118
+ providers: async () => (await loadConfig(this.directory)).providers,
1119
+ subject: () => currentGraphSubject(),
1120
+ allowed: (env, subject) => this.modelRelayAnswers(env, subject),
1121
+ startedHere: (env, runId, subject) => this.relayRunStartedHere(env, runId, subject),
1122
+ createAdapter: (provider, adapterOptions) => createAdapter(provider, adapterOptions),
1123
+ send: (env, engine, method, params, via) => this.sendModelRelay(env, engine, method, params, via),
1124
+ log: line => this.log('warn', line),
1125
+ });
812
1126
  this.codexAuth = options.codexAuth ?? new CodexAccountAuth();
813
1127
  this.anthropicAuth = options.anthropicAuth ?? new AnthropicConsoleAuth();
1128
+ this.environmentOptions = options.environments ?? {};
814
1129
  this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
815
1130
  this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
816
1131
  this.googleSignIn = options.managedSignIn?.google ?? googleSignIn();
@@ -818,6 +1133,8 @@ export class AppServer {
818
1133
  this.signInProbes = options.signInProbes;
819
1134
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
820
1135
  this.gh = options.gh ?? runGh;
1136
+ this.reviewSignalMs = options.reviewSignals?.intervalMs ?? REVIEW_SIGNAL_INTERVAL_MS;
1137
+ this.reviewBumpDelayMs = options.reviewSignals?.bumpDelayMs ?? REVIEW_BUMP_DELAY_MS;
821
1138
  this.git = options.git ?? gitIn;
822
1139
  this.pullRequestReader = new PullRequestReader(this.gh, Date.now, (sessionId, read, details) => {
823
1140
  void this.syncPullRequestRecord(sessionId, read, details).catch(error => this.log('warn', `Could not record ${read.url}'s checks: ${message(error)}`));
@@ -825,9 +1142,97 @@ export class AppServer {
825
1142
  this.pullRequestWatcher = new PullRequestWatcher({
826
1143
  home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
827
1144
  onUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
828
- wake: (sessionId, prompt, carry, origin) => this.wakeForPullRequest(sessionId, prompt, carry, origin),
1145
+ wake: (sessionId, prompt, carry, origin) => {
1146
+ const wakeId = this.wakeForPullRequest(sessionId, prompt, carry, origin);
1147
+ this.githubEvents.woke(sessionId);
1148
+ return wakeId;
1149
+ },
829
1150
  wakePending: id => this.timers.list().some(timer => timer.id === id),
830
1151
  log: (level, detail) => this.log(level, detail),
1152
+ covered: sessionId => this.githubEvents.covers(sessionId),
1153
+ onGhCall: sessionId => this.githubEvents.countGhCall(sessionId),
1154
+ agentWrites: sessionId => this.autoFixWrites(sessionId),
1155
+ onRead: (sessionId, pullRequest) => this.reviewLoop.pullRequestRead(sessionId, pullRequest),
1156
+ ...(options.githubApp?.now === undefined ? {} : { now: options.githubApp.now }),
1157
+ ...(options.githubApp?.checkNowDelayMs === undefined ? {} : { checkNowDelayMs: options.githubApp.checkNowDelayMs }),
1158
+ });
1159
+ this.githubClient = options.githubApp?.client ?? defaultGitHubAppClient();
1160
+ this.githubSignedIn = options.githubApp?.signedIn ?? (async (signal) => (await getAuthStatus(signal)).signedIn);
1161
+ // Read with a short bound: the window is flushed while the engine closes, and it must not wait on the auth lock.
1162
+ this.githubAccount = options.githubApp?.subject ?? (async () => { const status = await getAuthStatus(AbortSignal.timeout(2_000)).catch(() => undefined); return status?.signedIn ? status.subject : undefined; });
1163
+ this.mentions = new MentionTriggers({
1164
+ home: this.directory, gh: this.gh, client: this.githubClient,
1165
+ enabled: () => readGitHubAppTriggersEnabled(this.directory),
1166
+ writes: sessionId => this.mentionWrites(sessionId),
1167
+ wake: (sessionId, prompt, pullRequest) => this.wakeForMention(sessionId, prompt, pullRequest),
1168
+ log: (level, detail) => this.log(level, detail),
1169
+ ...(options.githubApp?.now === undefined ? {} : { now: options.githubApp.now }),
1170
+ ...(options.githubApp?.reactionBudgetMs === undefined ? {} : { reactionBudgetMs: options.githubApp.reactionBudgetMs }),
1171
+ ...(options.githubApp?.mentionRetryMs === undefined ? {} : { retryDelaysMs: options.githubApp.mentionRetryMs }),
1172
+ });
1173
+ this.githubEvents = new GitHubEventSource({
1174
+ home: this.directory, client: this.githubClient,
1175
+ watcher: {
1176
+ claim: () => this.pullRequestWatcher.claim(),
1177
+ holdsLease: () => this.pullRequestWatcher.holdsLease(),
1178
+ checkNow: (sessionId, checkOptions) => this.pullRequestWatcher.checkNow(sessionId, checkOptions),
1179
+ fullPass: () => { void this.pullRequestWatcher.poll({ force: true }); },
1180
+ headSha: sessionId => this.pullRequestWatcher.headSha(sessionId),
1181
+ },
1182
+ signedIn: this.githubSignedIn,
1183
+ locallyEnabled: () => readGitHubAppEventsEnabled(this.directory),
1184
+ onStale: sessionId => this.emit('session.pullRequest.stale', { sessionId }),
1185
+ onRequest: (sessionId, notice) => { void this.mentions.handle(sessionId, notice); },
1186
+ onLeaseAcquired: () => { this.mentions.reload(); this.reviewLoop.leaseAcquired(); },
1187
+ onSummary: summary => {
1188
+ // The window is gated like a run's events, on the signed-in account's plan and opt-out. Without a readable
1189
+ // subject that cannot be checked, so the window is not sent at all.
1190
+ const work = this.githubAccount().catch(() => undefined).then(subject => subject === undefined ? undefined
1191
+ : reportGitHubWatch({ home: this.directory, surface: configuredSurface('desktop'), subject }, summary));
1192
+ this.telemetrySettle = this.telemetrySettle.then(() => work).catch(() => { });
1193
+ return work;
1194
+ },
1195
+ log: (level, detail) => this.log(level, detail),
1196
+ ...(options.githubApp?.now === undefined ? {} : { now: options.githubApp.now }),
1197
+ });
1198
+ // The plan for Andorra review comes from the same account API as the bot's writes: in test mode, the test account
1199
+ // API with its token (a staging account's plan), otherwise the signed-in account's.
1200
+ const testAccount = accountApiTarget();
1201
+ this.githubMembership = options.githubApp?.membership ?? (testAccount.token !== undefined
1202
+ // That client writes nothing: no stored pass and no plan note under this home, which belong to the signed-in account.
1203
+ ? createMembershipClient({ accessToken: async () => testAccount.token, apiBaseUrl: () => testAccount.baseUrl, fetch: (...args) => globalThis.fetch(...args),
1204
+ allowLoopbackHttp: testAccount.loopback, storePass: async () => undefined, recordPlan: async () => { } })
1205
+ : signal => getMembership(signal, this.directory));
1206
+ this.reviewLoop = new ReviewLoopController({
1207
+ home: this.directory, gh: this.gh, client: this.githubClient,
1208
+ holdsLease: () => this.pullRequestWatcher.holdsLease(),
1209
+ coverage: (sessionId, pullRequest) => this.reviewCoverage(sessionId, pullRequest),
1210
+ readNow: sessionId => this.pullRequestWatcher.readNow(sessionId),
1211
+ headSha: sessionId => this.pullRequestWatcher.headSha(sessionId),
1212
+ sessionBusy: (sessionId, except) => this.sessionBusyForReview(sessionId, except),
1213
+ runOpen: async (runId) => this.run?.runId === runId || this.finishingRunId === runId || runIsOpen(this.directory, runId),
1214
+ // Closed with the app, or a record still saying running with no live claim (its engine was killed): not finished.
1215
+ runInterrupted: async (runId) => {
1216
+ const status = await readFile(runRecordPath(this.directory, runId, 'json'), 'utf8').then(text => JSON.parse(text).status, () => undefined);
1217
+ return status === 'interrupted' || status === 'running';
1218
+ },
1219
+ workspace: async (sessionId) => (await this.readSession(sessionId).catch(() => undefined))?.workspace,
1220
+ defaultModel: async () => {
1221
+ const config = await loadConfig(this.directory);
1222
+ const provider = config.providers.find(entry => entry.id === config.provider);
1223
+ return provider?.model ? { provider: provider.id, model: provider.model } : undefined;
1224
+ },
1225
+ writes: sessionId => this.autoFixWrites(sessionId),
1226
+ wake: (sessionId, prompt, pullRequest) => this.wakeForReview(sessionId, prompt, pullRequest),
1227
+ wakeArmed: wakeId => this.timers.get(wakeId) !== undefined,
1228
+ cancelWake: (sessionId, wakeId) => this.cancelReviewWake(sessionId, wakeId),
1229
+ emitUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
1230
+ emitLoop: event => this.emit('session.pullRequest.reviewLoop', { ...event }),
1231
+ turns: sessionId => this.sessionTurnCount(sessionId),
1232
+ log: (level, detail) => this.log(level, detail),
1233
+ // The reviewer child reads the same home: its providers, sign-ins and the hidden session it saves.
1234
+ reviewerEnv: { ANDORRACODE_HOME: this.directory },
1235
+ ...options.githubApp?.reviewLoop,
831
1236
  });
832
1237
  void pruneAttachments(this.directory).catch(() => { });
833
1238
  this.flow = new TerminalFlow(this.output, id => this.terminals.pause(id), id => this.terminals.resume(id));
@@ -954,10 +1359,7 @@ export class AppServer {
954
1359
  this.error.write(`[app-server] ${level}: ${detail}\n`);
955
1360
  }
956
1361
  async ready() {
957
- setAuthSignOutReporter(error => {
958
- this.emit('account.signed-out', { message: error.message });
959
- this.error.write(`[app-server] signed out: ${error.message}\n`);
960
- });
1362
+ setAuthSignOutReporter(error => this.accountSignedOut(error.message));
961
1363
  this.emit('ready', await this.hostInfo());
962
1364
  bootMark('ready.emitted');
963
1365
  if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed && !this.automationCheck) {
@@ -978,8 +1380,12 @@ export class AppServer {
978
1380
  this.automationCheck.unref();
979
1381
  check();
980
1382
  }
981
- if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed)
1383
+ if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed) {
982
1384
  this.pullRequestWatcher.start();
1385
+ this.githubEvents.start();
1386
+ this.reviewLoop.start();
1387
+ }
1388
+ this.syncModelRelayLinks();
983
1389
  if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed && !this.autoArchiveCheck) {
984
1390
  this.autoArchiveCheck = setInterval(() => { void this.reapSessions(); }, DAY_MS);
985
1391
  this.autoArchiveCheck.unref();
@@ -1117,6 +1523,7 @@ export class AppServer {
1117
1523
  ? [{ id: item.id, question: item.question, ...(item.choices === undefined ? {} : { choices: [...item.choices] }) }] : []),
1118
1524
  approvals: waiting.flatMap(item => item.kind === 'approval'
1119
1525
  ? [{ id: item.id, name: item.name, arguments: item.arguments }] : []),
1526
+ ...(this.modelRelay.awaiting(live.runId) ? { state: 'awaiting-desktop' } : {}),
1120
1527
  } };
1121
1528
  }
1122
1529
  async hostInfo() {
@@ -1213,7 +1620,9 @@ export class AppServer {
1213
1620
  const config = await loadConfig(this.directory);
1214
1621
  return { providers: providerViews(config.providers), active: config.provider };
1215
1622
  }
1216
- case 'providers.update': return this.updateProviders(params);
1623
+ case 'providers.update':
1624
+ this.relayWindowsCache.clear();
1625
+ return this.updateProviders(params);
1217
1626
  case 'andorra.status': {
1218
1627
  if (params.check !== undefined && typeof params.check !== 'boolean')
1219
1628
  throw new AppServerError('invalid-params', 'check must be a boolean');
@@ -1268,13 +1677,14 @@ export class AppServer {
1268
1677
  }
1269
1678
  case 'sessions.setJev': return { session: this.summary(await this.setSessionJev(params)) };
1270
1679
  case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
1680
+ case 'sessions.setPinned': return { session: this.summary(await this.setSessionPinned(params)) };
1271
1681
  case 'sessions.delete': return this.deleteSession(params);
1272
1682
  case 'sessions.pullRequest.get': return { pullRequest: pullRequestForClients(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
1273
1683
  case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest: pullRequestForClients(entry.pullRequest) })) };
1274
1684
  case 'sessions.pullRequest.update': {
1275
1685
  let settings;
1276
1686
  try {
1277
- settings = pullRequestSettings(params);
1687
+ settings = { ...pullRequestSettings(params), ...reviewLoopSettings(params) };
1278
1688
  }
1279
1689
  catch (error) {
1280
1690
  throw new AppServerError('invalid-params', message(error));
@@ -1309,6 +1719,10 @@ export class AppServer {
1309
1719
  case 'sessions.pullRequest.dequeue': return this.dequeueSessionPullRequest(params);
1310
1720
  case 'sessions.pullRequest.attach': return this.attachSessionPullRequest(params);
1311
1721
  case 'pullRequests.reviewRequests': return this.pullRequestReviewRequests(params.refresh === true);
1722
+ case 'github.status': return this.githubStatus();
1723
+ case 'github.connect': return this.githubConnect(params);
1724
+ case 'github.disconnect': return this.githubDisconnect();
1725
+ case 'github.setAgentWrites': return this.githubSetAgentWrites(params);
1312
1726
  case 'issues.list': return this.listWorkspaceIssues(params);
1313
1727
  case 'sessions.changes.list': return this.sessionChanges.list(changesSessionId(params.id), diffLines(params.maxLines, LIST_DIFF_LINES));
1314
1728
  case 'sessions.changes.get': {
@@ -1594,6 +2008,9 @@ export class AppServer {
1594
2008
  return { cancelled: controller !== undefined };
1595
2009
  }
1596
2010
  case 'browser.panel.result': return this.settlePanelRelay(params);
2011
+ case 'model.relay.claim': return this.modelRelay.claim(this.relayCall(params));
2012
+ case 'model.relay.progress': return this.relayProgress(params);
2013
+ case 'model.relay.result': return this.relayResult(params);
1597
2014
  case 'workspace.tree': {
1598
2015
  const root = await workspaceRoot(params.workspace);
1599
2016
  return readTree(root, { path: params.path, depth: params.depth });
@@ -1602,6 +2019,47 @@ export class AppServer {
1602
2019
  const root = await workspaceRoot(params.workspace);
1603
2020
  return readWorkspaceFile(root, params.path);
1604
2021
  }
2022
+ case 'workspace.write': {
2023
+ const root = await workspaceRoot(params.workspace);
2024
+ if (params.sessionId !== undefined && (typeof params.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(params.sessionId)))
2025
+ throw new AppServerError('invalid-params', 'sessionId must be a session id');
2026
+ // A save is recorded only in a task that exists, so an unknown id leaves no review record behind.
2027
+ const sessionId = typeof params.sessionId === 'string' && await stat(join(this.directory, 'sessions', `${params.sessionId}.json`)).then(() => true, () => false) ? params.sessionId : undefined;
2028
+ const target = await writeTarget(root, params).catch(error => { throw new AppServerError('invalid-params', message(error)); });
2029
+ const result = await this.sessionChanges.userWrite({ ...target, root, ...(sessionId ? { sessionId } : {}),
2030
+ onError: error => this.log('warn', `Could not record a saved file for review: ${message(error)}`) });
2031
+ if (!result.written || !result.changes)
2032
+ return result;
2033
+ const { changes, ...saved } = result;
2034
+ this.emitSessionChanges(changes);
2035
+ return saved;
2036
+ }
2037
+ case 'workspace.files': {
2038
+ const root = await workspaceRoot(params.workspace);
2039
+ return listWorkspaceFiles(root);
2040
+ }
2041
+ case 'workspace.linkBase': {
2042
+ const root = await workspaceRoot(params.workspace);
2043
+ return gitLinkBase(root);
2044
+ }
2045
+ case 'workspace.search': {
2046
+ // A newer search on the same channel (one Search view) cancels the one before it, from the moment it arrives.
2047
+ const channel = typeof params.channel === 'string' && params.channel.length <= 200 ? params.channel : undefined;
2048
+ const controller = new AbortController();
2049
+ if (channel) {
2050
+ this.workspaceSearches.get(channel)?.abort();
2051
+ this.workspaceSearches.set(channel, controller);
2052
+ }
2053
+ try {
2054
+ const root = await workspaceRoot(params.workspace);
2055
+ const options = searchOptions(params);
2056
+ return await searchWorkspace(root, options, controller.signal, ripgrepPath());
2057
+ }
2058
+ finally {
2059
+ if (channel && this.workspaceSearches.get(channel) === controller)
2060
+ this.workspaceSearches.delete(channel);
2061
+ }
2062
+ }
1605
2063
  case 'attachments.read': {
1606
2064
  const image = await readSpooledImage(this.directory, params.path);
1607
2065
  if (!image)
@@ -1663,28 +2121,23 @@ export class AppServer {
1663
2121
  case 'projects.add': return this.addProject(params);
1664
2122
  case 'projects.remove': return this.removeProject(params);
1665
2123
  case 'projects.relink': return this.relinkProject(params);
1666
- case 'remote.hosting.status': return this.remoteHostingStatus();
1667
- case 'remote.hosting.invitation.regenerate': return this.remoteHostingInvitationRegenerate();
1668
- case 'remote.hosting.shares.add': return this.remoteShareAdd(params);
1669
- case 'remote.hosting.shares.remove': return this.remoteShareRemove(params);
1670
- case 'remote.hosting.device.revoke': return this.remoteDeviceRevoke(params);
1671
- case 'remote.workspaces.list': return this.remoteWorkspacesList();
1672
- case 'remote.workspaces.probe': return this.remoteWorkspaceProbe(params);
1673
- case 'remote.workspaces.add': return this.remoteWorkspaceAdd(params);
1674
- case 'remote.workspaces.remove': return this.remoteWorkspaceRemove(params);
1675
- case 'remote.workspaces.rename': return this.remoteWorkspaceRename(params);
1676
- case 'remote.workspaces.setHost': return this.remoteWorkspaceSetHost(params);
2124
+ case 'environments.list': return this.environmentsList();
2125
+ case 'environments.link.claim': return this.environmentClaim(params);
2126
+ case 'environments.rename': return this.environmentRename(params);
2127
+ case 'environments.remove': return this.environmentRemove(params);
2128
+ case 'environments.cloud.get':
2129
+ case 'environments.cloud.start':
2130
+ case 'environments.cloud.stop':
2131
+ case 'environments.cloud.delete': return this.environmentCloud(method, params);
1677
2132
  case 'remote.roots.list': return this.remoteRootsList(params);
1678
2133
  case 'remote.projects.fetch': return this.remoteProjectsFetch(params);
1679
2134
  case 'remote.browse': return this.remoteBrowse(params);
1680
2135
  case 'remote.owner.roots': return this.remoteOwnerRoots(params);
1681
2136
  case 'remote.owner.browse': return this.remoteOwnerBrowse(params);
1682
2137
  case 'remote.owner.projects.add': return this.remoteOwnerAddProject(params);
1683
- case 'remote.hosting.invitation.full': return this.remoteHostingInvitationFull();
1684
2138
  case 'remote.engine.connect': return this.remoteEngineConnect(params);
1685
2139
  case 'remote.engine.request': return this.remoteEngineRequest(params);
1686
2140
  case 'remote.engine.disconnect': return this.remoteEngineDisconnect(params);
1687
- case 'remote.hosting.device.grant': return this.remoteDeviceGrant(params);
1688
2141
  case 'shutdown':
1689
2142
  await this.close();
1690
2143
  this.onStop?.();
@@ -1716,7 +2169,9 @@ export class AppServer {
1716
2169
  const target = targets.get(path) ?? path;
1717
2170
  const matching = all
1718
2171
  .filter(record => resolve(record.workspace) === resolve(target))
1719
- .sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt));
2172
+ // Pinned tasks lead the first page, so an old pinned task is never left on a page the rail has not loaded.
2173
+ .sort((left, right) => (left.pinned === true ? 0 : 1) - (right.pinned === true ? 0 : 1)
2174
+ || Date.parse(right.updatedAt) - Date.parse(left.updatedAt));
1720
2175
  const sessions = (limit === undefined ? matching : matching.slice(offset, offset + limit)).map(record => this.summary(record));
1721
2176
  return {
1722
2177
  requested: path,
@@ -1909,7 +2364,7 @@ export class AppServer {
1909
2364
  const content = params.content;
1910
2365
  const previousContent = params.previousContent;
1911
2366
  return this.serializeConfig(async () => {
1912
- if (this.run || this.starting || (await sessionsWithOpenRunClaims(this.directory)).active.size > 0) {
2367
+ if (this.run || this.starting || await this.taskRunsOpen()) {
1913
2368
  throw new AppServerError('busy', 'Finish active tasks before editing imported skill files.');
1914
2369
  }
1915
2370
  await writeSkillResource(id, path, content, previousContent, await loadConfig(this.directory), this.directory);
@@ -1943,11 +2398,27 @@ export class AppServer {
1943
2398
  return { id: installed.id };
1944
2399
  }));
1945
2400
  }
2401
+ /**
2402
+ * Whether a task's run is open anywhere on this home. A review loop's reviewer (a hidden session) is not a task: it
2403
+ * uses no skill or plugin, so it never holds up an edit or a removal.
2404
+ */
2405
+ async taskRunsOpen() {
2406
+ const { active } = await sessionsWithOpenRunClaims(this.directory);
2407
+ for (const sessionId of active) {
2408
+ if (!/^[A-Za-z0-9_-]{1,128}$/.test(sessionId))
2409
+ return true;
2410
+ const session = await readFile(join(this.directory, 'sessions', `${sessionId}.json`), 'utf8')
2411
+ .then(text => JSON.parse(text), () => undefined);
2412
+ if (!session || !hiddenSession(session))
2413
+ return true;
2414
+ }
2415
+ return false;
2416
+ }
1946
2417
  async removeExtension(params) {
1947
2418
  const kind = this.extensionKind(params.kind);
1948
2419
  const id = typeof params.id === 'string' ? params.id : '';
1949
2420
  return this.serializeConfig(async () => {
1950
- if (this.run || this.starting || (await sessionsWithOpenRunClaims(this.directory)).active.size > 0) {
2421
+ if (this.run || this.starting || await this.taskRunsOpen()) {
1951
2422
  throw new AppServerError('busy', 'A task is running and may still need this skill or plugin. Finish active tasks before removing installed bundles.');
1952
2423
  }
1953
2424
  const current = await loadConfig(this.directory);
@@ -2471,8 +2942,13 @@ export class AppServer {
2471
2942
  async signIn() {
2472
2943
  try {
2473
2944
  const status = await this.operation(180_000, signal => login({ signal, onMessage: detail => this.emit('account.login.message', { message: detail }) }));
2945
+ // A sign-in is not a sign-out: the links end as account-changed, so no window asks the person to sign in.
2946
+ this.endAccountLinks('account-changed');
2474
2947
  await this.publishAccount();
2475
2948
  this.checkHostedAfterAccountChange();
2949
+ // The new account's machines that are allowed here get their links.
2950
+ this.syncModelRelayLinks();
2951
+ this.githubEvents.refresh();
2476
2952
  return { signedIn: status.signedIn, subject: status.subject };
2477
2953
  }
2478
2954
  catch (error) {
@@ -2483,14 +2959,53 @@ export class AppServer {
2483
2959
  async signOut() {
2484
2960
  try {
2485
2961
  const { revoked } = await logout();
2962
+ this.endAccountLinks();
2486
2963
  await this.publishAccount();
2487
2964
  this.checkHostedAfterAccountChange();
2965
+ this.githubEvents.nudge();
2488
2966
  return { revoked };
2489
2967
  }
2490
2968
  catch (error) {
2969
+ // A failed sign-out may still have removed the stored sign-in, so the old account's links end either way.
2970
+ this.endAccountLinks();
2491
2971
  throw new AppServerError('auth', message(error));
2492
2972
  }
2493
2973
  }
2974
+ /** The stored sign-in was rejected and removed: the account is signed out without anyone asking. */
2975
+ accountSignedOut(detail) {
2976
+ this.endAccountLinks();
2977
+ this.githubEvents.nudge();
2978
+ this.emit('account.signed-out', { message: detail });
2979
+ this.error.write(`[app-server] signed out: ${detail}\n`);
2980
+ }
2981
+ /**
2982
+ * The relay socket and every machine link were opened for the signed-in account. When the account changes or
2983
+ * signs out they all end: each link with `remote.engine.closed` and `reason` (`login-required` after a sign-out,
2984
+ * `account-changed` after a sign-in), and the socket itself, so the next use dials again with the new sign-in.
2985
+ */
2986
+ endAccountLinks(reason = 'login-required') {
2987
+ // The old account's machines may not go on spending this computer's providers, linked or not.
2988
+ this.localRelay.dropAll();
2989
+ this.modelRelayRunsUnsaved.clear();
2990
+ this.modelRelayMissing.clear();
2991
+ this.accountGeneration += 1;
2992
+ this.cloudEnvironmentId = undefined;
2993
+ for (const [env, link] of [...this.engineLinks])
2994
+ this.forgetEngineLink(env, link, reason);
2995
+ for (const [env, link] of [...this.modelRelayLinks])
2996
+ this.forgetEngineLink(env, link, reason);
2997
+ this.modelRelaySync += 1;
2998
+ clearTimeout(this.modelRelayRefresh);
2999
+ this.modelRelayRefresh = undefined;
3000
+ const relay = this.relay;
3001
+ this.relay = undefined;
3002
+ relay?.dispose(reason === 'login-required'
3003
+ ? new AppServerError('login-required', SIGN_IN_FOR_ENVIRONMENTS)
3004
+ : new AppServerError('cancelled', 'The Andorra account changed.'));
3005
+ this.environmentIds = undefined;
3006
+ this.environmentIdsLoading = undefined;
3007
+ this.environmentIdsFailure = undefined;
3008
+ }
2494
3009
  /** Signing in or out changes what Andorra offers this account: ask now instead of at the next interval. */
2495
3010
  checkHostedAfterAccountChange() {
2496
3011
  if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed)
@@ -2577,7 +3092,7 @@ export class AppServer {
2577
3092
  return derived;
2578
3093
  // Allocated through the config write so two tasks created together agree on one identity instead of each keeping its
2579
3094
  // own, which would leave one of them filing against an id the registry never accepted.
2580
- const { ensureProjectIdentity } = await import('./remote/pairing.js');
3095
+ const { ensureProjectIdentity } = await import('./project-registry.js');
2581
3096
  const fresh = randomUUID().replace(/-/g, '').slice(0, 16);
2582
3097
  return await ensureProjectIdentity(root, fresh, this.directory).catch(() => undefined) ?? fresh;
2583
3098
  }
@@ -2720,8 +3235,33 @@ export class AppServer {
2720
3235
  if (await sessionHasOpenRun(this.directory, id))
2721
3236
  throw new AppServerError('busy', 'That task is running in another window. Stop the run or wait for it to finish, then archive it.');
2722
3237
  const record = await this.readSession(id);
2723
- const { autoArchived: _autoArchived, ...rest } = record;
2724
- const updated = { ...rest, archived };
3238
+ const { autoArchived: _autoArchived, ...kept } = record;
3239
+ // An archived task leaves the rail's list, so it does not stay pinned there.
3240
+ const { pinned: _pinned, ...unpinned } = kept;
3241
+ const updated = { ...(archived ? unpinned : kept), archived };
3242
+ await this.store().save(savedSessionFields(updated));
3243
+ this.emit('session.updated', { session: this.summary(updated) });
3244
+ return updated;
3245
+ });
3246
+ }
3247
+ /** Pins or unpins a task in the rail. The pin is rail-owned like a rename, so this window's own run may be pinned too: the run carries it forward when it saves. */
3248
+ async setSessionPinned(params) {
3249
+ const id = identifier(params.id, 'id');
3250
+ if (typeof params.pinned !== 'boolean')
3251
+ throw new AppServerError('invalid-params', 'pinned must be a boolean');
3252
+ const pinned = params.pinned;
3253
+ if (this.startingSession === id || this.starting)
3254
+ throw new AppServerError('busy', 'That task is starting. Wait for it to begin, then pin it.');
3255
+ const ownRunId = this.run?.sessionId === id ? this.run.runId
3256
+ : this.finishingRunId !== undefined && this.finishingSessionId === id ? this.finishingRunId : undefined;
3257
+ return this.withSessionMutation(id, async () => {
3258
+ if (await sessionHasOpenRun(this.directory, id, ownRunId === undefined ? {} : { ignoreRunId: ownRunId }))
3259
+ throw new AppServerError('busy', 'That task is running in another window. Stop the run or wait for it to finish, then pin it.');
3260
+ const record = await this.readSession(id);
3261
+ if (pinned && record.archived === true)
3262
+ throw new AppServerError('invalid-params', 'An archived task cannot be pinned. Unarchive it first.');
3263
+ const { pinned: _pinned, ...rest } = record;
3264
+ const updated = pinned ? { ...rest, pinned: true } : rest;
2725
3265
  await this.store().save(savedSessionFields(updated));
2726
3266
  this.emit('session.updated', { session: this.summary(updated) });
2727
3267
  return updated;
@@ -2739,8 +3279,11 @@ export class AppServer {
2739
3279
  void clearWakeClaims(this.directory, id).catch(() => { });
2740
3280
  this.emitTimers(id);
2741
3281
  await this.browserViews.release(id, 'That session was deleted.');
3282
+ const tracked = await readPullRequest(this.directory, id).catch(() => undefined);
2742
3283
  await removePullRequest(this.directory, id).catch(() => { });
2743
3284
  this.pullRequestReader.forget(id);
3285
+ if (tracked?.review && reviewLoopActive(tracked))
3286
+ this.reviewLoop.ended(id, tracked.review, 'cancelled', 'The task was deleted.');
2744
3287
  await removeSessionSkill(this.directory, id).catch(() => { });
2745
3288
  if (/^[A-Za-z0-9_-]{1,128}$/.test(id))
2746
3289
  await this.sessionChanges.remove(id).catch(() => { });
@@ -2790,6 +3333,8 @@ export class AppServer {
2790
3333
  throw new AppServerError('busy', 'The working tree is being switched to another branch. Try again when it finishes.');
2791
3334
  const originalRunId = identifier(params.runId, 'runId');
2792
3335
  let direction = params.direction === undefined ? undefined : text(params.direction, 'direction', MAX_TASK_CHARS);
3336
+ // A note rides on a direction the person sent; a resume without one has nothing to carry it.
3337
+ const note = direction === undefined ? undefined : noteParam(params.note);
2793
3338
  this.starting = true;
2794
3339
  const preparing = (async () => {
2795
3340
  this.assertRunning();
@@ -2852,6 +3397,12 @@ export class AppServer {
2852
3397
  const stoppedTurnAttachments = turn?.attachments?.length ? turn.attachments : undefined;
2853
3398
  if (turns[turns.length - 1] !== turn)
2854
3399
  throw new AppServerError('invalid-params', 'That attempt is no longer the newest turn in the session, so it cannot be resumed.');
3400
+ if (source.relayed === true && params.relay === undefined)
3401
+ throw new AppServerError('invalid-params', RELAYED_RESUME_NEEDS_DESKTOP);
3402
+ // A graph that came inline is not stored here: one of the same id on this machine is a different graph, or none.
3403
+ if (source.relayedGraph === true && (params.relay === null || typeof params.relay !== 'object' || params.relay.graph === undefined)) {
3404
+ throw new AppServerError('invalid-params', RELAYED_GRAPH_NEEDS_DESKTOP);
3405
+ }
2855
3406
  const rawSelection = typeof source.graphSelection === 'string' ? source.graphSelection : source.graph?.id;
2856
3407
  const graphId = rawSelection === 'software-engineer' ? 'default' : rawSelection === 'andorra' ? RETIRED_ANDORRA_SELECTION : rawSelection;
2857
3408
  if (!await claimRunResume(this.directory, originalRunId))
@@ -2875,9 +3426,11 @@ export class AppServer {
2875
3426
  ...(params.overrideAllNodes === true || carriedNodeModelOverrides === undefined ? {} : { nodeModelOverrides: carriedNodeModelOverrides }),
2876
3427
  ...(source.entryHistory === true ? { entryHistory: true } : {}),
2877
3428
  ...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
3429
+ ...(params.relay === undefined ? {} : { relay: params.relay }),
2878
3430
  ...(params.permissions === undefined ? {} : { permissions: params.permissions }),
2879
3431
  ...(sentAttachments === undefined ? {} : { attachments: sentAttachments }),
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 } : {}) });
3432
+ ...(note === undefined ? {} : { note }),
3433
+ }, { sameSession: sessionId, resumedFrom: originalRunId, ...(turn?.note ? { priorNote: turn.note } : {}), ...(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 } : {}) });
2881
3434
  }
2882
3435
  catch (error) {
2883
3436
  await releaseRunResumeClaim(this.directory, originalRunId);
@@ -2955,11 +3508,14 @@ export class AppServer {
2955
3508
  this.originalModelGraphs.set(switches, structuredClone(graph));
2956
3509
  return switches;
2957
3510
  }
2958
- async loadResumeGraph(selection, signal, overrideAllNodes, nodeModelOverrides, config) {
2959
- if (overrideAllNodes || nodeModelOverrides === undefined) {
2960
- return this.loadGraph(selection, signal, undefined, { bindProviders: !overrideAllNodes, allowDeleted: true, allowRetired: true });
2961
- }
2962
- const raw = await this.loadGraph(selection, signal, undefined, { bindProviders: false, allowDeleted: true, allowRetired: true });
3511
+ /** `source`: a relayed run's graph, already read; it is bound to `config` (the run's relayed providers) instead of being loaded. */
3512
+ async loadResumeGraph(selection, signal, overrideAllNodes, nodeModelOverrides, config, source) {
3513
+ const load = async (bindProviders) => source === undefined
3514
+ ? this.loadGraph(selection, signal, undefined, { bindProviders, allowDeleted: true, allowRetired: true })
3515
+ : bindProviders ? bindPortableGraphProviders(source, config) : structuredClone(source);
3516
+ if (overrideAllNodes || nodeModelOverrides === undefined)
3517
+ return load(!overrideAllNodes);
3518
+ const raw = await load(false);
2963
3519
  const prebound = structuredClone(raw);
2964
3520
  for (const [nodeId, pair] of Object.entries(nodeModelOverrides)) {
2965
3521
  const node = prebound.nodes[nodeId];
@@ -2978,6 +3534,9 @@ export class AppServer {
2978
3534
  ? undefined
2979
3535
  : text(params.automationContext, 'automationContext', AUTOMATION_CONTEXT_CHARS);
2980
3536
  const task = automationContext === undefined ? submitted : `${submitted}\n\n${automationContext}`;
3537
+ // Sent to the agent, kept on the turn for later turns, and never shown as part of the message (`run.note`).
3538
+ const note = noteParam(params.note);
3539
+ const turnNote = [internal?.priorNote, note].filter(Boolean).join('\n\n') || undefined;
2981
3540
  let attachments;
2982
3541
  let attachmentsFromStoppedTurn = false;
2983
3542
  try {
@@ -2992,8 +3551,12 @@ export class AppServer {
2992
3551
  catch (error) {
2993
3552
  throw new AppServerError('invalid-params', message(error));
2994
3553
  }
2995
- const config = await loadConfig(this.directory);
3554
+ // A resume may carry the graph of a run whose graph was deleted since, as a local resume may load it.
3555
+ const relay = readRelay(params.relay, { resume: internal?.resumedFrom !== undefined });
3556
+ const saved = await loadConfig(this.directory);
2996
3557
  bootMark('run.prepare.config-loaded');
3558
+ // A relayed run uses only the desktop's providers: this machine's are not consulted for it, sub-agents and overrides included.
3559
+ const config = relay === undefined ? saved : withRelayedProviders(saved, relay.providers);
2997
3560
  if (!config.providers.length)
2998
3561
  throw new AppServerError('invalid-params', 'Add a model provider in Settings before starting a task.');
2999
3562
  const providerId = params.provider === undefined ? config.provider : identifier(params.provider, 'provider');
@@ -3009,7 +3572,7 @@ export class AppServer {
3009
3572
  ? (carriedModelConfigured ? carriedModel : provider.model)
3010
3573
  : (params.model === undefined ? provider.model : text(params.model, 'model', 200));
3011
3574
  const effort = params.reasoningEffort === undefined || params.reasoningEffort === '' ? undefined : reasoningEffort(params.reasoningEffort);
3012
- if (effort !== undefined && !['openai-compatible', 'opencode-go', 'anthropic'].includes(provider.type))
3575
+ if (effort !== undefined && !supportsReasoningEffort(provider.type))
3013
3576
  throw new AppServerError('invalid-params', `The ${provider.type} provider does not support a thinking effort`);
3014
3577
  const overrideAllNodes = params.overrideAllNodes === true;
3015
3578
  const nodeModelOverrides = readNodeModelOverrides(params.nodeModelOverrides);
@@ -3023,9 +3586,10 @@ export class AppServer {
3023
3586
  const implicit = params.graph === undefined || params.graph === '';
3024
3587
  // A resumed attempt keeps the graph it stopped on, the removed Andorra preset included: its journal and
3025
3588
  // checkpoints name that graph's nodes. A new task that names the preset runs Default.
3026
- let selection = implicit ? configuredGraphSelection(config, await currentGraphSubject())
3027
- : internal?.resumedFrom !== undefined ? identifier(params.graph, 'graph') : currentGraphSelection(identifier(params.graph, 'graph'));
3028
- if (implicit && await this.selectionIsDeleted(selection))
3589
+ let selection = relay?.graph !== undefined ? relay.graph.id
3590
+ : implicit ? configuredGraphSelection(config, await currentGraphSubject())
3591
+ : internal?.resumedFrom !== undefined ? identifier(params.graph, 'graph') : currentGraphSelection(identifier(params.graph, 'graph'));
3592
+ if (relay?.graph === undefined && implicit && await this.selectionIsDeleted(selection))
3029
3593
  selection = 'default';
3030
3594
  const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
3031
3595
  if (requested) {
@@ -3066,7 +3630,8 @@ export class AppServer {
3066
3630
  const existing = await this.readSession(identifier(params.sessionId, 'sessionId'));
3067
3631
  if (resolve(existing.workspace) !== root)
3068
3632
  throw new AppServerError('invalid-params', 'That session belongs to a different project');
3069
- const { archived: _archived, autoArchived: _autoArchived, ...continued } = existing;
3633
+ // The pin belongs to the task the user pinned; its continuation is listed under it and shares its place.
3634
+ const { archived: _archived, autoArchived: _autoArchived, pinned: _pinned, ...continued } = existing;
3070
3635
  const { trajectoryId: _parentTrajectory, ...forked } = continued;
3071
3636
  if (!canExtendLineage(existing.ancestors)) {
3072
3637
  throw new AppServerError('invalid-params', 'This session has been continued too many times to keep its lineage, so it cannot be continued again. Start a new session instead.');
@@ -3085,6 +3650,22 @@ export class AppServer {
3085
3650
  const startedAt = new Date().toISOString();
3086
3651
  const accountSubject = await currentGraphSubject();
3087
3652
  const resumedFrom = internal?.resumedFrom;
3653
+ // A relayed run's graph is bound to the desktop's providers here, before it starts, so a node naming a provider the
3654
+ // desktop did not send is refused now instead of being looked up among this machine's providers.
3655
+ let relaySource;
3656
+ let relayPrepared;
3657
+ if (relay !== undefined) {
3658
+ try {
3659
+ relaySource = relay.graph ?? await this.loadGraph(selection, controller.signal, undefined, { bindProviders: false, ...(resumedFrom === undefined ? {} : { allowDeleted: true, allowRetired: true }) });
3660
+ if (resumedFrom === undefined)
3661
+ relayPrepared = this.graphForRun(await this.loadResumeGraph(selection, controller.signal, overrideAllNodes, undefined, config, relaySource), overrideAllNodes, provider.id, modelId);
3662
+ }
3663
+ catch (error) {
3664
+ if (error instanceof AppServerError)
3665
+ throw error;
3666
+ throw new AppServerError('invalid-params', message(error));
3667
+ }
3668
+ }
3088
3669
  let lineage = [];
3089
3670
  let resumeWarnings = [];
3090
3671
  const lineageJournals = new Map();
@@ -3097,7 +3678,7 @@ export class AppServer {
3097
3678
  let openingAttachments = resumedFrom === undefined ? attachments : undefined;
3098
3679
  if (resumedFrom !== undefined) {
3099
3680
  try {
3100
- const graph = resumedGraph = this.graphForRun(await this.loadResumeGraph(selection, controller.signal, overrideAllNodes, nodeModelOverrides, config), overrideAllNodes, provider.id, modelId, nodeModelOverrides);
3681
+ const graph = resumedGraph = this.graphForRun(await this.loadResumeGraph(selection, controller.signal, overrideAllNodes, nodeModelOverrides, config, relaySource), overrideAllNodes, provider.id, modelId, nodeModelOverrides);
3101
3682
  const chain = [];
3102
3683
  const visited = new Set();
3103
3684
  let lineageToolCalls = 0;
@@ -3144,8 +3725,9 @@ export class AppServer {
3144
3725
  }
3145
3726
  lineage = [...chain];
3146
3727
  if (internal?.freshAllowance === true) {
3728
+ const loopAttempts = internal.wake === undefined;
3147
3729
  for (const [nodeId, checkpoint] of collected)
3148
- collected.set(nodeId, { ...checkpoint, state: freshAllowance(checkpoint.state) });
3730
+ collected.set(nodeId, { ...checkpoint, state: freshAllowance(checkpoint.state, loopAttempts) });
3149
3731
  }
3150
3732
  if (internal?.compact === true) {
3151
3733
  for (const [nodeId, checkpoint] of collected)
@@ -3404,7 +3986,7 @@ export class AppServer {
3404
3986
  }
3405
3987
  const wake = internal?.wake !== undefined && (internal.resumedFrom === undefined || resumedDirection !== undefined) ? internal.wake : undefined;
3406
3988
  const directionNode = wake !== undefined && resumedDirection !== undefined ? internal?.wakeNode : undefined;
3407
- const marker = { task, completion: { summary: RUNNING_TURN_SUMMARY, tests: [], status: 'running' }, runId, ...(internal?.resumedFrom === undefined ? {} : { resumed: true }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(wake === undefined ? {} : { wake }) };
3989
+ const marker = { task, ...(turnNote === undefined ? {} : { note: turnNote }), completion: { summary: RUNNING_TURN_SUMMARY, tests: [], status: 'running' }, runId, ...(internal?.resumedFrom === undefined ? {} : { resumed: true }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(wake === undefined ? {} : { wake }) };
3408
3990
  record = {
3409
3991
  ...record,
3410
3992
  history: [...(record.history ?? []), marker],
@@ -3420,6 +4002,9 @@ export class AppServer {
3420
4002
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
3421
4003
  ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }),
3422
4004
  ...(entryHistory ? { entryHistory: true } : {}),
4005
+ // Only the fact is kept: the desktop's provider list never reaches this machine's disk.
4006
+ ...(relay === undefined ? {} : { relayed: true }),
4007
+ ...(relay?.graph === undefined ? {} : { relayedGraph: true }),
3423
4008
  ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }),
3424
4009
  ...(resumedDirection === undefined ? {} : { direction: resumedDirection }),
3425
4010
  ...(wake === undefined ? {} : { wake }),
@@ -3466,7 +4051,7 @@ export class AppServer {
3466
4051
  permissionControl.yolo = effective === 'full-access';
3467
4052
  this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, subagents: new Set(), steersClosed: false,
3468
4053
  permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
3469
- codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }) };
4054
+ codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
3470
4055
  {
3471
4056
  const continues = new Set([runId, ...lineage]);
3472
4057
  for (const timer of this.timers.list(record.id)) {
@@ -3483,9 +4068,10 @@ export class AppServer {
3483
4068
  }
3484
4069
  if (params.sessionId === undefined)
3485
4070
  this.titleSessionFromPrompt(record, task, provider, modelId, runId);
4071
+ const preparedGraph = resumedGraph ?? relayPrepared;
3486
4072
  const invocationText = internal?.resumedFrom === undefined ? task
3487
4073
  : internal.recoveredDirection === true || internal.wake !== undefined ? undefined : internal.direction;
3488
- const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(internal?.startNode === undefined ? {} : { startNode: internal.startNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(resumedGraph === undefined ? {} : { prepared: resumedGraph }) })
4074
+ const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, ...(note === undefined ? {} : { note }), ...(turnNote === undefined ? {} : { turnNote }), selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(internal?.startNode === undefined ? {} : { startNode: internal.startNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(preparedGraph === undefined ? {} : { prepared: preparedGraph }), ...(relay === undefined ? {} : { relayProviders: relay.providers }), ...(relay?.graph === undefined ? {} : { relayedGraph: true }) })
3489
4075
  .catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
3490
4076
  this.runTask = runTask;
3491
4077
  runTask.finally(() => {
@@ -3552,7 +4138,7 @@ export class AppServer {
3552
4138
  this.sessionTitles.clear();
3553
4139
  }
3554
4140
  async executeRun(input) {
3555
- const { runId, startedAt, telemetryRunId, accountSubject, task, selection, providerId, modelId, root, permissions, liveSteers, boundPermissions, reasoningEffort, overrideAllNodes = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, entryHistory = false, runInput, runState, automationContext, direction, wake, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, directionNode, startNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
4141
+ const { runId, startedAt, telemetryRunId, accountSubject, task, note, turnNote, selection, providerId, modelId, root, permissions, liveSteers, boundPermissions, reasoningEffort, overrideAllNodes = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, entryHistory = false, runInput, runState, automationContext, direction, wake, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, directionNode, startNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
3556
4142
  const signal = controller.signal;
3557
4143
  const panelHold = createPanelBrowserHold(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined);
3558
4144
  const liveRun = this.run?.runId === runId ? this.run : undefined;
@@ -3614,7 +4200,7 @@ export class AppServer {
3614
4200
  if (direction !== undefined) {
3615
4201
  const refs = attachments?.refs ?? [];
3616
4202
  const images = attachments?.images ?? [];
3617
- const said = wakeMessageText(wake, direction);
4203
+ const said = `${wakeMessageText(wake, direction)}${note ? `\n\n${note}` : ''}`;
3618
4204
  arm(wake === undefined ? undefined : directionNode, { ...(ownDirectionId === undefined ? {} : { id: ownDirectionId }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
3619
4205
  }
3620
4206
  const steering = armed.length === 0 ? undefined : armed;
@@ -3677,7 +4263,8 @@ export class AppServer {
3677
4263
  };
3678
4264
  const wakesArmed = [];
3679
4265
  try {
3680
- const config = await loadConfig(this.directory);
4266
+ const saved = await loadConfig(this.directory);
4267
+ const config = input.relayProviders === undefined ? saved : withRelayedProviders(saved, input.relayProviders);
3681
4268
  bootMark('run.exec.config-loaded');
3682
4269
  runConfig = config;
3683
4270
  if (archive.length === 0)
@@ -3819,6 +4406,7 @@ export class AppServer {
3819
4406
  ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
3820
4407
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
3821
4408
  ...(panelBrowserRelay ? { panelBrowserRelay: true } : {}),
4409
+ ...(input.relayProviders === undefined ? {} : { relayed: true }),
3822
4410
  ...(runInput === undefined ? {} : { input: runInput }),
3823
4411
  ...(runState === undefined ? {} : { state: runState }) };
3824
4412
  if (liveRun)
@@ -3874,7 +4462,7 @@ export class AppServer {
3874
4462
  await healthGate;
3875
4463
  runGoal = input.record.goal?.status === 'active' ? input.record.goal : undefined;
3876
4464
  const options = {
3877
- task, runId, provider: provider.id, model: snapshot.model, adapter: watchAndorra(provider.type, this.tracedAdapter(this.reasoningAdapter(createAdapter(snapshot, { sessionId: input.record.id })), provider.id)),
4465
+ task: note && direction === undefined ? `${task}\n\n${note}` : task, runId, provider: provider.id, model: snapshot.model, adapter: watchAndorra(provider.type, this.tracedAdapter(this.reasoningAdapter(this.adapterFor(snapshot, { sessionId: input.record.id, runId })), provider.id)),
3878
4466
  ...(openingAttachments === undefined ? {} : { attachments: openingAttachments }),
3879
4467
  ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }),
3880
4468
  tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined, panelHold),
@@ -3926,7 +4514,7 @@ export class AppServer {
3926
4514
  goalVerified = event.data.passed === true;
3927
4515
  if (event.type === 'dashboard.model.completed' && typeof event.data.provider === 'string' && typeof event.data.model === 'string') {
3928
4516
  const answered = config.providers.find(item => item.id === event.data.provider);
3929
- if (answered)
4517
+ if (answered && answered.type !== 'relayed')
3930
4518
  this.modelHealth.add(answered, event.data.model);
3931
4519
  }
3932
4520
  if ((event.type === 'subagent.started' || event.type === 'subagent.completed') && typeof event.data.subagentId === 'string') {
@@ -3960,8 +4548,11 @@ export class AppServer {
3960
4548
  }
3961
4549
  const created = pullRequestDetector.observe(event);
3962
4550
  const attachingNode = typeof event.data?.nodeId === 'string' && event.data.nodeId ? event.data.nodeId : undefined;
3963
- if (created)
3964
- void this.attachPullRequest(input.record.id, created, {}, wakeCarry, attachingNode === undefined ? undefined : { runId, nodeId: attachingNode }).catch(error => this.log('warn', `Could not attach ${created.url}: ${message(error)}`));
4551
+ if (created) {
4552
+ void this.attachPullRequest(input.record.id, created, {}, wakeCarry, attachingNode === undefined ? undefined : { runId, nodeId: attachingNode })
4553
+ .then(attached => this.reviewNewPullRequest(input.record.id, attached))
4554
+ .catch(error => this.log('warn', `Could not attach ${created.url}: ${message(error)}`));
4555
+ }
3965
4556
  },
3966
4557
  onUsage: (delta, origin) => {
3967
4558
  foldUsage(runUsage, delta);
@@ -4012,6 +4603,7 @@ export class AppServer {
4012
4603
  },
4013
4604
  ...(resumeFrom === undefined ? {} : { resumeFrom }),
4014
4605
  ...(lineageArtifacts === undefined ? {} : { artifactStore: lineageArtifacts }),
4606
+ reviewNode: this.reviewNodeService(input.record.id, runId, input.resumedFrom, () => liveSteers.filter(entry => entry.wake === undefined && entry.subagentId === undefined).map(entry => entry.id)),
4015
4607
  };
4016
4608
  bootMark('run.exec.options-built');
4017
4609
  this.emit('run.state', { runId, state: 'running' });
@@ -4024,6 +4616,10 @@ export class AppServer {
4024
4616
  finally {
4025
4617
  panelHold.stop();
4026
4618
  healthAbort.abort();
4619
+ // A loop this run's graph drove ends with the run, first, so no later step's failure leaves it running. An engine
4620
+ // that is closing leaves it for the run's resume.
4621
+ if (!this.closed)
4622
+ void endGraphLoops(this.directory, input.record.id, runId, this.reviewLoop).catch(error => this.log('warn', `Could not end the Andorra review loop of run ${runId}: ${message(error)}`));
4027
4623
  await healthSettled;
4028
4624
  // However the run ended, a run that spent from the hosted allowance asks for the new figure; never awaited.
4029
4625
  if (askedAndorra && process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed)
@@ -4082,11 +4678,11 @@ export class AppServer {
4082
4678
  }
4083
4679
  // A message read by a subagent keeps its recipient in the record and stays out of the history later
4084
4680
  // tasks are given: it was an instruction for that subagent's work, not for the run's own agent.
4085
- const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }),
4681
+ const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.note ? { note: entry.note } : {}), ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }),
4086
4682
  ...(entry.subagentId === undefined ? {} : { subagentId: entry.subagentId }) }));
4087
4683
  const contextSteers = steers.filter(steer => steer.subagentId === undefined);
4088
- archive.push({ task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) });
4089
- history = [...history, { task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(contextSteers.length ? { steers: contextSteers } : {}), ...(wake === undefined ? {} : { wake }) }].slice(-SESSION_HISTORY_TURNS);
4684
+ archive.push({ task, ...(turnNote === undefined ? {} : { note: turnNote }), completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) });
4685
+ history = [...history, { task, ...(turnNote === undefined ? {} : { note: turnNote }), completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(contextSteers.length ? { steers: contextSteers } : {}), ...(wake === undefined ? {} : { wake }) }].slice(-SESSION_HISTORY_TURNS);
4090
4686
  const record = { ...input.record, history: archive, contextHistory: history, updatedAt: new Date().toISOString(), usage,
4091
4687
  ...(result ? { widgets: result.widgets } : {}),
4092
4688
  context: contextUsedTokens > 0 ? { usedTokens: contextUsedTokens, ...(contextWindow === undefined ? {} : { window: contextWindow }),
@@ -4116,6 +4712,8 @@ export class AppServer {
4116
4712
  ...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
4117
4713
  ? { nodeModelOverrides: liveNodeOverrides } : {}),
4118
4714
  ...(entryHistory ? { entryHistory: true } : {}),
4715
+ ...(input.relayProviders === undefined ? {} : { relayed: true }),
4716
+ ...(input.relayedGraph ? { relayedGraph: true } : {}),
4119
4717
  ...(direction === undefined ? {} : { direction }),
4120
4718
  ...(wake === undefined ? {} : { wake }),
4121
4719
  ...(directionNode === undefined ? {} : { directionNode }),
@@ -4168,7 +4766,7 @@ export class AppServer {
4168
4766
  ? { ...result, status: 'interrupted', reason: APP_CLOSED_REASON }
4169
4767
  : result;
4170
4768
  const undelivered = undeliveredSteers.length
4171
- ? { undeliveredSteers: undeliveredSteers.map(entry => ({ id: entry.id, text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}) })) }
4769
+ ? { undeliveredSteers: undeliveredSteers.map(entry => ({ id: entry.id, text: entry.text, ...(entry.note ? { note: entry.note } : {}), ...(entry.refs?.length ? { attachments: entry.refs } : {}) })) }
4172
4770
  : {};
4173
4771
  if (result)
4174
4772
  this.emit('run.completed', { runId, sessionId: record.id, result: eventResult, session: this.terminalSummary(snapshot), ...undelivered });
@@ -4185,6 +4783,7 @@ export class AppServer {
4185
4783
  }
4186
4784
  await clearOpenRunClaim(this.directory, runId);
4187
4785
  releaseProcessWorkspace(root, runId);
4786
+ this.modelRelay.endRun(runId);
4188
4787
  if (this.run?.runId === runId)
4189
4788
  this.run = undefined;
4190
4789
  if (this.finishingRunId === runId) {
@@ -4192,6 +4791,8 @@ export class AppServer {
4192
4791
  this.finishingSessionId = undefined;
4193
4792
  }
4194
4793
  this.journals.delete(runId);
4794
+ // The run's claim is cleared: the review loop may start a round now, or see the fixer's turn end.
4795
+ this.reviewLoop.runEnded(record.id, runId, wake);
4195
4796
  if (unsaved !== undefined) {
4196
4797
  for (const id of wakesArmed) {
4197
4798
  this.timers.cancel(id);
@@ -4233,7 +4834,8 @@ export class AppServer {
4233
4834
  if (scopedNode === undefined && typeof params.overrideAllNodes !== 'boolean')
4234
4835
  throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
4235
4836
  const generation = run.modelChangeGeneration = (run.modelChangeGeneration ?? 0) + 1;
4236
- const config = await loadConfig(this.directory);
4837
+ const saved = await loadConfig(this.directory);
4838
+ const config = run.relayProviders === undefined ? saved : withRelayedProviders(saved, run.relayProviders);
4237
4839
  if (!config.providers.some(item => item.id === provider))
4238
4840
  throw new AppServerError('invalid-params', `Unknown provider: ${provider}`);
4239
4841
  await this.resolveModel(config, provider, model, run.controller.signal);
@@ -4276,7 +4878,7 @@ export class AppServer {
4276
4878
  else
4277
4879
  delete existing.overrideAllNodes;
4278
4880
  delete existing.nodeModelOverrides;
4279
- if (!['openai-compatible', 'opencode-go', 'anthropic'].includes(config.providers.find(item => item.id === provider)?.type ?? ''))
4881
+ if (!supportsReasoningEffort(config.providers.find(item => item.id === provider)?.type ?? ''))
4280
4882
  delete existing.reasoningEffort;
4281
4883
  }
4282
4884
  await writeOpenRunRecord(this.directory, existing);
@@ -4474,7 +5076,7 @@ export class AppServer {
4474
5076
  const resolved = await resolveModelContext(provider, model || provider.model, signal);
4475
5077
  if (reasoningEffort !== undefined)
4476
5078
  resolved.reasoningEffort = reasoningEffort;
4477
- return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(resolved, { sessionId })), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
5079
+ return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(this.adapterFor(resolved, { sessionId })), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
4478
5080
  }
4479
5081
  async analyticsConfigView(config) {
4480
5082
  try {
@@ -4490,7 +5092,7 @@ export class AppServer {
4490
5092
  const provider = config.providers.find(item => item.id === id);
4491
5093
  if (!provider)
4492
5094
  throw new Error(`Unknown provider: ${id}. Add it in Settings, then retry.`);
4493
- return { model: provider.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(provider, { sessionId })), id), ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }), providerType: provider.type, baseUrl: provider.baseUrl };
5095
+ return { model: provider.model, adapter: this.tracedAdapter(this.reasoningAdapter(this.adapterFor(provider, { sessionId })), id), ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }), providerType: provider.type, baseUrl: provider.baseUrl };
4494
5096
  }
4495
5097
  codeIntelligence(root, permissions, signal, options = {}) {
4496
5098
  const opened = this.codeIntelOpening.then(() => options.onlyWhileIdle && (this.run !== undefined || this.starting)
@@ -4612,7 +5214,7 @@ export class AppServer {
4612
5214
  await removePendingAgentInteraction(this.directory, runId, id)
4613
5215
  .catch(error => this.log('warn', 'Could not clear pending approval: ' + message(error)));
4614
5216
  if (this.pending.size === 0)
4615
- this.emit('run.state', { runId, state: 'running' });
5217
+ this.emit('run.state', { runId, state: this.modelRelay.awaiting(runId) ? 'awaiting-desktop' : 'running' });
4616
5218
  }
4617
5219
  if (answer === 'policy-changed')
4618
5220
  return 'policy-changed';
@@ -4638,7 +5240,7 @@ export class AppServer {
4638
5240
  await removePendingAgentInteraction(this.directory, runId, id)
4639
5241
  .catch(error => this.log('warn', 'Could not clear pending question: ' + message(error)));
4640
5242
  if (this.pending.size === 0)
4641
- this.emit('run.state', { runId, state: 'running' });
5243
+ this.emit('run.state', { runId, state: this.modelRelay.awaiting(runId) ? 'awaiting-desktop' : 'running' });
4642
5244
  }
4643
5245
  }
4644
5246
  settleApproval(params) {
@@ -4649,6 +5251,50 @@ export class AppServer {
4649
5251
  settle(params.policyChanged === true ? 'policy-changed' : params.approved === true ? 'approve' : 'deny');
4650
5252
  return { ok: true };
4651
5253
  }
5254
+ /**
5255
+ * The adapter a run talks to. A relayed provider's model is on the desktop, so its requests go through the model
5256
+ * relay as `runId`'s (the live run's when none is given, read when the request is made).
5257
+ */
5258
+ adapterFor(provider, options) {
5259
+ if (provider.type !== 'relayed')
5260
+ return createAdapter(provider, options.sessionId === undefined ? {} : { sessionId: options.sessionId });
5261
+ return { generate: request => {
5262
+ const runId = options.runId ?? this.run?.runId;
5263
+ if (runId === undefined)
5264
+ return Promise.reject(new Error('A relayed provider needs a run.'));
5265
+ return this.modelRelay.adapter(provider, runId, options.sessionId).generate(request);
5266
+ } };
5267
+ }
5268
+ /** The id, run and claimant of a model.relay call; the claimant is the connection the desktop's engine speaks through. */
5269
+ relayCall(params) {
5270
+ // The engine pool sets `claimant` to the caller's own connection, replacing anything the caller sent.
5271
+ return { id: text(params.id, 'id', 128), runId: text(params.runId, 'runId', 128), claimant: text(params.claimant, 'claimant', 256) };
5272
+ }
5273
+ relayProgress(params) {
5274
+ const call = this.relayCall(params);
5275
+ const kind = params.kind;
5276
+ if (kind !== 'alive' && kind !== 'request' && kind !== 'reasoning' && kind !== 'retry' && kind !== 'recovered-error')
5277
+ throw new AppServerError('invalid-params', 'kind must be alive, request, reasoning, retry or recovered-error.');
5278
+ if (kind === 'recovered-error' && (typeof params.code !== 'string' || !RELAY_FAILURE_CODE.test(params.code)))
5279
+ throw new AppServerError('invalid-params', 'A recovered-error progress carries its code.');
5280
+ const retry = params.retry;
5281
+ const validRetry = retry !== null && typeof retry === 'object' && !Array.isArray(retry)
5282
+ && Number.isSafeInteger(retry.retry) && Number.isSafeInteger(retry.maxRetries)
5283
+ && typeof retry.delayMs === 'number' && typeof retry.reason === 'string';
5284
+ if (kind === 'retry' && !validRetry)
5285
+ throw new AppServerError('invalid-params', 'A retry progress carries the retry it reports.');
5286
+ if (kind === 'reasoning' && typeof params.delta !== 'string')
5287
+ throw new AppServerError('invalid-params', 'A reasoning progress carries its delta.');
5288
+ return this.modelRelay.progress({ ...call, kind, ...(typeof params.delta === 'string' ? { delta: params.delta } : {}), ...(kind === 'retry' ? { retry: retry } : {}),
5289
+ ...(kind === 'recovered-error' ? { code: params.code } : {}) });
5290
+ }
5291
+ relayResult(params) {
5292
+ const call = this.relayCall(params);
5293
+ if (typeof params.ok !== 'boolean')
5294
+ throw new AppServerError('invalid-params', 'ok must be a boolean.');
5295
+ const error = readRelayFailure(params.error);
5296
+ return this.modelRelay.result({ ...call, ok: params.ok, ...(params.response === undefined ? {} : { response: params.response }), ...(error === undefined ? {} : { error }) });
5297
+ }
4652
5298
  panelBrowserRelayFor(sessionId) {
4653
5299
  return (operation, args, signal, timeoutMs = 40_000) => new Promise(resolve => {
4654
5300
  const id = randomUUID();
@@ -4703,6 +5349,7 @@ export class AppServer {
4703
5349
  async steerRun(params) {
4704
5350
  const runId = text(params.runId, 'runId', 200);
4705
5351
  const content = text(params.text, 'text', MAX_TASK_CHARS);
5352
+ const note = noteParam(params.note);
4706
5353
  const live = this.run;
4707
5354
  if (live === undefined || live.runId !== runId) {
4708
5355
  throw new AppServerError('not-found', 'That task is not running on this engine. Send the message as a new task.');
@@ -4734,7 +5381,8 @@ export class AppServer {
4734
5381
  const entry = {
4735
5382
  id: `${runId}#steer-${randomUUID()}`,
4736
5383
  text: content,
4737
- content: refs.length ? `${content}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: (resolved?.images.length ?? 0) > 0 })}` : content,
5384
+ content: `${content}${note ? `\n\n${note}` : ''}${refs.length ? `\n\n${attachmentReferenceBlock(refs, { imagesIncluded: (resolved?.images.length ?? 0) > 0 })}` : ''}`,
5385
+ ...(note ? { note } : {}),
4738
5386
  images: resolved?.images ?? [],
4739
5387
  ...(refs.length ? { refs } : {}),
4740
5388
  ...(roots.length ? { roots } : {}),
@@ -4979,448 +5627,1055 @@ export class AppServer {
4979
5627
  await editor.close().catch(() => { });
4980
5628
  return { closed: true };
4981
5629
  }
4982
- serializeRemote(operation) {
4983
- const next = this.remoteOps.then(operation, operation);
4984
- this.remoteOps = next.then(() => undefined, () => undefined);
4985
- return next;
5630
+ /** The one relay link this engine uses for every machine, created on first use and disposed in `close`. */
5631
+ relayLink() {
5632
+ if (this.closed)
5633
+ throw new AppServerError('cancelled', 'The engine is shutting down.');
5634
+ this.relay ??= this.environmentOptions.relayLink?.() ?? new RelayLink({ relayUrl: relayUrlFromEnvironment(), token: () => this.environmentAccessToken(), version: () => this.version() });
5635
+ return this.relay;
4986
5636
  }
4987
- startRemoteServe() {
4988
- return this.serializeRemote(async () => {
4989
- const { ensureRemoteServe } = await import('./remote/serve.js');
4990
- const outcome = await ensureRemoteServe({ directory: this.directory, owner: 'engine', version: await this.version() });
4991
- this.remoteServe = Promise.resolve(outcome);
4992
- });
5637
+ environmentAccessToken() {
5638
+ return this.environmentOptions.accessToken?.() ?? defaultEnvironmentAccessToken();
5639
+ }
5640
+ environmentControl() {
5641
+ if (this.environmentOptions.control)
5642
+ return this.environmentOptions.control;
5643
+ const base = AUTH_DEPLOYMENT.apiBaseUrl;
5644
+ return {
5645
+ list: token => listEnvironments(base, token),
5646
+ claim: (token, code, name) => claimEnvironment(base, token, code, name),
5647
+ rename: (token, id, name) => renameEnvironment(base, token, id, name),
5648
+ remove: (token, id) => removeEnvironment(base, token, id),
5649
+ cloudGet: token => cloudGet(base, token),
5650
+ cloudStart: (token, version) => cloudStart(base, token, version),
5651
+ cloudStop: token => cloudStop(base, token),
5652
+ cloudDelete: (token, environmentId) => cloudDelete(base, token, environmentId),
5653
+ };
4993
5654
  }
4994
- remoteError(error) {
5655
+ environmentError(error) {
4995
5656
  if (error instanceof AppServerError)
4996
5657
  return error;
4997
- if (error instanceof RemotePeerError) {
4998
- if (error.kind === 'identity' || error.kind === 'unauthorized')
4999
- return new AppServerError('auth', error.message);
5000
- if (error.kind === 'rejected')
5001
- return new AppServerError('remote', error.message);
5002
- return new AppServerError('network', error.message);
5658
+ if (error instanceof ControlError) {
5659
+ switch (error.code) {
5660
+ case 'unauthorized': return new AppServerError('login-required', SIGN_IN_FOR_ENVIRONMENTS);
5661
+ case 'code_unknown': return new AppServerError('invalid-params', 'That code was not recognised. Check it and try again.');
5662
+ case 'code_expired': return new AppServerError('invalid-params', `That code expired. Run ${bridgeCommand('link', false)} or ${bridgeCommand('link', true)} again on the machine.`);
5663
+ case 'code_used': return new AppServerError('invalid-params', 'That code was already used.');
5664
+ case 'environment_limit': return new AppServerError('invalid-params', 'You have linked the most machines allowed (10). Remove one first.');
5665
+ case 'invalid_name': return new AppServerError('invalid-params', MACHINE_NAME_RULE);
5666
+ case 'not_found': return new AppServerError('not-found', 'That machine is not linked to your account.');
5667
+ case 'cloud_not_enabled': return new AppServerError('forbidden', 'Cloud is not available for your account yet.');
5668
+ case 'cloud_environment': return new AppServerError('invalid-params', 'Delete Cloud from Settings → Environments.');
5669
+ case 'invalid_version': return new AppServerError('invalid-params', 'This version of Andorra Code cannot start Cloud. Update Andorra Code and try again.');
5670
+ case 'stopping': return new AppServerError('busy', 'Cloud is still stopping. Try again in a moment.');
5671
+ case 'network': return new AppServerError('network', error.message);
5672
+ default: return new AppServerError('remote', error.message);
5673
+ }
5003
5674
  }
5004
5675
  return new AppServerError('remote', message(error));
5005
5676
  }
5006
- remoteStatusFailure(error) {
5007
- if (error instanceof RemotePeerError) {
5008
- if (error.kind === 'identity')
5009
- return { status: 'identity-changed', statusDetail: error.message };
5010
- if (error.kind === 'unauthorized')
5011
- return { status: 'unauthorized', statusDetail: error.message };
5012
- if (error.kind === 'offline')
5013
- return { status: 'offline', statusDetail: error.message };
5677
+ async onlineEnvironments() {
5678
+ // Presence is a convenience: an unreachable relay lists every machine as offline rather than failing the list.
5679
+ return new Set(await this.relayLink().presence().catch(() => []));
5680
+ }
5681
+ async environmentsList() {
5682
+ const generation = this.accountGeneration;
5683
+ const token = await this.environmentAccessToken();
5684
+ const records = await this.environmentControl().list(token).catch((error) => { throw this.environmentError(error); });
5685
+ if (generation === this.accountGeneration) {
5686
+ // Cloud's item is missing from the list until its machine boots, and again while a start relaunches it, so only
5687
+ // Cloud's own answers (state none) and a change of account forget the id.
5688
+ const listedCloud = records.find(record => record.kind === 'cloud')?.id;
5689
+ if (listedCloud !== undefined)
5690
+ this.cloudEnvironmentId = listedCloud;
5691
+ this.environmentIds = { ids: new Set(records.map(record => record.id)), at: Date.now() };
5692
+ this.environmentIdsFailure = undefined;
5693
+ this.syncModelRelayLinks();
5694
+ }
5695
+ // An account with no machines has nothing to be online: do not open a relay socket just to ask.
5696
+ if (records.length === 0)
5697
+ return { environments: [] };
5698
+ const online = await this.onlineEnvironments();
5699
+ return { environments: records.map(record => ({ ...record, online: online.has(record.id) })) };
5700
+ }
5701
+ async environmentClaim(params) {
5702
+ const code = typeof params.code === 'string' ? params.code.trim() : '';
5703
+ if (!code || code.length > 64)
5704
+ throw new AppServerError('invalid-params', `Enter the code that ${bridgeCommand('link', false)} or ${bridgeCommand('link', true)} showed on the machine.`);
5705
+ const name = machineName(params.name);
5706
+ const token = await this.environmentAccessToken();
5707
+ const record = await this.environmentControl().claim(token, code, name).catch((error) => { throw this.environmentError(error); });
5708
+ this.environmentIds = undefined;
5709
+ this.environmentIdsFailure = undefined;
5710
+ return { environment: { ...record, online: (await this.onlineEnvironments()).has(record.id) } };
5711
+ }
5712
+ async environmentRename(params) {
5713
+ const id = environmentId(params.id);
5714
+ const name = machineName(params.name);
5715
+ const token = await this.environmentAccessToken();
5716
+ const record = await this.environmentControl().rename(token, id, name).catch((error) => { throw this.environmentError(error); });
5717
+ this.environmentIdsFailure = undefined;
5718
+ return { environment: { ...record, online: (await this.onlineEnvironments()).has(record.id) } };
5719
+ }
5720
+ async environmentCloud(method, params) {
5721
+ const only = method === 'environments.cloud.delete' ? cloudEnvironmentId(params.environmentId) : undefined;
5722
+ const generation = this.accountGeneration;
5723
+ const token = await this.environmentAccessToken();
5724
+ const control = this.environmentControl();
5725
+ const version = await this.version();
5726
+ // The token was read for the account that was signed in when the call began; a start retried after a switch must
5727
+ // not start the new account's Cloud.
5728
+ if (generation !== this.accountGeneration)
5729
+ throw new AppServerError('cancelled', 'The Andorra account changed.');
5730
+ if (method === 'environments.cloud.start' && !RELEASE_VERSION.test(version)) {
5731
+ throw new AppServerError('invalid-params', 'This build of Andorra Code cannot start Cloud. Install a released version.');
5732
+ }
5733
+ const view = (status, remember = true) => this.cloudView(status, version, remember && generation === this.accountGeneration);
5734
+ try {
5735
+ const status = await (method === 'environments.cloud.get' ? control.cloudGet(token)
5736
+ : method === 'environments.cloud.start' ? control.cloudStart(token, version)
5737
+ : method === 'environments.cloud.stop' ? control.cloudStop(token)
5738
+ : control.cloudDelete(token, only));
5739
+ return view(status);
5014
5740
  }
5015
- return { status: 'unknown', statusDetail: message(error) };
5016
- }
5017
- async peerCall(target, hosts, call, options = {}) {
5018
- let last;
5019
- for (const host of hosts) {
5741
+ catch (error) {
5742
+ if (method === 'environments.cloud.start' && error instanceof ControlError && error.code === 'no_capacity') {
5743
+ return view({ state: 'none', enabled: true, error: 'no_capacity' }, false);
5744
+ }
5745
+ throw this.environmentError(error);
5746
+ }
5747
+ }
5748
+ cloudView(status, engineVersion, remember) {
5749
+ if (remember)
5750
+ this.cloudEnvironmentId = status.state === 'none' ? undefined : status.environmentId ?? this.cloudEnvironmentId;
5751
+ const { version, ...rest } = status;
5752
+ return { ...rest, outdated: (status.state === 'starting' || status.state === 'running') && version !== undefined && version !== engineVersion };
5753
+ }
5754
+ async environmentRemove(params) {
5755
+ const id = environmentId(params.id);
5756
+ if (id === this.cloudEnvironmentId)
5757
+ throw new AppServerError('invalid-params', 'Delete Cloud from Settings \u2192 Environments.');
5758
+ // Refused before anything is awaited, so a request that arrives while the machine is removed is never claimed.
5759
+ const revokedBefore = this.modelRelayRevoked.has(id);
5760
+ this.modelRelayRevoked.add(id);
5761
+ this.localRelay.dropEnvironment(id);
5762
+ this.modelRelayRemoving.set(id, (this.modelRelayRemoving.get(id) ?? 0) + 1);
5763
+ try {
5020
5764
  try {
5021
- return await call(host);
5765
+ const token = await this.environmentAccessToken();
5766
+ await this.environmentControl().remove(token, id).catch((error) => { throw this.environmentError(error); });
5022
5767
  }
5023
5768
  catch (error) {
5024
- if (error instanceof RemotePeerError && (error.kind === 'offline' || error.kind === 'network')) {
5025
- last = error;
5026
- continue;
5027
- }
5028
- throw options.preservePeerError && error instanceof RemotePeerError ? error : this.remoteError(error);
5769
+ // Still linked: the machine keeps the permission it had.
5770
+ if (!revokedBefore)
5771
+ this.modelRelayRevoked.delete(id);
5772
+ throw error;
5773
+ }
5774
+ this.environmentIds = undefined;
5775
+ this.environmentIdsFailure = undefined;
5776
+ this.modelRelayUnsaved.delete(id);
5777
+ const own = this.modelRelayLinks.get(id);
5778
+ if (own)
5779
+ this.dropEngineLink(id, own);
5780
+ this.forgetUnsavedRuns(id);
5781
+ for (const key of [...this.modelRelayMissing.keys()])
5782
+ if (key.endsWith(`\u0000${id}`))
5783
+ this.modelRelayMissing.delete(key);
5784
+ await this.modelRelayRuns.forget(id).catch(error => this.log('warn', `Could not forget the tasks removed machine ${id} ran on this computer's models: ${message(error)}`));
5785
+ try {
5786
+ await this.forgetModelRelayEnvironment(id);
5787
+ }
5788
+ catch (error) {
5789
+ // The machine is gone from the account and refused here; only the file still names it. Saved again later, so a
5790
+ // restart in between is the one way it comes back, and then only until the account's list is read.
5791
+ this.log('warn', `Could not save that removed machine ${id} may no longer use this computer's models; trying again in 30 s: ${message(error)}`);
5792
+ this.retryModelRelaySave(() => this.forgetModelRelayEnvironment(id, () => this.modelRelayRevoked.has(id)));
5029
5793
  }
5030
5794
  }
5031
- if (last === undefined)
5032
- throw new AppServerError('network', `Could not reach ${target.host}:${target.port}.`);
5033
- throw options.preservePeerError && last instanceof RemotePeerError ? last : this.remoteError(last);
5034
- }
5035
- async remoteTarget(params) {
5036
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
5037
- const config = await loadConfig(this.directory);
5038
- const workspace = (config.remote?.workspaces ?? []).find(entry => entry.id === workspaceId);
5039
- if (!workspace)
5040
- throw new AppServerError('not-found', 'No paired workspace has that id.');
5041
- const hosts = [...(workspace.host !== undefined ? [workspace.host] : []), ...workspace.hosts].filter((entry, index, list) => list.indexOf(entry) === index);
5042
- const target = {
5043
- host: hosts[0] ?? '',
5044
- port: workspace.port,
5045
- transport: workspace.transport,
5046
- fingerprint: workspace.fingerprint,
5047
- ...(workspace.certPem !== undefined ? { certPem: workspace.certPem } : {}),
5048
- ...(workspace.token !== undefined ? { token: workspace.token } : {}),
5049
- };
5050
- if (!hosts.length)
5051
- throw new AppServerError('remote', 'That workspace has no host to contact.');
5052
- return { workspace, target, hosts };
5053
- }
5054
- remoteWorkspaceView(workspace, probe) {
5055
- const cached = {
5056
- ...(workspace.hostname !== undefined ? { hostname: workspace.hostname } : {}),
5057
- ...(workspace.platform !== undefined ? { platform: workspace.platform } : {}),
5058
- ...(workspace.version !== undefined ? { version: workspace.version } : {}),
5059
- };
5060
- const live = {
5061
- ...(probe.hostname !== undefined ? { hostname: probe.hostname } : {}),
5062
- ...(probe.platform !== undefined ? { platform: probe.platform } : {}),
5063
- ...(probe.version !== undefined ? { version: probe.version } : {}),
5064
- };
5065
- return {
5066
- id: workspace.id,
5067
- nickname: workspace.nickname,
5068
- host: workspace.host ?? workspace.hosts[0] ?? '',
5069
- hosts: workspace.hosts,
5070
- port: workspace.port,
5071
- transport: workspace.transport,
5072
- fingerprint: workspace.fingerprint,
5073
- ...cached,
5074
- ...live,
5075
- addedAt: workspace.addedAt,
5076
- status: probe.status,
5077
- grant: probe.grant ?? 'browse',
5078
- ...(probe.relay !== undefined ? { relay: probe.relay } : {}),
5079
- ...(probe.statusDetail !== undefined ? { statusDetail: probe.statusDetail } : {}),
5080
- };
5081
- }
5082
- async remoteHostingStatus() {
5083
- return this.serializeRemote(async () => {
5084
- const { remoteHostingStatus } = await import('./remote/serve.js');
5085
- const snapshot = await remoteHostingStatus({ directory: this.directory, ensureServing: true, owner: 'engine', version: await this.version() });
5086
- const { serve, installId, ...hosting } = snapshot;
5087
- if (serve !== undefined && serve.owned)
5088
- this.remoteServe = Promise.resolve(serve);
5089
- return { hosting };
5090
- });
5091
- }
5092
- async remoteHostingInvitationFull() {
5093
- if ((await loadConfig(this.directory)).remote?.hosting?.transport === 'http') {
5094
- throw new AppServerError('invalid-params', 'Full-control pairing requires HTTPS. Stop insecure HTTP hosting before granting owner authority.');
5795
+ finally {
5796
+ const left = (this.modelRelayRemoving.get(id) ?? 1) - 1;
5797
+ if (left > 0)
5798
+ this.modelRelayRemoving.set(id, left);
5799
+ else
5800
+ this.modelRelayRemoving.delete(id);
5095
5801
  }
5096
- const { createRemoteInvitation } = await import('./remote/pairing.js');
5097
- await createRemoteInvitation(this.directory, Date.now(), 'full');
5098
- return this.remoteHostingStatus();
5099
- }
5100
- async remoteHostingInvitationRegenerate() {
5101
- const { createRemoteInvitation } = await import('./remote/pairing.js');
5102
- await createRemoteInvitation(this.directory);
5103
- return this.remoteHostingStatus();
5802
+ const link = this.engineLinks.get(id);
5803
+ if (link) {
5804
+ this.dropEngineLink(id, link);
5805
+ this.emit('remote.engine.event', { workspaceId: id, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.closed', data: { reason: 'unlinked' } });
5806
+ }
5807
+ this.syncModelRelayLinks();
5808
+ return { removed: true };
5104
5809
  }
5105
- async remoteShareAdd(params) {
5106
- const path = typeof params.path === 'string' ? params.path.trim() : '';
5107
- if (!path || path.includes('\0'))
5108
- throw new AppServerError('invalid-params', 'A share needs the path of an existing folder.');
5109
- const realPath = await realpath(path).catch(() => undefined);
5110
- if (!realPath || !(await stat(realPath).catch(() => undefined))?.isDirectory())
5111
- throw new AppServerError('not-found', `No folder exists at ${path}.`);
5112
- const { addRemoteShare } = await import('./remote/pairing.js');
5810
+ /**
5811
+ * Whether `env` is one of the caller's environments, from the control list cached for 30 s, or the account's Cloud. The relay answers
5812
+ * not-found both for a machine whose bridge is away and for one the caller does not own; this tells them apart.
5813
+ * 'unknown' when the list could not be read for a reason other than sign-in, which callers treat as offline.
5814
+ */
5815
+ async environmentMembership(env, options = {}) {
5816
+ // The account's Cloud, as its own start or status answer named it, is owned before its first boot lists it.
5817
+ if (env === this.cloudEnvironmentId)
5818
+ return 'listed';
5819
+ let ids;
5113
5820
  try {
5114
- return { share: await addRemoteShare(realPath, { directory: this.directory, ...(typeof params.label === 'string' ? { label: params.label } : {}) }) };
5821
+ ids = await this.listedEnvironmentIds(options);
5115
5822
  }
5116
5823
  catch (error) {
5117
- throw new AppServerError('storage', message(error));
5824
+ const failure = this.environmentError(error);
5825
+ if (failure.code === 'login-required')
5826
+ throw failure;
5827
+ return 'unknown';
5118
5828
  }
5829
+ return ids.has(env) ? 'listed' : 'unlisted';
5119
5830
  }
5120
- async remoteShareRemove(params) {
5121
- const shareId = typeof params.shareId === 'string' ? params.shareId : '';
5122
- if (!shareId)
5123
- throw new AppServerError('invalid-params', 'shareId is required.');
5124
- const { removeRemoteShare } = await import('./remote/pairing.js');
5125
- return { removed: await removeRemoteShare(shareId, this.directory) };
5126
- }
5127
- async remoteDeviceRevoke(params) {
5128
- const deviceId = typeof params.deviceId === 'string' ? params.deviceId : '';
5129
- if (!deviceId)
5130
- throw new AppServerError('invalid-params', 'deviceId is required.');
5131
- const { revokeRemoteDevice } = await import('./remote/pairing.js');
5132
- return { revoked: await revokeRemoteDevice(deviceId, this.directory) };
5133
- }
5134
- async remoteDeviceGrant(params) {
5135
- const deviceId = typeof params.deviceId === 'string' ? params.deviceId : '';
5136
- if (!deviceId)
5137
- throw new AppServerError('invalid-params', 'deviceId is required.');
5138
- const { grantRemoteDevice } = await import('./remote/pairing.js');
5139
- const granted = await grantRemoteDevice(deviceId, this.directory).catch((error) => {
5140
- throw new AppServerError('storage', message(error));
5141
- });
5142
- if (!granted)
5143
- throw new AppServerError('not-found', 'No paired device has that id.');
5144
- return this.remoteHostingStatus();
5831
+ /**
5832
+ * The account's environment ids, cached for 30 s. A read that failed is remembered for as long, so callers that run
5833
+ * by themselves (answering model requests, retrying links) do not ask the service again on every turn; `fresh`
5834
+ * (a person's own action) asks it regardless.
5835
+ */
5836
+ listedEnvironmentIds(options = {}) {
5837
+ const cached = this.environmentIds;
5838
+ if (cached && Date.now() - cached.at < ENVIRONMENT_IDS_TTL_MS)
5839
+ return Promise.resolve(cached.ids);
5840
+ const failed = this.environmentIdsFailure;
5841
+ if (!options.fresh && !this.environmentIdsLoading && failed && Date.now() - failed.at < ENVIRONMENT_IDS_TTL_MS)
5842
+ return Promise.reject(failed.error);
5843
+ const generation = this.accountGeneration;
5844
+ const loading = this.environmentIdsLoading ??= (async () => {
5845
+ try {
5846
+ const records = await this.environmentControl().list(await this.environmentAccessToken());
5847
+ const ids = new Set(records.map(record => record.id));
5848
+ if (generation === this.accountGeneration) {
5849
+ this.environmentIds = { ids, at: Date.now() };
5850
+ this.environmentIdsFailure = undefined;
5851
+ }
5852
+ return ids;
5853
+ }
5854
+ catch (error) {
5855
+ if (generation === this.accountGeneration)
5856
+ this.environmentIdsFailure = { error, at: Date.now() };
5857
+ throw error;
5858
+ }
5859
+ })().finally(() => { if (this.environmentIdsLoading === loading)
5860
+ this.environmentIdsLoading = undefined; });
5861
+ return loading;
5862
+ }
5863
+ /** A call for a machine whose link is waiting for it to come back fails now instead of at its deadline. */
5864
+ refuseWhileReconnecting(env) {
5865
+ if (this.engineLinks.get(env)?.reconnecting)
5866
+ throw new AppServerError('network', MACHINE_OFFLINE);
5867
+ }
5868
+ hostOperation(params, op, operationParams = {}) {
5869
+ const env = environmentId(params.workspaceId);
5870
+ this.refuseWhileReconnecting(env);
5871
+ return this.relayLink().host(env, op, operationParams, Date.now() + REMOTE_HOST_DEADLINE_MS);
5145
5872
  }
5146
5873
  async remoteEngineConnect(params) {
5147
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
5148
5874
  const connectionId = typeof params.connectionId === 'string' ? params.connectionId : '';
5149
- if (!workspaceId || !connectionId)
5875
+ if (typeof params.workspaceId !== 'string' || !params.workspaceId || !connectionId)
5150
5876
  throw new AppServerError('invalid-params', 'workspaceId and connectionId are required.');
5151
- const { workspace, target, hosts } = await this.remoteTarget(params);
5152
- const existing = this.engineLinks.get(workspaceId);
5877
+ const env = environmentId(params.workspaceId);
5878
+ const existing = this.engineLinks.get(env);
5153
5879
  if (existing) {
5154
5880
  if (existing.connectionId === connectionId)
5155
5881
  return { ok: true, engine: REMOTE_LINK_ENGINE };
5156
- existing.controller.abort();
5157
- this.engineLinks.delete(workspaceId);
5882
+ this.dropEngineLink(env, existing);
5158
5883
  }
5159
- const controller = new AbortController();
5160
- this.engineLinks.set(workspaceId, { connectionId, controller });
5161
- const { peerWhoami } = await import('./remote/client.js');
5162
- let identity = {};
5884
+ const link = { owner: 'window', connectionId, ended: false, reconnecting: false, attempt: 0 };
5885
+ this.engineLinks.set(env, link);
5886
+ let opened;
5163
5887
  try {
5164
- const probed = await this.peerCall(target, hosts, host => peerWhoami(target, host), { preservePeerError: true });
5165
- identity = { hostname: probed.hostname, platform: probed.platform, version: probed.version, ...(probed.grant !== undefined ? { grant: probed.grant } : {}), ...(probed.capabilities !== undefined ? { capabilities: probed.capabilities } : {}) };
5888
+ opened = await this.openEngineLink(env, link);
5166
5889
  }
5167
- catch { }
5168
- void this.runEngineLink(workspaceId, workspace, connectionId, controller.signal, target, hosts).catch(() => undefined);
5169
- return { ok: true, engine: REMOTE_LINK_ENGINE, host: identity };
5890
+ catch (error) {
5891
+ const forget = () => { if (this.engineLinks.get(env) === link)
5892
+ this.engineLinks.delete(env); };
5893
+ if (!(error instanceof RelayClosedError && error.reason === 'not-found') || link.ended) {
5894
+ forget();
5895
+ throw error;
5896
+ }
5897
+ let membership;
5898
+ try {
5899
+ membership = await this.environmentMembership(env, { fresh: true });
5900
+ }
5901
+ catch (failure) {
5902
+ forget();
5903
+ throw failure;
5904
+ }
5905
+ if (link.ended || this.engineLinks.get(env) !== link)
5906
+ throw new AppServerError('cancelled', 'The connection to that machine was closed.');
5907
+ if (membership === 'unlisted') {
5908
+ forget();
5909
+ throw new AppServerError('not-found', 'That machine is not linked to your account.');
5910
+ }
5911
+ // Linked but away: keep the link and attach it by itself when the machine's bridge comes back.
5912
+ this.awaitMachine(env, link, 'offline');
5913
+ return { ok: true, engine: REMOTE_LINK_ENGINE, offline: true };
5914
+ }
5915
+ const identity = await this.machineIdentity(env);
5916
+ if (identity?.capabilities !== undefined && this.engineLinks.get(env) === link)
5917
+ link.capabilities = identity.capabilities;
5918
+ return { ok: true, engine: REMOTE_LINK_ENGINE, host: { ...opened.host, ...(identity ?? {}) } };
5170
5919
  }
5171
- remoteEngineDisconnect(params) {
5172
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
5173
- if (!workspaceId)
5174
- throw new AppServerError('invalid-params', 'workspaceId is required.');
5175
- const link = this.engineLinks.get(workspaceId);
5176
- if (link) {
5177
- link.controller.abort();
5178
- this.engineLinks.delete(workspaceId);
5920
+ /** What the machine's `whoami` adds to its host description (grant, capabilities); undefined when it could not be read. */
5921
+ async machineIdentity(env) {
5922
+ try {
5923
+ const whoami = await this.relayLink().host(env, 'whoami', {}, Date.now() + REMOTE_HOST_DEADLINE_MS);
5924
+ if (!whoami || typeof whoami !== 'object')
5925
+ return undefined;
5926
+ const { grant, capabilities } = whoami;
5927
+ return {
5928
+ ...(grant === 'browse' || grant === 'full' ? { grant } : {}),
5929
+ ...(Array.isArray(capabilities) ? { capabilities: capabilities.filter(entry => typeof entry === 'string') } : {}),
5930
+ };
5931
+ }
5932
+ catch {
5933
+ return undefined;
5179
5934
  }
5180
- return { ok: true };
5181
5935
  }
5182
- async runEngineLink(workspaceId, workspace, connectionId, signal, target, hosts) {
5183
- const { peerEngineEvents } = await import('./remote/client.js');
5184
- const closed = (reason) => {
5185
- if (this.engineLinks.get(workspaceId)?.connectionId === connectionId)
5186
- this.engineLinks.delete(workspaceId);
5187
- this.emit('remote.engine.event', { workspaceId, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.closed', data: { reason } });
5188
- };
5189
- while (!signal.aborted) {
5190
- try {
5191
- await this.peerCall(target, hosts, host => peerEngineEvents(target, host, connectionId, workspaceId, frame => {
5192
- this.emit('remote.engine.event', { workspaceId, engine: frame.engine, event: frame.event, data: frame.data });
5193
- }, signal), { preservePeerError: true });
5194
- if (signal.aborted)
5195
- return;
5196
- }
5197
- catch (error) {
5198
- if (signal.aborted)
5936
+ /** A reopen whose `whoami` failed asks again once the link is up, and reports the full host with another `reopened`. */
5937
+ retryMachineIdentity(env, link, host, left) {
5938
+ clearTimeout(link.identityRetry);
5939
+ const attempt = link.attempt;
5940
+ const stale = () => this.engineLinks.get(env) !== link || link.ended || link.reconnecting || link.attempt !== attempt;
5941
+ link.identityRetry = setTimeout(() => {
5942
+ link.identityRetry = undefined;
5943
+ if (stale())
5944
+ return;
5945
+ void this.machineIdentity(env).then(identity => {
5946
+ if (stale())
5199
5947
  return;
5200
- if (error instanceof RemotePeerError && (error.kind === 'identity' || error.kind === 'unauthorized' || error.kind === 'rejected')) {
5201
- closed(error.kind);
5948
+ if (identity === undefined) {
5949
+ if (left > 1)
5950
+ this.retryMachineIdentity(env, link, host, left - 1);
5202
5951
  return;
5203
5952
  }
5204
- }
5205
- await new Promise(resolve => {
5206
- const onAbort = () => { clearTimeout(timer); resolve(); };
5207
- const timer = setTimeout(() => { signal.removeEventListener('abort', onAbort); resolve(); }, 5_000);
5208
- timer.unref?.();
5209
- signal.addEventListener('abort', onAbort, { once: true });
5953
+ if (identity.capabilities !== undefined)
5954
+ link.capabilities = identity.capabilities;
5955
+ this.emit('remote.engine.event', { workspaceId: env, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.reopened', data: { host: { ...host, ...identity } } });
5210
5956
  });
5211
- if (signal.aborted)
5957
+ }, ENGINE_LINK_RETRY_MS);
5958
+ link.identityRetry.unref?.();
5959
+ }
5960
+ /** Whether `link` is still the one held for `env` in its own map, and not ended. */
5961
+ linkIsCurrent(env, link) {
5962
+ return (link.owner === 'engine' ? this.modelRelayLinks : this.engineLinks).get(env) === link && !link.ended;
5963
+ }
5964
+ openEngineLink(env, link) {
5965
+ return this.relayLink().open(env, link.connectionId, env, frame => {
5966
+ if (!this.linkIsCurrent(env, link))
5212
5967
  return;
5213
- const current = (await loadConfig(this.directory)).remote?.workspaces?.find(entry => entry.id === workspaceId);
5214
- if (!current || this.remoteTrustIdentity(current) !== this.remoteTrustIdentity(workspace)) {
5215
- closed('pairing-changed');
5968
+ // The relay delivers a reopened link's snapshot replay in the same turn as its `opened`, before the reopen's
5969
+ // continuation runs; hold those frames so `remote.engine.reopened` reaches the desktop first, and so the
5970
+ // engine's own link is up before a request on it is claimed.
5971
+ if (link.reconnecting) {
5972
+ (link.held ??= []).push(frame);
5216
5973
  return;
5217
5974
  }
5218
- }
5975
+ if (link.owner === 'engine')
5976
+ this.localRelay.handle(env, frame);
5977
+ else
5978
+ this.emitEngineFrame(env, frame);
5979
+ }, reason => this.engineLinkEnded(env, link, reason));
5219
5980
  }
5220
- async remoteEngineRequest(params) {
5221
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
5222
- const connectionId = typeof params.connectionId === 'string' ? params.connectionId : '';
5223
- const engine = typeof params.engine === 'string' ? params.engine : '';
5224
- const method = typeof params.method === 'string' ? params.method : '';
5225
- if (!workspaceId || !connectionId || !engine || !method)
5226
- throw new AppServerError('invalid-params', 'workspaceId, connectionId, engine, and method are required.');
5227
- const inner = params.params !== undefined && typeof params.params === 'object' && !Array.isArray(params.params)
5228
- ? params.params : undefined;
5229
- const ceiling = RELAY_LONG_METHODS.has(method) ? RELAY_LONG_DEADLINE_MS : RELAY_DEADLINE_MS;
5230
- const deadlineMs = typeof params.deadlineMs === 'number' && params.deadlineMs > 0 ? Math.min(Math.round(params.deadlineMs), ceiling) : undefined;
5231
- const { target, hosts } = await this.remoteTarget(params);
5232
- const { peerEngineRequest } = await import('./remote/client.js');
5233
- const deadlineAt = deadlineMs !== undefined ? Date.now() + deadlineMs : undefined;
5234
- const answer = await this.peerCall(target, hosts, host => peerEngineRequest(target, {
5235
- connectionId,
5236
- viewerWorkspaceId: workspaceId,
5237
- engine,
5238
- method,
5239
- ...(inner !== undefined ? { params: inner } : {}),
5240
- ...(deadlineMs !== undefined ? { deadlineMs } : {}),
5241
- }, host, deadlineAt));
5242
- if (answer.error) {
5243
- const code = RELAY_ERROR_CODES.has(answer.error.code) ? answer.error.code : 'remote';
5244
- throw new AppServerError(code, answer.error.message);
5245
- }
5246
- return answer.result ?? null;
5981
+ emitEngineFrame(env, frame) {
5982
+ // A relayed run's model calls are this engine's to answer, never the window's to show.
5983
+ if (this.localRelay.handle(env, frame))
5984
+ return;
5985
+ this.emit('remote.engine.event', { workspaceId: env, engine: frame.engine, event: frame.event, data: frame.data });
5247
5986
  }
5248
- async remoteWorkspacesList() {
5249
- const config = await loadConfig(this.directory);
5250
- const workspaces = config.remote?.workspaces ?? [];
5251
- if (!workspaces.length)
5252
- return { workspaces: [] };
5253
- const listed = await Promise.all(workspaces.map(workspace => this.remoteWorkspaceState(workspace)));
5254
- return { workspaces: listed };
5255
- }
5256
- async remoteWorkspaceState(workspace) {
5257
- const { peerWhoami } = await import('./remote/client.js');
5258
- const hosts = [...(workspace.host !== undefined ? [workspace.host] : []), ...workspace.hosts].filter((entry, index, list) => list.indexOf(entry) === index);
5259
- const target = {
5260
- host: hosts[0] ?? '',
5261
- port: workspace.port,
5262
- transport: workspace.transport,
5263
- fingerprint: workspace.fingerprint,
5264
- ...(workspace.certPem !== undefined ? { certPem: workspace.certPem } : {}),
5265
- ...(workspace.token !== undefined ? { token: workspace.token } : {}),
5266
- };
5267
- if (!hosts.length)
5268
- return this.remoteWorkspaceView(workspace, { status: 'unknown', statusDetail: 'No host to contact.' });
5269
- const deadlineAt = Date.now() + REMOTE_PROBE_DEADLINE_MS;
5270
- try {
5271
- const identity = await this.peerCall(target, hosts, host => peerWhoami(target, host, deadlineAt), { preservePeerError: true });
5272
- if (identity.grant !== undefined)
5273
- this.lastKnownGrants.set(workspace.id, identity.grant);
5274
- return this.remoteWorkspaceView(workspace, { status: 'online', hostname: identity.hostname, platform: identity.platform, version: identity.version, grant: identity.grant, ...(identity.relay !== undefined ? { relay: identity.relay } : {}) });
5987
+ engineLinkEnded(env, link, reason) {
5988
+ if (!this.linkIsCurrent(env, link))
5989
+ return;
5990
+ link.attempt += 1;
5991
+ if (reason === 'unlinked') {
5992
+ this.forgetEngineLink(env, link, reason);
5993
+ return;
5275
5994
  }
5276
- catch (error) {
5277
- const failure = error instanceof RemotePeerError ? error : new RemotePeerError('network', message(error));
5278
- const verdict = this.remoteStatusFailure(failure);
5279
- if ((verdict.status === 'offline' || verdict.status === 'unknown') && this.lastKnownGrants.has(workspace.id)) {
5280
- return this.remoteWorkspaceView(workspace, { ...verdict, grant: this.lastKnownGrants.get(workspace.id) });
5281
- }
5282
- return this.remoteWorkspaceView(workspace, verdict);
5995
+ if (reason === 'not-found' && link.owner === 'engine') {
5996
+ // The engine's own link does not ask the account's list: its 5-minute reconciliation drops a machine no longer listed.
5997
+ this.awaitMachine(env, link, 'offline');
5998
+ return;
5283
5999
  }
5284
- }
5285
- async remoteWorkspaceProbe(params) {
5286
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId.trim() : '';
5287
- if (!workspaceId)
5288
- throw new AppServerError('invalid-params', 'workspaceId is required.');
5289
- const config = await loadConfig(this.directory);
5290
- const workspace = (config.remote?.workspaces ?? []).find(item => item.id === workspaceId);
5291
- if (!workspace)
5292
- throw new AppServerError('not-found', 'No paired workspace has that id.');
5293
- const probed = await this.remoteWorkspaceState(workspace);
5294
- const current = (await loadConfig(this.directory)).remote?.workspaces?.find(item => item.id === workspaceId);
5295
- if (!current)
5296
- throw new AppServerError('not-found', 'No paired workspace has that id.');
5297
- if (this.remoteProbeIdentity(current) !== this.remoteProbeIdentity(workspace)) {
5298
- throw new AppServerError('remote', 'The pairing changed while the check was running; the next check reads the current record.');
6000
+ if (reason === 'not-found') {
6001
+ // The relay says not-found both for a machine whose bridge went away and for one the account no longer owns.
6002
+ void this.environmentMembership(env).then(membership => {
6003
+ if (!this.linkIsCurrent(env, link))
6004
+ return;
6005
+ if (membership === 'unlisted')
6006
+ this.forgetEngineLink(env, link, 'unlinked');
6007
+ else
6008
+ this.awaitMachine(env, link, 'offline');
6009
+ }, () => {
6010
+ if (this.linkIsCurrent(env, link))
6011
+ this.forgetEngineLink(env, link, 'login-required');
6012
+ });
6013
+ return;
5299
6014
  }
5300
- return { workspace: probed };
6015
+ this.awaitMachine(env, link, reason);
5301
6016
  }
5302
- remoteProbeIdentity(workspace) {
5303
- return JSON.stringify([workspace.nickname, workspace.host ?? null, workspace.hosts, workspace.port, workspace.transport, workspace.fingerprint, workspace.certPem, workspace.token]);
6017
+ /** A transient end keeps the link: the desktop keeps its clients and transcript while the engine reopens it. */
6018
+ awaitMachine(env, link, reason) {
6019
+ link.reconnecting = true;
6020
+ if (link.owner === 'window')
6021
+ this.emit('remote.engine.event', { workspaceId: env, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.reconnecting', data: { reason } });
6022
+ this.retryEngineLink(env, link);
5304
6023
  }
5305
- remoteTrustIdentity(workspace) {
5306
- return JSON.stringify([workspace.host ?? null, workspace.hosts, workspace.port, workspace.transport, workspace.fingerprint, workspace.certPem, workspace.token]);
5307
- }
5308
- async remoteWorkspaceAdd(params) {
5309
- const code = typeof params.code === 'string' ? params.code.trim() : '';
5310
- if (!code)
5311
- throw new AppServerError('invalid-params', 'A pairing code is required.');
5312
- const { decodePairingCode, addRemoteWorkspace, newWorkspaceId } = await import('./remote/pairing.js');
5313
- let decoded;
5314
- try {
5315
- decoded = decodePairingCode(code);
6024
+ retryEngineLink(env, link) {
6025
+ let delay = ENGINE_LINK_RETRY_MS;
6026
+ if (link.owner === 'engine') {
6027
+ link.downSince ??= Date.now();
6028
+ delay = modelRelayRetryMs(Date.now() - link.downSince);
5316
6029
  }
5317
- catch (error) {
6030
+ link.retry = setTimeout(() => {
6031
+ link.retry = undefined;
6032
+ if (this.linkIsCurrent(env, link))
6033
+ this.attemptEngineLink(env, link);
6034
+ }, delay);
6035
+ link.retry.unref?.();
6036
+ }
6037
+ /**
6038
+ * Opens `link` again (or, for the engine's own link, the first time); one that fails is retried in 5 s, or for the
6039
+ * engine's own link on its backoff.
6040
+ */
6041
+ attemptEngineLink(env, link) {
6042
+ const attempt = ++link.attempt;
6043
+ const stale = () => !this.linkIsCurrent(env, link) || link.attempt !== attempt;
6044
+ Promise.resolve().then(() => this.openEngineLink(env, link)).then(async (opened) => {
6045
+ if (stale()) {
6046
+ // Dropped while the open was in flight: the relay's side of it is closed too, unless a current link uses it.
6047
+ if (!this.linkIsCurrent(env, link) && this.modelRelayLinks.get(env)?.connectionId !== link.connectionId && this.engineLinks.get(env)?.connectionId !== link.connectionId) {
6048
+ this.relay?.close(env, link.connectionId);
6049
+ }
6050
+ return;
6051
+ }
6052
+ if (link.owner === 'engine') {
6053
+ // Up: the requests it delivered while opening are claimed through it now.
6054
+ link.reconnecting = false;
6055
+ link.downSince = undefined;
6056
+ const held = link.held ?? [];
6057
+ link.held = undefined;
6058
+ for (const frame of held)
6059
+ this.localRelay.handle(env, frame);
6060
+ return;
6061
+ }
6062
+ // The desktop learns what the machine supports from the host it is given, as on the first connect. Frames that
6063
+ // arrive meanwhile stay held, so `reopened` still comes first.
6064
+ const identity = await this.machineIdentity(env);
6065
+ if (stale())
6066
+ return;
6067
+ if (identity?.capabilities !== undefined)
6068
+ link.capabilities = identity.capabilities;
6069
+ link.reconnecting = false;
6070
+ const held = link.held ?? [];
6071
+ link.held = undefined;
6072
+ this.emit('remote.engine.event', { workspaceId: env, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.reopened', data: { host: { ...opened.host, ...(identity ?? {}) } } });
6073
+ for (const frame of held)
6074
+ this.emitEngineFrame(env, frame);
6075
+ if (identity === undefined)
6076
+ this.retryMachineIdentity(env, link, opened.host, IDENTITY_RETRIES);
6077
+ }, async (error) => {
6078
+ link.held = undefined;
6079
+ if (stale())
6080
+ return;
6081
+ if (error instanceof AppServerError && error.code === 'login-required') {
6082
+ this.forgetEngineLink(env, link, 'login-required');
6083
+ return;
6084
+ }
6085
+ if (error instanceof RelayClosedError && error.reason === 'unlinked') {
6086
+ this.forgetEngineLink(env, link, 'unlinked');
6087
+ return;
6088
+ }
6089
+ if (error instanceof RelayClosedError && error.reason === 'not-found' && link.owner === 'window') {
6090
+ let membership;
6091
+ try {
6092
+ membership = await this.environmentMembership(env);
6093
+ }
6094
+ catch {
6095
+ if (!stale())
6096
+ this.forgetEngineLink(env, link, 'login-required');
6097
+ return;
6098
+ }
6099
+ if (stale())
6100
+ return;
6101
+ if (membership === 'unlisted') {
6102
+ this.forgetEngineLink(env, link, 'unlinked');
6103
+ return;
6104
+ }
6105
+ }
6106
+ this.retryEngineLink(env, link);
6107
+ }).catch(() => undefined);
6108
+ }
6109
+ /**
6110
+ * Ends `link` for good. The machine's model work stops with it unless the machine is still reachable through its
6111
+ * other link; a machine that left the account stops either way.
6112
+ */
6113
+ forgetEngineLink(env, link, reason) {
6114
+ link.ended = true;
6115
+ clearTimeout(link.retry);
6116
+ clearTimeout(link.identityRetry);
6117
+ const links = link.owner === 'engine' ? this.modelRelayLinks : this.engineLinks;
6118
+ if (links.get(env) === link)
6119
+ links.delete(env);
6120
+ if (reason === 'unlinked' || (!this.modelRelayLinks.has(env) && !this.engineLinks.has(env)))
6121
+ this.localRelay.dropEnvironment(env);
6122
+ if (link.owner === 'window')
6123
+ this.emit('remote.engine.event', { workspaceId: env, engine: REMOTE_LINK_ENGINE, event: 'remote.engine.closed', data: { reason } });
6124
+ }
6125
+ /** Closes `link`. The machine's model work is kept: a new link may replace this one and deliver it. */
6126
+ dropEngineLink(env, link) {
6127
+ link.ended = true;
6128
+ clearTimeout(link.retry);
6129
+ clearTimeout(link.identityRetry);
6130
+ const links = link.owner === 'engine' ? this.modelRelayLinks : this.engineLinks;
6131
+ if (links.get(env) === link)
6132
+ links.delete(env);
6133
+ this.relay?.close(env, link.connectionId);
6134
+ }
6135
+ remoteEngineDisconnect(params) {
6136
+ const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
6137
+ if (!workspaceId)
6138
+ throw new AppServerError('invalid-params', 'workspaceId is required.');
6139
+ const link = this.engineLinks.get(workspaceId);
6140
+ if (link) {
6141
+ this.dropEngineLink(workspaceId, link);
6142
+ // The engine's own link to the machine, when it has one, goes on answering its model requests.
6143
+ if (!this.modelRelayLinks.has(workspaceId))
6144
+ this.localRelay.dropEnvironment(workspaceId);
6145
+ }
6146
+ return { ok: true };
6147
+ }
6148
+ /**
6149
+ * Whether a model request from `env` is answered here: allowed here for the signed-in account, not being removed,
6150
+ * and on that account's list. Which of its runs are answered is the run store's to say.
6151
+ */
6152
+ async modelRelayAnswers(env, subject) {
6153
+ if (this.modelRelayRevoked.has(env))
6154
+ return false;
6155
+ if (!(await this.modelRelayAllowed(subject)).has(env))
6156
+ return false;
6157
+ let listed;
6158
+ try {
6159
+ listed = await this.listedEnvironmentIds();
6160
+ }
6161
+ catch {
6162
+ return false;
6163
+ }
6164
+ return listed.has(env) && !this.modelRelayRevoked.has(env);
6165
+ }
6166
+ /** Whether `subject` started or resumed `runId` on `env` from this computer: recorded, or held in memory after a failed save. */
6167
+ async relayRunStartedHere(env, runId, subject) {
6168
+ if (subject === undefined)
6169
+ return false;
6170
+ return this.modelRelayRunsUnsaved.has(`${subject}\u0000${env}\u0000${runId}`) || this.modelRelayRuns.has(subject, env, runId);
6171
+ }
6172
+ /** Forgets the unsaved runs of `env` (for `subject`, or every account). */
6173
+ forgetUnsavedRuns(env, subject) {
6174
+ for (const entry of [...this.modelRelayRunsUnsaved]) {
6175
+ const [owner, machine] = entry.split('\u0000');
6176
+ if (machine === env && (subject === undefined || owner === subject))
6177
+ this.modelRelayRunsUnsaved.delete(entry);
6178
+ }
6179
+ }
6180
+ /**
6181
+ * The machines `subject` allowed to use this computer's models: its saved list and any whose save failed, less those
6182
+ * removed. Signed out, none.
6183
+ */
6184
+ async modelRelayAllowed(subject) {
6185
+ if (subject === undefined)
6186
+ return new Set();
6187
+ const saved = modelRelayAllowedFor((await loadConfig(this.directory)).environments, subject);
6188
+ const unsaved = [...this.modelRelayUnsaved].filter(entry => entry.startsWith(`${subject}\u0000`)).map(entry => entry.slice(subject.length + 1));
6189
+ return new Set([...saved, ...unsaved].filter(env => !this.modelRelayRevoked.has(env)));
6190
+ }
6191
+ /** Brings the engine's own links in line with the machines allowed here and on the account's list. */
6192
+ syncModelRelayLinks() {
6193
+ if (this.closed || process.env.ANDORRA_AUTOMATION_WORKER === '1')
6194
+ return;
6195
+ const chore = this.reconcileModelRelayLinks().catch(error => this.log('warn', `Could not link the machines that use this computer's models: ${message(error)}`));
6196
+ this.modelRelayChores.add(chore);
6197
+ void chore.finally(() => this.modelRelayChores.delete(chore));
6198
+ }
6199
+ async reconcileModelRelayLinks() {
6200
+ const sync = ++this.modelRelaySync;
6201
+ const generation = this.accountGeneration;
6202
+ const stale = () => this.closed || sync !== this.modelRelaySync || generation !== this.accountGeneration;
6203
+ const subject = await currentGraphSubject();
6204
+ const allowed = await this.modelRelayAllowed(subject);
6205
+ if (stale())
6206
+ return;
6207
+ if (allowed.size === 0) {
6208
+ // Nothing to answer: no link, no refresh, and no relay socket opened for it.
6209
+ for (const [env, link] of [...this.modelRelayLinks])
6210
+ this.releaseModelRelayLink(env, link);
6211
+ this.stopModelRelayRefresh();
6212
+ return;
6213
+ }
6214
+ let listed;
6215
+ const before = this.environmentIds;
6216
+ try {
6217
+ listed = await this.listedEnvironmentIds();
6218
+ }
6219
+ catch (error) {
6220
+ if (stale())
6221
+ return;
6222
+ if (this.environmentError(error).code === 'login-required') {
6223
+ for (const [env, link] of [...this.modelRelayLinks])
6224
+ this.releaseModelRelayLink(env, link);
6225
+ this.stopModelRelayRefresh();
6226
+ return;
6227
+ }
6228
+ // The list could not be read: the links stay as they are until the next refresh reads it.
6229
+ this.scheduleModelRelayRefresh();
6230
+ return;
6231
+ }
6232
+ if (stale())
6233
+ return;
6234
+ for (const [env, link] of [...this.modelRelayLinks]) {
6235
+ if (!allowed.has(env) || !listed.has(env))
6236
+ this.releaseModelRelayLink(env, link);
6237
+ }
6238
+ for (const env of allowed) {
6239
+ if (listed.has(env) && !this.modelRelayLinks.has(env))
6240
+ this.openModelRelayLink(env);
6241
+ }
6242
+ this.scheduleModelRelayRefresh();
6243
+ // Only a listing read from the service for this reconcile, not the 30 s copy, may lead to forgetting a machine.
6244
+ const fresh = this.environmentIds !== undefined && this.environmentIds !== before && this.environmentIds.ids === listed;
6245
+ // A newer reconcile does not stop a prune half done (it is idempotent); a close or an account change does.
6246
+ if (subject !== undefined && fresh)
6247
+ await this.pruneModelRelayList(subject, listed, () => this.closed || generation !== this.accountGeneration);
6248
+ }
6249
+ /**
6250
+ * Drops from `subject`'s entry, and from its recorded runs, the machines no longer on its account's list: those
6251
+ * missing from this fresh listing and from one at least a refresh interval earlier. Their links are closed at once by
6252
+ * the reconcile; only this forgetting waits. Nothing is written once `stale` says the engine closed or the account changed.
6253
+ */
6254
+ async pruneModelRelayList(subject, listed, stale) {
6255
+ if (stale())
6256
+ return;
6257
+ const saved = modelRelayAllowedFor((await loadConfig(this.directory)).environments, subject);
6258
+ const unsaved = [...this.modelRelayUnsaved].filter(entry => entry.startsWith(`${subject}\u0000`)).map(entry => entry.slice(subject.length + 1));
6259
+ if (stale())
6260
+ return;
6261
+ const now = Date.now();
6262
+ const gone = [];
6263
+ for (const env of new Set([...saved, ...unsaved])) {
6264
+ const key = `${subject}\u0000${env}`;
6265
+ if (listed.has(env)) {
6266
+ this.modelRelayMissing.delete(key);
6267
+ continue;
6268
+ }
6269
+ const since = this.modelRelayMissing.get(key);
6270
+ if (since === undefined)
6271
+ this.modelRelayMissing.set(key, now);
6272
+ else if (now - since >= MODEL_RELAY_REFRESH_MS)
6273
+ gone.push(env);
6274
+ }
6275
+ if (gone.length === 0)
6276
+ return;
6277
+ for (const env of gone) {
6278
+ this.modelRelayUnsaved.delete(`${subject}\u0000${env}`);
6279
+ this.forgetUnsavedRuns(env, subject);
6280
+ this.modelRelayMissing.delete(`${subject}\u0000${env}`);
6281
+ }
6282
+ try {
6283
+ await this.changeModelRelayList(map => {
6284
+ if (stale())
6285
+ return undefined;
6286
+ const list = modelRelayAllowedFor({ modelRelay: map }, subject);
6287
+ const kept = list.filter(env => !gone.includes(env));
6288
+ return kept.length === list.length ? undefined : { ...map, [subject]: kept };
6289
+ });
6290
+ if (stale())
6291
+ return;
6292
+ await this.modelRelayRuns.forgetFor(subject, gone);
6293
+ }
6294
+ catch (error) {
6295
+ this.log('warn', `Could not forget the machines that left your account: ${message(error)}`);
6296
+ }
6297
+ }
6298
+ /** Closes the engine's link to a machine that is no longer answered here, and stops its model work. */
6299
+ releaseModelRelayLink(env, link) {
6300
+ this.dropEngineLink(env, link);
6301
+ this.localRelay.dropEnvironment(env);
6302
+ }
6303
+ openModelRelayLink(env) {
6304
+ const link = { owner: 'engine', connectionId: `${MODEL_RELAY_CONNECTION_PREFIX}${randomBytes(16).toString('base64url')}`, ended: false, reconnecting: true, attempt: 0 };
6305
+ this.modelRelayLinks.set(env, link);
6306
+ this.attemptEngineLink(env, link);
6307
+ }
6308
+ scheduleModelRelayRefresh() {
6309
+ if (this.modelRelayRefresh !== undefined || this.closed)
6310
+ return;
6311
+ this.modelRelayRefresh = setTimeout(() => {
6312
+ this.modelRelayRefresh = undefined;
6313
+ // Read afresh, not from the 30 s cache: a machine removed elsewhere is what this is for.
6314
+ this.environmentIds = undefined;
6315
+ this.syncModelRelayLinks();
6316
+ }, MODEL_RELAY_REFRESH_MS);
6317
+ this.modelRelayRefresh.unref?.();
6318
+ }
6319
+ stopModelRelayRefresh() {
6320
+ clearTimeout(this.modelRelayRefresh);
6321
+ this.modelRelayRefresh = undefined;
6322
+ }
6323
+ /** Runs `save` once, MODEL_RELAY_SAVE_RETRY_MS from now; a second failure is logged and left to memory. */
6324
+ retryModelRelaySave(save) {
6325
+ const timer = setTimeout(() => {
6326
+ this.modelRelaySaveRetries.delete(timer);
6327
+ if (this.closed)
6328
+ return;
6329
+ void save().catch(error => this.log('warn', `Still could not save which machines may use this computer's models: ${message(error)}`));
6330
+ }, MODEL_RELAY_SAVE_RETRY_MS);
6331
+ timer.unref?.();
6332
+ this.modelRelaySaveRetries.add(timer);
6333
+ }
6334
+ async remoteEngineRequest(params) {
6335
+ const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
6336
+ const connectionId = typeof params.connectionId === 'string' ? params.connectionId : '';
6337
+ const engine = typeof params.engine === 'string' ? params.engine : '';
6338
+ const method = typeof params.method === 'string' ? params.method : '';
6339
+ if (!workspaceId || !connectionId || !engine || !method)
6340
+ throw new AppServerError('invalid-params', 'workspaceId, connectionId, engine, and method are required.');
6341
+ const env = environmentId(workspaceId);
6342
+ this.refuseWhileReconnecting(env);
6343
+ let inner = params.params !== undefined && typeof params.params === 'object' && !Array.isArray(params.params)
6344
+ ? params.params : undefined;
6345
+ const relayMachine = this.engineLinks.get(env)?.capabilities?.includes(MODEL_RELAY_CAPABILITY) === true;
6346
+ // A machine whose engine takes relayed providers runs this computer's models: its start carries them by id only.
6347
+ let relayed = false;
6348
+ if ((method === 'run.start' || method === 'run.resume') && relayMachine) {
6349
+ const enriched = await this.withModelRelay(method, inner ?? {});
6350
+ if (enriched !== undefined) {
6351
+ relayed = true;
6352
+ inner = enriched;
6353
+ }
6354
+ }
6355
+ if (method === 'run.setModel' && relayMachine && inner !== undefined)
6356
+ await this.checkRelayedModel(inner);
6357
+ const ceiling = RELAY_LONG_METHODS.has(method) ? RELAY_LONG_DEADLINE_MS : RELAY_DEADLINE_MS;
6358
+ const deadlineMs = typeof params.deadlineMs === 'number' && params.deadlineMs > 0 ? Math.min(Math.round(params.deadlineMs), ceiling) : undefined;
6359
+ const send = (sent) => {
6360
+ // The machine bounds the call by deadlineMs and answers with its own error; the slack lets that answer arrive.
6361
+ const deadlineAt = Date.now() + (deadlineMs ?? ceiling) + RELAY_TRANSPORT_SLACK_MS;
6362
+ return this.relayLink().request(env, {
6363
+ connectionId,
6364
+ viewerWorkspaceId: env,
6365
+ engine,
6366
+ method,
6367
+ ...(sent !== undefined ? { params: sent } : {}),
6368
+ ...(deadlineMs !== undefined ? { deadlineMs } : {}),
6369
+ }, deadlineAt);
6370
+ };
6371
+ let answer = await send(inner);
6372
+ // A resumed run that ran a graph from this computer needs it again; the machine's record names it.
6373
+ if (relayed && method === 'run.resume' && answer.error?.message === RELAYED_GRAPH_NEEDS_DESKTOP && inner !== undefined) {
6374
+ const graph = await this.relayedResumeGraph(env, connectionId, inner.runId, relayOfferedProviders(await loadConfig(this.directory)));
6375
+ if (graph !== undefined)
6376
+ answer = await send({ ...inner, relay: { ...inner.relay, graph } });
6377
+ }
6378
+ // The machine took a run on this computer's models: from now on that run's model requests are answered here.
6379
+ if (relayed && !answer.error)
6380
+ await this.adoptRelayedRun(env, answer.result);
6381
+ if (answer.error) {
6382
+ const code = RELAY_ERROR_CODES.has(answer.error.code) ? answer.error.code : 'remote';
6383
+ throw new AppServerError(code, answer.error.message);
6384
+ }
6385
+ return answer.result ?? null;
6386
+ }
6387
+ /**
6388
+ * Records the run a relayed start or resume answered with as this computer's on `env` (from the answer's `runId`),
6389
+ * lets a request of it that arrived first be taken now, and allows the machine.
6390
+ */
6391
+ async adoptRelayedRun(env, result) {
6392
+ const subject = await currentGraphSubject();
6393
+ const runId = result !== null && typeof result === 'object' && !Array.isArray(result) ? result.runId : undefined;
6394
+ if (subject !== undefined && typeof runId === 'string') {
6395
+ const unsaved = `${subject}\u0000${env}\u0000${runId}`;
6396
+ try {
6397
+ await this.modelRelayRuns.record(subject, env, runId);
6398
+ }
6399
+ catch (error) {
6400
+ this.modelRelayRunsUnsaved.add(unsaved);
6401
+ this.log('warn', `Could not save that this computer started task ${runId} on machine ${env}; it is answered until Andorra Code restarts, and saving is tried again in 30 s: ${message(error)}`);
6402
+ this.retryModelRelaySave(async () => {
6403
+ if (!this.modelRelayRunsUnsaved.has(unsaved))
6404
+ return;
6405
+ await this.modelRelayRuns.record(subject, env, runId);
6406
+ this.modelRelayRunsUnsaved.delete(unsaved);
6407
+ });
6408
+ }
6409
+ this.localRelay.reconsider(env, runId);
6410
+ }
6411
+ await this.allowModelRelay(env, subject);
6412
+ }
6413
+ /**
6414
+ * `params` of a run.start or run.resume for a machine that takes relayed providers, with `relay` added: this
6415
+ * computer's providers by id, model, models, context windows and effort only (never an address, a key or a sign-in),
6416
+ * and the graph to run when it is one only this computer has. A start always names its graph, so the machine never
6417
+ * falls back to one of its own. Undefined when this computer has no provider to offer: the request then goes as it
6418
+ * was, and the machine runs it on its own providers if it has any.
6419
+ */
6420
+ async withModelRelay(method, params) {
6421
+ const config = await loadConfig(this.directory);
6422
+ const providers = relayOfferedProviders(config);
6423
+ if (!providers.length)
6424
+ return undefined;
6425
+ const next = { ...params };
6426
+ let chosen;
6427
+ if (params.provider !== undefined) {
6428
+ if (typeof params.provider !== 'string' || !(chosen = findProviderById(providers, params.provider)))
6429
+ throw new AppServerError('invalid-params', PROVIDER_NOT_HERE);
6430
+ }
6431
+ else if (method === 'run.start') {
6432
+ // The machine would otherwise take the first relayed entry; this computer's own default is the one meant.
6433
+ const fallback = findProviderById(providers, config.provider);
6434
+ if (fallback !== undefined) {
6435
+ chosen = fallback;
6436
+ next.provider = fallback.id;
6437
+ if (params.model === undefined)
6438
+ next.model = fallback.model;
6439
+ }
6440
+ }
6441
+ if (params.model !== undefined && chosen !== undefined && (typeof params.model !== 'string' || !relayedModelIds(chosen).includes(params.model))) {
6442
+ throw new AppServerError('invalid-params', MODEL_NOT_HERE);
6443
+ }
6444
+ let graphId = typeof params.graph === 'string' && params.graph ? params.graph : undefined;
6445
+ if (graphId === undefined && method === 'run.start') {
6446
+ const selected = configuredGraphSelection(config, await currentGraphSubject());
6447
+ graphId = builtInGraph(selected) || await this.selectionIsDeleted(selected) ? 'default' : selected;
6448
+ next.graph = graphId;
6449
+ }
6450
+ // A resume may use a graph deleted since its run, as a local resume may; a new start may not.
6451
+ const loaded = graphId === undefined || builtInGraph(graphId) ? undefined : await this.desktopGraph(graphId, { allowDeleted: method === 'run.resume' });
6452
+ // As a local run does, the graph's portable provider ids are bound to this computer's providers (an older id of a Codex
6453
+ // sign-in names the one compatible profile here), so every node names an entry of `relay.providers`. A start that runs
6454
+ // every node on one model is not bound, as locally: the override replaces the nodes' providers on the machine.
6455
+ const graph = loaded === undefined || (method === 'run.start' && params.overrideAllNodes === true) ? loaded : this.relayBoundGraph(loaded, providers);
6456
+ next.relay = { providers: await this.relayedProviders(providers), ...(graph === undefined ? {} : { graph }) };
6457
+ return next;
6458
+ }
6459
+ /**
6460
+ * A run.setModel for a machine that takes relayed providers: a provider of this computer's may be switched only to a
6461
+ * model on its list. A provider id this computer does not have is the machine's own and is left to it.
6462
+ */
6463
+ async checkRelayedModel(params) {
6464
+ if (typeof params.provider !== 'string' || params.model === undefined)
6465
+ return;
6466
+ const provider = findProviderById((await loadConfig(this.directory)).providers.filter(entry => entry.type !== 'relayed'), params.provider);
6467
+ if (provider === undefined)
6468
+ return;
6469
+ if (typeof params.model !== 'string' || !relayedModelIds(provider).includes(params.model))
6470
+ throw new AppServerError('invalid-params', MODEL_NOT_HERE);
6471
+ }
6472
+ /**
6473
+ * Each provider as a relay entry, with the effective window of each listed model resolved here within 5 s in all.
6474
+ * A provider's windows are reused for 5 minutes while its address and models stay the same.
6475
+ */
6476
+ async relayedProviders(providers) {
6477
+ const controller = new AbortController();
6478
+ const windows = new Map();
6479
+ const keyOf = (provider) => JSON.stringify([provider.id, provider.type, provider.baseUrl, relayedModelIds(provider), provider.modelContextWindows ?? null]);
6480
+ const now = Date.now();
6481
+ for (const [key, entry] of [...this.relayWindowsCache])
6482
+ if (now - entry.at >= RELAY_WINDOWS_CACHE_MS)
6483
+ this.relayWindowsCache.delete(key);
6484
+ const unresolved = providers.filter(provider => {
6485
+ const cached = this.relayWindowsCache.get(keyOf(provider));
6486
+ if (cached !== undefined)
6487
+ windows.set(provider.id, cached.windows);
6488
+ return cached === undefined;
6489
+ });
6490
+ const resolving = Promise.allSettled(unresolved.map(async (provider) => {
6491
+ const resolved = await resolveModelContextWindows(provider, relayedModelIds(provider), controller.signal);
6492
+ windows.set(provider.id, resolved);
6493
+ if (!controller.signal.aborted)
6494
+ this.relayWindowsCache.set(keyOf(provider), { at: Date.now(), windows: resolved });
6495
+ }));
6496
+ let timer;
6497
+ if (unresolved.length)
6498
+ await Promise.race([resolving, new Promise(resolve => { timer = setTimeout(resolve, RELAY_WINDOWS_DEADLINE_MS); timer.unref?.(); })]);
6499
+ clearTimeout(timer);
6500
+ controller.abort();
6501
+ return providers.map(provider => {
6502
+ const models = provider.models === undefined ? undefined : relayedModelIds(provider).filter(model => provider.models.includes(model));
6503
+ const known = Object.fromEntries(Object.entries(windows.get(provider.id) ?? {}).filter(([, window]) => Number.isSafeInteger(window) && window > 0));
6504
+ return {
6505
+ id: provider.id, model: provider.model,
6506
+ ...(models === undefined || models.length === 0 ? {} : { models }),
6507
+ ...(Object.keys(known).length === 0 ? {} : { modelContextWindows: known }),
6508
+ ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
6509
+ };
6510
+ });
6511
+ }
6512
+ /** A graph this computer has, loaded under its membership rules; a graph it may not use fails with their message. */
6513
+ async desktopGraph(id, options = {}) {
6514
+ try {
6515
+ return await this.loadGraph(id, undefined, undefined, { bindProviders: false, ...(options.allowDeleted ? { allowDeleted: true } : {}) });
6516
+ }
6517
+ catch (error) {
6518
+ if (error instanceof AppServerError)
6519
+ throw error;
5318
6520
  throw new AppServerError('invalid-params', message(error));
5319
6521
  }
5320
- const typed = typeof params.nickname === 'string' && params.nickname.trim() ? params.nickname.trim() : undefined;
5321
- const nickname = (typed ?? decoded.n).slice(0, 64);
5322
- const local = await loadConfig(this.directory);
5323
- if ((local.remote?.workspaces ?? []).length >= 32) {
5324
- throw new AppServerError('storage', 'This machine already pairs with the maximum number of workspaces. Unpair one, then pair again — the code has not been used.');
5325
- }
5326
- const { redeemPairingPlan } = await import('./remote/client.js');
5327
- const redeemed = await redeemPairingPlan({ hosts: decoded.hosts, port: decoded.port, transport: decoded.transport, fingerprint: decoded.fp, invite: decoded.invite, name: decoded.n }, typed !== undefined ? { label: typed.slice(0, 64) } : {}).catch((error) => { throw this.remoteError(error); });
5328
- const workspace = {
5329
- id: newWorkspaceId(),
5330
- nickname,
5331
- hosts: decoded.hosts,
5332
- host: redeemed.host,
5333
- port: decoded.port,
5334
- transport: decoded.transport,
5335
- fingerprint: decoded.fp,
5336
- certPem: redeemed.certPem,
5337
- token: redeemed.credential,
5338
- ...(redeemed.hostname ? { hostname: redeemed.hostname } : {}),
5339
- ...(redeemed.platform ? { platform: redeemed.platform } : {}),
5340
- ...(redeemed.version ? { version: redeemed.version } : {}),
5341
- addedAt: new Date().toISOString(),
6522
+ }
6523
+ /** The graph a relayed run on `env` ran, from the machine's record of it, when it is one this computer has. */
6524
+ async relayedResumeGraph(env, connectionId, runId, providers) {
6525
+ if (typeof runId !== 'string' || !runId)
6526
+ return undefined;
6527
+ let answer;
6528
+ try {
6529
+ answer = await this.relayLink().request(env, { connectionId, viewerWorkspaceId: env, engine: REMOTE_PRIMARY, method: 'runs.get', params: { id: runId }, deadlineMs: MODEL_RELAY_CALL_MS }, Date.now() + MODEL_RELAY_CALL_MS + RELAY_TRANSPORT_SLACK_MS);
6530
+ }
6531
+ catch {
6532
+ return undefined;
6533
+ }
6534
+ const record = answer.result?.result;
6535
+ const raw = typeof record?.graphSelection === 'string' ? record.graphSelection : record?.graph?.id;
6536
+ if (typeof raw !== 'string' || !/^[\w:-]{1,128}$/.test(raw) || raw === SOFTWARE_ENGINEER_HARNESS.id || builtInGraph(raw))
6537
+ return undefined;
6538
+ const graph = await this.desktopGraph(raw, { allowDeleted: true });
6539
+ // The run already ran: a graph that no longer binds is sent as it is, and the machine says what is missing.
6540
+ try {
6541
+ return this.relayBoundGraph(graph, providers);
6542
+ }
6543
+ catch {
6544
+ return graph;
6545
+ }
6546
+ }
6547
+ /** `graph` with its portable provider ids bound to `providers`; one that cannot be bound is refused as a local start is. */
6548
+ relayBoundGraph(graph, providers) {
6549
+ try {
6550
+ return bindPortableGraphProviders(graph, { providers });
6551
+ }
6552
+ catch (error) {
6553
+ if (error instanceof GraphProviderUnavailableError)
6554
+ throw new AppServerError('invalid-params', error.message);
6555
+ throw error;
6556
+ }
6557
+ }
6558
+ /** Lists `env` among the machines `subject` allowed to use this computer's providers, the first time a relayed run starts there. */
6559
+ async allowModelRelay(env, subject) {
6560
+ // Signed out there is no account to allow it for; a run the machine took while it is being removed does not bring it back.
6561
+ if (subject === undefined || this.modelRelayRemoving.has(env))
6562
+ return;
6563
+ this.modelRelayRevoked.delete(env);
6564
+ const save = async () => {
6565
+ if (modelRelayAllowedFor((await loadConfig(this.directory)).environments, subject).includes(env))
6566
+ return;
6567
+ // Read again inside the write: a remove that began meanwhile wins. The oldest machines make room past the limit.
6568
+ await this.changeModelRelayList(map => {
6569
+ const list = modelRelayAllowedFor({ modelRelay: map }, subject);
6570
+ return list.includes(env) || this.modelRelayRevoked.has(env) ? undefined : withModelRelayEntry(map, subject, [...list, env]);
6571
+ });
5342
6572
  };
5343
- await addRemoteWorkspace(workspace, this.directory).catch((error) => {
5344
- throw new AppServerError('storage', `Paired with the host, but the workspace could not be saved locally (${message(error)}). That machine now lists a device for this machine — revoke it there before pairing again.`);
6573
+ const unsaved = `${subject}\u0000${env}`;
6574
+ try {
6575
+ await save();
6576
+ }
6577
+ catch (error) {
6578
+ // The machine already took the run: it is answered from memory, and the save is tried again.
6579
+ this.modelRelayUnsaved.add(unsaved);
6580
+ this.log('warn', `Could not save that machine ${env} may use this computer's models; it may until Andorra Code restarts, and saving is tried again in 30 s: ${message(error)}`);
6581
+ this.retryModelRelaySave(async () => {
6582
+ if (!this.modelRelayUnsaved.has(unsaved) || this.modelRelayRevoked.has(env))
6583
+ return;
6584
+ await save();
6585
+ this.modelRelayUnsaved.delete(unsaved);
6586
+ });
6587
+ }
6588
+ this.syncModelRelayLinks();
6589
+ }
6590
+ /** Withdraws `env`'s permission to use this computer's providers, for every account that allowed it. */
6591
+ async forgetModelRelayEnvironment(env, still = () => true) {
6592
+ const saved = (await loadConfig(this.directory)).environments?.modelRelay;
6593
+ if (!still() || !saved || Array.isArray(saved) || !Object.values(saved).some(list => list.includes(env)))
6594
+ return;
6595
+ // `still` is asked again inside the write: a machine allowed again meanwhile is left as it is.
6596
+ await this.changeModelRelayList(map => !still() || !Object.values(map).some(list => list.includes(env)) ? undefined
6597
+ : Object.fromEntries(Object.entries(map).map(([subject, list]) => [subject, list.filter(id => id !== env)])));
6598
+ }
6599
+ /**
6600
+ * Rewrites `environments.modelRelay`, a list per account; `change` answers undefined when there is nothing to change.
6601
+ * The list shape from before accounts were told apart is read as empty and replaced.
6602
+ */
6603
+ async changeModelRelayList(change) {
6604
+ let changed = false;
6605
+ const next = await this.serializeConfig(async () => {
6606
+ try {
6607
+ return await changeConfigFile(this.directory, current => {
6608
+ const saved = current.environments?.modelRelay;
6609
+ const map = saved && !Array.isArray(saved) ? { ...saved } : {};
6610
+ const updated = change(map);
6611
+ if (updated === undefined)
6612
+ return current;
6613
+ changed = true;
6614
+ return { ...current, environments: { ...current.environments, modelRelay: updated } };
6615
+ });
6616
+ }
6617
+ catch (error) {
6618
+ if (error instanceof AppServerError)
6619
+ throw error;
6620
+ throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
6621
+ }
5345
6622
  });
5346
- return { workspace: this.remoteWorkspaceView(workspace, { status: 'online', grant: redeemed.grant }) };
6623
+ if (changed)
6624
+ this.emit('config.changed', { config: await this.analyticsConfigView(next) });
5347
6625
  }
5348
- async remoteWorkspaceRemove(params) {
5349
- const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
5350
- if (!workspaceId)
5351
- throw new AppServerError('invalid-params', 'workspaceId is required.');
5352
- const { removeRemoteWorkspace } = await import('./remote/pairing.js');
5353
- return { removed: await removeRemoteWorkspace(workspaceId, this.directory) };
5354
- }
5355
- async remoteWorkspaceRename(params) {
5356
- const nickname = typeof params.nickname === 'string' ? params.nickname.trim() : '';
5357
- if (!nickname || nickname.length > 64 || /[\0\r\n]/.test(nickname))
5358
- throw new AppServerError('invalid-params', 'A workspace nickname is 1-64 printable characters.');
5359
- const { updateRemoteWorkspace } = await import('./remote/pairing.js');
5360
- const updated = await updateRemoteWorkspace(typeof params.workspaceId === 'string' ? params.workspaceId : '', { nickname }, this.directory);
5361
- if (!updated)
5362
- throw new AppServerError('not-found', 'No paired workspace has that id.');
5363
- return { workspace: this.remoteWorkspaceView(updated, { status: 'unknown' }) };
5364
- }
5365
- async remoteWorkspaceSetHost(params) {
5366
- const { isAllowedPeerHost } = await import('./remote/network.js');
5367
- let host;
5368
- if (params.host === null || params.host === undefined)
5369
- host = null;
5370
- else if (typeof params.host === 'string' && !params.host.trim())
5371
- host = null;
5372
- else if (typeof params.host === 'string') {
5373
- host = params.host.trim();
5374
- if (!isAllowedPeerHost(host))
5375
- throw new AppServerError('invalid-params', 'A workspace host must be a private address or a Tailscale name.');
6626
+ /**
6627
+ * A model.relay call to `env`'s engine `engine`. Without `via` it goes through the engine's own link when that is
6628
+ * up, else the window's; with `via` only through that link, since the machine takes a claim's later calls only
6629
+ * from the connection that claimed. A link that is gone or down answers cancelled or network.
6630
+ */
6631
+ async sendModelRelay(env, engine, method, params, via) {
6632
+ const candidates = [this.modelRelayLinks.get(env), this.engineLinks.get(env)].filter((link) => link !== undefined && !link.ended);
6633
+ const link = via === undefined ? candidates.find(entry => !entry.reconnecting) ?? candidates[0] : candidates.find(entry => entry.connectionId === via);
6634
+ if (!link)
6635
+ return { error: { code: 'cancelled', message: 'The connection to that machine was closed.' } };
6636
+ if (link.reconnecting || this.closed)
6637
+ return { error: { code: 'network', message: MACHINE_OFFLINE } };
6638
+ try {
6639
+ const answer = await this.relayLink().request(env, { connectionId: link.connectionId, viewerWorkspaceId: env, engine, method, params, deadlineMs: MODEL_RELAY_CALL_MS }, Date.now() + MODEL_RELAY_CALL_MS + RELAY_TRANSPORT_SLACK_MS);
6640
+ return { ...answer, via: link.connectionId };
6641
+ }
6642
+ catch (error) {
6643
+ return { error: { code: 'network', message: message(error) } };
5376
6644
  }
5377
- else
5378
- throw new AppServerError('invalid-params', 'host must be an address, a Tailscale name, or null.');
5379
- const { updateRemoteWorkspace } = await import('./remote/pairing.js');
5380
- const updated = await updateRemoteWorkspace(typeof params.workspaceId === 'string' ? params.workspaceId : '', { host }, this.directory);
5381
- if (!updated)
5382
- throw new AppServerError('not-found', 'No paired workspace has that id.');
5383
- return { workspace: this.remoteWorkspaceView(updated, { status: 'unknown' }) };
5384
6645
  }
5385
6646
  async remoteRootsList(params) {
5386
- const { target, hosts } = await this.remoteTarget(params);
5387
- const { peerRoots } = await import('./remote/client.js');
5388
- const roots = (await this.peerCall(target, hosts, host => peerRoots(target, host))).roots;
5389
- return { roots };
6647
+ const answer = await this.hostOperation(params, 'roots');
6648
+ const roots = answer?.roots;
6649
+ if (!Array.isArray(roots))
6650
+ throw new AppServerError('remote', 'The machine sent a malformed list of folders.');
6651
+ return { roots: roots };
5390
6652
  }
5391
6653
  async remoteProjectsFetch(params) {
5392
- const { target, hosts } = await this.remoteTarget(params);
5393
- const { peerProjects } = await import('./remote/client.js');
5394
- const projects = (await this.peerCall(target, hosts, host => peerProjects(target, host))).projects;
5395
- return { projects };
6654
+ const answer = await this.hostOperation(params, 'projects');
6655
+ const projects = answer?.projects;
6656
+ if (!Array.isArray(projects))
6657
+ throw new AppServerError('remote', 'The machine sent a malformed list of projects.');
6658
+ return { projects: projects };
5396
6659
  }
5397
6660
  async remoteBrowse(params) {
5398
6661
  const rootId = typeof params.rootId === 'string' ? params.rootId : '';
5399
6662
  if (!rootId)
5400
6663
  throw new AppServerError('invalid-params', 'remote.browse requires a rootId.');
5401
6664
  const rel = typeof params.rel === 'string' ? params.rel : '';
5402
- const { target, hosts } = await this.remoteTarget(params);
5403
- const { peerBrowse } = await import('./remote/client.js');
5404
- return await this.peerCall(target, hosts, host => peerBrowse(target, rootId, rel, host));
6665
+ return await this.hostOperation(params, 'browse', { root: rootId, rel });
5405
6666
  }
5406
6667
  async remoteOwnerRoots(params) {
5407
- const { target, hosts } = await this.remoteTarget(params);
5408
- const { peerOwnerRoots } = await import('./remote/client.js');
5409
- return this.peerCall(target, hosts, host => peerOwnerRoots(target, host));
6668
+ return this.hostOperation(params, 'owner.roots');
5410
6669
  }
5411
6670
  async remoteOwnerBrowse(params) {
5412
6671
  if (typeof params.path !== 'string' || params.path.length > 4096)
5413
6672
  throw new AppServerError('invalid-params', 'Host path required');
5414
- const { target, hosts } = await this.remoteTarget(params);
5415
- const { peerOwnerBrowse } = await import('./remote/client.js');
5416
- return this.peerCall(target, hosts, host => peerOwnerBrowse(target, params.path, host));
6673
+ return this.hostOperation(params, 'owner.browse', { path: params.path });
5417
6674
  }
5418
6675
  async remoteOwnerAddProject(params) {
5419
6676
  if (typeof params.path !== 'string' || params.path.length > 4096)
5420
6677
  throw new AppServerError('invalid-params', 'Host path required');
5421
- const { target, hosts } = await this.remoteTarget(params);
5422
- const { peerOwnerAddProject } = await import('./remote/client.js');
5423
- return this.peerCall(target, hosts, host => peerOwnerAddProject(target, params.path, host));
6678
+ return this.hostOperation(params, 'owner.projects.add', { path: params.path, ...(typeof params.name === 'string' ? { name: params.name } : {}) });
5424
6679
  }
5425
6680
  async listProjects() {
5426
6681
  const config = await loadConfig(this.directory);
@@ -5433,7 +6688,7 @@ export class AppServer {
5433
6688
  const realPath = await realpath(path).catch(() => undefined);
5434
6689
  if (!realPath || !(await stat(realPath).catch(() => undefined))?.isDirectory())
5435
6690
  throw new AppServerError('not-found', `No folder exists at ${path}.`);
5436
- const { addProjectEntry } = await import('./remote/pairing.js');
6691
+ const { addProjectEntry } = await import('./project-registry.js');
5437
6692
  await addProjectEntry(realPath, { directory: this.directory, ...(typeof params.name === 'string' ? { name: params.name } : {}) })
5438
6693
  .catch((error) => { throw new AppServerError('storage', message(error)); });
5439
6694
  return { ok: true };
@@ -5443,7 +6698,7 @@ export class AppServer {
5443
6698
  if (!path || path.includes('\0'))
5444
6699
  throw new AppServerError('invalid-params', 'projects.remove requires a folder path.');
5445
6700
  const stored = await realpath(path).catch(() => path);
5446
- const { removeProjectEntry } = await import('./remote/pairing.js');
6701
+ const { removeProjectEntry } = await import('./project-registry.js');
5447
6702
  return { removed: await removeProjectEntry(stored, this.directory) };
5448
6703
  }
5449
6704
  /** The browser profile a task browses on: its project identity when it carries one, otherwise its folder. */
@@ -5580,7 +6835,7 @@ export class AppServer {
5580
6835
  if (visibilityMoved)
5581
6836
  announceGraphVisibilityChange();
5582
6837
  if (merged) {
5583
- const { removeProjectEntry, rememberProjectIdentity } = await import('./remote/pairing.js');
6838
+ const { removeProjectEntry, rememberProjectIdentity } = await import('./project-registry.js');
5584
6839
  await removeProjectEntry(from, this.directory)
5585
6840
  .catch((error) => { throw new AppServerError('storage', message(error)); });
5586
6841
  await rememberProjectIdentity(to, targetIdentity ?? projectIdentity(to), this.directory)
@@ -5588,7 +6843,7 @@ export class AppServer {
5588
6843
  return { ok: true, path: to, name: projects.find(project => project.path === to)?.name ?? name, moved, merged: true };
5589
6844
  }
5590
6845
  if (fromListed) {
5591
- const { relinkProjectEntry, rememberProjectIdentity } = await import('./remote/pairing.js');
6846
+ const { relinkProjectEntry, rememberProjectIdentity } = await import('./project-registry.js');
5592
6847
  await relinkProjectEntry(from, to, { directory: this.directory, name })
5593
6848
  .catch((error) => { throw new AppServerError('storage', message(error)); });
5594
6849
  await rememberProjectIdentity(to, carried, this.directory)
@@ -5645,6 +6900,8 @@ export class AppServer {
5645
6900
  }
5646
6901
  emitPullRequest(sessionId, pullRequest) {
5647
6902
  this.emit('session.pullRequest.updated', { sessionId, pullRequest: pullRequestForClients(pullRequest) });
6903
+ // An attach, a finish or a dismiss changes the watched set: the GitHub App subscriptions follow it.
6904
+ this.githubEvents.nudge();
5648
6905
  const waiter = this.reviewWaiters.get(sessionId);
5649
6906
  if (!waiter)
5650
6907
  return;
@@ -5652,10 +6909,48 @@ export class AppServer {
5652
6909
  waiter({ kind: 'none' });
5653
6910
  else if (isFinishedPullRequest(pullRequest.state))
5654
6911
  waiter({ kind: 'finished', pullRequest });
5655
- else if (!pullRequest.autoFix)
5656
- waiter({ kind: 'off', pullRequest });
6912
+ else {
6913
+ const ended = this.watchedLoopEnded(sessionId, pullRequest);
6914
+ if (ended)
6915
+ waiter(ended);
6916
+ // A wait goes on while Auto-fix or a review loop is on: it answers off only when neither is.
6917
+ else if (!pullRequest.autoFix && !chatReviewLoopActive(pullRequest))
6918
+ waiter({ kind: 'off', pullRequest });
6919
+ }
6920
+ }
6921
+ /**
6922
+ * The end of the review loop a wait watches: the loop running when the wait started, or the first one switched on
6923
+ * while it waits. A loop that had already ended before is never answered again.
6924
+ */
6925
+ watchedLoopEnded(sessionId, pullRequest) {
6926
+ const wait = this.reviewWaitRuns.get(sessionId);
6927
+ if (!wait)
6928
+ return undefined;
6929
+ const review = pullRequest.review;
6930
+ if (wait.loop === undefined && chatReviewLoopActive(pullRequest))
6931
+ wait.loop = review.loop;
6932
+ if (wait.loop === undefined || review?.loop !== wait.loop || review.phase !== 'ended' || review.ended === undefined)
6933
+ return undefined;
6934
+ return { kind: 'review-ended', pullRequest, reason: review.ended.reason, ...(review.ended.detail === undefined ? {} : { detail: review.ended.detail }) };
6935
+ }
6936
+ /** A wait ended: the marker that held the review loop's round for it goes, unless a newer wait wrote its own. */
6937
+ async clearReviewWaiting(sessionId, wait) {
6938
+ if (wait.runId === undefined)
6939
+ return;
6940
+ const cleared = await withPullRequest(this.directory, sessionId, async () => {
6941
+ const current = await readPullRequest(this.directory, sessionId);
6942
+ const waiting = current?.review?.waiting;
6943
+ if (!current?.review || waiting === undefined || waiting.runId !== wait.runId || waiting.since !== wait.since)
6944
+ return undefined;
6945
+ const { waiting: _gone, ...review } = current.review;
6946
+ const next = { ...current, review, updatedAt: new Date().toISOString() };
6947
+ await writePullRequest(this.directory, sessionId, next);
6948
+ return next;
6949
+ });
6950
+ if (cleared)
6951
+ this.emitPullRequest(sessionId, cleared);
5657
6952
  }
5658
- async awaitReview(sessionId, signal, timeoutMs, origin) {
6953
+ async awaitReview(sessionId, signal, timeoutMs, origin, options = {}) {
5659
6954
  if (signal.aborted)
5660
6955
  return { kind: 'aborted' };
5661
6956
  if (this.reviewWaiters.has(sessionId) || this.reviewWaitsStarting.has(sessionId))
@@ -5676,15 +6971,22 @@ export class AppServer {
5676
6971
  }
5677
6972
  return await new Promise(resolve => {
5678
6973
  let settled = false;
6974
+ let signalTimer;
6975
+ // The run that waits: the review loop's round counts it as held while it waits (`review.waiting`).
6976
+ const wait = { ...(this.run?.sessionId === sessionId ? { runId: this.run.runId } : {}), since: new Date().toISOString() };
5679
6977
  const finish = (ended) => {
5680
6978
  if (settled)
5681
6979
  return false;
5682
6980
  settled = true;
5683
6981
  clearTimeout(timeout);
6982
+ clearTimeout(signalTimer);
5684
6983
  clearInterval(ticks);
5685
6984
  signal.removeEventListener('abort', aborted);
5686
6985
  if (this.reviewWaiters.get(sessionId) === finish)
5687
6986
  this.reviewWaiters.delete(sessionId);
6987
+ if (this.reviewWaitRuns.get(sessionId) === wait)
6988
+ this.reviewWaitRuns.delete(sessionId);
6989
+ void this.clearReviewWaiting(sessionId, wait).catch(error => this.log('warn', `Could not clear the review wait of session ${sessionId}: ${message(error)}`));
5688
6990
  resolve(ended);
5689
6991
  return true;
5690
6992
  };
@@ -5693,6 +6995,19 @@ export class AppServer {
5693
6995
  const fromRecord = () => {
5694
6996
  void this.reviewWaitFromRecord(sessionId, finish).catch(error => this.log('warn', `Could not read the pull request of session ${sessionId} for a review wait: ${message(error)}`));
5695
6997
  };
6998
+ // Codex's reactions come with no notice and are in no record, so the wait reads them itself: now, and
6999
+ // then as often as each read asks (sooner while a quiet head waits out the delay before a bump).
7000
+ const watch = {};
7001
+ const fromSignals = () => {
7002
+ void this.reviewWaitFromSignals(sessionId, finish, watch, () => settled, options.approveBump)
7003
+ .catch(error => { this.log('warn', `Could not read Codex's review signals for session ${sessionId}: ${message(error)}`); return this.reviewSignalMs; })
7004
+ .then(delay => {
7005
+ if (settled)
7006
+ return;
7007
+ signalTimer = setTimeout(fromSignals, delay);
7008
+ signalTimer.unref?.();
7009
+ });
7010
+ };
5696
7011
  let tick = 0;
5697
7012
  const ticks = setInterval(() => {
5698
7013
  const live = this.run;
@@ -5708,12 +7023,100 @@ export class AppServer {
5708
7023
  finish({ kind: 'aborted' });
5709
7024
  return;
5710
7025
  }
7026
+ this.reviewWaitRuns.set(sessionId, wait);
5711
7027
  this.reviewWaiters.set(sessionId, finish);
5712
7028
  fromRecord();
5713
- void this.pullRequestWatcher.poll();
7029
+ void this.pullRequestWatcher.readNow(sessionId);
7030
+ fromSignals();
5714
7031
  });
5715
7032
  }
7033
+ /**
7034
+ * One read of Codex's signals on a waiting session's PR; answers how long until the next read.
7035
+ *
7036
+ * A sign-off on the head commit ends the wait as approved, unless a review comment is still to be handed
7037
+ * over: comments come first. Where Codex shows nothing at all for the head (no eyes, no review, no comment,
7038
+ * nobody asked yet), the next read comes after the bump delay, and if that one is as quiet the wait posts
7039
+ * "@codex review", once per head and only in a repository Codex is known to review.
7040
+ */
7041
+ async reviewWaitFromSignals(sessionId, deliver, watch, settled, approveBump) {
7042
+ const every = this.reviewSignalMs;
7043
+ const current = await readPullRequest(this.directory, sessionId);
7044
+ // The record's own states (gone, finished, Auto-fix off) end the wait through the record.
7045
+ if (!current || isFinishedPullRequest(current.state) || !current.autoFix)
7046
+ return every;
7047
+ const gh = ghFor(this.gh, current);
7048
+ const seen = await readReviewSignals(gh, current);
7049
+ if (settled())
7050
+ return every;
7051
+ const head = seen.headSha;
7052
+ if (seen.approved) {
7053
+ delete watch.quiet;
7054
+ if (current.pendingFix !== undefined)
7055
+ return every;
7056
+ // An Andorra review loop in progress decides when this task's review is done: Codex's sign-off does not end the wait.
7057
+ if (chatReviewLoopActive(current))
7058
+ return every;
7059
+ const found = await newReviewComments(gh, current);
7060
+ if (found.threads > 0 || found.comments > 0) {
7061
+ void this.pullRequestWatcher.readNow(sessionId);
7062
+ return every;
7063
+ }
7064
+ deliver({ kind: 'approved', pullRequest: current, ...(head === undefined ? {} : { headSha: head }) });
7065
+ return every;
7066
+ }
7067
+ if (!approveBump || head === undefined || !seen.open || seen.reviewing || seen.reviewed || seen.asked || current.reviewBumped === head || watch.skipped === head) {
7068
+ delete watch.quiet;
7069
+ return every;
7070
+ }
7071
+ // The first quiet read only starts the delay: Codex usually reacts within seconds of a push.
7072
+ if (watch.quiet !== head) {
7073
+ watch.quiet = head;
7074
+ return this.reviewBumpDelayMs;
7075
+ }
7076
+ delete watch.quiet;
7077
+ const repository = `${current.owner}/${current.repo}`.toLowerCase();
7078
+ if (!seen.codexSeen && !this.codexRepositories.has(repository) && !await codexReviewsRepository(gh, current)) {
7079
+ watch.skipped = head;
7080
+ return every;
7081
+ }
7082
+ this.codexRepositories.add(repository);
7083
+ try {
7084
+ await approveBump(`Posts "${REVIEW_BUMP_COMMENT}" on ${current.url} as ${current.ghUser ?? 'your gh account'}, because Codex shows no sign of reviewing ${head.slice(0, 10)}.`);
7085
+ }
7086
+ catch (error) {
7087
+ this.log('info', `Did not ask Codex to review ${current.url}: ${message(error)}`);
7088
+ watch.skipped = head;
7089
+ return every;
7090
+ }
7091
+ if (settled())
7092
+ return every;
7093
+ // Recorded before it is posted: a head is asked for once, even when the post's outcome is unknown.
7094
+ const claimed = await withPullRequest(this.directory, sessionId, async () => {
7095
+ const latest = await readPullRequest(this.directory, sessionId);
7096
+ if (!latest || latest.url !== current.url || isFinishedPullRequest(latest.state) || !latest.autoFix || latest.reviewBumped === head)
7097
+ return false;
7098
+ await writePullRequest(this.directory, sessionId, { ...latest, reviewBumped: head, updatedAt: new Date().toISOString() });
7099
+ return true;
7100
+ });
7101
+ if (!claimed)
7102
+ return every;
7103
+ try {
7104
+ await gh(['pr', 'comment', current.url, '--body', REVIEW_BUMP_COMMENT]);
7105
+ this.log('info', `Asked Codex to review ${current.url} at ${head.slice(0, 10)}: it showed no sign of reviewing that commit.`);
7106
+ }
7107
+ catch (error) {
7108
+ this.log('warn', `Could not post "${REVIEW_BUMP_COMMENT}" on ${current.url}: ${message(error)}`);
7109
+ }
7110
+ return every;
7111
+ }
7112
+ /**
7113
+ * One look at the record for a wait, in whichever engine process it runs: how the PR or the review loop ended, the
7114
+ * review loop's next round (taken from the record, so a round another process posted reaches this wait), Auto-fix's
7115
+ * comments, and the marker that tells the lease holder this run waits.
7116
+ */
5716
7117
  async reviewWaitFromRecord(sessionId, deliver) {
7118
+ const wait = this.reviewWaitRuns.get(sessionId);
7119
+ let marked = false;
5717
7120
  const taken = await withPullRequest(this.directory, sessionId, async () => {
5718
7121
  const current = await readPullRequest(this.directory, sessionId);
5719
7122
  if (!current) {
@@ -5724,24 +7127,51 @@ export class AppServer {
5724
7127
  deliver({ kind: 'finished', pullRequest: current });
5725
7128
  return undefined;
5726
7129
  }
5727
- if (!current.autoFix) {
7130
+ const ended = this.watchedLoopEnded(sessionId, current);
7131
+ if (ended) {
7132
+ deliver(ended);
7133
+ return undefined;
7134
+ }
7135
+ const looping = chatReviewLoopActive(current);
7136
+ if (!current.autoFix && !looping) {
5728
7137
  deliver({ kind: 'off', pullRequest: current });
5729
7138
  return undefined;
5730
7139
  }
7140
+ const at = new Date().toISOString();
7141
+ let next = current;
7142
+ if (looping && wait?.runId !== undefined) {
7143
+ const review = current.review;
7144
+ const pendingReview = review.pendingReview;
7145
+ if (review.phase === 'fixing' && pendingReview !== undefined && pendingReview.runId === undefined && !this.timers.isHeld(pendingReview.wakeId)
7146
+ && deliver({ kind: 'review', prompt: pendingReview.prompt })) {
7147
+ if (this.reviewWakes.has(pendingReview.wakeId))
7148
+ this.cancelReviewWake(sessionId, pendingReview.wakeId);
7149
+ next = { ...current, review: { ...review, pendingReview: { ...pendingReview, runId: wait.runId, deliveredAt: at, held: true } }, updatedAt: at };
7150
+ await writePullRequest(this.directory, sessionId, next);
7151
+ return next;
7152
+ }
7153
+ if (review.waiting?.runId !== wait.runId || review.waiting.since !== wait.since) {
7154
+ next = { ...current, review: { ...review, waiting: { runId: wait.runId, since: wait.since } }, updatedAt: at };
7155
+ marked = true;
7156
+ }
7157
+ }
5731
7158
  const pending = current.pendingFix;
5732
- if (pending === undefined || this.timers.isHeld(pending.wakeId))
7159
+ const prompt = !current.autoFix || pending === undefined || this.timers.isHeld(pending.wakeId) ? undefined : pending.prompt ?? this.timers.get(pending.wakeId)?.prompt;
7160
+ if (pending !== undefined && prompt !== undefined && deliver({ kind: 'comments', prompt })) {
7161
+ if (this.autoFixWakes.has(pending.wakeId))
7162
+ this.cancelAutoFixWake(sessionId, pending.wakeId);
7163
+ next = { ...handedOver(next, pending), updatedAt: at };
7164
+ marked = false;
7165
+ }
7166
+ if (next === current)
5733
7167
  return undefined;
5734
- const prompt = pending.prompt ?? this.timers.get(pending.wakeId)?.prompt;
5735
- if (prompt === undefined || !deliver({ kind: 'comments', prompt }))
5736
- return undefined;
5737
- if (this.autoFixWakes.has(pending.wakeId))
5738
- this.cancelAutoFixWake(sessionId, pending.wakeId);
5739
- const next = { ...handedOver(current, pending), updatedAt: new Date().toISOString() };
5740
7168
  await writePullRequest(this.directory, sessionId, next);
5741
7169
  return next;
5742
7170
  });
5743
7171
  if (taken)
5744
7172
  this.emitPullRequest(sessionId, taken);
7173
+ if (marked)
7174
+ this.reviewLoop.waitStarted(sessionId);
5745
7175
  }
5746
7176
  async recordAutoFixDelivered(sessionId, wakeId) {
5747
7177
  try {
@@ -5757,8 +7187,22 @@ export class AppServer {
5757
7187
  this.emit('session.changes.updated', { sessionId: changes.sessionId, revision: changes.revision, changes: changes.changes });
5758
7188
  }
5759
7189
  async attachPullRequest(sessionId, ref, settings = {}, carry, origin) {
7190
+ const { gh: ghSettings, review: reviewSettings } = splitPullRequestSettings(settings);
7191
+ // Before the record's lock and before any gh write: the reviewer's model and the plan read (up to 10 s).
7192
+ const model = await this.reviewModelChange(reviewSettings);
7193
+ if (reviewSettings.review === true) {
7194
+ const before = await readPullRequest(this.directory, sessionId);
7195
+ if (!(before?.url === ref.url && reviewLoopActive(before)))
7196
+ await this.checkReviewPlan();
7197
+ }
7198
+ const afterTurns = reviewSettings.review === undefined ? undefined : await this.sessionTurnCount(sessionId);
7199
+ let replaced;
7200
+ let reviewed;
5760
7201
  const attached = await withPullRequest(this.directory, sessionId, async () => {
5761
7202
  const current = await readPullRequest(this.directory, sessionId);
7203
+ // Another PR replaces this task's: a loop running on the old one goes with it.
7204
+ if (current && current.url !== ref.url && reviewLoopActive(current))
7205
+ replaced = current.review;
5762
7206
  let next = current?.url === ref.url ? current : newPullRequest(ref);
5763
7207
  if (next !== current) {
5764
7208
  const read = await readPullRequestAsAnyAccount(this.gh, ref.url);
@@ -5771,33 +7215,181 @@ export class AppServer {
5771
7215
  }
5772
7216
  if (carry !== undefined)
5773
7217
  next = { ...next, carry: structuredClone(carry) };
5774
- if (origin !== undefined && (settings.autoFix === true || next.origin === undefined))
7218
+ // The node that switched Auto-fix or Andorra review on is where their wakes go.
7219
+ if (origin !== undefined && (settings.autoFix === true || settings.review === true || next.origin === undefined))
5775
7220
  next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
5776
- if (Object.keys(settings).length)
5777
- next = await applyPullRequestSettingsAsReadableAccount(this.gh, next, settings);
7221
+ // A refused switch-on changes nothing: its checks, and the settings' own, run before any gh write.
7222
+ if (Object.keys(reviewSettings).length) {
7223
+ if (reviewSettings.review === true && !reviewLoopActive(next))
7224
+ await this.checkReviewSwitchOn(sessionId, next);
7225
+ this.applyReviewSettingsTo(next, reviewSettings, model);
7226
+ }
7227
+ if (Object.keys(ghSettings).length)
7228
+ next = await applyPullRequestSettingsAsReadableAccount(this.gh, next, ghSettings);
7229
+ if (Object.keys(reviewSettings).length) {
7230
+ reviewed = this.applyReviewSettingsTo(next, reviewSettings, model, afterTurns);
7231
+ next = reviewed.next;
7232
+ }
5778
7233
  await writePullRequest(this.directory, sessionId, next);
5779
7234
  return next;
5780
7235
  });
5781
7236
  this.emitPullRequest(sessionId, attached);
7237
+ if (replaced)
7238
+ this.reviewLoop.ended(sessionId, replaced, 'switched-off', 'Another pull request was attached to this task.');
7239
+ this.reviewSettingsApplied(sessionId, reviewed);
5782
7240
  if (pullRequestNeedsWatch(attached))
5783
- void this.pullRequestWatcher.poll();
7241
+ void this.pullRequestWatcher.readNow(sessionId);
5784
7242
  return attached;
5785
7243
  }
7244
+ /** How many turns a task's history holds, a running turn included, for the review loop's transcript lines. */
7245
+ async sessionTurnCount(sessionId) {
7246
+ const session = await this.readSession(sessionId).catch(() => undefined);
7247
+ return Array.isArray(session?.history) ? session.history.length : undefined;
7248
+ }
7249
+ /** The reviewer's model from `reviewModel`: null clears it, undefined leaves it; a provider this engine lacks is refused. */
7250
+ async reviewModelChange(settings) {
7251
+ if (settings.reviewModel === undefined)
7252
+ return undefined;
7253
+ const parsed = settings.reviewModel === '' ? null : parseReviewModel(settings.reviewModel);
7254
+ if (parsed === undefined)
7255
+ throw new AppServerError('invalid-params', 'reviewModel must be provider/model');
7256
+ if (parsed !== null && !(await loadConfig(this.directory)).providers.some(provider => provider.id === parsed.provider)) {
7257
+ throw new AppServerError('invalid-params', `reviewModel names the provider ${parsed.provider}, which this engine does not have.`);
7258
+ }
7259
+ return parsed;
7260
+ }
7261
+ /** The Andorra review loop's settings on a record (the switch-on checks were made); the gh-backed settings are not here. */
7262
+ applyReviewSettingsTo(current, settings, model, afterTurns) {
7263
+ try {
7264
+ const applied = applyReviewSettings(current, settings, { now: new Date(), newLoop: () => newReviewLoopId(), ...(model === undefined ? {} : { model }), ...(afterTurns === undefined ? {} : { afterTurns }) });
7265
+ return { ...applied, ...(current.review === undefined ? {} : { before: current.review }) };
7266
+ }
7267
+ catch (error) {
7268
+ throw new AppServerError('invalid-params', message(error));
7269
+ }
7270
+ }
7271
+ /** A graph run's Andorra review nodes: rounds on the session's PR through the review loop (design/specs/andorra-review-loop.md, R12). */
7272
+ reviewNodeService(sessionId, runId, resumedFrom, steers) {
7273
+ return createReviewNodeService({
7274
+ home: this.directory, sessionId, runId, controller: this.reviewLoop, ...(resumedFrom === undefined ? {} : { resumedFrom }),
7275
+ enabled: () => readGitHubAppReviewsEnabled(this.directory),
7276
+ plan: async () => { try {
7277
+ await this.checkReviewPlan();
7278
+ return undefined;
7279
+ }
7280
+ catch (error) {
7281
+ return message(error);
7282
+ } },
7283
+ coverage: pullRequest => this.reviewCoverage(sessionId, pullRequest),
7284
+ readNow: () => this.pullRequestWatcher.readNow(sessionId),
7285
+ head: async () => { await this.pullRequestWatcher.readNow(sessionId).catch(() => { }); return this.pullRequestWatcher.headSha(sessionId); },
7286
+ writes: () => this.autoFixWrites(sessionId),
7287
+ steers,
7288
+ });
7289
+ }
7290
+ /** R18: not on the Free plan, and not while the plan cannot be read. Read outside the PR record's lock (up to 10 s). */
7291
+ async checkReviewPlan() {
7292
+ // Signed out, the plan read answers Free: say what is really missing.
7293
+ if (!await this.githubSignedIn().catch(() => false))
7294
+ throw new AppServerError('forbidden', coverageRefusal('signed-out', { owner: '', repo: '' }));
7295
+ const access = await this.githubMembership(AbortSignal.timeout(10_000)).catch(() => ({ paid: false, unavailable: true }));
7296
+ if (access.unavailable && !access.paid)
7297
+ throw new AppServerError('forbidden', 'Can\'t check your plan right now. Andorra review needs a paid plan; try again in a minute.');
7298
+ if (membershipPlanLabel(access.tier, access.paid) === 'Free')
7299
+ throw new AppServerError('forbidden', 'Andorra review needs a paid plan.');
7300
+ }
7301
+ /**
7302
+ * Why the Andorra review loop cannot be switched on for this PR (design/specs/andorra-review-loop.md, R11, R17), if it
7303
+ * cannot: the checks on the record as it is now, under its lock. The plan (R18) is read before the lock.
7304
+ */
7305
+ async checkReviewSwitchOn(sessionId, current) {
7306
+ const refuse = (text) => { throw new AppServerError('forbidden', text); };
7307
+ if (!await readGitHubAppReviewsEnabled(this.directory))
7308
+ refuse('Andorra review is turned off on this machine (github.app.reviews is false in the config).');
7309
+ if (isFinishedPullRequest(current.state))
7310
+ refuse(`${current.url} is ${current.state}; there is nothing left to review.`);
7311
+ const key = (pullRequest) => `${pullRequest.owner.toLowerCase()}/${pullRequest.repo.toLowerCase()}#${pullRequest.number}`;
7312
+ const tracked = await listPullRequests(this.directory).catch(() => []);
7313
+ if (tracked.some(entry => entry.sessionId !== sessionId && key(entry.pullRequest) === key(current) && reviewLoopActive(entry.pullRequest)))
7314
+ refuse('Another task is already reviewing this pull request.');
7315
+ // Coverage still being learned (`pending`, `unavailable`) is allowed: the round waits for it, up to an hour.
7316
+ const coverage = await this.reviewCoverage(sessionId, current);
7317
+ if (!coverageAllowsReview(coverage))
7318
+ refuse(coverageRefusal(coverage, current));
7319
+ }
7320
+ /** After a settings write: a switch-off ends the loop's round and wake; anything else is looked at by the loop. */
7321
+ reviewSettingsApplied(sessionId, applied) {
7322
+ if (applied === undefined)
7323
+ return;
7324
+ if (applied.switchedOff && applied.before)
7325
+ this.reviewLoop.ended(sessionId, applied.before, 'switched-off');
7326
+ this.reviewLoop.settingsChanged(sessionId);
7327
+ }
7328
+ /** A PR a task's `gh pr create` opened: with `github.app.reviewNewPullRequests`, its review loop starts on. A refusal is logged. */
7329
+ async reviewNewPullRequest(sessionId, attached) {
7330
+ if (attached.review !== undefined || !await readGitHubAppReviewNewPullRequests(this.directory))
7331
+ return;
7332
+ try {
7333
+ await this.updatePullRequest(sessionId, { review: true });
7334
+ this.log('info', `Andorra review is on for ${attached.url}, a pull request this task opened.`);
7335
+ }
7336
+ catch (error) {
7337
+ this.log('info', `Andorra review was not switched on for ${attached.url}: ${message(error)}`);
7338
+ }
7339
+ }
7340
+ /** The PR's GitHub App coverage for the review loop: the event source's, or the lease holder's in another process. */
7341
+ async reviewCoverage(sessionId, pullRequest) {
7342
+ if (!await readGitHubAppEventsEnabled(this.directory))
7343
+ return 'disabled';
7344
+ const snapshot = await this.githubEvents.snapshot();
7345
+ const entry = snapshot.pullRequests.find(candidate => candidate.sessionId === sessionId);
7346
+ return entry?.url === pullRequest.url ? entry.coverage : snapshot.reason ?? 'pending';
7347
+ }
7348
+ /** Whether a run of the session is open anywhere, leaving out `except`: the run held in await_review. */
7349
+ async sessionBusyForReview(sessionId, except) {
7350
+ if (this.run?.sessionId === sessionId && this.run.runId !== except)
7351
+ return true;
7352
+ // `startingSession` is known only for a resume: a start being prepared may be this task's (a continued session).
7353
+ if (this.starting && (this.startingSession === undefined || this.startingSession === sessionId))
7354
+ return true;
7355
+ return sessionHasOpenRun(this.directory, sessionId, except === undefined ? {} : { ignoreRunId: except });
7356
+ }
5786
7357
  async updatePullRequest(sessionId, settings, carry, origin) {
7358
+ const { gh: ghSettings, review: reviewSettings } = splitPullRequestSettings(settings);
7359
+ // Before the record's lock and before any gh write: the reviewer's model and the plan read (up to 10 s).
7360
+ const model = await this.reviewModelChange(reviewSettings);
7361
+ if (reviewSettings.review === true) {
7362
+ const before = await readPullRequest(this.directory, sessionId);
7363
+ if (before && !reviewLoopActive(before))
7364
+ await this.checkReviewPlan();
7365
+ }
7366
+ const afterTurns = reviewSettings.review === undefined ? undefined : await this.sessionTurnCount(sessionId);
7367
+ let reviewed;
5787
7368
  const updated = await withPullRequest(this.directory, sessionId, async () => {
5788
7369
  const current = await readPullRequest(this.directory, sessionId);
5789
7370
  if (!current)
5790
7371
  throw new AppServerError('not-found', 'This session has no pull request.');
7372
+ // A refused switch-on changes nothing: its checks, and the settings' own, run before any gh write.
7373
+ if (Object.keys(reviewSettings).length) {
7374
+ if (reviewSettings.review === true && !reviewLoopActive(current))
7375
+ await this.checkReviewSwitchOn(sessionId, current);
7376
+ this.applyReviewSettingsTo(current, reviewSettings, model);
7377
+ }
5791
7378
  let next;
5792
7379
  try {
5793
- next = await applyPullRequestSettingsAsReadableAccount(this.gh, current, settings);
7380
+ next = await applyPullRequestSettingsAsReadableAccount(this.gh, current, ghSettings);
5794
7381
  }
5795
7382
  catch (error) {
5796
7383
  throw new AppServerError('remote', message(error));
5797
7384
  }
7385
+ if (Object.keys(reviewSettings).length) {
7386
+ reviewed = this.applyReviewSettingsTo(next, reviewSettings, model, afterTurns);
7387
+ next = reviewed.next;
7388
+ }
5798
7389
  if (carry !== undefined)
5799
7390
  next = { ...next, carry: structuredClone(carry) };
5800
- if (origin !== undefined && settings.autoFix === true)
7391
+ // The node that switched Auto-fix or Andorra review on is where their wakes go.
7392
+ if (origin !== undefined && (settings.autoFix === true || settings.review === true))
5801
7393
  next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
5802
7394
  if (!next.autoFix && next.pendingFix) {
5803
7395
  this.cancelAutoFixWake(sessionId, next.pendingFix.wakeId);
@@ -5807,19 +7399,268 @@ export class AppServer {
5807
7399
  return next;
5808
7400
  });
5809
7401
  this.emitPullRequest(sessionId, updated);
7402
+ this.reviewSettingsApplied(sessionId, reviewed);
5810
7403
  if (pullRequestNeedsWatch(updated))
5811
- void this.pullRequestWatcher.poll();
7404
+ void this.pullRequestWatcher.readNow(sessionId);
5812
7405
  return updated;
5813
7406
  }
5814
- async dismissPullRequest(sessionId) {
5815
- await withPullRequest(this.directory, sessionId, async () => {
7407
+ /** With `agentChecked`, the agent's dismiss: the record is removed only while it is still that open PR. */
7408
+ async dismissPullRequest(sessionId, agentChecked) {
7409
+ const dismissed = await withPullRequest(this.directory, sessionId, async () => {
5816
7410
  const current = await readPullRequest(this.directory, sessionId);
7411
+ if (agentChecked !== undefined && current) {
7412
+ if (isFinishedPullRequest(current.state))
7413
+ throw new Error(keptPullRequestMessage(current));
7414
+ if (current.url !== agentChecked)
7415
+ throw new Error(`This task's pull request changed to ${current.url} while the dismiss was being checked. Nothing was changed.`);
7416
+ }
5817
7417
  if (current?.pendingFix)
5818
7418
  this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
5819
7419
  await removePullRequest(this.directory, sessionId);
7420
+ return current;
5820
7421
  });
5821
7422
  this.pullRequestReader.forget(sessionId);
5822
7423
  this.emitPullRequest(sessionId, null);
7424
+ // Dismissing the PR switches its review loop off: the round stops and the fixer's wake is withdrawn.
7425
+ if (dismissed?.review && reviewLoopActive(dismissed))
7426
+ this.reviewLoop.ended(sessionId, dismissed.review, 'switched-off', 'The pull request was dismissed from this task.');
7427
+ }
7428
+ /**
7429
+ * The agent's own dismiss (the `pull_request` tool). A merged or closed PR stays on the task, where the
7430
+ * sidebar and the PR tab show how the work ended; only the person removes that one. GitHub is asked first,
7431
+ * because an agent that has just merged calls this before the watcher has recorded the merge.
7432
+ */
7433
+ async dismissPullRequestForAgent(sessionId) {
7434
+ const current = await readPullRequest(this.directory, sessionId);
7435
+ if (!current)
7436
+ return;
7437
+ let state = current.state;
7438
+ if (!isFinishedPullRequest(state)) {
7439
+ const read = await readPullRequestAsAnyAccount(this.gh, current.url);
7440
+ if (read.seen)
7441
+ state = read.seen.state;
7442
+ if (isFinishedPullRequest(state))
7443
+ await this.pullRequestWatcher.readNow(sessionId).catch(() => { });
7444
+ }
7445
+ if (isFinishedPullRequest(state))
7446
+ throw new Error(keptPullRequestMessage({ url: current.url, state }));
7447
+ // The record is read again under its lock: an attach or a watcher read may have changed it during the GitHub read.
7448
+ await this.dismissPullRequest(sessionId, current.url);
7449
+ }
7450
+ githubError(error) {
7451
+ if (error instanceof AppServerError)
7452
+ return error;
7453
+ if (!(error instanceof GitHubAppError))
7454
+ return new AppServerError('internal', message(error));
7455
+ switch (error.code) {
7456
+ case 'signed-out':
7457
+ case 'unauthorized': return new AppServerError('login-required', 'Sign in to Andorra first: the GitHub App works through your Andorra account.');
7458
+ case 'not-allowed': return new AppServerError('forbidden', 'The GitHub App is not available to this Andorra account yet.');
7459
+ case 'forbidden': return new AppServerError('forbidden', error.message);
7460
+ case 'rate-limited': return new AppServerError('busy', 'The Andorra account service asked to wait. Try again in a minute.');
7461
+ case 'unavailable': return new AppServerError('network', error.message);
7462
+ default: return new AppServerError('remote', error.message);
7463
+ }
7464
+ }
7465
+ /**
7466
+ * Settings → GitHub: the account's GitHub connection and installations from the account API, whether this
7467
+ * engine is in event mode, and each watched PR's coverage. `not-covered` for a PR this engine reads through
7468
+ * gh becomes `not-installed`, with the hint to install the App there: the service never says "not installed".
7469
+ */
7470
+ async githubStatus() {
7471
+ const eventsOn = await readGitHubAppEventsEnabled(this.directory);
7472
+ const signedIn = await this.githubSignedIn().catch(() => false);
7473
+ let service;
7474
+ if (signedIn) {
7475
+ try {
7476
+ service = await this.githubClient.status();
7477
+ }
7478
+ catch (error) {
7479
+ // An account API without the GitHub App routes reads as the App being off, not as an error.
7480
+ if (!(error instanceof GitHubAppError && error.code === 'not-found'))
7481
+ throw this.githubError(error);
7482
+ service = { enabled: false, allowed: false, connection: null, installations: [] };
7483
+ }
7484
+ this.githubEvents.noteStatus(service);
7485
+ if (service.bot !== undefined)
7486
+ this.githubBot = service.bot;
7487
+ }
7488
+ const snapshot = await this.githubEvents.snapshot();
7489
+ const coverage = new Map(snapshot.pullRequests.map(entry => [entry.sessionId, entry]));
7490
+ const watched = (await listPullRequests(this.directory)).filter(entry => pullRequestNeedsWatch(entry.pullRequest));
7491
+ const localOff = !eventsOn ? (process.env.ANDORRA_GITHUB_APP?.trim().toLowerCase() === 'off' ? 'env' : 'config') : undefined;
7492
+ const pullRequests = watched.map(({ sessionId, pullRequest }) => {
7493
+ const known = coverage.get(sessionId);
7494
+ let state = !signedIn ? 'signed-out' : localOff !== undefined ? 'disabled' : known?.url === pullRequest.url ? known.coverage : 'pending';
7495
+ if (state === 'not-covered' && pullRequest.watchError === undefined)
7496
+ state = 'not-installed';
7497
+ return {
7498
+ sessionId, url: pullRequest.url, owner: pullRequest.owner, repo: pullRequest.repo, number: pullRequest.number, coverage: state,
7499
+ ...(state === 'not-installed' ? { hint: GITHUB_INSTALL_HINT(pullRequest.owner, pullRequest.repo), ...(service?.installUrl === undefined ? {} : { installUrl: service.installUrl }) } : {}),
7500
+ };
7501
+ });
7502
+ return {
7503
+ signedIn,
7504
+ enabled: service?.enabled ?? false,
7505
+ allowed: service?.allowed ?? false,
7506
+ ...(service?.bot === undefined ? {} : { bot: service.bot }),
7507
+ ...(service?.installUrl === undefined ? {} : { installUrl: service.installUrl }),
7508
+ connection: service?.connection ?? null,
7509
+ installations: service?.installations ?? [],
7510
+ agentWrites: await readGitHubAgentWrites(this.directory),
7511
+ // A mention can wake a task here only while this engine hears notices at all.
7512
+ triggers: eventsOn && await readGitHubAppTriggersEnabled(this.directory),
7513
+ // The Andorra review loop's per-machine settings: whether it may be switched on, and whether new PRs start with it.
7514
+ reviews: await readGitHubAppReviewsEnabled(this.directory),
7515
+ reviewNewPullRequests: await readGitHubAppReviewNewPullRequests(this.directory),
7516
+ events: {
7517
+ mode: !signedIn || localOff !== undefined ? 'off' : snapshot.mode,
7518
+ ...(localOff === undefined ? {} : { off: localOff }),
7519
+ ...(signedIn && localOff === undefined && snapshot.reason !== undefined ? { reason: snapshot.reason } : {}),
7520
+ },
7521
+ pullRequests,
7522
+ };
7523
+ }
7524
+ /** Settings → GitHub → "Agent replies on pull requests": `bot` (as the App's bot) or `me` (through gh as the person). Per engine. */
7525
+ async githubSetAgentWrites(params) {
7526
+ const value = params.value;
7527
+ if (typeof value !== 'string' || !GITHUB_AGENT_WRITES.includes(value))
7528
+ throw new AppServerError('invalid-params', 'value must be bot or me');
7529
+ const agentWrites = value;
7530
+ await this.serializeConfig(() => changeConfigFile(this.directory, current => ({
7531
+ ...current, github: { ...current.github, app: { ...current.github?.app, agentWrites } },
7532
+ })));
7533
+ return { agentWrites };
7534
+ }
7535
+ /**
7536
+ * Who an agent write on this session's PR goes to first, decided one way for the tool and the Auto-fix prompt:
7537
+ * the setting, and the PR's coverage as the event source (or, in another process, the lease holder) last
7538
+ * learned it. Events switched off here, or a PR the source has not looked at yet, are not covered.
7539
+ */
7540
+ async agentWriteRoute(sessionId, pullRequest) {
7541
+ const setting = await readGitHubAgentWrites(this.directory);
7542
+ if (setting === 'me')
7543
+ return { setting, coverage: 'disabled' };
7544
+ if (!await readGitHubAppEventsEnabled(this.directory))
7545
+ return { setting, coverage: 'disabled' };
7546
+ const snapshot = await this.githubEvents.snapshot();
7547
+ const entry = snapshot.pullRequests.find(candidate => candidate.sessionId === sessionId);
7548
+ return { setting, coverage: entry?.url === pullRequest.url ? entry.coverage : snapshot.reason ?? 'pending' };
7549
+ }
7550
+ /** The pull_request tool's reply, resolve and comment on the session's tracked PR (design/specs/github-app.md, "Bot replies"). */
7551
+ async agentPullRequestWrite(sessionId, write, options) {
7552
+ const pullRequest = await readPullRequest(this.directory, sessionId);
7553
+ if (!pullRequest)
7554
+ throw new Error('No pull request is tracked for this session; attach one first.');
7555
+ const { setting, coverage } = await this.agentWriteRoute(sessionId, pullRequest);
7556
+ // The approval names the bot it posts as.
7557
+ const botName = asksBot(setting, coverage) ? await this.githubBotName() : undefined;
7558
+ const current = async () => {
7559
+ const now = await readPullRequest(this.directory, sessionId);
7560
+ return now === undefined ? undefined : { pullRequest: now, ...await this.agentWriteRoute(sessionId, now) };
7561
+ };
7562
+ const result = await performAgentWrite({
7563
+ pullRequest, write, setting, coverage, client: this.githubClient, gh: this.gh, approve: options.approve, current,
7564
+ ...(botName === undefined ? {} : { botName }), ...(options.signal === undefined ? {} : { signal: options.signal }),
7565
+ });
7566
+ // Ids and the account only: never the body.
7567
+ const outcome = result.by === 'bot' ? `as ${result.as}` : result.by === 'gh' ? `through gh as ${result.as} (${result.reason})`
7568
+ : result.by === 'pending' ? `into ${result.as}'s pending review (${result.reason})` : `fate unknown (${result.requestId === undefined ? `through gh as ${result.as}` : `request ${result.requestId}`})`;
7569
+ this.log('info', `Agent ${write.action} on ${pullRequest.url}: ${outcome}`);
7570
+ if (result.by === 'bot' && result.as !== undefined)
7571
+ this.githubBot = result.as;
7572
+ // Phase 3: a mention of the bot in the agent's own reply or comment (through gh it is the person's) never
7573
+ // asks for this task again. Both routes are remembered, by the new comment's node id and link.
7574
+ if (write.action !== 'resolve' && (result.url !== undefined || result.nodeId !== undefined)) {
7575
+ await this.mentions.rememberOwn({ ...(result.nodeId === undefined ? {} : { id: result.nodeId }), ...(result.url === undefined ? {} : { url: result.url }) });
7576
+ }
7577
+ // An open PR tab shows the new reply or resolve at its next refresh; after one that may have posted, it shows whether it did.
7578
+ this.emit('session.pullRequest.stale', { sessionId });
7579
+ // The write went through gh only because no GitHub account is connected: a desktop offers to connect one.
7580
+ if (setting === 'bot' && coverage === 'not-connected')
7581
+ this.emit('github.connectNeeded', { sessionId });
7582
+ return result.text;
7583
+ }
7584
+ /** The App's bot login: `GET /v1/github`'s `bot`, read once (bounded) and kept, or learned from a write's `as`. */
7585
+ async githubBotName() {
7586
+ if (this.githubBot === undefined) {
7587
+ const status = await this.githubClient.status(AbortSignal.timeout(5_000)).catch(() => undefined);
7588
+ if (status?.bot !== undefined)
7589
+ this.githubBot = status.bot;
7590
+ }
7591
+ return this.githubBot;
7592
+ }
7593
+ /** For the Auto-fix prompt: whether this session's replies post as the bot (the tool's own rule), and the bot's name. */
7594
+ async autoFixWrites(sessionId) {
7595
+ const pullRequest = await readPullRequest(this.directory, sessionId);
7596
+ // The gh form names the bot only for its sentence on mentions: the name already known, never a read for it.
7597
+ const known = this.githubBot === undefined ? {} : { bot: this.githubBot };
7598
+ if (!pullRequest)
7599
+ return { botWrites: false, ...known };
7600
+ const { setting, coverage } = await this.agentWriteRoute(sessionId, pullRequest);
7601
+ if (!asksBot(setting, coverage))
7602
+ return { botWrites: false, ...known };
7603
+ // `<bot>` is GET /v1/github's `bot`; read once, and only when a covered PR's prompt needs it.
7604
+ const bot = await this.githubBotName();
7605
+ return { botWrites: true, ...(bot === undefined ? {} : { bot }) };
7606
+ }
7607
+ /**
7608
+ * For a mention's prompt: who the agent's answer posts as on this session's PR (the pull_request tool's rule),
7609
+ * and the bot's login, which also names the mention (`@andorra-code`, `@andorra-code-dev` on staging).
7610
+ */
7611
+ async mentionWrites(sessionId) {
7612
+ const pullRequest = await readPullRequest(this.directory, sessionId);
7613
+ const route = pullRequest === undefined ? undefined : await this.agentWriteRoute(sessionId, pullRequest);
7614
+ const bot = await this.githubBotName();
7615
+ return { botWrites: route !== undefined && asksBot(route.setting, route.coverage), ...(bot === undefined ? {} : { bot }) };
7616
+ }
7617
+ /**
7618
+ * Wakes the task for a mention, as Fix with Agent does: into a review wait the agent is in, or as the next
7619
+ * turn, shown as "Mentioned on GitHub". Each comment wakes once (`MentionTriggers` keeps the ids).
7620
+ */
7621
+ wakeForMention(sessionId, prompt, pullRequest) {
7622
+ const waiter = this.reviewWaiters.get(sessionId);
7623
+ if (waiter) {
7624
+ waiter({ kind: 'comments', prompt });
7625
+ return `review-${randomUUID()}`;
7626
+ }
7627
+ const timer = this.timers.arm(1, prompt, sessionId, pullRequest.carry, undefined);
7628
+ this.mentionWakes.add(timer.id);
7629
+ this.emitTimers(sessionId);
7630
+ this.armTimerCheck();
7631
+ return timer.id;
7632
+ }
7633
+ async githubConnect(params) {
7634
+ if (params.mode !== 'install' && params.mode !== 'authorize')
7635
+ throw new AppServerError('invalid-params', 'mode must be install or authorize');
7636
+ if (!await this.githubSignedIn().catch(() => false))
7637
+ throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
7638
+ let answer;
7639
+ try {
7640
+ answer = await this.githubClient.connect(params.mode);
7641
+ }
7642
+ catch (error) {
7643
+ throw this.githubError(error);
7644
+ }
7645
+ if (!answer.enabled)
7646
+ throw new AppServerError('forbidden', 'The GitHub App is turned off on the Andorra service for now.');
7647
+ return { url: answer.url };
7648
+ }
7649
+ async githubDisconnect() {
7650
+ if (!await this.githubSignedIn().catch(() => false))
7651
+ throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
7652
+ let answer;
7653
+ try {
7654
+ answer = await this.githubClient.disconnect();
7655
+ }
7656
+ catch (error) {
7657
+ throw this.githubError(error);
7658
+ }
7659
+ if (!answer.enabled)
7660
+ throw new AppServerError('forbidden', 'The GitHub App is turned off on the Andorra service for now.');
7661
+ // The service removed this account's subscriptions: the next subscription answers `not-connected`, and every PR is polled through gh.
7662
+ this.githubEvents.refresh();
7663
+ return { ok: true };
5823
7664
  }
5824
7665
  /**
5825
7666
  * The PR tab's read of a task's pull request: branches, author, mergeability, description, commits,
@@ -5999,7 +7840,7 @@ export class AppServer {
5999
7840
  if (written) {
6000
7841
  this.emitPullRequest(sessionId, written);
6001
7842
  if (pullRequestNeedsWatch(written))
6002
- void this.pullRequestWatcher.poll();
7843
+ void this.pullRequestWatcher.readNow(sessionId);
6003
7844
  }
6004
7845
  }
6005
7846
  /** A merge-side write's answer, with the merge state read again so the tab shows what GitHub now holds. */
@@ -6406,7 +8247,7 @@ export class AppServer {
6406
8247
  const prompt = fixChecksPrompt(pullRequest, {
6407
8248
  checks: failed.map(check => ({ name: check.name, ...(check.workflow === undefined ? {} : { workflow: check.workflow }), ...(check.url === undefined ? {} : { url: check.url }) })),
6408
8249
  ...(read.details.headSha === undefined ? {} : { headSha: read.details.headSha }), branch: read.details.headRefName, source: 'person',
6409
- });
8250
+ }, 0, { ...(this.githubBot === undefined ? {} : { bot: this.githubBot }) });
6410
8251
  const waiter = this.reviewWaiters.get(sessionId);
6411
8252
  if (waiter) {
6412
8253
  waiter({ kind: 'comments', prompt });
@@ -6598,7 +8439,7 @@ export class AppServer {
6598
8439
  async syncPullRequestRecord(sessionId, read, details) {
6599
8440
  const rollup = checksRollup(details.checks);
6600
8441
  if (details.state !== read.state && pullRequestNeedsWatch(read))
6601
- void this.pullRequestWatcher.poll();
8442
+ void this.pullRequestWatcher.readNow(sessionId);
6602
8443
  if (sameChecksRollup(rollup, read.checks))
6603
8444
  return;
6604
8445
  const written = await withPullRequest(this.directory, sessionId, async () => {
@@ -6629,10 +8470,33 @@ export class AppServer {
6629
8470
  return this.attachPullRequest(sessionId, ref, settings, carry, origin);
6630
8471
  },
6631
8472
  update: (settings, origin) => this.updatePullRequest(sessionId, settings, carry, origin),
6632
- awaitReview: (signal, timeoutMs, origin) => this.awaitReview(sessionId, signal, timeoutMs, origin),
6633
- dismiss: () => this.dismissPullRequest(sessionId),
8473
+ awaitReview: (signal, timeoutMs, origin, options) => this.awaitReview(sessionId, signal, timeoutMs, origin, options),
8474
+ dismiss: () => this.dismissPullRequestForAgent(sessionId),
8475
+ write: (write, options) => this.agentPullRequestWrite(sessionId, write, options),
6634
8476
  };
6635
8477
  }
8478
+ /**
8479
+ * The Andorra review loop's fixer wake: straight into a run of the session waiting in await_review here (which then holds
8480
+ * the round), or as the next turn, routed like Auto-fix's to the node that took the PR.
8481
+ */
8482
+ wakeForReview(sessionId, prompt, pullRequest) {
8483
+ const waiter = this.reviewWaiters.get(sessionId);
8484
+ const runId = this.reviewWaitRuns.get(sessionId)?.runId;
8485
+ if (waiter && runId !== undefined && waiter({ kind: 'review', prompt }))
8486
+ return { wakeId: `review-${randomUUID()}`, heldBy: runId };
8487
+ const timer = this.timers.arm(1, prompt, sessionId, pullRequest.carry, pullRequest.origin);
8488
+ this.reviewWakes.add(timer.id);
8489
+ this.emitTimers(sessionId);
8490
+ this.armTimerCheck();
8491
+ return { wakeId: timer.id };
8492
+ }
8493
+ cancelReviewWake(sessionId, wakeId) {
8494
+ this.reviewWakes.delete(wakeId);
8495
+ if (!this.timers.cancel(wakeId))
8496
+ return;
8497
+ void clearWakeClaim(this.directory, sessionId, wakeId).catch(() => { });
8498
+ this.emitTimers(sessionId);
8499
+ }
6636
8500
  wakeForPullRequest(sessionId, prompt, carry, origin) {
6637
8501
  const waiter = this.reviewWaiters.get(sessionId);
6638
8502
  if (waiter) {
@@ -6686,8 +8550,12 @@ export class AppServer {
6686
8550
  }
6687
8551
  spendWake(timer, reason) {
6688
8552
  this.timers.settle(timer.id);
8553
+ if (this.reviewWakes.delete(timer.id) && timer.owner !== undefined) {
8554
+ void this.reviewLoop.wakeSpent(timer.owner, timer.id, reason).catch(error => this.log('warn', `Could not end the Andorra review loop of session ${timer.owner}: ${message(error)}`));
8555
+ }
6689
8556
  this.autoFixWakes.delete(timer.id);
6690
8557
  this.fixWakes.delete(timer.id);
8558
+ this.mentionWakes.delete(timer.id);
6691
8559
  this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
6692
8560
  const sessionId = timer.owner;
6693
8561
  if (sessionId === undefined)
@@ -6697,7 +8565,7 @@ export class AppServer {
6697
8565
  this.emitTimers(sessionId);
6698
8566
  }
6699
8567
  nodeReminder(timer) {
6700
- return timer.origin !== undefined && !this.autoFixWakes.has(timer.id);
8568
+ return timer.origin !== undefined && !this.autoFixWakes.has(timer.id) && !this.reviewWakes.has(timer.id);
6701
8569
  }
6702
8570
  spendAttemptWakes(sessionId, attempts, reason, spent = () => true) {
6703
8571
  for (const timer of this.timers.list(sessionId)) {
@@ -6758,7 +8626,7 @@ export class AppServer {
6758
8626
  return { spent: 'the attempt that set it was stopped' };
6759
8627
  if (status === 'running' && typeof newestRecord.pid === 'number' && isPidAlive(newestRecord.pid))
6760
8628
  return { wait: 'its attempt is still running in another engine' };
6761
- const armedAt = this.autoFixWakes.has(timer.id) ? Number.NEGATIVE_INFINITY : timer.fireAt - timer.seconds * 1_000;
8629
+ const armedAt = this.autoFixWakes.has(timer.id) || this.reviewWakes.has(timer.id) ? Number.NEGATIVE_INFINITY : timer.fireAt - timer.seconds * 1_000;
6762
8630
  for (const attempt of chain) {
6763
8631
  const journal = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
6764
8632
  for (const line of journal.split('\n')) {
@@ -6809,6 +8677,7 @@ export class AppServer {
6809
8677
  }
6810
8678
  if (record === undefined) {
6811
8679
  this.timers.settle(timer.id);
8680
+ this.reviewWakes.delete(timer.id);
6812
8681
  void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
6813
8682
  this.emitTimers(sessionId);
6814
8683
  continue;
@@ -6838,7 +8707,32 @@ export class AppServer {
6838
8707
  continue;
6839
8708
  }
6840
8709
  }
8710
+ const reviewWake = this.reviewWakes.has(timer.id);
8711
+ if (reviewWake) {
8712
+ let deliver;
8713
+ try {
8714
+ deliver = await this.reviewLoop.confirmWake(sessionId, timer.id);
8715
+ }
8716
+ catch (error) {
8717
+ if (this.timers.get(timer.id) !== undefined)
8718
+ this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
8719
+ nextCheckIn = WAKE_RETRY_MS;
8720
+ this.log('warn', `Andorra review wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
8721
+ continue;
8722
+ }
8723
+ if (!deliver) {
8724
+ this.reviewWakes.delete(timer.id);
8725
+ this.timers.settle(timer.id);
8726
+ void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
8727
+ this.emitTimers(sessionId);
8728
+ this.log('info', `Dropped Andorra review wake ${timer.id}: session ${sessionId}'s review loop no longer asks for it`);
8729
+ continue;
8730
+ }
8731
+ }
6841
8732
  const autoFix = this.autoFixWakes.has(timer.id);
8733
+ // The review loop's wake is routed like Auto-fix's: to the node that took the PR, and kept when that node is done.
8734
+ const routed = autoFix || reviewWake;
8735
+ const wakeKind = autoFix ? 'auto-fix' : reviewWake ? 'andorra-review' : this.fixWakes.has(timer.id) ? 'fix-checks' : this.mentionWakes.has(timer.id) ? 'mention' : 'timer';
6842
8736
  let resume;
6843
8737
  let startNode;
6844
8738
  if (timer.origin !== undefined) {
@@ -6855,7 +8749,7 @@ export class AppServer {
6855
8749
  this.log('info', `Self-wake ${timer.id} waits: ${plan.wait}`);
6856
8750
  continue;
6857
8751
  }
6858
- if ('spent' in plan && !autoFix) {
8752
+ if ('spent' in plan && !routed) {
6859
8753
  this.spendWake(timer, plan.spent);
6860
8754
  continue;
6861
8755
  }
@@ -6869,21 +8763,26 @@ export class AppServer {
6869
8763
  : `Delivering self-wake ${timer.id} to session ${sessionId}`);
6870
8764
  try {
6871
8765
  const carry = timer.carry;
8766
+ let started;
6872
8767
  if (resume !== undefined) {
6873
8768
  try {
6874
- await this.resumeRun({ runId: resume, direction: timer.prompt,
6875
- ...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: autoFix ? 'auto-fix' : 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
8769
+ started = await this.resumeRun({ runId: resume, direction: timer.prompt,
8770
+ ...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: routed ? wakeKind : 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
6876
8771
  }
6877
8772
  catch (error) {
6878
- if (!autoFix || !isFinalWakeRefusal(error))
8773
+ if (!routed || !isFinalWakeRefusal(error))
6879
8774
  throw error;
6880
- this.log('info', `Auto-fix wake ${timer.id} starts at node ${timer.origin.nodeId}: ${resume} could not be continued (${message(error)})`);
8775
+ this.log('info', `${reviewWake ? 'Andorra review' : 'Auto-fix'} wake ${timer.id} starts at node ${timer.origin.nodeId}: ${resume} could not be continued (${message(error)})`);
6881
8776
  resume = undefined;
6882
8777
  startNode = timer.origin.nodeId;
6883
8778
  }
6884
8779
  }
6885
8780
  if (resume === undefined) {
6886
- await this.startRun({ workspace: record.workspace, sessionId, task: timer.prompt,
8781
+ // A relayed session's providers and graph are the desktop's: the carry's ids may name this machine's own,
8782
+ // so the wake is refused (finally) and the desktop resumes the session with its relay instead.
8783
+ if (carry?.relayed === true)
8784
+ throw new AppServerError('invalid-params', RELAYED_RESUME_NEEDS_DESKTOP);
8785
+ started = await this.startRun({ workspace: record.workspace, sessionId, task: timer.prompt,
6887
8786
  ...(carry?.graph === undefined ? {} : { graph: carry.graph }),
6888
8787
  ...(carry?.provider === undefined ? {} : { provider: carry.provider }),
6889
8788
  ...(carry?.model === undefined ? {} : { model: carry.model }),
@@ -6891,11 +8790,19 @@ export class AppServer {
6891
8790
  ...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
6892
8791
  ...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
6893
8792
  ...(carry?.input === undefined ? {} : { input: carry.input }),
6894
- ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: autoFix ? 'auto-fix' : this.fixWakes.has(timer.id) ? 'fix-checks' : 'timer', ...(startNode === undefined ? {} : { startNode }) });
8793
+ ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: wakeKind, ...(startNode === undefined ? {} : { startNode }) });
8794
+ }
8795
+ // Recorded before the timer goes: until then the loop sees its wake armed, never lost, and never arms it twice.
8796
+ const runId = started?.runId;
8797
+ if (reviewWake && typeof runId === 'string') {
8798
+ await this.reviewLoop.wakeDelivered(sessionId, timer.id, runId)
8799
+ .catch(error => this.log('warn', `Could not record the Andorra review delivery for session ${sessionId}: ${message(error)}`));
6895
8800
  }
6896
8801
  this.timers.settle(timer.id);
8802
+ this.reviewWakes.delete(timer.id);
6897
8803
  this.autoFixWakes.delete(timer.id);
6898
8804
  this.fixWakes.delete(timer.id);
8805
+ this.mentionWakes.delete(timer.id);
6899
8806
  void markAutoFixDelivered(this.directory, sessionId, timer.id)
6900
8807
  .then(pullRequest => { if (pullRequest)
6901
8808
  this.emitPullRequest(sessionId, pullRequest); })
@@ -6976,6 +8883,10 @@ export class AppServer {
6976
8883
  if (this.automationCheck)
6977
8884
  clearInterval(this.automationCheck);
6978
8885
  this.hosted.stop();
8886
+ await this.githubEvents.stop().catch(() => { });
8887
+ await this.mentions.stop().catch(() => { });
8888
+ // Before the lease goes: a round in flight stops its reviewer child and is resumed by the next lease holder.
8889
+ await this.reviewLoop.stop().catch(() => { });
6979
8890
  await this.pullRequestWatcher.stop().catch(() => { });
6980
8891
  for (const waiter of [...this.reviewWaiters.values()])
6981
8892
  waiter({ kind: 'aborted' });
@@ -6993,6 +8904,15 @@ export class AppServer {
6993
8904
  if (this.run && this.runAbort === undefined)
6994
8905
  this.runAbort = 'shutdown';
6995
8906
  this.run?.controller.abort();
8907
+ this.modelRelay.close();
8908
+ this.localRelay.close();
8909
+ // A reconciliation may be writing the allowed list or the run store: let it finish before the home can go.
8910
+ let choresTimer;
8911
+ await Promise.race([
8912
+ Promise.allSettled([...this.modelRelayChores, this.modelRelayRuns.settled()]),
8913
+ new Promise(resolve => { choresTimer = setTimeout(resolve, 5_000); choresTimer.unref?.(); }),
8914
+ ]);
8915
+ clearTimeout(choresTimer);
6996
8916
  for (const controller of this.operations)
6997
8917
  controller.abort();
6998
8918
  for (const settle of [...this.pending.values()])
@@ -7026,19 +8946,20 @@ export class AppServer {
7026
8946
  const codeIntel = this.codeIntel;
7027
8947
  this.codeIntel = undefined;
7028
8948
  await codeIntel?.manager.dispose().catch(() => { });
7029
- for (const [, link] of this.engineLinks)
7030
- link.controller.abort();
8949
+ for (const link of [...this.engineLinks.values(), ...this.modelRelayLinks.values()]) {
8950
+ link.ended = true;
8951
+ clearTimeout(link.retry);
8952
+ clearTimeout(link.identityRetry);
8953
+ }
7031
8954
  this.engineLinks.clear();
7032
- await Promise.race([
7033
- this.serializeRemote(async () => {
7034
- const serve = this.remoteServe;
7035
- this.remoteServe = undefined;
7036
- const outcome = await serve?.catch(() => undefined);
7037
- if (outcome && outcome.serving)
7038
- await outcome.release().catch(() => undefined);
7039
- }).catch(() => undefined),
7040
- new Promise(resolve => { const timer = setTimeout(resolve, 2_000); timer.unref?.(); }),
7041
- ]);
8955
+ this.modelRelayLinks.clear();
8956
+ this.stopModelRelayRefresh();
8957
+ for (const timer of this.modelRelaySaveRetries)
8958
+ clearTimeout(timer);
8959
+ this.modelRelaySaveRetries.clear();
8960
+ const relay = this.relay;
8961
+ this.relay = undefined;
8962
+ relay?.dispose();
7042
8963
  }
7043
8964
  }
7044
8965
  export async function runAppServer(options = {}) {
@@ -7055,7 +8976,6 @@ export async function runAppServer(options = {}) {
7055
8976
  error.write(`[app-server] run recovery failed: ${message(recovery)}\n`);
7056
8977
  }
7057
8978
  await server.ready();
7058
- void server.startRemoteServe().catch(failure => { error.write(`[app-server] remote serving failed: ${message(failure)}\n`); });
7059
8979
  const lines = createInterface({ input: options.input ?? process.stdin, crlfDelay: Infinity });
7060
8980
  await new Promise(resolve => {
7061
8981
  server.onStop = () => resolve();