@layernorm/overlay-agent-host 0.3.11 → 0.4.2

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 (190) hide show
  1. package/README.md +11 -1
  2. package/dist/acp-adapter.d.ts +47 -22
  3. package/dist/acp-adapter.d.ts.map +1 -1
  4. package/dist/acp-adapter.js +132 -40
  5. package/dist/acp-adapter.js.map +1 -1
  6. package/dist/acp-settings.d.ts +29 -0
  7. package/dist/acp-settings.d.ts.map +1 -0
  8. package/dist/acp-settings.js +48 -0
  9. package/dist/acp-settings.js.map +1 -0
  10. package/dist/acpx-adapter.d.ts +42 -24
  11. package/dist/acpx-adapter.d.ts.map +1 -1
  12. package/dist/acpx-adapter.js +153 -37
  13. package/dist/acpx-adapter.js.map +1 -1
  14. package/dist/acpx-session-identity.d.ts +35 -0
  15. package/dist/acpx-session-identity.d.ts.map +1 -0
  16. package/dist/acpx-session-identity.js +55 -0
  17. package/dist/acpx-session-identity.js.map +1 -0
  18. package/dist/action-title.d.ts +3 -0
  19. package/dist/action-title.d.ts.map +1 -0
  20. package/dist/action-title.js +11 -0
  21. package/dist/action-title.js.map +1 -0
  22. package/dist/adapter-manifests.d.ts +8 -6
  23. package/dist/adapter-manifests.d.ts.map +1 -1
  24. package/dist/adapter-manifests.js +19 -2
  25. package/dist/adapter-manifests.js.map +1 -1
  26. package/dist/adapter.d.ts +11 -1
  27. package/dist/adapter.d.ts.map +1 -1
  28. package/dist/adapter.js +9 -1
  29. package/dist/adapter.js.map +1 -1
  30. package/dist/agent-options.d.ts +4 -0
  31. package/dist/agent-options.d.ts.map +1 -0
  32. package/dist/agent-options.js +49 -0
  33. package/dist/agent-options.js.map +1 -0
  34. package/dist/cli.js +106 -82
  35. package/dist/cli.js.map +1 -1
  36. package/dist/config.d.ts +123 -10
  37. package/dist/config.d.ts.map +1 -1
  38. package/dist/config.js +18 -5
  39. package/dist/config.js.map +1 -1
  40. package/dist/connection.d.ts +3 -3
  41. package/dist/discovery-workspace.d.ts +6 -0
  42. package/dist/discovery-workspace.d.ts.map +1 -0
  43. package/dist/discovery-workspace.js +20 -0
  44. package/dist/discovery-workspace.js.map +1 -0
  45. package/dist/drive-cache.d.ts +58 -0
  46. package/dist/drive-cache.d.ts.map +1 -0
  47. package/dist/drive-cache.js +243 -0
  48. package/dist/drive-cache.js.map +1 -0
  49. package/dist/drive-client.d.ts +112 -0
  50. package/dist/drive-client.d.ts.map +1 -0
  51. package/dist/drive-client.js +273 -0
  52. package/dist/drive-client.js.map +1 -0
  53. package/dist/drive-journal.d.ts +1218 -0
  54. package/dist/drive-journal.d.ts.map +1 -0
  55. package/dist/drive-journal.js +290 -0
  56. package/dist/drive-journal.js.map +1 -0
  57. package/dist/drive-lease.d.ts +15 -0
  58. package/dist/drive-lease.d.ts.map +1 -0
  59. package/dist/drive-lease.js +79 -0
  60. package/dist/drive-lease.js.map +1 -0
  61. package/dist/drive-restoration.d.ts +16 -0
  62. package/dist/drive-restoration.d.ts.map +1 -0
  63. package/dist/drive-restoration.js +36 -0
  64. package/dist/drive-restoration.js.map +1 -0
  65. package/dist/drive-sync-state.d.ts +2346 -0
  66. package/dist/drive-sync-state.d.ts.map +1 -0
  67. package/dist/drive-sync-state.js +100 -0
  68. package/dist/drive-sync-state.js.map +1 -0
  69. package/dist/drive-sync.d.ts +56 -0
  70. package/dist/drive-sync.d.ts.map +1 -0
  71. package/dist/drive-sync.js +539 -0
  72. package/dist/drive-sync.js.map +1 -0
  73. package/dist/drive-writer.d.ts +27 -0
  74. package/dist/drive-writer.d.ts.map +1 -0
  75. package/dist/drive-writer.js +64 -0
  76. package/dist/drive-writer.js.map +1 -0
  77. package/dist/enrollment.js +1 -1
  78. package/dist/enrollment.js.map +1 -1
  79. package/dist/host-capabilities.d.ts +12 -0
  80. package/dist/host-capabilities.d.ts.map +1 -0
  81. package/dist/host-capabilities.js +70 -0
  82. package/dist/host-capabilities.js.map +1 -0
  83. package/dist/host-heartbeat.d.ts +14 -0
  84. package/dist/host-heartbeat.d.ts.map +1 -0
  85. package/dist/host-heartbeat.js +41 -0
  86. package/dist/host-heartbeat.js.map +1 -0
  87. package/dist/image-check.d.ts +1 -1
  88. package/dist/image-check.js +4 -4
  89. package/dist/image-check.js.map +1 -1
  90. package/dist/native-restoration.d.ts +7 -0
  91. package/dist/native-restoration.d.ts.map +1 -0
  92. package/dist/native-restoration.js +21 -0
  93. package/dist/native-restoration.js.map +1 -0
  94. package/dist/native-start-barrier.d.ts +27 -0
  95. package/dist/native-start-barrier.d.ts.map +1 -0
  96. package/dist/native-start-barrier.js +28 -0
  97. package/dist/native-start-barrier.js.map +1 -0
  98. package/dist/native-start-preparation.d.ts +6 -0
  99. package/dist/native-start-preparation.d.ts.map +1 -0
  100. package/dist/native-start-preparation.js +23 -0
  101. package/dist/native-start-preparation.js.map +1 -0
  102. package/dist/ordered-acp-updates.d.ts +11 -0
  103. package/dist/ordered-acp-updates.d.ts.map +1 -0
  104. package/dist/ordered-acp-updates.js +38 -0
  105. package/dist/ordered-acp-updates.js.map +1 -0
  106. package/dist/outbox-packing.d.ts +22 -0
  107. package/dist/outbox-packing.d.ts.map +1 -0
  108. package/dist/outbox-packing.js +51 -0
  109. package/dist/outbox-packing.js.map +1 -0
  110. package/dist/outbox-receipts.d.ts +20 -0
  111. package/dist/outbox-receipts.d.ts.map +1 -0
  112. package/dist/outbox-receipts.js +44 -0
  113. package/dist/outbox-receipts.js.map +1 -0
  114. package/dist/preparation-command-polling.d.ts +13 -0
  115. package/dist/preparation-command-polling.d.ts.map +1 -0
  116. package/dist/preparation-command-polling.js +62 -0
  117. package/dist/preparation-command-polling.js.map +1 -0
  118. package/dist/preparation-failure.d.ts +2 -0
  119. package/dist/preparation-failure.d.ts.map +1 -0
  120. package/dist/preparation-failure.js +19 -0
  121. package/dist/preparation-failure.js.map +1 -0
  122. package/dist/preview-hosting-access.d.ts +18 -0
  123. package/dist/preview-hosting-access.d.ts.map +1 -0
  124. package/dist/preview-hosting-access.js +48 -0
  125. package/dist/preview-hosting-access.js.map +1 -0
  126. package/dist/preview-hosting.d.ts +8 -0
  127. package/dist/preview-hosting.d.ts.map +1 -0
  128. package/dist/preview-hosting.js +19 -0
  129. package/dist/preview-hosting.js.map +1 -0
  130. package/dist/preview-mcp-relay.d.ts +8 -0
  131. package/dist/preview-mcp-relay.d.ts.map +1 -0
  132. package/dist/preview-mcp-relay.js +127 -0
  133. package/dist/preview-mcp-relay.js.map +1 -0
  134. package/dist/process-group.d.ts +4 -0
  135. package/dist/process-group.d.ts.map +1 -0
  136. package/dist/process-group.js +38 -0
  137. package/dist/process-group.js.map +1 -0
  138. package/dist/process-host-command.d.ts +14 -0
  139. package/dist/process-host-command.d.ts.map +1 -0
  140. package/dist/process-host-command.js +55 -0
  141. package/dist/process-host-command.js.map +1 -0
  142. package/dist/provider-run-credentials.d.ts +13 -0
  143. package/dist/provider-run-credentials.d.ts.map +1 -0
  144. package/dist/provider-run-credentials.js +27 -0
  145. package/dist/provider-run-credentials.js.map +1 -0
  146. package/dist/run-preparation.d.ts +9 -0
  147. package/dist/run-preparation.d.ts.map +1 -0
  148. package/dist/run-preparation.js +21 -0
  149. package/dist/run-preparation.js.map +1 -0
  150. package/dist/run-stream.d.ts +20 -0
  151. package/dist/run-stream.d.ts.map +1 -0
  152. package/dist/run-stream.js +96 -0
  153. package/dist/run-stream.js.map +1 -0
  154. package/dist/runtime-drive-controller.d.ts +26 -0
  155. package/dist/runtime-drive-controller.d.ts.map +1 -0
  156. package/dist/runtime-drive-controller.js +118 -0
  157. package/dist/runtime-drive-controller.js.map +1 -0
  158. package/dist/runtime-drive.d.ts +30 -0
  159. package/dist/runtime-drive.d.ts.map +1 -0
  160. package/dist/runtime-drive.js +151 -0
  161. package/dist/runtime-drive.js.map +1 -0
  162. package/dist/runtime-session-admission.d.ts +24 -0
  163. package/dist/runtime-session-admission.d.ts.map +1 -0
  164. package/dist/runtime-session-admission.js +46 -0
  165. package/dist/runtime-session-admission.js.map +1 -0
  166. package/dist/runtime-shutdown.d.ts +21 -0
  167. package/dist/runtime-shutdown.d.ts.map +1 -0
  168. package/dist/runtime-shutdown.js +27 -0
  169. package/dist/runtime-shutdown.js.map +1 -0
  170. package/dist/runtime-terminal-boundary.d.ts +18 -0
  171. package/dist/runtime-terminal-boundary.d.ts.map +1 -0
  172. package/dist/runtime-terminal-boundary.js +36 -0
  173. package/dist/runtime-terminal-boundary.js.map +1 -0
  174. package/dist/runtime.d.ts +71 -7
  175. package/dist/runtime.d.ts.map +1 -1
  176. package/dist/runtime.js +360 -188
  177. package/dist/runtime.js.map +1 -1
  178. package/dist/state.d.ts +29 -2
  179. package/dist/state.d.ts.map +1 -1
  180. package/dist/state.js +131 -0
  181. package/dist/state.js.map +1 -1
  182. package/dist/text-coalescer.d.ts +16 -0
  183. package/dist/text-coalescer.d.ts.map +1 -0
  184. package/dist/text-coalescer.js +55 -0
  185. package/dist/text-coalescer.js.map +1 -0
  186. package/dist/transport.d.ts +17 -13
  187. package/dist/transport.d.ts.map +1 -1
  188. package/dist/transport.js +43 -4
  189. package/dist/transport.js.map +1 -1
  190. package/package.json +2 -2
