@agentsignalnet/claude-plugin 0.2.78 → 0.2.79

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.79",
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.56"],
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.79",
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();
@@ -3947,8 +4086,8 @@ const server = createServer(async (req, res) => {
3947
4086
  error:
3948
4087
  `That channel belongs to ${on.company ?? 'another company'}, and this dashboard is ` +
3949
4088
  `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.',
4089
+ 'stop this one and start another with that company\'s key, or run a second ' +
4090
+ 'alongside it — it moves to a free port by itself.',
3952
4091
  channels: channels.map((c) => ({
3953
4092
  ref: c.ref,
3954
4093
  name: c.name ?? c.via,
@@ -4166,7 +4305,7 @@ const server = createServer(async (req, res) => {
4166
4305
  // /a/<recipient key or handle> -- one agent's conversation. The whole point
4167
4306
  // of a path rather than a port: several agents run at once, and a port each
4168
4307
  // means a port to remember each and a dashboard to start each.
4169
- if (url.pathname === '/' || url.pathname.startsWith('/a/')) {
4308
+ if (url.pathname === '/' || url.pathname === '/settings' || url.pathname.startsWith('/a/')) {
4170
4309
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', ...grant });
4171
4310
  res.end(PAGE);
4172
4311
  return;
@@ -4230,6 +4369,46 @@ async function nameChannels() {
4230
4369
  );
4231
4370
  }
4232
4371
 
4372
+ /**
4373
+ * THE RUNNING DASHBOARD ON A PORT, read off the lock this build already keeps.
4374
+ *
4375
+ * The link is printed once, on stderr, and when an agent starts this in the
4376
+ * background that line lands in a tool result nobody ever reads again. The
4377
+ * dashboard is then running, healthy, and unreachable: the address alone gets
4378
+ * the guard's flat "Not found.", and the token that would open it exists only
4379
+ * inside a process. Recovering one meant finding the pid, listing its open file
4380
+ * descriptors, and hoping somebody had pointed stderr at a file. That is not a
4381
+ * recovery procedure, it is an archaeology dig.
4382
+ *
4383
+ * So the URL goes into the lock metadata, which already exists, already names
4384
+ * the pid, and is already written 0600 in this user's own state directory. A
4385
+ * SECOND file keyed on the same port would have been the same fact in two
4386
+ * places, disagreeing the first time one of them was missed.
4387
+ *
4388
+ * Writing the token down at all is a trade, and it is paid for in two ways:
4389
+ * nobody new can read it -- 0600, in this user's own directory rather than
4390
+ * /tmp, and the same user already holds the API KEY this token merely fronts --
4391
+ * and closing the dashboard still revokes it, because dropLock() takes the file
4392
+ * with the process.
4393
+ */
4394
+ function linkOn(p) {
4395
+ try {
4396
+ const meta = JSON.parse(readFileSync(metaPathFor(p), 'utf8'));
4397
+ if (!meta?.url || !Number.isInteger(meta.pid)) return null;
4398
+ // A file outliving its process names a port nothing answers on. Sending
4399
+ // somebody to that link is worse than admitting the link is lost: they get
4400
+ // a refused connection and no idea whether they typed it wrong.
4401
+ try {
4402
+ process.kill(meta.pid, 0);
4403
+ } catch {
4404
+ return null;
4405
+ }
4406
+ return meta;
4407
+ } catch {
4408
+ return null;
4409
+ }
4410
+ }
4411
+
4233
4412
  /**
4234
4413
  * A PORT ALREADY IN USE IS ALMOST ALWAYS THIS SAME PROGRAM.
4235
4414
  *
@@ -4241,19 +4420,75 @@ async function nameChannels() {
4241
4420
  * one printed. That is the same shape as the 404 this page-and-note work has
4242
4421
  * been about: a healthy system presenting as a broken one.
4243
4422
  *
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.
4423
+ * This used to refuse and stop there, on the grounds that silently landing on
4424
+ * 8900 prints a link nobody expects and leaves two dashboards running. The
4425
+ * objection was right about silence and wrong about stopping. Two dashboards is
4426
+ * the SUPPORTED way to watch two companies -- binding is per process and /bind
4427
+ * refuses to switch -- so the thing people actually need is the second one, and
4428
+ * making them re-run the command with a port they had to pick themselves was an
4429
+ * obstacle rather than a safeguard.
4430
+ *
4431
+ * So it moves up a port, and pays off the silence instead: it says the default
4432
+ * was taken, hands over the RUNNING dashboard's link if that one wrote it down,
4433
+ * and says which port this one ended up on and that both are now up. Nobody
4434
+ * reads a stale dashboard wondering why it never updates, because the line
4435
+ * above the link tells them there is another one.
4436
+ *
4437
+ * A port typed as `--port` is different, and still refuses. See portInsisted.
4247
4438
  */
4439
+ const PORT_ATTEMPTS = 10;
4440
+ let attempt = 0;
4441
+
4442
+ /** Whatever can be said about the dashboard already holding a port. */
4443
+ function sayWhoHasIt(p) {
4444
+ const already = linkOn(p);
4445
+ if (already) {
4446
+ console.error(`A dashboard is already running there (pid ${already.pid}):`);
4447
+ console.error(` ${already.url}`);
4448
+ console.error('That is the link to hand over for that one — it carries its token.');
4449
+ } else {
4450
+ /*
4451
+ NOT "a dashboard is already running". Anything reaching here held the port
4452
+ without leaving a lock, and a dashboard that left one was settled long
4453
+ before listen() was called -- superseded or stood down to. So what is
4454
+ actually there is another program, or a dashboard old enough to predate
4455
+ the lock, and claiming to know which would be inventing it.
4456
+ */
4457
+ console.error('Whatever holds it left no link — another program, or a dashboard');
4458
+ console.error('from before this build. Find the link it printed, if it was one.');
4459
+ }
4460
+ }
4461
+
4248
4462
  server.on('error', (error) => {
4249
4463
  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} …`);
4464
+ const taken = port + attempt;
4465
+
4466
+ if (portInsisted) {
4467
+ console.error(`Port ${taken} is already in use, so this did not start.`);
4468
+ sayWhoHasIt(taken);
4469
+ console.error('You named that port with --port, so no other one was tried.');
4470
+ console.error('Drop the flag to let it find a free port by itself.');
4471
+ process.exit(1);
4472
+ }
4473
+
4474
+ // Once, about the default. Nine more lines about 8900, 8901 and 8902 being
4475
+ // busy tell the reader nothing they can act on.
4476
+ if (attempt === 0) {
4477
+ console.error(`Port ${port} is already in use.`);
4478
+ sayWhoHasIt(taken);
4479
+ }
4480
+
4481
+ attempt += 1;
4482
+ if (attempt < PORT_ATTEMPTS) {
4483
+ server.listen(port + attempt, '127.0.0.1');
4484
+ return;
4485
+ }
4486
+
4487
+ console.error(`Ports ${port}–${port + attempt - 1} are all in use, so this did not start.`);
4488
+ console.error('Stop some of them, or name a free one with --port.');
4254
4489
  } else if (error.code === 'EACCES') {
4255
4490
  console.error(`Not allowed to listen on port ${port}. Ports below 1024 need root;`);
4256
- console.error('pick a higher one with PORT.');
4491
+ console.error('pick a higher one with --port.');
4257
4492
  } else {
4258
4493
  console.error(`Could not listen on port ${port}: ${error.message}`);
4259
4494
  }
