@re-cinq/floor-studio 0.0.0-stage → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +208 -2
- package/dist/backend/agent-file-text.d.ts +16 -0
- package/dist/backend/agent-file-text.js +37 -0
- package/dist/backend/agent-views.d.ts +8 -0
- package/dist/backend/agent-views.js +28 -0
- package/dist/backend/collection-view.d.ts +3 -0
- package/dist/backend/collection-view.js +108 -0
- package/dist/backend/environment-usage.d.ts +5 -0
- package/dist/backend/environment-usage.js +19 -0
- package/dist/backend/fixture-files.d.ts +4 -0
- package/dist/backend/fixture-files.js +14 -0
- package/dist/backend/fixture-requests.d.ts +12 -0
- package/dist/backend/fixture-requests.js +25 -0
- package/dist/backend/guard.d.ts +14 -0
- package/dist/backend/guard.js +20 -0
- package/dist/backend/index.d.ts +2 -0
- package/dist/backend/index.js +3 -0
- package/dist/backend/present.d.ts +2 -0
- package/dist/backend/present.js +5 -0
- package/dist/backend/read-line.d.ts +11 -0
- package/dist/backend/read-line.js +46 -0
- package/dist/backend/requests.d.ts +47 -0
- package/dist/backend/requests.js +74 -0
- package/dist/backend/run-cancel-request.d.ts +6 -0
- package/dist/backend/run-cancel-request.js +12 -0
- package/dist/backend/run-files.d.ts +5 -0
- package/dist/backend/run-files.js +15 -0
- package/dist/backend/run-preview-request.d.ts +15 -0
- package/dist/backend/run-preview-request.js +25 -0
- package/dist/backend/run-read-request.d.ts +6 -0
- package/dist/backend/run-read-request.js +12 -0
- package/dist/backend/run-start-request.d.ts +6 -0
- package/dist/backend/run-start-request.js +35 -0
- package/dist/backend/skill-names.d.ts +3 -0
- package/dist/backend/skill-names.js +20 -0
- package/dist/backend/sources-on-disk.d.ts +2 -0
- package/dist/backend/sources-on-disk.js +9 -0
- package/dist/backend/start-studio.d.ts +19 -0
- package/dist/backend/start-studio.js +93 -0
- package/dist/backend/store-folder.d.ts +1 -0
- package/dist/backend/store-folder.js +10 -0
- package/dist/backend/watcher.d.ts +6 -0
- package/dist/backend/watcher.js +33 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +15 -0
- package/dist/protocol.d.ts +261 -0
- package/dist/protocol.js +79 -0
- package/dist/run/agent-command.d.ts +14 -0
- package/dist/run/agent-command.js +33 -0
- package/dist/run/prepare-workspace.d.ts +2 -0
- package/dist/run/prepare-workspace.js +14 -0
- package/dist/run/render-prompt.d.ts +1 -0
- package/dist/run/render-prompt.js +6 -0
- package/dist/run/run-edge.d.ts +8 -0
- package/dist/run/run-edge.js +8 -0
- package/dist/run/run-outcome.d.ts +12 -0
- package/dist/run/run-outcome.js +26 -0
- package/dist/run/run-preview.d.ts +29 -0
- package/dist/run/run-preview.js +31 -0
- package/dist/run/run-process.d.ts +16 -0
- package/dist/run/run-process.js +26 -0
- package/dist/run/run-produces.d.ts +12 -0
- package/dist/run/run-produces.js +13 -0
- package/dist/run/run-records.d.ts +22 -0
- package/dist/run/run-records.js +11 -0
- package/dist/run/run-result.d.ts +13 -0
- package/dist/run/run-result.js +10 -0
- package/dist/run/station-fixtures.d.ts +3 -0
- package/dist/run/station-fixtures.js +3 -0
- package/dist/run/vendor.d.ts +2 -0
- package/dist/run/vendor.js +11 -0
- package/dist/run/workspace.d.ts +21 -0
- package/dist/run/workspace.js +27 -0
- package/dist/shell/arguments.d.ts +15 -0
- package/dist/shell/arguments.js +32 -0
- package/dist/shell/open-browser.d.ts +7 -0
- package/dist/shell/open-browser.js +17 -0
- package/dist/shell/page-url.d.ts +6 -0
- package/dist/shell/page-url.js +5 -0
- package/dist/shell/static-files.d.ts +7 -0
- package/dist/shell/static-files.js +75 -0
- package/dist/shell/studio-command.d.ts +20 -0
- package/dist/shell/studio-command.js +48 -0
- package/dist/view.d.ts +100 -0
- package/dist/view.js +2 -0
- package/dist/web/assets/ibm-plex-sans-latin-300-b4i7YzLG.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-400-CDDApCn2.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-500-6ng42L7E.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-600-CuJfVYMP.woff2 +0 -0
- package/dist/web/assets/ibm-plex-sans-latin-700-Bxkt5Cjx.woff2 +0 -0
- package/dist/web/assets/index-Bb0f0ToW.css +1 -0
- package/dist/web/assets/index-bPZxSQCP.js +195 -0
- package/dist/web/assets/jetbrains-mono-latin-wght-B9CIFXIH.woff2 +0 -0
- package/dist/web/index.html +26 -0
- package/package.json +78 -4
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The environment a collection asks for: each `${NAME}` its line files and its agents' settings name, and where. A prompt is never filled, so an agent file counts by its frontmatter alone.
|
|
2
|
+
import { agentFileOf, pipelineFolderOf, placeholdersIn } from "@re-cinq/floor-pipeline";
|
|
3
|
+
const FRONTMATTER = /^---\n([\s\S]*?)\n---(?:\n|$)/;
|
|
4
|
+
export function environmentOf(files) {
|
|
5
|
+
const filesByName = new Map();
|
|
6
|
+
const uses = files.flatMap(({ path, text }) => placeholdersIn(filledTextOf(path, text)).map((name) => ({ name, path })));
|
|
7
|
+
uses.forEach(({ name, path }) => filesByName.set(name, [...(filesByName.get(name) ?? []), path]));
|
|
8
|
+
return [...filesByName]
|
|
9
|
+
.sort(([left], [right]) => left.localeCompare(right))
|
|
10
|
+
.map(([name, named]) => ({ name, files: named.sort() }));
|
|
11
|
+
}
|
|
12
|
+
function filledTextOf(path, text) {
|
|
13
|
+
if (pipelineFolderOf(path))
|
|
14
|
+
return text;
|
|
15
|
+
if (agentFileOf(path))
|
|
16
|
+
return FRONTMATTER.exec(text)?.[1] ?? "";
|
|
17
|
+
return "";
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=environment-usage.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Where the needs a node is tried with are kept: one JSON file for each node, in a dot folder the watcher ignores.
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { storeFolderIn } from "./store-folder.js";
|
|
5
|
+
export function fixtureFilesIn(dir) {
|
|
6
|
+
const fixtureFile = (line, node) => join(dir, ".floor-studio", "fixtures", line, `${node}.json`);
|
|
7
|
+
const readFixture = async (line, node) => readFile(fixtureFile(line, node), "utf8").then((text) => JSON.parse(text).needs, () => ({}));
|
|
8
|
+
const writeFixture = async (line, node, needs) => {
|
|
9
|
+
await storeFolderIn(dir, "fixtures", line);
|
|
10
|
+
await writeFile(fixtureFile(line, node), JSON.stringify({ needs }));
|
|
11
|
+
};
|
|
12
|
+
return { readFixture, writeFixture };
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=fixture-files.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Request } from "../protocol.js";
|
|
2
|
+
import type { CollectionView, NodeView } from "../view.js";
|
|
3
|
+
import type { Handler } from "./requests.js";
|
|
4
|
+
export declare function nodeOf({ lines }: CollectionView, lineId: string, nodeId: string): NodeView | undefined;
|
|
5
|
+
export type FixtureWrite = Extract<Request, {
|
|
6
|
+
type: "fixture.write";
|
|
7
|
+
}>;
|
|
8
|
+
export declare const fixtureWrite: Handler<FixtureWrite>;
|
|
9
|
+
export type FixtureRead = Extract<Request, {
|
|
10
|
+
type: "fixture.read";
|
|
11
|
+
}>;
|
|
12
|
+
export declare const fixtureRead: Handler<FixtureRead>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// The requests that save and read the needs a node is tried with. The line and node come only from the collection view, so a path-like name never reaches the disk.
|
|
2
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
3
|
+
export function nodeOf({ lines }, lineId, nodeId) {
|
|
4
|
+
const nodes = lines.find(({ id }) => id === lineId)?.nodes ?? [];
|
|
5
|
+
return nodes.find(({ id }) => id === nodeId);
|
|
6
|
+
}
|
|
7
|
+
function hasNode(view, lineId, nodeId) {
|
|
8
|
+
return nodeOf(view, lineId, nodeId) !== undefined;
|
|
9
|
+
}
|
|
10
|
+
export const fixtureWrite = {
|
|
11
|
+
type: "fixture.write",
|
|
12
|
+
handle: async (context, { line, node, needs }) => {
|
|
13
|
+
enforce(hasNode(await context.readCollection(), line, node), `line ${line} has no node ${node}`);
|
|
14
|
+
await context.writeFixture(line, node, needs);
|
|
15
|
+
return { written: `${line}/${node}` };
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
export const fixtureRead = {
|
|
19
|
+
type: "fixture.read",
|
|
20
|
+
handle: async (context, { line, node }) => {
|
|
21
|
+
enforce(hasNode(await context.readCollection(), line, node), `line ${line} has no node ${node}`);
|
|
22
|
+
return { needs: await context.readFixture(line, node) };
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=fixture-requests.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
declare const UNAUTHORIZED = 401;
|
|
2
|
+
declare const FORBIDDEN = 403;
|
|
3
|
+
export interface UpgradeAsked {
|
|
4
|
+
url: string | undefined;
|
|
5
|
+
origin: string | undefined;
|
|
6
|
+
token: string;
|
|
7
|
+
origins: readonly string[];
|
|
8
|
+
}
|
|
9
|
+
export interface UpgradeRefusal {
|
|
10
|
+
status: typeof UNAUTHORIZED | typeof FORBIDDEN;
|
|
11
|
+
reason: string;
|
|
12
|
+
}
|
|
13
|
+
export declare function upgradeRefusal({ url, origin, token, origins }: UpgradeAsked): UpgradeRefusal | undefined;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Who may open the socket. The backend writes files and starts processes, so no web page may reach it: the launch token keeps out a program that was not told it, the Origin check a page in the person's browser that guessed the port.
|
|
2
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
3
|
+
const UNAUTHORIZED = 401;
|
|
4
|
+
const FORBIDDEN = 403;
|
|
5
|
+
export function upgradeRefusal({ url, origin, token, origins }) {
|
|
6
|
+
// A client that is no browser sends no Origin; a browser always does, and its page must be one the shell served.
|
|
7
|
+
if (origin !== undefined && !origins.includes(origin))
|
|
8
|
+
return { status: FORBIDDEN, reason: "a page of another origin may not use this socket" };
|
|
9
|
+
if (!isSameToken(tokenOf(url), token))
|
|
10
|
+
return { status: UNAUTHORIZED, reason: "the socket needs the launch token" };
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
function tokenOf(url) {
|
|
14
|
+
return new URL(url ?? "/", "http://localhost").searchParams.get("token") ?? "";
|
|
15
|
+
}
|
|
16
|
+
// Hashed first so the two buffers are as long as each other: timingSafeEqual throws on unequal lengths, and a length is a clue.
|
|
17
|
+
function isSameToken(given, token) {
|
|
18
|
+
return timingSafeEqual(createHash("sha256").update(given).digest(), createHash("sha256").update(token).digest());
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=guard.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** The fields that say something: what is undefined or empty text is left out, so the view holds no key JSON would drop. */
|
|
2
|
+
export function present(fields) {
|
|
3
|
+
return Object.fromEntries(Object.entries(fields).filter(([, held]) => held !== undefined && held !== ""));
|
|
4
|
+
}
|
|
5
|
+
//# sourceMappingURL=present.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type AgentPrompts, type CollectionFile } from "@re-cinq/floor-pipeline";
|
|
2
|
+
import type { LineBody, StationBody } from "@re-cinq/floor-contracts";
|
|
3
|
+
import type { ViewProblem } from "../view.js";
|
|
4
|
+
export interface ReadLine {
|
|
5
|
+
id: string;
|
|
6
|
+
file: string;
|
|
7
|
+
body: LineBody;
|
|
8
|
+
bodies: ReadonlyMap<string, StationBody>;
|
|
9
|
+
problems: ViewProblem[];
|
|
10
|
+
}
|
|
11
|
+
export declare function readLine(file: CollectionFile, folder: string, prompts: AgentPrompts): ReadLine;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// One line file read on its own, so a line the collection's overlay would refuse for its problems is still a line, with the problems beside it.
|
|
2
|
+
import { enforce, validateLine } from "@re-cinq/floor-assembly-lines";
|
|
3
|
+
import { pipelineOf, pipelineProblems, readPipelineFile } from "@re-cinq/floor-pipeline";
|
|
4
|
+
export function readLine(file, folder, prompts) {
|
|
5
|
+
const pipeline = pipelineOf(readPipelineFile(file.text));
|
|
6
|
+
enforce(pipeline.line, "the file holds no line");
|
|
7
|
+
const body = lineBodyOf(pipeline.line.body, Object.keys(pipeline.files));
|
|
8
|
+
const bodies = new Map(pipeline.stations.map(({ id, body: station }) => [id, stationBodyOf(station)]));
|
|
9
|
+
const problems = [...folderProblems(folder, pipeline.line.id), ...lintProblems(file.text, prompts), ...validationProblems(body, bodies)];
|
|
10
|
+
return { id: pipeline.line.id, file: file.path, body, bodies, problems: withoutRepeats(problems) };
|
|
11
|
+
}
|
|
12
|
+
// A file may leave out every part of a line but its id: the rules read a line with each part present.
|
|
13
|
+
function lineBodyOf(written, fileNames) {
|
|
14
|
+
const files = Object.fromEntries(fileNames.map((name) => [name, ""]));
|
|
15
|
+
return { args: {}, nodes: [], edges: [], files, ...written };
|
|
16
|
+
}
|
|
17
|
+
function stationBodyOf(written) {
|
|
18
|
+
return { outcomes: [], needs: [], produces: [], ...written };
|
|
19
|
+
}
|
|
20
|
+
function folderProblems(folder, lineId) {
|
|
21
|
+
return lineId === folder ? [] : [{ rule: "folder-name", message: `the folder ${folder} must hold the line of that name, and its line is ${lineId}` }];
|
|
22
|
+
}
|
|
23
|
+
function lintProblems(text, prompts) {
|
|
24
|
+
return pipelineProblems(text, prompts).map(({ rule, node, detail }) => ({ rule, ...(node && { node }), message: detail }));
|
|
25
|
+
}
|
|
26
|
+
function validationProblems(body, bodies) {
|
|
27
|
+
const messages = validateLine(body, { stations: new Set(bodies.keys()), bodies });
|
|
28
|
+
return messages.map((message) => ({ rule: "line-validation", message }));
|
|
29
|
+
}
|
|
30
|
+
/** What the line check says in its words that a rule of the lint says in its own: the lint's is kept. */
|
|
31
|
+
const SAID_BY_LINT = [
|
|
32
|
+
{ says: /^edge \d+: (from|to) "/, rule: "dangling-edge" },
|
|
33
|
+
{ says: /has no outgoing edge$/, rule: "dead-end" },
|
|
34
|
+
{ says: /is not reachable from entry/, rule: "unreachable" },
|
|
35
|
+
{ says: /has no edge for outcome/, rule: "outcome-without-edge" },
|
|
36
|
+
];
|
|
37
|
+
function withoutRepeats(problems) {
|
|
38
|
+
const lint = problems.filter(({ rule }) => rule !== "line-validation");
|
|
39
|
+
return problems.filter((problem, index) => problems.findIndex((other) => other.message === problem.message) === index && !saidByLint(problem, lint));
|
|
40
|
+
}
|
|
41
|
+
function saidByLint({ rule, message }, lint) {
|
|
42
|
+
const subject = /"([^"]*)"/.exec(message)?.[1] ?? "";
|
|
43
|
+
const covering = SAID_BY_LINT.filter(({ says }) => rule === "line-validation" && says.test(message));
|
|
44
|
+
return covering.some(({ rule: lintRule }) => lint.some((other) => other.rule === lintRule && other.message.includes(subject) || other.node === subject));
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=read-line.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type Request, type ResultOf, type ServerFrame } from "../protocol.js";
|
|
2
|
+
import type { CollectionView } from "../view.js";
|
|
3
|
+
import type { AgentEdit } from "./agent-file-text.js";
|
|
4
|
+
import { type FixtureRead, type FixtureWrite } from "./fixture-requests.js";
|
|
5
|
+
import { type RunPreviewRequest } from "./run-preview-request.js";
|
|
6
|
+
import { type RunCancelRequest } from "./run-cancel-request.js";
|
|
7
|
+
import { type RunStartRequest } from "./run-start-request.js";
|
|
8
|
+
import { type RunReadRequest } from "./run-read-request.js";
|
|
9
|
+
import type { RunRecord, RunTranscript } from "../run/run-records.js";
|
|
10
|
+
export interface StudioContext {
|
|
11
|
+
readCollection(): Promise<CollectionView>;
|
|
12
|
+
/** Rewrites the agent file at a collection-relative path, refused when it changed since it was read. */
|
|
13
|
+
writeAgent(file: string, edit: AgentEdit): Promise<void>;
|
|
14
|
+
/** Rewrites an `.extra.md` file at a collection-relative path, refused when it changed since it was read. */
|
|
15
|
+
writeExtra(file: string, edit: {
|
|
16
|
+
text: string;
|
|
17
|
+
version: string;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
/** The saved needs of a node's fixture; empty when none was saved. */
|
|
20
|
+
readFixture(line: string, node: string): Promise<Record<string, string>>;
|
|
21
|
+
writeFixture(line: string, node: string, needs: Record<string, string>): Promise<void>;
|
|
22
|
+
readRun(run: string): Promise<RunTranscript | undefined>;
|
|
23
|
+
writeRun(run: string, transcript: RunTranscript): Promise<void>;
|
|
24
|
+
/** The record of each run started by `run.start`, by run id; kept after the run ends. */
|
|
25
|
+
runs: Map<string, RunRecord>;
|
|
26
|
+
/** Environment laid over the studio's own for each started process. */
|
|
27
|
+
runEnv?: Record<string, string>;
|
|
28
|
+
/** Sends a frame to every open socket. */
|
|
29
|
+
broadcast(frame: ServerFrame): void;
|
|
30
|
+
}
|
|
31
|
+
export interface Handler<Asked extends Request> {
|
|
32
|
+
type: Asked["type"];
|
|
33
|
+
handle(context: StudioContext, request: Asked): Promise<ResultOf<Asked>>;
|
|
34
|
+
}
|
|
35
|
+
type AgentWrite = Extract<Request, {
|
|
36
|
+
type: "agent.write";
|
|
37
|
+
}>;
|
|
38
|
+
type ExtraWrite = Extract<Request, {
|
|
39
|
+
type: "extra.write";
|
|
40
|
+
}>;
|
|
41
|
+
type CollectionRead = Extract<Request, {
|
|
42
|
+
type: "collection.read";
|
|
43
|
+
}>;
|
|
44
|
+
/** One handler for each request type: a test holds the list to `REQUEST_TYPES`. */
|
|
45
|
+
export declare const HANDLERS: (Handler<CollectionRead> | Handler<AgentWrite> | Handler<ExtraWrite> | Handler<FixtureWrite> | Handler<FixtureRead> | Handler<RunPreviewRequest> | Handler<RunStartRequest> | Handler<RunCancelRequest> | Handler<RunReadRequest>)[];
|
|
46
|
+
export declare function answerFrame(text: string, context: StudioContext): Promise<ServerFrame>;
|
|
47
|
+
export {};
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// A request in, one frame out. Adding a request type is its schema in the protocol and its handler in `HANDLERS`.
|
|
2
|
+
import { REQUEST_TYPES, requestSchema } from "../protocol.js";
|
|
3
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { fixtureRead, fixtureWrite } from "./fixture-requests.js";
|
|
6
|
+
import { runPreviewHandler } from "./run-preview-request.js";
|
|
7
|
+
import { runCancelHandler } from "./run-cancel-request.js";
|
|
8
|
+
import { runStartHandler } from "./run-start-request.js";
|
|
9
|
+
import { runReadHandler } from "./run-read-request.js";
|
|
10
|
+
function agentFileOf({ lines }, lineId, agentName) {
|
|
11
|
+
const nodes = lines.find(({ id }) => id === lineId)?.nodes ?? [];
|
|
12
|
+
const agents = nodes.map((node) => node.agent);
|
|
13
|
+
return agents.find((each) => each?.name === agentName)?.file;
|
|
14
|
+
}
|
|
15
|
+
const agentWrite = {
|
|
16
|
+
type: "agent.write",
|
|
17
|
+
handle: async (context, { line, agent, prompt, settings, version }) => {
|
|
18
|
+
const file = agentFileOf(await context.readCollection(), line, agent);
|
|
19
|
+
enforce(file, `line ${line} has no agent ${agent}`);
|
|
20
|
+
await context.writeAgent(file, { prompt, settings, version });
|
|
21
|
+
return { written: file };
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
function extraFileOf({ lines }, lineId, agentName) {
|
|
25
|
+
const nodes = lines.find(({ id }) => id === lineId)?.nodes ?? [];
|
|
26
|
+
const node = nodes.find((each) => each.agentDefinition === agentName && each.extra);
|
|
27
|
+
return node?.extra?.file;
|
|
28
|
+
}
|
|
29
|
+
const extraWrite = {
|
|
30
|
+
type: "extra.write",
|
|
31
|
+
handle: async (context, { line, agent, text, version }) => {
|
|
32
|
+
const file = extraFileOf(await context.readCollection(), line, agent);
|
|
33
|
+
enforce(file, `line ${line} has no extra file for agent ${agent}`);
|
|
34
|
+
await context.writeExtra(file, { text, version });
|
|
35
|
+
return { written: file };
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
const collectionRead = { type: "collection.read", handle: (context) => context.readCollection() };
|
|
39
|
+
/** One handler for each request type: a test holds the list to `REQUEST_TYPES`. */
|
|
40
|
+
export const HANDLERS = [collectionRead, agentWrite, extraWrite, fixtureWrite, fixtureRead, runPreviewHandler, runStartHandler, runCancelHandler, runReadHandler];
|
|
41
|
+
export async function answerFrame(text, context) {
|
|
42
|
+
const held = parsedJson(text);
|
|
43
|
+
const id = idOf(held);
|
|
44
|
+
const parsed = requestSchema.safeParse(held);
|
|
45
|
+
if (!parsed.success)
|
|
46
|
+
return { ...(id && { id }), type: "refused", reason: refusalOf(held, parsed.error) };
|
|
47
|
+
return handled(parsed.data, context);
|
|
48
|
+
}
|
|
49
|
+
async function handled(request, context) {
|
|
50
|
+
const handler = new Map(HANDLERS.map((each) => [each.type, each])).get(request.type);
|
|
51
|
+
if (!handler)
|
|
52
|
+
return { id: request.id, type: "refused", reason: `no handler for ${request.type}` };
|
|
53
|
+
return handler.handle(context, request).then((result) => ({ id: request.id, type: "result", result }), (cause) => ({ id: request.id, type: "refused", reason: cause instanceof Error ? cause.message : String(cause) }));
|
|
54
|
+
}
|
|
55
|
+
function parsedJson(text) {
|
|
56
|
+
try {
|
|
57
|
+
return JSON.parse(text);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return NOT_JSON;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const NOT_JSON = Symbol("not json");
|
|
64
|
+
function idOf(held) {
|
|
65
|
+
const id = typeof held === "object" && held !== null && "id" in held ? held.id : undefined;
|
|
66
|
+
return typeof id === "string" && id !== "" ? id : undefined;
|
|
67
|
+
}
|
|
68
|
+
function refusalOf(held, error) {
|
|
69
|
+
if (held === NOT_JSON)
|
|
70
|
+
return "the frame is not JSON";
|
|
71
|
+
const type = typeof held === "object" && held !== null && "type" in held ? held.type : undefined;
|
|
72
|
+
return REQUEST_TYPES.includes(type) ? z.prettifyError(error) : `unknown request type ${JSON.stringify(type)}; known: ${REQUEST_TYPES.join(", ")}`;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=requests.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The request that stops a started run; its `run.ended` frame comes from the start handler once the process is gone.
|
|
2
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
3
|
+
export const runCancelHandler = {
|
|
4
|
+
type: "run.cancel",
|
|
5
|
+
handle: async ({ runs }, { run }) => {
|
|
6
|
+
const running = runs.get(run)?.process;
|
|
7
|
+
enforce(running, `no running run ${run}`);
|
|
8
|
+
running.cancel();
|
|
9
|
+
return { cancelled: run };
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=run-cancel-request.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Where the runs are kept: one JSON file for each run, so a restarted studio can still read its transcript.
|
|
2
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { storeFolderIn } from "./store-folder.js";
|
|
5
|
+
const RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
6
|
+
export function runFilesIn(dir) {
|
|
7
|
+
const writeRun = async (run, { lines, ended }) => {
|
|
8
|
+
await writeFile(join(await storeFolderIn(dir, "runs"), `${run}.json`), JSON.stringify({ lines, ended }));
|
|
9
|
+
};
|
|
10
|
+
const readRun = async (run) => RUN_ID.test(run)
|
|
11
|
+
? readFile(join(dir, ".floor-studio", "runs", `${run}.json`), "utf8").then((text) => JSON.parse(text), () => undefined)
|
|
12
|
+
: undefined;
|
|
13
|
+
return { writeRun, readRun };
|
|
14
|
+
}
|
|
15
|
+
//# sourceMappingURL=run-files.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Request } from "../protocol.js";
|
|
2
|
+
import type { StationBody } from "@re-cinq/floor-contracts";
|
|
3
|
+
import type { LineView } from "../view.js";
|
|
4
|
+
import { type RunPreview } from "../run/run-preview.js";
|
|
5
|
+
import type { Handler, StudioContext } from "./requests.js";
|
|
6
|
+
export type RunPreviewRequest = Extract<Request, {
|
|
7
|
+
type: "run.preview";
|
|
8
|
+
}>;
|
|
9
|
+
export declare const runPreviewHandler: Handler<RunPreviewRequest>;
|
|
10
|
+
export interface PreviewedNode {
|
|
11
|
+
preview: RunPreview;
|
|
12
|
+
station: StationBody;
|
|
13
|
+
line: LineView;
|
|
14
|
+
}
|
|
15
|
+
export declare function previewFor(context: StudioContext, { line, node, fixture, folder, permission }: Omit<RunPreviewRequest, "id" | "type">): Promise<PreviewedNode>;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// The request that shows what a run of one agent node would do, before it is started.
|
|
2
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
3
|
+
import { extendedPrompt } from "@re-cinq/floor-pipeline";
|
|
4
|
+
import { runPreview } from "../run/run-preview.js";
|
|
5
|
+
import { nodeOf } from "./fixture-requests.js";
|
|
6
|
+
import { absentSourceBlockers } from "./sources-on-disk.js";
|
|
7
|
+
export const runPreviewHandler = {
|
|
8
|
+
type: "run.preview",
|
|
9
|
+
handle: async (context, request) => (await previewFor(context, request)).preview,
|
|
10
|
+
};
|
|
11
|
+
export async function previewFor(context, { line, node, fixture, folder, permission }) {
|
|
12
|
+
const collection = await context.readCollection();
|
|
13
|
+
const found = nodeOf(collection, line, node);
|
|
14
|
+
enforce(found?.kind, `line ${line} has no node ${node}`);
|
|
15
|
+
const { kind, outcomes, needs, produces, agentDefinition, agent } = found;
|
|
16
|
+
const station = { kind, outcomes, needs, produces, agentDefinition };
|
|
17
|
+
const preview = runPreview({ station, prompt: promptOf(found).trimEnd(), settings: (agent?.settings ?? {}), fixture, folder, permission });
|
|
18
|
+
const absent = await absentSourceBlockers([...preview.copies, ...preview.links]);
|
|
19
|
+
return { preview: { ...preview, blockers: [...preview.blockers, ...absent] }, station, line: collection.lines.find(({ id }) => id === line) };
|
|
20
|
+
}
|
|
21
|
+
function promptOf({ agent, extra }) {
|
|
22
|
+
const base = agent?.prompt ?? "";
|
|
23
|
+
return extra ? extendedPrompt(base, extra.text) : base;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=run-preview-request.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The request that reads a run's transcript from a line on, while it runs or after it ended.
|
|
2
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
3
|
+
import { readRecord } from "../run/run-records.js";
|
|
4
|
+
export const runReadHandler = {
|
|
5
|
+
type: "run.read",
|
|
6
|
+
handle: async ({ runs, readRun }, { run, after }) => {
|
|
7
|
+
const record = runs.get(run) ?? (await readRun(run));
|
|
8
|
+
enforce(record, `no run ${run}`);
|
|
9
|
+
return readRecord(record, after);
|
|
10
|
+
},
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=run-read-request.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The request that starts a run of one agent node and streams its output to every page.
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir } from "node:fs/promises";
|
|
4
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
5
|
+
import { prepareWorkspace } from "../run/prepare-workspace.js";
|
|
6
|
+
import { runProcess } from "../run/run-process.js";
|
|
7
|
+
import { appendLine, endRecord } from "../run/run-records.js";
|
|
8
|
+
import { runResult } from "../run/run-result.js";
|
|
9
|
+
import { previewFor } from "./run-preview-request.js";
|
|
10
|
+
export const runStartHandler = {
|
|
11
|
+
type: "run.start",
|
|
12
|
+
handle: async (context, request) => {
|
|
13
|
+
const { preview, station, line } = await previewFor(context, request);
|
|
14
|
+
enforce(preview.blockers.length === 0, preview.blockers.join("; "));
|
|
15
|
+
await mkdir(request.folder, { recursive: true });
|
|
16
|
+
await prepareWorkspace(preview);
|
|
17
|
+
const run = randomUUID();
|
|
18
|
+
const record = { lines: [] };
|
|
19
|
+
context.runs.set(run, record);
|
|
20
|
+
await context.writeRun(run, record);
|
|
21
|
+
const running = runProcess({ command: preview.command, folder: request.folder, env: { ...preview.env, ...context.runEnv } }, (line) => {
|
|
22
|
+
appendLine(record, line);
|
|
23
|
+
context.broadcast({ type: "run.output", run, line });
|
|
24
|
+
});
|
|
25
|
+
record.process = running;
|
|
26
|
+
void running.done.then(async ({ exitCode }) => {
|
|
27
|
+
const ending = { exitCode, ...(await runResult({ exitCode, lines: record.lines, station, line, node: request.node, folder: request.folder })) };
|
|
28
|
+
endRecord(record, ending);
|
|
29
|
+
await context.writeRun(run, record);
|
|
30
|
+
context.broadcast({ type: "run.ended", run, ...ending });
|
|
31
|
+
});
|
|
32
|
+
return { run };
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
//# sourceMappingURL=run-start-request.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// The skills a collection holds: one markdown file each under `skills/`, or one folder each under `agent-skills/skills/` with a SKILL.md.
|
|
2
|
+
import { access, readdir } from "node:fs/promises";
|
|
3
|
+
import { basename, join } from "node:path";
|
|
4
|
+
/** A skill file: `skills/<name>.md` or `agent-skills/skills/<name>/SKILL.md`. */
|
|
5
|
+
export function isSkillPath(path) {
|
|
6
|
+
return /^(skills\/[^/]+\.md|agent-skills\/skills\/[^/]+\/SKILL\.md)$/.test(path);
|
|
7
|
+
}
|
|
8
|
+
export async function skillNamesIn(dir) {
|
|
9
|
+
const files = await readdir(join(dir, "skills")).catch(() => []);
|
|
10
|
+
const fileNames = files.filter((file) => file.endsWith(".md")).map((file) => basename(file, ".md"));
|
|
11
|
+
const folderNames = await folderSkillNamesIn(dir);
|
|
12
|
+
return [...new Set([...fileNames, ...folderNames])].sort();
|
|
13
|
+
}
|
|
14
|
+
async function folderSkillNamesIn(dir) {
|
|
15
|
+
const root = join(dir, "agent-skills", "skills");
|
|
16
|
+
const folders = await readdir(root).catch(() => []);
|
|
17
|
+
const found = await Promise.all(folders.map((folder) => access(join(root, folder, "SKILL.md")).then(() => folder, () => undefined)));
|
|
18
|
+
return found.filter((folder) => folder !== undefined);
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=skill-names.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { access } from "node:fs/promises";
|
|
2
|
+
export async function absentSourceBlockers(placements) {
|
|
3
|
+
const absent = await Promise.all(placements.map(async ({ need, from }) => (await isOnDisk(from) ? [] : [`"${need}": ${from} is not on disk`])));
|
|
4
|
+
return absent.flat();
|
|
5
|
+
}
|
|
6
|
+
function isOnDisk(path) {
|
|
7
|
+
return access(path).then(() => true, () => false);
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=sources-on-disk.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface StudioOptions {
|
|
2
|
+
dir: string;
|
|
3
|
+
/** 0 picks a free port. */
|
|
4
|
+
port: number;
|
|
5
|
+
hostKeys: readonly string[];
|
|
6
|
+
/** The Origin of each page that may open the socket. A client that sends none is let in with the token. */
|
|
7
|
+
origins?: readonly string[];
|
|
8
|
+
/** Environment laid over the studio's own for each process a run starts. */
|
|
9
|
+
runEnv?: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
export interface Studio {
|
|
12
|
+
/** `ws://127.0.0.1:<port>`: the real port, the token not in it. */
|
|
13
|
+
url: string;
|
|
14
|
+
token: string;
|
|
15
|
+
/** The sockets that passed the token and origin check and are still open. */
|
|
16
|
+
pageCount(): number;
|
|
17
|
+
close(): Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
export declare function startStudio(options: StudioOptions): Promise<Studio>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The backend: one WebSocket server on the loopback address, a token and an origin check at the upgrade, a handler table for requests, and a watcher that pushes the collection again when a file changes.
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
import { basename, join, resolve } from "node:path";
|
|
6
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
7
|
+
import { collectionFilesIn, hostKeysIn, readAgentFile } from "@re-cinq/floor-pipeline";
|
|
8
|
+
import { WebSocket, WebSocketServer } from "ws";
|
|
9
|
+
import { PROTOCOL_VERSION } from "../protocol.js";
|
|
10
|
+
import { collectionView } from "./collection-view.js";
|
|
11
|
+
import { upgradeRefusal } from "./guard.js";
|
|
12
|
+
import { editedAgentText, textVersion, withOneNewline } from "./agent-file-text.js";
|
|
13
|
+
import { environmentOf } from "./environment-usage.js";
|
|
14
|
+
import { fixtureFilesIn } from "./fixture-files.js";
|
|
15
|
+
import { runFilesIn } from "./run-files.js";
|
|
16
|
+
import { answerFrame } from "./requests.js";
|
|
17
|
+
import { isSkillPath, skillNamesIn } from "./skill-names.js";
|
|
18
|
+
import { watchCollection } from "./watcher.js";
|
|
19
|
+
/** Never `0.0.0.0`: the backend writes files and starts processes. */
|
|
20
|
+
const LOOPBACK = "127.0.0.1";
|
|
21
|
+
const MAX_FRAME_BYTES = 4_194_304;
|
|
22
|
+
const TOKEN_BYTES = 32;
|
|
23
|
+
const GOING_AWAY = 1001;
|
|
24
|
+
const UPGRADE_REQUIRED = 426;
|
|
25
|
+
export async function startStudio(options) {
|
|
26
|
+
const { dir, hostKeys, origins = [] } = options;
|
|
27
|
+
enforce((await stat(dir).catch(() => undefined))?.isDirectory(), `${dir} is not a directory`);
|
|
28
|
+
const token = randomBytes(TOKEN_BYTES).toString("hex");
|
|
29
|
+
const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
|
|
30
|
+
const allHostKeys = async () => [...hostKeys, ...(await hostKeysIn(dir))];
|
|
31
|
+
const readCollection = async () => collectionRead(dir, await allHostKeys());
|
|
32
|
+
const writeAgent = async (file, edit) => {
|
|
33
|
+
const path = join(dir, file);
|
|
34
|
+
const text = editedAgentText(file, await readFile(path, "utf8"), edit);
|
|
35
|
+
readAgentFile(basename(file, ".md"), text, await allHostKeys());
|
|
36
|
+
await writeFile(path, text);
|
|
37
|
+
};
|
|
38
|
+
const context = { readCollection, writeAgent, writeExtra: (file, edit) => writeExtraFile(join(dir, file), edit), ...fixtureFilesIn(dir), ...runFilesIn(dir), runs: new Map(), runEnv: options.runEnv, broadcast: (frame) => sockets.clients.forEach((socket) => send(socket, frame)) };
|
|
39
|
+
const server = createServer(refuseHttp);
|
|
40
|
+
server.on("upgrade", (request, socket, head) => {
|
|
41
|
+
const refusal = upgradeRefusal({ url: request.url, origin: request.headers.origin, token, origins });
|
|
42
|
+
if (refusal)
|
|
43
|
+
return void refuseUpgrade(socket, refusal);
|
|
44
|
+
sockets.handleUpgrade(request, socket, head, (opened) => sockets.emit("connection", opened, request));
|
|
45
|
+
});
|
|
46
|
+
sockets.on("connection", (socket) => serve(socket, context));
|
|
47
|
+
const watcher = watchCollection(dir, () => void pushCollection(sockets, readCollection));
|
|
48
|
+
await new Promise((resolve) => server.listen(options.port, LOOPBACK, resolve));
|
|
49
|
+
return {
|
|
50
|
+
url: `ws://${LOOPBACK}:${server.address().port}`,
|
|
51
|
+
token,
|
|
52
|
+
pageCount: () => sockets.clients.size,
|
|
53
|
+
close: () => closed({ watcher, sockets, server, runs: context.runs }),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
async function collectionRead(dir, hostKeys) {
|
|
57
|
+
const files = (await collectionFilesIn(dir)).filter((file) => !isSkillPath(file.path));
|
|
58
|
+
return { ...collectionView(files, hostKeys), folder: basename(resolve(dir)), skills: await skillNamesIn(dir), environment: environmentOf(files) };
|
|
59
|
+
}
|
|
60
|
+
async function writeExtraFile(path, { text, version }) {
|
|
61
|
+
enforce(version === textVersion(await readFile(path, "utf8")), `${basename(path)} changed on disk since it was read`);
|
|
62
|
+
await writeFile(path, withOneNewline(text));
|
|
63
|
+
}
|
|
64
|
+
function refuseHttp(...given) {
|
|
65
|
+
const [, response] = given;
|
|
66
|
+
response.writeHead(UPGRADE_REQUIRED, { "Content-Type": "text/plain" });
|
|
67
|
+
response.end("this is a WebSocket backend: open a socket with the launch token\n");
|
|
68
|
+
}
|
|
69
|
+
function refuseUpgrade(socket, { status, reason }) {
|
|
70
|
+
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\n\r\n`);
|
|
71
|
+
}
|
|
72
|
+
function serve(socket, context) {
|
|
73
|
+
send(socket, { type: "hello", version: PROTOCOL_VERSION });
|
|
74
|
+
// ws closes the socket itself (1009 on an oversized frame); the listener only keeps the error from going unhandled.
|
|
75
|
+
socket.on("error", () => undefined);
|
|
76
|
+
socket.on("message", (frame) => void answerFrame(frame.toString(), context).then((answer) => send(socket, answer)));
|
|
77
|
+
}
|
|
78
|
+
function send(socket, frame) {
|
|
79
|
+
if (socket.readyState === WebSocket.OPEN)
|
|
80
|
+
socket.send(JSON.stringify(frame));
|
|
81
|
+
}
|
|
82
|
+
async function pushCollection(sockets, readCollection) {
|
|
83
|
+
const frame = await readCollection().then((collection) => ({ type: "collection", collection }), (error) => ({ type: "refused", reason: error.message }));
|
|
84
|
+
sockets.clients.forEach((socket) => send(socket, frame));
|
|
85
|
+
}
|
|
86
|
+
async function closed({ watcher, sockets, server, runs }) {
|
|
87
|
+
watcher.close();
|
|
88
|
+
runs.forEach((record) => record.process?.cancel());
|
|
89
|
+
sockets.clients.forEach((socket) => socket.close(GOING_AWAY, "the studio is stopping"));
|
|
90
|
+
await new Promise((resolve) => sockets.close(() => resolve()));
|
|
91
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=start-studio.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function storeFolderIn(dir: string, ...parts: string[]): Promise<string>;
|