agentpen-cli 0.1.2 → 0.1.4
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/README.md +19 -5
- package/cli/agentpen.js +67 -13
- package/cli/claude-share.js +46 -13
- package/cli/codex-app.js +20 -6
- package/cli/handoff.js +44 -28
- package/cli/install.js +128 -8
- package/cli/redact.js +32 -16
- package/package.json +2 -4
- package/server/agents.js +0 -250
- package/server/db.js +0 -161
- package/server/hub.js +0 -637
- package/server/index.js +0 -746
- package/server/notify.js +0 -91
- package/server/search.js +0 -34
- package/web/app.js +0 -518
- package/web/favicon.svg +0 -1
- package/web/index.html +0 -16
- package/web/session.js +0 -460
- package/web/styles.css +0 -263
- package/web/team-page.png +0 -0
package/server/hub.js
DELETED
|
@@ -1,637 +0,0 @@
|
|
|
1
|
-
// Live session hub: pairs one host CLI with any number of browser viewers.
|
|
2
|
-
// The host only ever dials out, so it works behind any corporate firewall.
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import { StringDecoder } from 'node:string_decoder';
|
|
6
|
-
import { q, id as newId, secret, sha, now, audit, RECORDINGS_DIR } from './db.js';
|
|
7
|
-
import { notify, retract, pushSessions, membersOf } from './notify.js';
|
|
8
|
-
import { AgentError, agentFor, ask, decide, sessionContext } from './agents.js';
|
|
9
|
-
import { indexSession } from './search.js';
|
|
10
|
-
|
|
11
|
-
const DRIVE_STEPS = 8; // an invited agent gets this many instructions before it must hand back
|
|
12
|
-
const DRIVE_WAIT_MS = Number(process.env.AGENTPEN_DRIVE_WAIT_MS) || 10 * 60_000;
|
|
13
|
-
const DRIVE_SETTLE_MS = Number(process.env.AGENTPEN_DRIVE_SETTLE_MS) || 3000;
|
|
14
|
-
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
15
|
-
|
|
16
|
-
const REPLAY_BYTES = 512 * 1024;
|
|
17
|
-
const MAX_BUFFERED = 8 * 1024 * 1024;
|
|
18
|
-
const MAX_RECORDING = 30 * 1024 * 1024;
|
|
19
|
-
const RECONNECT_GRACE_MS = Number(process.env.AGENTPEN_RECONNECT_MS) || 45_000;
|
|
20
|
-
const IDLE_MS = 2500;
|
|
21
|
-
// A teammate's stuck agent is the host's problem first; the team hears after this long.
|
|
22
|
-
const ESCALATE_MS = Number(process.env.AGENTPEN_ESCALATE_MS) || 60_000;
|
|
23
|
-
// "Your agent finished" is only worth a ping after a real stretch of work.
|
|
24
|
-
const DONE_MS = Number(process.env.AGENTPEN_DONE_MS) || 20_000;
|
|
25
|
-
const BASE_URL = () => process.env.AGENTPEN_URL || `http://localhost:${process.env.PORT || 4400}`;
|
|
26
|
-
|
|
27
|
-
// Text an agent prints when it has stopped to ask a human something.
|
|
28
|
-
const BLOCKED_RE = /(Do you want to|Would you like to|Do you trust)[^\n]{0,120}\?|❯\s*1\.\s*Yes|\(y\/n\)|\[y\/n\]|Allow (this|command|edit)/i;
|
|
29
|
-
const ANSI_RE = /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(\x07|\x1b\\)|\x1b[@-_]|[\x00-\x08\x0b-\x1f]/g;
|
|
30
|
-
|
|
31
|
-
const live = new Map(); // session id -> LiveSession
|
|
32
|
-
const feeds = new Map(); // workspace id -> Set<ws>
|
|
33
|
-
const feedTimers = new Map();
|
|
34
|
-
|
|
35
|
-
const send = (ws, m) => { if (ws && ws.readyState === 1) ws.send(JSON.stringify(m)); };
|
|
36
|
-
|
|
37
|
-
class LiveSession {
|
|
38
|
-
constructor(row, host, hello) {
|
|
39
|
-
this.id = row.id;
|
|
40
|
-
this.row = row;
|
|
41
|
-
this.host = host; // {id, name}
|
|
42
|
-
this.key = secret();
|
|
43
|
-
this.ws = null;
|
|
44
|
-
this.cols = clamp(hello.cols, 20, 400, 100);
|
|
45
|
-
this.rows = clamp(hello.rows, 5, 200, 30);
|
|
46
|
-
this.viewers = new Map();
|
|
47
|
-
this.nextConn = 1;
|
|
48
|
-
this.chunks = [];
|
|
49
|
-
this.bytes = 0;
|
|
50
|
-
this.chat = [];
|
|
51
|
-
this.state = 'working';
|
|
52
|
-
this.tail = '';
|
|
53
|
-
this.decoder = new StringDecoder('utf8');
|
|
54
|
-
this.idleTimer = null;
|
|
55
|
-
this.graceTimer = null;
|
|
56
|
-
this.lastNotify = 0;
|
|
57
|
-
this.driver = null; // an invited agent holding the wheel: { name, goal, step, max, by }
|
|
58
|
-
this.asking = false;
|
|
59
|
-
this.recBytes = 0;
|
|
60
|
-
this.kind = row.kind;
|
|
61
|
-
// A Claude Code session shared after it started has no terminal to type into. Prompts can
|
|
62
|
-
// reach it only once its host has run /agentpen inside it, which the CLI then reports.
|
|
63
|
-
this.promptable = false;
|
|
64
|
-
this.turns = new Map(); // thread sessions: turn id -> turn
|
|
65
|
-
this.order = [];
|
|
66
|
-
this.rec = null;
|
|
67
|
-
if (this.kind === 'thread') { this.state = 'idle'; return; }
|
|
68
|
-
this.rec = fs.createWriteStream(path.join(RECORDINGS_DIR, `${row.id}.cast`));
|
|
69
|
-
this.rec.on('error', () => { this.rec = null; });
|
|
70
|
-
this.rec.write(JSON.stringify({
|
|
71
|
-
version: 2, width: this.cols, height: this.rows,
|
|
72
|
-
timestamp: Math.floor(row.started_at / 1000), title: row.title,
|
|
73
|
-
}) + '\n');
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
get attached() { return this.kind === 'thread' && this.row.agent === 'claude'; }
|
|
77
|
-
get readOnly() { return this.attached && !this.promptable; }
|
|
78
|
-
|
|
79
|
-
setPromptable(on) {
|
|
80
|
-
if (!this.attached || this.promptable === on) return;
|
|
81
|
-
this.promptable = on;
|
|
82
|
-
for (const v of this.viewers.values()) {
|
|
83
|
-
v.canType = this.canType(v.user);
|
|
84
|
-
send(v.ws, { t: 'caps', prompts: on, canType: v.canType });
|
|
85
|
-
}
|
|
86
|
-
this.peopleChanged();
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
// A Codex app conversation arrives as changed turns plus the full turn order.
|
|
90
|
-
threadUpdate(m) {
|
|
91
|
-
const changed = [];
|
|
92
|
-
for (const raw of (Array.isArray(m.turns) ? m.turns : []).slice(0, MAX_TURNS)) {
|
|
93
|
-
const t = cleanTurn(raw);
|
|
94
|
-
if (!t) continue;
|
|
95
|
-
this.turns.set(t.id, t);
|
|
96
|
-
changed.push(t);
|
|
97
|
-
}
|
|
98
|
-
if (Array.isArray(m.order)) {
|
|
99
|
-
this.order = m.order.filter((id) => this.turns.has(id)).slice(-MAX_TURNS);
|
|
100
|
-
const keep = new Set(this.order);
|
|
101
|
-
for (const id of this.turns.keys()) if (!keep.has(id)) this.turns.delete(id);
|
|
102
|
-
}
|
|
103
|
-
const title = clip(m.title, 80);
|
|
104
|
-
if (title && title !== this.row.title) {
|
|
105
|
-
this.row.title = title;
|
|
106
|
-
q.run(`UPDATE sessions SET title=? WHERE id=?`, title, this.id);
|
|
107
|
-
publish(this.row.workspace_id);
|
|
108
|
-
}
|
|
109
|
-
this.broadcast({ t: 'thread', turns: changed, order: this.order, title: this.row.title });
|
|
110
|
-
this.setState(m.status === 'working' || m.status === 'blocked' ? m.status : 'idle');
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
transcript() {
|
|
114
|
-
return this.order.map((id) => this.turns.get(id));
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
summary() {
|
|
118
|
-
const seen = new Set();
|
|
119
|
-
const people = [];
|
|
120
|
-
for (const v of this.viewers.values()) {
|
|
121
|
-
const k = v.user.id || `g${v.conn}`;
|
|
122
|
-
if (seen.has(k)) continue;
|
|
123
|
-
seen.add(k);
|
|
124
|
-
people.push({ id: v.user.id, name: v.user.name, guest: !!v.user.guest, canType: v.canType });
|
|
125
|
-
}
|
|
126
|
-
const r = this.row;
|
|
127
|
-
return {
|
|
128
|
-
id: r.id, title: r.title, agent: r.agent, project: r.project, branch: r.branch,
|
|
129
|
-
access: r.access, state: this.state, started_at: r.started_at, kind: this.kind, prompts: this.attached ? this.promptable : undefined,
|
|
130
|
-
host: this.host, people,
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// Private means the host alone: not listed, not viewable, not announced.
|
|
135
|
-
visibleTo(userId) {
|
|
136
|
-
return this.row.access !== 'private' || userId === this.row.host_id;
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
canType(user) {
|
|
140
|
-
if (user.guest || this.readOnly) return false;
|
|
141
|
-
return user.id === this.row.host_id || this.row.access === 'control';
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
record(kind, data) {
|
|
145
|
-
if (!this.rec || this.recBytes > MAX_RECORDING) return;
|
|
146
|
-
const line = JSON.stringify([(now() - this.row.started_at) / 1000, kind, data]) + '\n';
|
|
147
|
-
this.recBytes += line.length;
|
|
148
|
-
this.rec.write(line);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
output(buf) {
|
|
152
|
-
this.chunks.push(buf);
|
|
153
|
-
this.bytes += buf.length;
|
|
154
|
-
while (this.bytes > REPLAY_BYTES && this.chunks.length > 1) this.bytes -= this.chunks.shift().length;
|
|
155
|
-
for (const v of this.viewers.values()) {
|
|
156
|
-
if (v.ws.readyState !== 1) continue;
|
|
157
|
-
if (v.ws.bufferedAmount > MAX_BUFFERED) { v.ws.terminate(); continue; }
|
|
158
|
-
v.ws.send(buf, { binary: true });
|
|
159
|
-
}
|
|
160
|
-
const text = this.decoder.write(buf);
|
|
161
|
-
if (text) {
|
|
162
|
-
this.record('o', text);
|
|
163
|
-
this.tail = (this.tail + text.replace(ANSI_RE, '')).slice(-1500);
|
|
164
|
-
}
|
|
165
|
-
this.setState('working');
|
|
166
|
-
clearTimeout(this.idleTimer);
|
|
167
|
-
this.idleTimer = setTimeout(() => {
|
|
168
|
-
// only the last few lines count: an answered question further up is history
|
|
169
|
-
this.setState(BLOCKED_RE.test(this.recentLines(6).join('\n')) ? 'blocked' : 'idle');
|
|
170
|
-
}, IDLE_MS);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
setState(state) {
|
|
174
|
-
if (this.state === state) return;
|
|
175
|
-
const prev = this.state;
|
|
176
|
-
this.state = state;
|
|
177
|
-
this.broadcast({ t: 'state', state });
|
|
178
|
-
publish(this.row.workspace_id);
|
|
179
|
-
if (state === 'working' && prev !== 'working') this.workStart = now();
|
|
180
|
-
if (prev === 'blocked') this.unblocked();
|
|
181
|
-
if (state === 'blocked') { this.notifyBlocked(); this.alertBlocked(); }
|
|
182
|
-
if (state === 'idle' && prev === 'working' && now() - (this.workStart || now()) >= DONE_MS) {
|
|
183
|
-
notify(this.row.host_id, { kind: 'done', title: `${this.agentName()} finished`, body: this.row.title, session: this.id, reply: 'prompt' });
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
agentName() {
|
|
188
|
-
const a = this.row.agent;
|
|
189
|
-
return a === 'claude' ? 'Claude' : a.startsWith('codex') ? 'Codex' : 'Your agent';
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
recentLines(n) {
|
|
193
|
-
return this.tail.split(/[\r\n]+/).map((l) => l.replace(/[│╭╰╮╯─]+/g, ' ').replace(/\s+/g, ' ').trim()).filter(Boolean).slice(-n);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// What the agent is actually asking, so the notification can be answered at a glance.
|
|
197
|
-
question() {
|
|
198
|
-
if (this.kind === 'thread') return this.attached ? 'Waiting for you in your terminal.' : 'Waiting for you to approve or answer in the Codex app.';
|
|
199
|
-
const lines = this.recentLines(6);
|
|
200
|
-
// the question itself reads better than the menu under it ("❯ 1. Yes")
|
|
201
|
-
return (lines.findLast((l) => /\?\s*$|\(y\/n\)/i.test(l)) || lines.findLast((l) => BLOCKED_RE.test(l)) || lines.at(-1) || 'It is waiting for input.').slice(0, 200);
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
alertBlocked() {
|
|
205
|
-
const body = this.question();
|
|
206
|
-
notify(this.row.host_id, { kind: 'needs_you', title: `${this.agentName()} needs you`, body: `${this.row.title}: ${body}`, session: this.id, reply: this.kind === 'terminal' ? 'prompt' : null, urgent: true });
|
|
207
|
-
clearTimeout(this.escalateTimer);
|
|
208
|
-
this.escalateTimer = setTimeout(() => {
|
|
209
|
-
if (this.state !== 'blocked' || !live.has(this.id) || this.row.access === 'private') return;
|
|
210
|
-
this.escalated = membersOf(this.row.workspace_id).filter((u) => u !== this.row.host_id);
|
|
211
|
-
const mins = Math.max(1, Math.round(ESCALATE_MS / 60_000));
|
|
212
|
-
for (const u of this.escalated) {
|
|
213
|
-
notify(u, { kind: 'team_blocked', title: `${this.host.name}'s agent is stuck`, body: `${this.row.title} has been waiting ${mins} min: ${body}`, session: this.id, reply: this.kind === 'terminal' && this.row.access === 'control' ? 'prompt' : null });
|
|
214
|
-
}
|
|
215
|
-
}, ESCALATE_MS);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
unblocked() {
|
|
219
|
-
clearTimeout(this.escalateTimer);
|
|
220
|
-
retract([this.row.host_id, ...(this.escalated || [])], this.id, ['needs_you', 'team_blocked']);
|
|
221
|
-
this.escalated = null;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Chat from anyone in the session; the host is usually in a terminal and would never see it otherwise.
|
|
225
|
-
// ---- invited agents ----
|
|
226
|
-
|
|
227
|
-
agentSay(name, text, extra = {}) {
|
|
228
|
-
const msg = { name, id: null, agent: true, text: String(text).slice(0, 4000), at: now(), ...extra };
|
|
229
|
-
this.chat.push(msg);
|
|
230
|
-
if (this.chat.length > 200) this.chat.shift();
|
|
231
|
-
this.broadcast({ t: 'chat', msg });
|
|
232
|
-
send(this.ws, { t: 'chat', msg });
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/** "@claude is this safe?" in chat: the agent reads the session and answers there. */
|
|
236
|
-
async askAgent(agent, user, question) {
|
|
237
|
-
if (this.asking) return this.agentSay(agent.name, 'One question at a time. I am still reading for the last one.', { error: true });
|
|
238
|
-
this.asking = true;
|
|
239
|
-
this.broadcast({ t: 'agent', name: agent.name, busy: true });
|
|
240
|
-
audit(this.row.workspace_id, 'session.agent', { session: this.id, actor: user, detail: `asked ${agent.name}${question ? `: ${question.slice(0, 200)}` : ''}` });
|
|
241
|
-
try {
|
|
242
|
-
const reply = await ask(agent, this.row.workspace_id, sessionContext({ row: this.row, live: this, hostName: this.host.name }), user.name, question);
|
|
243
|
-
if (live.has(this.id)) this.agentSay(agent.name, reply, { via: user.name });
|
|
244
|
-
} catch (e) {
|
|
245
|
-
if (!(e instanceof AgentError)) console.error(e);
|
|
246
|
-
if (live.has(this.id)) this.agentSay(agent.name, e instanceof AgentError ? e.message : 'Something went wrong while answering.', { error: true });
|
|
247
|
-
} finally {
|
|
248
|
-
this.asking = false;
|
|
249
|
-
this.broadcast({ t: 'agent', name: agent.name, busy: false });
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
driverView() {
|
|
254
|
-
const d = this.driver;
|
|
255
|
-
return d && { name: d.name, goal: d.goal, step: d.step, max: d.max, by: d.by };
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
announceDriver() {
|
|
259
|
-
this.broadcast({ t: 'driver', driver: this.driverView() });
|
|
260
|
-
publish(this.row.workspace_id);
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
/** A person takes the wheel back. */
|
|
264
|
-
stopDriver(why, actor) {
|
|
265
|
-
const d = this.driver;
|
|
266
|
-
if (!d) return;
|
|
267
|
-
d.stopped = true;
|
|
268
|
-
this.driver = null;
|
|
269
|
-
this.announceDriver();
|
|
270
|
-
this.agentSay(d.name, why);
|
|
271
|
-
if (actor) this.activity(actor, 'session.agent', `took the wheel back from ${d.name}`);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// Wait until the host's agent has finished reacting. Never acts while it is asking a human something.
|
|
275
|
-
async settled(d) {
|
|
276
|
-
const deadline = now() + DRIVE_WAIT_MS;
|
|
277
|
-
let told = false;
|
|
278
|
-
await sleep(DRIVE_SETTLE_MS);
|
|
279
|
-
while (!d.stopped && live.has(this.id)) {
|
|
280
|
-
if (this.state === 'idle') return true;
|
|
281
|
-
if (this.state === 'blocked' && !told) {
|
|
282
|
-
told = true;
|
|
283
|
-
this.agentSay(d.name, 'The agent is asking for approval. That is a human decision, so I am waiting for one of you.');
|
|
284
|
-
}
|
|
285
|
-
if (now() > deadline) return false;
|
|
286
|
-
await sleep(250);
|
|
287
|
-
}
|
|
288
|
-
return false;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/** The host hands the wheel to an invited agent for a bounded number of steps. */
|
|
292
|
-
async drive(agent, host, goal) {
|
|
293
|
-
const d = this.driver = { name: agent.name, goal, step: 0, max: DRIVE_STEPS, by: host.name, stopped: false };
|
|
294
|
-
const gone = () => d.stopped || !live.has(this.id);
|
|
295
|
-
const handBack = (text) => {
|
|
296
|
-
if (gone()) return;
|
|
297
|
-
d.stopped = true;
|
|
298
|
-
this.driver = null;
|
|
299
|
-
this.announceDriver();
|
|
300
|
-
this.agentSay(agent.name, text);
|
|
301
|
-
notify(this.row.host_id, { kind: 'done', title: `${agent.name} handed back the wheel`, body: `${this.row.title}: ${text}`.slice(0, 280), session: this.id });
|
|
302
|
-
};
|
|
303
|
-
this.announceDriver();
|
|
304
|
-
this.activity(host, 'session.agent', `handed the wheel to ${agent.name}: ${goal.slice(0, 200)}`);
|
|
305
|
-
this.agentSay(agent.name, `I have the wheel for up to ${DRIVE_STEPS} steps. Goal: ${goal}`, { via: host.name });
|
|
306
|
-
const history = [];
|
|
307
|
-
try {
|
|
308
|
-
for (let step = 1; step <= DRIVE_STEPS; step++) {
|
|
309
|
-
if (!(await this.settled(d))) return handBack('The agent did not settle in time, so I stopped. Over to you.');
|
|
310
|
-
d.step = step;
|
|
311
|
-
this.announceDriver();
|
|
312
|
-
const next = await decide(agent, this.row.workspace_id, sessionContext({ row: this.row, live: this, hostName: this.host.name }), { goal, by: host.name, step, max: DRIVE_STEPS, history });
|
|
313
|
-
if (gone()) return;
|
|
314
|
-
if (next.action !== 'instruct' || !String(next.instruction || '').trim()) return handBack(next.action === 'done' ? `Done. ${next.note}` : `I need a human. ${next.note}`);
|
|
315
|
-
// the screen may have changed while the model was thinking
|
|
316
|
-
if (this.state === 'blocked') return handBack('The agent is waiting on an approval, which is yours to give. Over to you.');
|
|
317
|
-
this.agentSay(agent.name, next.note);
|
|
318
|
-
if (!this.prompt({ id: null, name: `${agent.name} (for ${host.name})` }, next.instruction, true)) return handBack('I could not reach the agent. Over to you.');
|
|
319
|
-
history.push(next.instruction);
|
|
320
|
-
}
|
|
321
|
-
await this.settled(d);
|
|
322
|
-
handBack(`That was my ${DRIVE_STEPS} steps. Over to you.`);
|
|
323
|
-
} catch (e) {
|
|
324
|
-
if (!(e instanceof AgentError)) console.error(e);
|
|
325
|
-
handBack(e instanceof AgentError ? e.message : 'Something went wrong, so I stopped.');
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
say(user, raw) {
|
|
330
|
-
const text = String(raw || '').trim().slice(0, 2000);
|
|
331
|
-
if (!text) return false;
|
|
332
|
-
const invited = agentFor(text);
|
|
333
|
-
if (invited) queueMicrotask(() => this.askAgent(invited, user, text.replace(invited.mention, '').trim()));
|
|
334
|
-
const msg = { name: user.name, id: user.id, text, at: now() };
|
|
335
|
-
this.chat.push(msg);
|
|
336
|
-
if (this.chat.length > 200) this.chat.shift();
|
|
337
|
-
this.broadcast({ t: 'chat', msg });
|
|
338
|
-
send(this.ws, { t: 'chat', msg });
|
|
339
|
-
const watching = new Set([...this.viewers.values()].map((v) => v.user.id));
|
|
340
|
-
if (user.id !== this.row.host_id && !watching.has(this.row.host_id)) {
|
|
341
|
-
notify(this.row.host_id, { kind: 'chat', title: `${user.name} in ${this.row.title}`, body: text, session: this.id, reply: 'chat' });
|
|
342
|
-
}
|
|
343
|
-
return true;
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
// An attributed prompt for the agent. Returns false if it could not be delivered.
|
|
347
|
-
prompt(user, raw, asInvitedAgent = false) {
|
|
348
|
-
if (this.readOnly || (!asInvitedAgent && !this.canType(user)) || this.ws?.readyState !== 1) return false;
|
|
349
|
-
let text;
|
|
350
|
-
if (this.kind === 'thread') {
|
|
351
|
-
// a conversation takes the prompt as a message, queued under the sender's name
|
|
352
|
-
text = String(raw || '').trim().slice(0, 8000);
|
|
353
|
-
if (!text) return false;
|
|
354
|
-
send(this.ws, { t: 'prompt', text, by: user.name, rid: newId(16) });
|
|
355
|
-
} else {
|
|
356
|
-
text = String(raw || '').replace(/\r?\n/g, ' ').trim().slice(0, 8000);
|
|
357
|
-
if (!text) return false;
|
|
358
|
-
// text first, Enter after a beat: agents treat a same-tick "\r" as a pasted newline
|
|
359
|
-
this.ws.send(Buffer.from(text), { binary: true });
|
|
360
|
-
setTimeout(() => { if (this.ws?.readyState === 1) this.ws.send(Buffer.from('\r'), { binary: true }); }, 120);
|
|
361
|
-
}
|
|
362
|
-
this.activity(user, 'session.prompt', text);
|
|
363
|
-
if (user.id !== this.row.host_id && !asInvitedAgent) {
|
|
364
|
-
notify(this.row.host_id, { kind: 'prompt', title: `${user.name} prompted ${this.agentName() === 'Your agent' ? 'your agent' : this.agentName()}`, body: `${this.row.title}: ${text}`, session: this.id });
|
|
365
|
-
}
|
|
366
|
-
return true;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
notifyBlocked() {
|
|
370
|
-
if (now() - this.lastNotify < 60_000 || this.row.access === 'private') return;
|
|
371
|
-
this.lastNotify = now();
|
|
372
|
-
const ws = q.get(`SELECT slack_webhook FROM workspaces WHERE id=?`, this.row.workspace_id);
|
|
373
|
-
if (!ws?.slack_webhook) return;
|
|
374
|
-
const text = `:raised_hand: *${this.host.name}*'s agent is waiting on a human in *${this.row.title}* - <${BASE_URL()}/s/${this.id}|open the session>`;
|
|
375
|
-
fetch(ws.slack_webhook, {
|
|
376
|
-
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }),
|
|
377
|
-
}).catch(() => {});
|
|
378
|
-
}
|
|
379
|
-
|
|
380
|
-
broadcast(m) {
|
|
381
|
-
const s = JSON.stringify(m);
|
|
382
|
-
for (const v of this.viewers.values()) if (v.ws.readyState === 1) v.ws.send(s);
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
peopleChanged() {
|
|
386
|
-
const s = this.summary();
|
|
387
|
-
this.broadcast({ t: 'people', people: s.people });
|
|
388
|
-
send(this.ws, { t: 'people', people: s.people });
|
|
389
|
-
publish(this.row.workspace_id);
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
activity(actor, type, detail) {
|
|
393
|
-
audit(this.row.workspace_id, type, { session: this.id, actor, detail });
|
|
394
|
-
this.broadcast({ t: 'activity', event: { actor: actor?.name, type, detail, at: now() } });
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
setAccess(access, actor) {
|
|
398
|
-
this.row.access = access;
|
|
399
|
-
q.run(`UPDATE sessions SET access=? WHERE id=?`, access, this.id);
|
|
400
|
-
if (access === 'private') {
|
|
401
|
-
// everyone but the host leaves now, guest links die, and the team's alerts about it are taken down
|
|
402
|
-
q.run(`UPDATE sessions SET guest_hash=NULL WHERE id=?`, this.id);
|
|
403
|
-
for (const v of [...this.viewers.values()]) {
|
|
404
|
-
if (v.user.id === this.row.host_id) continue;
|
|
405
|
-
send(v.ws, { t: 'end', reason: `${this.host.name} made this session private` });
|
|
406
|
-
v.ws.close();
|
|
407
|
-
this.viewers.delete(v.conn);
|
|
408
|
-
}
|
|
409
|
-
clearTimeout(this.escalateTimer);
|
|
410
|
-
if (this.escalated) { retract(this.escalated, this.id, ['team_blocked']); this.escalated = null; }
|
|
411
|
-
}
|
|
412
|
-
for (const v of this.viewers.values()) {
|
|
413
|
-
v.canType = this.canType(v.user);
|
|
414
|
-
send(v.ws, { t: 'access', access, canType: v.canType });
|
|
415
|
-
}
|
|
416
|
-
this.activity(actor, 'session.access', access === 'control' ? 'teammates can type' : access === 'view' ? 'watch only' : 'private');
|
|
417
|
-
this.peopleChanged();
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
end(reason = 'ended') {
|
|
421
|
-
if (!live.has(this.id)) return;
|
|
422
|
-
live.delete(this.id);
|
|
423
|
-
clearTimeout(this.idleTimer);
|
|
424
|
-
clearTimeout(this.graceTimer);
|
|
425
|
-
if (this.state === 'blocked') this.unblocked();
|
|
426
|
-
clearTimeout(this.escalateTimer);
|
|
427
|
-
if (this.driver) { this.driver.stopped = true; this.driver = null; }
|
|
428
|
-
let hasRec = this.rec ? 1 : 0;
|
|
429
|
-
// make the session searchable once its recording is fully on disk
|
|
430
|
-
const chat = this.chat.slice();
|
|
431
|
-
const index = () => { try { indexSession(this.id, chat); } catch (e) { console.error('search index failed', e.message); } };
|
|
432
|
-
if (this.rec) this.rec.end(index); else setImmediate(index);
|
|
433
|
-
if (this.kind === 'thread' && this.order.length) {
|
|
434
|
-
try { fs.writeFileSync(path.join(RECORDINGS_DIR, `${this.id}.json`), JSON.stringify({ turns: this.transcript() })); hasRec = 1; } catch {}
|
|
435
|
-
}
|
|
436
|
-
q.run(`UPDATE sessions SET status='ended', ended_at=?, has_recording=?, guest_hash=NULL, end_reason=? WHERE id=?`, now(), hasRec, reason, this.id);
|
|
437
|
-
audit(this.row.workspace_id, 'session.end', { session: this.id, actor: this.host, detail: reason });
|
|
438
|
-
this.broadcast({ t: 'end', reason });
|
|
439
|
-
for (const v of this.viewers.values()) v.ws.close();
|
|
440
|
-
if (this.ws) { send(this.ws, { t: 'end', reason }); this.ws.close(); }
|
|
441
|
-
publish(this.row.workspace_id);
|
|
442
|
-
}
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
const clamp = (v, lo, hi, dflt) => (Number.isFinite(+v) ? Math.min(hi, Math.max(lo, Math.floor(+v))) : dflt);
|
|
446
|
-
const clip = (s, n) => String(s ?? '').replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, n);
|
|
447
|
-
|
|
448
|
-
const MAX_TURNS = 300;
|
|
449
|
-
const ROLES = new Set(['user', 'assistant', 'tool', 'plan']);
|
|
450
|
-
const text = (s, n) => (typeof s === 'string' ? s.slice(0, n) : '');
|
|
451
|
-
// The host is a signed-in member, but what it sends is still rebuilt field by field.
|
|
452
|
-
function cleanTurn(t) {
|
|
453
|
-
if (!t || typeof t.id !== 'string' || !t.id || t.id.length > 100) return null;
|
|
454
|
-
return {
|
|
455
|
-
id: t.id,
|
|
456
|
-
status: ['completed', 'interrupted', 'failed', 'inProgress'].includes(t.status) ? t.status : 'completed',
|
|
457
|
-
error: text(t.error, 500) || undefined,
|
|
458
|
-
items: (Array.isArray(t.items) ? t.items : []).slice(0, 400).filter((i) => i && ROLES.has(i.role)).map((i) => ({
|
|
459
|
-
id: text(i.id, 100), role: i.role, text: text(i.text, 20000), detail: text(i.detail, 4000) || undefined,
|
|
460
|
-
status: text(i.status, 40) || undefined, by: text(i.by, 60) || undefined,
|
|
461
|
-
})),
|
|
462
|
-
};
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// ---- host side -------------------------------------------------------------
|
|
466
|
-
|
|
467
|
-
export function attachHost(ws, user) {
|
|
468
|
-
let s = null;
|
|
469
|
-
ws.on('message', (data, isBinary) => {
|
|
470
|
-
if (isBinary) { if (s && s.ws === ws) s.output(data); return; }
|
|
471
|
-
let m;
|
|
472
|
-
try { m = JSON.parse(data); } catch { return; }
|
|
473
|
-
if (!s) {
|
|
474
|
-
if (m?.t !== 'hello') return ws.close();
|
|
475
|
-
s = m.resume ? resumeHost(ws, user, m) : startHost(ws, user, m);
|
|
476
|
-
return;
|
|
477
|
-
}
|
|
478
|
-
if (s.ws !== ws) return;
|
|
479
|
-
if (m.t === 'resize') {
|
|
480
|
-
s.cols = clamp(m.cols, 20, 400, s.cols);
|
|
481
|
-
s.rows = clamp(m.rows, 5, 200, s.rows);
|
|
482
|
-
s.record('r', `${s.cols}x${s.rows}`);
|
|
483
|
-
s.broadcast({ t: 'resize', cols: s.cols, rows: s.rows });
|
|
484
|
-
} else if (m.t === 'exit') {
|
|
485
|
-
s.end(s.kind === 'thread' ? 'sharing stopped' : 'agent exited');
|
|
486
|
-
} else if (m.t === 'thread' && s.kind === 'thread') {
|
|
487
|
-
s.threadUpdate(m);
|
|
488
|
-
} else if (m.t === 'caps') {
|
|
489
|
-
s.setPromptable(m.prompts === true);
|
|
490
|
-
} else if (m.t === 'prompt-result' && !m.ok) {
|
|
491
|
-
s.broadcast({ t: 'notice', text: `${s.agentName()} did not confirm that prompt. Check with the host before sending it again.` });
|
|
492
|
-
}
|
|
493
|
-
});
|
|
494
|
-
ws.on('close', () => {
|
|
495
|
-
if (!s || s.ws !== ws || !live.has(s.id)) return;
|
|
496
|
-
s.ws = null;
|
|
497
|
-
s.setState('reconnecting');
|
|
498
|
-
s.graceTimer = setTimeout(() => s.end('host disconnected'), RECONNECT_GRACE_MS);
|
|
499
|
-
});
|
|
500
|
-
ws.on('error', () => {});
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
function startHost(ws, user, m) {
|
|
504
|
-
const wsRow = m.workspace
|
|
505
|
-
? q.get(`SELECT w.* FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE m.user_id=? AND (w.slug=? OR w.id=?)`, user.id, m.workspace, m.workspace)
|
|
506
|
-
: q.get(`SELECT w.* FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE m.user_id=? ORDER BY m.created_at LIMIT 1`, user.id);
|
|
507
|
-
if (!wsRow) {
|
|
508
|
-
send(ws, { t: 'error', code: 'no_workspace', message: m.workspace ? `You are not a member of workspace "${m.workspace}".` : 'Create or join a workspace first.' });
|
|
509
|
-
ws.close();
|
|
510
|
-
return null;
|
|
511
|
-
}
|
|
512
|
-
const row = {
|
|
513
|
-
id: newId(10), workspace_id: wsRow.id, host_id: user.id,
|
|
514
|
-
title: clip(m.title, 80) || clip(m.project, 80) || 'Untitled session',
|
|
515
|
-
agent: clip(m.agent, 40) || 'claude', project: clip(m.project, 80) || null, branch: clip(m.branch, 80) || null,
|
|
516
|
-
access: ['view', 'control', 'private'].includes(m.access) ? m.access : wsRow.default_access,
|
|
517
|
-
status: 'live', started_at: now(), kind: m.kind === 'thread' ? 'thread' : 'terminal',
|
|
518
|
-
};
|
|
519
|
-
q.run(`INSERT INTO sessions (id, workspace_id, host_id, title, agent, project, branch, access, status, started_at, kind) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
|
|
520
|
-
row.id, row.workspace_id, row.host_id, row.title, row.agent, row.project, row.branch, row.access, row.status, row.started_at, row.kind);
|
|
521
|
-
const s = new LiveSession(row, { id: user.id, name: user.name }, m);
|
|
522
|
-
s.ws = ws;
|
|
523
|
-
live.set(s.id, s);
|
|
524
|
-
audit(row.workspace_id, 'session.start', { session: s.id, actor: user, detail: row.title });
|
|
525
|
-
for (const u of membersOf(row.workspace_id)) {
|
|
526
|
-
if (u !== user.id && row.access !== 'private') notify(u, { kind: 'started', title: `${user.name} is live`, body: `${row.title} · ${wsRow.name}`, session: s.id });
|
|
527
|
-
}
|
|
528
|
-
send(ws, { t: 'ready', id: s.id, key: s.key, url: `${BASE_URL()}/s/${s.id}`, workspace: { name: wsRow.name, slug: wsRow.slug }, access: row.access, handoff: !!wsRow.handoff });
|
|
529
|
-
publish(row.workspace_id);
|
|
530
|
-
return s;
|
|
531
|
-
}
|
|
532
|
-
|
|
533
|
-
function resumeHost(ws, user, m) {
|
|
534
|
-
const s = live.get(m.resume.id);
|
|
535
|
-
if (!s || s.row.host_id !== user.id || s.key !== m.resume.key) {
|
|
536
|
-
send(ws, { t: 'error', code: 'gone', message: 'That session has already ended.' });
|
|
537
|
-
ws.close();
|
|
538
|
-
return null;
|
|
539
|
-
}
|
|
540
|
-
clearTimeout(s.graceTimer);
|
|
541
|
-
if (s.ws && s.ws !== ws) s.ws.terminate();
|
|
542
|
-
s.ws = ws;
|
|
543
|
-
s.setState(s.kind === 'thread' ? 'idle' : 'working');
|
|
544
|
-
send(ws, { t: 'ready', id: s.id, key: s.key, url: `${BASE_URL()}/s/${s.id}`, resumed: true, access: s.row.access, handoff: !!q.get(`SELECT handoff FROM workspaces WHERE id=?`, s.row.workspace_id)?.handoff });
|
|
545
|
-
send(ws, { t: 'people', people: s.summary().people });
|
|
546
|
-
return s;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
// ---- viewer side -----------------------------------------------------------
|
|
550
|
-
|
|
551
|
-
export function attachViewer(ws, s, user) {
|
|
552
|
-
const conn = s.nextConn++;
|
|
553
|
-
const v = { ws, conn, user, canType: s.canType(user) };
|
|
554
|
-
const already = [...s.viewers.values()].some((o) => o.user.id && o.user.id === user.id);
|
|
555
|
-
s.viewers.set(conn, v);
|
|
556
|
-
send(ws, {
|
|
557
|
-
t: 'init', session: s.summary(), cols: s.cols, rows: s.rows,
|
|
558
|
-
you: { id: user.id, name: user.name, guest: !!user.guest, canType: v.canType, isHost: user.id === s.row.host_id },
|
|
559
|
-
chat: s.chat, thread: s.kind === 'thread' ? s.transcript() : undefined, driver: s.driverView(),
|
|
560
|
-
});
|
|
561
|
-
if (s.chunks.length) ws.send(Buffer.concat(s.chunks), { binary: true });
|
|
562
|
-
// ask the host for a clean repaint so full-screen UIs land pixel-perfect
|
|
563
|
-
if (s.kind === 'terminal') send(s.ws, { t: 'repaint' });
|
|
564
|
-
if (!already) {
|
|
565
|
-
s.activity(user, 'session.join', user.guest ? 'via guest link' : null);
|
|
566
|
-
if (user.id !== s.row.host_id) notify(s.row.host_id, { kind: 'joined', title: `${user.name} joined your session`, body: s.row.title, session: s.id });
|
|
567
|
-
}
|
|
568
|
-
s.peopleChanged();
|
|
569
|
-
|
|
570
|
-
ws.on('message', (data, isBinary) => {
|
|
571
|
-
if (data.length > 64 * 1024) return;
|
|
572
|
-
if (isBinary) {
|
|
573
|
-
if (v.canType && s.kind === 'terminal' && s.ws?.readyState === 1) s.ws.send(data, { binary: true });
|
|
574
|
-
return;
|
|
575
|
-
}
|
|
576
|
-
let m;
|
|
577
|
-
try { m = JSON.parse(data); } catch { return; }
|
|
578
|
-
if (m?.t === 'chat') s.say(user, m.text);
|
|
579
|
-
else if (m?.t === 'prompt') s.prompt(user, m.text);
|
|
580
|
-
});
|
|
581
|
-
ws.on('close', () => {
|
|
582
|
-
s.viewers.delete(conn);
|
|
583
|
-
if (live.has(s.id)) s.peopleChanged();
|
|
584
|
-
});
|
|
585
|
-
ws.on('error', () => {});
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
// ---- workspace feed --------------------------------------------------------
|
|
589
|
-
|
|
590
|
-
export const getLive = (sessionId) => live.get(sessionId);
|
|
591
|
-
// Everything live across a user's workspaces, for their notification stream.
|
|
592
|
-
export function liveForUser(userId) {
|
|
593
|
-
const names = new Map(q.all(`SELECT w.id, w.name FROM workspaces w JOIN memberships m ON m.workspace_id=w.id WHERE m.user_id=?`, userId).map((w) => [w.id, w.name]));
|
|
594
|
-
return [...live.values()].filter((s) => names.has(s.row.workspace_id) && s.visibleTo(userId)).map((s) => {
|
|
595
|
-
const { people, ...rest } = s.summary();
|
|
596
|
-
return { ...rest, watching: people.length, workspace: names.get(s.row.workspace_id), mine: s.row.host_id === userId, url: `${BASE_URL()}/s/${s.id}` };
|
|
597
|
-
});
|
|
598
|
-
}
|
|
599
|
-
export const liveList = (wsId, userId) => [...live.values()].filter((s) => s.row.workspace_id === wsId && s.visibleTo(userId)).map((s) => s.summary());
|
|
600
|
-
|
|
601
|
-
export function attachFeed(ws, wsId, userId) {
|
|
602
|
-
ws.userId = userId;
|
|
603
|
-
if (!feeds.has(wsId)) feeds.set(wsId, new Set());
|
|
604
|
-
feeds.get(wsId).add(ws);
|
|
605
|
-
send(ws, { t: 'sessions', live: liveList(wsId, userId) });
|
|
606
|
-
ws.on('close', () => feeds.get(wsId)?.delete(ws));
|
|
607
|
-
ws.on('error', () => {});
|
|
608
|
-
}
|
|
609
|
-
|
|
610
|
-
export function publish(wsId) {
|
|
611
|
-
if (feedTimers.has(wsId)) return;
|
|
612
|
-
feedTimers.set(wsId, setTimeout(() => {
|
|
613
|
-
feedTimers.delete(wsId);
|
|
614
|
-
pushSessions(wsId);
|
|
615
|
-
const set = feeds.get(wsId);
|
|
616
|
-
if (!set?.size) return;
|
|
617
|
-
// each person gets their own list: private sessions appear only to their host
|
|
618
|
-
for (const ws of set) if (ws.readyState === 1) ws.send(JSON.stringify({ t: 'sessions', live: liveList(wsId, ws.userId) }));
|
|
619
|
-
}, 120));
|
|
620
|
-
}
|
|
621
|
-
|
|
622
|
-
// A removed member must lose their open sockets, not just future requests.
|
|
623
|
-
export function dropUser(wsId, userId) {
|
|
624
|
-
for (const ws of feeds.get(wsId) || []) if (ws.userId === userId) ws.close();
|
|
625
|
-
for (const s of live.values()) {
|
|
626
|
-
if (s.row.workspace_id !== wsId) continue;
|
|
627
|
-
if (s.row.host_id === userId) { s.end('host removed from workspace'); continue; }
|
|
628
|
-
for (const v of s.viewers.values()) if (v.user.id === userId) v.ws.close();
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
export function newGuestLink(s, actor) {
|
|
633
|
-
const token = secret();
|
|
634
|
-
q.run(`UPDATE sessions SET guest_hash=? WHERE id=?`, sha(token), s.id);
|
|
635
|
-
s.activity(actor, 'session.guest_link', 'view-only link created');
|
|
636
|
-
return `${BASE_URL()}/s/${s.id}?guest=${token}`;
|
|
637
|
-
}
|