@andorra-labs/code 0.1.15 → 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 (242) 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-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +15 -10
  5. package/dist/src/agent-mcp-catalog.js +1 -0
  6. package/dist/src/agent-mcp.d.ts +4 -1
  7. package/dist/src/agent-mcp.js +46 -10
  8. package/dist/src/andorra/entry.d.ts +10 -0
  9. package/dist/src/andorra/entry.js +18 -4
  10. package/dist/src/andorra/hosted.d.ts +2 -1
  11. package/dist/src/andorra/hosted.js +2 -1
  12. package/dist/src/andorra/notices.d.ts +5 -0
  13. package/dist/src/andorra/notices.js +7 -0
  14. package/dist/src/andorra/state.d.ts +3 -2
  15. package/dist/src/andorra/state.js +4 -4
  16. package/dist/src/andorra/terminal.js +7 -2
  17. package/dist/src/anthropic-credentials.js +2 -0
  18. package/dist/src/app-server/error.d.ts +5 -0
  19. package/dist/src/app-server/error.js +7 -0
  20. package/dist/src/app-server/protocol.d.ts +22 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +89 -0
  23. package/dist/src/app-server/workspace.js +457 -11
  24. package/dist/src/app-server.d.ts +465 -32
  25. package/dist/src/app-server.js +3308 -517
  26. package/dist/src/auth/deployment.js +2 -2
  27. package/dist/src/bridge/cloud.d.ts +27 -0
  28. package/dist/src/bridge/cloud.js +187 -0
  29. package/dist/src/bridge/command.d.ts +30 -0
  30. package/dist/src/bridge/command.js +347 -0
  31. package/dist/src/bridge/control.d.ts +68 -0
  32. package/dist/src/bridge/control.js +233 -0
  33. package/dist/src/bridge/engines.d.ts +90 -0
  34. package/dist/src/bridge/engines.js +601 -0
  35. package/dist/src/bridge/host-ops.d.ts +9 -0
  36. package/dist/src/bridge/host-ops.js +129 -0
  37. package/dist/src/bridge/host.d.ts +47 -0
  38. package/dist/src/bridge/host.js +540 -0
  39. package/dist/src/bridge/link.d.ts +38 -0
  40. package/dist/src/bridge/link.js +508 -0
  41. package/dist/src/bridge/login-link.d.ts +29 -0
  42. package/dist/src/bridge/login-link.js +54 -0
  43. package/dist/src/bridge/protocol.d.ts +136 -0
  44. package/dist/src/bridge/protocol.js +11 -0
  45. package/dist/src/bridge/store.d.ts +12 -0
  46. package/dist/src/bridge/store.js +61 -0
  47. package/dist/src/bridge/wording.d.ts +6 -0
  48. package/dist/src/bridge/wording.js +10 -0
  49. package/dist/src/browser-runner.js +1 -0
  50. package/dist/src/browser-server.js +7 -1
  51. package/dist/src/browser-ui/style.css +3 -3
  52. package/dist/src/browser-ui/tokens.css +28 -17
  53. package/dist/src/change-authors.d.ts +41 -0
  54. package/dist/src/change-authors.js +146 -0
  55. package/dist/src/claude-provider.js +3 -1
  56. package/dist/src/cli.js +202 -38
  57. package/dist/src/codex-errors.js +4 -1
  58. package/dist/src/coding-tools.js +15 -15
  59. package/dist/src/command-screens.d.ts +6 -0
  60. package/dist/src/command-screens.js +19 -14
  61. package/dist/src/commands.d.ts +14 -1
  62. package/dist/src/compaction-phrases.d.ts +4 -0
  63. package/dist/src/compaction-phrases.js +20 -0
  64. package/dist/src/completion.js +82 -5
  65. package/dist/src/config.d.ts +71 -3
  66. package/dist/src/config.js +202 -77
  67. package/dist/src/context-compaction.js +2 -1
  68. package/dist/src/deadline.js +13 -1
  69. package/dist/src/decision/DecisionManager.js +3 -2
  70. package/dist/src/decision/checks.js +1 -1
  71. package/dist/src/decision/requestPhrases.d.ts +4 -0
  72. package/dist/src/decision/requestPhrases.js +22 -0
  73. package/dist/src/default-graph.js +1 -1
  74. package/dist/src/file-diff.d.ts +4 -0
  75. package/dist/src/file-diff.js +2 -1
  76. package/dist/src/github-app/agent-writes.d.ts +102 -0
  77. package/dist/src/github-app/agent-writes.js +320 -0
  78. package/dist/src/github-app/client.d.ts +349 -0
  79. package/dist/src/github-app/client.js +810 -0
  80. package/dist/src/github-app/event-source.d.ts +208 -0
  81. package/dist/src/github-app/event-source.js +684 -0
  82. package/dist/src/github-app/metrics.d.ts +32 -0
  83. package/dist/src/github-app/metrics.js +49 -0
  84. package/dist/src/github-app/review-loop.d.ts +274 -0
  85. package/dist/src/github-app/review-loop.js +1177 -0
  86. package/dist/src/github-app/review-node.d.ts +81 -0
  87. package/dist/src/github-app/review-node.js +205 -0
  88. package/dist/src/github-app/review-post.d.ts +73 -0
  89. package/dist/src/github-app/review-post.js +139 -0
  90. package/dist/src/github-app/review-text.d.ts +107 -0
  91. package/dist/src/github-app/review-text.js +1133 -0
  92. package/dist/src/github-app/review-threads.d.ts +47 -0
  93. package/dist/src/github-app/review-threads.js +107 -0
  94. package/dist/src/github-app/reviewer.d.ts +121 -0
  95. package/dist/src/github-app/reviewer.js +598 -0
  96. package/dist/src/github-app/store.d.ts +59 -0
  97. package/dist/src/github-app/store.js +148 -0
  98. package/dist/src/github-app/triggers.d.ts +141 -0
  99. package/dist/src/github-app/triggers.js +441 -0
  100. package/dist/src/github-inbox.d.ts +55 -0
  101. package/dist/src/github-inbox.js +153 -0
  102. package/dist/src/github-names.d.ts +8 -0
  103. package/dist/src/github-names.js +8 -0
  104. package/dist/src/glob-search.d.ts +61 -0
  105. package/dist/src/glob-search.js +180 -0
  106. package/dist/src/graph-health.js +13 -4
  107. package/dist/src/graph-manager-chat.js +1 -1
  108. package/dist/src/graph-preview.d.ts +46 -0
  109. package/dist/src/graph-preview.js +55 -0
  110. package/dist/src/graph-provider-portability.js +34 -11
  111. package/dist/src/graph-quota.d.ts +29 -2
  112. package/dist/src/graph-quota.js +68 -10
  113. package/dist/src/graph-runner.js +88 -10
  114. package/dist/src/graph-server.d.ts +1 -1
  115. package/dist/src/graph-server.js +11 -9
  116. package/dist/src/graph-sync.js +3 -3
  117. package/dist/src/graph-ui/app.js +201 -40
  118. package/dist/src/graph-ui/controls.css +1 -0
  119. package/dist/src/graph-ui/embed.js +2 -2
  120. package/dist/src/graph-ui/icons.js +3 -1
  121. package/dist/src/graph-ui/index.html +1 -1
  122. package/dist/src/graph-ui/manager.css +1 -1
  123. package/dist/src/graph-ui/manager.js +2 -2
  124. package/dist/src/graph-ui/sidebar.js +30 -0
  125. package/dist/src/graph-ui/studio-canvas.js +26 -13
  126. package/dist/src/graph-ui/studio.css +15 -7
  127. package/dist/src/graph-ui/studio.js +26 -5
  128. package/dist/src/graph-ui/style.css +77 -45
  129. package/dist/src/graph-ui/theme.js +3 -36
  130. package/dist/src/graph-ui/tokens.css +28 -20
  131. package/dist/src/graphs.d.ts +34 -1
  132. package/dist/src/graphs.js +162 -17
  133. package/dist/src/image-input.d.ts +16 -0
  134. package/dist/src/image-input.js +41 -0
  135. package/dist/src/membership.d.ts +30 -1
  136. package/dist/src/membership.js +48 -8
  137. package/dist/src/model-health-cache.js +1 -1
  138. package/dist/src/model-metadata.d.ts +7 -1
  139. package/dist/src/model-metadata.js +39 -17
  140. package/dist/src/model-relay/local.d.ts +116 -0
  141. package/dist/src/model-relay/local.js +468 -0
  142. package/dist/src/model-relay/remote.d.ts +129 -0
  143. package/dist/src/model-relay/remote.js +252 -0
  144. package/dist/src/model-relay/runs.d.ts +34 -0
  145. package/dist/src/model-relay/runs.js +146 -0
  146. package/dist/src/model-relay/wire.d.ts +5 -0
  147. package/dist/src/model-relay/wire.js +5 -0
  148. package/dist/src/plan-pass.d.ts +59 -0
  149. package/dist/src/plan-pass.js +165 -0
  150. package/dist/src/project-registry.d.ts +21 -0
  151. package/dist/src/project-registry.js +74 -0
  152. package/dist/src/provider-engine.js +3 -0
  153. package/dist/src/provider-import.d.ts +0 -12
  154. package/dist/src/provider-import.js +7 -195
  155. package/dist/src/providers.d.ts +40 -2
  156. package/dist/src/providers.js +93 -23
  157. package/dist/src/pull-request-checks.d.ts +26 -0
  158. package/dist/src/pull-request-checks.js +56 -0
  159. package/dist/src/pull-request-conversation.d.ts +134 -0
  160. package/dist/src/pull-request-conversation.js +221 -0
  161. package/dist/src/pull-request-create.d.ts +175 -0
  162. package/dist/src/pull-request-create.js +392 -0
  163. package/dist/src/pull-request-details.d.ts +242 -0
  164. package/dist/src/pull-request-details.js +614 -0
  165. package/dist/src/pull-request-edit.d.ts +23 -0
  166. package/dist/src/pull-request-edit.js +91 -0
  167. package/dist/src/pull-request-logs.d.ts +87 -0
  168. package/dist/src/pull-request-logs.js +183 -0
  169. package/dist/src/pull-request-merge.d.ts +112 -0
  170. package/dist/src/pull-request-merge.js +258 -0
  171. package/dist/src/pull-request-review.d.ts +137 -0
  172. package/dist/src/pull-request-review.js +401 -0
  173. package/dist/src/pull-requests.d.ts +369 -8
  174. package/dist/src/pull-requests.js +524 -55
  175. package/dist/src/react-runtime.js +38 -5
  176. package/dist/src/remote/engine-pool.d.ts +88 -4
  177. package/dist/src/remote/engine-pool.js +379 -90
  178. package/dist/src/remote/roots.d.ts +19 -0
  179. package/dist/src/remote/roots.js +45 -7
  180. package/dist/src/remote/types.d.ts +0 -44
  181. package/dist/src/run-control.d.ts +17 -0
  182. package/dist/src/run-control.js +47 -0
  183. package/dist/src/run-progress.d.ts +10 -0
  184. package/dist/src/run-progress.js +122 -0
  185. package/dist/src/run-records.d.ts +7 -2
  186. package/dist/src/run-records.js +71 -6
  187. package/dist/src/runtime.d.ts +9 -1
  188. package/dist/src/runtime.js +24 -4
  189. package/dist/src/session-changes.d.ts +35 -0
  190. package/dist/src/session-changes.js +194 -6
  191. package/dist/src/session-monitor.js +2 -1
  192. package/dist/src/session-reaper.d.ts +1 -1
  193. package/dist/src/session-reaper.js +6 -1
  194. package/dist/src/session-summary.d.ts +2 -1
  195. package/dist/src/session-summary.js +2 -1
  196. package/dist/src/sessions.d.ts +11 -1
  197. package/dist/src/sessions.js +17 -4
  198. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  199. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  200. package/dist/src/skills/bundled/provenance.json +2 -2
  201. package/dist/src/skills/runtime-skills.js +1 -1
  202. package/dist/src/subagent-run.js +1 -0
  203. package/dist/src/telemetry/capture-core.d.ts +17 -0
  204. package/dist/src/telemetry/capture-core.js +59 -1
  205. package/dist/src/telemetry/classify.d.ts +3 -1
  206. package/dist/src/telemetry/classify.js +37 -0
  207. package/dist/src/telemetry/emitter.d.ts +17 -0
  208. package/dist/src/telemetry/emitter.js +76 -5
  209. package/dist/src/telemetry/schema.d.ts +47 -2
  210. package/dist/src/telemetry/schema.js +120 -5
  211. package/dist/src/telemetry/surface.d.ts +3 -1
  212. package/dist/src/telemetry/surface.js +4 -1
  213. package/dist/src/telemetry/uploader.d.ts +6 -1
  214. package/dist/src/telemetry/uploader.js +22 -3
  215. package/dist/src/terminal-ui.d.ts +1 -0
  216. package/dist/src/terminal-ui.js +10 -3
  217. package/dist/src/test-edit-guard.d.ts +7 -0
  218. package/dist/src/test-edit-guard.js +49 -1
  219. package/dist/src/timers.d.ts +2 -0
  220. package/dist/src/tools.js +59 -9
  221. package/dist/src/transcript.js +8 -2
  222. package/dist/src/types.d.ts +7 -0
  223. package/dist/src/usage-analytics.js +18 -10
  224. package/package.json +6 -1
  225. package/dist/src/remote/cert.d.ts +0 -11
  226. package/dist/src/remote/cert.js +0 -87
  227. package/dist/src/remote/client.d.ts +0 -119
  228. package/dist/src/remote/client.js +0 -544
  229. package/dist/src/remote/command.d.ts +0 -4
  230. package/dist/src/remote/command.js +0 -194
  231. package/dist/src/remote/errors.d.ts +0 -11
  232. package/dist/src/remote/errors.js +0 -14
  233. package/dist/src/remote/network.d.ts +0 -22
  234. package/dist/src/remote/network.js +0 -102
  235. package/dist/src/remote/pairing.d.ts +0 -63
  236. package/dist/src/remote/pairing.js +0 -299
  237. package/dist/src/remote/pem.d.ts +0 -2
  238. package/dist/src/remote/pem.js +0 -7
  239. package/dist/src/remote/serve.d.ts +0 -68
  240. package/dist/src/remote/serve.js +0 -244
  241. package/dist/src/remote/server.d.ts +0 -21
  242. package/dist/src/remote/server.js +0 -406
