@layernorm/overlay-agent-host 0.3.10 → 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 (200) hide show
  1. package/README.md +20 -0
  2. package/dist/acp-adapter.d.ts +52 -13
  3. package/dist/acp-adapter.d.ts.map +1 -1
  4. package/dist/acp-adapter.js +193 -27
  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 +47 -15
  11. package/dist/acpx-adapter.d.ts.map +1 -1
  12. package/dist/acpx-adapter.js +158 -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 +13 -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 -79
  35. package/dist/cli.js.map +1 -1
  36. package/dist/config.d.ts +126 -10
  37. package/dist/config.d.ts.map +1 -1
  38. package/dist/config.js +19 -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.d.ts +1 -0
  78. package/dist/enrollment.d.ts.map +1 -1
  79. package/dist/enrollment.js +9 -2
  80. package/dist/enrollment.js.map +1 -1
  81. package/dist/eve-adapter.d.ts +15 -1
  82. package/dist/eve-adapter.d.ts.map +1 -1
  83. package/dist/eve-adapter.js +9 -0
  84. package/dist/eve-adapter.js.map +1 -1
  85. package/dist/fake-adapter.d.ts +14 -0
  86. package/dist/fake-adapter.d.ts.map +1 -1
  87. package/dist/fake-adapter.js +2 -0
  88. package/dist/fake-adapter.js.map +1 -1
  89. package/dist/host-capabilities.d.ts +12 -0
  90. package/dist/host-capabilities.d.ts.map +1 -0
  91. package/dist/host-capabilities.js +70 -0
  92. package/dist/host-capabilities.js.map +1 -0
  93. package/dist/host-heartbeat.d.ts +14 -0
  94. package/dist/host-heartbeat.d.ts.map +1 -0
  95. package/dist/host-heartbeat.js +41 -0
  96. package/dist/host-heartbeat.js.map +1 -0
  97. package/dist/image-check.d.ts +1 -1
  98. package/dist/image-check.js +4 -4
  99. package/dist/image-check.js.map +1 -1
  100. package/dist/native-restoration.d.ts +7 -0
  101. package/dist/native-restoration.d.ts.map +1 -0
  102. package/dist/native-restoration.js +21 -0
  103. package/dist/native-restoration.js.map +1 -0
  104. package/dist/native-start-barrier.d.ts +27 -0
  105. package/dist/native-start-barrier.d.ts.map +1 -0
  106. package/dist/native-start-barrier.js +28 -0
  107. package/dist/native-start-barrier.js.map +1 -0
  108. package/dist/native-start-preparation.d.ts +6 -0
  109. package/dist/native-start-preparation.d.ts.map +1 -0
  110. package/dist/native-start-preparation.js +23 -0
  111. package/dist/native-start-preparation.js.map +1 -0
  112. package/dist/ordered-acp-updates.d.ts +11 -0
  113. package/dist/ordered-acp-updates.d.ts.map +1 -0
  114. package/dist/ordered-acp-updates.js +38 -0
  115. package/dist/ordered-acp-updates.js.map +1 -0
  116. package/dist/outbox-packing.d.ts +22 -0
  117. package/dist/outbox-packing.d.ts.map +1 -0
  118. package/dist/outbox-packing.js +51 -0
  119. package/dist/outbox-packing.js.map +1 -0
  120. package/dist/outbox-receipts.d.ts +20 -0
  121. package/dist/outbox-receipts.d.ts.map +1 -0
  122. package/dist/outbox-receipts.js +44 -0
  123. package/dist/outbox-receipts.js.map +1 -0
  124. package/dist/preparation-command-polling.d.ts +13 -0
  125. package/dist/preparation-command-polling.d.ts.map +1 -0
  126. package/dist/preparation-command-polling.js +62 -0
  127. package/dist/preparation-command-polling.js.map +1 -0
  128. package/dist/preparation-failure.d.ts +2 -0
  129. package/dist/preparation-failure.d.ts.map +1 -0
  130. package/dist/preparation-failure.js +19 -0
  131. package/dist/preparation-failure.js.map +1 -0
  132. package/dist/preview-hosting-access.d.ts +18 -0
  133. package/dist/preview-hosting-access.d.ts.map +1 -0
  134. package/dist/preview-hosting-access.js +48 -0
  135. package/dist/preview-hosting-access.js.map +1 -0
  136. package/dist/preview-hosting.d.ts +8 -0
  137. package/dist/preview-hosting.d.ts.map +1 -0
  138. package/dist/preview-hosting.js +19 -0
  139. package/dist/preview-hosting.js.map +1 -0
  140. package/dist/preview-mcp-relay.d.ts +8 -0
  141. package/dist/preview-mcp-relay.d.ts.map +1 -0
  142. package/dist/preview-mcp-relay.js +127 -0
  143. package/dist/preview-mcp-relay.js.map +1 -0
  144. package/dist/process-group.d.ts +4 -0
  145. package/dist/process-group.d.ts.map +1 -0
  146. package/dist/process-group.js +38 -0
  147. package/dist/process-group.js.map +1 -0
  148. package/dist/process-host-command.d.ts +14 -0
  149. package/dist/process-host-command.d.ts.map +1 -0
  150. package/dist/process-host-command.js +55 -0
  151. package/dist/process-host-command.js.map +1 -0
  152. package/dist/provider-run-credentials.d.ts +13 -0
  153. package/dist/provider-run-credentials.d.ts.map +1 -0
  154. package/dist/provider-run-credentials.js +27 -0
  155. package/dist/provider-run-credentials.js.map +1 -0
  156. package/dist/run-preparation.d.ts +9 -0
  157. package/dist/run-preparation.d.ts.map +1 -0
  158. package/dist/run-preparation.js +21 -0
  159. package/dist/run-preparation.js.map +1 -0
  160. package/dist/run-stream.d.ts +20 -0
  161. package/dist/run-stream.d.ts.map +1 -0
  162. package/dist/run-stream.js +96 -0
  163. package/dist/run-stream.js.map +1 -0
  164. package/dist/runtime-drive-controller.d.ts +26 -0
  165. package/dist/runtime-drive-controller.d.ts.map +1 -0
  166. package/dist/runtime-drive-controller.js +118 -0
  167. package/dist/runtime-drive-controller.js.map +1 -0
  168. package/dist/runtime-drive.d.ts +30 -0
  169. package/dist/runtime-drive.d.ts.map +1 -0
  170. package/dist/runtime-drive.js +151 -0
  171. package/dist/runtime-drive.js.map +1 -0
  172. package/dist/runtime-session-admission.d.ts +24 -0
  173. package/dist/runtime-session-admission.d.ts.map +1 -0
  174. package/dist/runtime-session-admission.js +46 -0
  175. package/dist/runtime-session-admission.js.map +1 -0
  176. package/dist/runtime-shutdown.d.ts +21 -0
  177. package/dist/runtime-shutdown.d.ts.map +1 -0
  178. package/dist/runtime-shutdown.js +27 -0
  179. package/dist/runtime-shutdown.js.map +1 -0
  180. package/dist/runtime-terminal-boundary.d.ts +18 -0
  181. package/dist/runtime-terminal-boundary.d.ts.map +1 -0
  182. package/dist/runtime-terminal-boundary.js +36 -0
  183. package/dist/runtime-terminal-boundary.js.map +1 -0
  184. package/dist/runtime.d.ts +86 -7
  185. package/dist/runtime.d.ts.map +1 -1
  186. package/dist/runtime.js +435 -157
  187. package/dist/runtime.js.map +1 -1
  188. package/dist/state.d.ts +43 -2
  189. package/dist/state.d.ts.map +1 -1
  190. package/dist/state.js +167 -8
  191. package/dist/state.js.map +1 -1
  192. package/dist/text-coalescer.d.ts +16 -0
  193. package/dist/text-coalescer.d.ts.map +1 -0
  194. package/dist/text-coalescer.js +55 -0
  195. package/dist/text-coalescer.js.map +1 -0
  196. package/dist/transport.d.ts +17 -11
  197. package/dist/transport.d.ts.map +1 -1
  198. package/dist/transport.js +48 -5
  199. package/dist/transport.js.map +1 -1
  200. package/package.json +2 -2
