@re-cinq/floor-studio 0.9.0 → 0.11.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.
Files changed (122) hide show
  1. package/README.md +46 -4
  2. package/dist/backend/agent-run.d.ts +13 -0
  3. package/dist/backend/agent-run.js +32 -0
  4. package/dist/backend/collection-view.d.ts +2 -0
  5. package/dist/backend/collection-view.js +18 -8
  6. package/dist/backend/in-order.d.ts +1 -0
  7. package/dist/backend/in-order.js +10 -0
  8. package/dist/backend/last-tests.d.ts +10 -0
  9. package/dist/backend/last-tests.js +40 -0
  10. package/dist/backend/past-test-run-state.d.ts +2 -0
  11. package/dist/backend/past-test-run-state.js +19 -0
  12. package/dist/backend/past-test-runs.d.ts +2 -0
  13. package/dist/backend/past-test-runs.js +31 -0
  14. package/dist/backend/read-collection-view.d.ts +4 -0
  15. package/dist/backend/read-collection-view.js +19 -0
  16. package/dist/backend/read-test-line.d.ts +2 -0
  17. package/dist/backend/read-test-line.js +10 -0
  18. package/dist/backend/requests.d.ts +11 -1
  19. package/dist/backend/requests.js +4 -1
  20. package/dist/backend/run-cancel-request.d.ts +2 -1
  21. package/dist/backend/run-cancel-request.js +6 -3
  22. package/dist/backend/run-preview-request.d.ts +3 -2
  23. package/dist/backend/run-preview-request.js +6 -4
  24. package/dist/backend/run-start-request.js +2 -27
  25. package/dist/backend/start-studio.d.ts +4 -0
  26. package/dist/backend/start-studio.js +7 -13
  27. package/dist/backend/test-last-requests.d.ts +6 -0
  28. package/dist/backend/test-last-requests.js +6 -0
  29. package/dist/backend/test-list-requests.d.ts +9 -0
  30. package/dist/backend/test-list-requests.js +15 -0
  31. package/dist/backend/test-run-agent-visit.d.ts +13 -0
  32. package/dist/backend/test-run-agent-visit.js +73 -0
  33. package/dist/backend/test-run-folder.d.ts +5 -0
  34. package/dist/backend/test-run-folder.js +25 -0
  35. package/dist/backend/test-run-requests.d.ts +34 -0
  36. package/dist/backend/test-run-requests.js +112 -0
  37. package/dist/backend/test-run-session.d.ts +23 -0
  38. package/dist/backend/test-run-session.js +218 -0
  39. package/dist/backend/test-run-snapshot.d.ts +3 -0
  40. package/dist/backend/test-run-snapshot.js +25 -0
  41. package/dist/backend/test-run-supplied-files.d.ts +5 -0
  42. package/dist/backend/test-run-supplied-files.js +35 -0
  43. package/dist/backend/test-run-timeline.d.ts +6 -0
  44. package/dist/backend/test-run-timeline.js +13 -0
  45. package/dist/backend/test-run-visit-files.d.ts +8 -0
  46. package/dist/backend/test-run-visit-files.js +28 -0
  47. package/dist/cli.js +2 -2
  48. package/dist/folder-listing.d.ts +6 -0
  49. package/dist/folder-listing.js +2 -0
  50. package/dist/protocol.d.ts +179 -4
  51. package/dist/protocol.js +30 -4
  52. package/dist/run/result-line.d.ts +6 -0
  53. package/dist/run/result-line.js +18 -0
  54. package/dist/run/run-cost.d.ts +6 -0
  55. package/dist/run/run-cost.js +17 -0
  56. package/dist/run/run-outcome.d.ts +2 -0
  57. package/dist/run/run-outcome.js +4 -20
  58. package/dist/run/run-preview.d.ts +2 -0
  59. package/dist/run/run-preview.js +15 -6
  60. package/dist/run/run-process.d.ts +5 -3
  61. package/dist/run/run-process.js +13 -2
  62. package/dist/run/run-produces.d.ts +4 -0
  63. package/dist/run/run-produces.js +6 -1
  64. package/dist/run/run-records.d.ts +11 -0
  65. package/dist/run/run-result.js +15 -3
  66. package/dist/run/station-fixtures.d.ts +2 -1
  67. package/dist/run/station-fixtures.js +11 -0
  68. package/dist/shell/open-browser.d.ts +3 -3
  69. package/dist/shell/open-browser.js +7 -7
  70. package/dist/test-run/agent-report.d.ts +3 -0
  71. package/dist/test-run/agent-report.js +21 -0
  72. package/dist/test-run/brief.d.ts +6 -0
  73. package/dist/test-run/brief.js +25 -0
  74. package/dist/test-run/entered-value.d.ts +1 -0
  75. package/dist/test-run/entered-value.js +6 -0
  76. package/dist/test-run/event-answer.d.ts +13 -0
  77. package/dist/test-run/event-answer.js +13 -0
  78. package/dist/test-run/folder-names.d.ts +2 -0
  79. package/dist/test-run/folder-names.js +18 -0
  80. package/dist/test-run/next-transition.d.ts +3 -0
  81. package/dist/test-run/next-transition.js +10 -0
  82. package/dist/test-run/outcome-fields.d.ts +10 -0
  83. package/dist/test-run/outcome-fields.js +40 -0
  84. package/dist/test-run/past-listing.d.ts +3 -0
  85. package/dist/test-run/past-listing.js +5 -0
  86. package/dist/test-run/past-state.d.ts +5 -0
  87. package/dist/test-run/past-state.js +26 -0
  88. package/dist/test-run/run-bag.d.ts +5 -0
  89. package/dist/test-run/run-bag.js +12 -0
  90. package/dist/test-run/run-summary.d.ts +13 -0
  91. package/dist/test-run/run-summary.js +23 -0
  92. package/dist/test-run/stand-in-actions.d.ts +17 -0
  93. package/dist/test-run/stand-in-actions.js +26 -0
  94. package/dist/test-run/stand-in-report.d.ts +13 -0
  95. package/dist/test-run/stand-in-report.js +34 -0
  96. package/dist/test-run/start-blockers.d.ts +3 -0
  97. package/dist/test-run/start-blockers.js +21 -0
  98. package/dist/test-run/start-items.d.ts +12 -0
  99. package/dist/test-run/start-items.js +18 -0
  100. package/dist/test-run/test-line.d.ts +16 -0
  101. package/dist/test-run/test-line.js +24 -0
  102. package/dist/test-run/test-preview.d.ts +11 -0
  103. package/dist/test-run/test-preview.js +7 -0
  104. package/dist/test-run/test-run-state.d.ts +30 -0
  105. package/dist/test-run/test-run-state.js +2 -0
  106. package/dist/test-run/test-visit.d.ts +24 -0
  107. package/dist/test-run/test-visit.js +2 -0
  108. package/dist/test-run/timeline.d.ts +32 -0
  109. package/dist/test-run/timeline.js +4 -0
  110. package/dist/test-run/totals.d.ts +20 -0
  111. package/dist/test-run/totals.js +26 -0
  112. package/dist/test-run/visit-kind.d.ts +3 -0
  113. package/dist/test-run/visit-kind.js +10 -0
  114. package/dist/test-run/visit-record.d.ts +22 -0
  115. package/dist/test-run/visit-record.js +27 -0
  116. package/dist/view.d.ts +2 -0
  117. package/dist/web/assets/index-C5eUTmhR.css +1 -0
  118. package/dist/web/assets/index-mRcd501r.js +195 -0
  119. package/dist/web/index.html +2 -2
  120. package/package.json +5 -5
  121. package/dist/web/assets/index-ChU2BH_M.js +0 -195
  122. package/dist/web/assets/index-ChyDvQtL.css +0 -1
