feat: chained notebooks with when sections and host blocks (#11)
A notebook can include another one and continue with what it produced:
- core: parse :::when{param=a,b}, ::use{notebook= as= with=} and
::host{name= address= user= port= capture=}; composeNotebook namespaces
an included notebook's params, steps, captures and templates by alias
(cycles, missing files, depth > 4 and child errors are reported on the
use line). Defaults may reference captures and builtins
({{shellbook.public_key}}); required params and secrets gate only steps
of their own scope; secretEnv passes a scope's secrets under local names.
- protocol: NotebookResponse gains includes and builtins.
- server: compose includes on load, inject builtins (client values are
ignored), refuse steps in inactive when sections.
- web: render when/use/host blocks, group included params in the form,
add a created machine to Hosts and capture its name, reload when an
included notebook changes, run all checks only for active steps,
authoring snippets for when, use and host.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { registerSettings } from "./settings";
|
||||
import { hostsPlugin } from "./hosts";
|
||||
import { builtinValues, hostsPlugin } from "./hosts";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import websocket from "@fastify/websocket";
|
||||
import { loadConfig, type ServerConfig } from "./config";
|
||||
@@ -42,9 +42,10 @@ export async function buildApp(options: AppOptions = {}): Promise<FastifyInstanc
|
||||
if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth });
|
||||
await registerSettings(app, config);
|
||||
await app.register(websocket);
|
||||
await app.register(workspacePlugin, { config });
|
||||
const builtins = () => builtinValues(config);
|
||||
await app.register(workspacePlugin, { config, builtins });
|
||||
await app.register(hostsPlugin, { config });
|
||||
await app.register(runsPlugin, { config, hub });
|
||||
await app.register(runsPlugin, { config, hub, builtins });
|
||||
await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir });
|
||||
await app.register(chatPlugin, { config });
|
||||
|
||||
|
||||
@@ -43,6 +43,11 @@ export async function shellbookPublicKey(config: ServerConfig) {
|
||||
throw httpError(503, "ShellBook key unavailable");
|
||||
return `${parsed.type} ${parsed.getPublicSSH().toString("base64")}`;
|
||||
}
|
||||
/** Runtime values every notebook can reference ({{shellbook.public_key}}); empty when the key is unavailable. */
|
||||
export async function builtinValues(config: ServerConfig): Promise<Record<string, string>> {
|
||||
try { return { "shellbook.public_key": await shellbookPublicKey(config) }; }
|
||||
catch { return {}; }
|
||||
}
|
||||
export async function hostsPlugin(
|
||||
app: FastifyInstance,
|
||||
{ config }: { config: ServerConfig },
|
||||
|
||||
@@ -3,38 +3,41 @@ import { randomUUID } from "node:crypto";
|
||||
import { appendFile, mkdir, copyFile, stat, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { parseNotebook, resolveParams, renderStep, secretEnv, shellQuote, type Block, type Step, type Notebook, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
|
||||
import { blockActive, findStep, isBuiltin, resolveParams, renderStep, secretEnv, shellQuote, type Step, type Notebook, type ParamValues, type RenderedStep, type StartRunRequest, type HostInfo } from "@shellbook/core";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { Client } from "ssh2";
|
||||
import type { ServerConfig } from "../config";
|
||||
import { readHosts, readNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||
import { readHosts, loadNotebook, safeFile, safeRelative, httpError, SerialQueue } from "../workspace";
|
||||
import { connect, exec, localExec, scriptInput, sftp, sftpRequest, transfer, HostKeyError, sshFailure, type Output } from "../ssh";
|
||||
import { EventsHub } from "./events";
|
||||
import { runRoot, artifactFile, persistArtifacts, isSensitive, claimArtifact, sweepRuns } from "./artifacts";
|
||||
export { EventsHub } from "./events";
|
||||
|
||||
export function findStep(blocks: Block[], id: string): Step | undefined {
|
||||
for (const block of blocks) {
|
||||
if (block.type === "step" && block.step.attrs.id === id) return block.step;
|
||||
if (block.type === "after") { const found = findStep(block.blocks, id); if (found) return found; }
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[]) {
|
||||
/** `notebook` is the composed notebook (see loadNotebook); builtins come from the server only. */
|
||||
export function prepareRun(notebook: Notebook, req: StartRunRequest, hosts: HostInfo[], builtins: ParamValues = {}) {
|
||||
if (notebook.diagnostics.some(d => d.severity === "error")) throw httpError(400, "Notebook has errors");
|
||||
const step = findStep(notebook.blocks, req.stepId);
|
||||
if (!step) throw httpError(404, "Step not found");
|
||||
const names = hosts.map(h => h.name);
|
||||
const resolved = resolveParams(notebook, req.params, names);
|
||||
if (Object.keys(resolved.errors).length) throw httpError(400, "Parameters are missing or invalid");
|
||||
const rendered = renderStep(notebook, step, resolved.values, req.runtime, names);
|
||||
// A client cannot supply or override builtins.
|
||||
const runtime: ParamValues = Object.assign(Object.create(null) as ParamValues,
|
||||
Object.fromEntries(Object.entries(req.runtime).filter(([name]) => !isBuiltin(name))), builtins);
|
||||
const resolved = resolveParams(notebook, req.params, names, runtime);
|
||||
// Only parameters of the step's own scope gate it (an included notebook's form does not block the parent).
|
||||
// Same rule as core's renderStep: required params and secrets of the step's scope gate it;
|
||||
// other params only matter when the step references them (checked by renderStep below).
|
||||
const scope = step.attrs.scope ?? "";
|
||||
const gating = notebook.params.filter(def => (def.scope ?? "") === scope && (def.required || def.type === "secret"));
|
||||
if (gating.some(def => Object.hasOwn(resolved.errors, def.name))) throw httpError(400, "Parameters are missing or invalid");
|
||||
if (!blockActive(notebook, step.attrs.id, resolved.values)) throw httpError(400, "Step is not part of the selected options");
|
||||
const rendered = renderStep(notebook, step, resolved.values, runtime, names);
|
||||
if (rendered.missing.length || Object.keys(rendered.invalid).length) throw httpError(400, "Step parameters are missing or invalid");
|
||||
const host = hosts.find(h => h.name === rendered.host);
|
||||
if (!rendered.local && !host) throw httpError(400, "Unknown target host");
|
||||
for (const name of rendered.artifacts) safeRelative(name);
|
||||
if (rendered.kind === "check" && (rendered.uploads.length || rendered.artifacts.length)) throw httpError(400, "Checks cannot upload or collect artifacts");
|
||||
if (!Number.isFinite(step.attrs.timeoutSec) || step.attrs.timeoutSec <= 0) throw httpError(400, "Invalid timeout");
|
||||
return { step, rendered, host, env: secretEnv(notebook, resolved.values) };
|
||||
return { step, rendered, host, env: secretEnv(notebook, resolved.values, step.attrs.scope) };
|
||||
}
|
||||
|
||||
/** Streaming redaction retains possible secret prefixes across chunks. */
|
||||
@@ -179,7 +182,7 @@ export async function executeRun({ config, hub, runId, request, step, rendered,
|
||||
function stringMap(value: unknown): value is Record<string, string> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(v => typeof v === "string");
|
||||
}
|
||||
export async function runsPlugin(app: FastifyInstance, { config, hub }: { config: ServerConfig; hub: EventsHub }) {
|
||||
export async function runsPlugin(app: FastifyInstance, { config, hub, builtins = async () => ({}) }: { config: ServerConfig; hub: EventsHub; builtins?: () => Promise<ParamValues> }) {
|
||||
const queue = new SerialQueue();
|
||||
const active = new Set<string>();
|
||||
const downloads = new Set<Promise<void>>();
|
||||
@@ -197,8 +200,8 @@ export async function runsPlugin(app: FastifyInstance, { config, hub }: { config
|
||||
app.post<{ Body: StartRunRequest }>("/api/runs", async (req, reply) => {
|
||||
const body = req.body;
|
||||
if (!body || typeof body.notebookPath !== "string" || typeof body.stepId !== "string" || !stringMap(body.params) || !stringMap(body.runtime) || !stringMap(body.artifactSources) || (body.acceptHostKey !== undefined && typeof body.acceptHostKey !== "string")) throw httpError(400, "Invalid run request");
|
||||
const { source } = await readNotebook(config, body.notebookPath);
|
||||
const prepared = prepareRun(parseNotebook(source), body, await readHosts(config));
|
||||
const { notebook } = await loadNotebook(config, body.notebookPath);
|
||||
const prepared = prepareRun(notebook, body, await readHosts(config), await builtins());
|
||||
const runId = randomUUID();
|
||||
active.add(runId);
|
||||
// Queue immediately; defer the work to allow the HTTP response to reach the subscriber.
|
||||
|
||||
@@ -4,7 +4,7 @@ import { readFile, readdir, realpath, lstat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { parse } from "yaml";
|
||||
import { validateHost } from "../hosts/validation";
|
||||
import { parseNotebook, type HostInfo } from "@shellbook/core";
|
||||
import { composeNotebook, notebookIncludes, parseNotebook, type HostInfo, type Notebook, type ParamValues } from "@shellbook/core";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import type { ServerConfig } from "../config";
|
||||
|
||||
@@ -43,6 +43,29 @@ export async function readNotebook(config: ServerConfig, name: string) {
|
||||
return { file, source: await readFile(file, "utf8") };
|
||||
}
|
||||
|
||||
/** Upper bound on notebook files read for one composition (includes of includes). */
|
||||
const MAX_INCLUDE_FILES = 32;
|
||||
|
||||
/**
|
||||
* Read a notebook and compose its `::use` includes. Included files go through the same
|
||||
* workspace path rules; unreadable ones become "not found" diagnostics on the use line.
|
||||
*/
|
||||
export async function loadNotebook(config: ServerConfig, name: string) {
|
||||
const { file, source } = await readNotebook(config, name);
|
||||
const root = parseNotebook(source);
|
||||
const parsed = new Map<string, Notebook | undefined>([[name, root]]);
|
||||
const queue = notebookIncludes(root);
|
||||
while (queue.length && parsed.size < MAX_INCLUDE_FILES) {
|
||||
const next = queue.shift()!;
|
||||
if (parsed.has(next)) continue;
|
||||
const included = await readNotebook(config, next).then(r => parseNotebook(r.source), () => undefined);
|
||||
parsed.set(next, included);
|
||||
if (included) queue.push(...notebookIncludes(included));
|
||||
}
|
||||
const notebook = composeNotebook(name, root, include => parsed.get(include));
|
||||
return { file, source, notebook, includes: [...parsed.keys()].filter(include => include !== name) };
|
||||
}
|
||||
|
||||
export async function readHosts(config: ServerConfig): Promise<HostInfo[]> {
|
||||
return parseHosts(await readFile(path.join(config.workspaceDir, "hosts.yaml"), "utf8"));
|
||||
}
|
||||
@@ -72,7 +95,13 @@ export class SerialQueue {
|
||||
async idle() { await Promise.allSettled(this.tails.values()); }
|
||||
}
|
||||
|
||||
export async function workspacePlugin(app: FastifyInstance, { config }: { config: ServerConfig }) {
|
||||
export interface WorkspaceOptions {
|
||||
config: ServerConfig;
|
||||
/** Server-provided runtime values such as shellbook.public_key. */
|
||||
builtins?: () => Promise<ParamValues>;
|
||||
}
|
||||
|
||||
export async function workspacePlugin(app: FastifyInstance, { config, builtins = async () => ({}) }: WorkspaceOptions) {
|
||||
const saves = new SerialQueue();
|
||||
notebookManagement(app, config, saves);
|
||||
app.get("/api/hosts", async () => ({ hosts: await readHosts(config) }));
|
||||
@@ -93,8 +122,8 @@ export async function workspacePlugin(app: FastifyInstance, { config }: { config
|
||||
return { notebooks: notebooks.sort((a, b) => a.path.localeCompare(b.path)) };
|
||||
});
|
||||
app.get<{ Params: { path: string } }>("/api/notebooks/:path", async req => {
|
||||
const { source } = await readNotebook(config, req.params.path);
|
||||
return { path: req.params.path, source, notebook: parseNotebook(source), version: version(source) };
|
||||
const { source, notebook, includes } = await loadNotebook(config, req.params.path);
|
||||
return { path: req.params.path, source, notebook, includes, builtins: await builtins(), version: version(source) };
|
||||
});
|
||||
app.put<{ Params: { path: string }; Body: { source: string; baseVersion: string } }>("/api/notebooks/:path", async req => {
|
||||
if (!req.body || typeof req.body.source !== "string" || typeof req.body.baseVersion !== "string") throw httpError(400, "Invalid save request");
|
||||
|
||||
Reference in New Issue
Block a user