@re-cinq/floor-studio 0.11.4 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -9
- package/dist/backend/collection-view.js +2 -2
- package/dist/backend/floor-answers.d.ts +14 -0
- package/dist/backend/floor-answers.js +39 -0
- package/dist/backend/floor-blob-routes.d.ts +9 -0
- package/dist/backend/floor-blob-routes.js +30 -0
- package/dist/backend/floor-brief-route.d.ts +26 -0
- package/dist/backend/floor-brief-route.js +21 -0
- package/dist/backend/floor-connection-request.d.ts +6 -0
- package/dist/backend/floor-connection-request.js +9 -0
- package/dist/backend/floor-credentials.d.ts +16 -0
- package/dist/backend/floor-credentials.js +14 -0
- package/dist/backend/floor-event-routes.d.ts +14 -0
- package/dist/backend/floor-event-routes.js +80 -0
- package/dist/backend/floor-records-route.d.ts +3 -0
- package/dist/backend/floor-records-route.js +22 -0
- package/dist/backend/floor-request-body.d.ts +9 -0
- package/dist/backend/floor-request-body.js +30 -0
- package/dist/backend/floor-route.d.ts +12 -0
- package/dist/backend/floor-route.js +41 -0
- package/dist/backend/floor-start-route.d.ts +4 -0
- package/dist/backend/floor-start-route.js +21 -0
- package/dist/backend/floor-visits.d.ts +10 -0
- package/dist/backend/floor-visits.js +29 -0
- package/dist/backend/guard.d.ts +1 -0
- package/dist/backend/guard.js +1 -1
- package/dist/backend/parse-json-text.d.ts +1 -0
- package/dist/backend/parse-json-text.js +10 -0
- package/dist/backend/past-test-run-state.js +22 -4
- package/dist/backend/past-test-runs.js +2 -9
- package/dist/backend/requests.d.ts +10 -1
- package/dist/backend/requests.js +2 -1
- package/dist/backend/start-studio.d.ts +17 -0
- package/dist/backend/start-studio.js +45 -15
- package/dist/backend/test-floor-server.d.ts +27 -0
- package/dist/backend/test-floor-server.js +30 -0
- package/dist/backend/test-floor-token.d.ts +1 -0
- package/dist/backend/test-floor-token.js +19 -0
- package/dist/backend/test-run-folder.js +8 -5
- package/dist/backend/test-run-session.d.ts +3 -0
- package/dist/backend/test-run-session.js +56 -10
- package/dist/protocol.d.ts +13 -1
- package/dist/protocol.js +2 -1
- package/dist/shell/arguments.d.ts +2 -0
- package/dist/shell/arguments.js +12 -7
- package/dist/shell/loopback-server.d.ts +6 -0
- package/dist/shell/loopback-server.js +13 -0
- package/dist/shell/static-files.js +3 -6
- package/dist/shell/studio-command.d.ts +1 -1
- package/dist/shell/studio-command.js +24 -7
- package/dist/test-floor/blob-store.d.ts +10 -0
- package/dist/test-floor/blob-store.js +29 -0
- package/dist/test-floor/dispatch-queue.d.ts +19 -0
- package/dist/test-floor/dispatch-queue.js +90 -0
- package/dist/test-floor/visit-brief.d.ts +12 -0
- package/dist/test-floor/visit-brief.js +57 -0
- package/dist/test-floor/visit-tokens.d.ts +5 -0
- package/dist/test-floor/visit-tokens.js +12 -0
- package/dist/test-floor/worker-answer.d.ts +8 -0
- package/dist/test-floor/worker-answer.js +14 -0
- package/dist/test-run/event-answer.js +2 -1
- package/dist/test-run/outcome-fields.d.ts +2 -0
- package/dist/test-run/outcome-fields.js +3 -1
- package/dist/test-run/past-state.d.ts +7 -1
- package/dist/test-run/past-state.js +6 -2
- package/dist/test-run/stand-in-actions.d.ts +1 -0
- package/dist/test-run/stand-in-actions.js +6 -3
- package/dist/test-run/stand-in-report.js +3 -6
- package/dist/test-run/test-run-state.d.ts +5 -1
- package/dist/test-run/test-visit.d.ts +6 -0
- package/dist/test-run/timeline.d.ts +2 -1
- package/dist/test-run/visit-kind.d.ts +2 -1
- package/dist/test-run/visit-kind.js +6 -2
- package/dist/test-run/visit-record.d.ts +1 -0
- package/dist/test-run/visit-record.js +3 -3
- package/dist/view.d.ts +1 -0
- package/dist/web/assets/index-C8uog-4Z.css +1 -0
- package/dist/web/assets/index-CfJcNJKZ.js +195 -0
- package/dist/web/index.html +2 -2
- package/package.json +6 -5
- package/dist/web/assets/index-C5eUTmhR.css +0 -1
- package/dist/web/assets/index-mRcd501r.js +0 -195
package/README.md
CHANGED
|
@@ -26,23 +26,32 @@ node packages/studio/dist/cli.js path/to/collection
|
|
|
26
26
|
```
|
|
27
27
|
|
|
28
28
|
```
|
|
29
|
-
floor-studio [dir] [--port <n>] [--host-key <name>]... [--no-open]
|
|
29
|
+
floor-studio [dir] [--port <n>] [--floor-port <n>] [--host-key <name>]... [--no-open]
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
| option | meaning |
|
|
33
33
|
|---|---|
|
|
34
34
|
| `dir` | The collection. Default: the current directory. A directory that does not exist is an error, exit 1 |
|
|
35
35
|
| `--port <n>` | The port of the backend's socket on `127.0.0.1`. Default: a free one. The page's own port is always a free one |
|
|
36
|
+
| `--floor-port <n>` | The port of the [test floor](#the-test-floor) on `127.0.0.1`. Default: a free one. A port that is taken stops the start with exit 1, naming the port |
|
|
36
37
|
| `--host-key <name>` | A frontmatter key the host owns, accepted in an agent file and left out of its settings. Repeat it as often as needed. The `host_keys` of the collection's `floor-collection.yaml` count too, and are read again when that file changes. Studio reads its `groups` as well |
|
|
37
38
|
| `--no-open` | Print the url and do not open a browser. Without it the studio waits 3 seconds and opens the default browser with `xdg-open`, `open` or `start`. It skips that when a page has connected by then, such as a tab left open from before a restart. Failing to open a browser is not an error |
|
|
38
39
|
| `--help` | Print the usage and exit 0. A bad argument prints the usage to standard error and exits 2 |
|
|
39
40
|
|
|
40
|
-
It prints
|
|
41
|
+
It prints the page's url as `floor-studio: <url>`. What the page needs is in the fragment, which a browser does not send to a server:
|
|
41
42
|
|
|
42
43
|
```
|
|
43
44
|
http://127.0.0.1:<page port>/#socket=ws%3A%2F%2F127.0.0.1%3A<socket port>&token=<token>
|
|
44
45
|
```
|
|
45
46
|
|
|
47
|
+
Then it prints how a custom station's worker connects to the test floor:
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
floor-studio: test floor for custom stations:
|
|
51
|
+
export FLOOR_API_URL=http://127.0.0.1:<floor port>
|
|
52
|
+
export FLOOR_SERVICE_TOKEN=<token>
|
|
53
|
+
```
|
|
54
|
+
|
|
46
55
|
When `dist/web` does not exist the page server answers a plain page saying the page is not built. It serves only files under `dist/web`, with `Cache-Control: no-store`. It refuses a path that leaves the folder, by `..`, by a percent-encoded `..` or by a symlink.
|
|
47
56
|
|
|
48
57
|
## The page
|
|
@@ -89,7 +98,7 @@ The right-hand inspector shows the selected node's id and station, with tabs by
|
|
|
89
98
|
|
|
90
99
|
| tab | what it shows |
|
|
91
100
|
|---|---|
|
|
92
|
-
| Station | The description, each need with a sentence on how it is covered, each produce with the downstream nodes that read it, and the outcomes |
|
|
101
|
+
| Station | The description, each need with a sentence on how it is covered, each produce with the downstream nodes that read it, and the outcomes, with each produce's and outcome's description after an em dash |
|
|
93
102
|
| Events | What starts the node: an edge, an outside event, or the assembly line's own start, with its condition. The outside events that answer it, with the outcome each reports. What it raises: its events, each outcome with the node its edge starts (or that the run stops there), and the assembly lines a settled run starts |
|
|
94
103
|
| Prompt | The agent's prompt with each `{placeholder}` marked by its state, by the same name rule the lint uses (`placeholderPattern`). A table of the placeholders with their source, state and the nodes that fill them. The needs the prompt never uses. An editor when connected |
|
|
95
104
|
| Run | Runs this one station on your machine, see [Running one station](#running-one-station) |
|
|
@@ -143,11 +152,11 @@ The need values are saved in `.floor-studio/fixtures/<line>/<node>.json` and eac
|
|
|
143
152
|
|
|
144
153
|
### Testing a whole line
|
|
145
154
|
|
|
146
|
-
The backend can run a whole assembly line on your machine as a test run (`startTestRun` in `src/backend/test-run-session.ts`), through the `test.*` and `folder.*` requests in the protocol. Every screen has a breadcrumb trail (collection folder, line, Test locally, run folder) whose crumbs link back. The page's Test locally button opens a start screen (workspace folder, inputs, Start; a blocker shows as the refusal, and agents run under `acceptEdits`); the run screen lists the visits, offers a waiting visit's actions (a file output is pasted or given as a path on disk, not both), and has Cancel and the folder buttons. Every path is picked in one modal dialog, `PathPicker` in `web/src/app/PathPicker.tsx`: a folder or a file. The workspace picker opens in the folder typed in its field; every other picker, and the workspace picker with an empty field, opens in the home folder of the user the studio runs as. In file mode it lists only the files matching the chosen mask, and a file output declared at `annotated.md` offers `*.md` first, with All files always on offer. Its path bar works like a zsh line: the text after the last `/` filters the folder case-insensitively, by prefix and else by substring, hiding dot entries unless it starts with a dot; typing or deleting a `/` opens that folder; Tab completes one match in full or several to their common prefix; Enter chooses a file typed in full, opens a folder typed in full, or in folder mode uses the shown folder. The start screen shows the start inputs as the Bag at start: each input's kind, a subject mark, where the floor fills it from on each start event, and its value (git and file inputs with Browse); the run screen shows the run's bag as it grows, each item with its value or path and the start or visit that put it there. On either screen, a refused request shows its reason until a later request succeeds. When the connection drops and returns, the run screen reads its run again, since pushed changes are not replayed. The workspace and inputs a line was last started with are remembered per collection in `$XDG_CONFIG_HOME/floor-studio/last-tests.json` (or `~/.config/floor-studio/last-tests.json`), written when a start succeeds; a file that is not valid JSON counts as nothing remembered, and a failed write never fails the start.
|
|
155
|
+
The backend can run a whole assembly line on your machine as a test run (`startTestRun` in `src/backend/test-run-session.ts`), through the `test.*` and `folder.*` requests in the protocol. Every screen has a breadcrumb trail (collection folder, line, Test locally, run folder) whose crumbs link back. The page's Test locally button opens a start screen (workspace folder, inputs, Start; a blocker shows as the refusal, and agents run under `acceptEdits`); the run screen lists the visits, offers a waiting visit's actions, grouped per outcome with a dropdown for an `enum` field and a field's `description` as help text (a file output is pasted or given as a path on disk, not both), and has Cancel and the folder buttons. Every path is picked in one modal dialog, `PathPicker` in `web/src/app/PathPicker.tsx`: a folder or a file. The workspace picker opens in the folder typed in its field; every other picker, and the workspace picker with an empty field, opens in the home folder of the user the studio runs as. In file mode it lists only the files matching the chosen mask, and a file output declared at `annotated.md` offers `*.md` first, with All files always on offer. Its path bar works like a zsh line: the text after the last `/` filters the folder case-insensitively, by prefix and else by substring, hiding dot entries unless it starts with a dot; typing or deleting a `/` opens that folder; Tab completes one match in full or several to their common prefix; Enter chooses a file typed in full, opens a folder typed in full, or in folder mode uses the shown folder. The start screen shows the start inputs as the Bag at start: each input's kind, a subject mark, where the floor fills it from on each start event, and its value (git and file inputs with Browse); the run screen shows the run's bag as it grows, each item with its value or path and the start or visit that put it there. On either screen, a refused request shows its reason until a later request succeeds. When the connection drops and returns, the run screen reads its run again, since pushed changes are not replayed. The workspace and inputs a line was last started with are remembered per collection in `$XDG_CONFIG_HOME/floor-studio/last-tests.json` (or `~/.config/floor-studio/last-tests.json`), written when a start succeeds; a file that is not valid JSON counts as nothing remembered, and a failed write never fails the start.
|
|
147
156
|
|
|
148
157
|
A test run reads the line as saved on disk. It is refused before anything is written when an argument or line file has no value, or when the line cannot run locally: it fails validation, a node pins a station (`reviewer@abc123`), or a node fans out. One message lists every reason.
|
|
149
158
|
|
|
150
|
-
The floor's routing kernel decides each next step. An agent station runs with the same code as the Run tab. Any other station waits for a person, who answers with an outcome, values, and a file for each file output, picked from disk or pasted. The answer is refused, and the visit stays open, when the outcome is not the station's, a required field is neither entered nor supplied as a file, a picked file is not an absolute path, not on disk, or a folder rather than a file, a file is for an output that is not a file output, or the output's path leaves the visit's `outputs/` folder. A picked file that cannot be copied after the checks (it vanished, say) refuses the answer with the copy's error and leaves the visit open, so the person can answer again. A visit answers once, and a settled run takes no answers or events. An external event answers each waiting visit whose node `reports` match it, and is recorded in the timeline whether it answered anything or not. Cancel stops the running agent, or ends the wait for a person, and settles the run as `cancelled`. A cancel that arrives before the agent has started stops it as soon as it starts. Writes of a run's `timeline.jsonl` and `run.json` go one at a time, in the order they were asked for, so the last `run.json` holds the latest state. Test runs live as long as the studio: they are not resumed after a restart.
|
|
159
|
+
The floor's routing kernel decides each next step. An agent station runs with the same code as the Run tab. Any other station waits for a person, who answers with an outcome, values, and a file for each file output, picked from disk or pasted. The answer is refused, and the visit stays open, when the outcome is not the station's, a required field is neither entered nor supplied as a file, a value is outside the item's `enum`, a picked file is not an absolute path, not on disk, or a folder rather than a file, a file is for an output that is not a file output, or the output's path leaves the visit's `outputs/` folder. A picked file that cannot be copied after the checks (it vanished, say) refuses the answer with the copy's error and leaves the visit open, so the person can answer again. A visit answers once, and a settled run takes no answers or events. An external event answers each waiting visit whose node `reports` match it, and is recorded in the timeline whether it answered anything or not. Cancel stops the running agent, or ends the wait for a person, and settles the run as `cancelled`. A cancel that arrives before the agent has started stops it as soon as it starts. Writes of a run's `timeline.jsonl` and `run.json` go one at a time, in the order they were asked for, so the last `run.json` holds the latest state. Test runs live as long as the studio: they are not resumed after a restart.
|
|
151
160
|
|
|
152
161
|
A run never hangs on a failure. An agent that cannot be started (any blocker the Run tab would show) fails its visit with the blocker as the reason, and so does an agent that leaves a declared output as a link instead of a file it wrote, or reached through a linked folder (`notes/draft.md` where `notes` is a link): nothing is copied. Any other error while the run steps, a failed disk write for one, settles the run with outcome `error` and the error's message.
|
|
153
162
|
|
|
@@ -165,11 +174,36 @@ review-loop-20261127-141230/
|
|
|
165
174
|
transcript.jsonl
|
|
166
175
|
work/ the agent's working folder
|
|
167
176
|
outputs/ a copy of each file output, so a later visit never overwrites it; a file a person supplies goes at the output's declared path, or under the output's name when it declares none
|
|
168
|
-
|
|
177
|
+
records.jsonl what a test floor worker posted to its visit's records, one JSON line each
|
|
178
|
+
visit.json mode (local, simulated, or worker when a test floor worker's report was taken, with `worker` naming it), opened, reported, durationMs, the agent's own time and cost, outcome, next node
|
|
169
179
|
```
|
|
170
180
|
|
|
171
181
|
`durationMs` is the wall time between opened and reported. `agentDurationMs` and `costUsd` are what the agent stated, and are absent when it stated none.
|
|
172
182
|
|
|
183
|
+
### The test floor
|
|
184
|
+
|
|
185
|
+
The test floor stands in for the floor API, so a `kind: service` station's own worker, started however you start it, can be tested against a local test run. It is a plain HTTP server on `127.0.0.1` (`startTestFloor` in `src/backend/test-floor-server.ts`), started and closed with the command. Every request needs `Authorization: Bearer <token>`. The token is kept per collection in `.floor-studio/test-floor.json`, so a worker's env survives a restart; a missing or unreadable file gets a fresh token.
|
|
186
|
+
|
|
187
|
+
A visit to a service station waits like a person's visit, with the same buttons, and also queues a `station_run.dispatch {visitId}` tagged `station:<station id>` (`src/test-floor/dispatch-queue.ts`; the `visitId` is a UUID). The run does not wait for the worker. When the visit ends without the worker's report (a person answered, or the run settled), the dispatch is dropped and the worker gets one `station_run.abort` instead. The queue follows the floor's rules:
|
|
188
|
+
|
|
189
|
+
| Request | Answer |
|
|
190
|
+
|---|---|
|
|
191
|
+
| `POST /events/claim` `{tags, limit}` | 200 with up to `limit` events whose tags are all among `tags`, oldest first, each with `attempts`; 204 when there are none. A claimed event is not handed out again |
|
|
192
|
+
| `POST /events/:id/ack` | 204; the event is never claimed again |
|
|
193
|
+
| `POST /events/:id/fail` `{error, permanent}` | 204; the event is claimable again after the floor's backoff (1 s, 2 s, 4 s, up to 10 min), with `attempts` one higher. The 8th fail, or `permanent: true`, retires it |
|
|
194
|
+
| `GET /station-runs/:visitId/brief`, service or visit token | 200 `VisitBrief` (`src/test-floor/visit-brief.ts`) with a fresh visit `token`. Value needs come first; a file need is stored as a blob and given as `url: <test floor>/blobs/<hash>`; a git need is given as `repoUrl` (the local checkout) at `ref: "HEAD"`. 404 `no station run "<id>" to dispatch` for a visit the test floor does not know, 409 `station run "<id>" is already done` once the visit was answered or its run stopped, and 409 with the reason when a need's file is gone or its checkout is not a git repository |
|
|
195
|
+
| `GET /blobs/:hash`, service or visit token | 200 with the bytes and the stored content type. A visit token reads only the blobs its brief gave; anything else, and any hash that is not `sha256-<64 hex>`, is 404 `no blob "<hash>"` |
|
|
196
|
+
| `POST /blobs`, service or visit token | 201 `{hash, size}`. The first content type stored for a hash is kept; none given is `application/octet-stream`. Over 64 MiB is 413, and nothing is stored |
|
|
197
|
+
| `POST /events` `station_run.reported {visitId, worker?, report}`, service or visit token | 201 with the event; the visit reports as if a person pressed the outcome, and the run steps on. Checked in the floor's order: 400 `invalid event`, 403 for a visit token posting another name or for another visit, 400 `station_run.reported: <reason>`, 404 `no visit "<id>"`, 400 for a `runId` that is not the visit's run, 400 for an undeclared outcome or produce (`src/backend/floor-event-routes.ts`). A file output's value is the hash of a blob the test floor stored, copied to the visit's `outputs/`; a hash it did not store is 400 `<name>: no blob "<value>"`, and a required field missing for the outcome is 400 with the stand-in's wording. A report for a visit already answered, or a run settled or cancelled, is 201 and changes nothing: the first answer wins |
|
|
198
|
+
| `POST /station-runs/:visitId/records`, service or visit token | 201 `{ items }`; each record is appended to the visit's `records.jsonl`. 400 `invalid records` with the schema's `errors`, 404 `no visit "<id>"` |
|
|
199
|
+
| `POST /assembly-lines/:id/start` `{startItems}`, visit token | 201 `{ run, joined: false }`: a new test run of that line, in the starting run's workspace, from its copy of the definitions and with its permission. Each start item's `ref` is the value for its name; the run's `startItems` are what the line asks for. 400 `invalid start request` with the schema's `errors`, 404 `no station run "<id>"` for a visit the test floor does not know, 409 `station run "<id>" is already done, so it starts no run`, and 400 with the reason for a line the copy does not have or a required argument missing or blank; such a start writes nothing |
|
|
200
|
+
|
|
201
|
+
A claim records its time and its claimant, as the floor does: the `x-worker-id` header when sent (an empty one included), else the caller's address. Each claim or fail that changes a dispatch pushes `test.changed`; an ack does not. The page shows the test floor's export lines and each service station's tag in a Test floor panel, and the dispatch in the visit's row.
|
|
202
|
+
|
|
203
|
+
Ack and fail of an id the queue never gave answer 204 and change nothing. A claim is not taken back after 5 minutes, as the floor does, so a worker paused in a debugger keeps it. Every refusal is an RFC 9457 `application/problem+json` body, so the floor client reads it as a `FloorProblem`: 401 `missing or invalid bearer token` for a missing or wrong token, 403 for a visit token on a route outside its scope or on another visit, 400 for a body that is not a claim or a fail (with the schema's `errors`), an event or records, or a malformed URL, 404 naming the routes a station uses for any other route, and 500 `An internal server error occurred` for anything unexpected.
|
|
204
|
+
|
|
205
|
+
Where it differs from the floor: a visit token is an opaque string that stays valid while Studio runs, not until the deadline; nothing enforces the brief's `deadlineMinutes` of 60; blobs are kept per collection in `.floor-studio/blobs/<hash>` and are not hashed again when read; the service token posting an event other than `station_run.reported` is 400, since there is nothing to route it to; a required produce missing for the outcome is 400 at the post, where the floor refuses it only when the next node opens; the bag holds a file produce's `outputs/` path, not its hash; a records answer lists the records as posted; only a visit's token starts a run (400 for the service token), a start never joins an open run, `entry` is refused with 400, and `lineHash` is ignored, since the run's copy of the definitions is the version.
|
|
206
|
+
|
|
173
207
|
### The environment
|
|
174
208
|
|
|
175
209
|
The sidebar lists the variables the settings name as `${NAME}`, with the files using each. A setting written that way shows as a chip, `env: NAME`. The studio does not fill it.
|
|
@@ -209,19 +243,20 @@ Every frame is JSON in one WebSocket message. A request carries an `id` the clie
|
|
|
209
243
|
| client to backend | `{ id, type: "run.cancel", run }` | Stop a running run. Refused when none runs under that id. The result is `{ cancelled: run }` |
|
|
210
244
|
| client to backend | `{ id, type: "run.read", run, after }` | The transcript of a run from line number `after` on, running or ended, also after a restart. The result is `{ lines, ended? }` |
|
|
211
245
|
| client to backend | `{ id, type: "test.preview", line, entered }` | What starting a test run of the line would take. The result is `{ asked, missing, blockers, startItems, definitions }`: each argument and line file asked for with its kind, the ones without a value, why the line cannot run locally, the start items, and the collection files a start would copy |
|
|
212
|
-
| client to backend | `{ id, type: "test.start", line, workspace, entered, permission }` | Start a test run of the line as saved on disk, in a new folder inside `workspace`. Refused, with nothing written, for the reasons the preview lists, a workspace that is relative or not a folder,
|
|
213
|
-
| client to backend | `{ id, type: "test.list" }` | The test runs this studio has started, plus the past runs found in the workspaces each line was started in (from their `run.json`; a run a restart left mid-way is `stopped`), newest first: `[{ run, line, folder, status, startedAt, ending? }]`. The page lists a line's runs beside Test locally and badges each line in the sidebar with its runs in progress, asking again whenever the connection opens and on a `test.changed` frame that brings news (an unknown run, or a changed status or ending). `test.read` opens a past run from disk, read-only, but only a folder this scan found; in a stopped run, a visit that never reported reads stopped |
|
|
246
|
+
| client to backend | `{ id, type: "test.start", line, workspace, entered, permission }` | Start a test run of the line as saved on disk, in a new folder inside `workspace`. Refused, with nothing written, for the reasons the preview lists, or a workspace that is relative or not a folder. A run never reuses a folder: when `<line>-<UTC time>` is taken, as by a start in the same second, it takes the first free `-2`, `-3` and on. A start that fails after its folder is made removes that folder. The result is `{ run, folder }` |
|
|
247
|
+
| client to backend | `{ id, type: "test.list" }` | The test runs this studio has started, plus the past runs found in the workspaces each line was started in (from their `run.json`; a run a restart left mid-way is `stopped`), newest first: `[{ run, line, folder, status, startedAt, ending? }]`. The page lists a line's runs beside Test locally and badges each line in the sidebar with its runs in progress, asking again whenever the connection opens and on a `test.changed` frame that brings news (an unknown run, or a changed status or ending). `test.read` opens a past run from disk, read-only, but only a folder this scan found; in a stopped run, a visit that never reported reads stopped. A past run's bag is rebuilt from its `run.json`, its visits' `visit.json` and the line in its `definitions/`; with that folder gone it reads back without a bag. A `visit.json` that is not JSON reads as that visit unreported, and a `timeline.jsonl` line that is not JSON, such as one half written when the studio stopped, is skipped |
|
|
214
248
|
| client to backend | `{ id, type: "test.last", line }` | The values the line was last started with in this collection. The result is `{ workspace, entered }`, or `null` when nothing is remembered |
|
|
215
249
|
| client to backend | `{ id, type: "test.report", run, visit, outcome, produced, files? }` | Answer for a waiting visit, as the person standing in for its station. `files` maps each file output to `{ picked: <path> }` or `{ pasted: <text> }`. The result is `{ reported: visit }` once the run has stepped on |
|
|
216
250
|
| client to backend | `{ id, type: "test.event", run, event, payload }` | Send an external event. It answers each waiting visit whose node `reports` match it, as the floor does, and is recorded either way. The result is `{ answered }`, the visit ids |
|
|
217
251
|
| client to backend | `{ id, type: "test.read", run }` | The run's state. The result is the same `state` that `test.changed` carries |
|
|
218
252
|
| client to backend | `{ id, type: "test.cancel", run }` | Stop the run's agent, if one runs, and settle the run as `cancelled`. The result is `{ cancelled: run }`, sent once it has settled |
|
|
253
|
+
| client to backend | `{ id, type: "floor.connection" }` | Where the [test floor](#the-test-floor) listens and its service token: `{ url, token }`. Refused with `the test floor is not running` before it listens or after it closed. No pushed frame carries the token |
|
|
219
254
|
| client to backend | `{ id, type: "folder.list", path? }` | The names in a folder, for the page's picker: `{ path, parent, folders, files }`, each sorted. With no `path` it lists the home folder of the user the studio runs as. `parent` is `null` at the root. File contents are never read. Refused when `path` is relative or not a folder. A link to a folder is listed under `files` |
|
|
220
255
|
| client to backend | `{ id, type: "folder.open", path }` | Open a test run's folder, or a folder inside one, in the desktop's file manager; a past run `test.list` finds counts too. Only an existing folder whose real path, links resolved, lies inside a test run's folder is opened: a file, a missing path, a path that climbs out with `..`, and a link pointing out of the run are refused. The result is `{ opened: path }` |
|
|
221
256
|
| backend to client | `{ id, type: "result", result }` | The answer to a request. For `collection.read`, `result` is the collection view |
|
|
222
257
|
| backend to client | `{ id?, type: "refused", reason }` | A frame that is not JSON, fails its schema or has an unknown `type`, or a request that failed. The `id` is there when one could be read. Also pushed unasked, without an `id`, when a re-read after a change on disk fails, such as the folder being deleted. The socket stays open |
|
|
223
258
|
| backend to client | `{ type: "collection", collection }` | A file the collection reads changed on disk, whoever changed it. The whole view is sent again |
|
|
224
|
-
| backend to client | `{ type: "test.changed", run, state }` | A test run changed: a visit opened or reported, an event came in,
|
|
259
|
+
| backend to client | `{ type: "test.changed", run, state }` | A test run changed: a visit opened or reported, an event came in, the run settled, or a worker claimed or failed a service visit's dispatch. `state` is `{ folder, lineId, status, ending?, visits, actions }`, with `status` one of `running`, `waiting` and `settled`; `actions` lists, by visit id, what each visit waiting for a person offers. A service visit of a live run carries `dispatch: { tag, claimedAt?, claimedBy?, gaveUp? }`: just `tag` while unclaimed or put back after a fail, `claimedAt` and `claimedBy` once claimed, `gaveUp` with the error once failed for good; none once it reported, nor on a settled or past run. A request naming a run the studio does not have is refused with `there is no test run <id>` |
|
|
225
260
|
| backend to client | `{ type: "run.output", run, line: { stream, text } }` | One line a run wrote, on `stdout` or `stderr`, sent to every socket |
|
|
226
261
|
| backend to client | `{ type: "run.ended", run, exitCode, error?, outcome?, costUsd?, durationMs?, produced?, edge? }` | A run ended. `exitCode` is `null` when it was cancelled, and then the rest is absent. It is also `null` when the agent's program could not be started, and then `error` says why. Otherwise `outcome` is the agent's verdict, `produced` lists each file produce as `{ name, found }`, and `edge` is the `{ from, to, on }` the outcome takes (none from a terminal node). `costUsd` and `durationMs` are what the agent's final `result` line states as `total_cost_usd` and `duration_ms`. Each is absent unless the agent stated it as a finite number of zero or more, so an unstated cost is never read as zero |
|
|
227
262
|
|
|
@@ -246,6 +281,8 @@ The backend writes files and starts processes, so no web page may reach it. Thre
|
|
|
246
281
|
|
|
247
282
|
A refused upgrade gets no socket at all.
|
|
248
283
|
|
|
284
|
+
The test floor follows the same rules: it listens on `127.0.0.1` only, refuses to start without a token, and compares the bearer token in constant time.
|
|
285
|
+
|
|
249
286
|
## Change watching
|
|
250
287
|
|
|
251
288
|
The backend watches `dir` with `fs.watch` and `recursive: true`. It ignores a path the collection does not read and anything under a dot folder. It waits about 100 ms for the changes to settle, then pushes one `collection` frame to every open socket, or one `refused` frame without an `id` when the read fails. A file that is deleted or renamed is handled the same way. A watcher error does not stop the backend.
|
|
@@ -66,9 +66,9 @@ function extraOf(agentName, line, files) {
|
|
|
66
66
|
return text === undefined ? {} : { extra: { file, text, version: textVersion(text) } };
|
|
67
67
|
}
|
|
68
68
|
function stationFacts(station, { node, line, needContext }) {
|
|
69
|
-
const { kind, description, agentDefinition, resultRequired, outcomes = [], needs = [], produces = [] } = station ?? {};
|
|
69
|
+
const { kind, description, outcomeDescriptions, agentDefinition, resultRequired, outcomes = [], needs = [], produces = [] } = station ?? {};
|
|
70
70
|
return {
|
|
71
|
-
...present({ kind, description, agentDefinition, resultRequired }),
|
|
71
|
+
...present({ kind, description, outcomeDescriptions, agentDefinition, resultRequired }),
|
|
72
72
|
outcomes,
|
|
73
73
|
needs: needs.map((need) => ({ ...need, coverage: needCoverage(node, need, needContext) })),
|
|
74
74
|
produces: produces.map((produce) => ({ ...produce, readBy: readersOf(produce.name, node, line) })),
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ServerResponse } from "node:http";
|
|
2
|
+
export declare const SUCCESS = 200;
|
|
3
|
+
export declare const CREATED = 201;
|
|
4
|
+
export declare function answerJson(response: ServerResponse, body: unknown, status?: number): void;
|
|
5
|
+
export declare function answerNoContent(response: ServerResponse): void;
|
|
6
|
+
export declare const answerBadRequest: (response: ServerResponse, detail: string, errors?: string[]) => void;
|
|
7
|
+
export declare const answerUnauthorized: (response: ServerResponse) => void;
|
|
8
|
+
export declare const answerForbidden: (response: ServerResponse, detail: string) => void;
|
|
9
|
+
export declare const answerNotFound: (response: ServerResponse, detail: string) => void;
|
|
10
|
+
export declare const noVisit: (visitId: string) => string;
|
|
11
|
+
export declare const answerConflict: (response: ServerResponse, detail: string) => void;
|
|
12
|
+
export declare function answerPayloadTooLarge(response: ServerResponse, limit: number): void;
|
|
13
|
+
export declare const answerInternalError: (response: ServerResponse) => void;
|
|
14
|
+
export declare const answerRefusalWith: (response: ServerResponse, answer: (response: ServerResponse, detail: string) => void) => (error: unknown) => void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Refusal } from "@re-cinq/floor-assembly-lines";
|
|
2
|
+
export const SUCCESS = 200;
|
|
3
|
+
export const CREATED = 201;
|
|
4
|
+
const NO_CONTENT = 204;
|
|
5
|
+
const BAD_REQUEST = 400;
|
|
6
|
+
const UNAUTHORIZED = 401;
|
|
7
|
+
const FORBIDDEN = 403;
|
|
8
|
+
const NOT_FOUND = 404;
|
|
9
|
+
const CONFLICT = 409;
|
|
10
|
+
const PAYLOAD_TOO_LARGE = 413;
|
|
11
|
+
const INTERNAL_SERVER_ERROR = 500;
|
|
12
|
+
export function answerJson(response, body, status = SUCCESS) {
|
|
13
|
+
response.writeHead(status, { "Content-Type": "application/json" });
|
|
14
|
+
response.end(JSON.stringify(body));
|
|
15
|
+
}
|
|
16
|
+
export function answerNoContent(response) {
|
|
17
|
+
response.writeHead(NO_CONTENT).end();
|
|
18
|
+
}
|
|
19
|
+
export const answerBadRequest = (response, detail, errors) => answerProblem(response, { status: BAD_REQUEST, title: "Bad Request", detail, errors });
|
|
20
|
+
export const answerUnauthorized = (response) => answerProblem(response, { status: UNAUTHORIZED, title: "Unauthorized", detail: "missing or invalid bearer token" });
|
|
21
|
+
export const answerForbidden = (response, detail) => answerProblem(response, { status: FORBIDDEN, title: "Forbidden", detail });
|
|
22
|
+
export const answerNotFound = (response, detail) => answerProblem(response, { status: NOT_FOUND, title: "Not Found", detail });
|
|
23
|
+
export const noVisit = (visitId) => `no visit "${visitId}"`;
|
|
24
|
+
export const answerConflict = (response, detail) => answerProblem(response, { status: CONFLICT, title: "Conflict", detail });
|
|
25
|
+
export function answerPayloadTooLarge(response, limit) {
|
|
26
|
+
response.setHeader("Connection", "close");
|
|
27
|
+
answerProblem(response, { status: PAYLOAD_TOO_LARGE, title: "Request Entity Too Large", detail: `Payload content length greater than maximum allowed: ${limit}` });
|
|
28
|
+
}
|
|
29
|
+
export const answerInternalError = (response) => answerProblem(response, { status: INTERNAL_SERVER_ERROR, title: "Internal Server Error", detail: "An internal server error occurred" });
|
|
30
|
+
function answerProblem(response, { status, title, detail, errors }) {
|
|
31
|
+
response.writeHead(status, { "Content-Type": "application/problem+json" });
|
|
32
|
+
response.end(JSON.stringify({ type: "about:blank", title, status, detail, errors }));
|
|
33
|
+
}
|
|
34
|
+
export const answerRefusalWith = (response, answer) => (error) => {
|
|
35
|
+
if (!(error instanceof Refusal))
|
|
36
|
+
throw error;
|
|
37
|
+
answer(response, error.message);
|
|
38
|
+
};
|
|
39
|
+
//# sourceMappingURL=floor-answers.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { BlobStore } from "../test-floor/blob-store.js";
|
|
2
|
+
import type { GivenNeeds } from "./floor-brief-route.js";
|
|
3
|
+
import type { Route } from "./floor-route.js";
|
|
4
|
+
interface BlobServices {
|
|
5
|
+
blobs: BlobStore;
|
|
6
|
+
givenNeeds: GivenNeeds;
|
|
7
|
+
}
|
|
8
|
+
export declare const blobRoutesOf: ({ blobs, givenNeeds }: BlobServices) => Route[];
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { MAX_BLOB_BYTES, wasGivenBlob } from "@re-cinq/floor-assembly-lines";
|
|
2
|
+
import { answerBadRequest, answerJson, answerNotFound, answerPayloadTooLarge, CREATED, SUCCESS } from "./floor-answers.js";
|
|
3
|
+
import { bytesOf } from "./floor-request-body.js";
|
|
4
|
+
export const blobRoutesOf = ({ blobs, givenNeeds }) => [
|
|
5
|
+
{
|
|
6
|
+
method: "GET",
|
|
7
|
+
pattern: /^\/blobs\/([^/]+)$/,
|
|
8
|
+
visitsToo: true,
|
|
9
|
+
answer: async (request, response, [hash], credentials) => {
|
|
10
|
+
const isCovered = credentials.kind !== "visit" || wasGivenBlob(hash, givenNeeds.get(credentials.visitId) ?? []);
|
|
11
|
+
const blob = isCovered ? await blobs.read(hash) : undefined;
|
|
12
|
+
if (!blob)
|
|
13
|
+
return answerNotFound(response, `no blob "${hash}"`);
|
|
14
|
+
response.writeHead(SUCCESS, { "Content-Type": blob.contentType }).end(blob.bytes);
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
method: "POST",
|
|
19
|
+
pattern: /^\/blobs$/,
|
|
20
|
+
visitsToo: true,
|
|
21
|
+
answer: async (request, response) => {
|
|
22
|
+
if (Number(request.headers["content-length"]) > MAX_BLOB_BYTES)
|
|
23
|
+
return answerPayloadTooLarge(response, MAX_BLOB_BYTES);
|
|
24
|
+
await blobs
|
|
25
|
+
.store(await bytesOf(request), request.headers["content-type"] ?? "application/octet-stream")
|
|
26
|
+
.then((blobRef) => answerJson(response, blobRef, CREATED), (error) => answerBadRequest(response, error.message));
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
];
|
|
30
|
+
//# sourceMappingURL=floor-blob-routes.js.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { BlobStore } from "../test-floor/blob-store.js";
|
|
2
|
+
import type { VisitBrief } from "@re-cinq/floor-contracts";
|
|
3
|
+
import type { VisitTokens } from "../test-floor/visit-tokens.js";
|
|
4
|
+
import type { TestRun, VisitState } from "../test-run/test-visit.js";
|
|
5
|
+
import type { TestRunStart } from "./test-run-session.js";
|
|
6
|
+
import { type Route } from "./floor-route.js";
|
|
7
|
+
export interface FloorVisit {
|
|
8
|
+
run: TestRun;
|
|
9
|
+
runId: string;
|
|
10
|
+
visit: VisitState;
|
|
11
|
+
ended: boolean;
|
|
12
|
+
runFolder: string;
|
|
13
|
+
permission: TestRunStart["permission"];
|
|
14
|
+
}
|
|
15
|
+
export interface FloorVisits {
|
|
16
|
+
visitOf(floorVisitId: string): FloorVisit | undefined;
|
|
17
|
+
}
|
|
18
|
+
export type GivenNeeds = Map<string, VisitBrief["needs"]>;
|
|
19
|
+
export interface BriefServices {
|
|
20
|
+
visits: FloorVisits;
|
|
21
|
+
tokens: VisitTokens;
|
|
22
|
+
blobs: BlobStore;
|
|
23
|
+
givenNeeds: GivenNeeds;
|
|
24
|
+
floorUrl(): string;
|
|
25
|
+
}
|
|
26
|
+
export declare const briefRouteOf: (services: BriefServices) => Route;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { visitBriefOf } from "../test-floor/visit-brief.js";
|
|
2
|
+
import { answerConflict, answerJson, answerNotFound, answerRefusalWith } from "./floor-answers.js";
|
|
3
|
+
import { forOwnVisit } from "./floor-route.js";
|
|
4
|
+
export const briefRouteOf = (services) => ({
|
|
5
|
+
method: "GET",
|
|
6
|
+
pattern: /^\/station-runs\/([^/]+)\/brief$/,
|
|
7
|
+
visitsToo: true,
|
|
8
|
+
answer: forOwnVisit((response, floorVisitId) => answerBrief(response, floorVisitId, services)),
|
|
9
|
+
});
|
|
10
|
+
async function answerBrief(response, floorVisitId, { visits, tokens, blobs, givenNeeds, floorUrl }) {
|
|
11
|
+
const known = visits.visitOf(floorVisitId);
|
|
12
|
+
if (!known)
|
|
13
|
+
return answerNotFound(response, `no station run "${floorVisitId}" to dispatch`);
|
|
14
|
+
if (known.ended)
|
|
15
|
+
return answerConflict(response, `station run "${floorVisitId}" is already done`);
|
|
16
|
+
await visitBriefOf({ ...known, floorUrl: floorUrl(), mintToken: () => tokens.mint(floorVisitId), blobs }).then((brief) => {
|
|
17
|
+
givenNeeds.set(floorVisitId, brief.needs);
|
|
18
|
+
answerJson(response, brief);
|
|
19
|
+
}, answerRefusalWith(response, answerConflict));
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=floor-brief-route.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { enforce } from "@re-cinq/floor-assembly-lines";
|
|
2
|
+
export const floorConnectionHandler = {
|
|
3
|
+
type: "floor.connection",
|
|
4
|
+
async handle({ floorConnection }) {
|
|
5
|
+
enforce(floorConnection, "the test floor is not running");
|
|
6
|
+
return floorConnection;
|
|
7
|
+
},
|
|
8
|
+
};
|
|
9
|
+
//# sourceMappingURL=floor-connection-request.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { VisitTokens } from "../test-floor/visit-tokens.js";
|
|
3
|
+
export type Credentials = {
|
|
4
|
+
kind: "service";
|
|
5
|
+
} | {
|
|
6
|
+
kind: "visit";
|
|
7
|
+
visitId: string;
|
|
8
|
+
};
|
|
9
|
+
export interface CredentialSources {
|
|
10
|
+
token: string;
|
|
11
|
+
tokens: VisitTokens;
|
|
12
|
+
}
|
|
13
|
+
export declare function credentialsOf(request: IncomingMessage, { token, tokens }: CredentialSources): Credentials | undefined;
|
|
14
|
+
export declare const mayUse: (credentials: Credentials, { visitsToo }: {
|
|
15
|
+
visitsToo?: true;
|
|
16
|
+
}) => boolean;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { isSameToken } from "./guard.js";
|
|
2
|
+
const BEARER_PREFIX = "Bearer ";
|
|
3
|
+
export function credentialsOf(request, { token, tokens }) {
|
|
4
|
+
const authorization = request.headers.authorization ?? "";
|
|
5
|
+
const bearer = authorization.slice(BEARER_PREFIX.length);
|
|
6
|
+
if (!authorization.startsWith(BEARER_PREFIX))
|
|
7
|
+
return undefined;
|
|
8
|
+
if (isSameToken(bearer, token))
|
|
9
|
+
return { kind: "service" };
|
|
10
|
+
const visitId = tokens.visitOf(bearer);
|
|
11
|
+
return visitId === undefined ? undefined : { kind: "visit", visitId };
|
|
12
|
+
}
|
|
13
|
+
export const mayUse = (credentials, { visitsToo }) => credentials.kind === "service" || visitsToo === true;
|
|
14
|
+
//# sourceMappingURL=floor-credentials.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { BlobStore } from "../test-floor/blob-store.js";
|
|
2
|
+
import type { DispatchQueue } from "../test-floor/dispatch-queue.js";
|
|
3
|
+
import type { FloorVisits } from "./floor-brief-route.js";
|
|
4
|
+
import type { ReportFromWorker } from "./floor-visits.js";
|
|
5
|
+
import type { Route } from "./floor-route.js";
|
|
6
|
+
interface EventServices {
|
|
7
|
+
queue: DispatchQueue;
|
|
8
|
+
visits: FloorVisits;
|
|
9
|
+
blobs: BlobStore;
|
|
10
|
+
dispatchChanged: (floorVisitIds: string[]) => void;
|
|
11
|
+
reportFromWorker: ReportFromWorker;
|
|
12
|
+
}
|
|
13
|
+
export declare const eventRoutesOf: ({ queue, visits, blobs, dispatchChanged, reportFromWorker }: EventServices) => Route[];
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { reportRefusalOf } from "@re-cinq/floor-assembly-lines";
|
|
2
|
+
import { claimEventsSchema, enqueueEventSchema, failEventSchema, reportedPayloadSchema } from "@re-cinq/floor-pipeline/wire-schemas";
|
|
3
|
+
import { workerAnswerOf } from "../test-floor/worker-answer.js";
|
|
4
|
+
import { stationAt } from "../test-run/test-line.js";
|
|
5
|
+
import { CREATED, answerBadRequest, answerForbidden, answerJson, answerNoContent, answerNotFound, answerRefusalWith, noVisit } from "./floor-answers.js";
|
|
6
|
+
import { answerBody, issuesOf } from "./floor-request-body.js";
|
|
7
|
+
export const eventRoutesOf = ({ queue, visits, blobs, dispatchChanged, reportFromWorker }) => [
|
|
8
|
+
{ method: "POST", pattern: /^\/events$/, visitsToo: true, answer: (request, response, params, credentials) => answerPosted({ request, response, credentials, visits, blobs, reportFromWorker }) },
|
|
9
|
+
{
|
|
10
|
+
method: "POST",
|
|
11
|
+
pattern: /^\/events\/claim$/,
|
|
12
|
+
answer: (request, response) => answerBody(request, response, { schema: claimEventsSchema, invalidDetail: "invalid claim request" }, ({ tags, limit }) => answerClaimed(response, queue.claim(tags, limit, claimantOf(request)), dispatchChanged)),
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
method: "POST",
|
|
16
|
+
pattern: /^\/events\/([^/]+)\/ack$/,
|
|
17
|
+
answer: (request, response, [eventId]) => {
|
|
18
|
+
queue.ack(eventId);
|
|
19
|
+
answerNoContent(response);
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
method: "POST",
|
|
24
|
+
pattern: /^\/events\/([^/]+)\/fail$/,
|
|
25
|
+
answer: (request, response, [eventId]) => answerBody(request, response, { schema: failEventSchema, invalidDetail: "invalid fail request" }, ({ permanent, error }) => {
|
|
26
|
+
const failedVisitId = queue.fail(eventId, { permanent, error });
|
|
27
|
+
if (failedVisitId)
|
|
28
|
+
dispatchChanged([failedVisitId]);
|
|
29
|
+
answerNoContent(response);
|
|
30
|
+
}),
|
|
31
|
+
},
|
|
32
|
+
];
|
|
33
|
+
function answerPosted({ request, response, credentials, visits, blobs, reportFromWorker }) {
|
|
34
|
+
return answerBody(request, response, { schema: enqueueEventSchema, invalidDetail: "invalid event" }, (event) => {
|
|
35
|
+
const { name, payload } = event;
|
|
36
|
+
const isForeignVisit = credentials.kind === "visit" && payload.visitId !== credentials.visitId;
|
|
37
|
+
if (name === "station_run.reported" && isForeignVisit)
|
|
38
|
+
return answerForbidden(response, "a visit token may only post for its own visit");
|
|
39
|
+
if (name === "station_run.reported")
|
|
40
|
+
return answerReported(response, { event, visits, blobs, reportFromWorker });
|
|
41
|
+
if (credentials.kind === "visit")
|
|
42
|
+
return answerForbidden(response, "a visit token may only post station_run.reported");
|
|
43
|
+
answerBadRequest(response, "the Studio test floor takes only station_run.reported at POST /events");
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function answerReported(response, { event, visits, blobs, reportFromWorker }) {
|
|
47
|
+
const parsed = reportedPayloadSchema.safeParse(event.payload);
|
|
48
|
+
if (!parsed.success)
|
|
49
|
+
return answerBadRequest(response, `station_run.reported: ${issuesOf(parsed.error).join("; ")}`);
|
|
50
|
+
const { visitId, report, worker } = parsed.data;
|
|
51
|
+
const floorVisit = visits.visitOf(visitId);
|
|
52
|
+
if (!floorVisit)
|
|
53
|
+
return answerNotFound(response, noVisit(visitId));
|
|
54
|
+
const refusal = reportRefusalAt(floorVisit, event.runId, parsed.data);
|
|
55
|
+
if (refusal)
|
|
56
|
+
return answerBadRequest(response, refusal);
|
|
57
|
+
const { station } = stationAt(floorVisit.run.line, floorVisit.visit.nodeId);
|
|
58
|
+
const answer = workerAnswerOf(station, report, blobs.storedPathOf);
|
|
59
|
+
if (typeof answer === "string")
|
|
60
|
+
return answerBadRequest(response, answer);
|
|
61
|
+
await reportFromWorker(visitId, answer, worker).then(() => answerJson(response, event, CREATED), answerRefusalWith(response, answerBadRequest));
|
|
62
|
+
}
|
|
63
|
+
function reportRefusalAt({ run: { line }, runId: visitRunId, visit }, runId, { visitId, report }) {
|
|
64
|
+
if (runId !== undefined && runId !== visitRunId)
|
|
65
|
+
return `visit "${visitId}" is in run "${visitRunId}", not "${runId}"`;
|
|
66
|
+
return reportRefusalOf({ line: line.body, nodeId: visit.nodeId, stationOf: (stationId) => line.stations.get(stationId), report });
|
|
67
|
+
}
|
|
68
|
+
function answerClaimed(response, claimed, dispatchChanged) {
|
|
69
|
+
const handedOutVisitIds = claimed.flatMap((event) => (event.name === "station_run.dispatch" ? [event.payload.visitId] : []));
|
|
70
|
+
if (handedOutVisitIds.length > 0)
|
|
71
|
+
dispatchChanged(handedOutVisitIds);
|
|
72
|
+
if (claimed.length === 0)
|
|
73
|
+
return answerNoContent(response);
|
|
74
|
+
answerJson(response, claimed);
|
|
75
|
+
}
|
|
76
|
+
function claimantOf(request) {
|
|
77
|
+
const workerHeader = request.headers["x-worker-id"];
|
|
78
|
+
return typeof workerHeader === "string" ? workerHeader : request.socket.remoteAddress;
|
|
79
|
+
}
|
|
80
|
+
//# sourceMappingURL=floor-event-routes.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { createRecordsSchema } from "@re-cinq/floor-pipeline/wire-schemas";
|
|
4
|
+
import { answerJson, answerNotFound, CREATED, noVisit } from "./floor-answers.js";
|
|
5
|
+
import { answerBody } from "./floor-request-body.js";
|
|
6
|
+
import { forOwnVisit } from "./floor-route.js";
|
|
7
|
+
import { visitFolderOf } from "./test-run-visit-files.js";
|
|
8
|
+
export const recordsRouteOf = (visits) => ({
|
|
9
|
+
method: "POST",
|
|
10
|
+
pattern: /^\/station-runs\/([^/]+)\/records$/,
|
|
11
|
+
visitsToo: true,
|
|
12
|
+
answer: (request, response, params, credentials) => forOwnVisit((own, floorVisitId) => answerBody(request, own, { schema: createRecordsSchema, invalidDetail: "invalid records" }, async ({ records }) => {
|
|
13
|
+
const known = visits.visitOf(floorVisitId);
|
|
14
|
+
if (!known)
|
|
15
|
+
return answerNotFound(own, noVisit(floorVisitId));
|
|
16
|
+
const folder = visitFolderOf(known.runFolder, known.visit.id);
|
|
17
|
+
await mkdir(folder, { recursive: true });
|
|
18
|
+
await appendFile(join(folder, "records.jsonl"), records.map((record) => `${JSON.stringify(record)}\n`).join(""));
|
|
19
|
+
answerJson(own, { items: records }, CREATED);
|
|
20
|
+
}))(request, response, params, credentials),
|
|
21
|
+
});
|
|
22
|
+
//# sourceMappingURL=floor-records-route.js.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { ZodError, ZodType } from "zod";
|
|
3
|
+
export interface BodyRule<Body> {
|
|
4
|
+
schema: ZodType<Body>;
|
|
5
|
+
invalidDetail: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function answerBody<Body>(request: IncomingMessage, response: ServerResponse, { schema, invalidDetail }: BodyRule<Body>, answer: (body: Body) => void | Promise<void>): Promise<void>;
|
|
8
|
+
export declare function issuesOf({ issues }: ZodError): string[];
|
|
9
|
+
export declare function bytesOf(request: IncomingMessage): Promise<Buffer>;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { answerBadRequest } from "./floor-answers.js";
|
|
2
|
+
const NOT_JSON = Symbol("not json");
|
|
3
|
+
export async function answerBody(request, response, { schema, invalidDetail }, answer) {
|
|
4
|
+
const text = (await bytesOf(request)).toString("utf8");
|
|
5
|
+
const payload = text === "" ? undefined : parseJson(text);
|
|
6
|
+
const parsed = schema.safeParse(payload);
|
|
7
|
+
if (payload === NOT_JSON)
|
|
8
|
+
return answerBadRequest(response, "Invalid request payload JSON format");
|
|
9
|
+
if (!parsed.success)
|
|
10
|
+
return answerBadRequest(response, invalidDetail, issuesOf(parsed.error));
|
|
11
|
+
await answer(parsed.data);
|
|
12
|
+
}
|
|
13
|
+
export function issuesOf({ issues }) {
|
|
14
|
+
return issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
|
|
15
|
+
}
|
|
16
|
+
function parseJson(text) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(text);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return NOT_JSON;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export async function bytesOf(request) {
|
|
25
|
+
const chunks = [];
|
|
26
|
+
for await (const chunk of request)
|
|
27
|
+
chunks.push(chunk);
|
|
28
|
+
return Buffer.concat(chunks);
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=floor-request-body.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { type Credentials } from "./floor-credentials.js";
|
|
3
|
+
export interface Route {
|
|
4
|
+
method: string;
|
|
5
|
+
pattern: RegExp;
|
|
6
|
+
visitsToo?: true;
|
|
7
|
+
answer(request: IncomingMessage, response: ServerResponse, params: string[], credentials: Credentials): void | Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
type VisitAnswer = (response: ServerResponse, floorVisitId: string) => void | Promise<void>;
|
|
10
|
+
export declare const forOwnVisit: (answer: VisitAnswer) => Route["answer"];
|
|
11
|
+
export declare function answerServed(routes: Route[], credentials: Credentials, request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { answerBadRequest, answerForbidden, answerNotFound } from "./floor-answers.js";
|
|
2
|
+
import { mayUse } from "./floor-credentials.js";
|
|
3
|
+
const SERVED_ROUTES = [
|
|
4
|
+
"POST /events/claim",
|
|
5
|
+
"POST /events/{id}/ack",
|
|
6
|
+
"POST /events/{id}/fail",
|
|
7
|
+
"POST /events",
|
|
8
|
+
"GET /station-runs/{visit}/brief",
|
|
9
|
+
"POST /station-runs/{visit}/records",
|
|
10
|
+
"GET /blobs/{hash}",
|
|
11
|
+
"POST /blobs",
|
|
12
|
+
"POST /assembly-lines/{id}/start",
|
|
13
|
+
];
|
|
14
|
+
export const forOwnVisit = (answer) => (request, response, [floorVisitId], credentials) => credentials.kind === "visit" && credentials.visitId !== floorVisitId
|
|
15
|
+
? answerForbidden(response, "a visit token may only touch its own visit")
|
|
16
|
+
: answer(response, floorVisitId);
|
|
17
|
+
export async function answerServed(routes, credentials, request, response) {
|
|
18
|
+
for (const route of routes) {
|
|
19
|
+
const match = matchOf(request, route);
|
|
20
|
+
if (match && !mayUse(credentials, route))
|
|
21
|
+
return answerForbidden(response, "Insufficient scope");
|
|
22
|
+
if (match)
|
|
23
|
+
return answerDecoded(match, response, (params) => route.answer(request, response, params, credentials));
|
|
24
|
+
}
|
|
25
|
+
return answerNotFound(response, `the Studio test floor serves only what a station uses: ${SERVED_ROUTES.join(", ")}`);
|
|
26
|
+
}
|
|
27
|
+
/* v8 ignore next -- Node's server always sets url; the type allows undefined. */
|
|
28
|
+
const matchOf = (request, { method, pattern }) => (request.method === method ? pattern.exec((request.url ?? "").replace(/\?.*/, "")) : null);
|
|
29
|
+
function answerDecoded(match, response, answer) {
|
|
30
|
+
const params = decodedParams(match);
|
|
31
|
+
return params ? answer(params) : answerBadRequest(response, "Invalid request url");
|
|
32
|
+
}
|
|
33
|
+
function decodedParams(match) {
|
|
34
|
+
try {
|
|
35
|
+
return match.slice(1).map(decodeURIComponent);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=floor-route.js.map
|