package/dist/runtime.js CHANGED
@@ -1,107 +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;
13
- lastHeartbeatAt = 0;
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();
43
+ terminalRuns = new Set();
44
+ hostHeartbeat;
45
+ nextCapabilityRefreshAt = 0;
46
+ capabilityRefresh;
47
+ bootId = randomUUID();
48
+ executions = new Map();
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; }
14
55
  constructor(options) {
15
56
  this.options = options;
16
57
  this.adapters = new Map(options.adapters.map((adapter) => [adapter.capability.id, adapter]));
17
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);
18
63
  }
19
64
  async discoverCapabilities() {
20
- 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
+ }));
21
84
  }
22
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.
23
87
  if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
24
- await this.flushOutbox();
25
- if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000))
26
- 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
+ }
27
93
  }
28
94
  const response = await this.options.controlPlane.pollCommands({ waitMs, ...(signal ? { signal } : {}) });
29
- // Sequential on purpose: commands arrive ordered and may build on each
30
- // other (e.g. stop after start), so they must be processed in order.
31
- for (const command of response.commands) {
32
- // react-doctor-disable-next-line react-doctor/async-await-in-loop
33
- await this.processCommand(command);
34
- }
35
- await this.flushOutbox();
95
+ this.streamingNegotiated = response.streaming?.textDeltas === true && response.streaming.heartbeats === true;
96
+ if (response.resolvedThroughSequence !== undefined)
97
+ this.resolvedThroughSequence = Math.max(this.resolvedThroughSequence, response.resolvedThroughSequence);
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();
36
106
  return response.retryAfterMs ?? 0;