package/dist/runtime.js CHANGED
@@ -1,140 +1,204 @@
1
+ import { AdapterStartError } from './adapter.js';
1
2
  import { createHash, randomUUID } from 'node:crypto';
2
- import { platform, release } from 'node:os';
3
- import { eventBatchSchema, OVERLAY_AGENT_PROTOCOL_VERSION, } from '@layernorm/overlay-agent-bridge-protocol';
3
+ import { homedir } from 'node:os';
4
+ import { setTimeout as wait } from 'node:timers/promises';
5
+ import { agentSettingsSchema } from './acp-settings.js';
6
+ import { eventBatchSchema, OVERLAY_AGENT_PROTOCOL_VERSION, filesystemGrantSchema, } from '@layernorm/overlay-agent-bridge-protocol';
7
+ import { prepareRuntimeDrive } from './runtime-drive.js';
8
+ import { RuntimeDriveController } from './runtime-drive-controller.js';
9
+ import { createNativeTerminalIntent, observeActiveNativeRuns, withNativeTerminalBoundary } from './runtime-terminal-boundary.js';
10
+ import { HostHeartbeat } from './host-heartbeat.js';
11
+ import { buildHostCapabilities, updateHostCapabilities } from './host-capabilities.js';
12
+ import { PendingHostPrompts, quiesceHostRuns } from './runtime-shutdown.js';
13
+ import { withRunPreparation } from './run-preparation.js';
14
+ import { fetchProviderRunCredentials } from './provider-run-credentials.js';
15
+ import { requireNativeRestorationSource } from './native-restoration.js';
16
+ import { admitHostSession } from './runtime-session-admission.js';
17
+ import { nativePreparationFingerprint } from './native-start-preparation.js';
18
+ import { drainNativeSource, requestNativeStart } from './native-start-barrier.js';
19
+ import { OutboxReceipts } from './outbox-receipts.js';
20
+ import { processPolledCommands } from './preparation-command-polling.js';
21
+ import { processHostCommand } from './process-host-command.js';
4
22
  import { resolveFilesystemScope } from './filesystem-policy.js';
