@beatos/bridge-runner 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gordon Web Studio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,404 @@
1
- # Temporary Holding Version
1
+ # @beatos/bridge-runner
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The BeatOS Bridge runner. A small program that runs on your own computer. It
4
+ takes the BeatOS tasks you delegate to **Local AI** and works them with Claude
5
+ Code. Every run, question and approval shows up in BeatOS Bridge.
6
+
7
+ It only connects out to beatos.app. It opens no port and never opens your
8
+ computer to the internet. Nothing is merged, deployed or sent without your yes.
9
+
10
+ ## Contents
11
+
12
+ - [What you need](#what-you-need)
13
+ - [Quick start](#quick-start)
14
+ - [Connect this computer (pair)](#connect-this-computer-pair)
15
+ - [Start and stop](#start-and-stop)
16
+ - [Pause, resume, stop a run, revoke, remove](#pause-resume-stop-a-run-revoke-remove)
17
+ - [Commands and flags](#commands-and-flags)
18
+ - [Configuration (config.json)](#configuration-configjson)
19
+ - [Protect your private folders (protectPaths)](#protect-your-private-folders-protectpaths)
20
+ - [Projects: where the agent works](#projects-where-the-agent-works)
21
+ - [The key](#the-key)
22
+ - [Safety model](#safety-model)
23
+ - [Files and logs](#files-and-logs)
24
+ - [Update](#update)
25
+ - [Uninstall](#uninstall)
26
+ - [Troubleshooting](#troubleshooting)
27
+ - [Support](#support)
28
+
29
+ ## What you need
30
+
31
+ - **Node.js 22.6 or newer.** Check it:
32
+
33
+ ```bash
34
+ node --version
35
+ ```
36
+
37
+ It must say `v22.6.0` or higher. Get Node.js at https://nodejs.org.
38
+ - **Claude Code**, installed and signed in on this computer. See
39
+ https://code.claude.com/docs/en/setup. Check it:
40
+
41
+ ```bash
42
+ claude --version
43
+ ```
44
+
45
+ - **A BeatOS account with Bridge.**
46
+ - **git**, only if the agent works in a git repo (see [Projects](#projects-where-the-agent-works)).
47
+ **GitHub CLI (`gh`)**, signed in, only if you want the runner to open pull requests.
48
+
49
+ Operating system notes:
50
+
51
+ - **Windows:** use PowerShell or Windows Terminal. The runner finds
52
+ `claude.exe` by itself (npm global folder or nvm). If it cannot, set
53
+ `BEATOS_RUNNER_CLAUDE` to the full path of `claude.exe`. The key file is
54
+ limited to your Windows user with `icacls` (best effort).
55
+ - **macOS:** use Terminal. The runner calls `claude` from your PATH.
56
+ - **Linux:** use any terminal. The runner calls `claude` from your PATH.
57
+ - On macOS and Linux the key file gets permission 600 (only you can read it).
58
+
59
+ ## Quick start
60
+
61
+ 1. In BeatOS, open **Bridge**, then **Runners**. Tap **Get a code**.
62
+ 2. In a terminal on this computer:
63
+
64
+ ```bash
65
+ npx @beatos/bridge-runner pair K7F-29Q
66
+ npx @beatos/bridge-runner
67
+ ```
68
+
69
+ 3. Keep the terminal open. Delegate a task to **Local AI** in BeatOS.
70
+
71
+ ## Connect this computer (pair)
72
+
73
+ 1. In BeatOS, open **Bridge**, then **Runners**. Tap **Get a code** on the
74
+ Connect a computer card. The code (like `K7F-29Q`) works once, for 10
75
+ minutes.
76
+ 2. Open a terminal. Any folder works. Your home folder is a good choice.
77
+ 3. Run, with your code:
78
+
79
+ ```bash
80
+ npx @beatos/bridge-runner pair K7F-29Q
81
+ ```
82
+
83
+ The first time, npx asks to install the package. Type `y` and press Enter.
84
+
85
+ To give this computer its own name, add `--name`:
86
+
87
+ ```bash
88
+ npx @beatos/bridge-runner pair K7F-29Q --name "Laptop"
89
+ ```
90
+
91
+ Without `--name`, BeatOS names the computer `Local-AI-` plus 4 letters and
92
+ numbers (like `Local-AI-7F3A`), so two computers never look the same. Each
93
+ computer gets its own id and its own key.
94
+
95
+ The runner trades the code for its key, saves it in
96
+ `~/.beatos-runner/runner.key` and writes `~/.beatos-runner/config.json`. The
97
+ card in Bridge then shows "Connected:" and the name.
98
+
99
+ ## Start and stop
100
+
101
+ Start:
102
+
103
+ ```bash
104
+ npx @beatos/bridge-runner
105
+ ```
106
+
107
+ Keep the terminal open. The computer shows as online in Bridge within a
108
+ minute. Only one runner can run at a time on a computer.
109
+
110
+ Stop: press **Ctrl+C** in that terminal. The runner waits up to 15 seconds for
111
+ a running Claude session to save its state. A task that was cut continues in
112
+ the same Claude session the next time you start the runner.
113
+
114
+ Check once and exit (good for testing):
115
+
116
+ ```bash
117
+ npx @beatos/bridge-runner --once
118
+ ```
119
+
120
+ ## Pause, resume, stop a run, revoke, remove
121
+
122
+ You do all of this in BeatOS, on the Bridge screens. The runner follows within
123
+ `pollSeconds` (30 seconds by default).
124
+
125
+ | You want to | Where in BeatOS | What happens |
126
+ | --- | --- | --- |
127
+ | Stop new work on this computer | Runners, the computer's card, **Pause** | It stays online but takes no new tasks. |
128
+ | Take work again | Runners, the card, **Resume** | It takes new tasks again. |
129
+ | Pause one run | The run's page, **Pause** | The Claude session stops. The run keeps its session. |
130
+ | Continue that run | The run's page, **Resume** | The SAME Claude session continues. |
131
+ | Stop one run for good | The run's page, **Stop** | The session ends. The task goes back to you. |
132
+ | Cut this computer off | Runners, the card, **Revoke key** | The key is deleted. The runner stops at once and cannot come back. |
133
+ | Hide a revoked computer | Runners, the revoked card, **Remove** | It leaves the list. Its runs keep its name in their history. |
134
+
135
+ After a revoke, connect the computer again with a new code.
136
+
137
+ ## Commands and flags
138
+
139
+ This is the same as `npx @beatos/bridge-runner --help`:
140
+
141
+ ```text
142
+ Usage:
143
+ npx @beatos/bridge-runner pair <CODE> connect this computer (code from BeatOS)
144
+ --name "Laptop" name for this computer (optional)
145
+ --url https://beatos.app another BeatOS server (optional)
146
+ npx @beatos/bridge-runner start (keep the terminal open)
147
+ npx @beatos/bridge-runner --once one check, then exit
148
+ npx @beatos/bridge-runner --help, -h this help
149
+ npx @beatos/bridge-runner --version, -v the version
150
+ ```
151
+
152
+ Environment variables:
153
+
154
+ | Variable | Meaning |
155
+ | --- | --- |
156
+ | `BEATOS_RUNNER_HOME` | The runner folder. Default: `~/.beatos-runner`. |
157
+ | `BEATOS_RUNNER_CONFIG` | The config file. Default: `config.json` in the runner folder. |
158
+ | `BEATOS_RUNNER_KEY` | The key. When set, it wins over `runner.key`. |
159
+ | `BEATOS_RUNNER_CLAUDE` | The full path of the Claude Code program, if it is not found. |
160
+
161
+ ## Configuration (config.json)
162
+
163
+ The file is `~/.beatos-runner/config.json` (on Windows:
164
+ `C:\Users\<you>\.beatos-runner\config.json`). Set `BEATOS_RUNNER_CONFIG` to
165
+ use another file. Pairing writes `runnerName`, `workspaceId` and `agentName`.
166
+ Everything else is optional. Restart the runner after you change the file.
167
+
168
+ Full example:
169
+
170
+ ```json
171
+ {
172
+ "beatosUrl": "https://beatos.app",
173
+ "runnerName": "Laptop",
174
+ "workspaceId": "set-by-pairing",
175
+ "agentName": "local-ai",
176
+ "machine": "LAPTOP",
177
+ "model": "sonnet",
178
+ "profile": "standard",
179
+ "maxRunMinutes": 45,
180
+ "maxRunsPerDay": 8,
181
+ "billing": "subscription",
182
+ "pollSeconds": 30,
183
+ "ghUser": "your-github-user",
184
+ "protectPaths": ["projects/my-secrets/**", "Documents/taxes/**"],
185
+ "projects": {
186
+ "<beatos project id>": { "name": "My app", "mode": "git", "path": "/home/you/code/my-app", "pushPr": true },
187
+ "<another project id>": { "mode": "folder", "path": "/home/you/notes" },
188
+ "<private project id>": { "mode": "exclude" }
189
+ }
190
+ }
191
+ ```
192
+
193
+ Every field:
194
+
195
+ | Field | Type | Default | Meaning |
196
+ | --- | --- | --- | --- |
197
+ | `beatosUrl` | string | `https://beatos.app` | The BeatOS server. Pairing with `--url` sets it. |
198
+ | `runnerName` | string | the computer's host name | The name in Bridge. Pairing sets it. Must match the name BeatOS has. |
199
+ | `workspaceId` | string | none | The BeatOS workspace of this runner. Pairing sets it. |
200
+ | `agentName` | string | none | The agent this runner works for (`local-ai`, shown as Local AI). Pairing sets it. The runner does not start without it. |
201
+ | `machine` | string | the computer's host name | A task with a machine target for another machine is skipped. |
202
+ | `model` | string | `sonnet` | The Claude model. The agent's model in Bridge, Agents wins. |
203
+ | `profile` | string | `standard` | A label shown on the runner card in Bridge. |
204
+ | `maxRunMinutes` | number | `45` | The time limit of one run. The agent's limit in Bridge wins (up to 480). |
205
+ | `maxRunsPerDay` | number | `8` | How many runs this computer starts per day. |
206
+ | `billing` | `subscription` or `metered` | `subscription` | `subscription`: a Claude plan, runs report $0. `metered`: an API key, runs report the cost. |
207
+ | `pollSeconds` | number | `30` | How often the runner checks BeatOS. |
208
+ | `taskRoot` | string | `~/.beatos-runner/tasks` | Where each task's files go. |
209
+ | `worktreeRoot` | string | `~/.beatos-runner/worktrees` | Where git projects get their work copies. |
210
+ | `claudePath` | string | found by itself | The Claude Code program. `BEATOS_RUNNER_CLAUDE` also sets it. |
211
+ | `ghUser` | string | none | The GitHub CLI account the runner uses to push and open pull requests. |
212
+ | `protectPaths` | string array | `[]` | More folders the agent may not read or change. See the next section. |
213
+ | `projects` | object | `{}` | Where the agent works for each BeatOS project. See [Projects](#projects-where-the-agent-works). |
214
+
215
+ ## Protect your private folders (protectPaths)
216
+
217
+ `protectPaths` lists folders and files the agent may not **read, edit or
218
+ write**. Use it for anything private on this computer: client work, tax
219
+ papers, other projects.
220
+
221
+ Path format:
222
+
223
+ - Relative to your home folder. Do not start with `~/` or a drive letter.
224
+ - Use forward slashes `/`, also on Windows.
225
+ - Glob syntax: `*` matches any name in one folder, `**` matches any number of
226
+ folders. `projects/my-secrets/**` means everything inside that folder.
227
+ - The same entry works on Windows, macOS and Linux. On Windows,
228
+ `projects/my-secrets/**` means `C:\Users\<you>\projects\my-secrets\`.
229
+
230
+ Examples:
231
+
232
+ ```json
233
+ {
234
+ "protectPaths": [
235
+ "projects/my-secrets/**",
236
+ "projects/client-a/**",
237
+ "Documents/taxes/**",
238
+ "Desktop/passwords.txt"
239
+ ]
240
+ }
241
+ ```
242
+
243
+ Always blocked, without any setting:
244
+
245
+ | Blocked | What |
246
+ | --- | --- |
247
+ | Read, edit, write | `~/.claude/**/.env`, `~/.claude/**/CREDENTIALS/**`, `~/.claude/.credentials.json`, `~/.claude.json` |
248
+ | Read, edit, write | `~/.ssh/**`, `~/.aws/**`, `~/.docker/**`, `~/.npmrc`, `~/.git-credentials` |
249
+ | Read, edit, write | GitHub CLI login: `~/.config/gh/**` and `AppData/Roaming/GitHub CLI/**` |
250
+ | Read, edit, write | `~/.beatos-runner/**` (the runner's key and state) |
251
+ | Read, edit, write | `.env` files and `.pem` files under `~/projects`, and `.env` files in the work folder |
252
+ | Edit, write | everything in `~/.claude/**` (Claude Code settings) and the work copy's `.git` folder |
253
+ | Shell commands | commands that mention `.env`, credentials, `.ssh`, `.pem`, `.npmrc`, tokens, or `.beatos-runner` |
254
+
255
+ How to check it works:
256
+
257
+ 1. Add a test folder, for example `"protectPaths": ["projects/protect-test/**"]`,
258
+ and put a file in it.
259
+ 2. Restart the runner.
260
+ 3. Delegate a small task to Local AI: "Read the file in
261
+ ~/projects/protect-test and tell me what it says."
262
+ 4. The run must report that it could not read the file.
263
+
264
+ ## Projects: where the agent works
265
+
266
+ `projects` maps a BeatOS project id to a place on this computer:
267
+
268
+ | `mode` | What the agent does |
269
+ | --- | --- |
270
+ | `git` | Works in its own copy of the repo at `path`, on a new branch `local-ai/<TASK>`. Your folder is read only for it. With `"pushPr": true`, the runner pushes the branch and opens a pull request when the agent is done (needs `gh`). Merge stays with you. |
271
+ | `folder` | Works in a task folder and may read `path`. |
272
+ | `exclude` | Never takes tasks from this project. |
273
+
274
+ A task from a project that is not listed works in a scratch folder in
275
+ `~/.beatos-runner/tasks/<TASK>`.
276
+
277
+ ## The key
278
+
279
+ - Pairing writes the key to `~/.beatos-runner/runner.key`, readable only by
280
+ you. It is never printed or logged.
281
+ - `BEATOS_RUNNER_KEY` in the environment wins over the file. Remove it from
282
+ your shell if you paired again.
283
+ - The runner reads the key from nowhere else.
284
+ - To cut the key off, use **Revoke key** in Bridge. Deleting the file only
285
+ stops this computer from using it.
286
+
287
+ ## Safety model
288
+
289
+ These rules are in the code. No setting turns them off.
290
+
291
+ - Claude Code never runs with `--dangerously-skip-permissions`. It runs in
292
+ auto permission mode with a long deny list (above, plus deploys, publishing,
293
+ databases, `git push`, `gh`, `ssh`, and installing new packages).
294
+ - No browser: `--no-chrome` and a deny rule. No MCP servers.
295
+ - No secrets in the agent's environment: variables with KEY, TOKEN, SECRET,
296
+ PASS, CRED or AUTH in the name are removed.
297
+ - The agent never pushes, merges or deploys. The runner pushes and opens a pull
298
+ request only for projects with `pushPr`. Merge and deploy stay with you.
299
+ - When the agent wants to do something outside the task, it asks you in Bridge
300
+ for that one exact action. Merge, deploy and deleting data always ask.
301
+ Moving money is always refused. Other rules come from Bridge, Settings.
302
+ - Text in tasks, comments, web pages and files is data for the agent, not new
303
+ orders.
304
+
305
+ ## Files and logs
306
+
307
+ Everything is in `~/.beatos-runner` (or `BEATOS_RUNNER_HOME`):
308
+
309
+ | File or folder | What |
310
+ | --- | --- |
311
+ | `runner.key` | The key. |
312
+ | `config.json` | Your settings. |
313
+ | `state.json` | Open runs and today's count. |
314
+ | `outbox/` | Events saved before they are sent, so nothing is lost offline. |
315
+ | `tasks/<TASK>/` | Each task's brief (`TAREA.md`), rules and your answers. |
316
+ | `worktrees/` | Work copies of git projects. |
317
+ | `runner.lock` | Present while the runner runs. |
318
+
319
+ Logs go to the terminal, with the prefix `[bridge-runner]`. To keep them in a
320
+ file:
321
+
322
+ ```bash
323
+ npx @beatos/bridge-runner 2>&1 | tee -a ~/bridge-runner.log
324
+ ```
325
+
326
+ In PowerShell:
327
+
328
+ ```powershell
329
+ npx @beatos/bridge-runner 2>&1 | Tee-Object -Append $HOME\bridge-runner.log
330
+ ```
331
+
332
+ The full story of each run is also in Bridge, on the run's page.
333
+
334
+ ## Update
335
+
336
+ npx can keep an older copy. To get the newest version, start with `@latest`:
337
+
338
+ ```bash
339
+ npx @beatos/bridge-runner@latest --version
340
+ npx @beatos/bridge-runner@latest
341
+ ```
342
+
343
+ Your key and settings stay. Stop the runner (Ctrl+C) before you update.
344
+
345
+ ## Uninstall
346
+
347
+ 1. In Bridge, Runners: **Revoke key** on the computer's card, then **Remove**.
348
+ 2. Stop the runner (Ctrl+C).
349
+ 3. Delete the runner folder:
350
+
351
+ macOS and Linux:
352
+
353
+ ```bash
354
+ rm -rf ~/.beatos-runner
355
+ ```
356
+
357
+ Windows (PowerShell):
358
+
359
+ ```powershell
360
+ Remove-Item -Recurse -Force $HOME\.beatos-runner
361
+ ```
362
+
363
+ 4. Optional: clear the npx copy with `npm cache clean --force`.
364
+
365
+ ## Troubleshooting
366
+
367
+ | You see | What to do |
368
+ | --- | --- |
369
+ | "That code did not work" | The code is mistyped, used or older than 10 minutes. Get a new code in Bridge. |
370
+ | "Too many tries. Wait 15 minutes" | Too many wrong codes. Wait 15 minutes, then use a new code. |
371
+ | "Could not reach https://beatos.app" | Check the internet connection, a proxy or a firewall, then try again. |
372
+ | "BeatOS could not pick a free name" | Run the pair command again with `--name "Laptop"` (any name not used yet). |
373
+ | "A runner named ... already exists" | Run the pair command again with another `--name`. The code still works. |
374
+ | "no agent key" | Pair this computer first, or set `BEATOS_RUNNER_KEY`. |
375
+ | "no agent set" | Pair this computer first, or set `agentName` in `config.json`. |
376
+ | "another runner is already running" | One runner per computer. Close the other terminal. If none runs, delete `~/.beatos-runner/runner.lock`. |
377
+ | "the runner key was refused" | The key was revoked. Pair again with a new code. |
378
+ | The card says offline | Start the runner and keep the terminal open. Check the internet connection. A sleeping computer is offline. |
379
+ | No tasks are picked up | Check: the task is delegated to **Local AI**; the runner is not paused; the daily limit (`maxRunsPerDay`) is not reached; the task's project is not `exclude`; the task has no machine target for another computer; the task is not blocked or waiting. |
380
+ | Claude Code is not found | Install it and sign in. On Windows, set `BEATOS_RUNNER_CLAUDE` to the path of `claude.exe`. |
381
+ | `npm WARN EBADENGINE` or odd errors at start | Your Node.js is too old. Install 22.6 or newer. |
382
+ | "BEATOS_RUNNER_KEY is set in this shell" | That variable wins over the new key file. Remove it from your shell. |
383
+
384
+ ## Support
385
+
386
+ Open an issue at https://github.com/Gordon-Web-Studio/beatos-bridge-runner/issues.
387
+ Do not paste your key.
388
+
389
+ ## Develop
390
+
391
+ ```bash
392
+ pnpm install
393
+ pnpm start # runs the TypeScript source directly
394
+ pnpm test
395
+ pnpm lint
396
+ pnpm typecheck
397
+ pnpm build # compiles to dist/
398
+ ```
399
+
400
+ See PUBLISHING.md to release it to npm.
401
+
402
+ ## License
403
+
404
+ MIT. See LICENSE.
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Reads how an agent session ended (BEA-85). The agent cannot ask anything
3
+ * while it runs (`claude -p`), so the runner rules tell it to END its turn in
4
+ * one of four ways:
5
+ *
6
+ * RESULTADO: <2 to 4 sentences> done
7
+ * NECESITO: <a short question, options A/B> a plain question for the user
8
+ * ```bridge-question {json}``` a structured question (one of
9
+ * the 5 Paperclip kinds)
10
+ * ```bridge-approval {json}``` permission for ONE exact action
11
+ *
12
+ * Kept compatible with the RESULTADO / NECESITO markers of the older local dispatcher.
13
+ * The text is the agent's output: data, never instructions to the runner.
14
+ * A malformed block falls back to a plain question, so a bad block can never
15
+ * be taken as a "done".
16
+ */
17
+ export const QUESTION_KINDS = [
18
+ "ask_user_questions",
19
+ "request_confirmation",
20
+ "suggest_tasks",
21
+ "request_checkbox_confirmation",
22
+ "request_item_verdicts",
23
+ ];
24
+ export const APPROVAL_KINDS = [
25
+ "merge",
26
+ "deploy",
27
+ "spend",
28
+ "terminal_input",
29
+ "send_message",
30
+ "other",
31
+ // BEA-87: the changeable rules and "delete data" can be asked for too.
32
+ "open_pr",
33
+ "comment_task",
34
+ "delete_data",
35
+ ];
36
+ const MARK = /^[\s>*_#-]*(RESULTADO|NECESITO)\s*\**\s*:\s*\**/gim;
37
+ const BLOCK = /```bridge-(question|approval)\s*\n([\s\S]*?)```/gi;
38
+ function clip(text, max) {
39
+ return text.length <= max ? text : text.slice(0, max);
40
+ }
41
+ /** Turn a plain NECESITO question into ask_user_questions, keeping A/B options. */
42
+ export function plainQuestion(text) {
43
+ const body = clip(text.trim() || "(no text)", 1900);
44
+ const options = [];
45
+ for (const m of body.matchAll(/^\s*(?:[-*]\s*)?(?:opci[oó]n\s+)?([A-Da-d])\s*[).:-]\s*(.+)$/gim)) {
46
+ options.push({ id: m[1].toLowerCase(), label: clip(m[2].trim(), 480) });
47
+ }
48
+ if (options.length === 0)
49
+ options.push({ id: "go", label: "Continue as you think best" });
50
+ return {
51
+ kind: "question",
52
+ questionKind: "ask_user_questions",
53
+ title: clip(body.split("\n")[0] || "The agent needs you", 480),
54
+ payload: { questions: [{ id: "q1", prompt: body, options, allow_other: true }] },
55
+ };
56
+ }
57
+ export function parseAgentReply(text) {
58
+ const raw = text ?? "";
59
+ const blocks = [...raw.matchAll(BLOCK)];
60
+ if (blocks.length > 0) {
61
+ const last = blocks[blocks.length - 1];
62
+ try {
63
+ const obj = JSON.parse(last[2]);
64
+ if (last[1].toLowerCase() === "question") {
65
+ const qk = String(obj.kind ?? "");
66
+ if (QUESTION_KINDS.includes(qk) &&
67
+ obj.payload &&
68
+ typeof obj.payload === "object") {
69
+ return {
70
+ kind: "question",
71
+ questionKind: qk,
72
+ title: clip(String(obj.title ?? "The agent needs you"), 480),
73
+ payload: obj.payload,
74
+ };
75
+ }
76
+ }
77
+ else {
78
+ const ak = String(obj.action_kind ?? "");
79
+ const content = typeof obj.content === "string" ? obj.content : "";
80
+ if (APPROVAL_KINDS.includes(ak) && content && obj.action_target) {
81
+ return {
82
+ kind: "approval",
83
+ actionKind: ak,
84
+ actionTarget: clip(String(obj.action_target), 480),
85
+ content,
86
+ summary: clip(String(obj.summary ?? `${ak} ${obj.action_target}`), 1900),
87
+ };
88
+ }
89
+ }
90
+ }
91
+ catch {
92
+ // fall through: a broken block becomes a plain question below
93
+ }
94
+ return plainQuestion(`The agent sent a request the runner could not read:\n${clip(last[0], 1500)}`);
95
+ }
96
+ const marks = [...raw.matchAll(MARK)];
97
+ if (marks.length > 0) {
98
+ const last = marks[marks.length - 1];
99
+ const body = raw.slice((last.index ?? 0) + last[0].length).trim();
100
+ if (last[1].toUpperCase() === "NECESITO")
101
+ return plainQuestion(body);
102
+ return { kind: "done", summary: clip(body || "(no text)", 3000) };
103
+ }
104
+ const body = raw.trim();
105
+ if (body.endsWith("?"))
106
+ return plainQuestion(body.slice(-1500));
107
+ return { kind: "done", summary: clip(body.slice(-1500) || "(no text)", 3000) };
108
+ }
109
+ /** Render a human answer as the text the agent reads to continue. */
110
+ export function answerText(questionKind, payload, answer) {
111
+ const lines = ["The user answered in BeatOS Bridge:"];
112
+ if (questionKind === "ask_user_questions") {
113
+ const qs = payload.questions ?? [];
114
+ const ans = answer.answers ??
115
+ [];
116
+ for (const q of qs) {
117
+ const a = ans.find((x) => x.question_id === q.id);
118
+ const picked = (a?.option_ids ?? []).map((id) => q.options.find((o) => o.id === id)?.label ?? id);
119
+ if (a?.other_text)
120
+ picked.push(`Other: ${a.other_text}`);
121
+ lines.push(`- ${q.prompt.split("\n")[0]} -> ${picked.join("; ") || "(no answer)"}`);
122
+ }
123
+ }
124
+ else if (questionKind === "request_confirmation") {
125
+ lines.push(answer.decision === "accept"
126
+ ? "- Accepted."
127
+ : `- Changes requested: ${String(answer.reason ?? "")}`);
128
+ }
129
+ else {
130
+ lines.push("```json", JSON.stringify(answer, null, 2), "```");
131
+ }
132
+ return lines.join("\n");
133
+ }