37
107
  }
38
108
  async run(signal) {
39
109
  let attempt = 0;
40
- await this.refreshHostState();
41
- 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();
42
142
  try {
43
- if (Date.now() - this.lastHeartbeatAt >= 30_000)
44
- await this.heartbeat();
45
- const retryAfterMs = await this.pollOnce(25_000, signal);
46
- attempt = 0;
47
- if (retryAfterMs > 0)
48
- 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;
49
149
  }
50
- catch (error) {
51
- if (signal.aborted)
52
- break;
53
- const delay = nextReconnectDelay(attempt++);
54
- this.logger.warn('agent host poll failed', { error: safeError(error), delay });
55
- await abortableDelay(delay, signal);
150
+ finally {
151
+ this.stopBackgroundUploads();
152
+ await heartbeatStopped;
153
+ signal.removeEventListener('abort', abort);
56
154
  }
57
155
  }
58
156
  }
59
157
  async refreshHostState() {
60
158
  if (this.options.controlPlane.updateCapabilities) {
61
- await this.options.controlPlane.updateCapabilities({
62
- protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
63
- hostVersion: '0.0.1',
64
- platform: `${platform()} ${release()}`,
65
- adapters: await this.discoverCapabilities(),
66
- filesystem: this.options.filesystem,
67
- 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,
68
162
  });
163
+ await updateHostCapabilities(this.options.controlPlane, capabilities);
69
164
  }
70
- 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; });
71
176
  }
72
177
  async heartbeat() {
73
178
  await this.options.controlPlane.heartbeat?.();
74
- this.lastHeartbeatAt = Date.now();
179
+ if (this.options.durableLifecycle)
180
+ await observeActiveNativeRuns(this.sessions, this.executions, this.terminalRuns, (runId, process, execution) => this.emit(runId, { type: 'process_observation', payload: { process } }, execution));
75
181
  }
76
- async processCommand(command) {
77
- if (command.environmentId !== this.options.environmentId || command.workspaceId !== this.options.workspaceId) {
78
- throw new Error('command scope does not match this host');
79
- }
80
- const processed = this.options.state.getProcessedCommand(command.commandId);
81
- if (processed) {
82
- await this.acknowledge(command, processed.accepted, processed.errorMessage, processed.errorCode);
83
- return;
84
- }
85
- const cursor = this.options.state.commandCursor();
86
- if (cursor === 0 && command.sequence > 1) {
87
- this.options.state.adoptCommandCursor(command.sequence - 1);
88
- }
89
- const expectedSequence = this.options.state.commandCursor() + 1;
90
- if (command.sequence !== expectedSequence) {
91
- await this.acknowledge(command, false, `expected command sequence ${expectedSequence}`, 'command_sequence_gap');
92
- throw new Error(`expected command sequence ${expectedSequence}, received ${command.sequence}`);
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;
93
193
  }
194
+ const work = Promise.resolve().then(execute);
195
+ this.nativePreparations.set(command.commandId, { fingerprint, work });
94
196
  try {
95
- await this.dispatch(command);
96
- this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: true });
197
+ await work;
97
198
  }