23
+ import { packEventBatch, shrinkOversizedEvent } from './outbox-packing.js';
24
+ import { createRunStream } from './run-stream.js';
5
25
  import { StructuredLogger } from './logger.js';
6
- import { ControlPlaneRequestError, nextReconnectDelay } from './transport.js';
26
+ import { nextReconnectDelay } from './transport.js';
7
27
  export class AgentHostRuntime {
8
28
  options;
29
+ nativePreparations = new Map();
9
30
  adapters;
10
31
  sessions = new Map();
11
32
  logger;
12
33
  flushing;
34
+ outboxReceipts = new OutboxReceipts();
35
+ /** Highest sequence being uploaded per event stream; queued checkpoints above it may still be replaced. */
36
+ inFlight = new Map();
37
+ flushRetry;
38
+ flushFailures = 0;
39
+ outboxWarned = false;
40
+ uploadsStopped = false;
41
+ streamingNegotiated = false;
42
+ streams = new Map();
13
43
  terminalRuns = new Set();
14
- lastHeartbeatAt = 0;
44
+ hostHeartbeat;
45
+ nextCapabilityRefreshAt = 0;
46
+ capabilityRefresh;
15
47
  bootId = randomUUID();
16
48
  executions = new Map();
17
49
  resolvedThroughSequence = 0;
50
+ drives = new Map();
51
+ shuttingDown = false;
52
+ shutdownDrained = false;
53
+ prompts = new PendingHostPrompts(error => this.logger.warn('prompt callbacks failed', { error: safeError(error) }));
54
+ get canCloseState() { return this.shutdownDrained; }
18
55
  constructor(options) {
19
56
  this.options = options;
20
57
  this.adapters = new Map(options.adapters.map((adapter) => [adapter.capability.id, adapter]));
21
58
  this.logger = options.logger ?? new StructuredLogger();
59
+ this.hostHeartbeat = new HostHeartbeat(() => this.heartbeat());
60
+ }
61
+ updateFilesystemGrant(grant) {
62
+ this.options.filesystem = filesystemGrantSchema.parse(grant);
22
63
  }
23
64
  async discoverCapabilities() {
24
- return Promise.all([...this.adapters.values()].map((adapter) => adapter.discover()));
65
+ // Authenticated starts already captured the live catalog. Publish it without probing or replacing auth files during work.
66
+ if (this.options.fetchRunCredentials && [...this.sessions.keys()].some(runId => !this.terminalRuns.has(runId)))
67
+ return [...this.adapters.values()].map(adapter => adapter.capability);
68
+ const root = this.options.filesystem.mode === 'all_user_files' ? homedir() : this.options.filesystem.roots[0];
69
+ return Promise.all([...this.adapters.values()].map(async (adapter) => {
70
+ if (!root)
71
+ return adapter.capability;
72
+ let credentials;
73
+ if (this.options.fetchRunCredentials && this.options.controlPlane.fetchDiscoveryCredentials) {
74
+ try {
75
+ credentials = await this.options.controlPlane.fetchDiscoveryCredentials(adapter.capability.id);
76
+ }
77
+ catch {
78
+ this.logger.warn('adapter option credentials unavailable; keeping fallback catalog', { adapterId: adapter.capability.id });
79
+ return adapter.capability;
80
+ }
81
+ }
82
+ return adapter.discover({ workingDirectory: root, ...(credentials ? { credentials } : {}) });
83
+ }));
25
84
  }
26
85
  async pollOnce(waitMs = 25_000, signal) {
86
+ // A large backlog must not stop the host from receiving commands (a Stop most of all); it only gets reported.
27
87
  if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
28
- await this.flushOutbox();
29
- if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000))
30
- throw new Error('event outbox backpressure limit reached');
88
+ this.scheduleFlush();
89
+ if (!this.outboxWarned && this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
90
+ this.outboxWarned = true;
91
+ this.logger.warn('event outbox is backed up', { events: this.options.state.outboxSize() });
92
+ }
31
93
  }
32
94
  const response = await this.options.controlPlane.pollCommands({ waitMs, ...(signal ? { signal } : {}) });
95
+ this.streamingNegotiated = response.streaming?.textDeltas === true && response.streaming.heartbeats === true;
33
96
  if (response.resolvedThroughSequence !== undefined)
34
97
  this.resolvedThroughSequence = Math.max(this.resolvedThroughSequence, response.resolvedThroughSequence);
35
- // Sequential on purpose: commands arrive ordered and may build on each
36
- // other (e.g. stop after start), so they must be processed in order.
37
- for (const command of response.commands) {
38
- // react-doctor-disable-next-line react-doctor/async-await-in-loop
39
- await this.processCommand(command);
40
- }
41
- await this.flushOutbox();
98
+ await processPolledCommands({ commands: response.commands, ...(signal ? { signal } : {}),
99
+ process: (command, preparationSignal) => this.processCommand(command, preparationSignal),
100
+ poll: signal => this.options.controlPlane.pollCommands({ waitMs: 25_000, signal }),
101
+ received: next => { if (next.resolvedThroughSequence !== undefined)
102
+ this.resolvedThroughSequence = Math.max(this.resolvedThroughSequence, next.resolvedThroughSequence); },
103
+ onError: error => this.logger.warn('preparation command polling deferred', { error: safeError(error) }),
104
+ });
105
+ this.scheduleFlush();
42
106
  return response.retryAfterMs ?? 0;
43
107
  }
