@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.
- package/README.md +11 -1
- package/dist/acp-adapter.d.ts +47 -22
- package/dist/acp-adapter.d.ts.map +1 -1
- package/dist/acp-adapter.js +132 -40
- package/dist/acp-adapter.js.map +1 -1
- package/dist/acp-settings.d.ts +29 -0
- package/dist/acp-settings.d.ts.map +1 -0
- package/dist/acp-settings.js +48 -0
- package/dist/acp-settings.js.map +1 -0
- package/dist/acpx-adapter.d.ts +42 -24
- package/dist/acpx-adapter.d.ts.map +1 -1
- package/dist/acpx-adapter.js +153 -37
- package/dist/acpx-adapter.js.map +1 -1
- package/dist/acpx-session-identity.d.ts +35 -0
- package/dist/acpx-session-identity.d.ts.map +1 -0
- package/dist/acpx-session-identity.js +55 -0
- package/dist/acpx-session-identity.js.map +1 -0
- package/dist/action-title.d.ts +3 -0
- package/dist/action-title.d.ts.map +1 -0
- package/dist/action-title.js +11 -0
- package/dist/action-title.js.map +1 -0
- package/dist/adapter-manifests.d.ts +8 -6
- package/dist/adapter-manifests.d.ts.map +1 -1
- package/dist/adapter-manifests.js +19 -2
- package/dist/adapter-manifests.js.map +1 -1
- package/dist/adapter.d.ts +11 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +9 -1
- package/dist/adapter.js.map +1 -1
- package/dist/agent-options.d.ts +4 -0
- package/dist/agent-options.d.ts.map +1 -0
- package/dist/agent-options.js +49 -0
- package/dist/agent-options.js.map +1 -0
- package/dist/cli.js +106 -82
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +123 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +18 -5
- package/dist/config.js.map +1 -1
- package/dist/connection.d.ts +3 -3
- package/dist/discovery-workspace.d.ts +6 -0
- package/dist/discovery-workspace.d.ts.map +1 -0
- package/dist/discovery-workspace.js +20 -0
- package/dist/discovery-workspace.js.map +1 -0
- package/dist/drive-cache.d.ts +58 -0
- package/dist/drive-cache.d.ts.map +1 -0
- package/dist/drive-cache.js +243 -0
- package/dist/drive-cache.js.map +1 -0
- package/dist/drive-client.d.ts +112 -0
- package/dist/drive-client.d.ts.map +1 -0
- package/dist/drive-client.js +273 -0
- package/dist/drive-client.js.map +1 -0
- package/dist/drive-journal.d.ts +1218 -0
- package/dist/drive-journal.d.ts.map +1 -0
- package/dist/drive-journal.js +290 -0
- package/dist/drive-journal.js.map +1 -0
- package/dist/drive-lease.d.ts +15 -0
- package/dist/drive-lease.d.ts.map +1 -0
- package/dist/drive-lease.js +79 -0
- package/dist/drive-lease.js.map +1 -0
- package/dist/drive-restoration.d.ts +16 -0
- package/dist/drive-restoration.d.ts.map +1 -0
- package/dist/drive-restoration.js +36 -0
- package/dist/drive-restoration.js.map +1 -0
- package/dist/drive-sync-state.d.ts +2346 -0
- package/dist/drive-sync-state.d.ts.map +1 -0
- package/dist/drive-sync-state.js +100 -0
- package/dist/drive-sync-state.js.map +1 -0
- package/dist/drive-sync.d.ts +56 -0
- package/dist/drive-sync.d.ts.map +1 -0
- package/dist/drive-sync.js +539 -0
- package/dist/drive-sync.js.map +1 -0
- package/dist/drive-writer.d.ts +27 -0
- package/dist/drive-writer.d.ts.map +1 -0
- package/dist/drive-writer.js +64 -0
- package/dist/drive-writer.js.map +1 -0
- package/dist/enrollment.js +1 -1
- package/dist/enrollment.js.map +1 -1
- package/dist/host-capabilities.d.ts +12 -0
- package/dist/host-capabilities.d.ts.map +1 -0
- package/dist/host-capabilities.js +70 -0
- package/dist/host-capabilities.js.map +1 -0
- package/dist/host-heartbeat.d.ts +14 -0
- package/dist/host-heartbeat.d.ts.map +1 -0
- package/dist/host-heartbeat.js +41 -0
- package/dist/host-heartbeat.js.map +1 -0
- package/dist/image-check.d.ts +1 -1
- package/dist/image-check.js +4 -4
- package/dist/image-check.js.map +1 -1
- package/dist/native-restoration.d.ts +7 -0
- package/dist/native-restoration.d.ts.map +1 -0
- package/dist/native-restoration.js +21 -0
- package/dist/native-restoration.js.map +1 -0
- package/dist/native-start-barrier.d.ts +27 -0
- package/dist/native-start-barrier.d.ts.map +1 -0
- package/dist/native-start-barrier.js +28 -0
- package/dist/native-start-barrier.js.map +1 -0
- package/dist/native-start-preparation.d.ts +6 -0
- package/dist/native-start-preparation.d.ts.map +1 -0
- package/dist/native-start-preparation.js +23 -0
- package/dist/native-start-preparation.js.map +1 -0
- package/dist/ordered-acp-updates.d.ts +11 -0
- package/dist/ordered-acp-updates.d.ts.map +1 -0
- package/dist/ordered-acp-updates.js +38 -0
- package/dist/ordered-acp-updates.js.map +1 -0
- package/dist/outbox-packing.d.ts +22 -0
- package/dist/outbox-packing.d.ts.map +1 -0
- package/dist/outbox-packing.js +51 -0
- package/dist/outbox-packing.js.map +1 -0
- package/dist/outbox-receipts.d.ts +20 -0
- package/dist/outbox-receipts.d.ts.map +1 -0
- package/dist/outbox-receipts.js +44 -0
- package/dist/outbox-receipts.js.map +1 -0
- package/dist/preparation-command-polling.d.ts +13 -0
- package/dist/preparation-command-polling.d.ts.map +1 -0
- package/dist/preparation-command-polling.js +62 -0
- package/dist/preparation-command-polling.js.map +1 -0
- package/dist/preparation-failure.d.ts +2 -0
- package/dist/preparation-failure.d.ts.map +1 -0
- package/dist/preparation-failure.js +19 -0
- package/dist/preparation-failure.js.map +1 -0
- package/dist/preview-hosting-access.d.ts +18 -0
- package/dist/preview-hosting-access.d.ts.map +1 -0
- package/dist/preview-hosting-access.js +48 -0
- package/dist/preview-hosting-access.js.map +1 -0
- package/dist/preview-hosting.d.ts +8 -0
- package/dist/preview-hosting.d.ts.map +1 -0
- package/dist/preview-hosting.js +19 -0
- package/dist/preview-hosting.js.map +1 -0
- package/dist/preview-mcp-relay.d.ts +8 -0
- package/dist/preview-mcp-relay.d.ts.map +1 -0
- package/dist/preview-mcp-relay.js +127 -0
- package/dist/preview-mcp-relay.js.map +1 -0
- package/dist/process-group.d.ts +4 -0
- package/dist/process-group.d.ts.map +1 -0
- package/dist/process-group.js +38 -0
- package/dist/process-group.js.map +1 -0
- package/dist/process-host-command.d.ts +14 -0
- package/dist/process-host-command.d.ts.map +1 -0
- package/dist/process-host-command.js +55 -0
- package/dist/process-host-command.js.map +1 -0
- package/dist/provider-run-credentials.d.ts +13 -0
- package/dist/provider-run-credentials.d.ts.map +1 -0
- package/dist/provider-run-credentials.js +27 -0
- package/dist/provider-run-credentials.js.map +1 -0
- package/dist/run-preparation.d.ts +9 -0
- package/dist/run-preparation.d.ts.map +1 -0
- package/dist/run-preparation.js +21 -0
- package/dist/run-preparation.js.map +1 -0
- package/dist/run-stream.d.ts +20 -0
- package/dist/run-stream.d.ts.map +1 -0
- package/dist/run-stream.js +96 -0
- package/dist/run-stream.js.map +1 -0
- package/dist/runtime-drive-controller.d.ts +26 -0
- package/dist/runtime-drive-controller.d.ts.map +1 -0
- package/dist/runtime-drive-controller.js +118 -0
- package/dist/runtime-drive-controller.js.map +1 -0
- package/dist/runtime-drive.d.ts +30 -0
- package/dist/runtime-drive.d.ts.map +1 -0
- package/dist/runtime-drive.js +151 -0
- package/dist/runtime-drive.js.map +1 -0
- package/dist/runtime-session-admission.d.ts +24 -0
- package/dist/runtime-session-admission.d.ts.map +1 -0
- package/dist/runtime-session-admission.js +46 -0
- package/dist/runtime-session-admission.js.map +1 -0
- package/dist/runtime-shutdown.d.ts +21 -0
- package/dist/runtime-shutdown.d.ts.map +1 -0
- package/dist/runtime-shutdown.js +27 -0
- package/dist/runtime-shutdown.js.map +1 -0
- package/dist/runtime-terminal-boundary.d.ts +18 -0
- package/dist/runtime-terminal-boundary.d.ts.map +1 -0
- package/dist/runtime-terminal-boundary.js +36 -0
- package/dist/runtime-terminal-boundary.js.map +1 -0
- package/dist/runtime.d.ts +71 -7
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +360 -188
- package/dist/runtime.js.map +1 -1
- package/dist/state.d.ts +29 -2
- package/dist/state.d.ts.map +1 -1
- package/dist/state.js +131 -0
- package/dist/state.js.map +1 -1
- package/dist/text-coalescer.d.ts +16 -0
- package/dist/text-coalescer.d.ts.map +1 -0
- package/dist/text-coalescer.js +55 -0
- package/dist/text-coalescer.js.map +1 -0
- package/dist/transport.d.ts +17 -13
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +43 -4
- package/dist/transport.js.map +1 -1
- 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 {
|
|
3
|
-
import {
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
29
|
-
if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000))
|
|
30
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
47
|
-
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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.
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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
|
|
129
|
-
this.options.state.recordCommandResult(command.commandId, { sequence: command.sequence, accepted: true });
|
|
197
|
+
await work;
|
|
130
198
|
}
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
|
|
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
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
this.
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
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
|
|
277
|
-
|
|
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 =
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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, ...
|
|
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
|
-
|
|
301
|
-
|
|
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:
|
|
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
|
-
},
|
|
469
|
+
}, this.createStream(runId));
|
|
332
470
|
this.sessions.set(runId, session);
|
|
471
|
+
this.scheduleCapabilityRefresh();
|
|
333
472
|
return session;
|
|
334
473
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
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.
|
|
373
|
-
|
|
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.
|
|
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
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
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
|
|
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
|