@@ -4282,8 +4517,16 @@ async function settlePort() {
4282
4517
  it is right HERE, where the running build is not stale.
4283
4518
  */
4284
4519
  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} …`);
4520
+ console.error('Nothing to update, so it has been left alone.');
4521
+ // The link rather than instructions for finding it. "Find the link it
4522
+ // printed" is the advice this whole file has been unpicking: it is printed
4523
+ // once, into a tool result nobody reads again.
4524
+ if (running.url) {
4525
+ console.error(`Its link: ${running.url}`);
4526
+ } else {
4527
+ console.error('Find the link it printed when it started, or stop it first.');
4528
+ }
4529
+ console.error(`To run another alongside it for a second company: --port ${port + 1}`);
4287
4530
  process.exit(0);
4288
4531
  }
4289
4532
 
@@ -4316,17 +4559,35 @@ async function settlePort() {
4316
4559
  * first port's lock had disappeared while its process was still answering.
4317
4560
  */
4318
4561
  let holdsLock = false;
4562
+ let holdsMeta = false;
4319
4563
 
4320
4564
  /** Written after the bind, so the file never names a process that failed to start. */
4321
- function takeLock() {
4322
- if (!lockPath) return;
4565
+ function takeLock(url) {
4323
4566
  try {
4324
4567
  mkdirSync(lockRoot, { recursive: true });
4325
4568
  writeFileSync(
4326
- lockMetaPath,
4327
- JSON.stringify({ pid: process.pid, script: fileURLToPath(import.meta.url), mtime: buildTime(), port: bound }),
4569
+ metaPathFor(bound),
4570
+ JSON.stringify({
4571
+ pid: process.pid,
4572
+ script: fileURLToPath(import.meta.url),
4573
+ mtime: buildTime(),
4574
+ port: bound,
4575
+ // The link, so the next session can recover it without digging through
4576
+ // this process. See linkOn().
4577
+ url,
4578
+ }),
4328
4579
  { mode: 0o600 },
4329
4580
  );
4581
+ holdsMeta = true;
4582
+ /*
4583
+ THE PID FILE IS THE LOCK, and PORT=0 still takes none of it. Recording
4584
+ where this dashboard is and claiming a port against other builds are two
4585
+ different things: the first is safe for everybody, and the second is what
4586
+ "any free port" opted out of. Writing the metadata for a PORT=0 run makes
4587
+ its link recoverable; writing the pidfile would make it superseder-bait
4588
+ on a port it was handed at random.
4589
+ */
4590
+ if (!lockPath) return;
4330
4591
  writeFileSync(lockPath, String(process.pid), { mode: 0o600 });
4331
4592
  holdsLock = true;
4332
4593
  } catch {
@@ -4341,10 +4602,19 @@ function takeLock() {
4341
4602
  * whether the pid is alive rather than trusting the file.
4342
4603
  */
4343
4604
  function dropLock() {
4344
- if (!lockPath || !holdsLock) return;
4345
- for (const path of [lockPath, lockMetaPath]) {
4605
+ // Separately guarded: a PORT=0 run writes metadata and no pidfile, so one
4606
+ // flag cannot answer for both. Standing down writes neither, which is what
4607
+ // keeps a superseded start from deleting the survivor's files.
4608
+ if (holdsMeta) {
4609
+ try {
4610
+ unlinkSync(metaPathFor(bound));
4611
+ } catch {
4612
+ /* already gone */
4613
+ }
4614
+ }
4615
+ if (lockPath && holdsLock) {
4346
4616
  try {
4347
- unlinkSync(path);
4617
+ unlinkSync(lockPath);
4348
4618
  } catch {
4349
4619
  /* already gone */
4350
4620
  }
@@ -4358,21 +4628,47 @@ for (const signal of ['SIGINT', 'SIGTERM']) {
4358
4628
  });
4359
4629
  }
4360
4630
 
4631
+ /*
4632
+ SUPERSEDING HAPPENS FIRST, and the walk-up only ever sees what is left.
4633
+
4634
+ The two answers to a busy port look alike and are not. A port held by a
4635
+ dashboard that left a lock is settled above -- taken from an older build,
4636
+ stood down to a newer one -- and neither outcome reaches listen() on a port
4637
+ somebody else holds. What reaches the handler below is a port held by
4638
+ something that took no lock: another program, or a dashboard old enough to
4639
+ predate locks. Nothing can be superseded there, because there is nothing
4640
+ saying what it is, so moving up a port is the best answer available.
4641
+
4642
+ Ordered this way round, an update never walks up. It takes the port it came
4643
+ for, which is the whole point of taking it.
4644
+ */
4361
4645
  await settlePort();
4362
4646
 
4363
- server.listen(port, '127.0.0.1', () => {
4647
+ // A listener rather than a listen() callback, because listen() is called again
4648
+ // on each retry and its callback is a one-shot 'listening' handler -- so the
4649
+ // second attempt would have bound the port and printed nothing at all.
4650
+ server.on('listening', () => {
4364
4651
  // The port the OS actually gave us, not the one asked for. They differ
4365
4652
  // whenever PORT is 0 -- which is how anything automated starts a server
4366
4653
  // without picking a number and hoping -- and printing the request rather
4367
4654
  // than the result hands out a link to port 0, which connects to nothing.
4368
4655
  bound = server.address()?.port ?? port;
4369
- takeLock();
4370
- console.error(`Watching ${baseUrl} on http://127.0.0.1:${bound}/?t=${token}`);
4656
+ const url = `http://127.0.0.1:${bound}/?t=${token}`;
4657
+
4658
+ takeLock(url);
4659
+
4660
+ if (attempt > 0) {
4661
+ console.error(`Started this one on ${bound} instead. Both are now running.`);
4662
+ }
4663
+ console.error(`Watching ${baseUrl} on ${url}`);
4371
4664
  console.error('Loopback only, and the link carries a one-run token: it can now send and answer.');
4372
4665
  console.error('The key stays in this process; the page only ever talks to this server.');
4666
+ console.error(`The link is also in ${metaPathFor(bound)} until this stops.`);
4373
4667
  // After the link is printed, not before: the dashboard should be usable the
4374
4668
  // moment it says it is, and the names arrive a beat later.
4375
4669
  nameChannels().catch(() => {
4376
4670
  /* the rail falls back to refs, which is a label and not a failure */
4377
4671
  });
4378
4672
  });
4673
+
4674
+ server.listen(port, '127.0.0.1');