44
108
  async run(signal) {
45
109
  let attempt = 0;
46
- await this.refreshHostState();
47
- while (!signal.aborted) {
110
+ const abort = () => { this.shuttingDown = true; };
111
+ signal.addEventListener('abort', abort, { once: true });
112
+ if (signal.aborted)
113
+ abort();
114
+ try {
115
+ if (signal.aborted)
116
+ return;
117
+ await this.refreshHostState();
118
+ this.hostHeartbeat.start(signal, error => this.logger.warn('host heartbeat deferred', { error: safeError(error) }));
119
+ while (!signal.aborted) {
120
+ try {
121
+ if (Date.now() >= this.nextCapabilityRefreshAt)
122
+ this.scheduleCapabilityRefresh();
123
+ if (this.hostHeartbeat.due())
124
+ await this.hostHeartbeat.send();
125
+ const retryAfterMs = await this.pollOnce(25_000, signal);
126
+ attempt = 0;
127
+ if (retryAfterMs > 0)
128
+ await wait(retryAfterMs, undefined, { signal });
129
+ }
130
+ catch (error) {
131
+ if (signal.aborted)
132
+ break;
133
+ const delay = nextReconnectDelay(attempt++);
134
+ this.logger.warn('agent host poll failed', { error: safeError(error), delay });
135
+ await wait(delay, undefined, { signal }).catch(() => undefined);
136
+ }
137
+ }
138
+ }
139
+ finally {
140
+ this.shuttingDown = true;
141
+ const heartbeatStopped = this.hostHeartbeat.stop();
48
142
  try {
49
- if (Date.now() - this.lastHeartbeatAt >= 30_000)
50
- await this.heartbeat();
51
- const retryAfterMs = await this.pollOnce(25_000, signal);
52
- attempt = 0;
53
- if (retryAfterMs > 0)
54
- await abortableDelay(retryAfterMs, signal);
143
+ await quiesceHostRuns({ sessions: this.sessions.values(), prompts: this.prompts, streams: this.streams.values(), drives: this.drives.values() });
144
+ await heartbeatStopped;
145
+ await this.capabilityRefresh;
146
+ this.stopBackgroundUploads();
147
+ await this.flushing?.catch(error => this.logger.warn('queued events retained during shutdown', { error: safeError(error) }));
148
+ this.shutdownDrained = true;
55
149
  }
56
- catch (error) {
57
- if (signal.aborted)
58
- break;
59
- const delay = nextReconnectDelay(attempt++);
60
- this.logger.warn('agent host poll failed', { error: safeError(error), delay });
61
- await abortableDelay(delay, signal);
150
+ finally {
151
+ this.stopBackgroundUploads();
152
+ await heartbeatStopped;
153
+ signal.removeEventListener('abort', abort);
62
154
  }
63
155
  }
64
156
  }
65
157
  async refreshHostState() {
66
158
  if (this.options.controlPlane.updateCapabilities) {
67
- await this.options.controlPlane.updateCapabilities({
68
- protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
69
- ...(this.options.durableLifecycle ? { remoteLifecycleVersion: 2 } : {}),
70
- hostVersion: '0.3.11',
71
- platform: `${platform()} ${release()}`,
72
- adapters: (await this.discoverCapabilities()).map((capability) => {
73
- if (this.options.durableLifecycle)
74
- return capability;
75
- const { recovery, ...legacy } = capability;
76
- void recovery;
77
- return legacy;
78
- }),
79
- filesystem: this.options.filesystem,
80
- maxConcurrentRuns: Math.max(1, this.adapters.size),
159
+ const capabilities = buildHostCapabilities(await this.discoverCapabilities(), {
160
+ durableLifecycle: this.options.durableLifecycle === true, drive: Boolean(this.options.drive),
161
+ hostVersion: '0.4.2', filesystem: this.options.filesystem, maxConcurrentRuns: this.adapters.size,
81
162
  });
163
+ await updateHostCapabilities(this.options.controlPlane, capabilities);
82
164
  }
83
- await this.heartbeat();
165
+ const missingCloudCatalog = this.options.fetchRunCredentials && [...this.adapters.values()].some(adapter => !adapter.capability.options);
166
+ this.nextCapabilityRefreshAt = Date.now() + (missingCloudCatalog ? 60_000 : 24 * 60 * 60_000);
167
+ await this.hostHeartbeat.send();
168
+ }
169
+ scheduleCapabilityRefresh() {
170
+ if (this.capabilityRefresh || this.uploadsStopped || this.shuttingDown)
171
+ return;
172
+ this.capabilityRefresh = this.refreshHostState().catch(error => {
173
+ this.nextCapabilityRefreshAt = Date.now() + 60_000;
174
+ this.logger.warn('adapter options refresh deferred', { error: safeError(error) });
175
+ }).finally(() => { this.capabilityRefresh = undefined; });
84
176
  }
85
177
  async heartbeat() {
86
178
  await this.options.controlPlane.heartbeat?.();
87
- this.lastHeartbeatAt = Date.now();
88
179
  if (this.options.durableLifecycle)
89
- for (const [runId, session] of this.sessions) {
90
- const execution = this.executions.get(runId);
91
- if (!execution || this.terminalRuns.has(runId))
92
- continue;
93
- await this.emit(runId, { type: 'process_observation', payload: { process: await session.observe?.() ?? 'unknown' } }, execution);
94
- }
180
+ await observeActiveNativeRuns(this.sessions, this.executions, this.terminalRuns, (runId, process, execution) => this.emit(runId, { type: 'process_observation', payload: { process } }, execution));
95
181
  }
96
- async processCommand(command) {
97
- if (command.environmentId !== this.options.environmentId || command.workspaceId !== this.options.workspaceId) {
98
- throw new Error('command scope does not match this host');
99
- }
100
- const processed = this.options.state.getProcessedCommand(command.commandId);
101
- if (processed) {
102
- await this.acknowledge(command, processed.accepted, processed.errorMessage, processed.errorCode);
103
- return;
104
- }
105
- const cursor = this.options.state.commandCursor();
106
- if (cursor === 0 && command.sequence > 1) {
107
- this.options.state.adoptCommandCursor(command.sequence - 1);
108
- }
109
- const expectedSequence = this.options.state.commandCursor() + 1;
110
- if (command.sequence !== expectedSequence) {
111
- // The server attests which skipped numbers are already resolved; a hole it reports as
112
- // resolved is safe to jump over instead of wedging the whole command stream behind it.
113
- if (command.sequence > expectedSequence && command.sequence - 1 <= this.resolvedThroughSequence) {
114
- this.options.state.resumeCommandCursor(command.sequence - 1);
115
- }
116
- else {
117
- await this.acknowledge(command, false, `expected command sequence ${expectedSequence}`, 'command_sequence_gap');
118
- throw new Error(`expected command sequence ${expectedSequence}, received ${command.sequence}`);
119
- }
120
- }
121
- if (!this.options.state.claimCommand(command.commandId)) {
122
- const message = 'The previous command outcome is unknown; inspect the current execution instead of replaying it.';
123
- this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: false, errorCode: 'command_outcome_unknown', errorMessage: message });
124
- await this.acknowledge(command, false, message, 'command_outcome_unknown');
125
- return;
182
+ async processCommand(command, preparationSignal) {
183
+ const execute = () => processHostCommand({ command, state: this.options.state, environmentId: this.options.environmentId,
184
+ workspaceId: this.options.workspaceId, errorMessage: safeError, shuttingDown: this.shuttingDown, resolvedThroughSequence: this.resolvedThroughSequence,
185
+ dispatch: command => this.dispatch(command, preparationSignal), acknowledge: (command, accepted, message, code) => this.acknowledge(command, accepted, message, code) });
186
+ if (command.type !== 'start' || !command.payload.restore || !command.execution)
187
+ return execute();
188
+ const fingerprint = nativePreparationFingerprint(command), active = this.nativePreparations.get(command.commandId);
189
+ if (active) {
190
+ if (active.fingerprint !== fingerprint)
191
+ throw Error('Native preparation command changed during startup');
192
+ return active.work;
126
193
  }
194
+ const work = Promise.resolve().then(execute);
195
+ this.nativePreparations.set(command.commandId, { fingerprint, work });
127
196
  try {
128
- await this.dispatch(command);
129
- this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: true });
197
+ await work;
130
198
  }
131
- catch (error) {
132
- const message = safeError(error);
133
- this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: false, errorCode: 'command_rejected', errorMessage: message });
134
- await this.acknowledge(command, false, message, 'command_rejected');
135
- throw error;
199
+ finally {
200
+ this.nativePreparations.delete(command.commandId);
136
201
  }
137
- await this.acknowledge(command, true);
138
202
  }
139
203
  async uploadArtifact(runId, input) {
140
204
  const controlPlane = this.options.controlPlane;
@@ -158,25 +222,37 @@ export class AgentHostRuntime {
158
222
  }
159
223
  async flushOutboxInternal() {
160
224
  for (;;) {
161
- const events = this.options.state.pendingEvents(100);
225
+ if (this.shuttingDown && this.uploadsStopped)
226
+ return;
227
+ const events = this.options.state.pendingUploadEvents(100);
162
228
  if (events.length === 0)
163
229
  return;
164
- const batch = eventBatchSchema.parse({
165
- protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
166
- environmentId: this.options.environmentId,
167
- runId: events[0].runId,
168
- events,
169
- });
230
+ const packed = packEventBatch(this.options.environmentId, events);
231
+ if (!packed.batch) {
232
+ // One event larger than any upload: shrink it once, in place, so the stream keeps moving.
233
+ const shrunk = packed.oversized && shrinkOversizedEvent(packed.oversized);
234
+ if (!shrunk)
235
+ throw new Error(`event ${packed.oversized?.sourceSequence} cannot fit in an upload`);
236
+ this.options.state.replaceQueuedEvent(shrunk);
237
+ this.logger.warn('shortened an oversized text checkpoint', { runId: shrunk.runId, sequence: shrunk.sourceSequence });
238
+ continue;
239
+ }
240
+ const batch = eventBatchSchema.parse(packed.batch);
241
+ const stream = streamKey(batch.runId, batch.events[0].execution?.attemptId);
242
+ this.inFlight.set(stream, batch.events.at(-1).sourceSequence);
243
+ this.options.state.markUploadAttempt(batch.events);
170
244
  // Sequential on purpose: batches carry ordered sequences; the next
171
245
  // iteration reads pendingEvents after this batch is acknowledged.
172
246
  // react-doctor-disable-next-line react-doctor/async-await-in-loop
173
- const acknowledgement = await this.options.controlPlane.uploadEvents(batch);
247
+ const acknowledgement = await this.options.controlPlane.uploadEvents(batch).finally(() => this.inFlight.delete(stream));
174
248
  if (acknowledgement.accepted) {
175
249
  const lastSentSequence = batch.events.at(-1).sourceSequence;
176
- if (acknowledgement.acknowledgedSequence !== lastSentSequence) {
250
+ const attempted = this.options.state.uploadAttemptWatermark(batch.runId, batch.events[0].execution?.attemptId);
251
+ if (acknowledgement.acknowledgedSequence < lastSentSequence || acknowledgement.acknowledgedSequence > attempted) {
177
252
  throw new Error(`server acknowledged ${acknowledgement.acknowledgedSequence}, expected ${lastSentSequence}`);
178
253
  }
179
254
  this.options.state.acknowledgeEvents(batch.runId, acknowledgement.acknowledgedSequence, batch.events[0].execution?.attemptId);
255
+ this.outboxReceipts.record(acknowledgement);
180
256
  continue;
181
257
  }
182
258
  const lastSentSequence = batch.events.at(-1).sourceSequence;
@@ -187,7 +263,7 @@ export class AgentHostRuntime {
187
263
  throw new Error(`server requested unavailable event sequence ${acknowledgement.expectedSequence}`);
188
264
  }
189
265
  }
190
- async dispatch(command) {
266
+ async dispatch(command, preparationSignal) {
191
267
  this.acceptExecutionFence(command);
192
268
  if (command.type === 'observe') {
193
269
  const session = this.sessions.get(command.runId);
@@ -195,13 +271,15 @@ export class AgentHostRuntime {
195
271
  return;
196
272
  }
197
273
  if (command.type === 'start') {
198
- await this.startSession(command);
274
+ await this.startSession(command, preparationSignal);
199
275
  return;
200
276
  }
201
277
  if (command.type === 'shutdown') {
202
278
  const session = this.sessions.get(command.runId);
203
279
  if (session)
204
280
  await session.stop(command.payload.reason);
281
+ await this.drives.get(command.runId)?.closeAfterStopped();
282
+ this.drives.delete(command.runId);
205
283
  this.sessions.delete(command.runId);
206
284
  return;
207
285
  }
@@ -211,8 +289,10 @@ export class AgentHostRuntime {
211
289
  return;
212
290
  }
213
291
  const session = await this.requireSession(command.runId, command.type === 'reconnect' ? command.payload.remoteSessionId : undefined);
214
- if (command.type === 'prompt')
215
- await session.prompt(command.payload.prompt);
292
+ if (command.type === 'prompt') {
293
+ const report = this.failureReporter(command.runId);
294
+ this.prompts.track(session.prompt(command.payload.prompt).catch(error => report({ type: 'failed', payload: { code: 'adapter_prompt_failed', message: safeError(error), retryable: true } })));
295
+ }
216
296
  else if (command.type === 'approval_response')
217
297
  await session.approve(command.payload.requestKey, command.payload.optionId);
218
298
  else if (command.type === 'elicitation_response')
@@ -225,7 +305,7 @@ export class AgentHostRuntime {
225
305
  const process = await session.observe?.() ?? 'unknown';
226
306
  await this.emit(command.runId, { type: 'process_observation', payload: { process, recoveryOutcome: process === 'live' ? 'attached_live' : 'unavailable' } });
227
307
  if (process === 'live')
228
- void session.resume().catch(error => this.emit(command.runId, { type: 'failed', payload: { code: 'native_stream_unavailable', message: safeError(error), retryable: true } }));
308
+ this.prompts.track(session.resume().catch(error => this.emit(command.runId, { type: 'failed', payload: { code: 'native_stream_unavailable', message: safeError(error), retryable: true } })));
229
309
  return;
230
310
  }
231
311
  await session.resume();
@@ -242,63 +322,119 @@ export class AgentHostRuntime {
242
322
  // attempt was replaced): they cannot start a writer, so they bypass the fence.
243
323
  if (command.type === 'shutdown')
244
324
  return;
325
+ const restoring = command.type === 'start' && command.payload.restore;
326
+ if (restoring && command.type === 'start') {
327
+ if (this.sessions.has(command.runId))
328
+ throw Error('Cannot restore over a live session');
329
+ requireNativeRestorationSource(command, this.options.state.getSession(command.runId));
330
+ }
245
331
  const previous = this.executions.get(command.runId) ?? this.options.state.getSession(command.runId)?.execution;
246
332
  const replacesPrevious = previous && (previous.attemptId !== command.execution.attemptId || previous.generation !== command.execution.generation);
247
333
  // The server only emits `fresh` on an explicit start_fresh: that user action is the
248
334
  // proof-of-intent that authorizes replacing a persisted execution whose writer state
249
335
  // is unknown (e.g. this host restarted while a detached adapter child was running).
250
- if (replacesPrevious && !(command.type === 'start' && command.payload.fresh === true))
336
+ if (replacesPrevious && !restoring && !(command.type === 'start' && command.payload.fresh === true))
251
337
  throw new Error('execution replacement requires proof that the old writer stopped');
252
338
  this.executions.set(command.runId, { ...command.execution, hostBootId: this.bootId });
253
339
  if (replacesPrevious)
254
340
  this.terminalRuns.delete(command.runId);
255
341
  }
256
- async startSession(command) {
257
- if (command.payload.fresh) {
258
- // An explicit start_fresh authorizes teardown even when the persisted session is
259
- // not live here: the old process may be an orphan, and refusing would leave the
260
- // run unrecoverable.
261
- await this.sessions.get(command.runId)?.stop('Starting a fresh session');
262
- this.sessions.delete(command.runId);
263
- this.options.state.deleteSession(command.runId);
264
- this.options.state.deleteAdapterSessionState(command.runId);
265
- }
266
- else if (this.sessions.has(command.runId))
267
- return;
268
- else if (this.options.state.getSession(command.runId)) {
269
- // A crash after the external write but before the local ack leaves an unknown outcome.
270
- // Do not create another process or re-prompt it merely because delivery was repeated.
271
- throw new Error('persisted execution exists; observe or inspect its outcome before starting again');
272
- }
273
- if (command.execution && !this.options.state.claimExecution(command.runId, command.execution.attemptId))
274
- throw new Error('execution start outcome is unknown; inspect the existing process before continuing');
342
+ async startSession(command, preparationSignal) {
343
+ const execution = this.executions.get(command.runId);
344
+ return withRunPreparation({
345
+ enabled: Boolean(this.options.durableLifecycle && command.execution && command.payload.metadata.overlayPreparation === 1),
346
+ active: () => !this.shuttingDown && !preparationSignal?.aborted,
347
+ emit: () => this.emit(command.runId, { type: 'session_preparing', payload: {} }, execution),
348
+ onError: error => this.logger.warn('run preparation heartbeat deferred', { runId: command.runId, error: safeError(error) }),
349
+ }, () => this.initializeSession(command, preparationSignal));
350
+ }
351
+ async initializeSession(command, preparationSignal) {
352
+ preparationSignal?.throwIfAborted();
275
353
  const adapter = this.requireAdapter(command.payload.adapterId);
276
- const scope = await resolveFilesystemScope(this.options.filesystem, command.payload.workingDirectory);
277
- const credentials = await this.runCredentials(command.runId, command.payload.metadata.runCredentials === true);
354
+ const admission = await admitHostSession({ command, adapter, state: this.options.state, sessions: this.sessions });
355
+ if (admission.kind === 'already-active')
356
+ return;
357
+ const { settings, offset, restored } = admission;
358
+ let canonicalOffset = offset;
359
+ const credentials = await this.runCredentials(command.runId, command.payload.metadata.runCredentials === true, Boolean(restored));
278
360
  if (credentials === 'unavailable')
279
361
  return;
362
+ preparationSignal?.throwIfAborted();
363
+ const drive = await prepareRuntimeDrive(this.options, command, this.executions.get(command.runId));
364
+ const scope = drive ? { workingDirectory: drive.workingDirectory, additionalDirectories: drive.additionalDirectories }
365
+ : await resolveFilesystemScope(this.options.filesystem, command.payload.workingDirectory);
366
+ if (restored && scope.workingDirectory !== restored.workingDirectory) {
367
+ await drive?.close();
368
+ throw Error('Native restoration cannot change its original working directory');
369
+ }
370
+ if (this.shuttingDown || preparationSignal?.aborted) {
371
+ await drive?.close();
372
+ preparationSignal?.throwIfAborted();
373
+ throw Error('Host stopped before provider start');
374
+ }
375
+ if (restored && command.execution) {
376
+ try {
377
+ if (command.payload.metadata.overlayNativeAdmission === 1)
378
+ await drainNativeSource({ command, state: this.options.state,
379
+ receipts: this.outboxReceipts, flush: () => this.flushOutbox(), signal: preparationSignal });
380
+ preparationSignal?.throwIfAborted();
381
+ this.options.state.enterNativeProviderStart({ commandId: command.commandId, fingerprint: nativePreparationFingerprint(command),
382
+ previous: restored, nextExecution: { ...command.execution, hostBootId: this.bootId } });
383
+ if (command.payload.metadata.overlayNativeAdmission === 1)
384
+ canonicalOffset = await requestNativeStart({ command,
385
+ state: this.options.state, hostBootId: this.bootId, receipts: this.outboxReceipts,
386
+ emit: event => this.emit(command.runId, event), flush: () => this.flushOutbox(), signal: preparationSignal });
387
+ }
388
+ catch (error) {
389
+ await drive?.close();
390
+ throw error;
391
+ }
392
+ }
393
+ if (this.shuttingDown || preparationSignal?.aborted) {
394
+ await drive?.close();
395
+ preparationSignal?.throwIfAborted();
396
+ throw Error('Host stopped before provider start');
397
+ }
280
398
  // Bind callbacks before adapter code can emit, including during old-session teardown.
281
399
  const execution = this.executions.get(command.runId);
282
- const emit = (event) => this.emit(command.runId, event, execution);
283
- const session = await adapter.start({
284
- runId: command.runId,
285
- workingDirectory: scope.workingDirectory,
286
- additionalDirectories: scope.additionalDirectories,
287
- prompt: command.payload.prompt,
288
- ...(command.payload.sessionId ? { remoteSessionId: command.payload.sessionId } : {}),
289
- metadata: command.payload.metadata,
290
- ...(credentials ? { credentials } : {}),
291
- adapterState: this.options.state.getAdapterSessionState(command.runId, command.payload.adapterId),
292
- persistAdapterState: (state) => this.options.state.saveAdapterSessionState(command.runId, command.payload.adapterId, state),
293
- }, emit);
400
+ const emit = this.createStream(command.runId, execution, drive, canonicalOffset);
401
+ let session;
402
+ try {
403
+ session = await adapter.start({
404
+ onNativeTurnEnded: createNativeTerminalIntent({ execution, currentExecution: () => this.executions.get(command.runId),
405
+ shuttingDown: () => this.shuttingDown, markEnded: () => { this.terminalRuns.add(command.runId); } }),
406
+ runId: command.runId,
407
+ workingDirectory: scope.workingDirectory,
408
+ additionalDirectories: scope.additionalDirectories,
409
+ prompt: command.payload.prompt,
410
+ ...(command.payload.sessionId ? { remoteSessionId: command.payload.sessionId } : {}),
411
+ metadata: command.payload.metadata,
412
+ ...(credentials ? { credentials } : {}),
413
+ adapterState: this.options.state.getAdapterSessionState(command.runId, command.payload.adapterId),
414
+ persistAdapterState: (state) => this.options.state.saveAdapterSessionState(command.runId, command.payload.adapterId, state),
415
+ }, emit);
416
+ }
417
+ catch (error) {
418
+ if (error instanceof AdapterStartError && error.termination === 'confirmed') {
419
+ await this.drives.get(command.runId)?.closeAfterStopped();
420
+ this.drives.delete(command.runId);
421
+ this.streams.get(command.runId)?.stop();
422
+ this.streams.delete(command.runId);
423
+ }
424
+ else
425
+ this.drives.get(command.runId)?.retainUncertainStartup();
426
+ throw error;
427
+ }
294
428
  this.sessions.set(command.runId, session);
429
+ this.scheduleCapabilityRefresh();
295
430
  this.options.state.saveSession({ runId: command.runId, adapterId: command.payload.adapterId, remoteSessionId: session.remoteSessionId, workingDirectory: scope.workingDirectory,
296
- config: { version: 1, configReference: command.payload.bindingId, toolsReference: command.runId, ...(typeof command.payload.metadata.model === 'string' ? { model: command.payload.metadata.model } : {}) },
431
+ config: { version: 1, configReference: command.payload.bindingId, toolsReference: command.runId, ...settings },
297
432
  ...(command.execution ? { execution: { ...command.execution, hostBootId: this.bootId } } : {}),
298
433
  });
299
- await this.emit(command.runId, { type: 'session_started', payload: { remoteSessionId: session.remoteSessionId, adapterId: command.payload.adapterId } });
300
- if (!session.initialPromptHandled) {
301
- void session.prompt(command.payload.prompt).catch((error) => emit({ type: 'failed', payload: { code: 'adapter_prompt_failed', message: safeError(error), retryable: true } }));
434
+ await this.emit(command.runId, { type: 'session_started', payload: { remoteSessionId: session.remoteSessionId, adapterId: command.payload.adapterId,
435
+ ...(restored ? { restorationCommandId: command.commandId } : {}) } });
436
+ if (!this.shuttingDown && !preparationSignal?.aborted && !session.initialPromptHandled) {
437
+ this.prompts.track(session.prompt(command.payload.prompt).catch((error) => emit({ type: 'failed', payload: { code: 'adapter_prompt_failed', message: safeError(error), retryable: true } })));
302
438
  }
303
439
  return;
304
440
  }
@@ -323,44 +459,22 @@ export class AgentHostRuntime {
323
459
  if (credentials === 'unavailable')
324
460
  throw new Error('provider credentials are unavailable for this run');
325
461
  const session = await this.requireAdapter(stored.adapterId).start({
462
+ onNativeTurnEnded: createNativeTerminalIntent({ execution: this.executions.get(runId), currentExecution: () => this.executions.get(runId),
463
+ shuttingDown: () => this.shuttingDown, markEnded: () => { this.terminalRuns.add(runId); } }),
326
464
  runId, workingDirectory: scope.workingDirectory, additionalDirectories: scope.additionalDirectories,
327
- prompt: '', remoteSessionId: stored.remoteSessionId, metadata: { ...(stored.config?.model ? { model: stored.config.model } : {}) },
465
+ prompt: '', remoteSessionId: stored.remoteSessionId, metadata: agentSettingsSchema.parse(stored.config ?? {}),
328
466
  ...(credentials ? { credentials } : {}),
329
467
  adapterState: this.options.state.getAdapterSessionState(runId, stored.adapterId),
330
468
  persistAdapterState: (state) => this.options.state.saveAdapterSessionState(runId, stored.adapterId, state),
331
- }, (event) => this.emit(runId, event));
469
+ }, this.createStream(runId));
332
470
  this.sessions.set(runId, session);
471
+ this.scheduleCapabilityRefresh();
333
472
  return session;
334
473
  }
335
- /**
336
- * The provider credentials for a run. `undefined` means the run uses none
337
- * (no account bound, or this host does not fetch them); 'unavailable' means
338
- * the run cannot start, and the failure has already been reported.
339
- */
340
- async runCredentials(runId, requested) {
341
- const fetchCredentials = this.options.controlPlane.fetchRunCredentials?.bind(this.options.controlPlane);
342
- // Only a host holding the run-credentials method (Overlay Cloud) asks, and only when the run says it has an account.
343
- if (!fetchCredentials || !this.options.fetchRunCredentials || !requested)
344
- return undefined;
345
- try {
346
- return await fetchCredentials(runId);
347
- }
348
- catch (error) {
349
- const code = error instanceof ControlPlaneRequestError ? error.code : undefined;
350
- // No account on this binding: nothing to inject, the run proceeds as configured.
351
- if (code === 'provider_account_missing')
352
- return undefined;
353
- const needsSignIn = code === 'account_needs_reauth' || code === 'account_unavailable';
354
- await this.emit(runId, { type: 'failed', payload: {
355
- code: needsSignIn ? 'auth_required' : 'credentials_unavailable',
356
- message: needsSignIn
357
- ? 'This agent’s account needs to be reconnected in Settings → Agent accounts.'
358
- : 'The agent could not get its credentials. Try again.',
359
- retryable: !needsSignIn,
360
- } });
361
- this.logger.warn('run credentials unavailable', { runId, code: code ?? 'unknown' });
362
- return 'unavailable';
363
- }
474
+ runCredentials(runId, requested, retryPreparation = false) {
475
+ const execution = this.executions.get(runId);
476
+ return fetchProviderRunCredentials({ runId, requested: Boolean(this.options.fetchRunCredentials && requested),
477
+ retryPreparation, client: this.options.controlPlane, emit: event => this.emit(runId, event, execution), logger: this.logger });
364
478
  }
365
479
  requireAdapter(adapterId) {
366
480
  const adapter = this.adapters.get(adapterId);
@@ -368,27 +482,90 @@ export class AgentHostRuntime {
368
482
  throw new Error(`adapter is not installed: ${adapterId}`);
369
483
  return adapter;
370
484
  }
485
+ failureReporter(runId, execution = this.executions.get(runId)) {
486
+ return this.drives.get(runId)?.emit ?? this.streams.get(runId)?.emit
487
+ ?? (event => this.emit(runId, event, execution));
488
+ }
489
+ createStream(runId, execution = this.executions.get(runId), drive, textBaseOffset) {
490
+ this.streams.get(runId)?.stop();
491
+ const negotiated = this.streamingNegotiated;
492
+ const stream = createRunStream(event => this.emit(runId, event, execution), {
493
+ streaming: () => negotiated,
494
+ textBaseOffset,
495
+ active: () => this.sessions.has(runId) && !this.terminalRuns.has(runId),
496
+ observe: async () => await this.sessions.get(runId)?.observe?.() ?? 'unknown',
497
+ onError: error => this.logger.warn('run heartbeat deferred', { runId, error: safeError(error) }),
498
+ });
499
+ this.streams.set(runId, stream);
500
+ const forward = withNativeTerminalBoundary({ forward: stream.emit, execution,
501
+ currentExecution: () => this.executions.get(runId), shuttingDown: () => this.shuttingDown,
502
+ markEnded: () => { this.terminalRuns.add(runId); } });
503
+ if (!drive)
504
+ return forward;
505
+ const controller = new RuntimeDriveController(drive, forward, async () => {
506
+ const session = this.sessions.get(runId);
507
+ if (!session)
508
+ throw Error('Native startup termination is unconfirmed');
509
+ await session.stop('Confirming failed native writer termination');
510
+ }, this.options.drive?.syncIntervalMs);
511
+ this.drives.set(runId, controller);
512
+ return controller.emit;
513
+ }
514
+ /**
515
+ * Records an event and returns once it is durable on disk. Uploading happens in the background: an adapter that
516
+ * reports progress never waits on the network, so slow or failing uploads cannot hold back the agent's own output.
517
+ */
371
518
  async emit(runId, event, execution = this.executions.get(runId)) {
372
- if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
373
- throw new Error('event outbox backpressure limit reached');
374
- }
519
+ if (this.shuttingDown && ['completed', 'failed', 'cancelled'].includes(event.type))
520
+ return;
375
521
  const stored = {
376
522
  protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
377
523
  ...(execution ? { execution } : {}),
378
524
  eventId: randomUUID(), environmentId: this.options.environmentId, runId,
379
525
  occurredAt: Date.now(), ...event,
380
526
  };
381
- this.options.state.appendEvent(stored);
527
+ this.options.state.appendOrReplaceTextCheckpoint(stored, this.inFlight.get(streamKey(runId, execution?.attemptId)) ?? 0);
382
528
  const currentExecution = this.executions.get(runId);
383
529
  if (this.options.durableLifecycle && execution?.attemptId === currentExecution?.attemptId
384
530
  && execution?.generation === currentExecution?.generation && ['completed', 'cancelled', 'failed'].includes(event.type))
385
531
  this.terminalRuns.add(runId);
386
- try {
387
- await this.flushOutbox();
388
- }
389
- catch (error) {
390
- this.logger.warn('event upload deferred', { runId, error: safeError(error) });
391
- }
532
+ this.scheduleFlush();
533
+ }
534
+ /** Stops background upload passes, e.g. when the host shuts down; queued events stay on disk for next start. */
535
+ stopBackgroundUploads() {
536
+ this.uploadsStopped = true;
537
+ for (const stream of this.streams.values())
538
+ stream.stop();
539
+ for (const drive of this.drives.values())
540
+ drive.stopScheduling();
541
+ if (this.flushRetry)
542
+ clearTimeout(this.flushRetry);
543
+ this.flushRetry = undefined;
544
+ }
545
+ /** Starts an upload pass unless one is running (it drains new events too); retries failures with backoff. */
546
+ scheduleFlush() {
547
+ if (this.uploadsStopped || this.flushing || this.flushRetry)
548
+ return;
549
+ void this.flushOutbox().then(() => {
550
+ this.flushFailures = 0;
551
+ // An event recorded while the pass was finishing would otherwise wait for the next poll.
552
+ let queued = 0;
553
+ try {
554
+ queued = this.options.state.outboxSize();
555
+ }
556
+ catch {
557
+ return;
558
+ } // state closed: the host is shutting down
559
+ if (queued > 0)
560
+ this.scheduleFlush();
561
+ }, (error) => {
562
+ if (this.uploadsStopped || error?.code === 'ERR_INVALID_STATE')
563
+ return;
564
+ const delay = nextReconnectDelay(this.flushFailures++);
565
+ this.logger.warn('event upload deferred', { error: safeError(error), retryInMs: delay });
566
+ this.flushRetry = setTimeout(() => { this.flushRetry = undefined; this.scheduleFlush(); }, delay);
567
+ this.flushRetry.unref?.();
568
+ });
392
569
  }
393
570
  acknowledge(command, accepted, message, errorCode = 'command_rejected') {
394
571
  return this.options.controlPlane.acknowledgeCommand({
@@ -401,10 +578,5 @@ export class AgentHostRuntime {
401
578
  }
402
579
  }
403
580
  function safeError(error) { return error instanceof Error ? error.message.slice(0, 2_000) : 'Unknown host error'; }
404
- function abortableDelay(milliseconds, signal) {
405
- return new Promise((resolve, reject) => {
406
- const timer = setTimeout(resolve, milliseconds);
407
- signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
408
- });
409
- }
581
+ function streamKey(runId, attemptId) { return `${runId}\u0000${attemptId ?? ''}`; }
410
582
  //# sourceMappingURL=runtime.js.map