chore: add pnpm monorepo skeleton with core contracts

Shared notebook model (types.ts), HTTP/WebSocket protocol (protocol.ts) and
core function signatures (stubs) so core, server and web can be built in
parallel. Minimal Fastify server with a health route and test.
This commit is contained in:
Florian Schmidt
2026-11-15 23:51:06 +01:00
parent a5fea2f82f
commit d06f4336ae
17 changed files with 2095 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
// Public API of @shellbook/core. Pure functions, no I/O.
// Signatures are a CONTRACT used by server and web; implementations land in M0.
import type { Notebook, ParamValues, RenderedStep, Step } from "./types";
export type * from "./types";
export type * from "./protocol";
const notImplemented = (fn: string): never => {
throw new Error(`@shellbook/core: ${fn} is not implemented yet (M0)`);
};
/** Parse notebook Markdown (frontmatter, steps, :::after sections). Never throws; problems go to diagnostics. */
export function parseNotebook(source: string): Notebook {
return notImplemented(`parseNotebook(${source.length} chars)`);
}
/**
* Quote a value for POSIX sh. Returns the value unchanged when it only contains
* [A-Za-z0-9._/@:=+-] and is non-empty; otherwise single-quoted with ' escaped as '\''.
* The ONLY place in the codebase that quotes shell values.
*/
export function shellQuote(value: string): string {
return notImplemented(`shellQuote(${value.length} chars)`);
}
/**
* Resolve defaults ({{other}} references) and validate all params by type.
* Returns effective values and an error message per invalid/missing-required param.
* `hostNames` = names from hosts.yaml (for type "host").
*/
export function resolveParams(
notebook: Notebook,
values: ParamValues,
hostNames: readonly string[],
): { values: ParamValues; errors: Record<string, string> } {
return notImplemented(`resolveParams(${notebook.params.length}, ${Object.keys(values).length}, ${hostNames.length})`);
}
/**
* Substitute {{name}} in a step: script values are shell-quoted via shellQuote,
* attribute values (host, artifacts, uploads) are substituted raw but validated.
* Secret params must not be referenced with {{ }} (they are env vars) — reported in `invalid`.
*/
export function renderStep(
notebook: Notebook,
step: Step,
values: ParamValues,
runtime: ParamValues,
hostNames: readonly string[],
): RenderedStep {
return notImplemented(`renderStep(${notebook.title}, ${step.attrs.id}, ${Object.keys(values).length}, ${Object.keys(runtime).length}, ${hostNames.length})`);
}
/** Substitute {{name}} in prose/markdown for display (no quoting; secrets shown as ••••). */
export function renderText(text: string, values: ParamValues, notebook: Notebook): string {
return notImplemented(`renderText(${text.length}, ${Object.keys(values).length}, ${notebook.title})`);
}
/** Env vars for a run: every `secret` param as NAME=value (exact param name). Server-side only. */
export function secretEnv(notebook: Notebook, values: ParamValues): Record<string, string> {
return notImplemented(`secretEnv(${notebook.params.length}, ${Object.keys(values).length})`);
}
+125
View File
@@ -0,0 +1,125 @@
// HTTP + WebSocket protocol between apps/server and apps/web.
// CONTRACT: change only on purpose and update both sides in the same change.
// All HTTP routes are under /api and exchange JSON unless noted.
import type { Notebook, ParamValues } from "./types";
// ---- hosts -------------------------------------------------------------------
export interface HostInfo {
name: string;
address: string;
user: string;
port: number;
tags: string[];
}
// GET /api/hosts
export interface HostsResponse {
hosts: HostInfo[];
}
// ---- notebooks ---------------------------------------------------------------
export interface NotebookSummary {
/** Path relative to the workspace notebooks/ dir, forward slashes, e.g. "setup/ssh-key.md". */
path: string;
title: string;
}
// GET /api/notebooks
export interface NotebookListResponse {
notebooks: NotebookSummary[];
}
// GET /api/notebooks/:path (path URL-encoded)
export interface NotebookResponse {
path: string;
source: string;
notebook: Notebook;
/** Opaque version for optimistic concurrency on save. */
version: string;
}
// PUT /api/notebooks/:path
export interface SaveNotebookRequest {
source: string;
/** Version the edit was based on; 409 if the file changed meanwhile. */
baseVersion: string;
}
export interface SaveNotebookResponse {
version: string;
}
// ---- runs --------------------------------------------------------------------
// POST /api/runs
export interface StartRunRequest {
notebookPath: string;
stepId: string;
/** Values from the params form, including secrets (only ever sent here). */
params: ParamValues;
/** Runtime values from earlier `capture` steps in this browser session. */
runtime: ParamValues;
/** Artifacts from earlier runs this session, for `upload=`: artifact name -> runId. */
artifactSources: Record<string, string>;
/** Set when the user accepted an unknown host key (SHA256 fingerprint as shown). */
acceptHostKey?: string;
}
export interface StartRunResponse {
runId: string;
}
// GET /api/runs/:runId/artifacts/:name -> file download (application/octet-stream)
// ---- auth --------------------------------------------------------------------
// POST /api/auth/login {password} -> 204 + session cookie; 401 on failure
export interface LoginRequest {
password: string;
}
// POST /api/auth/logout -> 204
// GET /api/auth/me -> 200 {authenticated: true} | 401
// ---- events WebSocket: GET /api/events ---------------------------------------
// Server -> client messages (JSON text frames). Client sends nothing.
export type ServerEvent =
| {
type: "run.started";
runId: string;
notebookPath: string;
stepId: string;
host?: string;
/** The exact executed script (same as the client's rendered script). */
script: string;
}
| { type: "run.output"; runId: string; stream: "stdout" | "stderr"; data: string }
| {
type: "run.finished";
runId: string;
exitCode: number;
durationMs: number;
artifacts: string[];
captured?: { name: string; value: string };
}
| {
type: "run.hostKeyUnknown";
runId: string;
host: string;
/** e.g. "SHA256:abc..."; client re-POSTs with acceptHostKey after user confirmation. */
fingerprint: string;
/** True if a DIFFERENT key is already known (possible MITM) — UI must warn loudly. */
changed: boolean;
}
| { type: "run.error"; runId: string; message: string }
| { type: "file.changed"; path: string }
| { type: "file.deleted"; path: string };
// ---- terminal WebSocket: GET /api/terminal?session=<name> ---------------------
// Client -> server: JSON text frames TerminalClientMessage.
// Server -> client: raw terminal output as text frames.
export type TerminalClientMessage =
| { type: "input"; data: string }
| { type: "resize"; cols: number; rows: number };
+108
View File
@@ -0,0 +1,108 @@
// Shared data model for ShellBook notebooks (spec §3).
// This file is a CONTRACT between core, server and web. Change it only on purpose,
// and update every consumer in the same change.
export type ParamType = "host" | "name" | "path" | "string" | "choice" | "secret";
export interface ParamDef {
name: string;
type: ParamType;
required: boolean;
/** May reference other params with {{other}}. Never set for `secret`. */
default?: string;
label?: string;
/** Only for type "choice". */
options?: string[];
}
/** Param name -> current value. Missing key or "" means "not filled". */
export type ParamValues = Record<string, string>;
export type StepKind = "run" | "check";
export interface Upload {
/** Artifact name from an earlier step (template, may contain {{...}}). */
src: string;
/** Destination path on the target host (template). */
dst: string;
}
export interface StepAttrs {
/** Stable id. Explicit `id=` or slug of title; unique per notebook. */
id: string;
title?: string;
/** Raw template from `host="..."`; undefined when `on=local` or not set. */
host?: string;
/** `on=local`: run on the ShellBook server itself. */
local: boolean;
sudo: boolean;
/** Ask before running. Always false for checks. */
confirm: boolean;
/** Store trimmed stdout as runtime param with this name. */
capture?: string;
/** Artifact file name templates (run steps only). */
artifacts: string[];
uploads: Upload[];
timeoutSec: number;
}
/** 1-based, inclusive line range in the notebook source. */
export interface SourceRange {
startLine: number;
endLine: number;
}
export interface Step {
kind: StepKind;
/** Fence language, e.g. "sh" or "bash". */
lang: string;
attrs: StepAttrs;
/** Raw script template exactly as written (without the fence lines). */
script: string;
range: SourceRange;
}
export type Block =
| { type: "markdown"; text: string; range: SourceRange }
| { type: "step"; step: Step }
| {
type: "after";
stepId: string;
/** `:::after{step=x failed}` — shown when the step failed. */
onFailure: boolean;
blocks: Block[];
range: SourceRange;
};
export interface Diagnostic {
severity: "error" | "warning";
message: string;
line?: number;
}
export interface Notebook {
title: string;
params: ParamDef[];
blocks: Block[];
diagnostics: Diagnostic[];
}
/** A step with all templates resolved for concrete param values. */
export interface RenderedStep {
stepId: string;
kind: StepKind;
/** Resolved host name from hosts.yaml; undefined for local steps. */
host?: string;
local: boolean;
/**
* The exact script that will run (params substituted, shell-quoted, sudo NOT applied —
* sudo wrapping is an execution detail shown as a badge). Display == execution.
*/
script: string;
artifacts: string[];
uploads: Upload[];
/** Required params (incl. those referenced by this step) that are not filled. Non-empty => cannot run. */
missing: string[];
/** Validation errors per param name for values this step uses. Non-empty => cannot run. */
invalid: Record<string, string>;
}