98
- catch (error) {
99
- const message = safeError(error);
100
- this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: false, errorCode: 'command_rejected', errorMessage: message });
101
- await this.acknowledge(command, false, message, 'command_rejected');
102
- throw error;
199
+ finally {
200
+ this.nativePreparations.delete(command.commandId);
103
201
  }
104
- await this.acknowledge(command, true);
105
202
  }
106
203
  async uploadArtifact(runId, input) {
107
204
  const controlPlane = this.options.controlPlane;
@@ -125,87 +222,221 @@ export class AgentHostRuntime {
125
222
  }
126
223
  async flushOutboxInternal() {
127
224
  for (;;) {
128
- const events = this.options.state.pendingEvents(100);
225
+ if (this.shuttingDown && this.uploadsStopped)
226
+ return;
227
+ const events = this.options.state.pendingUploadEvents(100);
129
228
  if (events.length === 0)
130
229
  return;
131
- const batch = eventBatchSchema.parse({
132
- protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
133
- environmentId: this.options.environmentId,
134
- runId: events[0].runId,
135
- events,
136
- });
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);
137
244
  // Sequential on purpose: batches carry ordered sequences; the next
138
245
  // iteration reads pendingEvents after this batch is acknowledged.
139
246
  // react-doctor-disable-next-line react-doctor/async-await-in-loop
140
- const acknowledgement = await this.options.controlPlane.uploadEvents(batch);
247
+ const acknowledgement = await this.options.controlPlane.uploadEvents(batch).finally(() => this.inFlight.delete(stream));
141
248
  if (acknowledgement.accepted) {
142
249
  const lastSentSequence = batch.events.at(-1).sourceSequence;
143
- 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) {
144
252
  throw new Error(`server acknowledged ${acknowledgement.acknowledgedSequence}, expected ${lastSentSequence}`);
145
253
  }
146
- this.options.state.acknowledgeEvents(batch.runId, acknowledgement.acknowledgedSequence);
254
+ this.options.state.acknowledgeEvents(batch.runId, acknowledgement.acknowledgedSequence, batch.events[0].execution?.attemptId);
255
+ this.outboxReceipts.record(acknowledgement);
147
256
  continue;
148
257
  }
149
258
  const lastSentSequence = batch.events.at(-1).sourceSequence;
150
- if (acknowledgement.expectedSequence > events[0].sourceSequence && acknowledgement.expectedSequence <= lastSentSequence + 1) {
151
- this.options.state.discardEventsBefore(batch.runId, acknowledgement.expectedSequence);
259
+ if (!events[0].execution && acknowledgement.expectedSequence > events[0].sourceSequence && acknowledgement.expectedSequence <= lastSentSequence + 1) {
260
+ this.options.state.discardEventsBefore(batch.runId, acknowledgement.expectedSequence, batch.events[0].execution?.attemptId);
152
261
  continue;
153
262
  }
154
263
  throw new Error(`server requested unavailable event sequence ${acknowledgement.expectedSequence}`);
155
264
  }
156
265
  }
