@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
@@ -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,12 +17,14 @@ 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;
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;
24
28
  // The PR tab's review: a read of threads, viewed files and reviewers, and the writes, three of which answer with that read.
25
29
  const PULL_REQUEST_REVIEW_WRITES = ['sessions.pullRequest.submitReview', 'sessions.pullRequest.thread', 'sessions.pullRequest.markViewed', 'sessions.pullRequest.rerunChecks', 'sessions.pullRequest.requestReviewers'];
26
30
  const PULL_REQUEST_REVIEW_ANSWERS = ['sessions.pullRequest.review', 'sessions.pullRequest.submitReview', 'sessions.pullRequest.thread', 'sessions.pullRequest.requestReviewers'];
@@ -31,17 +35,24 @@ const PULL_REQUEST_MERGE_ANSWERS = ['sessions.pullRequest.mergeState', 'sessions
31
35
  // Phase 4: the conversation, suggestions, failed-check logs, editing the PR, the merge queue and attaching a PR to a task.
32
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'];
33
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'];
34
- const LARGE_RESPONSE_METHODS = new Set(['runs.get', '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']);
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']);
35
42
  const PRIMARY_METHODS = new Set([
36
- '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',
37
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',
38
48
  'sessions.skill.get', 'sessions.skill.update',
39
49
  'sessions.pullRequest.list', 'sessions.pullRequest.details', 'sessions.pullRequest.files', 'sessions.pullRequest.review', ...PULL_REQUEST_REVIEW_WRITES,
40
50
  'sessions.pullRequest.mergeState', 'sessions.pullRequest.draft', ...PULL_REQUEST_MERGE_WRITES,
41
51
  'sessions.pullRequest.checkLog', 'pullRequests.reviewRequests', 'issues.list', ...PULL_REQUEST_PHASE4_WRITES,
42
52
  'sessions.changes.list', 'sessions.changes.get', 'sessions.changes.keep', 'sessions.changes.undo',
53
+ 'github.status', ...GITHUB_APP_WRITES,
43
54
  'runs.list', 'runs.get', 'timers.list',
44
- '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',
45
56
  'graphs.list', 'graphs.get', 'graphs.select', 'graphs.visibility.set', 'graphs.visibility.import',
46
57
  'attachments.read',
47
58
  'config.get', 'projects.list', 'projects.add', 'projects.remove', 'projects.relink',
@@ -57,12 +68,14 @@ const PRIMARY_METHODS = new Set([
57
68
  'browser.panel.op', 'browser.panel.cancel',
58
69
  ]);
59
70
  const RUN_START_METHODS = new Set(['run.start', 'run.resume']);
60
- 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]);
61
74
  const TERMINAL_METHODS = new Set(['terminal.open', 'terminal.write', 'terminal.resize', 'terminal.close', 'terminal.closeAll']);
62
75
  const ALLOWED_METHODS = new Set([...PRIMARY_METHODS, ...RUN_START_METHODS, ...RUN_TARGET_METHODS, ...TERMINAL_METHODS]);
63
- 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']);
64
77
  const MUTATING_METHODS = new Set([
65
- ...RUN_START_METHODS, ...RUN_TARGET_METHODS, ...SESSION_MUTATION_METHODS, ...PULL_REQUEST_REVIEW_WRITES, ...PULL_REQUEST_MERGE_WRITES, ...PULL_REQUEST_PHASE4_WRITES, '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',
66
79
  'terminal.open', 'terminal.write', 'terminal.close', 'terminal.closeAll', 'workspace.checkout', 'projects.add', 'projects.remove', 'projects.relink',
67
80
  'graphs.visibility.set', 'graphs.visibility.import',
68
81
  'browser.runtime.install', 'browser.view.open', 'browser.view.navigate', 'browser.view.go', 'browser.view.activate',
@@ -71,6 +84,10 @@ const MUTATING_METHODS = new Set([
71
84
  'browser.extensions.commit', 'browser.extensions.discard', 'browser.extensions.remove', 'browser.extensions.setEnabled',
72
85
  'browser.extensions.reload', 'browser.extensions.restart',
73
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
+ }
74
91
  class ChildError extends Error {
75
92
  code;
76
93
  constructor(code, message) {
@@ -105,6 +122,13 @@ class ChildEngine {
105
122
  rejectReady;
106
123
  stopped = false;
107
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;
108
132
  advertised = [];
109
133
  stderrTail = [];
110
134
  constructor(id, command, home, onEvent, onExit) {
@@ -114,7 +138,7 @@ class ChildEngine {
114
138
  this.child = spawn(command[0], command.slice(1), {
115
139
  windowsHide: true,
116
140
  stdio: ['pipe', 'pipe', 'pipe'],
117
- env: { ...process.env, ANDORRACODE_HOME: home, ANDORRA_SURFACE: 'remote' },
141
+ env: engineEnvironment(home),
118
142
  });
119
143
  this.ready = new Promise((resolve, reject) => {
120
144
  this.resolveReady = resolve;
@@ -189,6 +213,9 @@ class ChildEngine {
189
213
  this.child.kill();
190
214
  this.onExit(this.id);
191
215
  }
216
+ get inFlight() {
217
+ return this.pending.size;
218
+ }
192
219
  supports(capability) {
193
220
  return this.advertised.includes(capability);
194
221
  }
@@ -243,6 +270,15 @@ class ChildEngine {
243
270
  });
244
271
  }
245
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
+ }
246
282
  export function relayEngineCommand() {
247
283
  const override = process.env.ANDORRA_REMOTE_ENGINE_COMMAND;
248
284
  if (override) {
@@ -272,6 +308,7 @@ function rootPartOf(value) {
272
308
  }
273
309
  export class RemoteEngineRelay {
274
310
  directory;
311
+ timing;
275
312
  children = new Map();
276
313
  retiringChildren = new Set();
277
314
  taskSeq = 0;
@@ -281,13 +318,67 @@ export class RemoteEngineRelay {
281
318
  runEngine = new Map();
282
319
  sessionEngine = new Map();
283
320
  activeRuns = new Map();
321
+ runStates = new Map();
284
322
  finishedRuns = new Map();
285
323
  translations = new Map();
286
- revocationTimer;
324
+ sinklessTimer;
287
325
  delivery = Promise.resolve();
288
326
  closed = false;
289
- constructor(directory) {
327
+ startsInFlight = 0;
328
+ engines;
329
+ stopWatching;
330
+ constructor(directory, timing = {}, options = {}) {
290
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);
291
382
  }
292
383
  async request(deviceId, body) {
293
384
  try {
@@ -296,7 +387,7 @@ export class RemoteEngineRelay {
296
387
  const translation = await this.translation(body.viewerWorkspaceId);
297
388
  const rewritten = OPAQUE_RESPONSE_METHODS.has(method) ? (result ?? null) : translation.rewrite(result ?? null);
298
389
  const serialized = JSON.stringify(rewritten) ?? 'null';
299
- 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;
300
391
  if (Buffer.byteLength(serialized) > cap) {
301
392
  return { error: { code: 'remote', message: `${method} answered larger than the remote link allows (${Math.round(cap / 1024 / 1024)} MiB).` } };
302
393
  }
@@ -332,8 +423,17 @@ export class RemoteEngineRelay {
332
423
  const deadline = this.childDeadline(body);
333
424
  if (TERMINAL_METHODS.has(method))
334
425
  return this.terminalRequest(connection, method, params, deadline);
335
- if (RUN_START_METHODS.has(method))
336
- 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
+ }
337
437
  if (RUN_TARGET_METHODS.has(method))
338
438
  return this.runTargetRequest(body, method, params, deadline);
339
439
  if (SESSION_MUTATION_METHODS.has(method) && typeof params.id === 'string') {
@@ -373,13 +473,15 @@ export class RemoteEngineRelay {
373
473
  }
374
474
  return answer;
375
475
  }
376
- async startRequest(body, method, params, deadline) {
476
+ async startRequest(connection, body, method, params, deadline) {
477
+ const version = this.engineVersion(connection);
377
478
  const { requireCapability, ...rest } = params;
378
479
  const required = typeof requireCapability === 'string' && requireCapability.length > 0 ? requireCapability : undefined;
379
480
  const translated = await this.translateParams(body.viewerWorkspaceId, rest);
380
481
  if (body.engine !== '' && body.engine !== REMOTE_PRIMARY_ENGINE) {
381
482
  const addressed = this.children.get(body.engine);
382
- 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) {
383
485
  if (this.retiringChildren.has(addressed.id)) {
384
486
  throw new RelayRefusal('busy', 'That engine is being stopped; try again.');
385
487
  }
@@ -392,7 +494,7 @@ export class RemoteEngineRelay {
392
494
  }
393
495
  const incompatible = [];
394
496
  for (const [id, engine] of [...this.children]) {
395
- if (id === REMOTE_PRIMARY_ENGINE)
497
+ if (id === REMOTE_PRIMARY_ENGINE || engine.version !== version)
396
498
  continue;
397
499
  if (required !== undefined && !engine.supports(required)) {
398
500
  if (!engine.busy && !this.retiringChildren.has(id))
@@ -420,6 +522,8 @@ export class RemoteEngineRelay {
420
522
  continue;
421
523
  if (!await this.childIsIdle(child))
422
524
  continue;
525
+ if (await this.childRunsBackground(child))
526
+ continue;
423
527
  await this.retireChild(child.id);
424
528
  break;
425
529
  }
@@ -427,7 +531,9 @@ export class RemoteEngineRelay {
427
531
  this.retiringChildren.delete(child.id);
428
532
  }
429
533
  }
430
- 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;
431
537
  try {
432
538
  if (required !== undefined && !spawned.supports(required)) {
433
539
  throw new RelayRefusal('invalid-params', `This machine's engine does not support ${required}.`);
@@ -440,6 +546,39 @@ export class RemoteEngineRelay {
440
546
  await this.retireChild(spawned.id);
441
547
  throw error;
442
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;
443
582
  }
444
583
  async runTargetRequest(body, method, params, deadline) {
445
584
  let owner;
@@ -453,7 +592,9 @@ export class RemoteEngineRelay {
453
592
  if (owner === undefined) {
454
593
  throw new RelayRefusal('not-found', 'That interaction is not waiting on this machine.');
455
594
  }
456
- 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);
457
598
  }
458
599
  async terminalRequest(connection, method, params, deadline) {
459
600
  const primary = await this.engine(REMOTE_PRIMARY_ENGINE);
@@ -511,43 +652,54 @@ export class RemoteEngineRelay {
511
652
  || (visibility !== undefined && Object.values(visibility).some(spelledList));
512
653
  if (!needs)
513
654
  return params;
514
- const translation = await this.translation(viewerWorkspaceId);
515
- const next = { ...params };
516
- if (typeof next.workspace === 'string' && isRemoteProjectSpelling(next.workspace))
517
- next.workspace = translation.toHost(next.workspace);
518
- if (typeof next.cwd === 'string' && isRemoteProjectSpelling(next.cwd))
519
- next.cwd = translation.toHost(next.cwd);
520
- if (typeof next.path === 'string' && isRemoteProjectSpelling(next.path))
521
- next.path = translation.toHost(next.path);
522
- if (workspaces !== undefined) {
523
- 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 => {
524
678
  if (typeof value !== 'string' || !isRemoteProjectSpelling(value))
525
- return value;
679
+ return [value];
526
680
  try {
527
- return translation.toHost(value);
681
+ return [translation.toHost(value)];
528
682
  }
529
683
  catch {
530
- return value;
684
+ return [];
531
685
  }
532
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));
533
702
  }
534
- // A visibility list is stored on this host, so it keeps host paths only. A viewer spelling this host cannot place
535
- // names no folder it shares and could never match here; it is left out rather than saved as a viewer's ID.
536
- const hostPaths = (list) => !Array.isArray(list) ? list : list.flatMap(value => {
537
- if (typeof value !== 'string' || !isRemoteProjectSpelling(value))
538
- return [value];
539
- try {
540
- return [translation.toHost(value)];
541
- }
542
- catch {
543
- return [];
544
- }
545
- });
546
- if (projects !== undefined)
547
- next.projects = hostPaths(projects);
548
- if (visibility !== undefined)
549
- next.visibility = Object.fromEntries(Object.entries(visibility).map(([graph, list]) => [graph, hostPaths(list)]));
550
- return next;
551
703
  }
552
704
  async restoreRequestedEcho(answer, original, viewerWorkspaceId) {
553
705
  const groups = answer?.groups;
@@ -566,9 +718,9 @@ export class RemoteEngineRelay {
566
718
  connection(deviceId, connectionId, viewerWorkspaceId) {
567
719
  let found = this.connections.get(connectionId);
568
720
  if (!found) {
569
- 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() };
570
722
  this.connections.set(connectionId, found);
571
- this.startRevocationPoll();
723
+ this.startSinklessSweep();
572
724
  }
573
725
  found.deviceId = deviceId;
574
726
  if (viewerWorkspaceId !== undefined)
@@ -602,14 +754,21 @@ export class RemoteEngineRelay {
602
754
  connection.browserStreams.clear();
603
755
  this.connections.delete(connection.id);
604
756
  }
605
- events(deviceId, connectionId, viewerWorkspaceId, sink, cut) {
757
+ events(deviceId, connectionId, viewerWorkspaceId, sink, cut, version) {
606
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);
607
762
  connection.sinks.add(sink);
608
763
  connection.cuts.add(cut);
609
764
  connection.sinklessSince = 0;
610
- 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);
611
769
  return () => {
612
770
  connection.sinks.delete(sink);
771
+ connection.installNotices.delete(sink);
613
772
  connection.cuts.delete(cut);
614
773
  if (connection.sinks.size > 0)
615
774
  return;
@@ -677,9 +836,13 @@ export class RemoteEngineRelay {
677
836
  this.runEngine.set(runId, engineId);
678
837
  if (typeof data.sessionId === 'string')
679
838
  this.sessionEngine.set(data.sessionId, engineId);
680
- if (engineId !== REMOTE_PRIMARY_ENGINE)
839
+ if (engineId !== REMOTE_PRIMARY_ENGINE) {
681
840
  this.activeRuns.set(engineId, data);
841
+ this.runStates.delete(engineId);
842
+ }
682
843
  }
844
+ if (event === 'run.state' && typeof data.state === 'string' && this.activeRuns.has(engineId))
845
+ this.runStates.set(engineId, data.state);
683
846
  if (event === 'run.completed' || event === 'run.failed') {
684
847
  if (runId !== undefined)
685
848
  this.runEngine.delete(runId);
@@ -690,6 +853,7 @@ export class RemoteEngineRelay {
690
853
  child.busy = false;
691
854
  if (engineId !== REMOTE_PRIMARY_ENGINE) {
692
855
  this.activeRuns.delete(engineId);
856
+ this.runStates.delete(engineId);
693
857
  this.finishedRuns.set(engineId, { event, data, at: Date.now() });
694
858
  if (this.finishedRuns.size > FINISHED_RUNS_REMEMBERED) {
695
859
  const oldest = this.finishedRuns.keys().next().value;
@@ -718,6 +882,8 @@ export class RemoteEngineRelay {
718
882
  for (const connection of [...this.connections.values()]) {
719
883
  if (connection.sinks.size === 0)
720
884
  continue;
885
+ if (connection.id.startsWith(MODEL_RELAY_CONNECTION_PREFIX) && !event.startsWith('model.relay.'))
886
+ continue;
721
887
  const translation = await this.translation(connection.viewerWorkspaceId);
722
888
  const frame = { engine: engineId, event, data: this.rewriteEventData(translation, event, data) };
723
889
  for (const sink of [...connection.sinks]) {
@@ -729,10 +895,11 @@ export class RemoteEngineRelay {
729
895
  }
730
896
  }
731
897
  rewriteEventData(translation, event, data) {
732
- if (event !== 'browser.panel.request' || data.arguments === undefined)
898
+ const field = VERBATIM_EVENT_FIELDS.get(event);
899
+ if (field === undefined || data[field] === undefined)
733
900
  return translation.rewrite(data);
734
- const { arguments: verbatim, ...rest } = data;
735
- return { ...translation.rewrite(rest), arguments: verbatim };
901
+ const { [field]: verbatim, ...rest } = data;
902
+ return { ...translation.rewrite(rest), [field]: verbatim };
736
903
  }
737
904
  onChildExit(engineId) {
738
905
  const interrupted = this.activeRuns.get(engineId);
@@ -741,8 +908,12 @@ export class RemoteEngineRelay {
741
908
  .then(recovered => reportInterruptedRuns({ home: this.directory, surface: configuredSurface('remote') }, recovered.interrupted))
742
909
  .catch(() => undefined);
743
910
  }
911
+ const exited = this.children.get(engineId);
744
912
  this.children.delete(engineId);
913
+ if (exited)
914
+ this.releaseEngine(exited);
745
915
  this.activeRuns.delete(engineId);
916
+ this.runStates.delete(engineId);
746
917
  for (const [runId, owner] of [...this.runEngine])
747
918
  if (owner === engineId)
748
919
  this.runEngine.delete(runId);
@@ -765,30 +936,62 @@ export class RemoteEngineRelay {
765
936
  throw new RelayRefusal('not-found', `No engine ${id} is serving this machine's remote surface.`);
766
937
  return this.spawnChild(REMOTE_PRIMARY_ENGINE);
767
938
  }
768
- async spawnChild(id) {
939
+ async spawnChild(id, version) {
769
940
  const existing = this.children.get(id);
770
941
  if (existing)
771
942
  return existing;
772
943
  if (this.closed)
773
944
  throw new RelayRefusal('remote', 'The remote engine relay is shutting down.');
774
- if (id !== REMOTE_PRIMARY_ENGINE) {
775
- const taskEngines = [...this.children.keys()].filter(childId => childId !== REMOTE_PRIMARY_ENGINE).length;
776
- if (taskEngines >= MAX_RELAY_ENGINES) {
777
- throw new RelayRefusal('busy', 'This machine is already running the most concurrent remote tasks it allows. Wait for one to finish.');
778
- }
779
- }
780
- 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;
781
956
  this.children.set(id, created);
957
+ if (id !== REMOTE_PRIMARY_ENGINE)
958
+ this.engines?.inUse(version ?? this.engines.hostVersion);
782
959
  try {
783
960
  await created.ready;
784
961
  }
785
962
  catch (error) {
786
- this.children.delete(id);
963
+ if (this.children.get(id) === created)
964
+ this.children.delete(id);
965
+ this.releaseEngine(created);
787
966
  await created.stop().catch(() => undefined);
788
967
  throw new RelayRefusal('remote', `Starting engine ${id} failed: ${error instanceof Error ? error.message : String(error)}`);
789
968
  }
790
969
  return created;
791
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
+ }
792
995
  async childIsIdle(child) {
793
996
  try {
794
997
  const info = await child.request('host.info', {}, 5_000);
@@ -798,13 +1001,27 @@ export class RemoteEngineRelay {
798
1001
  return false;
799
1002
  }
800
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
+ }
801
1014
  async childHoldsWake(child) {
802
1015
  try {
803
- 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;
804
1018
  return (listed?.sessions ?? []).some(entry => Array.isArray(entry.timers) && entry.timers.length > 0);
805
1019
  }
806
1020
  catch {
807
- 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;
808
1025
  }
809
1026
  }
810
1027
  async retireChild(id) {
@@ -812,6 +1029,7 @@ export class RemoteEngineRelay {
812
1029
  if (!child)
813
1030
  return;
814
1031
  this.children.delete(id);
1032
+ this.releaseEngine(child);
815
1033
  await child.stop().catch(() => undefined);
816
1034
  }
817
1035
  async translation(viewerWorkspaceId) {
@@ -844,40 +1062,98 @@ export class RemoteEngineRelay {
844
1062
  this.translations.set(viewerWorkspaceId, { at: now, translation });
845
1063
  return translation;
846
1064
  }
847
- startRevocationPoll() {
848
- 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)
849
1068
  return;
850
- const sweep = () => {
851
- void (async () => {
852
- const config = await loadConfig(this.directory);
853
- const valid = new Set((config.remote?.hosting?.devices ?? []).filter(device => device.grant === 'full').map(device => device.id));
854
- for (const [, connection] of [...this.connections]) {
855
- if (valid.has(connection.deviceId)) {
856
- if (connection.sinks.size === 0 && connection.sinklessSince !== 0 && Date.now() - connection.sinklessSince > SINKLESS_CONNECTION_TTL_MS) {
857
- this.sever(connection);
858
- }
859
- continue;
860
- }
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)
861
1073
  this.sever(connection);
862
- }
863
- })().catch(() => undefined);
864
- };
865
- this.revocationTimer = setInterval(sweep, REVOCATION_POLL_MS);
866
- 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
+ }
867
1135
  }
868
1136
  async close() {
869
1137
  if (this.closed)
870
1138
  return;
871
1139
  this.closed = true;
872
- if (this.revocationTimer !== undefined)
873
- clearInterval(this.revocationTimer);
1140
+ this.stopWatching();
1141
+ if (this.sinklessTimer !== undefined)
1142
+ clearInterval(this.sinklessTimer);
874
1143
  for (const connection of [...this.connections.values()])
875
1144
  this.sever(connection);
876
1145
  const children = [...this.children.values()];
877
1146
  this.children.clear();
1147
+ for (const child of children)
1148
+ this.releaseEngine(child);
878
1149
  await Promise.all(children.map(child => child.stop().catch(() => undefined)));
879
1150
  }
880
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']]);
881
1157
  const VERBATIM_FIELDS = new Set(['fileDiff']);
882
1158
  function rewritePaths(value, paths) {
883
1159
  if (typeof value === 'string')
@@ -892,5 +1168,6 @@ function rewritePaths(value, paths) {
892
1168
  }
893
1169
  return value;
894
1170
  }
895
- const OPAQUE_RESPONSE_METHODS = new Set(['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]);
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]);
896
1173
  export { REMOTE_PROJECT_PREFIX, isRemoteProjectSpelling, rootPartOf };