@openape/nest 0.2.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.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/dist/index.js +294 -0
  3. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Hofmann
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/dist/index.js ADDED
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { createServer } from "http";
5
+ import process from "process";
6
+
7
+ // src/api/agents.ts
8
+ import { execFile } from "child_process";
9
+ import { promisify } from "util";
10
+
11
+ // src/lib/registry.ts
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
+ import { homedir } from "os";
14
+ import { join } from "path";
15
+ var REGISTRY_DIR = join(homedir(), ".openape", "nest");
16
+ var REGISTRY_PATH = join(REGISTRY_DIR, "agents.json");
17
+ function emptyRegistry() {
18
+ return { version: 1, agents: [] };
19
+ }
20
+ function readRegistry() {
21
+ if (!existsSync(REGISTRY_PATH)) return emptyRegistry();
22
+ try {
23
+ const parsed = JSON.parse(readFileSync(REGISTRY_PATH, "utf8"));
24
+ if (parsed?.version !== 1 || !Array.isArray(parsed.agents)) return emptyRegistry();
25
+ return parsed;
26
+ } catch {
27
+ return emptyRegistry();
28
+ }
29
+ }
30
+ function writeRegistry(reg) {
31
+ mkdirSync(REGISTRY_DIR, { recursive: true });
32
+ writeFileSync(REGISTRY_PATH, `${JSON.stringify(reg, null, 2)}
33
+ `, { mode: 384 });
34
+ }
35
+ function listAgents() {
36
+ return readRegistry().agents;
37
+ }
38
+ function findAgent(name) {
39
+ return readRegistry().agents.find((a) => a.name === name);
40
+ }
41
+ function upsertAgent(entry) {
42
+ const reg = readRegistry();
43
+ const existing = reg.agents.findIndex((a) => a.name === entry.name);
44
+ if (existing >= 0) reg.agents[existing] = entry;
45
+ else reg.agents.push(entry);
46
+ writeRegistry(reg);
47
+ }
48
+ function removeAgent(name) {
49
+ const reg = readRegistry();
50
+ const before = reg.agents.length;
51
+ reg.agents = reg.agents.filter((a) => a.name !== name);
52
+ if (reg.agents.length === before) return false;
53
+ writeRegistry(reg);
54
+ return true;
55
+ }
56
+
57
+ // src/api/agents.ts
58
+ var execFileAsync = promisify(execFile);
59
+ var NAME_REGEX = /^[a-z][a-z0-9-]{0,23}$/;
60
+ function handleNestStatus(ctx) {
61
+ return {
62
+ agents: listAgents().length,
63
+ processes: ctx.supervisor.status()
64
+ };
65
+ }
66
+ function handleAgentsList(_ctx) {
67
+ return { agents: listAgents() };
68
+ }
69
+ async function handleAgentSpawn(ctx) {
70
+ const body = ctx.body;
71
+ const name = typeof body?.name === "string" ? body.name : "";
72
+ if (!NAME_REGEX.test(name)) {
73
+ throw new Error(`name must match ${NAME_REGEX} (got "${name}")`);
74
+ }
75
+ if (findAgent(name)) {
76
+ throw new Error(`agent "${name}" is already registered with this nest`);
77
+ }
78
+ const args = ["run", "--as", "root", "--", "apes", "agents", "spawn", name];
79
+ const includeBridge = body?.bridge === true;
80
+ if (includeBridge) {
81
+ args.push("--bridge");
82
+ if (typeof body?.bridgeKey === "string") args.push("--bridge-key", body.bridgeKey);
83
+ if (typeof body?.bridgeBaseUrl === "string") args.push("--bridge-base-url", body.bridgeBaseUrl);
84
+ if (typeof body?.bridgeModel === "string") args.push("--bridge-model", body.bridgeModel);
85
+ }
86
+ ctx.log(`nest: spawning agent "${name}" via apes...`);
87
+ const { stdout: _stdout } = await execFileAsync(ctx.apesBin, args, { maxBuffer: 4 * 1024 * 1024 });
88
+ const uid = await readUidFromDscl(name);
89
+ const entry = {
90
+ name,
91
+ uid,
92
+ home: `/Users/${name}`,
93
+ email: "",
94
+ // filled in on first sync — we don't know it locally
95
+ registeredAt: Math.floor(Date.now() / 1e3),
96
+ bridge: includeBridge ? {
97
+ baseUrl: typeof body?.bridgeBaseUrl === "string" ? body.bridgeBaseUrl : void 0,
98
+ apiKey: typeof body?.bridgeKey === "string" ? body.bridgeKey : void 0,
99
+ model: typeof body?.bridgeModel === "string" ? body.bridgeModel : void 0
100
+ } : void 0
101
+ };
102
+ upsertAgent(entry);
103
+ ctx.supervisor.reconcile(listAgents());
104
+ return { name, email: entry.email, uid, home: entry.home };
105
+ }
106
+ async function handleAgentDestroy(ctx, name) {
107
+ if (!NAME_REGEX.test(name)) throw new Error(`invalid agent name "${name}"`);
108
+ const entry = findAgent(name);
109
+ if (!entry) throw new Error(`agent "${name}" not registered with this nest`);
110
+ ctx.supervisor.stop(name);
111
+ ctx.log(`nest: destroying agent "${name}"...`);
112
+ const args = ["run", "--as", "root", "--", "apes", "agents", "destroy", name, "--force"];
113
+ await execFileAsync(ctx.apesBin, args, { maxBuffer: 4 * 1024 * 1024 });
114
+ removeAgent(name);
115
+ ctx.supervisor.reconcile(listAgents());
116
+ return { name, removed: true };
117
+ }
118
+ async function readUidFromDscl(name) {
119
+ try {
120
+ const { stdout } = await execFileAsync("/usr/bin/dscl", [".", "-read", `/Users/${name}`, "UniqueID"]);
121
+ const match = stdout.match(/UniqueID:\s*(\d+)/);
122
+ if (match) return Number(match[1]);
123
+ } catch {
124
+ }
125
+ return -1;
126
+ }
127
+
128
+ // src/lib/supervisor.ts
129
+ import { spawn } from "child_process";
130
+ var MIN_BACKOFF_MS = 1e3;
131
+ var MAX_BACKOFF_MS = 6e4;
132
+ var Supervisor = class {
133
+ constructor(deps) {
134
+ this.deps = deps;
135
+ }
136
+ children = /* @__PURE__ */ new Map();
137
+ /**
138
+ * Bring the supervised set in line with the desired set. Spawns
139
+ * agents that aren't running, kills agents that are no longer in
140
+ * the registry. Idempotent — call after every registry mutation.
141
+ */
142
+ reconcile(desired) {
143
+ const desiredNames = new Set(desired.map((a) => a.name));
144
+ for (const [name] of this.children) {
145
+ if (!desiredNames.has(name)) this.stop(name);
146
+ }
147
+ for (const agent of desired) {
148
+ if (!this.children.has(agent.name)) this.start(agent);
149
+ }
150
+ }
151
+ /** Number of currently-running supervised processes. */
152
+ size() {
153
+ return this.children.size;
154
+ }
155
+ /** Snapshot of supervised state — useful for /agents GET. */
156
+ status() {
157
+ const now = Date.now();
158
+ return Array.from(this.children.entries()).map(([name, s]) => ({
159
+ name,
160
+ pid: s.child.pid ?? -1,
161
+ uptimeSec: Math.floor((now - s.startedAt) / 1e3),
162
+ consecutiveCrashes: s.consecutiveCrashes
163
+ }));
164
+ }
165
+ start(agent) {
166
+ if (this.children.has(agent.name)) return;
167
+ this.deps.log(`supervisor: starting ${agent.name}`);
168
+ this.spawnChild(agent, 0);
169
+ }
170
+ stop(name) {
171
+ const s = this.children.get(name);
172
+ if (!s) return;
173
+ this.deps.log(`supervisor: stopping ${name}`);
174
+ if (s.restartTimer) clearTimeout(s.restartTimer);
175
+ this.children.delete(name);
176
+ try {
177
+ s.child.kill("SIGTERM");
178
+ } catch {
179
+ }
180
+ }
181
+ /** Kill all children — called on daemon shutdown. */
182
+ stopAll() {
183
+ for (const name of Array.from(this.children.keys())) this.stop(name);
184
+ }
185
+ spawnChild(agent, prevCrashes) {
186
+ const args = ["run", "--as", agent.name, "--", "openape-chat-bridge"];
187
+ const child = spawn(this.deps.apesBin, args, {
188
+ stdio: ["ignore", "pipe", "pipe"],
189
+ detached: false
190
+ });
191
+ child.stdout?.on("data", (chunk) => this.forwardLog(agent.name, "stdout", chunk));
192
+ child.stderr?.on("data", (chunk) => this.forwardLog(agent.name, "stderr", chunk));
193
+ const supervised = {
194
+ child,
195
+ consecutiveCrashes: prevCrashes,
196
+ startedAt: Date.now()
197
+ };
198
+ this.children.set(agent.name, supervised);
199
+ child.on("exit", (code, signal) => {
200
+ const stillManaged = this.children.get(agent.name) === supervised;
201
+ if (!stillManaged) return;
202
+ const ranLongEnough = Date.now() - supervised.startedAt > 3e4;
203
+ const nextCrashes = ranLongEnough ? 1 : prevCrashes + 1;
204
+ const backoff = Math.min(MAX_BACKOFF_MS, MIN_BACKOFF_MS * 2 ** Math.max(0, nextCrashes - 1));
205
+ this.deps.log(
206
+ `supervisor: ${agent.name} exited code=${code} signal=${signal ?? "none"} consecutive=${nextCrashes} \u2192 respawn in ${backoff}ms`
207
+ );
208
+ supervised.restartTimer = setTimeout(() => {
209
+ if (this.children.get(agent.name) !== supervised) return;
210
+ this.children.delete(agent.name);
211
+ this.spawnChild(agent, nextCrashes);
212
+ }, backoff);
213
+ });
214
+ }
215
+ forwardLog(name, stream, chunk) {
216
+ const text = chunk.toString("utf8");
217
+ for (const line of text.split("\n")) {
218
+ const trimmed = line.trimEnd();
219
+ if (!trimmed) continue;
220
+ this.deps.log(`[${name}/${stream}] ${trimmed}`);
221
+ }
222
+ }
223
+ };
224
+
225
+ // src/index.ts
226
+ var HOST = "127.0.0.1";
227
+ var PORT = Number(process.env.OPENAPE_NEST_PORT ?? 9091);
228
+ var APES_BIN = process.env.OPENAPE_APES_BIN ?? "apes";
229
+ function log(line) {
230
+ process.stderr.write(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}
231
+ `);
232
+ }
233
+ var supervisor = new Supervisor({ apesBin: APES_BIN, log });
234
+ supervisor.reconcile(listAgents());
235
+ log(`nest: supervisor reconciled, ${supervisor.size()} agent process(es) running`);
236
+ async function readJsonBody(req) {
237
+ const chunks = [];
238
+ for await (const chunk of req) chunks.push(chunk);
239
+ if (chunks.length === 0) return {};
240
+ const text = Buffer.concat(chunks).toString("utf8");
241
+ if (!text.trim()) return {};
242
+ try {
243
+ return JSON.parse(text);
244
+ } catch {
245
+ throw new Error("invalid JSON body");
246
+ }
247
+ }
248
+ function send(res, status, body) {
249
+ res.writeHead(status, { "content-type": "application/json" });
250
+ res.end(JSON.stringify(body));
251
+ }
252
+ var server = createServer((req, res) => {
253
+ ;
254
+ (async () => {
255
+ try {
256
+ const url = new URL(req.url ?? "/", `http://${HOST}:${PORT}`);
257
+ const body = req.method && ["POST", "PUT", "PATCH"].includes(req.method) ? await readJsonBody(req) : {};
258
+ const ctx = { url, body, log, apesBin: APES_BIN, supervisor };
259
+ if (req.method === "GET" && url.pathname === "/status") {
260
+ return send(res, 200, handleNestStatus(ctx));
261
+ }
262
+ if (req.method === "GET" && url.pathname === "/agents") {
263
+ return send(res, 200, handleAgentsList(ctx));
264
+ }
265
+ if (req.method === "POST" && url.pathname === "/agents") {
266
+ const result = await handleAgentSpawn(ctx);
267
+ return send(res, 201, result);
268
+ }
269
+ const destroyMatch = req.method === "DELETE" && url.pathname.match(/^\/agents\/([^/]+)$/);
270
+ if (destroyMatch) {
271
+ const result = await handleAgentDestroy(ctx, destroyMatch[1]);
272
+ return send(res, 200, result);
273
+ }
274
+ send(res, 404, { error: "not found" });
275
+ } catch (err) {
276
+ const msg = err instanceof Error ? err.message : String(err);
277
+ log(`nest: request failed: ${msg}`);
278
+ send(res, 500, { error: msg });
279
+ }
280
+ })();
281
+ });
282
+ server.listen(PORT, HOST, () => {
283
+ log(`nest: listening on http://${HOST}:${PORT}`);
284
+ });
285
+ process.on("SIGTERM", () => {
286
+ log("nest: SIGTERM \u2014 stopping supervisor");
287
+ supervisor.stopAll();
288
+ server.close(() => process.exit(0));
289
+ });
290
+ process.on("SIGINT", () => {
291
+ log("nest: SIGINT \u2014 stopping supervisor");
292
+ supervisor.stopAll();
293
+ server.close(() => process.exit(0));
294
+ });
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@openape/nest",
3
+ "version": "0.2.0",
4
+ "description": "OpenApe Nest — local control-plane daemon that supervises agent processes on this computer. Talks to troop SP for ownership state, spawns/destroys agents via DDISA always-grants, supervises chat-bridge children (replacing per-agent launchd plists).",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "private": false,
8
+ "bin": {
9
+ "openape-nest": "./dist/index.mjs"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "README.md"
14
+ ],
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "dependencies": {
19
+ "ofetch": "^1.4.1",
20
+ "@openape/cli-auth": "0.3.0"
21
+ },
22
+ "devDependencies": {
23
+ "@antfu/eslint-config": "^7.6.1",
24
+ "@types/node": "^22.19.13",
25
+ "eslint": "^9.35.0",
26
+ "tsup": "^8.5.1",
27
+ "typescript": "^5.9.3",
28
+ "vitest": "^3.2.4"
29
+ },
30
+ "engines": {
31
+ "node": ">=22"
32
+ },
33
+ "keywords": [
34
+ "openape",
35
+ "nest",
36
+ "agent",
37
+ "control-plane",
38
+ "supervisor"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "dev": "tsup --watch",
43
+ "typecheck": "tsc --noEmit",
44
+ "lint": "eslint .",
45
+ "lint:fix": "eslint . --fix",
46
+ "test": "vitest run"
47
+ }
48
+ }