Compare commits
164
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
add923c74a | ||
|
|
d4a6008bd6 | ||
|
|
83a51832d7 | ||
|
|
9e63a258d0 | ||
|
|
328d90fb88 | ||
|
|
ca5ab288f6 | ||
|
|
5fd0f72221 | ||
|
|
5003dc0377 | ||
|
|
0a78d130e5 | ||
|
|
4295aad88e | ||
|
|
9dfd3b1105 | ||
|
|
22e8714040 | ||
|
|
11e7ede8a4 | ||
|
|
27315d35cf | ||
|
|
525c639041 | ||
|
|
42c80fa9e1 | ||
|
|
56e0830700 | ||
|
|
0844b35ebb | ||
|
|
566739e02c | ||
|
|
38b56a7877 | ||
|
|
0596503db5 | ||
|
|
3668b02b94 | ||
|
|
c0159ca0a1 | ||
|
|
159ed53103 | ||
|
|
723e676b75 | ||
|
|
661114370f | ||
|
|
a1d7b9ad5a | ||
|
|
5548b0f4e9 | ||
|
|
295cc59e1e | ||
|
|
6a7e4ebd5e | ||
|
|
9e8146192c | ||
|
|
6171d747db | ||
|
|
84609c0373 | ||
|
|
28d5e7f939 | ||
|
|
4128380a3d | ||
|
|
cf57d3fd8f | ||
|
|
da8a46cfe8 | ||
|
|
ed50130a6a | ||
|
|
bd2123166f | ||
|
|
d9db931bd0 | ||
|
|
69f2efb591 | ||
|
|
568674fef7 | ||
|
|
3c6b70845c | ||
|
|
35ef72081f | ||
|
|
59c42b2086 | ||
|
|
3b8164f1c0 | ||
|
|
8877f893e5 | ||
|
|
043ae17fbf | ||
|
|
944f086ec7 | ||
|
|
dd93cfd613 | ||
|
|
64cc292d7e | ||
|
|
7e889adf71 | ||
|
|
7e9ef899c1 | ||
|
|
03e729d103 | ||
|
|
eab335b755 | ||
|
|
f42b58f789 | ||
|
|
5737752744 | ||
|
|
f79199777d | ||
|
|
b9d0884335 | ||
|
|
6a6d5747a3 | ||
|
|
b19c4a2593 | ||
|
|
a934e2a69f | ||
|
|
af346f6066 | ||
|
|
7b0cfceb68 | ||
|
|
26021865c1 | ||
|
|
7440b8d009 | ||
|
|
0cb67e856f | ||
|
|
038a0a25ce | ||
|
|
1b27ce319a | ||
|
|
7563569c8a | ||
|
|
efff54157b | ||
|
|
2000ec3f48 | ||
|
|
7c800705bf | ||
|
|
19511012f8 | ||
|
|
0e8ad3a8e1 | ||
|
|
b43e405947 | ||
|
|
d5269c8662 | ||
|
|
aa5bf7d5ef | ||
|
|
510de183b1 | ||
|
|
db5e7c80cf | ||
|
|
38be3ba7f0 | ||
|
|
a19638d112 | ||
|
|
1cbddeb104 | ||
|
|
301aeda5f3 | ||
|
|
853ace3828 | ||
|
|
8ccc6762d4 | ||
|
|
6d01007ea6 | ||
|
|
02463ba55d | ||
|
|
85af10ebad | ||
|
|
0778f8f0ae | ||
|
|
6afc1160b6 | ||
|
|
c32edcfc6f | ||
|
|
740359ffd9 | ||
|
|
a309deb479 | ||
|
|
0fd722e829 | ||
|
|
2e6cc71f7a | ||
|
|
84403aec0c | ||
|
|
b28b1b9f24 | ||
|
|
810c7fbac3 | ||
|
|
304044da40 | ||
|
|
419d92e810 | ||
|
|
23112b111c | ||
|
|
b547308e05 | ||
|
|
3c3c5c6e03 | ||
|
|
1601d5a335 | ||
|
|
96b3d60a4a | ||
|
|
3dfbad6f03 | ||
|
|
d5c5415756 | ||
|
|
6dfd2401c9 | ||
|
|
31923f70e7 | ||
|
|
8cd4f199f1 | ||
|
|
1b9b298827 | ||
|
|
bce7b3a551 | ||
|
|
17d3d3e63a | ||
|
|
5c961c446f | ||
|
|
b77582f6a6 | ||
|
|
b3865d240f | ||
|
|
a81b94d4ab | ||
|
|
67d1a400e8 | ||
|
|
1c201d59c9 | ||
|
|
663e8143d4 | ||
|
|
8ce4935132 | ||
|
|
d1f8ab86d1 | ||
|
|
3020cd2312 | ||
|
|
b72213261a | ||
|
|
7e5c98920e | ||
|
|
67f5236b01 | ||
|
|
e9876858a8 | ||
|
|
56a22847f5 | ||
|
|
1271f797e9 | ||
|
|
4f952ce771 | ||
|
|
fec6d76fb3 | ||
|
|
da7355dce0 | ||
|
|
400b2f9696 | ||
|
|
160b5ad65a | ||
|
|
ef44c502db | ||
|
|
0651b63926 | ||
|
|
0c521ffa20 | ||
|
|
01d68bda88 | ||
|
|
89e0dde9e0 | ||
|
|
5ebc89d89d | ||
|
|
32fa76fccb | ||
|
|
2e96d2f67d | ||
|
|
932efb5186 | ||
|
|
6ba61a8b4b | ||
|
|
8368697744 | ||
|
|
966fed1829 | ||
|
|
67c834ac65 | ||
|
|
c00dd04494 | ||
|
|
abf5859415 | ||
|
|
fe8d6a25c0 | ||
|
|
738415710c | ||
|
|
4c7e438ea3 | ||
|
|
fd0fa75cc2 | ||
|
|
50c08818d6 | ||
|
|
1712670610 | ||
|
|
6b0164c2ba | ||
|
|
0966599c8a | ||
|
|
171f8a03f6 | ||
|
|
cb48c882a0 | ||
|
|
3cbd98b14f | ||
|
|
9fc0d675cd | ||
|
|
1b0e3841e4 | ||
|
|
76443ec06d |
@@ -1,22 +0,0 @@
|
||||
# anthropic-consumer's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/anthropic-consumer
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc apply/index.ts usage/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/anthropic-consumer/dist /app/modules/anthropic-consumer/dist
|
||||
# No serve-time entrypoints: every container of this module names its command (`run` on a
|
||||
# schedule), so nothing here serves — deliberately no MESH_TOOL_MODULES.
|
||||
@@ -14,19 +14,10 @@
|
||||
"secrets": {
|
||||
"model-access": "${dir:state}/access-token"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"emits": [
|
||||
"usage.session"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -46,66 +37,39 @@
|
||||
},
|
||||
{
|
||||
"id": "apply",
|
||||
"type": "container",
|
||||
"name": "mesh-anthropic-consumer-apply",
|
||||
"network": "host",
|
||||
"type": "process",
|
||||
"name": "anthropic-consumer-apply",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"apply/index.js"
|
||||
],
|
||||
"schedule": "*/5 * * * *",
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/anthropic-consumer/dist/apply/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:state}:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "/run/state/access-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "/run/state/model.json",
|
||||
"MESH_CLAUDE_CREDENTIALS_FILE": "/run/state/claude/.credentials.json",
|
||||
"MESH_CLAUDE_IDENTITY_FILE": "/run/state/claude/.claude.json"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
},
|
||||
{
|
||||
"id": "usage",
|
||||
"type": "container",
|
||||
"name": "mesh-anthropic-consumer-usage",
|
||||
"network": "host",
|
||||
"schedule": "*/5 * * * *",
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/anthropic-consumer/dist/usage/index.js"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:state}:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_CLAUDE_PROJECTS_DIR": "/run/state/claude/projects",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "/run/state/out/session-usage.json",
|
||||
"MESH_TOOLS_MAIN": "/app/dist/main.js"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
"MESH_MODEL_ACCESS_SECRET_FILE": "${dir:state}/access-token",
|
||||
"MESH_MODEL_ACCESS_BIND_FILE": "${dir:state}/model.json",
|
||||
"MESH_CLAUDE_CREDENTIALS_FILE": "${dir:state}/claude/.credentials.json",
|
||||
"MESH_CLAUDE_IDENTITY_FILE": "${dir:state}/claude/.claude.json"
|
||||
}
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"apply/index.js",
|
||||
"usage/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"usage/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLAUDE_PROJECTS_DIR": "${dir:state}/claude/projects",
|
||||
"MESH_ANTHROPIC_USAGE_OUT": "${dir:state}/out/session-usage.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@
|
||||
// per session. The consumer IS the (node,module) session's fixed binding, so no per-message account
|
||||
// attribution is done — just the totals (port map "don't-map" #3).
|
||||
//
|
||||
// Runs as `mesh-tools run` (no broker), so events are emitted best-effort via the sibling mesh-tools
|
||||
// `emit` primitive; the totals are also written to a file so the reading is observable without one.
|
||||
// Runs in the node's runtime (novox/hq ADR 0198), every five minutes, so events are emitted through
|
||||
// the runtime as this module; the totals are also written to a file so the reading is observable
|
||||
// without one.
|
||||
|
||||
import { readdirSync, statSync, readFileSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
|
||||
import { readSessionFile, type SessionUsage } from "../transcript.js";
|
||||
|
||||
/** The vendor-neutral usage row ADR 0054 fixes — the shape the model-usage store upserts. Kept local
|
||||
@@ -116,22 +119,20 @@ function atomicWrite(path: string, content: string): void {
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
|
||||
/** Emit best-effort via the sibling mesh-tools `emit`, which wires a broker a run step has none. */
|
||||
/** Emit best-effort through the runtime: a reading that could not be announced is still in the file. */
|
||||
async function emitUsage(body: Record<string, unknown>): Promise<void> {
|
||||
const main = process.env.MESH_TOOLS_MAIN ?? "/app/dist/main.js";
|
||||
const { spawn } = await import("node:child_process");
|
||||
await new Promise<void>((resolve) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[main, "emit", "usage.session", JSON.stringify(body)],
|
||||
{ stdio: "inherit" },
|
||||
);
|
||||
child.on("exit", () => resolve());
|
||||
child.on("error", (err) => {
|
||||
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
try {
|
||||
await emit("usage.session", body);
|
||||
} catch (err) {
|
||||
console.error(`[anthropic-consumer] could not emit usage: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
await main();
|
||||
// The cadence the scheduled container had: once at start, then every five minutes. Not awaited, so the
|
||||
// runtime's handshake is answered while a long first reading is still under way.
|
||||
const EVERY_MS = 5 * 60 * 1000;
|
||||
const tick = (): void => {
|
||||
void main().catch((err) => console.error(`[anthropic-consumer] usage reading failed: ${err}`));
|
||||
};
|
||||
tick();
|
||||
setInterval(tick, EVERY_MS);
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
# audit-logger's runtime: the shared runtime image, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The toolkit is in the base image, so
|
||||
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
|
||||
# repository and a path (novox/hq ADR 0069) rather than only on a workstation that happens to have
|
||||
# the siblings laid out beside it.
|
||||
|
||||
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
|
||||
# They are different images on purpose — the first carries a compiler and the second must not, or
|
||||
# every running container would carry one it never invokes. The mesh answers both with the copies it
|
||||
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
|
||||
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
|
||||
# nobody told stops here and says which module to build first.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the toolkit it will run against.
|
||||
WORKDIR /app/modules/audit-logger
|
||||
COPY . .
|
||||
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
|
||||
# symlinks to a launcher that requires its library relatively — resolved away when the base image
|
||||
# was assembled.
|
||||
RUN node /app/node_modules/typescript/bin/tsc audit.ts index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/audit-logger/dist /app/modules/audit-logger/dist
|
||||
# **Served, not run.** This subscribes on import, and the serve mode binds the broker before it
|
||||
# imports anything — `run` exists for a step that works offline and exits, and would leave this
|
||||
# with nothing to subscribe to.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/audit-logger/dist/index.js
|
||||
@@ -5,27 +5,21 @@
|
||||
"consumes": [
|
||||
"**"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:state}/broker"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js"
|
||||
],
|
||||
"env": {
|
||||
"AUDIT_LOG": "${dir:trail}/audit.log"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -40,21 +34,6 @@
|
||||
"id": "trail",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "run",
|
||||
"type": "container",
|
||||
"name": "mesh-audit-logger",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:trail}:/trail"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"AUDIT_LOG": "/trail/audit.log"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
|
||||
@@ -15,7 +15,7 @@ test("audit-logger records every event to the trail as one line each", async ()
|
||||
const path = join(dir, "audit.log");
|
||||
|
||||
// The audit-logger's whole behaviour: consume everything, record it.
|
||||
await on("**", async (event) => record(event, path));
|
||||
await on("#", async (event) => record(event, path)); // the pattern index.ts subscribes
|
||||
|
||||
process.env.MESH_MODULE = "umami";
|
||||
process.env.MESH_NODE = "anchor";
|
||||
@@ -24,7 +24,9 @@ test("audit-logger records every event to the trail as one line each", async ()
|
||||
|
||||
const lines = (await readFile(path, "utf8")).trim().split("\n").map((l) => JSON.parse(l));
|
||||
assert.equal(lines.length, 2);
|
||||
assert.deepEqual(lines.map((l) => l.type), ["umami.site.created", "node.anchor.joined"]);
|
||||
// A module names its events locally (design 29); the module is the `source`, which together with
|
||||
// the type says whose event it was. This broker does no namespacing, so the type is as emitted.
|
||||
assert.deepEqual(lines.map((l) => l.type), ["site.created", "node.anchor.joined"]);
|
||||
assert.equal(lines[0].source, "umami");
|
||||
assert.equal(lines[0].node, "anchor");
|
||||
assert.equal(lines[0].body.domain, "my-app");
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# baserow's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/baserow
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/baserow/dist /app/modules/baserow/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/baserow/dist/tools/index.js
|
||||
+14
-36
@@ -25,8 +25,7 @@
|
||||
"postgres-database": "${dir:state}/database.secret"
|
||||
},
|
||||
"own-secrets": {
|
||||
"admin": "${dir:state}/admin.secret",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"admin": "${dir:state}/admin.secret"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -92,45 +91,24 @@
|
||||
"mode": "0600",
|
||||
"content": "{\n \"password\": \"${secret:admin}\",\n \"host\": \"${bound:route:name}\"\n}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-baserow",
|
||||
"network": "baserow",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BASEROW_URL": "http://baserow:80",
|
||||
"MESH_BASEROW_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BASEROW_URL": "http://127.0.0.1:${port:80}",
|
||||
"MESH_BASEROW_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# bazarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/bazarr
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/bazarr/dist /app/modules/bazarr/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/bazarr/dist/index.js,/app/modules/bazarr/dist/tools/index.js
|
||||
@@ -1,173 +0,0 @@
|
||||
// The Bazarr API client — bazarr's own code, living in the module (novox/hq ADR 0039). Bazarr
|
||||
// manages subtitles for a Sonarr/Radarr library: it tracks which episodes and movies are still
|
||||
// missing subtitles, searches providers for them, and records what it downloaded. This client
|
||||
// talks its /api surface (keyed by an X-API-KEY header); bazarr's tools and events import it.
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
export interface WantedSubtitle {
|
||||
kind: "episode" | "movie";
|
||||
title: string; // series + episode, or movie title
|
||||
path?: string;
|
||||
seriesId?: number; // sonarr series id (episodes)
|
||||
episodeId?: number; // sonarr episode id (episodes)
|
||||
radarrId?: number; // radarr movie id (movies)
|
||||
missing: string[]; // language names still missing
|
||||
}
|
||||
|
||||
export interface ProviderSubtitle {
|
||||
provider: string;
|
||||
language: string;
|
||||
hearingImpaired: boolean;
|
||||
forced: boolean;
|
||||
score?: number;
|
||||
release?: string;
|
||||
subtitle: string; // the opaque token Bazarr uses to download this exact result
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
kind: "episode" | "movie";
|
||||
id: string; // stable dedup key across polls
|
||||
title: string;
|
||||
language?: string;
|
||||
provider?: string;
|
||||
path?: string;
|
||||
timestamp?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** The settings-merged config the mesh delivers (novox/hq ADR 0046): { url, apiKey, token, password, user, ... }. */
|
||||
function meshConfig(file?: string): Record<string, string> {
|
||||
if (!file) return {};
|
||||
try { return JSON.parse(readFileSync(file, "utf8")) as Record<string, string>; }
|
||||
catch { return {}; }
|
||||
}
|
||||
|
||||
/** Read a secret the mesh mounted at a file path (an own-secret delivered by `secret accept`);
|
||||
* absent or unreadable yields undefined so callers fall back rather than crash. */
|
||||
function readSecret(file?: string): string | undefined {
|
||||
if (!file) return undefined;
|
||||
try { return readFileSync(file, "utf8").trim(); }
|
||||
catch { return undefined; }
|
||||
}
|
||||
|
||||
export class BazarrClient {
|
||||
readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
private readonly apiKey: string,
|
||||
) {
|
||||
this.baseUrl = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/** Build from the module's resolved environment. Bazarr's API is keyed; without URL and key
|
||||
* there is nothing to talk to, so this throws rather than run half-configured. */
|
||||
static fromEnv(env: NodeJS.ProcessEnv = process.env): BazarrClient {
|
||||
const cfg = meshConfig(env.MESH_BAZARR_CONFIG_FILE);
|
||||
const url = cfg.url ?? env.MESH_BAZARR_URL;
|
||||
const apiKey = cfg.apiKey ?? readSecret(env.MESH_BAZARR_API_KEY_FILE) ?? env.MESH_BAZARR_API_KEY;
|
||||
if (!url) throw new Error("no Bazarr URL — set MESH_BAZARR_URL");
|
||||
if (!apiKey) throw new Error("no Bazarr API key — set MESH_BAZARR_API_KEY");
|
||||
return new BazarrClient(url, apiKey);
|
||||
}
|
||||
|
||||
private async request(method: string, path: string, params: Record<string, string> = {}): Promise<any> {
|
||||
const url = new URL(`${this.baseUrl}/api${path}`);
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
const res = await fetch(url.toString(), { method, headers: { "X-API-KEY": this.apiKey, Accept: "application/json" } });
|
||||
if (!res.ok) throw new Error(`Bazarr API ${method} ${path}: ${res.status} ${await res.text()}`);
|
||||
// Downloads/patches return an empty body; only GETs carry JSON.
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : {};
|
||||
}
|
||||
|
||||
private get(path: string, params?: Record<string, string>): Promise<any> {
|
||||
return this.request("GET", path, params);
|
||||
}
|
||||
|
||||
private languageNames(missing: any[]): string[] {
|
||||
return (missing ?? []).map((m: any) => m?.name ?? m?.code2 ?? m?.code3).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Episodes and movies still missing subtitles — Bazarr's core "what's left to do" list. */
|
||||
async getWanted(limit = 50): Promise<WantedSubtitle[]> {
|
||||
const [eps, movies] = await Promise.all([
|
||||
this.get("/episodes/wanted", { start: "0", length: String(limit) }),
|
||||
this.get("/movies/wanted", { start: "0", length: String(limit) }),
|
||||
]);
|
||||
const episodes: WantedSubtitle[] = (eps?.data ?? []).map((e: any) => ({
|
||||
kind: "episode" as const,
|
||||
title: `${e.seriesTitle ?? e.series ?? "Unknown"} — ${e.episodeTitle ?? e.episode_title ?? ""}`.trim(),
|
||||
path: e.path,
|
||||
seriesId: e.sonarrSeriesId,
|
||||
episodeId: e.sonarrEpisodeId,
|
||||
missing: this.languageNames(e.missing_subtitles),
|
||||
}));
|
||||
const films: WantedSubtitle[] = (movies?.data ?? []).map((m: any) => ({
|
||||
kind: "movie" as const,
|
||||
title: m.title ?? "Unknown",
|
||||
path: m.path,
|
||||
radarrId: m.radarrId,
|
||||
missing: this.languageNames(m.missing_subtitles),
|
||||
}));
|
||||
return [...episodes, ...films];
|
||||
}
|
||||
|
||||
/** Ask providers what subtitles are available for one wanted episode — a manual search. */
|
||||
async searchEpisode(episodeId: number): Promise<ProviderSubtitle[]> {
|
||||
const raw = await this.get("/providers/episodes", { episodeid: String(episodeId) });
|
||||
return this.mapProviderResults(raw);
|
||||
}
|
||||
|
||||
/** Ask providers what subtitles are available for one movie — a manual search. */
|
||||
async searchMovie(radarrId: number): Promise<ProviderSubtitle[]> {
|
||||
const raw = await this.get("/providers/movies", { radarrid: String(radarrId) });
|
||||
return this.mapProviderResults(raw);
|
||||
}
|
||||
|
||||
private mapProviderResults(raw: any): ProviderSubtitle[] {
|
||||
const list = Array.isArray(raw) ? raw : (raw?.data ?? []);
|
||||
return list.map((r: any) => ({
|
||||
provider: r.provider,
|
||||
language: r.language?.name ?? r.language ?? "unknown",
|
||||
hearingImpaired: Boolean(r.hearing_impaired ?? r.hi),
|
||||
forced: Boolean(r.forced),
|
||||
score: r.score,
|
||||
release: r.release_info?.[0] ?? r.release_info,
|
||||
subtitle: r.subtitle,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Recent subtitle-download history, episodes and movies together, newest first. Each entry
|
||||
* carries a stable id so the events poller can tell a fresh download from one already seen. */
|
||||
async getHistory(limit = 40): Promise<HistoryEntry[]> {
|
||||
const [eps, movies] = await Promise.all([
|
||||
this.get("/episodes/history", { start: "0", length: String(limit) }),
|
||||
this.get("/movies/history", { start: "0", length: String(limit) }),
|
||||
]);
|
||||
const key = (kind: string, r: any): string =>
|
||||
`${kind}:${r.timestamp ?? r.parsed_timestamp ?? ""}:${r.subtitles_path ?? r.path ?? ""}:${r.language?.code3 ?? r.language ?? ""}`;
|
||||
const episodes: HistoryEntry[] = (eps?.data ?? []).map((r: any) => ({
|
||||
kind: "episode" as const,
|
||||
id: key("episode", r),
|
||||
title: `${r.seriesTitle ?? "Unknown"} — ${r.episodeTitle ?? ""}`.trim(),
|
||||
language: r.language?.name ?? r.language,
|
||||
provider: r.provider,
|
||||
path: r.subtitles_path,
|
||||
timestamp: r.timestamp,
|
||||
description: r.description,
|
||||
}));
|
||||
const films: HistoryEntry[] = (movies?.data ?? []).map((r: any) => ({
|
||||
kind: "movie" as const,
|
||||
id: key("movie", r),
|
||||
title: r.title ?? "Unknown",
|
||||
language: r.language?.name ?? r.language,
|
||||
provider: r.provider,
|
||||
path: r.subtitles_path,
|
||||
timestamp: r.timestamp,
|
||||
description: r.description,
|
||||
}));
|
||||
return [...episodes, ...films];
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
// bazarr's events. The tool runtime imports this once the broker is bound. Bazarr's one genuinely
|
||||
// observable thing is a subtitle arriving: it works away in the background, searching providers for
|
||||
// the missing-subtitle list, and when it succeeds a subtitle appears in its history. That is worth
|
||||
// announcing to the mesh.
|
||||
//
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.bazarr.subtitle.downloaded — a subtitle was fetched for an episode or movie
|
||||
//
|
||||
// Bazarr has nothing on the mesh it usefully reacts to (a download completing is Sonarr/Radarr's
|
||||
// business, and they trigger Bazarr directly), so it consumes nothing — a pure emitter.
|
||||
//
|
||||
// The event is observation-based: poll history and diff. Primed silently on the first look, or a
|
||||
// restart would re-announce the whole recent history as freshly downloaded.
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { BazarrClient } from "./client.js";
|
||||
|
||||
const bazarr = BazarrClient.fromEnv();
|
||||
|
||||
const seen = new Set<string>();
|
||||
let primed = false;
|
||||
async function pollHistory(): Promise<void> {
|
||||
const entries = await bazarr.getHistory(40);
|
||||
for (const entry of entries) {
|
||||
if (seen.has(entry.id)) continue;
|
||||
if (primed) {
|
||||
await emit("subtitle.downloaded", {
|
||||
kind: entry.kind,
|
||||
title: entry.title,
|
||||
language: entry.language,
|
||||
provider: entry.provider,
|
||||
path: entry.path,
|
||||
});
|
||||
}
|
||||
seen.add(entry.id);
|
||||
}
|
||||
primed = true;
|
||||
}
|
||||
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const run = (): void => void fn().catch((err) => console.error(`[bazarr] ${err}`));
|
||||
setInterval(run, everyMs);
|
||||
run();
|
||||
};
|
||||
tick(pollHistory, 60_000);
|
||||
|
||||
console.log("[bazarr] watching subtitle-download history");
|
||||
@@ -1,145 +0,0 @@
|
||||
{
|
||||
"module": "bazarr",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"emits": [
|
||||
"subtitle.downloaded"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker",
|
||||
"api-key": "${dir:mesh-state}/api-key"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "web",
|
||||
"port": 6767,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "managing subtitles"
|
||||
}
|
||||
],
|
||||
"accesses": [
|
||||
{
|
||||
"id": "movies",
|
||||
"path": "/services/media/movies",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"id": "series",
|
||||
"path": "/services/media/series",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"id": "anime",
|
||||
"path": "/services/media/anime",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"id": "downloads",
|
||||
"path": "/services/media/downloads",
|
||||
"mode": "read"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"path": "/services/bazarr/config",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "bazarr",
|
||||
"image": "lscr.io/linuxserver/bazarr@sha256:3a820372f19fcb2981ea19fe4b5382934d67414afaba974bce831ddda0a64a02",
|
||||
"env": {
|
||||
"PUID": "1000",
|
||||
"PGID": "1000",
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"ports": [
|
||||
"6767"
|
||||
],
|
||||
"volumes": [
|
||||
"/services/bazarr/config:/config",
|
||||
"${access:movies}:/movies",
|
||||
"${access:series}:/series",
|
||||
"${access:anime}:/anime",
|
||||
"${access:downloads}:/downloads"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/config.json",
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-bazarr",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/api-key:/run/secrets/api-key:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro",
|
||||
"/services/bazarr/config:/var/lib/bazarr/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BAZARR_URL": "http://127.0.0.1:6767",
|
||||
"MESH_BAZARR_API_KEY_FILE": "/run/secrets/api-key",
|
||||
"MESH_BAZARR_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BAZARR_CONFIG_DIR": "/var/lib/bazarr/config"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "subs",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:mesh-state}/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-bazarr",
|
||||
"version": "0.1.0",
|
||||
"description": "bazarr — subtitle management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
// bazarr's tools — its own code (novox/hq ADR 0039), importing bazarr's client. They return
|
||||
// structured data; the mesh serves them through the sdk's tool harness.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { BazarrClient } from "../client.js";
|
||||
|
||||
export function getBazarrTools(bazarr: BazarrClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "bazarr_wanted",
|
||||
description: "Episodes and movies still missing subtitles, with the languages each still needs.",
|
||||
input: { limit: { type: "number", description: "max items per kind (default 50)" } },
|
||||
run: async (args) => {
|
||||
const wanted = await bazarr.getWanted(args.limit ? Number(args.limit) : 50);
|
||||
return { count: wanted.length, wanted };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bazarr_search_subtitles",
|
||||
description: "Manually search subtitle providers for one wanted item — pass an episodeId or a radarrId.",
|
||||
input: {
|
||||
episodeId: { type: "number", description: "a Sonarr episode id (from bazarr_wanted)" },
|
||||
radarrId: { type: "number", description: "a Radarr movie id (from bazarr_wanted)" },
|
||||
},
|
||||
run: async (args) => {
|
||||
if (args.episodeId !== undefined) {
|
||||
const results = await bazarr.searchEpisode(Number(args.episodeId));
|
||||
return { kind: "episode", episodeId: Number(args.episodeId), count: results.length, results };
|
||||
}
|
||||
if (args.radarrId !== undefined) {
|
||||
const results = await bazarr.searchMovie(Number(args.radarrId));
|
||||
return { kind: "movie", radarrId: Number(args.radarrId), count: results.length, results };
|
||||
}
|
||||
throw new Error("pass either episodeId or radarrId");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bazarr_history",
|
||||
description: "Recent subtitle-download history — what was downloaded, for which title, from which provider.",
|
||||
input: { limit: { type: "number", description: "max entries per kind (default 40)" } },
|
||||
run: async (args) => {
|
||||
const history = await bazarr.getHistory(args.limit ? Number(args.limit) : 40);
|
||||
return { count: history.length, history };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// Exposed only when Bazarr is configured; otherwise bazarr contributes no tools rather than
|
||||
// failing the whole runtime.
|
||||
registerModuleTools("bazarr", (env) => {
|
||||
try {
|
||||
return getBazarrTools(BazarrClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
# bookshelf's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/bookshelf
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/bookshelf/dist /app/modules/bookshelf/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/bookshelf/dist/index.js,/app/modules/bookshelf/dist/tools/index.js
|
||||
@@ -1,136 +0,0 @@
|
||||
// The Bookshelf API client — bookshelf's own code, living in the module (novox/hq ADR 0039).
|
||||
// Ported from the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own
|
||||
// copy, so a change to Bookshelf's API rebuilds only bookshelf and nothing else. Both this module's
|
||||
// tools and its events entrypoint import it, and nothing outside bookshelf does.
|
||||
//
|
||||
// Bookshelf is a Readarr fork (ghcr.io/pennydreadful/bookshelf). It speaks the Servarr v1 API; its
|
||||
// content is "book". Unlike Sonarr/Radarr it exposes no calendar endpoint, so there is no calendar
|
||||
// tool here — matching hal, which excluded bookshelf from its calendar-capable apps.
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Bookshelf speaks the v1 API; its content is "book".
|
||||
const API_VERSION = "v1";
|
||||
const CONTENT_ENDPOINT = "book";
|
||||
const APP_NAME = "Bookshelf";
|
||||
|
||||
export interface BookshelfQueueItem {
|
||||
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||
id: number;
|
||||
title: string;
|
||||
status: string;
|
||||
size: string;
|
||||
sizeleft: string;
|
||||
timeleft?: string;
|
||||
}
|
||||
|
||||
export interface BookshelfContentItem {
|
||||
title: string;
|
||||
author?: string;
|
||||
year?: number;
|
||||
status?: string;
|
||||
monitored: boolean;
|
||||
}
|
||||
|
||||
export class BookshelfClient {
|
||||
readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
private readonly apiKey: string,
|
||||
) {
|
||||
this.baseUrl = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||
* runtime shares its network), and the API key is read from MESH_BOOKSHELF_API_KEY or, failing
|
||||
* that, discovered from the server's own config.xml under MESH_BOOKSHELF_CONFIG_DIR — the same
|
||||
* file Bookshelf writes it to, so a running server needs nothing configured by hand. Throws when
|
||||
* no key can be found, so the tools/events simply do not load (the harness treats the throw as
|
||||
* "exposes nothing").
|
||||
*/
|
||||
static fromEnv(env: NodeJS.ProcessEnv = process.env): BookshelfClient {
|
||||
const url = env.MESH_BOOKSHELF_URL ?? `http://127.0.0.1:${env.MESH_BOOKSHELF_PORT ?? "8787"}`;
|
||||
const configDir = env.MESH_BOOKSHELF_CONFIG_DIR ?? "/config";
|
||||
const apiKey = env.MESH_BOOKSHELF_API_KEY ?? BookshelfClient.detectApiKey(configDir);
|
||||
if (!apiKey) {
|
||||
throw new Error("Bookshelf not configured — set MESH_BOOKSHELF_API_KEY or make the config dir readable");
|
||||
}
|
||||
return new BookshelfClient(url, apiKey);
|
||||
}
|
||||
|
||||
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||
static detectApiKey(configDir: string): string | null {
|
||||
const config = join(configDir, "config.xml");
|
||||
if (existsSync(config)) {
|
||||
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||
if (params) {
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
}
|
||||
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||
}
|
||||
|
||||
async getContent(limit?: number): Promise<BookshelfContentItem[]> {
|
||||
const data = await this.get(CONTENT_ENDPOINT);
|
||||
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||
const mapped = items.map((item) => ({
|
||||
title: item.title ?? "Unknown",
|
||||
author: item.author?.authorName ?? item.authorName,
|
||||
year: item.releaseDate ? new Date(item.releaseDate).getFullYear() : item.year,
|
||||
status: item.status,
|
||||
monitored: item.monitored ?? true,
|
||||
}));
|
||||
return limit ? mapped.slice(0, limit) : mapped;
|
||||
}
|
||||
|
||||
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||
async searchContent(term: string): Promise<BookshelfContentItem[]> {
|
||||
const all = await this.getContent();
|
||||
const lower = term.toLowerCase();
|
||||
return all.filter(
|
||||
(item) =>
|
||||
item.title.toLowerCase().includes(lower) ||
|
||||
(item.author?.toLowerCase().includes(lower) ?? false),
|
||||
);
|
||||
}
|
||||
|
||||
async getQueue(): Promise<{ totalRecords: number; items: BookshelfQueueItem[] }> {
|
||||
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||
const records = data.records ?? [];
|
||||
return {
|
||||
totalRecords: data.totalRecords ?? records.length,
|
||||
items: records.map((r) => ({
|
||||
id: r.id,
|
||||
title: r.title ?? r.book?.title ?? r.author?.authorName ?? "Unknown",
|
||||
status: r.status ?? "unknown",
|
||||
size: formatBytes(r.size ?? 0),
|
||||
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||
timeleft: r.timeleft,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
// bookshelf's events. The tool runtime imports this once the broker is bound. It watches the
|
||||
// download queue and turns its comings and goings into mesh events — the same mechanism radarr uses,
|
||||
// applied to a Servarr book manager.
|
||||
//
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.bookshelf.book.grabbed — a release entered the queue (Bookshelf grabbed it)
|
||||
// module.bookshelf.download.completed — a release left the queue, imported. This routing key is
|
||||
// what the plex module consumes (module.*.download.completed)
|
||||
// to rescan, so a new audiobook becomes a visible item.
|
||||
// Consumes: none.
|
||||
//
|
||||
// NOTE: the hal bookshelf module emitted no events (its hooks only did install-time provisioning).
|
||||
// This queue watcher is new in nox, modelled exactly on radarr's — bookshelf is a Servarr app with
|
||||
// the same queue semantics, so the diff-and-emit pattern carries over unchanged.
|
||||
//
|
||||
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { BookshelfClient, type BookshelfQueueItem } from "./client.js";
|
||||
|
||||
// Building the client throws when Bookshelf has no URL/key yet. Like the tools (see tools/index.ts),
|
||||
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||
function buildClient(): BookshelfClient | null {
|
||||
try {
|
||||
return BookshelfClient.fromEnv();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const bookshelf = buildClient();
|
||||
|
||||
// Bookshelf removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||
|
||||
const inQueue = new Map<number, BookshelfQueueItem>();
|
||||
let primed = false;
|
||||
|
||||
async function pollQueue(bookshelf: BookshelfClient): Promise<void> {
|
||||
const { items } = await bookshelf.getQueue();
|
||||
const now = new Map(items.map((i) => [i.id, i]));
|
||||
|
||||
if (primed) {
|
||||
// Entered the queue since last look — Bookshelf grabbed a release.
|
||||
for (const [id, item] of now) {
|
||||
if (!inQueue.has(id)) await emit("book.grabbed", { title: item.title, status: item.status });
|
||||
}
|
||||
// Left the queue — imported and done, unless it was last seen failing.
|
||||
for (const [id, item] of inQueue) {
|
||||
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||
await emit("download.completed", { title: item.title });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inQueue.clear();
|
||||
for (const [id, item] of now) inQueue.set(id, item);
|
||||
primed = true;
|
||||
}
|
||||
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const run = (): void => void fn().catch((err) => console.error(`[bookshelf] ${err}`));
|
||||
setInterval(run, everyMs);
|
||||
run();
|
||||
};
|
||||
|
||||
if (bookshelf) {
|
||||
tick(() => pollQueue(bookshelf), 30_000);
|
||||
console.log("[bookshelf] watching the download queue, emitting grabs and completions");
|
||||
} else {
|
||||
console.log("[bookshelf] not configured — events idle until an API key is available");
|
||||
}
|
||||
@@ -1,120 +0,0 @@
|
||||
{
|
||||
"module": "bookshelf",
|
||||
"version": "1",
|
||||
"slug": "books",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"emits": [
|
||||
"book.grabbed",
|
||||
"download.completed"
|
||||
],
|
||||
"consumes": [],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "web",
|
||||
"port": 8787,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "managing the ebook/audiobook library"
|
||||
}
|
||||
],
|
||||
"accesses": [
|
||||
{
|
||||
"id": "books",
|
||||
"path": "/services/media/books",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"id": "downloads",
|
||||
"path": "/services/media/downloads",
|
||||
"mode": "read-write"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"path": "/services/bookshelf/config",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "bookshelf",
|
||||
"image": "ghcr.io/pennydreadful/bookshelf@sha256:388eecc94362580eae31ee0a454be6af516f8a311f8432a521c202fb475f4359",
|
||||
"env": {
|
||||
"PUID": "1000",
|
||||
"PGID": "1000",
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"ports": [
|
||||
"8787"
|
||||
],
|
||||
"volumes": [
|
||||
"/services/bookshelf/config:/config",
|
||||
"${access:books}:/books",
|
||||
"${access:downloads}:/downloads"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-bookshelf",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"/services/bookshelf/config:/var/lib/bookshelf/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_BOOKSHELF_URL": "http://127.0.0.1:8787",
|
||||
"MESH_BOOKSHELF_CONFIG_DIR": "/var/lib/bookshelf/config"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "books",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:mesh-state}/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-bookshelf",
|
||||
"version": "0.1.0",
|
||||
"description": "bookshelf — ebook/audiobook management (Readarr fork). Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
// bookshelf's tools — ported from the shared hal `arr` sdk (novox/hq ADR 0039), importing
|
||||
// bookshelf's own client. They return structured data (not the pre-formatted text hal returned); the
|
||||
// mesh serves them through the sdk's tool harness. Bookshelf has no calendar endpoint, so there is
|
||||
// no calendar tool — matching hal, which excluded it from its calendar-capable apps.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { BookshelfClient } from "../client.js";
|
||||
|
||||
export function getBookshelfTools(bookshelf: BookshelfClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "bookshelf_status",
|
||||
description: "Bookshelf status overview: version, book count, monitored count, queue size.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const [status, content, queue] = await Promise.all([
|
||||
bookshelf.getStatus(),
|
||||
bookshelf.getContent(),
|
||||
bookshelf.getQueue(),
|
||||
]);
|
||||
return {
|
||||
app: status.appName,
|
||||
version: status.version,
|
||||
books: content.length,
|
||||
monitored: content.filter((c) => c.monitored).length,
|
||||
queue: queue.totalRecords,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_library",
|
||||
description: "List books from the Bookshelf library.",
|
||||
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||
run: async (args) => {
|
||||
const items = await bookshelf.getContent(args.limit ? Number(args.limit) : 50);
|
||||
return { count: items.length, books: items };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_search",
|
||||
description:
|
||||
"Search the Bookshelf library for books by title or author (filters existing content, not indexers).",
|
||||
input: { query: { type: "string", description: "the search term" } },
|
||||
run: async (args) => {
|
||||
const query = String(args.query);
|
||||
return { query, results: await bookshelf.searchContent(query) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bookshelf_queue",
|
||||
description: "Show the Bookshelf download queue — what is downloading and how far along.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const queue = await bookshelf.getQueue();
|
||||
return { count: queue.totalRecords, items: queue.items };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// The tools exist only when Bookshelf is configured; without a URL and key, bookshelf contributes
|
||||
// none rather than failing the whole runtime.
|
||||
registerModuleTools("bookshelf", (env) => {
|
||||
try {
|
||||
return getBookshelfTools(BookshelfClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
ARG GO_BASE
|
||||
ARG ALPINE_BASE
|
||||
# builder's own image: the build machine itself, compiled into a container.
|
||||
# build-agent's image: the build machine itself, compiled into a container (novox/hq ADR 0190).
|
||||
#
|
||||
# **The source is not vendored here.** builder's actual code — cmd/mesh-builder, internal/builder,
|
||||
# internal/catalogue — lives in the mesh-controller repository, the same control plane it is one
|
||||
@@ -0,0 +1,15 @@
|
||||
# build-agent
|
||||
|
||||
The mesh's build machine as a role every machine can hold (novox/hq ADR 0190). It holds the node seat
|
||||
`node-build-agent`: every holder pulls one build at a time from the role's one work queue when it is
|
||||
idle, so a tier of many images is built by as many machines as hold the seat and are online, and a
|
||||
machine that is off builds nothing and blocks nothing. The controller asks the role, never a machine;
|
||||
the outcome names the machine that built it.
|
||||
|
||||
What a holding machine needs is what the builder always needed, said here once: a container runtime
|
||||
(the socket is mounted), the artifact store and the package registry as provisions, a workspace, and
|
||||
the bus credential. The code is `cmd/mesh-builder` in the mesh-controller repository, compiled from
|
||||
that repository's main (`build.artifacts[].context`); this module ships the packaging.
|
||||
|
||||
Assign it to every machine with a container runtime. It replaces `builder`, the one-holder form of the
|
||||
same thing; retire that once this is assigned where it was.
|
||||
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"module": "builder",
|
||||
"module": "build-agent",
|
||||
"version": "1",
|
||||
"slug": "agent",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
"name": "mesh-build-machine",
|
||||
"scope": "mesh"
|
||||
"name": "node-build-agent",
|
||||
"scope": "node"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
@@ -36,19 +37,19 @@
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "builder-env",
|
||||
"id": "agent-env",
|
||||
"type": "file",
|
||||
"path": "${dir:mesh-state}/builder.env",
|
||||
"path": "${dir:mesh-state}/build-agent.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_BROKER_FILE=/run/mesh/broker\nMESH_NODE=${machine:name}\nMESH_REGISTRY=${bound:artifact-store:at}:${bound:artifact-store:port}\nMESH_PACKAGE_BINDING=/run/mesh/package-registry.json\nMESH_NPM_TOKEN_FILE=/run/mesh/package-registry.secret\nMESH_WORKSPACE=${dir:workspace}\n"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "mesh-builder",
|
||||
"name": "mesh-build-agent",
|
||||
"artifact": "server",
|
||||
"env-file": [
|
||||
"${dir:mesh-state}/builder.env"
|
||||
"${dir:mesh-state}/build-agent.env"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:mesh-state}:/run/mesh:ro",
|
||||
@@ -56,7 +57,7 @@
|
||||
"/var/run/docker.sock:/var/run/docker.sock"
|
||||
],
|
||||
"restart-on": [
|
||||
"builder-env"
|
||||
"agent-env"
|
||||
],
|
||||
"network": "host"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# claude-code
|
||||
|
||||
The operator's agent on a machine (novox/hq design 36): its package, its machine-wide managed
|
||||
configuration, and the consumer side of the Anthropic licence manager (design 39, ADR 0183).
|
||||
|
||||
## What it owns
|
||||
|
||||
Two directories, declared, so the mesh refuses a second module owning either:
|
||||
|
||||
- `/etc/claude-code`, the agent's machine-wide managed directory, root's, `0755`.
|
||||
- `~/.claude` under the operator account's home, the operator's, `0700`. The module owns the directory —
|
||||
that it exists, who owns it, its mode — and of what is inside only what it writes. Everything else
|
||||
in it (memory, history, projects, local settings, a person's own rules and skills) is the person's
|
||||
and is never read or written (hq ADR 0182). Unassigned, the module leaves the directory: the host
|
||||
removes a directory only when it is empty.
|
||||
|
||||
## What it writes
|
||||
|
||||
Under the agent's managed directory, `/etc/claude-code`, owned whole by this module and rewritten
|
||||
whenever the node's tool runtime collects the module's tools:
|
||||
|
||||
| file | holds |
|
||||
|---|---|
|
||||
| `managed-mcp.json` | the tool servers every session loads: the mesh's console as `mesh`, and the servers set in this module's `mcp_servers` setting. **Exclusive**: a server not listed here does not load — not one added with `claude mcp add`, not a project's `.mcp.json`, not a plugin's |
|
||||
| `managed-settings.json` | the repositories' attribution convention, the claude.ai connectors kept beside the managed servers, and the key-helper while the node holds an API-key licence |
|
||||
| `CLAUDE.md` | how a session on this mesh works, this node's name and role, the conventions |
|
||||
|
||||
Under the operator's home, only `~/.claude/.credentials.json`, and only when the licence manager hands
|
||||
this node a subscription token. Nothing else under the home is read or written.
|
||||
|
||||
## Over NATS
|
||||
|
||||
Everything between this module and the rest of the mesh is NATS, in three kinds: an **event** says that
|
||||
something happened and carries no secret, because a stream keeps it; a **request** carries a token,
|
||||
because nothing keeps it (hq design 32 §10); and **state** is the current value of something every node
|
||||
must see, a node that joins later included — kept, so it carries no secret either (hq ADR 0201).
|
||||
|
||||
| what | how |
|
||||
|---|---|
|
||||
| the licence manager rotated a licence, or switched this node | its `licence.rotated` / `licence.switched` event; this module then asks `anthropic-licence-manager.current` for its token, sealed to the key it sends |
|
||||
| this node starts | it asks `current` once, so a node that was off catches up |
|
||||
| a person ran `/login` here | the credentials file gains a refresh token this module never writes; it asks `anthropic-licence-manager.adopt` at once with the grant sealed to the manager's key — the one time a refresh token travels, because the login made the manager's stale |
|
||||
| an MCP server registered through this module | a key in the module's `servers` state — `all.<server>` for every node, `<node>.<server>` for one; every node watches it and renders what applies to it, a node's own entry over the one for every node. A node that joins later, or was off, reads the whole current set at start; unregistering is a delete. An entry with a secret in its `env` or `headers` is refused by the runtime |
|
||||
|
||||
## Tools
|
||||
|
||||
`claude_code_status`, `claude_code_render`, `claude_code_pull`, `claude_code_mcp_list`,
|
||||
`claude_code_mcp_register` (this node by default; `nodes: "all"` or a list for more — called for this
|
||||
node alone, its answer names the other nodes running claude-code), `claude_code_mcp_unregister`.
|
||||
|
||||
## Settings
|
||||
|
||||
Per node or for the whole mesh, through `mesh-controller.settings module=claude-code`:
|
||||
|
||||
- `role` — what this node is, in a few words; shown to every session.
|
||||
- `mcp_servers` — extra tool servers, set by the operator for the mesh or a node, beside the ones
|
||||
registered through the tools; keyed by name, in the vendor's `.mcp.json` entry shape
|
||||
(`{"type":"http","url":…}` or `{"type":"stdio","command":…,"args":[…]}`). The name `mesh` is the
|
||||
module's own and cannot be set. Put a person's own servers here, or they stop loading.
|
||||
|
||||
## On a machine that carried the predecessor
|
||||
|
||||
Remove these by hand, once; the mesh removes nothing it did not make (ADR 0182):
|
||||
|
||||
- `~/.claude/CLAUDE.md`
|
||||
- `~/.claude/rules/00-hal-mesh.md`, `~/.claude/rules/conventions.md`
|
||||
- `~/.claude/skills/cleanup/`, `~/.claude/skills/hal-switch-license/`
|
||||
- the hand-made console entry in `~/.claude.json` under `mcpServers` — it is ignored now anyway
|
||||
|
||||
## Escalation
|
||||
|
||||
Writing `/etc/claude-code` needs root. The runtime runs as the operator account, and the module uses
|
||||
that account's passwordless `sudo`; on a machine without it, `claude_code_render` says so and nothing
|
||||
is written.
|
||||
@@ -0,0 +1,112 @@
|
||||
// The agent's credentials file, and whether an offered grant may replace what it holds (novox/hq
|
||||
// ADR 0183, design 36 §5). Pure where it decides, so the rules are tested without a file.
|
||||
//
|
||||
// The file is the vendor's: `{ claudeAiOauth: { accessToken, expiresAt, refreshTokenExpiresAt?,
|
||||
// scopes?, subscriptionType?, rateLimitTier? }, ... }`. A node never holds a refresh token, so the
|
||||
// one this module writes never carries one, and a full grant a login left behind is stripped the
|
||||
// moment the manager hands the node its own.
|
||||
//
|
||||
// The lineage rule is the predecessor's, with the incidents that earned it: a rotation of the same
|
||||
// licence is applied only if newer; a grant re-issued by a login is adopted whatever its expiry; a
|
||||
// switch to another licence is applied regardless, because across licences the expiries are
|
||||
// unrelated numbers.
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
export interface Grant {
|
||||
readonly accessToken: string;
|
||||
readonly expiresAt: number;
|
||||
readonly refreshTokenExpiresAt?: number | null;
|
||||
readonly scopes?: readonly string[] | null;
|
||||
readonly subscriptionType?: string | null;
|
||||
readonly rateLimitTier?: string | null;
|
||||
}
|
||||
|
||||
export type ApplySource = "rotation" | "switch";
|
||||
|
||||
export type ApplyDecision =
|
||||
| { apply: true; reissued?: boolean }
|
||||
| { apply: false; reason: "already-current" }
|
||||
| { apply: false; reason: "not-newer"; localExpiresAt: number };
|
||||
|
||||
/** Two refresh-token expiries within a day are one lineage; a login starts a fresh window weeks away. */
|
||||
export const GENERATION_TOLERANCE_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export function sameGeneration(a?: number | null, b?: number | null): boolean {
|
||||
if (a == null || b == null) return true;
|
||||
return Math.abs(Number(a) - Number(b)) <= GENERATION_TOLERANCE_MS;
|
||||
}
|
||||
|
||||
export function decideApply(local: Grant | null | undefined, offered: Grant, source: ApplySource): ApplyDecision {
|
||||
if (!local?.accessToken) return { apply: true };
|
||||
if (local.accessToken === offered.accessToken) return { apply: false, reason: "already-current" };
|
||||
const reissued = !sameGeneration(local.refreshTokenExpiresAt, offered.refreshTokenExpiresAt);
|
||||
if (source === "rotation" && !reissued && Number(local.expiresAt) >= Number(offered.expiresAt)) {
|
||||
return { apply: false, reason: "not-newer", localExpiresAt: Number(local.expiresAt) };
|
||||
}
|
||||
return reissued ? { apply: true, reissued: true } : { apply: true };
|
||||
}
|
||||
|
||||
type Oauth = Record<string, unknown> & { accessToken?: string; refreshToken?: string; expiresAt?: number };
|
||||
type Credentials = Record<string, unknown> & { claudeAiOauth?: Oauth };
|
||||
|
||||
export function readCredentials(path: string): Credentials | null {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(path, "utf8")) as Credentials;
|
||||
return parsed && typeof parsed === "object" ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The grant the file holds, or null. */
|
||||
export function grantOf(creds: Credentials | null): Grant | null {
|
||||
const o = creds?.claudeAiOauth;
|
||||
if (!o?.accessToken) return null;
|
||||
return {
|
||||
accessToken: o.accessToken,
|
||||
expiresAt: Number(o.expiresAt ?? 0),
|
||||
refreshTokenExpiresAt: o.refreshTokenExpiresAt == null ? null : Number(o.refreshTokenExpiresAt),
|
||||
};
|
||||
}
|
||||
|
||||
/** Does the file hold a full grant — a refresh token this module never writes, so a person's login? */
|
||||
export function holdsLogin(creds: Credentials | null): boolean {
|
||||
return typeof creds?.claudeAiOauth?.refreshToken === "string" && creds.claudeAiOauth.refreshToken.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The handed grant laid over what is there — a rotation of the licence the node already holds — or,
|
||||
* for a switch, in place of it: the old licence's grant goes whole, scopes and subscription included,
|
||||
* and only keys outside the grant (another kind of credential the vendor keeps in the file) stay.
|
||||
* Either way, no refresh token survives.
|
||||
*/
|
||||
export function replacedBy(local: Credentials | null, grant: Grant): Credentials {
|
||||
const next: Credentials = { ...(local ?? {}) };
|
||||
delete next.claudeAiOauth;
|
||||
return withGrant(next, grant);
|
||||
}
|
||||
|
||||
/** Overlay the handed grant on what is there, and delete any refresh token. */
|
||||
export function withGrant(local: Credentials | null, grant: Grant): Credentials {
|
||||
const next: Credentials = { ...(local ?? {}) };
|
||||
const oauth: Oauth = { ...(local?.claudeAiOauth ?? {}) };
|
||||
oauth.accessToken = grant.accessToken;
|
||||
oauth.expiresAt = grant.expiresAt;
|
||||
for (const k of ["refreshTokenExpiresAt", "scopes", "subscriptionType", "rateLimitTier"] as const) {
|
||||
const v = grant[k];
|
||||
if (v != null) oauth[k] = v as unknown;
|
||||
}
|
||||
delete oauth.refreshToken;
|
||||
next.claudeAiOauth = oauth;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Write atomically at 0600: a partial credentials file must never be read as a whole one. */
|
||||
export function writeCredentials(path: string, creds: Credentials): void {
|
||||
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${path}.mesh-tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(creds, null, 2) + "\n", { mode: 0o600 });
|
||||
renameSync(tmp, path);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Which account the agent is logged in as (novox/hq ADR 0183): not in the token, but in the agent's
|
||||
// own state file beside the home, `~/.claude.json` → `oauthAccount`. Read to attribute a login; written,
|
||||
// three keys and nothing else, when a licence is switched, so the file Claude Code shows the account from
|
||||
// names the account whose token it now holds (as the predecessor learned: two files that disagree make
|
||||
// a later login look like the wrong account).
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
|
||||
export interface Identity {
|
||||
readonly accountUuid: string;
|
||||
readonly emailAddress?: string;
|
||||
readonly organizationUuid?: string;
|
||||
}
|
||||
|
||||
export function readIdentity(stateFile: string): Identity | null {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(stateFile, "utf8")) as { oauthAccount?: Record<string, unknown> };
|
||||
const a = raw.oauthAccount;
|
||||
if (!a || typeof a.accountUuid !== "string") return null;
|
||||
return {
|
||||
accountUuid: a.accountUuid,
|
||||
emailAddress: typeof a.emailAddress === "string" ? a.emailAddress : undefined,
|
||||
organizationUuid: typeof a.organizationUuid === "string" ? a.organizationUuid : undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Point the state file's account at `id`, keeping every other key as found. Returns whether the file
|
||||
* changed; a file that cannot be read as an object is left alone rather than replaced.
|
||||
*/
|
||||
export function writeIdentity(stateFile: string, id: Identity): boolean {
|
||||
let raw: Record<string, unknown>;
|
||||
try {
|
||||
raw = JSON.parse(readFileSync(stateFile, "utf8")) as Record<string, unknown>;
|
||||
if (!raw || typeof raw !== "object") return false;
|
||||
} catch {
|
||||
raw = {};
|
||||
}
|
||||
const current = (raw.oauthAccount ?? {}) as Record<string, unknown>;
|
||||
if (current.accountUuid === id.accountUuid && current.emailAddress === id.emailAddress
|
||||
&& current.organizationUuid === id.organizationUuid) return false;
|
||||
raw.oauthAccount = { ...current, accountUuid: id.accountUuid, emailAddress: id.emailAddress, organizationUuid: id.organizationUuid };
|
||||
const tmp = `${stateFile}.mesh-tmp`;
|
||||
writeFileSync(tmp, JSON.stringify(raw, null, 2), { mode: 0o600 });
|
||||
renameSync(tmp, stateFile);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
{
|
||||
"module": "claude-code",
|
||||
"version": "1",
|
||||
"slug": "agent",
|
||||
"capabilities": [
|
||||
"package-manager"
|
||||
],
|
||||
"requires": [
|
||||
"mcp-endpoint"
|
||||
],
|
||||
"binds": {
|
||||
"mcp-endpoint": "${dir:state}/mcp-endpoint.json"
|
||||
},
|
||||
"consumes": [
|
||||
"claude-licence-manager.licence.rotated",
|
||||
"claude-licence-manager.licence.switched"
|
||||
],
|
||||
"state": [
|
||||
"servers"
|
||||
],
|
||||
"tools": [
|
||||
"claude_code_status",
|
||||
"claude_code_render",
|
||||
"claude_code_pull",
|
||||
"claude_code_mcp_list",
|
||||
"claude_code_mcp_register",
|
||||
"claude_code_mcp_unregister"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "package",
|
||||
"type": "package",
|
||||
"package": "claude-code"
|
||||
},
|
||||
{
|
||||
"id": "managed",
|
||||
"type": "directory",
|
||||
"path": "/etc/claude-code",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "agent-home",
|
||||
"type": "directory",
|
||||
"path": "${machine:account-home}/.claude",
|
||||
"mode": "0700",
|
||||
"owner": "${machine:account}"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"owner": "${machine:account}",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "facts",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/facts.json",
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"content": "{\n \"node\": \"${machine:name}\",\n \"console\": \"http://127.0.0.1:${bound:mcp-endpoint:port}/mcp\"\n}\n"
|
||||
},
|
||||
{
|
||||
"id": "settings",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/settings.json",
|
||||
"mode": "0600",
|
||||
"owner": "${machine:account}",
|
||||
"merge": "json",
|
||||
"content": "{\n \"role\": \"\",\n \"mcp_servers\": {}\n}\n"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLAUDE_CODE_STATE": "${dir:state}",
|
||||
"MESH_CLAUDE_CODE_FACTS": "${dir:state}/facts.json",
|
||||
"MESH_CLAUDE_CODE_SETTINGS": "${dir:state}/settings.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// What claude-code does on a node, written against two things it is handed — a way to ask a tool on the
|
||||
// bus and a way to emit an event — so every path is tested without a bus (novox/hq design 36 §4–§5,
|
||||
// ADR 0183, ADR 0198).
|
||||
//
|
||||
// **Over NATS, in two kinds** (design 32 §10): an event says that something happened and carries no
|
||||
// secret, because a stream keeps it; a token travels on a request, which nothing keeps. So:
|
||||
// - the licence manager's `licence.rotated` and `licence.switched` events tell this module to ask the
|
||||
// seat for its current token, sealed to the key it sends with the request;
|
||||
// - a login a person made here — a refresh token this module never writes — is offered to the seat at
|
||||
// once, sealed to the seat's key: the one moment a refresh token travels, because the login made the
|
||||
// manager's stale;
|
||||
// - an MCP server registered through this module is **state, not an event** (novox/hq ADR 0201): one
|
||||
// key per server in the module's `servers` bucket — `all.<server>` for every node, `<node>.<server>`
|
||||
// for one — which every node watches. A node that joins later, or was off, reads the whole current set
|
||||
// at start; unregistering is a delete. A secret never goes in an entry: the runtime refuses one.
|
||||
|
||||
import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { render, entryProblem, MANAGED_DIR, type Binding, type Facts, type Settings, type Servers } from "./render.js";
|
||||
import { generateKeyPair, open, seal, type SealedBox } from "./seal.js";
|
||||
import { decideApply, grantOf, holdsLogin, readCredentials, replacedBy, withGrant, writeCredentials, type Grant } from "./grant.js";
|
||||
import { readIdentity, writeIdentity, type Identity } from "./identity.js";
|
||||
|
||||
export const SEAT = "anthropic-licence-manager";
|
||||
|
||||
export interface Paths {
|
||||
state: string;
|
||||
facts: string;
|
||||
settings: string;
|
||||
home: string;
|
||||
node: string;
|
||||
}
|
||||
|
||||
/** A tool on the bus: its address and arguments in, its JSON answer out. */
|
||||
export type Ask = (address: string, args: Record<string, unknown>) => Promise<unknown>;
|
||||
/** An event of this module's, by its local name. */
|
||||
export type Emit = (type: string, body: unknown) => Promise<void>;
|
||||
/** Write one managed file; answers what happened. */
|
||||
export type WriteManaged = (name: string, content: string) => string;
|
||||
|
||||
export const readJson = <T>(p: string, fallback: T): T => {
|
||||
try {
|
||||
return JSON.parse(readFileSync(p, "utf8")) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const credentialsPath = (p: Paths) => join(p.home, ".claude", ".credentials.json");
|
||||
const accountPath = (p: Paths) => join(p.home, ".claude.json");
|
||||
const bindingPath = (p: Paths) => join(p.state, "licence.json");
|
||||
const apiKeyPath = (p: Paths) => join(p.state, "api-key");
|
||||
export const helperPath = (p: Paths) => join(p.state, "api-key-helper");
|
||||
const keyPath = (p: Paths) => join(p.state, "key.pem");
|
||||
const pubPath = (p: Paths) => join(p.state, "key.pub.pem");
|
||||
const registryPath = (p: Paths) => join(p.state, "mcp-servers.json");
|
||||
|
||||
export function keypair(p: Paths): { publicKey: string; privateKey: string } {
|
||||
if (!existsSync(keyPath(p))) {
|
||||
const k = generateKeyPair();
|
||||
writeFileSync(keyPath(p), k.privateKey, { mode: 0o600 });
|
||||
writeFileSync(pubPath(p), k.publicKey, { mode: 0o644 });
|
||||
}
|
||||
return { privateKey: readFileSync(keyPath(p), "utf8"), publicKey: readFileSync(pubPath(p), "utf8") };
|
||||
}
|
||||
|
||||
export function registered(p: Paths): Servers {
|
||||
return readJson<Servers>(registryPath(p), {});
|
||||
}
|
||||
|
||||
export function renderNow(p: Paths, write: WriteManaged): string[] {
|
||||
const facts = readJson<Facts | null>(p.facts, null);
|
||||
if (!facts?.console) throw new Error(`the mesh has not rendered ${p.facts} yet; nothing to write`);
|
||||
const files = render(facts, readJson<Settings>(p.settings, {}), readJson<Binding | null>(bindingPath(p), null),
|
||||
helperPath(p), registered(p));
|
||||
return Object.entries(files).map(([name, content]) => write(name, content));
|
||||
}
|
||||
|
||||
// ---- the licence ----------------------------------------------------------------------------------
|
||||
|
||||
/** What the seat answers to `current`: the licence this node is bound to and its token, sealed. */
|
||||
export interface Current {
|
||||
licence: string;
|
||||
kind: "subscription" | "api-key";
|
||||
sealed: SealedBox;
|
||||
identity?: Identity | null;
|
||||
}
|
||||
|
||||
/** Ask the seat for this node's current token and apply it. */
|
||||
export async function pull(p: Paths, ask: Ask, write: WriteManaged): Promise<Record<string, unknown>> {
|
||||
const answer = (await ask(`${SEAT}.current`, { node: p.node, public_key: keypair(p).publicKey })) as Current | null;
|
||||
if (!answer?.sealed) return { applied: false, reason: "the seat holds no licence for this node" };
|
||||
return apply(p, answer, write);
|
||||
}
|
||||
|
||||
/** Apply what the seat handed over. A switch replaces the grant whole and cleans up after the old licence. */
|
||||
export function apply(p: Paths, handed: Current, write: WriteManaged): Record<string, unknown> {
|
||||
const plain = open(handed.sealed, keypair(p).privateKey);
|
||||
const previous = readJson<Binding | null>(bindingPath(p), null);
|
||||
const switched = previous?.licence !== handed.licence;
|
||||
let outcome: Record<string, unknown> = { applied: true, licence: handed.licence, kind: handed.kind, switched };
|
||||
if (handed.kind === "api-key") {
|
||||
writeFileSync(apiKeyPath(p), plain.trim() + "\n", { mode: 0o600 });
|
||||
writeFileSync(helperPath(p), `#!/bin/sh\nexec cat '${apiKeyPath(p)}'\n`, { mode: 0o700 });
|
||||
chmodSync(helperPath(p), 0o700);
|
||||
} else {
|
||||
const grant = JSON.parse(plain) as Grant;
|
||||
const local = readCredentials(credentialsPath(p));
|
||||
const d = decideApply(grantOf(local), grant, switched ? "switch" : "rotation");
|
||||
if (d.apply) writeCredentials(credentialsPath(p), switched ? replacedBy(local, grant) : withGrant(local, grant));
|
||||
else outcome = { applied: false, licence: handed.licence, reason: "reason" in d ? d.reason : undefined }; // narrowed by hand: the build compiles without strict
|
||||
// Away from the API key: it goes, with its helper.
|
||||
rmSync(apiKeyPath(p), { force: true });
|
||||
rmSync(helperPath(p), { force: true });
|
||||
}
|
||||
if (switched && handed.identity?.accountUuid) {
|
||||
outcome.account = writeIdentity(accountPath(p), handed.identity) ? "updated" : "unchanged";
|
||||
}
|
||||
writeFileSync(bindingPath(p), JSON.stringify({ licence: handed.licence, kind: handed.kind }) + "\n", { mode: 0o600 });
|
||||
try {
|
||||
outcome.rendered = renderNow(p, write); // the key-helper comes or goes with the licence's kind
|
||||
} catch (err) {
|
||||
outcome.rendered = { failed: err instanceof Error ? err.message : String(err) };
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
|
||||
/** A licence event from the manager: is it for this node? */
|
||||
export function concerns(p: Paths, type: string, body: { licence?: string; node?: string }): boolean {
|
||||
if (type.endsWith("licence.switched")) return body.node === p.node;
|
||||
if (type.endsWith("licence.rotated")) return body.licence === readJson<Binding | null>(bindingPath(p), null)?.licence;
|
||||
return false;
|
||||
}
|
||||
|
||||
/** A refresh token in the credentials file is a login: this module never writes one. Offer it to the seat. */
|
||||
export async function offerLogin(p: Paths, ask: Ask): Promise<Record<string, unknown> | null> {
|
||||
const creds = readCredentials(credentialsPath(p));
|
||||
if (!holdsLogin(creds)) return null;
|
||||
const key = (await ask(`${SEAT}.public_key`, {})) as { public_key?: string } | null;
|
||||
if (!key?.public_key) throw new Error("the licence manager did not say what key to seal a login to");
|
||||
return (await ask(`${SEAT}.adopt`, {
|
||||
node: p.node,
|
||||
identity: readIdentity(accountPath(p)),
|
||||
sealed: seal(JSON.stringify(creds!.claudeAiOauth), key.public_key),
|
||||
})) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
// ---- MCP servers ----------------------------------------------------------------------------------
|
||||
|
||||
export interface Registration {
|
||||
name: string;
|
||||
entry?: Record<string, unknown>;
|
||||
/** Which nodes: this one (absent), every node running the module ("all"), or a list. */
|
||||
nodes?: "all" | string[];
|
||||
}
|
||||
|
||||
/** The `servers` state, as this module reaches it through the runtime (`state("servers")` in the SDK). */
|
||||
export interface ServerState {
|
||||
put(key: string, value: Record<string, unknown>): Promise<number>;
|
||||
delete(key: string): Promise<void>;
|
||||
keys(): Promise<string[]>;
|
||||
}
|
||||
|
||||
/** One change to the `servers` state, as a watch hands it over. */
|
||||
export interface ServerChange {
|
||||
key: string;
|
||||
op: "put" | "delete";
|
||||
value?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The key a registration lives at: `all.<server>` for every node, `<node>.<server>` for one. */
|
||||
export const keyOf = (scope: string, name: string) => `${scope}.${name}`;
|
||||
|
||||
/**
|
||||
* What this node takes from the `servers` state: the entries for every node and for this one, by key —
|
||||
* kept in memory from the watch, and written through to the module's own file whenever what applies here
|
||||
* changes, so the managed directory can be rendered without the bus.
|
||||
*/
|
||||
export class ServerView {
|
||||
private readonly entries = new Map<string, Record<string, unknown>>();
|
||||
constructor(private readonly p: Paths) {}
|
||||
|
||||
/** Take one change; answers whether what applies to this node changed. */
|
||||
take(c: ServerChange): boolean {
|
||||
const dot = c.key.indexOf(".");
|
||||
const scope = c.key.slice(0, dot), name = c.key.slice(dot + 1);
|
||||
if (dot <= 0 || (scope !== "all" && scope !== this.p.node)) return false;
|
||||
if (c.op === "put" && c.value && entryProblem(name, c.value) === null) this.entries.set(c.key, c.value);
|
||||
else this.entries.delete(c.key);
|
||||
return this.writeThrough();
|
||||
}
|
||||
|
||||
/** What applies here: every node's entries, with this node's own laid over them by server name. */
|
||||
effective(): Servers {
|
||||
const out: Record<string, Record<string, unknown>> = {};
|
||||
for (const scope of ["all", this.p.node]) {
|
||||
for (const [key, entry] of [...this.entries].sort(([a], [b]) => a.localeCompare(b))) {
|
||||
if (key.startsWith(scope + ".")) out[key.slice(scope.length + 1)] = entry;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private writeThrough(): boolean {
|
||||
const now = JSON.stringify(this.effective(), null, 2) + "\n";
|
||||
let before = "";
|
||||
try {
|
||||
before = readFileSync(registryPath(this.p), "utf8");
|
||||
} catch {
|
||||
/* none yet */
|
||||
}
|
||||
if (now === before) return false;
|
||||
writeFileSync(registryPath(this.p), now, { mode: 0o600 });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** A change from the watch: take it, and render when what applies here changed. */
|
||||
export function onServerChange(view: ServerView, c: ServerChange, p: Paths, write: WriteManaged): string | null {
|
||||
if (!view.take(c)) return null;
|
||||
renderNow(p, write);
|
||||
return `${c.op === "put" ? "registered" : "unregistered"} ${c.key}`;
|
||||
}
|
||||
|
||||
const scopesOf = (p: Paths, nodes: Registration["nodes"]): string[] =>
|
||||
nodes === undefined ? [p.node] : nodes === "all" ? ["all"] : nodes;
|
||||
|
||||
/**
|
||||
* Register (or with no entry, unregister) a server: a put (or delete) per scope in the `servers` state.
|
||||
* Taken into this node's view at once, so the answer says what it did here; every other node takes it
|
||||
* from its watch, and a node that joins later from the current state.
|
||||
*/
|
||||
export async function registerServer(p: Paths, r: Registration, servers: ServerState, view: ServerView,
|
||||
write: WriteManaged, others: () => Promise<string[]>): Promise<Record<string, unknown>> {
|
||||
if (r.entry) {
|
||||
const problem = entryProblem(r.name, r.entry);
|
||||
if (problem) return { registered: false, reason: problem };
|
||||
}
|
||||
const scopes = scopesOf(p, r.nodes);
|
||||
// Compared before and after rather than read from take(): this node's own watch may hand the view the
|
||||
// same change first, and then take() here finds nothing new although this call made it.
|
||||
const before = JSON.stringify(view.effective());
|
||||
for (const scope of scopes) {
|
||||
const key = keyOf(scope, r.name);
|
||||
if (r.entry) await servers.put(key, r.entry);
|
||||
else await servers.delete(key);
|
||||
view.take({ key, op: r.entry ? "put" : "delete", value: r.entry });
|
||||
}
|
||||
const changedHere = JSON.stringify(view.effective()) !== before;
|
||||
const here = scopes.includes("all") || scopes.includes(p.node);
|
||||
const answer: Record<string, unknown> = {
|
||||
[r.entry ? "registered" : "unregistered"]: r.name,
|
||||
on: r.nodes === undefined ? [p.node] : r.nodes,
|
||||
here: here ? (changedHere ? "changed" : "already so") : "not this node",
|
||||
rendered: changedHere ? renderNow(p, write) : [],
|
||||
};
|
||||
if (!r.entry && view.effective()[r.name]) {
|
||||
answer.still = `${r.name} still applies here from another registration (for every node, or for this one); unregister that too`;
|
||||
}
|
||||
if (r.nodes === undefined) {
|
||||
// The question the operator wanted asked: here only, or more?
|
||||
const elsewhere = (await others().catch(() => [] as string[])).filter((n) => n !== p.node);
|
||||
answer.also = elsewhere.length
|
||||
? `claude-code also runs on ${elsewhere.join(", ")}. To ${r.entry ? "register" : "unregister"} it there too, call again with nodes: "all" or a list of those nodes.`
|
||||
: `To do the same on every node running claude-code, call again with nodes: "all".`;
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
|
||||
export { MANAGED_DIR };
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@novox/module-claude-code",
|
||||
"version": "0.1.0",
|
||||
"description": "claude-code — the operator's agent on a machine: its managed configuration, and the consumer side of the Anthropic licence manager (novox/hq design 36).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "tsc seal.ts grant.ts identity.ts render.ts node.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist",
|
||||
"test": "npm run build && node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
},
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// What the module writes into the agent's machine-wide managed directory (novox/hq design 36 §1–§4).
|
||||
// Pure: composed from the facts the mesh rendered, the settings the operator set and the licence the
|
||||
// node holds, so what lands under /etc is tested without a machine.
|
||||
//
|
||||
// Three files, owned whole by this module:
|
||||
// managed-mcp.json the tool servers every session loads: the mesh's console as `mesh`, and the
|
||||
// servers the operator declared for the mesh or this node. Exclusive by the
|
||||
// vendor's rule — a server not listed here does not load — which is why the
|
||||
// list is the module's settings and nothing else (operator's choice, 2026-10-03).
|
||||
// managed-settings.json the mesh's keys only: the repositories' attribution convention, the
|
||||
// claude.ai connectors kept beside the managed servers, and — for an API-key
|
||||
// licence only — the key-helper. A person's preferences are theirs.
|
||||
// CLAUDE.md how a session on this mesh works, who this node is, the conventions.
|
||||
|
||||
export const MANAGED_DIR = "/etc/claude-code";
|
||||
|
||||
export interface Facts {
|
||||
readonly node: string;
|
||||
readonly console: string;
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
readonly role?: string;
|
||||
/** Extra tool servers, in the vendor's `.mcp.json` entry shape, keyed by name. */
|
||||
readonly mcp_servers?: Readonly<Record<string, Record<string, unknown>>>;
|
||||
}
|
||||
|
||||
export interface Binding {
|
||||
readonly licence: string;
|
||||
readonly kind: "subscription" | "api-key";
|
||||
}
|
||||
|
||||
export interface Rendered {
|
||||
readonly [file: string]: string;
|
||||
}
|
||||
|
||||
const MESH_ENTRY = "mesh";
|
||||
|
||||
export type Servers = Readonly<Record<string, Record<string, unknown>>>;
|
||||
|
||||
/** Whether an entry is one the vendor's managed file takes: a name of letters, digits, `-` and `_`, and
|
||||
* an http/sse server with a url or a stdio server with a command. Returns why not, or null. */
|
||||
export function entryProblem(name: string, entry: Record<string, unknown>): string | null {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(name)) return `"${name}" is not a name the agent takes: letters, digits, - and _`;
|
||||
if (name === MESH_ENTRY) return `"${MESH_ENTRY}" is the mesh's own entry`;
|
||||
const type = entry?.type ?? "stdio";
|
||||
if (type === "http" || type === "sse" || type === "streamable-http") {
|
||||
return typeof entry.url === "string" && entry.url ? null : `an ${type} server needs a url`;
|
||||
}
|
||||
if (type === "stdio") return typeof entry.command === "string" && entry.command ? null : "a stdio server needs a command";
|
||||
return `"${String(type)}" is not a server type the agent knows (http, sse, stdio)`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compose the three files. `registered` is the module's own list on this node — what was registered
|
||||
* through its tools — laid over the servers the operator set in its settings.
|
||||
*/
|
||||
export function render(facts: Facts, settings: Settings, binding: Binding | null, helperPath: string,
|
||||
registered: Servers = {}): Rendered {
|
||||
const servers: Record<string, unknown> = {};
|
||||
for (const [name, entry] of Object.entries({ ...(settings.mcp_servers ?? {}), ...registered })) {
|
||||
if (entryProblem(name, entry) !== null) continue; // the mesh's own entry, or one the agent would refuse
|
||||
servers[name] = entry;
|
||||
}
|
||||
servers[MESH_ENTRY] = { type: "http", url: facts.console };
|
||||
|
||||
const managed: Record<string, unknown> = {
|
||||
attribution: { commit: "", pr: "" },
|
||||
allowAllClaudeAiMcps: true,
|
||||
};
|
||||
if (binding?.kind === "api-key") managed.apiKeyHelper = helperPath;
|
||||
|
||||
return {
|
||||
"managed-mcp.json": json({ mcpServers: sortKeys(servers) }),
|
||||
"managed-settings.json": json(managed),
|
||||
"CLAUDE.md": instructions(facts, settings),
|
||||
};
|
||||
}
|
||||
|
||||
function json(v: unknown): string {
|
||||
return JSON.stringify(v, null, 2) + "\n";
|
||||
}
|
||||
|
||||
function sortKeys(o: Record<string, unknown>): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.keys(o).sort().map((k) => [k, o[k]]));
|
||||
}
|
||||
|
||||
export function instructions(facts: Facts, settings: Settings): string {
|
||||
const role = settings.role?.trim() ? settings.role.trim() : "not stated — set it in this module's settings for the node";
|
||||
return `# This machine is a node of a Novox mesh
|
||||
|
||||
Written by the mesh's \`claude-code\` module. Edit the module's settings or the catalogue, never this file:
|
||||
it is rewritten whenever the module renders.
|
||||
|
||||
## Who this node is
|
||||
|
||||
- **Node:** \`${facts.node}\`
|
||||
- **Role:** ${role}
|
||||
- The other nodes, their roles and what runs where: ask the controller (\`mesh-controller.nodes\`,
|
||||
\`mesh-controller.node\`). Nothing here lists them, because a copy drifts.
|
||||
|
||||
## How a session on this mesh works
|
||||
|
||||
The console is the only way to the mesh: the MCP server named \`mesh\`. It offers five tools, and
|
||||
everything else is an address you find and call through them:
|
||||
|
||||
- \`mesh_search\` — words in, matching addresses out. \`mesh_describe\` — one address's arguments.
|
||||
- \`mesh_call\` — call an address. A seat the mesh holds once is \`<seat>.<verb>\` (the mesh's own verbs
|
||||
are \`mesh-controller.<verb>\`: \`status\`, \`plan\`, \`node\`, \`assign\`, \`push\`, \`settings\`);
|
||||
a module on a machine is \`<node>/<module>.<tool>\`.
|
||||
- \`mesh_overview\` and \`mesh_machine\` — the mesh's seats and machines, and what one machine runs.
|
||||
|
||||
- **Symptom first.** For an error, a failing service or anything unexpected, search the record with the
|
||||
literal text before forming a hypothesis: the records module's \`records_search\`, then
|
||||
\`records_read\`.
|
||||
- **Ask the mesh before changing it**, and change it through the controller's verbs or the catalogue.
|
||||
- **A licence** through the \`anthropic-licence-manager\` seat's verbs. Never edit the agent's credentials
|
||||
file by hand, never print or ask for a token.
|
||||
|
||||
## Hard rules
|
||||
|
||||
- A file the mesh manages is changed through the verb or the catalogue that owns it, never on disk. If
|
||||
unsure, \`mesh-controller.plan\` for the node says what the mesh writes there.
|
||||
- Never write to a store's database by hand; schema changes are numbered migrations.
|
||||
- Never push to a main branch: a branch, a pull request, and a human approval for every merge.
|
||||
- The mesh creates no symlinks, and nobody else does either.
|
||||
- A package is declared in a module, never installed by hand.
|
||||
|
||||
## Conventions
|
||||
|
||||
- Commit messages are concise, in the imperative, about why.
|
||||
- Test before pushing: nodes update unattended.
|
||||
- The playbooks in the record say how research, decisions, designs, issues and hand-offs are done.
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// Sealing a token to one recipient (novox/hq ADR 0183): the manager seals what it hands a node to that
|
||||
// node's agent module key, and a node seals a waiting login to the key the manager names. X25519 for
|
||||
// the agreement, HKDF-SHA256 for the key, AES-256-GCM for the box — all from Node's own library, so a
|
||||
// bundle carries no dependency and no secret ever crosses the bus in the clear.
|
||||
//
|
||||
// A sealed box is `{ v: 1, eph, iv, tag, ct }`, every field base64. `eph` is a one-time public key, so
|
||||
// two boxes of one value to one recipient share nothing, and only the recipient's private key opens it.
|
||||
|
||||
import {
|
||||
createCipheriv, createDecipheriv, createPrivateKey, createPublicKey, diffieHellman,
|
||||
generateKeyPairSync, hkdfSync, randomBytes, type KeyObject,
|
||||
} from "node:crypto";
|
||||
|
||||
export interface SealedBox {
|
||||
readonly v: 1;
|
||||
readonly eph: string;
|
||||
readonly iv: string;
|
||||
readonly tag: string;
|
||||
readonly ct: string;
|
||||
}
|
||||
|
||||
/** A recipient's keypair, as the two PEM strings it is kept and published as. */
|
||||
export interface KeyPairPem {
|
||||
readonly publicKey: string;
|
||||
readonly privateKey: string;
|
||||
}
|
||||
|
||||
const INFO = Buffer.from("novox-mesh sealed box v1");
|
||||
|
||||
export function generateKeyPair(): KeyPairPem {
|
||||
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
||||
return {
|
||||
publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
||||
privateKey: privateKey.export({ type: "pkcs8", format: "pem" }).toString(),
|
||||
};
|
||||
}
|
||||
|
||||
function keyFor(secret: Buffer, eph: Buffer, recipient: Buffer): Buffer {
|
||||
// The ephemeral and the recipient's public halves are bound into the key, so a box cannot be
|
||||
// re-addressed to another recipient by swapping its `eph`.
|
||||
return Buffer.from(hkdfSync("sha256", secret, Buffer.concat([eph, recipient]), INFO, 32));
|
||||
}
|
||||
|
||||
function rawPublic(key: KeyObject): Buffer {
|
||||
return key.export({ type: "spki", format: "der" }).subarray(-32);
|
||||
}
|
||||
|
||||
export function seal(plaintext: string, recipientPublicPem: string): SealedBox {
|
||||
const recipient = createPublicKey(recipientPublicPem);
|
||||
const eph = generateKeyPairSync("x25519");
|
||||
const secret = diffieHellman({ privateKey: eph.privateKey, publicKey: recipient });
|
||||
const ephRaw = eph.publicKey.export({ type: "spki", format: "der" });
|
||||
const key = keyFor(secret, ephRaw, rawPublic(recipient));
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
||||
return {
|
||||
v: 1,
|
||||
eph: ephRaw.toString("base64"),
|
||||
iv: iv.toString("base64"),
|
||||
tag: cipher.getAuthTag().toString("base64"),
|
||||
ct: ct.toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
/** Open a box with the recipient's private key. Throws on a box for another key or one tampered with. */
|
||||
export function open(box: SealedBox, privateKeyPem: string): string {
|
||||
if (!box || box.v !== 1) throw new Error("not a sealed box this module can open");
|
||||
const priv = createPrivateKey(privateKeyPem);
|
||||
const ephRaw = Buffer.from(box.eph, "base64");
|
||||
const eph = createPublicKey({ key: ephRaw, format: "der", type: "spki" });
|
||||
const secret = diffieHellman({ privateKey: priv, publicKey: eph });
|
||||
const key = keyFor(secret, ephRaw, rawPublic(createPublicKey(priv)));
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(box.iv, "base64"));
|
||||
decipher.setAuthTag(Buffer.from(box.tag, "base64"));
|
||||
return Buffer.concat([decipher.update(Buffer.from(box.ct, "base64")), decipher.final()]).toString("utf8");
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
decideApply, grantOf, holdsLogin, readCredentials, withGrant, writeCredentials, type Grant,
|
||||
} from "../dist/grant.js";
|
||||
|
||||
const NOW = 1_700_000_000_000;
|
||||
const HOUR = 3_600_000;
|
||||
const g = (over: Partial<Grant> = {}): Grant => ({
|
||||
accessToken: "tok-A", expiresAt: NOW + HOUR, refreshTokenExpiresAt: NOW + 30 * 24 * HOUR, ...over,
|
||||
});
|
||||
|
||||
test("a rotation applies a newer grant of the same licence", () => {
|
||||
assert.deepEqual(decideApply(g(), g({ accessToken: "tok-B", expiresAt: NOW + 2 * HOUR }), "rotation"), { apply: true });
|
||||
});
|
||||
|
||||
test("a rotation refuses a grant that arrived late and is older", () => {
|
||||
const d = decideApply(g({ accessToken: "new", expiresAt: NOW + 2 * HOUR }), g({ accessToken: "old" }), "rotation");
|
||||
assert.equal(d.apply === false && d.reason, "not-newer");
|
||||
});
|
||||
|
||||
test("a grant re-issued by a login is adopted even though it expires sooner (2026-09-05)", () => {
|
||||
const local = g({ expiresAt: NOW + 8 * HOUR, refreshTokenExpiresAt: NOW + 30 * 24 * HOUR });
|
||||
const offered = g({ accessToken: "reissued", expiresAt: NOW + HOUR, refreshTokenExpiresAt: NOW + 5 * 24 * HOUR });
|
||||
assert.deepEqual(decideApply(local, offered, "rotation"), { apply: true, reissued: true });
|
||||
});
|
||||
|
||||
test("a switch to another licence applies whatever the expiries say", () => {
|
||||
const local = g({ expiresAt: NOW + 8 * HOUR });
|
||||
assert.equal(decideApply(local, g({ accessToken: "other", expiresAt: NOW + HOUR }), "switch").apply, true);
|
||||
});
|
||||
|
||||
test("the same token is not rewritten", () => {
|
||||
assert.deepEqual(decideApply(g(), g(), "switch"), { apply: false, reason: "already-current" });
|
||||
});
|
||||
|
||||
test("a full grant left by a login is seen as a login, and stripped when the node's own is written", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "claude-code-"));
|
||||
const path = join(dir, ".claude", ".credentials.json");
|
||||
writeFileSync(join(dir, "x"), "");
|
||||
const login = { claudeAiOauth: { accessToken: "at-login", refreshToken: "rt-login", expiresAt: NOW }, other: 1 };
|
||||
assert.equal(holdsLogin(login), true);
|
||||
writeCredentials(path, withGrant(login, g({ accessToken: "at-mesh", scopes: ["user:inference"] })));
|
||||
const back = readCredentials(path)!;
|
||||
assert.equal(holdsLogin(back), false);
|
||||
assert.equal(grantOf(back)!.accessToken, "at-mesh");
|
||||
assert.deepEqual(back.claudeAiOauth!.scopes, ["user:inference"]);
|
||||
assert.equal(back.other, 1, "a key the module does not know was lost");
|
||||
assert.ok(!readFileSync(path, "utf8").includes("rt-login"));
|
||||
assert.equal(statSync(path).mode & 0o777, 0o600);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { readIdentity } from "../dist/identity.js";
|
||||
|
||||
test("the account is read from the agent's state file", () => {
|
||||
const p = join(mkdtempSync(join(tmpdir(), "cc-id-")), ".claude.json");
|
||||
writeFileSync(p, JSON.stringify({ oauthAccount: { accountUuid: "u-1", emailAddress: "a@example.org" }, other: 2 }));
|
||||
assert.deepEqual(readIdentity(p), { accountUuid: "u-1", emailAddress: "a@example.org", organizationUuid: undefined });
|
||||
});
|
||||
|
||||
test("no state file, or no account in it, is no identity rather than a guess", () => {
|
||||
assert.equal(readIdentity("/nonexistent/.claude.json"), null);
|
||||
const p = join(mkdtempSync(join(tmpdir(), "cc-id-")), ".claude.json");
|
||||
writeFileSync(p, "{}");
|
||||
assert.equal(readIdentity(p), null);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
apply, concerns, keypair, offerLogin, onServerChange, pull, registerServer, registered, ServerView, type Paths,
|
||||
type ServerChange, type ServerState,
|
||||
} from "../dist/node.js";
|
||||
import { generateKeyPair, open, seal } from "../dist/seal.js";
|
||||
|
||||
const NOW = Date.now();
|
||||
function node(name = "laptop"): { p: Paths; written: Record<string, string> } {
|
||||
const root = mkdtempSync(join(tmpdir(), "cc-node-"));
|
||||
const p = { state: join(root, "state"), facts: join(root, "state", "facts.json"), settings: join(root, "state", "settings.json"), home: join(root, "home"), node: name };
|
||||
mkdirSync(p.state, { recursive: true });
|
||||
mkdirSync(join(p.home, ".claude"), { recursive: true });
|
||||
writeFileSync(p.facts, JSON.stringify({ node: name, console: "http://127.0.0.1:4270/mcp" }));
|
||||
writeFileSync(p.settings, JSON.stringify({ role: "", mcp_servers: {} }));
|
||||
return { p, written: {} };
|
||||
}
|
||||
const writer = (w: Record<string, string>) => (name: string, content: string) => { w[name] = content; return `${name}: written`; };
|
||||
const creds = (p: Paths) => JSON.parse(readFileSync(join(p.home, ".claude", ".credentials.json"), "utf8"));
|
||||
const grantFor = (p: Paths, licence: string, token: string, kind: "subscription" | "api-key" = "subscription", identity?: object) => ({
|
||||
licence, kind, identity,
|
||||
sealed: seal(kind === "api-key" ? token : JSON.stringify({ accessToken: token, expiresAt: NOW + 3_600_000, refreshTokenExpiresAt: NOW + 86_400_000, subscriptionType: licence }), keypair(p).publicKey),
|
||||
});
|
||||
|
||||
test("a pull asks the seat with this node's key and applies what it answers", async () => {
|
||||
const { p, written } = node();
|
||||
let asked: [string, Record<string, unknown>] | null = null;
|
||||
const r = await pull(p, async (address, args) => { asked = [address, args]; return grantFor(p, "personal", "at-1"); }, writer(written));
|
||||
assert.equal(asked![0], "anthropic-licence-manager.current");
|
||||
assert.equal(asked![1].node, "laptop");
|
||||
assert.match(String(asked![1].public_key), /BEGIN PUBLIC KEY/);
|
||||
assert.equal(r.applied, true);
|
||||
assert.equal(creds(p).claudeAiOauth.accessToken, "at-1");
|
||||
assert.ok(written["managed-mcp.json"]);
|
||||
});
|
||||
|
||||
test("a switch replaces the old licence's grant whole and points the account at the new one", () => {
|
||||
const { p, written } = node();
|
||||
writeFileSync(join(p.home, ".claude.json"), JSON.stringify({ oauthAccount: { accountUuid: "old" }, projects: { keep: 1 } }));
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
const r = apply(p, grantFor(p, "work", "at-2", "subscription", { accountUuid: "new", emailAddress: "w@example.org" }), writer(written));
|
||||
assert.equal(r.switched, true);
|
||||
assert.equal(creds(p).claudeAiOauth.accessToken, "at-2");
|
||||
assert.equal(creds(p).claudeAiOauth.subscriptionType, "work", "the old licence's subscription type survived the switch");
|
||||
const account = JSON.parse(readFileSync(join(p.home, ".claude.json"), "utf8"));
|
||||
assert.equal(account.oauthAccount.accountUuid, "new");
|
||||
assert.deepEqual(account.projects, { keep: 1 });
|
||||
});
|
||||
|
||||
test("switching to the API key adds the key-helper; switching away removes the key and the helper", () => {
|
||||
const { p, written } = node();
|
||||
apply(p, grantFor(p, "api", "sk-key", "api-key"), writer(written));
|
||||
assert.ok(JSON.parse(written["managed-settings.json"]).apiKeyHelper);
|
||||
assert.ok(existsSync(join(p.state, "api-key")));
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
assert.ok(!("apiKeyHelper" in JSON.parse(written["managed-settings.json"])));
|
||||
assert.ok(!existsSync(join(p.state, "api-key")) && !existsSync(join(p.state, "api-key-helper")));
|
||||
});
|
||||
|
||||
test("a rotation event concerns the node bound to that licence; a switch event the node it names", () => {
|
||||
const { p, written } = node();
|
||||
apply(p, grantFor(p, "personal", "at-1"), writer(written));
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.rotated", { licence: "personal" }), true);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.rotated", { licence: "work" }), false);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.switched", { node: "laptop", licence: "work" }), true);
|
||||
assert.equal(concerns(p, "claude-licence-manager.licence.switched", { node: "server" }), false);
|
||||
});
|
||||
|
||||
test("a login is offered to the seat sealed to the seat's key, with the account it belongs to", async () => {
|
||||
const { p } = node();
|
||||
const manager = generateKeyPair();
|
||||
writeFileSync(join(p.home, ".claude", ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "at-login", refreshToken: "rt-login", expiresAt: NOW } }));
|
||||
writeFileSync(join(p.home, ".claude.json"), JSON.stringify({ oauthAccount: { accountUuid: "u-9" } }));
|
||||
const calls: [string, Record<string, unknown>][] = [];
|
||||
await offerLogin(p, async (address, args) => { calls.push([address, args]); return address.endsWith("public_key") ? { public_key: manager.publicKey } : { adopted: true }; });
|
||||
assert.deepEqual(calls.map((c) => c[0]), ["anthropic-licence-manager.public_key", "anthropic-licence-manager.adopt"]);
|
||||
const adopt = calls[1][1] as { identity: { accountUuid: string }; sealed: never };
|
||||
assert.equal(adopt.identity.accountUuid, "u-9");
|
||||
assert.equal(JSON.parse(open(adopt.sealed, manager.privateKey)).refreshToken, "rt-login");
|
||||
assert.ok(!JSON.stringify(adopt).includes("rt-login"), "the refresh token crossed in the clear");
|
||||
});
|
||||
|
||||
test("no refresh token in the file is no login, and nothing is asked", async () => {
|
||||
const { p } = node();
|
||||
writeFileSync(join(p.home, ".claude", ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "at", expiresAt: NOW } }));
|
||||
assert.equal(await offerLogin(p, async () => { throw new Error("asked"); }), null);
|
||||
});
|
||||
|
||||
/** The `servers` state as the bus holds it, shared by every node in a test, with each node's watch. */
|
||||
function bus() {
|
||||
const kept = new Map<string, Record<string, unknown>>();
|
||||
const watchers: ((c: ServerChange) => void)[] = [];
|
||||
const state: ServerState = {
|
||||
put: async (key, value) => { kept.set(key, value); watchers.forEach((w) => w({ key, op: "put", value })); return kept.size; },
|
||||
delete: async (key) => { kept.delete(key); watchers.forEach((w) => w({ key, op: "delete" })); },
|
||||
keys: async () => [...kept.keys()].sort(),
|
||||
};
|
||||
/** A node joining: its view takes the current state, then every change. */
|
||||
const join = (n: { p: Paths; written: Record<string, string> }) => {
|
||||
const view = new ServerView(n.p);
|
||||
for (const [key, value] of kept) onServerChange(view, { key, op: "put", value }, n.p, writer(n.written));
|
||||
watchers.push((c) => onServerChange(view, c, n.p, writer(n.written)));
|
||||
return view;
|
||||
};
|
||||
return { state, join, kept };
|
||||
}
|
||||
|
||||
test("registering a server here puts it under this node's key, renders it, and asks about the other nodes", async () => {
|
||||
const n = node();
|
||||
const b = bus();
|
||||
const view = b.join(n);
|
||||
const r = await registerServer(n.p, { name: "search", entry: { type: "http", url: "https://s.example/mcp" } },
|
||||
b.state, view, writer(n.written), async () => ["laptop", "server", "desktop"]);
|
||||
assert.equal(r.here, "changed");
|
||||
assert.match(String(r.also), /server, desktop/);
|
||||
assert.deepEqual([...b.kept.keys()], ["laptop.search"]);
|
||||
assert.ok(JSON.parse(n.written["managed-mcp.json"]).mcpServers.search);
|
||||
});
|
||||
|
||||
test("registering for every node reaches the others through their watch, and a node joining later reads it", async () => {
|
||||
const a = node("laptop"), s = node("server");
|
||||
const b = bus();
|
||||
const va = b.join(a);
|
||||
b.join(s);
|
||||
await registerServer(a.p, { name: "docs", entry: { type: "stdio", command: "docs-mcp" }, nodes: "all" },
|
||||
b.state, va, writer(a.written), async () => []);
|
||||
assert.deepEqual([...b.kept.keys()], ["all.docs"]);
|
||||
assert.deepEqual(registered(s.p).docs, { type: "stdio", command: "docs-mcp" });
|
||||
assert.ok(JSON.parse(s.written["managed-mcp.json"]).mcpServers.docs);
|
||||
// The gap events left: a node assigned after the registration takes the whole current set at start.
|
||||
const late = node("desktop");
|
||||
b.join(late);
|
||||
assert.deepEqual(registered(late.p).docs, { type: "stdio", command: "docs-mcp" });
|
||||
// Unregistering is a delete, and every node's view drops it.
|
||||
await registerServer(a.p, { name: "docs", nodes: "all" }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(s.p).docs, undefined);
|
||||
assert.equal(registered(late.p).docs, undefined);
|
||||
});
|
||||
|
||||
test("a node's own registration overrides the one for every node; other nodes' keys leave this one alone", async () => {
|
||||
const a = node("laptop"), s = node("server");
|
||||
const b = bus();
|
||||
const va = b.join(a);
|
||||
const vs = b.join(s);
|
||||
await registerServer(a.p, { name: "x", entry: { type: "http", url: "https://all" }, nodes: "all" }, b.state, va, writer(a.written), async () => []);
|
||||
await registerServer(a.p, { name: "x", entry: { type: "http", url: "https://laptop" } }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(a.p).x.url, "https://laptop");
|
||||
assert.equal(registered(s.p).x.url, "https://all");
|
||||
await registerServer(a.p, { name: "only", entry: { type: "http", url: "https://o" }, nodes: ["server"] }, b.state, va, writer(a.written), async () => []);
|
||||
assert.equal(registered(a.p).only, undefined);
|
||||
assert.equal(registered(s.p).only.url, "https://o");
|
||||
// Unregistering here leaves the every-node one applying, and says so.
|
||||
const r = await registerServer(a.p, { name: "x" }, b.state, va, writer(a.written), async () => []);
|
||||
assert.match(String(r.still), /still applies here/);
|
||||
assert.equal(registered(a.p).x.url, "https://all");
|
||||
assert.equal(vs.effective().x.url, "https://all");
|
||||
});
|
||||
|
||||
test("a bad entry is refused before anything is put; a repeated change changes nothing", async () => {
|
||||
const n = node();
|
||||
const b = bus();
|
||||
const view = b.join(n);
|
||||
const r = await registerServer(n.p, { name: "mesh", entry: { type: "http", url: "https://x" } }, b.state, view, writer(n.written), async () => []);
|
||||
assert.equal(r.registered, false);
|
||||
assert.equal(b.kept.size, 0);
|
||||
assert.equal(onServerChange(view, { key: "all.a", op: "put", value: { type: "http", url: "https://a" } }, n.p, writer(n.written)), "registered all.a");
|
||||
assert.equal(onServerChange(view, { key: "all.a", op: "put", value: { type: "http", url: "https://a" } }, n.p, writer(n.written)), null);
|
||||
assert.equal(onServerChange(view, { key: "server.b", op: "put", value: { type: "http", url: "https://b" } }, n.p, writer(n.written)), null);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { render } from "../dist/render.js";
|
||||
|
||||
const facts = { node: "workstation", console: "http://127.0.0.1:4270/mcp" };
|
||||
|
||||
test("the console is the `mesh` server, and an operator's servers are listed beside it", () => {
|
||||
const out = render(facts, { mcp_servers: { search: { type: "http", url: "https://s.example/mcp" } } }, null, "/h");
|
||||
const mcp = JSON.parse(out["managed-mcp.json"]);
|
||||
assert.deepEqual(Object.keys(mcp.mcpServers), ["mesh", "search"]);
|
||||
assert.deepEqual(mcp.mcpServers.mesh, { type: "http", url: facts.console });
|
||||
});
|
||||
|
||||
test("a setting cannot replace the mesh's own entry, and a name the vendor refuses is left out", () => {
|
||||
const out = render(facts, { mcp_servers: { mesh: { type: "http", url: "http://evil" }, "bad name": {} } }, null, "/h");
|
||||
const mcp = JSON.parse(out["managed-mcp.json"]);
|
||||
assert.equal(mcp.mcpServers.mesh.url, facts.console);
|
||||
assert.ok(!("bad name" in mcp.mcpServers));
|
||||
});
|
||||
|
||||
test("managed settings carry the mesh's keys only, and the key-helper only for an API-key licence", () => {
|
||||
const sub = JSON.parse(render(facts, {}, { licence: "personal", kind: "subscription" }, "/h")["managed-settings.json"]);
|
||||
assert.deepEqual(sub, { attribution: { commit: "", pr: "" }, allowAllClaudeAiMcps: true });
|
||||
const key = JSON.parse(render(facts, {}, { licence: "api", kind: "api-key" }, "/state/api-key-helper")["managed-settings.json"]);
|
||||
assert.equal(key.apiKeyHelper, "/state/api-key-helper");
|
||||
assert.ok(!("model" in key), "a preference is the person's");
|
||||
});
|
||||
|
||||
test("the instruction file names the node and its role, and no other node", () => {
|
||||
const md = render(facts, { role: "the laptop" }, null, "/h")["CLAUDE.md"];
|
||||
assert.match(md, /\*\*Node:\*\* `workstation`/);
|
||||
assert.match(md, /\*\*Role:\*\* the laptop/);
|
||||
assert.match(md, /mesh_call/);
|
||||
assert.match(md, /records_search/);
|
||||
});
|
||||
|
||||
test("rendering is deterministic, so an unchanged input writes nothing", () => {
|
||||
const s = { mcp_servers: { b: { type: "http", url: "https://b" }, a: { type: "http", url: "https://a" } } };
|
||||
assert.deepEqual(render(facts, s, null, "/h"), render(facts, s, null, "/h"));
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { generateKeyPair, open, seal } from "../dist/seal.js";
|
||||
|
||||
test("a box opens with its recipient's key and yields the value", () => {
|
||||
const k = generateKeyPair();
|
||||
assert.equal(open(seal("at-secret", k.publicKey), k.privateKey), "at-secret");
|
||||
});
|
||||
|
||||
test("a box sealed for one node does not open with another node's key", () => {
|
||||
const a = generateKeyPair();
|
||||
const b = generateKeyPair();
|
||||
assert.throws(() => open(seal("at-secret", a.publicKey), b.privateKey));
|
||||
});
|
||||
|
||||
test("a tampered box is refused, not opened to garbage", () => {
|
||||
const k = generateKeyPair();
|
||||
const box = seal("at-secret", k.publicKey);
|
||||
const ct = Buffer.from(box.ct, "base64");
|
||||
ct[0] ^= 0xff;
|
||||
assert.throws(() => open({ ...box, ct: ct.toString("base64") }, k.privateKey));
|
||||
});
|
||||
|
||||
test("two boxes of one value share nothing a reader could compare", () => {
|
||||
const k = generateKeyPair();
|
||||
const x = seal("at-secret", k.publicKey);
|
||||
const y = seal("at-secret", k.publicKey);
|
||||
assert.notEqual(x.ct, y.ct);
|
||||
assert.notEqual(x.eph, y.eph);
|
||||
assert.ok(!JSON.stringify(x).includes("at-secret"));
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
// claude-code's bundle (novox/hq design 36, ADR 0183). The node's runtime launches it over stdio, as the
|
||||
// operator account (ADR 0193), and is its bus (ADR 0198): it asks tools, emits and consumes through the
|
||||
// runtime. It is given its state directory and two files the mesh renders into it (ADR 0192), beside the
|
||||
// runtime's own words. **stdout is the MCP channel**: everything this module says, it says on stderr.
|
||||
//
|
||||
// At start it renders the agent's managed directory, asks the licence manager for this node's token,
|
||||
// begins watching the credentials file for a login, takes the manager's licence events, and watches the
|
||||
// module's `servers` state — every node's MCP server registrations (novox/hq ADR 0201). node.ts holds the
|
||||
// logic.
|
||||
|
||||
import { mkdtempSync, readFileSync, rmSync, watchFile, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { join } from "node:path";
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { broker } from "@novox/mesh-sdk/messaging";
|
||||
import { on } from "@novox/mesh-sdk/events";
|
||||
import { state } from "@novox/mesh-sdk/state";
|
||||
|
||||
import {
|
||||
MANAGED_DIR, SEAT, ServerView, concerns, keypair, offerLogin, onServerChange, pull, readJson, registerServer,
|
||||
registered, renderNow, type Ask, type Paths, type Registration, type ServerChange, type ServerState, type WriteManaged,
|
||||
} from "../node.js";
|
||||
import { grantOf, holdsLogin, readCredentials } from "../grant.js";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const say = (line: string) => console.error(`[claude-code] ${line}`);
|
||||
const fingerprint = (s: string) => "sha256:" + createHash("sha256").update(s).digest("hex").slice(0, 16);
|
||||
|
||||
function pathsFrom(env: NodeJS.ProcessEnv): Paths | null {
|
||||
const state = env.MESH_CLAUDE_CODE_STATE, facts = env.MESH_CLAUDE_CODE_FACTS;
|
||||
const settings = env.MESH_CLAUDE_CODE_SETTINGS, home = env.MESH_OPERATOR_HOME, node = env.MESH_NODE;
|
||||
if (!state || !facts || !settings || !home || !node) return null;
|
||||
return { state, facts, settings, home, node };
|
||||
}
|
||||
|
||||
/** Write one managed file as root, only when its content changed. */
|
||||
const writeManaged: WriteManaged = (name, content) => {
|
||||
const path = join(MANAGED_DIR, name);
|
||||
try {
|
||||
if (readFileSync(path, "utf8") === content) return `${name}: unchanged`;
|
||||
} catch {
|
||||
/* absent */
|
||||
}
|
||||
// From a file, never /dev/stdin: Node hands a child its input over a socket, which /dev/stdin cannot
|
||||
// open (ENXIO) — found on the first assignment, where nothing under /etc/claude-code was ever written.
|
||||
const staged = mkdtempSync(join(tmpdir(), "claude-code-"));
|
||||
const source = join(staged, name);
|
||||
writeFileSync(source, content, { mode: 0o644 });
|
||||
const asRoot = process.getuid?.() === 0;
|
||||
const cmd = asRoot ? ["install", "-D", "-m", "0644", source, path] : ["sudo", "-n", "install", "-D", "-m", "0644", source, path];
|
||||
const r = spawnSync(cmd[0], cmd.slice(1), { encoding: "utf8" });
|
||||
rmSync(staged, { recursive: true, force: true });
|
||||
if (r.status !== 0) {
|
||||
throw new Error(`${name}: could not be written to ${MANAGED_DIR} (${(r.stderr || r.error?.message || "").trim()}); ` +
|
||||
`the module writes there through the operator account's passwordless sudo`);
|
||||
}
|
||||
return `${name}: written`;
|
||||
};
|
||||
|
||||
/** A tool on the bus, through the runtime; its MCP answer read back as JSON where it is JSON. */
|
||||
const ask: Ask = async (address, args) => {
|
||||
const answer = (await broker().request<Record<string, unknown>, { content?: { text?: string }[]; isError?: boolean }>(address, args)) ?? {};
|
||||
const text = answer.content?.map((c) => c.text ?? "").join("") ?? "";
|
||||
if (answer.isError) throw new Error(`${address}: ${text}`);
|
||||
try {
|
||||
return JSON.parse(text);
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
};
|
||||
|
||||
/** The nodes claude-code runs on, from the controller's list of modules — for the register tool's question. */
|
||||
async function nodesRunningMe(): Promise<string[]> {
|
||||
const out = await ask("mesh-controller.modules", {});
|
||||
const text = typeof out === "string" ? out : String((out as { output?: string })?.output ?? "");
|
||||
const line = text.split("\n").find((l) => /^claude-code\s/.test(l)) ?? "";
|
||||
const on = line.split(" on ")[1] ?? "";
|
||||
return on.trim() === "nothing" ? [] : on.split(",").map((s) => s.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function status(p: Paths): Record<string, unknown> {
|
||||
const creds = readCredentials(join(p.home, ".claude", ".credentials.json"));
|
||||
const grant = grantOf(creds);
|
||||
const managed = ["managed-mcp.json", "managed-settings.json", "CLAUDE.md"].map((f) => {
|
||||
try {
|
||||
return { file: join(MANAGED_DIR, f), fingerprint: fingerprint(readFileSync(join(MANAGED_DIR, f), "utf8")) };
|
||||
} catch {
|
||||
return { file: join(MANAGED_DIR, f), fingerprint: null };
|
||||
}
|
||||
});
|
||||
return {
|
||||
node: p.node,
|
||||
licence: readJson(join(p.state, "licence.json"), null),
|
||||
token: grant ? { fingerprint: fingerprint(grant.accessToken), expiresAt: new Date(grant.expiresAt).toISOString(),
|
||||
loginWaiting: holdsLogin(creds) } : null,
|
||||
managed,
|
||||
registered: Object.keys(registered(p)),
|
||||
};
|
||||
}
|
||||
|
||||
/** The module's MCP servers on the bus (ADR 0201): its own state, which every node of it watches. */
|
||||
const servers = () => state<Record<string, unknown>>("servers") as unknown as ServerState;
|
||||
|
||||
/** What this node takes from that state, kept from the watch. One per process. */
|
||||
let view: ServerView | null = null;
|
||||
const viewOf = (p: Paths) => (view ??= new ServerView(p));
|
||||
|
||||
function tools(p: Paths): ToolDefinition[] {
|
||||
const nodesArg = { type: "string", description: 'more nodes: "all" for every node running claude-code, or a comma-separated list; absent is this node only' };
|
||||
const nodesOf = (v: unknown): Registration["nodes"] =>
|
||||
v === undefined || v === "" ? undefined : v === "all" ? "all" : String(v).split(",").map((s) => s.trim()).filter(Boolean);
|
||||
return [
|
||||
{
|
||||
name: "claude_code_status",
|
||||
description: "Claude Code on this machine as the mesh configured it: the licence it holds and when its token expires, the managed files, the MCP servers registered here. Fingerprints only, never a token.",
|
||||
input: {},
|
||||
run: async () => status(p),
|
||||
},
|
||||
{
|
||||
name: "claude_code_render",
|
||||
description: "Write Claude Code's managed directory now, from the mesh's facts, this module's settings and the servers registered here.",
|
||||
input: {},
|
||||
run: async () => ({ rendered: renderNow(p, writeManaged) }),
|
||||
},
|
||||
{
|
||||
name: "claude_code_pull",
|
||||
description: "Ask the licence manager for this node's current token now and apply it, rather than waiting for its next event.",
|
||||
input: {},
|
||||
run: async () => pull(p, ask, writeManaged),
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_list",
|
||||
description: "The MCP servers registered through this module: those that apply on this node (beside the console, `mesh`, and those set in the module's settings), and every registration on the mesh, by key — `all.<server>` for every node, `<node>.<server>` for one.",
|
||||
input: {},
|
||||
run: async () => ({ here: registered(p), everywhere: await servers().keys() }),
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_register",
|
||||
description: "Register an MCP server with Claude Code on this node, every node, or a list — an http/sse server by url, or a stdio server by command. Kept on the bus, so a node that joins later takes it too. Never put a secret in env or headers: the mesh refuses one.",
|
||||
input: {
|
||||
name: { type: "string", description: "the server's name: letters, digits, - and _" },
|
||||
type: { type: "string", description: "http, sse or stdio (default stdio when a command is given, http when a url is)" },
|
||||
url: { type: "string", description: "an http or sse server's url" },
|
||||
command: { type: "string", description: "a stdio server's program" },
|
||||
args: { type: "array", description: "a stdio server's arguments" },
|
||||
env: { type: "object", description: "a stdio server's environment" },
|
||||
headers: { type: "object", description: "an http server's headers" },
|
||||
nodes: nodesArg,
|
||||
},
|
||||
run: async (a) => {
|
||||
const entry: Record<string, unknown> = { type: a.type ?? (a.url ? "http" : "stdio") };
|
||||
for (const k of ["url", "command", "args", "env", "headers"]) if (a[k] !== undefined) entry[k] = a[k];
|
||||
return registerServer(p, { name: String(a.name ?? ""), entry, nodes: nodesOf(a.nodes) }, servers(), viewOf(p), writeManaged, nodesRunningMe);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "claude_code_mcp_unregister",
|
||||
description: "Remove an MCP server registered through this module, on this node or more.",
|
||||
input: { name: { type: "string", description: "the server's name" }, nodes: nodesArg },
|
||||
run: async (a) => registerServer(p, { name: String(a.name ?? ""), nodes: nodesOf(a.nodes) }, servers(), viewOf(p), writeManaged, nodesRunningMe),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
registerModuleTools("claude-code", (env) => {
|
||||
const p = pathsFrom(env);
|
||||
if (!p) return [];
|
||||
try {
|
||||
keypair(p);
|
||||
for (const line of renderNow(p, writeManaged)) if (!line.endsWith("unchanged")) say(line);
|
||||
} catch (err) {
|
||||
say(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
return tools(p);
|
||||
});
|
||||
|
||||
// Launched by the runtime: the bus is there from the first line (ADR 0198). Outside it — a test, a
|
||||
// build — nothing below runs.
|
||||
const p = process.env.MESH_SERVED_MODULE ? pathsFrom(process.env) : null;
|
||||
if (p) {
|
||||
const loud = (what: string) => (err: unknown) => say(`${what}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
|
||||
void on<{ licence?: string; node?: string }>("claude-licence-manager.licence.*", async (event) => {
|
||||
if (!concerns(p, event.type, event.body ?? {})) return;
|
||||
say(`${event.type} — asking ${SEAT} for this node's token`);
|
||||
say(JSON.stringify(await pull(p, ask, writeManaged).catch((e) => ({ failed: String(e) }))));
|
||||
}).catch(loud("the licence events"));
|
||||
|
||||
// Every node's MCP servers: the whole current set first, then each change (ADR 0201). **Not awaited
|
||||
// where the module is imported**: the runtime waits on the handshake, and a bucket that is not on the
|
||||
// bus yet — or a grant the bus has not reloaded — answers late; awaited here, that left the bundle
|
||||
// unable to answer `initialize` in time and the module unserved (found on its first assignment). So it
|
||||
// watches beside the handshake and asks again until the state answers; until then the managed
|
||||
// directory holds what the file kept from the last run.
|
||||
const watchServers = (attempt = 0): void => {
|
||||
state<Record<string, unknown>>("servers").watch((c) => {
|
||||
try {
|
||||
const done = onServerChange(viewOf(p), c as ServerChange, p, writeManaged);
|
||||
if (done) say(done);
|
||||
} catch (err) {
|
||||
loud(`taking ${c.op} ${c.key}`)(err); // the view took it; the next render writes it
|
||||
}
|
||||
}).then(
|
||||
() => say(`watching the MCP servers${attempt ? ` (after ${attempt} refusal(s))` : ""}`),
|
||||
(err) => {
|
||||
const wait = [2, 5, 10, 30][attempt] ?? 60;
|
||||
say(`the MCP servers cannot be watched yet (${err instanceof Error ? err.message : String(err)}); asking again in ${wait}s`);
|
||||
setTimeout(() => watchServers(attempt + 1), wait * 1000);
|
||||
});
|
||||
};
|
||||
watchServers();
|
||||
|
||||
// Catch up once at start: a node that was off takes its current token now.
|
||||
void pull(p, ask, writeManaged).then((r) => say(`at start: ${JSON.stringify(r)}`), loud("asking for this node's token at start"));
|
||||
|
||||
// A login: a refresh token appears in the credentials file. Polled, because the file is replaced by
|
||||
// rename and a watch on the old inode would go quiet.
|
||||
const credentials = join(p.home, ".claude", ".credentials.json");
|
||||
watchFile(credentials, { interval: 5000 }, () => {
|
||||
void offerLogin(p, ask).then((r) => { if (r) say(`a login here was offered to ${SEAT}: ${JSON.stringify(r)}`); },
|
||||
loud("offering a login to the licence manager"));
|
||||
});
|
||||
}
|
||||
@@ -8,5 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["client.ts", "index.ts", "tools/index.ts"]
|
||||
"include": ["seal.ts", "grant.ts", "identity.ts", "render.ts", "node.ts", "tools/index.ts"]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
# cloudflare-dns's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/cloudflare-dns
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts provisioner/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/cloudflare-dns/dist /app/modules/cloudflare-dns/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/cloudflare-dns/dist/tools/index.js,/app/modules/cloudflare-dns/dist/provisioner/index.js
|
||||
@@ -18,20 +18,13 @@
|
||||
"public-dns": "${dir:grants}/mesh.json"
|
||||
},
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"token": "${dir:state}/token"
|
||||
},
|
||||
"emits": [
|
||||
"record.created",
|
||||
"record.removed"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -50,48 +43,30 @@
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-cloudflare-dns",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:grants}:/grants",
|
||||
"${dir:state}/token:/run/secrets/token:ro",
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLOUDFLARE_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_CLOUDFLARE_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_RECEIVES": "/var/lib/cloudflare-dns/grants/mesh.json"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CLOUDFLARE_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_CLOUDFLARE_CONFIG_FILE": "${dir:state}/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# confluence's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/confluence
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/confluence/dist /app/modules/confluence/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/confluence/dist/tools/index.js
|
||||
@@ -3,16 +3,9 @@
|
||||
"version": "1",
|
||||
"slug": "confl",
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"token": "${dir:state}/token"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -26,46 +19,27 @@
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-runtime-confluence",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:state}/token:/run/secrets/token:ro",
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CONFLUENCE_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_CONFLUENCE_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_CONFLUENCE_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_CONFLUENCE_CONFIG_FILE": "${dir:state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager",
|
||||
"service-manager"
|
||||
"service-manager",
|
||||
"uplink-dhcpcd"
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
|
||||
@@ -59,7 +59,10 @@
|
||||
],
|
||||
"volumes": [
|
||||
"/var/lib/mesh-registry:/var/lib/registry"
|
||||
]
|
||||
],
|
||||
"env": {
|
||||
"REGISTRY_STORAGE_DELETE_ENABLED": "true"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,166 @@
|
||||
# docker
|
||||
|
||||
The container runtime as a module (novox/hq to-be 42 phase 1, item 8; research 027/01–02; ADR 0166,
|
||||
ADR 0207). It claims the node seat `node-container-runtime`. That seat carries no verbs yet: its verbs,
|
||||
and the host creating containers through its holder, wait on ADR 0166's acceptance. Until then the
|
||||
tools below are the module's own.
|
||||
|
||||
## What it declares
|
||||
|
||||
| resource | what | the host's rule |
|
||||
|---|---|---|
|
||||
| `package` | `docker` | installed if absent; never uninstalled when the module goes |
|
||||
| `buildx` | `docker-buildx` | the same. Only the build machine has it today; `docker build` needs it for BuildKit everywhere |
|
||||
| `socket` | `docker.socket` running, enabled at boot | given back as found when the module goes (ADR 0118) |
|
||||
| `prune-service`, `prune-timer` | `/etc/systemd/system/docker-prune.{service,timer}`, written whole | removed with the module |
|
||||
| `prune` | `docker-prune.timer` running, enabled at boot; restarted when either file changes | stopped and disabled with the module (the mesh made the unit) |
|
||||
|
||||
The weekly prune takes **dangling images and build cache unused for a week, and nothing else**. It
|
||||
takes no volume, no container and no image a container uses, so it never touches a container the mesh
|
||||
holds. It runs at idle priority, at a random point in the hour after the weekly mark. A run missed
|
||||
while the machine was off happens at the next boot.
|
||||
|
||||
**Capabilities:** `package-manager`, `service-manager`, `privileged`. It does not declare
|
||||
`container-runtime`: under ADR 0165, which is still proposed, that word means a running daemon, and
|
||||
the module that installs the daemon cannot require it.
|
||||
|
||||
## What it does not declare yet, and why
|
||||
|
||||
Three things this module should own are already declared by other modules on every machine. The
|
||||
controller refuses two modules on one node that declare the same `path`, `unit`, `name` or `package`
|
||||
(`checkResources`, mesh-controller `internal/catalogue/resolve.go`). Declaring any of them here would
|
||||
make the module unassignable everywhere. The refusals were checked against the controller's own
|
||||
check:
|
||||
|
||||
```
|
||||
zsh and docker both declare the name "${machine:account}"
|
||||
dnsmasq and docker both declare the path "/etc/docker/daemon.json"
|
||||
dnsmasq and docker both declare the unit "docker.service"
|
||||
```
|
||||
|
||||
### 1. `/etc/docker/daemon.json` and `docker.service` (issue 190)
|
||||
|
||||
Today the file has three writers. Each writes into it (`into: json`, ADR 0102) and reloads the
|
||||
service:
|
||||
|
||||
- **`dnsmasq`** writes `dns` and `live-restore`, through `dnsmasq.runtime-dns` and `dnsmasq.runtime`.
|
||||
- **The private network**, generated by the controller (`internal/overlay/generator.go`), writes
|
||||
`insecure-registries`. The collision check does not see generated resources.
|
||||
- **Nobody** writes log rotation. One machine has `log-driver` and `log-opts` by hand.
|
||||
|
||||
**The change proposed, in one merge:**
|
||||
|
||||
1. `dnsmasq` drops its `runtime-dns` and `runtime` resources.
|
||||
2. `docker` adds the two resources below:
|
||||
|
||||
```json
|
||||
{"id": "daemon", "type": "file", "path": "/etc/docker/daemon.json", "mode": "0644", "into": "json",
|
||||
"content": "{\"dns\": [\"${machine:address}\"], \"live-restore\": true, \"log-driver\": \"json-file\", \"log-opts\": {\"max-size\": \"100m\", \"max-file\": \"5\"}}\n"},
|
||||
{"id": "runtime", "type": "service", "unit": "docker.service", "state": "running", "boot": "enabled", "reload-on": ["daemon"]}
|
||||
```
|
||||
|
||||
The service is **reloaded, never restarted**: a restart stops every container. The daemon reads
|
||||
`live-restore` on a reload. It reads `dns`, `log-driver` and `log-opts` only at its next start, so
|
||||
they apply then (to containers created afterwards, for the log keys). With `live-restore` on, that
|
||||
start keeps every container running.
|
||||
|
||||
**Why one merge, and only after this module is on every machine:**
|
||||
|
||||
- In one apply, the host first gives back the resources that are no longer declared, then applies
|
||||
the new ones (mesh-host `apply.go`).
|
||||
- `dnsmasq` gives back `dns` and `live-restore` to what they held before it, and `docker` sets them
|
||||
again in the same apply. The daemon is reloaded once, after both steps.
|
||||
- A machine pushed the new `dnsmasq` *without* this module would keep its pre-mesh values for both
|
||||
keys. On one machine that is `live-restore: false`, and the next daemon restart there would stop
|
||||
every container.
|
||||
|
||||
**Later:** the controller hands the registry to this module as a value, and the overlay stops
|
||||
generating its two resources (issue 190, steps 2 and 5). Until then the overlay keeps writing its one
|
||||
key beside this module's. The host merges disjoint keys correctly; the mesh-host `into.go` record is
|
||||
per resource.
|
||||
|
||||
### 2. The operator account's membership of the `docker` group
|
||||
|
||||
The right shape is the host's `user` shape. Its `groups` are additive: the host runs
|
||||
`usermod --append` and never takes a group away.
|
||||
|
||||
```json
|
||||
{"id": "group", "type": "user", "name": "${machine:account}", "groups": ["docker"]}
|
||||
```
|
||||
|
||||
`zsh` already declares a `user` resource for the same account (its login shell). The controller
|
||||
compares `name` across modules, so the two collide.
|
||||
|
||||
**The change proposed (mesh-controller, `checkResources`):** judge a `user` resource by the fields it
|
||||
sets, not by its name:
|
||||
|
||||
- `shell` and `home` stay single-owner;
|
||||
- `groups` may be declared by any number of modules, because the host only adds them.
|
||||
|
||||
Then this module declares the resource above, and no module has to carry another's group.
|
||||
|
||||
Today the operator account is in the group on every machine, by hand. Nothing is lost while it waits.
|
||||
|
||||
## The bootstrap's runtime
|
||||
|
||||
On the machine the mesh was first installed on, the foundation bundle declared `package docker`
|
||||
(`container-runtime`) and `docker.service` running and enabled (`container-runtime-running`). ADR 0207
|
||||
§5 exempts them.
|
||||
|
||||
- The host records them under their bare ids, with origin *carried*. A mesh declaration's orphan pass
|
||||
never sees them (mesh-host `store.go`).
|
||||
- So `docker.package` here is a **second record of the same package**. The apply says "already
|
||||
installed", and neither record ever uninstalls it.
|
||||
- This module does not declare `docker.service` today, so nothing overlaps there. The proposed step
|
||||
1 would add a second record of that unit. Its found state is *running*, because genesis started
|
||||
it, so undeclaring this module would leave the daemon running.
|
||||
|
||||
## Tools
|
||||
|
||||
The tools run as the operator account. If the daemon's socket refuses that account, a call is asked
|
||||
again through `sudo -n` (a process keeps the groups it started with). Every call has a 20 s bound.
|
||||
A failure is an error naming how it failed, never an empty answer.
|
||||
|
||||
**Every container on the machine is in scope.** A container the mesh holds carries the host's label
|
||||
`mesh-host.id` (its value names the assignment), and every answer says `mesh_held`.
|
||||
|
||||
| tool | | what |
|
||||
|---|---|---|
|
||||
| `docker_list` | r | every container: image, state, health, restarts, ports, mounts, compose project, `mesh_held`; filter by owner, state or name |
|
||||
| `docker_inspect` | r | one container whole, **environment values left out** (names kept) |
|
||||
| `docker_logs` | r | the last lines of both streams, merged in order, with timestamps (default 200, at most 2000) |
|
||||
| `docker_stats` | r | CPU, memory, I/O and process count per running container, heaviest first |
|
||||
| `docker_start` / `docker_stop` / `docker_restart` | a | one container. On a mesh-held one, the answer says the host restores its declared state at its next apply |
|
||||
| `docker_top` | r | the processes inside one container |
|
||||
| `docker_images` | r | images, largest first, with the containers using each; `dangling`, `unused` or `used` |
|
||||
| `docker_prune` | a | dangling images and build cache, and stopped containers the mesh does not hold if `containers` is true. **A dry run unless `dry_run` is false. Never a volume** |
|
||||
| `docker_disk_usage` | r | `docker system df -v`: total, active and reclaimable per kind, with the largest of each |
|
||||
| `docker_networks` | r | networks, subnets, and the containers on each |
|
||||
| `docker_volumes` | r | volumes, who mounts each, whether the mesh holds one of them, anonymous or not, and sizes if asked |
|
||||
| `docker_events` | r | the runtime's events over a window ending now (default 60 min, at most 24 h), without exec noise |
|
||||
| `docker_daemon_config` | r | `daemon.json` as on disk, `docker info`'s essentials, and keys the daemon has not taken yet |
|
||||
| `docker_unlabelled` | r | the containers the mesh does not hold: the cleanup list |
|
||||
| `docker_problems` | r | unhealthy, restarting, dead, killed for memory, failed, or restarted five times or more |
|
||||
| `docker_ports` | r | every published port, and the containers on the host's network |
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
go test ./...
|
||||
```
|
||||
|
||||
The tests run against a fake runner and cover:
|
||||
|
||||
- escalation through `sudo -n` on a refused socket, and never as root;
|
||||
- each failure named by its cause;
|
||||
- a name or id never read as an option;
|
||||
- mesh-held marking;
|
||||
- the environment left out of `inspect`;
|
||||
- the restore note on a mesh-held act;
|
||||
- prune being a dry run by default and never reaching a volume, a mesh container or `--volumes`;
|
||||
- the log merge;
|
||||
- size parsing;
|
||||
- what the daemon has not yet taken;
|
||||
- event filtering;
|
||||
- volume ownership;
|
||||
- that the tools served are exactly the manifest's `tools`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,360 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type call struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
// fake answers each command by the first rule whose prefix matches "name arg arg…".
|
||||
type fake struct {
|
||||
rules []rule
|
||||
calls []call
|
||||
}
|
||||
|
||||
type rule struct {
|
||||
prefix string
|
||||
ran Ran
|
||||
}
|
||||
|
||||
func (f *fake) on(prefix string, r Ran) *fake { f.rules = append(f.rules, rule{prefix, r}); return f }
|
||||
|
||||
func (f *fake) run(_ context.Context, name string, args ...string) Ran {
|
||||
f.calls = append(f.calls, call{name, args})
|
||||
line := strings.Join(append([]string{name}, args...), " ")
|
||||
for _, r := range f.rules {
|
||||
if strings.HasPrefix(line, r.prefix) {
|
||||
return r.ran
|
||||
}
|
||||
}
|
||||
return Ran{Status: 1, Stderr: "unexpected: " + line}
|
||||
}
|
||||
|
||||
func (f *fake) ran(prefix string) bool {
|
||||
for _, c := range f.calls {
|
||||
if strings.HasPrefix(strings.Join(append([]string{c.name}, c.args...), " "), prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func client(f *fake, uid int) *Client {
|
||||
return &Client{Run: f.run, UID: uid, ReadFile: func(string) ([]byte, error) { return nil, fs.ErrNotExist },
|
||||
Now: func() time.Time { return time.Date(2026, 10, 4, 12, 0, 0, 0, time.UTC) }}
|
||||
}
|
||||
|
||||
const held = `{"Id":"aaaaaaaaaaaaaaaa","Name":"/mesh-web","Created":"2026-10-01T00:00:00Z","Image":"sha256:img1",
|
||||
"Config":{"Image":"web:1","Labels":{"mesh-host.id":"hello-web.server","mesh-host.spec":"x"},"Env":["PASSWORD=hunter2","PATH=/bin"]},
|
||||
"State":{"Status":"running","Running":true,"StartedAt":"2026-10-01T00:00:01Z","FinishedAt":"0001-01-01T00:00:00Z","Health":{"Status":"healthy"}},
|
||||
"HostConfig":{"RestartPolicy":{"Name":"unless-stopped"},"NetworkMode":"bridge"},
|
||||
"NetworkSettings":{"Ports":{"80/tcp":[{"HostIp":"0.0.0.0","HostPort":"8080"}]}},
|
||||
"Mounts":[{"Type":"volume","Name":"webdata","Destination":"/data","RW":true}]}`
|
||||
|
||||
const stray = `{"Id":"bbbbbbbbbbbbbbbb","Name":"/dev-db","Created":"2026-09-01T00:00:00Z","Image":"sha256:img2",
|
||||
"Config":{"Image":"postgres:16","Labels":{"com.docker.compose.project":"dev","com.docker.compose.project.working_dir":"/home/op/dev"}},
|
||||
"State":{"Status":"exited","ExitCode":1,"FinishedAt":"2026-09-02T00:00:00Z"},
|
||||
"HostConfig":{"RestartPolicy":{"Name":"no"}},"NetworkSettings":{"Ports":{}},
|
||||
"Mounts":[{"Type":"volume","Name":"dbdata","Destination":"/var/lib/postgresql/data","RW":true}]}`
|
||||
|
||||
func machine() *fake {
|
||||
return (&fake{}).
|
||||
on("docker ps --all --quiet --no-trunc", Ran{Stdout: "aaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbb\n"}).
|
||||
on("docker container inspect aaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbb", Ran{Stdout: "[" + held + "," + stray + "]"}).
|
||||
on("docker container inspect mesh-web", Ran{Stdout: "[" + held + "]"}).
|
||||
on("docker container inspect dev-db", Ran{Stdout: "[" + stray + "]"})
|
||||
}
|
||||
|
||||
func TestARefusedSocketIsAskedAgainThroughSudoWithoutAPromptUnlessThisIsRoot(t *testing.T) {
|
||||
denied := Ran{Status: 1, Stderr: "permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get ...: dial unix /var/run/docker.sock: connect: permission denied\n"}
|
||||
f := (&fake{}).on("docker ", denied).on("sudo -n docker info", Ran{Stdout: "{}"})
|
||||
if _, err := client(f, 1000).docker(context.Background(), "info", "--format", "{{json .}}"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.ran("sudo -n docker info --format") {
|
||||
t.Fatalf("not escalated: %+v", f.calls)
|
||||
}
|
||||
f = (&fake{}).on("docker ", denied)
|
||||
if _, err := client(f, 0).docker(context.Background(), "info"); err == nil || f.ran("sudo") {
|
||||
t.Fatalf("root escalated or answered: %v %+v", err, f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailuresAreNamedByHowTheyFailed(t *testing.T) {
|
||||
denied := Ran{Status: 1, Stderr: "permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock\n"}
|
||||
cases := map[string]*fake{
|
||||
"may not escalate without a prompt": (&fake{}).on("docker ", denied).on("sudo ", Ran{Status: 1, Stderr: "sudo: a password is required\n"}),
|
||||
"sudo is not installed": (&fake{}).on("docker ", denied).on("sudo ", Ran{Status: 127, Err: "ENOENT"}),
|
||||
"docker is not installed": (&fake{}).on("docker ", Ran{Status: 127, Err: "ENOENT"}),
|
||||
"daemon is not answering": (&fake{}).on("docker ", Ran{Status: 1, Stderr: "Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?\n"}),
|
||||
"did not answer: no answer within": (&fake{}).on("docker ", Ran{Status: 124, Err: "no answer within 20 s"}),
|
||||
"docker info failed (3): boom": (&fake{}).on("docker ", Ran{Status: 3, Stderr: "boom\n"}),
|
||||
}
|
||||
for want, f := range cases {
|
||||
_, err := client(f, 1000).docker(context.Background(), "info")
|
||||
if err == nil || !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("want %q, got %v", want, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestANameIsNeverAnOption(t *testing.T) {
|
||||
for _, bad := range []string{"--help", "-v", "", "a b", "x;y"} {
|
||||
if _, err := Ref(bad); err == nil {
|
||||
t.Errorf("%q accepted", bad)
|
||||
}
|
||||
}
|
||||
for _, good := range []string{"mesh-web", "aaaaaaaaaaaa", "registry.mesh.internal:5100/x@sha256:abc", "dev_db.1"} {
|
||||
if _, err := Ref(good); err != nil {
|
||||
t.Errorf("%q refused: %v", good, err)
|
||||
}
|
||||
}
|
||||
f := machine()
|
||||
for _, verb := range []string{"start", "stop", "restart"} {
|
||||
if _, err := client(f, 1000).Act(context.Background(), verb, "--rm"); err == nil {
|
||||
t.Errorf("%s took an option", verb)
|
||||
}
|
||||
}
|
||||
if len(f.calls) != 0 {
|
||||
t.Fatalf("docker was called: %+v", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryContainerIsListedAndTheMeshsAreMarked(t *testing.T) {
|
||||
c := client(machine(), 1000)
|
||||
all, err := c.Containers(context.Background(), "", "", "")
|
||||
if err != nil || len(all) != 2 {
|
||||
t.Fatalf("%v %+v", err, all)
|
||||
}
|
||||
web, db := all[1], all[0]
|
||||
if !web.MeshHeld || web.HeldBy != "hello-web.server" || web.Module != "hello-web" || web.Health != "healthy" {
|
||||
t.Errorf("held: %+v", web)
|
||||
}
|
||||
if !reflect.DeepEqual(web.Ports, []string{"0.0.0.0:8080->80/tcp"}) || web.Mounts[0].Name != "webdata" {
|
||||
t.Errorf("ports/mounts: %+v", web)
|
||||
}
|
||||
if db.MeshHeld || db.Compose != "dev" || db.ComposeDir != "/home/op/dev" || db.FinishedAt == "" {
|
||||
t.Errorf("stray: %+v", db)
|
||||
}
|
||||
mesh, _ := c.Containers(context.Background(), "mesh", "", "")
|
||||
other, _ := c.Containers(context.Background(), "other", "", "")
|
||||
if len(mesh) != 1 || mesh[0].Name != "mesh-web" || len(other) != 1 || other[0].Name != "dev-db" {
|
||||
t.Errorf("held filter: %+v / %+v", mesh, other)
|
||||
}
|
||||
if _, err := c.Containers(context.Background(), "mine", "", ""); err == nil {
|
||||
t.Error("an unknown held filter was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoContainersIsAnEmptyListAndAFailureIsAnError(t *testing.T) {
|
||||
got, err := client((&fake{}).on("docker ps", Ran{}), 1000).Containers(context.Background(), "", "", "")
|
||||
if err != nil || got == nil || len(got) != 0 {
|
||||
t.Fatalf("%v %v", got, err)
|
||||
}
|
||||
if _, err := client((&fake{}).on("docker ps", Ran{Status: 1, Stderr: "Cannot connect to the Docker daemon\n"}), 1000).Containers(context.Background(), "", "", ""); err == nil {
|
||||
t.Fatal("a daemon that does not answer read as no containers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectLeavesTheEnvironmentsValuesOut(t *testing.T) {
|
||||
got, err := client(machine(), 1000).Inspect(context.Background(), "mesh-web")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := json.Marshal(got)
|
||||
if strings.Contains(string(b), "hunter2") || !strings.Contains(string(b), `"PASSWORD"`) || got["mesh_held"] != true {
|
||||
t.Fatalf("%s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActingOnAMeshContainerSaysTheHostRestoresIt(t *testing.T) {
|
||||
f := machine().on("docker stop", Ran{}).on("docker start", Ran{})
|
||||
got, err := client(f, 1000).Act(context.Background(), "stop", "mesh-web")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.ran("docker stop --time 10 mesh-web") || got["mesh_held"] != true || !strings.Contains(got["note"].(string), "host restores") {
|
||||
t.Fatalf("%v %+v", got, f.calls)
|
||||
}
|
||||
got, _ = client(f, 1000).Act(context.Background(), "start", "dev-db")
|
||||
if _, noted := got["note"]; noted || got["mesh_held"] != false {
|
||||
t.Fatalf("a stray was noted: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPruneIsADryRunByDefaultAndNeverTouchesAVolumeOrAMeshContainer(t *testing.T) {
|
||||
f := machine().
|
||||
on("docker image ls --no-trunc --filter dangling=true", Ran{Stdout: `{"ID":"sha256:dead","Size":"1.5GB"}` + "\n"}).
|
||||
on("docker system df --format", Ran{Stdout: `{"Type":"Build Cache","TotalCount":"3","Size":"2GB","Reclaimable":"1GB"}` + "\n"}).
|
||||
on("docker image prune", Ran{Stdout: "Deleted Images:\nx\n\nTotal reclaimed space: 1.5GB\n"}).
|
||||
on("docker builder prune", Ran{Stdout: "Total:\t1GB\n"}).
|
||||
on("docker container rm", Ran{})
|
||||
c := client(f, 1000)
|
||||
got, err := c.Prune(context.Background(), PruneAsk{Images: true, BuildCache: true, Containers: true, DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.ran("docker image prune") || f.ran("docker builder prune") || f.ran("docker container rm") {
|
||||
t.Fatalf("a dry run removed something: %+v", f.calls)
|
||||
}
|
||||
if got["images"].(map[string]any)["dangling"] != 1 || !reflect.DeepEqual(got["containers"].(map[string]any)["stopped_not_held"], []string{"dev-db"}) {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
got, err = c.Prune(context.Background(), PruneAsk{Images: true, BuildCache: true, Containers: true, OlderThanH: 24})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.ran("docker image prune --force --filter until=24h") || !f.ran("docker builder prune --force --filter until=24h") || !f.ran("docker container rm dev-db") {
|
||||
t.Fatalf("not pruned: %+v", f.calls)
|
||||
}
|
||||
for _, c := range f.calls {
|
||||
line := strings.Join(c.args, " ")
|
||||
if strings.Contains(line, "volume") || strings.Contains(line, "mesh-web") && c.args[0] != "container" || strings.Contains(line, "--volumes") || strings.Contains(line, "--all") && c.args[0] != "ps" {
|
||||
t.Errorf("prune reached too far: %s", line)
|
||||
}
|
||||
}
|
||||
if got["images"].(map[string]any)["reclaimed"] != "1.5GB" || got["build_cache"].(map[string]any)["reclaimed"] != "1GB" {
|
||||
t.Errorf("reclaimed: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogsMergeBothStreamsInOrderAndKeepTheTail(t *testing.T) {
|
||||
f := (&fake{}).on("docker logs", Ran{Stdout: "2026-10-04T10:00:01Z out one\n2026-10-04T10:00:03Z out two\n", Stderr: "2026-10-04T10:00:02Z err one\n"})
|
||||
got, err := client(f, 1000).Logs(context.Background(), "web", 2, "30m")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got["lines"], []string{"2026-10-04T10:00:02Z err one", "2026-10-04T10:00:03Z out two"}) {
|
||||
t.Fatalf("%v", got["lines"])
|
||||
}
|
||||
if !f.ran("docker logs --timestamps --tail 2 --since 30m web") {
|
||||
t.Fatalf("%+v", f.calls)
|
||||
}
|
||||
if _, err := client(f, 1000).Logs(context.Background(), "web", 2, "--follow"); err == nil {
|
||||
t.Fatal("since took an option")
|
||||
}
|
||||
f = (&fake{}).on("docker logs", Ran{Status: 1, Stderr: "Error response from daemon: No such container: nope\n"})
|
||||
if _, err := client(f, 1000).Logs(context.Background(), "nope", 2, ""); err == nil {
|
||||
t.Fatal("a missing container read as no lines")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizesAreReadAsDockerPrintsThem(t *testing.T) {
|
||||
for in, want := range map[string]int64{"0B": 0, "55.63GB": 55630000000, "33.2MiB": 34812723, "1.5kB": 1500, "12MB (34%)": 12000000, "N/A": -1} {
|
||||
if got := Bytes(in); got != want {
|
||||
t.Errorf("%s: %d, want %d", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaemonConfigSaysWhatTheDaemonHasNotTakenYet(t *testing.T) {
|
||||
f := (&fake{}).on("docker info", Ran{Stdout: `{"ServerVersion":"29.8.2","LiveRestoreEnabled":false,"LoggingDriver":"json-file","RegistryConfig":{"IndexConfigs":{"docker.io":{"Secure":true},"registry.mesh.internal:5100":{"Secure":false}}}}`})
|
||||
c := client(f, 1000)
|
||||
c.ReadFile = func(string) ([]byte, error) {
|
||||
return []byte(`{"live-restore": true, "dns": ["10.0.0.1"], "log-driver": "local"}`), nil
|
||||
}
|
||||
got, err := c.DaemonConfig(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending := strings.Join(got["pending"].([]string), "\n")
|
||||
if !strings.Contains(pending, "live-restore is true in the file and false") || !strings.Contains(pending, "log-driver is local") {
|
||||
t.Errorf("pending: %s", pending)
|
||||
}
|
||||
if !reflect.DeepEqual(got["daemon"].(map[string]any)["InsecureRegistries"], []string{"registry.mesh.internal:5100"}) {
|
||||
t.Errorf("registries: %v", got["daemon"])
|
||||
}
|
||||
if !reflect.DeepEqual(got["read_only_at_start"], []string{"dns", "log-driver"}) {
|
||||
t.Errorf("start-only: %v", got["read_only_at_start"])
|
||||
}
|
||||
c.ReadFile = func(string) ([]byte, error) { return nil, os.ErrNotExist }
|
||||
got, _ = c.DaemonConfig(context.Background())
|
||||
if !strings.HasPrefix(got["file_state"].(string), "absent") {
|
||||
t.Errorf("absent: %v", got["file_state"])
|
||||
}
|
||||
c.ReadFile = func(string) ([]byte, error) { return nil, errors.New("permission denied") }
|
||||
got, _ = c.DaemonConfig(context.Background())
|
||||
if !strings.HasPrefix(got["file_state"].(string), "unreadable") {
|
||||
t.Errorf("unreadable: %v", got["file_state"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventsAreABoundedWindowWithoutExecNoise(t *testing.T) {
|
||||
out := `{"Type":"container","Action":"exec_start: pg_isready","Actor":{"ID":"aaaaaaaaaaaaaaaa","Attributes":{"name":"db"}},"timeNano":1}
|
||||
{"Type":"container","Action":"die","Actor":{"ID":"aaaaaaaaaaaaaaaa","Attributes":{"name":"web","mesh-host.id":"hello-web.server","exitCode":"137"}},"timeNano":2}
|
||||
`
|
||||
f := (&fake{}).on("docker events", Ran{Stdout: out})
|
||||
got, err := client(f, 1000).Events(context.Background(), 30, "container", 10, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
evs := got["events"].([]map[string]any)
|
||||
if len(evs) != 1 || evs[0]["action"] != "die" || evs[0]["mesh_held"] != true || evs[0]["exit_code"] != "137" {
|
||||
t.Fatalf("%v", evs)
|
||||
}
|
||||
if !f.ran("docker events --since 30m --until 0s --format {{json .}} --filter type=container") {
|
||||
t.Fatalf("%+v", f.calls)
|
||||
}
|
||||
if _, err := client(f, 1000).Events(context.Background(), 30, "secret", 10, false); err == nil {
|
||||
t.Fatal("an unknown type was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestVolumesSayWhoMountsThemAndWhetherTheMeshDoes(t *testing.T) {
|
||||
f := machine().
|
||||
on("docker volume ls --quiet", Ran{Stdout: "webdata\ndbdata\nloose\n"}).
|
||||
on("docker volume inspect", Ran{Stdout: `[{"Name":"webdata","Driver":"local"},{"Name":"dbdata","Driver":"local"},{"Name":"loose","Driver":"local","Labels":{"com.docker.volume.anonymous":""}}]`})
|
||||
got, err := client(f, 1000).Volumes(context.Background(), false, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vols := got["volumes"].([]map[string]any)
|
||||
if vols[0]["mesh_held"] != true || vols[1]["mesh_held"] != false || len(vols[2]["mounted_by"].([]map[string]any)) != 0 || vols[2]["anonymous"] != true {
|
||||
t.Fatalf("%v", vols)
|
||||
}
|
||||
got, _ = client(f, 1000).Volumes(context.Background(), true, false)
|
||||
if got["count"] != 1 {
|
||||
t.Fatalf("unmounted: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagesNameTheirUsers(t *testing.T) {
|
||||
f := machine().on("docker image ls", Ran{Stdout: `{"ID":"sha256:img1","Repository":"web","Tag":"1","Size":"100MB"}
|
||||
{"ID":"sha256:img3","Repository":"<none>","Tag":"<none>","Size":"2GB"}
|
||||
`})
|
||||
got, err := client(f, 1000).Images(context.Background(), "", "", 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imgs := got["images"].([]Image)
|
||||
if imgs[0].ID != "sha256:img3" || !imgs[0].Dangling || imgs[1].UsedBy[0] != "mesh-web" || !imgs[1].MeshUsed {
|
||||
t.Fatalf("%+v", imgs)
|
||||
}
|
||||
got, _ = client(f, 1000).Images(context.Background(), "unused", "", 10)
|
||||
if got["count"] != 1 {
|
||||
t.Fatalf("unused: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProblemsNameWhyAndUnlabelledIsTheCleanupList(t *testing.T) {
|
||||
c := client(machine(), 1000)
|
||||
p, err := c.Problems(context.Background())
|
||||
if err != nil || len(p) != 1 || p[0]["name"] != "dev-db" || p[0]["why"].([]string)[0] != "exited 1" {
|
||||
t.Fatalf("%v %v", p, err)
|
||||
}
|
||||
u, err := c.Unlabelled(context.Background())
|
||||
if err != nil || u["count"] != 1 {
|
||||
t.Fatalf("%v %v", u, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
// docker's Go tools bundle (novox/hq ADR 0188, ADR 0193): a process the node's tool runtime launches
|
||||
// and speaks MCP over stdio to, through the Go SDK. It answers for every container on this machine —
|
||||
// the mesh's and every other — and for the runtime's images, networks, volumes, events and
|
||||
// configuration. It runs as the operator account (ADR 0175 §4); docker.go says how it reaches the
|
||||
// daemon's socket. The host applies the module's resources; these tools answer about the runtime.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// An empty name serves as the module the runtime names (MESH_SERVED_MODULE): docker.
|
||||
if err := stdio.Serve("", tools(NewClient())); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var containerArg = map[string]any{"type": "string", "description": "the container's name or id"}
|
||||
|
||||
func tools(c *Client) []stdio.Tool {
|
||||
ctx := context.Background()
|
||||
act := func(verb, description string) stdio.Tool {
|
||||
return stdio.Tool{
|
||||
Name: "docker_" + verb, Description: description,
|
||||
Input: map[string]any{"container": containerArg},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
ref, err := text(args, "container")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Act(ctx, verb, ref)
|
||||
},
|
||||
}
|
||||
}
|
||||
return []stdio.Tool{
|
||||
{
|
||||
Name: "docker_list",
|
||||
Description: "Every container on this machine — the mesh's and every other — with its image, state, health, restarts, " +
|
||||
"published ports, mounts, compose project, and mesh_held/held_by (the assignment that holds it).",
|
||||
Input: map[string]any{
|
||||
"held": map[string]any{"type": "string", "enum": []string{"all", "mesh", "other"}, "description": "whose: all (default), the mesh's, or the others"},
|
||||
"state": map[string]any{"type": "string", "description": "only containers in this state (running, exited, created, restarting, paused, dead)"},
|
||||
"match": map[string]any{"type": "string", "description": "only containers whose name or image contains this"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
list, err := c.Containers(ctx, optional(args, "held"), optional(args, "state"), optional(args, "match"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"count": len(list), "containers": list}, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_inspect",
|
||||
Description: "One container whole, as docker inspects it, with mesh_held; its environment's values are left out (names kept), because that is where a container's secrets are.",
|
||||
Input: map[string]any{"container": containerArg},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
ref, err := text(args, "container")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Inspect(ctx, ref)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_logs",
|
||||
Description: "The last lines one container wrote, both streams merged in order, each with its timestamp (default 200, at most 2000 lines; a line is cut at 4 KiB).",
|
||||
Input: map[string]any{
|
||||
"container": containerArg,
|
||||
"lines": map[string]any{"type": "integer", "description": "how many lines from the end (default 200, at most 2000)"},
|
||||
"since": map[string]any{"type": "string", "description": "only lines since then: a duration such as 30m or 2h, or a time"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
ref, err := text(args, "container")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := bounded(args, "lines", 200, 2000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Logs(ctx, ref, n, optional(args, "since"))
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_stats",
|
||||
Description: "What the running containers use now — CPU, memory, network and disk I/O, processes — the heaviest by memory first; or one container's.",
|
||||
Input: map[string]any{"container": map[string]any{"type": "string", "description": "one container (optional)"}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
stats, err := c.Stats(ctx, optional(args, "container"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"count": len(stats), "containers": stats}, nil
|
||||
},
|
||||
},
|
||||
act("start", "Start one container. A container the mesh holds is started too, and the answer says the host restores what its declaration says at its next apply."),
|
||||
act("stop", "Stop one container (ten seconds, then killed). For a container the mesh holds, the answer says the host will start it again at its next apply if its declaration says running."),
|
||||
act("restart", "Restart one container (ten seconds to stop, then killed); the answer says whether the mesh holds it."),
|
||||
{
|
||||
Name: "docker_top",
|
||||
Description: "The processes running inside one container: pid, user, elapsed time, CPU, resident memory and command.",
|
||||
Input: map[string]any{"container": containerArg},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
ref, err := text(args, "container")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Top(ctx, ref)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_images",
|
||||
Description: "The images on this machine, the largest first, each with its size and the containers using it (and whether one of them is the mesh's). " +
|
||||
"filter: all, dangling, unused or used.",
|
||||
Input: map[string]any{
|
||||
"filter": map[string]any{"type": "string", "enum": []string{"all", "dangling", "unused", "used"}, "description": "which images (default all)"},
|
||||
"match": map[string]any{"type": "string", "description": "only images whose repository:tag contains this"},
|
||||
"limit": map[string]any{"type": "integer", "description": "how many to show (default 100, at most 1000); count says how many matched"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
n, err := bounded(args, "limit", 100, 1000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Images(ctx, optional(args, "filter"), optional(args, "match"), n)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_prune",
|
||||
Description: "Reclaim space: dangling images and unused build cache, and — only when containers is true — stopped containers the mesh does not hold. " +
|
||||
"Never a volume, never a container the mesh holds, never an image a container uses. A dry run by default: it lists what would go; dry_run false removes it.",
|
||||
Input: map[string]any{
|
||||
"dry_run": map[string]any{"type": "boolean", "description": "list only (default true)"},
|
||||
"images": map[string]any{"type": "boolean", "description": "dangling images (default true)"},
|
||||
"build_cache": map[string]any{"type": "boolean", "description": "build cache nothing refers to (default true)"},
|
||||
"containers": map[string]any{"type": "boolean", "description": "stopped containers the mesh does not hold (default false); what they mounted is kept"},
|
||||
"older_than_hours": map[string]any{"type": "integer", "description": "only what is older than this many hours (default 0: any age)"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
older := 0
|
||||
if v, ok := args["older_than_hours"]; ok && v != nil && v != float64(0) {
|
||||
n, err := bounded(args, "older_than_hours", 0, 24*365)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
older = n
|
||||
}
|
||||
return c.Prune(ctx, PruneAsk{
|
||||
DryRun: flag(args, "dry_run", true), Images: flag(args, "images", true), BuildCache: flag(args, "build_cache", true),
|
||||
Containers: flag(args, "containers", false), OlderThanH: older,
|
||||
})
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_disk_usage",
|
||||
Description: "What the runtime takes on disk (docker system df -v): per kind — images, containers, volumes, build cache — the total, the active and the reclaimable, and the largest of each.",
|
||||
Input: map[string]any{"top": map[string]any{"type": "integer", "description": "how many of the largest per kind (default 10, at most 100)"}},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
n, err := bounded(args, "top", 10, 100)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.DiskUsage(ctx, n)
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_networks",
|
||||
Description: "Every network the runtime has: driver, scope, subnets and gateway, and the running containers on it with their addresses and whether the mesh holds them.",
|
||||
Run: func(map[string]any) (any, error) { return c.Networks(ctx) },
|
||||
},
|
||||
{
|
||||
Name: "docker_volumes",
|
||||
Description: "Every volume with the containers mounting it, whether the mesh holds any of them, whether it is anonymous, its compose project, and — when sizes is true (slower) — its size.",
|
||||
Input: map[string]any{
|
||||
"unmounted": map[string]any{"type": "boolean", "description": "only volumes no container mounts (default false)"},
|
||||
"sizes": map[string]any{"type": "boolean", "description": "measure each volume (default false: it walks every volume)"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
return c.Volumes(ctx, flag(args, "unmounted", false), flag(args, "sizes", false))
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_events",
|
||||
Description: "What the runtime did in a window ending now (default the last 60 minutes, at most 24 hours): containers created, started, died, health changes, images pulled — with mesh_held. Exec events are left out unless asked.",
|
||||
Input: map[string]any{
|
||||
"minutes": map[string]any{"type": "integer", "description": "how far back (default 60, at most 1440)"},
|
||||
"type": map[string]any{"type": "string", "description": "only one kind: container, image, network, volume, daemon, plugin or builder"},
|
||||
"limit": map[string]any{"type": "integer", "description": "the latest this many (default 200, at most 2000)"},
|
||||
"execs": map[string]any{"type": "boolean", "description": "include exec_* events (default false: health checks make many)"},
|
||||
},
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
minutes, err := bounded(args, "minutes", 60, 1440)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
limit, err := bounded(args, "limit", 200, 2000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Events(ctx, minutes, optional(args, "type"), limit, flag(args, "execs", false))
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_daemon_config",
|
||||
Description: "The runtime's configuration: /etc/docker/daemon.json as it is on disk, the daemon's essentials as it runs now (docker info: version, storage and logging drivers, " +
|
||||
"live restore, root directory, insecure registries, warnings), and where the two differ — keys a reload or only a restart would take.",
|
||||
Run: func(map[string]any) (any, error) { return c.DaemonConfig(ctx) },
|
||||
},
|
||||
{
|
||||
Name: "docker_unlabelled",
|
||||
Description: "The containers the mesh does not hold — the cleanup list — each with its image, state, compose project and directory, ports and mounts.",
|
||||
Run: func(map[string]any) (any, error) { return c.Unlabelled(ctx) },
|
||||
},
|
||||
{
|
||||
Name: "docker_problems",
|
||||
Description: "Every container that is not well: unhealthy, restarting, dead, killed for memory, exited with a failure, or restarted five times or more — with whether the mesh holds it.",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
p, err := c.Problems(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"count": len(p), "containers": p}, nil
|
||||
},
|
||||
},
|
||||
{
|
||||
Name: "docker_ports",
|
||||
Description: "Every port the containers publish on this machine (address:port -> container port), and the containers on the host's network, which publish whatever they listen on.",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
p, err := c.Ports(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"count": len(p), "ports": p}, nil
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func text(args map[string]any, key string) (string, error) {
|
||||
s, _ := args[key].(string)
|
||||
if s = strings.TrimSpace(s); s == "" {
|
||||
return "", fmt.Errorf("%s is required", key)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func optional(args map[string]any, key string) string {
|
||||
s, _ := args[key].(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func flag(args map[string]any, key string, def bool) bool {
|
||||
if b, ok := args[key].(bool); ok {
|
||||
return b
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// bounded is a whole number argument, defaulted when absent and held to a ceiling.
|
||||
func bounded(args map[string]any, key string, def, most int) (int, error) {
|
||||
v, ok := args[key]
|
||||
if !ok || v == nil {
|
||||
return def, nil
|
||||
}
|
||||
f, ok := v.(float64)
|
||||
if !ok || f != math.Trunc(f) || f < 1 {
|
||||
return 0, fmt.Errorf("%s must be a whole number of at least 1", key)
|
||||
}
|
||||
return int(math.Min(f, float64(most))), nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Ran is what a command did: its output, its exit status, and why it never ran to an answer.
|
||||
type Ran struct {
|
||||
Stdout string
|
||||
Stderr string
|
||||
Status int
|
||||
// Err is "ENOENT" when the program is not installed, or says it was ended for taking too long.
|
||||
Err string
|
||||
}
|
||||
|
||||
// Runner runs one command, so every tool can be tested without a daemon.
|
||||
type Runner func(ctx context.Context, name string, args ...string) Ran
|
||||
|
||||
// CallTimeout is how long one docker command may take: below the runtime's thirty-second call
|
||||
// limit, so a daemon that hangs is answered as such rather than as a call the runtime gave up on.
|
||||
const CallTimeout = 20 * time.Second
|
||||
|
||||
// ExecRunner runs a command on this machine, bounded by CallTimeout.
|
||||
func ExecRunner(ctx context.Context, name string, args ...string) Ran {
|
||||
ctx, cancel := context.WithTimeout(ctx, CallTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
var out, errb bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errb
|
||||
err := cmd.Run()
|
||||
r := Ran{Stdout: out.String(), Stderr: errb.String()}
|
||||
var exitErr *exec.ExitError
|
||||
switch {
|
||||
case errors.Is(ctx.Err(), context.DeadlineExceeded):
|
||||
r.Status, r.Err = 124, fmt.Sprintf("no answer within %d s", int(CallTimeout/time.Second))
|
||||
case errors.Is(err, exec.ErrNotFound):
|
||||
r.Status, r.Err = 127, "ENOENT"
|
||||
case errors.As(err, &exitErr):
|
||||
r.Status = exitErr.ExitCode()
|
||||
case err != nil:
|
||||
r.Status, r.Err = 1, err.Error()
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func firstLine(s string) string {
|
||||
for _, l := range strings.Split(s, "\n") {
|
||||
if l = strings.TrimSpace(l); l != "" {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTheToolsServedAreTheToolsTheManifestNames(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Tools []string `json:"tools"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
served := []string{}
|
||||
for _, tool := range tools(client(&fake{}, 1000)) {
|
||||
if !strings.HasPrefix(tool.Name, "docker_") || tool.Description == "" || tool.Run == nil {
|
||||
t.Errorf("tool %q", tool.Name)
|
||||
}
|
||||
served = append(served, tool.Name)
|
||||
}
|
||||
sort.Strings(served)
|
||||
listed := append([]string{}, m.Tools...)
|
||||
sort.Strings(listed)
|
||||
if !reflect.DeepEqual(served, listed) {
|
||||
t.Fatalf("served %v, manifest %v", served, listed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNumbersAreDefaultedAndBounded(t *testing.T) {
|
||||
if n, _ := bounded(map[string]any{}, "lines", 200, 2000); n != 200 {
|
||||
t.Error(n)
|
||||
}
|
||||
if n, _ := bounded(map[string]any{"lines": float64(99999)}, "lines", 200, 2000); n != 2000 {
|
||||
t.Error(n)
|
||||
}
|
||||
for _, bad := range []any{float64(0), float64(-1), float64(1.5), "10"} {
|
||||
if _, err := bounded(map[string]any{"lines": bad}, "lines", 200, 2000); err == nil {
|
||||
t.Errorf("%v accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStopFromTheToolNeedsAContainer(t *testing.T) {
|
||||
for _, tool := range tools(client(&fake{}, 1000)) {
|
||||
if tool.Name == "docker_stop" {
|
||||
if _, err := tool.Run(map[string]any{}); err == nil {
|
||||
t.Fatal("a stop without a container was accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
module docker
|
||||
|
||||
go 1.22
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.1.6
|
||||
@@ -0,0 +1,2 @@
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6 h1:9qzdYONYbJdWcu6sxQcq9v1LI0JxcfkiKYkMUzJSkVQ=
|
||||
git.novox.be/novox/mesh-sdk/go v0.1.6/go.mod h1:GFuZUElBZ9A++mxgIKo97aXXo+kV0uJ/UkbhQPPIbrY=
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"module": "docker",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"package-manager",
|
||||
"service-manager",
|
||||
"privileged"
|
||||
],
|
||||
"claims": [
|
||||
{
|
||||
"name": "node-container-runtime",
|
||||
"scope": "node"
|
||||
}
|
||||
],
|
||||
"tools": [
|
||||
"docker_list",
|
||||
"docker_inspect",
|
||||
"docker_logs",
|
||||
"docker_stats",
|
||||
"docker_start",
|
||||
"docker_stop",
|
||||
"docker_restart",
|
||||
"docker_top",
|
||||
"docker_images",
|
||||
"docker_prune",
|
||||
"docker_disk_usage",
|
||||
"docker_networks",
|
||||
"docker_volumes",
|
||||
"docker_events",
|
||||
"docker_daemon_config",
|
||||
"docker_unlabelled",
|
||||
"docker_problems",
|
||||
"docker_ports"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "package",
|
||||
"type": "package",
|
||||
"package": "docker"
|
||||
},
|
||||
{
|
||||
"id": "buildx",
|
||||
"type": "package",
|
||||
"package": "docker-buildx"
|
||||
},
|
||||
{
|
||||
"id": "socket",
|
||||
"type": "service",
|
||||
"unit": "docker.socket",
|
||||
"state": "running",
|
||||
"boot": "enabled"
|
||||
},
|
||||
{
|
||||
"id": "prune-service",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/docker-prune.service",
|
||||
"mode": "0644",
|
||||
"content": "# Generated by the mesh. Do not edit — module docker writes this file and replaces it at every push.\n[Unit]\nDescription=Prune dangling images and unused build cache (the mesh's docker module)\n# Never volumes, never a container, never an image a container uses: dangling\n# images and build cache nothing refers to, unused for a week. What a person\n# prunes beyond that is docker_prune's, by hand.\nAfter=docker.service\nConditionPathExists=/run/docker.sock\n\n[Service]\nType=oneshot\nNice=19\nIOSchedulingClass=idle\nExecStart=/usr/bin/docker image prune --force --filter until=168h\nExecStart=/usr/bin/docker builder prune --force --filter until=168h\n"
|
||||
},
|
||||
{
|
||||
"id": "prune-timer",
|
||||
"type": "file",
|
||||
"path": "/etc/systemd/system/docker-prune.timer",
|
||||
"mode": "0644",
|
||||
"content": "# Generated by the mesh. Do not edit — module docker writes this file and replaces it at every push.\n[Unit]\nDescription=Weekly prune of dangling images and unused build cache (the mesh's docker module)\n\n[Timer]\nOnCalendar=weekly\nRandomizedDelaySec=1h\nPersistent=true\n\n[Install]\nWantedBy=timers.target\n"
|
||||
},
|
||||
{
|
||||
"id": "prune",
|
||||
"type": "service",
|
||||
"unit": "docker-prune.timer",
|
||||
"state": "running",
|
||||
"boot": "enabled",
|
||||
"restart-on": [
|
||||
"prune-service",
|
||||
"prune-timer"
|
||||
]
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "go",
|
||||
"system": "arch",
|
||||
"from": "cmd/docker-tools",
|
||||
"binary": "docker-tools",
|
||||
"loads": [
|
||||
"docker-tools"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+221
-36
@@ -1,51 +1,236 @@
|
||||
// fail2ban's own code, in the module (novox/hq ADR 0039). The jails and the daemon are declared
|
||||
// resources — the mesh writes /etc/fail2ban/jail.d/* and keeps fail2ban.service running (see
|
||||
// module.json). This code exists only to read and steer the *live* state the daemon owns at
|
||||
// runtime: which IPs are banned right now, and the manual ban/unban an operator reaches for. That
|
||||
// state (the running bans, /var/lib/fail2ban's sqlite) is fail2ban's, not the mesh's — the mesh
|
||||
// reconciles the config, never the ban list.
|
||||
// fail2ban's own code, in the module (novox/hq ADR 0039). The jails are composed by the mesh from
|
||||
// the modules a machine runs (to-be 31) and written as declared resources; the daemon is kept
|
||||
// running by one. This code exists only to read and steer the *live* state the daemon owns: who is
|
||||
// banned now and until when, and the ban or release an operator asks for — the node-intrusion-
|
||||
// prevention seat's four verbs (ADR 0179). The daemon's state is fail2ban's, not the mesh's: the
|
||||
// mesh composes the jails and never writes the ban list.
|
||||
//
|
||||
// Spoken through fail2ban-client over the daemon's socket. Client and daemon come from the one
|
||||
// package this module declares on the machine, and the socket is root's: root is the module's
|
||||
// concern (ADR 0175 §4), and the runtime loading this bundle runs as the operator's account (to-be
|
||||
// 38 WP4), so the client is run through sudo without a prompt where the account is not root.
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { accessSync, constants } from "node:fs";
|
||||
import { isIP } from "node:net";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
const run = promisify(execFile);
|
||||
const execFileP = promisify(execFile);
|
||||
|
||||
/** A command runner, so the verbs can be tested without a daemon. */
|
||||
export type Runner = (cmd: string, args: string[]) => Promise<string>;
|
||||
|
||||
/** The command as it is run: as given when this process is root, else through sudo without a
|
||||
* prompt. The daemon's socket answers only to root. */
|
||||
export function escalated(cmd: string, args: string[], uid: number | undefined = process.getuid?.()): [string, string[]] {
|
||||
if (uid === 0) return [cmd, args];
|
||||
return ["sudo", ["-n", cmd, ...args]];
|
||||
}
|
||||
|
||||
/** Whether a tool is on this machine: an executable of that name on the path, or where the
|
||||
* system keeps its administration. */
|
||||
export function installed(tool: string, path: string = process.env.PATH ?? ""): boolean {
|
||||
const dirs = [...path.split(delimiter), "/usr/sbin", "/sbin", "/usr/bin"].filter((d) => d !== "");
|
||||
return dirs.some((dir) => {
|
||||
try {
|
||||
accessSync(join(dir, tool), constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const execRunner: Runner = async (cmd, args) => {
|
||||
if (!installed(cmd)) throw new Error(`${cmd} is not installed on this machine`);
|
||||
const [program, argv] = escalated(cmd, args);
|
||||
try {
|
||||
const { stdout } = await execFileP(program, argv, { maxBuffer: 16 * 1024 * 1024 });
|
||||
return stdout;
|
||||
} catch (err) {
|
||||
const e = err as { code?: string | number; stderr?: string; stdout?: string; message?: string };
|
||||
const said = `${e.stdout ?? ""}${e.stderr ?? ""}`.trim();
|
||||
// What failed is named by how it failed: sudo missing is a spawn error, sudo refusing speaks
|
||||
// on its own stderr line, and the rest is the client's own answer.
|
||||
if (program === "sudo") {
|
||||
if (e.code === "ENOENT") throw new Error(`${cmd} needs root, and sudo is not installed here for the runtime's account to escalate with`);
|
||||
if (/^sudo:/m.test(said)) throw new Error(`${cmd} needs root and the runtime's account may not run it without a prompt: ${said}`);
|
||||
}
|
||||
if (/Failed to access socket path|Is fail2ban running|Permission denied to socket/i.test(said)) {
|
||||
throw new Error("fail2ban is not running on this machine, or its socket does not answer the runtime's account");
|
||||
}
|
||||
// fail2ban-client's own last line is the one a person reads ("Sorry but the jail 'x' does not exist").
|
||||
const lines = said.split("\n").map((l) => l.trim()).filter(Boolean);
|
||||
throw new Error(lines.length ? lines[lines.length - 1] : (e.message ?? `${cmd} failed`));
|
||||
}
|
||||
};
|
||||
|
||||
/** One jail as the daemon reports it. */
|
||||
export interface JailStatus {
|
||||
jail: string;
|
||||
/** What the jail is reading: files or journal matches, as fail2ban names them. */
|
||||
watching: string[];
|
||||
/** Addresses with failures counted against them right now, and all failures since the jail started. */
|
||||
failing: { now: number; total: number };
|
||||
/** Addresses held right now, and all bans since the jail started. */
|
||||
banned: { now: number; total: number; addresses: string[] };
|
||||
}
|
||||
|
||||
/** One ban as the daemon holds it. */
|
||||
export interface Ban {
|
||||
ip: string;
|
||||
jail: string;
|
||||
/** When the ban was placed, in the machine's local time as fail2ban prints it. */
|
||||
since: string;
|
||||
/** When the ban ends; "never" for a permanent ban. */
|
||||
until: string;
|
||||
}
|
||||
|
||||
export interface JailSettings {
|
||||
jail: string;
|
||||
bantime: string;
|
||||
findtime: string;
|
||||
maxretry: number;
|
||||
ignoreip: string[];
|
||||
actions: string[];
|
||||
/** The log files the jail reads, when it reads files. */
|
||||
logpath: string[];
|
||||
/** The journal match the jail reads, when it reads the journal. */
|
||||
journalmatch: string;
|
||||
}
|
||||
|
||||
export class Fail2banClient {
|
||||
static fromEnv(_env: NodeJS.ProcessEnv = process.env): Fail2banClient {
|
||||
private readonly run: Runner;
|
||||
|
||||
constructor(run: Runner = execRunner) {
|
||||
this.run = run;
|
||||
}
|
||||
|
||||
/** The daemon as this machine has it, through its own client. */
|
||||
static onThisMachine(): Fail2banClient {
|
||||
return new Fail2banClient();
|
||||
}
|
||||
|
||||
/** Overview of every jail, or the detailed status of one — currently-banned IPs and totals. */
|
||||
async status(jail?: string): Promise<string> {
|
||||
private client(...args: string[]): Promise<string> {
|
||||
return this.run("fail2ban-client", args);
|
||||
}
|
||||
|
||||
/** The jails the daemon runs, by name. */
|
||||
async jails(): Promise<string[]> {
|
||||
const out = await this.client("status");
|
||||
const m = out.match(/Jail list:\s*(.*)/);
|
||||
if (!m) return [];
|
||||
return m[1].split(",").map((j) => j.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
/** Every jail with what it watches and holds, or one jail's detail. */
|
||||
async status(jail?: string): Promise<{ jails: JailStatus[] }> {
|
||||
const names = jail ? [jail] : await this.jails();
|
||||
const jails: JailStatus[] = [];
|
||||
for (const name of names) {
|
||||
jails.push(parseJailStatus(name, await this.client("status", name)));
|
||||
}
|
||||
return { jails };
|
||||
}
|
||||
|
||||
/** Every address banned now, with the jail holding it and when the ban ends. */
|
||||
async banned(jail?: string): Promise<{ banned: Ban[] }> {
|
||||
const names = jail ? [jail] : await this.jails();
|
||||
const banned: Ban[] = [];
|
||||
for (const name of names) {
|
||||
banned.push(...parseBans(name, await this.client("get", name, "banip", "--with-time")));
|
||||
}
|
||||
banned.sort((a, b) => a.until.localeCompare(b.until) || a.ip.localeCompare(b.ip));
|
||||
return { banned };
|
||||
}
|
||||
|
||||
/** Ban one address in one jail now. The daemon's own answer is how many addresses it added. */
|
||||
async ban(ip: string, jail: string): Promise<{ banned: Ban | null; added: number }> {
|
||||
address(ip);
|
||||
name(jail);
|
||||
const out = await this.client("set", jail, "banip", ip);
|
||||
const added = Number.parseInt(out.trim(), 10) || 0;
|
||||
const held = (await this.banned(jail)).banned.find((b) => b.ip === ip) ?? null;
|
||||
return { banned: held, added };
|
||||
}
|
||||
|
||||
/** Let one address go, from one jail or from every jail. The daemon's answer is how many it released. */
|
||||
async unban(ip: string, jail?: string): Promise<{ released: number; ip: string; jail: string | "every jail" }> {
|
||||
address(ip);
|
||||
let out: string;
|
||||
if (jail) {
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "status", jail]);
|
||||
return stdout;
|
||||
name(jail);
|
||||
out = await this.client("set", jail, "unbanip", ip);
|
||||
} else {
|
||||
out = await this.client("unban", ip);
|
||||
}
|
||||
const { stdout: overview } = await run("sudo", ["fail2ban-client", "status"]);
|
||||
const match = overview.match(/Jail list:\s*(.+)/);
|
||||
if (!match) return overview;
|
||||
|
||||
const jails = match[1].split(",").map((j) => j.trim()).filter(Boolean);
|
||||
const parts: string[] = [overview.trimEnd(), ""];
|
||||
for (const j of jails) {
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "status", j]);
|
||||
parts.push(`=== ${j} ===`, stdout.trimEnd(), "");
|
||||
}
|
||||
return parts.join("\n");
|
||||
return { released: Number.parseInt(out.trim(), 10) || 0, ip, jail: jail ?? "every jail" };
|
||||
}
|
||||
|
||||
/** Manually ban an IP in a jail. Mutates live state, not a mesh-managed file. */
|
||||
async ban(jail: string, ip: string): Promise<string> {
|
||||
const { stdout } = await run("sudo", ["fail2ban-client", "set", jail, "banip", ip]);
|
||||
return stdout;
|
||||
}
|
||||
|
||||
/** Unban an IP from one jail, or from every jail when no jail is given. */
|
||||
async unban(ip: string, jail?: string): Promise<string> {
|
||||
const args = jail
|
||||
? ["fail2ban-client", "set", jail, "unbanip", ip]
|
||||
: ["fail2ban-client", "unban", ip];
|
||||
const { stdout } = await run("sudo", args);
|
||||
return stdout;
|
||||
/** One jail's effective settings — the module's own tool, beside the seat's verbs. */
|
||||
async settings(jail: string): Promise<JailSettings> {
|
||||
name(jail);
|
||||
const get = (key: string) => this.client("get", jail, key);
|
||||
const [bantime, findtime, maxretry, ignoreip, actions, logpath, journalmatch] = await Promise.all([
|
||||
get("bantime"), get("findtime"), get("maxretry"), get("ignoreip"), get("actions"), get("logpath"),
|
||||
get("journalmatch"),
|
||||
]);
|
||||
return {
|
||||
jail,
|
||||
bantime: bantime.trim(),
|
||||
findtime: findtime.trim(),
|
||||
maxretry: Number.parseInt(maxretry.trim(), 10),
|
||||
ignoreip: listed(ignoreip),
|
||||
actions: actions.split("\n").slice(1).map((l) => l.trim()).filter(Boolean),
|
||||
logpath: /No file is currently monitored/.test(logpath) ? [] : listed(logpath),
|
||||
journalmatch: journalmatch.split("\n").slice(1).map((l) => l.trim()).filter(Boolean).join(" "),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** fail2ban's tree listings: lines like "|- 127.0.0.0/8" and "`- ::1", after a heading. */
|
||||
function listed(out: string): string[] {
|
||||
return out
|
||||
.split("\n")
|
||||
.map((l) => l.replace(/^[\s|`-]+/, "").trim())
|
||||
.filter((l, i) => i > 0 && l.length > 0);
|
||||
}
|
||||
|
||||
export function parseJailStatus(jail: string, out: string): JailStatus {
|
||||
const field = (label: string) => {
|
||||
const m = out.match(new RegExp(label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ":\\t?\\s*(.*)"));
|
||||
return m ? m[1].trim() : "";
|
||||
};
|
||||
const num = (label: string) => Number.parseInt(field(label), 10) || 0;
|
||||
const watching = [field("File list"), field("Journal matches")].filter(Boolean);
|
||||
return {
|
||||
jail,
|
||||
watching,
|
||||
failing: { now: num("Currently failed"), total: num("Total failed") },
|
||||
banned: {
|
||||
now: num("Currently banned"),
|
||||
total: num("Total banned"),
|
||||
addresses: field("Banned IP list").split(/\s+/).filter(Boolean),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `get <jail> banip --with-time` prints one ban per line: "IP \tsince + seconds = until". */
|
||||
export function parseBans(jail: string, out: string): Ban[] {
|
||||
const bans: Ban[] = [];
|
||||
for (const line of out.split("\n")) {
|
||||
const m = line.match(/^(\S+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \+ (-?\d+) = (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}|\S+)/);
|
||||
if (!m) continue;
|
||||
bans.push({ ip: m[1], jail, since: m[2], until: Number(m[3]) < 0 ? "never" : m[4] });
|
||||
}
|
||||
return bans;
|
||||
}
|
||||
|
||||
function address(ip: string): void {
|
||||
if (!isIP(ip)) throw new Error(`${JSON.stringify(ip)} is not an address`);
|
||||
}
|
||||
|
||||
function name(jail: string): void {
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(jail)) throw new Error(`${JSON.stringify(jail)} is not a jail's name`);
|
||||
}
|
||||
|
||||
@@ -7,9 +7,22 @@
|
||||
"claims": [
|
||||
{
|
||||
"name": "node-intrusion-prevention",
|
||||
"scope": "node"
|
||||
"scope": "node",
|
||||
"serves": [
|
||||
"status",
|
||||
"banned",
|
||||
"ban",
|
||||
"unban"
|
||||
]
|
||||
}
|
||||
],
|
||||
"tools": [
|
||||
"fail2ban_settings"
|
||||
],
|
||||
"jailing": {
|
||||
"into": "/etc/fail2ban/jail.d/mesh.conf",
|
||||
"filter-into": "/etc/fail2ban/filter.d"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "package",
|
||||
@@ -28,19 +41,31 @@
|
||||
"path": "/etc/fail2ban/action.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "filter-d",
|
||||
"type": "directory",
|
||||
"path": "/etc/fail2ban/filter.d",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "run-dir",
|
||||
"type": "directory",
|
||||
"path": "/var/run/fail2ban",
|
||||
"mode": "0755"
|
||||
},
|
||||
{
|
||||
"id": "jail-local",
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.local",
|
||||
"mode": "0644",
|
||||
"content": "[INCLUDES]\n\nbefore = paths-arch.conf\n\n[DEFAULT]\n\n# Never act on the machine itself or on a tunnel peer: the mesh's private range is\n# ${machine:mesh-range}, named here rather than written as a value the module cannot\n# know (novox/hq ADR 0112). Without this, fail2ban could ban the mesh's own nodes.\nignoreip = 127.0.0.1/8 ::1 ${machine:mesh-range}\n\nbantime = 10m\nfindtime = 10m\nmaxretry = 5\n\n# Ban through iptables, not through a firewall front-end the machine may not have. ufw is\n# installed on two of this mesh's machines and absent on the other two, and fail2ban finds out\n# only at ban time: the service reports healthy, the jail counts the attempt, the ban command\n# exits 127, and nothing is blocked. Proven on 2026-09-28 -- 'ufw: command not found' on a\n# machine the mesh reported as protected.\n#\n# The action below is this module's own, already used by the recidive jail on every machine\n# here, and it bans in DOCKER-USER as well as INPUT, so a container's published port is\n# covered too.\nbanaction = iptables-allports-dualchain\nbanaction_allports = iptables-allports-dualchain\n\n[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n"
|
||||
"content": "[INCLUDES]\n\nbefore = paths-arch.conf\n\n[DEFAULT]\n\n# Never act on the machine itself or on a tunnel peer: the mesh's private range is\n# ${machine:mesh-range}, named here rather than written as a value the module cannot\n# know (novox/hq ADR 0112). Without this, fail2ban could ban the mesh's own nodes.\n# **A ban list never holds a neighbour.** The mesh's own range is named rather than written\n# (novox/hq ADR 0112), and every private range beside it: a source on one is somebody's own\n# network, not the internet. On a machine behind a router that reflects local traffic, every\n# client in the house arrives as the gateway's address — so one mistyped local request banned\n# 192.168.1.1 on the home server and would have cut the whole house off from it (ADR 0186).\nignoreip = 127.0.0.1/8 ::1 ${machine:mesh-range} 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 169.254.0.0/16 fc00::/7 fe80::/10\n\n# Three failures in a day ban for a day (novox/hq ADR 0179). The attackers this mesh sees pace\n# themselves at one try every ten minutes, under any ten-minute window; a day's window counts\n# them, and a day's ban costs a person who mistyped three times once, from one address, while\n# the mesh's own range is never banned at all.\nbantime = 1d\nfindtime = 1d\nmaxretry = 3\n\n# Ban through iptables, not through a firewall front-end the machine may not have. ufw is\n# installed on two of this mesh's machines and absent on the other two, and fail2ban finds out\n# only at ban time: the service reports healthy, the jail counts the attempt, the ban command\n# exits 127, and nothing is blocked. Proven on 2026-09-28 -- 'ufw: command not found' on a\n# machine the mesh reported as protected.\n#\n# The action below is this module's own, already used by the recidive jail on every machine\n# here, and it bans in DOCKER-USER as well as INPUT, so a container's published port is\n# covered too.\nbanaction = iptables-allports-dualchain\nbanaction_allports = iptables-allports-dualchain\n\n[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\n"
|
||||
},
|
||||
{
|
||||
"id": "jail-sshd",
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.d/sshd.conf",
|
||||
"mode": "0644",
|
||||
"content": "[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\nmaxretry = 5\n"
|
||||
"content": "[sshd]\nenabled = true\nport = ssh\nlogpath = %(sshd_log)s\nbackend = %(sshd_backend)s\nmaxretry = 3\nfindtime = 1d\nbantime = 1d\n"
|
||||
},
|
||||
{
|
||||
"id": "log",
|
||||
@@ -55,7 +80,7 @@
|
||||
"type": "file",
|
||||
"path": "/etc/fail2ban/jail.d/recidive.conf",
|
||||
"mode": "0644",
|
||||
"content": "[recidive]\nenabled = true\nlogpath = /var/log/fail2ban.log\n# Ban in both INPUT (host services like SSH) and DOCKER-USER (container services)\nbanaction = iptables-allports-dualchain\nbantime = 1w\nfindtime = 1d\n"
|
||||
"content": "[recidive]\nenabled = true\nlogpath = /var/log/fail2ban.log\n# Ban in both INPUT (host services like SSH) and DOCKER-USER (container services)\nbanaction = iptables-allports-dualchain\n# Banned twice in two weeks, by any jail, is banned for four (novox/hq ADR 0179).\nbantime = 4w\nfindtime = 2w\nmaxretry = 2\n"
|
||||
},
|
||||
{
|
||||
"id": "action-dualchain",
|
||||
@@ -81,8 +106,21 @@
|
||||
"jail-local",
|
||||
"jail-sshd",
|
||||
"jail-recidive",
|
||||
"action-dualchain"
|
||||
"action-dualchain",
|
||||
"composed-jails"
|
||||
]
|
||||
}
|
||||
]
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
{
|
||||
"name": "@novox/module-fail2ban",
|
||||
"version": "0.1.0",
|
||||
"description": "fail2ban — intrusion prevention: the mesh declares the jails and keeps the daemon running; its ban/unban/status tools live here.",
|
||||
"description": "fail2ban \u2014 intrusion prevention: the mesh composes the jails and keeps the daemon running; this module holds the node-intrusion-prevention seat and serves its verbs status, banned, ban and unban (novox/hq to-be 31, ADR 0179).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
"@novox/mesh-sdk": "^0.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc client.ts tools/index.ts --module NodeNext --moduleResolution NodeNext --target ES2022 --rootDir . --outDir dist",
|
||||
"test": "node --test --experimental-strip-types 'test/*.test.ts'"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// The intrusion prevention's verbs over a fake daemon, with the shapes fail2ban-client 1.1.0 printed
|
||||
// on the control node on 2026-10-02 (novox/hq ADR 0179).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Fail2banClient, escalated, installed, parseBans, parseJailStatus, type Runner } from "../client.ts";
|
||||
|
||||
const STATUS = "Status\n|- Number of jail:\t2\n`- Jail list:\trecidive, sshd\n";
|
||||
const RECIDIVE =
|
||||
"Status for the jail: recidive\n|- Filter\n| |- Currently failed:\t36\n| |- Total failed:\t149\n" +
|
||||
"| `- File list:\t/var/log/fail2ban.log\n`- Actions\n |- Currently banned:\t9\n |- Total banned:\t13\n" +
|
||||
" `- Banned IP list:\t195.178.110.30 45.148.10.240 92.118.39.71\n";
|
||||
const SSHD =
|
||||
"Status for the jail: sshd\n|- Filter\n| |- Currently failed:\t5\n| |- Total failed:\t11776\n" +
|
||||
"| `- Journal matches:\t_SYSTEMD_UNIT=sshd.service + _COMM=sshd\n`- Actions\n |- Currently banned:\t0\n" +
|
||||
" |- Total banned:\t150\n `- Banned IP list:\t\n";
|
||||
const WITH_TIME =
|
||||
"195.178.110.30 \t2026-09-26 23:18:47 + 604800 = 2026-10-03 23:18:47\n" +
|
||||
"92.118.39.71 \t2026-09-28 10:33:49 + 604800 = 2026-10-05 10:33:49\n";
|
||||
|
||||
function fake(answers: Record<string, string>, calls: string[][] = []): Runner {
|
||||
return async (cmd, args) => {
|
||||
calls.push([cmd, ...args]);
|
||||
const key = args.join(" ");
|
||||
if (key in answers) return answers[key];
|
||||
throw new Error(`unexpected ${cmd} ${key}`);
|
||||
};
|
||||
}
|
||||
|
||||
test("a jail's status is read into numbers, what it watches and who it holds", () => {
|
||||
const s = parseJailStatus("recidive", RECIDIVE);
|
||||
assert.deepEqual(s, {
|
||||
jail: "recidive",
|
||||
watching: ["/var/log/fail2ban.log"],
|
||||
failing: { now: 36, total: 149 },
|
||||
banned: { now: 9, total: 13, addresses: ["195.178.110.30", "45.148.10.240", "92.118.39.71"] },
|
||||
});
|
||||
const j = parseJailStatus("sshd", SSHD);
|
||||
assert.deepEqual(j.watching, ["_SYSTEMD_UNIT=sshd.service + _COMM=sshd"]);
|
||||
assert.deepEqual(j.banned, { now: 0, total: 150, addresses: [] });
|
||||
});
|
||||
|
||||
test("status covers every jail the daemon lists, or the one named", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({ status: STATUS, "status recidive": RECIDIVE, "status sshd": SSHD }, calls));
|
||||
const all = await f.status();
|
||||
assert.deepEqual(all.jails.map((j) => j.jail), ["recidive", "sshd"]);
|
||||
const one = await f.status("sshd");
|
||||
assert.equal(one.jails.length, 1);
|
||||
assert.deepEqual(calls[calls.length - 1], ["fail2ban-client", "status", "sshd"]);
|
||||
});
|
||||
|
||||
test("bans are read with when they were placed and when they end, a permanent one as never", () => {
|
||||
const bans = parseBans("recidive", WITH_TIME + "203.0.113.9 \t2026-10-01 00:00:00 + -1 = never\n");
|
||||
assert.equal(bans.length, 3);
|
||||
assert.deepEqual(bans[0], { ip: "195.178.110.30", jail: "recidive", since: "2026-09-26 23:18:47", until: "2026-10-03 23:18:47" });
|
||||
assert.equal(bans[2].until, "never");
|
||||
assert.deepEqual(parseBans("sshd", "\n"), []);
|
||||
});
|
||||
|
||||
test("banned gathers every jail's bans, soonest to end first", async () => {
|
||||
const f = new Fail2banClient(fake({
|
||||
status: STATUS,
|
||||
"get recidive banip --with-time": WITH_TIME,
|
||||
"get sshd banip --with-time": "198.51.100.7 \t2026-10-02 15:06:58 + 600 = 2026-10-02 15:16:58\n",
|
||||
}));
|
||||
const { banned } = await f.banned();
|
||||
assert.deepEqual(banned.map((b) => `${b.ip}@${b.jail}`), ["198.51.100.7@sshd", "195.178.110.30@recidive", "92.118.39.71@recidive"]);
|
||||
});
|
||||
|
||||
test("ban asks the daemon by jail and answers with the ban as held; a non-address is refused before anything runs", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({
|
||||
"set recidive banip 198.51.100.7": "1\n",
|
||||
"get recidive banip --with-time": WITH_TIME + "198.51.100.7 \t2026-10-02 17:00:00 + 604800 = 2026-10-09 17:00:00\n",
|
||||
}, calls));
|
||||
const r = await f.ban("198.51.100.7", "recidive");
|
||||
assert.equal(r.added, 1);
|
||||
assert.equal(r.banned?.until, "2026-10-09 17:00:00");
|
||||
assert.deepEqual(calls[0], ["fail2ban-client", "set", "recidive", "banip", "198.51.100.7"]);
|
||||
await assert.rejects(() => f.ban("not-an-ip", "recidive"), /is not an address/);
|
||||
await assert.rejects(() => f.ban("198.51.100.7", "a jail; rm"), /is not a jail's name/);
|
||||
assert.equal(calls.length, 2);
|
||||
});
|
||||
|
||||
test("unban releases from one jail or from every jail", async () => {
|
||||
const calls: string[][] = [];
|
||||
const f = new Fail2banClient(fake({ "set sshd unbanip 198.51.100.7": "1\n", "unban 198.51.100.7": "2\n" }, calls));
|
||||
assert.deepEqual(await f.unban("198.51.100.7", "sshd"), { released: 1, ip: "198.51.100.7", jail: "sshd" });
|
||||
assert.deepEqual(await f.unban("198.51.100.7"), { released: 2, ip: "198.51.100.7", jail: "every jail" });
|
||||
assert.deepEqual(calls[1], ["fail2ban-client", "unban", "198.51.100.7"]);
|
||||
});
|
||||
|
||||
test("a jail's settings are read from the daemon's listings", async () => {
|
||||
const f = new Fail2banClient(fake({
|
||||
"get sshd bantime": "86400\n", "get sshd findtime": "86400\n", "get sshd maxretry": "3\n",
|
||||
"get sshd ignoreip": "These IP addresses/networks are ignored:\n|- 127.0.0.0/8\n|- 10.10.0.0/24\n`- ::1\n",
|
||||
"get sshd actions": "The jail sshd has the following actions:\niptables-allports-dualchain\n",
|
||||
"get sshd logpath": "No file is currently monitored\n",
|
||||
"get sshd journalmatch": "Current match filter:\n_SYSTEMD_UNIT=sshd.service + _COMM=sshd\n",
|
||||
}));
|
||||
assert.deepEqual(await f.settings("sshd"), {
|
||||
jail: "sshd", bantime: "86400", findtime: "86400", maxretry: 3,
|
||||
ignoreip: ["127.0.0.0/8", "10.10.0.0/24", "::1"], actions: ["iptables-allports-dualchain"],
|
||||
logpath: [], journalmatch: "_SYSTEMD_UNIT=sshd.service + _COMM=sshd",
|
||||
});
|
||||
});
|
||||
|
||||
test("the client runs as given by root and through sudo without a prompt by anyone else", () => {
|
||||
assert.deepEqual(escalated("fail2ban-client", ["status"], 0), ["fail2ban-client", ["status"]]);
|
||||
assert.deepEqual(escalated("fail2ban-client", ["set", "sshd", "banip", "198.51.100.7"], 1000),
|
||||
["sudo", ["-n", "fail2ban-client", "set", "sshd", "banip", "198.51.100.7"]]);
|
||||
assert.equal(installed("sh"), true);
|
||||
assert.equal(installed("no-such-client-of-the-mesh"), false);
|
||||
});
|
||||
@@ -1,55 +1,62 @@
|
||||
// fail2ban's tools — reading and steering the live ban state. The jails themselves are declared
|
||||
// resources (module.json); these three touch what the running daemon holds: what is banned now,
|
||||
// and the manual ban/unban an operator reaches for. The daemon's state is fail2ban's own, so this
|
||||
// is the only way to see or change it — the mesh reconciles the config, not the bans.
|
||||
// The intrusion prevention's tools: the node-intrusion-prevention seat's four verbs — who is banned,
|
||||
// the jails' state, ban one, let one go — and the module's own reading of a jail's settings
|
||||
// (novox/hq to-be 31, ADR 0179). The jails themselves are composed by the mesh from the modules a
|
||||
// machine runs and written as declared resources; these touch only what the running daemon holds.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { Fail2banClient } from "../client.js";
|
||||
|
||||
export function getFail2banTools(fail2ban: Fail2banClient): ToolDefinition[] {
|
||||
export function getSeatVerbs(fail2ban: Fail2banClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "fail2ban_status",
|
||||
name: "status",
|
||||
description:
|
||||
"fail2ban status on this node — the jails and their live bans. Omit `jail` for every jail, or name one for its detail.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
jail: {
|
||||
type: "string",
|
||||
description: "A specific jail (e.g. sshd, recidive); omit for the overview of all jails.",
|
||||
},
|
||||
},
|
||||
},
|
||||
run: async (args) => ({ status: await fail2ban.status(args.jail as string | undefined) }),
|
||||
"Every jail on this machine with what it watches, how many addresses it is counting failures against and holding now, and the totals since it started; one jail's detail when named.",
|
||||
input: { jail: { type: "string", description: "one jail (optional)" } },
|
||||
run: async (args) => fail2ban.status(args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
{
|
||||
name: "fail2ban_ban",
|
||||
description: "Manually ban an IP address in a jail — a live change to the running daemon, not a mesh-managed file.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
jail: { type: "string", description: "Jail name (e.g. sshd, recidive)." },
|
||||
ip: { type: "string", description: "IP address to ban." },
|
||||
},
|
||||
required: ["jail", "ip"],
|
||||
},
|
||||
run: async (args) => ({ result: await fail2ban.ban(args.jail as string, args.ip as string) }),
|
||||
name: "banned",
|
||||
description: "Every address banned on this machine right now, with the jail that holds it, when it was banned and when the ban ends.",
|
||||
input: { jail: { type: "string", description: "one jail (optional)" } },
|
||||
run: async (args) => fail2ban.banned(args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
{
|
||||
name: "fail2ban_unban",
|
||||
description: "Unban an IP address from one jail, or from every jail when `jail` is omitted.",
|
||||
name: "ban",
|
||||
description:
|
||||
"Ban one address in one jail now, for the jail's ban time — an operator's act on the live ban list, which the mesh never writes itself.",
|
||||
input: {
|
||||
type: "object",
|
||||
properties: {
|
||||
ip: { type: "string", description: "IP address to unban." },
|
||||
jail: { type: "string", description: "A specific jail; omit to unban from all jails." },
|
||||
},
|
||||
required: ["ip"],
|
||||
ip: { type: "string", description: "the address" },
|
||||
jail: { type: "string", description: "the jail to hold it (recidive for the long ban)" },
|
||||
},
|
||||
run: async (args) => ({ result: await fail2ban.unban(args.ip as string, args.jail as string | undefined) }),
|
||||
run: async (args) => fail2ban.ban(String(args.ip ?? ""), String(args.jail ?? "")),
|
||||
},
|
||||
{
|
||||
name: "unban",
|
||||
description: "Let one address go, from one jail or from every jail when none is named.",
|
||||
input: {
|
||||
ip: { type: "string", description: "the address" },
|
||||
jail: { type: "string", description: "one jail (optional)" },
|
||||
},
|
||||
run: async (args) => fail2ban.unban(String(args.ip ?? ""), args.jail ? String(args.jail) : undefined),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
registerModuleTools("fail2ban", () => getFail2banTools(Fail2banClient.fromEnv()));
|
||||
export function getFail2banTools(fail2ban: Fail2banClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "fail2ban_settings",
|
||||
description:
|
||||
"One jail's effective settings on this machine: ban time, window, tries, the addresses it never bans, its actions and what it reads.",
|
||||
input: { jail: { type: "string", description: "the jail" } },
|
||||
run: async (args) => fail2ban.settings(String(args.jail ?? "")),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const fail2ban = Fail2banClient.onThisMachine();
|
||||
// The seat's verbs under the seat's name: the runtime serves them on the seat's subjects where this
|
||||
// module holds it (ADR 0159, 0160). The module's own under its own.
|
||||
registerModuleTools("node-intrusion-prevention", () => getSeatVerbs(fail2ban));
|
||||
registerModuleTools("fail2ban", () => getFail2banTools(fail2ban));
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
# gitea's runtime: the tool runtime, carrying this module's compiled provisioner, tools and event
|
||||
# consumer.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk is in the base image, so
|
||||
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
|
||||
# repository and a path (novox/hq ADR 0069) rather than only on a workstation that happens to have
|
||||
# the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
|
||||
# They are different images on purpose — the first carries a compiler and the second must not, or
|
||||
# every running container would carry one it never invokes. The mesh answers both with the copies it
|
||||
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
|
||||
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
|
||||
# nobody told stops here and says which module to build first.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the sdk it will run against.
|
||||
WORKDIR /app/modules/gitea
|
||||
COPY . .
|
||||
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
|
||||
# symlinks to a launcher that requires its library relatively — resolved away when the base image
|
||||
# was assembled.
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts token.ts index.ts provisioner/index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
# **No apt packages.** gitea's provisioner talks to the forge over HTTP (the gitea REST API), not
|
||||
# through a CLI the way postgres drives psql — so the runtime base holds everything this needs.
|
||||
COPY --from=build /app/modules/gitea/dist /app/modules/gitea/dist
|
||||
# What a tool host should load from this module: its event consumer and its tools, which are
|
||||
# separate entrypoints because they are loaded by different things. The provisioner is the third,
|
||||
# and is not listed here — the declaration names it in the container's `args`, because it is what
|
||||
# this module's own container runs. One image, because they are one module and share a client.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/gitea/dist/index.js,/app/modules/gitea/dist/tools/index.js,/app/modules/gitea/dist/provisioner/index.js
|
||||
@@ -45,6 +45,14 @@ export interface GiteaPull {
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export interface GiteaComment {
|
||||
id: number;
|
||||
user?: string;
|
||||
body: string;
|
||||
created_at?: string;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export interface GiteaLabel {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -257,6 +265,64 @@ export class GiteaClient {
|
||||
);
|
||||
}
|
||||
|
||||
/** Close or reopen a pull request without merging it. A pull request is an issue to the forge's
|
||||
* state machine, and the pulls endpoint takes the same `state`. */
|
||||
async setPullState(owner: string, repo: string, index: number, state: "open" | "closed"): Promise<GiteaPull> {
|
||||
return GiteaClient.mapPull(
|
||||
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify({ state }) }),
|
||||
);
|
||||
}
|
||||
|
||||
/** Change a pull request's title or body; a field left undefined is left alone. */
|
||||
async updatePullRequest(owner: string, repo: string, index: number, data: { title?: string; body?: string }): Promise<GiteaPull> {
|
||||
return GiteaClient.mapPull(
|
||||
await this.request<any>(`/repos/${owner}/${repo}/pulls/${index}`, { method: "PATCH", body: JSON.stringify(data) }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The unified diff of a pull request, as text. */
|
||||
async pullDiff(owner: string, repo: string, index: number): Promise<string> {
|
||||
return this.requestText(`/repos/${owner}/${repo}/pulls/${index}.diff`);
|
||||
}
|
||||
|
||||
/** Every comment on an issue or pull request, oldest first. */
|
||||
async listComments(owner: string, repo: string, index: number): Promise<GiteaComment[]> {
|
||||
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/issues/${index}/comments`);
|
||||
return (raw ?? []).map((c) => ({
|
||||
id: Number(c?.id ?? 0),
|
||||
user: c?.user?.login,
|
||||
body: String(c?.body ?? ""),
|
||||
created_at: c?.created_at,
|
||||
html_url: String(c?.html_url ?? ""),
|
||||
}));
|
||||
}
|
||||
|
||||
/** One file's contents at a ref (default the repository's default branch), decoded. */
|
||||
async getFile(owner: string, repo: string, path: string, ref?: string): Promise<{ path: string; ref?: string; sha: string; size: number; content: string }> {
|
||||
const qs = ref ? `?ref=${encodeURIComponent(ref)}` : "";
|
||||
const f = await this.request<any>(`/repos/${owner}/${repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}${qs}`);
|
||||
if (!f || f.type !== "file") throw new Error(`Gitea API: ${path} is not a file`);
|
||||
const content = f.encoding === "base64" ? Buffer.from(String(f.content ?? ""), "base64").toString("utf8") : String(f.content ?? "");
|
||||
return { path, ref, sha: String(f.sha ?? ""), size: Number(f.size ?? content.length), content };
|
||||
}
|
||||
|
||||
async listBranches(owner: string, repo: string): Promise<{ name: string; commit: string; protected: boolean }[]> {
|
||||
const raw = await this.request<any[]>(`/repos/${owner}/${repo}/branches?limit=100`);
|
||||
return (raw ?? []).map((b) => ({ name: String(b?.name ?? ""), commit: String(b?.commit?.id ?? ""), protected: Boolean(b?.protected) }));
|
||||
}
|
||||
|
||||
async deleteBranch(owner: string, repo: string, branch: string): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/branches/${encodeURIComponent(branch)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
/** A request whose answer is text, not JSON — a diff. Same token handling as request(). */
|
||||
private async requestText(path: string): Promise<string> {
|
||||
const token = await this.tokens.current();
|
||||
const res = await this.send(path, { headers: { Accept: "text/plain" } }, token);
|
||||
if (!res.ok) throw new Error(`Gitea API ${path}: ${res.status} ${await res.text()}`);
|
||||
return res.text();
|
||||
}
|
||||
|
||||
async mergePullRequest(owner: string, repo: string, index: number, method = "merge", deleteBranch = false): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/pulls/${index}/merge`, {
|
||||
method: "POST",
|
||||
|
||||
+31
-46
@@ -85,9 +85,6 @@
|
||||
"scope": "mesh"
|
||||
}
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
@@ -145,7 +142,8 @@
|
||||
"volumes": [
|
||||
"${dir:data}:/data"
|
||||
],
|
||||
"secrets-in-environment": "gitea honours GITEA__database__PASSWD__FILE and GITEA__security__INTERNAL_TOKEN__FILE; convertible, awaiting a bed that proves it"
|
||||
"secrets-in-environment": "gitea honours GITEA__database__PASSWD__FILE and GITEA__security__INTERNAL_TOKEN__FILE; convertible, awaiting a bed that proves it",
|
||||
"logging": "journald"
|
||||
},
|
||||
{
|
||||
"id": "admin-bootstrap",
|
||||
@@ -179,32 +177,6 @@
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-gitea",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:grants}:${dir:grants}:ro",
|
||||
"${dir:state}/admin.secret:/run/secrets/admin:ro",
|
||||
"${dir:runtime-state}:/run/state"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "/run/secrets/admin",
|
||||
"MESH_GITEA_STATE_DIR": "/run/state",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
},
|
||||
"artifact": "runtime",
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
]
|
||||
}
|
||||
],
|
||||
"provides": [
|
||||
@@ -218,24 +190,37 @@
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_GITEA_ADMIN_USER": "mesh-admin",
|
||||
"MESH_GITEA_ADMIN_PASSWORD_FILE": "${dir:state}/admin.secret",
|
||||
"MESH_GITEA_STATE_DIR": "${dir:runtime-state}",
|
||||
"MESH_RECEIVES": "${dir:grants}/npm.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"jails": [
|
||||
{
|
||||
"name": "gitea",
|
||||
"failregex": "^.*Failed authentication attempt for .* from <HOST>(?::\\d+)?\\s*$\n ^.*Invalid user .* from <HOST> port \\d+\\s*$\n ^.*User \\S+ from <HOST> not allowed because .*$",
|
||||
"jail": "backend = systemd\njournalmatch = CONTAINER_NAME=gitea\nport = http,https,222\nmaxretry = 3\nfindtime = 1d\nbantime = 1d"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ interface Forge {
|
||||
tokens: Map<string, string>;
|
||||
scopesOf: Map<string, string[]>;
|
||||
admins: Map<string, string>;
|
||||
pullState: string;
|
||||
pullTitle: string;
|
||||
branchDeleted: boolean;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -41,6 +44,9 @@ function fakeForge(): Promise<Forge> {
|
||||
tokens: new Map<string, string>(), // name -> value
|
||||
scopesOf: new Map<string, string[]>(), // value -> scopes, so a route can enforce them like gitea does
|
||||
admins: new Map([[ADMIN, PASSWORD]]),
|
||||
pullState: "open",
|
||||
pullTitle: "The console shipped",
|
||||
branchDeleted: false,
|
||||
};
|
||||
// write:X implies read:X — gitea's own rule (models/auth/access_token_scope.go).
|
||||
const covers = (scopes: string[], required: string): boolean =>
|
||||
@@ -86,6 +92,37 @@ function fakeForge(): Promise<Forge> {
|
||||
}
|
||||
return json(res, 405, { message: "method not allowed" });
|
||||
}
|
||||
const tokenOf = (): string => {
|
||||
const h = req.headers.authorization ?? "";
|
||||
return h.startsWith("token ") ? h.slice(6) : "";
|
||||
};
|
||||
const pull = url.pathname.match(/^\/api\/v1\/repos\/novox\/hq\/pulls\/(\d+)(\.diff)?$/);
|
||||
if (pull) {
|
||||
if (![...forge.tokens.values()].includes(tokenOf())) return json(res, 401, { message: "token is required" });
|
||||
if (pull[2]) {
|
||||
res.writeHead(200, { "Content-Type": "text/plain" });
|
||||
return res.end("diff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n");
|
||||
}
|
||||
if (req.method === "PATCH") {
|
||||
const patch = await body(req);
|
||||
forge.pullState = patch?.state ?? forge.pullState;
|
||||
forge.pullTitle = patch?.title ?? forge.pullTitle;
|
||||
}
|
||||
return json(res, 200, { number: Number(pull[1]), title: forge.pullTitle, state: forge.pullState, merged: false,
|
||||
user: { login: "mesh-admin" }, head: { ref: "feat/x" }, base: { ref: "main" }, html_url: "http://fake/novox/hq/pulls/" + pull[1] });
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/issues/223/comments") {
|
||||
return json(res, 200, [{ id: 1, user: { login: "jochen" }, body: "landed elsewhere", created_at: "2026-10-01T00:00:00Z", html_url: "http://fake/c/1" }]);
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/contents/README.md") {
|
||||
return json(res, 200, { type: "file", encoding: "base64", sha: "abc", size: 5, content: Buffer.from("hello").toString("base64") });
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/branches") {
|
||||
return json(res, 200, [{ name: "main", protected: true, commit: { id: "aaaa" } }, { name: "feat/x", protected: false, commit: { id: "bbbb" } }]);
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/novox/hq/branches/feat%2Fx" || url.pathname === "/api/v1/repos/novox/hq/branches/feat/x") {
|
||||
if (req.method === "DELETE") { forge.branchDeleted = true; return json(res, 204, null); }
|
||||
}
|
||||
if (url.pathname === "/api/v1/repos/search") {
|
||||
// The client lists through the search endpoint since 2026-09-28 (the forge's whole view);
|
||||
// it sits under `repository`, which write:repository covers.
|
||||
@@ -140,6 +177,9 @@ function fakeForge(): Promise<Forge> {
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
get mints() { return forge.mints; },
|
||||
get lastScopes() { return forge.lastScopes; },
|
||||
get pullState() { return forge.pullState; },
|
||||
get pullTitle() { return forge.pullTitle; },
|
||||
get branchDeleted() { return forge.branchDeleted; },
|
||||
tokens: forge.tokens,
|
||||
scopesOf: forge.scopesOf,
|
||||
admins: forge.admins,
|
||||
@@ -360,6 +400,16 @@ test("the tools register once there is a way to a token, and the first call mint
|
||||
"gitea_list_repos", "gitea_create_repo", "gitea_delete_repo",
|
||||
"gitea_list_issues", "gitea_get_issue", "gitea_create_issue", "gitea_close_issue", "gitea_add_comment",
|
||||
"gitea_list_pull_requests", "gitea_get_pull_request", "gitea_create_pull_request", "gitea_merge_pull_request",
|
||||
"gitea_close_pull_request",
|
||||
"gitea_reopen_pull_request",
|
||||
"gitea_update_pull_request",
|
||||
"gitea_pull_request_files",
|
||||
"gitea_pull_request_diff",
|
||||
"gitea_list_comments",
|
||||
"gitea_reopen_issue",
|
||||
"gitea_get_file",
|
||||
"gitea_list_branches",
|
||||
"gitea_delete_branch",
|
||||
"gitea_list_labels", "gitea_create_label",
|
||||
"gitea_api",
|
||||
],
|
||||
@@ -370,3 +420,32 @@ test("the tools register once there is a way to a token, and the first call mint
|
||||
assert.equal(result.repos.length, 1);
|
||||
assert.equal(forge.mints, before + 1);
|
||||
});
|
||||
|
||||
// The forge's tools reach every action a review needs without a checkout and without the API
|
||||
// escape hatch: close a pull request whose work landed elsewhere, read its diff, its comments, a
|
||||
// file, the branches, and delete the branch left behind. Against the fake forge, through the
|
||||
// compiled tools, the way the console calls them.
|
||||
test("a pull request can be closed, read and cleaned up through the tools", async () => {
|
||||
const { env } = await delivered(forge);
|
||||
const tools = collectTools(env).find((c) => c.module === "gitea")!.tools;
|
||||
const tool = (name: string) => tools.find((t) => t.name === name)!;
|
||||
for (const name of ["gitea_close_pull_request", "gitea_reopen_pull_request", "gitea_update_pull_request", "gitea_pull_request_files",
|
||||
"gitea_pull_request_diff", "gitea_list_comments", "gitea_reopen_issue", "gitea_get_file", "gitea_list_branches", "gitea_delete_branch"]) {
|
||||
assert.ok(tool(name), `${name} is not a tool`);
|
||||
}
|
||||
const closed = (await tool("gitea_close_pull_request").run({ owner: "novox", repo: "hq", number: 223 })) as { pull: { state: string } };
|
||||
assert.equal(closed.pull.state, "closed");
|
||||
assert.equal(forge.pullState, "closed");
|
||||
const renamed = (await tool("gitea_update_pull_request").run({ owner: "novox", repo: "hq", number: 223, title: "Superseded" })) as { pull: { title: string } };
|
||||
assert.equal(renamed.pull.title, "Superseded");
|
||||
const diff = (await tool("gitea_pull_request_diff").run({ owner: "novox", repo: "hq", number: 223 })) as { diff: string };
|
||||
assert.match(diff.diff, /^diff --git/);
|
||||
const comments = (await tool("gitea_list_comments").run({ owner: "novox", repo: "hq", number: 223 })) as { comments: { body: string }[] };
|
||||
assert.equal(comments.comments[0].body, "landed elsewhere");
|
||||
const file = (await tool("gitea_get_file").run({ owner: "novox", repo: "hq", path: "README.md" })) as { file: { content: string } };
|
||||
assert.equal(file.file.content, "hello");
|
||||
const branches = (await tool("gitea_list_branches").run({ owner: "novox", repo: "hq" })) as { branches: { name: string }[] };
|
||||
assert.deepEqual(branches.branches.map((b) => b.name), ["main", "feat/x"]);
|
||||
await tool("gitea_delete_branch").run({ owner: "novox", repo: "hq", branch: "feat/x" });
|
||||
assert.equal(forge.branchDeleted, true);
|
||||
});
|
||||
|
||||
@@ -254,6 +254,131 @@ export function getGiteaTools(gitea: GiteaClient): ToolDefinition[] {
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: "gitea_close_pull_request",
|
||||
description: "Close a pull request without merging it — one whose work landed elsewhere, or was abandoned.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.setPullState(String(args.owner), String(args.repo), Number(args.number), "closed"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_reopen_pull_request",
|
||||
description: "Reopen a closed, unmerged pull request.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.setPullState(String(args.owner), String(args.repo), Number(args.number), "open"),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_update_pull_request",
|
||||
description: "Change a pull request's title or body; a field not given is left as it is.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
title: { type: "string", description: "the new title (optional)" },
|
||||
body: { type: "string", description: "the new body, markdown (optional)" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
pull: await gitea.updatePullRequest(String(args.owner), String(args.repo), Number(args.number), {
|
||||
title: args.title === undefined ? undefined : String(args.title),
|
||||
body: args.body === undefined ? undefined : String(args.body),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_pull_request_files",
|
||||
description: "The files a pull request changes, as paths from the repository's root (up to 100; says when there are more).",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => gitea.listPullFiles(String(args.owner), String(args.repo), Number(args.number)),
|
||||
},
|
||||
{
|
||||
name: "gitea_pull_request_diff",
|
||||
description: "A pull request's unified diff, as text — for reviewing it without a checkout.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
diff: await gitea.pullDiff(String(args.owner), String(args.repo), Number(args.number)),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_list_comments",
|
||||
description: "Every comment on an issue or pull request, oldest first.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the issue or PR number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
comments: await gitea.listComments(String(args.owner), String(args.repo), Number(args.number)),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_reopen_issue",
|
||||
description: "Reopen a closed issue.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
number: { type: "number", description: "the issue number" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
issue: await gitea.setIssueState(String(args.owner), String(args.repo), Number(args.number), "open"),
|
||||
}),
|
||||
},
|
||||
|
||||
// ---- Contents and branches ----
|
||||
{
|
||||
name: "gitea_get_file",
|
||||
description: "One file's contents from a repository, decoded, at a branch, tag or commit (default the repository's default branch).",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
path: { type: "string", description: "the file's path from the repository's root" },
|
||||
ref: { type: "string", description: "branch, tag or commit (optional)" },
|
||||
},
|
||||
run: async (args) => ({
|
||||
file: await gitea.getFile(String(args.owner), String(args.repo), String(args.path), args.ref ? String(args.ref) : undefined),
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: "gitea_list_branches",
|
||||
description: "Every branch of a repository with the commit it points at.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
},
|
||||
run: async (args) => ({ branches: await gitea.listBranches(String(args.owner), String(args.repo)) }),
|
||||
},
|
||||
{
|
||||
name: "gitea_delete_branch",
|
||||
description: "Delete a branch — a feature branch whose pull request was closed rather than merged. Refused by the forge for a protected branch.",
|
||||
input: {
|
||||
owner: { type: "string", description: "the repository owner" },
|
||||
repo: { type: "string", description: "the repository name" },
|
||||
branch: { type: "string", description: "the branch name" },
|
||||
},
|
||||
run: async (args) => {
|
||||
await gitea.deleteBranch(String(args.owner), String(args.repo), String(args.branch));
|
||||
return { deleted: true, branch: String(args.branch) };
|
||||
},
|
||||
},
|
||||
|
||||
// ---- Labels ----
|
||||
{
|
||||
name: "gitea_list_labels",
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# gitlab's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/gitlab
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/gitlab/dist /app/modules/gitlab/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/gitlab/dist/tools/index.js
|
||||
+14
-40
@@ -2,16 +2,9 @@
|
||||
"module": "gitlab",
|
||||
"version": "1",
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"token": "${dir:state}/token"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -25,46 +18,27 @@
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-runtime-gitlab",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:state}/token:/run/secrets/token:ro",
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITLAB_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_GITLAB_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GITLAB_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_GITLAB_CONFIG_FILE": "${dir:state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# grafana's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/grafana
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/grafana/dist /app/modules/grafana/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/grafana/dist/index.js,/app/modules/grafana/dist/tools/index.js
|
||||
+16
-36
@@ -5,8 +5,7 @@
|
||||
"alert.firing"
|
||||
],
|
||||
"own-secrets": {
|
||||
"admin": "${dir:mesh-state}/admin",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"admin": "${dir:mesh-state}/admin"
|
||||
},
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
@@ -112,25 +111,6 @@
|
||||
"mode": "0600",
|
||||
"content": "{\n \"user\": \"admin\",\n \"password\": \"${secret:admin}\"\n}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-grafana",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_GRAFANA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GRAFANA_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
@@ -162,23 +142,23 @@
|
||||
"influxdb-api": "${dir:mesh-state}/influxdb-api"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_GRAFANA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GRAFANA_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
# home-assistant's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/home-assistant
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts provisions/hass.ts provisions/probe.ts provisions/connections.ts provisions/mesh.ts provisions/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/home-assistant/dist /app/modules/home-assistant/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/home-assistant/dist/index.js,/app/modules/home-assistant/dist/tools/index.js
|
||||
# NOT dist/provisions/index.js: that is a step the host runs to completion, named by the
|
||||
# `provisions` container's args as `mesh-tools run …` (novox/hq ADR 0052). Listed here it would run
|
||||
# inside the serving sidecar too, and exit it.
|
||||
@@ -9,7 +9,6 @@
|
||||
"state.changed"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker",
|
||||
"token": "${dir:mesh-state}/token"
|
||||
},
|
||||
"listens": [
|
||||
@@ -80,55 +79,27 @@
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-home-assistant",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/token:/run/secrets/token:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_HOMEASSISTANT_URL": "http://127.0.0.1:${port:8123}",
|
||||
"MESH_HOMEASSISTANT_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_HOMEASSISTANT_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
"id": "provisions-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/provisions.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_HOMEASSISTANT_URL=http://127.0.0.1:${port:8123}\nMESH_HOMEASSISTANT_TOKEN_FILE=${dir:mesh-state}/token\nMESH_PROVISIONS_DIR=${dir:state}\nMESH_WRITTEN_DIR=${dir:written}\n"
|
||||
},
|
||||
{
|
||||
"id": "provisions",
|
||||
"type": "container",
|
||||
"name": "mesh-home-assistant-provisions",
|
||||
"network": "host",
|
||||
"run-once": true,
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/token:/run/secrets/token:ro",
|
||||
"${dir:written}:/var/lib/home-assistant-provisions",
|
||||
"${dir:state}/mqtt-topic.json:/run/provisions/mqtt-topic.json:ro",
|
||||
"${dir:state}/mqtt-topic.secret:/run/provisions/mqtt-topic.secret:ro",
|
||||
"${dir:state}/sonarr-api.json:/run/provisions/sonarr-api.json:ro",
|
||||
"${dir:state}/sonarr-api.secret:/run/provisions/sonarr-api.secret:ro",
|
||||
"${dir:state}/radarr-api.json:/run/provisions/radarr-api.json:ro",
|
||||
"${dir:state}/radarr-api.secret:/run/provisions/radarr-api.secret:ro",
|
||||
"${dir:state}/lidarr-api.json:/run/provisions/lidarr-api.json:ro",
|
||||
"${dir:state}/lidarr-api.secret:/run/provisions/lidarr-api.secret:ro"
|
||||
"type": "process",
|
||||
"name": "home-assistant-provisions",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"provisions/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_HOMEASSISTANT_URL": "http://127.0.0.1:${port:8123}",
|
||||
"MESH_HOMEASSISTANT_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_PROVISIONS_DIR": "/run/provisions",
|
||||
"MESH_WRITTEN_DIR": "/var/lib/home-assistant-provisions"
|
||||
},
|
||||
"args": [
|
||||
"run",
|
||||
"/app/modules/home-assistant/dist/provisions/index.js"
|
||||
"run-once": true,
|
||||
"env-file": [
|
||||
"${dir:state}/provisions.env"
|
||||
],
|
||||
"restart-on": [
|
||||
"provisions-env",
|
||||
"bound-mqtt-topic",
|
||||
"secret-mqtt-topic",
|
||||
"bound-sonarr-api",
|
||||
@@ -137,8 +108,7 @@
|
||||
"secret-radarr-api",
|
||||
"bound-lidarr-api",
|
||||
"secret-lidarr-api"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
]
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
@@ -173,23 +143,25 @@
|
||||
"lidarr-api": "${dir:state}/lidarr-api.secret"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisions/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_HOMEASSISTANT_URL": "http://127.0.0.1:${port:8123}",
|
||||
"MESH_HOMEASSISTANT_TOKEN_FILE": "${dir:mesh-state}/token",
|
||||
"MESH_HOMEASSISTANT_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# icecast's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/icecast
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/icecast/dist /app/modules/icecast/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/icecast/dist/index.js,/app/modules/icecast/dist/tools/index.js
|
||||
+15
-37
@@ -28,9 +28,6 @@
|
||||
"stream.started",
|
||||
"stream.stopped"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "stream",
|
||||
@@ -95,45 +92,26 @@
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-icecast",
|
||||
"network": "icecast",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_ICECAST_URL": "http://icecast:8000",
|
||||
"MESH_ICECAST_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_ICECAST_URL": "http://127.0.0.1:${port:8000}",
|
||||
"MESH_ICECAST_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# influxdb's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/influxdb
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts grants.ts provisioner/index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/influxdb/dist /app/modules/influxdb/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/influxdb/dist/tools/index.js,/app/modules/influxdb/dist/provisioner/index.js
|
||||
@@ -11,7 +11,6 @@
|
||||
"container-runtime"
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker",
|
||||
"admin": "${dir:state}/admin.secret",
|
||||
"admin-token": "${dir:state}/admin-token.secret"
|
||||
},
|
||||
@@ -100,29 +99,6 @@
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-influxdb",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:state}/admin-token.secret:/run/secrets/admin-token:ro",
|
||||
"${dir:grants}:${dir:grants}:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_INFLUXDB_URL": "http://127.0.0.1:${port:8086}",
|
||||
"MESH_INFLUXDB_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_INFLUXDB_TOKEN_FILE": "/run/secrets/admin-token",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
@@ -135,23 +111,25 @@
|
||||
}
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_INFLUXDB_URL": "http://127.0.0.1:${port:8086}",
|
||||
"MESH_INFLUXDB_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_INFLUXDB_TOKEN_FILE": "${dir:state}/admin-token.secret",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@
|
||||
"type": "file",
|
||||
"path": "${dir:state}/api.env",
|
||||
"mode": "0600",
|
||||
"content": "NODE_ENV=production\nPORT=9000\nMONGO_URL=mongodb://${bound:mongodb-database:as}:${secret:mongodb-database}@${bound:mongodb-database:at}:${bound:mongodb-database:port}/${bound:mongodb-database:as}?authSource=${bound:mongodb-database:as}\nMONGO_DB=${bound:mongodb-database:as}\nMINIO_BUCKET=mesh-novox-invoice\nMINIO_ENDPOINT=${bound:s3-bucket:at}\nMINIO_PORT=${bound:s3-bucket:port}\nMINIO_ACCESSKEY=${bound:s3-bucket:as}\nMINIO_SECRET=${secret:s3-bucket}\n"
|
||||
"content": "NODE_ENV=production\nPORT=9000\nMONGO_URL=mongodb://${bound:mongodb-database:as}:${secret:mongodb-database}@${bound:mongodb-database:at}:${bound:mongodb-database:port}/${bound:mongodb-database:as}?authSource=${bound:mongodb-database:as}\nMONGO_DB=${bound:mongodb-database:as}\nMINIO_BUCKET=${bound:s3-bucket:bucket}\nMINIO_ENDPOINT=${bound:s3-bucket:at}\nMINIO_PORT=${bound:s3-bucket:port}\nMINIO_ACCESSKEY=${bound:s3-bucket:as}\nMINIO_SECRET=${secret:s3-bucket}\n"
|
||||
},
|
||||
{
|
||||
"id": "net",
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# jira's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/jira
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/jira/dist /app/modules/jira/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/jira/dist/tools/index.js
|
||||
+14
-40
@@ -2,16 +2,9 @@
|
||||
"module": "jira",
|
||||
"version": "1",
|
||||
"own-secrets": {
|
||||
"token": "${dir:state}/token",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"token": "${dir:state}/token"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -25,46 +18,27 @@
|
||||
"merge": "json",
|
||||
"content": "{}",
|
||||
"mode": "0600"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-runtime-jira",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:state}/token:/run/secrets/token:ro",
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_JIRA_TOKEN_FILE": "/run/secrets/token",
|
||||
"MESH_JIRA_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_JIRA_TOKEN_FILE": "${dir:state}/token",
|
||||
"MESH_JIRA_CONFIG_FILE": "${dir:state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
# keycloak's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the sdk it will run against. The compiler
|
||||
# is invoked by its real path: node_modules/.bin entries are launcher symlinks the base image
|
||||
# resolved away.
|
||||
WORKDIR /app/modules/keycloak
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts oidc.ts index.ts provisioner/index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/keycloak/dist /app/modules/keycloak/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled. A container that instead ran only its
|
||||
# provisioner (`run`) served no tools and emitted no events; a container that named no command
|
||||
# ran no provisioner at all.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/keycloak/dist/index.js,/app/modules/keycloak/dist/tools/index.js,/app/modules/keycloak/dist/provisioner/index.js
|
||||
@@ -62,8 +62,7 @@
|
||||
"oidc-client": "${dir:grants}"
|
||||
},
|
||||
"own-secrets": {
|
||||
"admin": "${dir:state}/admin.secret",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"admin": "${dir:state}/admin.secret"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
@@ -144,49 +143,30 @@
|
||||
"mode": "0600",
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-keycloak",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro",
|
||||
"${dir:state}/admin.secret:/run/secrets/admin:ro",
|
||||
"${dir:grants}:${dir:grants}:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_KEYCLOAK_URL": "http://127.0.0.1:${port:8080}",
|
||||
"MESH_KEYCLOAK_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_KEYCLOAK_PASSWORD_FILE": "/run/secrets/admin",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_KEYCLOAK_URL": "http://127.0.0.1:${port:8080}",
|
||||
"MESH_KEYCLOAK_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_KEYCLOAK_PASSWORD_FILE": "${dir:state}/admin.secret",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
{
|
||||
"module": "lab",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"container-runtime",
|
||||
"virtualisation"
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "."
|
||||
},
|
||||
{
|
||||
"id": "work",
|
||||
"type": "directory",
|
||||
"path": "/var/lib/mesh-lab-runs",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "runtime-env",
|
||||
"type": "file",
|
||||
"path": "${dir:state}/lab.env",
|
||||
"mode": "0600",
|
||||
"content": "MESH_LAB_FORGE=${setting:forge}\n"
|
||||
},
|
||||
{
|
||||
"id": "git",
|
||||
"type": "package",
|
||||
"package": "git"
|
||||
},
|
||||
{
|
||||
"id": "make",
|
||||
"type": "package",
|
||||
"package": "make"
|
||||
},
|
||||
{
|
||||
"id": "python",
|
||||
"type": "package",
|
||||
"package": "python"
|
||||
},
|
||||
{
|
||||
"id": "file",
|
||||
"type": "package",
|
||||
"package": "file"
|
||||
},
|
||||
{
|
||||
"id": "iproute2",
|
||||
"type": "package",
|
||||
"package": "iproute2"
|
||||
},
|
||||
{
|
||||
"id": "sudo",
|
||||
"type": "package",
|
||||
"package": "sudo"
|
||||
},
|
||||
{
|
||||
"id": "npm",
|
||||
"type": "package",
|
||||
"package": "npm"
|
||||
},
|
||||
{
|
||||
"id": "go",
|
||||
"type": "package",
|
||||
"package": "go"
|
||||
},
|
||||
{
|
||||
"id": "incus",
|
||||
"type": "package",
|
||||
"package": "incus"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_LAB_WORK": "${dir:work}",
|
||||
"MESH_LAB_ENV_FILE": "${dir:state}/lab.env"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"name": "@novox/module-lab",
|
||||
"version": "0.1.0",
|
||||
"description": "lab — the lab, as a module: runs beds against the forge's branches when the mesh asks (novox/hq ADR 0172).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": { "@novox/mesh-sdk": "^0.1.0" },
|
||||
"devDependencies": { "@types/node": "^22.0.0", "typescript": "^5.6.0" }
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// lab's tools — the lab, as the mesh asks for it (novox/hq ADR 0172). They run on the machine the
|
||||
// lab is assigned to, and only there: a bed raises virtual machines on that machine's virtualisation.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { listRuns, readStatus, REPOSITORIES, running, start, stop, tail } from "./runs.js";
|
||||
|
||||
export function getLabTools(env: NodeJS.ProcessEnv): ToolDefinition[] {
|
||||
const work = env.MESH_LAB_WORK ?? "/var/lib/mesh-lab-runs";
|
||||
// The forge is an operator's setting, which reaches a file and never a bundle's words (novox/hq
|
||||
// ADR 0192): read from the env-file the mesh fills, at each call, so a changed setting is used
|
||||
// without restarting the runtime. MESH_LAB_FORGE itself still wins, for a hand-run instance.
|
||||
const forgeOf = (): string => (env.MESH_LAB_FORGE ?? wordIn(env.MESH_LAB_ENV_FILE, "MESH_LAB_FORGE")).replace(/\/+$/, "");
|
||||
return [
|
||||
{
|
||||
name: "lab_check",
|
||||
description: "Whether this machine can run the lab's beds: the lab's own check, against the forge's main branch.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const forge = forgeOf();
|
||||
if (!forge) return { ok: false, output: "the lab's forge is not set: settings for lab, {\"forge\": \"<url>\"}" };
|
||||
const dir = `${work}/check`;
|
||||
spawnSync("rm", ["-rf", dir]);
|
||||
const clone = spawnSync("git", ["clone", "--quiet", "--depth", "1", `${forge}/novox/mesh-lab.git`, dir], { encoding: "utf8" });
|
||||
if (clone.status !== 0) return { ok: false, output: clone.stderr };
|
||||
spawnSync("npm", ["ci", "--no-audit", "--no-fund", "--loglevel=error"], { cwd: dir, encoding: "utf8" });
|
||||
const check = spawnSync("node", ["--experimental-strip-types", "src/cli.ts", "check"], { cwd: dir, encoding: "utf8" });
|
||||
return { ok: check.status === 0, output: `${check.stdout}${check.stderr}`.trim() };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lab_run",
|
||||
description:
|
||||
"Run the lab's beds against branches on the forge: fresh checkouts of every repository the lab builds, " +
|
||||
"side by side, then the suite on the named test files. Answers at once with the run's id; lab_status " +
|
||||
"and lab_log follow it. One run at a time.",
|
||||
input: {
|
||||
tests: { type: "string", description: "the bed test files, comma-separated, relative to mesh-lab (e.g. test/integration/mesh.test.ts)" },
|
||||
refs: {
|
||||
type: "string",
|
||||
description: `a JSON object of repository to branch, for any of ${REPOSITORIES.join(", ")}; the rest run main`,
|
||||
},
|
||||
},
|
||||
run: async (args) => {
|
||||
const forge = forgeOf();
|
||||
if (!forge) return { started: false, reason: "the lab's forge is not set: settings for lab, {\"forge\": \"<url>\"}" };
|
||||
const tests = String(args.tests ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
||||
if (tests.length === 0) return { started: false, reason: "name at least one bed test file" };
|
||||
let refs: Record<string, string> = {};
|
||||
if (args.refs) {
|
||||
try {
|
||||
refs = JSON.parse(String(args.refs)) as Record<string, string>;
|
||||
} catch {
|
||||
return { started: false, reason: "refs is not a JSON object of repository to branch" };
|
||||
}
|
||||
}
|
||||
const stranger = Object.keys(refs).filter((r) => !REPOSITORIES.includes(r));
|
||||
if (stranger.length > 0) return { started: false, reason: `the lab does not build ${stranger.join(", ")}` };
|
||||
const busy = running(work);
|
||||
if (busy) return { started: false, reason: `${busy.id} is still ${busy.state}; one run at a time`, running: busy };
|
||||
return { started: true, run: start(work, forge, tests, refs) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lab_status",
|
||||
description: "A run's state, the commits it tested and how it ended — or every run, newest first, when no id is given.",
|
||||
input: { id: { type: "string", description: "the run's id (optional)" } },
|
||||
run: async (args) => {
|
||||
if (args.id) return readStatus(work, String(args.id)) ?? { found: false, id: String(args.id) };
|
||||
return { runs: listRuns(work).slice(0, 10) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lab_log",
|
||||
description: "The last lines of a run's log.",
|
||||
input: {
|
||||
id: { type: "string", description: "the run's id" },
|
||||
lines: { type: "number", description: "how many lines from the end (default 200)" },
|
||||
},
|
||||
run: async (args) => ({ id: String(args.id), log: tail(work, String(args.id), Number(args.lines ?? 200)) }),
|
||||
},
|
||||
{
|
||||
name: "lab_stop",
|
||||
description: "Stop a run and everything it started.",
|
||||
input: { id: { type: "string", description: "the run's id" } },
|
||||
run: async (args) => stop(work, String(args.id)) ?? { found: false, id: String(args.id) },
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** One word from an env-file (`KEY=value` lines), or "" when the file or the word is absent. */
|
||||
export function wordIn(file: string | undefined, word: string): string {
|
||||
if (!file) return "";
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
for (const line of text.split("\n")) {
|
||||
const at = line.indexOf("=");
|
||||
if (at > 0 && line.slice(0, at).trim() === word) return line.slice(at + 1).trim();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
registerModuleTools("lab", (env) => getLabTools(env));
|
||||
@@ -0,0 +1,175 @@
|
||||
// A lab run: fresh checkouts of the named branches, side by side, then the lab's suite on the named
|
||||
// beds (novox/hq ADR 0172).
|
||||
//
|
||||
// **A run is a detached script with its own process group**, so it outlives the tool call that started
|
||||
// it and `stop` ends everything it started. It writes what it is doing to a status file beside its log,
|
||||
// and that file is the whole of what the tools read back: a runtime that restarts mid-run still answers
|
||||
// for it, and says it was lost rather than pretending it is still going.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** The repositories a lab run checks out, side by side, as the lab expects its siblings. */
|
||||
export const REPOSITORIES = ["mesh-lab", "mesh-controller", "mesh-host", "mesh-catalog", "mesh-tools", "mesh-sdk"];
|
||||
|
||||
export interface RunStatus {
|
||||
id: string;
|
||||
state: "checking-out" | "building" | "running" | "passed" | "failed" | "stopped" | "lost";
|
||||
started: string;
|
||||
ended?: string;
|
||||
tests: string[];
|
||||
refs: Record<string, string>;
|
||||
commits?: Record<string, string>;
|
||||
exit?: number;
|
||||
pid?: number;
|
||||
}
|
||||
|
||||
export function runDir(work: string, id: string): string {
|
||||
return join(work, id);
|
||||
}
|
||||
|
||||
function statusPath(work: string, id: string): string {
|
||||
return join(runDir(work, id), "status.json");
|
||||
}
|
||||
|
||||
export function readStatus(work: string, id: string): RunStatus | undefined {
|
||||
try {
|
||||
const s = JSON.parse(readFileSync(statusPath(work, id), "utf8")) as RunStatus;
|
||||
// A run whose process is gone while its status still says it is going was lost — the runtime or
|
||||
// the machine restarted under it. Said, rather than left reading as running for ever.
|
||||
if (!["passed", "failed", "stopped", "lost"].includes(s.state) && s.pid && !alive(s.pid)) {
|
||||
s.state = "lost";
|
||||
}
|
||||
return s;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function alive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function listRuns(work: string): RunStatus[] {
|
||||
if (!existsSync(work)) return [];
|
||||
return readdirSync(work)
|
||||
.filter((d) => d.startsWith("run-"))
|
||||
.map((id) => readStatus(work, id))
|
||||
.filter((s): s is RunStatus => !!s)
|
||||
.sort((a, b) => b.started.localeCompare(a.started));
|
||||
}
|
||||
|
||||
/** The run still going, if any: one at a time, because two would contend for the same machine. */
|
||||
export function running(work: string): RunStatus | undefined {
|
||||
return listRuns(work).find((s) => !["passed", "failed", "stopped", "lost"].includes(s.state));
|
||||
}
|
||||
|
||||
const shellQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/**
|
||||
* The script one run executes. Every step writes its state first, so a run that dies says where.
|
||||
*
|
||||
* The environment is the one the lab's README describes for a run against sibling checkouts, pointed
|
||||
* at this run's own tree, so what is built and claimed is exactly what was checked out.
|
||||
*/
|
||||
export function script(work: string, id: string, forge: string, tests: string[], refs: Record<string, string>): string {
|
||||
const dir = runDir(work, id);
|
||||
const setState = (state: string) =>
|
||||
`node -e ${shellQuote(
|
||||
`const f=${JSON.stringify(join(dir, "status.json"))};const s=JSON.parse(require("fs").readFileSync(f,"utf8"));s.state=${JSON.stringify(state)};require("fs").writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)}`;
|
||||
const clones = REPOSITORIES.map((repo) => {
|
||||
const ref = refs[repo] ?? "main";
|
||||
return [
|
||||
`git clone --quiet --depth 50 --branch ${shellQuote(ref)} ${shellQuote(`${forge}/novox/${repo}.git`)} ${shellQuote(join(dir, repo))}`,
|
||||
`echo "${repo} $(git -C ${shellQuote(join(dir, repo))} rev-parse HEAD)" >> ${shellQuote(join(dir, "commits.txt"))}`,
|
||||
].join("\n");
|
||||
}).join("\n");
|
||||
const bin = join(dir, "bin");
|
||||
return `set -euo pipefail
|
||||
cd ${shellQuote(dir)}
|
||||
${setState("checking-out")}
|
||||
${clones}
|
||||
node -e ${shellQuote(
|
||||
`const fs=require("fs");const f=${JSON.stringify(join(dir, "status.json"))};const s=JSON.parse(fs.readFileSync(f,"utf8"));s.commits=Object.fromEntries(fs.readFileSync(${JSON.stringify(join(dir, "commits.txt"))},"utf8").trim().split("\\n").map(l=>l.split(" ")));fs.writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)}
|
||||
${setState("building")}
|
||||
# The @novox scope resolves from the mesh's own package registry on the forge, as the build machine
|
||||
# resolves it; nothing else is asked of it.
|
||||
printf '%s\n' ${shellQuote(`@novox:registry=${forge}/api/packages/novox/npm/`)} > ${shellQuote(join(dir, ".npmrc"))}
|
||||
export NPM_CONFIG_USERCONFIG=${shellQuote(join(dir, ".npmrc"))}
|
||||
for repo in mesh-sdk mesh-tools mesh-lab; do (cd ${shellQuote(dir)}/$repo && npm ci --no-audit --no-fund --loglevel=error); done
|
||||
(cd ${shellQuote(dir)}/mesh-sdk && npm run build --if-present)
|
||||
(cd ${shellQuote(dir)}/mesh-tools && npm run build --if-present)
|
||||
mkdir -p ${shellQuote(bin)}
|
||||
for p in postgres-provisioner objectstore-provisioner route-proxy; do
|
||||
(cd ${shellQuote(dir)}/mesh-controller && CGO_ENABLED=0 go build -o ${shellQuote(bin)}/$p ./examples/$p)
|
||||
done
|
||||
export MESH_LAB_HOST_BINARY=${shellQuote(join(dir, "mesh-host", "mesh-host"))}
|
||||
export MESH_LAB_BUNDLE=${shellQuote(join(dir, "mesh-host", "examples", "foundation-first-node-nats.lock"))}
|
||||
export MESH_LAB_MODULES=${shellQuote(join(dir, "mesh-controller", "examples", "modules"))}
|
||||
export MESH_LAB_BUILDER=${shellQuote(join(dir, "mesh-controller", "build", "mesh-builder"))}
|
||||
export MESH_LAB_BOOTSTRAP_BINARY=${shellQuote(join(dir, "mesh-host", "mesh-bootstrap"))}
|
||||
export MESH_LAB_CATALOG=${shellQuote(join(dir, "mesh-catalog", "modules"))}
|
||||
export MESH_LAB_PROVISIONER=${shellQuote(join(bin, "postgres-provisioner"))}
|
||||
export MESH_LAB_OBJECTSTORE_PROVISIONER=${shellQuote(join(bin, "objectstore-provisioner"))}
|
||||
export MESH_LAB_ROUTE_PROXY=${shellQuote(join(bin, "route-proxy"))}
|
||||
${setState("running")}
|
||||
cd ${shellQuote(join(dir, "mesh-lab"))}
|
||||
node --experimental-strip-types src/cli.ts suite ${tests.map(shellQuote).join(" ")}
|
||||
`;
|
||||
}
|
||||
|
||||
/** start begins a run and returns at once with its status. */
|
||||
export function start(work: string, forge: string, tests: string[], refs: Record<string, string>): RunStatus {
|
||||
const id = `run-${new Date().toISOString().replace(/[:.]/g, "-")}`;
|
||||
const dir = runDir(work, id);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const status: RunStatus = { id, state: "checking-out", started: new Date().toISOString(), tests, refs };
|
||||
writeFileSync(statusPath(work, id), JSON.stringify(status, null, 2));
|
||||
writeFileSync(join(dir, "run.sh"), script(work, id, forge, tests, refs), { mode: 0o700 });
|
||||
|
||||
// The wrapper records how the run ended, then removes the checkouts and keeps the log and status: a
|
||||
// run's tree is its own, and the next run starts from fresh ones (novox/hq ADR 0172).
|
||||
const wrapper = `bash ${shellQuote(join(dir, "run.sh"))} > ${shellQuote(join(dir, "run.log"))} 2>&1; code=$?
|
||||
node -e ${shellQuote(
|
||||
`const f=${JSON.stringify(statusPath(work, id))};const s=JSON.parse(require("fs").readFileSync(f,"utf8"));if(s.state!=="stopped"){s.state=process.argv[1]==="0"?"passed":"failed"};s.exit=Number(process.argv[1]);s.ended=new Date().toISOString();require("fs").writeFileSync(f,JSON.stringify(s,null,2))`,
|
||||
)} "$code"
|
||||
cd ${shellQuote(dir)} && rm -rf ${REPOSITORIES.map(shellQuote).join(" ")} bin`;
|
||||
const child = spawn("bash", ["-c", wrapper], { detached: true, stdio: "ignore" });
|
||||
child.unref();
|
||||
status.pid = child.pid;
|
||||
writeFileSync(statusPath(work, id), JSON.stringify(status, null, 2));
|
||||
return status;
|
||||
}
|
||||
|
||||
/** stop ends a run and everything it started, by its process group. */
|
||||
export function stop(work: string, id: string): RunStatus | undefined {
|
||||
const s = readStatus(work, id);
|
||||
if (!s || !s.pid) return s;
|
||||
if (["passed", "failed", "stopped", "lost"].includes(s.state)) return s;
|
||||
s.state = "stopped";
|
||||
writeFileSync(statusPath(work, id), JSON.stringify(s, null, 2));
|
||||
try {
|
||||
process.kill(-s.pid, "SIGTERM");
|
||||
} catch {
|
||||
// Already gone between the read and the kill.
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/** tail is the last lines of a run's log. */
|
||||
export function tail(work: string, id: string, lines: number): string {
|
||||
try {
|
||||
const all = readFileSync(join(runDir(work, id), "run.log"), "utf8").split("\n");
|
||||
return all.slice(-Math.max(1, lines)).join("\n");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -8,5 +8,5 @@
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": ["client.ts", "index.ts", "tools/index.ts"]
|
||||
"include": ["tools/index.ts", "tools/runs.ts"]
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
# letta's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/letta
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/letta/dist /app/modules/letta/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/letta/dist/tools/index.js
|
||||
+14
-36
@@ -26,8 +26,7 @@
|
||||
},
|
||||
"own-secrets": {
|
||||
"server-password": "${dir:state}/server-password.secret",
|
||||
"openai-api-key": "${dir:state}/openai-api-key.secret",
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
"openai-api-key": "${dir:state}/openai-api-key.secret"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
@@ -84,45 +83,24 @@
|
||||
"mode": "0600",
|
||||
"content": "{\n \"password\": \"${secret:server-password}\"\n}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-letta",
|
||||
"network": "letta",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_LETTA_URL": "http://letta:8283",
|
||||
"MESH_LETTA_CONFIG_FILE": "/run/config/config.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "tools",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_LETTA_URL": "http://127.0.0.1:${port:8283}",
|
||||
"MESH_LETTA_CONFIG_FILE": "${dir:mesh-state}/config.json"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# lidarr's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
WORKDIR /app/modules/lidarr
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/lidarr/dist /app/modules/lidarr/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/lidarr/dist/index.js,/app/modules/lidarr/dist/tools/index.js
|
||||
@@ -1,144 +0,0 @@
|
||||
// The Lidarr API client — lidarr's own code, living in the module (novox/hq ADR 0039). Ported from
|
||||
// the shared hal `arr` client, but self-contained: in nox each Servarr app owns its own copy, so a
|
||||
// change to Lidarr's API rebuilds only lidarr and nothing else. Both this module's tools and its
|
||||
// events entrypoint import it, and nothing outside lidarr does.
|
||||
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
// Lidarr speaks the v1 API (Radarr/Sonarr are v3); its content is the "artist".
|
||||
const API_VERSION = "v1";
|
||||
const CONTENT_ENDPOINT = "artist";
|
||||
const APP_NAME = "Lidarr";
|
||||
|
||||
export interface LidarrQueueItem {
|
||||
/** The queue record id — stable while the item is in the queue, so events can diff on it. */
|
||||
id: number;
|
||||
title: string;
|
||||
status: string;
|
||||
size: string;
|
||||
sizeleft: string;
|
||||
timeleft?: string;
|
||||
}
|
||||
|
||||
export interface LidarrCalendarItem {
|
||||
title: string;
|
||||
date: string;
|
||||
overview?: string;
|
||||
}
|
||||
|
||||
export interface LidarrContentItem {
|
||||
title: string;
|
||||
status?: string;
|
||||
monitored: boolean;
|
||||
}
|
||||
|
||||
export class LidarrClient {
|
||||
readonly baseUrl: string;
|
||||
|
||||
constructor(
|
||||
url: string,
|
||||
private readonly apiKey: string,
|
||||
) {
|
||||
this.baseUrl = url.replace(/\/$/, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build from the module's resolved environment. The URL defaults to the server on this node (the
|
||||
* runtime shares its network), and the API key is read from MESH_LIDARR_API_KEY or, failing that,
|
||||
* discovered from the server's own config.xml under MESH_LIDARR_CONFIG_DIR — the same file Lidarr
|
||||
* writes it to, so a running server needs nothing configured by hand. Throws when no key can be
|
||||
* found, so the tools/events simply do not load (the harness treats the throw as "exposes
|
||||
* nothing").
|
||||
*/
|
||||
static fromEnv(env: NodeJS.ProcessEnv = process.env): LidarrClient {
|
||||
const url = env.MESH_LIDARR_URL ?? `http://127.0.0.1:${env.MESH_LIDARR_PORT ?? "8686"}`;
|
||||
const configDir = env.MESH_LIDARR_CONFIG_DIR ?? "/config";
|
||||
const apiKey = env.MESH_LIDARR_API_KEY ?? LidarrClient.detectApiKey(configDir);
|
||||
if (!apiKey) {
|
||||
throw new Error("Lidarr not configured — set MESH_LIDARR_API_KEY or make the config dir readable");
|
||||
}
|
||||
return new LidarrClient(url, apiKey);
|
||||
}
|
||||
|
||||
/** Discover the API key from the server's config.xml, falling back to null. Every Servarr app
|
||||
* writes <ApiKey> into config.xml at the root of its config directory. */
|
||||
static detectApiKey(configDir: string): string | null {
|
||||
const config = join(configDir, "config.xml");
|
||||
if (existsSync(config)) {
|
||||
const match = readFileSync(config, "utf8").match(/<ApiKey>([^<]+)<\/ApiKey>/);
|
||||
if (match) return match[1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async get(endpoint: string, params?: Record<string, string>): Promise<unknown> {
|
||||
const url = new URL(`${this.baseUrl}/api/${API_VERSION}/${endpoint}`);
|
||||
if (params) {
|
||||
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
|
||||
}
|
||||
const res = await fetch(url.toString(), { headers: { "X-Api-Key": this.apiKey } });
|
||||
if (!res.ok) throw new Error(`${APP_NAME} API /${endpoint}: ${res.status} ${await res.text()}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async getStatus(): Promise<{ appName: string; version: string }> {
|
||||
const data = (await this.get("system/status")) as { appName?: string; version?: string };
|
||||
return { appName: data.appName || APP_NAME, version: data.version ?? "unknown" };
|
||||
}
|
||||
|
||||
async getContent(limit?: number): Promise<LidarrContentItem[]> {
|
||||
const data = await this.get(CONTENT_ENDPOINT);
|
||||
const items: any[] = Array.isArray(data) ? data : ((data as any)?.records ?? []);
|
||||
const mapped = items.map((item) => ({
|
||||
// Lidarr's content is an artist; its display name is artistName, not title.
|
||||
title: item.artistName ?? item.title ?? "Unknown",
|
||||
status: item.status,
|
||||
monitored: item.monitored ?? true,
|
||||
}));
|
||||
return limit ? mapped.slice(0, limit) : mapped;
|
||||
}
|
||||
|
||||
/** Library search is a filter over existing content, not an indexer lookup — same as hal's. */
|
||||
async searchContent(term: string): Promise<LidarrContentItem[]> {
|
||||
const all = await this.getContent();
|
||||
const lower = term.toLowerCase();
|
||||
return all.filter((item) => item.title.toLowerCase().includes(lower));
|
||||
}
|
||||
|
||||
async getQueue(): Promise<{ totalRecords: number; items: LidarrQueueItem[] }> {
|
||||
const data = (await this.get("queue", { pageSize: "50" })) as { totalRecords?: number; records?: any[] };
|
||||
const records = data.records ?? [];
|
||||
return {
|
||||
totalRecords: data.totalRecords ?? records.length,
|
||||
items: records.map((r) => ({
|
||||
id: r.id,
|
||||
title: r.title ?? r.artist?.artistName ?? r.album?.title ?? "Unknown",
|
||||
status: r.status ?? "unknown",
|
||||
size: formatBytes(r.size ?? 0),
|
||||
sizeleft: formatBytes(r.sizeleft ?? 0),
|
||||
timeleft: r.timeleft,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async getCalendar(days = 7): Promise<LidarrCalendarItem[]> {
|
||||
const start = new Date().toISOString().split("T")[0];
|
||||
const end = new Date(Date.now() + days * 86400000).toISOString().split("T")[0];
|
||||
const data = await this.get("calendar", { start, end });
|
||||
const items: any[] = Array.isArray(data) ? data : [];
|
||||
return items.map((item) => ({
|
||||
// A Lidarr calendar entry is an album release.
|
||||
title: item.title ?? item.artist?.artistName ?? "Unknown",
|
||||
date: item.releaseDate ?? "",
|
||||
overview: item.overview?.slice(0, 150),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return "0 B";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
// lidarr's events. The tool runtime imports this once the broker is bound. It watches the download
|
||||
// queue and turns its comings and goings into mesh events.
|
||||
//
|
||||
// Emits (novox/hq ADR 0041/0042):
|
||||
// module.lidarr.album.grabbed — a release entered the queue (Lidarr grabbed it)
|
||||
// module.lidarr.download.completed — a release left the queue, imported. The download.completed
|
||||
// routing key matches what a media consumer subscribes to
|
||||
// (module.*.download.completed) to rescan its library.
|
||||
// Consumes: none.
|
||||
//
|
||||
// The queue is polled and diffed, primed silently on the first look (like plex's index.ts) so a
|
||||
// restart mid-download does not re-announce everything already in flight as freshly grabbed.
|
||||
|
||||
import { emit } from "@novox/mesh-sdk/events";
|
||||
import { LidarrClient, type LidarrQueueItem } from "./client.js";
|
||||
|
||||
// Building the client throws when Lidarr has no URL/key yet. Like the tools (see tools/index.ts),
|
||||
// the events entrypoint must not crash the runtime for that — it stays idle until configured.
|
||||
function buildClient(): LidarrClient | null {
|
||||
try {
|
||||
return LidarrClient.fromEnv();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const lidarr = buildClient();
|
||||
|
||||
// Lidarr removes an item from the queue once it has been imported; a "warning"/"failed" status is
|
||||
// how a stuck or broken grab shows itself, so we do not call those a completion when they vanish.
|
||||
const FAILED_STATUSES = new Set(["failed", "warning"]);
|
||||
|
||||
const inQueue = new Map<number, LidarrQueueItem>();
|
||||
let primed = false;
|
||||
|
||||
async function pollQueue(lidarr: LidarrClient): Promise<void> {
|
||||
const { items } = await lidarr.getQueue();
|
||||
const now = new Map(items.map((i) => [i.id, i]));
|
||||
|
||||
if (primed) {
|
||||
// Entered the queue since last look — Lidarr grabbed a release.
|
||||
for (const [id, item] of now) {
|
||||
if (!inQueue.has(id)) await emit("album.grabbed", { title: item.title, status: item.status });
|
||||
}
|
||||
// Left the queue — imported and done, unless it was last seen failing.
|
||||
for (const [id, item] of inQueue) {
|
||||
if (!now.has(id) && !FAILED_STATUSES.has(item.status)) {
|
||||
await emit("download.completed", { title: item.title });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inQueue.clear();
|
||||
for (const [id, item] of now) inQueue.set(id, item);
|
||||
primed = true;
|
||||
}
|
||||
|
||||
const tick = (fn: () => Promise<void>, everyMs: number): void => {
|
||||
const run = (): void => void fn().catch((err) => console.error(`[lidarr] ${err}`));
|
||||
setInterval(run, everyMs);
|
||||
run();
|
||||
};
|
||||
|
||||
if (lidarr) {
|
||||
tick(() => pollQueue(lidarr), 30_000);
|
||||
console.log("[lidarr] watching the download queue, emitting grabs and completions");
|
||||
} else {
|
||||
console.log("[lidarr] not configured — events idle until an API key is available");
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
{
|
||||
"module": "lidarr",
|
||||
"version": "1",
|
||||
"capabilities": [
|
||||
"container-runtime"
|
||||
],
|
||||
"emits": [
|
||||
"album.grabbed",
|
||||
"download.completed"
|
||||
],
|
||||
"consumes": [],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"listens": [
|
||||
{
|
||||
"name": "web",
|
||||
"port": 8686,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "managing music"
|
||||
}
|
||||
],
|
||||
"accesses": [
|
||||
{
|
||||
"id": "music",
|
||||
"path": "/services/media/music",
|
||||
"mode": "read-write"
|
||||
},
|
||||
{
|
||||
"id": "downloads",
|
||||
"path": "/services/media/downloads",
|
||||
"mode": "read-write"
|
||||
}
|
||||
],
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "config",
|
||||
"type": "directory",
|
||||
"path": "/services/lidarr/config",
|
||||
"mode": "0700",
|
||||
"owner": "1000:1000"
|
||||
},
|
||||
{
|
||||
"id": "server",
|
||||
"type": "container",
|
||||
"name": "lidarr",
|
||||
"image": "lscr.io/linuxserver/lidarr@sha256:6b38dd330b0c653351c2e23c8b962ea51c95683dd7acace9d106c922baf85f75",
|
||||
"env": {
|
||||
"PUID": "1000",
|
||||
"PGID": "1000",
|
||||
"TZ": "Etc/UTC"
|
||||
},
|
||||
"ports": [
|
||||
"8686"
|
||||
],
|
||||
"volumes": [
|
||||
"/services/lidarr/config:/config",
|
||||
"${access:music}:/music",
|
||||
"${access:downloads}:/downloads"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-lidarr",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"/services/lidarr/config:/var/lib/lidarr/config:ro"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_LIDARR_URL": "http://127.0.0.1:8686",
|
||||
"MESH_LIDARR_CONFIG_DIR": "/var/lib/lidarr/config"
|
||||
},
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"requires": [
|
||||
"route"
|
||||
],
|
||||
"contributes": {
|
||||
"route": {
|
||||
"label": "lidarr",
|
||||
"endpoint": "web"
|
||||
}
|
||||
},
|
||||
"binds": {
|
||||
"route": "${dir:mesh-state}/route.json"
|
||||
},
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
{
|
||||
"name": "@novox/module-lidarr",
|
||||
"version": "0.1.0",
|
||||
"description": "lidarr — music management. Its API client, tools and events live here (novox/hq ADR 0039).",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@novox/mesh-sdk": "^0.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.0.0",
|
||||
"typescript": "^5.6.0"
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
// lidarr's tools — ported from the shared hal sdk (novox/hq ADR 0039), importing lidarr's own
|
||||
// client. They return structured data (not pre-formatted text as hal did); the mesh serves them
|
||||
// through the sdk's tool harness.
|
||||
|
||||
import { registerModuleTools, type ToolDefinition } from "@novox/mesh-sdk/tools";
|
||||
import { LidarrClient } from "../client.js";
|
||||
|
||||
export function getLidarrTools(lidarr: LidarrClient): ToolDefinition[] {
|
||||
return [
|
||||
{
|
||||
name: "lidarr_status",
|
||||
description: "Lidarr status overview: version, artist count, monitored count, queue size.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const [status, content, queue] = await Promise.all([
|
||||
lidarr.getStatus(),
|
||||
lidarr.getContent(),
|
||||
lidarr.getQueue(),
|
||||
]);
|
||||
return {
|
||||
app: status.appName,
|
||||
version: status.version,
|
||||
artists: content.length,
|
||||
monitored: content.filter((c) => c.monitored).length,
|
||||
queue: queue.totalRecords,
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lidarr_library",
|
||||
description: "List artists from the Lidarr library.",
|
||||
input: { limit: { type: "number", description: "max items to return (default 50)" } },
|
||||
run: async (args) => {
|
||||
const items = await lidarr.getContent(args.limit ? Number(args.limit) : 50);
|
||||
return { count: items.length, artists: items };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lidarr_search",
|
||||
description: "Search the Lidarr library for artists by name (filters existing content, not indexers).",
|
||||
input: { query: { type: "string", description: "the search term" } },
|
||||
run: async (args) => {
|
||||
const query = String(args.query);
|
||||
return { query, results: await lidarr.searchContent(query) };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lidarr_queue",
|
||||
description: "Show the Lidarr download queue — what is downloading and how far along.",
|
||||
input: {},
|
||||
run: async () => {
|
||||
const queue = await lidarr.getQueue();
|
||||
return { count: queue.totalRecords, items: queue.items };
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "lidarr_calendar",
|
||||
description: "Upcoming album releases from the Lidarr calendar.",
|
||||
input: { days: { type: "number", description: "how many days to look ahead (default 7)" } },
|
||||
run: async (args) => {
|
||||
const days = args.days ? Number(args.days) : 7;
|
||||
const items = await lidarr.getCalendar(days);
|
||||
items.sort((a, b) => a.date.localeCompare(b.date));
|
||||
return { days, count: items.length, items };
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// The tools exist only when Lidarr is configured; without a URL and key, lidarr contributes none
|
||||
// rather than failing the whole runtime.
|
||||
registerModuleTools("lidarr", (env) => {
|
||||
try {
|
||||
return getLidarrTools(LidarrClient.fromEnv(env));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
# mailu's runtime: the tool runtime, carrying this module's compiled code.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk and the tool runtime are in
|
||||
# the base images, published like any other artifact — which is what makes this buildable by the
|
||||
# mesh from a repository and a path (novox/hq ADR 0069) rather than only on a workstation that
|
||||
# happens to have the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned (novox/hq issue 044): the image this is COMPILED in and the
|
||||
# image it RUNS in — the second must not carry a compiler. Declared in module.json's `build.on`.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the sdk it will run against. The compiler
|
||||
# is invoked by its real path: node_modules/.bin entries are launcher symlinks the base image
|
||||
# resolved away.
|
||||
WORKDIR /app/modules/mailu
|
||||
COPY . .
|
||||
RUN node /app/node_modules/typescript/bin/tsc client.ts index.ts tools/index.ts provisioner/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/mailu/dist /app/modules/mailu/dist
|
||||
# Every serve-time entrypoint, loaded by the runtime in serve mode: tools and events serve, and a
|
||||
# provider's provisioner runs its reconcile loop in the same process, with the broker connected —
|
||||
# the convention novox/hq issues 060/061 settled. A container that instead ran only its
|
||||
# provisioner (`run`) served no tools and emitted no events; a container that named no command
|
||||
# ran no provisioner at all.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/mailu/dist/index.js,/app/modules/mailu/dist/tools/index.js,/app/modules/mailu/dist/provisioner/index.js
|
||||
+40
-43
@@ -135,11 +135,15 @@
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "automx: mail client autoconfiguration; the autoconfig, autodiscover and automx names are route grants reaching it here"
|
||||
},
|
||||
{
|
||||
"name": "admin-api",
|
||||
"port": 8080,
|
||||
"protocol": "tcp",
|
||||
"from": "machine",
|
||||
"why": "the admin API, which this module's own code reaches on loopback from the node's runtime now that it runs outside the mailu network"
|
||||
}
|
||||
],
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
@@ -305,6 +309,9 @@
|
||||
"name": "mailu-admin",
|
||||
"image": "ghcr.io/mailu/admin@sha256:6dbfdadc4a9590dcb7652357b505200115b689b74008653bbf369e4599a3be5a",
|
||||
"network": "mailu",
|
||||
"ports": [
|
||||
"8080"
|
||||
],
|
||||
"env-file": [
|
||||
"${dir:state}/mailu.env",
|
||||
"${dir:state}/secret.env",
|
||||
@@ -462,7 +469,8 @@
|
||||
],
|
||||
"dns": [
|
||||
"192.168.203.254"
|
||||
]
|
||||
],
|
||||
"logging": "journald"
|
||||
},
|
||||
{
|
||||
"id": "runtime-config",
|
||||
@@ -472,31 +480,6 @@
|
||||
"content": "{}\n",
|
||||
"merge": "json"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-mailu",
|
||||
"network": "mailu",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:state}/api-token.secret:/run/secrets/api-token:ro",
|
||||
"${dir:grants}:${dir:grants}:ro",
|
||||
"${dir:mesh-state}/config.json:/run/config/config.json:ro",
|
||||
"/var/run/docker.sock:/var/run/docker.sock"
|
||||
],
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"MESH_MAILU_URL": "http://mailu-admin:8080/api/v1",
|
||||
"MESH_MAILU_API_KEY_FILE": "/run/secrets/api-token",
|
||||
"MESH_MAILU_IMAP_CONTAINER": "mailu-imap",
|
||||
"MESH_MAILU_CONFIG_FILE": "/run/config/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
},
|
||||
"restart-on": [
|
||||
"runtime-config"
|
||||
],
|
||||
"artifact": "runtime"
|
||||
},
|
||||
{
|
||||
"id": "automx",
|
||||
"type": "container",
|
||||
@@ -516,16 +499,6 @@
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
},
|
||||
{
|
||||
"arg": "PYTHON_BASE",
|
||||
"image": "python@sha256:25f3cfeaceca14921366af4d1240b56457ef46273bdb508c7b0e8f469f6fd228"
|
||||
@@ -533,9 +506,26 @@
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"provisioner/index.js"
|
||||
],
|
||||
"env": {
|
||||
"MESH_MAILU_URL": "http://127.0.0.1:${port:8080}/api/v1",
|
||||
"MESH_MAILU_API_KEY_FILE": "${dir:state}/api-token.secret",
|
||||
"MESH_MAILU_IMAP_CONTAINER": "mailu-imap",
|
||||
"MESH_MAILU_CONFIG_FILE": "${dir:mesh-state}/config.json",
|
||||
"MESH_RECEIVES": "${dir:grants}/mesh.json"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "automx",
|
||||
@@ -561,5 +551,12 @@
|
||||
},
|
||||
"grants": {
|
||||
"smtp": "${dir:grants}"
|
||||
}
|
||||
},
|
||||
"jails": [
|
||||
{
|
||||
"name": "mailu-front",
|
||||
"failregex": "^.*(?:imap|pop3|submission|managesieve)-login: .*\\(auth failed, \\d+ attempts(?: in \\d+ secs)?\\):.*rip=<HOST>(?:,|$)",
|
||||
"jail": "backend = systemd\njournalmatch = CONTAINER_NAME=mailu-front\nport = smtp,submission,submissions,imap,imaps,pop3,pop3s\nmaxretry = 3\nfindtime = 1d\nbantime = 1d"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
# mesh-catalog's runtime: the tool runtime, carrying the catalogue's compiled graph, its consumer
|
||||
# of what the builder announces, and its tools.
|
||||
#
|
||||
# **Built from this module's own directory and nothing else.** The sdk is in the base image, so
|
||||
# nothing is copied out of a neighbouring checkout — which is what lets the mesh build this from a
|
||||
# repository and a path (novox/hq ADR 0069) rather than only on a workstation with the siblings.
|
||||
#
|
||||
# Two bases, named rather than pinned: the image this is COMPILED in, and the image it RUNS in.
|
||||
# They are different images on purpose — the first carries a compiler and the second must not, or
|
||||
# every running container would carry one it never invokes. The mesh answers both with the copies it
|
||||
# holds, because a fingerprint written here would name one particular copy and no other mesh has it
|
||||
# (novox/hq issue 044). Declared in module.json's `build.on`; deliberately no defaults, so a build
|
||||
# nobody told stops here and says which module to build first.
|
||||
ARG BUILD_BASE
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${BUILD_BASE} AS build
|
||||
# Compiled under /app/modules so `@novox/mesh-sdk` resolves upward into the base's own
|
||||
# node_modules — the module is compiled against exactly the sdk it will run against.
|
||||
WORKDIR /app/modules/mesh-catalog
|
||||
COPY . .
|
||||
# The compiler is invoked by its real path rather than through node_modules/.bin, whose entries are
|
||||
# symlinks to a launcher that requires its library relatively — resolved away when the base image
|
||||
# was assembled.
|
||||
RUN node /app/node_modules/typescript/bin/tsc pg.d.ts store.ts index.ts tools/index.ts prepare/index.ts \
|
||||
--module NodeNext --moduleResolution NodeNext --target ES2022 --outDir dist
|
||||
|
||||
# **A module may need something the base image does not carry.** The base holds what every module
|
||||
# needs — the sdk, the broker client — and a postgres driver is not that: the one other module that
|
||||
# reaches a database shells out to psql instead. So the catalogue brings its own.
|
||||
#
|
||||
# Installed into an empty directory rather than into the module's, because the module's package.json
|
||||
# also names `@novox/mesh-sdk`, which is not on any registry — it is in the base image. Asking npm to
|
||||
# resolve this module's dependencies would therefore fail on the one it already has.
|
||||
RUN mkdir -p /deps && cd /deps && \
|
||||
npm install --omit=dev --no-audit --no-fund --no-package-lock pg@8
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
COPY --from=build /app/modules/mesh-catalog/dist /app/modules/mesh-catalog/dist
|
||||
# Beside the compiled code, so `pg` resolves from it while `@novox/mesh-sdk` keeps walking up to the
|
||||
# base image's own node_modules — the module gets its extra dependency without shadowing the sdk it
|
||||
# was compiled against.
|
||||
COPY --from=build /deps/node_modules /app/modules/mesh-catalog/node_modules
|
||||
# Both entrypoints, loaded in serve mode.
|
||||
#
|
||||
# **A consumer cannot be started with `run`.** That mode imports an entrypoint without binding a
|
||||
# broker — it is for a step that does its work offline and exits — and the catalogue's whole job is
|
||||
# to listen for what the builder announces. Serve binds the broker first, then imports these, so
|
||||
# `on()` has something to subscribe to.
|
||||
ENV MESH_TOOL_MODULES=/app/modules/mesh-catalog/dist/index.js,/app/modules/mesh-catalog/dist/tools/index.js
|
||||
|
||||
# And what prepares this module's state, for the runtime's `prepare` mode (novox/hq ADR 0135). Named
|
||||
# here, beside the entrypoints above, because the module knows which of its files prepares its state
|
||||
# and nothing else could: the mesh asks one word and this says what answers it.
|
||||
ENV MESH_PREPARE=/app/modules/mesh-catalog/dist/prepare/index.js
|
||||
@@ -25,9 +25,6 @@
|
||||
"secrets": {
|
||||
"postgres-database": "${dir:state}/database.secret"
|
||||
},
|
||||
"own-secrets": {
|
||||
"broker": "${dir:mesh-state}/broker"
|
||||
},
|
||||
"consumes": [
|
||||
"mesh-build-machine.built",
|
||||
"mesh-controller.built-before"
|
||||
@@ -38,14 +35,7 @@
|
||||
"rebuild-needed",
|
||||
"catching-up"
|
||||
],
|
||||
"prepares": true,
|
||||
"resources": [
|
||||
{
|
||||
"id": "mesh-state",
|
||||
"type": "directory",
|
||||
"mode": "0700",
|
||||
"place": "mesh"
|
||||
},
|
||||
{
|
||||
"id": "state",
|
||||
"type": "directory",
|
||||
@@ -60,43 +50,41 @@
|
||||
"content": "postgresql://${bound:postgres-database:as}:${secret:postgres-database}@${bound:postgres-database:at}:${bound:postgres-database:port}/${bound:postgres-database:as}\n"
|
||||
},
|
||||
{
|
||||
"id": "runtime",
|
||||
"type": "container",
|
||||
"name": "mesh-catalog",
|
||||
"network": "host",
|
||||
"volumes": [
|
||||
"${dir:mesh-state}/broker:/run/secrets/broker:ro",
|
||||
"${dir:state}:/run/state",
|
||||
"${dir:state}/database.url:/run/secrets/database-url:ro"
|
||||
"id": "prepare",
|
||||
"type": "process",
|
||||
"name": "mesh-catalog-prepare",
|
||||
"artifact": "code",
|
||||
"run": [
|
||||
"node",
|
||||
"prepare/index.js"
|
||||
],
|
||||
"run-once": true,
|
||||
"env": {
|
||||
"MESH_BROKER_FILE": "/run/secrets/broker",
|
||||
"DATABASE_URL_FILE": "/run/secrets/database-url"
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url"
|
||||
},
|
||||
"artifact": "runtime",
|
||||
"restart-on": [
|
||||
"database-url"
|
||||
]
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"on": [
|
||||
{
|
||||
"arg": "BUILD_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "build"
|
||||
},
|
||||
{
|
||||
"arg": "RUNTIME_BASE",
|
||||
"module": "mesh-tools",
|
||||
"artifact": "runtime"
|
||||
}
|
||||
],
|
||||
"artifacts": [
|
||||
{
|
||||
"name": "runtime",
|
||||
"kind": "image",
|
||||
"from": "Dockerfile"
|
||||
"name": "code",
|
||||
"kind": "bundle",
|
||||
"language": "typescript",
|
||||
"entrypoints": [
|
||||
"index.js",
|
||||
"tools/index.js",
|
||||
"prepare/index.js"
|
||||
],
|
||||
"loads": [
|
||||
"index.js",
|
||||
"tools/index.js"
|
||||
],
|
||||
"env": {
|
||||
"DATABASE_URL_FILE": "${dir:state}/database.url"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Vendored
+3
-3
@@ -1,9 +1,9 @@
|
||||
// Ambient types for `pg` (node-postgres), which ships its types only via the separate `@types/pg`
|
||||
// package. Rather than pull that in at tsc time, this declares the exact slice model-usage uses —
|
||||
// the same precedent anthropic-manager sets for `tweetnacl-sealedbox-js` (a local ambient .d.ts,
|
||||
// listed in tsconfig `include`, default-imported). The real `pg` is installed into the module's
|
||||
// runtime image (package.json `dependencies`; novox/hq ADR 0052), so this types the code without
|
||||
// deciding what runs.
|
||||
// listed in tsconfig `include`, default-imported). The real `pg` is the package.json dependency the
|
||||
// builder installs and inlines into the module's bundle (novox/hq ADR 0198 §4), so this types the
|
||||
// code without deciding what runs.
|
||||
declare module "pg" {
|
||||
/** One checked-out connection. Needed because registering a module-version and its edges is one
|
||||
* act: a half-written registration is a graph that lies about what something was built against. */
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
// nothing anywhere said so.
|
||||
//
|
||||
// Nothing here connects to the broker. Preparation runs before the version that would use it, so
|
||||
// there is nothing yet to talk to; the runtime's `prepare` mode imports this and awaits it, and this
|
||||
// process exiting non-zero is how the host knows not to start the runtime.
|
||||
// there is nothing yet to talk to: the host runs this file as a run-once process, with the module's
|
||||
// words and no bus (novox/hq ADR 0198 §3), before the node's runtime is started with the version
|
||||
// that needs it, and this process exiting non-zero is how the host knows the step did not complete.
|
||||
import { Graph } from "../store.js";
|
||||
|
||||
const graph = Graph.fromEnv();
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
# The console (novox/hq ADR 0152, design 34): the mesh's tools for whoever is on a machine, served
|
||||
# over MCP on that machine's loopback.
|
||||
#
|
||||
# **Nothing is compiled here.** The console is the tool runtime's own client — `mesh serve` — which
|
||||
# the runtime image already carries beside the runtime it runs modules with. This recipe changes the
|
||||
# program the image starts and nothing else, so the console is exactly the client a person can run by
|
||||
# hand, started by the mesh instead, on the credential the mesh sealed to the machine.
|
||||
#
|
||||
# One base, named rather than pinned: the mesh answers with the copy it holds (novox/hq issue 044).
|
||||
ARG RUNTIME_BASE
|
||||
|
||||
FROM ${RUNTIME_BASE}
|
||||
ENTRYPOINT ["node", "dist/mesh.js"]
|
||||
@@ -1,38 +0,0 @@
|
||||
# mesh-console
|
||||
|
||||
The mesh's tools, on the machine a person sits at, served by a module the mesh assigned there
|
||||
(novox/hq [ADR 0152](https://git.novox.be/novox/hq), design 34).
|
||||
|
||||
Assign it to a machine and an agent on that machine has the mesh's tools at
|
||||
`http://127.0.0.1:<port>/mcp` — MCP over HTTP, `initialize`, `tools/list`, `tools/call`. A person at
|
||||
a terminal reaches the same endpoint with `mesh tools --console http://127.0.0.1:<port>` and
|
||||
`mesh call <module>.<tool> --console …`, with no credential of their own: the console holds it.
|
||||
|
||||
## What it is
|
||||
|
||||
The tool runtime's own client, `mesh serve`, started by the mesh on the credential it sealed to the
|
||||
machine for `<node>.mesh-console`. The manifest says three things nothing else in the catalogue says
|
||||
together:
|
||||
|
||||
- `invokes: ["*"]` — it calls every tool on the mesh, and the bus grants exactly that publish side;
|
||||
- a listener `from: machine` — loopback only, and the filter opens nothing for it;
|
||||
- no `emits`, no `consumes`, no `tools` — nothing on the bus can address it.
|
||||
|
||||
**Loopback is the authority boundary.** Whoever can connect is on the machine, and whoever is on the
|
||||
machine is the account that owns the mesh there (ADR 0034, ADR 0144). There is no token and no login,
|
||||
and `mesh serve` refuses to bind anything but a loopback address.
|
||||
|
||||
## What it lists
|
||||
|
||||
What the running modules answer: every tool runtime serves a `tools` verb for its module, and the
|
||||
console asks the catalogue which modules the mesh holds and each module what it serves. A module that
|
||||
did not answer — not assigned, not up, or built before the runtime answered `tools` — is named in the
|
||||
list's `_meta.notAnswering` and can still be called by `<module>.<tool>`.
|
||||
|
||||
The mesh's own verbs (`status`, `push`, `assign`) are the `mesh-controller` seat's tools under
|
||||
ADR 0132 and are not served on the bus yet; they appear here when they are.
|
||||
|
||||
## Port
|
||||
|
||||
The manifest declares port 4270 and the mesh assigns the machine port as it does for any listener;
|
||||
the console binds `127.0.0.1:${port:4270}`. `node show <machine>` says which port a machine was given.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user