157
- async dispatch(command) {
266
+ async dispatch(command, preparationSignal) {
267
+ this.acceptExecutionFence(command);
268
+ if (command.type === 'observe') {
269
+ const session = this.sessions.get(command.runId);
270
+ await this.emit(command.runId, { type: 'process_observation', payload: { process: session ? await session.observe?.() ?? 'unknown' : 'unknown' } });
271
+ return;
272
+ }
158
273
  if (command.type === 'start') {
159
- if (command.payload.fresh) {
160
- await this.sessions.get(command.runId)?.stop('Starting a fresh session');
161
- this.sessions.delete(command.runId);
162
- this.options.state.deleteSession(command.runId);
163
- this.options.state.deleteAdapterSessionState(command.runId);
164
- }
165
- else if (this.sessions.has(command.runId))
166
- return;
167
- const adapter = this.requireAdapter(command.payload.adapterId);
168
- const scope = await resolveFilesystemScope(this.options.filesystem, command.payload.workingDirectory);
169
- const credentials = await this.runCredentials(command.runId, command.payload.metadata.runCredentials === true);
170
- if (credentials === 'unavailable')
171
- return;
172
- const session = await adapter.start({
173
- runId: command.runId,
174
- workingDirectory: scope.workingDirectory,
175
- additionalDirectories: scope.additionalDirectories,
176
- prompt: command.payload.prompt,
177
- ...(command.payload.sessionId ? { remoteSessionId: command.payload.sessionId } : {}),
178
- metadata: command.payload.metadata,
179
- ...(credentials ? { credentials } : {}),
180
- adapterState: this.options.state.getAdapterSessionState(command.runId, command.payload.adapterId),
181
- persistAdapterState: (state) => this.options.state.saveAdapterSessionState(command.runId, command.payload.adapterId, state),
182
- }, (event) => this.emit(command.runId, event));
183
- this.sessions.set(command.runId, session);
184
- this.options.state.saveSession({ runId: command.runId, adapterId: command.payload.adapterId, remoteSessionId: session.remoteSessionId, workingDirectory: scope.workingDirectory });
185
- await this.emit(command.runId, { type: 'session_started', payload: { remoteSessionId: session.remoteSessionId, adapterId: command.payload.adapterId } });
186
- if (!session.initialPromptHandled) {
187
- void session.prompt(command.payload.prompt).catch((error) => this.emit(command.runId, { type: 'failed', payload: { code: 'adapter_prompt_failed', message: safeError(error), retryable: true } }));
188
- }
274
+ await this.startSession(command, preparationSignal);
189
275
  return;
190
276
  }
191
277
  if (command.type === 'shutdown') {
192
278
  const session = this.sessions.get(command.runId);
193
279
  if (session)
194
280
  await session.stop(command.payload.reason);
281
+ await this.drives.get(command.runId)?.closeAfterStopped();
282
+ this.drives.delete(command.runId);
195
283
  this.sessions.delete(command.runId);
196
284
  return;
197
285
  }
286
+ if (command.execution && command.type === 'cancel' && !this.sessions.has(command.runId)) {
287
+ // An empty JS map does not prove an orphaned subprocess stopped.
288
+ await this.emit(command.runId, { type: 'process_observation', payload: { process: 'unknown', recoveryOutcome: 'unavailable' } });
289
+ return;
290
+ }
198
291
  const session = await this.requireSession(command.runId, command.type === 'reconnect' ? command.payload.remoteSessionId : undefined);
199
- if (command.type === 'prompt')
200
- 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
+ }
201
296
  else if (command.type === 'approval_response')
202
297
  await session.approve(command.payload.requestKey, command.payload.optionId);
203
298
  else if (command.type === 'elicitation_response')
204
299
  await session.elicit(command.payload.requestKey, command.payload.action, command.payload.content);
205
300
  else if (command.type === 'cancel')
206
301
  await session.cancel(command.payload.reason);
207
- else if (command.type === 'reconnect')
302
+ else if (command.type === 'reconnect') {
303
+ const stored = this.options.state.getSession(command.runId);
304
+ if (command.execution && stored && this.requireAdapter(stored.adapterId).capability.protocol === 'eve') {
305
+ const process = await session.observe?.() ?? 'unknown';
306
+ await this.emit(command.runId, { type: 'process_observation', payload: { process, recoveryOutcome: process === 'live' ? 'attached_live' : 'unavailable' } });
307
+ if (process === 'live')
308
+ this.prompts.track(session.resume().catch(error => this.emit(command.runId, { type: 'failed', payload: { code: 'native_stream_unavailable', message: safeError(error), retryable: true } })));
309
+ return;
310
+ }
208
311
  await session.resume();
312
+ if (command.execution)
313
+ await this.emit(command.runId, { type: 'process_observation', payload: { process: await session.observe?.() ?? 'unknown', recoveryOutcome: 'attached_live' } });
314
+ }
315
+ }
316
+ acceptExecutionFence(command) {
317
+ if (!command.execution)
318
+ return;
319
+ if (!this.options.durableLifecycle)
320
+ throw new Error('remote lifecycle extension was not negotiated');
321
+ // The server delivers shutdowns for runs this host may never have seen (or whose
322
+ // attempt was replaced): they cannot start a writer, so they bypass the fence.
323
+ if (command.type === 'shutdown')
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
+ }
331
+ const previous = this.executions.get(command.runId) ?? this.options.state.getSession(command.runId)?.execution;
332
+ const replacesPrevious = previous && (previous.attemptId !== command.execution.attemptId || previous.generation !== command.execution.generation);
333
+ // The server only emits `fresh` on an explicit start_fresh: that user action is the
334
+ // proof-of-intent that authorizes replacing a persisted execution whose writer state
335
+ // is unknown (e.g. this host restarted while a detached adapter child was running).
336
+ if (replacesPrevious && !restoring && !(command.type === 'start' && command.payload.fresh === true))
337
+ throw new Error('execution replacement requires proof that the old writer stopped');
338
+ this.executions.set(command.runId, { ...command.execution, hostBootId: this.bootId });
339
+ if (replacesPrevious)
340
+ this.terminalRuns.delete(command.runId);
341
+ }
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();
353
+ const adapter = this.requireAdapter(command.payload.adapterId);
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));
360
+ if (credentials === 'unavailable')
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
+ }
398
+ // Bind callbacks before adapter code can emit, including during old-session teardown.
399
+ const execution = this.executions.get(command.runId);
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
+ }
428
+ this.sessions.set(command.runId, session);
429
+ this.scheduleCapabilityRefresh();
430
+ this.options.state.saveSession({ runId: command.runId, adapterId: command.payload.adapterId, remoteSessionId: session.remoteSessionId, workingDirectory: scope.workingDirectory,
431
+ config: { version: 1, configReference: command.payload.bindingId, toolsReference: command.runId, ...settings },
432
+ ...(command.execution ? { execution: { ...command.execution, hostBootId: this.bootId } } : {}),
433
+ });
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 } })));
438
+ }
439
+ return;
209
440
  }