package/README.md CHANGED
@@ -125,22 +125,51 @@ The tab has a field for each need:
125
125
 
126
126
  Folder is where the run happens. Permission is `acceptEdits` or `bypass`, as in the pod.
127
127
 
128
- Preview shows the rendered prompt, the command and the blockers. A blocker is a required need with no value, a source path that does not exist, or a model the studio cannot run. A run with blockers is refused.
128
+ Preview shows the rendered prompt, the command and the blockers. A blocker is a required need with no value, a source path that does not exist, a model the studio cannot run, a picked folder that is not an absolute path, or a need or produce whose declared `path` would land outside the picked folder (`../outside/plan.md`; a name that only begins with two dots, such as `..notes/plan.md`, stays inside and is allowed). A run with blockers is refused before the folder is created, and nothing is saved.
129
129
 
130
130
  Run starts it and Cancel stops it. The transcript streams in as what the agent said, each tool it called (`› Read tests.json`), each refusal in red, and the run's turns, time and cost. Raw shows the lines as `claude` printed them.
131
131
 
132
132
  When the run ends the tab shows the agent's final answer under Answer. Its words are text, and any JSON object in it is laid out field by field, each list item a numbered block, with the `LORE_NODE_RESULT` line left out. Below it, each under its label:
133
133
 
134
134
  - the outcome, which is the agent's verdict read from its final result
135
- - the exit code, none when cancelled
135
+ - the exit code, none when cancelled or when the agent's program could not be started, in which case the reason is shown (`could not start claude: spawn claude ENOENT`)
136
136
  - each produce as found or missing. A produce `from: output` is found when the agent gave a final answer
137
137
  - the edge taken, which is also lit on the graph
138
138
  - the events raised next
139
139
 
140
- Two things match the pod. The run gets the agent's `config.env` over the studio's own environment, so `CLAUDE_CODE_DISABLE_CLAUDE_MDS` and the like apply. And `/workspace`, as the pod spells the working folder, is replaced by the picked folder in the prompt's text and in the `<name>_path` parameters.
140
+ Two things match the pod. The run gets the agent's `config.env` over the studio's own environment, so `CLAUDE_CODE_DISABLE_CLAUDE_MDS` and the like apply. And `/workspace`, as the pod spells the working folder, is replaced by the picked folder in the prompt's text and in the `<name>_path` parameters. The folder goes in as written: a folder whose own path has a `workspace` segment, a `$` or a `{name}` is not rewritten again.
141
141
 
142
142
  The need values are saved in `.floor-studio/fixtures/<line>/<node>.json` and each run in `.floor-studio/runs/<id>.json`, both in the collection folder. They are keyed by the line's name, so they do not move when a line folder moves into a group folder. The store folder gets a `.gitignore` of `*` on its first write. The run's id is kept in the page's fragment (`&run=<id>`), so after a reload the tab reads the transcript again with `run.read`, also for a run still going. Closing the studio cancels its runs.
143
143
 
