@fungi.computer/computer 0.16.6 → 0.17.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.
@@ -0,0 +1,4 @@
1
+ # Standalone frozen dependency closure, installed only by fungi-tools.
2
+ allowBuilds:
3
+ "@google/genai": false
4
+ protobufjs: false
@@ -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";
@@ -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
@@ -66,13 +66,16 @@ import { z } from "zod";
66
66
  import { SystemTrustContainerBackend } from "./container-system-trust.js";
67
67
  import { computerTransportBackend } from "./transport-backend.js";
68
68
  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";
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, computerServiceDeclarationSchema, serviceLogsInputSchema, serviceNameInputSchema, } from "@fungi.computer/computer-contract";
70
70
  import { agentWorkspacePath, createWorkspaceFilesPort, readBoundedWorkspaceText, workspaceRoot, workspaceFileExists, listWorkspaceFiles, } from "./files.js";
71
71
  import { computerExecutionResult } from "./execution-result.js";
72
72
  import { ComputerOperationRecord } from "./operation-record.js";
73
73
  import { createComputerExecutionLifecycle } from "./execution-lifecycle.js";
74
74
  import { applyWorkspacePatch } from "./files-patch.js";
75
75
  import { ComputerProcessInventory, drainProcessExit, ProcessLogTail, failedObservation, observeProcess, waitForProcessExit, } from "./process-inventory.js";
76
+ import { ComputerServiceInventory } from "./services.js";
77
+ import { applyDeclaredServices } from "./services-apply.js";
78
+ import { declareService, listServices, removeService, restartService, serviceLogs, setServiceEnabled, } from "./services-tools.js";
76
79
  import { assertComputerContainersEnabled, ComputerContainersPausedError, configureComputerContainer, hostedComputerContainersPaused, } from "./container-policy.js";
77
80
  import { OnBoxVmContainerHost, onBoxVmPlacement, } from "./on-box-vm.js";
78
81
  import { computerKeepAwake } from "./fleet/keep-awake.js";
