@fungi.computer/computer 0.16.6 → 0.18.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/Dockerfile +21 -4
- package/container/computer-init.mjs +28 -0
- package/container/computer-start.sh +8 -1
- package/container/fungi-services +2 -0
- package/container/fungi-services.mjs +190 -0
- package/container/package.json +2 -1
- package/container/pnpm-lock.yaml +8 -0
- package/container/services-render.mjs +126 -0
- package/container/terminal-assets/global-tools.sh +4 -0
- package/container/terminal-server.mjs +55 -16
- package/container/tools/cli.mjs +55 -0
- package/container/tools/fungi-tools +14 -0
- package/container/tools/install.mjs +310 -0
- package/container/tools/manifest.mjs +111 -0
- package/container/tools/pi/package.json +8 -0
- package/container/tools/pi/pnpm-lock.yaml +1174 -0
- package/container/tools/pi/pnpm-workspace.yaml +4 -0
- package/dist/fleet/wire.d.ts +14 -0
- package/dist/fleet/wire.js +7 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +150 -25
- package/dist/port-failure.d.ts +10 -2
- package/dist/port-failure.js +25 -5
- package/dist/port-ownership.d.ts +16 -0
- package/dist/port-ownership.js +36 -0
- package/dist/preview-wait.d.ts +24 -0
- package/dist/preview-wait.js +47 -0
- package/dist/process-inventory.js +7 -21
- package/dist/services-apply.d.ts +54 -0
- package/dist/services-apply.js +66 -0
- package/dist/services-tools.d.ts +30 -0
- package/dist/services-tools.js +91 -0
- package/dist/services.d.ts +38 -0
- package/dist/services.js +123 -0
- package/dist/team-candidate-builder.mjs +29 -12
- package/package.json +17 -8
package/dist/fleet/wire.d.ts
CHANGED
|
@@ -26,6 +26,13 @@ export declare const computerActionSchema: z.ZodEnum<{
|
|
|
26
26
|
processKill: "processKill";
|
|
27
27
|
processLogs: "processLogs";
|
|
28
28
|
processWait: "processWait";
|
|
29
|
+
serviceDeclare: "serviceDeclare";
|
|
30
|
+
serviceList: "serviceList";
|
|
31
|
+
serviceLogs: "serviceLogs";
|
|
32
|
+
serviceStop: "serviceStop";
|
|
33
|
+
serviceStart: "serviceStart";
|
|
34
|
+
serviceRestart: "serviceRestart";
|
|
35
|
+
serviceRemove: "serviceRemove";
|
|
29
36
|
exposePort: "exposePort";
|
|
30
37
|
unexposePort: "unexposePort";
|
|
31
38
|
listPorts: "listPorts";
|
|
@@ -65,6 +72,13 @@ export declare const computerGrantSchema: z.ZodObject<{
|
|
|
65
72
|
processKill: "processKill";
|
|
66
73
|
processLogs: "processLogs";
|
|
67
74
|
processWait: "processWait";
|
|
75
|
+
serviceDeclare: "serviceDeclare";
|
|
76
|
+
serviceList: "serviceList";
|
|
77
|
+
serviceLogs: "serviceLogs";
|
|
78
|
+
serviceStop: "serviceStop";
|
|
79
|
+
serviceStart: "serviceStart";
|
|
80
|
+
serviceRestart: "serviceRestart";
|
|
81
|
+
serviceRemove: "serviceRemove";
|
|
68
82
|
exposePort: "exposePort";
|
|
69
83
|
unexposePort: "unexposePort";
|
|
70
84
|
listPorts: "listPorts";
|
package/dist/fleet/wire.js
CHANGED
|
@@ -12,6 +12,13 @@ export const computerActionSchema = z.enum([
|
|
|
12
12
|
"processKill",
|
|
13
13
|
"processLogs",
|
|
14
14
|
"processWait",
|
|
15
|
+
"serviceDeclare",
|
|
16
|
+
"serviceList",
|
|
17
|
+
"serviceLogs",
|
|
18
|
+
"serviceStop",
|
|
19
|
+
"serviceStart",
|
|
20
|
+
"serviceRestart",
|
|
21
|
+
"serviceRemove",
|
|
15
22
|
"exposePort",
|
|
16
23
|
"unexposePort",
|
|
17
24
|
"listPorts",
|
package/dist/index.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { FilesPort } from "@fungi.computer/knapsack";
|
|
|
9
9
|
import { z } from "zod";
|
|
10
10
|
import { type ComputerExecutionBudget, type ComputerExecutionHostHooks, type ComputerExecRequest, type ComputerOperationResult, type ComputerFileReadInput, type ComputerFileByteReadInput, type ComputerFileReplacement, type ComputerFileReplacementResult, type ComputerValue, writeInputSchema, writeOutputSchema, processLogsOutputSchema, processWaitOutputSchema, type ComputerProcess } from "@fungi.computer/computer-contract";
|
|
11
11
|
import { createWorkspaceFilesPort } from "./files.js";
|
|
12
|
+
import { ComputerServiceInventory } from "./services.js";
|
|
12
13
|
import { OnBoxVmContainerHost, type OnBoxVmEnv, type OnBoxVmPlacement, type OnBoxVmSshCertificate } from "./on-box-vm.js";
|
|
13
14
|
import { type AttachedBackend, type AttachedBackendView, type BackendNeed, type BackendRoute, type ComputerSize, type ContainerRuntimeStart, type HostedBacking } from "./computer-backends.js";
|
|
14
15
|
import { LocalBackendConnections } from "./local-backend.js";
|
|
@@ -112,6 +113,8 @@ declare class ContainerComputer extends ContainerComputerBase {
|
|
|
112
113
|
protected computerSize(): ComputerSize;
|
|
113
114
|
/** A runtime of a hosted backend started; owners meter it. */
|
|
114
115
|
protected containerRuntimeStarted(start: ContainerRuntimeStart): void;
|
|
116
|
+
/** Work every runtime start owes the Computer itself, apart from owners' metering. */
|
|
117
|
+
protected hostedRuntimeStarted(backing: HostedBacking): void;
|
|
115
118
|
/** The single routing decision over this Computer's attached backends. */
|
|
116
119
|
protected routeBackend(backend: string | undefined, need: BackendNeed): Extract<BackendRoute, {
|
|
117
120
|
kind: "routed";
|
|
@@ -178,6 +181,14 @@ export declare class ComputerDO extends ContainerComputer implements ComputerFil
|
|
|
178
181
|
* the durable value; a container's platform backstop follows it.
|
|
179
182
|
*/
|
|
180
183
|
keepAwake(enabled?: boolean): Promise<boolean>;
|
|
184
|
+
/**
|
|
185
|
+
* The declared services. The process inventory is built first because it
|
|
186
|
+
* owns the exposed-port table a service port is admitted through.
|
|
187
|
+
*/
|
|
188
|
+
protected get services(): ComputerServiceInventory;
|
|
189
|
+
protected hostedRuntimeStarted(backing: HostedBacking): void;
|
|
190
|
+
/** The Agent tools for declared services, once the host accepts the call. */
|
|
191
|
+
serviceToolAfterAcceptance(tool: string, input: ComputerValue, accept: () => void): Promise<ComputerValue>;
|
|
181
192
|
/** Ordinary Computers have no credential host; resource hosts override it. */
|
|
182
193
|
protected executionHooks(): ComputerExecutionHostHooks | undefined;
|
|
183
194
|
/**
|
package/dist/index.js
CHANGED
|
@@ -51,7 +51,8 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
|
|
|
51
51
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
52
52
|
});
|
|
53
53
|
import { boundExecStream } from "./exec-output.js";
|
|
54
|
-
import { portPreviewFailure
|
|
54
|
+
import { portPreviewFailure } from "./port-failure.js";
|
|
55
|
+
import { forwardPreviewWaitingForPort } from "./preview-wait.js";
|
|
55
56
|
export { createLocalBackendReplayStore } from "./local-backend-replay.js";
|
|
56
57
|
import { computerInternetAccess } from "./internet-access.js";
|
|
57
58
|
import { createComputerVaultReferences, isVaultExecutionContext, vaultExecutionHooks, } from "./vault-references.js";
|
|
@@ -66,13 +67,16 @@ import { z } from "zod";
|
|
|
66
67
|
import { SystemTrustContainerBackend } from "./container-system-trust.js";
|
|
67
68
|
import { computerTransportBackend } from "./transport-backend.js";
|
|
68
69
|
import { PullPendingTracker } from "./pull-pending.js";
|
|
69
|
-
import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, moveInputSchema, moveOutputSchema, ComputerFileMoveError, ComputerFileRemoveError, removeInputSchema, removeOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, processWaitInputSchema, processWaitOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, } from "@fungi.computer/computer-contract";
|
|
70
|
+
import { ComputerFileConflict, ComputerFileRangeError, ComputerFileTooLargeError, capabilityNameSchema, computerValueSchema, computerCapabilities, computerPortInputSchema, computerPortOutputSchema, computerPortRemovalOutputSchema, computerPortsOutputSchema, computerPortSchema, ComputerPortLimitError, ComputerPortReservedError, computerTerminalPort, isComputerReservedPort, maximumExposedPorts, maximumProcessRecords, execInputSchema, execOutputSchema, computerToolResult, computerExecutionRequestSchema, genericComputerExecutionBudget, mintComputerRequestId, listInputSchema, listOutputSchema, maximumFileBytes, mkdirInputSchema, mkdirOutputSchema, moveInputSchema, moveOutputSchema, ComputerFileMoveError, ComputerFileRemoveError, removeInputSchema, removeOutputSchema, readInputSchema, readBytesInputSchema, readOutputSchema, replaceInputSchema, writeInputSchema, writeOutputSchema, processIdInputSchema, processKillOutputSchema, processListOutputSchema, processLogsInputSchema, processLogsOutputSchema, processWaitInputSchema, processWaitOutputSchema, maximumProcessLogLines, processStartInputSchema, processStartToolInputSchema, ComputerProcessNotFoundError, computerServiceDeclarationSchema, serviceLogsInputSchema, serviceNameInputSchema, } from "@fungi.computer/computer-contract";
|
|
70
71
|
import { agentWorkspacePath, createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceRoot, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
|
|
71
72
|
import { computerExecutionResult } from "./execution-result.js";
|
|
72
73
|
import { ComputerOperationRecord } from "./operation-record.js";
|
|
73
74
|
import { createComputerExecutionLifecycle } from "./execution-lifecycle.js";
|
|
74
75
|
import { applyWorkspacePatch } from "./files-patch.js";
|
|
75
76
|
import { ComputerProcessInventory, drainProcessExit, ProcessLogTail, failedObservation, observeProcess, waitForProcessExit, } from "./process-inventory.js";
|
|
77
|
+
import { ComputerServiceInventory } from "./services.js";
|
|
78
|
+
import { applyDeclaredServices } from "./services-apply.js";
|
|
79
|
+
import { declareService, listServices, removeService, restartService, serviceLogs, setServiceEnabled, } from "./services-tools.js";
|
|
76
80
|
import { assertComputerContainersEnabled, ComputerContainersPausedError, configureComputerContainer, hostedComputerContainersPaused, } from "./container-policy.js";
|
|
77
81
|
import { OnBoxVmContainerHost, onBoxVmPlacement, } from "./on-box-vm.js";
|
|
78
82
|
import { computerKeepAwake } from "./fleet/keep-awake.js";
|
|
@@ -400,6 +404,10 @@ class ContainerComputer extends ContainerComputerBase {
|
|
|
400
404
|
containerRuntimeStarted(start) {
|
|
401
405
|
void start;
|
|
402
406
|
}
|
|
407
|
+
/** Work every runtime start owes the Computer itself, apart from owners' metering. */
|
|
408
|
+
hostedRuntimeStarted(backing) {
|
|
409
|
+
void backing;
|
|
410
|
+
}
|
|
403
411
|
/** The single routing decision over this Computer's attached backends. */
|
|
404
412
|
routeBackend(backend, need) {
|
|
405
413
|
const route = routeComputerBackend(this.attachedBackends(), (id) => this.localConnections.online(id), { backend, need });
|
|
@@ -438,6 +446,7 @@ class ContainerComputer extends ContainerComputerBase {
|
|
|
438
446
|
: this.onBoxVmHost(backing.hostId);
|
|
439
447
|
return new MeteredContainerHost(host, backing, () => this.computerSize(), (start) => {
|
|
440
448
|
this.containerRuntimeStarted(start);
|
|
449
|
+
this.hostedRuntimeStarted(start.backing);
|
|
441
450
|
});
|
|
442
451
|
}
|
|
443
452
|
/** The on-box VM host service for `hostId`, one per placement. */
|
|
@@ -633,6 +642,105 @@ export class ComputerDO extends ContainerComputer {
|
|
|
633
642
|
#vaultReferenceRecord;
|
|
634
643
|
#processStarts = new Map();
|
|
635
644
|
#terminalSync;
|
|
645
|
+
#serviceRecord;
|
|
646
|
+
#servicesApplied = Promise.resolve();
|
|
647
|
+
/**
|
|
648
|
+
* The declared services. The process inventory is built first because it
|
|
649
|
+
* owns the exposed-port table a service port is admitted through.
|
|
650
|
+
*/
|
|
651
|
+
get services() {
|
|
652
|
+
void this.#processes;
|
|
653
|
+
this.#serviceRecord ??= new ComputerServiceInventory(this.state.storage, () => Date.now());
|
|
654
|
+
return this.#serviceRecord;
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Every runtime start (a wake, a recycle's replacement, a bump) brings the
|
|
658
|
+
* declared services back. One apply runs at a time, in start order; a
|
|
659
|
+
* failure is logged with its cause and leaves the next start to try again.
|
|
660
|
+
*/
|
|
661
|
+
/** The declared services' view of this Computer: awake or not, and a command run on it. */
|
|
662
|
+
#servicesRuntime(backend) {
|
|
663
|
+
return {
|
|
664
|
+
awake: async () => {
|
|
665
|
+
const route = this.hostedRoute();
|
|
666
|
+
return (route !== undefined && (await this.containerRunning(route.backing)));
|
|
667
|
+
},
|
|
668
|
+
run: async (command) => {
|
|
669
|
+
const env_2 = { stack: [], error: void 0, hasError: false };
|
|
670
|
+
try {
|
|
671
|
+
const target = backend ?? this.requireHostedRoute().id;
|
|
672
|
+
const workspace = await this.readyWorkspace();
|
|
673
|
+
const run = __addDisposableResource(env_2, await workspace.runtime.exec(command, {
|
|
674
|
+
backend: target,
|
|
675
|
+
encoding: "utf8",
|
|
676
|
+
timeoutMs: 30_000,
|
|
677
|
+
}), false);
|
|
678
|
+
const { status, exitCode, stdout, stderr } = await run.result();
|
|
679
|
+
return { status, exitCode, stdout, stderr };
|
|
680
|
+
}
|
|
681
|
+
catch (e_2) {
|
|
682
|
+
env_2.error = e_2;
|
|
683
|
+
env_2.hasError = true;
|
|
684
|
+
}
|
|
685
|
+
finally {
|
|
686
|
+
__disposeResources(env_2);
|
|
687
|
+
}
|
|
688
|
+
},
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Everything that renders or controls the services runs here, one at a time
|
|
693
|
+
* in arrival order, and reads the declarations only when its turn comes. A
|
|
694
|
+
* wake's apply and a tool's apply therefore never race: the later one always
|
|
695
|
+
* carries the newer declarations.
|
|
696
|
+
*/
|
|
697
|
+
#serialServices(work) {
|
|
698
|
+
const turn = this.#servicesApplied.then(work);
|
|
699
|
+
this.#servicesApplied = turn.then(() => undefined, () => undefined);
|
|
700
|
+
return turn;
|
|
701
|
+
}
|
|
702
|
+
hostedRuntimeStarted(backing) {
|
|
703
|
+
const runtime = this.#servicesRuntime(attachedBackendId(backing));
|
|
704
|
+
const applied = this.#serialServices(async () => {
|
|
705
|
+
try {
|
|
706
|
+
await applyDeclaredServices({
|
|
707
|
+
inventory: this.services,
|
|
708
|
+
run: runtime.run,
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
catch (cause) {
|
|
712
|
+
Effect.runSync(Effect.logError("Computer declared services were not applied", Redacted.make(cause)));
|
|
713
|
+
}
|
|
714
|
+
});
|
|
715
|
+
this.state.waitUntil(applied);
|
|
716
|
+
}
|
|
717
|
+
/** The Agent tools for declared services, once the host accepts the call. */
|
|
718
|
+
async serviceToolAfterAcceptance(tool, input, accept) {
|
|
719
|
+
accept();
|
|
720
|
+
return await this.#serialServices(() => this.#serviceTool(tool, input));
|
|
721
|
+
}
|
|
722
|
+
async #serviceTool(tool, input) {
|
|
723
|
+
const runtime = this.#servicesRuntime();
|
|
724
|
+
const inventory = this.services;
|
|
725
|
+
switch (tool) {
|
|
726
|
+
case "declare_service":
|
|
727
|
+
return computerValueSchema.parse(await declareService(inventory, runtime, computerServiceDeclarationSchema.parse(input), "agent"));
|
|
728
|
+
case "list_services":
|
|
729
|
+
return computerValueSchema.parse(await listServices(inventory, runtime));
|
|
730
|
+
case "service_logs":
|
|
731
|
+
return computerValueSchema.parse(await serviceLogs(inventory, runtime, serviceLogsInputSchema.parse(input)));
|
|
732
|
+
case "stop_service":
|
|
733
|
+
return computerValueSchema.parse(await setServiceEnabled(inventory, runtime, serviceNameInputSchema.parse(input).name, false));
|
|
734
|
+
case "start_service":
|
|
735
|
+
return computerValueSchema.parse(await setServiceEnabled(inventory, runtime, serviceNameInputSchema.parse(input).name, true));
|
|
736
|
+
case "restart_service":
|
|
737
|
+
return computerValueSchema.parse(await restartService(inventory, runtime, serviceNameInputSchema.parse(input).name));
|
|
738
|
+
case "remove_service":
|
|
739
|
+
return computerValueSchema.parse(await removeService(inventory, runtime, serviceNameInputSchema.parse(input).name));
|
|
740
|
+
default:
|
|
741
|
+
throw new Error(`Computer capability is unavailable: ${tool}`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
636
744
|
get #processes() {
|
|
637
745
|
this.#processRecord ??= new ComputerProcessInventory(this.state.storage, () => Date.now());
|
|
638
746
|
return this.#processRecord;
|
|
@@ -742,23 +850,23 @@ export class ComputerDO extends ContainerComputer {
|
|
|
742
850
|
let observed;
|
|
743
851
|
let archivedExit = false;
|
|
744
852
|
try {
|
|
745
|
-
const
|
|
853
|
+
const env_3 = { stack: [], error: void 0, hasError: false };
|
|
746
854
|
try {
|
|
747
855
|
// Hold both handles unread. A live execution admits only one subscriber;
|
|
748
856
|
// two successful gets therefore prove archived native completion.
|
|
749
|
-
const first = __addDisposableResource(
|
|
857
|
+
const first = __addDisposableResource(env_3, await runtime.getExec(invocationId, { resume: "tail" }), false);
|
|
750
858
|
void first;
|
|
751
|
-
const second = __addDisposableResource(
|
|
859
|
+
const second = __addDisposableResource(env_3, await runtime.getExec(invocationId, { resume: "tail" }), false);
|
|
752
860
|
void second;
|
|
753
861
|
archivedExit = true;
|
|
754
862
|
observed = { state: "exited", exitCode: null, sync: "unknown" };
|
|
755
863
|
}
|
|
756
|
-
catch (
|
|
757
|
-
|
|
758
|
-
|
|
864
|
+
catch (e_3) {
|
|
865
|
+
env_3.error = e_3;
|
|
866
|
+
env_3.hasError = true;
|
|
759
867
|
}
|
|
760
868
|
finally {
|
|
761
|
-
__disposeResources(
|
|
869
|
+
__disposeResources(env_3);
|
|
762
870
|
}
|
|
763
871
|
}
|
|
764
872
|
catch (cause) {
|
|
@@ -908,10 +1016,19 @@ export class ComputerDO extends ContainerComputer {
|
|
|
908
1016
|
const hosted = this.hostedRoute();
|
|
909
1017
|
if (hosted === undefined)
|
|
910
1018
|
throw new ComputerBackendUnavailableError("no_backend");
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1019
|
+
// A declared, enabled service on this port is still starting after a wake
|
|
1020
|
+
// while the port is closed: wait for it, up to 20 s.
|
|
1021
|
+
const service = this.services
|
|
1022
|
+
.list()
|
|
1023
|
+
.find(({ enabled, port: owned }) => enabled && owned === port);
|
|
1024
|
+
return await forwardPreviewWaitingForPort({
|
|
1025
|
+
service: service === undefined ? undefined : { name: service.name, port },
|
|
1026
|
+
port,
|
|
1027
|
+
request,
|
|
1028
|
+
attempt: () => this.withHostedResponse(hosted.backing, () => this.hostedContainerHost(hosted.backing)
|
|
1029
|
+
.port(port)
|
|
1030
|
+
.fetch(new Request(forwarded, { headers }))),
|
|
1031
|
+
});
|
|
915
1032
|
}
|
|
916
1033
|
catch (cause) {
|
|
917
1034
|
console.error("Computer runtime operation failed", cause);
|
|
@@ -1182,6 +1299,14 @@ export class ComputerDO extends ContainerComputer {
|
|
|
1182
1299
|
return this.processLogsAfterAcceptance(input, accept);
|
|
1183
1300
|
case "wait_process":
|
|
1184
1301
|
return await this.waitProcessAfterAcceptance(input, accept);
|
|
1302
|
+
case "declare_service":
|
|
1303
|
+
case "list_services":
|
|
1304
|
+
case "service_logs":
|
|
1305
|
+
case "stop_service":
|
|
1306
|
+
case "start_service":
|
|
1307
|
+
case "restart_service":
|
|
1308
|
+
case "remove_service":
|
|
1309
|
+
return await this.serviceToolAfterAcceptance(selected, input, accept);
|
|
1185
1310
|
}
|
|
1186
1311
|
await this.prepareFiles();
|
|
1187
1312
|
const workspace = await this.readyWorkspace();
|
|
@@ -1755,10 +1880,10 @@ export class ComputerDO extends ContainerComputer {
|
|
|
1755
1880
|
if (hosted === undefined)
|
|
1756
1881
|
return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
|
|
1757
1882
|
try {
|
|
1758
|
-
const
|
|
1883
|
+
const env_4 = { stack: [], error: void 0, hasError: false };
|
|
1759
1884
|
try {
|
|
1760
1885
|
const workspace = await this.readyWorkspace();
|
|
1761
|
-
const readiness = __addDisposableResource(
|
|
1886
|
+
const readiness = __addDisposableResource(env_4, await workspace.runtime.exec("true", {
|
|
1762
1887
|
backend: hosted.id,
|
|
1763
1888
|
encoding: "utf8",
|
|
1764
1889
|
timeoutMs: 10_000,
|
|
@@ -1768,12 +1893,12 @@ export class ComputerDO extends ContainerComputer {
|
|
|
1768
1893
|
return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
|
|
1769
1894
|
}
|
|
1770
1895
|
}
|
|
1771
|
-
catch (
|
|
1772
|
-
|
|
1773
|
-
|
|
1896
|
+
catch (e_4) {
|
|
1897
|
+
env_4.error = e_4;
|
|
1898
|
+
env_4.hasError = true;
|
|
1774
1899
|
}
|
|
1775
1900
|
finally {
|
|
1776
|
-
__disposeResources(
|
|
1901
|
+
__disposeResources(env_4);
|
|
1777
1902
|
}
|
|
1778
1903
|
}
|
|
1779
1904
|
catch (cause) {
|
|
@@ -1847,17 +1972,17 @@ export { LocalBackendOfflineError, localBackendAudience, localBackendDialPath, o
|
|
|
1847
1972
|
/** Keep each native Workspace lease inside the operation that uses it. */
|
|
1848
1973
|
export function createComputerFilesPort(computer) {
|
|
1849
1974
|
async function withFiles(operation) {
|
|
1850
|
-
const
|
|
1975
|
+
const env_5 = { stack: [], error: void 0, hasError: false };
|
|
1851
1976
|
try {
|
|
1852
|
-
const workspace = __addDisposableResource(
|
|
1977
|
+
const workspace = __addDisposableResource(env_5, await getWorkspace(computer), false);
|
|
1853
1978
|
return await operation(createWorkspaceFilesPort(workspace, computer));
|
|
1854
1979
|
}
|
|
1855
|
-
catch (
|
|
1856
|
-
|
|
1857
|
-
|
|
1980
|
+
catch (e_5) {
|
|
1981
|
+
env_5.error = e_5;
|
|
1982
|
+
env_5.hasError = true;
|
|
1858
1983
|
}
|
|
1859
1984
|
finally {
|
|
1860
|
-
__disposeResources(
|
|
1985
|
+
__disposeResources(env_5);
|
|
1861
1986
|
}
|
|
1862
1987
|
}
|
|
1863
1988
|
return {
|
package/dist/port-failure.d.ts
CHANGED
|
@@ -6,13 +6,21 @@ declare const hostRefusalSchema: Schema.Literals<readonly ["not_running", "not_l
|
|
|
6
6
|
* the Computer answers on that port. `unreachable`: Fungi could not reach the
|
|
7
7
|
* Computer. `expired`: the preview link's five-minute ticket ran out.
|
|
8
8
|
*/
|
|
9
|
-
export type PortPreviewFailure = Schema.Schema.Type<typeof hostRefusalSchema> | "unreachable" | "expired";
|
|
9
|
+
export type PortPreviewFailure = Schema.Schema.Type<typeof hostRefusalSchema> | "unreachable" | "expired" | "service_timeout";
|
|
10
|
+
/**
|
|
11
|
+
* The VM host's typed refusal, or null when the reply is the guest's own.
|
|
12
|
+
* vmd pipes an upgrade's bytes raw, so on an upgrade request the header could
|
|
13
|
+
* be the guest's and is never read.
|
|
14
|
+
*/
|
|
15
|
+
export declare function portPreviewRefusal(response: Response, request: Request): PortPreviewFailure | null;
|
|
16
|
+
/** How long a preview waits for a declared service to open its port. */
|
|
17
|
+
export declare const declaredPortWaitSeconds = 20;
|
|
10
18
|
/**
|
|
11
19
|
* The one answer a failed preview gives: a styled page in plain words for a
|
|
12
20
|
* browser document, or `{ error: reason }` for a script's request. Raw
|
|
13
21
|
* upstream text never reaches the viewer.
|
|
14
22
|
*/
|
|
15
|
-
export declare function portPreviewFailure(reason: PortPreviewFailure, request: Request, port?: number): Promise<Response>;
|
|
23
|
+
export declare function portPreviewFailure(reason: PortPreviewFailure, request: Request, port?: number, service?: string): Promise<Response>;
|
|
16
24
|
/**
|
|
17
25
|
* What a preview answers for a forwarded port reply: the VM host's own
|
|
18
26
|
* refusal in plain words, or the guest's reply as it is, minus cookies.
|
package/dist/port-failure.js
CHANGED
|
@@ -17,12 +17,14 @@ const hostRefusalSchema = Schema.Literals([
|
|
|
17
17
|
* vmd pipes an upgrade's bytes raw, so on an upgrade request the header could
|
|
18
18
|
* be the guest's and is never read.
|
|
19
19
|
*/
|
|
20
|
-
function
|
|
20
|
+
export function portPreviewRefusal(response, request) {
|
|
21
21
|
if (request.headers.has("upgrade"))
|
|
22
22
|
return null;
|
|
23
23
|
const named = Schema.decodeUnknownOption(hostRefusalSchema)(response.headers.get(portFailureHeader));
|
|
24
24
|
return Option.isSome(named) ? named.value : null;
|
|
25
25
|
}
|
|
26
|
+
/** How long a preview waits for a declared service to open its port. */
|
|
27
|
+
export const declaredPortWaitSeconds = 20;
|
|
26
28
|
const copy = {
|
|
27
29
|
not_running: () => ({
|
|
28
30
|
title: "This Computer is asleep",
|
|
@@ -42,12 +44,23 @@ const copy = {
|
|
|
42
44
|
title: "This preview link has expired",
|
|
43
45
|
detail: "Open the preview again from Fungi to get a fresh link.",
|
|
44
46
|
}),
|
|
47
|
+
service_timeout: (port, service) => ({
|
|
48
|
+
title: service === undefined || port === undefined
|
|
49
|
+
? "The service didn't open its port in time"
|
|
50
|
+
: serviceTimeoutMessage(service, port),
|
|
51
|
+
detail: "Check its output under Services on this Computer's card, then reload this page.",
|
|
52
|
+
}),
|
|
45
53
|
};
|
|
54
|
+
/** The one sentence for a declared service that never opened its port. */
|
|
55
|
+
function serviceTimeoutMessage(service, port) {
|
|
56
|
+
return `${service} didn't open port ${String(port)} within ${String(declaredPortWaitSeconds)} s`;
|
|
57
|
+
}
|
|
46
58
|
const statuses = {
|
|
47
59
|
not_running: 503,
|
|
48
60
|
not_listening: 502,
|
|
49
61
|
unreachable: 502,
|
|
50
62
|
expired: 403,
|
|
63
|
+
service_timeout: 504,
|
|
51
64
|
};
|
|
52
65
|
// The preview origin is isolated and loads no Fungi asset, so the page's
|
|
53
66
|
// styling travels inline and follows the viewer's light or dark scheme.
|
|
@@ -67,12 +80,19 @@ a:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
|
67
80
|
* browser document, or `{ error: reason }` for a script's request. Raw
|
|
68
81
|
* upstream text never reaches the viewer.
|
|
69
82
|
*/
|
|
70
|
-
export async function portPreviewFailure(reason, request, port) {
|
|
83
|
+
export async function portPreviewFailure(reason, request, port, service) {
|
|
71
84
|
const headers = { "Cache-Control": "no-store" };
|
|
72
85
|
const status = statuses[reason];
|
|
73
86
|
if (request.headers.get("sec-fetch-dest") !== "document")
|
|
74
|
-
return Response.json(
|
|
75
|
-
|
|
87
|
+
return Response.json(reason === "service_timeout"
|
|
88
|
+
? {
|
|
89
|
+
error: reason,
|
|
90
|
+
message: service === undefined || port === undefined
|
|
91
|
+
? "The service didn't open its port in time"
|
|
92
|
+
: serviceTimeoutMessage(service, port),
|
|
93
|
+
}
|
|
94
|
+
: { error: reason }, { status, headers });
|
|
95
|
+
const { title, detail } = copy[reason](port, service);
|
|
76
96
|
const page = await html `<!doctype html>
|
|
77
97
|
<html lang="en">
|
|
78
98
|
<meta charset="utf-8" />
|
|
@@ -95,7 +115,7 @@ export async function portPreviewFailure(reason, request, port) {
|
|
|
95
115
|
* refusal in plain words, or the guest's reply as it is, minus cookies.
|
|
96
116
|
*/
|
|
97
117
|
export async function portPreviewReply(response, request, port) {
|
|
98
|
-
const refused =
|
|
118
|
+
const refused = portPreviewRefusal(response, request);
|
|
99
119
|
if (refused !== null) {
|
|
100
120
|
await response.body?.cancel();
|
|
101
121
|
return await portPreviewFailure(refused, request, port);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** The durable SQLite surface that holds a Computer's exposed ports. */
|
|
2
|
+
export type ExposedPortStorage = Pick<DurableObjectStorage, "sql" | "transactionSync">;
|
|
3
|
+
/**
|
|
4
|
+
* Create the exposed-port table. Every owner of a port (a process or a
|
|
5
|
+
* declared service) shares it, so one port has exactly one owner.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createExposedPorts(storage: ExposedPortStorage): void;
|
|
8
|
+
/**
|
|
9
|
+
* Admit one port for `owner` inside the caller's transaction. A port an owner
|
|
10
|
+
* already exposed by hand (no owner) is adopted without taking it over; a port
|
|
11
|
+
* another owner holds, or a daemon port, is refused; the exposure count is
|
|
12
|
+
* bounded.
|
|
13
|
+
*/
|
|
14
|
+
export declare function claimPort(storage: ExposedPortStorage, port: number, owner: string): void;
|
|
15
|
+
/** Drop the exposures `owner` holds; a port exposed by hand is never owned. */
|
|
16
|
+
export declare function releasePortsOwnedBy(storage: ExposedPortStorage, owner: string): void;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ComputerPortConflictError, ComputerPortLimitError, ComputerPortReservedError, isComputerReservedPort, maximumExposedPorts, } from "@fungi.computer/computer-contract";
|
|
2
|
+
/**
|
|
3
|
+
* Create the exposed-port table. Every owner of a port (a process or a
|
|
4
|
+
* declared service) shares it, so one port has exactly one owner.
|
|
5
|
+
*/
|
|
6
|
+
export function createExposedPorts(storage) {
|
|
7
|
+
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_exposed_ports (port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535), process_id TEXT) STRICT");
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Admit one port for `owner` inside the caller's transaction. A port an owner
|
|
11
|
+
* already exposed by hand (no owner) is adopted without taking it over; a port
|
|
12
|
+
* another owner holds, or a daemon port, is refused; the exposure count is
|
|
13
|
+
* bounded.
|
|
14
|
+
*/
|
|
15
|
+
export function claimPort(storage, port, owner) {
|
|
16
|
+
if (isComputerReservedPort(port))
|
|
17
|
+
throw new ComputerPortReservedError(port);
|
|
18
|
+
const exposure = storage.sql
|
|
19
|
+
.exec("SELECT process_id FROM computer_exposed_ports WHERE port = ?", port)
|
|
20
|
+
.toArray()[0];
|
|
21
|
+
if (exposure === undefined) {
|
|
22
|
+
const ports = storage.sql
|
|
23
|
+
.exec("SELECT COUNT(*) AS count FROM computer_exposed_ports")
|
|
24
|
+
.toArray()[0]?.count ?? maximumExposedPorts;
|
|
25
|
+
if (ports >= maximumExposedPorts)
|
|
26
|
+
throw new ComputerPortLimitError();
|
|
27
|
+
storage.sql.exec("INSERT INTO computer_exposed_ports (port, process_id) VALUES (?, ?)", port, owner);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (exposure.process_id !== null && exposure.process_id !== owner)
|
|
31
|
+
throw new ComputerPortConflictError();
|
|
32
|
+
}
|
|
33
|
+
/** Drop the exposures `owner` holds; a port exposed by hand is never owned. */
|
|
34
|
+
export function releasePortsOwnedBy(storage, owner) {
|
|
35
|
+
storage.sql.exec("DELETE FROM computer_exposed_ports WHERE process_id = ?", owner);
|
|
36
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** How long a preview waits for a declared service to open its port. */
|
|
2
|
+
export declare const declaredPortWaitMs: number;
|
|
3
|
+
/** A declared, enabled service that owns the previewed port. */
|
|
4
|
+
export type PreviewedService = Readonly<{
|
|
5
|
+
name: string;
|
|
6
|
+
port: number;
|
|
7
|
+
}>;
|
|
8
|
+
/**
|
|
9
|
+
* Forward one preview request. When an enabled declared service owns the port,
|
|
10
|
+
* a closed port is the service still starting after a wake, so keep trying for
|
|
11
|
+
* up to 20 s and then say which service never opened which port. A port no
|
|
12
|
+
* service declares is answered at once, as is any request that cannot be
|
|
13
|
+
* replayed (a body, or an upgrade): the host's refusal means it never reached
|
|
14
|
+
* the guest, but a streamed body is already spent.
|
|
15
|
+
*/
|
|
16
|
+
export declare function forwardPreviewWaitingForPort(options: {
|
|
17
|
+
service: PreviewedService | undefined;
|
|
18
|
+
request: Request;
|
|
19
|
+
port: number;
|
|
20
|
+
/** One try against the guest; throws when the Computer cannot be reached. */
|
|
21
|
+
attempt: () => Promise<Response>;
|
|
22
|
+
now?: () => number;
|
|
23
|
+
delay?: (ms: number) => Promise<void>;
|
|
24
|
+
}): Promise<Response>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { declaredPortWaitSeconds, portPreviewFailure, portPreviewReply, portPreviewRefusal, } from "./port-failure.js";
|
|
2
|
+
/** How long a preview waits for a declared service to open its port. */
|
|
3
|
+
export const declaredPortWaitMs = declaredPortWaitSeconds * 1_000;
|
|
4
|
+
const pollMs = 500;
|
|
5
|
+
/**
|
|
6
|
+
* Forward one preview request. When an enabled declared service owns the port,
|
|
7
|
+
* a closed port is the service still starting after a wake, so keep trying for
|
|
8
|
+
* up to 20 s and then say which service never opened which port. A port no
|
|
9
|
+
* service declares is answered at once, as is any request that cannot be
|
|
10
|
+
* replayed (a body, or an upgrade): the host's refusal means it never reached
|
|
11
|
+
* the guest, but a streamed body is already spent.
|
|
12
|
+
*/
|
|
13
|
+
export async function forwardPreviewWaitingForPort(options) {
|
|
14
|
+
const { service, request, attempt } = options;
|
|
15
|
+
const now = options.now ?? (() => Date.now());
|
|
16
|
+
const delay = options.delay ??
|
|
17
|
+
((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
18
|
+
const { port } = options;
|
|
19
|
+
const replayable = service !== undefined &&
|
|
20
|
+
request.body === null &&
|
|
21
|
+
!request.headers.has("upgrade");
|
|
22
|
+
const reply = (response) => portPreviewReply(response, request, port);
|
|
23
|
+
if (!replayable) {
|
|
24
|
+
const response = await attempt();
|
|
25
|
+
return await reply(response);
|
|
26
|
+
}
|
|
27
|
+
const deadline = now() + declaredPortWaitMs;
|
|
28
|
+
let last;
|
|
29
|
+
for (;;) {
|
|
30
|
+
last = await tryOnce(attempt);
|
|
31
|
+
if (last.ok) {
|
|
32
|
+
if (portPreviewRefusal(last.response, request) !== "not_listening")
|
|
33
|
+
return await reply(last.response);
|
|
34
|
+
await last.response.body?.cancel();
|
|
35
|
+
}
|
|
36
|
+
// A failed try is the Computer unreachable this time: it may be mid-start.
|
|
37
|
+
if (now() >= deadline || request.signal.aborted)
|
|
38
|
+
break;
|
|
39
|
+
await delay(Math.min(pollMs, Math.max(1, deadline - now())));
|
|
40
|
+
}
|
|
41
|
+
if (!last.ok)
|
|
42
|
+
throw last.cause;
|
|
43
|
+
return await portPreviewFailure("service_timeout", request, port, service.name);
|
|
44
|
+
}
|
|
45
|
+
function tryOnce(attempt) {
|
|
46
|
+
return attempt().then((response) => ({ ok: true, response }), (cause) => ({ ok: false, cause }));
|
|
47
|
+
}
|
|
@@ -51,9 +51,10 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
|
|
|
51
51
|
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
52
52
|
});
|
|
53
53
|
import { z } from "zod";
|
|
54
|
-
import { computerProcessSchema, processStartInputSchema, mintComputerProcessId, ComputerProcessLimitError,
|
|
54
|
+
import { computerProcessSchema, processStartInputSchema, mintComputerProcessId, ComputerProcessLimitError, maximumProcessLogLineCharacters, maximumProcessLogLines, maximumProcessRecords, maximumRunningProcesses, } from "@fungi.computer/computer-contract";
|
|
55
55
|
import { ComputerOperationConflictError } from "./operation-record.js";
|
|
56
56
|
import { initializePortAccess } from "./port-access.js";
|
|
57
|
+
import { claimPort, createExposedPorts, releasePortsOwnedBy, } from "./port-ownership.js";
|
|
57
58
|
function toProcess(row) {
|
|
58
59
|
return computerProcessSchema.parse({
|
|
59
60
|
id: row.id,
|
|
@@ -161,7 +162,7 @@ export class ComputerProcessInventory {
|
|
|
161
162
|
storage.sql.exec("INSERT INTO computer_schema_meta (id, version) VALUES (0, ?)", processSchemaVersion);
|
|
162
163
|
}
|
|
163
164
|
storage.sql.exec("CREATE TABLE IF NOT EXISTS computer_processes (id TEXT PRIMARY KEY, request_scope TEXT NOT NULL, request_id TEXT NOT NULL, input_hash TEXT NOT NULL, backend TEXT NOT NULL, command TEXT NOT NULL, cwd TEXT, port INTEGER, state TEXT NOT NULL CHECK (state IN ('running','exited')), exit_code INTEGER, sync TEXT NOT NULL DEFAULT 'unknown' CHECK (sync IN ('synced','pending','unknown')), started_at INTEGER NOT NULL, ended_at INTEGER, ended_reason TEXT CHECK (ended_reason IN ('idle-sleep')), log_tail TEXT NOT NULL DEFAULT '', log_truncated INTEGER NOT NULL DEFAULT 0, CHECK ((state = 'running') = (ended_at IS NULL)), UNIQUE(request_scope, request_id)) STRICT");
|
|
164
|
-
storage
|
|
165
|
+
createExposedPorts(storage);
|
|
165
166
|
initializePortAccess(storage);
|
|
166
167
|
});
|
|
167
168
|
}
|
|
@@ -200,23 +201,8 @@ export class ComputerProcessInventory {
|
|
|
200
201
|
if (running >= maximumRunningProcesses)
|
|
201
202
|
throw new ComputerProcessLimitError();
|
|
202
203
|
const id = mintComputerProcessId();
|
|
203
|
-
if (input.port !== undefined)
|
|
204
|
-
|
|
205
|
-
throw new ComputerPortReservedError(input.port);
|
|
206
|
-
const exposure = this.#storage.sql
|
|
207
|
-
.exec("SELECT process_id FROM computer_exposed_ports WHERE port = ?", input.port)
|
|
208
|
-
.toArray()[0];
|
|
209
|
-
if (exposure !== undefined && exposure.process_id !== null)
|
|
210
|
-
throw new ComputerPortConflictError();
|
|
211
|
-
if (exposure === undefined) {
|
|
212
|
-
const ports = this.#storage.sql
|
|
213
|
-
.exec("SELECT COUNT(*) AS count FROM computer_exposed_ports")
|
|
214
|
-
.toArray()[0]?.count ?? maximumExposedPorts;
|
|
215
|
-
if (ports >= maximumExposedPorts)
|
|
216
|
-
throw new ComputerPortLimitError();
|
|
217
|
-
this.#storage.sql.exec("INSERT INTO computer_exposed_ports (port, process_id) VALUES (?, ?)", input.port, id);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
204
|
+
if (input.port !== undefined)
|
|
205
|
+
claimPort(this.#storage, input.port, id);
|
|
220
206
|
this.#storage.sql.exec("INSERT INTO computer_processes (id, request_scope, request_id, input_hash, backend, command, cwd, port, state, started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'running', ?)", id, input.requestScope, input.requestId, inputHash, backend, input.command, input.cwd ?? null, input.port ?? null, now);
|
|
221
207
|
// Each scope retains its own newest 64 rows, including running processes.
|
|
222
208
|
this.#storage.sql.exec("DELETE FROM computer_processes WHERE request_scope = ? AND state = 'exited' AND id NOT IN (SELECT id FROM computer_processes WHERE request_scope = ? AND state = 'exited' ORDER BY started_at DESC, id DESC LIMIT MAX(0, ? - (SELECT COUNT(*) FROM computer_processes WHERE request_scope = ? AND state = 'running')))", input.requestScope, input.requestScope, maximumProcessRecords, input.requestScope);
|
|
@@ -232,7 +218,7 @@ export class ComputerProcessInventory {
|
|
|
232
218
|
exited(id, exitCode, sync = "unknown") {
|
|
233
219
|
return this.#storage.transactionSync(() => {
|
|
234
220
|
this.#storage.sql.exec("UPDATE computer_processes SET state = 'exited', exit_code = ?, sync = ?, ended_at = ? WHERE id = ? AND state = 'running'", exitCode, sync, this.#now(), id);
|
|
235
|
-
this.#storage
|
|
221
|
+
releasePortsOwnedBy(this.#storage, id);
|
|
236
222
|
return this.#require(id);
|
|
237
223
|
});
|
|
238
224
|
}
|
|
@@ -249,7 +235,7 @@ export class ComputerProcessInventory {
|
|
|
249
235
|
.toArray();
|
|
250
236
|
this.#storage.sql.exec("UPDATE computer_processes SET state = 'exited', exit_code = NULL, sync = 'unknown', ended_at = ?, ended_reason = 'idle-sleep' WHERE backend = ? AND state = 'running'", this.#now(), backend);
|
|
251
237
|
for (const { id } of ids)
|
|
252
|
-
this.#storage
|
|
238
|
+
releasePortsOwnedBy(this.#storage, id);
|
|
253
239
|
});
|
|
254
240
|
}
|
|
255
241
|
/** Replace the retained output tail of one process, if its record is still kept. */
|