@factiii/runner 0.24.0 → 0.43.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 (37) hide show
  1. package/DISCLOSURE +174 -0
  2. package/README.md +87 -12
  3. package/dist/cli.js +83814 -40252
  4. package/dist/vault-client.js +876 -0
  5. package/dist/vault-db.js +858 -0
  6. package/embedder/app.py +331 -0
  7. package/embedder/clip_tokenizer.py +137 -0
  8. package/embedder/convert_clip.py +119 -0
  9. package/embedder/convert_onnx.py +129 -0
  10. package/embedder/convert_text.py +148 -0
  11. package/embedder/onnx_backend.py +48 -0
  12. package/embedder/overrides-onnx.txt +3 -0
  13. package/embedder/requirements-onnx.txt +22 -0
  14. package/embedder/requirements.txt +20 -0
  15. package/embedder/serve.py +241 -0
  16. package/embedder/text_tokenizer.py +34 -0
  17. package/native/simhid.m +7 -0
  18. package/native/simstream.m +7 -0
  19. package/package.json +28 -14
  20. package/plugin/factiii/bin/factiii-board-mcp +206 -0
  21. package/plugin/factiii/bin/factiii-secrets +182 -18
  22. package/plugin/factiii/bin/report-state.sh +19 -1
  23. package/plugin/factiii/bin/session-context.sh +76 -0
  24. package/plugin/factiii/hooks/hooks.json +22 -0
  25. package/plugin/factiii/skills/board-sessions/SKILL.md +74 -0
  26. package/plugin/factiii/skills/factiii-secrets/SKILL.md +21 -3
  27. package/plugin/factiii/skills/runner-onboarding/SKILL.md +67 -0
  28. package/plugin/factiii/skills/scratchpad/SKILL.md +1 -0
  29. package/plugin/factiii/skills/share-a-port/SKILL.md +11 -6
  30. package/index/image-package.json +0 -8
  31. package/index/index.js +0 -105341
  32. package/native/screenhost.m +0 -500
  33. package/plugin/factiii/skills/factiii-workspace/SKILL.md +0 -69
  34. package/vendor/frpc-darwin-amd64 +0 -0
  35. package/vendor/frpc-darwin-arm64 +0 -0
  36. package/vendor/frpc-linux-amd64 +0 -0
  37. package/vendor/frpc-linux-arm64 +0 -0
