@4fu/arbor-supervisor-process 0.0.0-stage → 2026.1106.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 4fuu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # arbor
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ arbor is a framework for an agent without sessions: many context windows run
4
+ at once over one shared record, so work moves in parallel, replies come fast,
5
+ and every window can find everything that was ever done.
6
+
7
+ A deployment composes the pieces it wants and registers plugins for the domains
8
+ it serves. The framework guarantees what an agent cannot guarantee for itself -
9
+ the record, isolation, exactly-once effects, the checks, dispatch - and leaves
10
+ everything that takes judgment, such as git, merges and conflicts, to the agent.
11
+
12
+ ## Core ideas
13
+
14
+ - **No sessions to manage.** Work runs in disposable context windows. Any
15
+ number run at the same time; none of them owns anything, and a window that
16
+ ends loses nothing. The model looks up what it needs instead of carrying it.
17
+ - **One record, shared live.** Every input, tool call, result, send and note
18
+ revision goes into one journal and is visible to every window as
19
+ soon as it is written. Records never merge and are never lost.
20
+ - **Dispatch by a judge.** A judge (Jev by default, replaceable) decides which
21
+ live window takes a new input, or opens a new one. There is no router session
22
+ and no main line.
23
+ - **Current without locks.** Windows run in parallel. New events on a
24
+ conversation a window is in are steered into it as they arrive; only a note
25
+ write is checked against the revision the window read.
26
+ - **Mechanisms in the framework, policy in the agent.** The framework
27
+ guarantees what an agent cannot guarantee for itself - the record, isolation,
28
+ exactly-once effects, the checks, dispatch. Everything that takes judgment,
29
+ such as git, merges and conflicts, is the agent's.
30
+ - **A directory per window.** Each window gets its own directory, and a
31
+ continuation keeps working in its predecessor's directory in place. It is not
32
+ bound to a repository; the agent clones and pushes what it needs.
33
+ - **A self-changing environment.** The model adds and changes skills, MCP
34
+ servers and resident services itself; a `reload` validates the change and
35
+ broadcasts it to every live window as a delta of names and descriptions.
36
+ - **Minimal limits.** The framework sets no policy. Permissions, privacy
37
+ review, budgets and approvals belong to deployments built on it, through
38
+ hooks.
39
+ - **Direct tools plus code mode.** Decisions are direct tools; everything else
40
+ is a module called from `code_exec`. There is no CLI.
41
+ - **Every module is replaceable.** The agent backend (pi by default), the
42
+ journal, notes, workspaces, the judge, channels and the rest are interfaces
43
+ ([docs/architecture.md](docs/architecture.md#interfaces)).
44
+
45
+ ## Install
46
+
47
+ Node 24 or newer. Every package is published separately, so a deployment
48
+ installs the core and the defaults it wants:
49
+
50
+ ```sh
51
+ npm install @4fu/arbor-core @4fu/arbor-journal-sqlite @4fu/arbor-notes-sqlite \
52
+ @4fu/arbor-environment-dir @4fu/arbor-supervisor-process @4fu/arbor-agent-pi \
53
+ @4fu/arbor-workspace-dir
54
+ ```
55
+
56
+ `@4fu/arbor-plugin-http` is optional; it is the example plugin below.
57
+ `@4fu/arbor-segmenter-jieba` is an optional peer of the journal.
58
+
59
+ ## A minimal host
60
+
61
+ The smallest host needs a journal and a backend. Adding the defaults and one
62
+ plugin is what a deployment usually starts from:
63
+
64
+ ```js
65
+ import { mkdtemp } from "node:fs/promises";
66
+ import { tmpdir } from "node:os";
67
+ import { join } from "node:path";
68
+ import { Arbor } from "@4fu/arbor-core";
69
+ import { DirectoryEnvironment } from "@4fu/arbor-environment-dir";
70
+ import { SqliteJournal } from "@4fu/arbor-journal-sqlite";
71
+ import { SqliteNoteStore } from "@4fu/arbor-notes-sqlite";
72
+ import { ProcessSupervisor } from "@4fu/arbor-supervisor-process";
73
+ import { DirectoryWorkspace } from "@4fu/arbor-workspace-dir";
74
+ import { PiAgentBackend } from "@4fu/arbor-agent-pi";
75
+ import { HttpChannel, httpPlugin } from "@4fu/arbor-plugin-http";
76
+
77
+ const root = await mkdtemp(join(tmpdir(), "arbor-"));
78
+
79
+ // Every module below is a default implementation of an interface. Replace any
80
+ // one by passing your own; the host does not change.
81
+ const journal = new SqliteJournal({ path: join(root, "journal.sqlite") });
82
+ const notes = new SqliteNoteStore({ path: join(root, "notes.sqlite"), journal });
83
+ const supervisor = new ProcessSupervisor({ root: join(root, "services") });
84
+ const environment = new DirectoryEnvironment({ root: join(root, "env"), supervisor });
85
+ const workspace = new DirectoryWorkspace({ root: join(root, "workspaces") });
86
+
87
+ // A plugin adds; it never patches the core. This one is a chat channel: a
88
+ // webhook in, a window's sends out, and a page that drives the whole host.
89
+ let arbor;
90
+ const channel = new HttpChannel({ host: "127.0.0.1", port: 8787, board: () => arbor.boardLines() });
91
+ arbor = new Arbor({
92
+ journal,
93
+ notes,
94
+ backend: new PiAgentBackend(),
95
+ workspace,
96
+ environment,
97
+ supervisor,
98
+ plugins: [httpPlugin({ channel })],
99
+ });
100
+
101
+ await arbor.start();
102
+ await channel.listen();
103
+ ```
104
+
105
+ `arbor.open(task)` dispatches one task, and the journal is where everything that
106
+ happened can be read back ([docs/journal.md](docs/journal.md)). The workspace a
107
+ window gets, and how a continuation keeps working in it, are in
108
+ [docs/workspaces.md](docs/workspaces.md).
109
+
110
+ ## Packages
111
+
112
+ | Package | What it is |
113
+ | --- | --- |
114
+ | [`@4fu/arbor-interfaces`](packages/interfaces) | every replaceable interface, plus the core's own shapes. Types only. |
115
+ | [`@4fu/arbor-errors`](packages/errors) | the error shape every refusal uses: the rule and the next action |
116
+ | [`@4fu/arbor-prompt`](packages/prompt) | typed blocks, the one deterministic renderer and the replaceable text table |
117
+ | [`@4fu/arbor-tools`](packages/tools) | the entry points: direct tools, code mode modules, the host API |
118
+ | [`@4fu/arbor-journal-sqlite`](packages/journal-sqlite) | the default `Journal` and `BlobStore` on SQLite |
119
+ | [`@4fu/arbor-notes-sqlite`](packages/notes-sqlite) | the default `NoteStore` on SQLite, beside the journal |
120
+ | [`@4fu/arbor-segmenter-jieba`](packages/segmenter-jieba) | the default `Segmenter`: jieba's dictionary segmentation for the word index, optional |
121
+ | [`@4fu/arbor-workspace-dir`](packages/workspace-dir) | the default `Workspace`: one directory per window, with a continuation working in its predecessor's directory in place |
122
+ | [`@4fu/arbor-environment-dir`](packages/environment-dir) | the default `Environment`: one `/env` directory, a revision per item, validation and deltas |
123
+ | [`@4fu/arbor-supervisor-process`](packages/supervisor-process) | the default `Supervisor`: one host process per service, restart with backoff, logs |
124
+ | [`@4fu/arbor-judge-jev`](packages/judge-jev) | the default `Judge`: Jev, TypeSafe AI's System One classifier, answering the dispatch decisions |
125
+ | [`@4fu/arbor-agent-pi`](packages/agent-pi) | the default `AgentBackend`: pi-agent-core in process |
126
+ | [`@4fu/arbor-plugin-http`](packages/plugin-http) | the HTTP test channel: a webhook in, sends out, a page that drives the whole host |
127
+ | [`@4fu/arbor-core`](packages/core) | the service layer: one implementation of every operation - the window lifecycle, dispatch, coordination, the board, notes access, workspaces, effects and schedules |
128
+
129
+ ### Defaults are examples
130
+
131
+ Every default above is a reference implementation of its interface, written to
132
+ be read and replaced. A real deployment is expected to swap out the ones that do
133
+ not fit: the SQLite journal and notes, the directory workspace, the process
134
+ supervisor, the environment directory, the HTTP test plugin and the Jev judge
135
+ are all examples of what an interface can be satisfied by, not commitments.
136
+ What a deployment keeps is its own choice, and the interfaces are the contract
137
+ ([docs/architecture.md](docs/architecture.md#interfaces)).
138
+
139
+ Each package's own documentation holds the limits of that default, so a
140
+ deployment can see what it would be taking on before it adopts one.
141
+
142
+ ## Documents
143
+
144
+ | Page | Contents |
145
+ | --- | --- |
146
+ | [docs/overview.md](docs/overview.md) | goals, concepts, principles, routes considered |
147
+ | [docs/architecture.md](docs/architecture.md) | layers, interfaces, stack, models, plugins, hooks, data placement |
148
+ | [docs/journal.md](docs/journal.md) | events and their order, targets, watermarks, external ids, refs, tracing, media, redaction |
149
+ | [docs/windows.md](docs/windows.md) | window lifecycle, prompt layout, reminders, continuation |
150
+ | [docs/dispatch.md](docs/dispatch.md) | task sources, judge decisions, insertion timing, backpressure, scheduled tasks |
151
+ | [docs/coordination.md](docs/coordination.md) | the board, expectations, deliveries and broadcasts, staying current, effects |
152
+ | [docs/environment.md](docs/environment.md) | skills, MCP servers and services: using, changing, reload, built-in skills, deltas |
153
+ | [docs/memory.md](docs/memory.md) | notes, the active set, anchors, links |
154
+ | [docs/workspaces.md](docs/workspaces.md) | per-window directories: isolation, continuity, what the agent does |
155
+ | [docs/tools.md](docs/tools.md) | direct tools and code mode modules |
156
+ | [docs/prompting.md](docs/prompting.md) | how every model-facing text is written: layers, notes, deliveries, errors, judge questions, terms |
157
+ | [docs/release.md](docs/release.md) | calendar versioning, the manual release steps, how a package is published |
158
+
159
+ ## Repository layout
160
+
161
+ `pnpm check` typechecks and tests every package on its TypeScript sources.
162
+ `pnpm build` emits the `dist` publishing needs, and `pnpm pack` shows what each
163
+ tarball would contain ([docs/release.md](docs/release.md)).
164
+
165
+ | Path | Layer |
166
+ | --- | --- |
167
+ | `packages/interfaces` | the interfaces layer: every replaceable interface, plus the core's own shapes. Types only. |
168
+ | `packages/errors` | the error shape every refusal uses: the rule and the next action |
169
+ | `packages/journal-sqlite` | the default `Journal` and `BlobStore` on SQLite |
170
+ | `packages/segmenter-jieba` | the default `Segmenter`: jieba's dictionary segmentation for the word index, optional |
171
+ | `packages/notes-sqlite` | the default `NoteStore` on SQLite, beside the journal |
172
+ | `packages/judge-jev` | the default `Judge`: Jev, TypeSafe AI's System One classifier, answering the dispatch decisions |
173
+ | `packages/workspace-dir` | the default `Workspace`: one directory per window, with a continuation working in its predecessor's directory in place, and the lookup of another window's directory it contributes to the catalog |
174
+ | `packages/environment-dir` | the default `Environment`: one `/env` directory, a revision per item, validation and deltas |
175
+ | `packages/supervisor-process` | the default `Supervisor`: one host process per service, restart with backoff, logs |
176
+ | `packages/plugin-http` | the HTTP test channel: a webhook in, sends out, a page that drives the whole host |
177
+ | `packages/prompt` | typed blocks, the one deterministic renderer and the replaceable text table |
178
+ | `packages/agent-pi` | the default `AgentBackend`: pi-agent-core in process |
179
+ | `packages/tools` | the entry points: direct tools, code mode modules, the host API |
180
+ | `packages/core` | the service layer: one implementation of every operation - the window lifecycle, dispatch, coordination, the board, notes access, workspaces, effects, schedules and the snapshot epochs |
181
+
182
+ `mise.toml` pins the toolchain - Node and pnpm - installed under
183
+ `~/.local/share/mise`, and `.agents/setup` prepares a machine from it. A machine
184
+ without mise is expected to carry Node 24 or newer and pnpm 12 already.
185
+
186
+ ## License
187
+
188
+ MIT, see [LICENSE](LICENSE).
package/index.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @4fu/arbor-supervisor-process - the default `Supervisor`: one host process per
3
+ * service, restarted with backoff after a crash, with logs, state changes and
4
+ * quotas (docs/environment.md#services).
5
+ */
6
+ export { ProcessSupervisor, type ProcessSupervisorOptions } from "./process-supervisor.ts";
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @4fu/arbor-supervisor-process - the default `Supervisor`: one host process per
3
+ * service, restarted with backoff after a crash, with logs, state changes and
4
+ * quotas (docs/environment.md#services).
5
+ */
6
+ export { ProcessSupervisor } from "./process-supervisor.js";
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@4fu/arbor-supervisor-process",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2026.1106.0",
4
+ "type": "module",
5
+ "description": "The default Supervisor: one host process per service, restarted with backoff after a crash, with logs and state changes reported to the host.",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "default": "./index.js"
10
+ }
11
+ },
12
+ "types": "./index.d.ts",
13
+ "main": "./index.js",
14
+ "files": [
15
+ "index.d.ts",
16
+ "index.js",
17
+ "process-supervisor.d.ts",
18
+ "process-supervisor.js"
19
+ ],
20
+ "engines": {
21
+ "node": ">=24"
22
+ },
23
+ "license": "MIT",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/4fuu/arbor.git",
27
+ "directory": "packages/supervisor-process"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public"
31
+ },
32
+ "dependencies": {
33
+ "@4fu/arbor-errors": "2026.1106.0",
34
+ "@4fu/arbor-interfaces": "2026.1106.0"
35
+ }
36
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The default `Supervisor`: one host process per service, restarted with backoff
3
+ * after a crash, with logs and state changes reported to the host
4
+ * (docs/environment.md#services).
5
+ *
6
+ * ```text
7
+ * <root>/logs/<name>.log the service's own output, appended as it comes
8
+ * ```
9
+ *
10
+ * A service is started with its own directory as its working directory, and its
11
+ * secrets are injected by name: the configuration names them, the host resolves
12
+ * their values, and neither is written down here. What a service does to the
13
+ * outside world directly is outside the effect queue; an action that should be
14
+ * recorded and guaranteed goes through the host API.
15
+ *
16
+ * Quotas are the one approximation: a memory quota is applied with `ulimit -v`,
17
+ * which bounds address space rather than resident memory, and CPU shares are
18
+ * not applied, because cgroups need privileges a host process does not have.
19
+ */
20
+ import type { LogOptions, LogPage, Ref, ServiceHandle, ServiceSpec, ServiceStatus, Supervisor } from "@4fu/arbor-interfaces";
21
+ export interface ProcessSupervisorOptions {
22
+ /** The directory the logs live in. */
23
+ root: string;
24
+ /** Where a secret's value comes from. A configuration names one, never holds it. */
25
+ secretOf?: (name: string) => string | undefined;
26
+ /** The clock. Tests pass a fixed one. */
27
+ now?: () => number;
28
+ /** Records one state change and answers with its event ref. */
29
+ record?: (status: ServiceStatus) => Promise<Ref | undefined>;
30
+ }
31
+ export declare class ProcessSupervisor implements Supervisor {
32
+ private readonly root;
33
+ private readonly secretOf;
34
+ private readonly clock;
35
+ private readonly record;
36
+ private readonly running;
37
+ private handler;
38
+ private logRoot;
39
+ constructor(options: ProcessSupervisorOptions);
40
+ /**
41
+ * Start a service and wait for its health check. An upgrade is another start:
42
+ * the running revision is stopped first, so the swap is the item's, not the
43
+ * process's.
44
+ */
45
+ start(spec: ServiceSpec): Promise<ServiceHandle>;
46
+ status(name: string): Promise<ServiceStatus>;
47
+ stop(name: string): Promise<void>;
48
+ restart(name: string): Promise<ServiceHandle>;
49
+ logs(name: string, options?: LogOptions): Promise<LogPage>;
50
+ /** Report every state change to the host, so it records one and runs its hooks. */
51
+ onStateChange(handler: (status: ServiceStatus) => void | Promise<void>): void;
52
+ /** The services this supervisor runs, for `services.list`. */
53
+ list(): Promise<readonly ServiceStatus[]>;
54
+ private statusOf;
55
+ /** Start the process, or record that it never came up. */
56
+ private spawn;
57
+ /**
58
+ * Wait for the health check. A service that never becomes healthy is stopped
59
+ * and left failed, so `reload` refuses the install.
60
+ */
61
+ private healthy;
62
+ /** True when the process is up. */
63
+ private alive;
64
+ /** One health check: a 2xx on the service's own port, on the loopback interface. */
65
+ private reachable;
66
+ private kill;
67
+ /** One state change: recorded by the host, then reported to it. */
68
+ private move;
69
+ private logPath;
70
+ /** The log of a service this host no longer runs, for a restart. */
71
+ private readLog;
72
+ }
@@ -0,0 +1,330 @@
1
+ /**
2
+ * The default `Supervisor`: one host process per service, restarted with backoff
3
+ * after a crash, with logs and state changes reported to the host
4
+ * (docs/environment.md#services).
5
+ *
6
+ * ```text
7
+ * <root>/logs/<name>.log the service's own output, appended as it comes
8
+ * ```
9
+ *
10
+ * A service is started with its own directory as its working directory, and its
11
+ * secrets are injected by name: the configuration names them, the host resolves
12
+ * their values, and neither is written down here. What a service does to the
13
+ * outside world directly is outside the effect queue; an action that should be
14
+ * recorded and guaranteed goes through the host API.
15
+ *
16
+ * Quotas are the one approximation: a memory quota is applied with `ulimit -v`,
17
+ * which bounds address space rather than resident memory, and CPU shares are
18
+ * not applied, because cgroups need privileges a host process does not have.
19
+ */
20
+ import { spawn } from "node:child_process";
21
+ import { appendFile, mkdir, readFile } from "node:fs/promises";
22
+ import { get } from "node:http";
23
+ import { join } from "node:path";
24
+ import { arborError } from "@4fu/arbor-errors";
25
+ import { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from "@4fu/arbor-interfaces";
26
+ /** How many lines one service keeps in memory for `services.logs`. */
27
+ const LOG_MEMORY_LINES = 2000;
28
+ /** How often the health check runs. */
29
+ const DEFAULT_INTERVAL_MS = 500;
30
+ /** How long a health check may take before the start is refused. */
31
+ const DEFAULT_TIMEOUT_MS = 30000;
32
+ /** How many times a service is restarted before it is left failed. */
33
+ const DEFAULT_MAX_RETRIES = 5;
34
+ /** How long to wait between restarts. */
35
+ const DEFAULT_BACKOFF_MS = 1000;
36
+ export class ProcessSupervisor {
37
+ root;
38
+ secretOf;
39
+ clock;
40
+ record;
41
+ running = new Map();
42
+ handler;
43
+ logRoot;
44
+ constructor(options) {
45
+ this.root = options.root;
46
+ this.secretOf = options.secretOf;
47
+ this.clock = options.now ?? (() => Date.now());
48
+ this.record = options.record;
49
+ }
50
+ /**
51
+ * Start a service and wait for its health check. An upgrade is another start:
52
+ * the running revision is stopped first, so the swap is the item's, not the
53
+ * process's.
54
+ */
55
+ async start(spec) {
56
+ const existing = this.running.get(spec.name);
57
+ if (existing !== undefined)
58
+ await this.kill(existing);
59
+ const service = {
60
+ spec,
61
+ revision: (existing?.revision ?? 0) + 1,
62
+ state: "starting",
63
+ restarts: existing?.restarts ?? 0,
64
+ since: this.clock(),
65
+ lines: [],
66
+ refs: [],
67
+ stopping: false,
68
+ };
69
+ this.running.set(spec.name, service);
70
+ await this.spawn(service);
71
+ await this.healthy(service);
72
+ return { name: spec.name, revision: service.revision, state: service.state };
73
+ }
74
+ async status(name) {
75
+ const service = this.running.get(name);
76
+ if (service === undefined) {
77
+ throw arborError({
78
+ code: "not_found",
79
+ rule: "service.notfound",
80
+ message: `服务:没有服务 ${name}`,
81
+ nextAction: "用 services.list 查看当前的服务。",
82
+ details: { name },
83
+ });
84
+ }
85
+ return this.statusOf(service);
86
+ }
87
+ async stop(name) {
88
+ const service = this.running.get(name);
89
+ if (service === undefined)
90
+ return;
91
+ service.stopping = true;
92
+ await this.kill(service);
93
+ await this.move(service, "stopped");
94
+ }
95
+ async restart(name) {
96
+ const service = this.running.get(name);
97
+ if (service === undefined) {
98
+ throw arborError({
99
+ code: "not_found",
100
+ rule: "service.notfound",
101
+ message: `服务:没有服务 ${name}`,
102
+ nextAction: "用 services.list 查看当前的服务。",
103
+ details: { name },
104
+ });
105
+ }
106
+ service.stopping = false;
107
+ service.restarts = 0;
108
+ await this.kill(service);
109
+ await this.spawn(service);
110
+ await this.healthy(service);
111
+ return { name, revision: service.revision, state: service.state };
112
+ }
113
+ async logs(name, options) {
114
+ const service = this.running.get(name);
115
+ const limit = clamp(options?.limit ?? options?.tail ?? DEFAULT_PAGE_LIMIT);
116
+ const lines = service === undefined ? await this.readLog(name) : [...service.lines];
117
+ const tail = options?.tail === undefined ? lines : lines.slice(-options.tail);
118
+ const items = tail.slice(-limit);
119
+ return {
120
+ items,
121
+ total: lines.length,
122
+ limit,
123
+ name,
124
+ nextCall: `services.logs({ name: ${JSON.stringify(name)}, tail: ${limit} })`,
125
+ };
126
+ }
127
+ /** Report every state change to the host, so it records one and runs its hooks. */
128
+ onStateChange(handler) {
129
+ this.handler = handler;
130
+ }
131
+ /** The services this supervisor runs, for `services.list`. */
132
+ async list() {
133
+ return [...this.running.values()].map((service) => this.statusOf(service));
134
+ }
135
+ statusOf(service) {
136
+ return {
137
+ name: service.spec.name,
138
+ revision: service.revision,
139
+ state: service.state,
140
+ restarts: service.restarts,
141
+ since: service.since,
142
+ ports: [...(service.spec.ports ?? [])],
143
+ ...(service.lastError === undefined ? {} : { lastError: service.lastError }),
144
+ refs: [...service.refs],
145
+ };
146
+ }
147
+ /** Start the process, or record that it never came up. */
148
+ async spawn(service) {
149
+ const spec = service.spec;
150
+ const secrets = {};
151
+ for (const name of spec.secrets ?? []) {
152
+ const value = this.secretOf?.(name);
153
+ if (value !== undefined && value !== "")
154
+ secrets[name] = value;
155
+ }
156
+ if (this.logRoot === undefined) {
157
+ this.logRoot = mkdir(join(this.root, "logs"), { recursive: true }).then(() => undefined);
158
+ }
159
+ await this.logRoot;
160
+ const command = quotaCommand(spec);
161
+ const child = spawn(command.bin, command.args, {
162
+ ...(spec.dir === undefined ? {} : { cwd: spec.dir }),
163
+ env: { ...process.env, ...(spec.env ?? {}), ...secrets },
164
+ stdio: ["ignore", "pipe", "pipe"],
165
+ });
166
+ service.child = child;
167
+ const note = (chunk) => {
168
+ const text = chunk.toString("utf8");
169
+ for (const line of text.split("\n")) {
170
+ if (line === "")
171
+ continue;
172
+ service.lines.push(line);
173
+ if (service.lines.length > LOG_MEMORY_LINES)
174
+ service.lines.shift();
175
+ void appendFile(this.logPath(spec.name), `${line}\n`, "utf8").catch(() => { });
176
+ }
177
+ };
178
+ child.stdout?.on("data", note);
179
+ child.stderr?.on("data", note);
180
+ child.on("error", (error) => {
181
+ service.lastError = {
182
+ code: "unavailable",
183
+ rule: "service.spawn.failed",
184
+ message: `服务 ${spec.name} 启动失败:${error.message}`,
185
+ nextAction: "检查 command 和 args 是否可在主机上运行。",
186
+ };
187
+ });
188
+ child.on("exit", (code, signal) => {
189
+ service.child = undefined;
190
+ if (service.stopping)
191
+ return;
192
+ const max = spec.restart?.maxRetries ?? DEFAULT_MAX_RETRIES;
193
+ service.lastError = {
194
+ code: "unavailable",
195
+ rule: "service.crashed",
196
+ message: `服务 ${spec.name} 退出(code ${code ?? "null"}${signal === null ? "" : `, signal ${signal}`})`,
197
+ nextAction: "用 services.logs 查看输出,修好后用 reload 重新安装。",
198
+ };
199
+ if (service.restarts >= max) {
200
+ void this.move(service, "failed");
201
+ return;
202
+ }
203
+ service.restarts += 1;
204
+ const backoff = spec.restart?.backoffMs ?? DEFAULT_BACKOFF_MS;
205
+ service.timer = setTimeout(() => {
206
+ // A restart that fails is reported through `status`, not through a
207
+ // rejection nobody is waiting for.
208
+ void this.spawn(service)
209
+ .then(() => this.healthy(service))
210
+ .catch(() => { });
211
+ }, backoff);
212
+ service.timer.unref();
213
+ });
214
+ }
215
+ /**
216
+ * Wait for the health check. A service that never becomes healthy is stopped
217
+ * and left failed, so `reload` refuses the install.
218
+ */
219
+ async healthy(service) {
220
+ const check = service.spec.healthCheck;
221
+ const timeout = check?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
222
+ const interval = check?.intervalMs ?? DEFAULT_INTERVAL_MS;
223
+ const deadline = Date.now() + timeout;
224
+ for (;;) {
225
+ const ok = check === undefined || check.port === undefined ? this.alive(service) : await this.reachable(check.port, check.path ?? "/");
226
+ if (ok) {
227
+ await this.move(service, "running");
228
+ return;
229
+ }
230
+ if (Date.now() >= deadline || service.state === "failed") {
231
+ service.lastError = {
232
+ code: "unavailable",
233
+ rule: "service.health_check",
234
+ message: `服务 ${service.spec.name} 没有在 ${timeout} ms 内通过健康检查`,
235
+ nextAction: "用 services.logs 查看输出,修好后用 reload 重新安装。",
236
+ };
237
+ await this.kill(service);
238
+ await this.move(service, "failed");
239
+ throw arborError({
240
+ code: "unavailable",
241
+ rule: "service.health_check",
242
+ message: `服务 ${service.spec.name} 没有通过健康检查`,
243
+ nextAction: "用 services.logs 查看服务的输出,修好后重新调用 reload。",
244
+ details: { name: service.spec.name },
245
+ });
246
+ }
247
+ await sleep(interval);
248
+ }
249
+ }
250
+ /** True when the process is up. */
251
+ alive(service) {
252
+ return service.child !== undefined && service.child.exitCode === null;
253
+ }
254
+ /** One health check: a 2xx on the service's own port, on the loopback interface. */
255
+ reachable(port, path) {
256
+ return new Promise((resolve) => {
257
+ const request = get({ host: "127.0.0.1", port, path }, (response) => {
258
+ response.resume();
259
+ resolve((response.statusCode ?? 500) >= 200 && (response.statusCode ?? 500) < 300);
260
+ });
261
+ request.on("error", () => resolve(false));
262
+ request.setTimeout(2000, () => {
263
+ request.destroy();
264
+ resolve(false);
265
+ });
266
+ });
267
+ }
268
+ async kill(service) {
269
+ if (service.timer !== undefined) {
270
+ clearTimeout(service.timer);
271
+ service.timer = undefined;
272
+ }
273
+ const child = service.child;
274
+ service.child = undefined;
275
+ if (child === undefined)
276
+ return;
277
+ child.kill("SIGTERM");
278
+ await new Promise((resolve) => {
279
+ if (child.exitCode !== null || child.signalCode !== null) {
280
+ resolve();
281
+ return;
282
+ }
283
+ const timer = setTimeout(() => child.kill("SIGKILL"), 2000);
284
+ child.once("exit", () => {
285
+ clearTimeout(timer);
286
+ resolve();
287
+ });
288
+ });
289
+ }
290
+ /** One state change: recorded by the host, then reported to it. */
291
+ async move(service, state) {
292
+ if (service.state === state)
293
+ return;
294
+ service.state = state;
295
+ service.since = this.clock();
296
+ const status = this.statusOf(service);
297
+ const ref = this.record === undefined ? undefined : await this.record(status).catch(() => undefined);
298
+ if (ref !== undefined)
299
+ service.refs.push(ref);
300
+ await this.handler?.(status);
301
+ }
302
+ logPath(name) {
303
+ return join(this.root, "logs", `${name}.log`);
304
+ }
305
+ /** The log of a service this host no longer runs, for a restart. */
306
+ async readLog(name) {
307
+ const text = await readFile(this.logPath(name), "utf8").catch(() => "");
308
+ return text.split("\n").filter((line) => line !== "");
309
+ }
310
+ }
311
+ /** A memory quota is applied with `ulimit`, so the command is wrapped in a shell. */
312
+ function quotaCommand(spec) {
313
+ const args = [...(spec.args ?? [])];
314
+ const memory = spec.quota?.memoryBytes;
315
+ if (memory === undefined || memory <= 0)
316
+ return { bin: spec.command, args };
317
+ const kilobytes = Math.max(1, Math.floor(memory / 1024));
318
+ return {
319
+ bin: "/bin/sh",
320
+ args: ["-c", `ulimit -v ${kilobytes}; exec "$@"`, "arbor-service", spec.command, ...args],
321
+ };
322
+ }
323
+ function clamp(limit) {
324
+ if (!Number.isFinite(limit))
325
+ return DEFAULT_PAGE_LIMIT;
326
+ return Math.min(Math.max(1, Math.floor(limit)), MAX_PAGE_LIMIT);
327
+ }
328
+ function sleep(ms) {
329
+ return new Promise((resolve) => setTimeout(resolve, ms));
330
+ }