210
441
  async requireSession(runId, requestedRemoteSessionId) {
211
442
  const active = this.sessions.get(runId);
@@ -216,50 +447,34 @@ export class AgentHostRuntime {
216
447
  throw new Error(`remote session not found for run ${runId}`);
217
448
  if (requestedRemoteSessionId && requestedRemoteSessionId !== stored.remoteSessionId)
218
449
  throw new Error('reconnect session does not match persisted session');
450
+ const adapter = this.requireAdapter(stored.adapterId);
451
+ if (adapter.capability.recovery?.interruptedTurnContinuation !== true) {
452
+ if (this.options.durableLifecycle)
453
+ await this.emit(runId, { type: 'process_observation', payload: { process: 'unknown', recoveryOutcome: 'unavailable' } });
454
+ throw new Error('adapter cannot restore interrupted execution or in-memory approval; inspect the original process');
455
+ }
219
456
  const scope = await resolveFilesystemScope(this.options.filesystem, stored.workingDirectory);
220
457
  // A resumed session needs its credentials again; whether this run has an account is the server's call.
221
458
  const credentials = await this.runCredentials(runId, this.options.fetchRunCredentials === true);
222
459
  if (credentials === 'unavailable')
223
460
  throw new Error('provider credentials are unavailable for this run');
224
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); } }),
225
464
  runId, workingDirectory: scope.workingDirectory, additionalDirectories: scope.additionalDirectories,
226
- prompt: '', remoteSessionId: stored.remoteSessionId, metadata: {},
465
+ prompt: '', remoteSessionId: stored.remoteSessionId, metadata: agentSettingsSchema.parse(stored.config ?? {}),
227
466
  ...(credentials ? { credentials } : {}),
228
467
  adapterState: this.options.state.getAdapterSessionState(runId, stored.adapterId),
229
468
  persistAdapterState: (state) => this.options.state.saveAdapterSessionState(runId, stored.adapterId, state),
