pi-remote-web 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/CHANGELOG.md +6 -0
- package/DESIGN.md +128 -0
- package/LICENSE +21 -0
- package/README.md +77 -2
- package/SECURITY.md +5 -0
- package/bin/pi-remote-web.mjs +7 -0
- package/package.json +22 -4
- package/public/app.js +286 -0
- package/public/icon.svg +1 -0
- package/public/index.html +63 -0
- package/public/manifest.webmanifest +12 -0
- package/public/style.css +79 -0
- package/src/cli.mjs +183 -0
- package/src/commands.mjs +16 -0
- package/src/config.mjs +101 -0
- package/src/list-child.mjs +47 -0
- package/src/list-sessions.mjs +35 -0
- package/src/pi-install.mjs +33 -0
- package/src/projects.mjs +14 -0
- package/src/server.mjs +105 -0
- package/src/sessions.mjs +238 -0
- package/src/util.mjs +81 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "Pi Remote",
|
|
3
|
+
"short_name": "Pi Remote",
|
|
4
|
+
"description": "Use your Pi sessions from a private browser. Updates only while the page is open.",
|
|
5
|
+
"id": "/",
|
|
6
|
+
"start_url": "/",
|
|
7
|
+
"scope": "/",
|
|
8
|
+
"display": "standalone",
|
|
9
|
+
"background_color": "#11151c",
|
|
10
|
+
"theme_color": "#11151c",
|
|
11
|
+
"icons": [{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }]
|
|
12
|
+
}
|
package/public/style.css
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
:root { color-scheme: dark; font: 16px/1.5 system-ui, sans-serif; background: #101318; color: #e9edf4; }
|
|
2
|
+
* { box-sizing: border-box; }
|
|
3
|
+
/* Stop the browser's pull-to-refresh, which reloads the app and drops the draft. */
|
|
4
|
+
html, body { overscroll-behavior-y: none; }
|
|
5
|
+
[hidden] { display: none !important; }
|
|
6
|
+
body { margin: auto; max-width: 48rem; height: 100dvh; display: flex; flex-direction: column; padding: env(safe-area-inset-top) 1rem env(safe-area-inset-bottom); }
|
|
7
|
+
.appbar, .actions { display: flex; align-items: center; gap: .6rem; }
|
|
8
|
+
.appbar { margin-bottom: .5rem; }
|
|
9
|
+
.titles { flex: 1; min-width: 0; }
|
|
10
|
+
h1 { font-size: 1.2rem; overflow-wrap: anywhere; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
|
|
11
|
+
h2 { font-size: 1.1rem; }
|
|
12
|
+
h3 { font-size: .9rem; color: #b7d3ff; }
|
|
13
|
+
/* Positioned so the absolute .sr text stays inside the scroll areas instead of stretching the page. */
|
|
14
|
+
main, #scroll { flex: 1; min-height: 0; overflow-y: auto; overscroll-behavior-y: contain; position: relative; }
|
|
15
|
+
#scroll, #home, #project { padding-right: .35rem; }
|
|
16
|
+
#chat { height: 100%; display: flex; flex-direction: column; }
|
|
17
|
+
label { display: block; margin: .5rem 0; }
|
|
18
|
+
pre, p, .notice { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
19
|
+
button, input, select, textarea { font: inherit; border: 1px solid #49586c; border-radius: .6rem; padding: .55rem .7rem; min-height: 44px; }
|
|
20
|
+
input, textarea, select { width: 100%; background: #181f29; color: inherit; }
|
|
21
|
+
button { background: #b7d3ff; color: #10213c; cursor: pointer; }
|
|
22
|
+
button.secondary { background: #222c3a; color: #edf1f7; }
|
|
23
|
+
button.danger { background: #392126; color: #ffc9c9; border-color: #8a3b45; }
|
|
24
|
+
button.icon { min-width: 44px; padding: 0; display: grid; place-items: center; }
|
|
25
|
+
button:disabled { opacity: .55; cursor: default; }
|
|
26
|
+
button:focus-visible { outline: 3px solid #ffd58a; outline-offset: 2px; }
|
|
27
|
+
#home button, #archives button { display: block; width: 100%; text-align: left; margin-bottom: .5rem; overflow-wrap: anywhere; }
|
|
28
|
+
button.card { background: #181f29; color: #e9edf4; }
|
|
29
|
+
button.card.live { box-shadow: inset 4px 0 #b7d3ff; }
|
|
30
|
+
.card .meta { display: block; font-size: .8rem; color: #a3b1c4; }
|
|
31
|
+
.card .meta.busy { color: #b7d3ff; font-weight: 600; }
|
|
32
|
+
.card .meta.attention, #status.attention { color: #ffd58a; font-weight: 600; }
|
|
33
|
+
.notice, #error, article, .dialog { background: #181f29; border-radius: .65rem; padding: .6rem .75rem; margin: .5rem 0; }
|
|
34
|
+
.dialog { background: #241f14; border: 1px solid #8f7638; border-left: 4px solid #ffd58a; }
|
|
35
|
+
.dialog h3 { margin: 0 0 .35rem; font-size: 1rem; color: #ffd58a; }
|
|
36
|
+
.dialog p { margin: .25rem 0 .5rem; }
|
|
37
|
+
.dialog .actions { flex-wrap: wrap; margin-top: .5rem; }
|
|
38
|
+
#error { background: #392126; color: #ffe4e4; }
|
|
39
|
+
.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
40
|
+
article p, #live, #queued p { margin: .25rem 0; }
|
|
41
|
+
article.user { background: #1e3350; border: 1px solid #34527a; margin-left: 12%; }
|
|
42
|
+
#live:not(:empty) { background: #181f29; border-radius: .65rem; padding: .6rem .75rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
43
|
+
#queued p { color: #9aa8bb; font-size: .9rem; }
|
|
44
|
+
pre.tool { font: .85rem/1.4 ui-monospace, monospace; margin: .4rem 0; padding: .35rem .55rem; background: #10151c; border-left: 3px solid #5f7491; border-radius: 0 .4rem .4rem 0; color: #cdd6e3; }
|
|
45
|
+
pre.tool .tag { display: block; font: 600 .72rem/1.4 system-ui, sans-serif; color: #9fbbe0; }
|
|
46
|
+
#composer { border-top: 1px solid #49586c; padding-bottom: .5rem; }
|
|
47
|
+
.composer-head { display: flex; align-items: baseline; gap: .6rem; }
|
|
48
|
+
.composer-head label { flex: none; }
|
|
49
|
+
#status { flex: 1; min-width: 0; margin: 0; text-align: right; font-size: .85rem; color: #9aa8bb; }
|
|
50
|
+
#status.busy { color: #b7d3ff; font-weight: 600; }
|
|
51
|
+
#status.busy::before { content: ''; display: inline-block; width: .55rem; height: .55rem; margin-right: .4rem; border-radius: 50%; background: currentColor; animation: pulse 1.2s ease-in-out infinite; }
|
|
52
|
+
@keyframes pulse { 50% { opacity: .3; } }
|
|
53
|
+
@media (prefers-reduced-motion: reduce) { #status.busy::before { animation: none; } }
|
|
54
|
+
#subtitle { margin: -.55rem 0 .5rem; font-size: .8rem; line-height: 1.3; color: #a3b1c4; white-space: normal; }
|
|
55
|
+
#subtitle .thinking { white-space: nowrap; }
|
|
56
|
+
#subtitle .thinking::before { content: '· '; }
|
|
57
|
+
#setup { margin: .75rem 0 .5rem; }
|
|
58
|
+
#setup-toggle { display: flex; align-items: center; gap: .6rem; width: 100%; text-align: left; }
|
|
59
|
+
#setup-toggle .setup-text { flex: 1; min-width: 0; }
|
|
60
|
+
#setup-summary { display: block; font-weight: 600; overflow-wrap: anywhere; }
|
|
61
|
+
#setup-summary .thinking { display: block; font-size: .9rem; font-weight: 400; color: #a3b1c4; }
|
|
62
|
+
#setup-toggle .change { flex: none; font-size: .9rem; font-weight: 600; color: #b7d3ff; }
|
|
63
|
+
#setup-panel { margin-top: .4rem; padding: .4rem .6rem .6rem; background: #181f29; border: 1px solid #34527a; border-radius: .65rem; }
|
|
64
|
+
#setup-panel h3 { margin: .3rem 0 .4rem; }
|
|
65
|
+
/* While picking, the panel fills the screen and only the model list scrolls, so the
|
|
66
|
+
summary, thinking pills and Done stay in view. */
|
|
67
|
+
#project:has(#setup-panel:not([hidden])) { height: 100%; display: flex; flex-direction: column; }
|
|
68
|
+
#project:has(#setup-panel:not([hidden])) > :not(#setup) { display: none; }
|
|
69
|
+
#setup:has(#setup-panel:not([hidden])), #setup-panel { flex: 0 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
|
70
|
+
#model-list { flex: 0 1 auto; min-height: 6rem; overflow-y: auto; overscroll-behavior: contain; }
|
|
71
|
+
button.choice { position: relative; display: block; width: 100%; margin-bottom: .35rem; padding-right: 2.6rem; text-align: left; overflow-wrap: anywhere; background: #10151c; border-color: #2c3a4d; }
|
|
72
|
+
button.choice[aria-checked="true"] { background: #1e3350; border-color: #b7d3ff; }
|
|
73
|
+
button.choice[aria-checked="true"]::after { content: '✓'; position: absolute; right: .85rem; top: 50%; transform: translateY(-50%); font-weight: 700; color: #b7d3ff; }
|
|
74
|
+
#thinking { display: flex; flex-wrap: wrap; gap: .4rem; }
|
|
75
|
+
button.pill { min-width: 44px; padding: .45rem .9rem; border-radius: 999px; background: #222c3a; color: #edf1f7; }
|
|
76
|
+
button.pill[aria-checked="true"] { background: #b7d3ff; color: #10213c; border-color: #b7d3ff; font-weight: 600; }
|
|
77
|
+
#setup-done, #start { width: 100%; }
|
|
78
|
+
#setup-toggle, #setup-done { flex: none; }
|
|
79
|
+
#setup-done { margin-top: .75rem; }
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import net from 'node:net';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import { Writable } from 'node:stream';
|
|
7
|
+
import {
|
|
8
|
+
DEFAULT_PORT, MIN_PASSWORD_LENGTH, configPath, createConfig, hashCredentials, loadConfig, localOrigin, saveConfig,
|
|
9
|
+
validateRemoteOrigin,
|
|
10
|
+
} from './config.mjs';
|
|
11
|
+
import { listInChild } from './list-sessions.mjs';
|
|
12
|
+
import { discoverPi } from './pi-install.mjs';
|
|
13
|
+
import { discoverProjects } from './projects.mjs';
|
|
14
|
+
import { createServer } from './server.mjs';
|
|
15
|
+
import { createSessions } from './sessions.mjs';
|
|
16
|
+
|
|
17
|
+
const USAGE = `Usage: pi-remote-web [options]
|
|
18
|
+
|
|
19
|
+
Starts a private web app on 127.0.0.1 for your Pi sessions. The first run asks for a
|
|
20
|
+
project root and a username and password.
|
|
21
|
+
|
|
22
|
+
Options:
|
|
23
|
+
--root <dir> Use this folder and its direct subfolders as projects
|
|
24
|
+
--remote-origin <url> Allow this exact HTTPS address, e.g. https://mac.tailnet.ts.net
|
|
25
|
+
--local-only Remove the remote address
|
|
26
|
+
--port <n> Listen on this port (default ${DEFAULT_PORT})
|
|
27
|
+
--change-password Replace the username and password
|
|
28
|
+
--pi-dir <dir> Use this Pi install (the @earendil-works/pi-coding-agent folder)
|
|
29
|
+
--help Show this help
|
|
30
|
+
|
|
31
|
+
Remote prompts run with all of Pi's tool permissions. This is not a sandbox.`;
|
|
32
|
+
|
|
33
|
+
const VALUE_OPTIONS = { '--root': 'root', '--remote-origin': 'remoteOrigin', '--port': 'port', '--pi-dir': 'piDir' };
|
|
34
|
+
const FLAG_OPTIONS = { '--local-only': 'localOnly', '--change-password': 'changePassword', '--help': 'help' };
|
|
35
|
+
|
|
36
|
+
export function parseArgs(args) {
|
|
37
|
+
const options = {};
|
|
38
|
+
for (let i = 0; i < args.length; i++) {
|
|
39
|
+
const arg = args[i];
|
|
40
|
+
if (FLAG_OPTIONS[arg]) options[FLAG_OPTIONS[arg]] = true;
|
|
41
|
+
else if (VALUE_OPTIONS[arg]) {
|
|
42
|
+
const key = VALUE_OPTIONS[arg];
|
|
43
|
+
if (options[key] !== undefined || args[i + 1] === undefined || args[i + 1].startsWith('--')) throw new Error(`Expected one value for ${arg}`);
|
|
44
|
+
options[key] = args[++i];
|
|
45
|
+
} else throw new Error(`Unknown option: ${arg}. Run with --help.`);
|
|
46
|
+
}
|
|
47
|
+
if (options.port !== undefined) {
|
|
48
|
+
const port = Number(options.port);
|
|
49
|
+
if (!/^\d+$/.test(options.port) || port < 1 || port > 65535) throw new Error('--port must be 1–65535');
|
|
50
|
+
options.port = port;
|
|
51
|
+
}
|
|
52
|
+
if (options.remoteOrigin !== undefined) validateRemoteOrigin(options.remoteOrigin);
|
|
53
|
+
if (options.remoteOrigin !== undefined && options.localOnly) throw new Error('Use --remote-origin or --local-only, not both');
|
|
54
|
+
return options;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function expandDirectory(value, home = homedir()) {
|
|
58
|
+
const expanded = value === '~' ? home : value.startsWith('~/') ? join(home, value.slice(2)) : resolve(value);
|
|
59
|
+
const path = realpathSync(expanded);
|
|
60
|
+
if (!statSync(path).isDirectory()) throw new Error('Project root must be a directory');
|
|
61
|
+
return path;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Creates or updates the config. Every change is explicit; a failure leaves the file unchanged.
|
|
65
|
+
export async function prepare(options, { path = configPath(), prompts, home = homedir(), cwd = process.cwd(), discover = discoverPi } = {}) {
|
|
66
|
+
if (!existsSync(path)) {
|
|
67
|
+
const root = expandDirectory(options.root ?? await prompts.root(cwd), home);
|
|
68
|
+
const pi = discover({ piDir: options.piDir, home });
|
|
69
|
+
const { username, password } = await prompts.credentials();
|
|
70
|
+
return createConfig(path, { username, password, root, pi, port: options.port, remoteOrigin: options.remoteOrigin });
|
|
71
|
+
}
|
|
72
|
+
const existing = loadConfig(path);
|
|
73
|
+
const next = { ...existing };
|
|
74
|
+
if (options.root) next.root = expandDirectory(options.root, home);
|
|
75
|
+
if (options.piDir || !existsSync(existing.pi.cliPath) || !existsSync(existing.pi.sdkPath)) {
|
|
76
|
+
next.pi = discover({ piDir: options.piDir, home });
|
|
77
|
+
}
|
|
78
|
+
if (options.port) next.port = options.port;
|
|
79
|
+
if (options.remoteOrigin) next.remoteOrigin = options.remoteOrigin;
|
|
80
|
+
if (options.localOnly) delete next.remoteOrigin;
|
|
81
|
+
if (options.changePassword) {
|
|
82
|
+
const { username, password } = await prompts.credentials();
|
|
83
|
+
next.credentials = hashCredentials(username, password);
|
|
84
|
+
}
|
|
85
|
+
return JSON.stringify(next) === JSON.stringify(existing) ? existing : saveConfig(path, next);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function ask(rl, question, options) {
|
|
89
|
+
let onClose;
|
|
90
|
+
const closed = new Promise((_, reject) => {
|
|
91
|
+
onClose = () => reject(new Error('Input closed before setup finished. Run again in an interactive terminal.'));
|
|
92
|
+
rl.once('close', onClose);
|
|
93
|
+
});
|
|
94
|
+
try { return await Promise.race([rl.question(question, options), closed]); } finally { rl.removeListener('close', onClose); }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function requireTerminal() {
|
|
98
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) throw new Error('Setup needs an interactive terminal');
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const terminalPrompts = {
|
|
102
|
+
async root(defaultRoot) {
|
|
103
|
+
requireTerminal();
|
|
104
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, historySize: 0 });
|
|
105
|
+
try { return (await ask(rl, `Project root [${defaultRoot}]: `)).trim() || defaultRoot; } finally { rl.close(); }
|
|
106
|
+
},
|
|
107
|
+
// Passwords are never accepted as arguments, so they stay out of shell history.
|
|
108
|
+
async credentials() {
|
|
109
|
+
requireTerminal();
|
|
110
|
+
let hidden = false;
|
|
111
|
+
const output = new Writable({ write(chunk, encoding, done) { if (!hidden) process.stdout.write(chunk, encoding); done(); } });
|
|
112
|
+
const rl = createInterface({ input: process.stdin, output, terminal: true, historySize: 0 });
|
|
113
|
+
const abort = new AbortController();
|
|
114
|
+
rl.on('SIGINT', () => abort.abort());
|
|
115
|
+
try {
|
|
116
|
+
const username = await ask(rl, 'Username: ', { signal: abort.signal });
|
|
117
|
+
process.stdout.write(`Password (hidden, at least ${MIN_PASSWORD_LENGTH} characters): `);
|
|
118
|
+
hidden = true;
|
|
119
|
+
const password = await ask(rl, '', { signal: abort.signal });
|
|
120
|
+
process.stdout.write('\nConfirm password: ');
|
|
121
|
+
const confirmation = await ask(rl, '', { signal: abort.signal });
|
|
122
|
+
if (password !== confirmation) throw new Error('Passwords do not match');
|
|
123
|
+
return { username, password };
|
|
124
|
+
} finally { rl.close(); process.stdout.write('\n'); }
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
function portInUse(port) {
|
|
129
|
+
return new Promise(resolvePort => {
|
|
130
|
+
const socket = net.connect({ host: '127.0.0.1', port });
|
|
131
|
+
socket.once('connect', () => { socket.destroy(); resolvePort(true); });
|
|
132
|
+
socket.once('error', () => { socket.destroy(); resolvePort(false); });
|
|
133
|
+
socket.setTimeout(1000, () => { socket.destroy(); resolvePort(true); });
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function start(config) {
|
|
138
|
+
const projects = discoverProjects(config.root);
|
|
139
|
+
const sessions = createSessions({
|
|
140
|
+
projects, cliPath: config.pi.cliPath,
|
|
141
|
+
listSessions: (cwd, signal) => listInChild('sessions', config.pi.sdkPath, cwd, signal),
|
|
142
|
+
listModels: (cwd, signal) => listInChild('models', config.pi.sdkPath, cwd, signal),
|
|
143
|
+
});
|
|
144
|
+
const app = createServer(config, { sessions });
|
|
145
|
+
await new Promise((resolveListen, reject) => {
|
|
146
|
+
app.server.once('error', reject);
|
|
147
|
+
app.server.listen(config.port, '127.0.0.1', resolveListen);
|
|
148
|
+
});
|
|
149
|
+
return { app, projects };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// A running service holds the saved port. On the first run only the chosen port matters.
|
|
153
|
+
export const portsToCheck = (savedPort, chosenPort) =>
|
|
154
|
+
[...new Set([savedPort, chosenPort ?? savedPort ?? DEFAULT_PORT].filter(Boolean))];
|
|
155
|
+
|
|
156
|
+
export async function main(args = process.argv.slice(2)) {
|
|
157
|
+
const options = parseArgs(args);
|
|
158
|
+
if (options.help) { console.log(USAGE); return; }
|
|
159
|
+
const path = configPath();
|
|
160
|
+
const savedPort = existsSync(path) ? loadConfig(path).port : undefined;
|
|
161
|
+
for (const port of portsToCheck(savedPort, options.port)) {
|
|
162
|
+
if (await portInUse(port)) throw new Error(`Port ${port} is in use. Stop the running service before you start or change settings.`);
|
|
163
|
+
}
|
|
164
|
+
const config = await prepare(options, { path, prompts: terminalPrompts });
|
|
165
|
+
const { app, projects } = await start(config);
|
|
166
|
+
console.log(`pi-remote-web is running. Remote prompts have all of Pi's tool permissions.`);
|
|
167
|
+
console.log(` This computer: ${localOrigin(config.port)}`);
|
|
168
|
+
if (config.remoteOrigin) {
|
|
169
|
+
console.log(` Remote: ${config.remoteOrigin}`);
|
|
170
|
+
console.log(' Keep the remote address private: use Tailscale Serve, never Funnel or a public tunnel.');
|
|
171
|
+
if (!new URL(config.remoteOrigin).hostname.endsWith('.ts.net')) {
|
|
172
|
+
console.log(' Warning: this is not a Tailscale address. Make sure only your own devices can reach it.');
|
|
173
|
+
}
|
|
174
|
+
} else {
|
|
175
|
+
console.log(' Remote: off (see --remote-origin)');
|
|
176
|
+
}
|
|
177
|
+
console.log(` Projects: ${projects.length} under ${config.root} (restart to see new folders)`);
|
|
178
|
+
console.log('Press Ctrl+C to stop. This also stops conversations started from the browser.');
|
|
179
|
+
const stop = () => { app.close().catch(() => { process.exitCode = 1; }); };
|
|
180
|
+
process.once('SIGINT', stop);
|
|
181
|
+
process.once('SIGTERM', stop);
|
|
182
|
+
return app;
|
|
183
|
+
}
|
package/src/commands.mjs
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { LIMITS, hasOnly, isFilled } from './util.mjs';
|
|
2
|
+
|
|
3
|
+
export function validCommand(c) {
|
|
4
|
+
const only = (...fields) => hasOnly(c, ['sessionId', 'action', ...fields]);
|
|
5
|
+
if (typeof c?.sessionId !== 'string' || !c.sessionId) return false;
|
|
6
|
+
switch (c.action) {
|
|
7
|
+
case 'stop': case 'abort': return only();
|
|
8
|
+
case 'prompt': return only('text', 'mode') && isFilled(c.text, LIMITS.prompt) && ['steer', 'followUp'].includes(c.mode);
|
|
9
|
+
case 'answer':
|
|
10
|
+
return typeof c.dialogId === 'string' && c.dialogId.length > 0 && (
|
|
11
|
+
(only('dialogId', 'confirmed') && typeof c.confirmed === 'boolean') ||
|
|
12
|
+
(only('dialogId', 'value') && typeof c.value === 'string') ||
|
|
13
|
+
(only('dialogId', 'cancelled') && c.cancelled === true));
|
|
14
|
+
default: return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { createHash, randomBytes, scrypt, scryptSync, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { hasOnly, isObject } from './util.mjs';
|
|
7
|
+
|
|
8
|
+
export const DEFAULT_PORT = 8787;
|
|
9
|
+
export const MIN_PASSWORD_LENGTH = 12;
|
|
10
|
+
|
|
11
|
+
const scryptAsync = promisify(scrypt);
|
|
12
|
+
const scryptOptions = { N: 16384, r: 8, p: 1, maxmem: 32 * 1024 * 1024 };
|
|
13
|
+
const CONFIG_KEYS = ['port', 'remoteOrigin', 'credentials', 'agentToken', 'root', 'pi', 'maxProcesses'];
|
|
14
|
+
|
|
15
|
+
const validUsername = value => typeof value === 'string' && /^[A-Za-z0-9_.@-]{1,64}$/.test(value);
|
|
16
|
+
const validPassword = value => typeof value === 'string' && Buffer.byteLength(value) <= 1024 &&
|
|
17
|
+
[...value].length >= MIN_PASSWORD_LENGTH;
|
|
18
|
+
const absolutePath = value => typeof value === 'string' && !value.includes('\0') && isAbsolute(value);
|
|
19
|
+
const scriptPath = value => absolutePath(value) && /\.(?:mjs|cjs|js)$/.test(value);
|
|
20
|
+
|
|
21
|
+
export function configPath() {
|
|
22
|
+
return process.env.PI_REMOTE_WEB_CONFIG || join(homedir(), '.config', 'pi-remote-web', 'config.json');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Browsers leave out the default port, so port 80 has no `:80` in Host or Origin.
|
|
26
|
+
export const localOrigin = port => new URL(`http://127.0.0.1:${port}`).origin;
|
|
27
|
+
|
|
28
|
+
export function hashCredentials(username, password) {
|
|
29
|
+
if (!validUsername(username)) throw new Error('Username must be 1–64 ASCII letters, digits, _, ., @ or -');
|
|
30
|
+
if (!validPassword(password)) {
|
|
31
|
+
throw new Error(`Password must contain at least ${MIN_PASSWORD_LENGTH} characters and be at most 1024 UTF-8 bytes`);
|
|
32
|
+
}
|
|
33
|
+
const salt = randomBytes(16).toString('hex');
|
|
34
|
+
const hash = scryptSync(password, Buffer.from(salt, 'hex'), 32, scryptOptions).toString('hex');
|
|
35
|
+
return { username, algorithm: 'scrypt', salt, hash };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function verifyCredentials(credentials, username, password) {
|
|
39
|
+
if (!validUsername(username) || !validPassword(password)) return false;
|
|
40
|
+
const hash = await scryptAsync(password, Buffer.from(credentials.salt, 'hex'), 32, scryptOptions);
|
|
41
|
+
const digest = value => createHash('sha256').update(value).digest();
|
|
42
|
+
const usernameMatches = timingSafeEqual(digest(username), digest(credentials.username));
|
|
43
|
+
const passwordMatches = timingSafeEqual(hash, Buffer.from(credentials.hash, 'hex'));
|
|
44
|
+
return usernameMatches && passwordMatches;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The remote origin must be an exact HTTPS origin, such as a Tailscale Serve address.
|
|
48
|
+
export function validateRemoteOrigin(value) {
|
|
49
|
+
let url;
|
|
50
|
+
try { url = new URL(value); } catch { throw new Error('Remote origin must be a URL such as https://machine.tailnet.ts.net'); }
|
|
51
|
+
if (url.protocol !== 'https:' || url.origin !== value || url.username || url.password) {
|
|
52
|
+
throw new Error('Remote origin must be an exact HTTPS origin with no path or trailing slash');
|
|
53
|
+
}
|
|
54
|
+
if (/^\d+(?:\.\d+){3}$/.test(url.hostname) || url.hostname.startsWith('[')) {
|
|
55
|
+
throw new Error('Remote origin must use a host name, not an IP address');
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function validateConfig(config) {
|
|
61
|
+
if (!hasOnly(config, CONFIG_KEYS)) throw new Error('Unknown config field');
|
|
62
|
+
if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) throw new Error('Invalid port');
|
|
63
|
+
if (config.remoteOrigin !== undefined) validateRemoteOrigin(config.remoteOrigin);
|
|
64
|
+
const c = config.credentials;
|
|
65
|
+
if (!hasOnly(c, ['username', 'algorithm', 'salt', 'hash']) || !validUsername(c.username) || c.algorithm !== 'scrypt' ||
|
|
66
|
+
!/^[a-f0-9]{32}$/.test(c.salt ?? '') || !/^[a-f0-9]{64}$/.test(c.hash ?? '')) throw new Error('Invalid credentials');
|
|
67
|
+
if (!absolutePath(config.root)) throw new Error('Project root must be an absolute path');
|
|
68
|
+
if (!isObject(config.pi) || !hasOnly(config.pi, ['cliPath', 'sdkPath']) ||
|
|
69
|
+
!scriptPath(config.pi.cliPath) || !scriptPath(config.pi.sdkPath)) throw new Error('Invalid Pi install paths');
|
|
70
|
+
const { agentToken, maxProcesses, ...current } = config;
|
|
71
|
+
return current;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function loadConfig(path = configPath()) {
|
|
75
|
+
if (process.platform !== 'win32' && (statSync(path).mode & 0o077) !== 0) throw new Error('Config file permissions must be 0600');
|
|
76
|
+
return validateConfig(JSON.parse(readFileSync(path, 'utf8')));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createConfig(path, { username, password, root, pi, port = DEFAULT_PORT, remoteOrigin }) {
|
|
80
|
+
const config = validateConfig({
|
|
81
|
+
port, ...(remoteOrigin ? { remoteOrigin } : {}),
|
|
82
|
+
credentials: hashCredentials(username, password),
|
|
83
|
+
root, pi,
|
|
84
|
+
});
|
|
85
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
86
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
87
|
+
return config;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Validates first, then replaces the file atomically, so a bad change leaves it untouched.
|
|
91
|
+
export function saveConfig(path, config) {
|
|
92
|
+
config = validateConfig(config);
|
|
93
|
+
const temporary = `${path}.${randomBytes(8).toString('hex')}.tmp`;
|
|
94
|
+
try {
|
|
95
|
+
writeFileSync(temporary, `${JSON.stringify(config, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
|
|
96
|
+
renameSync(temporary, path);
|
|
97
|
+
} finally {
|
|
98
|
+
try { unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
99
|
+
}
|
|
100
|
+
return config;
|
|
101
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { promptLabel } from './util.mjs';
|
|
5
|
+
|
|
6
|
+
// Run by listInChild in its own process, in the project folder:
|
|
7
|
+
// node list-child.mjs <sdkPath> <cwd> sessions|models. Only metadata is written, as the
|
|
8
|
+
// last line of output, after anything an extension printed.
|
|
9
|
+
const [sdkPath, cwd, mode] = process.argv.slice(2);
|
|
10
|
+
const sdk = await import(pathToFileURL(sdkPath).href);
|
|
11
|
+
const write = value => process.stdout.write(`\n${JSON.stringify(value)}`, () => process.exit(0));
|
|
12
|
+
|
|
13
|
+
// The thinking levels Pi offers for a model (docs/models.md, "Map thinking levels"): none
|
|
14
|
+
// without reasoning; `null` in thinkingLevelMap hides a level; xhigh and max need a string.
|
|
15
|
+
const LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
16
|
+
const levels = model => model.reasoning ? LEVELS.filter(level => {
|
|
17
|
+
const mapped = model.thinkingLevelMap?.[level];
|
|
18
|
+
return mapped !== null && (!['xhigh', 'max'].includes(level) || mapped !== undefined);
|
|
19
|
+
}) : [];
|
|
20
|
+
|
|
21
|
+
if (mode === 'models') {
|
|
22
|
+
// Models with usable auth, as in Pi's /model picker. A session loads the extensions,
|
|
23
|
+
// which can add providers. Defaults come from Pi's settings for this folder.
|
|
24
|
+
const modelRuntime = await sdk.ModelRuntime.create();
|
|
25
|
+
const { session } = await sdk.createAgentSession({ cwd, modelRuntime, sessionManager: sdk.SessionManager.inMemory() });
|
|
26
|
+
const available = await modelRuntime.getAvailable();
|
|
27
|
+
session.dispose();
|
|
28
|
+
await modelRuntime.settleCredentialWrites();
|
|
29
|
+
const settings = sdk.SettingsManager.create(cwd);
|
|
30
|
+
const models = available.slice(0, 500).map(m => ({ provider: String(m.provider), id: String(m.id),
|
|
31
|
+
name: String(m.name || m.id), levels: levels(m) }))
|
|
32
|
+
.sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name));
|
|
33
|
+
write({ models, defaults: { provider: settings.getDefaultProvider() ?? '', id: settings.getDefaultModel() ?? '',
|
|
34
|
+
thinking: settings.getDefaultThinkingLevel() ?? 'medium' } });
|
|
35
|
+
} else {
|
|
36
|
+
// The same session folder the Pi CLI uses without --session-dir: the environment variable,
|
|
37
|
+
// then the `sessionDir` setting (relative to the project folder), then Pi's default.
|
|
38
|
+
const fromEnv = process.env.PI_CODING_AGENT_SESSION_DIR;
|
|
39
|
+
const sessionDir = fromEnv ? fromEnv.replace(/^~(?=$|\/)/, homedir()) : sdk.SettingsManager.create(cwd).getSessionDir();
|
|
40
|
+
// Pi returns sessions newest first.
|
|
41
|
+
const sessions = await sdk.SessionManager.list(cwd, sessionDir);
|
|
42
|
+
// Pi joins a relative session folder to each file name unchanged; Pi itself reads it from
|
|
43
|
+
// the project folder, so resolve it there.
|
|
44
|
+
write(sessions.slice(0, 500).map(({ path, cwd: sessionCwd, name, firstMessage, modified }) =>
|
|
45
|
+
({ path: path ? resolve(cwd, String(path)) : '', cwd: String(sessionCwd ?? ''), name: String(name ?? ''),
|
|
46
|
+
firstMessage: promptLabel(firstMessage), modified })));
|
|
47
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { OperationError } from './util.mjs';
|
|
4
|
+
|
|
5
|
+
const HELPER = fileURLToPath(new URL('./list-child.mjs', import.meta.url));
|
|
6
|
+
const WHAT = { sessions: 'previous conversations', models: 'models' };
|
|
7
|
+
|
|
8
|
+
// Pi's session listing reads the text of every session in a project, and its model listing
|
|
9
|
+
// loads the user's extensions. Each runs in a child process with its own heap limit, is
|
|
10
|
+
// killed at the deadline, and sends back only metadata, so a project cannot exhaust the service.
|
|
11
|
+
export function listInChild(mode, sdkPath, cwd, signal) {
|
|
12
|
+
return new Promise((resolve, reject) => {
|
|
13
|
+
const child = spawn(process.execPath, ['--max-old-space-size=256', HELPER, sdkPath, cwd, mode],
|
|
14
|
+
{ cwd, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
15
|
+
let output = '', done = false;
|
|
16
|
+
const finish = (error, value) => {
|
|
17
|
+
if (done) return;
|
|
18
|
+
done = true;
|
|
19
|
+
signal?.removeEventListener('abort', timeout);
|
|
20
|
+
if (child.exitCode === null) child.kill('SIGKILL');
|
|
21
|
+
error ? reject(new OperationError(error)) : resolve(value);
|
|
22
|
+
};
|
|
23
|
+
const failed = () => finish(`Could not read ${WHAT[mode]}`);
|
|
24
|
+
const timeout = () => finish(`Reading ${WHAT[mode]} took too long`);
|
|
25
|
+
if (signal?.aborted) return timeout();
|
|
26
|
+
signal?.addEventListener('abort', timeout, { once: true });
|
|
27
|
+
child.stdout.setEncoding('utf8');
|
|
28
|
+
child.stdout.on('data', chunk => { output += chunk; });
|
|
29
|
+
child.on('error', failed);
|
|
30
|
+
child.on('close', code => {
|
|
31
|
+
if (code !== 0) return failed();
|
|
32
|
+
try { finish(null, JSON.parse(output.slice(output.lastIndexOf('\n') + 1))); } catch { failed(); }
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const PACKAGE = '@earendil-works/pi-coding-agent';
|
|
7
|
+
|
|
8
|
+
// Finds the Pi CLI and SDK entry points. Order: an explicit directory, the Pi installer's
|
|
9
|
+
// current release, then a normally resolvable package.
|
|
10
|
+
export function discoverPi({ piDir, env = process.env, home = homedir() } = {}) {
|
|
11
|
+
const candidates = [];
|
|
12
|
+
if (piDir) candidates.push(resolve(piDir));
|
|
13
|
+
else {
|
|
14
|
+
const install = env.PI_MANAGED_INSTALL_ROOT || join(home, '.pi', 'agent', 'install');
|
|
15
|
+
try {
|
|
16
|
+
const version = readFileSync(join(install, 'current-version'), 'utf8').trim();
|
|
17
|
+
if (/^[A-Za-z0-9_+.-]+$/.test(version) && version !== '.' && version !== '..') {
|
|
18
|
+
candidates.push(join(install, 'releases', version, 'node_modules', PACKAGE));
|
|
19
|
+
}
|
|
20
|
+
} catch { /* Try a normally resolvable package next. */ }
|
|
21
|
+
try { candidates.push(resolve(dirname(createRequire(import.meta.url).resolve(PACKAGE)), '..')); } catch { /* Not installed. */ }
|
|
22
|
+
}
|
|
23
|
+
for (const directory of candidates) {
|
|
24
|
+
try {
|
|
25
|
+
const metadata = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'));
|
|
26
|
+
if (metadata.name !== PACKAGE) continue;
|
|
27
|
+
const cliPath = realpathSync(join(directory, 'dist', 'cli.js'));
|
|
28
|
+
const sdkPath = realpathSync(join(directory, 'dist', 'index.js'));
|
|
29
|
+
if (statSync(cliPath).isFile() && statSync(sdkPath).isFile()) return { cliPath, sdkPath };
|
|
30
|
+
} catch { /* Try the next candidate. */ }
|
|
31
|
+
}
|
|
32
|
+
throw new Error(`Cannot find Pi. Pass --pi-dir /absolute/path/to/${PACKAGE}`);
|
|
33
|
+
}
|
package/src/projects.mjs
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readdirSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export function discoverProjects(rootPath) {
|
|
6
|
+
const root = realpathSync(rootPath);
|
|
7
|
+
const folders = readdirSync(root, { withFileTypes: true })
|
|
8
|
+
.filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))
|
|
9
|
+
.map(entry => join(root, entry.name)).sort();
|
|
10
|
+
return [root, ...folders].map(cwd => ({
|
|
11
|
+
id: `p_${createHash('sha256').update(cwd).digest('hex').slice(0, 32)}`,
|
|
12
|
+
name: basename(cwd) || cwd, cwd,
|
|
13
|
+
}));
|
|
14
|
+
}
|
package/src/server.mjs
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import http from 'node:http';
|
|
4
|
+
import { validCommand } from './commands.mjs';
|
|
5
|
+
import { localOrigin, validateConfig, verifyCredentials } from './config.mjs';
|
|
6
|
+
import { OperationError, hasOnly, isText, isUuid } from './util.mjs';
|
|
7
|
+
|
|
8
|
+
const COOKIE = 'pi_remote_web';
|
|
9
|
+
const ASSETS = new Map([
|
|
10
|
+
['/', ['index.html', 'text/html; charset=utf-8']],
|
|
11
|
+
['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
|
|
12
|
+
['/style.css', ['style.css', 'text/css; charset=utf-8']],
|
|
13
|
+
['/manifest.webmanifest', ['manifest.webmanifest', 'application/manifest+json']],
|
|
14
|
+
['/icon.svg', ['icon.svg', 'image/svg+xml']],
|
|
15
|
+
]);
|
|
16
|
+
const HEADERS = {
|
|
17
|
+
'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
|
|
18
|
+
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self'; " +
|
|
19
|
+
"manifest-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
|
|
20
|
+
};
|
|
21
|
+
const invalid = () => new OperationError('Invalid request', 400);
|
|
22
|
+
async function body(req) {
|
|
23
|
+
if (!/^application\/json(?:\s*;.*)?$/i.test(req.headers['content-type'] ?? '')) throw invalid();
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let size = 0;
|
|
26
|
+
for await (const chunk of req) {
|
|
27
|
+
size += chunk.length;
|
|
28
|
+
if (size > 65536) throw invalid();
|
|
29
|
+
chunks.push(chunk);
|
|
30
|
+
}
|
|
31
|
+
try { return JSON.parse(Buffer.concat(chunks)); } catch { throw invalid(); }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createServer(config, { sessions }) {
|
|
35
|
+
validateConfig(config);
|
|
36
|
+
const origins = new Map([localOrigin(config.port), config.remoteOrigin].filter(Boolean).map(o => [new URL(o).host, o]));
|
|
37
|
+
const cookies = new Map();
|
|
38
|
+
let attempts = [];
|
|
39
|
+
const server = http.createServer(async (req, res) => {
|
|
40
|
+
const reply = (data, status = 200) => res.writeHead(status, { ...HEADERS, 'Content-Type': 'application/json' }).end(JSON.stringify(data));
|
|
41
|
+
try {
|
|
42
|
+
const origin = origins.get(req.headers.host);
|
|
43
|
+
if (!origin) throw new OperationError('Invalid Host', 403);
|
|
44
|
+
if ((req.method !== 'GET' || req.headers.origin !== undefined) && req.headers.origin !== origin) throw new OperationError('Invalid Origin', 403);
|
|
45
|
+
if (req.method === 'GET' && ASSETS.has(req.url)) {
|
|
46
|
+
const [file, type] = ASSETS.get(req.url);
|
|
47
|
+
const content = await readFile(new URL(`../public/${file}`, import.meta.url));
|
|
48
|
+
return res.writeHead(200, { ...HEADERS, 'Content-Type': type }).end(content);
|
|
49
|
+
}
|
|
50
|
+
const id = (req.headers.cookie ?? '').split(';').map(c => c.trim()).find(c => c.startsWith(`${COOKIE}=`))?.slice(COOKIE.length + 1);
|
|
51
|
+
const setCookie = (value, age) => res.setHeader('Set-Cookie', `${COOKIE}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${age}${origin.startsWith('https:') ? '; Secure' : ''}`);
|
|
52
|
+
const route = `${req.method} ${req.url}`;
|
|
53
|
+
if (route === 'POST /api/login') {
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
attempts = attempts.filter(t => now - t < 60000);
|
|
56
|
+
if (attempts.length >= 10) throw new OperationError('Too many sign-in attempts; wait a minute', 429);
|
|
57
|
+
attempts.push(now);
|
|
58
|
+
const input = await body(req);
|
|
59
|
+
if (!await verifyCredentials(config.credentials, input?.username, input?.password)) throw new OperationError('Invalid credentials', 401);
|
|
60
|
+
for (const [key, entry] of cookies) if (entry.expires <= now) cookies.delete(key);
|
|
61
|
+
const token = randomBytes(32).toString('base64url');
|
|
62
|
+
cookies.set(token, { origin, expires: now + 8 * 3600000 });
|
|
63
|
+
setCookie(token, 8 * 3600);
|
|
64
|
+
return reply({});
|
|
65
|
+
}
|
|
66
|
+
const cookie = cookies.get(id);
|
|
67
|
+
if (cookie?.origin !== origin || cookie.expires <= Date.now()) throw new OperationError('Sign in required', 401);
|
|
68
|
+
if (route === 'POST /api/logout') {
|
|
69
|
+
if (req.headers['content-length'] !== '0' && (req.headers['content-length'] || req.headers['transfer-encoding'])) await body(req);
|
|
70
|
+
cookies.delete(id); setCookie('', 0); return reply({});
|
|
71
|
+
}
|
|
72
|
+
if (route === 'GET /api/state') return reply({ projects: sessions.listProjects(), sessions: sessions.snapshots() });
|
|
73
|
+
const url = new URL(req.url, origin);
|
|
74
|
+
if (req.method === 'GET' && ['/api/archives', '/api/models'].includes(url.pathname)) {
|
|
75
|
+
if ([...url.searchParams.keys()].join() !== 'projectId') throw invalid();
|
|
76
|
+
const projectId = url.searchParams.get('projectId');
|
|
77
|
+
return reply(url.pathname === '/api/models' ? await sessions.listModels(projectId) : { archives: await sessions.listArchives(projectId) });
|
|
78
|
+
}
|
|
79
|
+
if (route === 'POST /api/sessions') {
|
|
80
|
+
// Start: {projectId, provider?, model?, thinking?}. Resume: {projectId, archiveId} keeps its own model.
|
|
81
|
+
const input = await body(req);
|
|
82
|
+
const choice = ['provider', 'model', 'thinking'];
|
|
83
|
+
if (!hasOnly(input, ['projectId', 'archiveId', ...choice]) || typeof input.projectId !== 'string' ||
|
|
84
|
+
choice.some(key => input[key] !== undefined && (!isText(input[key], 200) || input.archiveId !== undefined)) ||
|
|
85
|
+
(input.archiveId !== undefined && !isUuid(input.archiveId))) throw invalid();
|
|
86
|
+
return reply(await sessions.start(input));
|
|
87
|
+
}
|
|
88
|
+
if (route === 'POST /api/command') {
|
|
89
|
+
const c = await body(req);
|
|
90
|
+
if (!validCommand(c)) throw invalid();
|
|
91
|
+
await sessions.command(c); return reply({});
|
|
92
|
+
}
|
|
93
|
+
throw new OperationError('Not found', 404);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
if (error instanceof OperationError) return reply({ error: error.message }, error.status);
|
|
96
|
+
return reply({ error: 'Request failed' }, 500);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
return { server, close() {
|
|
100
|
+
sessions.close();
|
|
101
|
+
const stopped = new Promise(resolve => server.close(resolve));
|
|
102
|
+
server.closeAllConnections();
|
|
103
|
+
return stopped;
|
|
104
|
+
} };
|
|
105
|
+
}
|