@agentsignalnet/claude-plugin 0.2.78 → 0.2.81

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agentsignal",
3
3
  "displayName": "AgentSignal",
4
- "version": "0.2.78",
4
+ "version": "0.2.81",
5
5
  "description": "Page a human from inside Claude Code, or become an addressable agent that other agents can reach.",
6
6
  "author": {
7
7
  "name": "Data Group AI",
package/.mcp.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "mcpServers": {
3
3
  "agentsignal": {
4
4
  "command": "npx",
5
- "args": ["-y", "@agentsignalnet/mcp@0.2.55"],
5
+ "args": ["-y", "@agentsignalnet/mcp@0.2.57"],
6
6
  "env": {
7
7
  "AGENTSIGNAL_API_KEY": "${user_config.api_key}",
8
8
  "AGENTSIGNAL_JOIN_TOKEN": "${user_config.join_token}",
@@ -20,9 +20,14 @@ a link to it hands somebody.
20
20
  Run it in the BACKGROUND. It is a server, not a command that finishes, and
21
21
  waiting on it in the foreground hangs the turn until something kills it.
22
22
 
23
- If it says the port is already in use, that is usually a dashboard ALREADY
24
- RUNNING and working. Do not start a second one on another port -- find the
25
- link the running one printed, in the output of whatever started it.
23
+ If 8899 is taken it moves up -- 8900, 8901 -- and says so, because a second
24
+ dashboard is the SUPPORTED way to watch a second company rather than a
25
+ mistake to prevent. Read what it printed: it names the port it stepped over,
26
+ hands you the link of the dashboard already there, and says which port this
27
+ one took. Both are then running, and they are different dashboards.
28
+
29
+ To pin a port, `--port 8900`. That one REFUSES if it is busy rather than
30
+ moving, on the grounds that a number typed just now is an instruction.
26
31
 
27
32
  `${CLAUDE_PLUGIN_ROOT}` is where the plugin was installed. If the variable is
28
33
  not set, the script is at `plugins/agentsignal/scripts/dashboard.mjs` in
@@ -46,13 +51,30 @@ a link to it hands somebody.
46
51
  waiting and which companies it is offering.
47
52
 
48
53
  The answer holds for the life of that process, so a second company means a
49
- second dashboard on another port rather than switching this one.
54
+ second dashboard rather than switching this one. Just start another; it
55
+ finds its own port. The new one asks the same question, and the answer to
56
+ that one is theirs too -- including when the obvious answer is the company
57
+ the first dashboard is not showing.
50
58
 
51
59
  4. Give the user the PRINTED link, the one carrying `?t=`. It is spent once for
52
60
  a cookie and after that the plain address works, so hand over the printed one
53
61
  even though the address bar will not keep it.
54
62
 
55
- Default port 8899; set `PORT` if it is taken.
63
+ Default port 8899, moving up if it is taken. `PORT` sets the starting point;
64
+ `--port` pins one and refuses to move.
65
+
66
+ IF THE LINK IS LOST -- a background start whose output has scrolled away, or
67
+ a dashboard from an earlier session -- it is on disk, per port, and does not
68
+ need the process to be dug into:
69
+
70
+ ```
71
+ cat ~/.agentsignal/dashboards/8899.json
72
+ ```
73
+
74
+ One file per running dashboard, named for its port, removed when that
75
+ dashboard stops. A port with no file is a dashboard started before this was
76
+ added, or one that was killed outright; the link is genuinely gone then and
77
+ the fix is to stop it and start another.
56
78
 
57
79
  - `http://127.0.0.1:8899/` — the whole channel, once the link has been opened
58
80
  - `http://127.0.0.1:8899/a/$1` — one agent's side of it, when a handle was
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentsignalnet/claude-plugin",
3
- "version": "0.2.78",
3
+ "version": "0.2.81",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -127,7 +127,63 @@ function borrowFromMcpConfig() {
127
127
  */
128
128
  let apiKey = process.env.AGENTSIGNAL_API_KEY;
129
129
  let baseUrl = process.env.AGENTSIGNAL_BASE_URL;
130
- const port = Number(process.env.PORT ?? 8899);
130
+
131
+ /**
132
+ * `--port 8900`, `--port=8900`, or PORT. The flag wins, and the flag INSISTS.
133
+ *
134
+ * Three ways to name a port and only two behaviours, so the line is drawn where
135
+ * the difference actually is -- not at "was a number supplied" but at "did a
136
+ * person type this number, just now, meaning this run".
137
+ *
138
+ * - The 8899 default and PORT are a STARTING POINT. The retry at the bottom
139
+ * of this file walks up from either when it is busy. PORT is usually
140
+ * ambient: inherited from a shell profile, a launch config, or something
141
+ * three layers up that nobody is thinking about at the moment it collides.
142
+ * Refusing to start over a number the person may not know is set trades a
143
+ * working dashboard for a lecture.
144
+ * - `--port` is an INSTRUCTION. It was typed at the moment of running, about
145
+ * this run, so quietly landing somewhere else is ignoring it -- and then
146
+ * printing a link to a port they never asked for. That case refuses and
147
+ * says the port is taken.
148
+ *
149
+ * Which is also why the flag beats PORT when they disagree: one of them is a
150
+ * decision and the other is an inheritance.
151
+ */
152
+ function portFlag(argv) {
153
+ for (let i = 0; i < argv.length; i += 1) {
154
+ // `?? ''` rather than the missing value itself: `--port` with nothing after
155
+ // it is a typed instruction with the number left off, and returning
156
+ // undefined there would quietly hand the run back to PORT or to 8899. The
157
+ // empty string is not a port and is rejected below, which is the answer.
158
+ if (argv[i] === '--port') return argv[i + 1] ?? '';
159
+ const inline = /^--port=(.*)$/.exec(argv[i]);
160
+ if (inline) return inline[1];
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ const insisted = portFlag(process.argv.slice(2));
166
+
167
+ /**
168
+ * An empty PORT is NOT SET, which is what an unset variable looks like once a
169
+ * shell or a spawn has passed it through. An empty `--port` is a mistake. The
170
+ * same empty string, read two ways, because only one of them was typed.
171
+ */
172
+ const fromEnv = (process.env.PORT ?? '').trim() === '' ? undefined : process.env.PORT;
173
+ const requested = insisted ?? fromEnv;
174
+
175
+ /** True only for `--port`: the one form that refuses rather than moving up. */
176
+ const portInsisted = insisted !== undefined;
177
+ const port = Number(requested ?? 8899);
178
+
179
+ if (String(requested ?? '8899').trim() === '' || !Number.isInteger(port) || port < 0 || port > 65535) {
180
+ // Left alone, a typo reaches listen() as NaN and an empty --port reaches it
181
+ // as 0 -- and node reads both as "any free port". So the mistake became a
182
+ // dashboard on a port nobody can predict rather than a complaint about the
183
+ // mistake.
184
+ console.error(`"${requested}" is not a port. Give a whole number from 0 to 65535.`);
185
+ process.exit(1);
186
+ }
131
187
 
132
188
  /**
133
189
  * The port actually BOUND, which is not always the one asked for.
@@ -154,7 +210,11 @@ let bound = port;
154
210
  * Two things rather than one, because each covers the other's gap: binding to
155
211
  * 127.0.0.1 stops the network, and the token stops anything else on this
156
212
  * machine -- another user's process, a page in your browser guessing the port.
157
- * Minted per run and never written down, so closing the dashboard revokes it.
213
+ * Minted per run, so closing the dashboard revokes it.
214
+ *
215
+ * It IS written down, once, into the lock metadata at takeLock() below -- 0600,
216
+ * in this user's own state directory, removed on the way out. That is a
217
+ * deliberate trade and the note at linkOn() argues it.
158
218
  */
159
219
  const token = randomUUID();
160
220
 
@@ -186,7 +246,18 @@ const COOKIE = 'agentsignal_viewer';
186
246
  */
187
247
  const lockRoot = process.env.AGENTSIGNAL_STATE_DIR || join(homedir(), '.agentsignal');
188
248
  const lockPath = port ? join(lockRoot, `dashboard-${port}.pid`) : null;
189
- const lockMetaPath = port ? join(lockRoot, `dashboard-${port}.meta.json`) : null;
249
+
250
+ /**
251
+ * Keyed on a port given as an argument rather than on `port`, because the two
252
+ * differ exactly when it matters. PORT=0 does not know its port until the bind
253
+ * has happened, and that is the case where the address is least guessable and
254
+ * the recorded link is worth the most.
255
+ */
256
+ function metaPathFor(p) {
257
+ return join(lockRoot, `dashboard-${p}.meta.json`);
258
+ }
259
+
260
+ const lockMetaPath = port ? metaPathFor(port) : null;
190
261
 
191
262
  /** When THIS build was written, which is what decides who is newer. */
192
263
  function buildTime() {
@@ -212,11 +283,12 @@ function holder() {
212
283
  }
213
284
  try {
214
285
  const meta = JSON.parse(readFileSync(lockMetaPath, 'utf8'));
215
- if (meta?.pid === pid) return { pid, script: meta.script ?? null, mtime: meta.mtime ?? 0 };
286
+ if (meta?.pid === pid)
287
+ return { pid, script: meta.script ?? null, mtime: meta.mtime ?? 0, url: meta.url ?? null };
216
288
  } catch {
217
289
  /* absent, unreadable, or about somebody else */
218
290
  }
219
- return { pid, script: null, mtime: 0 };
291
+ return { pid, script: null, mtime: 0, url: null };
220
292
  }
221
293
 
222
294
  async function goneWithin(pid, ms) {
@@ -300,7 +372,7 @@ const answerCache = new Map();
300
372
 
301
373
  /** The routes a person navigates to, as opposed to the ones the page polls. */
302
374
  function isPage(pathname) {
303
- return pathname === '/' || pathname.startsWith('/a/');
375
+ return pathname === '/' || pathname === '/settings' || pathname.startsWith('/a/');
304
376
  }
305
377
 
306
378
  /**
@@ -1053,6 +1125,16 @@ const PAGE = `<!doctype html>
1053
1125
  #compose button:hover { filter:brightness(1.06); }
1054
1126
  #compose button:focus-visible { outline:none; box-shadow:var(--focus); }
1055
1127
 
1128
+ #machine-link { display:block; margin:0; padding:.5rem .6rem; border:1px solid var(--line);
1129
+ border-radius:10px; font-size:.75rem; letter-spacing:.07em;
1130
+ text-transform:uppercase; color:inherit; text-decoration:none; }
1131
+ #machine-link:hover { border-color:var(--accent); }
1132
+ #machine-link.on { border-color:var(--accent); font-weight:600; }
1133
+ /* :not([hidden]) is load-bearing. The hidden attribute hides by way of a UA
1134
+ display:none, and ANY author display rule outranks it -- so a bare
1135
+ display:flex here put the machine panel above the conversation everywhere. */
1136
+ #settingsbody:not([hidden]) { display:flex; flex-direction:column; gap:.4rem; }
1137
+ #invitebox:not(:empty) { margin-top:.9rem; padding-top:.7rem; border-top:1px solid var(--line); }
1056
1138
  #setup { margin:0; border:1px solid var(--line); border-radius:10px;
1057
1139
  padding:.6rem .75rem; background:var(--card); }
1058
1140
  #setup summary { cursor:pointer; font-size:.75rem; letter-spacing:.07em;
@@ -1100,9 +1182,10 @@ const PAGE = `<!doctype html>
1100
1182
  <aside id="side" aria-label="Channels">
1101
1183
  <p class="rail-title" id="rail-title">Channels</p>
1102
1184
  <nav id="who-nav"></nav>
1103
- <details id="setup"><summary>This machine</summary><div id="setupbody">reading…</div></details>
1185
+ <a id="machine-link" href="/settings">This machine</a>
1104
1186
  </aside>
1105
1187
  <main>
1188
+ <div id="settingsbody" hidden>reading…</div>
1106
1189
  <div id="pending"></div>
1107
1190
  <div id="log" class="empty">Waiting for traffic…</div>
1108
1191
  <form id="compose" autocomplete="off">
@@ -1114,6 +1197,13 @@ const PAGE = `<!doctype html>
1114
1197
  </main>
1115
1198
  <aside id="right" aria-label="Who is working">
1116
1199
  <div id="rightbody"></div>
1200
+ <!--
1201
+ A SEPARATE BOX, because workers() rewrites #rightbody on every poll. An
1202
+ invite form living in there would have its half-typed name, and the code it
1203
+ just minted, wiped a second or two later -- which is exactly when somebody
1204
+ is reading the code in order to paste it.
1205
+ -->
1206
+ <div id="invitebox"></div>
1117
1207
  </aside>
1118
1208
  </div>
1119
1209
  <script>
@@ -1735,8 +1825,8 @@ const PAGE = `<!doctype html>
1735
1825
  '</div>',
1736
1826
  )
1737
1827
  .join('') +
1738
- '<p class="elsewhere-why">A different company, so a different dashboard. Start one ' +
1739
- 'with that key, on another port if this one is busy.</p></div>'
1828
+ '<p class="elsewhere-why">A different company, so a different dashboard. Start ' +
1829
+ 'another one — it finds its own port when this one has 8899.</p></div>'
1740
1830
  : '');
1741
1831
 
1742
1832
  markNav();
@@ -1859,10 +1949,21 @@ const PAGE = `<!doctype html>
1859
1949
  let stick = true;
1860
1950
  let shownAgent = null;
1861
1951
 
1952
+ /*
1953
+ NOTHING TO FOLLOW ON THE MACHINE'S PAGE. Sticking to the bottom is right for
1954
+ a log that grows underneath you and wrong for a settings form that does not:
1955
+ unguarded, every tick scrolled the window down and left the top of the page
1956
+ -- the identities table and the guide -- above the fold on arrival.
1957
+ */
1958
+ const following = () => !document.getElementById('log')?.hidden;
1959
+
1862
1960
  const atBottom = () =>
1961
+ following() &&
1863
1962
  document.documentElement.scrollHeight - (window.scrollY + window.innerHeight) <= NEAR_BOTTOM;
1864
1963
 
1865
- const toBottom = () => window.scrollTo(0, document.documentElement.scrollHeight);
1964
+ const toBottom = () => {
1965
+ if (following()) window.scrollTo(0, document.documentElement.scrollHeight);
1966
+ };
1866
1967
 
1867
1968
  /**
1868
1969
  * MEASURED BEFORE THE REDRAW, and not from a scroll listener.
@@ -2375,7 +2476,59 @@ const PAGE = `<!doctype html>
2375
2476
  /* the channel still works without it; this is guidance, not a gate */
2376
2477
  }
2377
2478
 
2378
- document.getElementById('setupbody').innerHTML =
2479
+ /*
2480
+ BRING SOMEBODY IN sits beside WHO IS WORKING, because they are the same
2481
+ question a beat apart: who is here, and who else should be. It was at the
2482
+ bottom of a drawer in the rail, under the identities table and the roster,
2483
+ which is the last place somebody looks when the answer to "nobody is
2484
+ picking this up" is to invite one more.
2485
+ */
2486
+ const invitebox = document.getElementById('invitebox');
2487
+ if (invitebox) {
2488
+ invitebox.innerHTML = d.channel
2489
+ ? '<form id="invite"><div class="meta">Bring somebody in</div>' +
2490
+ '<input id="iname" placeholder="what to call them" maxlength="80" />' +
2491
+ '<select id="itype">' +
2492
+ '<option value="partner">partner — works alongside you</option>' +
2493
+ '<option value="subagent">subagent — asks before it acts</option>' +
2494
+ '<option value="worker">worker — one task, reports once</option>' +
2495
+ '</select><button type="submit">Make a code</button>' +
2496
+ '<div class="meta" id="imsg"></div></form>'
2497
+ : '';
2498
+ }
2499
+
2500
+ const inviteForm = document.getElementById('invite');
2501
+ if (inviteForm) {
2502
+ inviteForm.onsubmit = async (event) => {
2503
+ event.preventDefault();
2504
+ const msg = document.getElementById('imsg');
2505
+ msg.textContent = 'minting…';
2506
+ const result = await post('/invite', {
2507
+ channel: d.channel.ref,
2508
+ name: document.getElementById('iname').value.trim() || undefined,
2509
+ connection_type: document.getElementById('itype').value,
2510
+ });
2511
+ if (result.error) {
2512
+ msg.textContent = result.error;
2513
+ return;
2514
+ }
2515
+ // Shown once, and shown as the line they actually run. A code with no
2516
+ // instruction next to it gets pasted into a config file, which is the
2517
+ // slow path and leaves a credential in a file.
2518
+ msg.innerHTML =
2519
+ 'Send them this — single use' +
2520
+ (result.expires_at ? ', expires ' + esc(new Date(result.expires_at).toLocaleString()) : '') +
2521
+ ':<br><code>/agentsignal:join ' +
2522
+ esc(result.code) +
2523
+ '</code>';
2524
+ };
2525
+ }
2526
+
2527
+ // The rest is the machine's own page, and there is no element to fill when
2528
+ // the conversation is what is on screen.
2529
+ const panel = document.getElementById('settingsbody');
2530
+ if (!panel) return;
2531
+ panel.innerHTML =
2379
2532
  guide +
2380
2533
  '<table class="ids"><tr><th>agent</th><th>project</th><th>where</th><th></th></tr>' +
2381
2534
  rows +
@@ -2384,17 +2537,7 @@ const PAGE = `<!doctype html>
2384
2537
  ? '<div class="meta" style="margin-top:.6rem">Who this channel reaches</div>' +
2385
2538
  '<table class="ids"><tr><th>name</th><th>kind</th><th></th></tr>' +
2386
2539
  reach +
2387
- '</table>' +
2388
- (d.channel
2389
- ? '<form id="invite"><div class="meta">Bring somebody in</div>' +
2390
- '<input id="iname" placeholder="what to call them" maxlength="80" />' +
2391
- '<select id="itype">' +
2392
- '<option value="partner">partner — works alongside you</option>' +
2393
- '<option value="subagent">subagent — asks before it acts</option>' +
2394
- '<option value="worker">worker — one task, reports once</option>' +
2395
- '</select><button type="submit">Make a code</button>' +
2396
- '<div class="meta" id="imsg"></div></form>'
2397
- : '')
2540
+ '</table>'
2398
2541
  : '') +
2399
2542
  (d.here
2400
2543
  ? connected
@@ -2627,33 +2770,6 @@ const PAGE = `<!doctype html>
2627
2770
  };
2628
2771
  }
2629
2772
 
2630
- const inviteForm = document.getElementById('invite');
2631
- if (inviteForm) {
2632
- inviteForm.onsubmit = async (event) => {
2633
- event.preventDefault();
2634
- const msg = document.getElementById('imsg');
2635
- msg.textContent = 'minting…';
2636
- const result = await post('/invite', {
2637
- channel: d.channel.ref,
2638
- name: document.getElementById('iname').value.trim() || undefined,
2639
- connection_type: document.getElementById('itype').value,
2640
- });
2641
- if (result.error) {
2642
- msg.textContent = result.error;
2643
- return;
2644
- }
2645
- // Shown once, and shown as the line they actually run. A code with no
2646
- // instruction next to it gets pasted into a config file, which is the
2647
- // slow path and leaves a credential in a file.
2648
- msg.innerHTML =
2649
- 'Send them this — single use' +
2650
- (result.expires_at ? ', expires ' + esc(new Date(result.expires_at).toLocaleString()) : '') +
2651
- ':<br><code>/agentsignal:join ' +
2652
- esc(result.code) +
2653
- '</code>';
2654
- };
2655
- }
2656
-
2657
2773
  const form = document.getElementById('connect');
2658
2774
  if (!form) return;
2659
2775
  form.onsubmit = async (event) => {
@@ -2731,6 +2847,29 @@ const PAGE = `<!doctype html>
2731
2847
  // the navigations they replaced. No push: this IS the pop.
2732
2848
  addEventListener('popstate', () => filterTo(agentFromPath(location.pathname), false));
2733
2849
 
2850
+ /*
2851
+ THE MACHINE IS A PAGE NOW, not a drawer in the rail.
2852
+
2853
+ It had grown to five things -- the onboarding guide, every identity this
2854
+ machine holds, who the channel reaches, connecting a project, and the limits
2855
+ -- inside a <details> in a 15rem column, under the channel list. A column
2856
+ that narrow turns a settings table into a word per line, and a drawer that
2857
+ long is one somebody opens, scrolls, and closes without reading.
2858
+
2859
+ Same shell either way: the rail still lists channels and the right-hand
2860
+ column still says who is working, because leaving the machine's page is one
2861
+ click on a channel and both of those are how you do it.
2862
+ */
2863
+ if (location.pathname === '/settings') {
2864
+ document.getElementById('settingsbody').hidden = false;
2865
+ for (const id of ['pending', 'log', 'compose']) {
2866
+ const el = document.getElementById(id);
2867
+ if (el) el.hidden = true;
2868
+ }
2869
+ document.getElementById('machine-link')?.classList.add('on');
2870
+ document.title = 'AgentSignal — this machine';
2871
+ }
2872
+
2734
2873
  roster(activeRef(), true);
2735
2874
  setup();
2736
2875
  pending();
@@ -3063,7 +3202,19 @@ const server = createServer(async (req, res) => {
3063
3202
  if (url.pathname === '/onboarding' && req.method === 'GET') {
3064
3203
  const here = repoRoot(process.cwd());
3065
3204
  const mine = identitiesHere(baseUrl);
3066
- const roster = await upstream('/v1/agents');
3205
+ /*
3206
+ SCOPED, for the same reason /setup is. Counts rather than names, but they
3207
+ are still the other company's counts -- "3 reachable" about people this
3208
+ dashboard is not for, on the page that claims to describe this machine's
3209
+ setup. A checklist that reports itself from real state has to read the
3210
+ right state.
3211
+ */
3212
+ const onboardingOn =
3213
+ boundTo || companiesKnown().length <= 1 ? channelFor(url.searchParams.get('channel')) : null;
3214
+ const roster =
3215
+ onboardingOn && inScope(onboardingOn)
3216
+ ? await upstream('/v1/agents', onboardingOn.key)
3217
+ : { error: 'unscoped' };
3067
3218
  const others = roster.error
3068
3219
  ? []
3069
3220
  : (roster.recipients ?? []).filter((r) => r.key !== (self && self.key));
@@ -3266,7 +3417,36 @@ const server = createServer(async (req, res) => {
3266
3417
  }
3267
3418
 
3268
3419
  if (url.pathname === '/setup') {
3269
- const roster = await upstream('/v1/agents');
3420
+ /*
3421
+ SCOPED LIKE EVERYTHING ELSE, because it was not, and that was a hole.
3422
+
3423
+ This read `upstream('/v1/agents')` with no key, which defaults to
3424
+ `apiKey` -- and apiKey is `channels[0].key`, the FIRST key this machine
3425
+ happened to find. Not the bound company's. On a machine holding keys to
3426
+ two, a dashboard bound to one showed the other's roster: names, and the
3427
+ email addresses of its people, under the heading "Who this channel
3428
+ reaches". Reported from a real machine, where logging in to one company
3429
+ listed the members of the other.
3430
+
3431
+ Disclosure was the visible half. The worse half is that `channel` came
3432
+ back from the same call, and the invite form posts `d.channel.ref` -- so
3433
+ "Bring somebody in", on a dashboard scoped to one company, minted a join
3434
+ code for the OTHER company's channel. That is not showing the wrong
3435
+ thing, it is handing out access to it.
3436
+
3437
+ The rest of this file already had the answer: bind first, read nothing
3438
+ while the question is open, and ask the bound channel's own key. Those
3439
+ three lines are all that was missing here.
3440
+ */
3441
+ const known = companiesKnown();
3442
+ if (!boundTo && known.length === 1) boundTo = known[0].account;
3443
+
3444
+ // NOTHING IS READ WHILE THE QUESTION IS OPEN -- the same rule /messages
3445
+ // keeps, and for the same reason: reading on is showing one company's
3446
+ // people behind a question about which company this is.
3447
+ const on = boundTo || known.length <= 1 ? channelFor(url.searchParams.get('channel')) : null;
3448
+
3449
+ const roster = on && inScope(on) ? await upstream('/v1/agents', on.key) : { error: 'unscoped' };
3270
3450
  const inChannel = new Set(
3271
3451
  roster.error ? [] : (roster.recipients ?? []).map((r) => r.key),
3272
3452
  );
@@ -3947,8 +4127,8 @@ const server = createServer(async (req, res) => {
3947
4127
  error:
3948
4128
  `That channel belongs to ${on.company ?? 'another company'}, and this dashboard is ` +
3949
4129
  `for ${nameOf(boundTo) ?? 'one company'}. Open it in its own dashboard: ` +
3950
- 'stop this one and start another with that company\'s key, or run a second on ' +
3951
- 'another port with PORT.',
4130
+ 'stop this one and start another with that company\'s key, or run a second ' +
4131
+ 'alongside it — it moves to a free port by itself.',
3952
4132
  channels: channels.map((c) => ({
3953
4133
  ref: c.ref,
3954
4134
  name: c.name ?? c.via,
@@ -4166,7 +4346,7 @@ const server = createServer(async (req, res) => {
4166
4346
  // /a/<recipient key or handle> -- one agent's conversation. The whole point
4167
4347
  // of a path rather than a port: several agents run at once, and a port each
4168
4348
  // means a port to remember each and a dashboard to start each.
4169
- if (url.pathname === '/' || url.pathname.startsWith('/a/')) {
4349
+ if (url.pathname === '/' || url.pathname === '/settings' || url.pathname.startsWith('/a/')) {
4170
4350
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', ...grant });
4171
4351
  res.end(PAGE);
4172
4352
  return;
@@ -4230,6 +4410,46 @@ async function nameChannels() {
4230
4410
  );
4231
4411
  }
4232
4412
 
4413
+ /**
4414
+ * THE RUNNING DASHBOARD ON A PORT, read off the lock this build already keeps.
4415
+ *
4416
+ * The link is printed once, on stderr, and when an agent starts this in the
4417
+ * background that line lands in a tool result nobody ever reads again. The
4418
+ * dashboard is then running, healthy, and unreachable: the address alone gets
4419
+ * the guard's flat "Not found.", and the token that would open it exists only
4420
+ * inside a process. Recovering one meant finding the pid, listing its open file
4421
+ * descriptors, and hoping somebody had pointed stderr at a file. That is not a
4422
+ * recovery procedure, it is an archaeology dig.
4423
+ *
4424
+ * So the URL goes into the lock metadata, which already exists, already names
4425
+ * the pid, and is already written 0600 in this user's own state directory. A
4426
+ * SECOND file keyed on the same port would have been the same fact in two
4427
+ * places, disagreeing the first time one of them was missed.
4428
+ *
4429
+ * Writing the token down at all is a trade, and it is paid for in two ways:
4430
+ * nobody new can read it -- 0600, in this user's own directory rather than
4431
+ * /tmp, and the same user already holds the API KEY this token merely fronts --
4432
+ * and closing the dashboard still revokes it, because dropLock() takes the file
4433
+ * with the process.
4434
+ */
4435
+ function linkOn(p) {
4436
+ try {
4437
+ const meta = JSON.parse(readFileSync(metaPathFor(p), 'utf8'));
4438
+ if (!meta?.url || !Number.isInteger(meta.pid)) return null;
4439
+ // A file outliving its process names a port nothing answers on. Sending
4440
+ // somebody to that link is worse than admitting the link is lost: they get
4441
+ // a refused connection and no idea whether they typed it wrong.
4442
+ try {
4443
+ process.kill(meta.pid, 0);
4444
+ } catch {
4445
+ return null;
4446
+ }
4447
+ return meta;
4448
+ } catch {
4449
+ return null;
4450
+ }
4451
+ }
4452
+
4233
4453
  /**
4234
4454
  * A PORT ALREADY IN USE IS ALMOST ALWAYS THIS SAME PROGRAM.
4235
4455
  *
@@ -4241,19 +4461,75 @@ async function nameChannels() {
4241
4461
  * one printed. That is the same shape as the 404 this page-and-note work has
4242
4462
  * been about: a healthy system presenting as a broken one.
4243
4463
  *
4244
- * Nothing is retried and no other port is chosen. Silently landing on 8900
4245
- * would print a link nobody expects and leave two dashboards running, which is
4246
- * how you end up reading a stale one and wondering why it never updates.
4464
+ * This used to refuse and stop there, on the grounds that silently landing on
4465
+ * 8900 prints a link nobody expects and leaves two dashboards running. The
4466
+ * objection was right about silence and wrong about stopping. Two dashboards is
4467
+ * the SUPPORTED way to watch two companies -- binding is per process and /bind
4468
+ * refuses to switch -- so the thing people actually need is the second one, and
4469
+ * making them re-run the command with a port they had to pick themselves was an
4470
+ * obstacle rather than a safeguard.
4471
+ *
4472
+ * So it moves up a port, and pays off the silence instead: it says the default
4473
+ * was taken, hands over the RUNNING dashboard's link if that one wrote it down,
4474
+ * and says which port this one ended up on and that both are now up. Nobody
4475
+ * reads a stale dashboard wondering why it never updates, because the line
4476
+ * above the link tells them there is another one.
4477
+ *
4478
+ * A port typed as `--port` is different, and still refuses. See portInsisted.
4247
4479
  */
4480
+ const PORT_ATTEMPTS = 10;
4481
+ let attempt = 0;
4482
+
4483
+ /** Whatever can be said about the dashboard already holding a port. */
4484
+ function sayWhoHasIt(p) {
4485
+ const already = linkOn(p);
4486
+ if (already) {
4487
+ console.error(`A dashboard is already running there (pid ${already.pid}):`);
4488
+ console.error(` ${already.url}`);
4489
+ console.error('That is the link to hand over for that one — it carries its token.');
4490
+ } else {
4491
+ /*
4492
+ NOT "a dashboard is already running". Anything reaching here held the port
4493
+ without leaving a lock, and a dashboard that left one was settled long
4494
+ before listen() was called -- superseded or stood down to. So what is
4495
+ actually there is another program, or a dashboard old enough to predate
4496
+ the lock, and claiming to know which would be inventing it.
4497
+ */
4498
+ console.error('Whatever holds it left no link — another program, or a dashboard');
4499
+ console.error('from before this build. Find the link it printed, if it was one.');
4500
+ }
4501
+ }
4502
+
4248
4503
  server.on('error', (error) => {
4249
4504
  if (error.code === 'EADDRINUSE') {
4250
- console.error(`Port ${port} is already in use, so this did not start.`);
4251
- console.error('That is usually a dashboard already running — find the link it');
4252
- console.error('printed when it started, or stop it and start this again.');
4253
- console.error(`To run a second one alongside it, set PORT: PORT=${port + 1} …`);
4505
+ const taken = port + attempt;
4506
+
4507
+ if (portInsisted) {
4508
+ console.error(`Port ${taken} is already in use, so this did not start.`);
4509
+ sayWhoHasIt(taken);
4510
+ console.error('You named that port with --port, so no other one was tried.');
4511
+ console.error('Drop the flag to let it find a free port by itself.');
4512
+ process.exit(1);
4513
+ }
4514
+
4515
+ // Once, about the default. Nine more lines about 8900, 8901 and 8902 being
4516
+ // busy tell the reader nothing they can act on.
4517
+ if (attempt === 0) {
4518
+ console.error(`Port ${port} is already in use.`);
4519
+ sayWhoHasIt(taken);
4520
+ }
4521
+
4522
+ attempt += 1;
4523
+ if (attempt < PORT_ATTEMPTS) {
4524
+ server.listen(port + attempt, '127.0.0.1');
4525
+ return;
4526
+ }
4527
+
4528
+ console.error(`Ports ${port}–${port + attempt - 1} are all in use, so this did not start.`);
4529
+ console.error('Stop some of them, or name a free one with --port.');
4254
4530
  } else if (error.code === 'EACCES') {
4255
4531
  console.error(`Not allowed to listen on port ${port}. Ports below 1024 need root;`);
4256
- console.error('pick a higher one with PORT.');
4532
+ console.error('pick a higher one with --port.');
4257
4533
  } else {
4258
4534
  console.error(`Could not listen on port ${port}: ${error.message}`);
4259
4535
  }
@@ -4282,8 +4558,16 @@ async function settlePort() {
4282
4558
  it is right HERE, where the running build is not stale.
4283
4559
  */
4284
4560
  console.error(`Port ${port} is already served by a dashboard of the same build or newer (pid ${running.pid}).`);
4285
- console.error('Nothing to update, so it has been left alone — find the link it printed');
4286
- console.error(`when it started, or stop it first. To run another alongside it: PORT=${port + 1} …`);
4561
+ console.error('Nothing to update, so it has been left alone.');
4562
+ // The link rather than instructions for finding it. "Find the link it
4563
+ // printed" is the advice this whole file has been unpicking: it is printed
4564
+ // once, into a tool result nobody reads again.
4565
+ if (running.url) {
4566
+ console.error(`Its link: ${running.url}`);
4567
+ } else {
4568
+ console.error('Find the link it printed when it started, or stop it first.');
4569
+ }
4570
+ console.error(`To run another alongside it for a second company: --port ${port + 1}`);
4287
4571
  process.exit(0);
4288
4572
  }
4289
4573
 
@@ -4316,17 +4600,35 @@ async function settlePort() {
4316
4600
  * first port's lock had disappeared while its process was still answering.
4317
4601
  */
4318
4602
  let holdsLock = false;
4603
+ let holdsMeta = false;
4319
4604
 
4320
4605
  /** Written after the bind, so the file never names a process that failed to start. */
4321
- function takeLock() {
4322
- if (!lockPath) return;
4606
+ function takeLock(url) {
4323
4607
  try {
4324
4608
  mkdirSync(lockRoot, { recursive: true });
4325
4609
  writeFileSync(
4326
- lockMetaPath,
4327
- JSON.stringify({ pid: process.pid, script: fileURLToPath(import.meta.url), mtime: buildTime(), port: bound }),
4610
+ metaPathFor(bound),
4611
+ JSON.stringify({
4612
+ pid: process.pid,
4613
+ script: fileURLToPath(import.meta.url),
4614
+ mtime: buildTime(),
4615
+ port: bound,
4616
+ // The link, so the next session can recover it without digging through
4617
+ // this process. See linkOn().
4618
+ url,
4619
+ }),
4328
4620
  { mode: 0o600 },
4329
4621
  );
4622
+ holdsMeta = true;
4623
+ /*
4624
+ THE PID FILE IS THE LOCK, and PORT=0 still takes none of it. Recording
4625
+ where this dashboard is and claiming a port against other builds are two
4626
+ different things: the first is safe for everybody, and the second is what
4627
+ "any free port" opted out of. Writing the metadata for a PORT=0 run makes
4628
+ its link recoverable; writing the pidfile would make it superseder-bait
4629
+ on a port it was handed at random.
4630
+ */
4631
+ if (!lockPath) return;
4330
4632
  writeFileSync(lockPath, String(process.pid), { mode: 0o600 });
4331
4633
  holdsLock = true;
4332
4634
  } catch {
@@ -4341,10 +4643,19 @@ function takeLock() {
4341
4643
  * whether the pid is alive rather than trusting the file.
4342
4644
  */
4343
4645
  function dropLock() {
4344
- if (!lockPath || !holdsLock) return;
4345
- for (const path of [lockPath, lockMetaPath]) {
4646
+ // Separately guarded: a PORT=0 run writes metadata and no pidfile, so one
4647
+ // flag cannot answer for both. Standing down writes neither, which is what
4648
+ // keeps a superseded start from deleting the survivor's files.
4649
+ if (holdsMeta) {
4346
4650
  try {
4347
- unlinkSync(path);
4651
+ unlinkSync(metaPathFor(bound));
4652
+ } catch {
4653
+ /* already gone */
4654
+ }
4655
+ }
4656
+ if (lockPath && holdsLock) {
4657
+ try {
4658
+ unlinkSync(lockPath);
4348
4659
  } catch {
4349
4660
  /* already gone */
4350
4661
  }
@@ -4358,21 +4669,47 @@ for (const signal of ['SIGINT', 'SIGTERM']) {
4358
4669
  });
4359
4670
  }
4360
4671
 
4672
+ /*
4673
+ SUPERSEDING HAPPENS FIRST, and the walk-up only ever sees what is left.
4674
+
4675
+ The two answers to a busy port look alike and are not. A port held by a
4676
+ dashboard that left a lock is settled above -- taken from an older build,
4677
+ stood down to a newer one -- and neither outcome reaches listen() on a port
4678
+ somebody else holds. What reaches the handler below is a port held by
4679
+ something that took no lock: another program, or a dashboard old enough to
4680
+ predate locks. Nothing can be superseded there, because there is nothing
4681
+ saying what it is, so moving up a port is the best answer available.
4682
+
4683
+ Ordered this way round, an update never walks up. It takes the port it came
4684
+ for, which is the whole point of taking it.
4685
+ */
4361
4686
  await settlePort();
4362
4687
 
4363
- server.listen(port, '127.0.0.1', () => {
4688
+ // A listener rather than a listen() callback, because listen() is called again
4689
+ // on each retry and its callback is a one-shot 'listening' handler -- so the
4690
+ // second attempt would have bound the port and printed nothing at all.
4691
+ server.on('listening', () => {
4364
4692
  // The port the OS actually gave us, not the one asked for. They differ
4365
4693
  // whenever PORT is 0 -- which is how anything automated starts a server
4366
4694
  // without picking a number and hoping -- and printing the request rather
4367
4695
  // than the result hands out a link to port 0, which connects to nothing.
4368
4696
  bound = server.address()?.port ?? port;
4369
- takeLock();
4370
- console.error(`Watching ${baseUrl} on http://127.0.0.1:${bound}/?t=${token}`);
4697
+ const url = `http://127.0.0.1:${bound}/?t=${token}`;
4698
+
4699
+ takeLock(url);
4700
+
4701
+ if (attempt > 0) {
4702
+ console.error(`Started this one on ${bound} instead. Both are now running.`);
4703
+ }
4704
+ console.error(`Watching ${baseUrl} on ${url}`);
4371
4705
  console.error('Loopback only, and the link carries a one-run token: it can now send and answer.');
4372
4706
  console.error('The key stays in this process; the page only ever talks to this server.');
4707
+ console.error(`The link is also in ${metaPathFor(bound)} until this stops.`);
4373
4708
  // After the link is printed, not before: the dashboard should be usable the
4374
4709
  // moment it says it is, and the names arrive a beat later.
4375
4710
  nameChannels().catch(() => {
4376
4711
  /* the rail falls back to refs, which is a label and not a failure */
4377
4712
  });
4378
4713
  });
4714
+
4715
+ server.listen(port, '127.0.0.1');