@neta-art/cohub-cli 10.24.0 → 10.25.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/bin/cohub.js +4 -1
- package/dist/board-gpu/page.js +1566 -71230
- package/dist/bootstrap.js +67 -27
- package/dist/build.json +1 -1
- package/dist/{board-kernel/FilterPipe.js → chunks/Geometry.js} +10447 -10469
- package/dist/chunks/about.js +102 -0
- package/dist/chunks/app-realtime.js +2216 -0
- package/dist/chunks/app-realtime2.js +2 -0
- package/dist/chunks/app-ref.js +88 -0
- package/dist/chunks/apps.js +1423 -0
- package/dist/chunks/auth.js +175 -0
- package/dist/chunks/avatar.js +146 -0
- package/dist/chunks/board-export-resources.js +232 -0
- package/dist/chunks/board-export.js +874 -0
- package/dist/chunks/board-export2.js +2 -0
- package/dist/{board-kernel.js → chunks/board-kernel.js} +18032 -28512
- package/dist/chunks/board-kernel2.js +4 -0
- package/dist/chunks/board-profile.js +69 -0
- package/dist/chunks/board-simulate.js +315 -0
- package/dist/chunks/board-time.js +34 -0
- package/dist/chunks/boards.js +1943 -0
- package/dist/{board-kernel → chunks}/browserAll.js +9 -8
- package/dist/chunks/channels.js +64 -0
- package/dist/chunks/client.js +12606 -0
- package/dist/chunks/command-input.js +17 -0
- package/dist/chunks/commander.js +2962 -0
- package/dist/chunks/cron-jobs.js +163 -0
- package/dist/chunks/daemon.js +545 -0
- package/dist/chunks/daemon2.js +2 -0
- package/dist/chunks/desktop.js +172 -0
- package/dist/chunks/endpoint-options.js +26 -0
- package/dist/chunks/env-proxy.js +35 -0
- package/dist/chunks/environment.js +154 -0
- package/dist/chunks/feedback.js +120 -0
- package/dist/chunks/generations.js +379 -0
- package/dist/chunks/host.js +9 -0
- package/dist/chunks/http-put.js +131 -0
- package/dist/chunks/id.js +2416 -0
- package/dist/{board-kernel → chunks}/init.js +1 -1
- package/dist/chunks/install.js +11959 -0
- package/dist/chunks/launch.js +374 -0
- package/dist/chunks/local-media.js +47 -0
- package/dist/chunks/me.js +134 -0
- package/dist/chunks/media.js +315 -0
- package/dist/chunks/models.js +242 -0
- package/dist/chunks/operands.js +46 -0
- package/dist/chunks/package-paths.js +13 -0
- package/dist/chunks/policy.js +221 -0
- package/dist/chunks/preferences.js +29 -0
- package/dist/chunks/profile.js +64 -0
- package/dist/chunks/prompts.js +41 -0
- package/dist/chunks/public.js +2 -0
- package/dist/chunks/public2.js +244 -0
- package/dist/chunks/references.js +197 -0
- package/dist/chunks/referrals.js +90 -0
- package/dist/chunks/rolldown-runtime.js +26 -0
- package/dist/chunks/rooms-connect.js +2 -0
- package/dist/chunks/rooms-connect2.js +151 -0
- package/dist/chunks/rooms-rtc.js +309 -0
- package/dist/chunks/rooms.js +211 -0
- package/dist/chunks/run.js +220 -0
- package/dist/chunks/runtime.js +638 -0
- package/dist/chunks/runtime2.js +286 -0
- package/dist/chunks/runtimes.js +48 -0
- package/dist/chunks/safe-remote-image.js +198 -0
- package/dist/chunks/schemas.js +6017 -0
- package/dist/chunks/search.js +113 -0
- package/dist/chunks/self-update.js +238 -0
- package/dist/chunks/serve.js +1246 -0
- package/dist/chunks/session-status.js +24 -0
- package/dist/chunks/skills.js +35 -0
- package/dist/chunks/spaces.js +5080 -0
- package/dist/chunks/src.js +405 -0
- package/dist/chunks/supervisor.js +2511 -0
- package/dist/chunks/supervisor2.js +2 -0
- package/dist/chunks/tasks.js +82 -0
- package/dist/chunks/themes.js +2898 -0
- package/dist/chunks/version.js +2 -0
- package/dist/chunks/version2.js +22 -0
- package/dist/chunks/version3.js +18 -0
- package/dist/chunks/web.js +7 -0
- package/dist/{board-kernel → chunks}/webworkerAll.js +1 -1
- package/dist/runtime/native/pi-extension.js +174 -166
- package/dist/runtime/worker.js +27 -16
- package/package.json +8 -9
- package/dist/about.d.ts +0 -2
- package/dist/about.js +0 -71
- package/dist/app-download.d.ts +0 -11
- package/dist/app-download.js +0 -252
- package/dist/app-ref.d.ts +0 -5
- package/dist/app-ref.js +0 -8
- package/dist/app-target.d.ts +0 -26
- package/dist/app-target.js +0 -55
- package/dist/auth.d.ts +0 -45
- package/dist/auth.js +0 -307
- package/dist/avatar.d.ts +0 -55
- package/dist/avatar.js +0 -104
- package/dist/board-command-support.d.ts +0 -6
- package/dist/board-command-support.js +0 -88
- package/dist/board-export-resources.d.ts +0 -12
- package/dist/board-export-resources.js +0 -51
- package/dist/board-export.d.ts +0 -110
- package/dist/board-export.js +0 -592
- package/dist/board-fonts.d.ts +0 -11
- package/dist/board-fonts.js +0 -10
- package/dist/board-gpu/daemon.d.ts +0 -11
- package/dist/board-gpu/daemon.js +0 -295
- package/dist/board-gpu/index.d.ts +0 -33
- package/dist/board-gpu/index.js +0 -189
- package/dist/board-gpu/protocol.d.ts +0 -77
- package/dist/board-gpu/protocol.js +0 -1
- package/dist/board-kernel.d.ts +0 -5
- package/dist/board-media-export.d.ts +0 -17
- package/dist/board-media-export.js +0 -164
- package/dist/board-media.d.ts +0 -5
- package/dist/board-media.js +0 -66
- package/dist/board-profile.d.ts +0 -21
- package/dist/board-profile.js +0 -67
- package/dist/board-simulate.d.ts +0 -67
- package/dist/board-simulate.js +0 -259
- package/dist/board-time.d.ts +0 -3
- package/dist/board-time.js +0 -34
- package/dist/bootstrap.d.ts +0 -2
- package/dist/client.d.ts +0 -5
- package/dist/client.js +0 -24
- package/dist/command-input.d.ts +0 -4
- package/dist/command-input.js +0 -16
- package/dist/commands/app-commerce.d.ts +0 -2
- package/dist/commands/app-commerce.js +0 -228
- package/dist/commands/app-domains.d.ts +0 -2
- package/dist/commands/app-domains.js +0 -133
- package/dist/commands/apps.d.ts +0 -4
- package/dist/commands/apps.js +0 -827
- package/dist/commands/auth.d.ts +0 -2
- package/dist/commands/auth.js +0 -186
- package/dist/commands/boards/authoring.d.ts +0 -2
- package/dist/commands/boards/authoring.js +0 -166
- package/dist/commands/boards/examples.d.ts +0 -10
- package/dist/commands/boards/examples.js +0 -118
- package/dist/commands/boards.d.ts +0 -13
- package/dist/commands/boards.js +0 -836
- package/dist/commands/channels.d.ts +0 -2
- package/dist/commands/channels.js +0 -74
- package/dist/commands/cron-jobs.d.ts +0 -2
- package/dist/commands/cron-jobs.js +0 -155
- package/dist/commands/decision.d.ts +0 -4
- package/dist/commands/decision.js +0 -113
- package/dist/commands/desktop.d.ts +0 -10
- package/dist/commands/desktop.js +0 -233
- package/dist/commands/feedback.d.ts +0 -2
- package/dist/commands/feedback.js +0 -131
- package/dist/commands/generations.d.ts +0 -2
- package/dist/commands/generations.js +0 -427
- package/dist/commands/host.d.ts +0 -2
- package/dist/commands/host.js +0 -11
- package/dist/commands/me.d.ts +0 -2
- package/dist/commands/me.js +0 -121
- package/dist/commands/models.d.ts +0 -28
- package/dist/commands/models.js +0 -271
- package/dist/commands/profile.d.ts +0 -2
- package/dist/commands/profile.js +0 -81
- package/dist/commands/prompts.d.ts +0 -2
- package/dist/commands/prompts.js +0 -37
- package/dist/commands/public.d.ts +0 -20
- package/dist/commands/public.js +0 -291
- package/dist/commands/references.d.ts +0 -2
- package/dist/commands/references.js +0 -193
- package/dist/commands/referrals.d.ts +0 -2
- package/dist/commands/referrals.js +0 -88
- package/dist/commands/rooms-connect.d.ts +0 -17
- package/dist/commands/rooms-connect.js +0 -140
- package/dist/commands/rooms-rtc-binary.d.ts +0 -2
- package/dist/commands/rooms-rtc-binary.js +0 -107
- package/dist/commands/rooms-rtc.d.ts +0 -21
- package/dist/commands/rooms-rtc.js +0 -171
- package/dist/commands/rooms.d.ts +0 -3
- package/dist/commands/rooms.js +0 -277
- package/dist/commands/run.d.ts +0 -13
- package/dist/commands/run.js +0 -246
- package/dist/commands/runtime.d.ts +0 -3
- package/dist/commands/runtime.js +0 -320
- package/dist/commands/sandboxd-binary.d.ts +0 -11
- package/dist/commands/sandboxd-binary.js +0 -238
- package/dist/commands/search.d.ts +0 -2
- package/dist/commands/search.js +0 -114
- package/dist/commands/session-access.d.ts +0 -2
- package/dist/commands/session-access.js +0 -70
- package/dist/commands/skills.d.ts +0 -2
- package/dist/commands/skills.js +0 -34
- package/dist/commands/space-activity.d.ts +0 -26
- package/dist/commands/space-activity.js +0 -147
- package/dist/commands/space-commerce.d.ts +0 -2
- package/dist/commands/space-commerce.js +0 -514
- package/dist/commands/space-displays.d.ts +0 -2
- package/dist/commands/space-displays.js +0 -620
- package/dist/commands/space-files.d.ts +0 -5
- package/dist/commands/space-files.js +0 -215
- package/dist/commands/space-invitations.d.ts +0 -29
- package/dist/commands/space-invitations.js +0 -189
- package/dist/commands/space-turns.d.ts +0 -49
- package/dist/commands/space-turns.js +0 -205
- package/dist/commands/space-wallet.d.ts +0 -2
- package/dist/commands/space-wallet.js +0 -141
- package/dist/commands/space-webhooks.d.ts +0 -7
- package/dist/commands/space-webhooks.js +0 -73
- package/dist/commands/spaces.d.ts +0 -25
- package/dist/commands/spaces.js +0 -2170
- package/dist/commands/tasks.d.ts +0 -8
- package/dist/commands/tasks.js +0 -80
- package/dist/commands/version.d.ts +0 -2
- package/dist/commands/version.js +0 -21
- package/dist/endpoint-options.d.ts +0 -4
- package/dist/endpoint-options.js +0 -26
- package/dist/env-proxy.d.ts +0 -5
- package/dist/env-proxy.js +0 -20
- package/dist/help-path.d.ts +0 -18
- package/dist/help-path.js +0 -223
- package/dist/host/auth.d.ts +0 -20
- package/dist/host/auth.js +0 -119
- package/dist/host/login-env.d.ts +0 -1
- package/dist/host/login-env.js +0 -31
- package/dist/host/runtime.d.ts +0 -35
- package/dist/host/runtime.js +0 -395
- package/dist/host/runtimes.d.ts +0 -9
- package/dist/host/runtimes.js +0 -42
- package/dist/host/serve.d.ts +0 -2
- package/dist/host/serve.js +0 -117
- package/dist/host/workspaces.d.ts +0 -2
- package/dist/host/workspaces.js +0 -18
- package/dist/http-put.d.ts +0 -25
- package/dist/http-put.js +0 -132
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -129
- package/dist/launcher.d.ts +0 -4
- package/dist/launcher.js +0 -38
- package/dist/local-media.d.ts +0 -2
- package/dist/local-media.js +0 -30
- package/dist/network-error.d.ts +0 -3
- package/dist/network-error.js +0 -22
- package/dist/output.d.ts +0 -46
- package/dist/output.js +0 -244
- package/dist/runtime/archive-store.d.ts +0 -54
- package/dist/runtime/archive-store.js +0 -379
- package/dist/runtime/cli-path.d.ts +0 -5
- package/dist/runtime/cli-path.js +0 -27
- package/dist/runtime/codex-usage.d.ts +0 -7
- package/dist/runtime/codex-usage.js +0 -11
- package/dist/runtime/connection.d.ts +0 -42
- package/dist/runtime/connection.js +0 -789
- package/dist/runtime/diagnostics.d.ts +0 -107
- package/dist/runtime/diagnostics.js +0 -392
- package/dist/runtime/harnesses/chained-projection.d.ts +0 -40
- package/dist/runtime/harnesses/chained-projection.js +0 -95
- package/dist/runtime/harnesses/chained-transcript.d.ts +0 -24
- package/dist/runtime/harnesses/chained-transcript.js +0 -62
- package/dist/runtime/harnesses/claude-approval.d.ts +0 -34
- package/dist/runtime/harnesses/claude-approval.js +0 -124
- package/dist/runtime/harnesses/claude-transcript.d.ts +0 -8
- package/dist/runtime/harnesses/claude-transcript.js +0 -138
- package/dist/runtime/harnesses/claude.d.ts +0 -8
- package/dist/runtime/harnesses/claude.js +0 -225
- package/dist/runtime/harnesses/codex-approval.d.ts +0 -25
- package/dist/runtime/harnesses/codex-approval.js +0 -69
- package/dist/runtime/harnesses/codex.d.ts +0 -4
- package/dist/runtime/harnesses/codex.js +0 -269
- package/dist/runtime/harnesses/cursor-transcript.d.ts +0 -37
- package/dist/runtime/harnesses/cursor-transcript.js +0 -183
- package/dist/runtime/harnesses/cursor.d.ts +0 -24
- package/dist/runtime/harnesses/cursor.js +0 -620
- package/dist/runtime/harnesses/index.d.ts +0 -16
- package/dist/runtime/harnesses/index.js +0 -73
- package/dist/runtime/harnesses/pi.d.ts +0 -4
- package/dist/runtime/harnesses/pi.js +0 -247
- package/dist/runtime/harnesses/process.d.ts +0 -31
- package/dist/runtime/harnesses/process.js +0 -75
- package/dist/runtime/harnesses/stream-json.d.ts +0 -48
- package/dist/runtime/harnesses/stream-json.js +0 -336
- package/dist/runtime/harnesses/types.d.ts +0 -117
- package/dist/runtime/harnesses/types.js +0 -1
- package/dist/runtime/harnesses/workbuddy-transcript.d.ts +0 -8
- package/dist/runtime/harnesses/workbuddy-transcript.js +0 -127
- package/dist/runtime/harnesses/workbuddy.d.ts +0 -21
- package/dist/runtime/harnesses/workbuddy.js +0 -123
- package/dist/runtime/instance.d.ts +0 -20
- package/dist/runtime/instance.js +0 -247
- package/dist/runtime/json-rpc.d.ts +0 -53
- package/dist/runtime/json-rpc.js +0 -212
- package/dist/runtime/launch.d.ts +0 -25
- package/dist/runtime/launch.js +0 -247
- package/dist/runtime/local-workspace.d.ts +0 -15
- package/dist/runtime/local-workspace.js +0 -52
- package/dist/runtime/model-catalog.d.ts +0 -12
- package/dist/runtime/model-catalog.js +0 -84
- package/dist/runtime/native/adapters.d.ts +0 -15
- package/dist/runtime/native/adapters.js +0 -11
- package/dist/runtime/native/approvals.d.ts +0 -18
- package/dist/runtime/native/approvals.js +0 -54
- package/dist/runtime/native/archive.d.ts +0 -19
- package/dist/runtime/native/archive.js +0 -142
- package/dist/runtime/native/attach.d.ts +0 -36
- package/dist/runtime/native/attach.js +0 -128
- package/dist/runtime/native/codex-link.d.ts +0 -60
- package/dist/runtime/native/codex-link.js +0 -322
- package/dist/runtime/native/config.d.ts +0 -16
- package/dist/runtime/native/config.js +0 -24
- package/dist/runtime/native/daemon.d.ts +0 -92
- package/dist/runtime/native/daemon.js +0 -380
- package/dist/runtime/native/execution.d.ts +0 -26
- package/dist/runtime/native/execution.js +0 -34
- package/dist/runtime/native/identity.d.ts +0 -9
- package/dist/runtime/native/identity.js +0 -15
- package/dist/runtime/native/ingest.d.ts +0 -263
- package/dist/runtime/native/ingest.js +0 -884
- package/dist/runtime/native/install.d.ts +0 -9
- package/dist/runtime/native/install.js +0 -113
- package/dist/runtime/native/paths.d.ts +0 -2
- package/dist/runtime/native/paths.js +0 -7
- package/dist/runtime/native/pi-extension.d.ts +0 -36
- package/dist/runtime/native/pi-link.d.ts +0 -69
- package/dist/runtime/native/pi-link.js +0 -269
- package/dist/runtime/native/results.d.ts +0 -41
- package/dist/runtime/native/results.js +0 -128
- package/dist/runtime/native/sessions.d.ts +0 -45
- package/dist/runtime/native/sessions.js +0 -87
- package/dist/runtime/native/transcript.d.ts +0 -89
- package/dist/runtime/native/transcript.js +0 -656
- package/dist/runtime/native/translate.d.ts +0 -46
- package/dist/runtime/native/translate.js +0 -299
- package/dist/runtime/native/transport.d.ts +0 -7
- package/dist/runtime/native/transport.js +0 -16
- package/dist/runtime/native/version.d.ts +0 -5
- package/dist/runtime/native/version.js +0 -21
- package/dist/runtime/preferences.d.ts +0 -7
- package/dist/runtime/preferences.js +0 -22
- package/dist/runtime/presentation.d.ts +0 -32
- package/dist/runtime/presentation.js +0 -124
- package/dist/runtime/process-group.d.ts +0 -5
- package/dist/runtime/process-group.js +0 -161
- package/dist/runtime/projection-store.d.ts +0 -27
- package/dist/runtime/projection-store.js +0 -30
- package/dist/runtime/space-binding.d.ts +0 -48
- package/dist/runtime/space-binding.js +0 -342
- package/dist/runtime/supervisor.d.ts +0 -19
- package/dist/runtime/supervisor.js +0 -441
- package/dist/runtime/turn-projection.d.ts +0 -41
- package/dist/runtime/turn-projection.js +0 -120
- package/dist/runtime/worker.d.ts +0 -1
- package/dist/safe-remote-image.d.ts +0 -36
- package/dist/safe-remote-image.js +0 -191
- package/dist/self-update.d.ts +0 -7
- package/dist/self-update.js +0 -202
- package/dist/session-status.d.ts +0 -10
- package/dist/session-status.js +0 -25
- package/dist/space-files/limit.d.ts +0 -2
- package/dist/space-files/limit.js +0 -16
- package/dist/space-files/operands.d.ts +0 -17
- package/dist/space-files/operands.js +0 -33
- package/dist/space-files/transfer.d.ts +0 -53
- package/dist/space-files/transfer.js +0 -297
- package/dist/space-files/upload.d.ts +0 -17
- package/dist/space-files/upload.js +0 -76
- package/dist/space.d.ts +0 -44
- package/dist/space.js +0 -192
- package/dist/version.d.ts +0 -2
- package/dist/version.js +0 -17
- package/dist/web.d.ts +0 -1
- package/dist/web.js +0 -4
- /package/dist/{board-kernel → chunks}/lexer.js +0 -0
|
@@ -0,0 +1,2511 @@
|
|
|
1
|
+
import { t as packagePath } from "./package-paths.js";
|
|
2
|
+
import { t as CLI_VERSION } from "./version2.js";
|
|
3
|
+
import { a as runtimeCapabilitiesSchema, b as assertHarnessAccess, c as runtimeHelloCapabilities, l as runtimeReadySchema, m as runtimeNativeStopSchema, n as RUNTIME_MAX_FRAME_BYTES, o as runtimeCommandSchema, p as runtimeApprovalDecisionSchema, s as runtimeEventSchema } from "./runtime.js";
|
|
4
|
+
import { F as AuthRequiredError, P as describeError, W as resolveAccessToken, Y as readRuntimeSpaceBindings, c as ownRuntimeInstance, h as currentIdentityKey, o as UNCONFIRMED_WORK, t as createClient, u as runtimeInstanceDirectory } from "./client.js";
|
|
5
|
+
import { A as formatVersion, B as closeHost, E as CodexShared, F as piTranslator, G as RuntimeDiagnostics, H as ProcessCleanupUncertainError, I as ArchiveNotRestorableError, J as serializeDiagnosticError, L as PI_MIN_VERSION, M as SizeLimitError, N as LiveProgress, P as codexTranslator, R as PiLink, S as harnessAdapter, U as confirmQuiescentProcessGroup, V as record$1, Y as serializeProjectionRecords, a as NativeIngest, b as atomicRuntimeJson, c as runtimeStateRoot, d as createDiagnosticConsole, j as harnessVersion, k as atLeast, n as piExtensionSource, r as piExtensionState, s as readNativeConfig, v as readTranscript, w as refreshHarnesses, x as discoverHarnesses, y as RuntimeArchiveStore, z as controlSocketPath } from "./install.js";
|
|
6
|
+
import { d as resolveWebsocketUrl } from "./environment.js";
|
|
7
|
+
import { t as readRuntimePreferences } from "./preferences.js";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { homedir, tmpdir } from "node:os";
|
|
10
|
+
import { createReadStream, createWriteStream, mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { delimiter, dirname, join } from "node:path";
|
|
12
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
13
|
+
import { createServer } from "node:net";
|
|
14
|
+
import { createInterface } from "node:readline";
|
|
15
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
16
|
+
import { PassThrough, Readable } from "node:stream";
|
|
17
|
+
import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
18
|
+
import { pipeline } from "node:stream/promises";
|
|
19
|
+
import { isDeepStrictEqual } from "node:util";
|
|
20
|
+
const BINARY_NAME = "cohub-sandboxd";
|
|
21
|
+
const binaryName = (goos) => goos === "windows" ? `${BINARY_NAME}.exe` : BINARY_NAME;
|
|
22
|
+
const cdnBaseUrl = () => (process.env.COHUB_SANDBOXD_CDN_BASE_URL?.trim() || "https://public.cohub.live/sandboxd").replace(/\/+$/, "");
|
|
23
|
+
const DOWNLOAD_TIMEOUT_MS = 12e4;
|
|
24
|
+
const LOCK_STALE_MS = 3e5;
|
|
25
|
+
const GOOS_BY_PLATFORM = {
|
|
26
|
+
darwin: "darwin",
|
|
27
|
+
linux: "linux",
|
|
28
|
+
win32: "windows"
|
|
29
|
+
};
|
|
30
|
+
const GOARCH_BY_ARCH = {
|
|
31
|
+
x64: "amd64",
|
|
32
|
+
arm64: "arm64"
|
|
33
|
+
};
|
|
34
|
+
var SandboxdDownloadError = class extends Error {
|
|
35
|
+
name = "SandboxdDownloadError";
|
|
36
|
+
};
|
|
37
|
+
const resolveTarget = () => {
|
|
38
|
+
const goos = GOOS_BY_PLATFORM[process.platform];
|
|
39
|
+
const goarch = GOARCH_BY_ARCH[process.arch];
|
|
40
|
+
if (!goos || !goarch) throw new SandboxdDownloadError(`Unsupported platform ${process.platform}/${process.arch}. Set COHUB_SANDBOXD_BIN to a locally built binary.`);
|
|
41
|
+
return {
|
|
42
|
+
goos,
|
|
43
|
+
goarch
|
|
44
|
+
};
|
|
45
|
+
};
|
|
46
|
+
const cacheDir = (version) => join(homedir(), ".cache", "cohub", "sandboxd", version);
|
|
47
|
+
const cachedBinaryPath = (version, target) => join(cacheDir(version), binaryName(target.goos));
|
|
48
|
+
const archiveName = (version, target) => `${BINARY_NAME}_${version}_${target.goos}_${target.goarch}.tar.gz`;
|
|
49
|
+
const isExecutableFile = async (path) => {
|
|
50
|
+
const info = await lstat(path).catch(() => null);
|
|
51
|
+
return Boolean(info?.isFile());
|
|
52
|
+
};
|
|
53
|
+
const isSafeArchiveFile = async (path) => {
|
|
54
|
+
const info = await lstat(path).catch(() => null);
|
|
55
|
+
return Boolean(info?.isFile() && info.nlink === 1);
|
|
56
|
+
};
|
|
57
|
+
const sha256File = async (path) => {
|
|
58
|
+
const hash = createHash("sha256");
|
|
59
|
+
await pipeline(createReadStream(path), hash);
|
|
60
|
+
return hash.digest("hex");
|
|
61
|
+
};
|
|
62
|
+
const withTimeout = async (what, fn) => {
|
|
63
|
+
const controller = new AbortController();
|
|
64
|
+
const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
|
|
65
|
+
try {
|
|
66
|
+
return await fn(controller.signal);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
if (err instanceof SandboxdDownloadError) throw err;
|
|
69
|
+
if (controller.signal.aborted) throw new SandboxdDownloadError(`${what} timed out after ${DOWNLOAD_TIMEOUT_MS / 1e3}s`);
|
|
70
|
+
throw new SandboxdDownloadError(`${what} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
71
|
+
} finally {
|
|
72
|
+
clearTimeout(timer);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const downloadToFile = (url, accept, destPath) => withTimeout(`Download of ${url}`, async (signal) => {
|
|
76
|
+
const response = await fetch(url, {
|
|
77
|
+
signal,
|
|
78
|
+
headers: { accept }
|
|
79
|
+
});
|
|
80
|
+
if (!response.ok) throw new SandboxdDownloadError(`Download failed (${response.status}) for ${url}`);
|
|
81
|
+
if (!response.body) throw new SandboxdDownloadError(`Empty response body for ${url}`);
|
|
82
|
+
await pipeline(Readable.fromWeb(response.body), createWriteStream(destPath));
|
|
83
|
+
});
|
|
84
|
+
const fetchText = (url, accept) => withTimeout(`Download of ${url}`, async (signal) => {
|
|
85
|
+
const response = await fetch(url, {
|
|
86
|
+
signal,
|
|
87
|
+
headers: { accept }
|
|
88
|
+
});
|
|
89
|
+
if (!response.ok) throw new SandboxdDownloadError(`Download failed (${response.status}) for ${url}`);
|
|
90
|
+
return (await response.text()).trim();
|
|
91
|
+
});
|
|
92
|
+
function validSandboxdArchiveEntries(entries, goos) {
|
|
93
|
+
const expected = [
|
|
94
|
+
binaryName(goos),
|
|
95
|
+
"LICENSE",
|
|
96
|
+
"NOTICE"
|
|
97
|
+
];
|
|
98
|
+
return entries.length === expected.length && expected.every((entry) => entries.includes(entry));
|
|
99
|
+
}
|
|
100
|
+
const tarCommand = () => {
|
|
101
|
+
if (process.platform !== "win32") return "tar";
|
|
102
|
+
if (!process.env.SystemRoot) throw new SandboxdDownloadError("SystemRoot is not set; cannot locate tar.exe");
|
|
103
|
+
return join(process.env.SystemRoot, "System32", "tar.exe");
|
|
104
|
+
};
|
|
105
|
+
const listTarGz = (archivePath, verbose = false) => new Promise((res, rej) => {
|
|
106
|
+
const child = spawn(tarCommand(), [verbose ? "-tvzf" : "-tzf", archivePath], { stdio: [
|
|
107
|
+
"ignore",
|
|
108
|
+
"pipe",
|
|
109
|
+
"pipe"
|
|
110
|
+
] });
|
|
111
|
+
let stdout = "";
|
|
112
|
+
let stderr = "";
|
|
113
|
+
child.stdout.on("data", (chunk) => {
|
|
114
|
+
stdout += chunk.toString();
|
|
115
|
+
});
|
|
116
|
+
child.stderr.on("data", (chunk) => {
|
|
117
|
+
stderr += chunk.toString();
|
|
118
|
+
});
|
|
119
|
+
child.on("error", rej);
|
|
120
|
+
child.on("close", (code) => code === 0 ? res(stdout.split("\n").map((line) => line.trim()).filter(Boolean)) : rej(new SandboxdDownloadError(`tar listing failed: ${stderr.trim() || `exit ${code}`}`)));
|
|
121
|
+
});
|
|
122
|
+
async function validateSandboxdArchive(archivePath, goos) {
|
|
123
|
+
const entries = await listTarGz(archivePath);
|
|
124
|
+
if (!validSandboxdArchiveEntries(entries, goos)) throw new SandboxdDownloadError(`Unexpected sandbox archive contents: ${entries.join(", ") || "(empty)"}`);
|
|
125
|
+
const details = await listTarGz(archivePath, true);
|
|
126
|
+
if (details.length !== entries.length || details.some((line) => !line.startsWith("-") || /(?: link to | -> | == )/.test(line))) throw new SandboxdDownloadError("Sandbox archive must contain only regular files");
|
|
127
|
+
return entries;
|
|
128
|
+
}
|
|
129
|
+
const extractTarGz = (archivePath, cwd) => new Promise((res, rej) => {
|
|
130
|
+
const child = spawn(tarCommand(), [
|
|
131
|
+
"-xzf",
|
|
132
|
+
archivePath,
|
|
133
|
+
"-C",
|
|
134
|
+
cwd
|
|
135
|
+
], { stdio: [
|
|
136
|
+
"ignore",
|
|
137
|
+
"ignore",
|
|
138
|
+
"pipe"
|
|
139
|
+
] });
|
|
140
|
+
let stderr = "";
|
|
141
|
+
child.stderr.on("data", (chunk) => {
|
|
142
|
+
stderr += chunk.toString();
|
|
143
|
+
});
|
|
144
|
+
child.on("error", rej);
|
|
145
|
+
child.on("close", (code) => code === 0 ? res() : rej(new SandboxdDownloadError(`tar extraction failed: ${stderr.trim() || `exit ${code}`}`)));
|
|
146
|
+
});
|
|
147
|
+
const withLock = async (version, fn) => {
|
|
148
|
+
const lockPath = join(cacheDir(version), ".download.lock");
|
|
149
|
+
await mkdir(dirname(lockPath), { recursive: true });
|
|
150
|
+
for (let attempt = 0; attempt < 600; attempt += 1) try {
|
|
151
|
+
await mkdir(lockPath);
|
|
152
|
+
try {
|
|
153
|
+
return await fn();
|
|
154
|
+
} finally {
|
|
155
|
+
await rm(lockPath, {
|
|
156
|
+
recursive: true,
|
|
157
|
+
force: true
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
} catch (err) {
|
|
161
|
+
if (err.code !== "EEXIST") throw err;
|
|
162
|
+
const info = await stat(lockPath).catch(() => null);
|
|
163
|
+
if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
|
|
164
|
+
await rm(lockPath, {
|
|
165
|
+
recursive: true,
|
|
166
|
+
force: true
|
|
167
|
+
}).catch(() => void 0);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
171
|
+
}
|
|
172
|
+
throw new SandboxdDownloadError("Timed out waiting for the sandboxd download lock");
|
|
173
|
+
};
|
|
174
|
+
const downloadAndVerify = async (version, target) => {
|
|
175
|
+
const name = archiveName(version, target);
|
|
176
|
+
const archiveUrl = `${cdnBaseUrl()}/${version}/${name}`;
|
|
177
|
+
const checksumUrl = `${archiveUrl}.sha256`;
|
|
178
|
+
const tempDir = await mkdtemp(join(tmpdir(), "cohub-sandboxd-"));
|
|
179
|
+
try {
|
|
180
|
+
const archivePath = join(tempDir, name);
|
|
181
|
+
await downloadToFile(archiveUrl, "application/gzip", archivePath);
|
|
182
|
+
const expected = (await fetchText(checksumUrl, "text/plain")).split(/\s+/)[0]?.toLowerCase();
|
|
183
|
+
if (!expected || !/^[0-9a-f]{64}$/.test(expected)) throw new SandboxdDownloadError(`Invalid checksum manifest for ${name}`);
|
|
184
|
+
const actual = (await sha256File(archivePath)).toLowerCase();
|
|
185
|
+
if (actual !== expected) throw new SandboxdDownloadError(`Checksum mismatch for ${name} (expected ${expected}, got ${actual})`);
|
|
186
|
+
const entries = await validateSandboxdArchive(archivePath, target.goos);
|
|
187
|
+
await extractTarGz(archivePath, tempDir);
|
|
188
|
+
for (const entry of entries) if (!await isSafeArchiveFile(join(tempDir, entry))) throw new SandboxdDownloadError(`Unsafe sandbox archive entry: ${entry}`);
|
|
189
|
+
const extractedBinary = join(tempDir, binaryName(target.goos));
|
|
190
|
+
if (!await isSafeArchiveFile(extractedBinary)) throw new SandboxdDownloadError(`Archive ${name} did not contain ${binaryName(target.goos)}`);
|
|
191
|
+
const dest = cachedBinaryPath(version, target);
|
|
192
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
193
|
+
await rename(extractedBinary, dest).catch(async (err) => {
|
|
194
|
+
if (err.code !== "EXDEV") throw err;
|
|
195
|
+
await copyFile(extractedBinary, dest);
|
|
196
|
+
});
|
|
197
|
+
await chmod(dest, 493);
|
|
198
|
+
return dest;
|
|
199
|
+
} finally {
|
|
200
|
+
await rm(tempDir, {
|
|
201
|
+
recursive: true,
|
|
202
|
+
force: true
|
|
203
|
+
}).catch(() => void 0);
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
const ensureSandboxdBinary = async (options = {}) => {
|
|
207
|
+
const override = process.env.COHUB_SANDBOXD_BIN?.trim();
|
|
208
|
+
if (override) {
|
|
209
|
+
if (!await isExecutableFile(override)) throw new SandboxdDownloadError(`COHUB_SANDBOXD_BIN=${override} is not a file`);
|
|
210
|
+
return override;
|
|
211
|
+
}
|
|
212
|
+
const version = options.version?.trim() || "v2.95.0";
|
|
213
|
+
const target = resolveTarget();
|
|
214
|
+
const cached = cachedBinaryPath(version, target);
|
|
215
|
+
if (await isExecutableFile(cached)) return cached;
|
|
216
|
+
return withLock(version, async () => {
|
|
217
|
+
if (await isExecutableFile(cached)) return cached;
|
|
218
|
+
options.onStatus?.(`Downloading sandbox runtime ${version} (${target.goos}/${target.goarch})`);
|
|
219
|
+
const path = await downloadAndVerify(version, target);
|
|
220
|
+
options.onStatus?.("Sandbox runtime ready");
|
|
221
|
+
return path;
|
|
222
|
+
});
|
|
223
|
+
};
|
|
224
|
+
//#endregion
|
|
225
|
+
//#region src/runtime/native/execution.ts
|
|
226
|
+
/** Run one Cohub Turn in a local harness through its adapter. */
|
|
227
|
+
async function executeTurn(executor, input, emit, signal, requestId, context) {
|
|
228
|
+
signal.throwIfAborted();
|
|
229
|
+
assertHarnessAccess(input.harness, input.accessMode);
|
|
230
|
+
const diverged = await executor.results.admit(input);
|
|
231
|
+
const started = async (session) => {
|
|
232
|
+
await executor.results.start(session, input, requestId);
|
|
233
|
+
executor.ingest.begin(session, input.sessionId, input.turnId);
|
|
234
|
+
};
|
|
235
|
+
const turn = {
|
|
236
|
+
input,
|
|
237
|
+
emit,
|
|
238
|
+
signal,
|
|
239
|
+
diverged,
|
|
240
|
+
started,
|
|
241
|
+
context
|
|
242
|
+
};
|
|
243
|
+
let run;
|
|
244
|
+
try {
|
|
245
|
+
run = await harnessAdapter(input.harness).run(executor, turn);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
executor.ingest.end(input.turnId);
|
|
248
|
+
throw error;
|
|
249
|
+
}
|
|
250
|
+
let uncertainCleanup;
|
|
251
|
+
if (run.host) uncertainCleanup = await closeHost(run.host, run.message.errorMessage);
|
|
252
|
+
const message = signal.aborted ? {
|
|
253
|
+
...run.message,
|
|
254
|
+
stopReason: "aborted"
|
|
255
|
+
} : run.message;
|
|
256
|
+
const archive = !harnessAdapter(input.harness).session.archive ? null : await executor.archives.stage({
|
|
257
|
+
sessionId: input.sessionId,
|
|
258
|
+
harness: input.harness,
|
|
259
|
+
nativeSessionId: run.session.nativeSessionId,
|
|
260
|
+
path: run.session.path
|
|
261
|
+
}, input.turnId).catch((error) => {
|
|
262
|
+
executor.diagnostics?.log("warn", "archive.capture_failed", { error: serializeDiagnosticError(error) }, {
|
|
263
|
+
...context,
|
|
264
|
+
component: "archive"
|
|
265
|
+
});
|
|
266
|
+
return null;
|
|
267
|
+
});
|
|
268
|
+
executor.ingest.advance(run.session.path, input.turnId);
|
|
269
|
+
return {
|
|
270
|
+
session: run.session,
|
|
271
|
+
event: {
|
|
272
|
+
type: "turn.end",
|
|
273
|
+
message,
|
|
274
|
+
resume: run.resume,
|
|
275
|
+
archive
|
|
276
|
+
},
|
|
277
|
+
...uncertainCleanup ? { uncertainCleanup } : {}
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
//#endregion
|
|
281
|
+
//#region src/runtime/native/results.ts
|
|
282
|
+
var ContextRequiredError = class extends Error {};
|
|
283
|
+
const missing = (error) => error?.code === "ENOENT";
|
|
284
|
+
/** One small receipt per Cohub-executed Turn until the server acknowledges its result. */
|
|
285
|
+
var ExecutionResults = class {
|
|
286
|
+
root;
|
|
287
|
+
constructor(root) {
|
|
288
|
+
this.root = root;
|
|
289
|
+
}
|
|
290
|
+
path(sessionId) {
|
|
291
|
+
return join(this.root, "executions", `${sessionId}.json`);
|
|
292
|
+
}
|
|
293
|
+
async read(sessionId) {
|
|
294
|
+
try {
|
|
295
|
+
const receipt = JSON.parse(await readFile(this.path(sessionId), "utf8"));
|
|
296
|
+
if (receipt.version !== 2 || receipt.sessionId !== sessionId) throw new Error("Invalid execution receipt");
|
|
297
|
+
return receipt;
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (missing(error)) return null;
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Admit a new Turn. An unacknowledged earlier Turn is released once the server has settled it;
|
|
305
|
+
* otherwise the server must decide first, so a result is never overwritten unseen.
|
|
306
|
+
*/
|
|
307
|
+
async admit(input) {
|
|
308
|
+
const receipt = await this.read(input.sessionId);
|
|
309
|
+
if (!receipt || receipt.turnId === input.turnId) return null;
|
|
310
|
+
const { resolvedTurnIds, settledTurnIds, complete } = input.context;
|
|
311
|
+
const resolved = resolvedTurnIds?.includes(receipt.turnId) === true;
|
|
312
|
+
if (resolved || settledTurnIds?.includes(receipt.turnId)) {
|
|
313
|
+
await rm(this.path(input.sessionId), { force: true });
|
|
314
|
+
return resolved ? receipt.session.path : null;
|
|
315
|
+
}
|
|
316
|
+
if (complete === false) throw new ContextRequiredError("Server resolution is required for the pending native execution");
|
|
317
|
+
throw new Error(`Local turn ${receipt.turnId} has unconfirmed results; reconcile it before continuing`);
|
|
318
|
+
}
|
|
319
|
+
async start(session, input, requestId) {
|
|
320
|
+
await atomicRuntimeJson(this.path(input.sessionId), {
|
|
321
|
+
version: 2,
|
|
322
|
+
requestId,
|
|
323
|
+
sessionId: input.sessionId,
|
|
324
|
+
turnId: input.turnId,
|
|
325
|
+
session
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
async record(session, input, requestId, events, uncertainCleanup) {
|
|
329
|
+
await atomicRuntimeJson(this.path(input.sessionId), {
|
|
330
|
+
version: 2,
|
|
331
|
+
requestId,
|
|
332
|
+
sessionId: input.sessionId,
|
|
333
|
+
turnId: input.turnId,
|
|
334
|
+
session,
|
|
335
|
+
events,
|
|
336
|
+
...uncertainCleanup ? { uncertainCleanup } : {}
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
async recover(input, requestId) {
|
|
340
|
+
const receipt = await this.read(input.sessionId);
|
|
341
|
+
if (!receipt || receipt.turnId !== input.turnId || receipt.session.harness !== input.harness) return null;
|
|
342
|
+
if (requestId && receipt.requestId != null && receipt.requestId !== requestId) throw new Error("Runtime result execution identity mismatch");
|
|
343
|
+
if (receipt.events) {
|
|
344
|
+
if (receipt.uncertainCleanup && !receipt.uncertainCleanup.confirmedAt) {
|
|
345
|
+
if (!await confirmQuiescentProcessGroup(receipt.uncertainCleanup.processGroupId)) return null;
|
|
346
|
+
receipt.uncertainCleanup.confirmedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
347
|
+
await atomicRuntimeJson(this.path(input.sessionId), receipt);
|
|
348
|
+
}
|
|
349
|
+
return {
|
|
350
|
+
session: receipt.session,
|
|
351
|
+
events: receipt.events.map((event) => runtimeEventSchema.parse(event))
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
const events = await this.fromTranscript(receipt);
|
|
355
|
+
if (!events) return null;
|
|
356
|
+
await this.record(receipt.session, receipt, receipt.requestId, events);
|
|
357
|
+
return {
|
|
358
|
+
session: receipt.session,
|
|
359
|
+
events
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
async acknowledge(sessionId, turnId) {
|
|
363
|
+
if ((await this.read(sessionId))?.turnId !== turnId) throw new Error("Runtime acknowledgement identity mismatch");
|
|
364
|
+
await rm(this.path(sessionId), { force: true });
|
|
365
|
+
}
|
|
366
|
+
async pendingTurnIds(sessionId) {
|
|
367
|
+
const receipt = await this.read(sessionId);
|
|
368
|
+
return receipt ? [receipt.turnId] : [];
|
|
369
|
+
}
|
|
370
|
+
async *pendingBatches() {
|
|
371
|
+
const names = await readdir(join(this.root, "executions")).catch((error) => {
|
|
372
|
+
if (missing(error)) return [];
|
|
373
|
+
throw error;
|
|
374
|
+
});
|
|
375
|
+
let batch = [];
|
|
376
|
+
for (const name of names) {
|
|
377
|
+
if (!name.endsWith(".json")) continue;
|
|
378
|
+
const receipt = await this.read(name.slice(0, -5)).catch(() => null);
|
|
379
|
+
if (!receipt) continue;
|
|
380
|
+
batch.push({
|
|
381
|
+
sessionId: receipt.sessionId,
|
|
382
|
+
turnId: receipt.turnId,
|
|
383
|
+
harness: receipt.session.harness
|
|
384
|
+
});
|
|
385
|
+
if (batch.length >= 64) {
|
|
386
|
+
yield batch;
|
|
387
|
+
batch = [];
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (batch.length) yield batch;
|
|
391
|
+
}
|
|
392
|
+
async fromTranscript(receipt) {
|
|
393
|
+
const transcript = await readTranscript(receipt.session.path, receipt.session.harness).catch(() => null);
|
|
394
|
+
const turn = transcript?.turns.find((entry) => entry.cloudTurnId === receipt.turnId);
|
|
395
|
+
const result = turn?.result;
|
|
396
|
+
if (!result || result.status === "interrupted" || turn !== transcript?.turns.at(-1)) return null;
|
|
397
|
+
const messages = result.messages.filter((message) => message.content.length);
|
|
398
|
+
if (!messages.length) return null;
|
|
399
|
+
const message = (entry, ordinal) => ({
|
|
400
|
+
ordinal,
|
|
401
|
+
content: entry.content,
|
|
402
|
+
provider: entry.provider ?? null,
|
|
403
|
+
model: entry.model ?? null,
|
|
404
|
+
usage: entry.usage ?? null,
|
|
405
|
+
stopReason: entry.stopReason ?? "stop",
|
|
406
|
+
errorMessage: entry.errorMessage ?? null
|
|
407
|
+
});
|
|
408
|
+
return [...messages.slice(0, -1).map((entry, index) => ({
|
|
409
|
+
type: "message.commit",
|
|
410
|
+
message: message(entry, index)
|
|
411
|
+
})), {
|
|
412
|
+
type: "turn.end",
|
|
413
|
+
message: message(messages.at(-1), messages.length - 1),
|
|
414
|
+
resume: "native",
|
|
415
|
+
archive: null
|
|
416
|
+
}];
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/runtime/connection.ts
|
|
421
|
+
async function serveRuntime(options) {
|
|
422
|
+
const runtimeId = options.runtimeId ?? options.diagnostics?.runtimeId ?? randomUUID();
|
|
423
|
+
let backoff = 500;
|
|
424
|
+
let attempt = 0;
|
|
425
|
+
let conflictSince = null;
|
|
426
|
+
const executions = options.executions ?? /* @__PURE__ */ new Map();
|
|
427
|
+
const seen = /* @__PURE__ */ new Set();
|
|
428
|
+
const announce = { current: null };
|
|
429
|
+
const catalog = {
|
|
430
|
+
current: options.capabilities,
|
|
431
|
+
publish: null
|
|
432
|
+
};
|
|
433
|
+
const uploads = new AbortController();
|
|
434
|
+
const uploadSignal = AbortSignal.any([options.signal, uploads.signal]);
|
|
435
|
+
const log = (level, event, data, context) => options.diagnostics?.log(level, event, data, context);
|
|
436
|
+
const flush = () => options.executor.archives.flush(uploadSignal).catch((error) => {
|
|
437
|
+
if (!uploadSignal.aborted) log("warn", "archive.flush_failed", { error: serializeDiagnosticError(error) });
|
|
438
|
+
});
|
|
439
|
+
const timer = setInterval(() => {
|
|
440
|
+
flush();
|
|
441
|
+
}, 1e4);
|
|
442
|
+
let refreshing = false;
|
|
443
|
+
const refreshCatalog = async () => {
|
|
444
|
+
if (!options.refreshCapabilities || refreshing || options.signal.aborted) return;
|
|
445
|
+
refreshing = true;
|
|
446
|
+
try {
|
|
447
|
+
const next = await options.refreshCapabilities(catalog.current);
|
|
448
|
+
runtimeCapabilitiesSchema.parse(next);
|
|
449
|
+
if (options.signal.aborted || isDeepStrictEqual(next, catalog.current)) return;
|
|
450
|
+
catalog.current = next;
|
|
451
|
+
log("info", "runtime.catalog_changed", {
|
|
452
|
+
harnesses: next.harnesses,
|
|
453
|
+
modelCount: next.models.length
|
|
454
|
+
});
|
|
455
|
+
catalog.publish?.();
|
|
456
|
+
} catch (error) {
|
|
457
|
+
log("warn", "runtime.catalog_refresh_failed", { error: serializeDiagnosticError(error) });
|
|
458
|
+
} finally {
|
|
459
|
+
refreshing = false;
|
|
460
|
+
}
|
|
461
|
+
};
|
|
462
|
+
const catalogTimer = options.refreshCapabilities ? setInterval(() => {
|
|
463
|
+
refreshCatalog();
|
|
464
|
+
}, options.capabilitiesRefreshMs ?? 36e5) : void 0;
|
|
465
|
+
flush();
|
|
466
|
+
log("info", "runtime.started", {
|
|
467
|
+
runtimeId,
|
|
468
|
+
workspace: options.cwd,
|
|
469
|
+
harnesses: options.capabilities.harnesses
|
|
470
|
+
});
|
|
471
|
+
try {
|
|
472
|
+
while (!options.signal.aborted) {
|
|
473
|
+
attempt += 1;
|
|
474
|
+
let readyAt = 0;
|
|
475
|
+
const connectStartedAt = Date.now();
|
|
476
|
+
let outcome;
|
|
477
|
+
try {
|
|
478
|
+
outcome = await connect({
|
|
479
|
+
...options,
|
|
480
|
+
runtimeId,
|
|
481
|
+
attempt,
|
|
482
|
+
executions,
|
|
483
|
+
seen,
|
|
484
|
+
announce,
|
|
485
|
+
catalog,
|
|
486
|
+
onReady: () => {
|
|
487
|
+
readyAt = Date.now();
|
|
488
|
+
conflictSince = null;
|
|
489
|
+
options.onReady();
|
|
490
|
+
flush();
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (options.signal.aborted) return;
|
|
495
|
+
log("warn", "runtime.connection_failed", { error: serializeDiagnosticError(error) });
|
|
496
|
+
outcome = { kind: "retry" };
|
|
497
|
+
}
|
|
498
|
+
options.onDisconnected?.();
|
|
499
|
+
if (options.signal.aborted) return;
|
|
500
|
+
if (outcome.kind === "fatal") throw new Error(`Runtime connection rejected (${[outcome.code, outcome.reason].filter(Boolean).join(" ")}); ${outcome.code === 4403 ? "check Space permissions" : "upgrade the CLI"}`);
|
|
501
|
+
if (readyAt && Date.now() - readyAt >= 6e4) {
|
|
502
|
+
backoff = 500;
|
|
503
|
+
attempt = 0;
|
|
504
|
+
}
|
|
505
|
+
if (outcome.kind === "conflict") {
|
|
506
|
+
conflictSince ??= Date.now();
|
|
507
|
+
if (Date.now() - conflictSince >= (options.leaseConflictTimeoutMs ?? 9e4)) throw new Error("Space is already connected to another Runtime");
|
|
508
|
+
}
|
|
509
|
+
log("debug", "runtime.reconnect_scheduled", {
|
|
510
|
+
attempt: attempt || 1,
|
|
511
|
+
delayMs: backoff,
|
|
512
|
+
outcome: outcome.kind,
|
|
513
|
+
connectedMs: Date.now() - connectStartedAt,
|
|
514
|
+
readyMs: readyAt ? Date.now() - readyAt : null,
|
|
515
|
+
activeExecutions: executions.size
|
|
516
|
+
});
|
|
517
|
+
await setTimeout$1(backoff / 2 + Math.random() * backoff / 2, void 0, { signal: options.signal }).catch(() => void 0);
|
|
518
|
+
backoff = Math.min(3e4, backoff * 2);
|
|
519
|
+
}
|
|
520
|
+
} finally {
|
|
521
|
+
clearInterval(catalogTimer);
|
|
522
|
+
for (const execution of executions.values()) execution.controller.abort();
|
|
523
|
+
await Promise.allSettled([...executions.values()].map((entry) => entry.promise));
|
|
524
|
+
clearInterval(timer);
|
|
525
|
+
uploads.abort();
|
|
526
|
+
await flush();
|
|
527
|
+
log("info", "runtime.stopped", { runtimeId });
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function frameIdentity(frame) {
|
|
531
|
+
const value = frame;
|
|
532
|
+
const event = value?.event;
|
|
533
|
+
const pick = (input) => typeof input === "string" ? input : void 0;
|
|
534
|
+
return {
|
|
535
|
+
frameType: pick(value?.type),
|
|
536
|
+
requestId: pick(value?.requestId),
|
|
537
|
+
eventType: pick(event?.type),
|
|
538
|
+
sessionId: pick(event?.sessionId) ?? pick(event?.input?.sessionId),
|
|
539
|
+
turnId: pick(event?.turnId) ?? pick(event?.input?.turnId),
|
|
540
|
+
harness: pick(event?.input?.harness),
|
|
541
|
+
nativeSessionId: pick(event?.input?.nativeSessionId),
|
|
542
|
+
turnCount: Array.isArray(event?.input?.turns) ? event.input.turns.length : void 0,
|
|
543
|
+
turnIds: Array.isArray(event?.input?.turns) ? event.input.turns.slice(0, 10).map((turn) => pick(turn?.turnId)).filter(Boolean) : void 0
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
function executionContext(connectionId, input) {
|
|
547
|
+
return {
|
|
548
|
+
connectionId,
|
|
549
|
+
sessionId: input.sessionId,
|
|
550
|
+
turnId: input.turnId,
|
|
551
|
+
harness: input.harness,
|
|
552
|
+
requestId: input.traceContext?.requestId ?? input.requestId ?? null,
|
|
553
|
+
traceContext: input.traceContext
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
async function connect(options) {
|
|
557
|
+
const log = (level, event, data, context) => options.diagnostics?.log(level, event, data, context);
|
|
558
|
+
const connectedAt = Date.now();
|
|
559
|
+
log("debug", "runtime.websocket.connecting", {
|
|
560
|
+
attempt: options.attempt,
|
|
561
|
+
url: options.url
|
|
562
|
+
});
|
|
563
|
+
let currentToken;
|
|
564
|
+
try {
|
|
565
|
+
currentToken = await options.token();
|
|
566
|
+
} catch (error) {
|
|
567
|
+
log("warn", error instanceof Error && error.name === "AuthRequiredError" ? "runtime.auth_required" : "runtime.auth_token_failed", { error: serializeDiagnosticError(error) });
|
|
568
|
+
throw error;
|
|
569
|
+
}
|
|
570
|
+
const runtimeUrl = new URL(options.url);
|
|
571
|
+
runtimeUrl.searchParams.set("runtimeId", options.runtimeId);
|
|
572
|
+
const socket = new WebSocket(runtimeUrl.toString());
|
|
573
|
+
const active = options.executions;
|
|
574
|
+
const seen = options.seen;
|
|
575
|
+
const disconnected = new AbortController();
|
|
576
|
+
const contexts = /* @__PURE__ */ new Map();
|
|
577
|
+
let lastHeartbeat = Date.now();
|
|
578
|
+
let openedAt = 0;
|
|
579
|
+
let readyAt = 0;
|
|
580
|
+
let connectionId = null;
|
|
581
|
+
let fatal = false;
|
|
582
|
+
let fatalCode = 0;
|
|
583
|
+
let fatalReason = "";
|
|
584
|
+
let conflict = false;
|
|
585
|
+
let unauthorized = false;
|
|
586
|
+
let readyTimer;
|
|
587
|
+
const nativePending = /* @__PURE__ */ new Map();
|
|
588
|
+
let nativeChannelReady = false;
|
|
589
|
+
const send = (frame) => {
|
|
590
|
+
if (socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > 33554432) {
|
|
591
|
+
log("warn", "runtime.frame_send_unavailable", {
|
|
592
|
+
readyState: socket.readyState,
|
|
593
|
+
bufferedBytes: socket.bufferedAmount
|
|
594
|
+
}, { connectionId });
|
|
595
|
+
throw new Error("Runtime connection unavailable");
|
|
596
|
+
}
|
|
597
|
+
const data = JSON.stringify(frame);
|
|
598
|
+
const bytes = Buffer.byteLength(data);
|
|
599
|
+
if (bytes > 33554432) {
|
|
600
|
+
const identity = frameIdentity(frame);
|
|
601
|
+
const execution = identity.requestId ? active.get(identity.requestId) : void 0;
|
|
602
|
+
log("error", "runtime.frame_too_large", {
|
|
603
|
+
bytes,
|
|
604
|
+
maxBytes: RUNTIME_MAX_FRAME_BYTES,
|
|
605
|
+
...identity
|
|
606
|
+
}, execution ? executionContext(connectionId, execution) : { connectionId });
|
|
607
|
+
throw new SizeLimitError("Runtime frame exceeds transfer limit");
|
|
608
|
+
}
|
|
609
|
+
socket.send(data);
|
|
610
|
+
};
|
|
611
|
+
const closeTransport = () => socket.close();
|
|
612
|
+
/** What the Gateway holds for this connection. */
|
|
613
|
+
let registered = null;
|
|
614
|
+
let capabilitiesFrame = false;
|
|
615
|
+
const publishCatalog = () => {
|
|
616
|
+
const current = options.catalog.current;
|
|
617
|
+
if (!connectionId || isDeepStrictEqual(registered, capabilitiesFrame ? current : runtimeHelloCapabilities(current))) return;
|
|
618
|
+
if (!capabilitiesFrame) {
|
|
619
|
+
log("info", "runtime.catalog_reconnect", void 0, { connectionId });
|
|
620
|
+
closeTransport();
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
try {
|
|
624
|
+
send({
|
|
625
|
+
type: "runtime.capabilities",
|
|
626
|
+
capabilities: current
|
|
627
|
+
});
|
|
628
|
+
registered = current;
|
|
629
|
+
log("info", "runtime.catalog_published", { modelCount: current.models.length }, { connectionId });
|
|
630
|
+
} catch (error) {
|
|
631
|
+
log("warn", "runtime.catalog_publish_failed", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
632
|
+
closeTransport();
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
const shutdown = () => {
|
|
636
|
+
for (const execution of active.values()) execution.controller.abort();
|
|
637
|
+
closeTransport();
|
|
638
|
+
};
|
|
639
|
+
const sendNative = (event) => new Promise((resolve, reject) => {
|
|
640
|
+
if (!nativeChannelReady || !connectionId) {
|
|
641
|
+
reject(/* @__PURE__ */ new Error("Runtime native channel is unavailable"));
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
const requestId = randomUUID();
|
|
645
|
+
const timer = setTimeout(() => {
|
|
646
|
+
nativePending.delete(requestId);
|
|
647
|
+
reject(/* @__PURE__ */ new Error("Native Runtime event timed out"));
|
|
648
|
+
}, event.type === "ingest" ? 12e4 : 3e4);
|
|
649
|
+
nativePending.set(requestId, {
|
|
650
|
+
resolve,
|
|
651
|
+
reject,
|
|
652
|
+
timer
|
|
653
|
+
});
|
|
654
|
+
try {
|
|
655
|
+
send({
|
|
656
|
+
type: "runtime.native",
|
|
657
|
+
requestId,
|
|
658
|
+
event
|
|
659
|
+
});
|
|
660
|
+
} catch (error) {
|
|
661
|
+
clearTimeout(timer);
|
|
662
|
+
nativePending.delete(requestId);
|
|
663
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
664
|
+
}
|
|
665
|
+
});
|
|
666
|
+
options.signal.addEventListener("abort", shutdown, { once: true });
|
|
667
|
+
const heartbeat = setInterval(() => {
|
|
668
|
+
const heartbeatAgeMs = Date.now() - lastHeartbeat;
|
|
669
|
+
if (heartbeatAgeMs > 3e4) {
|
|
670
|
+
log("error", "runtime.heartbeat_timeout", {
|
|
671
|
+
ageMs: heartbeatAgeMs,
|
|
672
|
+
activeExecutions: active.size,
|
|
673
|
+
readyState: socket.readyState,
|
|
674
|
+
bufferedBytes: socket.bufferedAmount
|
|
675
|
+
}, { connectionId });
|
|
676
|
+
closeTransport();
|
|
677
|
+
if (heartbeatAgeMs > 45e3) handleClose({
|
|
678
|
+
code: 1006,
|
|
679
|
+
reason: "Runtime heartbeat timed out",
|
|
680
|
+
wasClean: false
|
|
681
|
+
}, true);
|
|
682
|
+
} else if (connectionId) {
|
|
683
|
+
try {
|
|
684
|
+
send({ type: "runtime.heartbeat" });
|
|
685
|
+
} catch (error) {
|
|
686
|
+
log("warn", "runtime.heartbeat_send_failed", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
687
|
+
closeTransport();
|
|
688
|
+
}
|
|
689
|
+
options.token().then((next) => {
|
|
690
|
+
if (next !== currentToken) try {
|
|
691
|
+
send({
|
|
692
|
+
type: "runtime.auth",
|
|
693
|
+
token: next
|
|
694
|
+
});
|
|
695
|
+
currentToken = next;
|
|
696
|
+
log("debug", "runtime.auth_refreshed", void 0, { connectionId });
|
|
697
|
+
} catch (error) {
|
|
698
|
+
log("warn", "runtime.auth_refresh_send_failed", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
699
|
+
closeTransport();
|
|
700
|
+
}
|
|
701
|
+
}).catch((error) => {
|
|
702
|
+
log("warn", "runtime.auth_refresh_failed", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
703
|
+
closeTransport();
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
}, 1e4);
|
|
707
|
+
const announceHere = (execution) => {
|
|
708
|
+
try {
|
|
709
|
+
send({
|
|
710
|
+
type: "runtime.recovery",
|
|
711
|
+
executions: [execution]
|
|
712
|
+
});
|
|
713
|
+
log("info", "runtime.detached_result_announced", void 0, executionContext(connectionId, execution));
|
|
714
|
+
} catch {}
|
|
715
|
+
};
|
|
716
|
+
/** Replays a saved result, or answers explicitly that none is available; never leaves the server waiting. */
|
|
717
|
+
const replaySaved = async (requestId, input, context, executionRequestId) => {
|
|
718
|
+
let saved = null;
|
|
719
|
+
try {
|
|
720
|
+
saved = await options.executor.results.recover(input, executionRequestId);
|
|
721
|
+
} catch (error) {
|
|
722
|
+
log("error", "runtime.recovery_failed", { error: serializeDiagnosticError(error) }, context);
|
|
723
|
+
}
|
|
724
|
+
if (saved) for (const event of saved.events) send({
|
|
725
|
+
type: "runtime.event",
|
|
726
|
+
requestId,
|
|
727
|
+
event
|
|
728
|
+
});
|
|
729
|
+
else send({
|
|
730
|
+
type: "runtime.event",
|
|
731
|
+
requestId,
|
|
732
|
+
event: {
|
|
733
|
+
type: "turn.error",
|
|
734
|
+
uncertain: true,
|
|
735
|
+
message: "Result unavailable; files retained"
|
|
736
|
+
}
|
|
737
|
+
});
|
|
738
|
+
};
|
|
739
|
+
let closeHandled = false;
|
|
740
|
+
let resolveClosed = () => {};
|
|
741
|
+
const closed = new Promise((resolve) => {
|
|
742
|
+
resolveClosed = resolve;
|
|
743
|
+
});
|
|
744
|
+
const handleClose = (event, forced = false) => {
|
|
745
|
+
if (closeHandled) return;
|
|
746
|
+
closeHandled = true;
|
|
747
|
+
unauthorized = event.code === 4401;
|
|
748
|
+
fatal = [4400, 4403].includes(event.code);
|
|
749
|
+
if (fatal) {
|
|
750
|
+
fatalCode = event.code;
|
|
751
|
+
fatalReason = event.reason;
|
|
752
|
+
}
|
|
753
|
+
conflict = event.code === 4409;
|
|
754
|
+
disconnected.abort();
|
|
755
|
+
const now = Date.now();
|
|
756
|
+
log(options.signal.aborted ? "debug" : fatal || conflict ? "error" : "warn", fatal ? "runtime.websocket.rejected" : "runtime.websocket.closed", {
|
|
757
|
+
code: event.code,
|
|
758
|
+
reason: event.reason,
|
|
759
|
+
wasClean: event.wasClean,
|
|
760
|
+
forced,
|
|
761
|
+
durationMs: now - connectedAt,
|
|
762
|
+
openMs: openedAt ? now - openedAt : null,
|
|
763
|
+
readyMs: readyAt ? now - readyAt : null,
|
|
764
|
+
lastInboundAgeMs: now - lastHeartbeat,
|
|
765
|
+
bufferedBytes: socket.bufferedAmount,
|
|
766
|
+
activeExecutions: active.size,
|
|
767
|
+
fatal,
|
|
768
|
+
conflict
|
|
769
|
+
}, { connectionId });
|
|
770
|
+
nativeChannelReady = false;
|
|
771
|
+
for (const pending of nativePending.values()) {
|
|
772
|
+
clearTimeout(pending.timer);
|
|
773
|
+
pending.reject(/* @__PURE__ */ new Error("Runtime native channel disconnected"));
|
|
774
|
+
}
|
|
775
|
+
nativePending.clear();
|
|
776
|
+
options.onDisconnected?.();
|
|
777
|
+
const executionMustStop = options.signal.aborted || fatal || conflict;
|
|
778
|
+
if (options.announce.current === announceHere) options.announce.current = null;
|
|
779
|
+
if (options.catalog.publish === publishCatalog) options.catalog.publish = null;
|
|
780
|
+
for (const [requestId, execution] of active) if (executionMustStop) {
|
|
781
|
+
log("error", "runtime.execution_transport_invalidated", {
|
|
782
|
+
code: event.code,
|
|
783
|
+
reason: event.reason
|
|
784
|
+
}, executionContext(connectionId, execution));
|
|
785
|
+
execution.controller.abort();
|
|
786
|
+
} else if (execution.recovery) execution.controller.abort();
|
|
787
|
+
else if (!execution.detached) {
|
|
788
|
+
execution.detached = true;
|
|
789
|
+
log("warn", "runtime.execution_transport_detached", {
|
|
790
|
+
code: event.code,
|
|
791
|
+
reason: event.reason
|
|
792
|
+
}, executionContext(connectionId, execution));
|
|
793
|
+
execution.promise.finally(() => {
|
|
794
|
+
if (!execution.result || active.get(requestId) !== execution) return;
|
|
795
|
+
options.announce.current?.({
|
|
796
|
+
sessionId: execution.sessionId,
|
|
797
|
+
turnId: execution.turnId,
|
|
798
|
+
harness: execution.harness
|
|
799
|
+
});
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
resolveClosed();
|
|
803
|
+
};
|
|
804
|
+
socket.addEventListener("close", (event) => handleClose(event), { once: true });
|
|
805
|
+
socket.addEventListener("error", (event) => {
|
|
806
|
+
const detail = event;
|
|
807
|
+
log("warn", "runtime.websocket.error", {
|
|
808
|
+
type: event.type,
|
|
809
|
+
message: typeof detail.message === "string" && detail.message ? detail.message : void 0,
|
|
810
|
+
readyState: socket.readyState,
|
|
811
|
+
opened: openedAt > 0,
|
|
812
|
+
ready: readyAt > 0,
|
|
813
|
+
lastInboundAgeMs: Date.now() - lastHeartbeat,
|
|
814
|
+
error: serializeDiagnosticError(detail.error ?? /* @__PURE__ */ new Error("WebSocket error"))
|
|
815
|
+
}, { connectionId });
|
|
816
|
+
socket.close();
|
|
817
|
+
});
|
|
818
|
+
socket.addEventListener("open", () => {
|
|
819
|
+
openedAt = Date.now();
|
|
820
|
+
try {
|
|
821
|
+
log("info", "runtime.websocket.open", {
|
|
822
|
+
attempt: options.attempt,
|
|
823
|
+
durationMs: Date.now() - connectedAt
|
|
824
|
+
});
|
|
825
|
+
registered = runtimeHelloCapabilities(options.catalog.current);
|
|
826
|
+
send({
|
|
827
|
+
type: "runtime.hello",
|
|
828
|
+
version: 1,
|
|
829
|
+
spaceId: options.spaceId,
|
|
830
|
+
token: currentToken,
|
|
831
|
+
capabilities: registered,
|
|
832
|
+
client: {
|
|
833
|
+
name: "cli",
|
|
834
|
+
version: CLI_VERSION
|
|
835
|
+
}
|
|
836
|
+
});
|
|
837
|
+
} catch (error) {
|
|
838
|
+
log("error", "runtime.hello_failed", { error: serializeDiagnosticError(error) });
|
|
839
|
+
closeTransport();
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
socket.addEventListener("message", (event) => {
|
|
843
|
+
(async () => {
|
|
844
|
+
let raw;
|
|
845
|
+
try {
|
|
846
|
+
raw = JSON.parse(String(event.data));
|
|
847
|
+
} catch (error) {
|
|
848
|
+
log("error", "runtime.protocol.invalid_json", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
849
|
+
throw error;
|
|
850
|
+
}
|
|
851
|
+
lastHeartbeat = Date.now();
|
|
852
|
+
if (raw.type === "runtime.ready") {
|
|
853
|
+
const frame = runtimeReadySchema.parse(raw);
|
|
854
|
+
if (connectionId === frame.connectionId) return;
|
|
855
|
+
if (connectionId) throw new Error("Runtime connection identity changed");
|
|
856
|
+
connectionId = frame.connectionId;
|
|
857
|
+
readyAt = Date.now();
|
|
858
|
+
clearTimeout(readyTimer);
|
|
859
|
+
log("info", "runtime.ready", {
|
|
860
|
+
connectionId,
|
|
861
|
+
durationMs: readyAt - connectedAt,
|
|
862
|
+
detachedExecutions: [...active.values()].filter((entry) => entry.detached).length
|
|
863
|
+
}, { connectionId });
|
|
864
|
+
nativeChannelReady = true;
|
|
865
|
+
capabilitiesFrame = frame.features?.includes("capabilities") === true;
|
|
866
|
+
options.onNativeChannel?.(sendNative, { approvals: frame.features?.includes("approvals") === true });
|
|
867
|
+
options.onReady();
|
|
868
|
+
options.announce.current = announceHere;
|
|
869
|
+
options.catalog.publish = publishCatalog;
|
|
870
|
+
publishCatalog();
|
|
871
|
+
let recoveryBatch = 0;
|
|
872
|
+
for await (const executions of options.executor.results.pendingBatches()) {
|
|
873
|
+
recoveryBatch += 1;
|
|
874
|
+
log("info", "runtime.recovery_batch_sent", {
|
|
875
|
+
batch: recoveryBatch,
|
|
876
|
+
count: executions.length
|
|
877
|
+
}, { connectionId });
|
|
878
|
+
send({
|
|
879
|
+
type: "runtime.recovery",
|
|
880
|
+
executions
|
|
881
|
+
});
|
|
882
|
+
}
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (!connectionId) throw new Error("Runtime handshake is incomplete");
|
|
886
|
+
if (raw.type === "runtime.heartbeat") return;
|
|
887
|
+
if (raw.type === "runtime.native.stop") {
|
|
888
|
+
const stop = runtimeNativeStopSchema.safeParse(raw);
|
|
889
|
+
if (!stop.success) {
|
|
890
|
+
log("warn", "runtime.protocol.invalid_native_stop", { error: stop.error.message }, { connectionId });
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
if (stop.data.spaceId === options.spaceId) options.onNativeStop?.(stop.data);
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
if (raw.type === "runtime.approval.decision") {
|
|
897
|
+
const decision = runtimeApprovalDecisionSchema.safeParse(raw);
|
|
898
|
+
if (!decision.success) {
|
|
899
|
+
log("warn", "runtime.protocol.invalid_approval_decision", { error: decision.error.message }, { connectionId });
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
if (decision.data.spaceId === options.spaceId) options.onApprovalDecision?.(decision.data);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (raw.type === "runtime.native.result") {
|
|
906
|
+
const result = raw;
|
|
907
|
+
const pending = result.requestId ? nativePending.get(result.requestId) : null;
|
|
908
|
+
if (!pending) return;
|
|
909
|
+
clearTimeout(pending.timer);
|
|
910
|
+
nativePending.delete(result.requestId ?? "");
|
|
911
|
+
if (result.error) pending.reject(new Error(result.error));
|
|
912
|
+
else pending.resolve(result.result);
|
|
913
|
+
return;
|
|
914
|
+
}
|
|
915
|
+
const frame = runtimeCommandSchema.parse(raw);
|
|
916
|
+
if (frame.type === "session.context") {
|
|
917
|
+
log("debug", "runtime.context_received", { messageCount: frame.context.messages.length }, { connectionId });
|
|
918
|
+
contexts.get(frame.requestId)?.(frame.context);
|
|
919
|
+
contexts.delete(frame.requestId);
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
if (frame.type === "turn.abort") {
|
|
923
|
+
log("info", "runtime.turn_abort_received", void 0, {
|
|
924
|
+
connectionId,
|
|
925
|
+
requestId: frame.requestId
|
|
926
|
+
});
|
|
927
|
+
active.get(frame.requestId)?.controller.abort();
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
if (frame.type === "turn.ack") {
|
|
931
|
+
const execution = active.get(frame.requestId);
|
|
932
|
+
if (!execution) return;
|
|
933
|
+
const context = executionContext(connectionId, execution);
|
|
934
|
+
try {
|
|
935
|
+
await execution.promise;
|
|
936
|
+
if (!execution.result) throw new Error("Runtime result is not available");
|
|
937
|
+
await options.executor.results.acknowledge(execution.sessionId, frame.turnId);
|
|
938
|
+
} catch (error) {
|
|
939
|
+
log("error", "runtime.turn_ack_failed", {
|
|
940
|
+
revision: frame.revision,
|
|
941
|
+
error: serializeDiagnosticError(error)
|
|
942
|
+
}, context);
|
|
943
|
+
active.delete(frame.requestId);
|
|
944
|
+
send({
|
|
945
|
+
type: "runtime.event",
|
|
946
|
+
requestId: frame.requestId,
|
|
947
|
+
event: {
|
|
948
|
+
type: "turn.error",
|
|
949
|
+
message: "Local acknowledgement failed; result retained"
|
|
950
|
+
}
|
|
951
|
+
});
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
log("info", "runtime.turn_acknowledged", { revision: frame.revision }, context);
|
|
955
|
+
active.delete(frame.requestId);
|
|
956
|
+
send({
|
|
957
|
+
type: "runtime.event",
|
|
958
|
+
requestId: frame.requestId,
|
|
959
|
+
event: { type: "turn.acknowledged" }
|
|
960
|
+
});
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
if (frame.type === "turn.recover") {
|
|
964
|
+
const identity = frame.execution;
|
|
965
|
+
if (identity.spaceId !== options.spaceId) throw new Error("Invalid Runtime target");
|
|
966
|
+
const context = executionContext(connectionId, {
|
|
967
|
+
...identity,
|
|
968
|
+
requestId: frame.traceContext?.requestId,
|
|
969
|
+
traceContext: frame.traceContext
|
|
970
|
+
});
|
|
971
|
+
log("info", "runtime.recovery_requested", void 0, context);
|
|
972
|
+
const previous = active.get(frame.requestId);
|
|
973
|
+
if (previous) {
|
|
974
|
+
if (previous.sessionId !== identity.sessionId || previous.turnId !== identity.turnId || previous.harness !== identity.harness) throw new Error("Runtime recovery identity changed");
|
|
975
|
+
await previous.promise;
|
|
976
|
+
await replaySaved(frame.requestId, identity, context);
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const running = [...active].find(([, entry]) => entry.turnId === identity.turnId && entry.sessionId === identity.sessionId && entry.harness === identity.harness);
|
|
980
|
+
const recovery = {
|
|
981
|
+
...identity,
|
|
982
|
+
requestId: frame.traceContext?.requestId,
|
|
983
|
+
traceContext: frame.traceContext,
|
|
984
|
+
controller: new AbortController(),
|
|
985
|
+
promise: Promise.resolve(),
|
|
986
|
+
recovery: true
|
|
987
|
+
};
|
|
988
|
+
active.set(frame.requestId, recovery);
|
|
989
|
+
recovery.promise = (async () => {
|
|
990
|
+
try {
|
|
991
|
+
if (running) {
|
|
992
|
+
if (running[1].detached) {
|
|
993
|
+
log("info", "runtime.recovery_waiting_detached", { runningRequestId: running[0] }, context);
|
|
994
|
+
const stopped = recovery.controller.signal;
|
|
995
|
+
await Promise.race([running[1].promise, new Promise((resolve) => stopped.addEventListener("abort", () => resolve(), { once: true }))]);
|
|
996
|
+
stopped.throwIfAborted();
|
|
997
|
+
} else {
|
|
998
|
+
running[1].controller.abort();
|
|
999
|
+
await running[1].promise;
|
|
1000
|
+
}
|
|
1001
|
+
if (active.get(running[0]) === running[1]) active.delete(running[0]);
|
|
1002
|
+
}
|
|
1003
|
+
const saved = await options.executor.results.recover(identity);
|
|
1004
|
+
recovery.controller.signal.throwIfAborted();
|
|
1005
|
+
const last = saved?.events.at(-1);
|
|
1006
|
+
if (!saved || last?.type !== "turn.end") throw new Error("No confirmed result");
|
|
1007
|
+
recovery.result = {
|
|
1008
|
+
session: saved.session,
|
|
1009
|
+
event: last
|
|
1010
|
+
};
|
|
1011
|
+
for (const event of saved.events) send({
|
|
1012
|
+
type: "runtime.event",
|
|
1013
|
+
requestId: frame.requestId,
|
|
1014
|
+
event
|
|
1015
|
+
});
|
|
1016
|
+
} catch (error) {
|
|
1017
|
+
if (!recovery.controller.signal.aborted) {
|
|
1018
|
+
log("error", "runtime.recovery_failed", { error: serializeDiagnosticError(error) }, context);
|
|
1019
|
+
try {
|
|
1020
|
+
send({
|
|
1021
|
+
type: "runtime.event",
|
|
1022
|
+
requestId: frame.requestId,
|
|
1023
|
+
event: {
|
|
1024
|
+
type: "turn.error",
|
|
1025
|
+
uncertain: true,
|
|
1026
|
+
message: "Result unavailable; files retained"
|
|
1027
|
+
}
|
|
1028
|
+
});
|
|
1029
|
+
} catch {}
|
|
1030
|
+
}
|
|
1031
|
+
if (active.get(frame.requestId) === recovery) active.delete(frame.requestId);
|
|
1032
|
+
}
|
|
1033
|
+
})();
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
if (frame.input.spaceId !== options.spaceId || !options.catalog.current.harnesses.includes(frame.input.harness)) throw new Error("Invalid Runtime target");
|
|
1037
|
+
const context = executionContext(connectionId, frame.input);
|
|
1038
|
+
log("info", "runtime.turn_received", {
|
|
1039
|
+
requestId: frame.requestId,
|
|
1040
|
+
resumeOnly: frame.resumeOnly === true
|
|
1041
|
+
}, context);
|
|
1042
|
+
const previous = active.get(frame.requestId);
|
|
1043
|
+
if (previous) {
|
|
1044
|
+
if (previous.sessionId !== frame.input.sessionId || previous.turnId !== frame.input.turnId || previous.harness !== frame.input.harness) throw new Error("Runtime execution identity changed");
|
|
1045
|
+
log("info", "runtime.execution_resumed", {
|
|
1046
|
+
detached: previous.detached === true,
|
|
1047
|
+
settled: Boolean(previous.result)
|
|
1048
|
+
}, executionContext(connectionId, frame.input));
|
|
1049
|
+
await previous.promise;
|
|
1050
|
+
await replaySaved(frame.requestId, frame.input, context, frame.requestId);
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const requestContext = async (executionSignal) => {
|
|
1054
|
+
const signal = AbortSignal.any([executionSignal, disconnected.signal]);
|
|
1055
|
+
signal.throwIfAborted();
|
|
1056
|
+
const pendingTurnIds = await options.executor.results.pendingTurnIds(frame.input.sessionId);
|
|
1057
|
+
log("debug", "runtime.context_requested", { pendingTurnCount: pendingTurnIds.length }, context);
|
|
1058
|
+
return new Promise((resolve, reject) => {
|
|
1059
|
+
const abort = () => {
|
|
1060
|
+
clearTimeout(timeout);
|
|
1061
|
+
contexts.delete(frame.requestId);
|
|
1062
|
+
signal.removeEventListener("abort", abort);
|
|
1063
|
+
reject(/* @__PURE__ */ new Error("Runtime context request aborted"));
|
|
1064
|
+
};
|
|
1065
|
+
const timeout = setTimeout(abort, 6e4);
|
|
1066
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1067
|
+
contexts.set(frame.requestId, (nextContext) => {
|
|
1068
|
+
clearTimeout(timeout);
|
|
1069
|
+
signal.removeEventListener("abort", abort);
|
|
1070
|
+
resolve(nextContext);
|
|
1071
|
+
});
|
|
1072
|
+
try {
|
|
1073
|
+
send({
|
|
1074
|
+
type: "runtime.event",
|
|
1075
|
+
requestId: frame.requestId,
|
|
1076
|
+
event: {
|
|
1077
|
+
type: "context.required",
|
|
1078
|
+
pendingTurnIds
|
|
1079
|
+
}
|
|
1080
|
+
});
|
|
1081
|
+
} catch {
|
|
1082
|
+
abort();
|
|
1083
|
+
}
|
|
1084
|
+
if (signal.aborted) abort();
|
|
1085
|
+
});
|
|
1086
|
+
};
|
|
1087
|
+
if ([...active.values()].some((entry) => entry.sessionId === frame.input.sessionId) && !frame.input.context.complete) frame.input.context = await requestContext(options.signal);
|
|
1088
|
+
const repeated = seen.has(frame.requestId);
|
|
1089
|
+
for (const [requestId, entry] of active) {
|
|
1090
|
+
if (entry.sessionId !== frame.input.sessionId) continue;
|
|
1091
|
+
const resolved = frame.input.context.resolvedTurnIds?.includes(entry.turnId);
|
|
1092
|
+
const settled = entry.result && frame.input.context.settledTurnIds?.includes(entry.turnId);
|
|
1093
|
+
if (!resolved && !settled) continue;
|
|
1094
|
+
entry.controller.abort();
|
|
1095
|
+
await entry.promise;
|
|
1096
|
+
active.delete(requestId);
|
|
1097
|
+
}
|
|
1098
|
+
if ([...active.values()].some((entry) => entry.sessionId === frame.input.sessionId) || active.size >= 8) {
|
|
1099
|
+
log("warn", "runtime.turn_rejected_busy", { activeExecutions: active.size }, context);
|
|
1100
|
+
send({
|
|
1101
|
+
type: "runtime.event",
|
|
1102
|
+
requestId: frame.requestId,
|
|
1103
|
+
event: {
|
|
1104
|
+
type: "turn.error",
|
|
1105
|
+
message: "Local Runtime is busy"
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
seen.add(frame.requestId);
|
|
1111
|
+
if (seen.size > 4096) {
|
|
1112
|
+
const oldest = seen.values().next().value;
|
|
1113
|
+
if (oldest) seen.delete(oldest);
|
|
1114
|
+
}
|
|
1115
|
+
const controller = new AbortController();
|
|
1116
|
+
const execution = {
|
|
1117
|
+
controller,
|
|
1118
|
+
sessionId: frame.input.sessionId,
|
|
1119
|
+
turnId: frame.input.turnId,
|
|
1120
|
+
harness: frame.input.harness,
|
|
1121
|
+
requestId: frame.input.requestId,
|
|
1122
|
+
traceContext: frame.input.traceContext,
|
|
1123
|
+
promise: Promise.resolve()
|
|
1124
|
+
};
|
|
1125
|
+
active.set(frame.requestId, execution);
|
|
1126
|
+
const durableEvents = [];
|
|
1127
|
+
const emit = (value) => {
|
|
1128
|
+
if (value.type === "message.commit") durableEvents.push(value);
|
|
1129
|
+
if (disconnected.signal.aborted || socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > 33554432) return;
|
|
1130
|
+
try {
|
|
1131
|
+
send({
|
|
1132
|
+
type: "runtime.event",
|
|
1133
|
+
requestId: frame.requestId,
|
|
1134
|
+
event: value
|
|
1135
|
+
});
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
if (!disconnected.signal.aborted && socket.readyState === WebSocket.OPEN) throw error;
|
|
1138
|
+
}
|
|
1139
|
+
};
|
|
1140
|
+
execution.promise = (async () => {
|
|
1141
|
+
try {
|
|
1142
|
+
const saved = await options.executor.results.recover(frame.input, frame.requestId);
|
|
1143
|
+
if (saved) {
|
|
1144
|
+
const last = saved.events.at(-1);
|
|
1145
|
+
if (last?.type !== "turn.end") throw new Error("Incomplete saved Runtime result");
|
|
1146
|
+
execution.result = {
|
|
1147
|
+
session: saved.session,
|
|
1148
|
+
event: last
|
|
1149
|
+
};
|
|
1150
|
+
for (const event of saved.events) emit(event);
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
if (frame.resumeOnly || repeated) {
|
|
1154
|
+
emit({
|
|
1155
|
+
type: "turn.error",
|
|
1156
|
+
message: "Execution outcome is unknown; native files retained, no replay",
|
|
1157
|
+
uncertain: true
|
|
1158
|
+
});
|
|
1159
|
+
active.delete(frame.requestId);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
const run = () => executeTurn(options.executor, frame.input, emit, controller.signal, frame.requestId, context);
|
|
1163
|
+
for (let retry = 0;; retry += 1) try {
|
|
1164
|
+
execution.result = await run();
|
|
1165
|
+
break;
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
if (!(error instanceof ContextRequiredError) || retry >= 2) throw error;
|
|
1168
|
+
frame.input.context = await requestContext(controller.signal);
|
|
1169
|
+
}
|
|
1170
|
+
await options.executor.results.record(execution.result.session, frame.input, frame.requestId, [...durableEvents, execution.result.event], execution.result.uncertainCleanup);
|
|
1171
|
+
if (execution.result.uncertainCleanup) log("warn", "runtime.turn_cleanup_pending", { cleanup: execution.result.uncertainCleanup.error }, context);
|
|
1172
|
+
emit(execution.result.event);
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
log("error", "runtime.turn_failed", {
|
|
1175
|
+
uncertain: Boolean(execution.result) || frame.resumeOnly === true || error instanceof ProcessCleanupUncertainError,
|
|
1176
|
+
error: serializeDiagnosticError(error)
|
|
1177
|
+
}, context);
|
|
1178
|
+
try {
|
|
1179
|
+
emit({
|
|
1180
|
+
type: "turn.error",
|
|
1181
|
+
message: describeError(error),
|
|
1182
|
+
uncertain: !!execution.result || frame.resumeOnly === true || error instanceof ProcessCleanupUncertainError
|
|
1183
|
+
});
|
|
1184
|
+
} catch {}
|
|
1185
|
+
active.delete(frame.requestId);
|
|
1186
|
+
}
|
|
1187
|
+
})();
|
|
1188
|
+
})().catch((error) => {
|
|
1189
|
+
log("error", "runtime.protocol_error", { error: serializeDiagnosticError(error) }, { connectionId });
|
|
1190
|
+
closeTransport();
|
|
1191
|
+
});
|
|
1192
|
+
});
|
|
1193
|
+
readyTimer = setTimeout(() => {
|
|
1194
|
+
log("error", "runtime.handshake_timeout", { timeoutMs: 15e3 }, { connectionId });
|
|
1195
|
+
socket.close(4408, "Runtime handshake timed out");
|
|
1196
|
+
}, 15e3);
|
|
1197
|
+
if (options.signal.aborted) shutdown();
|
|
1198
|
+
try {
|
|
1199
|
+
await closed;
|
|
1200
|
+
} finally {
|
|
1201
|
+
clearTimeout(readyTimer);
|
|
1202
|
+
clearInterval(heartbeat);
|
|
1203
|
+
options.signal.removeEventListener("abort", shutdown);
|
|
1204
|
+
}
|
|
1205
|
+
if (unauthorized && !options.signal.aborted) await options.token(true);
|
|
1206
|
+
return fatal ? {
|
|
1207
|
+
kind: "fatal",
|
|
1208
|
+
code: fatalCode,
|
|
1209
|
+
reason: fatalReason
|
|
1210
|
+
} : conflict ? { kind: "conflict" } : { kind: "retry" };
|
|
1211
|
+
}
|
|
1212
|
+
//#endregion
|
|
1213
|
+
//#region src/runtime/cli-path.ts
|
|
1214
|
+
const ENTRY = packagePath("bin", "cohub.js");
|
|
1215
|
+
/**
|
|
1216
|
+
* Puts this Runtime's own `cohub` last on PATH, so what it runs can always call the CLI while a
|
|
1217
|
+
* `cohub` already on PATH (a global install that updates itself) still comes first.
|
|
1218
|
+
*/
|
|
1219
|
+
function appendCliToPath(env = process.env, node = process.execPath, entry = ENTRY) {
|
|
1220
|
+
const dir = join(homedir(), ".cache", "cohub", "cli", createHash("sha256").update(`${node}\0${entry}`).digest("hex").slice(0, 12));
|
|
1221
|
+
const windows = process.platform === "win32";
|
|
1222
|
+
const script = windows ? `@"${node}" "${entry}" %*\r\n` : `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`;
|
|
1223
|
+
mkdirSync(dir, { recursive: true });
|
|
1224
|
+
const file = join(dir, windows ? "cohub.cmd" : "cohub");
|
|
1225
|
+
const temporary = `${file}.${process.pid}`;
|
|
1226
|
+
writeFileSync(temporary, script, { mode: 493 });
|
|
1227
|
+
renameSync(temporary, file);
|
|
1228
|
+
const path = env.PATH?.split(delimiter).filter(Boolean) ?? [];
|
|
1229
|
+
if (!path.includes(dir)) env.PATH = [...path, dir].join(delimiter);
|
|
1230
|
+
return dir;
|
|
1231
|
+
}
|
|
1232
|
+
const quote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
|
|
1233
|
+
//#endregion
|
|
1234
|
+
//#region src/runtime/native/approvals.ts
|
|
1235
|
+
/** How long a card waits for a person; unanswered, the request is declined. */
|
|
1236
|
+
const APPROVAL_TIMEOUT_MS = 18e5;
|
|
1237
|
+
/** Asks the web for a decision over the control connection; without one, it declines. */
|
|
1238
|
+
var ApprovalBroker = class {
|
|
1239
|
+
timeoutMs;
|
|
1240
|
+
send = null;
|
|
1241
|
+
pending = /* @__PURE__ */ new Map();
|
|
1242
|
+
constructor(timeoutMs = APPROVAL_TIMEOUT_MS) {
|
|
1243
|
+
this.timeoutMs = timeoutMs;
|
|
1244
|
+
}
|
|
1245
|
+
/** `null` when the Gateway cannot relay decisions; open cards are then declined. */
|
|
1246
|
+
connect(send) {
|
|
1247
|
+
this.send = send;
|
|
1248
|
+
if (!send) for (const entry of this.pending.values()) entry.resolve("decline");
|
|
1249
|
+
}
|
|
1250
|
+
get available() {
|
|
1251
|
+
return this.send !== null;
|
|
1252
|
+
}
|
|
1253
|
+
async request(sessionId, turnId, request, signal) {
|
|
1254
|
+
const send = this.send;
|
|
1255
|
+
if (!send || signal.aborted) return "decline";
|
|
1256
|
+
const id = randomUUID();
|
|
1257
|
+
const now = Date.now();
|
|
1258
|
+
let timer;
|
|
1259
|
+
let onAbort = () => {};
|
|
1260
|
+
const decided = new Promise((resolve) => {
|
|
1261
|
+
this.pending.set(id, {
|
|
1262
|
+
sessionId,
|
|
1263
|
+
turnId,
|
|
1264
|
+
resolve
|
|
1265
|
+
});
|
|
1266
|
+
timer = setTimeout(() => resolve("decline"), this.timeoutMs);
|
|
1267
|
+
onAbort = () => resolve("decline");
|
|
1268
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1269
|
+
});
|
|
1270
|
+
try {
|
|
1271
|
+
await send({
|
|
1272
|
+
type: "approval",
|
|
1273
|
+
sessionId,
|
|
1274
|
+
turnId,
|
|
1275
|
+
approval: {
|
|
1276
|
+
...request,
|
|
1277
|
+
id,
|
|
1278
|
+
requestedAt: new Date(now).toISOString(),
|
|
1279
|
+
expiresAt: new Date(now + this.timeoutMs).toISOString()
|
|
1280
|
+
}
|
|
1281
|
+
});
|
|
1282
|
+
return await decided;
|
|
1283
|
+
} catch {
|
|
1284
|
+
return "decline";
|
|
1285
|
+
} finally {
|
|
1286
|
+
clearTimeout(timer);
|
|
1287
|
+
signal.removeEventListener("abort", onAbort);
|
|
1288
|
+
this.pending.delete(id);
|
|
1289
|
+
this.send?.({
|
|
1290
|
+
type: "approval.closed",
|
|
1291
|
+
sessionId,
|
|
1292
|
+
turnId,
|
|
1293
|
+
approvalId: id
|
|
1294
|
+
}).catch(() => void 0);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
decide(input) {
|
|
1298
|
+
const entry = this.pending.get(input.approvalId);
|
|
1299
|
+
if (entry && entry.sessionId === input.sessionId && entry.turnId === input.turnId) entry.resolve(input.decision);
|
|
1300
|
+
}
|
|
1301
|
+
};
|
|
1302
|
+
//#endregion
|
|
1303
|
+
//#region src/runtime/turn-projection.ts
|
|
1304
|
+
const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1305
|
+
const iso = (value) => value ?? (/* @__PURE__ */ new Date(0)).toISOString();
|
|
1306
|
+
const sourceSessionId = (turn) => turn.sourceSessionId ?? turn.sessionId;
|
|
1307
|
+
const sourceTurnId = (turn) => turn.sourceTurnId ?? turn.id;
|
|
1308
|
+
const userMessageId = (turn) => {
|
|
1309
|
+
const value = record(turn.meta).userMessageId;
|
|
1310
|
+
return typeof value === "string" && value ? value : `${turn.id}:user`;
|
|
1311
|
+
};
|
|
1312
|
+
function hydrateToolDetails(content, calls) {
|
|
1313
|
+
const byId = new Map(calls.map((call) => [call.id, call]));
|
|
1314
|
+
return content.map((block) => {
|
|
1315
|
+
if (block.type === "tool_use") {
|
|
1316
|
+
const call = byId.get(block.id);
|
|
1317
|
+
return call ? {
|
|
1318
|
+
...block,
|
|
1319
|
+
input: call.input
|
|
1320
|
+
} : block;
|
|
1321
|
+
}
|
|
1322
|
+
if (block.type === "tool_result") {
|
|
1323
|
+
const call = byId.get(block.tool_use_id);
|
|
1324
|
+
return call?.result ? {
|
|
1325
|
+
...block,
|
|
1326
|
+
content: call.result.content ?? block.content,
|
|
1327
|
+
is_error: call.result.isError
|
|
1328
|
+
} : block;
|
|
1329
|
+
}
|
|
1330
|
+
return block;
|
|
1331
|
+
});
|
|
1332
|
+
}
|
|
1333
|
+
async function hydrateIntermediateMessage(turn, message, client, signal) {
|
|
1334
|
+
signal?.throwIfAborted();
|
|
1335
|
+
const toolCalls = await client.turns.intermediate.getToolCalls(turn.id, message, { signal });
|
|
1336
|
+
return {
|
|
1337
|
+
id: message.id,
|
|
1338
|
+
turnId: turn.id,
|
|
1339
|
+
role: message.role,
|
|
1340
|
+
content: hydrateToolDetails(message.content, toolCalls?.toolCalls ?? []),
|
|
1341
|
+
provider: message.provider,
|
|
1342
|
+
model: message.model,
|
|
1343
|
+
usage: message.usage,
|
|
1344
|
+
stopReason: message.stopReason,
|
|
1345
|
+
errorMessage: message.errorMessage,
|
|
1346
|
+
meta: message.meta,
|
|
1347
|
+
sourceSessionId: message.sessionId,
|
|
1348
|
+
sequence: message.sequence ?? 0,
|
|
1349
|
+
createdAt: iso(message.createdAt)
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
async function mapWithConcurrency(items, concurrency, mapper) {
|
|
1353
|
+
const results = new Array(items.length);
|
|
1354
|
+
let next = 0;
|
|
1355
|
+
const worker = async () => {
|
|
1356
|
+
for (;;) {
|
|
1357
|
+
const index = next++;
|
|
1358
|
+
if (index >= items.length) return;
|
|
1359
|
+
const item = items[index];
|
|
1360
|
+
if (item === void 0) return;
|
|
1361
|
+
results[index] = await mapper(item);
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker));
|
|
1365
|
+
return results;
|
|
1366
|
+
}
|
|
1367
|
+
async function hydrateSessionTurn(turn, client, signal) {
|
|
1368
|
+
const sourceId = sourceSessionId(turn);
|
|
1369
|
+
const messages = [];
|
|
1370
|
+
if (turn.userContent.length) messages.push({
|
|
1371
|
+
id: userMessageId(turn),
|
|
1372
|
+
turnId: turn.id,
|
|
1373
|
+
role: "user",
|
|
1374
|
+
content: turn.userContent,
|
|
1375
|
+
meta: {
|
|
1376
|
+
userMessageId: userMessageId(turn),
|
|
1377
|
+
turnId: turn.id
|
|
1378
|
+
},
|
|
1379
|
+
sourceSessionId: sourceId,
|
|
1380
|
+
sequence: turn.sequence * 1e6,
|
|
1381
|
+
createdAt: iso(turn.createdAt)
|
|
1382
|
+
});
|
|
1383
|
+
const objectKey = turn.intermediateIndex?.messagesObjectKey;
|
|
1384
|
+
if (!objectKey && (turn.intermediateSummary?.messageCount ?? 0) > 0) throw new Error(`Intermediate message index is unavailable for Turn ${turn.id}`);
|
|
1385
|
+
if (objectKey) {
|
|
1386
|
+
const archive = await client.turns.intermediate.get(turn.id, objectKey, { signal });
|
|
1387
|
+
if (!archive) throw new Error(`Intermediate messages are unavailable for Turn ${turn.id}`);
|
|
1388
|
+
const intermediate = await mapWithConcurrency(archive.messages, 8, (message) => hydrateIntermediateMessage(turn, message, client, signal));
|
|
1389
|
+
messages.push(...intermediate.map((message) => ({
|
|
1390
|
+
...message,
|
|
1391
|
+
sequence: turn.sequence * 1e6 + 1e5 + message.sequence
|
|
1392
|
+
})));
|
|
1393
|
+
}
|
|
1394
|
+
const hasFinalGenerationResult = messages.some((message) => message.role === "assistant" && message.meta?.messageKind === "generation_result" && ["completed", "failed"].includes(String(message.meta.generationStatus)));
|
|
1395
|
+
if (turn.assistantContent?.length && !hasFinalGenerationResult) messages.push({
|
|
1396
|
+
id: `${turn.id}:assistant`,
|
|
1397
|
+
turnId: turn.id,
|
|
1398
|
+
role: turn.intent === "compact" ? "system" : "assistant",
|
|
1399
|
+
content: turn.assistantContent,
|
|
1400
|
+
provider: turn.provider,
|
|
1401
|
+
model: turn.model,
|
|
1402
|
+
usage: turn.finalUsage,
|
|
1403
|
+
stopReason: turn.stopReason,
|
|
1404
|
+
errorMessage: turn.errorMessage,
|
|
1405
|
+
meta: {
|
|
1406
|
+
...turn.meta ?? {},
|
|
1407
|
+
turnId: turn.id,
|
|
1408
|
+
createdAt: turn.createdAt
|
|
1409
|
+
},
|
|
1410
|
+
sourceSessionId: sourceId,
|
|
1411
|
+
sequence: turn.sequence * 1e6 + 9e5,
|
|
1412
|
+
createdAt: iso(turn.createdAt)
|
|
1413
|
+
});
|
|
1414
|
+
messages.sort((left, right) => left.sequence - right.sequence || left.id.localeCompare(right.id));
|
|
1415
|
+
return {
|
|
1416
|
+
id: turn.id,
|
|
1417
|
+
sourceSessionId: sourceId,
|
|
1418
|
+
sourceTurnId: sourceTurnId(turn),
|
|
1419
|
+
sequence: turn.sequence,
|
|
1420
|
+
status: turn.status,
|
|
1421
|
+
intent: turn.intent,
|
|
1422
|
+
provider: turn.provider,
|
|
1423
|
+
model: turn.model,
|
|
1424
|
+
userContent: turn.userContent,
|
|
1425
|
+
assistantContent: turn.assistantContent,
|
|
1426
|
+
meta: turn.meta,
|
|
1427
|
+
createdAt: iso(turn.createdAt),
|
|
1428
|
+
startedAt: turn.startedAt,
|
|
1429
|
+
completedAt: turn.completedAt,
|
|
1430
|
+
durationMs: turn.durationMs,
|
|
1431
|
+
messages
|
|
1432
|
+
};
|
|
1433
|
+
}
|
|
1434
|
+
async function listSessionProjectionTurns(source, sessionId, options = {}) {
|
|
1435
|
+
const client = source.session(sessionId);
|
|
1436
|
+
const turns = [];
|
|
1437
|
+
const throughSequence = options.throughSequence ?? null;
|
|
1438
|
+
let cursor = options.afterSequence && options.afterSequence > 0 ? options.afterSequence : void 0;
|
|
1439
|
+
for (;;) {
|
|
1440
|
+
options.signal?.throwIfAborted();
|
|
1441
|
+
const page = await client.turns.listPaginated({
|
|
1442
|
+
cursor,
|
|
1443
|
+
limit: 100,
|
|
1444
|
+
direction: "newer"
|
|
1445
|
+
}, { signal: options.signal });
|
|
1446
|
+
const visible = page.turns.filter((turn) => (throughSequence == null || turn.sequence <= throughSequence) && turn.id !== options.excludeTurnId && ![
|
|
1447
|
+
"queued",
|
|
1448
|
+
"running",
|
|
1449
|
+
"abort_requested"
|
|
1450
|
+
].includes(turn.status));
|
|
1451
|
+
turns.push(...visible);
|
|
1452
|
+
if (throughSequence != null && page.turns.some((turn) => turn.sequence >= throughSequence)) break;
|
|
1453
|
+
if (!page.hasMore) break;
|
|
1454
|
+
if (page.nextCursor === void 0 || page.nextCursor === cursor) throw new Error("Session Turn pagination did not advance");
|
|
1455
|
+
cursor = page.nextCursor;
|
|
1456
|
+
}
|
|
1457
|
+
return mapWithConcurrency(turns, 4, (turn) => hydrateSessionTurn(turn, client, options.signal));
|
|
1458
|
+
}
|
|
1459
|
+
function projectTurnBatch(input, target) {
|
|
1460
|
+
return harnessAdapter(target).session.project(input);
|
|
1461
|
+
}
|
|
1462
|
+
//#endregion
|
|
1463
|
+
//#region src/runtime/projection-store.ts
|
|
1464
|
+
/** Give the projection's own records (the native header) the identity of the file it becomes. */
|
|
1465
|
+
function rebindProjectionNativeSession(result, nativeSessionId) {
|
|
1466
|
+
const records = harnessAdapter(result.projection.target).session.rebind(result.projection.records, nativeSessionId);
|
|
1467
|
+
return {
|
|
1468
|
+
...result,
|
|
1469
|
+
projection: {
|
|
1470
|
+
...result.projection,
|
|
1471
|
+
records
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
/**
|
|
1476
|
+
* Materializes a Session's durable Turns into one harness-specific native file. Cohub never appends
|
|
1477
|
+
* to a native file it did not just write, so every projection is complete up to the Session head.
|
|
1478
|
+
*/
|
|
1479
|
+
var ProjectionStore = class {
|
|
1480
|
+
source;
|
|
1481
|
+
constructor(source) {
|
|
1482
|
+
this.source = source;
|
|
1483
|
+
}
|
|
1484
|
+
async project(input, signal) {
|
|
1485
|
+
const throughSequence = input.throughTurnId ? (await this.source.session(input.sessionId).turns.get(input.throughTurnId, { signal })).turn.sequence : 0;
|
|
1486
|
+
const turns = await listSessionProjectionTurns(this.source, input.sessionId, {
|
|
1487
|
+
throughSequence,
|
|
1488
|
+
excludeTurnId: input.turnId,
|
|
1489
|
+
signal
|
|
1490
|
+
});
|
|
1491
|
+
return {
|
|
1492
|
+
projection: projectTurnBatch({
|
|
1493
|
+
spaceId: input.spaceId,
|
|
1494
|
+
sessionId: input.sessionId,
|
|
1495
|
+
nativeSessionId: input.nativeSessionId,
|
|
1496
|
+
cwd: input.cwd,
|
|
1497
|
+
provider: input.provider,
|
|
1498
|
+
turns
|
|
1499
|
+
}, input.target),
|
|
1500
|
+
turns
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
};
|
|
1504
|
+
//#endregion
|
|
1505
|
+
//#region src/runtime/native/sessions.ts
|
|
1506
|
+
/** Chooses the native file a Turn runs in. 1. */
|
|
1507
|
+
var NativeSessions = class {
|
|
1508
|
+
options;
|
|
1509
|
+
projections;
|
|
1510
|
+
constructor(options) {
|
|
1511
|
+
this.options = options;
|
|
1512
|
+
this.projections = new ProjectionStore(options.projectionSource);
|
|
1513
|
+
}
|
|
1514
|
+
async prepare(input) {
|
|
1515
|
+
const existing = this.options.ingest.transcriptFor(input.sessionId, input.harness, input.context.throughTurnId);
|
|
1516
|
+
if (existing && input.resumable(existing)) return {
|
|
1517
|
+
session: {
|
|
1518
|
+
harness: existing.harness,
|
|
1519
|
+
nativeSessionId: existing.nativeSessionId,
|
|
1520
|
+
path: existing.path,
|
|
1521
|
+
cwd: existing.cwd
|
|
1522
|
+
},
|
|
1523
|
+
resume: "native"
|
|
1524
|
+
};
|
|
1525
|
+
const archive = input.context.archive;
|
|
1526
|
+
if (archive && archive.harness === input.harness && archive.sessionId === input.sessionId && archive.turnId === input.context.throughTurnId) {
|
|
1527
|
+
const restored = await this.restore(input, archive, input.signal).catch((error) => {
|
|
1528
|
+
input.signal?.throwIfAborted();
|
|
1529
|
+
this.options.onRestoreFailed?.(error, {
|
|
1530
|
+
sessionId: input.sessionId,
|
|
1531
|
+
harness: input.harness,
|
|
1532
|
+
unrestorable: error instanceof ArchiveNotRestorableError
|
|
1533
|
+
});
|
|
1534
|
+
return null;
|
|
1535
|
+
});
|
|
1536
|
+
if (restored) {
|
|
1537
|
+
const through = (await readTranscript(restored.path, restored.harness).catch(() => null))?.turns.at(-1)?.key ?? null;
|
|
1538
|
+
if (through) this.options.ingest.adopt(restored, input.sessionId, {
|
|
1539
|
+
turnKey: through,
|
|
1540
|
+
turnId: input.context.throughTurnId
|
|
1541
|
+
});
|
|
1542
|
+
else this.options.ingest.adopt(restored, input.sessionId);
|
|
1543
|
+
return {
|
|
1544
|
+
session: restored,
|
|
1545
|
+
resume: "restored"
|
|
1546
|
+
};
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
const projected = await this.project(input);
|
|
1550
|
+
if (projected.resume !== "new" || !harnessAdapter(input.harness).session.startsWithoutFile) this.options.ingest.adopt(projected.session, input.sessionId);
|
|
1551
|
+
return projected;
|
|
1552
|
+
}
|
|
1553
|
+
async restore(input, archive, signal) {
|
|
1554
|
+
const id = randomUUID();
|
|
1555
|
+
const raw = join(this.options.root, "native", "restored", `${id}.jsonl`);
|
|
1556
|
+
const format = harnessAdapter(input.harness).session.archive;
|
|
1557
|
+
if (!format) throw new ArchiveNotRestorableError(`${input.harness} archives are not restorable`);
|
|
1558
|
+
try {
|
|
1559
|
+
const restored = await this.options.archives.restore(archive, raw, signal);
|
|
1560
|
+
const path = format.target({
|
|
1561
|
+
id,
|
|
1562
|
+
nativeSessionId: restored.nativeSessionId,
|
|
1563
|
+
cwd: input.cwd
|
|
1564
|
+
});
|
|
1565
|
+
const imported = await format.import({
|
|
1566
|
+
source: raw,
|
|
1567
|
+
target: path,
|
|
1568
|
+
nativeSessionId: restored.nativeSessionId,
|
|
1569
|
+
id,
|
|
1570
|
+
cwd: input.cwd,
|
|
1571
|
+
signal
|
|
1572
|
+
});
|
|
1573
|
+
return {
|
|
1574
|
+
harness: input.harness,
|
|
1575
|
+
nativeSessionId: imported.nativeSessionId,
|
|
1576
|
+
path,
|
|
1577
|
+
cwd: input.cwd
|
|
1578
|
+
};
|
|
1579
|
+
} finally {
|
|
1580
|
+
await rm(raw, { force: true }).catch(() => void 0);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
async project(input) {
|
|
1584
|
+
const format = harnessAdapter(input.harness).session;
|
|
1585
|
+
const nativeSessionId = randomUUID();
|
|
1586
|
+
const path = format.path(nativeSessionId, input.cwd);
|
|
1587
|
+
const projection = rebindProjectionNativeSession(await this.projections.project({
|
|
1588
|
+
spaceId: this.options.spaceId,
|
|
1589
|
+
sessionId: input.sessionId,
|
|
1590
|
+
turnId: input.turnId,
|
|
1591
|
+
nativeSessionId,
|
|
1592
|
+
cwd: input.cwd,
|
|
1593
|
+
provider: input.provider,
|
|
1594
|
+
target: input.harness,
|
|
1595
|
+
throughTurnId: input.context.throughTurnId
|
|
1596
|
+
}, input.signal), nativeSessionId);
|
|
1597
|
+
const session = {
|
|
1598
|
+
harness: input.harness,
|
|
1599
|
+
nativeSessionId,
|
|
1600
|
+
path,
|
|
1601
|
+
cwd: input.cwd
|
|
1602
|
+
};
|
|
1603
|
+
if ((!projection.turns.length || !projection.projection.records.length) && format.startsWithoutFile) return {
|
|
1604
|
+
session,
|
|
1605
|
+
resume: "new"
|
|
1606
|
+
};
|
|
1607
|
+
await mkdir(dirname(path), {
|
|
1608
|
+
recursive: true,
|
|
1609
|
+
mode: 448
|
|
1610
|
+
});
|
|
1611
|
+
const temporary = `${path}.${randomUUID()}.projection`;
|
|
1612
|
+
await writeFile(temporary, serializeProjectionRecords(projection.projection.records), { mode: 384 });
|
|
1613
|
+
await rename(temporary, path);
|
|
1614
|
+
return {
|
|
1615
|
+
session,
|
|
1616
|
+
resume: projection.turns.length ? "handoff" : "new"
|
|
1617
|
+
};
|
|
1618
|
+
}
|
|
1619
|
+
};
|
|
1620
|
+
//#endregion
|
|
1621
|
+
//#region src/runtime/native/transport.ts
|
|
1622
|
+
/**
|
|
1623
|
+
* Transcript ingest travels over the existing Runtime WebSocket: one connection, one credential, no
|
|
1624
|
+
* second channel and no local receipts.
|
|
1625
|
+
*/
|
|
1626
|
+
function nativeWebSocketTransport(send) {
|
|
1627
|
+
const call = async (event, options) => {
|
|
1628
|
+
options?.signal?.throwIfAborted();
|
|
1629
|
+
return await send(event);
|
|
1630
|
+
};
|
|
1631
|
+
return {
|
|
1632
|
+
ingest: (event, options) => call(event, options),
|
|
1633
|
+
known: async (turnIds, options) => (await call({
|
|
1634
|
+
type: "known",
|
|
1635
|
+
input: { turnIds }
|
|
1636
|
+
}, options)).turns,
|
|
1637
|
+
progress: (event, options) => call(event, options),
|
|
1638
|
+
status: (sessionId, turnId, controllable, options) => call({
|
|
1639
|
+
type: "status",
|
|
1640
|
+
sessionId,
|
|
1641
|
+
turnId,
|
|
1642
|
+
...controllable === void 0 ? {} : { controllable }
|
|
1643
|
+
}, options)
|
|
1644
|
+
};
|
|
1645
|
+
}
|
|
1646
|
+
//#endregion
|
|
1647
|
+
//#region src/runtime/native/daemon.ts
|
|
1648
|
+
const text = (value) => typeof value === "string" ? value : "";
|
|
1649
|
+
/** Streamed previews reach the web at most this often. */
|
|
1650
|
+
const STREAM_INTERVAL_MS = 250;
|
|
1651
|
+
/** A client Cohub cannot stream is previewed from its file, at most this often. */
|
|
1652
|
+
const FILE_PREVIEW_INTERVAL_MS = 2e3;
|
|
1653
|
+
/** A file preview waits at least this many times as long as its last read took. */
|
|
1654
|
+
const FILE_PREVIEW_COST_FACTOR = 20;
|
|
1655
|
+
/**
|
|
1656
|
+
* Everything the Runtime does with native sessions: the ingest engine (data plane), the Pi and
|
|
1657
|
+
* Codex links (control plane), and the executor that runs Cohub Turns through them.
|
|
1658
|
+
*/
|
|
1659
|
+
var NativeRuntime = class {
|
|
1660
|
+
options;
|
|
1661
|
+
ingest;
|
|
1662
|
+
executor;
|
|
1663
|
+
pi;
|
|
1664
|
+
codex;
|
|
1665
|
+
streams = /* @__PURE__ */ new Map();
|
|
1666
|
+
filePreviews = /* @__PURE__ */ new Map();
|
|
1667
|
+
watched = /* @__PURE__ */ new Map();
|
|
1668
|
+
active = /* @__PURE__ */ new Set();
|
|
1669
|
+
send = null;
|
|
1670
|
+
approvals = new ApprovalBroker();
|
|
1671
|
+
extension = "missing";
|
|
1672
|
+
constructor(options) {
|
|
1673
|
+
this.options = options;
|
|
1674
|
+
this.pi = new PiLink({
|
|
1675
|
+
socketPath: controlSocketPath(options.root),
|
|
1676
|
+
owns: (cwd) => this.ingest.owns(cwd),
|
|
1677
|
+
onEvent: (link, event) => this.onPiEvent(link, event),
|
|
1678
|
+
onConnect: (link) => this.ingest.controlChanged("pi", link.sessionId),
|
|
1679
|
+
onDisconnect: (link) => {
|
|
1680
|
+
this.endStream(`pi:${link.sessionId}`);
|
|
1681
|
+
this.ingest.controlChanged("pi", link.sessionId);
|
|
1682
|
+
if (link.sessionFile) this.ingest.touch(link.sessionFile);
|
|
1683
|
+
},
|
|
1684
|
+
onDroppedLine: (nativeSessionId, bytes) => options.diagnostics.log("warn", "native.pi_line_dropped", {
|
|
1685
|
+
nativeSessionId,
|
|
1686
|
+
bytes
|
|
1687
|
+
}, {
|
|
1688
|
+
component: "native",
|
|
1689
|
+
harness: "pi"
|
|
1690
|
+
})
|
|
1691
|
+
});
|
|
1692
|
+
this.codex = new CodexShared(options.executables.codex || "codex", options.root, Boolean(options.config?.codexShared) && options.harnesses.includes("codex"));
|
|
1693
|
+
this.codex.onConnect((channel) => this.observeCodex(channel));
|
|
1694
|
+
this.codex.onRelease((threadId) => {
|
|
1695
|
+
this.watched.delete(threadId);
|
|
1696
|
+
this.endStream(`codex:${threadId}`);
|
|
1697
|
+
});
|
|
1698
|
+
this.ingest = new NativeIngest({
|
|
1699
|
+
spaceId: options.spaceId,
|
|
1700
|
+
cwd: options.root,
|
|
1701
|
+
harnesses: this.synced,
|
|
1702
|
+
enabledAt: options.config?.enabledAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1703
|
+
root: options.stateRoot,
|
|
1704
|
+
archives: options.archives,
|
|
1705
|
+
hooks: {
|
|
1706
|
+
settled: (state, mtimeMs) => {
|
|
1707
|
+
const link = state.harness === "pi" ? this.pi.find(state.nativeSessionId) : null;
|
|
1708
|
+
if (!link) return null;
|
|
1709
|
+
if (!link.idle) return false;
|
|
1710
|
+
return link.settledAt >= mtimeMs ? true : null;
|
|
1711
|
+
},
|
|
1712
|
+
controllable: (state) => state.harness === "pi" ? this.pi.find(state.nativeSessionId) !== null : state.harness === "codex" && this.codex.enabled && (this.active.has(state.nativeSessionId) || this.watched.has(state.nativeSessionId) || this.codex.driving.has(state.nativeSessionId)),
|
|
1713
|
+
abortTurn: (state) => {
|
|
1714
|
+
(state.harness === "pi" ? this.pi.abort(state.nativeSessionId) : state.harness === "codex" && state.runningTurnKey ? this.codex.interrupt(state.nativeSessionId, state.runningTurnKey) : Promise.resolve(false)).catch((error) => options.diagnostics.log("warn", "native.stop_failed", { error: serializeDiagnosticError(error) }, {
|
|
1715
|
+
harness: state.harness,
|
|
1716
|
+
sessionId: state.sessionId ?? void 0
|
|
1717
|
+
}));
|
|
1718
|
+
},
|
|
1719
|
+
onGrowth: (state) => this.onGrowth(state),
|
|
1720
|
+
onRunning: (state, turnId) => this.onRunning(state, turnId),
|
|
1721
|
+
onError: (error, context) => options.diagnostics.log("warn", "native.sync_pending", {
|
|
1722
|
+
path: context.path,
|
|
1723
|
+
error: serializeDiagnosticError(error)
|
|
1724
|
+
}, {
|
|
1725
|
+
component: "native",
|
|
1726
|
+
harness: context.harness
|
|
1727
|
+
})
|
|
1728
|
+
}
|
|
1729
|
+
});
|
|
1730
|
+
const results = new ExecutionResults(options.stateRoot);
|
|
1731
|
+
this.executor = {
|
|
1732
|
+
cwd: options.root,
|
|
1733
|
+
executables: options.executables,
|
|
1734
|
+
sessions: new NativeSessions({
|
|
1735
|
+
root: options.stateRoot,
|
|
1736
|
+
spaceId: options.spaceId,
|
|
1737
|
+
projectionSource: options.projectionSource,
|
|
1738
|
+
archives: options.archives,
|
|
1739
|
+
ingest: this.ingest,
|
|
1740
|
+
onRestoreFailed: (error, context) => options.diagnostics.log("warn", "native.restore_failed", {
|
|
1741
|
+
error: serializeDiagnosticError(error),
|
|
1742
|
+
unrestorable: context.unrestorable
|
|
1743
|
+
}, {
|
|
1744
|
+
component: "archive",
|
|
1745
|
+
harness: context.harness,
|
|
1746
|
+
sessionId: context.sessionId
|
|
1747
|
+
})
|
|
1748
|
+
}),
|
|
1749
|
+
results,
|
|
1750
|
+
ingest: this.ingest,
|
|
1751
|
+
archives: options.archives,
|
|
1752
|
+
pi: this.pi,
|
|
1753
|
+
codex: this.codex,
|
|
1754
|
+
approvals: this.approvals,
|
|
1755
|
+
piExtension: piExtensionSource(),
|
|
1756
|
+
diagnostics: options.diagnostics
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
get synced() {
|
|
1760
|
+
const { config, root, harnesses } = this.options;
|
|
1761
|
+
return config?.root === root ? config.harnesses.filter((harness) => harnesses.includes(harness)) : [];
|
|
1762
|
+
}
|
|
1763
|
+
async start(signal) {
|
|
1764
|
+
const degraded = (event) => (error) => this.options.diagnostics.log("warn", event, { error: serializeDiagnosticError(error) }, { component: "native" });
|
|
1765
|
+
await this.ingest.load().catch(degraded("native.ledger_unreadable"));
|
|
1766
|
+
await this.refreshScope();
|
|
1767
|
+
if (this.options.harnesses.includes("pi")) {
|
|
1768
|
+
const version = await harnessVersion(this.options.executables.pi || "pi");
|
|
1769
|
+
if (!atLeast(version, PI_MIN_VERSION)) this.pi.unavailable = `Pi ${formatVersion(version)} predates the Cohub extension (${PI_MIN_VERSION.join(".")}+); upgrade Pi, then restart the Runtime`;
|
|
1770
|
+
else await this.pi.listen(signal).catch((error) => {
|
|
1771
|
+
this.pi.unavailable = `Pi control socket unavailable (${serializeDiagnosticError(error).message}); restart the Runtime`;
|
|
1772
|
+
degraded("native.pi_socket_unavailable")(error);
|
|
1773
|
+
});
|
|
1774
|
+
this.extension = await piExtensionState().catch(() => "missing");
|
|
1775
|
+
}
|
|
1776
|
+
await this.ingest.watch(signal).catch(degraded("native.watch_unavailable"));
|
|
1777
|
+
if (this.codex.enabled) this.codex.get();
|
|
1778
|
+
}
|
|
1779
|
+
/** `approvals`: the Gateway relays approval decisions back. */
|
|
1780
|
+
connect(send, features = {}) {
|
|
1781
|
+
this.send = send;
|
|
1782
|
+
this.ingest.connect(send ? nativeWebSocketTransport(send) : null);
|
|
1783
|
+
this.approvals.connect(send && features.approvals ? send : null);
|
|
1784
|
+
}
|
|
1785
|
+
stop(sessionId, turnId) {
|
|
1786
|
+
return this.ingest.stop(sessionId, turnId);
|
|
1787
|
+
}
|
|
1788
|
+
status() {
|
|
1789
|
+
const ingest = this.ingest.status();
|
|
1790
|
+
return {
|
|
1791
|
+
synced: this.synced,
|
|
1792
|
+
transcripts: ingest.transcripts,
|
|
1793
|
+
running: ingest.running,
|
|
1794
|
+
pi: this.options.harnesses.includes("pi") ? {
|
|
1795
|
+
extension: this.extension,
|
|
1796
|
+
connected: this.pi.list().length,
|
|
1797
|
+
unavailable: this.pi.unavailable
|
|
1798
|
+
} : null,
|
|
1799
|
+
codex: this.options.harnesses.includes("codex") ? {
|
|
1800
|
+
control: this.codex.enabled ? "shared" : "private",
|
|
1801
|
+
watching: this.watched.size
|
|
1802
|
+
} : null,
|
|
1803
|
+
import: ingest.import
|
|
1804
|
+
};
|
|
1805
|
+
}
|
|
1806
|
+
async control(action, message) {
|
|
1807
|
+
if (action === "reload") return await this.reload();
|
|
1808
|
+
if (action !== "import") throw new Error("Unknown Runtime control request");
|
|
1809
|
+
if (!this.synced.length) throw new Error("Native sync is not enabled for this directory; run cohub runtime up");
|
|
1810
|
+
const filter = {
|
|
1811
|
+
...Array.isArray(message.harnesses) && message.harnesses.length ? { harnesses: message.harnesses } : {},
|
|
1812
|
+
...typeof message.nativeSessionId === "string" && message.nativeSessionId ? { nativeSessionId: message.nativeSessionId } : {}
|
|
1813
|
+
};
|
|
1814
|
+
if (message.command === "pause") return this.ingest.pauseImport();
|
|
1815
|
+
if (message.command === "start") return await this.ingest.startImport(filter, typeof message.concurrency === "number" ? message.concurrency : 4);
|
|
1816
|
+
const plan = await this.ingest.plan(filter);
|
|
1817
|
+
return {
|
|
1818
|
+
files: plan.length,
|
|
1819
|
+
bytes: plan.reduce((sum, candidate) => sum + candidate.size, 0),
|
|
1820
|
+
sample: plan.slice(0, 20).map(({ harness, path, nativeSessionId, mtimeMs, size }) => ({
|
|
1821
|
+
harness,
|
|
1822
|
+
path,
|
|
1823
|
+
nativeSessionId,
|
|
1824
|
+
mtimeMs,
|
|
1825
|
+
size
|
|
1826
|
+
}))
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
async reload() {
|
|
1830
|
+
await this.refreshScope();
|
|
1831
|
+
this.options.config = await readNativeConfig(this.options.stateRoot, this.options.identity);
|
|
1832
|
+
this.ingest.configure(this.synced, this.options.config?.enabledAt ?? (/* @__PURE__ */ new Date()).toISOString());
|
|
1833
|
+
this.codex.enabled = Boolean(this.options.config?.codexShared) && this.options.harnesses.includes("codex");
|
|
1834
|
+
if (this.codex.enabled) this.codex.get();
|
|
1835
|
+
if (this.options.harnesses.includes("pi")) this.extension = await piExtensionState().catch(() => "missing");
|
|
1836
|
+
return this.status();
|
|
1837
|
+
}
|
|
1838
|
+
async refreshScope() {
|
|
1839
|
+
const { bindings } = await readRuntimeSpaceBindings().catch(() => ({ bindings: [] }));
|
|
1840
|
+
this.ingest.exclude(bindings.filter((binding) => binding.key === this.options.identity && binding.spaceId !== this.options.spaceId).map((binding) => binding.root));
|
|
1841
|
+
}
|
|
1842
|
+
async close(signal) {
|
|
1843
|
+
for (const stream of this.streams.values()) stream.progress.dispose();
|
|
1844
|
+
for (const preview of this.filePreviews.values()) {
|
|
1845
|
+
preview.progress.dispose();
|
|
1846
|
+
if (preview.timer) clearTimeout(preview.timer);
|
|
1847
|
+
}
|
|
1848
|
+
await Promise.allSettled([
|
|
1849
|
+
this.pi.close(),
|
|
1850
|
+
this.codex.close(),
|
|
1851
|
+
this.ingest.close(signal)
|
|
1852
|
+
]);
|
|
1853
|
+
}
|
|
1854
|
+
sink(harness, nativeSessionId) {
|
|
1855
|
+
return (progress) => {
|
|
1856
|
+
const running = this.ingest.running(harness, nativeSessionId);
|
|
1857
|
+
if (!running?.sessionId || !running.runningTurnId || !this.send) return null;
|
|
1858
|
+
return this.send({
|
|
1859
|
+
type: "progress",
|
|
1860
|
+
sessionId: running.sessionId,
|
|
1861
|
+
turnId: running.runningTurnId,
|
|
1862
|
+
progress
|
|
1863
|
+
}).catch(() => ({ accepted: false }));
|
|
1864
|
+
};
|
|
1865
|
+
}
|
|
1866
|
+
/**
|
|
1867
|
+
* A connected Pi. A user prompt starting and the agent settling are the two moments its file has
|
|
1868
|
+
* something to persist; everything between streams as a preview of a Turn someone runs there.
|
|
1869
|
+
*/
|
|
1870
|
+
onPiEvent(link, event) {
|
|
1871
|
+
const key = `pi:${link.sessionId}`;
|
|
1872
|
+
const type = text(event.type);
|
|
1873
|
+
const userPrompt = type === "message_end" && record$1(event.message).role === "user";
|
|
1874
|
+
if (userPrompt || type === "agent_settled") {
|
|
1875
|
+
if (link.sessionFile) this.ingest.touch(link.sessionFile);
|
|
1876
|
+
}
|
|
1877
|
+
if (type === "agent_start") this.endStream(key);
|
|
1878
|
+
if (type === "agent_settled") {
|
|
1879
|
+
this.endStream(key);
|
|
1880
|
+
return;
|
|
1881
|
+
}
|
|
1882
|
+
this.ingest.alive("pi", link.sessionId);
|
|
1883
|
+
if (!this.ingest.running("pi", link.sessionId) && !userPrompt && !this.streams.has(key)) return;
|
|
1884
|
+
this.stream(key, "pi", link.sessionId).translator.push(event);
|
|
1885
|
+
}
|
|
1886
|
+
stream(key, harness, nativeSessionId) {
|
|
1887
|
+
let stream = this.streams.get(key);
|
|
1888
|
+
if (!stream) {
|
|
1889
|
+
const progress = new LiveProgress(this.sink(harness, nativeSessionId), STREAM_INTERVAL_MS);
|
|
1890
|
+
const emit = (update) => progress.apply(update);
|
|
1891
|
+
stream = {
|
|
1892
|
+
progress,
|
|
1893
|
+
translator: harness === "pi" ? piTranslator(emit) : codexTranslator(emit, {
|
|
1894
|
+
provider: null,
|
|
1895
|
+
model: null
|
|
1896
|
+
})
|
|
1897
|
+
};
|
|
1898
|
+
this.streams.set(key, stream);
|
|
1899
|
+
}
|
|
1900
|
+
return stream;
|
|
1901
|
+
}
|
|
1902
|
+
endStream(key) {
|
|
1903
|
+
this.streams.get(key)?.progress.dispose();
|
|
1904
|
+
this.streams.delete(key);
|
|
1905
|
+
}
|
|
1906
|
+
endFilePreview(path) {
|
|
1907
|
+
const preview = this.filePreviews.get(path);
|
|
1908
|
+
if (!preview) return;
|
|
1909
|
+
preview.progress.dispose();
|
|
1910
|
+
if (preview.timer) clearTimeout(preview.timer);
|
|
1911
|
+
this.filePreviews.delete(path);
|
|
1912
|
+
}
|
|
1913
|
+
observeCodex(channel) {
|
|
1914
|
+
const offEvent = channel.onEvent((event) => this.onCodexEvent(event));
|
|
1915
|
+
const offClose = channel.onClose(() => {
|
|
1916
|
+
offEvent();
|
|
1917
|
+
offClose();
|
|
1918
|
+
const lost = /* @__PURE__ */ new Set([...this.watched.keys(), ...this.active]);
|
|
1919
|
+
this.watched.clear();
|
|
1920
|
+
this.active.clear();
|
|
1921
|
+
for (const key of [...this.streams.keys()]) if (key.startsWith("codex:")) this.endStream(key);
|
|
1922
|
+
for (const threadId of lost) this.ingest.controlChanged("codex", threadId);
|
|
1923
|
+
});
|
|
1924
|
+
channel.request("thread/loaded/list", {}).then((result) => {
|
|
1925
|
+
for (const threadId of Array.isArray(result.data) ? result.data : []) if (typeof threadId === "string") this.watchCodexThread(channel, threadId, false);
|
|
1926
|
+
}).catch(() => void 0);
|
|
1927
|
+
}
|
|
1928
|
+
async watchCodexThread(channel, threadId, busy) {
|
|
1929
|
+
if (this.watched.has(threadId)) return;
|
|
1930
|
+
const read = await channel.request("thread/read", { threadId }).catch(() => null);
|
|
1931
|
+
const thread = record$1(read?.thread);
|
|
1932
|
+
if (!busy && record$1(thread.status).type !== "active") return;
|
|
1933
|
+
if (!this.ingest.owns(text(thread.cwd)) || thread.parentThreadId || thread.ephemeral === true) return;
|
|
1934
|
+
this.active.add(threadId);
|
|
1935
|
+
if (this.codex.driving.has(threadId)) return;
|
|
1936
|
+
this.watched.set(threadId, { path: text(thread.path) || null });
|
|
1937
|
+
this.ingest.controlChanged("codex", threadId);
|
|
1938
|
+
await this.codex.join(threadId).catch((error) => {
|
|
1939
|
+
this.watched.delete(threadId);
|
|
1940
|
+
this.options.diagnostics.log("debug", "native.codex_join_failed", { error: serializeDiagnosticError(error) }, { harness: "codex" });
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
onCodexEvent(event) {
|
|
1944
|
+
if (event.id != null) return;
|
|
1945
|
+
const threadId = text(event.params.threadId);
|
|
1946
|
+
if (!threadId) return;
|
|
1947
|
+
if (event.method === "thread/status/changed") {
|
|
1948
|
+
if (record$1(event.params.status).type === "active") this.codex.get().then((channel) => channel && this.watchCodexThread(channel, threadId, true));
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
const watched = this.watched.get(threadId);
|
|
1952
|
+
if (!watched || this.codex.driving.has(threadId)) return;
|
|
1953
|
+
this.ingest.alive("codex", threadId);
|
|
1954
|
+
const key = `codex:${threadId}`;
|
|
1955
|
+
if (event.method === "turn/started") this.endStream(key);
|
|
1956
|
+
if (event.method === "turn/completed") {
|
|
1957
|
+
this.endStream(key);
|
|
1958
|
+
if (watched.path) this.ingest.touch(watched.path);
|
|
1959
|
+
this.codex.release(threadId);
|
|
1960
|
+
return;
|
|
1961
|
+
}
|
|
1962
|
+
this.stream(key, "codex", threadId).translator.push(event);
|
|
1963
|
+
}
|
|
1964
|
+
/**
|
|
1965
|
+
* A terminal Pi runs many Turns in one process; once the ledger knows which one is running, its
|
|
1966
|
+
* tools are told, so a `cohub` call from a tool names the right Space, Session and Turn.
|
|
1967
|
+
*/
|
|
1968
|
+
onRunning(state, turnId) {
|
|
1969
|
+
if (!turnId) this.endFilePreview(state.path);
|
|
1970
|
+
if (state.harness !== "pi" || !state.sessionId || !this.pi.find(state.nativeSessionId)) return;
|
|
1971
|
+
this.pi.context(state.nativeSessionId, {
|
|
1972
|
+
COHUB_SPACE_ID: this.options.spaceId,
|
|
1973
|
+
COHUB_SESSION_ID: state.sessionId,
|
|
1974
|
+
COHUB_TURN_ID: turnId
|
|
1975
|
+
}).catch(() => void 0);
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* A running Turn's file grew. A connected client streams it already; otherwise the preview is
|
|
1979
|
+
* read from the file, at a pace set by a timer, not by every write.
|
|
1980
|
+
*/
|
|
1981
|
+
onGrowth(state) {
|
|
1982
|
+
this.ingest.alive(state.harness, state.nativeSessionId);
|
|
1983
|
+
if (state.harness === "codex" && this.codex.enabled && !this.watched.has(state.nativeSessionId)) this.codex.get();
|
|
1984
|
+
if (state.harness === "pi" ? this.pi.find(state.nativeSessionId) !== null : this.watched.has(state.nativeSessionId)) return;
|
|
1985
|
+
let preview = this.filePreviews.get(state.path);
|
|
1986
|
+
if (!preview) {
|
|
1987
|
+
preview = {
|
|
1988
|
+
progress: new LiveProgress(this.sink(state.harness, state.nativeSessionId), 0),
|
|
1989
|
+
timer: null,
|
|
1990
|
+
readMs: 0
|
|
1991
|
+
};
|
|
1992
|
+
this.filePreviews.set(state.path, preview);
|
|
1993
|
+
}
|
|
1994
|
+
const entry = preview;
|
|
1995
|
+
entry.timer ??= setTimeout(() => {
|
|
1996
|
+
if (!state.runningTurnId) {
|
|
1997
|
+
this.endFilePreview(state.path);
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
const startedAt = performance.now();
|
|
2001
|
+
readTranscript(state.path, state.harness).then((transcript) => {
|
|
2002
|
+
if (!state.runningTurnId) {
|
|
2003
|
+
this.endFilePreview(state.path);
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
const tail = transcript.turns.at(-1);
|
|
2007
|
+
entry.progress.replace((tail?.messages ?? []).map((message) => ({
|
|
2008
|
+
content: message.content,
|
|
2009
|
+
provider: message.provider ?? null,
|
|
2010
|
+
model: message.model ?? null
|
|
2011
|
+
})));
|
|
2012
|
+
}).catch(() => void 0).finally(() => {
|
|
2013
|
+
entry.readMs = performance.now() - startedAt;
|
|
2014
|
+
entry.timer = null;
|
|
2015
|
+
});
|
|
2016
|
+
}, Math.max(FILE_PREVIEW_INTERVAL_MS, FILE_PREVIEW_COST_FACTOR * entry.readMs));
|
|
2017
|
+
entry.timer.unref?.();
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
//#endregion
|
|
2021
|
+
//#region src/runtime/supervisor.ts
|
|
2022
|
+
const DISPLAY_ANSWER_MS = 1e4;
|
|
2023
|
+
const ACTIVITY_MS = 6e4;
|
|
2024
|
+
function sandboxOutputLevel(value, stream) {
|
|
2025
|
+
const level = typeof value === "string" ? value.toLowerCase() : "";
|
|
2026
|
+
if ([
|
|
2027
|
+
"debug",
|
|
2028
|
+
"info",
|
|
2029
|
+
"warn",
|
|
2030
|
+
"error"
|
|
2031
|
+
].includes(level)) return level;
|
|
2032
|
+
return stream === "stderr" ? "warn" : "debug";
|
|
2033
|
+
}
|
|
2034
|
+
/**
|
|
2035
|
+
* Windows cannot hand sandboxd an extra inherited pipe, so control frames use a
|
|
2036
|
+
* named pipe instead. Only the first client is accepted; the name is unguessable.
|
|
2037
|
+
*/
|
|
2038
|
+
async function listenWindowsControlPipe() {
|
|
2039
|
+
const path = `\\\\.\\pipe\\cohub-sandboxd-${randomUUID()}`;
|
|
2040
|
+
const stream = new PassThrough();
|
|
2041
|
+
const server = createServer((socket) => {
|
|
2042
|
+
server.close();
|
|
2043
|
+
socket.on("error", () => stream.end());
|
|
2044
|
+
socket.pipe(stream);
|
|
2045
|
+
});
|
|
2046
|
+
await new Promise((resolve, reject) => {
|
|
2047
|
+
server.once("error", reject);
|
|
2048
|
+
server.listen(path, () => {
|
|
2049
|
+
server.removeListener("error", reject);
|
|
2050
|
+
resolve();
|
|
2051
|
+
});
|
|
2052
|
+
});
|
|
2053
|
+
return {
|
|
2054
|
+
path,
|
|
2055
|
+
stream,
|
|
2056
|
+
close: () => {
|
|
2057
|
+
server.close();
|
|
2058
|
+
stream.end();
|
|
2059
|
+
}
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
async function runRuntime(config, onState, externalSignal, onDiagnostic) {
|
|
2063
|
+
const controller = new AbortController();
|
|
2064
|
+
const signal = externalSignal ? AbortSignal.any([externalSignal, controller.signal]) : controller.signal;
|
|
2065
|
+
const stop = () => controller.abort();
|
|
2066
|
+
process.once("SIGINT", stop);
|
|
2067
|
+
process.once("SIGTERM", stop);
|
|
2068
|
+
appendCliToPath();
|
|
2069
|
+
const space = createClient().space(config.spaceId);
|
|
2070
|
+
const stateRoot = runtimeStateRoot(config.spaceId);
|
|
2071
|
+
const archives = new RuntimeArchiveStore(join(stateRoot, "archives"), space);
|
|
2072
|
+
const consoleSink = config.background ? void 0 : createDiagnosticConsole(config.verbose);
|
|
2073
|
+
const diagnostics = new RuntimeDiagnostics({
|
|
2074
|
+
root: stateRoot,
|
|
2075
|
+
spaceId: config.spaceId,
|
|
2076
|
+
runtimeId: randomUUID(),
|
|
2077
|
+
onEvent: (event) => {
|
|
2078
|
+
consoleSink?.(event);
|
|
2079
|
+
onDiagnostic?.(event);
|
|
2080
|
+
}
|
|
2081
|
+
});
|
|
2082
|
+
archives.setErrorReporter((error, index) => diagnostics.log("warn", "archive.upload_pending", { error: serializeDiagnosticError(error) }, {
|
|
2083
|
+
component: "archive",
|
|
2084
|
+
sessionId: index?.sessionId,
|
|
2085
|
+
turnId: index?.turnId,
|
|
2086
|
+
harness: index?.harness
|
|
2087
|
+
}));
|
|
2088
|
+
const native = new NativeRuntime({
|
|
2089
|
+
spaceId: config.spaceId,
|
|
2090
|
+
root: config.root,
|
|
2091
|
+
stateRoot,
|
|
2092
|
+
harnesses: config.harnesses,
|
|
2093
|
+
executables: config.executables,
|
|
2094
|
+
identity: config.identity,
|
|
2095
|
+
config: await readNativeConfig(stateRoot, config.identity).catch(() => null),
|
|
2096
|
+
archives,
|
|
2097
|
+
projectionSource: space,
|
|
2098
|
+
diagnostics
|
|
2099
|
+
});
|
|
2100
|
+
let status = {
|
|
2101
|
+
spaceId: config.spaceId,
|
|
2102
|
+
root: config.root,
|
|
2103
|
+
runtimeId: diagnostics.runtimeId,
|
|
2104
|
+
pid: process.pid,
|
|
2105
|
+
version: CLI_VERSION,
|
|
2106
|
+
harnesses: config.harnesses,
|
|
2107
|
+
background: config.background,
|
|
2108
|
+
...config.display ? { display: config.display } : {},
|
|
2109
|
+
state: "starting",
|
|
2110
|
+
harnessConnected: false,
|
|
2111
|
+
workspaceConnected: false,
|
|
2112
|
+
diagnosticsPath: diagnostics.directory
|
|
2113
|
+
};
|
|
2114
|
+
const summary = () => ({
|
|
2115
|
+
...status,
|
|
2116
|
+
native: native.status()
|
|
2117
|
+
});
|
|
2118
|
+
let instance;
|
|
2119
|
+
let hasBeenReady = false;
|
|
2120
|
+
const update = (patch) => {
|
|
2121
|
+
const next = {
|
|
2122
|
+
...status,
|
|
2123
|
+
...patch
|
|
2124
|
+
};
|
|
2125
|
+
if (next.state !== "stopping" && next.state !== "attention") next.state = next.harnessConnected && next.workspaceConnected ? "ready" : hasBeenReady ? "reconnecting" : "starting";
|
|
2126
|
+
if (JSON.stringify(status) === JSON.stringify(next)) return;
|
|
2127
|
+
const becameReady = next.state === "ready" && status.state !== "ready";
|
|
2128
|
+
status = next;
|
|
2129
|
+
if (becameReady) {
|
|
2130
|
+
hasBeenReady = true;
|
|
2131
|
+
diagnostics.log("info", "runtime.available");
|
|
2132
|
+
}
|
|
2133
|
+
onState({ ...status });
|
|
2134
|
+
instance?.changed();
|
|
2135
|
+
};
|
|
2136
|
+
let bridgeTask;
|
|
2137
|
+
let retryDisconnectedBridge;
|
|
2138
|
+
let nativeStarted = false;
|
|
2139
|
+
let tokenInFlight = null;
|
|
2140
|
+
const executions = /* @__PURE__ */ new Map();
|
|
2141
|
+
let bridgeControl = null;
|
|
2142
|
+
let workspace = null;
|
|
2143
|
+
let displayAnswer = null;
|
|
2144
|
+
const applyKeepAwake = async () => {
|
|
2145
|
+
if (bridgeControl?.features.includes("keepAwake")) bridgeControl.send({
|
|
2146
|
+
type: "keepAwake",
|
|
2147
|
+
enabled: (await readRuntimePreferences()).keepAwake
|
|
2148
|
+
});
|
|
2149
|
+
};
|
|
2150
|
+
const setDisplay = async (spec) => {
|
|
2151
|
+
if (bridgeControl && !bridgeControl.features.includes("display")) throw new Error("This Runtime cannot change its screen while running; reconnect it");
|
|
2152
|
+
if (!spec) update({
|
|
2153
|
+
display: void 0,
|
|
2154
|
+
displayOnRequest: void 0,
|
|
2155
|
+
displayNeeds: void 0
|
|
2156
|
+
});
|
|
2157
|
+
if (!bridgeControl) {
|
|
2158
|
+
if (!spec) return summary();
|
|
2159
|
+
throw new Error("The file bridge is restarting; try again");
|
|
2160
|
+
}
|
|
2161
|
+
const { send } = bridgeControl;
|
|
2162
|
+
const before = status.displayOnRequest;
|
|
2163
|
+
if (spec) update({ displayOnRequest: true });
|
|
2164
|
+
const frame = await new Promise((resolve, reject) => {
|
|
2165
|
+
const timer = setTimeout(() => {
|
|
2166
|
+
displayAnswer = null;
|
|
2167
|
+
if (spec) send({
|
|
2168
|
+
type: "display",
|
|
2169
|
+
spec: ""
|
|
2170
|
+
});
|
|
2171
|
+
update({
|
|
2172
|
+
display: void 0,
|
|
2173
|
+
displayOnRequest: void 0,
|
|
2174
|
+
displayNeeds: void 0
|
|
2175
|
+
});
|
|
2176
|
+
reject(/* @__PURE__ */ new Error("The file bridge did not answer"));
|
|
2177
|
+
}, DISPLAY_ANSWER_MS);
|
|
2178
|
+
displayAnswer = (answer) => {
|
|
2179
|
+
if (!answer.error && answer.spec !== spec) return;
|
|
2180
|
+
clearTimeout(timer);
|
|
2181
|
+
displayAnswer = null;
|
|
2182
|
+
resolve(answer);
|
|
2183
|
+
};
|
|
2184
|
+
send({
|
|
2185
|
+
type: "display",
|
|
2186
|
+
spec
|
|
2187
|
+
});
|
|
2188
|
+
});
|
|
2189
|
+
if (frame.error) {
|
|
2190
|
+
update({ displayOnRequest: before });
|
|
2191
|
+
throw new Error(frame.error);
|
|
2192
|
+
}
|
|
2193
|
+
return summary();
|
|
2194
|
+
};
|
|
2195
|
+
const token = (forceRefresh = false) => {
|
|
2196
|
+
tokenInFlight ??= (async () => {
|
|
2197
|
+
if (currentIdentityKey() !== config.identity) throw new AuthRequiredError("Runtime account changed; sign in to the original account");
|
|
2198
|
+
const value = await resolveAccessToken({ forceRefresh });
|
|
2199
|
+
if (!value) throw new AuthRequiredError();
|
|
2200
|
+
if (currentIdentityKey() !== config.identity) throw new AuthRequiredError("Runtime account changed");
|
|
2201
|
+
return value;
|
|
2202
|
+
})().finally(() => {
|
|
2203
|
+
tokenInFlight = null;
|
|
2204
|
+
});
|
|
2205
|
+
return tokenInFlight;
|
|
2206
|
+
};
|
|
2207
|
+
try {
|
|
2208
|
+
instance = await ownRuntimeInstance(runtimeInstanceDirectory(config.identity, config.spaceId), summary, async (force) => {
|
|
2209
|
+
if (!force) {
|
|
2210
|
+
for await (const batch of native.executor.results.pendingBatches()) if (batch.length) throw new Error(`${UNCONFIRMED_WORK}. Use down --yes to stop; results and files are retained`);
|
|
2211
|
+
}
|
|
2212
|
+
update({ state: "stopping" });
|
|
2213
|
+
setTimeout(stop, 30);
|
|
2214
|
+
}, (action, message) => {
|
|
2215
|
+
if (action === "display") return setDisplay(String(message.spec ?? ""));
|
|
2216
|
+
if (action === "keepAwake") return applyKeepAwake();
|
|
2217
|
+
if (action === "workspace") return Promise.resolve(status.state === "ready" ? workspace : null);
|
|
2218
|
+
return native.control(action, message);
|
|
2219
|
+
});
|
|
2220
|
+
onState({ ...status });
|
|
2221
|
+
diagnostics.log("info", "runtime.cli_started", {
|
|
2222
|
+
platform: process.platform,
|
|
2223
|
+
node: process.versions.node,
|
|
2224
|
+
harnesses: config.harnesses
|
|
2225
|
+
});
|
|
2226
|
+
const [binary, capabilities] = await Promise.all([ensureSandboxdBinary({ onStatus: (message) => diagnostics.log("info", "sandboxd.download", { message }) }), config.capabilities ?? discoverHarnesses(config.harnesses, config.executables, config.root)]);
|
|
2227
|
+
signal.throwIfAborted();
|
|
2228
|
+
const url = new URL(resolveWebsocketUrl());
|
|
2229
|
+
url.pathname = url.pathname.replace(/\/ws$/, "/runtime/relay");
|
|
2230
|
+
const relay = new URL(url);
|
|
2231
|
+
relay.pathname = relay.pathname.replace(/\/runtime\/relay$/, "/sandbox/relay");
|
|
2232
|
+
const runBridge = async () => {
|
|
2233
|
+
let attempts = 0;
|
|
2234
|
+
while (!signal.aborted) {
|
|
2235
|
+
if (!status.harnessConnected) {
|
|
2236
|
+
await setTimeout$1(500, void 0, { signal }).catch(() => void 0);
|
|
2237
|
+
continue;
|
|
2238
|
+
}
|
|
2239
|
+
const startedAt = Date.now();
|
|
2240
|
+
let refreshTimer;
|
|
2241
|
+
let probeTimer;
|
|
2242
|
+
let managed = false;
|
|
2243
|
+
let childStopped = false;
|
|
2244
|
+
let bridgeDisconnected = false;
|
|
2245
|
+
let terminating = false;
|
|
2246
|
+
let recoveryTimer;
|
|
2247
|
+
let controlPipe = null;
|
|
2248
|
+
try {
|
|
2249
|
+
const initialToken = await token();
|
|
2250
|
+
signal.throwIfAborted();
|
|
2251
|
+
if (process.platform === "win32") controlPipe = await listenWindowsControlPipe();
|
|
2252
|
+
const spawnedScreen = status.display ?? "";
|
|
2253
|
+
const localToken = randomBytes(32).toString("base64url");
|
|
2254
|
+
const bridge = spawn(binary, [
|
|
2255
|
+
"--local",
|
|
2256
|
+
"--space",
|
|
2257
|
+
config.spaceId,
|
|
2258
|
+
"--root",
|
|
2259
|
+
config.root,
|
|
2260
|
+
"--relay",
|
|
2261
|
+
process.env.COHUB_RELAY_URL?.trim() || relay.toString()
|
|
2262
|
+
], {
|
|
2263
|
+
stdio: controlPipe ? [
|
|
2264
|
+
"pipe",
|
|
2265
|
+
"pipe",
|
|
2266
|
+
"pipe"
|
|
2267
|
+
] : [
|
|
2268
|
+
"pipe",
|
|
2269
|
+
"pipe",
|
|
2270
|
+
"pipe",
|
|
2271
|
+
"pipe"
|
|
2272
|
+
],
|
|
2273
|
+
windowsHide: true,
|
|
2274
|
+
env: {
|
|
2275
|
+
...process.env,
|
|
2276
|
+
COHUB_RELAY_TOKEN: initialToken,
|
|
2277
|
+
COHUB_LOCAL_TOKEN: localToken,
|
|
2278
|
+
COHUB_RUNTIME_ID: status.runtimeId,
|
|
2279
|
+
COHUB_LOG_FORMAT: "json",
|
|
2280
|
+
COHUB_RUNTIME_MANAGED: "1",
|
|
2281
|
+
COHUB_DISPLAY: spawnedScreen,
|
|
2282
|
+
...controlPipe ? { COHUB_RUNTIME_CONTROL_PIPE: controlPipe.path } : {}
|
|
2283
|
+
}
|
|
2284
|
+
});
|
|
2285
|
+
bridge.stdin?.on("error", () => void 0);
|
|
2286
|
+
const closed = new Promise((resolve) => {
|
|
2287
|
+
let drainTimer;
|
|
2288
|
+
bridge.once("error", (error) => diagnostics.log("error", "sandboxd.process_error", { error: serializeDiagnosticError(error) }));
|
|
2289
|
+
bridge.once("exit", (code, exitSignal) => {
|
|
2290
|
+
childStopped = true;
|
|
2291
|
+
clearTimeout(recoveryTimer);
|
|
2292
|
+
recoveryTimer = void 0;
|
|
2293
|
+
if (!signal.aborted) diagnostics.log("warn", "sandboxd.process_exit", {
|
|
2294
|
+
code,
|
|
2295
|
+
signal: exitSignal
|
|
2296
|
+
});
|
|
2297
|
+
drainTimer = setTimeout(() => {
|
|
2298
|
+
diagnostics.log("warn", "sandboxd.stdio_drain_timeout");
|
|
2299
|
+
for (const stream of bridge.stdio) stream?.destroy();
|
|
2300
|
+
}, 1e3);
|
|
2301
|
+
});
|
|
2302
|
+
bridge.once("close", () => {
|
|
2303
|
+
childStopped = true;
|
|
2304
|
+
clearTimeout(drainTimer);
|
|
2305
|
+
resolve();
|
|
2306
|
+
});
|
|
2307
|
+
});
|
|
2308
|
+
for (const streamName of ["stdout", "stderr"]) {
|
|
2309
|
+
const stream = bridge[streamName];
|
|
2310
|
+
if (!stream) continue;
|
|
2311
|
+
createInterface({ input: stream }).on("line", (line) => {
|
|
2312
|
+
let parsed = null;
|
|
2313
|
+
try {
|
|
2314
|
+
const value = JSON.parse(line);
|
|
2315
|
+
if (value && typeof value === "object" && !Array.isArray(value)) parsed = value;
|
|
2316
|
+
} catch {}
|
|
2317
|
+
const data = parsed ? Object.fromEntries(Object.entries(parsed).filter(([key]) => ![
|
|
2318
|
+
"msg",
|
|
2319
|
+
"level",
|
|
2320
|
+
"time"
|
|
2321
|
+
].includes(key))) : {};
|
|
2322
|
+
diagnostics.log(sandboxOutputLevel(parsed?.level, streamName), "sandboxd.log", {
|
|
2323
|
+
...data,
|
|
2324
|
+
message: parsed?.msg ?? line
|
|
2325
|
+
}, { component: "sandboxd" });
|
|
2326
|
+
});
|
|
2327
|
+
}
|
|
2328
|
+
const control = controlPipe ? controlPipe.stream : bridge.stdio[3];
|
|
2329
|
+
createInterface({ input: control }).on("line", (line) => {
|
|
2330
|
+
try {
|
|
2331
|
+
const event = JSON.parse(line);
|
|
2332
|
+
if (event.type === "hello") managed = true;
|
|
2333
|
+
if (event.type === "features") {
|
|
2334
|
+
bridgeControl = {
|
|
2335
|
+
features: event.features,
|
|
2336
|
+
send: (frame) => bridge.stdin?.write(`${JSON.stringify(frame)}\n`)
|
|
2337
|
+
};
|
|
2338
|
+
applyKeepAwake().catch(() => void 0);
|
|
2339
|
+
if ((status.display ?? "") !== spawnedScreen) bridgeControl.send({
|
|
2340
|
+
type: "display",
|
|
2341
|
+
spec: status.display ?? ""
|
|
2342
|
+
});
|
|
2343
|
+
}
|
|
2344
|
+
if (event.type === "local" && Number.isInteger(event.port)) {
|
|
2345
|
+
workspace = {
|
|
2346
|
+
url: `http://127.0.0.1:${event.port}`,
|
|
2347
|
+
token: localToken
|
|
2348
|
+
};
|
|
2349
|
+
update({ direct: true });
|
|
2350
|
+
}
|
|
2351
|
+
if (event.type === "display") {
|
|
2352
|
+
update({
|
|
2353
|
+
display: event.spec || void 0,
|
|
2354
|
+
displayNeeds: event.needs?.length ? event.needs : void 0
|
|
2355
|
+
});
|
|
2356
|
+
displayAnswer?.(event);
|
|
2357
|
+
}
|
|
2358
|
+
if (event.type === "connected" || event.type === "disconnected") {
|
|
2359
|
+
const connected = event.type === "connected";
|
|
2360
|
+
bridgeDisconnected = !connected;
|
|
2361
|
+
update({ workspaceConnected: connected });
|
|
2362
|
+
diagnostics.log(connected ? "info" : "warn", `sandboxd.${event.type}`);
|
|
2363
|
+
retryDisconnectedBridge?.();
|
|
2364
|
+
}
|
|
2365
|
+
} catch {
|
|
2366
|
+
diagnostics.log("warn", "sandboxd.control_invalid");
|
|
2367
|
+
}
|
|
2368
|
+
});
|
|
2369
|
+
const refresh = async () => {
|
|
2370
|
+
try {
|
|
2371
|
+
const next = await token();
|
|
2372
|
+
if (!childStopped && managed && !signal.aborted) bridge.stdin?.write(`${JSON.stringify({
|
|
2373
|
+
type: "auth",
|
|
2374
|
+
token: next
|
|
2375
|
+
})}\n`);
|
|
2376
|
+
} catch (error) {
|
|
2377
|
+
diagnostics.log("warn", error instanceof AuthRequiredError ? "runtime.auth_required" : "runtime.auth_token_failed", { error: serializeDiagnosticError(error) });
|
|
2378
|
+
}
|
|
2379
|
+
if (!childStopped && !signal.aborted) refreshTimer = setTimeout(() => void refresh(), 1e4);
|
|
2380
|
+
};
|
|
2381
|
+
refresh();
|
|
2382
|
+
const probe = async () => {
|
|
2383
|
+
if (!managed && !childStopped && !signal.aborted) try {
|
|
2384
|
+
const remote = await space.getRuntime(void 0, { signal: AbortSignal.any([signal, AbortSignal.timeout(5e3)]) });
|
|
2385
|
+
if (!childStopped && !managed) update({ workspaceConnected: remote.runtimeId === status.runtimeId && remote.workspace?.online === true });
|
|
2386
|
+
} catch {
|
|
2387
|
+
if (!childStopped && !managed) update({ workspaceConnected: false });
|
|
2388
|
+
}
|
|
2389
|
+
if (!childStopped && !signal.aborted && !managed) probeTimer = setTimeout(() => void probe(), 5e3);
|
|
2390
|
+
};
|
|
2391
|
+
probeTimer = setTimeout(() => void probe(), 1e3);
|
|
2392
|
+
const terminate = () => {
|
|
2393
|
+
if (terminating || childStopped) return;
|
|
2394
|
+
terminating = true;
|
|
2395
|
+
clearTimeout(recoveryTimer);
|
|
2396
|
+
recoveryTimer = void 0;
|
|
2397
|
+
if (process.platform === "win32") bridge.stdin?.end();
|
|
2398
|
+
else bridge.kill("SIGTERM");
|
|
2399
|
+
const timeout = setTimeout(() => bridge.kill("SIGKILL"), 3e3);
|
|
2400
|
+
closed.finally(() => clearTimeout(timeout));
|
|
2401
|
+
};
|
|
2402
|
+
retryDisconnectedBridge = () => {
|
|
2403
|
+
if (signal.aborted || !status.harnessConnected || !bridgeDisconnected || terminating || childStopped) {
|
|
2404
|
+
clearTimeout(recoveryTimer);
|
|
2405
|
+
recoveryTimer = void 0;
|
|
2406
|
+
} else if (!recoveryTimer) recoveryTimer = setTimeout(() => {
|
|
2407
|
+
recoveryTimer = void 0;
|
|
2408
|
+
if (!signal.aborted && status.harnessConnected && bridgeDisconnected && !terminating && !childStopped) {
|
|
2409
|
+
diagnostics.log("info", "sandboxd.lease_recovery");
|
|
2410
|
+
terminate();
|
|
2411
|
+
}
|
|
2412
|
+
}, 3e4);
|
|
2413
|
+
};
|
|
2414
|
+
signal.addEventListener("abort", terminate, { once: true });
|
|
2415
|
+
if (signal.aborted) terminate();
|
|
2416
|
+
await closed;
|
|
2417
|
+
signal.removeEventListener("abort", terminate);
|
|
2418
|
+
} catch (error) {
|
|
2419
|
+
if (!signal.aborted) diagnostics.log("warn", "sandboxd.restart_failed", { error: serializeDiagnosticError(error) });
|
|
2420
|
+
} finally {
|
|
2421
|
+
retryDisconnectedBridge = void 0;
|
|
2422
|
+
bridgeControl = null;
|
|
2423
|
+
workspace = null;
|
|
2424
|
+
childStopped = true;
|
|
2425
|
+
controlPipe?.close();
|
|
2426
|
+
clearTimeout(refreshTimer);
|
|
2427
|
+
clearTimeout(probeTimer);
|
|
2428
|
+
clearTimeout(recoveryTimer);
|
|
2429
|
+
update({
|
|
2430
|
+
workspaceConnected: false,
|
|
2431
|
+
direct: void 0
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
if (Date.now() - startedAt > 6e4) attempts = 0;
|
|
2435
|
+
const backoff = Math.min(3e4, 500 * 2 ** Math.min(attempts++, 6));
|
|
2436
|
+
await setTimeout$1(backoff / 2 + Math.random() * backoff / 2, void 0, { signal }).catch(() => void 0);
|
|
2437
|
+
}
|
|
2438
|
+
};
|
|
2439
|
+
bridgeTask = runBridge();
|
|
2440
|
+
const activity = setInterval(() => {
|
|
2441
|
+
if (executions.size || native.status().running) bridgeControl?.send({ type: "activity" });
|
|
2442
|
+
}, ACTIVITY_MS);
|
|
2443
|
+
activity.unref();
|
|
2444
|
+
signal.addEventListener("abort", () => clearInterval(activity), { once: true });
|
|
2445
|
+
await native.start(signal);
|
|
2446
|
+
nativeStarted = true;
|
|
2447
|
+
let importRequested = Boolean(config.importHistory);
|
|
2448
|
+
await serveRuntime({
|
|
2449
|
+
spaceId: config.spaceId,
|
|
2450
|
+
cwd: config.root,
|
|
2451
|
+
url: url.toString(),
|
|
2452
|
+
capabilities,
|
|
2453
|
+
refreshCapabilities: (current) => refreshHarnesses(current, config.executables, config.root, (harness, error) => diagnostics.log("warn", "runtime.harness_catalog_failed", {
|
|
2454
|
+
harness,
|
|
2455
|
+
error: serializeDiagnosticError(error)
|
|
2456
|
+
})),
|
|
2457
|
+
runtimeId: status.runtimeId,
|
|
2458
|
+
diagnostics,
|
|
2459
|
+
token,
|
|
2460
|
+
signal,
|
|
2461
|
+
executor: native.executor,
|
|
2462
|
+
executions,
|
|
2463
|
+
onReady: () => {
|
|
2464
|
+
update({ harnessConnected: true });
|
|
2465
|
+
retryDisconnectedBridge?.();
|
|
2466
|
+
},
|
|
2467
|
+
onDisconnected: () => {
|
|
2468
|
+
native.connect(null);
|
|
2469
|
+
update({ harnessConnected: false });
|
|
2470
|
+
retryDisconnectedBridge?.();
|
|
2471
|
+
},
|
|
2472
|
+
onNativeStop: (stop) => {
|
|
2473
|
+
native.stop(stop.sessionId, stop.turnId);
|
|
2474
|
+
},
|
|
2475
|
+
onApprovalDecision: (decision) => {
|
|
2476
|
+
native.executor.approvals.decide(decision);
|
|
2477
|
+
},
|
|
2478
|
+
onNativeChannel: (send, features) => {
|
|
2479
|
+
native.connect(send, features);
|
|
2480
|
+
if (!importRequested) return;
|
|
2481
|
+
importRequested = false;
|
|
2482
|
+
native.control("import", { command: "start" }).catch((error) => diagnostics.log("warn", "native.import_failed", { error: serializeDiagnosticError(error) }));
|
|
2483
|
+
}
|
|
2484
|
+
});
|
|
2485
|
+
} catch (error) {
|
|
2486
|
+
if (!signal.aborted) {
|
|
2487
|
+
update({ state: "attention" });
|
|
2488
|
+
diagnostics.log("error", "runtime.failed", { error: serializeDiagnosticError(error) });
|
|
2489
|
+
throw error;
|
|
2490
|
+
}
|
|
2491
|
+
} finally {
|
|
2492
|
+
controller.abort();
|
|
2493
|
+
try {
|
|
2494
|
+
await bridgeTask;
|
|
2495
|
+
if (nativeStarted) await native.close(AbortSignal.timeout(5e3));
|
|
2496
|
+
} finally {
|
|
2497
|
+
try {
|
|
2498
|
+
await diagnostics.close();
|
|
2499
|
+
} finally {
|
|
2500
|
+
try {
|
|
2501
|
+
await instance?.close();
|
|
2502
|
+
} finally {
|
|
2503
|
+
process.removeListener("SIGINT", stop);
|
|
2504
|
+
process.removeListener("SIGTERM", stop);
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
//#endregion
|
|
2511
|
+
export { sandboxOutputLevel as n, runRuntime as t };
|