@@ -400,6 +403,10 @@ class ContainerComputer extends ContainerComputerBase {
400
403
  containerRuntimeStarted(start) {
401
404
  void start;
402
405
  }
406
+ /** Work every runtime start owes the Computer itself, apart from owners' metering. */
407
+ hostedRuntimeStarted(backing) {
408
+ void backing;
409
+ }
403
410
  /** The single routing decision over this Computer's attached backends. */
404
411
  routeBackend(backend, need) {
405
412
  const route = routeComputerBackend(this.attachedBackends(), (id) => this.localConnections.online(id), { backend, need });
@@ -438,6 +445,7 @@ class ContainerComputer extends ContainerComputerBase {
438
445
  : this.onBoxVmHost(backing.hostId);
439
446
  return new MeteredContainerHost(host, backing, () => this.computerSize(), (start) => {
440
447
  this.containerRuntimeStarted(start);
448
+ this.hostedRuntimeStarted(start.backing);
441
449
  });
442
450
  }
443
451
  /** The on-box VM host service for `hostId`, one per placement. */
@@ -633,6 +641,105 @@ export class ComputerDO extends ContainerComputer {
633
641
  #vaultReferenceRecord;
634
642
  #processStarts = new Map();
635
643
  #terminalSync;
644
+ #serviceRecord;
645
+ #servicesApplied = Promise.resolve();
646
+ /**
647
+ * The declared services. The process inventory is built first because it
648
+ * owns the exposed-port table a service port is admitted through.
649
+ */
650
+ get services() {
651
+ void this.#processes;
652
+ this.#serviceRecord ??= new ComputerServiceInventory(this.state.storage, () => Date.now());
653
+ return this.#serviceRecord;
654
+ }
655
+ /**
656
+ * Every runtime start (a wake, a recycle's replacement, a bump) brings the
657
+ * declared services back. One apply runs at a time, in start order; a
658
+ * failure is logged with its cause and leaves the next start to try again.
659
+ */
660
+ /** The declared services' view of this Computer: awake or not, and a command run on it. */
661
+ #servicesRuntime(backend) {
662
+ return {
663
+ awake: async () => {
664
+ const route = this.hostedRoute();
665
+ return (route !== undefined && (await this.containerRunning(route.backing)));
666
+ },
667
+ run: async (command) => {
668
+ const env_2 = { stack: [], error: void 0, hasError: false };
669
+ try {
670
+ const target = backend ?? this.requireHostedRoute().id;
671
+ const workspace = await this.readyWorkspace();
672
+ const run = __addDisposableResource(env_2, await workspace.runtime.exec(command, {
673
+ backend: target,
674
+ encoding: "utf8",
675
+ timeoutMs: 30_000,
676
+ }), false);
677
+ const { status, exitCode, stdout, stderr } = await run.result();
678
+ return { status, exitCode, stdout, stderr };
679
+ }
680
+ catch (e_2) {
681
+ env_2.error = e_2;
682
+ env_2.hasError = true;
683
+ }
684
+ finally {
685
+ __disposeResources(env_2);
686
+ }
687
+ },
688
+ };
689
+ }
690
+ /**
691
+ * Everything that renders or controls the services runs here, one at a time
692
+ * in arrival order, and reads the declarations only when its turn comes. A
693
+ * wake's apply and a tool's apply therefore never race: the later one always
694
+ * carries the newer declarations.
695
+ */
696
+ #serialServices(work) {
697
+ const turn = this.#servicesApplied.then(work);
698
+ this.#servicesApplied = turn.then(() => undefined, () => undefined);
699
+ return turn;
700
+ }
701
+ hostedRuntimeStarted(backing) {
702
+ const runtime = this.#servicesRuntime(attachedBackendId(backing));
703
+ const applied = this.#serialServices(async () => {
704
+ try {
705
+ await applyDeclaredServices({
706
+ inventory: this.services,
707
+ run: runtime.run,
708
+ });
709
+ }
710
+ catch (cause) {
711
+ Effect.runSync(Effect.logError("Computer declared services were not applied", Redacted.make(cause)));
712
+ }
713
+ });
714
+ this.state.waitUntil(applied);
715
+ }
716
+ /** The Agent tools for declared services, once the host accepts the call. */
717
+ async serviceToolAfterAcceptance(tool, input, accept) {
718
+ accept();
719
+ return await this.#serialServices(() => this.#serviceTool(tool, input));
720
+ }
721
+ async #serviceTool(tool, input) {
722
+ const runtime = this.#servicesRuntime();
723
+ const inventory = this.services;
724
+ switch (tool) {
725
+ case "declare_service":
726
+ return computerValueSchema.parse(await declareService(inventory, runtime, computerServiceDeclarationSchema.parse(input), "agent"));
727
+ case "list_services":
728
+ return computerValueSchema.parse(await listServices(inventory, runtime));
729
+ case "service_logs":
730
+ return computerValueSchema.parse(await serviceLogs(inventory, runtime, serviceLogsInputSchema.parse(input)));
731
+ case "stop_service":
732
+ return computerValueSchema.parse(await setServiceEnabled(inventory, runtime, serviceNameInputSchema.parse(input).name, false));
733
+ case "start_service":
734
+ return computerValueSchema.parse(await setServiceEnabled(inventory, runtime, serviceNameInputSchema.parse(input).name, true));
735
+ case "restart_service":
736
+ return computerValueSchema.parse(await restartService(inventory, runtime, serviceNameInputSchema.parse(input).name));
737
+ case "remove_service":
738
+ return computerValueSchema.parse(await removeService(inventory, runtime, serviceNameInputSchema.parse(input).name));
739
+ default:
740
+ throw new Error(`Computer capability is unavailable: ${tool}`);
741
+ }
742
+ }
636
743
  get #processes() {
637
744
  this.#processRecord ??= new ComputerProcessInventory(this.state.storage, () => Date.now());
638
745
  return this.#processRecord;
