@agentsignalnet/claude-plugin 0.2.56
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/.claude-plugin/plugin.json +34 -0
- package/.mcp.json +14 -0
- package/LICENSE +86 -0
- package/README.md +174 -0
- package/commands/chat.md +47 -0
- package/commands/fleet.md +41 -0
- package/commands/inbox.md +28 -0
- package/commands/invite.md +104 -0
- package/commands/join.md +61 -0
- package/commands/update.md +121 -0
- package/commands/work.md +117 -0
- package/hooks/hooks.json +47 -0
- package/package.json +32 -0
- package/scripts/chat-viewer.mjs +2829 -0
- package/scripts/inbox-daemon.mjs +677 -0
- package/scripts/inbox-hook.mjs +197 -0
- package/scripts/state.mjs +275 -0
- package/scripts/watchers.mjs +203 -0
- package/skills/agent-coordination/SKILL.md +232 -0
|
@@ -0,0 +1,2829 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Watch a channel's agents talk, in a browser.
|
|
4
|
+
*
|
|
5
|
+
* AGENTSIGNAL_API_KEY=as_live_… node scripts/chat-viewer.mjs
|
|
6
|
+
*
|
|
7
|
+
* WHY NOT IN THE MCP SERVER
|
|
8
|
+
*
|
|
9
|
+
* The obvious place to put this is the MCP server, since that is what already
|
|
10
|
+
* holds a credential -- and it is the wrong place. That server speaks stdio,
|
|
11
|
+
* is started and killed by whichever client launched it, and there may be
|
|
12
|
+
* several at once; giving it a listening socket means two sessions fighting
|
|
13
|
+
* over a port and a page that dies when a model finishes its turn. A viewer
|
|
14
|
+
* outlives any one session, so it is its own process.
|
|
15
|
+
*
|
|
16
|
+
* WHY THE KEY STAYS HERE
|
|
17
|
+
*
|
|
18
|
+
* The page never sees it. The browser calls this server, this server calls
|
|
19
|
+
* AgentSignal. An API key in page JavaScript is one "view source" away from
|
|
20
|
+
* being someone else's key, and this one can page real devices.
|
|
21
|
+
*
|
|
22
|
+
* WHAT IT SHOWS
|
|
23
|
+
*
|
|
24
|
+
* `GET /v1/messages` for the channel the key belongs to, which since
|
|
25
|
+
* 20260804000100 says who each message came from as well as who it went to.
|
|
26
|
+
* A message sent with the API key itself has no sender -- the key speaks for
|
|
27
|
+
* the channel rather than for anyone in it -- and is shown as such rather than
|
|
28
|
+
* being attributed to a guess.
|
|
29
|
+
*
|
|
30
|
+
* Bodies are the first 120 characters. That truncation is in the log function
|
|
31
|
+
* on purpose and this does not work around it.
|
|
32
|
+
*/
|
|
33
|
+
import { createServer } from 'node:http';
|
|
34
|
+
import { randomUUID } from 'node:crypto';
|
|
35
|
+
import { readFileSync } from 'node:fs';
|
|
36
|
+
import { homedir } from 'node:os';
|
|
37
|
+
import { join } from 'node:path';
|
|
38
|
+
import { mkdirSync, writeFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
|
|
39
|
+
import { randomUUID as uuid } from 'node:crypto';
|
|
40
|
+
import {
|
|
41
|
+
identities as identitiesHere,
|
|
42
|
+
readKeychain,
|
|
43
|
+
repoRoot,
|
|
44
|
+
repoSlug,
|
|
45
|
+
writeDir,
|
|
46
|
+
} from './state.mjs';
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The key, from the MCP server on this machine that already holds one.
|
|
50
|
+
*
|
|
51
|
+
* Only consulted when the environment does not supply one. It exists because
|
|
52
|
+
* of how this gets launched: `.claude/launch.json` can name a command and a
|
|
53
|
+
* port but cannot carry a secret, and a launch config is a committed file, so
|
|
54
|
+
* the alternative is either pasting a live key into the repo or pasting it
|
|
55
|
+
* into a shell every time. Both are worse than reading the one already sitting
|
|
56
|
+
* in the client's own config on the same machine, under the same user.
|
|
57
|
+
*
|
|
58
|
+
* It reports WHICH server it borrowed from and never the key itself. A viewer
|
|
59
|
+
* that silently goes looking for credentials is indistinguishable from one
|
|
60
|
+
* that steals them; saying so out loud is the whole difference.
|
|
61
|
+
*
|
|
62
|
+
* The base URL comes from the same server or not at all. Half a credential
|
|
63
|
+
* pair -- a production key pointed at localhost, or the reverse -- is how a
|
|
64
|
+
* development run ends up paging somebody real.
|
|
65
|
+
*/
|
|
66
|
+
function borrowFromMcpConfig() {
|
|
67
|
+
let config;
|
|
68
|
+
try {
|
|
69
|
+
config = JSON.parse(readFileSync(join(homedir(), '.claude.json'), 'utf8'));
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const found = [];
|
|
75
|
+
const walk = (node) => {
|
|
76
|
+
if (!node || typeof node !== 'object') return;
|
|
77
|
+
for (const [key, value] of Object.entries(node)) {
|
|
78
|
+
if (key === 'mcpServers' && value && typeof value === 'object') {
|
|
79
|
+
for (const [name, server] of Object.entries(value)) {
|
|
80
|
+
const argv = (server?.args ?? []).join(' ');
|
|
81
|
+
const key = server?.env?.AGENTSIGNAL_API_KEY;
|
|
82
|
+
if (argv.includes('agentsignalnet/mcp') && key) {
|
|
83
|
+
found.push({ name, key, baseUrl: server.env.AGENTSIGNAL_BASE_URL });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
} else walk(value);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
walk(config);
|
|
90
|
+
|
|
91
|
+
// More than one and there is no principled way to choose: they may be
|
|
92
|
+
// different accounts, and picking wrong shows somebody else's conversation.
|
|
93
|
+
if (found.length !== 1) return found.length > 1 ? { ambiguous: found.map((f) => f.name) } : null;
|
|
94
|
+
return found[0];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Which agent is THIS machine's, so the page can put it on the right.
|
|
99
|
+
*
|
|
100
|
+
* "Yours" needs a definition that is a fact rather than a guess, and there is
|
|
101
|
+
* one: the agent this machine registered as, whose credential the MCP server
|
|
102
|
+
* wrote down. Not the channel's creator, not whoever sorts first -- those are
|
|
103
|
+
* somebody's agent, but not necessarily the one at this keyboard.
|
|
104
|
+
*
|
|
105
|
+
* The same directories the daemon and the MCP server search, in the same
|
|
106
|
+
* order, so all three agree about who this is. Returning null is fine and
|
|
107
|
+
* common: a viewer run from a machine that only holds an API key has no agent
|
|
108
|
+
* of its own, and then nothing is on the right, which is honest.
|
|
109
|
+
*/
|
|
110
|
+
let apiKey = process.env.AGENTSIGNAL_API_KEY;
|
|
111
|
+
let baseUrl = process.env.AGENTSIGNAL_BASE_URL;
|
|
112
|
+
const port = Number(process.env.PORT ?? 8899);
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* A token in the URL, and loopback only.
|
|
116
|
+
*
|
|
117
|
+
* This server used to be read-only and bound to every interface, which was
|
|
118
|
+
* already "anyone on the coffee-shop wifi can read your channel". It can now
|
|
119
|
+
* SEND and ANSWER, so the same exposure would be "anyone on the network can
|
|
120
|
+
* page your colleagues and approve your agents' work".
|
|
121
|
+
*
|
|
122
|
+
* Two things rather than one, because each covers the other's gap: binding to
|
|
123
|
+
* 127.0.0.1 stops the network, and the token stops anything else on this
|
|
124
|
+
* machine -- another user's process, a page in your browser guessing the port.
|
|
125
|
+
* Minted per run and never written down, so closing the viewer revokes it.
|
|
126
|
+
*/
|
|
127
|
+
const token = randomUUID();
|
|
128
|
+
|
|
129
|
+
if (!apiKey) {
|
|
130
|
+
const borrowed = borrowFromMcpConfig();
|
|
131
|
+
if (borrowed?.ambiguous) {
|
|
132
|
+
console.error(
|
|
133
|
+
`Several AgentSignal MCP servers hold a key (${borrowed.ambiguous.join(', ')}).\n` +
|
|
134
|
+
'They may be different accounts, so set AGENTSIGNAL_API_KEY to say which.',
|
|
135
|
+
);
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
138
|
+
if (borrowed) {
|
|
139
|
+
apiKey = borrowed.key;
|
|
140
|
+
baseUrl ??= borrowed.baseUrl;
|
|
141
|
+
console.log(`Using the API key from MCP server "${borrowed.name}" in ~/.claude.json.`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
baseUrl = (baseUrl ?? 'https://api.agentsignal.net').replace(/\/+$/, '');
|
|
146
|
+
|
|
147
|
+
const identities = identitiesHere(baseUrl);
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* A KEY AN AGENT ON THIS MACHINE ALREADY HOLDS.
|
|
151
|
+
*
|
|
152
|
+
* Third and last, because the first two are somebody saying which key to use
|
|
153
|
+
* and this one is a choice made on their behalf. A web join now mints an agent
|
|
154
|
+
* its own key, scoped to the one channel, and writes it beside the credential
|
|
155
|
+
* -- so the ordinary case is that what this viewer needs is already on disk,
|
|
156
|
+
* and nobody should have to be told to go and find it. Being told was the
|
|
157
|
+
* whole of the old setup.
|
|
158
|
+
*
|
|
159
|
+
* REFUSES RATHER THAN PICKS when identities hold different keys, for the same
|
|
160
|
+
* reason borrowFromMcpConfig does: a key names one channel, so two keys are
|
|
161
|
+
* two channels, and picking wrong shows somebody else's conversation.
|
|
162
|
+
* Identical ones are not a conflict -- one agent reachable through several
|
|
163
|
+
* state directories is still one key.
|
|
164
|
+
*
|
|
165
|
+
* Announced, like the borrowed one, because a viewer that goes looking for
|
|
166
|
+
* credentials silently is indistinguishable from one that steals them.
|
|
167
|
+
*/
|
|
168
|
+
if (!apiKey) {
|
|
169
|
+
const holders = identities.filter((who) => who.api_key_ref || who.api_key);
|
|
170
|
+
const distinct = new Set(holders.map((who) => who.api_key_ref ?? who.api_key));
|
|
171
|
+
if (distinct.size > 1) {
|
|
172
|
+
console.error(
|
|
173
|
+
`Agents here hold different channel keys (${holders
|
|
174
|
+
.map((who) => who.handle ?? who.key)
|
|
175
|
+
.join(', ')}).\n` +
|
|
176
|
+
'Those are different channels, so set AGENTSIGNAL_API_KEY to say which.',
|
|
177
|
+
);
|
|
178
|
+
process.exit(1);
|
|
179
|
+
}
|
|
180
|
+
const holder = holders[0];
|
|
181
|
+
if (holder) {
|
|
182
|
+
try {
|
|
183
|
+
apiKey = holder.api_key_ref ? readKeychain(holder.api_key_ref) : holder.api_key;
|
|
184
|
+
} catch (error) {
|
|
185
|
+
// Named rather than swallowed. Falling through to "no key is set" would
|
|
186
|
+
// be a lie -- there is one, it is exactly where it says, and the fix is
|
|
187
|
+
// to unlock the keychain rather than to go and find a key.
|
|
188
|
+
console.error(
|
|
189
|
+
`${holder.handle ?? holder.key} holds a key at ${holder.api_key_ref}, ` +
|
|
190
|
+
`and it could not be read.\n${error.message}\n` +
|
|
191
|
+
'Unlock the keychain, or set AGENTSIGNAL_API_KEY for this run.',
|
|
192
|
+
);
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
console.log(
|
|
196
|
+
`Using ${holder.handle ?? holder.key}'s own channel key, from ` +
|
|
197
|
+
`${holder.api_key_ref ?? join(holder.dir, 'agent.json')}.`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* SETTINGS ARE MACHINE-WIDE, for the reason the lock is.
|
|
204
|
+
*
|
|
205
|
+
* "How many agents may run here" and "what does an agent have to ask before
|
|
206
|
+
* acting" are questions about this computer, not about one checkout. Keyed on
|
|
207
|
+
* a credential they would move the moment somebody joined, which is the exact
|
|
208
|
+
* bug that had three watchers running: a setting that relocates is not a
|
|
209
|
+
* setting.
|
|
210
|
+
*
|
|
211
|
+
* Deliberately NOT on agentsignal.net. The server cannot enumerate the folders
|
|
212
|
+
* on a laptop and should not be able to, so the half of onboarding that is
|
|
213
|
+
* about this machine has to be answered by something running on it.
|
|
214
|
+
*/
|
|
215
|
+
const settingsPath = join(homedir(), '.agentsignal', 'settings.json');
|
|
216
|
+
|
|
217
|
+
/** Defaults chosen so that answering nothing is still a safe configuration. */
|
|
218
|
+
const DEFAULT_SETTINGS = {
|
|
219
|
+
// A cap, not a target. Enforced at /connect below, which is the only place
|
|
220
|
+
// this viewer can create one.
|
|
221
|
+
max_agents: 4,
|
|
222
|
+
// What a NEW agent is unless somebody says otherwise. `subagent` proposes
|
|
223
|
+
// and waits for approve/disapprove before acting; `partner` works its own
|
|
224
|
+
// tasks; `worker` does one job and reports. Defaulting to the one that asks
|
|
225
|
+
// is the only defensible direction -- the cost of asking too often is
|
|
226
|
+
// annoyance, and the cost of asking too rarely is an agent acting unasked.
|
|
227
|
+
default_connection_type: 'subagent',
|
|
228
|
+
// How long the local copy of the conversation is kept, in days. A week is
|
|
229
|
+
// long enough to scroll back through a working week and short enough that
|
|
230
|
+
// a machine does not accumulate a year of other people's messages nobody
|
|
231
|
+
// decided to keep. 0 means keep nothing beyond what is on screen.
|
|
232
|
+
history_days: 7,
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
function settings() {
|
|
236
|
+
try {
|
|
237
|
+
const stored = JSON.parse(readFileSync(settingsPath, 'utf8'));
|
|
238
|
+
return { ...DEFAULT_SETTINGS, ...stored };
|
|
239
|
+
} catch {
|
|
240
|
+
return { ...DEFAULT_SETTINGS };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* THE CONVERSATION, KEPT LOCALLY, so watching it stops costing money.
|
|
246
|
+
*
|
|
247
|
+
* The log endpoint charges one credit per call and this viewer polls every two
|
|
248
|
+
* seconds, so an idle channel was billing roughly eighteen hundred times an
|
|
249
|
+
* hour to be told nothing had happened -- while re-downloading a hundred
|
|
250
|
+
* messages it already had. The API half of this now refunds a call that
|
|
251
|
+
* returns nothing new; this half is what makes the calls return nothing new,
|
|
252
|
+
* by asking with `since` instead of asking for the last hundred every time.
|
|
253
|
+
*
|
|
254
|
+
* ONE FILE PER CHANNEL, under the machine-wide directory beside the lock and
|
|
255
|
+
* the settings, because a conversation belongs to a channel rather than to a
|
|
256
|
+
* checkout and the same channel is watched from several of them.
|
|
257
|
+
*/
|
|
258
|
+
const historyDir = join(homedir(), '.agentsignal', 'history');
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Which channel's history this is. Unknown until the API answers once, so it
|
|
262
|
+
* starts generic and is replaced by the real ref on the first successful read.
|
|
263
|
+
*/
|
|
264
|
+
let channelRef = 'channel';
|
|
265
|
+
|
|
266
|
+
const historyFile = (ref) =>
|
|
267
|
+
join(historyDir, `${String(ref || 'channel').replace(/[^A-Za-z0-9._-]/g, '-')}.json`);
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* What is safe to keep, which is not the same as what arrived.
|
|
271
|
+
*
|
|
272
|
+
* AN ENCRYPTED MESSAGE LEAVES A RECORD AND NOT ITS CONTENTS. The read-once
|
|
273
|
+
* guarantee rests on plaintext never being cached; a local store that held
|
|
274
|
+
* decrypted bodies would void it silently, and no test would fail. So the row
|
|
275
|
+
* is kept -- who sent it, when, that it happened -- with the body and title
|
|
276
|
+
* dropped. The conversation stays legible as a sequence of events, and the
|
|
277
|
+
* one thing that must not persist does not.
|
|
278
|
+
*/
|
|
279
|
+
function keepable(m) {
|
|
280
|
+
if (!m || !m.id) return null;
|
|
281
|
+
if (m.encrypted) {
|
|
282
|
+
const { body, title, preview, ...rest } = m;
|
|
283
|
+
return { ...rest, encrypted: true, body: null, title: null, preview: null };
|
|
284
|
+
}
|
|
285
|
+
return m;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function readHistory(ref) {
|
|
289
|
+
try {
|
|
290
|
+
const stored = JSON.parse(readFileSync(historyFile(ref), 'utf8'));
|
|
291
|
+
return Array.isArray(stored.messages) ? stored.messages : [];
|
|
292
|
+
} catch {
|
|
293
|
+
return [];
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Merge, prune, write. Newest first, matching what the API returns, so the
|
|
299
|
+
* page's own ordering does not have to know where a message came from.
|
|
300
|
+
*/
|
|
301
|
+
function writeHistory(ref, messages, days) {
|
|
302
|
+
const cutoff = Number.isFinite(days) && days > 0 ? Date.now() - days * 86400_000 : null;
|
|
303
|
+
const kept = messages
|
|
304
|
+
.filter((m) => {
|
|
305
|
+
if (cutoff === null) return true;
|
|
306
|
+
const at = Date.parse(m.created_at ?? '');
|
|
307
|
+
// A row with an unreadable timestamp is kept rather than dropped: losing
|
|
308
|
+
// a message to a parsing quirk is worse than keeping one an hour too
|
|
309
|
+
// long, and this is a cache rather than a ledger.
|
|
310
|
+
return Number.isNaN(at) ? true : at >= cutoff;
|
|
311
|
+
})
|
|
312
|
+
.sort((a, b) => Date.parse(b.created_at ?? 0) - Date.parse(a.created_at ?? 0));
|
|
313
|
+
|
|
314
|
+
mkdirSync(historyDir, { recursive: true, mode: 0o700 });
|
|
315
|
+
writeFileSync(
|
|
316
|
+
historyFile(ref),
|
|
317
|
+
JSON.stringify({ ref, saved_at: new Date().toISOString(), messages: kept }, null, 0),
|
|
318
|
+
{ mode: 0o600 },
|
|
319
|
+
);
|
|
320
|
+
return kept;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function saveSettings(next) {
|
|
324
|
+
mkdirSync(join(homedir(), '.agentsignal'), { recursive: true, mode: 0o700 });
|
|
325
|
+
writeFileSync(settingsPath, JSON.stringify(next, null, 2), { mode: 0o600 });
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Which of this machine's identities is "me" in THIS channel.
|
|
330
|
+
*
|
|
331
|
+
* Not simply the first. A machine holds an identity per project now, and those
|
|
332
|
+
* can be in different accounts -- this one has two. The API key names one
|
|
333
|
+
* channel, and an identity from the other account has no messages in it, so
|
|
334
|
+
* taking the first would align nothing to the right and quietly claim the
|
|
335
|
+
* wrong agent is you.
|
|
336
|
+
*
|
|
337
|
+
* Resolved against the channel's own roster, which is the only thing that
|
|
338
|
+
* actually knows. Left null until that returns: a wrong answer here is worse
|
|
339
|
+
* than a late one, and the column is cosmetic.
|
|
340
|
+
*/
|
|
341
|
+
let self = null;
|
|
342
|
+
|
|
343
|
+
if (!apiKey) {
|
|
344
|
+
console.error(
|
|
345
|
+
'AGENTSIGNAL_API_KEY is not set, no AgentSignal MCP server in ~/.claude.json has one,\n' +
|
|
346
|
+
'and no agent on this machine holds one of its own.\n' +
|
|
347
|
+
'It needs to be a channel key (as_live_… or as_test_…) — a device credential\n' +
|
|
348
|
+
'reads one agent’s inbox, which is one side of a conversation rather than the whole of it.\n' +
|
|
349
|
+
'Connecting this agent from Agent setup on the dashboard mints it one.',
|
|
350
|
+
);
|
|
351
|
+
process.exit(1);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const PAGE = `<!doctype html>
|
|
355
|
+
<html lang="en">
|
|
356
|
+
<head>
|
|
357
|
+
<meta charset="utf-8">
|
|
358
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
359
|
+
<title>AgentSignal — channel</title>
|
|
360
|
+
<style>
|
|
361
|
+
/* LIGHT, and not a preference.
|
|
362
|
+
color-scheme is pinned so the browser renders selects, scrollbars and
|
|
363
|
+
focus rings light as well -- left at "light dark" those follow the OS and
|
|
364
|
+
a dark select sits in a light panel looking like a rendering fault.
|
|
365
|
+
There is no dark block any more: one theme that is right beats two that
|
|
366
|
+
are each half-tested, and the dark one was being tested by nobody. */
|
|
367
|
+
:root {
|
|
368
|
+
color-scheme: light;
|
|
369
|
+
--bg: #f6f7f9;
|
|
370
|
+
--fg: #15181e;
|
|
371
|
+
--dim: #626a78;
|
|
372
|
+
--line: #e2e6ec;
|
|
373
|
+
--card: #ffffff;
|
|
374
|
+
--panel: #ffffff;
|
|
375
|
+
--mine-bg: #eef3ff;
|
|
376
|
+
--rail: #fafbfc;
|
|
377
|
+
/* DEFINED AT LAST. Roughly twenty rules ask for var(--hair,#ddd) and until
|
|
378
|
+
now every one of them took the fallback, because nothing ever declared
|
|
379
|
+
it -- so every input, button and panel edge in the page was a hardcoded
|
|
380
|
+
grey that no theme could reach. That is why the chrome and the cards
|
|
381
|
+
never quite agreed. One declaration puts all of them on the palette. */
|
|
382
|
+
--hair: var(--line);
|
|
383
|
+
--accent-ink: #2f5fd0;
|
|
384
|
+
--accent-soft: #eaf0fe;
|
|
385
|
+
--focus: 0 0 0 3px rgba(47, 95, 208, .18);
|
|
386
|
+
/* Two weights, because one shadow doing both jobs is either too heavy for
|
|
387
|
+
a resting card or too light to lift a panel off the page. */
|
|
388
|
+
--lift: 0 1px 2px rgba(16, 24, 40, .04);
|
|
389
|
+
--lift-2: 0 1px 3px rgba(16, 24, 40, .06), 0 4px 12px rgba(16, 24, 40, .04);
|
|
390
|
+
}
|
|
391
|
+
* { box-sizing: border-box; }
|
|
392
|
+
body {
|
|
393
|
+
margin: 0; background: var(--bg); color: var(--fg);
|
|
394
|
+
font: 15px/1.5 ui-sans-serif, -apple-system, "Segoe UI", system-ui, sans-serif;
|
|
395
|
+
}
|
|
396
|
+
header {
|
|
397
|
+
position: sticky; top: 0; background: var(--bg); border-bottom: 1px solid var(--line);
|
|
398
|
+
padding: 14px 20px; display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap;
|
|
399
|
+
/* Z-INDEX, or the bar reads as see-through while being perfectly opaque.
|
|
400
|
+
Its background is --bg and always was; what scrolled across it was
|
|
401
|
+
message text. The clipwrap div is position:relative for the fade-out,
|
|
402
|
+
and a POSITIONED element with z-index:auto paints above the backgrounds
|
|
403
|
+
of static ones -- ties broken by document order, which the header loses
|
|
404
|
+
to every message on the page. So it was painted first and then covered,
|
|
405
|
+
one card at a time. Any value above auto fixes it; 5 leaves room to put
|
|
406
|
+
something between the two later.
|
|
407
|
+
|
|
408
|
+
No backticks in here: this whole document is a template literal, and a
|
|
409
|
+
comment is not a comment to the string that contains it. */
|
|
410
|
+
z-index: 5;
|
|
411
|
+
}
|
|
412
|
+
h1 { font-size: 15px; margin: 0; font-weight: 600; letter-spacing: -0.01em; }
|
|
413
|
+
.meta { color: var(--dim); font-size: 13px; }
|
|
414
|
+
/* A LIST, not a row of pills. As a header strip these wrapped onto more
|
|
415
|
+
lines with every agent that joined, pushing the conversation down the
|
|
416
|
+
page; a fleet is a thing that grows, so the control for it belongs
|
|
417
|
+
somewhere vertical where growing costs nothing. */
|
|
418
|
+
nav { display: block; margin: 0 0 .9rem; }
|
|
419
|
+
nav a {
|
|
420
|
+
font-size: 13px; text-decoration: none; color: var(--dim);
|
|
421
|
+
border: 1px solid transparent; border-radius: 8px; padding: 6px 8px;
|
|
422
|
+
display: flex; align-items: center; gap: 8px; margin-bottom: 2px;
|
|
423
|
+
}
|
|
424
|
+
/* The two names, stacked. min-width:0 is what lets the ellipsis inside
|
|
425
|
+
actually happen -- a flex child defaults to min-width:auto and refuses to
|
|
426
|
+
shrink below its content, so the row overflows instead of trimming. */
|
|
427
|
+
.stack { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 1px; }
|
|
428
|
+
.alias {
|
|
429
|
+
font-size: 11px; color: var(--dim); line-height: 1.3;
|
|
430
|
+
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
|
431
|
+
}
|
|
432
|
+
nav a:hover { background: var(--accent-soft); color: var(--fg); }
|
|
433
|
+
nav a:focus-visible { outline: none; box-shadow: var(--focus); }
|
|
434
|
+
nav a .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
435
|
+
nav a.whole { font-weight: 600; color: var(--fg); }
|
|
436
|
+
/* The indent IS the parent-child relationship, so it needs a line to read as
|
|
437
|
+
one rather than as ragged alignment. */
|
|
438
|
+
nav .kids { margin-left: 10px; padding-left: 10px; border-left: 1px solid var(--line); }
|
|
439
|
+
/* FILLED, not outlined. A hard border on a rounded, padded, full-width row
|
|
440
|
+
is the shape of a text input, and the selected channel was reliably
|
|
441
|
+
mistaken for one -- a box at the top of a panel that looks like a field
|
|
442
|
+
invites people to type in it. A soft fill says "selected" without
|
|
443
|
+
borrowing another control's silhouette. */
|
|
444
|
+
nav a.on { color: var(--accent-ink); background: var(--accent-soft);
|
|
445
|
+
border-color: transparent; font-weight: 600; }
|
|
446
|
+
/* The dot carries the state and the text carries the evidence for it, so
|
|
447
|
+
nobody has to trust a colour they cannot check. */
|
|
448
|
+
nav a i { width: 6px; height: 6px; border-radius: 50%; background: currentColor; opacity: 0.35; }
|
|
449
|
+
nav a.live i { background: #3fb950; opacity: 1; }
|
|
450
|
+
nav a.live { color: var(--fg); }
|
|
451
|
+
nav a em { font-style: normal; opacity: 0.55; font-size: 11px; }
|
|
452
|
+
.dot { width: 7px; height: 7px; border-radius: 50%; background: #3fb950; display: inline-block; }
|
|
453
|
+
/* Room below the last message. The page appends as things arrive and the
|
|
454
|
+
newest is the one being read, so ending flush with the viewport puts the
|
|
455
|
+
line you care about hard against the edge. The generous bottom also means
|
|
456
|
+
a message that lands mid-read does not shove the text under the fold. */
|
|
457
|
+
/* max(), not a bare 25vh: a short window makes a proportional value small
|
|
458
|
+
exactly when the room is most wanted, and a viewport that reports zero
|
|
459
|
+
height makes it nothing at all. The floor is what the rule is really for;
|
|
460
|
+
the proportion just keeps it in scale on a tall screen. */
|
|
461
|
+
/* SIDEBAR BESIDE THE CONVERSATION, not above it. What this machine is
|
|
462
|
+
changes rarely and is consulted deliberately; the conversation changes
|
|
463
|
+
every two seconds and is what the page is for. Stacked, the rare thing
|
|
464
|
+
pushed the frequent one down the screen. */
|
|
465
|
+
#shell { display:flex; gap:20px; align-items:flex-start;
|
|
466
|
+
max-width:1400px; margin:0 auto; padding:20px 20px max(140px, 25vh); }
|
|
467
|
+
|
|
468
|
+
/* BOTH RAILS LOOK LIKE RAILS.
|
|
469
|
+
They used to be bare content sitting on the page background, which made
|
|
470
|
+
the left one read as part of the conversation and the right one as a
|
|
471
|
+
tooltip that had got stuck. A rail needs a surface: its own ground, an
|
|
472
|
+
edge, and a little lift. The middle column keeps the page background, so
|
|
473
|
+
the three regions are told apart by material rather than by whitespace. */
|
|
474
|
+
#side, #right {
|
|
475
|
+
background: var(--rail);
|
|
476
|
+
border: 1px solid var(--line);
|
|
477
|
+
border-radius: 12px;
|
|
478
|
+
box-shadow: var(--lift);
|
|
479
|
+
padding: 14px;
|
|
480
|
+
position: sticky;
|
|
481
|
+
/* Below the sticky header rather than under it. 92px is that header
|
|
482
|
+
at its two-row height; a smaller offset tucks the panel behind it
|
|
483
|
+
on the way past. */
|
|
484
|
+
top: 92px;
|
|
485
|
+
max-height: calc(100vh - 112px);
|
|
486
|
+
overflow-y: auto;
|
|
487
|
+
}
|
|
488
|
+
#side { flex:0 0 300px; }
|
|
489
|
+
main { flex:1 1 auto; min-width:0; padding:0; }
|
|
490
|
+
|
|
491
|
+
/* The label that says what a rail IS. Without one, a column of agent names
|
|
492
|
+
and a column of agent names are the same column twice. */
|
|
493
|
+
.rail-title {
|
|
494
|
+
font-size: 11px; font-weight: 600; letter-spacing: .07em; text-transform: uppercase;
|
|
495
|
+
color: var(--dim); margin: 0 0 10px; padding: 0 2px;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/* One column when there is not room for two. 900px rather than a device
|
|
499
|
+
width: the breakpoint is about whether 320 + 24 + a readable column fits,
|
|
500
|
+
which is a fact about this layout and not about anybody's phone. */
|
|
501
|
+
/* WHO IS WORKING, on the right, and OPEN.
|
|
502
|
+
It used to be collapsed behind a floating button, on the reasoning that
|
|
503
|
+
the conversation is what the page is for. In use that was wrong twice
|
|
504
|
+
over: the button was the only thing telling you the panel existed, and a
|
|
505
|
+
panel you have to discover is one nobody opens. Who is working is context
|
|
506
|
+
for every line in the middle, so it belongs beside them. */
|
|
507
|
+
#right { flex:0 0 280px; }
|
|
508
|
+
.worker { border:1px solid var(--line); border-radius:8px; padding:.5rem .6rem;
|
|
509
|
+
margin-bottom:.5rem; background:var(--card); }
|
|
510
|
+
.worker .top { display:flex; align-items:baseline; gap:6px; }
|
|
511
|
+
.worker .nm { font-weight:600; font-size:13px; flex:1; min-width:0;
|
|
512
|
+
overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
513
|
+
.worker .kind { font-size:11px; opacity:.7; }
|
|
514
|
+
.worker .said { font-size:12px; color:var(--dim); margin-top:.25rem;
|
|
515
|
+
display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;
|
|
516
|
+
overflow:hidden; }
|
|
517
|
+
.worker .none { font-size:12px; color:var(--dim); font-style:italic; }
|
|
518
|
+
.worker i { width:6px; height:6px; border-radius:50%; background:currentColor;
|
|
519
|
+
opacity:.35; display:inline-block; }
|
|
520
|
+
.worker.live i { background:#3fb950; opacity:1; }
|
|
521
|
+
|
|
522
|
+
@media (max-width: 900px) {
|
|
523
|
+
#shell { display:block; }
|
|
524
|
+
#side { position:static; max-height:none; margin:0 0 1rem; }
|
|
525
|
+
#right { position:static; max-height:none; margin:1rem 0 0; }
|
|
526
|
+
}
|
|
527
|
+
.msg {
|
|
528
|
+
border: 1px solid var(--line); border-left: 3px solid var(--accent, var(--dim));
|
|
529
|
+
background: var(--card); border-radius: 8px; padding: 11px 14px; margin-bottom: 10px;
|
|
530
|
+
max-width: 78%;
|
|
531
|
+
}
|
|
532
|
+
/* This machine's own agent on the right, everybody else on the left, the way
|
|
533
|
+
a phone does it. The side is doing the work a name label otherwise has to,
|
|
534
|
+
so a conversation can be followed without reading every "from". */
|
|
535
|
+
.msg.mine {
|
|
536
|
+
margin-left: auto;
|
|
537
|
+
border-left: 1px solid var(--line);
|
|
538
|
+
border-right: 3px solid var(--accent, var(--dim));
|
|
539
|
+
background: var(--mine-bg);
|
|
540
|
+
}
|
|
541
|
+
.msg.mine .who { justify-content: flex-end; }
|
|
542
|
+
/* Membership events are facts about the channel, not things anybody said, so
|
|
543
|
+
they get a centred line rather than a bubble. Rendering them as messages
|
|
544
|
+
would put a delivery state and a "to" on something that was neither sent
|
|
545
|
+
nor addressed. */
|
|
546
|
+
.event {
|
|
547
|
+
max-width: 100%; margin: 14px 0; text-align: center;
|
|
548
|
+
color: var(--dim); font-size: 12.5px;
|
|
549
|
+
}
|
|
550
|
+
.event b { color: var(--fg); font-weight: 600; }
|
|
551
|
+
.event .time { margin-left: 6px; }
|
|
552
|
+
.who { font-size: 13px; margin-bottom: 4px; display: flex; gap: 7px; align-items: baseline; flex-wrap: wrap; }
|
|
553
|
+
.from { font-weight: 600; color: var(--accent, var(--fg)); }
|
|
554
|
+
.arrow, .time, .state { color: var(--dim); font-size: 12px; }
|
|
555
|
+
.title { font-weight: 600; }
|
|
556
|
+
.body { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
557
|
+
/* Collapsed to roughly six lines. A max-height rather than a line clamp so
|
|
558
|
+
the measurement below can compare scrollHeight against it and only offer
|
|
559
|
+
"more" on messages that actually have more -- a clamp reports nothing
|
|
560
|
+
useful about what it hid. */
|
|
561
|
+
.body.clip { max-height: 8.4em; overflow: hidden; }
|
|
562
|
+
.more {
|
|
563
|
+
background: none; border: 0; padding: 2px 0; margin-top: 4px;
|
|
564
|
+
color: var(--dim); font: inherit; font-size: 12px; cursor: pointer;
|
|
565
|
+
text-decoration: underline; text-underline-offset: 2px;
|
|
566
|
+
}
|
|
567
|
+
.more:hover { color: var(--fg); }
|
|
568
|
+
/* Fades the last line of a collapsed body so it reads as cut off rather
|
|
569
|
+
than as a message that happens to end awkwardly. */
|
|
570
|
+
.clipwrap { position: relative; }
|
|
571
|
+
.clipwrap.on::after {
|
|
572
|
+
content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 2em;
|
|
573
|
+
background: linear-gradient(transparent, var(--bg)); pointer-events: none;
|
|
574
|
+
}
|
|
575
|
+
/* What is still unanswered. Present only while something is, so it cannot
|
|
576
|
+
become furniture people stop seeing. */
|
|
577
|
+
.guide { border:1px solid var(--line); border-left:3px solid var(--dim);
|
|
578
|
+
padding:.6rem .75rem; margin:0 0 .8rem; background:var(--card); }
|
|
579
|
+
.guidehead { font-weight:600; margin-bottom:.35rem; }
|
|
580
|
+
.step { font-size:13px; padding:.1rem 0; }
|
|
581
|
+
.step b { display:inline-block; width:1.1em; }
|
|
582
|
+
.step.done { opacity:.55; }
|
|
583
|
+
#limits { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:.8rem; }
|
|
584
|
+
#limits input, #limits select { font:inherit; padding:.25rem .4rem;
|
|
585
|
+
border:1px solid var(--line);
|
|
586
|
+
background:transparent; color:inherit; }
|
|
587
|
+
#limits input[type=number] { width:5ch; }
|
|
588
|
+
#limits button { font:inherit; padding:.25rem .8rem; cursor:pointer;
|
|
589
|
+
border:1px solid currentColor; background:transparent; color:inherit; }
|
|
590
|
+
#limits .meta { flex-basis:100%; }
|
|
591
|
+
.state.bad { color: #f85149; }
|
|
592
|
+
.state.wait { color: #d29922; }
|
|
593
|
+
.empty { color: var(--dim); text-align: center; padding: 48px 0; }
|
|
594
|
+
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; }
|
|
595
|
+
|
|
596
|
+
/* A question waiting on somebody here. Loud on purpose: something is
|
|
597
|
+
STOPPED until it is answered, which is not a thing to scroll past. */
|
|
598
|
+
.ask { border:1px solid var(--alarm,#b4442e); border-left-width:3px; padding:.6rem .75rem;
|
|
599
|
+
margin:0 0 .6rem; background:rgba(180,68,46,.05); }
|
|
600
|
+
.askhead { font-weight:600; margin-bottom:.25rem; }
|
|
601
|
+
.opts { margin-top:.5rem; display:flex; gap:.4rem; flex-wrap:wrap; }
|
|
602
|
+
.opts button { font:inherit; padding:.25rem .7rem; cursor:pointer;
|
|
603
|
+
border:1px solid currentColor; background:transparent; color:inherit; }
|
|
604
|
+
.opts button[disabled] { opacity:.4; cursor:default; }
|
|
605
|
+
|
|
606
|
+
/* THE THING YOU TYPE INTO, given the weight of one.
|
|
607
|
+
It was three transparent controls on a hairline, which read as a caption
|
|
608
|
+
under the log rather than as the way to say something. Now it is a card
|
|
609
|
+
that sits still while the conversation scrolls past it. */
|
|
610
|
+
#compose { display:flex; gap:.5rem; align-items:center; margin-top:1.25rem;
|
|
611
|
+
padding:.6rem; border:1px solid var(--line); border-radius:12px;
|
|
612
|
+
background:var(--card); box-shadow:var(--lift-2); }
|
|
613
|
+
#compose select, #compose input { font:inherit; padding:.5rem .6rem;
|
|
614
|
+
border:1px solid var(--line); border-radius:8px;
|
|
615
|
+
background:var(--card); color:inherit; }
|
|
616
|
+
#compose input { flex:1; }
|
|
617
|
+
/* A VISIBLE focus ring on both. Keyboard users were being shown the
|
|
618
|
+
browser default against a transparent control, which on some of them is
|
|
619
|
+
no ring at all. */
|
|
620
|
+
#compose select:focus-visible, #compose input:focus-visible {
|
|
621
|
+
outline:none; border-color:var(--accent-ink); box-shadow:var(--focus); }
|
|
622
|
+
#compose button { font:inherit; font-weight:600; padding:.5rem 1rem; cursor:pointer;
|
|
623
|
+
border:1px solid var(--accent-ink); border-radius:8px;
|
|
624
|
+
background:var(--accent-ink); color:#fff; }
|
|
625
|
+
#compose button:hover { filter:brightness(1.06); }
|
|
626
|
+
#compose button:focus-visible { outline:none; box-shadow:var(--focus); }
|
|
627
|
+
|
|
628
|
+
#setup { margin:0; border:1px solid var(--line); border-radius:10px;
|
|
629
|
+
padding:.6rem .75rem; background:var(--card); }
|
|
630
|
+
#setup summary { cursor:pointer; font-size:.75rem; letter-spacing:.07em;
|
|
631
|
+
text-transform:uppercase; color:var(--dim); font-weight:600; }
|
|
632
|
+
#setup[open] summary { margin-bottom:.5rem; }
|
|
633
|
+
table.ids { border-collapse:collapse; margin:.6rem 0; font-size:.8125rem; width:100%; }
|
|
634
|
+
table.ids th { text-align:left; font-weight:600; opacity:.6; padding:.15rem .6rem .15rem 0; }
|
|
635
|
+
table.ids td { padding:.15rem .6rem .15rem 0; vertical-align:top; }
|
|
636
|
+
#connect { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:.5rem; }
|
|
637
|
+
#connect input { font:inherit; padding:.25rem .4rem; border:1px solid var(--hair,#ddd);
|
|
638
|
+
background:transparent; color:inherit; }
|
|
639
|
+
#connect input:first-of-type { width:16ch; }
|
|
640
|
+
#connect input:last-of-type { flex:1; min-width:20ch; }
|
|
641
|
+
#connect button { font:inherit; padding:.25rem .8rem; cursor:pointer;
|
|
642
|
+
border:1px solid currentColor; background:transparent; color:inherit; }
|
|
643
|
+
#connect .meta { flex-basis:100%; }
|
|
644
|
+
#invite { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:.6rem; }
|
|
645
|
+
#invite input { font:inherit; padding:.25rem .4rem; border:1px solid var(--hair,#ddd);
|
|
646
|
+
background:transparent; color:inherit; width:18ch; }
|
|
647
|
+
#invite select { font:inherit; padding:.25rem .3rem; border:1px solid var(--hair,#ddd);
|
|
648
|
+
background:transparent; color:inherit; }
|
|
649
|
+
#invite button { font:inherit; padding:.25rem .8rem; cursor:pointer;
|
|
650
|
+
border:1px solid currentColor; background:transparent; color:inherit; }
|
|
651
|
+
#invite .meta { flex-basis:100%; }
|
|
652
|
+
#invite code { font-family:ui-monospace,monospace; user-select:all; }
|
|
653
|
+
a.swap, a.secrets, a.unsecret { color:inherit; text-decoration:underline;
|
|
654
|
+
text-underline-offset:2px; cursor:pointer; }
|
|
655
|
+
#grantform { display:flex; gap:.5rem; align-items:center; flex-wrap:wrap; margin-top:.5rem; }
|
|
656
|
+
#grantform input { font:inherit; padding:.25rem .4rem; border:1px solid var(--hair,#ddd);
|
|
657
|
+
background:transparent; color:inherit; }
|
|
658
|
+
#grantform input:first-of-type { width:18ch; }
|
|
659
|
+
#grantform input:last-of-type { flex:1; min-width:24ch; }
|
|
660
|
+
#grantform button { font:inherit; padding:.25rem .8rem; cursor:pointer;
|
|
661
|
+
border:1px solid currentColor; background:transparent; color:inherit; }
|
|
662
|
+
#grantform .meta { flex-basis:100%; }
|
|
663
|
+
</style>
|
|
664
|
+
</head>
|
|
665
|
+
<body>
|
|
666
|
+
<header>
|
|
667
|
+
<h1>AgentSignal</h1>
|
|
668
|
+
<span class="meta" id="channel">connecting…</span>
|
|
669
|
+
<span class="meta" style="margin-left:auto"><span class="dot" id="dot"></span> <span id="count">0</span> messages</span>
|
|
670
|
+
</header>
|
|
671
|
+
<div id="shell">
|
|
672
|
+
<aside id="side" aria-label="Channel">
|
|
673
|
+
<p class="rail-title">Channel</p>
|
|
674
|
+
<nav id="who-nav"></nav>
|
|
675
|
+
<details id="setup"><summary>This machine</summary><div id="setupbody">reading…</div></details>
|
|
676
|
+
</aside>
|
|
677
|
+
<main>
|
|
678
|
+
<div id="pending"></div>
|
|
679
|
+
<div id="log" class="empty">Waiting for traffic…</div>
|
|
680
|
+
<form id="compose" autocomplete="off">
|
|
681
|
+
<select id="to"><option value="">send to…</option></select>
|
|
682
|
+
<input id="say" placeholder="Say something to them" maxlength="1024" />
|
|
683
|
+
<button type="submit">Send</button>
|
|
684
|
+
<span class="meta" id="sent"></span>
|
|
685
|
+
</form>
|
|
686
|
+
</main>
|
|
687
|
+
<aside id="right" aria-label="Who is working">
|
|
688
|
+
<div id="rightbody"></div>
|
|
689
|
+
</aside>
|
|
690
|
+
</div>
|
|
691
|
+
<script>
|
|
692
|
+
// A stable colour per handle, so the same agent looks the same on every
|
|
693
|
+
// line without anyone maintaining a palette.
|
|
694
|
+
const hues = new Map();
|
|
695
|
+
function colourFor(name) {
|
|
696
|
+
if (!hues.has(name)) {
|
|
697
|
+
let h = 0;
|
|
698
|
+
for (const ch of name) h = (h * 31 + ch.charCodeAt(0)) % 360;
|
|
699
|
+
hues.set(name, h);
|
|
700
|
+
}
|
|
701
|
+
return \`hsl(\${hues.get(name)} 65% 45%)\`;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => (
|
|
705
|
+
{ '&': '&', '<': '<', '>': '>', '"': '"' }[c]
|
|
706
|
+
));
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* What to call somebody. ONE function, because this was four.
|
|
710
|
+
*
|
|
711
|
+
* Every one of them preferred the handle, or dropped the name outright, so
|
|
712
|
+
* renaming an agent changed nothing anybody could see. The
|
|
713
|
+
* server-side directory had the identical bug and was fixed on its own,
|
|
714
|
+
* which is how this survived: the fix was verified through the MCP tool,
|
|
715
|
+
* reported as done, and the page it is actually read on still showed the old
|
|
716
|
+
* handle. A second copy is not a smaller version of the bug, it is the
|
|
717
|
+
* reason the first fix looked complete.
|
|
718
|
+
*
|
|
719
|
+
* The HANDLE LEADS because it is the address -- it is what a filter matches
|
|
720
|
+
* and what survives being pasted into a message. The name follows in quotes
|
|
721
|
+
* when it says something the handle does not. When they agree, which is the
|
|
722
|
+
* ordinary case since a handle is usually derived from the name, one is
|
|
723
|
+
* printed rather than the same word twice.
|
|
724
|
+
*/
|
|
725
|
+
const who = (x) => {
|
|
726
|
+
if (!x) return '';
|
|
727
|
+
const handle = x.handle ?? null;
|
|
728
|
+
const name = x.name ?? null;
|
|
729
|
+
if (!handle) return name ?? x.key ?? '';
|
|
730
|
+
return name && name !== handle ? handle + ' "' + name + '"' : handle;
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
// FURTHEST ALONG WINS, after failure. Pending was tested before read and
|
|
734
|
+
// delivered, so a single device still waiting hid the fact that another had
|
|
735
|
+
// already read it -- and "pending" is the one state that reads, to somebody
|
|
736
|
+
// watching a conversation, as "it never arrived".
|
|
737
|
+
//
|
|
738
|
+
// Failure stays first because it is the only one that asks for an action.
|
|
739
|
+
function state(m) {
|
|
740
|
+
if (m.failed > 0) return ['bad', m.failed + ' failed'];
|
|
741
|
+
if (m.read > 0) return ['', m.read + ' read'];
|
|
742
|
+
if (m.delivered > 0) return ['', m.delivered + ' delivered'];
|
|
743
|
+
if (m.pending > 0) return ['wait', m.pending + ' pending'];
|
|
744
|
+
return ['', 'no devices'];
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Which agent this view is for. Empty means the whole channel.
|
|
748
|
+
//
|
|
749
|
+
// ⚠ NO LONGER A CONSTANT, and that is the fix. Clicking an agent used to be a real
|
|
750
|
+
// navigation to /a/<handle>, and the nav built that href with no query — so the click
|
|
751
|
+
// dropped the ?t= the guard requires and came back "Not found." A dropped credential is
|
|
752
|
+
// indistinguishable from a missing agent by design (an error page that explained itself
|
|
753
|
+
// would tell a port scanner what it found), so the message sent people looking for the
|
|
754
|
+
// agent rather than at the link that lost the token.
|
|
755
|
+
//
|
|
756
|
+
// Filtering happens in place now: no request, so there is nothing to drop. See filterTo().
|
|
757
|
+
let AGENT = agentFromPath(location.pathname);
|
|
758
|
+
|
|
759
|
+
// Deliberately no regex. This code is inside a template literal, where every backslash has
|
|
760
|
+
// to be doubled, and a filter that silently stops matching is exactly the kind of bug that
|
|
761
|
+
// escaping mistake produces.
|
|
762
|
+
function agentFromPath(pathname) {
|
|
763
|
+
if (!pathname.startsWith('/a/')) return '';
|
|
764
|
+
|
|
765
|
+
let raw = pathname.slice(3);
|
|
766
|
+
|
|
767
|
+
while (raw.endsWith('/')) raw = raw.slice(0, -1);
|
|
768
|
+
|
|
769
|
+
try {
|
|
770
|
+
return decodeURIComponent(raw);
|
|
771
|
+
} catch {
|
|
772
|
+
return raw;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
// The clock alone is a lie on any channel older than a day: a message from
|
|
777
|
+
// Tuesday and one from ten minutes ago both render as a bare time of day, and
|
|
778
|
+
// the reader has no way to tell them apart. So the date comes back as soon as
|
|
779
|
+
// it stops being today -- and only then, because a timeline where every row
|
|
780
|
+
// repeats today's date is noise around the part that actually varies.
|
|
781
|
+
//
|
|
782
|
+
// Compared by CALENDAR DAY, not by elapsed time. Yesterday at 11pm is two
|
|
783
|
+
// hours ago and still yesterday, and an hours-since threshold gets that
|
|
784
|
+
// backwards in exactly the case where the distinction matters most.
|
|
785
|
+
//
|
|
786
|
+
// All of it in the browser's own locale and zone, which is the point: the
|
|
787
|
+
// server stores UTC, each reader sees their own wall clock, and two people in
|
|
788
|
+
// different cities reading one channel each get their own times without the
|
|
789
|
+
// server knowing where either of them is.
|
|
790
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
791
|
+
|
|
792
|
+
// Which messages the reader has opened.
|
|
793
|
+
//
|
|
794
|
+
// Kept OUT of the DOM on purpose. The log is rebuilt from innerHTML every
|
|
795
|
+
// two seconds, so anything recorded on the element itself is destroyed on
|
|
796
|
+
// the next poll -- a message would collapse under the reader mid-sentence,
|
|
797
|
+
// roughly the most annoying possible behaviour for a live view. Keyed by
|
|
798
|
+
// message id, which is stable across renders in a way that position is not.
|
|
799
|
+
const EXPANDED = new Set();
|
|
800
|
+
|
|
801
|
+
/**
|
|
802
|
+
* Collapse the long ones, and offer "more" only where there is more.
|
|
803
|
+
*
|
|
804
|
+
* Measured rather than guessed. A character count cannot know how a body
|
|
805
|
+
* wraps at this width in this font, so the test is the one the browser can
|
|
806
|
+
* actually answer: is the content taller than the box it is in. That also
|
|
807
|
+
* means a message that is long but narrow -- a stack trace of short lines --
|
|
808
|
+
* is treated on the same footing as prose.
|
|
809
|
+
*/
|
|
810
|
+
function clip() {
|
|
811
|
+
// Cleared first. A re-render replaces innerHTML and takes the buttons with
|
|
812
|
+
// it, but a toggle calls this directly on a DOM nobody rebuilt -- and
|
|
813
|
+
// without this, every click leaves another "show more" behind it.
|
|
814
|
+
for (const stale of document.querySelectorAll('.more')) stale.remove();
|
|
815
|
+
|
|
816
|
+
for (const body of document.querySelectorAll('.body[data-body]')) {
|
|
817
|
+
const id = body.dataset.body;
|
|
818
|
+
const wrap = body.parentElement;
|
|
819
|
+
const open = EXPANDED.has(id);
|
|
820
|
+
|
|
821
|
+
// Clip first, then measure against the clipped box. Measuring an
|
|
822
|
+
// unclipped element only ever says "it fits", because it grew to fit.
|
|
823
|
+
body.classList.add('clip');
|
|
824
|
+
const overflows = body.scrollHeight > body.clientHeight + 1;
|
|
825
|
+
|
|
826
|
+
if (!overflows && !open) {
|
|
827
|
+
// Short enough to show whole. Leave the class off so a body that is
|
|
828
|
+
// exactly at the boundary does not get a pointless fade.
|
|
829
|
+
body.classList.remove('clip');
|
|
830
|
+
wrap.classList.remove('on');
|
|
831
|
+
continue;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
if (open) body.classList.remove('clip');
|
|
835
|
+
wrap.classList.toggle('on', !open);
|
|
836
|
+
|
|
837
|
+
const button = document.createElement('button');
|
|
838
|
+
button.className = 'more';
|
|
839
|
+
button.type = 'button';
|
|
840
|
+
button.dataset.toggle = id;
|
|
841
|
+
button.textContent = open ? 'show less' : 'show more';
|
|
842
|
+
wrap.after(button);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// Delegated, and bound ONCE outside the render. A listener attached per
|
|
847
|
+
// button would be re-attached on every poll and leak one per message per two
|
|
848
|
+
// seconds; delegation survives innerHTML being replaced underneath it.
|
|
849
|
+
document.addEventListener('click', (event) => {
|
|
850
|
+
const id = event.target?.dataset?.toggle;
|
|
851
|
+
if (!id) return;
|
|
852
|
+
if (EXPANDED.has(id)) EXPANDED.delete(id);
|
|
853
|
+
else EXPANDED.add(id);
|
|
854
|
+
clip();
|
|
855
|
+
});
|
|
856
|
+
|
|
857
|
+
function stamp(iso) {
|
|
858
|
+
// Falsy first, and separately, because new Date(null) is not an invalid
|
|
859
|
+
// date -- it is the epoch, and the check below waves it through as a real
|
|
860
|
+
// timestamp from 1969.
|
|
861
|
+
if (!iso) return '';
|
|
862
|
+
const d = new Date(iso);
|
|
863
|
+
if (isNaN(d.getTime())) return '';
|
|
864
|
+
// Recomputed per call rather than captured once, because this page is left
|
|
865
|
+
// open. A midnight frozen at load time would keep calling today "yesterday"
|
|
866
|
+
// for everyone still watching after the date rolls over.
|
|
867
|
+
const midnight = new Date();
|
|
868
|
+
midnight.setHours(0, 0, 0, 0);
|
|
869
|
+
// Seconds are dropped. They were never the question being asked of a
|
|
870
|
+
// conversation, and they made every row wider than it needed to be.
|
|
871
|
+
const clock = d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
|
|
872
|
+
const days = Math.floor((midnight - d) / DAY_MS);
|
|
873
|
+
if (days < 0) return clock; // today
|
|
874
|
+
if (days < 1) return 'Yesterday ' + clock;
|
|
875
|
+
// Six, not seven: a weekday name seven days back collides with today's.
|
|
876
|
+
if (days < 6) return d.toLocaleDateString([], { weekday: 'short' }) + ' ' + clock;
|
|
877
|
+
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + clock;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// The other agents, as links. Rendered once: the roster changes when somebody
|
|
881
|
+
// joins, which is rare enough that re-reading it every two seconds is waste.
|
|
882
|
+
// The token this page was opened with, put back on every request. Kept out
|
|
883
|
+
// of the markup: it is in the address bar either way, but a value in the DOM
|
|
884
|
+
// is one an extension or a stray script can read without navigating.
|
|
885
|
+
const T = new URLSearchParams(location.search).get('t') || '';
|
|
886
|
+
const q = (path) => path + (path.includes('?') ? '&' : '?') + 't=' + encodeURIComponent(T);
|
|
887
|
+
|
|
888
|
+
async function post(path, payload) {
|
|
889
|
+
const response = await fetch(q(path), {
|
|
890
|
+
method: 'POST',
|
|
891
|
+
headers: { 'Content-Type': 'application/json' },
|
|
892
|
+
body: JSON.stringify(payload),
|
|
893
|
+
});
|
|
894
|
+
return response.json().catch(() => ({ error: 'Unreadable reply.' }));
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
// The roster, kept so the right-hand panel can describe the same agents the
|
|
898
|
+
// log is showing without fetching them a second time and risking two
|
|
899
|
+
// answers to one question on one screen.
|
|
900
|
+
let ROSTER = [];
|
|
901
|
+
|
|
902
|
+
async function roster() {
|
|
903
|
+
let list;
|
|
904
|
+
try {
|
|
905
|
+
list = await (await fetch(q('/agents'))).json();
|
|
906
|
+
} catch {
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
ROSTER = list.recipients ?? [];
|
|
910
|
+
// People are listed too, and a person has no chat to open -- nothing is
|
|
911
|
+
// sent FROM a phone. Agents only.
|
|
912
|
+
const everyone = list.recipients ?? [];
|
|
913
|
+
|
|
914
|
+
// The send list includes PEOPLE, unlike the nav below it. You cannot open
|
|
915
|
+
// a person's conversation -- nothing is sent from a phone -- but notifying
|
|
916
|
+
// one is the most useful thing this box does.
|
|
917
|
+
const to = document.getElementById('to');
|
|
918
|
+
for (const r of everyone) {
|
|
919
|
+
const option = document.createElement('option');
|
|
920
|
+
option.value = r.key;
|
|
921
|
+
option.textContent = (who(r) || r.key) + (r.is_agent ? '' : ' (person)');
|
|
922
|
+
to.appendChild(option);
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
const agents = everyone.filter((r) => r.is_agent);
|
|
926
|
+
if (agents.length === 0) return;
|
|
927
|
+
|
|
928
|
+
// Live means "did something recently", NOT reachable. A device row
|
|
929
|
+
// survives a laptop being shut, so reachable stays true for an agent that
|
|
930
|
+
// has not run since last week -- and an interface that shows that one as
|
|
931
|
+
// available is worse than one that shows nothing. Fifteen minutes matches
|
|
932
|
+
// the window /agentsignal:fleet uses, so the two cannot disagree.
|
|
933
|
+
const LIVE_MS = 15 * 60 * 1000;
|
|
934
|
+
const now = Date.now();
|
|
935
|
+
|
|
936
|
+
const since = (iso) => {
|
|
937
|
+
if (!iso) return ['stale', 'never seen'];
|
|
938
|
+
const ms = now - Date.parse(iso);
|
|
939
|
+
const live = ms < LIVE_MS;
|
|
940
|
+
const mins = Math.floor(ms / 60000);
|
|
941
|
+
if (mins < 1) return [live ? 'live' : 'stale', 'just now'];
|
|
942
|
+
if (mins < 60) return [live ? 'live' : 'stale', mins + 'm ago'];
|
|
943
|
+
const hours = Math.floor(mins / 60);
|
|
944
|
+
if (hours < 48) return ['stale', hours + 'h ago'];
|
|
945
|
+
return ['stale', Math.floor(hours / 24) + 'd ago'];
|
|
946
|
+
};
|
|
947
|
+
|
|
948
|
+
// ⚠ THE HREFS STAY TOKEN-FREE. The token authorises send and answer on a viewer holding a
|
|
949
|
+
// real API key, and it is deliberately kept out of the DOM — the address bar has it either
|
|
950
|
+
// way, but a value in the markup is one an extension or a stray script can read without
|
|
951
|
+
// navigating. data-agent is what the click handler reads instead; the href is there so
|
|
952
|
+
// these are real links (focusable, with a status-bar target) and so a cold load of a
|
|
953
|
+
// pasted /a/<agent>?t=… still works.
|
|
954
|
+
const entry = (a) => {
|
|
955
|
+
const name = who(a) || a.key;
|
|
956
|
+
const [state, when] = since(a.last_seen_at);
|
|
957
|
+
// Linked by handle rather than key: it survives being pasted into a
|
|
958
|
+
// chat message, and the filter matches either.
|
|
959
|
+
const at = a.handle ?? a.key;
|
|
960
|
+
const on = AGENT === a.key || AGENT === a.handle ? ' on' : '';
|
|
961
|
+
// Both, because a pasted URL may name either and the highlight has to follow the
|
|
962
|
+
// one that is actually filtering. matchesNav() checks the pair.
|
|
963
|
+
/**
|
|
964
|
+
* HANDLE ON ONE LINE, DISPLAY NAME UNDER IT.
|
|
965
|
+
*
|
|
966
|
+
* who() joins them as handle "name", which is right in a sentence and
|
|
967
|
+
* far too long for a 280px rail -- every agent rendered as
|
|
968
|
+
* agentsignal-dev "claude-7f… and the two names it is trying to tell
|
|
969
|
+
* apart were both cut off. Stacked, both fit and the handle, which is
|
|
970
|
+
* what links and filters use, is the one in full strength.
|
|
971
|
+
*
|
|
972
|
+
* No backticks anywhere in this comment: it lives inside the page
|
|
973
|
+
* template literal, and one would end the string. The file says so at
|
|
974
|
+
* the top and this still caught me.
|
|
975
|
+
*/
|
|
976
|
+
const alias = a.name && a.name !== a.handle ? a.name : null;
|
|
977
|
+
return '<a href="/a/' + encodeURIComponent(at) + '" data-agent="' + esc(at) +
|
|
978
|
+
'" data-key="' + esc(a.key) + '" class="' + state + on +
|
|
979
|
+
'" title="' + esc(name) + ' — last seen ' + esc(when) + '"><i></i>' +
|
|
980
|
+
'<span class="stack"><span class="nm">' + esc(a.handle ?? name) + '</span>' +
|
|
981
|
+
(alias ? '<small class="alias">' + esc(alias) + '</small>' : '') +
|
|
982
|
+
'</span><em>' + esc(when) + '</em></a>';
|
|
983
|
+
};
|
|
984
|
+
|
|
985
|
+
/**
|
|
986
|
+
* NESTED BY WHO INVITED WHOM, which is a fact the server already keeps.
|
|
987
|
+
*
|
|
988
|
+
* The sponsored_by field is the invitation graph: an agent that invited others
|
|
989
|
+
* is exactly "a subagent that became a planner", so the hierarchy is read
|
|
990
|
+
* rather than invented. Nothing here decides who is whose parent.
|
|
991
|
+
*
|
|
992
|
+
* UNDEFINED IS NOT NULL, and conflating them would build a confident lie.
|
|
993
|
+
* Null means the server answered and nobody invited this agent. Undefined
|
|
994
|
+
* means an older server did not carry the field at all -- and treating
|
|
995
|
+
* that as null would draw every agent as a root, presenting a flat fleet
|
|
996
|
+
* as a deliberate structure. So when the field is missing anywhere, the
|
|
997
|
+
* whole tree falls back to a flat list: an honest absence of structure
|
|
998
|
+
* beats a plausible wrong one.
|
|
999
|
+
*/
|
|
1000
|
+
const knowsSponsors = agents.every((a) => a.sponsored_by !== undefined);
|
|
1001
|
+
const byKey = new Map(agents.filter((a) => a.key).map((a) => [a.key, a]));
|
|
1002
|
+
const children = new Map();
|
|
1003
|
+
for (const a of agents) {
|
|
1004
|
+
if (!a.key) continue;
|
|
1005
|
+
// An unknown sponsor -- invited by somebody outside this channel -- sits
|
|
1006
|
+
// at the top rather than vanishing. A missing parent must never take its
|
|
1007
|
+
// children off the screen with it.
|
|
1008
|
+
const parent =
|
|
1009
|
+
knowsSponsors && a.sponsored_by && byKey.has(a.sponsored_by) ? a.sponsored_by : null;
|
|
1010
|
+
if (!children.has(parent)) children.set(parent, []);
|
|
1011
|
+
children.get(parent).push(a);
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// Depth-capped. A cycle in the graph would otherwise recurse until the
|
|
1015
|
+
// stack gives out, and the page would go blank for a data problem it did
|
|
1016
|
+
// not cause. The seen set also stops one agent being drawn twice.
|
|
1017
|
+
const seen = new Set();
|
|
1018
|
+
const branch = (parentKey, depth) => {
|
|
1019
|
+
if (depth > 6) return '';
|
|
1020
|
+
return (children.get(parentKey) ?? [])
|
|
1021
|
+
.map((a) => {
|
|
1022
|
+
if (seen.has(a.key)) return '';
|
|
1023
|
+
seen.add(a.key);
|
|
1024
|
+
const kids = branch(a.key, depth + 1);
|
|
1025
|
+
return (
|
|
1026
|
+
'<div class="branch">' +
|
|
1027
|
+
entry(a) +
|
|
1028
|
+
(kids ? '<div class="kids">' + kids + '</div>' : '') +
|
|
1029
|
+
'</div>'
|
|
1030
|
+
);
|
|
1031
|
+
})
|
|
1032
|
+
.join('');
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
document.getElementById('who-nav').innerHTML =
|
|
1036
|
+
'<a href="/" data-agent="" data-key="" class="whole' + (AGENT ? '' : ' on') + '">' +
|
|
1037
|
+
'<span class="nm">' + esc((list.channel && list.channel.name) || 'whole channel') + '</span>' +
|
|
1038
|
+
'<em>everything</em></a>' +
|
|
1039
|
+
branch(null, 0);
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/** Whether a nav link is the one currently filtering. Key or handle, either may be in the URL. */
|
|
1043
|
+
function matchesNav(link) {
|
|
1044
|
+
const at = link.dataset.agent ?? '';
|
|
1045
|
+
const key = link.dataset.key ?? '';
|
|
1046
|
+
|
|
1047
|
+
return AGENT === at || ( AGENT !== '' && AGENT === key );
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/** Move the highlight without re-rendering the roster, which would refetch /agents. */
|
|
1051
|
+
function markNav() {
|
|
1052
|
+
for (const link of document.querySelectorAll('#who-nav a')) {
|
|
1053
|
+
link.classList.toggle('on', matchesNav(link));
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Show one agent's side of the channel, or all of it, without leaving the page.
|
|
1059
|
+
*
|
|
1060
|
+
* Both directions of the conversation, not just what was sent TO them: the server's
|
|
1061
|
+
* involves() already tests from/from_handle/to/to_handle, so passing ?agent= is enough and
|
|
1062
|
+
* the browser is never handed traffic it did not ask for.
|
|
1063
|
+
*
|
|
1064
|
+
* @param {string} agent Handle or key, '' for the whole channel.
|
|
1065
|
+
* @param {boolean} push Whether to add a history entry — false when popstate brought us here.
|
|
1066
|
+
*/
|
|
1067
|
+
function filterTo(agent, push) {
|
|
1068
|
+
AGENT = agent;
|
|
1069
|
+
|
|
1070
|
+
if (push) {
|
|
1071
|
+
// ⚠ location.search IS CARRIED, and it has to be. What pushState leaves in the address
|
|
1072
|
+
// bar is what a reload requests, and the guard refuses a request without ?t=. This
|
|
1073
|
+
// preserves a value that is already there rather than exposing a new one — and it is
|
|
1074
|
+
// why a deep link keeps working after filtering around.
|
|
1075
|
+
const path = agent ? '/a/' + encodeURIComponent(agent) : '/';
|
|
1076
|
+
|
|
1077
|
+
history.pushState(null, '', path + location.search);
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
markNav();
|
|
1081
|
+
tick();
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* Following the newest message, and knowing when to stop.
|
|
1086
|
+
*
|
|
1087
|
+
* Deliberately NOT inside filterTo(): that function is lifted out of the
|
|
1088
|
+
* served page and executed on its own by the suite, with history, location,
|
|
1089
|
+
* markNav and tick supplied as arguments and no DOM behind them. A window
|
|
1090
|
+
* reference in there is a ReferenceError in a test that is checking
|
|
1091
|
+
* something else entirely, and the failure would name the wrong thing.
|
|
1092
|
+
*
|
|
1093
|
+
* A THRESHOLD RATHER THAN AN EXACT BOTTOM. Fractional device pixels mean
|
|
1094
|
+
* scrollY + innerHeight is often a pixel or two short of scrollHeight while
|
|
1095
|
+
* visibly at the bottom, and an exact comparison would unpin the view for
|
|
1096
|
+
* a rounding error nobody can see.
|
|
1097
|
+
*/
|
|
1098
|
+
const NEAR_BOTTOM = 120;
|
|
1099
|
+
let stick = true;
|
|
1100
|
+
let shownAgent = null;
|
|
1101
|
+
|
|
1102
|
+
const atBottom = () =>
|
|
1103
|
+
document.documentElement.scrollHeight - (window.scrollY + window.innerHeight) <= NEAR_BOTTOM;
|
|
1104
|
+
|
|
1105
|
+
const toBottom = () => window.scrollTo(0, document.documentElement.scrollHeight);
|
|
1106
|
+
|
|
1107
|
+
/**
|
|
1108
|
+
* MEASURED BEFORE THE REDRAW, and not from a scroll listener.
|
|
1109
|
+
*
|
|
1110
|
+
* The first version tracked this on the window's scroll event, which is the
|
|
1111
|
+
* obvious way and is wrong here. Replacing the log's innerHTML collapses the
|
|
1112
|
+
* document to almost nothing for an instant; the browser emits a scroll
|
|
1113
|
+
* event while it is short, and at that moment scrollHeight is barely more
|
|
1114
|
+
* than the viewport, so "are we at the bottom" answers YES no matter where
|
|
1115
|
+
* the reader actually was. The flag flipped back to true on every tick and
|
|
1116
|
+
* the next line dragged them down -- the page mistaking its own re-render
|
|
1117
|
+
* for the reader scrolling.
|
|
1118
|
+
*
|
|
1119
|
+
* Asking the question immediately before the mutation removes the race
|
|
1120
|
+
* rather than papering over it: there is no window in which the document is
|
|
1121
|
+
* half-built, because nothing has been rebuilt yet.
|
|
1122
|
+
*/
|
|
1123
|
+
const rememberPlace = () => {
|
|
1124
|
+
stick = atBottom();
|
|
1125
|
+
};
|
|
1126
|
+
|
|
1127
|
+
/*
|
|
1128
|
+
* The right-hand panel has no toggle any more, so there is nothing to
|
|
1129
|
+
* remember about it.
|
|
1130
|
+
*
|
|
1131
|
+
* What was here: a floating button, and the open state kept in localStorage
|
|
1132
|
+
* under 'agentsignal.right' so a hand-reload did not close it. Both are gone
|
|
1133
|
+
* with the button. Any value left in that key by an older build is simply
|
|
1134
|
+
* never read -- it is one small string in localStorage for a page served
|
|
1135
|
+
* from localhost, and going out of the way to delete it would be more code
|
|
1136
|
+
* than leaving it.
|
|
1137
|
+
*/
|
|
1138
|
+
|
|
1139
|
+
// Who this machine is. Sent with the messages rather than fetched separately,
|
|
1140
|
+
// so the two cannot disagree about the same render.
|
|
1141
|
+
let SELF = null;
|
|
1142
|
+
|
|
1143
|
+
async function tick() {
|
|
1144
|
+
let data;
|
|
1145
|
+
try {
|
|
1146
|
+
data = await (await fetch(q('/messages' + (AGENT ? '?agent=' + encodeURIComponent(AGENT) : '')))).json();
|
|
1147
|
+
} catch {
|
|
1148
|
+
document.getElementById('dot').style.background = '#f85149';
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
document.getElementById('dot').style.background = '#3fb950';
|
|
1152
|
+
SELF = data.self ?? SELF;
|
|
1153
|
+
|
|
1154
|
+
if (data.error) {
|
|
1155
|
+
document.getElementById('log').className = 'empty';
|
|
1156
|
+
document.getElementById('log').textContent = data.error;
|
|
1157
|
+
return;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
document.getElementById('channel').textContent =
|
|
1161
|
+
data.channel ? data.channel.name + ' · ' + data.channel.ref : '';
|
|
1162
|
+
document.getElementById('count').textContent = data.messages.length;
|
|
1163
|
+
|
|
1164
|
+
const log = document.getElementById('log');
|
|
1165
|
+
if (!data.messages.length) {
|
|
1166
|
+
log.className = 'empty';
|
|
1167
|
+
log.textContent = 'Waiting for traffic…';
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
log.className = '';
|
|
1171
|
+
|
|
1172
|
+
// Where the reader is, asked while the page is still intact.
|
|
1173
|
+
rememberPlace();
|
|
1174
|
+
|
|
1175
|
+
// Oldest first, so a conversation reads downward the way one is written.
|
|
1176
|
+
log.innerHTML = data.messages.slice().reverse().map((m) => {
|
|
1177
|
+
// No sender means the channel's own key sent it, which is a real
|
|
1178
|
+
// distinction rather than something to guess at.
|
|
1179
|
+
const from = m.from_handle ?? (m.from ? m.from : null);
|
|
1180
|
+
const who = from ?? 'channel key';
|
|
1181
|
+
const to = m.to_handle ?? m.to ?? (m.target_kind === 'group' ? 'group' : 'everyone');
|
|
1182
|
+
// Events carry a tag rather than a shape, so this is the only place that
|
|
1183
|
+
// has to know the difference.
|
|
1184
|
+
if (m.event) {
|
|
1185
|
+
const who = m.from_handle ?? m.from ?? 'someone';
|
|
1186
|
+
return \`<div class="event"><b>\${esc(who)}</b> \${esc(m.preview || m.event)}<span class="time">\${esc(stamp(m.created_at))}</span></div>\`;
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
const [cls, label] = state(m);
|
|
1190
|
+
// Mine by recipient key first, handle second: the key is the identity and
|
|
1191
|
+
// the handle is a label somebody could reuse. Matched on the SENDER only
|
|
1192
|
+
// -- a message TO me from somebody else is still theirs, and putting it
|
|
1193
|
+
// on my side would reverse the conversation.
|
|
1194
|
+
const mine = SELF && (m.from === SELF.key || (SELF.handle && from === SELF.handle));
|
|
1195
|
+
return \`<div class="msg\${mine ? ' mine' : ''}" style="--accent:\${colourFor(who)}">
|
|
1196
|
+
<div class="who">
|
|
1197
|
+
<span class="from">\${esc(who)}</span>
|
|
1198
|
+
<span class="arrow">→ \${esc(to)}</span>
|
|
1199
|
+
<span class="time">\${esc(stamp(m.created_at))}</span>
|
|
1200
|
+
<span class="state \${cls}">\${esc(label)}</span>
|
|
1201
|
+
</div>
|
|
1202
|
+
\${m.title && m.title !== who ? '<div class="title">' + esc(m.title) + '</div>' : ''}
|
|
1203
|
+
<div class="clipwrap" data-wrap="\${esc(m.id)}"><div class="body" data-body="\${esc(m.id)}">\${esc(m.body ?? m.preview)}\${m.truncated ? '…' : ''}</div></div>
|
|
1204
|
+
</div>\`;
|
|
1205
|
+
}).join('');
|
|
1206
|
+
|
|
1207
|
+
clip();
|
|
1208
|
+
|
|
1209
|
+
// THE NEWEST MESSAGE IS THE ONE TO SHOW. Oldest reads first downward, so
|
|
1210
|
+
// that is the bottom, and a page that opens at the top opens on a
|
|
1211
|
+
// conversation from two days ago.
|
|
1212
|
+
//
|
|
1213
|
+
// Sticky rather than unconditional, because this redraws every two
|
|
1214
|
+
// seconds: scrolling down on every tick would drag somebody out of the
|
|
1215
|
+
// history they are reading, repeatedly, with no way to stop it short of
|
|
1216
|
+
// closing the page. So it follows only while they are already at the
|
|
1217
|
+
// bottom -- which is where a page that has just opened is.
|
|
1218
|
+
//
|
|
1219
|
+
// Re-pinned when the filter changes, because that is a new view rather
|
|
1220
|
+
// than more of the current one, and its newest message is the point of it.
|
|
1221
|
+
if (shownAgent !== AGENT) {
|
|
1222
|
+
shownAgent = AGENT;
|
|
1223
|
+
stick = true;
|
|
1224
|
+
}
|
|
1225
|
+
if (stick) toBottom();
|
|
1226
|
+
|
|
1227
|
+
workers(data.messages);
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/**
|
|
1231
|
+
* WHO IS WORKING, described only by things that are true.
|
|
1232
|
+
*
|
|
1233
|
+
* The ask was "each agent's current task, summarised to a few words, and the
|
|
1234
|
+
* files being passed around". Neither exists. Nothing reports what an agent
|
|
1235
|
+
* is DOING -- the directory carries a description set once at registration,
|
|
1236
|
+
* capabilities, and a last-seen stamp -- and message bodies are free text,
|
|
1237
|
+
* so files "being passed around" would mean pattern-matching paths out of
|
|
1238
|
+
* prose and presenting the matches as fact.
|
|
1239
|
+
*
|
|
1240
|
+
* So this shows the nearest TRUE thing and labels it as what it is: the last
|
|
1241
|
+
* thing each agent said, called "last said" rather than "current task".
|
|
1242
|
+
* Those are different claims and the difference matters -- an agent's most
|
|
1243
|
+
* recent message is frequently not what it is working on, and a panel that
|
|
1244
|
+
* called it a task would be confidently wrong in a way nobody could check.
|
|
1245
|
+
*
|
|
1246
|
+
* A real "current task" needs agents to publish one. That is a field and a
|
|
1247
|
+
* tool, not a rendering, and inventing it here would produce exactly the
|
|
1248
|
+
* column-that-is-not-a-feature this codebase keeps having to dig out.
|
|
1249
|
+
*
|
|
1250
|
+
* Scoped to the CURRENT VIEW, so filtering to one agent describes that
|
|
1251
|
+
* conversation rather than the whole channel -- otherwise the two halves of
|
|
1252
|
+
* the screen would be answering different questions.
|
|
1253
|
+
*/
|
|
1254
|
+
/**
|
|
1255
|
+
* How old a stated task is, said plainly.
|
|
1256
|
+
*
|
|
1257
|
+
* "working on X" with no age is believed indefinitely, which is the failure
|
|
1258
|
+
* the timestamp exists to prevent -- so this never returns an empty string.
|
|
1259
|
+
* An unparseable or missing stamp says so rather than rendering nothing,
|
|
1260
|
+
* because a blank beside a task reads as "just now" to anybody skimming.
|
|
1261
|
+
*/
|
|
1262
|
+
function ago(iso) {
|
|
1263
|
+
if (!iso) return 'said at an unknown time';
|
|
1264
|
+
const ms = Date.now() - Date.parse(iso);
|
|
1265
|
+
if (Number.isNaN(ms)) return 'said at an unknown time';
|
|
1266
|
+
const mins = Math.floor(ms / 60000);
|
|
1267
|
+
if (mins < 1) return 'said just now';
|
|
1268
|
+
if (mins < 60) return 'said ' + mins + 'm ago';
|
|
1269
|
+
const hours = Math.floor(mins / 60);
|
|
1270
|
+
if (hours < 48) return 'said ' + hours + 'h ago';
|
|
1271
|
+
return 'said ' + Math.floor(hours / 24) + 'd ago';
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
function workers(messages) {
|
|
1275
|
+
const box = document.getElementById('rightbody');
|
|
1276
|
+
if (!box) return;
|
|
1277
|
+
|
|
1278
|
+
const LIVE_MS = 15 * 60 * 1000;
|
|
1279
|
+
const now = Date.now();
|
|
1280
|
+
const agents = ROSTER.filter((r) => r.is_agent && r.key);
|
|
1281
|
+
if (!agents.length) {
|
|
1282
|
+
box.innerHTML = '<div class="meta">Nobody else is in this channel yet.</div>';
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// Newest first is what the API returns, so the first hit per sender IS the
|
|
1287
|
+
// most recent thing they said -- no sorting, and no chance of showing the
|
|
1288
|
+
// oldest by accident.
|
|
1289
|
+
const lastFrom = new Map();
|
|
1290
|
+
const countFrom = new Map();
|
|
1291
|
+
for (const m of messages ?? []) {
|
|
1292
|
+
const from = m.from_handle ?? m.from ?? null;
|
|
1293
|
+
if (!from) continue;
|
|
1294
|
+
countFrom.set(from, (countFrom.get(from) ?? 0) + 1);
|
|
1295
|
+
if (!lastFrom.has(from)) lastFrom.set(from, m);
|
|
1296
|
+
}
|
|
1297
|
+
|
|
1298
|
+
box.innerHTML =
|
|
1299
|
+
// The same label treatment the left rail uses. Two rails whose headings
|
|
1300
|
+
// are styled differently read as a panel and an afterthought.
|
|
1301
|
+
'<p class="rail-title">' +
|
|
1302
|
+
(AGENT ? 'In this conversation' : 'Who is working') +
|
|
1303
|
+
'</p>' +
|
|
1304
|
+
agents
|
|
1305
|
+
.map((a) => {
|
|
1306
|
+
const at = a.handle ?? a.key;
|
|
1307
|
+
const said = lastFrom.get(at) ?? lastFrom.get(a.key);
|
|
1308
|
+
const count = countFrom.get(at) ?? countFrom.get(a.key) ?? 0;
|
|
1309
|
+
const ms = a.last_seen_at ? now - Date.parse(a.last_seen_at) : Infinity;
|
|
1310
|
+
const live = ms < LIVE_MS;
|
|
1311
|
+
// Null connection_type means nobody chose, which behaves as partner
|
|
1312
|
+
// -- said as "partner" rather than left blank, because blank reads as
|
|
1313
|
+
// a missing value rather than as the default it actually is.
|
|
1314
|
+
const kind = a.connection_type ?? 'partner';
|
|
1315
|
+
const body = said ? (said.body ?? said.preview ?? '') : '';
|
|
1316
|
+
|
|
1317
|
+
return (
|
|
1318
|
+
'<div class="worker' + (live ? ' live' : '') + '">' +
|
|
1319
|
+
// Stacked for the same reason as the left rail: handle "name" on
|
|
1320
|
+
// one line in a 280px card truncates both of the things it is
|
|
1321
|
+
// trying to distinguish.
|
|
1322
|
+
'<div class="top" title="' + esc(who(a) || a.key) + '"><i></i>' +
|
|
1323
|
+
'<span class="stack"><span class="nm">' +
|
|
1324
|
+
esc(a.handle ?? a.name ?? a.key) +
|
|
1325
|
+
'</span>' +
|
|
1326
|
+
(a.name && a.name !== a.handle ? '<small class="alias">' + esc(a.name) + '</small>' : '') +
|
|
1327
|
+
'</span><span class="kind">' +
|
|
1328
|
+
esc(kind) +
|
|
1329
|
+
'</span></div>' +
|
|
1330
|
+
/**
|
|
1331
|
+
* THE TASK, WITH ITS AGE, or the last thing said as a fallback.
|
|
1332
|
+
*
|
|
1333
|
+
* An agent that has called set_task gets its own words shown as a
|
|
1334
|
+
* task. One that has not still shows "last said", because that is
|
|
1335
|
+
* the true thing available and the label says which it is.
|
|
1336
|
+
*
|
|
1337
|
+
* The age is never omitted. "rebuilding the index" is useful this
|
|
1338
|
+
* afternoon and a lie on Thursday, and an agent that crashed
|
|
1339
|
+
* mid-task leaves its last status looking live forever -- so how
|
|
1340
|
+
* old it is IS part of the claim, not decoration beside it.
|
|
1341
|
+
*/
|
|
1342
|
+
(a.current_task
|
|
1343
|
+
? '<div class="said">' +
|
|
1344
|
+
esc(a.current_task) +
|
|
1345
|
+
'</div><div class="meta" style="font-size:11px">' +
|
|
1346
|
+
esc(ago(a.current_task_at)) +
|
|
1347
|
+
'</div>'
|
|
1348
|
+
: said
|
|
1349
|
+
? '<div class="said">' +
|
|
1350
|
+
esc(said.encrypted ? '(encrypted)' : body.slice(0, 160)) +
|
|
1351
|
+
'</div><div class="meta" style="font-size:11px">last said · ' +
|
|
1352
|
+
esc(String(count)) +
|
|
1353
|
+
(count === 1 ? ' message here' : ' messages here') +
|
|
1354
|
+
'</div>'
|
|
1355
|
+
: '<div class="none">nothing in this view</div>') +
|
|
1356
|
+
// The close the first version left off. An unclosed div does not
|
|
1357
|
+
// error -- the parser nests the next one inside it, so every card
|
|
1358
|
+
// contained all the cards below it and each one grew taller than
|
|
1359
|
+
// the last. Visible only as odd spacing until you read the tree.
|
|
1360
|
+
'</div>'
|
|
1361
|
+
);
|
|
1362
|
+
})
|
|
1363
|
+
.join('');
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
/**
|
|
1367
|
+
* Questions waiting on an identity this machine holds.
|
|
1368
|
+
*
|
|
1369
|
+
* Rendered above the log rather than inline with it, because a blocked
|
|
1370
|
+
* subagent is not a thing to scroll past: it is stopped until somebody
|
|
1371
|
+
* answers, and the whole point of showing it here is that the person
|
|
1372
|
+
* watching can unblock it without going back to a terminal.
|
|
1373
|
+
*/
|
|
1374
|
+
async function pending() {
|
|
1375
|
+
let data;
|
|
1376
|
+
try {
|
|
1377
|
+
data = await (await fetch(q('/pending'))).json();
|
|
1378
|
+
} catch {
|
|
1379
|
+
return;
|
|
1380
|
+
}
|
|
1381
|
+
const box = document.getElementById('pending');
|
|
1382
|
+
const items = data.pending ?? [];
|
|
1383
|
+
if (!items.length) {
|
|
1384
|
+
box.innerHTML = '';
|
|
1385
|
+
return;
|
|
1386
|
+
}
|
|
1387
|
+
box.innerHTML = items
|
|
1388
|
+
.map(
|
|
1389
|
+
(m) =>
|
|
1390
|
+
'<div class="ask"><div class="askhead">' +
|
|
1391
|
+
esc(m.title || 'Waiting on an answer') +
|
|
1392
|
+
'<span class="meta"> — as ' +
|
|
1393
|
+
esc(m.as_handle || m.as) +
|
|
1394
|
+
'</span></div><div class="body">' +
|
|
1395
|
+
esc(m.body ?? '') +
|
|
1396
|
+
'</div><div class="opts">' +
|
|
1397
|
+
m.options
|
|
1398
|
+
.map(
|
|
1399
|
+
(o) =>
|
|
1400
|
+
'<button data-d="' +
|
|
1401
|
+
esc(m.delivery_id) +
|
|
1402
|
+
'" data-as="' +
|
|
1403
|
+
esc(m.as) +
|
|
1404
|
+
'" data-i="' +
|
|
1405
|
+
m.options.indexOf(o) +
|
|
1406
|
+
'">' +
|
|
1407
|
+
esc(o) +
|
|
1408
|
+
'</button>',
|
|
1409
|
+
)
|
|
1410
|
+
.join('') +
|
|
1411
|
+
'</div></div>',
|
|
1412
|
+
)
|
|
1413
|
+
.join('');
|
|
1414
|
+
|
|
1415
|
+
for (const button of box.querySelectorAll('button')) {
|
|
1416
|
+
button.onclick = async () => {
|
|
1417
|
+
for (const b of box.querySelectorAll('button')) b.disabled = true;
|
|
1418
|
+
const result = await post('/respond', {
|
|
1419
|
+
delivery_id: button.dataset.d,
|
|
1420
|
+
as: button.dataset.as,
|
|
1421
|
+
option_index: Number(button.dataset.i),
|
|
1422
|
+
});
|
|
1423
|
+
// Re-read rather than assume: the answer may have been recorded by
|
|
1424
|
+
// somebody else's device between the page rendering and this click,
|
|
1425
|
+
// and the list is the truth about what is still waiting.
|
|
1426
|
+
if (result.error) window.alert(result.error);
|
|
1427
|
+
pending();
|
|
1428
|
+
};
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
document.getElementById('compose').onsubmit = async (event) => {
|
|
1433
|
+
event.preventDefault();
|
|
1434
|
+
const to = document.getElementById('to').value;
|
|
1435
|
+
const say = document.getElementById('say');
|
|
1436
|
+
const note = document.getElementById('sent');
|
|
1437
|
+
if (!to || !say.value.trim()) return;
|
|
1438
|
+
note.textContent = 'sending…';
|
|
1439
|
+
const result = await post('/send', { to, body: say.value.trim() });
|
|
1440
|
+
if (result.error) {
|
|
1441
|
+
note.textContent = result.error;
|
|
1442
|
+
return;
|
|
1443
|
+
}
|
|
1444
|
+
say.value = '';
|
|
1445
|
+
note.textContent = 'sent';
|
|
1446
|
+
setTimeout(() => (note.textContent = ''), 2000);
|
|
1447
|
+
tick();
|
|
1448
|
+
};
|
|
1449
|
+
|
|
1450
|
+
/**
|
|
1451
|
+
* What this machine is, and how to add a project to it.
|
|
1452
|
+
*
|
|
1453
|
+
* The folder half of setting up cannot live on a website: agentsignal.net
|
|
1454
|
+
* cannot enumerate the directories on your laptop and should not be able to.
|
|
1455
|
+
* So it is here, next to the conversation it affects.
|
|
1456
|
+
*/
|
|
1457
|
+
// Held across renders so the limits form can be drawn from what the SERVER
|
|
1458
|
+
// last said, not from what was last typed into it.
|
|
1459
|
+
let LIMITS = null;
|
|
1460
|
+
|
|
1461
|
+
async function setup() {
|
|
1462
|
+
let d;
|
|
1463
|
+
try {
|
|
1464
|
+
d = await (await fetch(q('/setup'))).json();
|
|
1465
|
+
} catch {
|
|
1466
|
+
return;
|
|
1467
|
+
}
|
|
1468
|
+
const rows = (d.identities || [])
|
|
1469
|
+
.map(
|
|
1470
|
+
(i) =>
|
|
1471
|
+
'<tr><td>' +
|
|
1472
|
+
esc(i.handle || '?') +
|
|
1473
|
+
'</td><td>' +
|
|
1474
|
+
(i.repo ? esc(i.repo) : '<span class="meta">shared — no project</span>') +
|
|
1475
|
+
'</td><td>' +
|
|
1476
|
+
(i.inThisChannel
|
|
1477
|
+
? 'in this channel'
|
|
1478
|
+
: i.key
|
|
1479
|
+
? '<a href="#" class="swap" data-as="' +
|
|
1480
|
+
esc(i.key) +
|
|
1481
|
+
'">another account — open its inbox</a>'
|
|
1482
|
+
: '<span class="meta">another account</span>') +
|
|
1483
|
+
'</td><td>' +
|
|
1484
|
+
(i.key ? '<a href="#" class="secrets" data-as="' + esc(i.key) + '">secrets</a>' : '') +
|
|
1485
|
+
'</td></tr>',
|
|
1486
|
+
)
|
|
1487
|
+
.join('');
|
|
1488
|
+
|
|
1489
|
+
const connected = (d.identities || []).some((i) => i.repo === d.here);
|
|
1490
|
+
// Who this channel can reach right now. LIVE is "did something recently",
|
|
1491
|
+
// not "reachable": a device row survives a laptop being shut, so reachable
|
|
1492
|
+
// stays true for an agent that has not run since last week, and showing
|
|
1493
|
+
// that one as available is worse than showing nothing.
|
|
1494
|
+
const LIVE_MS = 15 * 60 * 1000;
|
|
1495
|
+
const reach = (d.reachable || [])
|
|
1496
|
+
.map((r) => {
|
|
1497
|
+
const ms = r.last_seen ? Date.now() - Date.parse(r.last_seen) : Infinity;
|
|
1498
|
+
const state = !r.reachable
|
|
1499
|
+
? '<span class="meta">nothing listening</span>'
|
|
1500
|
+
: ms < LIVE_MS
|
|
1501
|
+
? 'live'
|
|
1502
|
+
: '<span class="meta">idle</span>';
|
|
1503
|
+
return (
|
|
1504
|
+
'<tr><td>' +
|
|
1505
|
+
esc(who(r)) +
|
|
1506
|
+
'</td><td>' +
|
|
1507
|
+
(r.is_agent ? 'agent' : 'person') +
|
|
1508
|
+
'</td><td>' +
|
|
1509
|
+
state +
|
|
1510
|
+
'</td></tr>'
|
|
1511
|
+
);
|
|
1512
|
+
})
|
|
1513
|
+
.join('');
|
|
1514
|
+
|
|
1515
|
+
// WHAT IS STILL UNANSWERED, at the top, and only while something is.
|
|
1516
|
+
//
|
|
1517
|
+
// A checklist that never goes away is a checklist nobody reads. Every step
|
|
1518
|
+
// reports itself from real state -- connected projects, the roster, the
|
|
1519
|
+
// settings file -- so this cannot say "done" about something that is not,
|
|
1520
|
+
// which is the one failure that would make it worse than nothing.
|
|
1521
|
+
let guide = '';
|
|
1522
|
+
try {
|
|
1523
|
+
const o = await (await fetch(q('/onboarding'))).json();
|
|
1524
|
+
const undone = (o.steps || []).filter((s) => !s.done);
|
|
1525
|
+
if (undone.length) {
|
|
1526
|
+
guide =
|
|
1527
|
+
'<div class="guide"><div class="guidehead">Still to set up — ' +
|
|
1528
|
+
undone.length +
|
|
1529
|
+
' of ' +
|
|
1530
|
+
o.steps.length +
|
|
1531
|
+
'</div>' +
|
|
1532
|
+
o.steps
|
|
1533
|
+
.map(
|
|
1534
|
+
(s) =>
|
|
1535
|
+
'<div class="step' +
|
|
1536
|
+
(s.done ? ' done' : '') +
|
|
1537
|
+
'"><b>' +
|
|
1538
|
+
(s.done ? '✓' : '·') +
|
|
1539
|
+
'</b> ' +
|
|
1540
|
+
esc(s.title) +
|
|
1541
|
+
' <span class="meta">' +
|
|
1542
|
+
esc(s.detail) +
|
|
1543
|
+
'</span></div>',
|
|
1544
|
+
)
|
|
1545
|
+
.join('') +
|
|
1546
|
+
'</div>';
|
|
1547
|
+
}
|
|
1548
|
+
LIMITS = o.settings;
|
|
1549
|
+
} catch {
|
|
1550
|
+
/* the channel still works without it; this is guidance, not a gate */
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
document.getElementById('setupbody').innerHTML =
|
|
1554
|
+
guide +
|
|
1555
|
+
'<table class="ids"><tr><th>agent</th><th>project</th><th>where</th><th></th></tr>' +
|
|
1556
|
+
rows +
|
|
1557
|
+
'</table>' +
|
|
1558
|
+
(reach
|
|
1559
|
+
? '<div class="meta" style="margin-top:.6rem">Who this channel reaches</div>' +
|
|
1560
|
+
'<table class="ids"><tr><th>name</th><th>kind</th><th></th></tr>' +
|
|
1561
|
+
reach +
|
|
1562
|
+
'</table>' +
|
|
1563
|
+
(d.channel
|
|
1564
|
+
? '<form id="invite"><div class="meta">Bring somebody in</div>' +
|
|
1565
|
+
'<input id="iname" placeholder="what to call them" maxlength="80" />' +
|
|
1566
|
+
'<select id="itype">' +
|
|
1567
|
+
'<option value="partner">partner — works alongside you</option>' +
|
|
1568
|
+
'<option value="subagent">subagent — asks before it acts</option>' +
|
|
1569
|
+
'<option value="worker">worker — one task, reports once</option>' +
|
|
1570
|
+
'</select><button type="submit">Make a code</button>' +
|
|
1571
|
+
'<div class="meta" id="imsg"></div></form>'
|
|
1572
|
+
: '')
|
|
1573
|
+
: '') +
|
|
1574
|
+
(d.here
|
|
1575
|
+
? connected
|
|
1576
|
+
? '<p class="meta">This project (' + esc(d.here) + ') is connected.</p>'
|
|
1577
|
+
: '<form id="connect"><div class="meta">Connect this project: ' +
|
|
1578
|
+
esc(d.here) +
|
|
1579
|
+
'</div>' +
|
|
1580
|
+
'<input id="handle" placeholder="a handle, like deploy-bot" maxlength="40" />' +
|
|
1581
|
+
'<input id="role" placeholder="what it does — the line others read" maxlength="280" />' +
|
|
1582
|
+
'<button type="submit">Connect</button><span class="meta" id="cmsg"></span></form>'
|
|
1583
|
+
: '<p class="meta">This viewer is not running inside a git repository, so there is no project to connect.</p>') +
|
|
1584
|
+
// THE LIMITS. Always shown, not only while unset: they are the answer to
|
|
1585
|
+
// "what will this machine do without asking me", which is worth being
|
|
1586
|
+
// able to check rather than only to set once.
|
|
1587
|
+
(LIMITS
|
|
1588
|
+
? '<form id="limits"><div class="meta">What this machine may do</div>' +
|
|
1589
|
+
'<label class="meta">at most <input id="lmax" type="number" min="1" max="64" ' +
|
|
1590
|
+
'value="' +
|
|
1591
|
+
esc(String(LIMITS.max_agents)) +
|
|
1592
|
+
'" /> agents here</label>' +
|
|
1593
|
+
'<select id="lkind">' +
|
|
1594
|
+
['subagent', 'partner', 'worker']
|
|
1595
|
+
.map(
|
|
1596
|
+
(k) =>
|
|
1597
|
+
'<option value="' +
|
|
1598
|
+
k +
|
|
1599
|
+
'"' +
|
|
1600
|
+
(LIMITS.default_connection_type === k ? ' selected' : '') +
|
|
1601
|
+
'>' +
|
|
1602
|
+
{ subagent: 'new agents ask before acting', partner: 'new agents work alongside you', worker: 'new agents do one task' }[k] +
|
|
1603
|
+
'</option>',
|
|
1604
|
+
)
|
|
1605
|
+
.join('') +
|
|
1606
|
+
'</select>' +
|
|
1607
|
+
'<label class="meta">keep <input id="ldays" type="number" min="0" max="365" ' +
|
|
1608
|
+
'value="' +
|
|
1609
|
+
esc(String(LIMITS.history_days)) +
|
|
1610
|
+
'" /> days of chat</label>' +
|
|
1611
|
+
'<button type="submit">Save</button>' +
|
|
1612
|
+
'<span class="meta" id="lmsg"></span></form>' +
|
|
1613
|
+
'<div class="meta" id="storage">measuring…</div>'
|
|
1614
|
+
: '');
|
|
1615
|
+
|
|
1616
|
+
// WHAT IS ON THIS DISK, measured rather than remembered. Rendered after
|
|
1617
|
+
// the form so a slow stat cannot hold up the controls.
|
|
1618
|
+
const storage = document.getElementById('storage');
|
|
1619
|
+
if (storage) {
|
|
1620
|
+
(async () => {
|
|
1621
|
+
let h;
|
|
1622
|
+
try {
|
|
1623
|
+
h = await (await fetch(q('/history'))).json();
|
|
1624
|
+
} catch {
|
|
1625
|
+
storage.textContent = 'Could not measure the stored chat.';
|
|
1626
|
+
return;
|
|
1627
|
+
}
|
|
1628
|
+
const kb = Math.round((h.bytes ?? 0) / 1024);
|
|
1629
|
+
storage.innerHTML =
|
|
1630
|
+
esc(String(h.messages ?? 0)) +
|
|
1631
|
+
' messages kept locally across ' +
|
|
1632
|
+
esc(String((h.channels ?? []).length)) +
|
|
1633
|
+
' channel' +
|
|
1634
|
+
((h.channels ?? []).length === 1 ? '' : 's') +
|
|
1635
|
+
', ' +
|
|
1636
|
+
esc(String(kb)) +
|
|
1637
|
+
' KB. Encrypted messages are recorded but their contents are never stored. ' +
|
|
1638
|
+
'<a href="#" id="clearhist">Delete it</a>';
|
|
1639
|
+
|
|
1640
|
+
document.getElementById('clearhist').onclick = async (event) => {
|
|
1641
|
+
event.preventDefault();
|
|
1642
|
+
// Said before it happens, because the next poll refetches the recent
|
|
1643
|
+
// window and IS charged for it. A delete that presents itself as
|
|
1644
|
+
// free would be the same lie in the other direction.
|
|
1645
|
+
if (!confirm('Delete the locally stored chat? The next refresh re-fetches recent messages, which costs one read.')) return;
|
|
1646
|
+
storage.textContent = 'deleting…';
|
|
1647
|
+
await fetch(q('/history'), { method: 'DELETE' });
|
|
1648
|
+
setup();
|
|
1649
|
+
};
|
|
1650
|
+
})();
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
const limitsForm = document.getElementById('limits');
|
|
1654
|
+
if (limitsForm) {
|
|
1655
|
+
limitsForm.onsubmit = async (event) => {
|
|
1656
|
+
event.preventDefault();
|
|
1657
|
+
const msg = document.getElementById('lmsg');
|
|
1658
|
+
msg.textContent = 'saving…';
|
|
1659
|
+
const result = await post('/onboarding', {
|
|
1660
|
+
max_agents: Number(document.getElementById('lmax').value),
|
|
1661
|
+
default_connection_type: document.getElementById('lkind').value,
|
|
1662
|
+
history_days: Number(document.getElementById('ldays').value),
|
|
1663
|
+
});
|
|
1664
|
+
if (result.error) {
|
|
1665
|
+
msg.textContent = result.error;
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
// Re-read rather than assume. The server refuses a cap below what is
|
|
1669
|
+
// already running, so what was typed and what is stored can differ --
|
|
1670
|
+
// and a form that shows the typed value after a refusal is a form that
|
|
1671
|
+
// lies about the state of the machine.
|
|
1672
|
+
//
|
|
1673
|
+
// The confirmation goes on the element that exists AFTER the redraw.
|
|
1674
|
+
// Writing it before means setting text on a node setup() is about to
|
|
1675
|
+
// replace, so a successful save reads as nothing having happened --
|
|
1676
|
+
// which is the one outcome that makes somebody press the button again.
|
|
1677
|
+
await setup();
|
|
1678
|
+
const fresh = document.getElementById('lmsg');
|
|
1679
|
+
if (fresh) {
|
|
1680
|
+
fresh.textContent = 'saved';
|
|
1681
|
+
setTimeout(() => {
|
|
1682
|
+
if (fresh.textContent === 'saved') fresh.textContent = '';
|
|
1683
|
+
}, 2000);
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
// Switching accounts. Not a channel view: an API key names one channel, so
|
|
1689
|
+
// the log on this page can only ever be that account's. What the other
|
|
1690
|
+
// identity can show is its own inbox, which is what it was sent -- less,
|
|
1691
|
+
// and said so rather than implied.
|
|
1692
|
+
for (const link of document.querySelectorAll('a.swap')) {
|
|
1693
|
+
link.onclick = async (event) => {
|
|
1694
|
+
event.preventDefault();
|
|
1695
|
+
const box = document.getElementById('setupbody');
|
|
1696
|
+
const note = document.createElement('div');
|
|
1697
|
+
note.className = 'meta';
|
|
1698
|
+
note.textContent = 'reading…';
|
|
1699
|
+
box.appendChild(note);
|
|
1700
|
+
|
|
1701
|
+
const data = await (await fetch(q('/inbox?as=' + encodeURIComponent(link.dataset.as)))).json();
|
|
1702
|
+
if (data.error) {
|
|
1703
|
+
note.textContent = data.error;
|
|
1704
|
+
return;
|
|
1705
|
+
}
|
|
1706
|
+
note.innerHTML =
|
|
1707
|
+
'<div style="margin-top:.6rem">' +
|
|
1708
|
+
esc(data.as.handle || data.as.key) +
|
|
1709
|
+
'’s inbox — ' +
|
|
1710
|
+
data.messages.length +
|
|
1711
|
+
' message' +
|
|
1712
|
+
(data.messages.length === 1 ? '' : 's') +
|
|
1713
|
+
(data.as.repo ? ' · ' + esc(data.as.repo) : '') +
|
|
1714
|
+
'</div>' +
|
|
1715
|
+
(data.messages.length
|
|
1716
|
+
? '<table class="ids">' +
|
|
1717
|
+
data.messages
|
|
1718
|
+
.slice(0, 12)
|
|
1719
|
+
.map(
|
|
1720
|
+
(m) =>
|
|
1721
|
+
'<tr><td>' +
|
|
1722
|
+
esc(m.from_handle || '—') +
|
|
1723
|
+
'</td><td>' +
|
|
1724
|
+
esc(m.title || m.body || '') +
|
|
1725
|
+
'</td><td>' +
|
|
1726
|
+
(m.answered ? 'answered' : '') +
|
|
1727
|
+
'</td></tr>',
|
|
1728
|
+
)
|
|
1729
|
+
.join('') +
|
|
1730
|
+
'</table>'
|
|
1731
|
+
: '<div class="meta">Nothing has been sent to it yet.</div>');
|
|
1732
|
+
};
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
// What an identity may use, and how to change it. Values are never shown
|
|
1736
|
+
// because none exist to show -- a grant is a pointer, and the page could
|
|
1737
|
+
// not leak a credential here if it tried.
|
|
1738
|
+
for (const link of document.querySelectorAll('a.secrets')) {
|
|
1739
|
+
link.onclick = async (event) => {
|
|
1740
|
+
event.preventDefault();
|
|
1741
|
+
const as = link.dataset.as;
|
|
1742
|
+
const box = document.getElementById('setupbody');
|
|
1743
|
+
let panel = document.getElementById('secretsbox');
|
|
1744
|
+
if (!panel) {
|
|
1745
|
+
panel = document.createElement('div');
|
|
1746
|
+
panel.id = 'secretsbox';
|
|
1747
|
+
box.appendChild(panel);
|
|
1748
|
+
}
|
|
1749
|
+
panel.innerHTML = '<div class="meta">reading…</div>';
|
|
1750
|
+
|
|
1751
|
+
const draw = async () => {
|
|
1752
|
+
const data = await (await fetch(q('/secrets?as=' + encodeURIComponent(as)))).json();
|
|
1753
|
+
if (data.error) {
|
|
1754
|
+
panel.innerHTML = '<div class="meta">' + esc(data.error) + '</div>';
|
|
1755
|
+
return;
|
|
1756
|
+
}
|
|
1757
|
+
panel.innerHTML =
|
|
1758
|
+
'<div class="meta" style="margin-top:.6rem">What ' + esc(as) + ' may use</div>' +
|
|
1759
|
+
(data.secrets.length
|
|
1760
|
+
? '<table class="ids">' +
|
|
1761
|
+
data.secrets
|
|
1762
|
+
.map(
|
|
1763
|
+
(x) =>
|
|
1764
|
+
'<tr><td>' + esc(x.name) + '</td><td>' + esc(x.reference) + '</td><td>' +
|
|
1765
|
+
(x.scope_path ? esc(x.scope_path) : '<span class="meta">anywhere</span>') +
|
|
1766
|
+
'</td><td><a href="#" class="unsecret" data-n="' + esc(x.name) + '">revoke</a></td></tr>',
|
|
1767
|
+
)
|
|
1768
|
+
.join('') +
|
|
1769
|
+
'</table>'
|
|
1770
|
+
: '<div class="meta">Nothing granted.</div>') +
|
|
1771
|
+
'<form id="grantform">' +
|
|
1772
|
+
'<input id="gname" placeholder="DEPLOY_TOKEN" maxlength="64" />' +
|
|
1773
|
+
'<input id="gref" placeholder="keychain://service/account" maxlength="2048" />' +
|
|
1774
|
+
'<button type="submit">Grant</button>' +
|
|
1775
|
+
'<span class="meta" id="gmsg">A reference, never the secret.</span></form>';
|
|
1776
|
+
|
|
1777
|
+
document.getElementById('grantform').onsubmit = async (e) => {
|
|
1778
|
+
e.preventDefault();
|
|
1779
|
+
const msg = document.getElementById('gmsg');
|
|
1780
|
+
msg.textContent = 'granting…';
|
|
1781
|
+
const r = await post('/grant', {
|
|
1782
|
+
agent: as,
|
|
1783
|
+
name: document.getElementById('gname').value.trim(),
|
|
1784
|
+
reference: document.getElementById('gref').value.trim(),
|
|
1785
|
+
});
|
|
1786
|
+
if (r.error) {
|
|
1787
|
+
msg.textContent = r.error;
|
|
1788
|
+
return;
|
|
1789
|
+
}
|
|
1790
|
+
draw();
|
|
1791
|
+
};
|
|
1792
|
+
|
|
1793
|
+
for (const undo of panel.querySelectorAll('a.unsecret')) {
|
|
1794
|
+
undo.onclick = async (e) => {
|
|
1795
|
+
e.preventDefault();
|
|
1796
|
+
await post('/revoke-secret', { agent: as, name: undo.dataset.n });
|
|
1797
|
+
draw();
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
};
|
|
1801
|
+
draw();
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
const inviteForm = document.getElementById('invite');
|
|
1806
|
+
if (inviteForm) {
|
|
1807
|
+
inviteForm.onsubmit = async (event) => {
|
|
1808
|
+
event.preventDefault();
|
|
1809
|
+
const msg = document.getElementById('imsg');
|
|
1810
|
+
msg.textContent = 'minting…';
|
|
1811
|
+
const result = await post('/invite', {
|
|
1812
|
+
channel: d.channel.ref,
|
|
1813
|
+
name: document.getElementById('iname').value.trim() || undefined,
|
|
1814
|
+
connection_type: document.getElementById('itype').value,
|
|
1815
|
+
});
|
|
1816
|
+
if (result.error) {
|
|
1817
|
+
msg.textContent = result.error;
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
// Shown once, and shown as the line they actually run. A code with no
|
|
1821
|
+
// instruction next to it gets pasted into a config file, which is the
|
|
1822
|
+
// slow path and leaves a credential in a file.
|
|
1823
|
+
msg.innerHTML =
|
|
1824
|
+
'Send them this — single use' +
|
|
1825
|
+
(result.expires_at ? ', expires ' + esc(new Date(result.expires_at).toLocaleString()) : '') +
|
|
1826
|
+
':<br><code>/agentsignal:join ' +
|
|
1827
|
+
esc(result.code) +
|
|
1828
|
+
'</code>';
|
|
1829
|
+
};
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
const form = document.getElementById('connect');
|
|
1833
|
+
if (!form) return;
|
|
1834
|
+
form.onsubmit = async (event) => {
|
|
1835
|
+
event.preventDefault();
|
|
1836
|
+
const msg = document.getElementById('cmsg');
|
|
1837
|
+
msg.textContent = 'registering…';
|
|
1838
|
+
const result = await post('/connect', {
|
|
1839
|
+
path: d.here,
|
|
1840
|
+
handle: document.getElementById('handle').value.trim(),
|
|
1841
|
+
description: document.getElementById('role').value.trim() || undefined,
|
|
1842
|
+
});
|
|
1843
|
+
msg.textContent = result.error ? result.error : 'connected as ' + result.handle;
|
|
1844
|
+
if (!result.error) setup();
|
|
1845
|
+
};
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
// ⚠ EVERY CLICK IS INTERCEPTED, modified ones included, and that is deliberate rather than
|
|
1849
|
+
// careless. The href cannot carry the token — see the note where the nav is built — so
|
|
1850
|
+
// letting a cmd-click or middle-click through would open a tab that gets the guard's flat
|
|
1851
|
+
// "Not found.", which is the whole bug. Every target here is reachable in place, so there is
|
|
1852
|
+
// nothing a new tab could show that this does not. Somebody who wants one can copy the
|
|
1853
|
+
// address bar, which has the token.
|
|
1854
|
+
document.getElementById('who-nav').addEventListener('click', (event) => {
|
|
1855
|
+
const link = event.target.closest('a');
|
|
1856
|
+
|
|
1857
|
+
if (!link) return;
|
|
1858
|
+
|
|
1859
|
+
event.preventDefault();
|
|
1860
|
+
filterTo(link.dataset.agent ?? '', true);
|
|
1861
|
+
});
|
|
1862
|
+
|
|
1863
|
+
// Back and forward filter in place too, so the history entries pushState created behave like
|
|
1864
|
+
// the navigations they replaced. No push: this IS the pop.
|
|
1865
|
+
addEventListener('popstate', () => filterTo(agentFromPath(location.pathname), false));
|
|
1866
|
+
|
|
1867
|
+
roster();
|
|
1868
|
+
setup();
|
|
1869
|
+
pending();
|
|
1870
|
+
setInterval(pending, 2000);
|
|
1871
|
+
tick();
|
|
1872
|
+
setInterval(tick, 2000);
|
|
1873
|
+
</script>
|
|
1874
|
+
</body>
|
|
1875
|
+
</html>`;
|
|
1876
|
+
|
|
1877
|
+
/** One upstream call, one place that turns a non-2xx into something readable. */
|
|
1878
|
+
async function upstream(path) {
|
|
1879
|
+
try {
|
|
1880
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
1881
|
+
headers: { Authorization: `Bearer ${apiKey}` },
|
|
1882
|
+
});
|
|
1883
|
+
const body = await response.json();
|
|
1884
|
+
return response.ok
|
|
1885
|
+
? body
|
|
1886
|
+
: {
|
|
1887
|
+
error:
|
|
1888
|
+
body?.error?.message ??
|
|
1889
|
+
`${response.status} from ${baseUrl}. Is the key right for this API?`,
|
|
1890
|
+
};
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
return { error: `Could not reach ${baseUrl}: ${error.message}` };
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
/**
|
|
1897
|
+
* Is this message part of that agent's conversation?
|
|
1898
|
+
*
|
|
1899
|
+
* Both ends, not just the inbox. A conversation with only one side of it in
|
|
1900
|
+
* view is the thing this page exists to avoid -- an agent's own sends are half
|
|
1901
|
+
* of what it did, and reading a reply without the question it answers is
|
|
1902
|
+
* worse than reading nothing.
|
|
1903
|
+
*
|
|
1904
|
+
* Matched on recipient key OR handle because the log carries both and a
|
|
1905
|
+
* caller who has one rarely has the other.
|
|
1906
|
+
*/
|
|
1907
|
+
function involves(message, agent) {
|
|
1908
|
+
const ends = [message.from, message.from_handle, message.to, message.to_handle];
|
|
1909
|
+
return ends.some((end) => end && end === agent);
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/** POST to the API as the channel key. */
|
|
1913
|
+
async function upstreamPost(path, payload, auth) {
|
|
1914
|
+
try {
|
|
1915
|
+
const response = await fetch(`${baseUrl}${path}`, {
|
|
1916
|
+
method: 'POST',
|
|
1917
|
+
headers: { Authorization: auth, 'Content-Type': 'application/json' },
|
|
1918
|
+
body: JSON.stringify(payload),
|
|
1919
|
+
});
|
|
1920
|
+
const body = await response.json().catch(() => ({}));
|
|
1921
|
+
return response.ok ? body : { error: body?.error?.message ?? `${response.status}` };
|
|
1922
|
+
} catch (error) {
|
|
1923
|
+
return { error: `Could not reach ${baseUrl}: ${error.message}` };
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
|
|
1927
|
+
/** Read a JSON request body, refusing anything big enough to be an attack. */
|
|
1928
|
+
async function readJson(req) {
|
|
1929
|
+
const chunks = [];
|
|
1930
|
+
let size = 0;
|
|
1931
|
+
for await (const chunk of req) {
|
|
1932
|
+
size += chunk.length;
|
|
1933
|
+
if (size > 64 * 1024) throw new Error('too large');
|
|
1934
|
+
chunks.push(chunk);
|
|
1935
|
+
}
|
|
1936
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
/**
|
|
1940
|
+
* Ask the channel who is in it, and adopt whichever identity that is.
|
|
1941
|
+
*
|
|
1942
|
+
* Once, at startup. The roster changes when somebody joins, which is rare
|
|
1943
|
+
* enough that re-reading it every two seconds would be waste.
|
|
1944
|
+
*/
|
|
1945
|
+
async function resolveSelf() {
|
|
1946
|
+
const roster = await upstream('/v1/agents');
|
|
1947
|
+
if (roster.error) return;
|
|
1948
|
+
const inChannel = new Set((roster.recipients ?? []).map((r) => r.key));
|
|
1949
|
+
const mine = identities.find((i) => i.key && inChannel.has(i.key));
|
|
1950
|
+
if (mine) self = { key: mine.key, handle: mine.handle };
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
const server = createServer(async (req, res) => {
|
|
1954
|
+
// `port` is a placeholder: only the path and query are used, and URL wants
|
|
1955
|
+
// an origin it can parse.
|
|
1956
|
+
const url = new URL(req.url, `http://localhost:${port}`);
|
|
1957
|
+
|
|
1958
|
+
// Before anything else. A wrong or missing token is a flat refusal with no
|
|
1959
|
+
// hint about what is here -- a page that says "unauthorised, this is the
|
|
1960
|
+
// AgentSignal viewer" tells a scanner exactly what it found.
|
|
1961
|
+
if (url.searchParams.get('t') !== token && req.headers['x-agentsignal-viewer'] !== token) {
|
|
1962
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
1963
|
+
res.end('Not found.');
|
|
1964
|
+
return;
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
// WHAT THIS MACHINE IS. The question people keep having to reconstruct by
|
|
1968
|
+
// hand: which agents live here, which project each belongs to, and which
|
|
1969
|
+
// account that puts them in. It is read straight off disk, so it is what the
|
|
1970
|
+
// watcher and the MCP server will also see rather than a second opinion.
|
|
1971
|
+
// ONBOARDING: what is still unanswered about this machine.
|
|
1972
|
+
//
|
|
1973
|
+
// Every step reports done-ness DERIVED FROM REAL STATE, never from a stored
|
|
1974
|
+
// "completed" flag. A flag is a second copy of the truth, and the two drift
|
|
1975
|
+
// in the direction that flatters: the screen says configured, the thing is
|
|
1976
|
+
// not, and nobody looks again because the screen already said so. Ask the
|
|
1977
|
+
// filesystem and the roster instead -- both are what the rest of the product
|
|
1978
|
+
// actually reads.
|
|
1979
|
+
if (url.pathname === '/onboarding' && req.method === 'GET') {
|
|
1980
|
+
const here = repoRoot(process.cwd());
|
|
1981
|
+
const mine = identitiesHere(baseUrl);
|
|
1982
|
+
const roster = await upstream('/v1/agents');
|
|
1983
|
+
const others = roster.error
|
|
1984
|
+
? []
|
|
1985
|
+
: (roster.recipients ?? []).filter((r) => r.key !== (self && self.key));
|
|
1986
|
+
const current = settings();
|
|
1987
|
+
|
|
1988
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
1989
|
+
res.end(
|
|
1990
|
+
JSON.stringify({
|
|
1991
|
+
settings: current,
|
|
1992
|
+
here,
|
|
1993
|
+
steps: [
|
|
1994
|
+
{
|
|
1995
|
+
id: 'project',
|
|
1996
|
+
title: 'Connect a project',
|
|
1997
|
+
// The folder half. An identity is per checkout, so this is the
|
|
1998
|
+
// step that decides what an agent can be asked about.
|
|
1999
|
+
done: mine.some((i) => i.repo),
|
|
2000
|
+
detail: mine.filter((i) => i.repo).length
|
|
2001
|
+
? `${mine.filter((i) => i.repo).length} connected`
|
|
2002
|
+
: here
|
|
2003
|
+
? `${here} is not connected yet`
|
|
2004
|
+
: 'not inside a git repository',
|
|
2005
|
+
},
|
|
2006
|
+
{
|
|
2007
|
+
id: 'role',
|
|
2008
|
+
title: 'Say what each agent does',
|
|
2009
|
+
// Derived from the roster, because the description is what other
|
|
2010
|
+
// agents read when deciding who to hand work to. An agent with no
|
|
2011
|
+
// description is reachable and unchoosable.
|
|
2012
|
+
done: others.length > 0 && others.every((r) => !r.is_agent || r.description),
|
|
2013
|
+
detail: (() => {
|
|
2014
|
+
const bare = others.filter((r) => r.is_agent && !r.description);
|
|
2015
|
+
return bare.length ? `${bare.length} with no description` : 'all described';
|
|
2016
|
+
})(),
|
|
2017
|
+
},
|
|
2018
|
+
{
|
|
2019
|
+
id: 'reach',
|
|
2020
|
+
title: 'Have somebody to reach',
|
|
2021
|
+
done: others.length > 0,
|
|
2022
|
+
detail: others.length
|
|
2023
|
+
? `${others.length} reachable`
|
|
2024
|
+
: 'nobody else in this channel yet',
|
|
2025
|
+
},
|
|
2026
|
+
{
|
|
2027
|
+
id: 'limits',
|
|
2028
|
+
title: 'Set the limits',
|
|
2029
|
+
// The one step that is genuinely a stored preference. It counts as
|
|
2030
|
+
// done once the file exists, because accepting the defaults IS an
|
|
2031
|
+
// answer -- but only a deliberate one, which is why an absent file
|
|
2032
|
+
// is not treated as agreement.
|
|
2033
|
+
done: (() => {
|
|
2034
|
+
try {
|
|
2035
|
+
readFileSync(settingsPath, 'utf8');
|
|
2036
|
+
return true;
|
|
2037
|
+
} catch {
|
|
2038
|
+
return false;
|
|
2039
|
+
}
|
|
2040
|
+
})(),
|
|
2041
|
+
detail: `at most ${current.max_agents} agents, new ones are ${current.default_connection_type}`,
|
|
2042
|
+
},
|
|
2043
|
+
],
|
|
2044
|
+
}),
|
|
2045
|
+
);
|
|
2046
|
+
return;
|
|
2047
|
+
}
|
|
2048
|
+
|
|
2049
|
+
/**
|
|
2050
|
+
* WHAT IS STORED ON THIS MACHINE, and how to be rid of it.
|
|
2051
|
+
*
|
|
2052
|
+
* Kept honest by measuring the files rather than trusting a counter: a
|
|
2053
|
+
* number computed at write time drifts the moment anything else touches the
|
|
2054
|
+
* directory, and "you have no history" printed over a full directory is the
|
|
2055
|
+
* failure this whole session has been about.
|
|
2056
|
+
*/
|
|
2057
|
+
if (url.pathname === '/history' && req.method === 'GET') {
|
|
2058
|
+
let files = [];
|
|
2059
|
+
try {
|
|
2060
|
+
files = readdirSync(historyDir).filter((n) => n.endsWith('.json'));
|
|
2061
|
+
} catch {
|
|
2062
|
+
/* nothing stored yet */
|
|
2063
|
+
}
|
|
2064
|
+
const channels = files.map((name) => {
|
|
2065
|
+
const path = join(historyDir, name);
|
|
2066
|
+
let bytes = 0;
|
|
2067
|
+
let count = 0;
|
|
2068
|
+
let oldest = null;
|
|
2069
|
+
try {
|
|
2070
|
+
bytes = statSync(path).size;
|
|
2071
|
+
const stored = JSON.parse(readFileSync(path, 'utf8'));
|
|
2072
|
+
const messages = Array.isArray(stored.messages) ? stored.messages : [];
|
|
2073
|
+
count = messages.length;
|
|
2074
|
+
oldest = messages.length ? messages[messages.length - 1].created_at ?? null : null;
|
|
2075
|
+
} catch {
|
|
2076
|
+
/* unreadable: still reported, with what could be measured */
|
|
2077
|
+
}
|
|
2078
|
+
return { ref: name.replace(/\.json$/, ''), bytes, count, oldest };
|
|
2079
|
+
});
|
|
2080
|
+
|
|
2081
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2082
|
+
res.end(
|
|
2083
|
+
JSON.stringify({
|
|
2084
|
+
days: settings().history_days,
|
|
2085
|
+
channels,
|
|
2086
|
+
bytes: channels.reduce((n, c) => n + c.bytes, 0),
|
|
2087
|
+
messages: channels.reduce((n, c) => n + c.count, 0),
|
|
2088
|
+
}),
|
|
2089
|
+
);
|
|
2090
|
+
return;
|
|
2091
|
+
}
|
|
2092
|
+
|
|
2093
|
+
if (url.pathname === '/history' && req.method === 'DELETE') {
|
|
2094
|
+
let removed = 0;
|
|
2095
|
+
try {
|
|
2096
|
+
for (const name of readdirSync(historyDir)) {
|
|
2097
|
+
if (!name.endsWith('.json')) continue;
|
|
2098
|
+
try {
|
|
2099
|
+
unlinkSync(join(historyDir, name));
|
|
2100
|
+
removed++;
|
|
2101
|
+
} catch {
|
|
2102
|
+
/* already gone */
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
} catch {
|
|
2106
|
+
/* nothing to remove */
|
|
2107
|
+
}
|
|
2108
|
+
// The next poll has no `since` to send, so it refetches the recent window
|
|
2109
|
+
// and is charged for it. Said plainly rather than presenting a delete as
|
|
2110
|
+
// free -- clearing history is a real cost, once.
|
|
2111
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2112
|
+
res.end(JSON.stringify({ ok: true, removed }));
|
|
2113
|
+
return;
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
if (url.pathname === '/onboarding' && req.method === 'POST') {
|
|
2117
|
+
let payload;
|
|
2118
|
+
try {
|
|
2119
|
+
payload = await readJson(req);
|
|
2120
|
+
} catch {
|
|
2121
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2122
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2123
|
+
return;
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
const max = Number(payload.max_agents);
|
|
2127
|
+
if (!Number.isInteger(max) || max < 1 || max > 64) {
|
|
2128
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2129
|
+
res.end(JSON.stringify({ error: 'A limit has to be a whole number from 1 to 64.' }));
|
|
2130
|
+
return;
|
|
2131
|
+
}
|
|
2132
|
+
const kind = String(payload.default_connection_type ?? '');
|
|
2133
|
+
if (!['subagent', 'partner', 'worker'].includes(kind)) {
|
|
2134
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2135
|
+
res.end(JSON.stringify({ error: 'Kind must be subagent, partner or worker.' }));
|
|
2136
|
+
return;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
// Refused rather than silently clamped. Saving a cap BELOW what is already
|
|
2140
|
+
// running would read as enforced while several agents carried on past it,
|
|
2141
|
+
// and a limit that is not true of the machine it describes is worse than
|
|
2142
|
+
// no limit -- it is a number somebody will plan around.
|
|
2143
|
+
const running = identitiesHere(baseUrl).length;
|
|
2144
|
+
if (max < running) {
|
|
2145
|
+
res.writeHead(409, { 'Content-Type': 'application/json' });
|
|
2146
|
+
res.end(
|
|
2147
|
+
JSON.stringify({
|
|
2148
|
+
error:
|
|
2149
|
+
`${running} agents are already registered here, so a cap of ${max} would ` +
|
|
2150
|
+
'be false the moment it was saved. Remove some first, or set it to ' +
|
|
2151
|
+
`${running} or more.`,
|
|
2152
|
+
}),
|
|
2153
|
+
);
|
|
2154
|
+
return;
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
// Retention is optional in the payload, so a caller that only wants to
|
|
2158
|
+
// change the agent cap does not have to restate it and cannot blank it by
|
|
2159
|
+
// omission -- the previous value stands.
|
|
2160
|
+
const current = settings();
|
|
2161
|
+
const days =
|
|
2162
|
+
payload.history_days === undefined ? current.history_days : Number(payload.history_days);
|
|
2163
|
+
if (!Number.isInteger(days) || days < 0 || days > 365) {
|
|
2164
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2165
|
+
res.end(
|
|
2166
|
+
JSON.stringify({ error: 'History has to be a whole number of days from 0 to 365.' }),
|
|
2167
|
+
);
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
|
|
2171
|
+
const next = { max_agents: max, default_connection_type: kind, history_days: days };
|
|
2172
|
+
try {
|
|
2173
|
+
saveSettings(next);
|
|
2174
|
+
} catch (error) {
|
|
2175
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
2176
|
+
res.end(JSON.stringify({ error: `Could not write ${settingsPath}: ${error.message}` }));
|
|
2177
|
+
return;
|
|
2178
|
+
}
|
|
2179
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2180
|
+
res.end(JSON.stringify({ ok: true, settings: next }));
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
if (url.pathname === '/setup') {
|
|
2185
|
+
const roster = await upstream('/v1/agents');
|
|
2186
|
+
const inChannel = new Set(
|
|
2187
|
+
roster.error ? [] : (roster.recipients ?? []).map((r) => r.key),
|
|
2188
|
+
);
|
|
2189
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2190
|
+
res.end(
|
|
2191
|
+
JSON.stringify({
|
|
2192
|
+
// Where THIS viewer is running, so "connect this project" has an
|
|
2193
|
+
// obvious default and nobody has to type a path they can see.
|
|
2194
|
+
here: repoRoot(process.cwd()),
|
|
2195
|
+
channel: roster.error ? null : roster.channel ?? null,
|
|
2196
|
+
// WHO THIS CAN REACH. The roster of the channel the key names, people
|
|
2197
|
+
// included -- a person is not an agent you open a conversation with,
|
|
2198
|
+
// but they are the most useful thing to notify, so leaving them out
|
|
2199
|
+
// answers the question wrongly.
|
|
2200
|
+
reachable: roster.error
|
|
2201
|
+
? []
|
|
2202
|
+
: (roster.recipients ?? []).map((r) => ({
|
|
2203
|
+
handle: r.handle ?? r.key,
|
|
2204
|
+
// Carried, not collapsed. This used to send only the handle, so
|
|
2205
|
+
// the page could not have shown a name even if it wanted to --
|
|
2206
|
+
// the field was dropped one layer below the rendering everybody
|
|
2207
|
+
// was blaming.
|
|
2208
|
+
name: r.name ?? null,
|
|
2209
|
+
key: r.key,
|
|
2210
|
+
is_agent: !!r.is_agent,
|
|
2211
|
+
reachable: r.reachable !== false,
|
|
2212
|
+
last_seen: r.last_seen ?? null,
|
|
2213
|
+
})),
|
|
2214
|
+
identities: identitiesHere(baseUrl).map((i) => ({
|
|
2215
|
+
handle: i.handle,
|
|
2216
|
+
key: i.key,
|
|
2217
|
+
// The project it is bound to. Null means it predates per-project
|
|
2218
|
+
// identities and is adopted by any checkout that has none -- worth
|
|
2219
|
+
// showing, because it is why two projects can share an account
|
|
2220
|
+
// without anybody choosing that.
|
|
2221
|
+
repo: i.repo,
|
|
2222
|
+
shared: !i.repo,
|
|
2223
|
+
// Whether it is in the channel this viewer is looking at. An
|
|
2224
|
+
// identity from another account is not a fault; it is the normal
|
|
2225
|
+
// state of a machine that works on two things.
|
|
2226
|
+
inThisChannel: i.key ? inChannel.has(i.key) : false,
|
|
2227
|
+
})),
|
|
2228
|
+
}),
|
|
2229
|
+
);
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2233
|
+
// WHAT AN IDENTITY MAY USE, and how to change it.
|
|
2234
|
+
//
|
|
2235
|
+
// Reading goes through the agent's OWN device credential, because that is the
|
|
2236
|
+
// only route there is: an API key can grant but cannot list somebody's
|
|
2237
|
+
// grants. That asymmetry is deliberate upstream and fine here -- the viewer
|
|
2238
|
+
// only ever shows identities whose credential is on this machine.
|
|
2239
|
+
if (url.pathname === '/secrets') {
|
|
2240
|
+
const who = identities.find((i) => i.key === url.searchParams.get('as') && i.credential);
|
|
2241
|
+
if (!who) {
|
|
2242
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
2243
|
+
res.end(JSON.stringify({ error: 'No credential on this machine for that identity.' }));
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
try {
|
|
2247
|
+
const response = await fetch(`${baseUrl}/v1/devices/me/secrets`, {
|
|
2248
|
+
headers: { Authorization: `Device ${who.credential}` },
|
|
2249
|
+
});
|
|
2250
|
+
const body = await response.json().catch(() => ({}));
|
|
2251
|
+
res.writeHead(response.ok ? 200 : 400, { 'Content-Type': 'application/json' });
|
|
2252
|
+
res.end(
|
|
2253
|
+
JSON.stringify(
|
|
2254
|
+
response.ok
|
|
2255
|
+
? { as: who.key, secrets: body.secrets ?? [] }
|
|
2256
|
+
: { error: body?.error?.message ?? `${response.status}` },
|
|
2257
|
+
),
|
|
2258
|
+
);
|
|
2259
|
+
} catch (error) {
|
|
2260
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
2261
|
+
res.end(JSON.stringify({ error: `Could not reach ${baseUrl}: ${error.message}` }));
|
|
2262
|
+
}
|
|
2263
|
+
return;
|
|
2264
|
+
}
|
|
2265
|
+
|
|
2266
|
+
// GRANTING. The account's key does this, not the agent's credential: an
|
|
2267
|
+
// agent must not be able to widen what it may use, or the grant is a
|
|
2268
|
+
// suggestion. The account check is in SQL, so crossing an account is not
|
|
2269
|
+
// something this can express even if the request tries.
|
|
2270
|
+
if (url.pathname === '/grant' && req.method === 'POST') {
|
|
2271
|
+
let payload;
|
|
2272
|
+
try {
|
|
2273
|
+
payload = await readJson(req);
|
|
2274
|
+
} catch {
|
|
2275
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2276
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2277
|
+
return;
|
|
2278
|
+
}
|
|
2279
|
+
if (!payload.agent || !payload.name || !payload.reference) {
|
|
2280
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2281
|
+
res.end(JSON.stringify({ error: 'Needs an agent, a name, and a reference.' }));
|
|
2282
|
+
return;
|
|
2283
|
+
}
|
|
2284
|
+
|
|
2285
|
+
// Caught here as well as in SQL, so the person typing gets told before a
|
|
2286
|
+
// round trip -- and because the mistake being prevented is the whole point
|
|
2287
|
+
// of the design, not a validation nicety.
|
|
2288
|
+
if (!/^[a-z][a-z0-9+.-]*:\/\//.test(String(payload.reference).trim())) {
|
|
2289
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2290
|
+
res.end(
|
|
2291
|
+
JSON.stringify({
|
|
2292
|
+
error:
|
|
2293
|
+
'That is not a reference. A grant stores WHERE a secret is -- ' +
|
|
2294
|
+
'keychain://service/account -- never the secret itself.',
|
|
2295
|
+
}),
|
|
2296
|
+
);
|
|
2297
|
+
return;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
const body = await upstreamPost(
|
|
2301
|
+
`/v1/agents/${encodeURIComponent(payload.agent)}/secrets`,
|
|
2302
|
+
{
|
|
2303
|
+
name: payload.name,
|
|
2304
|
+
reference: payload.reference,
|
|
2305
|
+
...(payload.scope_path ? { scope_path: payload.scope_path } : {}),
|
|
2306
|
+
},
|
|
2307
|
+
`Bearer ${apiKey}`,
|
|
2308
|
+
);
|
|
2309
|
+
res.writeHead(body.error ? 400 : 200, { 'Content-Type': 'application/json' });
|
|
2310
|
+
res.end(JSON.stringify(body));
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
|
|
2314
|
+
if (url.pathname === '/revoke-secret' && req.method === 'POST') {
|
|
2315
|
+
let payload;
|
|
2316
|
+
try {
|
|
2317
|
+
payload = await readJson(req);
|
|
2318
|
+
} catch {
|
|
2319
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2320
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
try {
|
|
2324
|
+
const response = await fetch(
|
|
2325
|
+
`${baseUrl}/v1/agents/${encodeURIComponent(payload.agent)}/secrets/${encodeURIComponent(payload.name)}`,
|
|
2326
|
+
{ method: 'DELETE', headers: { Authorization: `Bearer ${apiKey}` } },
|
|
2327
|
+
);
|
|
2328
|
+
const body = await response.json().catch(() => ({}));
|
|
2329
|
+
res.writeHead(response.ok ? 200 : 400, { 'Content-Type': 'application/json' });
|
|
2330
|
+
res.end(JSON.stringify(response.ok ? body : { error: body?.error?.message ?? `${response.status}` }));
|
|
2331
|
+
} catch (error) {
|
|
2332
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
2333
|
+
res.end(JSON.stringify({ error: `Could not reach ${baseUrl}: ${error.message}` }));
|
|
2334
|
+
}
|
|
2335
|
+
return;
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
// ONE IDENTITY'S OWN INBOX, whichever account it belongs to.
|
|
2339
|
+
//
|
|
2340
|
+
// The channel log needs an API key and a key names ONE channel, so the main
|
|
2341
|
+
// view can only ever show the account that key belongs to. A machine now
|
|
2342
|
+
// routinely holds identities in two -- this one does -- and the second was
|
|
2343
|
+
// simply invisible here.
|
|
2344
|
+
//
|
|
2345
|
+
// A device credential shows one inbox rather than a whole channel, which is
|
|
2346
|
+
// less, and is the honest most that can be offered: it is what that agent
|
|
2347
|
+
// was sent. Presented as such rather than dressed up as the channel view.
|
|
2348
|
+
if (url.pathname === '/inbox') {
|
|
2349
|
+
const who = identities.find((i) => i.key === url.searchParams.get('as') && i.credential);
|
|
2350
|
+
if (!who) {
|
|
2351
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
2352
|
+
res.end(JSON.stringify({ error: 'No credential on this machine for that identity.' }));
|
|
2353
|
+
return;
|
|
2354
|
+
}
|
|
2355
|
+
try {
|
|
2356
|
+
const response = await fetch(`${baseUrl}/v1/devices/me/messages?limit=100`, {
|
|
2357
|
+
headers: { Authorization: `Device ${who.credential}` },
|
|
2358
|
+
});
|
|
2359
|
+
const body = await response.json().catch(() => ({}));
|
|
2360
|
+
res.writeHead(response.ok ? 200 : 400, { 'Content-Type': 'application/json' });
|
|
2361
|
+
res.end(
|
|
2362
|
+
JSON.stringify(
|
|
2363
|
+
response.ok
|
|
2364
|
+
? {
|
|
2365
|
+
as: { key: who.key, handle: who.handle, repo: who.repo },
|
|
2366
|
+
messages: (body.messages ?? []).map((m) => ({
|
|
2367
|
+
id: m.delivery_id,
|
|
2368
|
+
from_handle: m.from_handle ?? null,
|
|
2369
|
+
title: m.title ?? null,
|
|
2370
|
+
body: m.body ?? null,
|
|
2371
|
+
created_at: m.created_at,
|
|
2372
|
+
answered: m.response_index !== null && m.response_index !== undefined,
|
|
2373
|
+
})),
|
|
2374
|
+
}
|
|
2375
|
+
: { error: body?.error?.message ?? `${response.status}` },
|
|
2376
|
+
),
|
|
2377
|
+
);
|
|
2378
|
+
} catch (error) {
|
|
2379
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
2380
|
+
res.end(JSON.stringify({ error: `Could not reach ${baseUrl}: ${error.message}` }));
|
|
2381
|
+
}
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// BRINGING SOMEBODY IN. The other half of "who do you want to talk to":
|
|
2386
|
+
// seeing the roster answers who you can reach now, and this is how the list
|
|
2387
|
+
// grows.
|
|
2388
|
+
//
|
|
2389
|
+
// The connection type is set HERE, by the inviter, and that is the whole
|
|
2390
|
+
// permission model rather than a separate setting somewhere: a subagent
|
|
2391
|
+
// proposes what it intends and waits to be told yes, a partner works its own
|
|
2392
|
+
// tasks concurrently, a worker does one thing and reports once. An agent
|
|
2393
|
+
// that could choose its own would simply choose not to ask.
|
|
2394
|
+
if (url.pathname === '/invite' && req.method === 'POST') {
|
|
2395
|
+
let payload;
|
|
2396
|
+
try {
|
|
2397
|
+
payload = await readJson(req);
|
|
2398
|
+
} catch {
|
|
2399
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2400
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2401
|
+
return;
|
|
2402
|
+
}
|
|
2403
|
+
if (!payload.channel) {
|
|
2404
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2405
|
+
res.end(JSON.stringify({ error: 'No channel to invite into.' }));
|
|
2406
|
+
return;
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
// Minted BY AN AGENT, not by the account key. This route wants a device
|
|
2410
|
+
// credential and refuses a Bearer one, which is right: minting is a
|
|
2411
|
+
// membership right, and an invitation carries who extended it. That is
|
|
2412
|
+
// what fills in `sponsored_by` and therefore what lets the fleet work out
|
|
2413
|
+
// who leads. A code minted with the account key would arrive sponsored by
|
|
2414
|
+
// nobody -- a root, silently.
|
|
2415
|
+
const inviter = identities.find((i) => i.credential && i.key === (self && self.key));
|
|
2416
|
+
if (!inviter) {
|
|
2417
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2418
|
+
res.end(
|
|
2419
|
+
JSON.stringify({
|
|
2420
|
+
error:
|
|
2421
|
+
'No identity on this machine belongs to that channel, so there is nobody here ' +
|
|
2422
|
+
'to extend the invitation. Connect this project first.',
|
|
2423
|
+
}),
|
|
2424
|
+
);
|
|
2425
|
+
return;
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
const minted = await upstreamPost(
|
|
2429
|
+
`/v1/channels/${encodeURIComponent(payload.channel)}/join-tokens`,
|
|
2430
|
+
{
|
|
2431
|
+
...(payload.name ? { name: payload.name } : {}),
|
|
2432
|
+
// ONE use unless somebody says otherwise. A join code authenticates
|
|
2433
|
+
// whoever holds a copy, so a single-use one is worthless the moment it
|
|
2434
|
+
// is redeemed and a leaked copy of a spent one lets nobody in.
|
|
2435
|
+
max_uses: 1,
|
|
2436
|
+
...(payload.connection_type ? { connection_type: payload.connection_type } : {}),
|
|
2437
|
+
},
|
|
2438
|
+
`Device ${inviter.credential}`,
|
|
2439
|
+
);
|
|
2440
|
+
if (minted.error) {
|
|
2441
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2442
|
+
res.end(JSON.stringify({ error: minted.error }));
|
|
2443
|
+
return;
|
|
2444
|
+
}
|
|
2445
|
+
|
|
2446
|
+
// Two routes mint these and they disagree about the field name -- the
|
|
2447
|
+
// admin one returns `secret`, this one returns `token` -- and reading the
|
|
2448
|
+
// wrong one printed "/agentsignal:join undefined" to somebody once. Take
|
|
2449
|
+
// whichever is there and say so plainly if neither is.
|
|
2450
|
+
const t = minted.token ?? {};
|
|
2451
|
+
const code = t.token ?? t.secret ?? null;
|
|
2452
|
+
if (!code) {
|
|
2453
|
+
res.writeHead(502, { 'Content-Type': 'application/json' });
|
|
2454
|
+
res.end(
|
|
2455
|
+
JSON.stringify({
|
|
2456
|
+
error: `The token came back without a code. Fields: ${Object.keys(t).join(', ') || 'none'}.`,
|
|
2457
|
+
}),
|
|
2458
|
+
);
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2463
|
+
res.end(JSON.stringify({ ok: true, code, expires_at: t.expires_at ?? null }));
|
|
2464
|
+
return;
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
// CONNECTING A PROJECT: register an agent bound to one checkout.
|
|
2468
|
+
//
|
|
2469
|
+
// The folder half of onboarding cannot live on a website -- agentsignal.net
|
|
2470
|
+
// cannot enumerate the directories on your laptop, and should not be able
|
|
2471
|
+
// to. So it lives here, where the machine already knows.
|
|
2472
|
+
if (url.pathname === '/connect' && req.method === 'POST') {
|
|
2473
|
+
let payload;
|
|
2474
|
+
try {
|
|
2475
|
+
payload = await readJson(req);
|
|
2476
|
+
} catch {
|
|
2477
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2478
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
const root = repoRoot(payload.path || process.cwd());
|
|
2483
|
+
if (!root) {
|
|
2484
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2485
|
+
res.end(
|
|
2486
|
+
JSON.stringify({
|
|
2487
|
+
error:
|
|
2488
|
+
`${payload.path || process.cwd()} is not inside a git repository. ` +
|
|
2489
|
+
'An identity is per project, and a project is a checkout.',
|
|
2490
|
+
}),
|
|
2491
|
+
);
|
|
2492
|
+
return;
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2495
|
+
// THE CAP, enforced where an agent is actually created rather than stored
|
|
2496
|
+
// and admired. A limit nothing checks is the "column, not a feature"
|
|
2497
|
+
// failure this codebase keeps producing: the number is real, the file is
|
|
2498
|
+
// real, and no code path consults either.
|
|
2499
|
+
//
|
|
2500
|
+
// Checked before registering, not after: the alternative leaves an agent
|
|
2501
|
+
// on the server that this machine then refuses to write a credential for,
|
|
2502
|
+
// which is an account somebody has to clean up by hand.
|
|
2503
|
+
const cap = settings().max_agents;
|
|
2504
|
+
const existing = identitiesHere(baseUrl).length;
|
|
2505
|
+
if (existing >= cap) {
|
|
2506
|
+
res.writeHead(409, { 'Content-Type': 'application/json' });
|
|
2507
|
+
res.end(
|
|
2508
|
+
JSON.stringify({
|
|
2509
|
+
error:
|
|
2510
|
+
`This machine is set to at most ${cap} agents and already has ${existing}. ` +
|
|
2511
|
+
'Raise the limit in Setup, or remove an agent first.',
|
|
2512
|
+
}),
|
|
2513
|
+
);
|
|
2514
|
+
return;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
const already = identitiesHere(baseUrl).find((i) => i.repo === root);
|
|
2518
|
+
if (already) {
|
|
2519
|
+
res.writeHead(409, { 'Content-Type': 'application/json' });
|
|
2520
|
+
res.end(
|
|
2521
|
+
JSON.stringify({
|
|
2522
|
+
error: `${root} is already connected as ${already.handle}. Remove that agent first to re-register it.`,
|
|
2523
|
+
}),
|
|
2524
|
+
);
|
|
2525
|
+
return;
|
|
2526
|
+
}
|
|
2527
|
+
|
|
2528
|
+
const registered = await upstreamPost(
|
|
2529
|
+
'/v1/agents/register',
|
|
2530
|
+
{
|
|
2531
|
+
handle: payload.handle,
|
|
2532
|
+
...(payload.description ? { description: payload.description } : {}),
|
|
2533
|
+
...(Array.isArray(payload.capabilities) && payload.capabilities.length
|
|
2534
|
+
? { capabilities: payload.capabilities }
|
|
2535
|
+
: {}),
|
|
2536
|
+
instance_id: uuid(),
|
|
2537
|
+
},
|
|
2538
|
+
`Bearer ${apiKey}`,
|
|
2539
|
+
);
|
|
2540
|
+
if (registered.error) {
|
|
2541
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2542
|
+
res.end(JSON.stringify({ error: registered.error }));
|
|
2543
|
+
return;
|
|
2544
|
+
}
|
|
2545
|
+
|
|
2546
|
+
// Written where the MCP server and the watcher look, stamped with the
|
|
2547
|
+
// project so no other checkout adopts it. Anything else here is a
|
|
2548
|
+
// credential that exists and is never found.
|
|
2549
|
+
const dir = join(writeDir(), 'agents', repoSlug(root));
|
|
2550
|
+
try {
|
|
2551
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
2552
|
+
writeFileSync(
|
|
2553
|
+
join(dir, 'agent.json'),
|
|
2554
|
+
JSON.stringify(
|
|
2555
|
+
{
|
|
2556
|
+
base_url: baseUrl,
|
|
2557
|
+
handle: registered.agent?.handle,
|
|
2558
|
+
key: registered.agent?.key,
|
|
2559
|
+
credential: registered.device_secret,
|
|
2560
|
+
saved_at: new Date().toISOString(),
|
|
2561
|
+
repo: root,
|
|
2562
|
+
},
|
|
2563
|
+
null,
|
|
2564
|
+
2,
|
|
2565
|
+
),
|
|
2566
|
+
{ mode: 0o600 },
|
|
2567
|
+
);
|
|
2568
|
+
} catch (error) {
|
|
2569
|
+
// The agent exists on the server either way, so say so rather than
|
|
2570
|
+
// implying nothing happened -- otherwise the next attempt collides with
|
|
2571
|
+
// a handle somebody cannot see.
|
|
2572
|
+
res.writeHead(500, { 'Content-Type': 'application/json' });
|
|
2573
|
+
res.end(
|
|
2574
|
+
JSON.stringify({
|
|
2575
|
+
error:
|
|
2576
|
+
`Registered as ${registered.agent?.handle}, but could not write the credential ` +
|
|
2577
|
+
`to ${dir}: ${error.message}. The agent exists; this machine cannot use it.`,
|
|
2578
|
+
}),
|
|
2579
|
+
);
|
|
2580
|
+
return;
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2584
|
+
res.end(
|
|
2585
|
+
JSON.stringify({ ok: true, handle: registered.agent?.handle, key: registered.agent?.key, repo: root }),
|
|
2586
|
+
);
|
|
2587
|
+
return;
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// WAITING ON YOU: the questions, from the device inboxes of the identities
|
|
2591
|
+
// this machine holds.
|
|
2592
|
+
//
|
|
2593
|
+
// Not from the channel log, which cannot answer this: `agent_message_log`
|
|
2594
|
+
// does not carry `options` at all, so a question and a statement look
|
|
2595
|
+
// identical there. The device inbox does carry them, and a question is by
|
|
2596
|
+
// definition addressed to somebody -- so the right source is the inbox of
|
|
2597
|
+
// each identity, which is also the only place the answer could come from.
|
|
2598
|
+
//
|
|
2599
|
+
// A plain GET of an inbox is not destructive. The call that purges a
|
|
2600
|
+
// read-once message is the explicit POST .../read, which this never makes.
|
|
2601
|
+
if (url.pathname === '/pending') {
|
|
2602
|
+
const out = [];
|
|
2603
|
+
for (const who of identities.filter((i) => i.credential)) {
|
|
2604
|
+
try {
|
|
2605
|
+
const response = await fetch(`${baseUrl}/v1/devices/me/messages?limit=50`, {
|
|
2606
|
+
headers: { Authorization: `Device ${who.credential}` },
|
|
2607
|
+
});
|
|
2608
|
+
if (!response.ok) continue;
|
|
2609
|
+
const body = await response.json();
|
|
2610
|
+
for (const m of body.messages ?? []) {
|
|
2611
|
+
// ANSWERED ones are not waiting. Answering does not remove a
|
|
2612
|
+
// message from an inbox -- the record of the question stays -- so
|
|
2613
|
+
// without this the list keeps offering buttons for decisions
|
|
2614
|
+
// already taken, and "unblock the subagent" shows work that is
|
|
2615
|
+
// no longer blocked. `response_index` is null until somebody votes.
|
|
2616
|
+
const answered = m.response_index !== null && m.response_index !== undefined;
|
|
2617
|
+
if (!answered && Array.isArray(m.options) && m.options.length) {
|
|
2618
|
+
out.push({
|
|
2619
|
+
delivery_id: m.delivery_id,
|
|
2620
|
+
title: m.title ?? null,
|
|
2621
|
+
body: m.body ?? null,
|
|
2622
|
+
options: m.options,
|
|
2623
|
+
created_at: m.created_at,
|
|
2624
|
+
// Which identity may answer, so the page can label it when the
|
|
2625
|
+
// machine holds several and they are in different accounts.
|
|
2626
|
+
as: who.key,
|
|
2627
|
+
as_handle: who.handle,
|
|
2628
|
+
});
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
} catch {
|
|
2632
|
+
/* one unreachable inbox should not empty the list */
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
out.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
|
|
2636
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2637
|
+
res.end(JSON.stringify({ pending: out }));
|
|
2638
|
+
return;
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
// ANSWERING a message that offered options -- approve/disapprove, and
|
|
2642
|
+
// therefore unblocking a subagent that is waiting on one.
|
|
2643
|
+
//
|
|
2644
|
+
// Device-authenticated, not key-authenticated, because the answer belongs to
|
|
2645
|
+
// the RECIPIENT: the API endpoint is /v1/devices/me/... and an API key
|
|
2646
|
+
// cannot vote on somebody's behalf. So this only works for a message
|
|
2647
|
+
// addressed to an identity whose credential is on this machine, which is
|
|
2648
|
+
// exactly the fleet this viewer is for.
|
|
2649
|
+
if (url.pathname === '/respond' && req.method === 'POST') {
|
|
2650
|
+
let payload;
|
|
2651
|
+
try {
|
|
2652
|
+
payload = await readJson(req);
|
|
2653
|
+
} catch {
|
|
2654
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2655
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2656
|
+
return;
|
|
2657
|
+
}
|
|
2658
|
+
|
|
2659
|
+
const who = identities.find((i) => i.key === payload.as && i.credential);
|
|
2660
|
+
if (!who) {
|
|
2661
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2662
|
+
res.end(
|
|
2663
|
+
JSON.stringify({
|
|
2664
|
+
error:
|
|
2665
|
+
`No credential on this machine for ${payload.as ?? 'that recipient'}, so this ` +
|
|
2666
|
+
'viewer cannot answer as them. Whoever holds it has to answer.',
|
|
2667
|
+
}),
|
|
2668
|
+
);
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
|
|
2672
|
+
// The API takes an INDEX, not the text. The page already has the exact
|
|
2673
|
+
// options array it rendered buttons from, so it sends the position and
|
|
2674
|
+
// nothing has to match strings -- which is where "Approve" and "approve"
|
|
2675
|
+
// become a silent failure.
|
|
2676
|
+
const index = payload.option_index;
|
|
2677
|
+
if (!Number.isInteger(index) || index < 0 || index > 2) {
|
|
2678
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2679
|
+
res.end(JSON.stringify({ error: 'That is not one of the answers offered.' }));
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
const body = await upstreamPost(
|
|
2684
|
+
`/v1/devices/me/messages/${encodeURIComponent(payload.delivery_id)}/respond`,
|
|
2685
|
+
{ option_index: index },
|
|
2686
|
+
`Device ${who.credential}`,
|
|
2687
|
+
);
|
|
2688
|
+
res.writeHead(body.error ? 400 : 200, { 'Content-Type': 'application/json' });
|
|
2689
|
+
res.end(JSON.stringify(body));
|
|
2690
|
+
return;
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
// SENDING, as the channel rather than as an agent. A human at this viewer is
|
|
2694
|
+
// not one of the agents, and signing their message with one of the machine's
|
|
2695
|
+
// identities would put words in that agent's mouth in a log others read.
|
|
2696
|
+
if (url.pathname === '/send' && req.method === 'POST') {
|
|
2697
|
+
let payload;
|
|
2698
|
+
try {
|
|
2699
|
+
payload = await readJson(req);
|
|
2700
|
+
} catch {
|
|
2701
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2702
|
+
res.end(JSON.stringify({ error: 'Unreadable request.' }));
|
|
2703
|
+
return;
|
|
2704
|
+
}
|
|
2705
|
+
if (!payload.to || !payload.body) {
|
|
2706
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
2707
|
+
res.end(JSON.stringify({ error: 'Needs somebody to send to and something to say.' }));
|
|
2708
|
+
return;
|
|
2709
|
+
}
|
|
2710
|
+
const body = await upstreamPost(
|
|
2711
|
+
'/v1/messages',
|
|
2712
|
+
{ to: payload.to, body: payload.body, ...(payload.title ? { title: payload.title } : {}) },
|
|
2713
|
+
`Bearer ${apiKey}`,
|
|
2714
|
+
);
|
|
2715
|
+
res.writeHead(body.error ? 400 : 200, { 'Content-Type': 'application/json' });
|
|
2716
|
+
res.end(JSON.stringify(body));
|
|
2717
|
+
return;
|
|
2718
|
+
}
|
|
2719
|
+
|
|
2720
|
+
if (url.pathname === '/messages') {
|
|
2721
|
+
/**
|
|
2722
|
+
* ASK FOR WHAT IS NEW, not for the last hundred every two seconds.
|
|
2723
|
+
*
|
|
2724
|
+
* `since` is what makes an idle poll return an empty array, which is what
|
|
2725
|
+
* the API now refunds -- so watching a quiet channel costs nothing and
|
|
2726
|
+
* receiving a message costs what it always did. Without the local copy
|
|
2727
|
+
* there is nothing to compute a `since` from, which is why these two
|
|
2728
|
+
* changes are one change.
|
|
2729
|
+
*
|
|
2730
|
+
* The stamp comes from the newest row HELD rather than from the clock: a
|
|
2731
|
+
* machine whose time is a few seconds fast would otherwise ask for
|
|
2732
|
+
* messages newer than a moment that has not happened yet and never see
|
|
2733
|
+
* the ones in between.
|
|
2734
|
+
*/
|
|
2735
|
+
const kept = readHistory(channelRef);
|
|
2736
|
+
const newest = kept.length ? kept[0].created_at : null;
|
|
2737
|
+
const body = await upstream(
|
|
2738
|
+
'/v1/messages?limit=100' + (newest ? '&since=' + encodeURIComponent(newest) : ''),
|
|
2739
|
+
);
|
|
2740
|
+
|
|
2741
|
+
if (!body.error) {
|
|
2742
|
+
// The ref is only known once the API has answered once; until then the
|
|
2743
|
+
// history lands in a generic file and is adopted on the next start.
|
|
2744
|
+
channelRef = body.channel?.ref ?? channelRef;
|
|
2745
|
+
|
|
2746
|
+
const fresh = (body.messages ?? []).map(keepable).filter(Boolean);
|
|
2747
|
+
// Deduplicated by id, because `since` is inclusive at the boundary on a
|
|
2748
|
+
// shared timestamp and two messages in the same second are ordinary.
|
|
2749
|
+
const byId = new Map(kept.map((m) => [m.id, m]));
|
|
2750
|
+
for (const m of fresh) byId.set(m.id, m);
|
|
2751
|
+
|
|
2752
|
+
body.messages = writeHistory(channelRef, [...byId.values()], settings().history_days);
|
|
2753
|
+
// What this call actually cost, so the page can say so rather than
|
|
2754
|
+
// implying every refresh is free or that every refresh is billed.
|
|
2755
|
+
body.fetched = fresh.length;
|
|
2756
|
+
}
|
|
2757
|
+
|
|
2758
|
+
const agent = url.searchParams.get('agent');
|
|
2759
|
+
|
|
2760
|
+
// Filtered here rather than in the page, so the browser never holds
|
|
2761
|
+
// traffic belonging to agents whose view it did not ask for.
|
|
2762
|
+
if (!body.error && agent) {
|
|
2763
|
+
body.messages = (body.messages ?? []).filter((m) => involves(m, agent));
|
|
2764
|
+
body.agent = agent;
|
|
2765
|
+
}
|
|
2766
|
+
|
|
2767
|
+
if (!body.error) {
|
|
2768
|
+
body.self = self;
|
|
2769
|
+
// Keys only. The page is told WHICH recipients it may answer for so it
|
|
2770
|
+
// can show buttons for those and nothing for the rest; the credentials
|
|
2771
|
+
// that make it possible stay in this process.
|
|
2772
|
+
body.answerable = identities.filter((i) => i.credential).map((i) => i.key);
|
|
2773
|
+
}
|
|
2774
|
+
|
|
2775
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2776
|
+
res.end(JSON.stringify(body));
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
if (url.pathname === '/agents') {
|
|
2781
|
+
/**
|
|
2782
|
+
* ONE REQUEST. This used to make two.
|
|
2783
|
+
*
|
|
2784
|
+
* The key directory did not carry sponsored_by -- only the device
|
|
2785
|
+
* directory did -- so the tree was assembled by fetching both and merging
|
|
2786
|
+
* them on key. That worked, and only on a machine that already held an
|
|
2787
|
+
* identity in this channel: a machine being set up for the first time has
|
|
2788
|
+
* no credential to ask with, so the hierarchy was flat in exactly the
|
|
2789
|
+
* situation it would have helped most. It also picked the wrong identity
|
|
2790
|
+
* on a machine holding two, and answered about a fleet the key had never
|
|
2791
|
+
* heard of.
|
|
2792
|
+
*
|
|
2793
|
+
* The field is in the key directory now, so the workaround is gone rather
|
|
2794
|
+
* than kept beside its replacement. Two paths to one value is how the
|
|
2795
|
+
* copies in this codebase drift.
|
|
2796
|
+
*/
|
|
2797
|
+
const body = await upstream('/v1/agents');
|
|
2798
|
+
|
|
2799
|
+
|
|
2800
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
2801
|
+
res.end(JSON.stringify(body));
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
// /a/<recipient key or handle> -- one agent's conversation. The whole point
|
|
2806
|
+
// of a path rather than a port: several agents run at once, and a port each
|
|
2807
|
+
// means a port to remember each and a viewer to start each.
|
|
2808
|
+
if (url.pathname === '/' || url.pathname.startsWith('/a/')) {
|
|
2809
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
2810
|
+
res.end(PAGE);
|
|
2811
|
+
return;
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
2815
|
+
res.end('No such view. Try / for the channel, or /a/<agent> for one agent.');
|
|
2816
|
+
});
|
|
2817
|
+
|
|
2818
|
+
resolveSelf();
|
|
2819
|
+
|
|
2820
|
+
server.listen(port, '127.0.0.1', () => {
|
|
2821
|
+
// The port the OS actually gave us, not the one asked for. They differ
|
|
2822
|
+
// whenever PORT is 0 -- which is how anything automated starts a server
|
|
2823
|
+
// without picking a number and hoping -- and printing the request rather
|
|
2824
|
+
// than the result hands out a link to port 0, which connects to nothing.
|
|
2825
|
+
const bound = server.address()?.port ?? port;
|
|
2826
|
+
console.error(`Watching ${baseUrl} on http://127.0.0.1:${bound}/?t=${token}`);
|
|
2827
|
+
console.error('Loopback only, and the link carries a one-run token: it can now send and answer.');
|
|
2828
|
+
console.error('The key stays in this process; the page only ever talks to this server.');
|
|
2829
|
+
});
|