@@ -4,6 +4,8 @@ import { loadConfig } from '../config.js';
4
4
  import { reconcileInterruptedRuns } from '../run-records.js';
5
5
  import { configuredSurface, reportInterruptedRuns } from '../telemetry/surface.js';
6
6
  import { authorizedRoots } from './roots.js';
7
+ import { MODEL_RELAY_CONNECTION_PREFIX } from '../model-relay/wire.js';
8
+ import { REMOTE_ENGINE_INSTALL_FAILED_EVENT, REMOTE_ENGINE_INSTALLING_EVENT, REMOTE_ENGINE_READY_EVENT } from '../app-server/protocol.js';
7
9
  export const REMOTE_PRIMARY_ENGINE = 'remote-primary';
8
10
  export const RELAY_CAPABILITY_REQUIREMENT = 'remote.engine.relay.capability';
9
11
  const TASK_PREFIX = 'remote-task-';
@@ -15,21 +17,42 @@ const CHILD_DEADLINE_SLACK_MS = 5_000;
15
17
  const MAX_CHILD_DEADLINE_MS = 300_000;
16
18
  const LONG_DEADLINE_METHODS = new Set(['browser.runtime.install']);
17
19
  const MAX_LONG_CHILD_DEADLINE_MS = 1_260_000;