@@ -742,23 +849,23 @@ export class ComputerDO extends ContainerComputer {
742
849
  let observed;
743
850
  let archivedExit = false;
744
851
  try {
745
- const env_2 = { stack: [], error: void 0, hasError: false };
852
+ const env_3 = { stack: [], error: void 0, hasError: false };
746
853
  try {
747
854
  // Hold both handles unread. A live execution admits only one subscriber;
748
855
  // two successful gets therefore prove archived native completion.
749
- const first = __addDisposableResource(env_2, await runtime.getExec(invocationId, { resume: "tail" }), false);
856
+ const first = __addDisposableResource(env_3, await runtime.getExec(invocationId, { resume: "tail" }), false);
750
857
  void first;
751
- const second = __addDisposableResource(env_2, await runtime.getExec(invocationId, { resume: "tail" }), false);
858
+ const second = __addDisposableResource(env_3, await runtime.getExec(invocationId, { resume: "tail" }), false);
752
859
  void second;
753
860
  archivedExit = true;
754
861
  observed = { state: "exited", exitCode: null, sync: "unknown" };
755
862
  }
756
- catch (e_2) {
757
- env_2.error = e_2;
758
- env_2.hasError = true;
863
+ catch (e_3) {
864
+ env_3.error = e_3;
865
+ env_3.hasError = true;
759
866
  }
760
867
  finally {
761
- __disposeResources(env_2);
868
+ __disposeResources(env_3);
762
869
  }
763
870
  }
764
871
  catch (cause) {
@@ -1182,6 +1289,14 @@ export class ComputerDO extends ContainerComputer {
1182
1289
  return this.processLogsAfterAcceptance(input, accept);
1183
1290
  case "wait_process":
1184
1291
  return await this.waitProcessAfterAcceptance(input, accept);
1292
+ case "declare_service":
1293
+ case "list_services":
1294
+ case "service_logs":
1295
+ case "stop_service":
1296
+ case "start_service":
1297
+ case "restart_service":
1298
+ case "remove_service":
1299
+ return await this.serviceToolAfterAcceptance(selected, input, accept);
1185
1300
  }
1186
1301
  await this.prepareFiles();
1187
1302
  const workspace = await this.readyWorkspace();
@@ -1755,10 +1870,10 @@ export class ComputerDO extends ContainerComputer {
1755
1870
  if (hosted === undefined)
1756
1871
  return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
1757
1872
  try {
1758
- const env_3 = { stack: [], error: void 0, hasError: false };
1873
+ const env_4 = { stack: [], error: void 0, hasError: false };
1759
1874
  try {
1760
1875
  const workspace = await this.readyWorkspace();
1761
- const readiness = __addDisposableResource(env_3, await workspace.runtime.exec("true", {
1876
+ const readiness = __addDisposableResource(env_4, await workspace.runtime.exec("true", {
1762
1877
  backend: hosted.id,
1763
1878
  encoding: "utf8",
1764
1879
  timeoutMs: 10_000,
@@ -1768,12 +1883,12 @@ export class ComputerDO extends ContainerComputer {
1768
1883
  return Response.json({ error: "Computer container is unavailable" }, { status: 502 });
1769
1884
  }
1770
1885
  }
1771
- catch (e_3) {
1772
- env_3.error = e_3;
1773
- env_3.hasError = true;
1886
+ catch (e_4) {
1887
+ env_4.error = e_4;
1888
+ env_4.hasError = true;
1774
1889
  }
1775
1890
  finally {
1776
- __disposeResources(env_3);
1891
+ __disposeResources(env_4);
1777
1892
  }
1778
1893
  }
1779
1894
  catch (cause) {
@@ -1847,17 +1962,17 @@ export { LocalBackendOfflineError, localBackendAudience, localBackendDialPath, o
1847
1962
  /** Keep each native Workspace lease inside the operation that uses it. */
1848
1963
  export function createComputerFilesPort(computer) {
1849
1964
  async function withFiles(operation) {
1850
- const env_4 = { stack: [], error: void 0, hasError: false };
1965
+ const env_5 = { stack: [], error: void 0, hasError: false };
1851
1966
  try {
1852
- const workspace = __addDisposableResource(env_4, await getWorkspace(computer), false);
1967
+ const workspace = __addDisposableResource(env_5, await getWorkspace(computer), false);
1853
1968
  return await operation(createWorkspaceFilesPort(workspace, computer));
1854
1969
  }
1855
- catch (e_4) {
1856
- env_4.error = e_4;
1857
- env_4.hasError = true;
1970
+ catch (e_5) {
1971
+ env_5.error = e_5;
1972
+ env_5.hasError = true;
1858
1973
  }
1859
1974
  finally {
1860
- __disposeResources(env_4);
1975
+ __disposeResources(env_5);
1861
1976
  }
1862
1977
  }
1863
1978
  return {
@@ -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
+ }
@@ -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, ComputerPortReservedError, ComputerPortConflictError, ComputerPortLimitError, isComputerReservedPort, maximumExposedPorts, maximumProcessLogLineCharacters, maximumProcessLogLines, maximumProcessRecords, maximumRunningProcesses, } from "@fungi.computer/computer-contract";
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.sql.exec("CREATE TABLE IF NOT EXISTS computer_exposed_ports (port INTEGER PRIMARY KEY CHECK (port BETWEEN 1 AND 65535), process_id TEXT) STRICT");
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
- if (isComputerReservedPort(input.port))
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.sql.exec("DELETE FROM computer_exposed_ports WHERE process_id = ?", id);
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.sql.exec("DELETE FROM computer_exposed_ports WHERE process_id = ?", id);
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. */
@@ -0,0 +1,34 @@
1
+ import type { ComputerServiceInventory, ComputerServicesApply } from "./services.js";
2
+ /** The command result `applyDeclaredServices` needs from the Computer's exec path. */
3
+ export type ServicesCommandResult = Readonly<{
4
+ status: string;
5
+ exitCode: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }>;
9
+ /** `fungi-services apply` did not finish; the Computer's services may be stopped. */
10
+ export declare class ComputerServicesApplyError extends Error {
11
+ constructor(result: ServicesCommandResult);
12
+ }
13
+ /** A read or control command of `fungi-services` did not finish. */
14
+ export declare class ComputerServicesCommandError extends Error {
15
+ constructor(operation: string, result: ServicesCommandResult);
16
+ }
17
+ /**
18
+ * The shell command that hands `fungi-services apply` the declarations. The
19
+ * JSON travels as base64, which holds only characters a single-quoted word
20
+ * keeps literal, so no declared byte reaches the shell as syntax.
21
+ */
22
+ export declare function servicesApplyCommand(payload: ComputerServicesApply): string;
23
+ /**
24
+ * Bring a runtime to the declared services: re-admit their ports, then render
25
+ * and start them. On a fresh runtime a Computer with nothing declared runs
26
+ * nothing, because its scan directory is already empty; a live runtime that
27
+ * just lost its last declaration still needs the apply that stops it, so a
28
+ * caller that changed a declaration passes `whenEmpty: "run"`.
29
+ */
30
+ export declare function applyDeclaredServices(options: {
31
+ inventory: ComputerServiceInventory;
32
+ run: (command: string) => Promise<ServicesCommandResult>;
33
+ whenEmpty?: "run" | "skip";
34
+ }): Promise<"applied" | "none">;
@@ -0,0 +1,43 @@
1
+ /** `fungi-services apply` did not finish; the Computer's services may be stopped. */
2
+ export class ComputerServicesApplyError extends Error {
3
+ constructor(result) {
4
+ super(`Computer services could not be applied (${result.status}, exit ${String(result.exitCode)}): ${result.stderr.slice(0, 500)}`);
5
+ this.name = "ComputerServicesApplyError";
6
+ }
7
+ }
8
+ /** A read or control command of `fungi-services` did not finish. */
9
+ export class ComputerServicesCommandError extends Error {
10
+ constructor(operation, result) {
11
+ super(`Computer services ${operation} failed (${result.status}, exit ${String(result.exitCode)}): ${result.stderr.slice(0, 500)}`);
12
+ this.name = "ComputerServicesCommandError";
13
+ }
14
+ }
15
+ /**
16
+ * The shell command that hands `fungi-services apply` the declarations. The
17
+ * JSON travels as base64, which holds only characters a single-quoted word
18
+ * keeps literal, so no declared byte reaches the shell as syntax.
19
+ */
20
+ export function servicesApplyCommand(payload) {
21
+ let binary = "";
22
+ for (const byte of new TextEncoder().encode(JSON.stringify(payload)))
23
+ binary += String.fromCharCode(byte);
24
+ const encoded = btoa(binary);
25
+ return `printf %s '${encoded}' | base64 -d | fungi-services apply`;
26
+ }
27
+ /**
28
+ * Bring a runtime to the declared services: re-admit their ports, then render
29
+ * and start them. On a fresh runtime a Computer with nothing declared runs
30
+ * nothing, because its scan directory is already empty; a live runtime that
31
+ * just lost its last declaration still needs the apply that stops it, so a
32
+ * caller that changed a declaration passes `whenEmpty: "run"`.
33
+ */
34
+ export async function applyDeclaredServices(options) {
35
+ options.inventory.ensurePorts();
36
+ const payload = options.inventory.applyPayload();
37
+ if (payload.services.length === 0 && options.whenEmpty !== "run")
38
+ return "none";
39
+ const result = await options.run(servicesApplyCommand(payload));
40
+ if (result.status !== "completed" || result.exitCode !== 0)
41
+ throw new ComputerServicesApplyError(result);
42
+ return "applied";
43
+ }
@@ -0,0 +1,30 @@
1
+ import { computerServiceViewSchema, serviceLogsOutputSchema, type serviceListOutputSchema } from "@fungi.computer/computer-contract";
2
+ import { z } from "zod";
3
+ import { type ServicesCommandResult } from "./services-apply.js";
4
+ import type { ComputerServiceDeclaration, ComputerServiceInventory } from "./services.js";
5
+ /** What the Agent tools need of a Computer: whether it is awake, and a command run on it. */
6
+ export type ServicesRuntime = Readonly<{
7
+ /** True only while a hosted runtime is running; asking never starts one. */
8
+ awake: () => Promise<boolean>;
9
+ run: (command: string) => Promise<ServicesCommandResult>;
10
+ }>;
11
+ export type ComputerServiceView = z.output<typeof computerServiceViewSchema>;
12
+ export type ComputerServiceList = z.output<typeof serviceListOutputSchema>;
13
+ /** `list_services`: every declaration with its live status; reading never wakes the Computer. */
14
+ export declare function listServices(inventory: ComputerServiceInventory, runtime: ServicesRuntime): Promise<ComputerServiceList>;
15
+ /** `declare_service`: save, then start now if the Computer is awake. */
16
+ export declare function declareService(inventory: ComputerServiceInventory, runtime: ServicesRuntime, input: ComputerServiceDeclaration, declaredBy: string): Promise<ComputerServiceView>;
17
+ /** `stop_service` and `start_service`: change whether it is declared as running. */
18
+ export declare function setServiceEnabled(inventory: ComputerServiceInventory, runtime: ServicesRuntime, name: string, enabled: boolean): Promise<ComputerServiceView>;
19
+ /** `restart_service`: apply first, then restart one that was already declared to run. */
20
+ export declare function restartService(inventory: ComputerServiceInventory, runtime: ServicesRuntime, name: string): Promise<ComputerServiceView>;
21
+ /** `remove_service`: forget it, stopping it if the Computer is awake. */
22
+ export declare function removeService(inventory: ComputerServiceInventory, runtime: ServicesRuntime, name: string): Promise<{
23
+ name: string;
24
+ removed: true;
25
+ }>;
26
+ /** `service_logs`: the newest lines, kept only while the Computer is awake. */
27
+ export declare function serviceLogs(inventory: ComputerServiceInventory, runtime: ServicesRuntime, input: {
28
+ name: string;
29
+ lines?: number | undefined;
30
+ }): Promise<z.output<typeof serviceLogsOutputSchema>>;
@@ -0,0 +1,91 @@
1
+ import { ComputerServiceNotFoundError, computerServiceViewSchema, computerServiceNameSchema, maximumProcessLogLines, serviceLogsOutputSchema, } from "@fungi.computer/computer-contract";
2
+ import { z } from "zod";
3
+ import { applyDeclaredServices, ComputerServicesCommandError, } from "./services-apply.js";
4
+ const supervisorStatus = z.strictObject({
5
+ services: z.record(computerServiceNameSchema, z.strictObject({
6
+ state: z.enum(["up", "restarting", "down"]),
7
+ pid: z.number().int().positive().optional(),
8
+ seconds: z.number().int().nonnegative().optional(),
9
+ })),
10
+ });
11
+ const logTail = serviceLogsOutputSchema;
12
+ async function command(runtime, operation, text) {
13
+ const result = await runtime.run(text);
14
+ if (result.status !== "completed" || result.exitCode !== 0)
15
+ throw new ComputerServicesCommandError(operation, result);
16
+ return result.stdout;
17
+ }
18
+ /** Render and start what is declared, now, but only on a runtime that already runs. */
19
+ async function applyWhileAwake(inventory, runtime) {
20
+ if (!(await runtime.awake()))
21
+ return false;
22
+ await applyDeclaredServices({
23
+ inventory,
24
+ run: (text) => runtime.run(text),
25
+ whenEmpty: "run",
26
+ });
27
+ return true;
28
+ }
29
+ async function views(inventory, runtime) {
30
+ const declared = inventory.list();
31
+ const awake = await runtime.awake();
32
+ const live = awake
33
+ ? supervisorStatus.parse(JSON.parse(await command(runtime, "status", "fungi-services status"))).services
34
+ : {};
35
+ return declared.map((service) => computerServiceViewSchema.parse({
36
+ ...service,
37
+ status: !awake
38
+ ? { state: "asleep" }
39
+ : (live[service.name] ??
40
+ // Declared and enabled but not rendered yet, or stopped and not rendered.
41
+ { state: service.enabled ? "restarting" : "down" }),
42
+ }));
43
+ }
44
+ async function viewOf(inventory, runtime, service) {
45
+ const found = (await views(inventory, runtime)).find((view) => view.name === service.name);
46
+ if (found === undefined)
47
+ throw new ComputerServiceNotFoundError(service.name);
48
+ return found;
49
+ }
50
+ /** `list_services`: every declaration with its live status; reading never wakes the Computer. */
51
+ export async function listServices(inventory, runtime) {
52
+ return { services: [...(await views(inventory, runtime))] };
53
+ }
54
+ /** `declare_service`: save, then start now if the Computer is awake. */
55
+ export async function declareService(inventory, runtime, input, declaredBy) {
56
+ const service = inventory.declare(input, declaredBy);
57
+ await applyWhileAwake(inventory, runtime);
58
+ return viewOf(inventory, runtime, service);
59
+ }
60
+ /** `stop_service` and `start_service`: change whether it is declared as running. */
61
+ export async function setServiceEnabled(inventory, runtime, name, enabled) {
62
+ const service = inventory.setEnabled(name, enabled);
63
+ await applyWhileAwake(inventory, runtime);
64
+ return viewOf(inventory, runtime, service);
65
+ }
66
+ /** `restart_service`: apply first, then restart one that was already declared to run. */
67
+ export async function restartService(inventory, runtime, name) {
68
+ const before = inventory.get(name);
69
+ if (before === undefined)
70
+ throw new ComputerServiceNotFoundError(name);
71
+ const service = inventory.setEnabled(name, true);
72
+ if (await applyWhileAwake(inventory, runtime))
73
+ if (before.enabled)
74
+ await command(runtime, "restart", `fungi-services restart ${name}`);
75
+ return viewOf(inventory, runtime, service);
76
+ }
77
+ /** `remove_service`: forget it, stopping it if the Computer is awake. */
78
+ export async function removeService(inventory, runtime, name) {
79
+ inventory.remove(name);
80
+ await applyWhileAwake(inventory, runtime);
81
+ return { name, removed: true };
82
+ }
83
+ /** `service_logs`: the newest lines, kept only while the Computer is awake. */
84
+ export async function serviceLogs(inventory, runtime, input) {
85
+ if (inventory.get(input.name) === undefined)
86
+ throw new ComputerServiceNotFoundError(input.name);
87
+ if (!(await runtime.awake()))
88
+ return { name: input.name, lines: [], truncated: false };
89
+ const lines = input.lines ?? maximumProcessLogLines;
90
+ return logTail.parse(JSON.parse(await command(runtime, "logs", `fungi-services logs ${input.name} ${String(lines)}`)));
91
+ }