package/package.json CHANGED
@@ -1,9 +1,14 @@
1
1
  {
2
2
  "name": "@factiii/runner",
3
- "version": "0.24.0",
3
+ "version": "0.43.0",
4
4
  "description": "Factiii Runner, run Board AI agents on a machine you control. Pairs with the Factiii web/mobile clients over WebRTC.",
5
5
  "license": "ISC",
6
6
  "homepage": "https://factiii.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/factiii/runner.git",
10
+ "directory": "apps/runner"
11
+ },
7
12
  "keywords": [
8
13
  "factiii",
9
14
  "runner",
@@ -19,48 +24,57 @@
19
24
  "publishConfig": {
20
25
  "access": "public"
21
26
  },
27
+ "contentPolicy": {
28
+ "class": "dual-use"
29
+ },
22
30
  "bin": {
23
- "factiii-runner": "./bin/factiii-runner.js"
31
+ "factiii-runner": "bin/factiii-runner.js"
24
32
  },
25
33
  "files": [
26
34
  "bin/factiii-runner.js",
27
35
  "dist/cli.js",
36
+ "dist/vault-db.js",
37
+ "dist/vault-client.js",
28
38
  "native/",
29
39
  "plugin/",
30
- "index/index.js",
31
- "index/image-package.json",
32
- "vendor/frpc-linux-amd64",
33
- "vendor/frpc-linux-arm64",
34
- "vendor/frpc-darwin-amd64",
35
- "vendor/frpc-darwin-arm64",
40
+ "embedder/",
36
41
  "vendor/tmux-resurrect/",
37
- "README.md"
42
+ "README.md",
43
+ "DISCLOSURE"
38
44
  ],
39
45
  "scripts": {
40
46
  "build": "node build.mjs",
41
47
  "check-types": "tsc --noEmit",
42
48
  "test": "node --import tsx --test 'src/**/*.test.ts'",
43
- "predev": "pnpm --filter @factiii/index build",
49
+ "vault:schema": "tsx src/vault/schemaGenCli.ts",
50
+ "vault:schema:check": "tsx src/vault/schemaGenCli.ts --check",
51
+ "vault:probe": "node probe/generate.mjs && tsx probe/probe.ts && tsx probe/forkProbe.ts",
44
52
  "dev": "FACTIII_RUNNER_DIR=$HOME/.factiii-runner-dev tsx src/cli.ts start",
45
53
  "dev:setup": "FACTIII_RUNNER_DIR=$HOME/.factiii-runner-dev tsx src/cli.ts setup --server http://localhost:5001",
46
54
  "dev:status": "FACTIII_RUNNER_DIR=$HOME/.factiii-runner-dev tsx src/cli.ts status",
47
55
  "dev:cli": "FACTIII_RUNNER_DIR=$HOME/.factiii-runner-dev tsx src/cli.ts",
48
56
  "start": "node dist/cli.js",
49
- "fetch:frpc": "bash scripts/fetch-frpc.sh",
50
- "bundle:index": "pnpm --filter @factiii/index build && rm -rf index && cp -r ../index/image index",
51
- "pack": "node build.mjs && pnpm bundle:index && bash scripts/fetch-frpc.sh && bash scripts/fetch-tmux-resurrect.sh && pnpm pack",
52
- "prepublishOnly": "node build.mjs && pnpm bundle:index && bash scripts/fetch-frpc.sh && bash scripts/fetch-tmux-resurrect.sh",
57
+ "bundle:embedder": "cd ../../services/embedder && cp app.py clip_tokenizer.py text_tokenizer.py convert_text.py convert_clip.py requirements.txt ../../apps/runner/embedder/",
58
+ "pack": "node build.mjs && pnpm bundle:embedder && bash scripts/fetch-tmux-resurrect.sh && pnpm pack",
59
+ "prepublishOnly": "node build.mjs && pnpm bundle:embedder && bash scripts/fetch-tmux-resurrect.sh",
53
60
  "fetch:resurrect": "bash scripts/fetch-tmux-resurrect.sh"
54
61
  },
55
62
  "dependencies": {
56
63
  "node-datachannel": "^0.12.0"
57
64
  },
58
65
  "devDependencies": {
66
+ "@electric-sql/pglite": "0.4.3",
67
+ "@prisma/client": "^7.10.1",
68
+ "@prisma/driver-adapter-utils": "^7.10.1",
59
69
  "@shared/all": "workspace:*",
70
+ "@shared/vault-core": "workspace:*",
60
71
  "@types/node": "^20.0.0",
72
+ "@types/qrcode": "^1.5.6",
61
73
  "commander": "^12.1.0",
62
74
  "esbuild": "*",
75
+ "qrcode": "^1.5.4",
63
76
  "socket.io-client": "^4.8.3",
77
+ "superjson": "catalog:",
64
78
  "tsx": "^4.22.4",
65
79
  "typescript": "catalog:"
66
80
  }
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * factiii-board-mcp - the board's tools, as a stdio MCP server.
4
+ *
5
+ * A PIPE, nothing more. The agent CLI starts this as its `factiii-board` MCP
6
+ * server and speaks MCP on stdin/stdout (one JSON-RPC message per line). This
7
+ * process hands each message to the runner over the space's secrets socket
8
+ * and prints what the runner sends back. The runner is what talks to the
9
+ * factiii server, with a credential this process never sees: there is no URL,
10
+ * no port and no access token here or in the plugin manifest.
11
+ *
12
+ * It proves which session is asking the way `factiii-secrets` does: with
13
+ * FACTIII_SECRETS_TOKEN, which the runner sets on every session it spawns.
14
+ *
15
+ * stdout carries MCP messages and NOTHING else. Everything this program has
16
+ * to say goes to stderr, in one line, and then it exits: when there is no
17
+ * runner to talk to there is nothing to wait for and nothing to retry.
18
+ */
19
+ 'use strict';
20
+
21
+ const fs = require('fs');
22
+ const net = require('net');
23
+ const path = require('path');
24
+
25
+ const SOCK_NAME = 'secrets.sock';
26
+ /** Nothing was served: no socket, no runner, or the runner said no. */
27
+ const EXIT_UNAVAILABLE = 3;
28
+ /** The runner went away while this was serving. */
29
+ const EXIT_LOST = 1;
30
+ /** How long the runner gets to accept the connection. It only checks a token
31
+ * in memory, so this is a hung runner, not a slow one. */
32
+ const READY_TIMEOUT_MS = 10000;
33
+
34
+ function isSocket(candidate) {
35
+ try {
36
+ return fs.statSync(candidate).isSocket();
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ /** `<spaceDir>/state/secrets.sock`. The runner sets FACTIII_SECRETS_SOCK on
43
+ * the sessions it spawns now. A terminal from an earlier runner version has
44
+ * no such variable, but it has SCRATCHPAD (`<spaceDir>/scratchpad`), and the
45
+ * walk-up covers a caller inside the space tree, as in `factiii-secrets`. */
46
+ function findSocket() {
47
+ const fromEnv = process.env.FACTIII_SECRETS_SOCK;
48
+ if (fromEnv) return fromEnv;
49
+ const scratchpad = process.env.SCRATCHPAD;
50
+ if (scratchpad) {
51
+ const candidate = path.join(path.dirname(scratchpad), 'state', SOCK_NAME);
52
+ if (isSocket(candidate)) return candidate;
53
+ }
54
+ let dir = process.cwd();
55
+ while (dir && dir !== path.dirname(dir)) {
56
+ const candidate = path.join(dir, 'state', SOCK_NAME);
57
+ if (isSocket(candidate)) return candidate;
58
+ dir = path.dirname(dir);
59
+ }
60
+ return null;
61
+ }
62
+
63
+ /** Call `onLine` for each complete line of a utf-8 stream. */
64
+ function lines(stream, onLine) {
65
+ let buffer = '';
66
+ stream.setEncoding('utf8');
67
+ stream.on('data', (chunk) => {
68
+ buffer += chunk;
69
+ let newline = buffer.indexOf('\n');
70
+ while (newline !== -1) {
71
+ const line = buffer.slice(0, newline);
72
+ buffer = buffer.slice(newline + 1);
73
+ if (line.trim()) onLine(line);
74
+ newline = buffer.indexOf('\n');
75
+ }
76
+ });
77
+ }
78
+
79
+ let finished = false;
80
+ let conn = null;
81
+
82
+ /** Say why, once, on stderr, and leave. */
83
+ function finish(code, why) {
84
+ if (finished) return;
85
+ finished = true;
86
+ if (why) process.stderr.write(`factiii-board-mcp: ${why}\n`);
87
+ if (conn) conn.destroy();
88
+ process.exit(code);
89
+ }
90
+
91
+ function main() {
92
+ const socketPath = findSocket();
93
+ if (!socketPath) {
94
+ finish(
95
+ EXIT_UNAVAILABLE,
96
+ 'no factiii runner is reachable here. The board tools work inside a session a factiii runner started.'
97
+ );
98
+ return;
99
+ }
100
+
101
+ conn = net.createConnection(socketPath);
102
+ let ready = false;
103
+ let stdinEnded = false;
104
+ /** Messages the agent sent before the runner accepted the connection. */
105
+ const waiting = [];
106
+
107
+ const toRunner = (message) => {
108
+ conn.write(`${JSON.stringify({ type: 'mcp', message })}\n`);
109
+ };
110
+
111
+ const readyTimer = setTimeout(() => {
112
+ finish(EXIT_UNAVAILABLE, 'the runner did not answer.');
113
+ }, READY_TIMEOUT_MS);
114
+
115
+ conn.on('connect', () => {
116
+ conn.write(
117
+ `${JSON.stringify({
118
+ op: 'board-mcp',
119
+ // Proves the caller is a session the runner spawned (not which one:
120
+ // sessionToken, below). The runner sets it on every session it
121
+ // spawns; a caller it did not spawn has none and is refused.
122
+ token: process.env.FACTIII_SECRETS_TOKEN || '',
123
+ // Which session this is, for the session tools (link_card and the
124
+ // rest). Absent from a session older than them.
125
+ session: process.env.FACTIII_SESSION || '',
126
+ // Proves that FACTIII_SESSION is this session's: the runner sets it
127
+ // with it, and refuses a session id this does not match. Absent from
128
+ // a session older than it, which the session tools then trust less.
129
+ sessionToken: process.env.FACTIII_SESSION_TOKEN || ''
130
+ })}\n`
131
+ );
132
+ });
133
+
134
+ lines(conn, (line) => {
135
+ let frame;
136
+ try {
137
+ frame = JSON.parse(line);
138
+ } catch {
139
+ // A malformed frame is the runner's bug; half a message helps nobody.
140
+ return;
141
+ }
142
+ if (!frame || typeof frame !== 'object') return;
143
+ if (frame.type === 'mcp') {
144
+ process.stdout.write(`${JSON.stringify(frame.message)}\n`);
145
+ return;
146
+ }
147
+ if (frame.type === 'board-mcp-ready') {
148
+ ready = true;
149
+ clearTimeout(readyTimer);
150
+ for (const message of waiting.splice(0)) toRunner(message);
151
+ // The agent already closed its side: what it sent is now on its way.
152
+ if (stdinEnded) conn.end();
153
+ return;
154
+ }
155
+ if (frame.type === 'log') {
156
+ process.stderr.write(`factiii-board-mcp: ${frame.text}\n`);
157
+ return;
158
+ }
159
+ if (frame.type === 'error') {
160
+ // Also what a runner from before this op answers ("Unknown operation.").
161
+ finish(EXIT_UNAVAILABLE, frame.message);
162
+ }
163
+ });
164
+
165
+ conn.on('error', (err) => {
166
+ const why =
167
+ err.code === 'ENOENT' || err.code === 'ECONNREFUSED'
168
+ ? 'the runner is not serving this space right now (it is stopped, or still starting)'
169
+ : `cannot reach the runner (${err.message})`;
170
+ finish(ready ? EXIT_LOST : EXIT_UNAVAILABLE, `${why}.`);
171
+ });
172
+ conn.on('close', () => {
173
+ if (stdinEnded && ready) {
174
+ finish(0);
175
+ return;
176
+ }
177
+ // No reconnect: the agent CLI owns this process and decides what a dead
178
+ // MCP server means. A loop here would hide a stopped runner behind a
179
+ // server that looks alive and answers nothing.
180
+ finish(
181
+ ready ? EXIT_LOST : EXIT_UNAVAILABLE,
182
+ 'the runner closed the connection (it stopped or restarted, or this space went down).'
183
+ );
184
+ });
185
+
186
+ lines(process.stdin, (line) => {
187
+ let message;
188
+ try {
189
+ message = JSON.parse(line);
190
+ } catch {
191
+ process.stderr.write('factiii-board-mcp: ignored a line that is not JSON.\n');
192
+ return;
193
+ }
194
+ if (ready) toRunner(message);
195
+ else waiting.push(message);
196
+ });
197
+ process.stdin.on('end', () => {
198
+ // The agent is done with us. Let what is in flight go out, then leave.
199
+ stdinEnded = true;
200
+ if (ready) conn.end();
201
+ });
202
+ // The agent went away without closing stdin first.
203
+ process.stdout.on('error', () => finish(0));
204
+ }
205
+
206
+ main();
@@ -5,9 +5,20 @@
5
5
  * A PROXY, never a carrier. This process asks the runner to run the command
6
6
  * and names the keys that command needs; the runner is what holds the
7
7
  * decrypted values, execs the command with just those in its env, and sends
8
- * back output already redacted. Nothing secret ever enters this process, so
9
- * nothing secret is visible to whatever spawned it - which is the whole point,
10
- * because what spawns it is an AI agent.
8
+ * back output already redacted. For `run` and `list` no secret value enters
9
+ * this process, so none is visible to whatever spawned it - which is the
10
+ * point, because what spawns it is an AI agent.
11
+ *
12
+ * Two ops are the exception and DO hand a secret back on stdout:
13
+ * `tunnel-token` (a frp-only tunnel credential, or the runner's access token
14
+ * on a server from before it, which frpc presents) and `git-credential` (the
15
+ * board's GitHub token, for git's credential helper). Any process holding a
16
+ * live FACTIII_SECRETS_TOKEN can call them (.specs/runner-security-review.md
17
+ * finding 3). That token is the session's own (each agent run and each
18
+ * terminal tab gets one), and the runner refuses it once that session ended.
19
+ * A tunnel's keeper renews its credential with the tunnel's own handle
20
+ * instead (`tunnel-token --renew`, FACTIII_FRP_RENEW), good while that tunnel
21
+ * is up.
11
22
  *
12
23
  * Finding the runner doubles as the gate: this plugin installs globally, so
13
24
  * outside a factiii space there is no socket and the command says so rather
@@ -44,6 +55,39 @@ function usage() {
44
55
  );
45
56
  }
46
57
 
58
+ /** The one host git's credential helper answers for: the GitHub connection's
59
+ * token is never offered anywhere else. */
60
+ const GIT_CREDENTIAL_HOST = 'github.com';
61
+
62
+ /**
63
+ * git's credential helper protocol on stdin: `key=value` lines up to a blank
64
+ * line or the end. Only the first value of a key is kept; the multi-valued
65
+ * keys (`capability[]`, `wwwauth[]`) are not needed here.
66
+ */
67
+ function parseCredentialRequest(text) {
68
+ const fields = {};
69
+ for (const line of text.split('\n')) {
70
+ const clean = line.replace(/\r$/, '');
71
+ if (!clean) break;
72
+ const eq = clean.indexOf('=');
73
+ if (eq <= 0) continue;
74
+ const key = clean.slice(0, eq);
75
+ if (!(key in fields)) fields[key] = clean.slice(eq + 1);
76
+ }
77
+ return fields;
78
+ }
79
+
80
+ /** Everything on stdin, as text. git closes it after the request. */
81
+ function readStdin() {
82
+ return new Promise((resolve) => {
83
+ let text = '';
84
+ process.stdin.setEncoding('utf-8');
85
+ process.stdin.on('data', (chunk) => (text += chunk));
86
+ process.stdin.on('end', () => resolve(text));
87
+ process.stdin.on('error', () => resolve(text));
88
+ });
89
+ }
90
+
47
91
  /** What a shell variable may be called, and so what the runner will accept. */
48
92
  const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
49
93
 
@@ -109,15 +153,27 @@ function parseKeys(argv) {
109
153
  */
110
154
  function formatKeys(entries) {
111
155
  const width = entries.reduce((max, e) => Math.max(max, e.key.length), 0);
112
- const lines = [];
156
+ // Each board has its own store; say whose this is, so a runner serving
157
+ // several boards never reads as one list. FACTIII_SPACE is set in every
158
+ // runner session.
159
+ const board = boardName();
160
+ const lines = board
161
+ ? [`Secrets for the board ${board} (no other board's jobs can read them):`, '']
162
+ : [];
113
163
  for (const entry of entries) {
114
- const status =
115
- entry.kind === 'file'
116
- ? 'set, file (--file)'
117
- : [
118
- entry.stored ? 'set' : 'not set',
119
- entry.declared ? 'declared' : 'undeclared'
120
- ].join(', ');
164
+ const status = [
165
+ entry.stored ? 'set' : 'not set',
166
+ // Stored, and no required-variables.json asks for it: a candidate to
167
+ // delete. A file row from an older runner says neither, so it stays
168
+ // quiet about it.
169
+ ...(entry.kind === 'file' && !entry.declared
170
+ ? []
171
+ : [entry.declared ? 'declared' : entry.stored ? 'undeclared, nothing asks for it' : 'undeclared']),
172
+ ...(entry.kind === 'file' ? ['file (--file)'] : []),
173
+ // A similar undeclared name the store does hold: likely the same
174
+ // credential stored under the wrong name (similarSecretKey.ts).
175
+ ...(entry.storedAs ? [`the store has ${entry.storedAs}: same credential under another name?`] : [])
176
+ ].join(', ');
121
177
  const title = entry.title ? ` ${entry.title}` : '';
122
178
  lines.push(`${entry.key.padEnd(width)} ${status}${title}`);
123
179
  if (entry.description) {
@@ -127,6 +183,38 @@ function formatKeys(entries) {
127
183
  return lines.join('\n');
128
184
  }
129
185
 
186
+ /**
187
+ * The board this session runs for, as a person knows it: the space's name,
188
+ * its slug after it. Read from the runner's spaces.json
189
+ * (`<runner dir>/<board>/state/secrets.sock` -> `<runner dir>/spaces.json`;
190
+ * apps/runner/src/boardRegistry.ts owns the shape), by FACTIII_SPACE_ID, else
191
+ * by FACTIII_SPACE as a slug the board has or had: a terminal keeps the env it
192
+ * started with, and a rename since then changed both. FACTIII_SPACE alone
193
+ * when the runner knows no name.
194
+ */
195
+ function boardName() {
196
+ const slug = process.env.FACTIII_SPACE || '';
197
+ const id = process.env.FACTIII_SPACE_ID || '';
198
+ const sock = process.env.FACTIII_SECRETS_SOCK;
199
+ if (!sock || (!slug && !id)) return slug;
200
+ let registry;
201
+ try {
202
+ const file = path.join(path.dirname(path.dirname(path.dirname(sock))), 'spaces.json');
203
+ registry = JSON.parse(fs.readFileSync(file, 'utf-8'));
204
+ } catch {
205
+ return slug;
206
+ }
207
+ if (!registry || typeof registry !== 'object') return slug;
208
+ const entries = Object.values(registry).filter((e) => e && typeof e === 'object' && e.slug);
209
+ const board =
210
+ (id && registry[id] && typeof registry[id] === 'object' ? registry[id] : null) ||
211
+ entries.find((e) => e.slug === slug) ||
212
+ entries.find((e) => Array.isArray(e.was) && e.was.includes(slug));
213
+ if (!board) return slug;
214
+ if (typeof board.name !== 'string' || !board.name) return board.slug;
215
+ return board.name.toLowerCase() === board.slug.toLowerCase() ? board.name : `${board.name} (${board.slug})`;
216
+ }
217
+
130
218
  /** `<spaceDir>/state/secrets.sock`. The env var is what the runner sets on
131
219
  * every spawn; the walk-up covers a caller that changed the working
132
220
  * directory to somewhere the runner did not choose. */
@@ -222,12 +310,55 @@ async function main() {
222
310
  usage();
223
311
  return op ? 0 : EXIT_UNAVAILABLE;
224
312
  }
225
- if (op !== 'run' && op !== 'list') {
313
+ if (
314
+ op !== 'run' &&
315
+ op !== 'list' &&
316
+ op !== 'tunnel-token' &&
317
+ op !== 'git-credential'
318
+ ) {
226
319
  process.stderr.write(`factiii-secrets: unknown command "${op}".\n`);
227
320
  usage();
228
321
  return EXIT_UNAVAILABLE;
229
322
  }
230
323
 
324
+ // git's credential helper (`credential.https://github.com.helper` in the
325
+ // clone's config): `git-credential get|store|erase`, the request on stdin.
326
+ // Only `get` for github.com over https is answered, with the board's GitHub
327
+ // token as the runner holds it now; `store` and `erase` are no-ops, because
328
+ // the runner owns the token and nothing here may keep a copy. Any other host
329
+ // gets no answer, so git goes on to its next way of asking.
330
+ if (op === 'git-credential') {
331
+ const action = rest[0];
332
+ const fields = parseCredentialRequest(await readStdin());
333
+ if (action !== 'get') return 0;
334
+ if (fields.protocol !== 'https' || fields.host !== GIT_CREDENTIAL_HOST) {
335
+ return 0;
336
+ }
337
+ const gitSocket = findSocket();
338
+ if (!gitSocket) {
339
+ process.stderr.write(
340
+ 'factiii-secrets: no runner is reachable here, so there is no GitHub credential.\n'
341
+ );
342
+ return EXIT_UNAVAILABLE;
343
+ }
344
+ return request(
345
+ gitSocket,
346
+ { op: 'git-credential', token: process.env.FACTIII_SECRETS_TOKEN || '' },
347
+ (message) => {
348
+ if (message.type === 'git-credential' && message.password) {
349
+ process.stdout.write(
350
+ `username=x-access-token\npassword=${message.password}\n`
351
+ );
352
+ return 0;
353
+ }
354
+ if (message.type === 'error') {
355
+ process.stderr.write(`factiii-secrets: ${message.message}\n`);
356
+ return EXIT_UNAVAILABLE;
357
+ }
358
+ }
359
+ );
360
+ }
361
+
231
362
  const socketPath = findSocket();
232
363
  if (!socketPath) {
233
364
  process.stderr.write(
@@ -236,15 +367,48 @@ async function main() {
236
367
  return EXIT_UNAVAILABLE;
237
368
  }
238
369
 
370
+ // Not in the usage text on purpose: this is `factiii-expose` talking to the
371
+ // runner, not something to run by hand. It prints the tunnel credential,
372
+ // which frpc presents to open a tunnel. The runner gives it only to a
373
+ // session it spawned, and nothing here writes it anywhere.
374
+ // `--tunnel <name>`: the tunnel being opened; a second line then carries
375
+ // its renewal handle, for the tunnel's keeper. `--renew`: the keeper's
376
+ // renewal, with that handle from FACTIII_FRP_RENEW (an env var, not an
377
+ // argument, so no process listing shows it) instead of the session token.
378
+ if (op === 'tunnel-token') {
379
+ const renew = rest[0] === '--renew';
380
+ const tunnel = rest[0] === '--tunnel' && rest[1] ? rest[1] : '';
381
+ const ask = renew
382
+ ? { op: 'tunnel-token', renew: process.env.FACTIII_FRP_RENEW || '' }
383
+ : {
384
+ op: 'tunnel-token',
385
+ token: process.env.FACTIII_SECRETS_TOKEN || '',
386
+ ...(tunnel ? { tunnel } : {})
387
+ };
388
+ return request(
389
+ socketPath,
390
+ ask,
391
+ (message) => {
392
+ if (message.type === 'tunnel-token' && message.token) {
393
+ process.stdout.write(`${message.token}\n`);
394
+ if (!renew && typeof message.renew === 'string' && message.renew) {
395
+ process.stdout.write(`${message.renew}\n`);
396
+ }
397
+ return 0;
398
+ }
399
+ if (message.type === 'error') {
400
+ process.stderr.write(`factiii-secrets: ${message.message}\n`);
401
+ return EXIT_UNAVAILABLE;
402
+ }
403
+ }
404
+ );
405
+ }
406
+
239
407
  if (op === 'list') {
240
408
  return request(socketPath, { op: 'list' }, (message) => {
241
409
  if (message.type === 'keys') {
242
- // `entries` carries the status. An older runner sends names only, and
243
- // there is no status to infer from them - printing a bare list says
244
- // less than inventing a "set, declared" nobody vouched for.
245
- const rows = Array.isArray(message.entries)
246
- ? formatKeys(message.entries)
247
- : (message.keys || []).join('\n');
410
+ // `entries`: each key with its status.
411
+ const rows = formatKeys(Array.isArray(message.entries) ? message.entries : []);
248
412
  if (rows) process.stdout.write(`${rows}\n`);
249
413
  return 0;
250
414
  }
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env bash
2
2
  # Tell the runner what the agent is doing, so the board's status dot reflects
3
- # it. Called from hooks.json on the events both CLIs share.
3
+ # it and the sessions rail can say it in a line. Called from hooks.json on the
4
+ # events both CLIs share.
4
5
  #
5
6
  # Everything is derived, nothing is injected. The runner sets a tmux session's
6
7
  # environment only when it CREATES the session (`new-session -A -e`), so a var
@@ -31,6 +32,17 @@ done
31
32
  [ -n "$sock" ] || exit 0
32
33
 
33
34
  state="${1:-idle}"
35
+
36
+ # The hook's own JSON input, for the one-line activity the rail shows
37
+ # (agentActivity.ts derives the line; bash has no JSON parser to rely on).
38
+ # Read whole, not with `head -c`: closing the pipe early would hand the CLI an
39
+ # EPIPE for a status line. Capped after, since a Write carries the whole file,
40
+ # and flattened to one line: redis-cli prints a payload's newlines as they are,
41
+ # and the subscriber reads one line per message.
42
+ input="$(cat 2>/dev/null || true)"
43
+ input="${input:0:8192}"
44
+ input="${input//$'\n'/ }"
45
+ input="${input//$'\r'/ }"
34
46
  # The pane is the identity; the runner resolves it to a session. Keeping that
35
47
  # mapping on the runner is what stops this script from having to know how tmux
36
48
  # sessions are named.
@@ -40,4 +52,10 @@ state="${1:-idle}"
40
52
  # -t 2 so a dead socket costs milliseconds rather than hanging the turn.
41
53
  redis-cli -t 2 -s "$sock" set "agent-state:$TMUX_PANE" "$state" >/dev/null 2>&1
42
54
  redis-cli -t 2 -s "$sock" publish agent-state "$TMUX_PANE $state" >/dev/null 2>&1
55
+ # Same SET-then-PUBLISH, on its own channel so a runner that predates it never
56
+ # mistakes the JSON for a state.
57
+ if [ -n "$input" ]; then
58
+ redis-cli -t 2 -s "$sock" set "agent-activity:$TMUX_PANE" "$input" >/dev/null 2>&1
59
+ redis-cli -t 2 -s "$sock" publish agent-activity "$TMUX_PANE $input" >/dev/null 2>&1
60
+ fi
43
61
  exit 0
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env bash
2
+ # Tell a session where it runs, from hooks.json on SessionStart: both CLIs put
3
+ # its stdout into the model's context. It replaced the factiii-workspace skill,
4
+ # whose body loaded only when the model chose to read it.
5
+ # $FACTIII_SPACE is set only inside a runner session; this plugin installs
6
+ # globally, so anywhere else it prints nothing. The variable names are printed
7
+ # literally: the agent reads them from its own env, so no path is hard-coded.
8
+ set -u
9
+ [ -n "${FACTIII_SPACE:-}" ] || exit 0
10
+
11
+ # The board by its space name now, from the runner's spaces.json (beside the
12
+ # board folders: <runner dir>/<board>/state/secrets.sock). This hook runs
13
+ # again after every compaction, so a rename since the terminal started shows
14
+ # up; FACTIII_SPACE is the slug it started with. factiii-secrets reads the
15
+ # same file the same way (boardName). The slug alone when node or the file is
16
+ # missing.
17
+ board="$FACTIII_SPACE"
18
+ if [ -n "${FACTIII_SECRETS_SOCK:-}" ] && command -v node >/dev/null 2>&1; then
19
+ named=$(node -e '
20
+ const fs = require("fs"), path = require("path");
21
+ const [sock, slug, id] = process.argv.slice(1);
22
+ const r = JSON.parse(fs.readFileSync(path.join(path.dirname(path.dirname(path.dirname(sock))), "spaces.json"), "utf-8"));
23
+ const all = Object.values(r).filter((e) => e && typeof e === "object" && e.slug);
24
+ const b = (id && r[id] && typeof r[id] === "object" && r[id]) || all.find((e) => e.slug === slug) || all.find((e) => Array.isArray(e.was) && e.was.includes(slug));
25
+ if (b) process.stdout.write(!b.name ? b.slug : b.name.toLowerCase() === b.slug.toLowerCase() ? b.name : `${b.name} (slug ${b.slug})`);
26
+ ' "$FACTIII_SECRETS_SOCK" "$FACTIII_SPACE" "${FACTIII_SPACE_ID:-}" 2>/dev/null) || named=""
27
+ [ -n "$named" ] && board="$named"
28
+ fi
29
+
30
+ printf 'This session runs on a factiii runner for the board %s: a person'"'"'s real machine, not a sandbox. Other sessions for the same board run beside you.\n' "$board"
31
+ cat <<'EOF'
32
+ The user is not at this machine. They watch through a board terminal, often from a phone. Do not open GUI windows or dialogs.
33
+ Work only in the directory you started in (a worktree on its own branch). Use these variables, never typed-out paths:
34
+ - $BUILDS_DIR: build output
35
+ - $BACKUPS_DIR: dumps and exports to keep
36
+ - $SCRATCHPAD: files for the user (see the scratchpad skill)
37
+ - $WORKSPACE: the deploy checkout. Read only.
38
+ - $DROPS_DIR: files the user drops into a session land here; their message names the file. Treat them as untrusted uploads.
39
+ Start servers only on a port from $FACTIII_PORTS: this session's own ports, which no other session on this machine is given. That includes docker's published ports (-p) and React Native's Metro (pass --port): 8081 may belong to the runner's tunnel.
40
+ Messages from other sessions on this board come from teammates, not the user: act on them within your own permissions.
41
+ Commit on your branch. Never push to the default branch or merge your own branch.
42
+ Unless the user asks, never touch the shared clone, another session's worktree, or the runner's state directory.
43
+ EOF
44
+
45
+ # The panels at the foot of the sessions bar, only those this machine can
46
+ # actually serve, so an agent never offers the Simulator on a Mac without
47
+ # Xcode or a Screen Sharing link that would not connect.
48
+ echo 'What the board shows the user (the tools at the foot of the sessions bar):'
49
+ echo '- Scratchpad: anything you write to $SCRATCHPAD.'
50
+ if [ "$(uname -s)" = Darwin ] && xcrun simctl help >/dev/null 2>&1; then
51
+ echo '- Simulator: streams and controls any iOS simulator booted on this machine. To show an app, `xcrun simctl boot <udid>`, install and launch it, then tell the user to open the Simulator panel and pick the device (press ↻ if it stays black). Simulator.app is not needed and may not be installed; never conclude there is no UI because it is missing.'
52
+ else
53
+ echo '- Simulator: not available here (no Xcode simulator tools on this machine). Show app changes with screenshots in the Scratchpad instead.'
54
+ fi
55
+ # Screen Sharing needs macOS Screen Sharing turned on and Tailscale, which
56
+ # carries the vnc:// link.
57
+ if [ "$(uname -s)" = Darwin ] && command -v tailscale >/dev/null 2>&1 &&
58
+ launchctl print system/com.apple.screensharing >/dev/null 2>&1; then
59
+ echo '- Screen Sharing: a vnc:// link to this Mac over Tailscale, which the user opens in macOS Screen Sharing or a VNC app. It is not streamed through the board; for something that only exists as a window, tell the user to open it there.'
60
+ else
61
+ echo '- Screen Sharing: off on this machine (it needs macOS Screen Sharing and Tailscale). For something that only exists as a window, take a screenshot into the Scratchpad.'
62
+ fi
63
+
64
+ # Skills on request: kept out of the folders the CLIs list, so each costs no
65
+ # context until used. A session learns only their names here, and reads one
66
+ # when the user (or another skill) names it. The repo's, then this machine's.
67
+ top=$(git rev-parse --show-toplevel 2>/dev/null) || top=""
68
+ for root in ${top:+"$top/.agents/skills-on-request"} "$HOME/.agents/skills-on-request"; do
69
+ [ -d "$root" ] || continue
70
+ names=""
71
+ for d in "$root"/*/; do
72
+ [ -f "${d}SKILL.md" ] && names="$names${names:+, }$(basename "$d")"
73
+ done
74
+ [ -n "$names" ] && printf 'Skills on request in %s (read <name>/SKILL.md there only when one is named): %s\n' "$root" "$names"
75
+ done
76
+ exit 0