18
- const REVOCATION_POLL_MS = 5_000;
19
- const SINKLESS_CONNECTION_TTL_MS = 30_000;
20
+ const SINKLESS_SWEEP_MS = 5_000;
21
+ const SINKLESS_CONNECTION_TTL_MS = 5 * 60_000;
20
22
  const FINISHED_RUN_TTL_MS = 5 * 60_000;
21
23
  const FINISHED_RUNS_REMEMBERED = 8;
22
24
  const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
23
25
  const MAX_LARGE_RESPONSE_BYTES = 12 * 1024 * 1024;
24
- const LARGE_RESPONSE_METHODS = new Set(['runs.get', 'workspace.diff', 'workspace.git', 'sessions.trajectory', 'browser.view.selection', 'attachments.read', 'sessions.changes.list', 'sessions.changes.get']);
26
+ // A claim answers with the model request's payload (at most 12 MiB of JSON); the cap leaves room for its envelope.
27
+ const MODEL_RELAY_CLAIM_RESPONSE_BYTES = 13 * 1024 * 1024;
28
+ // The PR tab's review: a read of threads, viewed files and reviewers, and the writes, three of which answer with that read.
29
+ const PULL_REQUEST_REVIEW_WRITES = ['sessions.pullRequest.submitReview', 'sessions.pullRequest.thread', 'sessions.pullRequest.markViewed', 'sessions.pullRequest.rerunChecks', 'sessions.pullRequest.requestReviewers'];
30
+ const PULL_REQUEST_REVIEW_ANSWERS = ['sessions.pullRequest.review', 'sessions.pullRequest.submitReview', 'sessions.pullRequest.thread', 'sessions.pullRequest.requestReviewers'];
31
+ // The PR tab's merge and create: a read of the merge state and the writes that merge, update the branch,
32
+ // mark it ready, and open a pull request from the task's folder; the draft read names its branches and commits.
33
+ const PULL_REQUEST_MERGE_WRITES = ['sessions.pullRequest.merge', 'sessions.pullRequest.updateBranch', 'sessions.pullRequest.ready', 'sessions.pullRequest.create'];
34
+ const PULL_REQUEST_MERGE_ANSWERS = ['sessions.pullRequest.mergeState', 'sessions.pullRequest.merge', 'sessions.pullRequest.updateBranch', 'sessions.pullRequest.ready', 'sessions.pullRequest.draft'];
35
+ // Phase 4: the conversation, suggestions, failed-check logs, editing the PR, the merge queue and attaching a PR to a task.
36
+ const PULL_REQUEST_PHASE4_WRITES = ['sessions.pullRequest.comment', 'sessions.pullRequest.react', 'sessions.pullRequest.applySuggestion', 'sessions.pullRequest.fixChecks', 'sessions.pullRequest.edit', 'sessions.pullRequest.setState', 'sessions.pullRequest.dequeue', 'sessions.pullRequest.attach'];
37
+ const PULL_REQUEST_PHASE4_ANSWERS = ['sessions.pullRequest.comment', 'sessions.pullRequest.react', 'sessions.pullRequest.applySuggestion', 'sessions.pullRequest.checkLog', 'sessions.pullRequest.edit', 'sessions.pullRequest.setState', 'sessions.pullRequest.dequeue', 'pullRequests.reviewRequests', 'issues.list'];
38
+ // The GitHub App (design/specs/github-app.md): its status is a read; connecting and disconnecting change the account's link,
39
+ // and setAgentWrites changes who the agent's PR replies post as on that machine.
40
+ const GITHUB_APP_WRITES = ['github.connect', 'github.disconnect', 'github.setAgentWrites'];
41
+ const LARGE_RESPONSE_METHODS = new Set(['runs.get', 'workspace.files', 'workspace.search', 'sessions.pullRequest.details', 'sessions.pullRequest.files', ...PULL_REQUEST_REVIEW_ANSWERS, ...PULL_REQUEST_MERGE_ANSWERS, ...PULL_REQUEST_PHASE4_ANSWERS, 'workspace.diff', 'workspace.git', 'sessions.trajectory', 'browser.view.selection', 'attachments.read', 'sessions.changes.list', 'sessions.changes.get']);
25
42
  const PRIMARY_METHODS = new Set([
26
- 'sessions.list', 'sessions.get', 'sessions.create', 'sessions.rename', 'sessions.setJev', 'sessions.setArchived', 'sessions.delete',
43
+ 'sessions.list', 'sessions.get', 'sessions.create', 'sessions.rename', 'sessions.setJev', 'sessions.setArchived', 'sessions.setPinned', 'sessions.delete',
27
44
  'sessions.trajectory',
45
+ // The run a task engine is serving, with the approval or question it waits on: how a window recovers one whose
46
+ // announcement was too large to cross the relay.
47
+ 'run.current',
28
48
  'sessions.skill.get', 'sessions.skill.update',
29
- 'sessions.pullRequest.list',
49
+ 'sessions.pullRequest.list', 'sessions.pullRequest.details', 'sessions.pullRequest.files', 'sessions.pullRequest.review', ...PULL_REQUEST_REVIEW_WRITES,
50
+ 'sessions.pullRequest.mergeState', 'sessions.pullRequest.draft', ...PULL_REQUEST_MERGE_WRITES,
51
+ 'sessions.pullRequest.checkLog', 'pullRequests.reviewRequests', 'issues.list', ...PULL_REQUEST_PHASE4_WRITES,
30
52
  'sessions.changes.list', 'sessions.changes.get', 'sessions.changes.keep', 'sessions.changes.undo',
53
+ 'github.status', ...GITHUB_APP_WRITES,
31
54
  'runs.list', 'runs.get', 'timers.list',
32
- 'workspace.tree', 'workspace.read', 'workspace.git', 'workspace.branches', 'workspace.checkout', 'workspace.diff',
55
+ 'workspace.tree', 'workspace.read', 'workspace.files', 'workspace.search', 'workspace.linkBase', 'workspace.git', 'workspace.branches', 'workspace.checkout', 'workspace.diff',
33
56
  'graphs.list', 'graphs.get', 'graphs.select', 'graphs.visibility.set', 'graphs.visibility.import',
34
57
  'attachments.read',
35
58
  'config.get', 'projects.list', 'projects.add', 'projects.remove', 'projects.relink',
@@ -45,12 +68,14 @@ const PRIMARY_METHODS = new Set([
45
68
  'browser.panel.op', 'browser.panel.cancel',
46
69
  ]);
47
70
  const RUN_START_METHODS = new Set(['run.start', 'run.resume']);
48
- const RUN_TARGET_METHODS = new Set(['run.setModel', 'run.setPermissions', 'run.cancel', 'run.steer', 'run.approve', 'run.answer', 'browser.panel.result']);
71
+ // The relay methods a desktop uses to answer a remote run's model calls; the engine pool stamps the caller as claimant.
72
+ const MODEL_RELAY_METHODS = new Set(['model.relay.claim', 'model.relay.progress', 'model.relay.result']);
73
+ const RUN_TARGET_METHODS = new Set(['run.setModel', 'run.setPermissions', 'run.cancel', 'run.steer', 'run.approve', 'run.answer', 'browser.panel.result', ...MODEL_RELAY_METHODS]);
49
74
  const TERMINAL_METHODS = new Set(['terminal.open', 'terminal.write', 'terminal.resize', 'terminal.close', 'terminal.closeAll']);
50
75
  const ALLOWED_METHODS = new Set([...PRIMARY_METHODS, ...RUN_START_METHODS, ...RUN_TARGET_METHODS, ...TERMINAL_METHODS]);
51
- const SESSION_MUTATION_METHODS = new Set(['sessions.rename', 'sessions.setJev', 'sessions.setArchived', 'sessions.delete']);
76
+ const SESSION_MUTATION_METHODS = new Set(['sessions.rename', 'sessions.setJev', 'sessions.setArchived', 'sessions.setPinned', 'sessions.delete']);
52
77
  const MUTATING_METHODS = new Set([
53
- ...RUN_START_METHODS, ...RUN_TARGET_METHODS, ...SESSION_MUTATION_METHODS, 'sessions.skill.update', 'sessions.changes.keep', 'sessions.changes.undo',
78
+ ...RUN_START_METHODS, ...RUN_TARGET_METHODS, ...SESSION_MUTATION_METHODS, ...PULL_REQUEST_REVIEW_WRITES, ...PULL_REQUEST_MERGE_WRITES, ...PULL_REQUEST_PHASE4_WRITES, ...GITHUB_APP_WRITES, 'sessions.skill.update', 'sessions.changes.keep', 'sessions.changes.undo',
54
79
  'terminal.open', 'terminal.write', 'terminal.close', 'terminal.closeAll', 'workspace.checkout', 'projects.add', 'projects.remove', 'projects.relink',
55
80
  'graphs.visibility.set', 'graphs.visibility.import',
56
81
  'browser.runtime.install', 'browser.view.open', 'browser.view.navigate', 'browser.view.go', 'browser.view.activate',
@@ -59,6 +84,10 @@ const MUTATING_METHODS = new Set([
59
84
  'browser.extensions.commit', 'browser.extensions.discard', 'browser.extensions.remove', 'browser.extensions.setEnabled',
60
85
  'browser.extensions.reload', 'browser.extensions.restart',
61
86
  ]);
87
+ /** How the relay treats a method: whether a desktop may call it on a machine, and whether it changes something there (no deadline slack). */
88
+ export function relayMethodClass(method) {
89
+ return { relayed: ALLOWED_METHODS.has(method), primary: PRIMARY_METHODS.has(method), mutating: MUTATING_METHODS.has(method) };
90
+ }
62
91
  class ChildError extends Error {
63
92
  code;
64
93
  constructor(code, message) {
@@ -93,6 +122,13 @@ class ChildEngine {
93
122
  rejectReady;
94
123
  stopped = false;
95
124
  busy = false;
125
+ /** Spawned for a task start that has not been answered yet. */
126
+ starting = false;
127
+ /** The desktop version this engine serves; undefined for the host's own. */
128
+ version;
129
+ released = false;
130
+ /** When this engine first failed to say what wakes it holds, cleared by its next answer. */
131
+ unansweredSince;
96
132
  advertised = [];
97
133
  stderrTail = [];
98
134
  constructor(id, command, home, onEvent, onExit) {
@@ -102,7 +138,7 @@ class ChildEngine {
102
138
  this.child = spawn(command[0], command.slice(1), {
103
139
  windowsHide: true,
104
140
  stdio: ['pipe', 'pipe', 'pipe'],
105
- env: { ...process.env, ANDORRACODE_HOME: home, ANDORRA_SURFACE: 'remote' },
141
+ env: engineEnvironment(home),
106
142
  });
107
143
  this.ready = new Promise((resolve, reject) => {
108
144
  this.resolveReady = resolve;
@@ -177,6 +213,9 @@ class ChildEngine {
177
213
  this.child.kill();
178
214
  this.onExit(this.id);
179
215
  }
216
+ get inFlight() {
217
+ return this.pending.size;
218
+ }
180
219
  supports(capability) {
181
220
  return this.advertised.includes(capability);
182
221
  }
@@ -231,6 +270,15 @@ class ChildEngine {
231
270
  });
232
271
  }
233
272
  }
273
+ // The launcher's variables are for the host it started: an engine that saw them would act as a host under the launcher.
274
+ const LAUNCHER_VARIABLES = new Set(['ANDORRA_BRIDGE_ENGINES', 'ANDORRA_BRIDGE_LAUNCHER_PID', 'ANDORRA_BRIDGE_NPM']);
275
+ function engineEnvironment(home) {
276
+ const env = {};
277
+ for (const [key, value] of Object.entries(process.env))
278
+ if (!LAUNCHER_VARIABLES.has(key.toUpperCase()))
279
+ env[key] = value;
280
+ return { ...env, ANDORRACODE_HOME: home, ANDORRA_SURFACE: 'remote' };
281
+ }
234
282
  export function relayEngineCommand() {
235
283
  const override = process.env.ANDORRA_REMOTE_ENGINE_COMMAND;
236
284
  if (override) {
@@ -260,6 +308,7 @@ function rootPartOf(value) {
260
308
  }
261
309
  export class RemoteEngineRelay {
262
310
  directory;
311
+ timing;
263
312
  children = new Map();
264
313
  retiringChildren = new Set();
265
314
  taskSeq = 0;
@@ -269,13 +318,67 @@ export class RemoteEngineRelay {
269
318
  runEngine = new Map();
270
319
  sessionEngine = new Map();
271
320
  activeRuns = new Map();
321
+ runStates = new Map();
272
322
  finishedRuns = new Map();
273
323
  translations = new Map();
274
- revocationTimer;
324
+ sinklessTimer;
275
325
  delivery = Promise.resolve();
276
326
  closed = false;
277
- constructor(directory) {
327
+ startsInFlight = 0;
328
+ engines;
329
+ stopWatching;
330
+ constructor(directory, timing = {}, options = {}) {
278
331
  this.directory = directory;
332
+ this.timing = timing;
333
+ this.engines = options.engines;
334
+ this.stopWatching = this.engines?.watch?.(event => this.announceInstall(event)) ?? (() => undefined);
335
+ }
336
+ /** The engine version a connection's tasks run on: undefined for the host's own, and always without a store. */
337
+ engineVersion(connection) {
338
+ const version = connection?.version;
339
+ if (!this.engines || version === undefined || version === this.engines.hostVersion)
340
+ return undefined;
341
+ return version;
342
+ }
343
+ announceInstall(event) {
344
+ for (const connection of [...this.connections.values()]) {
345
+ if (this.engineVersion(connection) === event.version)
346
+ this.sendInstallEvent(connection, event);
347
+ }
348
+ }
349
+ sendInstallEvent(connection, event) {
350
+ if (this.closed)
351
+ return;
352
+ const notice = `${event.version} ${event.state}`;
353
+ const frame = event.state === 'installing'
354
+ ? { engine: REMOTE_PRIMARY_ENGINE, event: REMOTE_ENGINE_INSTALLING_EVENT, data: { version: event.version } }
355
+ : event.state === 'ready'
356
+ ? { engine: REMOTE_PRIMARY_ENGINE, event: REMOTE_ENGINE_READY_EVENT, data: { version: event.version } }
357
+ : { engine: REMOTE_PRIMARY_ENGINE, event: REMOTE_ENGINE_INSTALL_FAILED_EVENT, data: { version: event.version, reason: event.reason } };
358
+ for (const sink of [...connection.sinks]) {
359
+ if (connection.installNotices.get(sink) === notice)
360
+ continue;
361
+ connection.installNotices.set(sink, notice);
362
+ try {
363
+ sink(frame);
364
+ }
365
+ catch { }
366
+ }
367
+ }
368
+ prepareEngine(connection) {
369
+ const version = this.engineVersion(connection);
370
+ const engines = this.engines;
371
+ if (version === undefined || !engines?.prepare)
372
+ return;
373
+ void engines.prepare(version).then(state => {
374
+ // A new install is announced to every connection of the version; one already under way, or a failure still cooling
375
+ // down, only to this newcomer. The state is read again now: the install may have ended since prepare answered.
376
+ if (state === 'started' || state === 'none' || this.connections.get(connection.id) !== connection)
377
+ return;
378
+ const current = engines.installState?.(version);
379
+ if (current !== undefined)
380
+ this.sendInstallEvent(connection, { version, ...current });
381
+ }).catch(() => undefined);
279
382
  }
280
383
  async request(deviceId, body) {
281
384
  try {
@@ -284,7 +387,7 @@ export class RemoteEngineRelay {
284
387
  const translation = await this.translation(body.viewerWorkspaceId);
285
388
  const rewritten = OPAQUE_RESPONSE_METHODS.has(method) ? (result ?? null) : translation.rewrite(result ?? null);
286
389
  const serialized = JSON.stringify(rewritten) ?? 'null';
287
- const cap = LARGE_RESPONSE_METHODS.has(method) ? MAX_LARGE_RESPONSE_BYTES : MAX_RESPONSE_BYTES;
390
+ const cap = method === 'model.relay.claim' ? MODEL_RELAY_CLAIM_RESPONSE_BYTES : LARGE_RESPONSE_METHODS.has(method) ? MAX_LARGE_RESPONSE_BYTES : MAX_RESPONSE_BYTES;
288
391
  if (Buffer.byteLength(serialized) > cap) {
289
392
  return { error: { code: 'remote', message: `${method} answered larger than the remote link allows (${Math.round(cap / 1024 / 1024)} MiB).` } };
290
393
  }
@@ -320,8 +423,17 @@ export class RemoteEngineRelay {
320
423
  const deadline = this.childDeadline(body);
321
424
  if (TERMINAL_METHODS.has(method))
322
425
  return this.terminalRequest(connection, method, params, deadline);
323
- if (RUN_START_METHODS.has(method))
324
- return this.startRequest(body, method, params, deadline);
426
+ if (RUN_START_METHODS.has(method)) {
427
+ this.startsInFlight += 1;
428
+ try {
429
+ return await this.startRequest(connection, body, method, params, deadline);
430
+ }
431
+ finally {
432
+ // The start stays counted until the events its engine sent before answering (run.started) are delivered, so
433
+ // runningTasks() never reads zero between the answer and the run becoming active.
434
+ void this.delivery.then(() => { this.startsInFlight -= 1; });
435
+ }
436
+ }
325
437
  if (RUN_TARGET_METHODS.has(method))
326
438
  return this.runTargetRequest(body, method, params, deadline);
327
439
  if (SESSION_MUTATION_METHODS.has(method) && typeof params.id === 'string') {
@@ -361,13 +473,15 @@ export class RemoteEngineRelay {
361
473
  }
362
474
  return answer;
363
475
  }
364
- async startRequest(body, method, params, deadline) {
476
+ async startRequest(connection, body, method, params, deadline) {
477
+ const version = this.engineVersion(connection);
365
478
  const { requireCapability, ...rest } = params;
366
479
  const required = typeof requireCapability === 'string' && requireCapability.length > 0 ? requireCapability : undefined;
367
480
  const translated = await this.translateParams(body.viewerWorkspaceId, rest);
368
481
  if (body.engine !== '' && body.engine !== REMOTE_PRIMARY_ENGINE) {
369
482
  const addressed = this.children.get(body.engine);
370
- if (addressed !== undefined) {
483
+ // An engine of another version is passed over: the desktop's own version resumes the run from its state on disk.
484
+ if (addressed !== undefined && addressed.version === version) {
371
485
  if (this.retiringChildren.has(addressed.id)) {
372
486
  throw new RelayRefusal('busy', 'That engine is being stopped; try again.');
373
487
  }
@@ -380,7 +494,7 @@ export class RemoteEngineRelay {
380
494
  }
381
495
  const incompatible = [];
382
496
  for (const [id, engine] of [...this.children]) {
383
- if (id === REMOTE_PRIMARY_ENGINE)
497
+ if (id === REMOTE_PRIMARY_ENGINE || engine.version !== version)
384
498
  continue;
385
499
  if (required !== undefined && !engine.supports(required)) {
386
500
  if (!engine.busy && !this.retiringChildren.has(id))
@@ -408,6 +522,8 @@ export class RemoteEngineRelay {
408
522
  continue;
409
523
  if (!await this.childIsIdle(child))
410
524
  continue;
525
+ if (await this.childRunsBackground(child))
526
+ continue;
411
527
  await this.retireChild(child.id);
412
528
  break;
413
529
  }
@@ -415,7 +531,9 @@ export class RemoteEngineRelay {
415
531
  this.retiringChildren.delete(child.id);
416
532
  }
417
533
  }
418
- const spawned = await this.spawnChild(`${TASK_PREFIX}${++this.taskSeq}`);
534
+ await this.reclaimIdleEngine();
535
+ const spawned = await this.spawnChild(`${TASK_PREFIX}${++this.taskSeq}`, version);
536
+ spawned.starting = true;
419
537
  try {
420
538
  if (required !== undefined && !spawned.supports(required)) {
421
539
  throw new RelayRefusal('invalid-params', `This machine's engine does not support ${required}.`);
@@ -428,6 +546,39 @@ export class RemoteEngineRelay {
428
546
  await this.retireChild(spawned.id);
429
547
  throw error;
430
548
  }
549
+ finally {
550
+ spawned.starting = false;
551
+ }
552
+ }
553
+ // Engines that finished their tasks stay for reuse by their own version; at the cap one of them, of any version, gives way rather than refuse the start.
554
+ async reclaimIdleEngine() {
555
+ if (this.taskEngineCount() < MAX_RELAY_ENGINES)
556
+ return;
557
+ const unclaimed = (child) => !this.retiringChildren.has(child.id) && !child.busy && !child.starting
558
+ && child.inFlight === 0 && !this.activeRuns.has(child.id) && this.children.get(child.id) === child;
559
+ for (const child of [...this.children.values()]) {
560
+ if (child.id === REMOTE_PRIMARY_ENGINE || !unclaimed(child))
561
+ continue;
562
+ this.retiringChildren.add(child.id);
563
+ try {
564
+ if (await this.childHoldsWake(child))
565
+ continue;
566
+ if (!await this.childIsIdle(child))
567
+ continue;
568
+ if (await this.childRunsBackground(child))
569
+ continue;
570
+ if (child.busy || child.starting || child.inFlight > 0 || this.activeRuns.has(child.id))
571
+ continue;
572
+ await this.retireChild(child.id);
573
+ return;
574
+ }
575
+ finally {
576
+ this.retiringChildren.delete(child.id);
577
+ }
578
+ }
579
+ }
580
+ taskEngineCount() {
581
+ return [...this.children.keys()].filter(childId => childId !== REMOTE_PRIMARY_ENGINE).length;
431
582
  }
432
583
  async runTargetRequest(body, method, params, deadline) {
433
584
  let owner;
@@ -441,7 +592,9 @@ export class RemoteEngineRelay {
441
592
  if (owner === undefined) {
442
593
  throw new RelayRefusal('not-found', 'That interaction is not waiting on this machine.');
443
594
  }
444
- return (await this.engine(owner)).request(method, params, deadline);
595
+ // The claimant is the caller's own connection; whatever the caller sent is replaced. The rest of the params are model output and stay untranslated.
596
+ const forwarded = MODEL_RELAY_METHODS.has(method) ? { ...params, claimant: body.connectionId } : params;
597
+ return (await this.engine(owner)).request(method, forwarded, deadline);
445
598
  }
446
599
  async terminalRequest(connection, method, params, deadline) {
447
600
  const primary = await this.engine(REMOTE_PRIMARY_ENGINE);
@@ -499,43 +652,54 @@ export class RemoteEngineRelay {
499
652
  || (visibility !== undefined && Object.values(visibility).some(spelledList));
500
653
  if (!needs)
501
654
  return params;
502
- const translation = await this.translation(viewerWorkspaceId);
503
- const next = { ...params };
504
- if (typeof next.workspace === 'string' && isRemoteProjectSpelling(next.workspace))
505
- next.workspace = translation.toHost(next.workspace);
506
- if (typeof next.cwd === 'string' && isRemoteProjectSpelling(next.cwd))
507
- next.cwd = translation.toHost(next.cwd);
508
- if (typeof next.path === 'string' && isRemoteProjectSpelling(next.path))
509
- next.path = translation.toHost(next.path);
510
- if (workspaces !== undefined) {
511
- next.workspaces = workspaces.map(value => {
655
+ const apply = (translation) => {
656
+ const next = { ...params };
657
+ if (typeof next.workspace === 'string' && isRemoteProjectSpelling(next.workspace))
658
+ next.workspace = translation.toHost(next.workspace);
659
+ if (typeof next.cwd === 'string' && isRemoteProjectSpelling(next.cwd))
660
+ next.cwd = translation.toHost(next.cwd);
661
+ if (typeof next.path === 'string' && isRemoteProjectSpelling(next.path))
662
+ next.path = translation.toHost(next.path);
663
+ if (workspaces !== undefined) {
664
+ next.workspaces = workspaces.map(value => {
665
+ if (typeof value !== 'string' || !isRemoteProjectSpelling(value))
666
+ return value;
667
+ try {
668
+ return translation.toHost(value);
669
+ }
670
+ catch {
671
+ return value;
672
+ }
673
+ });
674
+ }
675
+ // A visibility list is stored on this host, so it keeps host paths only. A viewer spelling this host cannot place
676
+ // names no folder it shares and could never match here; it is left out rather than saved as a viewer's ID.
677
+ const hostPaths = (list) => !Array.isArray(list) ? list : list.flatMap(value => {
512
678
  if (typeof value !== 'string' || !isRemoteProjectSpelling(value))
513
- return value;
679
+ return [value];
514
680
  try {
515
- return translation.toHost(value);
681
+ return [translation.toHost(value)];
516
682
  }
517
683
  catch {
518
- return value;
684
+ return [];
519
685
  }
520
686
  });
687
+ if (projects !== undefined)
688
+ next.projects = hostPaths(projects);
689
+ if (visibility !== undefined)
690
+ next.visibility = Object.fromEntries(Object.entries(visibility).map(([graph, list]) => [graph, hostPaths(list)]));
691
+ return next;
692
+ };
693
+ try {
694
+ return apply(await this.translation(viewerWorkspaceId));
695
+ }
696
+ catch (error) {
697
+ // The folder map is kept for a few seconds, so a project added since is missing from it: a miss is checked once against a fresh map.
698
+ if (!(error instanceof RelayRefusal) || error.code !== 'not-found')
699
+ throw error;
700
+ this.translations.delete(viewerWorkspaceId);
701
+ return apply(await this.translation(viewerWorkspaceId));
521
702
  }
522
- // A visibility list is stored on this host, so it keeps host paths only. A viewer spelling this host cannot place
523
- // names no folder it shares and could never match here; it is left out rather than saved as a viewer's ID.
524
- const hostPaths = (list) => !Array.isArray(list) ? list : list.flatMap(value => {
525
- if (typeof value !== 'string' || !isRemoteProjectSpelling(value))
526
- return [value];
527
- try {
528
- return [translation.toHost(value)];
529
- }
530
- catch {
531
- return [];
532
- }
533
- });
534
- if (projects !== undefined)
535
- next.projects = hostPaths(projects);
536
- if (visibility !== undefined)
537
- next.visibility = Object.fromEntries(Object.entries(visibility).map(([graph, list]) => [graph, hostPaths(list)]));
538
- return next;
539
703
  }
540
704
  async restoreRequestedEcho(answer, original, viewerWorkspaceId) {
541
705
  const groups = answer?.groups;
@@ -554,9 +718,9 @@ export class RemoteEngineRelay {
554
718
  connection(deviceId, connectionId, viewerWorkspaceId) {
555
719
  let found = this.connections.get(connectionId);
556
720
  if (!found) {
557
- found = { id: connectionId, deviceId, terminals: new Map(), browserStreams: new Set(), sinks: new Set(), cuts: new Set(), sinklessSince: Date.now() };
721
+ found = { id: connectionId, deviceId, terminals: new Map(), browserStreams: new Set(), sinks: new Set(), cuts: new Set(), sinklessSince: Date.now(), installNotices: new Map() };
558
722
  this.connections.set(connectionId, found);
559
- this.startRevocationPoll();
723
+ this.startSinklessSweep();
560
724
  }
561
725
  found.deviceId = deviceId;
562
726
  if (viewerWorkspaceId !== undefined)
@@ -590,14 +754,21 @@ export class RemoteEngineRelay {
590
754
  connection.browserStreams.clear();
591
755
  this.connections.delete(connection.id);
592
756
  }
593
- events(deviceId, connectionId, viewerWorkspaceId, sink, cut) {
757
+ events(deviceId, connectionId, viewerWorkspaceId, sink, cut, version) {
594
758
  const connection = this.connection(deviceId, connectionId, viewerWorkspaceId);
759
+ connection.version = version;
760
+ // A sink that opens is told the current install state; the sinks already open have heard it.
761
+ connection.installNotices.delete(sink);
595
762
  connection.sinks.add(sink);
596
763
  connection.cuts.add(cut);
597
764
  connection.sinklessSince = 0;
598
- this.replayTo(connection, viewerWorkspaceId, sink);
765
+ this.prepareEngine(connection);
766
+ // A desktop engine's own link answers model requests only: it is shown no run, so nothing is replayed to it.
767
+ if (!connectionId.startsWith(MODEL_RELAY_CONNECTION_PREFIX))
768
+ this.replayTo(connection, viewerWorkspaceId, sink);
599
769
  return () => {
600
770
  connection.sinks.delete(sink);
771
+ connection.installNotices.delete(sink);
601
772
  connection.cuts.delete(cut);
602
773
  if (connection.sinks.size > 0)
603
774
  return;
@@ -665,9 +836,13 @@ export class RemoteEngineRelay {
665
836
  this.runEngine.set(runId, engineId);
666
837
  if (typeof data.sessionId === 'string')
667
838
  this.sessionEngine.set(data.sessionId, engineId);
668
- if (engineId !== REMOTE_PRIMARY_ENGINE)
839
+ if (engineId !== REMOTE_PRIMARY_ENGINE) {
669
840
  this.activeRuns.set(engineId, data);
841
+ this.runStates.delete(engineId);
842
+ }
670
843
  }
844
+ if (event === 'run.state' && typeof data.state === 'string' && this.activeRuns.has(engineId))
845
+ this.runStates.set(engineId, data.state);
671
846
  if (event === 'run.completed' || event === 'run.failed') {
672
847
  if (runId !== undefined)
673
848
  this.runEngine.delete(runId);
@@ -678,6 +853,7 @@ export class RemoteEngineRelay {
678
853
  child.busy = false;
679
854
  if (engineId !== REMOTE_PRIMARY_ENGINE) {
680
855
  this.activeRuns.delete(engineId);
856
+ this.runStates.delete(engineId);
681
857
  this.finishedRuns.set(engineId, { event, data, at: Date.now() });
682
858
  if (this.finishedRuns.size > FINISHED_RUNS_REMEMBERED) {
683
859
  const oldest = this.finishedRuns.keys().next().value;
@@ -706,6 +882,8 @@ export class RemoteEngineRelay {
706
882
  for (const connection of [...this.connections.values()]) {
707
883
  if (connection.sinks.size === 0)
708
884
  continue;
885
+ if (connection.id.startsWith(MODEL_RELAY_CONNECTION_PREFIX) && !event.startsWith('model.relay.'))
886
+ continue;
709
887
  const translation = await this.translation(connection.viewerWorkspaceId);
710
888
  const frame = { engine: engineId, event, data: this.rewriteEventData(translation, event, data) };
711
889
  for (const sink of [...connection.sinks]) {
@@ -717,10 +895,11 @@ export class RemoteEngineRelay {
717
895
  }
718
896
  }
719
897
  rewriteEventData(translation, event, data) {
720
- if (event !== 'browser.panel.request' || data.arguments === undefined)
898
+ const field = VERBATIM_EVENT_FIELDS.get(event);
899
+ if (field === undefined || data[field] === undefined)
721
900
  return translation.rewrite(data);
722
- const { arguments: verbatim, ...rest } = data;
723
- return { ...translation.rewrite(rest), arguments: verbatim };
901
+ const { [field]: verbatim, ...rest } = data;
902
+ return { ...translation.rewrite(rest), [field]: verbatim };
724
903
  }
725
904
  onChildExit(engineId) {
726
905
  const interrupted = this.activeRuns.get(engineId);
@@ -729,8 +908,12 @@ export class RemoteEngineRelay {
729
908
  .then(recovered => reportInterruptedRuns({ home: this.directory, surface: configuredSurface('remote') }, recovered.interrupted))
730
909
  .catch(() => undefined);
731
910
  }
911
+ const exited = this.children.get(engineId);
732
912
  this.children.delete(engineId);
913
+ if (exited)
914
+ this.releaseEngine(exited);
733
915
  this.activeRuns.delete(engineId);
916
+ this.runStates.delete(engineId);
734
917
  for (const [runId, owner] of [...this.runEngine])
735
918
  if (owner === engineId)
736
919
  this.runEngine.delete(runId);
@@ -753,30 +936,62 @@ export class RemoteEngineRelay {
753
936
  throw new RelayRefusal('not-found', `No engine ${id} is serving this machine's remote surface.`);
754
937
  return this.spawnChild(REMOTE_PRIMARY_ENGINE);
755
938
  }
756
- async spawnChild(id) {
939
+ async spawnChild(id, version) {
757
940
  const existing = this.children.get(id);
758
941
  if (existing)
759
942
  return existing;
760
943
  if (this.closed)
761
944
  throw new RelayRefusal('remote', 'The remote engine relay is shutting down.');
762
- if (id !== REMOTE_PRIMARY_ENGINE) {
763
- const taskEngines = [...this.children.keys()].filter(childId => childId !== REMOTE_PRIMARY_ENGINE).length;
764
- if (taskEngines >= MAX_RELAY_ENGINES) {
765
- throw new RelayRefusal('busy', 'This machine is already running the most concurrent remote tasks it allows. Wait for one to finish.');
766
- }
767
- }
768
- const created = new ChildEngine(id, relayEngineCommand(), this.directory, (engineId, event, data) => this.enqueue(engineId, event, data), engineId => this.onChildExit(engineId));
945
+ this.refuseAtEngineCap(id);
946
+ const command = await this.engineCommand(version);
947
+ if (this.closed)
948
+ throw new RelayRefusal('remote', 'The remote engine relay is shutting down.');
949
+ const raced = this.children.get(id);
950
+ if (raced)
951
+ return raced;
952
+ // Checked again: other starts may have spawned while this one waited for its command.
953
+ this.refuseAtEngineCap(id);
954
+ const created = new ChildEngine(id, command, this.directory, (engineId, event, data) => this.enqueue(engineId, event, data), engineId => this.onChildExit(engineId));
955
+ created.version = version;
769
956
  this.children.set(id, created);
957
+ if (id !== REMOTE_PRIMARY_ENGINE)
958
+ this.engines?.inUse(version ?? this.engines.hostVersion);
770
959
  try {
771
960
  await created.ready;
772
961
  }
773
962
  catch (error) {
774
- this.children.delete(id);
963
+ if (this.children.get(id) === created)
964
+ this.children.delete(id);
965
+ this.releaseEngine(created);
775
966
  await created.stop().catch(() => undefined);
776
967
  throw new RelayRefusal('remote', `Starting engine ${id} failed: ${error instanceof Error ? error.message : String(error)}`);
777
968
  }
778
969
  return created;
779
970
  }
971
+ refuseAtEngineCap(id) {
972
+ if (id === REMOTE_PRIMARY_ENGINE)
973
+ return;
974
+ if (this.taskEngineCount() >= MAX_RELAY_ENGINES) {
975
+ throw new RelayRefusal('busy', 'This machine is already running the most concurrent remote tasks it allows. Wait for one to finish.');
976
+ }
977
+ }
978
+ async engineCommand(version) {
979
+ if (!this.engines)
980
+ return relayEngineCommand();
981
+ try {
982
+ return await this.engines.commandFor(version);
983
+ }
984
+ catch (error) {
985
+ const code = error?.code;
986
+ throw new RelayRefusal(typeof code === 'string' && KNOWN_CODES.has(code) ? code : 'remote', error instanceof Error ? error.message : String(error));
987
+ }
988
+ }
989
+ releaseEngine(child) {
990
+ if (child.released || child.id === REMOTE_PRIMARY_ENGINE || !this.engines)
991
+ return;
992
+ child.released = true;
993
+ this.engines.released(child.version ?? this.engines.hostVersion);
994
+ }
780
995
  async childIsIdle(child) {
781
996
  try {
782
997
  const info = await child.request('host.info', {}, 5_000);
@@ -786,13 +1001,27 @@ export class RemoteEngineRelay {
786
1001
  return false;
787
1002
  }
788
1003
  }
1004
+ // An engine that cannot say is taken to have one: retiring it would end the process with it.
1005
+ async childRunsBackground(child) {
1006
+ try {
1007
+ const listed = await child.request('background.list', {}, 5_000);
1008
+ return (listed?.tasks ?? []).some(task => task.running === true);
1009
+ }
1010
+ catch {
1011
+ return true;
1012
+ }
1013
+ }
789
1014
  async childHoldsWake(child) {
790
1015
  try {
791
- const listed = await child.request('timers.list', {}, 5_000);
1016
+ const listed = await child.request('timers.list', {}, this.timing.wakeAnswerMs ?? 5_000);
1017
+ child.unansweredSince = undefined;
792
1018
  return (listed?.sessions ?? []).some(entry => Array.isArray(entry.timers) && entry.timers.length > 0);
793
1019
  }
794
1020
  catch {
795
- return true;
1021
+ // It may hold a wake it cannot report, but an engine that hangs for good must not hold the host's restart for good.
1022
+ const now = (this.timing.now ?? Date.now)();
1023
+ child.unansweredSince ??= now;
1024
+ return now - child.unansweredSince < UNANSWERING_ENGINE_HOLD_MS;
796
1025
  }
797
1026
  }
798
1027
  async retireChild(id) {
@@ -800,6 +1029,7 @@ export class RemoteEngineRelay {
800
1029
  if (!child)
801
1030
  return;
802
1031
  this.children.delete(id);
1032
+ this.releaseEngine(child);
803
1033
  await child.stop().catch(() => undefined);
804
1034
  }
805
1035
  async translation(viewerWorkspaceId) {
@@ -832,40 +1062,98 @@ export class RemoteEngineRelay {
832
1062
  this.translations.set(viewerWorkspaceId, { at: now, translation });
833
1063
  return translation;
834
1064
  }
835
- startRevocationPoll() {
836
- if (this.revocationTimer !== undefined)
1065
+ // A connection nobody listens to is abandoned (a viewer that never came back); sever it so its terminals and streams are reclaimed.
1066
+ startSinklessSweep() {
1067
+ if (this.sinklessTimer !== undefined)
837
1068
  return;
838
- const sweep = () => {
839
- void (async () => {
840
- const config = await loadConfig(this.directory);
841
- const valid = new Set((config.remote?.hosting?.devices ?? []).filter(device => device.grant === 'full').map(device => device.id));
842
- for (const [, connection] of [...this.connections]) {
843
- if (valid.has(connection.deviceId)) {
844
- if (connection.sinks.size === 0 && connection.sinklessSince !== 0 && Date.now() - connection.sinklessSince > SINKLESS_CONNECTION_TTL_MS) {
845
- this.sever(connection);
846
- }
847
- continue;
848
- }
1069
+ const ttl = this.timing.sinklessTtlMs ?? SINKLESS_CONNECTION_TTL_MS;
1070
+ this.sinklessTimer = setInterval(() => {
1071
+ for (const connection of [...this.connections.values()]) {
1072
+ if (connection.sinks.size === 0 && connection.sinklessSince !== 0 && Date.now() - connection.sinklessSince > ttl)
849
1073
  this.sever(connection);
850
- }
851
- })().catch(() => undefined);
852
- };
853
- this.revocationTimer = setInterval(sweep, REVOCATION_POLL_MS);
854
- this.revocationTimer.unref?.();
1074
+ }
1075
+ }, this.timing.sweepMs ?? SINKLESS_SWEEP_MS);
1076
+ this.sinklessTimer.unref?.();
1077
+ }
1078
+ /** Runs doing work on this machine: a run waiting for the user's computer, an approval or an answer is not counted. */
1079
+ activity() {
1080
+ let running = 0;
1081
+ for (const engineId of this.activeRuns.keys())
1082
+ if (!WAITING_RUN_STATES.has(this.runStates.get(engineId) ?? ''))
1083
+ running += 1;
1084
+ return { running };
1085
+ }
1086
+ /** Task starts in flight plus runs on task engines, waiting ones included: what a host restart would interrupt. */
1087
+ runningTasks() {
1088
+ return this.startsInFlight + this.activeRuns.size;
1089
+ }
1090
+ /**
1091
+ * Work a host restart would lose that runningTasks() may not show: a terminal open on the primary engine, and in any engine
1092
+ * a wake armed (it lives only in that engine's memory and starts a run when due), a run as the engine itself reports it
1093
+ * (one it started from a wake, the primary's included, which no run.start announced), or a background process still running.
1094
+ * An engine that does not answer counts as holding for UNANSWERING_ENGINE_HOLD_MS of silence, and no longer.
1095
+ */
1096
+ async holdsWork() {
1097
+ if (this.terminalOwner.size > 0)
1098
+ return true;
1099
+ for (const child of [...this.children.values()])
1100
+ if (await this.childHoldsWork(child))
1101
+ return true;
1102
+ return false;
1103
+ }
1104
+ async childHoldsWork(child) {
1105
+ const deadline = this.timing.wakeAnswerMs ?? 5_000;
1106
+ try {
1107
+ // Wakes are asked before runs: an engine keeps a firing wake listed until the run it starts is its running run, so in
1108
+ // this order a wake on its way to becoming a run is seen as one or the other.
1109
+ const listed = await child.request('timers.list', {}, deadline);
1110
+ const info = await child.request('host.info', {}, deadline);
1111
+ const background = await child.request('background.list', {}, deadline);
1112
+ child.unansweredSince = undefined;
1113
+ return (listed?.sessions ?? []).some(entry => Array.isArray(entry.timers) && entry.timers.length > 0)
1114
+ || info?.running === true
1115
+ || (background?.tasks ?? []).some(task => task.running === true);
1116
+ }
1117
+ catch {
1118
+ const now = (this.timing.now ?? Date.now)();
1119
+ child.unansweredSince ??= now;
1120
+ return now - child.unansweredSince < UNANSWERING_ENGINE_HOLD_MS;
1121
+ }
1122
+ }
1123
+ /** The engine version the desktop that opened this connection runs, or undefined when it said none or the connection is gone. */
1124
+ connectionVersion(connectionId) {
1125
+ return this.connections.get(connectionId)?.version;
1126
+ }
1127
+ disconnect(deviceId, connectionId) {
1128
+ for (const connection of [...this.connections.values()]) {
1129
+ if (connection.deviceId !== deviceId)
1130
+ continue;
1131
+ if (connectionId !== undefined && connection.id !== connectionId)
1132
+ continue;
1133
+ this.sever(connection);
1134
+ }
855
1135
  }
856
1136
  async close() {
857
1137
  if (this.closed)
858
1138
  return;
859
1139
  this.closed = true;
860
- if (this.revocationTimer !== undefined)
861
- clearInterval(this.revocationTimer);
1140
+ this.stopWatching();
1141
+ if (this.sinklessTimer !== undefined)
1142
+ clearInterval(this.sinklessTimer);
862
1143
  for (const connection of [...this.connections.values()])
863
1144
  this.sever(connection);
864
1145
  const children = [...this.children.values()];
865
1146
  this.children.clear();
1147
+ for (const child of children)
1148
+ this.releaseEngine(child);
866
1149
  await Promise.all(children.map(child => child.stop().catch(() => undefined)));
867
1150
  }
868
1151
  }
1152
+ /** How long an engine that keeps failing to say what wakes it holds is taken to hold one. */
1153
+ export const UNANSWERING_ENGINE_HOLD_MS = 120_000;
1154
+ const WAITING_RUN_STATES = new Set(['awaiting-desktop', 'awaiting-approval', 'awaiting-input']);
1155
+ // Event fields whose content is not a path on this machine (a page's arguments) and must arrive as the engine emitted it.
1156
+ const VERBATIM_EVENT_FIELDS = new Map([['browser.panel.request', 'arguments']]);
869
1157
  const VERBATIM_FIELDS = new Set(['fileDiff']);
870
1158
  function rewritePaths(value, paths) {
871
1159
  if (typeof value === 'string')
@@ -880,5 +1168,6 @@ function rewritePaths(value, paths) {
880
1168
  }
881
1169
  return value;
882
1170
  }
883
- const OPAQUE_RESPONSE_METHODS = new Set(['browser.view.selection', 'browser.view.cursor', 'sessions.changes.list', 'sessions.changes.get']);
1171
+ // A claim's answer carries a model request's payload: model input, never a path on this machine, so it is not rewritten.
1172
+ const OPAQUE_RESPONSE_METHODS = new Set(['model.relay.claim', 'browser.view.selection', 'browser.view.cursor', 'sessions.changes.list', 'sessions.changes.get', 'sessions.pullRequest.details', 'sessions.pullRequest.files', ...PULL_REQUEST_REVIEW_ANSWERS, ...PULL_REQUEST_MERGE_ANSWERS, 'sessions.pullRequest.create', ...PULL_REQUEST_PHASE4_ANSWERS]);
884
1173
  export { REMOTE_PROJECT_PREFIX, isRemoteProjectSpelling, rootPartOf };