@layernorm/overlay-agent-host 0.4.2 → 0.5.0
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 +40 -27
- package/dist/cli.js +56 -189
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +13 -277
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +21 -48
- package/dist/config.js.map +1 -1
- package/dist/connection.d.ts +10 -10
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +1 -1
- package/dist/connection.js.map +1 -1
- package/dist/doctor.d.ts +2 -2
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +7 -23
- package/dist/doctor.js.map +1 -1
- package/dist/enrollment.d.ts +4 -4
- package/dist/enrollment.d.ts.map +1 -1
- package/dist/enrollment.js +4 -16
- package/dist/enrollment.js.map +1 -1
- package/dist/host-capabilities.d.ts +5 -9
- package/dist/host-capabilities.d.ts.map +1 -1
- package/dist/host-capabilities.js +7 -63
- package/dist/host-capabilities.js.map +1 -1
- package/dist/index.d.ts +2 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -10
- package/dist/index.js.map +1 -1
- package/dist/local-tools-browser.d.ts +54 -0
- package/dist/local-tools-browser.d.ts.map +1 -0
- package/dist/local-tools-browser.js +360 -0
- package/dist/local-tools-browser.js.map +1 -0
- package/dist/local-tools-errors.d.ts +8 -0
- package/dist/local-tools-errors.d.ts.map +1 -0
- package/dist/local-tools-errors.js +14 -0
- package/dist/local-tools-errors.js.map +1 -0
- package/dist/local-tools-exec.d.ts +27 -0
- package/dist/local-tools-exec.d.ts.map +1 -0
- package/dist/local-tools-exec.js +128 -0
- package/dist/local-tools-exec.js.map +1 -0
- package/dist/local-tools-macos.d.ts +20 -0
- package/dist/local-tools-macos.d.ts.map +1 -0
- package/dist/local-tools-macos.js +217 -0
- package/dist/local-tools-macos.js.map +1 -0
- package/dist/local-tools-paths.d.ts +13 -0
- package/dist/local-tools-paths.d.ts.map +1 -0
- package/dist/local-tools-paths.js +76 -0
- package/dist/local-tools-paths.js.map +1 -0
- package/dist/local-tools-terminal.d.ts +19 -0
- package/dist/local-tools-terminal.d.ts.map +1 -0
- package/dist/local-tools-terminal.js +201 -0
- package/dist/local-tools-terminal.js.map +1 -0
- package/dist/local-tools.d.ts +53 -0
- package/dist/local-tools.d.ts.map +1 -0
- package/dist/local-tools.js +219 -0
- package/dist/local-tools.js.map +1 -0
- package/dist/preview-hosting-access.d.ts +1 -1
- package/dist/preview-hosting-access.d.ts.map +1 -1
- package/dist/preview-hosting-access.js +1 -1
- package/dist/preview-hosting-access.js.map +1 -1
- package/dist/preview-hosting.d.ts +2 -7
- package/dist/preview-hosting.d.ts.map +1 -1
- package/dist/preview-hosting.js +2 -11
- package/dist/preview-hosting.js.map +1 -1
- package/dist/runtime.d.ts +11 -124
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +32 -551
- package/dist/runtime.js.map +1 -1
- package/dist/transport.d.ts +12 -29
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +15 -73
- package/dist/transport.js.map +1 -1
- package/docker-compose.example.yml +1 -1
- package/package.json +4 -8
- package/dist/acp-adapter.d.ts +0 -85
- package/dist/acp-adapter.d.ts.map +0 -1
- package/dist/acp-adapter.js +0 -418
- package/dist/acp-adapter.js.map +0 -1
- package/dist/acp-settings.d.ts +0 -29
- package/dist/acp-settings.d.ts.map +0 -1
- package/dist/acp-settings.js +0 -48
- package/dist/acp-settings.js.map +0 -1
- package/dist/acpx-adapter.d.ts +0 -122
- package/dist/acpx-adapter.d.ts.map +0 -1
- package/dist/acpx-adapter.js +0 -444
- package/dist/acpx-adapter.js.map +0 -1
- package/dist/acpx-session-identity.d.ts +0 -35
- package/dist/acpx-session-identity.d.ts.map +0 -1
- package/dist/acpx-session-identity.js +0 -55
- package/dist/acpx-session-identity.js.map +0 -1
- package/dist/action-title.d.ts +0 -3
- package/dist/action-title.d.ts.map +0 -1
- package/dist/action-title.js +0 -11
- package/dist/action-title.js.map +0 -1
- package/dist/adapter-manifests.d.ts +0 -49
- package/dist/adapter-manifests.d.ts.map +0 -1
- package/dist/adapter-manifests.js +0 -47
- package/dist/adapter-manifests.js.map +0 -1
- package/dist/adapter.d.ts +0 -50
- package/dist/adapter.d.ts.map +0 -1
- package/dist/adapter.js +0 -10
- package/dist/adapter.js.map +0 -1
- package/dist/agent-options.d.ts +0 -4
- package/dist/agent-options.d.ts.map +0 -1
- package/dist/agent-options.js +0 -49
- package/dist/agent-options.js.map +0 -1
- package/dist/discovery-workspace.d.ts +0 -6
- package/dist/discovery-workspace.d.ts.map +0 -1
- package/dist/discovery-workspace.js +0 -20
- package/dist/discovery-workspace.js.map +0 -1
- package/dist/drive-cache.d.ts +0 -58
- package/dist/drive-cache.d.ts.map +0 -1
- package/dist/drive-cache.js +0 -243
- package/dist/drive-cache.js.map +0 -1
- package/dist/drive-client.d.ts +0 -112
- package/dist/drive-client.d.ts.map +0 -1
- package/dist/drive-client.js +0 -273
- package/dist/drive-client.js.map +0 -1
- package/dist/drive-journal.d.ts +0 -1218
- package/dist/drive-journal.d.ts.map +0 -1
- package/dist/drive-journal.js +0 -290
- package/dist/drive-journal.js.map +0 -1
- package/dist/drive-lease.d.ts +0 -15
- package/dist/drive-lease.d.ts.map +0 -1
- package/dist/drive-lease.js +0 -79
- package/dist/drive-lease.js.map +0 -1
- package/dist/drive-restoration.d.ts +0 -16
- package/dist/drive-restoration.d.ts.map +0 -1
- package/dist/drive-restoration.js +0 -36
- package/dist/drive-restoration.js.map +0 -1
- package/dist/drive-sync-state.d.ts +0 -2346
- package/dist/drive-sync-state.d.ts.map +0 -1
- package/dist/drive-sync-state.js +0 -100
- package/dist/drive-sync-state.js.map +0 -1
- package/dist/drive-sync.d.ts +0 -56
- package/dist/drive-sync.d.ts.map +0 -1
- package/dist/drive-sync.js +0 -539
- package/dist/drive-sync.js.map +0 -1
- package/dist/drive-writer.d.ts +0 -27
- package/dist/drive-writer.d.ts.map +0 -1
- package/dist/drive-writer.js +0 -64
- package/dist/drive-writer.js.map +0 -1
- package/dist/eve-adapter.d.ts +0 -75
- package/dist/eve-adapter.d.ts.map +0 -1
- package/dist/eve-adapter.js +0 -332
- package/dist/eve-adapter.js.map +0 -1
- package/dist/export-config.d.ts +0 -20
- package/dist/export-config.d.ts.map +0 -1
- package/dist/export-config.js +0 -128
- package/dist/export-config.js.map +0 -1
- package/dist/fake-adapter.d.ts +0 -43
- package/dist/fake-adapter.d.ts.map +0 -1
- package/dist/fake-adapter.js +0 -43
- package/dist/fake-adapter.js.map +0 -1
- package/dist/filesystem-policy.d.ts +0 -7
- package/dist/filesystem-policy.d.ts.map +0 -1
- package/dist/filesystem-policy.js +0 -23
- package/dist/filesystem-policy.js.map +0 -1
- package/dist/hermes-readiness.d.ts +0 -6
- package/dist/hermes-readiness.d.ts.map +0 -1
- package/dist/hermes-readiness.js +0 -21
- package/dist/hermes-readiness.js.map +0 -1
- package/dist/image-check.d.ts +0 -29
- package/dist/image-check.d.ts.map +0 -1
- package/dist/image-check.js +0 -61
- package/dist/image-check.js.map +0 -1
- package/dist/native-restoration.d.ts +0 -7
- package/dist/native-restoration.d.ts.map +0 -1
- package/dist/native-restoration.js +0 -21
- package/dist/native-restoration.js.map +0 -1
- package/dist/native-start-barrier.d.ts +0 -27
- package/dist/native-start-barrier.d.ts.map +0 -1
- package/dist/native-start-barrier.js +0 -28
- package/dist/native-start-barrier.js.map +0 -1
- package/dist/native-start-preparation.d.ts +0 -6
- package/dist/native-start-preparation.d.ts.map +0 -1
- package/dist/native-start-preparation.js +0 -23
- package/dist/native-start-preparation.js.map +0 -1
- package/dist/ordered-acp-updates.d.ts +0 -11
- package/dist/ordered-acp-updates.d.ts.map +0 -1
- package/dist/ordered-acp-updates.js +0 -38
- package/dist/ordered-acp-updates.js.map +0 -1
- package/dist/outbox-packing.d.ts +0 -22
- package/dist/outbox-packing.d.ts.map +0 -1
- package/dist/outbox-packing.js +0 -51
- package/dist/outbox-packing.js.map +0 -1
- package/dist/outbox-receipts.d.ts +0 -20
- package/dist/outbox-receipts.d.ts.map +0 -1
- package/dist/outbox-receipts.js +0 -44
- package/dist/outbox-receipts.js.map +0 -1
- package/dist/preparation-command-polling.d.ts +0 -13
- package/dist/preparation-command-polling.d.ts.map +0 -1
- package/dist/preparation-command-polling.js +0 -62
- package/dist/preparation-command-polling.js.map +0 -1
- package/dist/preparation-failure.d.ts +0 -2
- package/dist/preparation-failure.d.ts.map +0 -1
- package/dist/preparation-failure.js +0 -19
- package/dist/preparation-failure.js.map +0 -1
- package/dist/preview-mcp-relay.d.ts +0 -8
- package/dist/preview-mcp-relay.d.ts.map +0 -1
- package/dist/preview-mcp-relay.js +0 -127
- package/dist/preview-mcp-relay.js.map +0 -1
- package/dist/process-group.d.ts +0 -4
- package/dist/process-group.d.ts.map +0 -1
- package/dist/process-group.js +0 -38
- package/dist/process-group.js.map +0 -1
- package/dist/process-host-command.d.ts +0 -14
- package/dist/process-host-command.d.ts.map +0 -1
- package/dist/process-host-command.js +0 -55
- package/dist/process-host-command.js.map +0 -1
- package/dist/provider-run-credentials.d.ts +0 -13
- package/dist/provider-run-credentials.d.ts.map +0 -1
- package/dist/provider-run-credentials.js +0 -27
- package/dist/provider-run-credentials.js.map +0 -1
- package/dist/run-preparation.d.ts +0 -9
- package/dist/run-preparation.d.ts.map +0 -1
- package/dist/run-preparation.js +0 -21
- package/dist/run-preparation.js.map +0 -1
- package/dist/run-stream.d.ts +0 -20
- package/dist/run-stream.d.ts.map +0 -1
- package/dist/run-stream.js +0 -96
- package/dist/run-stream.js.map +0 -1
- package/dist/runtime-drive-controller.d.ts +0 -26
- package/dist/runtime-drive-controller.d.ts.map +0 -1
- package/dist/runtime-drive-controller.js +0 -118
- package/dist/runtime-drive-controller.js.map +0 -1
- package/dist/runtime-drive.d.ts +0 -30
- package/dist/runtime-drive.d.ts.map +0 -1
- package/dist/runtime-drive.js +0 -151
- package/dist/runtime-drive.js.map +0 -1
- package/dist/runtime-session-admission.d.ts +0 -24
- package/dist/runtime-session-admission.d.ts.map +0 -1
- package/dist/runtime-session-admission.js +0 -46
- package/dist/runtime-session-admission.js.map +0 -1
- package/dist/runtime-shutdown.d.ts +0 -21
- package/dist/runtime-shutdown.d.ts.map +0 -1
- package/dist/runtime-shutdown.js +0 -27
- package/dist/runtime-shutdown.js.map +0 -1
- package/dist/runtime-terminal-boundary.d.ts +0 -18
- package/dist/runtime-terminal-boundary.d.ts.map +0 -1
- package/dist/runtime-terminal-boundary.js +0 -36
- package/dist/runtime-terminal-boundary.js.map +0 -1
- package/dist/state.d.ts +0 -87
- package/dist/state.d.ts.map +0 -1
- package/dist/state.js +0 -348
- package/dist/state.js.map +0 -1
- package/dist/text-coalescer.d.ts +0 -16
- package/dist/text-coalescer.d.ts.map +0 -1
- package/dist/text-coalescer.js +0 -55
- package/dist/text-coalescer.js.map +0 -1
package/dist/runtime.js
CHANGED
|
@@ -1,582 +1,63 @@
|
|
|
1
|
-
import { AdapterStartError } from './adapter.js';
|
|
2
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
-
import { homedir } from 'node:os';
|
|
4
1
|
import { setTimeout as wait } from 'node:timers/promises';
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
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';
|
|
2
|
+
import { filesystemGrantSchema } from '@layernorm/overlay-agent-bridge-protocol';
|
|
3
|
+
import { buildHostCapabilities } from './host-capabilities.js';
|
|
10
4
|
import { HostHeartbeat } from './host-heartbeat.js';
|
|
11
|
-
import {
|
|
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';
|
|
22
|
-
import { resolveFilesystemScope } from './filesystem-policy.js';
|
|
23
|
-
import { packEventBatch, shrinkOversizedEvent } from './outbox-packing.js';
|
|
24
|
-
import { createRunStream } from './run-stream.js';
|
|
5
|
+
import { LocalToolLoop } from './local-tools.js';
|
|
25
6
|
import { StructuredLogger } from './logger.js';
|
|
26
|
-
|
|
7
|
+
const CAPABILITY_REFRESH_MS = 24 * 60 * 60_000;
|
|
8
|
+
/**
|
|
9
|
+
* The host's whole job: keep this machine's environment online, advertise its
|
|
10
|
+
* local tools, and answer Overlay's tool calls. It starts no agent harness.
|
|
11
|
+
*/
|
|
27
12
|
export class AgentHostRuntime {
|
|
28
13
|
options;
|
|
29
|
-
nativePreparations = new Map();
|
|
30
|
-
adapters;
|
|
31
|
-
sessions = new Map();
|
|
32
14
|
logger;
|
|
33
|
-
|
|
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; }
|
|
15
|
+
heartbeat;
|
|
55
16
|
constructor(options) {
|
|
56
17
|
this.options = options;
|
|
57
|
-
this.adapters = new Map(options.adapters.map((adapter) => [adapter.capability.id, adapter]));
|
|
58
18
|
this.logger = options.logger ?? new StructuredLogger();
|
|
59
|
-
this.
|
|
19
|
+
this.heartbeat = new HostHeartbeat(() => options.controlPlane.heartbeat());
|
|
60
20
|
}
|
|
61
21
|
updateFilesystemGrant(grant) {
|
|
62
22
|
this.options.filesystem = filesystemGrantSchema.parse(grant);
|
|
63
23
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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 } : {}) });
|
|
24
|
+
get filesystem() { return this.options.filesystem; }
|
|
25
|
+
async refreshCapabilities() {
|
|
26
|
+
await this.options.controlPlane.updateCapabilities(buildHostCapabilities({
|
|
27
|
+
filesystem: this.options.filesystem, localTools: await this.options.localTools.capability(),
|
|
83
28
|
}));
|
|
84
29
|
}
|
|
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.
|
|
87
|
-
if (this.options.state.outboxSize() >= (this.options.maxOutboxEvents ?? 10_000)) {
|
|
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
|
-
}
|
|
93
|
-
}
|
|
94
|
-
const response = await this.options.controlPlane.pollCommands({ waitMs, ...(signal ? { signal } : {}) });
|
|
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();
|
|
106
|
-
return response.retryAfterMs ?? 0;
|
|
107
|
-
}
|
|
108
30
|
async run(signal) {
|
|
109
|
-
|
|
110
|
-
const abort = () => { this.shuttingDown = true; };
|
|
111
|
-
signal.addEventListener('abort', abort, { once: true });
|
|
31
|
+
await this.retryUntilAborted(signal, async () => { await this.refreshCapabilities(); await this.heartbeat.send(); }, 'host registration deferred');
|
|
112
32
|
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();
|
|
142
|
-
try {
|
|
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;
|
|
149
|
-
}
|
|
150
|
-
finally {
|
|
151
|
-
this.stopBackgroundUploads();
|
|
152
|
-
await heartbeatStopped;
|
|
153
|
-
signal.removeEventListener('abort', abort);
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
async refreshHostState() {
|
|
158
|
-
if (this.options.controlPlane.updateCapabilities) {
|
|
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,
|
|
162
|
-
});
|
|
163
|
-
await updateHostCapabilities(this.options.controlPlane, capabilities);
|
|
164
|
-
}
|
|
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
33
|
return;
|
|
172
|
-
this.
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
}
|
|
177
|
-
async heartbeat() {
|
|
178
|
-
await this.options.controlPlane.heartbeat?.();
|
|
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));
|
|
181
|
-
}
|
|
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;
|
|
193
|
-
}
|
|
194
|
-
const work = Promise.resolve().then(execute);
|
|
195
|
-
this.nativePreparations.set(command.commandId, { fingerprint, work });
|
|
34
|
+
this.heartbeat.start(signal, error => this.logger.warn('host heartbeat deferred', { error: safeError(error) }));
|
|
35
|
+
const refresh = setInterval(() => void this.refreshCapabilities().catch(error => this.logger.warn('capability refresh deferred', { error: safeError(error) })), CAPABILITY_REFRESH_MS);
|
|
36
|
+
refresh.unref?.();
|
|
37
|
+
this.logger.info('local tools ready', { environmentId: this.options.environmentId });
|
|
196
38
|
try {
|
|
197
|
-
await
|
|
39
|
+
await new LocalToolLoop(this.options.controlPlane, this.options.localTools, this.logger).run(signal);
|
|
198
40
|
}
|
|
199
41
|
finally {
|
|
200
|
-
|
|
42
|
+
clearInterval(refresh);
|
|
43
|
+
await this.heartbeat.stop();
|
|
201
44
|
}
|
|
202
45
|
}
|
|
203
|
-
async
|
|
204
|
-
|
|
205
|
-
if (!controlPlane.createArtifactUpload || !controlPlane.uploadArtifactBytes || !controlPlane.completeArtifactUpload) {
|
|
206
|
-
throw new Error('control plane does not support artifact uploads');
|
|
207
|
-
}
|
|
208
|
-
const sha256 = createHash('sha256').update(input.bytes).digest('hex');
|
|
209
|
-
const upload = await controlPlane.createArtifactUpload({ protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
|
|
210
|
-
runId, name: input.name, mediaType: input.mediaType, size: input.bytes.byteLength, sha256 });
|
|
211
|
-
await controlPlane.uploadArtifactBytes(upload, input.bytes);
|
|
212
|
-
await controlPlane.completeArtifactUpload(upload.artifactId);
|
|
213
|
-
await this.emit(runId, { type: 'artifact', payload: { name: input.name, mediaType: input.mediaType,
|
|
214
|
-
size: input.bytes.byteLength, sha256, uploadReference: upload.uploadReference } });
|
|
215
|
-
return upload.artifactId;
|
|
216
|
-
}
|
|
217
|
-
async flushOutbox() {
|
|
218
|
-
if (this.flushing)
|
|
219
|
-
return this.flushing;
|
|
220
|
-
this.flushing = this.flushOutboxInternal().finally(() => { this.flushing = undefined; });
|
|
221
|
-
return this.flushing;
|
|
222
|
-
}
|
|
223
|
-
async flushOutboxInternal() {
|
|
224
|
-
for (;;) {
|
|
225
|
-
if (this.shuttingDown && this.uploadsStopped)
|
|
226
|
-
return;
|
|
227
|
-
const events = this.options.state.pendingUploadEvents(100);
|
|
228
|
-
if (events.length === 0)
|
|
229
|
-
return;
|
|
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);
|
|
244
|
-
// Sequential on purpose: batches carry ordered sequences; the next
|
|
245
|
-
// iteration reads pendingEvents after this batch is acknowledged.
|
|
246
|
-
// react-doctor-disable-next-line react-doctor/async-await-in-loop
|
|
247
|
-
const acknowledgement = await this.options.controlPlane.uploadEvents(batch).finally(() => this.inFlight.delete(stream));
|
|
248
|
-
if (acknowledgement.accepted) {
|
|
249
|
-
const lastSentSequence = batch.events.at(-1).sourceSequence;
|
|
250
|
-
const attempted = this.options.state.uploadAttemptWatermark(batch.runId, batch.events[0].execution?.attemptId);
|
|
251
|
-
if (acknowledgement.acknowledgedSequence < lastSentSequence || acknowledgement.acknowledgedSequence > attempted) {
|
|
252
|
-
throw new Error(`server acknowledged ${acknowledgement.acknowledgedSequence}, expected ${lastSentSequence}`);
|
|
253
|
-
}
|
|
254
|
-
this.options.state.acknowledgeEvents(batch.runId, acknowledgement.acknowledgedSequence, batch.events[0].execution?.attemptId);
|
|
255
|
-
this.outboxReceipts.record(acknowledgement);
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
const lastSentSequence = batch.events.at(-1).sourceSequence;
|
|
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);
|
|
261
|
-
continue;
|
|
262
|
-
}
|
|
263
|
-
throw new Error(`server requested unavailable event sequence ${acknowledgement.expectedSequence}`);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
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
|
-
}
|
|
273
|
-
if (command.type === 'start') {
|
|
274
|
-
await this.startSession(command, preparationSignal);
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
if (command.type === 'shutdown') {
|
|
278
|
-
const session = this.sessions.get(command.runId);
|
|
279
|
-
if (session)
|
|
280
|
-
await session.stop(command.payload.reason);
|
|
281
|
-
await this.drives.get(command.runId)?.closeAfterStopped();
|
|
282
|
-
this.drives.delete(command.runId);
|
|
283
|
-
this.sessions.delete(command.runId);
|
|
284
|
-
return;
|
|
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
|
-
}
|
|
291
|
-
const session = await this.requireSession(command.runId, command.type === 'reconnect' ? command.payload.remoteSessionId : undefined);
|
|
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
|
-
}
|
|
296
|
-
else if (command.type === 'approval_response')
|
|
297
|
-
await session.approve(command.payload.requestKey, command.payload.optionId);
|
|
298
|
-
else if (command.type === 'elicitation_response')
|
|
299
|
-
await session.elicit(command.payload.requestKey, command.payload.action, command.payload.content);
|
|
300
|
-
else if (command.type === 'cancel')
|
|
301
|
-
await session.cancel(command.payload.reason);
|
|
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
|
-
}
|
|
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) {
|
|
46
|
+
async retryUntilAborted(signal, work, message) {
|
|
47
|
+
for (let attempt = 0; !signal.aborted; attempt++) {
|
|
376
48
|
try {
|
|
377
|
-
|
|
378
|
-
|
|
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 });
|
|
49
|
+
await work();
|
|
50
|
+
return;
|
|
387
51
|
}
|
|
388
52
|
catch (error) {
|
|
389
|
-
|
|
390
|
-
|
|
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);
|
|
53
|
+
const delay = Math.min(30_000, 500 * 2 ** Math.min(attempt, 6));
|
|
54
|
+
this.logger.warn(message, { error: safeError(error), delay });
|
|
55
|
+
await wait(delay, undefined, { signal }).catch(() => undefined);
|
|
423
56
|
}
|
|
424
|
-
else
|
|
425
|
-
this.drives.get(command.runId)?.retainUncertainStartup();
|
|
426
|
-
throw error;
|
|
427
57
|
}
|
|
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;
|
|
440
|
-
}
|
|
441
|
-
async requireSession(runId, requestedRemoteSessionId) {
|
|
442
|
-
const active = this.sessions.get(runId);
|
|
443
|
-
if (active)
|
|
444
|
-
return active;
|
|
445
|
-
const stored = this.options.state.getSession(runId);
|
|
446
|
-
if (!stored)
|
|
447
|
-
throw new Error(`remote session not found for run ${runId}`);
|
|
448
|
-
if (requestedRemoteSessionId && requestedRemoteSessionId !== stored.remoteSessionId)
|
|
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
|
-
}
|
|
456
|
-
const scope = await resolveFilesystemScope(this.options.filesystem, stored.workingDirectory);
|
|
457
|
-
// A resumed session needs its credentials again; whether this run has an account is the server's call.
|
|
458
|
-
const credentials = await this.runCredentials(runId, this.options.fetchRunCredentials === true);
|
|
459
|
-
if (credentials === 'unavailable')
|
|
460
|
-
throw new Error('provider credentials are unavailable for this run');
|
|
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); } }),
|
|
464
|
-
runId, workingDirectory: scope.workingDirectory, additionalDirectories: scope.additionalDirectories,
|
|
465
|
-
prompt: '', remoteSessionId: stored.remoteSessionId, metadata: agentSettingsSchema.parse(stored.config ?? {}),
|
|
466
|
-
...(credentials ? { credentials } : {}),
|
|
467
|
-
adapterState: this.options.state.getAdapterSessionState(runId, stored.adapterId),
|
|
468
|
-
persistAdapterState: (state) => this.options.state.saveAdapterSessionState(runId, stored.adapterId, state),
|
|
469
|
-
}, this.createStream(runId));
|
|
470
|
-
this.sessions.set(runId, session);
|
|
471
|
-
this.scheduleCapabilityRefresh();
|
|
472
|
-
return session;
|
|
473
|
-
}
|
|
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 });
|
|
478
|
-
}
|
|
479
|
-
requireAdapter(adapterId) {
|
|
480
|
-
const adapter = this.adapters.get(adapterId);
|
|
481
|
-
if (!adapter)
|
|
482
|
-
throw new Error(`adapter is not installed: ${adapterId}`);
|
|
483
|
-
return adapter;
|
|
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
|
-
*/
|
|
518
|
-
async emit(runId, event, execution = this.executions.get(runId)) {
|
|
519
|
-
if (this.shuttingDown && ['completed', 'failed', 'cancelled'].includes(event.type))
|
|
520
|
-
return;
|
|
521
|
-
const stored = {
|
|
522
|
-
protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
|
|
523
|
-
...(execution ? { execution } : {}),
|
|
524
|
-
eventId: randomUUID(), environmentId: this.options.environmentId, runId,
|
|
525
|
-
occurredAt: Date.now(), ...event,
|
|
526
|
-
};
|
|
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
|
-
});
|
|
569
|
-
}
|
|
570
|
-
acknowledge(command, accepted, message, errorCode = 'command_rejected') {
|
|
571
|
-
return this.options.controlPlane.acknowledgeCommand({
|
|
572
|
-
protocolVersion: OVERLAY_AGENT_PROTOCOL_VERSION,
|
|
573
|
-
commandId: command.commandId,
|
|
574
|
-
environmentId: this.options.environmentId,
|
|
575
|
-
accepted,
|
|
576
|
-
...(!accepted ? { error: { code: errorCode, message: message ?? 'command rejected' } } : {}),
|
|
577
|
-
});
|
|
578
58
|
}
|
|
579
59
|
}
|
|
580
|
-
function safeError(error) {
|
|
581
|
-
|
|
60
|
+
function safeError(error) {
|
|
61
|
+
return error instanceof Error ? error.message.slice(0, 500) : String(error).slice(0, 500);
|
|
62
|
+
}
|
|
582
63
|
//# sourceMappingURL=runtime.js.map
|