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.
@@ -0,0 +1,238 @@
1
+ import { spawn as spawnProcess } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { realpathSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { LIMITS, OperationError, messageText, promptLabel, transcript, transcriptEntry } from './util.mjs';
6
+
7
+ const MAX_PROCESSES = 4;
8
+ const MAX_LINE = 8 * 1024 * 1024;
9
+ const TIMEOUT = 15000;
10
+ const roles = ['user', 'assistant', 'toolResult'];
11
+ const disconnected = () => new OperationError('Pi disconnected');
12
+
13
+ function sessionPath(cwd, file) {
14
+ const path = resolve(cwd, file);
15
+ try { return realpathSync(path); } catch (error) {
16
+ if (error.code !== 'ENOENT') throw error;
17
+ return path;
18
+ }
19
+ }
20
+
21
+ // Frame bytes before decoding so a partial line cannot grow past the cap.
22
+ function readLines(stream, receive, oversized) {
23
+ let parts = [], size = 0;
24
+ stream.on('data', chunk => {
25
+ for (let start = 0; start < chunk.length;) {
26
+ const newline = chunk.indexOf(10, start);
27
+ const end = newline < 0 ? chunk.length : newline;
28
+ size += end - start;
29
+ if (size <= MAX_LINE) parts.push(chunk.subarray(start, end));
30
+ else parts = [];
31
+ if (newline < 0) break;
32
+ if (size > MAX_LINE) oversized();
33
+ else receive(Buffer.concat(parts, size).toString('utf8'));
34
+ parts = []; size = 0; start = end + 1;
35
+ }
36
+ });
37
+ }
38
+
39
+ function worker(child, project, path, isOpen, onExit) {
40
+ const state = { id: randomUUID(), projectId: project.id, name: 'New conversation', model: '', busy: false, status: 'starting',
41
+ messages: [], live: '', dialogs: [], queued: [] };
42
+ const pending = new Map(), dialogTimers = new Map();
43
+ let stopping = false, failed = null, firstPrompt = '';
44
+ const append = entry => { state.messages = [...state.messages, entry].slice(-LIMITS.messages); };
45
+ function write(record) {
46
+ return new Promise((resolve, reject) => {
47
+ if (stopping) return reject(disconnected());
48
+ child.stdin.write(`${JSON.stringify(record)}\n`, error => error ? reject(disconnected()) : resolve());
49
+ });
50
+ }
51
+ function request(type) {
52
+ const id = randomUUID();
53
+ return new Promise((resolve, reject) => {
54
+ const finish = (error, data) => {
55
+ clearTimeout(timer); pending.delete(id);
56
+ if (error) reject(error); else resolve(data);
57
+ };
58
+ const timer = setTimeout(() => finish(new OperationError('Pi timed out', 504)), TIMEOUT);
59
+ pending.set(id, finish);
60
+ write({ type, id }).catch(finish);
61
+ });
62
+ }
63
+ async function refresh() {
64
+ const info = await request('get_state');
65
+ const m = info.model;
66
+ state.model = m ? promptLabel(`${m.name || m.id}${m.reasoning ? ` · Thinking: ${info.thinkingLevel}` : ''}`) : '';
67
+ if (info.sessionFile) {
68
+ const next = sessionPath(project.cwd, info.sessionFile);
69
+ if (path !== next) {
70
+ if (isOpen(next)) {
71
+ state.status = 'Stopped: this conversation is already open';
72
+ stop();
73
+ throw new OperationError(state.status);
74
+ }
75
+ state.messages = []; firstPrompt = '';
76
+ path = next;
77
+ }
78
+ }
79
+ try {
80
+ const history = await request('get_messages');
81
+ const messages = history.messages.filter(m => roles.includes(m?.role));
82
+ state.messages = transcript(messages);
83
+ firstPrompt = promptLabel(messageText(messages.find(m => m.role === 'user')));
84
+ } catch (error) {
85
+ if (error.status !== 504) throw error;
86
+ // Oversized replies are dropped. Keep message_end events, including newer ones.
87
+ if (!state.messages.some(m => m.text === 'Earlier history unavailable')) {
88
+ append({ role: 'assistant', text: 'Earlier history unavailable' });
89
+ }
90
+ } finally {
91
+ state.name = info.sessionName || firstPrompt || 'New conversation';
92
+ }
93
+ }
94
+ function update() { refresh().catch(() => { if (!stopping) state.status = 'Could not read conversation'; }); }
95
+ function dropDialog(id) {
96
+ clearTimeout(dialogTimers.get(id)); dialogTimers.delete(id);
97
+ state.dialogs = state.dialogs.filter(d => d.id !== id);
98
+ }
99
+ function receive(r) {
100
+ if (stopping) return;
101
+ switch (r.type) {
102
+ case 'response':
103
+ if (r.command === 'prompt') {
104
+ state.status = r.success ? 'ready' : 'Pi rejected the prompt';
105
+ update();
106
+ } else pending.get(r.id)?.(r.success ? null : new OperationError('Pi rejected the request'), r.data);
107
+ break;
108
+ case 'agent_start': state.busy = true; break;
109
+ // A failed reply waits for agent_end: Pi drops it from history when it retries.
110
+ case 'agent_end':
111
+ if (failed && !r.willRetry) append(failed);
112
+ failed = null; break;
113
+ case 'agent_settled': state.busy = false; state.live = ''; update(); break;
114
+ case 'queue_update':
115
+ state.queued = ['steer', 'followUp'].flatMap(mode => (r[mode === 'steer' ? 'steering' : mode] ?? [])
116
+ .map(text => ({ mode, text })));
117
+ break;
118
+ case 'message_update':
119
+ if (r.assistantMessageEvent?.type === 'text_delta') state.live = (state.live + r.assistantMessageEvent.delta).slice(-LIMITS.messageText);
120
+ break;
121
+ case 'message_end': {
122
+ if (!roles.includes(r.message?.role)) break;
123
+ const entry = transcriptEntry(r.message);
124
+ if (r.message.role === 'assistant' && r.message.stopReason === 'error') failed = entry;
125
+ else if (entry) append(entry);
126
+ state.live = ''; break;
127
+ }
128
+ case 'extension_ui_request': {
129
+ const { id, method, options, title, message, placeholder, prefill } = r;
130
+ if (!['select', 'confirm', 'input', 'editor'].includes(method)) break;
131
+ if (typeof id !== 'string' || (method === 'select' && !Array.isArray(options))) break;
132
+ state.dialogs.push({ id, method, options, title, message, placeholder, prefill });
133
+ if (Number.isFinite(r.timeout) && r.timeout > 0) {
134
+ dialogTimers.set(id, setTimeout(() => dropDialog(id), Math.min(r.timeout, 2147483647)));
135
+ }
136
+ break;
137
+ }
138
+ }
139
+ }
140
+ function finish() {
141
+ stopping = true;
142
+ for (const fail of pending.values()) fail(disconnected());
143
+ for (const timer of dialogTimers.values()) clearTimeout(timer);
144
+ }
145
+ function stop() {
146
+ if (stopping) return;
147
+ finish(); child.stdin.end();
148
+ const timer = setTimeout(() => child.kill('SIGKILL'), 1000);
149
+ timer.unref(); child.once('exit', () => clearTimeout(timer));
150
+ }
151
+ readLines(child.stdout, line => { try { receive(JSON.parse(line)); } catch { stop(); } },
152
+ () => append({ role: 'assistant', text: 'Some Pi output was too large to show' }));
153
+ child.stderr.resume();
154
+ child.stdin.on('error', stop);
155
+ child.once('error', () => { finish(); onExit(state.id); });
156
+ child.once('exit', () => { finish(); onExit(state.id); });
157
+
158
+ async function command(c) {
159
+ if (c.action === 'stop') return stop();
160
+ if (c.action === 'abort') { await request('clear_queue'); await request('abort'); return; }
161
+ if (c.action === 'prompt') return write({ type: 'prompt', id: randomUUID(), message: c.text, streamingBehavior: c.mode });
162
+ const dialog = state.dialogs.find(d => d.id === c.dialogId);
163
+ if (!dialog) throw new OperationError('Dialog already answered or closed');
164
+ const response = { type: 'extension_ui_response', id: dialog.id };
165
+ if (c.cancelled) response.cancelled = true;
166
+ else if (dialog.method === 'confirm' && typeof c.confirmed === 'boolean') response.confirmed = c.confirmed;
167
+ else if (dialog.method !== 'confirm' && typeof c.value === 'string' &&
168
+ (dialog.method !== 'select' || dialog.options.includes(c.value))) response.value = c.value;
169
+ else throw new OperationError('Invalid answer');
170
+ let timer;
171
+ try {
172
+ await Promise.race([write(response), new Promise((_, reject) => {
173
+ timer = setTimeout(() => reject(new OperationError('Pi timed out', 504)), TIMEOUT);
174
+ })]);
175
+ dropDialog(dialog.id);
176
+ } finally { clearTimeout(timer); }
177
+ }
178
+ return { state, command, stop, refresh, get path() { return path; }, get stopping() { return stopping; } };
179
+ }
180
+
181
+ export function createSessions({ projects, cliPath, listSessions, listModels, spawn = spawnProcess }) {
182
+ const workers = new Map(), archives = new Map(), catalogs = new Map();
183
+ const isOpen = path => [...workers.values()].some(w => w.path === path);
184
+ function project(id) {
185
+ const found = projects.find(p => p.id === id);
186
+ if (!found) throw new OperationError('Project unavailable');
187
+ return found;
188
+ }
189
+ return {
190
+ listProjects: () => projects.map(({ id, name }) => ({ id, name })),
191
+ snapshots: () => [...workers.values()].filter(w => !w.stopping).map(w => w.state),
192
+ async listArchives(projectId) {
193
+ const cwd = project(projectId).cwd;
194
+ const listed = await listSessions(cwd, AbortSignal.timeout(30000));
195
+ const entries = Array.isArray(listed) ? listed : [];
196
+ const previous = archives.get(projectId) ?? new Map();
197
+ const paths = new Map();
198
+ archives.set(projectId, paths);
199
+ return entries.filter(e => e.cwd === cwd && e.path).map(e => {
200
+ const archiveId = [...previous].find(([, path]) => path === e.path)?.[0] ?? randomUUID();
201
+ paths.set(archiveId, e.path);
202
+ return { archiveId, name: e.name || '', firstMessage: e.firstMessage || '', modified: e.modified };
203
+ });
204
+ },
205
+ // The last listing per project is the only set a new conversation may choose from.
206
+ async listModels(projectId) {
207
+ const list = await listModels(project(projectId).cwd, AbortSignal.timeout(30000));
208
+ catalogs.set(projectId, Array.isArray(list?.models) ? list.models : []);
209
+ return list;
210
+ },
211
+ async start({ projectId, archiveId, provider, model, thinking }) {
212
+ const target = project(projectId);
213
+ const chosen = catalogs.get(projectId)?.find(m => m.provider === provider && m.id === model);
214
+ const levelOk = chosen && (chosen.levels.length ? chosen.levels.includes(thinking) : thinking === undefined);
215
+ if ((provider ?? model ?? thinking) !== undefined && !levelOk) throw new OperationError('Unknown model or thinking level', 400);
216
+ if (workers.size >= MAX_PROCESSES) throw new OperationError('Session limit reached');
217
+ const file = archives.get(projectId)?.get(archiveId);
218
+ if (archiveId && !file) throw new OperationError('Unknown previous conversation');
219
+ const path = file && sessionPath(target.cwd, file);
220
+ if (path && isOpen(path)) throw new OperationError('Session already running');
221
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('PI_SESSION_')));
222
+ const args = [cliPath, '--mode', 'rpc', ...(path ? ['--session', path] : []),
223
+ ...(chosen ? ['--provider', chosen.provider, '--model', chosen.id, ...(thinking ? ['--thinking', thinking] : [])] : [])];
224
+ const child = spawn(process.execPath, args, { cwd: target.cwd, env, stdio: 'pipe' });
225
+ const w = worker(child, target, path, isOpen, id => workers.delete(id));
226
+ workers.set(w.state.id, w);
227
+ try { await w.refresh(); } catch (error) { w.stop(); throw error; }
228
+ w.state.status = 'ready';
229
+ return { sessionId: w.state.id };
230
+ },
231
+ command(c) {
232
+ const w = workers.get(c.sessionId);
233
+ if (!w || w.stopping) throw new OperationError('Unknown session');
234
+ return w.command(c);
235
+ },
236
+ close() { for (const w of workers.values()) w.stop(); },
237
+ };
238
+ }
package/src/util.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // Small shared validators and limits. Every value from a browser or Pi is untrusted.
2
+
3
+ export const LIMITS = Object.freeze({
4
+ messages: 100,
5
+ messageText: 8000,
6
+ prompt: 16000,
7
+ });
8
+
9
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
+
11
+ export const isUuid = value => typeof value === 'string' && UUID.test(value);
12
+ export const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
13
+ export const hasOnly = (value, keys) => isObject(value) && Object.keys(value).every(key => keys.includes(key));
14
+ export const isText = (value, max) => typeof value === 'string' && value.length <= max;
15
+ export const isFilled = (value, max) => isText(value, max) && value.trim().length > 0;
16
+
17
+ // Only these errors carry text safe to show in the browser.
18
+ export class OperationError extends Error {
19
+ constructor(message, status = 409) { super(message); this.status = status; }
20
+ }
21
+
22
+ // The field that says what a built-in tool call does; other tools show all arguments.
23
+ const TOOL_FIELDS = Object.freeze({ bash: 'command', read: 'path', write: 'path', edit: 'path' });
24
+ const oneLine = value => value.replace(/\s+/g, ' ').trim();
25
+
26
+ // A prompt as a conversation label: one line, at most 100 characters.
27
+ export function promptLabel(text) {
28
+ const line = oneLine(String(text ?? ''));
29
+ return line.length > 100 ? `${line.slice(0, 99)}…` : line;
30
+ }
31
+
32
+ // One line for a tool call: `[Tool: name] summary`. The summary is capped at 300
33
+ // characters and can hold secrets, just like tool output.
34
+ function toolCallText(block) {
35
+ const name = oneLine(String(block?.name)).slice(0, 100);
36
+ const args = block?.arguments;
37
+ const field = Object.hasOwn(TOOL_FIELDS, name) ? TOOL_FIELDS[name] : '';
38
+ let summary = '';
39
+ if (field && isObject(args) && typeof args[field] === 'string') summary = args[field];
40
+ else if (typeof args === 'string') summary = args;
41
+ else if (args !== undefined && !(isObject(args) && Object.keys(args).length === 0)) {
42
+ try { summary = JSON.stringify(args) ?? ''; } catch { summary = ''; }
43
+ }
44
+ summary = oneLine(summary.slice(0, 2000));
45
+ if (summary.length > 300) summary = `${summary.slice(0, 299)}…`;
46
+ return summary ? `[Tool: ${name}] ${summary}` : `[Tool: ${name}]`;
47
+ }
48
+
49
+ // Text projection of a Pi message: no reasoning or image data; tool calls as one line each.
50
+ export function messageText(message) {
51
+ if (!isObject(message)) return '';
52
+ if (typeof message.content === 'string') return message.content.slice(0, LIMITS.messageText);
53
+ if (!Array.isArray(message.content)) return '';
54
+ return message.content.slice(0, 100).map(block => {
55
+ if (block?.type === 'text') return String(block.text ?? '').slice(0, LIMITS.messageText);
56
+ if (block?.type === 'toolCall') return toolCallText(block);
57
+ if (block?.type === 'image') return '[Image omitted]';
58
+ return '';
59
+ }).filter(Boolean).join('\n').slice(0, LIMITS.messageText);
60
+ }
61
+
62
+ // A transcript entry for a Pi message, or null when it has nothing to show, such as an
63
+ // assistant message with only reasoning. A stopped or failed reply with no text gets a
64
+ // fixed note: Pi's own error text is never shown, as it can hold paths.
65
+ export function transcriptEntry(message) {
66
+ const text = messageText(message);
67
+ if (text || message?.role !== 'assistant') return { role: message?.role, text };
68
+ if (message.stopReason === 'aborted') return { role: 'assistant', text: '[Stopped]' };
69
+ if (message.stopReason === 'error') return { role: 'assistant', text: '[Pi reported an error]' };
70
+ return null;
71
+ }
72
+
73
+ // The last LIMITS.messages entries worth showing, read from the end.
74
+ export function transcript(messages) {
75
+ const entries = [];
76
+ for (let i = messages.length - 1; i >= 0 && entries.length < LIMITS.messages; i--) {
77
+ const entry = transcriptEntry(messages[i]);
78
+ if (entry) entries.push(entry);
79
+ }
80
+ return entries.reverse();
81
+ }