144
+ ### Testing a whole line
145
+
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.
147
+
148
+ 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
+
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.
151
+
152
+ 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
+
154
+ The run is recorded in a new folder inside the workspace folder you give, named after the line and the start time in UTC:
155
+
156
+ ```
157
+ review-loop-20261127-141230/
158
+ definitions/ the collection as it was when the run started; the run reads only this copy
159
+ run.json line, start time, start items, status, ending, and time and cost per node and in all; rewritten on every change
160
+ timeline.jsonl run_started, visit_opened, visit_reported, event_received, run_settled, each with its time
161
+ visits/
162
+ 001-write-1/
163
+ inputs.json what the station received, written when the visit opens
164
+ prompt.md the rendered prompt (agent visits)
165
+ transcript.jsonl
166
+ work/ the agent's working folder
167
+ 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
+ visit.json mode (local or simulated), opened, reported, durationMs, the agent's own time and cost, outcome, next node
169
+ ```
170
+
171
+ `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
+
144
173
  ### The environment
145
174
 
146
175
  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.
@@ -161,6 +190,8 @@ await studio.close();
161
190
 
162
191
  `startStudio` resolves to `{ url, token, close }`. `url` has the real port and not the token. `close()` closes the sockets, the server and the watcher. `startStudio` rejects when `dir` is not a directory.
163
192
 
193
+ Three functions of the backend's source are what a caller that runs more than one station builds on. `readCollectionView(dir, hostKeys)` reads the view of any collection folder, not only the one the studio was started in. `previewOf(collection, request)` works out a node's run against a view it is handed, and `previewFor(context, request)` does the same against the studio's own folder. `startAgentRun(context, previewed, { node, folder })` runs the agent and resolves to `{ run, ended }`, where `ended` is a promise of the same ending the `run.ended` frame carries. `run.start` is `previewFor` followed by `startAgentRun`, so a station runs through one piece of code whoever starts it.
194
+
164
195
  ## The protocol
165
196
 
166
197
  Every frame is JSON in one WebSocket message. A request carries an `id` the client chooses and is answered by one `result` or `refused` frame with that `id`. The backend also pushes frames nobody asked for.
@@ -177,11 +208,22 @@ Every frame is JSON in one WebSocket message. A request carries an `id` the clie
177
208
  | client to backend | `{ id, type: "run.start", line, node, fixture, folder, permission }` | Start a run of an agent node. Refused when the preview has blockers. The result is `{ run }`, the run's id |
178
209
  | client to backend | `{ id, type: "run.cancel", run }` | Stop a running run. Refused when none runs under that id. The result is `{ cancelled: run }` |
179
210
  | 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
+ | 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, or a run folder that already exists. The result is `{ run, 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 |
214
+ | 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
+ | 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
+ | 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
+ | client to backend | `{ id, type: "test.read", run }` | The run's state. The result is the same `state` that `test.changed` carries |
218
+ | 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 |
219
+ | 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
+ | 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 }` |
180
221
  | backend to client | `{ id, type: "result", result }` | The answer to a request. For `collection.read`, `result` is the collection view |
181
222
  | 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 |
182
223
  | 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, or the run settled. `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 request naming a run the studio does not have is refused with `there is no test run <id>` |
183
225
  | backend to client | `{ type: "run.output", run, line: { stream, text } }` | One line a run wrote, on `stdout` or `stderr`, sent to every socket |
184
- | backend to client | `{ type: "run.ended", run, exitCode, outcome?, produced?, edge? }` | A run ended. `exitCode` is `null` when it was cancelled, and then the rest is absent. 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) |
226
+ | 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 |
185
227
 
186
228
  A new request type is one schema in `src/protocol.ts` and one handler in the table in `src/backend/requests.ts`.
187
229
 
@@ -0,0 +1,13 @@
1
+ import { type RunEnding } from "../run/run-records.js";
2
+ import type { StudioContext } from "./requests.js";
3
+ import type { PreviewedNode } from "./run-preview-request.js";
4
+ export interface AgentRun {
5
+ run: string;
6
+ ended: Promise<RunEnding>;
7
+ }
8
+ interface AgentRunTarget {
9
+ node: string;
10
+ folder: string;
11
+ }
12
+ export declare function startAgentRun(context: StudioContext, { preview, station, line }: PreviewedNode, { node, folder }: AgentRunTarget): Promise<AgentRun>;
13
+ export {};
@@ -0,0 +1,32 @@
1
+ // Runs one agent node in its folder, streams its output to every page and resolves with how it ended.
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 { blockerReasonOf } from "../run/run-preview.js";
7
+ import { runProcess } from "../run/run-process.js";
8
+ import { appendLine, endRecord } from "../run/run-records.js";
9
+ import { runResult } from "../run/run-result.js";
10
+ export async function startAgentRun(context, { preview, station, line }, { node, folder }) {
11
+ enforce(preview.blockers.length === 0, blockerReasonOf(preview));
12
+ await mkdir(folder, { recursive: true });
13
+ await prepareWorkspace(preview);
14
+ const run = randomUUID();
15
+ const record = { lines: [] };
16
+ context.runs.set(run, record);
17
+ await context.writeRun(run, record);
18
+ const running = runProcess({ command: preview.command, folder, env: { ...preview.env, ...context.runEnv } }, (outputLine) => {
19
+ appendLine(record, outputLine);
20
+ context.broadcast({ type: "run.output", run, line: outputLine });
21
+ });
22
+ record.process = running;
23
+ const ended = running.done.then(async (processEnding) => {
24
+ const ending = { ...processEnding, ...(await runResult({ exitCode: processEnding.exitCode, lines: record.lines, station, line, node, folder })) };
25
+ endRecord(record, ending);
26
+ await context.writeRun(run, record);
27
+ context.broadcast({ type: "run.ended", run, ...ending });
28
+ return ending;
29
+ });
30
+ return { run, ended };
31
+ }
32
+ //# sourceMappingURL=agent-run.js.map
@@ -1,3 +1,5 @@
1
1
  import { type CollectionFile } from "@re-cinq/floor-pipeline";