230
- }, (event) => this.emit(runId, event));
469
+ }, this.createStream(runId));
231
470
  this.sessions.set(runId, session);
471
+ this.scheduleCapabilityRefresh();
232
472
  return session;
233
473
  }
234
- /**
235
- * The provider credentials for a run. `undefined` means the run uses none
236
- * (no account bound, or this host does not fetch them); 'unavailable' means
237
- * the run cannot start, and the failure has already been reported.
238
- */
239
- async runCredentials(runId, requested) {
240
- const fetchCredentials = this.options.controlPlane.fetchRunCredentials?.bind(this.options.controlPlane);
241
- // Only a host holding the run-credentials method (Overlay Cloud) asks, and only when the run says it has an account.
242
- if (!fetchCredentials || !this.options.fetchRunCredentials || !requested)
243
- return undefined;
244
- try {
245
- return await fetchCredentials(runId);
246
- }
247
- catch (error) {
248
- const code = error instanceof ControlPlaneRequestError ? error.code : undefined;
249
- // No account on this binding: nothing to inject, the run proceeds as configured.
250
- if (code === 'provider_account_missing')
251
- return undefined;
252
- const needsSignIn = code === 'account_needs_reauth' || code === 'account_unavailable';
253
- await this.emit(runId, { type: 'failed', payload: {
254
- code: needsSignIn ? 'auth_required' : 'credentials_unavailable',
255
- message: needsSignIn
256
- ? 'This agent’s account needs to be reconnected in Settings → Agent accounts.'
257
- : 'The agent could not get its credentials. Try again.',
258
- retryable: !needsSignIn,
259
- } });
260
- this.logger.warn('run credentials unavailable', { runId, code: code ?? 'unknown' });
261
- return 'unavailable';
262
- }
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 });
263
478
  }
264
479
  requireAdapter(adapterId) {
265
480
  const adapter = this.adapters.get(adapterId);
@@ -267,22 +482,90 @@ export class AgentHostRuntime {
267
482
  throw new Error(`adapter is not installed: ${adapterId}`);
268
483
  return adapter;
269
484
  }
270
- async emit(runId, event) {
271
- if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
272
- throw new Error('event outbox backpressure limit reached');
273
- }
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
+ */
518
+ async emit(runId, event, execution = this.executions.get(runId)) {
519
+ if (this.shuttingDown && ['completed', 'failed', 'cancelled'].includes(event.type))
520
+ return;
274
521
  const stored = {
275
522
  protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
523
+ ...(execution ? { execution } : {}),
276
524
  eventId: randomUUID(), environmentId: this.options.environmentId, runId,
277
525
  occurredAt: Date.now(), ...event,
278
526
  };
279
- this.options.state.appendEvent(stored);
280
- try {
281
- await this.flushOutbox();
282
- }
283
- catch (error) {
284
- this.logger.warn('event upload deferred', { runId, error: safeError(error) });
285
- }
527
+ this.options.state.appendOrReplaceTextCheckpoint(stored, this.inFlight.get(streamKey(runId, execution?.attemptId)) ?? 0);
528
+ const currentExecution = this.executions.get(runId);
529
+ if (this.options.durableLifecycle && execution?.attemptId === currentExecution?.attemptId
530
+ && execution?.generation === currentExecution?.generation && ['completed', 'cancelled', 'failed'].includes(event.type))
531
+ this.terminalRuns.add(runId);
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
+ });
286
569
  }
287
570
  acknowledge(command, accepted, message, errorCode = 'command_rejected') {
288
571
  return this.options.controlPlane.acknowledgeCommand({
@@ -295,10 +578,5 @@ export class AgentHostRuntime {
295
578
  }
296
579
  }
297
580
  function safeError(error) { return error instanceof Error ? error.message.slice(0, 2_000) : 'Unknown host error'; }
298
- function abortableDelay(milliseconds, signal) {
299
- return new Promise((resolve, reject) => {
300
- const timer = setTimeout(resolve, milliseconds);
301
- signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
302
- });
303
- }
581
+ function streamKey(runId, attemptId) { return `${runId}\u0000${attemptId ?? ''}`; }
304
582
  //# sourceMappingURL=runtime.js.map