2
2
  import type { CollectionView } from "../view.js";
3
+ import { type ReadLine } from "./read-line.js";
3
4
  export declare function collectionView(files: readonly CollectionFile[], hostKeys: readonly string[], groups?: readonly string[]): CollectionView;
5
+ export declare function readLinesOf(files: readonly CollectionFile[], hostKeys: readonly string[], groups: readonly string[]): ReadLine[];
@@ -10,17 +10,27 @@ const AS_WRITTEN = new Proxy({}, { get: (...given) => `\${${String(given[1])}}`
10
10
  /** Nothing is shipped: the studio shows the collection on its own. */
11
11
  const NOTHING_SHIPPED = { pipelines: [], agents: new Map() };
12
12
  export function collectionView(files, hostKeys, groups = []) {
13
- const readFiles = withoutReplacedFiles(files, groups);
14
- const overlay = collectionOverlay({ files: readFiles, shipped: NOTHING_SHIPPED, env: AS_WRITTEN, hostKeys, groups });
15
- const lineFiles = lineLayoutOf(readFiles).read;
16
- const reads = lineFiles.map((file) => attempt(file.path, () => readLine(file, file.folder, promptsOf(overlay.agents))));
17
- const read = reads.flatMap((result) => ("made" in result ? [result.made] : []));
13
+ const { readFiles, overlay, lineFiles, reads } = readingOf(files, hostKeys, groups);
14
+ const read = madeOf(reads);
18
15
  const surroundings = { lines: read.map(({ id, body }) => ({ id, body })), agents: overlay.agents, agentFiles: agentFilesByName(readFiles), files: readFiles };
19
16
  const views = read.map((line) => attempt(line.file, () => lineViewOf(line, surroundings)));
20
- const lines = views.flatMap((result) => ("made" in result ? [result.made] : []));
17
+ const lines = madeOf(views);
21
18
  const refused = refusedOf(overlay, { lineFiles, failures: [...reads, ...views] });
22
19
  return { lines, agents: agentViews(overlay.agents, surroundings.agentFiles, lines), refused, counts: countsOf(lines, overlay, refused) };
23
20
  }
21
+ export function readLinesOf(files, hostKeys, groups) {
22
+ return madeOf(readingOf(files, hostKeys, groups).reads);
23
+ }
24
+ function readingOf(files, hostKeys, groups) {
25
+ const readFiles = withoutReplacedFiles(files, groups);
26
+ const overlay = collectionOverlay({ files: readFiles, shipped: NOTHING_SHIPPED, env: AS_WRITTEN, hostKeys, groups });
27
+ const lineFiles = lineLayoutOf(readFiles).read;
28
+ const reads = lineFiles.map((file) => attempt(file.path, () => readLine(file, file.folder, promptsOf(overlay.agents))));
29
+ return { readFiles, overlay, lineFiles, reads };
30
+ }
31
+ function madeOf(results) {
32
+ return results.flatMap((result) => ("made" in result ? [result.made] : []));
33
+ }
24
34
  function promptsOf(agents) {
25
35
  return new Map([...agents].map(([name, agent]) => [name, agent.settings.prompt]));
26
36
  }
@@ -56,9 +66,9 @@ function extraOf(agentName, line, files) {
56
66
  return text === undefined ? {} : { extra: { file, text, version: textVersion(text) } };
57
67
  }
58
68
  function stationFacts(station, { node, line, needContext }) {
59
- const { kind, description, agentDefinition, outcomes = [], needs = [], produces = [] } = station ?? {};
69
+ const { kind, description, agentDefinition, resultRequired, outcomes = [], needs = [], produces = [] } = station ?? {};
60
70
  return {
61
- ...present({ kind, description, agentDefinition }),
71
+ ...present({ kind, description, agentDefinition, resultRequired }),
62
72
  outcomes,
63
73
  needs: needs.map((need) => ({ ...need, coverage: needCoverage(node, need, needContext) })),
64
74
  produces: produces.map((produce) => ({ ...produce, readBy: readersOf(produce.name, node, line) })),
@@ -0,0 +1 @@
1
+ export declare function inOrder(): <T>(task: () => Promise<T>) => Promise<T>;
@@ -0,0 +1,10 @@
1
+ // A queue that runs async tasks one at a time, in the order they were handed in.
2
+ export function inOrder() {
3
+ let tail = Promise.resolve();
4
+ return (task) => {
5
+ const result = tail.then(task);
6
+ tail = result.catch(() => undefined);
7
+ return result;
8
+ };
9
+ }
10
+ //# sourceMappingURL=in-order.js.map
@@ -0,0 +1,10 @@
1
+ export interface LastTest {
2
+ workspace: string;
3
+ entered: Record<string, string>;
4
+ }
5
+ export declare function readLastTest(collectionDir: string, line: string): Promise<LastTest | null>;
6
+ export declare function rememberedWorkspaces(collectionDir: string): Promise<{
7
+ line: string;
8
+ workspace: string;
9
+ }[]>;
10
+ export declare function rememberLastTest(collectionDir: string, line: string, lastTest: LastTest): Promise<void>;
@@ -0,0 +1,40 @@
1
+ // The values each line was last tested with, kept per collection in the user's config folder.
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ export async function readLastTest(collectionDir, line) {
6
+ const remembered = (await readLastTests())[collectionDir]?.[line];
7
+ return remembered ? { workspace: remembered.workspace, entered: remembered.entered } : null;
8
+ }
9
+ export async function rememberedWorkspaces(collectionDir) {
10
+ const lines = (await readLastTests())[collectionDir] ?? {};
11
+ return Object.entries(lines).flatMap(([line, remembered]) => (remembered?.workspaces ?? []).map((workspace) => ({ line, workspace })));
12
+ }
13
+ export async function rememberLastTest(collectionDir, line, lastTest) {
14
+ const file = lastTestsFile();
15
+ await mkdir(dirname(file), { recursive: true });
16
+ await writeFile(file, JSON.stringify(withLastTest(await readLastTests(), collectionDir, line, lastTest)));
17
+ }
18
+ function withLastTest(all, collectionDir, line, lastTest) {
19
+ const previous = all[collectionDir]?.[line];
20
+ const used = previous?.workspaces ?? [];
21
+ const workspaces = used.includes(lastTest.workspace) ? used : [...used, lastTest.workspace];
22
+ return { ...all, [collectionDir]: { ...all[collectionDir], [line]: { ...lastTest, workspaces } } };
23
+ }
24
+ async function readLastTests() {
25
+ const raw = await readFile(lastTestsFile(), "utf8").catch(() => undefined);
26
+ return raw ? parseLastTests(raw) : {};
27
+ }
28
+ function parseLastTests(raw) {
29
+ try {
30
+ return JSON.parse(raw) ?? {};
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
36
+ function lastTestsFile() {
37
+ const configFolder = process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
38
+ return join(configFolder, "floor-studio", "last-tests.json");
39
+ }
40
+ //# sourceMappingURL=last-tests.js.map
@@ -0,0 +1,2 @@
1
+ import type { TestRunState } from "../test-run/test-run-state.js";
2
+ export declare function readPastRun(collectionDir: string, folder: string): Promise<TestRunState | undefined>;
@@ -0,0 +1,19 @@
1
+ // Reads a past test run's state back from its folder: run.json, timeline.jsonl and visits/*/visit.json.
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { pastStateOf } from "../test-run/past-state.js";
5
+ import { pastTestRuns } from "./past-test-runs.js";
6
+ import { RUN_FILE, TIMELINE_FILE } from "./test-run-timeline.js";
7
+ import { visitFolderOf } from "./test-run-visit-files.js";
8
+ export async function readPastRun(collectionDir, folder) {
9
+ const known = (await pastTestRuns(collectionDir)).some((listing) => listing.folder === folder);
10
+ return known ? stateIn(folder) : undefined;
11
+ }
12
+ async function stateIn(folder) {
13
+ const summary = JSON.parse(await readFile(join(folder, RUN_FILE), "utf8"));
14
+ const timeline = (await readFile(join(folder, TIMELINE_FILE), "utf8")).split("\n").filter(Boolean).map((line) => JSON.parse(line));
15
+ const ids = await readdir(join(folder, "visits")).catch(() => []);
16
+ const records = await Promise.all(ids.map(async (id) => JSON.parse(await readFile(join(visitFolderOf(folder, id), "visit.json"), "utf8").catch(() => "null"))));
17
+ return pastStateOf(folder, summary, timeline, Object.fromEntries(records.filter((record) => record !== null).map((record) => [record.id, record])));
18
+ }
19
+ //# sourceMappingURL=past-test-run-state.js.map
@@ -0,0 +1,2 @@
1
+ import type { TestRunListing } from "../test-run/test-run-state.js";
2
+ export declare function pastTestRuns(collectionDir: string): Promise<TestRunListing[]>;
@@ -0,0 +1,31 @@
1
+ // The runs earlier studios left in the workspaces a collection's lines were tested in.
2
+ import { readdir, readFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { pastListingOf } from "../test-run/past-listing.js";
5
+ import { rememberedWorkspaces } from "./last-tests.js";
6
+ import { RUN_FILE } from "./test-run-timeline.js";
7
+ export async function pastTestRuns(collectionDir) {
8
+ const remembered = await rememberedWorkspaces(collectionDir);
9
+ const found = await Promise.all(remembered.map(({ line, workspace }) => runsOf(line, workspace)));
10
+ return found.flat();
11
+ }
12
+ async function runsOf(line, workspace) {
13
+ const entries = await readdir(workspace, { withFileTypes: true }).catch(() => []);
14
+ const folders = entries.filter((entry) => entry.isDirectory() && entry.name.startsWith(`${line}-`)).map((entry) => join(workspace, entry.name));
15
+ const listings = await Promise.all(folders.map(listingIn));
16
+ return listings.filter((listing) => listing !== null).filter((listing) => listing.line === line);
17
+ }
18
+ async function listingIn(folder) {
19
+ const raw = await readFile(join(folder, RUN_FILE), "utf8").catch(() => undefined);
20
+ const summary = raw === undefined ? null : parseSummary(raw);
21
+ return summary && pastListingOf(folder, summary);
22
+ }
23
+ function parseSummary(raw) {
24
+ try {
25
+ return JSON.parse(raw);
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ //# sourceMappingURL=past-test-runs.js.map
@@ -0,0 +1,4 @@
1
+ import type { CollectionView } from "../view.js";
2
+ import type { ReadLine } from "./read-line.js";
3
+ export declare function readCollectionView(dir: string, hostKeys: readonly string[]): Promise<CollectionView>;
4
+ export declare function readLinesIn(dir: string): Promise<ReadLine[]>;
@@ -0,0 +1,19 @@
1
+ // How a collection folder becomes a CollectionView: its agent files, its settings, its skills and the host keys from both the caller and the settings.
2
+ import { basename, resolve } from "node:path";
3
+ import { collectionFilesIn, collectionSettingsIn } from "@re-cinq/floor-pipeline";
4
+ import { collectionView, readLinesOf } from "./collection-view.js";
5
+ import { environmentOf } from "./environment-usage.js";
6
+ import { isSkillPath, skillNamesIn } from "./skill-names.js";
7
+ export async function readCollectionView(dir, hostKeys) {
8
+ const { files, settings } = await gatheredFrom(dir);
9
+ return { ...collectionView(files, [...hostKeys, ...settings.hostKeys], settings.groups), folder: basename(resolve(dir)), skills: await skillNamesIn(dir), environment: environmentOf(files) };
10
+ }
11
+ export async function readLinesIn(dir) {
12
+ const { files, settings } = await gatheredFrom(dir);
13
+ return readLinesOf(files, settings.hostKeys, settings.groups);
14
+ }
15
+ async function gatheredFrom(dir) {
16
+ const files = (await collectionFilesIn(dir)).filter((file) => !isSkillPath(file.path));
17
+ return { files, settings: await collectionSettingsIn(dir) };
18
+ }
19
+ //# sourceMappingURL=read-collection-view.js.map
@@ -0,0 +1,2 @@
1
+ import type { TestLine } from "../test-run/test-line.js";
2
+ export declare function readTestLine(dir: string, lineId: string): Promise<TestLine>;
@@ -0,0 +1,10 @@
1
+ // One line of a collection folder as the local test run's rules read it.
2
+ import { enforce } from "@re-cinq/floor-assembly-lines";
3
+ import { readLinesIn } from "./read-collection-view.js";
4
+ export async function readTestLine(dir, lineId) {
5
+ const lines = await readLinesIn(dir);
6
+ const line = lines.find(({ id }) => id === lineId);
7
+ enforce(line, `the collection has no line ${lineId}`);
8
+ return { id: line.id, body: line.body, stations: line.bodies };
9
+ }
10
+ //# sourceMappingURL=read-test-line.js.map
@@ -6,6 +6,10 @@ import { type RunPreviewRequest } from "./run-preview-request.js";
6
6
  import { type RunCancelRequest } from "./run-cancel-request.js";
7
7
  import { type RunStartRequest } from "./run-start-request.js";
8
8
  import { type RunReadRequest } from "./run-read-request.js";
9
+ import { type TestListRequest } from "./test-list-requests.js";
10
+ import { type TestLastRequest } from "./test-last-requests.js";
11
+ import { type FolderListRequest, type TestEventRequest, type FolderOpenRequest, type TestCancelRequest, type TestPreviewRequest, type TestReadRequest, type TestReportRequest, type TestStartRequest } from "./test-run-requests.js";
12
+ import type { TestRunSession } from "./test-run-session.js";
9
13
  import type { RunRecord, RunTranscript } from "../run/run-records.js";
10
14
  export interface StudioContext {
11
15
  readCollection(): Promise<CollectionView>;
@@ -23,10 +27,16 @@ export interface StudioContext {
23
27
  writeRun(run: string, transcript: RunTranscript): Promise<void>;
24
28
  /** The record of each run started by `run.start`, by run id; kept after the run ends. */
25
29
  runs: Map<string, RunRecord>;
30
+ /** The folder the studio serves: a test run snapshots it. */
31
+ collectionDir: string;
32
+ /** Each local test run started by `test.start`, by run id; kept after the run ends. */
33
+ testRuns: Map<string, TestRunSession>;
26
34
  /** Environment laid over the studio's own for each started process. */
27
35
  runEnv?: Record<string, string>;
28
36
  /** Sends a frame to every open socket. */
29
37
  broadcast(frame: ServerFrame): void;
38
+ /** Opens a folder in the desktop's file manager. */
39
+ openFolder(path: string): void;
30
40
  }
31
41
  export interface Handler<Asked extends Request> {
32
42
  type: Asked["type"];
@@ -42,6 +52,6 @@ type CollectionRead = Extract<Request, {
42
52
  type: "collection.read";
43
53
  }>;
44
54
  /** 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>)[];
55
+ export declare const HANDLERS: (Handler<CollectionRead> | Handler<AgentWrite> | Handler<ExtraWrite> | Handler<FixtureWrite> | Handler<FixtureRead> | Handler<RunPreviewRequest> | Handler<RunStartRequest> | Handler<RunCancelRequest> | Handler<RunReadRequest> | Handler<TestStartRequest> | Handler<TestReportRequest> | Handler<TestCancelRequest> | Handler<TestReadRequest> | Handler<TestPreviewRequest> | Handler<FolderOpenRequest> | Handler<FolderListRequest> | Handler<TestEventRequest> | Handler<TestLastRequest> | Handler<TestListRequest>)[];
46
56
  export declare function answerFrame(text: string, context: StudioContext): Promise<ServerFrame>;
47
57
  export {};
@@ -7,6 +7,9 @@ import { runPreviewHandler } from "./run-preview-request.js";
7
7
  import { runCancelHandler } from "./run-cancel-request.js";
8
8
  import { runStartHandler } from "./run-start-request.js";
9
9
  import { runReadHandler } from "./run-read-request.js";
10
+ import { testListHandler } from "./test-list-requests.js";
11
+ import { testLastHandler } from "./test-last-requests.js";
12
+ import { folderListHandler, testEventHandler, folderOpenHandler, testCancelHandler, testPreviewHandler, testReadHandler, testReportHandler, testStartHandler } from "./test-run-requests.js";
10
13
  function agentFileOf({ lines }, lineId, agentName) {
11
14
  const nodes = lines.find(({ id }) => id === lineId)?.nodes ?? [];
12
15
  const agents = nodes.map((node) => node.agent);
@@ -37,7 +40,7 @@ const extraWrite = {
37
40
  };
38
41
  const collectionRead = { type: "collection.read", handle: (context) => context.readCollection() };
39
42
  /** 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];
43
+ export const HANDLERS = [collectionRead, agentWrite, extraWrite, fixtureWrite, fixtureRead, runPreviewHandler, runStartHandler, runCancelHandler, runReadHandler, testStartHandler, testReportHandler, testCancelHandler, testReadHandler, testPreviewHandler, folderOpenHandler, folderListHandler, testEventHandler, testLastHandler, testListHandler];
41
44
  export async function answerFrame(text, context) {
42
45
  const held = parsedJson(text);
43
46
  const id = idOf(held);
@@ -1,6 +1,7 @@
1
1
  import type { Request } from "../protocol.js";
2
- import type { Handler } from "./requests.js";
2
+ import type { Handler, StudioContext } from "./requests.js";
3
3
  export type RunCancelRequest = Extract<Request, {
4
4
  type: "run.cancel";
5
5
  }>;
6
6
  export declare const runCancelHandler: Handler<RunCancelRequest>;
7
+ export declare function cancelRun(runs: StudioContext["runs"], run: string): boolean;
@@ -3,10 +3,13 @@ import { enforce } from "@re-cinq/floor-assembly-lines";
3
3
  export const runCancelHandler = {
4
4
  type: "run.cancel",
5
5
  handle: async ({ runs }, { run }) => {
6
- const running = runs.get(run)?.process;
7
- enforce(running, `no running run ${run}`);
8
- running.cancel();
6
+ enforce(cancelRun(runs, run), `no running run ${run}`);
9
7
  return { cancelled: run };
10
8
  },
11
9
  };
10
+ export function cancelRun(runs, run) {
11
+ const running = runs.get(run)?.process;
12
+ running?.cancel();
13
+ return running !== undefined;
14
+ }
12
15
  //# sourceMappingURL=run-cancel-request.js.map
@@ -1,6 +1,6 @@
1
1
  import type { Request } from "../protocol.js";
2
2
  import type { StationBody } from "@re-cinq/floor-contracts";
3
- import type { LineView } from "../view.js";
3
+ import type { CollectionView, LineView } from "../view.js";
4
4
  import { type RunPreview } from "../run/run-preview.js";
5
5
  import type { Handler, StudioContext } from "./requests.js";
6
6
  export type RunPreviewRequest = Extract<Request, {
@@ -12,4 +12,5 @@ export interface PreviewedNode {
12
12
  station: StationBody;
13
13
  line: LineView;
14
14
  }
15
- export declare function previewFor(context: StudioContext, { line, node, fixture, folder, permission }: Omit<RunPreviewRequest, "id" | "type">): Promise<PreviewedNode>;
15
+ export declare function previewFor(context: StudioContext, request: Omit<RunPreviewRequest, "id" | "type">): Promise<PreviewedNode>;
16
+ export declare function previewOf(collection: CollectionView, { line, node, fixture, folder, permission }: Omit<RunPreviewRequest, "id" | "type">): Promise<PreviewedNode>;
@@ -8,12 +8,14 @@ export const runPreviewHandler = {
8
8
  type: "run.preview",
9
9
  handle: async (context, request) => (await previewFor(context, request)).preview,
10
10
  };
11
- export async function previewFor(context, { line, node, fixture, folder, permission }) {
12
- const collection = await context.readCollection();
11
+ export async function previewFor(context, request) {
12
+ return previewOf(await context.readCollection(), request);
13
+ }
14
+ export async function previewOf(collection, { line, node, fixture, folder, permission }) {
13
15
  const found = nodeOf(collection, line, node);
14
16
  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 { kind, outcomes, needs, produces, agentDefinition, resultRequired, agent } = found;
18
+ const station = { kind, outcomes, needs, produces, agentDefinition, resultRequired };
17
19
  const preview = runPreview({ station, prompt: promptOf(found).trimEnd(), settings: (agent?.settings ?? {}), fixture, folder, permission });
18
20
  const absent = await absentSourceBlockers([...preview.copies, ...preview.links]);
19
21
  return { preview: { ...preview, blockers: [...preview.blockers, ...absent] }, station, line: collection.lines.find(({ id }) => id === line) };
@@ -1,34 +1,9 @@
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";
1
+ import { startAgentRun } from "./agent-run.js";
9
2
  import { previewFor } from "./run-preview-request.js";
10
3
  export const runStartHandler = {
11
4
  type: "run.start",
12
5
  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
- });
6
+ const { run } = await startAgentRun(context, await previewFor(context, request), request);
32
7
  return { run };
33
8
  },
34
9
  };
@@ -7,6 +7,10 @@ export interface StudioOptions {
7
7
  origins?: readonly string[];
8
8
  /** Environment laid over the studio's own for each process a run starts. */
9
9
  runEnv?: Record<string, string>;
10
+ /** Opens a run folder; the desktop opens it when none is given. */
11
+ openFolder?: (path: string) => void;
12
+ /** How long the folder stays quiet before the collection is pushed again; the watcher's own default when none is given. */
13
+ watchDebounceMs?: number;
10
14
  }
11
15
  export interface Studio {
12
16
  /** `ws://127.0.0.1:<port>`: the real port, the token not in it. */
@@ -2,19 +2,18 @@
2
2
  import { randomBytes } from "node:crypto";
3
3
  import { readFile, stat, writeFile } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
- import { basename, join, resolve } from "node:path";
5
+ import { basename, join } from "node:path";
6
6
  import { enforce } from "@re-cinq/floor-assembly-lines";
7
- import { collectionFilesIn, collectionSettingsIn, hostKeysIn, readAgentFile } from "@re-cinq/floor-pipeline";
7
+ import { hostKeysIn, readAgentFile } from "@re-cinq/floor-pipeline";
8
8
  import { WebSocket, WebSocketServer } from "ws";
9
9
  import { PROTOCOL_VERSION } from "../protocol.js";
10
- import { collectionView } from "./collection-view.js";
11
10
  import { upgradeRefusal } from "./guard.js";
12
11
  import { editedAgentText, textVersion, withOneNewline } from "./agent-file-text.js";
13
- import { environmentOf } from "./environment-usage.js";
12
+ import { openOnDesktop } from "../shell/open-browser.js";
14
13
  import { fixtureFilesIn } from "./fixture-files.js";
15
14
  import { runFilesIn } from "./run-files.js";
16
15
  import { answerFrame } from "./requests.js";
17
- import { isSkillPath, skillNamesIn } from "./skill-names.js";
16
+ import { readCollectionView } from "./read-collection-view.js";
18
17
  import { watchCollection } from "./watcher.js";
19
18
  /** Never `0.0.0.0`: the backend writes files and starts processes. */
20
19
  const LOOPBACK = "127.0.0.1";
@@ -28,14 +27,14 @@ export async function startStudio(options) {
28
27
  const token = randomBytes(TOKEN_BYTES).toString("hex");
29
28
  const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
30
29
  const allHostKeys = async () => [...hostKeys, ...(await hostKeysIn(dir))];
31
- const readCollection = () => collectionRead(dir, hostKeys);
30
+ const readCollection = () => readCollectionView(dir, hostKeys);
32
31
  const writeAgent = async (file, edit) => {
33
32
  const path = join(dir, file);
34
33
  const text = editedAgentText(file, await readFile(path, "utf8"), edit);
35
34
  readAgentFile(basename(file, ".md"), text, await allHostKeys());
36
35
  await writeFile(path, text);
37
36
  };
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)) };
37
+ const context = { readCollection, writeAgent, writeExtra: (file, edit) => writeExtraFile(join(dir, file), edit), ...fixtureFilesIn(dir), ...runFilesIn(dir), runs: new Map(), collectionDir: dir, testRuns: new Map(), runEnv: options.runEnv, broadcast: (frame) => sockets.clients.forEach((socket) => send(socket, frame)), openFolder: options.openFolder ?? openOnDesktop };
39
38
  const server = createServer(refuseHttp);
40
39
  server.on("upgrade", (request, socket, head) => {
41
40
  const refusal = upgradeRefusal({ url: request.url, origin: request.headers.origin, token, origins });
@@ -44,7 +43,7 @@ export async function startStudio(options) {
44
43
  sockets.handleUpgrade(request, socket, head, (opened) => sockets.emit("connection", opened, request));
45
44
  });
46
45
  sockets.on("connection", (socket) => serve(socket, context));
47
- const watcher = watchCollection(dir, () => void pushCollection(sockets, readCollection));
46
+ const watcher = watchCollection(dir, () => void pushCollection(sockets, readCollection), options.watchDebounceMs);
48
47
  await new Promise((resolve) => server.listen(options.port, LOOPBACK, resolve));
49
48
  return {
50
49
  url: `ws://${LOOPBACK}:${server.address().port}`,
@@ -53,11 +52,6 @@ export async function startStudio(options) {
53
52
  close: () => closed({ watcher, sockets, server, runs: context.runs }),
54
53
  };
55
54
  }
56
- async function collectionRead(dir, hostKeys) {
57
- const files = (await collectionFilesIn(dir)).filter((file) => !isSkillPath(file.path));
58
- const settings = await collectionSettingsIn(dir);
59
- return { ...collectionView(files, [...hostKeys, ...settings.hostKeys], settings.groups), folder: basename(resolve(dir)), skills: await skillNamesIn(dir), environment: environmentOf(files) };
60
- }
61
55
  async function writeExtraFile(path, { text, version }) {
62
56
  enforce(version === textVersion(await readFile(path, "utf8")), `${basename(path)} changed on disk since it was read`);
63
57
  await writeFile(path, withOneNewline(text));
@@ -0,0 +1,6 @@
1
+ import type { Request } from "../protocol.js";
2
+ import type { Handler } from "./requests.js";
3
+ export type TestLastRequest = Extract<Request, {
4
+ type: "test.last";
5
+ }>;
6
+ export declare const testLastHandler: Handler<TestLastRequest>;