clavarium 0.2.212-beta.1 → 0.2.213-beta.1

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.
@@ -57,7 +57,10 @@ fi
57
57
  # here: not signed in (at its start, or signed out on the way: « Login expired », 15-11), its sign-in started by itself, its link sent to the person's chat, the code they paste
58
58
  # there typed back (02-11, tried on a real Claude Code); an update installed told to the agent, which restarts
59
59
  # when it suits it (never in the middle of its work). A tool that changes its words: only these lines change.
60
+ # Since 15-11 (#362) its sign-in rules are those of config/tools.json ("signin.screen", --tool): the lines
61
+ # below are the fallback of an older server, and its notice. The link may go to another conversation (screen-watch.mjs).
60
62
  node "$(dirname "$0")/screen-watch.mjs" \
63
+ --tool claude-code \
61
64
  'type:(Not logged in|Login expired|OAuth token (has )?expired|Invalid API key)[^\n]{0,24}/login=/login' \
62
65
  'keys:Select login method:=Enter' \
63
66
  'link:https://(claude\.ai|claude\.com|console\.anthropic\.com)/\S*oauth\S*' \
@@ -29,6 +29,7 @@ node "$here/toml-block.mjs" .codex/config.toml tools "$block" \
29
29
  # WHAT ITS SCREEN ASKS, read by the generic screen-watch -- Codex's own words: its sign-in link (and the
30
30
  # code beside it) sent to the person's chat; an update told to the agent, which restarts when it suits it.
31
31
  node "$here/screen-watch.mjs" \
32
+ --tool codex \
32
33
  'link:https://auth\.openai\.com/\S+' \
33
34
  'link:https://chatgpt\.com/\S*auth\S*' \
34
35
  'notice:update available[^\n]{0,120}=Your tool has an update: when nothing runs, touch /work/.parley/restart-asked to take it up.' \
@@ -15,9 +15,25 @@
15
15
  * code:PATTERN the tool waits for a code the person gets after signing in: the next message they write
16
16
  * in the chat that looks like one (no space, 10 to 300 signs) is typed there, then Enter.
17
17
  * Only the last LINES lines are read: what the tool prints of its own work above never counts.
18
+ *
19
+ * THE RULES FROM THE TOOLS' CONFIGURATION (15-11, #362): `--tool ID` reads the rules of that tool from
20
+ * screen-rules.json beside this file (written by the server from config/tools.json, "signin.screen"); its
21
+ * link/keys/type/code rules then replace those its launcher gave, which stay as the fallback of a launcher
22
+ * or a server older than this. Its notice rules are its launcher's always.
23
+ *
24
+ * A SIGN-IN LINK HANDED TO ANOTHER CONVERSATION (15-11, #362). The link is not told in the chat at once: it is
25
+ * written in the chat folder (signin-ask.json) and the server says where it goes (signin-route.json):
26
+ * companion another conversation, with a browser already signed in, opens it; the person only clicks
27
+ * Authorize there. The code it reads is typed here by the server; nothing is told here.
28
+ * person the link told in the chat, as before (no companion, or it failed, or the person asked).
29
+ * done the server typed the code.
30
+ * No answer within HAND_MS (an older server): told to the person. The link is never written anywhere else.
18
31
  */
19
32
  import { spawnSync } from 'node:child_process';
20
- import { readFileSync, statSync } from 'node:fs';
33
+ import { randomUUID } from 'node:crypto';
34
+ import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
35
+ import { dirname, join } from 'node:path';
36
+ import { fileURLToPath } from 'node:url';
21
37
 
22
38
  const LINES = 12; const EVERY_MS = 3000;
23
39
  const KEYS = new Set(['Enter', 'Down', 'Up', 'Left', 'Right', 'Escape', 'Tab', 'y', 'n', '1', '2', '3']);
@@ -31,6 +47,18 @@ export function rulesOf(args) {
31
47
  try { return [{ kind: m[1], re: new RegExp(pattern, 'i'), value }]; } catch { return []; }
32
48
  });
33
49
  }
50
+ /* What the person pastes, or the companion gives back, that may be typed as a code: no space, 10 to 300 signs. */
51
+ export const CODE = /^[A-Za-z0-9_#.~+/=-]{10,300}$/;
52
+ export const RULES_FILE = 'screen-rules.json';
53
+ const SIGNIN_KINDS = new Set(['link', 'keys', 'type', 'code']);
54
+ /* The rules of this start: those of the tool's configuration when there are any (`file`: screen-rules.json
55
+ read, { toolId: [rule, ...] }), its launcher's notices kept; else all its launcher gave (15-11). */
56
+ export function rulesFor(args, file = null) {
57
+ const at = args.indexOf('--tool'); const tool = at >= 0 ? args[at + 1] : null;
58
+ const given = rulesOf(at >= 0 ? args.filter((_, i) => i !== at && i !== at + 1) : args);
59
+ const own = tool && file && typeof file === 'object' && Array.isArray(file[tool]) ? rulesOf(file[tool].filter((r) => typeof r === 'string')).filter((r) => SIGNIN_KINDS.has(r.kind)) : [];
60
+ return own.length ? [...own, ...given.filter((r) => r.kind === 'notice')] : given;
61
+ }
34
62
  /* -> what to do on this screen: [{ kind, match, value }], each once (seen: a Set kept between looks). */
35
63
  export function actionsOn(screen, rules, seen) {
36
64
  /* A long link the tool's screen broke over several lines (full lines, no space): put back in one. */
@@ -56,9 +84,43 @@ export function actionsOn(screen, rules, seen) {
56
84
  return out;
57
85
  }
58
86
 
87
+ /* Where a sign-in link goes, step by step (15-11, #362): what to do, as a list of effects the caller runs --
88
+ { do: 'ask', ask } (write signin-ask.json), 'tell-link' { a } (the link in the person's chat), 'arm' (the next
89
+ code the person pastes is typed), 'tell-paste' (say so). `route()`: signin-route.json as read, or null. */
90
+ export const HAND_MS = 20_000;
91
+ export class Relay {
92
+ #ask = null; #now; #id; #route; #chat;
93
+ constructor({ route = () => null, chat = () => true, now = () => Date.now(), id = () => randomUUID() } = {}) { this.#route = route; this.#chat = chat; this.#now = now; this.#id = id; }
94
+ /* Told to the person: the ask says so too (`told`), so that a server that reads it late hands it to nobody. */
95
+ #person() { const a = this.#ask; a.route = 'person'; return [{ do: 'ask', ask: { ...a.file, told: true } }, { do: 'tell-link', a: a.a }, ...(a.codeSeen ? [{ do: 'arm' }, { do: 'tell-paste' }] : [])]; }
96
+ link(a) {
97
+ /* No chat folder: nowhere to hand it over, nobody but the person (and the chat is off anyway). */
98
+ if (!this.#chat()) return [{ do: 'tell-link', a }];
99
+ const id = this.#id(); const at = this.#now();
100
+ this.#ask = { id, at, a, route: null, codeSeen: false, file: { id, at: new Date(at).toISOString(), link: a.match, around: a.around ?? '' } };
101
+ return [{ do: 'ask', ask: this.#ask.file }];
102
+ }
103
+ code() {
104
+ const a = this.#ask;
105
+ if (!a || a.route === 'person') return [{ do: 'arm' }, { do: 'tell-paste' }];
106
+ /* Handed over, or not known yet: the person is not asked to paste, unless it comes back to them. */
107
+ a.codeSeen = true; return [];
108
+ }
109
+ step() {
110
+ const a = this.#ask; if (!a || a.route === 'person') return [];
111
+ const r = this.#route(); const mine = r && r.id === a.id ? r.route : null;
112
+ if (mine === 'done') { this.#ask = null; return []; }
113
+ if (mine === 'person') return this.#person();
114
+ if (mine === 'companion') { a.route = 'companion'; return []; }
115
+ if (a.route === null && this.#now() - a.at > HAND_MS) return this.#person();
116
+ return [];
117
+ }
118
+ }
119
+
59
120
  const main = process.argv[1]?.endsWith('screen-watch.mjs');
60
121
  if (main) {
61
- const rules = rulesOf(process.argv.slice(2));
122
+ let file = null; try { file = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), RULES_FILE), 'utf8')); } catch { /* none: its launcher's rules */ }
123
+ const rules = rulesFor(process.argv.slice(2), file);
62
124
  const tmux = ['-L', process.env.SCREEN_WATCH_SOCKET ?? 'clavarium'];
63
125
  const pane = process.env.SCREEN_WATCH_PANE ?? '=main:';
64
126
  const chat = process.env.PARLEY_DIR ?? '/work/.parley';
@@ -73,23 +135,35 @@ if (main) {
73
135
  for (const line of text.split('\n').filter(Boolean)) {
74
136
  let m; try { m = JSON.parse(line); } catch { continue; }
75
137
  const code = String(m?.text ?? '').trim();
76
- if (/^[A-Za-z0-9_#.~+/=-]{10,300}$/.test(code)) {
138
+ if (CODE.test(code)) {
77
139
  spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, '-l', '--', code], { timeout: 5000 });
78
140
  spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, 'Enter'], { timeout: 5000 });
79
141
  awaiting = null; return;
80
142
  }
81
143
  }
82
144
  };
145
+ /* The sign-in link's way (Relay): asked in the chat folder, routed by the server. */
146
+ const readRoute = () => { try { return JSON.parse(readFileSync(`${chat}/signin-route.json`, 'utf8')); } catch { return null; } };
147
+ const relay = new Relay({ route: readRoute, chat: () => existsSync(chat) });
148
+ const run = (effects) => {
149
+ for (const e of effects) {
150
+ if (e.do === 'ask') { try { writeFileSync(`${chat}/.signin-ask.json.new`, JSON.stringify(e.ask)); renameSync(`${chat}/.signin-ask.json.new`, `${chat}/signin-ask.json`); } catch { /* not written: no answer comes, told to the person after HAND_MS */ } }
151
+ if (e.do === 'tell-link') spawnSync('parley', ['tell', `Your tool asks you to open this link: ${e.a.match}${e.a.around && e.a.around !== e.a.match ? `\n\n\`\`\`\n${e.a.around}\n\`\`\`` : ''}`, '--dir', chat], { timeout: 10_000 });
152
+ if (e.do === 'arm') awaiting = codeFrom();
153
+ if (e.do === 'tell-paste') spawnSync('parley', ['tell', 'Once signed in, paste here the code the page gives you.', '--dir', chat], { timeout: 10_000 });
154
+ }
155
+ };
83
156
  const look = () => {
84
157
  typeCode();
158
+ run(relay.step());
85
159
  const r = spawnSync('tmux', [...tmux, 'capture-pane', '-p', '-t', pane], { encoding: 'utf8', timeout: 5000 });
86
160
  if (r.status !== 0) return;
87
161
  for (const a of actionsOn(r.stdout, rules, seen)) {
88
- if (a.kind === 'link') spawnSync('parley', ['tell', `Your tool asks you to open this link: ${a.match}${a.around && a.around !== a.match ? `\n\n\`\`\`\n${a.around}\n\`\`\`` : ''}`, '--dir', chat], { timeout: 10_000 });
162
+ if (a.kind === 'link') run(relay.link(a));
89
163
  if (a.kind === 'notice') spawnSync('docket', ['remind', '--in', '1m', a.value, '--dir', process.env.DOCKET_DIR ?? '/work/.docket'], { timeout: 10_000 });
90
164
  if (a.kind === 'keys') for (const k of a.value) spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, k], { timeout: 5000 });
91
165
  if (a.kind === 'type') { spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, '-l', '--', a.value], { timeout: 5000 }); spawnSync('tmux', [...tmux, 'send-keys', '-t', pane, 'Enter'], { timeout: 5000 }); }
92
- if (a.kind === 'code') { awaiting = codeFrom(); spawnSync('parley', ['tell', 'Once signed in, paste here the code the page gives you.', '--dir', chat], { timeout: 10_000 }); }
166
+ if (a.kind === 'code') run(relay.code());
93
167
  }
94
168
  };
95
169
  /* Its life is the tool's: started just before the launcher becomes the tool (exec), it ends with it. */
@@ -34,6 +34,7 @@ node "$here/toml-block.mjs" .vibe/config.toml tools "$block" \
34
34
  # WHAT ITS SCREEN ASKS, read by the generic screen-watch -- Vibe's own words: an update told to the
35
35
  # agent, which restarts when it suits it.
36
36
  node "$here/screen-watch.mjs" \
37
+ --tool vibe \
37
38
  'notice:(new version|update) (is )?available[^\n]{0,120}=Your tool has an update: when nothing runs, touch /work/.parley/restart-asked to take it up.' \
38
39
  </dev/null >/dev/null 2>&1 &
39
40
  exec "$@"
package/config/tools.json CHANGED
@@ -72,6 +72,12 @@
72
72
  "claude.ai",
73
73
  "claude.com",
74
74
  "anthropic.com"
75
+ ],
76
+ "screen": [
77
+ "type:(Not logged in|Login expired|OAuth token (has )?expired|Invalid API key)[^\\n]{0,24}/login=/login",
78
+ "keys:Select login method:=Enter",
79
+ "link:https://(claude\\.ai|claude\\.com|console\\.anthropic\\.com)/\\S*oauth\\S*",
80
+ "code:Paste code here"
75
81
  ]
76
82
  }
77
83
  },
@@ -117,7 +123,24 @@
117
123
  "opencode-ai"
118
124
  ],
119
125
  "npm-writable"
120
- ]
126
+ ],
127
+ "signin": {
128
+ "senders": [
129
+ "anthropic.com",
130
+ "claude.com",
131
+ "claude.ai"
132
+ ],
133
+ "links": [
134
+ "claude.ai",
135
+ "claude.com",
136
+ "anthropic.com"
137
+ ],
138
+ "note": "15-11: screen rules from its Anthropic sign-in plugin (opencode-anthropic-auth 0.0.13: the link, then \"Paste the authorization code here\"); not tried on a real OpenCode screen; OpenCode has no launcher yet, so nothing reads them.",
139
+ "screen": [
140
+ "link:https://(claude\\.ai|console\\.anthropic\\.com)/oauth/authorize\\S*",
141
+ "code:Paste the authorization code here"
142
+ ]
143
+ }
121
144
  },
122
145
  {
123
146
  "id": "guichet",
@@ -210,7 +233,21 @@
210
233
  ],
211
234
  "npm-writable"
212
235
  ],
213
- "launch": "codex.sh"
236
+ "launch": "codex.sh",
237
+ "signin": {
238
+ "senders": [
239
+ "openai.com"
240
+ ],
241
+ "links": [
242
+ "openai.com",
243
+ "chatgpt.com"
244
+ ],
245
+ "note": "15-11: the links codex.sh watched (02-11); a device sign-in shows a one-time code beside its link, handed over with it.",
246
+ "screen": [
247
+ "link:https://auth\\.openai\\.com/\\S+",
248
+ "link:https://chatgpt\\.com/\\S*auth\\S*"
249
+ ]
250
+ }
214
251
  },
215
252
  {
216
253
  "id": "vibe",
@@ -271,7 +308,19 @@
271
308
  "/opt/vibe/bin/vibe",
272
309
  "/usr/local/bin/vibe"
273
310
  ]
274
- ]
311
+ ],
312
+ "signin": {
313
+ "senders": [
314
+ "mistral.ai"
315
+ ],
316
+ "links": [
317
+ "mistral.ai"
318
+ ],
319
+ "note": "15-11: screen rule from mistral-vibe 3.1.2 (browser sign-in at console.mistral.ai, which it then polls: no code to type); its own words on the screen not tried.",
320
+ "screen": [
321
+ "link:https://(console|auth)\\.mistral\\.ai/\\S+"
322
+ ]
323
+ }
275
324
  },
276
325
  {
277
326
  "id": "gemini",
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.212-beta.1",
3
+ "version": "0.2.213-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.212-beta.1",
9
+ "version": "0.2.213-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
13
13
  "@xterm/xterm": "^6.0.0",
14
- "clavarium-binder": "0.1.62-next.1",
14
+ "clavarium-binder": "0.1.63-next.1",
15
15
  "clavarium-docket": "0.1.2-next.2",
16
- "clavarium-parley": "0.17.94-next.1",
16
+ "clavarium-parley": "0.17.95-next.1",
17
17
  "clavarium-tether": "0.1.0-next.67",
18
18
  "mammoth": "1.13.0",
19
19
  "mermaid": "11.17.2",
@@ -761,9 +761,9 @@
761
761
  }
762
762
  },
763
763
  "node_modules/clavarium-binder": {
764
- "version": "0.1.62-next.1",
765
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.62-next.1.tgz",
766
- "integrity": "sha512-YhBt+k29zbASU931T5kPAnsZwo5JVgGw94HRs4UoKL2WHK4WVvmn54RCzTBSnHCWuvo4Lc27eLcxl0rNb+6Yug==",
764
+ "version": "0.1.63-next.1",
765
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.63-next.1.tgz",
766
+ "integrity": "sha512-+zk4f8JRnF7D3z2g17QkeoUIlBYooQZ5arSDsMNF4MtmyBeLQ429ou97bMb2zslCwCwxv9QgrbIbUQF8AnsSzg==",
767
767
  "license": "MIT",
768
768
  "bin": {
769
769
  "binder": "bin/binder.mjs",
@@ -787,9 +787,9 @@
787
787
  }
788
788
  },
789
789
  "node_modules/clavarium-parley": {
790
- "version": "0.17.94-next.1",
791
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.94-next.1.tgz",
792
- "integrity": "sha512-EPlSnEevH6sw2yfFLGG+KP3mlAIUQhPwHP/uaa7IoQva8zme0cqRm4bS+2o7jyAdtmV0cmxA9iDwC6MYTrgBWA==",
790
+ "version": "0.17.95-next.1",
791
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.95-next.1.tgz",
792
+ "integrity": "sha512-O4AOoNf9H6VejHu7ur9e8J4xDZMFDrhtrRjOef9FY/0T1WIyrNW6lOMT3UfxTTfNij+EWbnJCBRQX8iO7ZGUMQ==",
793
793
  "license": "MIT",
794
794
  "bin": {
795
795
  "parley": "bin/parley.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.212-beta.1",
3
+ "version": "0.2.213-beta.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
@@ -45,9 +45,9 @@
45
45
  "dependencies": {
46
46
  "@xterm/addon-fit": "^0.11.0",
47
47
  "@xterm/xterm": "^6.0.0",
48
- "clavarium-binder": "0.1.62-next.1",
48
+ "clavarium-binder": "0.1.63-next.1",
49
49
  "clavarium-docket": "0.1.2-next.2",
50
- "clavarium-parley": "0.17.94-next.1",
50
+ "clavarium-parley": "0.17.95-next.1",
51
51
  "clavarium-tether": "0.1.0-next.67",
52
52
  "mammoth": "1.13.0",
53
53
  "mermaid": "11.17.2",
package/server/api.mjs CHANGED
@@ -29,6 +29,9 @@
29
29
  * {} (no machine): out of its shared machine, into one of its own (15-11)
30
30
  * POST /api/conversations/<name>/copy {title?, machine?, machineMb?, reminders?}: a copy -- its work, its tool's state, its accesses (its reminders and wake-ups when asked); it untouched (202)
31
31
  * POST /api/conversations/<name>/rebuild {reset?, confirm?}: built again; reset (confirm: its name) for a working one too
32
+ * POST /api/signin-companion {companion}: the conversation that signs the others' tools in with its browser ('' none; 15-11); {clicks}: it clicks Authorize itself
33
+ * POST /api/conversations/<name>/signin-companion {companion}: its own (a conversation, "none"), or null for the general one; never itself
34
+ * POST /api/conversations/<name>/signin-link its sign-in handed to a companion: shown to the person instead
32
35
  * POST /api/conversations/<name>/ask-first {on}: its tool asks before acting (true), or acts without asking in its machine (false, the default), from its next start
33
36
  * POST /api/conversations/<name>/resume {on}: its tool takes up its last session when it starts (true), or starts fresh
34
37
  * POST /api/conversations/<name>/terminal/repair its terminal does not come though its machine runs: repaired
@@ -410,6 +413,8 @@ export async function handleApi(request, response, conversations, headers, resou
410
413
  if (pathname === '/api/git-hosts' && gitAccess) return send(200, gitAccess.hosts()), true;
411
414
  if (pathname === '/api/platform' && platform) return send(200, platform), true;
412
415
  if (pathname === '/api/instance' && instance) return send(200, instance.about()), true;
416
+ /* The sign-in companions (signinhelp.mjs, 15-11): the general one, each conversation's own, their browsers. */
417
+ if (pathname === '/api/signin-companion' && conversations.signinHelp) return send(200, conversations.signinHelp.view()), true;
413
418
  if (pathname === '/api/shelf' && shelf) return send(200, shelf.about()), true;
414
419
  /* Settings, Updates (updates.mjs): what runs, what is out, the mode, what happened. */
415
420
  if (pathname === '/api/updates' && updates) return send(200, updates.about()), true;
@@ -1000,6 +1005,12 @@ export async function handleApi(request, response, conversations, headers, resou
1000
1005
  }
1001
1006
  const later = /^\/api\/conversations\/([^/]+)\/machine\/cancel$/.exec(pathname);
1002
1007
  if (later) return send(200, conversations.cancelResize(decodeURIComponent(later[1]))), true;
1008
+ /* DELEGATED SIGN-IN (signinhelp.mjs, 15-11): the companion of all, of one conversation, and the link shown to the person instead. */
1009
+ if (pathname === '/api/signin-companion' && conversations.signinHelp) return send(200, body.clicks !== undefined ? conversations.signinHelp.setClicks(body.clicks) : conversations.signinHelp.setGeneral(body.companion)), true;
1010
+ const companionOf = /^\/api\/conversations\/([^/]+)\/signin-companion$/.exec(pathname);
1011
+ if (companionOf && conversations.signinHelp) return send(200, conversations.signinHelp.setFor(decodeURIComponent(companionOf[1]), body.companion ?? null)), true;
1012
+ const linkOf = /^\/api\/conversations\/([^/]+)\/signin-link$/.exec(pathname);
1013
+ if (linkOf && conversations.signinHelp) return send(200, conversations.signinHelp.showLink(decodeURIComponent(linkOf[1]))), true;
1003
1014
  const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
1004
1015
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
1005
1016
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
@@ -1402,6 +1402,10 @@ export class Conversations {
1402
1402
  const state = await this.#vms.state(name, { fresh: true }).catch(() => undefined);
1403
1403
  if (tool.state && state !== 'Running') throw new Refusal(409, 'Its shared machine is not running: open the conversation first, so that its tool\'s state can come along.', { retry: false });
1404
1404
  const memory = Math.max(tool.memoryMb, Number(c.memoryMb) || tool.memoryMb);
1405
+ /* One of its own left by an attempt cut short (a restart meanwhile): not its machine any more -- removed
1406
+ first, so that the room it takes is counted free (15-11, seen on test-c). */
1407
+ const states = await this.#vms.states().catch(() => null);
1408
+ if (states?.has(vmName(name))) await this.#vms.removeVm(vmName(name)).catch(() => {});
1405
1409
  await this.room({ kind: 'create', memoryMb: memory });
1406
1410
  const act = this.#take(name, 'move');
1407
1411
  this.#cancelStop(name);
@@ -52,11 +52,16 @@ export const AGAIN_MS = 30 * 60_000;
52
52
  /* ...this many times at most (the first included); then its chat says so. */
53
53
  export const TOLD_MAX = 3;
54
54
 
55
+ /* AN ANSWER NEVER SHOWN (15-11, #362): the note of a sign-in a companion did for another conversation is
56
+ the code it read (signinhelp.mjs) -- typed into that tool, never said in a chat nor shown to the owner. */
57
+ const SECRET_KINDS = new Set(['signin-help']);
58
+ const hidden = (event) => SECRET_KINDS.has(event?.kind);
59
+ const HIDDEN = '(not shown)';
55
60
  /* One line in the chat: what was handled, cut short; the docket keeps it whole. */
56
61
  const cut = (text, max) => { const s = String(text ?? '').replace(/\s+/g, ' ').trim(); return s.length > max ? `${s.slice(0, max - 1)}…` : s; };
57
62
 
58
63
  export class Dockets {
59
- #resources; #store; #say; #event; #alert; #idle; #awake; #chatOn; #now; #every; #zone;
64
+ #resources; #store; #say; #event; #alert; #idle; #awake; #chatOn; #now; #every; #zone; #acked;
60
65
  #listening = new Map(); #zoned = new Set(); #busy = false;
61
66
  /* The reminders a key set: plan id -> its name, for the line its chat shows. */
62
67
  #setBy = new Map();
@@ -65,9 +70,10 @@ export class Dockets {
65
70
  in its chat (Talk.event). `alert({title, body, url})`: the owner's devices. `idle(name)`: not in a
66
71
  turn (its pulse). `awake()`: the conversations whose machine runs. `chatOn(name)`. `now()`: ms. */
67
72
  /* `zone`: the time zone the tool's times are read in -- this server's, as its wake-ups' (a machine runs in UTC). */
73
+ /* `acked(name, e)`: told of every answer of its tool, { event, ack } (signinhelp.mjs reads its own kind). */
68
74
  constructor({ store, resources, say, event = () => {}, alert = () => {}, idle = () => true, awake = () => [], chatOn = () => false, now = () => Date.now(), listenEveryMs = 2000,
69
- zone = Intl.DateTimeFormat().resolvedOptions().timeZone }) {
70
- this.#zone = zone; this.#store = store; this.#resources = resources; this.#say = say; this.#event = event; this.#alert = alert; this.#idle = idle; this.#awake = awake; this.#chatOn = chatOn; this.#now = now; this.#every = listenEveryMs;
75
+ zone = Intl.DateTimeFormat().resolvedOptions().timeZone, acked = () => {} }) {
76
+ this.#acked = acked; this.#zone = zone; this.#store = store; this.#resources = resources; this.#say = say; this.#event = event; this.#alert = alert; this.#idle = idle; this.#awake = awake; this.#chatOn = chatOn; this.#now = now; this.#every = listenEveryMs;
71
77
  }
72
78
 
73
79
  #dir(name) { return `${this.#resources.workFolder(name)}/${FOLDER}`; }
@@ -105,7 +111,7 @@ export class Dockets {
105
111
  return {
106
112
  on: true,
107
113
  plans: s.plans.filter((p) => !p.off && p.next !== null && !(p.due !== undefined && s.events.some((e) => e.plan === p.id))).map((p) => ({ id: p.id, text: p.text, cron: p.cron ?? null, next: new Date(p.next).toISOString(), tz: p.tz })),
108
- events: s.events.slice(-20).reverse().map((e) => ({ id: e.id, at: e.at, from: e.from, kind: e.kind, text: e.text, state: e.state, ...(e.ack ? { note: e.ack.note } : {}), told: told[e.id]?.count ?? 0 })),
114
+ events: s.events.slice(-20).reverse().map((e) => ({ id: e.id, at: e.at, from: e.from, kind: e.kind, text: e.text, state: e.state, ...(e.ack ? { note: hidden(e) ? HIDDEN : e.ack.note } : {}), told: told[e.id]?.count ?? 0 })),
109
115
  waiting: s.waiting,
110
116
  };
111
117
  }
@@ -135,6 +141,8 @@ export class Dockets {
135
141
 
136
142
  /* What the tool did: said in its chat; a failure alerts its owner. */
137
143
  #heard(name, e) {
144
+ if (e.type === 'acked') { try { void Promise.resolve(this.#acked(name, { event: e.event, ack: e.ack })).catch(() => {}); } catch { /* a hook that fails stops nothing */ } }
145
+ if (e.type === 'acked' && e.ack.kind === 'done' && hidden(e.event)) { this.#line(name, { kind: 'docket-done', text: 'Handled: a sign-in for another conversation.', topic: 'Handled', brief: 'Sign-in' }); return; }
138
146
  if (e.type === 'acked' && e.ack.kind === 'done') this.#line(name, { kind: 'docket-done', text: `Handled: ${cut(e.event.text, 80)}${e.ack.note ? ` -- ${cut(e.ack.note, 120)}` : ''}`, topic: 'Handled', brief: e.event.text.slice(0, 60) });
139
147
  if (e.type === 'acked' && e.ack.kind === 'failed') {
140
148
  this.#line(name, { kind: 'docket-failed', text: `Could not be handled: ${e.event.text} -- ${e.ack.note}`, tone: 'warn', topic: 'Not handled' });
package/server/guide.mjs CHANGED
@@ -91,7 +91,7 @@ export function commonText() {
91
91
  /* Dictation into the terminal is marked once per message (app.js); in the chat, parley read says it. */
92
92
  '- A message in your terminal that starts with a microphone sign (U+1F3A4), or that parley read says was dictated, came by voice: a word may be misheard; when a key word seems wrong, ask rather than guess.',
93
93
  /* The commands, the one path every assistant has, MCP or not (#352): MCP tools, where given, are the same. */
94
- '- Commands installed (each with --help): parley (the chat), docket (what woke you, your reminders), binder (the lists you were given), tether (your accesses, alone: what you were given; a server of tools: tether mcp TARGET, then tether mcp TARGET TOOL \'{json}\'). The same may also be among your tools (MCP).',
94
+ '- Commands installed (each with --help): parley (the chat), docket (what woke you, your reminders), binder (lists, "classeur": yours too), tether (your accesses, alone: what you were given; a server of tools: tether mcp TARGET, then tether mcp TARGET TOOL \'{json}\'). The same may also be among your tools (MCP).',
95
95
  '- The rest is yours to explore (ls, --help).',
96
96
  '',
97
97
  ].join('\n');
@@ -133,7 +133,7 @@ export function ownText({ name, tool, shared, workKept, resources = [], chat, on
133
133
  /* Its docket (dockets.mjs): what wakes it waits there until it says done or failed. */
134
134
  if (chat) out.push('- What wakes you (a file arrived, the clock, a call) waits in your docket: when told "run docket", run it, do each, then docket done ID or docket failed ID "why". To be reminded later: docket remind --at "2026-10-23 09:00" (or --in 2h, --cron "0 9 * * 1") "what for". docket --help says all.');
135
135
  /* Its lists (binders.mjs): kept on the server, asked for through .binder; a person approves. */
136
- out.push('- Lists kept with the person (batches, tasks, customers...): binder shows those you were given; add, note, attach, move them; a gate waits for the person\'s tick. binder --help says all.');
136
+ out.push('- Lists kept with the person (batches, tasks, customers, people...; "classeur", "fiches" in French): the binder command, in your terminal, not an MCP tool. binder shows those you were given; binder new TEMPLATE "name" makes one (templates: simple, people, customers, development, batches, priorities, roadmap); add, note, attach, move cards; a gate waits for the person\'s tick. binder --help says all.');
137
137
  /* Its binder of batches is shown beside the chat (web/app.js): the person ticks there. */
138
138
  if (chat) out.push('- When you work in batches: keep them in a binder of batches, shown beside the chat. None yet: make it once (binder new batches; MCP: new-list, template batches). Then one card each (binder add Batches "title"), kept up to date; start only those the person ticked.');
139
139
  out.push(online === false ? '- Internet: off.' : '- Internet: on.');
@@ -240,20 +240,30 @@ export class Guide {
240
240
  async setLines(name, input) {
241
241
  this.#known(name);
242
242
  const lines = readLines(input);
243
- if (lines.length) this.#store.put({ name, lines }); else this.#store.remove(name);
243
+ { const { lines: _old, ...kept } = this.#store.get(name) ?? { name }; this.#store.put(lines.length ? { ...kept, name, lines } : { ...kept, name }); }
244
244
  await this.changed(name);
245
245
  return this.about(name);
246
246
  }
247
247
 
248
248
  /* ---- into the machine ---- */
249
- async #writeOwn(name) {
249
+ async #writeOwn(name, fresh = false) {
250
250
  const text = this.own(name);
251
251
  /* In a shared machine, its own file, readable by its own user only: its door shows it at OWN_PATH (#221). */
252
252
  const shared = this.#vms.shared?.(name) === true;
253
253
  const r = await this.#vms.exec(name, ['sudo', '-n', 'install', '-D', '-m', shared ? '0440' : '0444', '-o', 'root', '-g', shared ? sharedUser(name) : 'root', '/dev/stdin', shared ? ownGuideFile(name) : OWN_PATH], { input: text, timeoutMs: 30_000 });
254
254
  if (r.code !== 0) throw new Error(`its guide could not be written: ${firstLine(r.stderr) || `exit ${r.code}`}`);
255
255
  this.#written.set(name, text);
256
+ /* WHAT IT READ (15-11, its owner's ask: a tool kept on with its old setup did not know it changed): its
257
+ guide as written, the common part with it; changed since it last read it, its docket tells it -- not at
258
+ its start (`fresh`), when it reads it anyway. */
259
+ const seen = sha(`${commonText()}\n${text}`);
260
+ const was = this.#store.get(name)?.read;
261
+ if (was === seen) return;
262
+ if (was && !fresh && typeof this.told === 'function') { try { this.told(name, TELL_AGAIN); } catch { /* its docket may be off */ } }
263
+ this.#store.put({ ...(this.#store.get(name) ?? { name }), read: seen });
256
264
  }
265
+ /* Set by the server (15-11): its docket told that its guide changed. (name, line) */
266
+ told = null;
257
267
 
258
268
  /* The marked block in the tool's own instruction file. Resolves with
259
269
  'written', 'same', or throws with why it was left alone. */
@@ -275,7 +285,7 @@ export class Guide {
275
285
  in the way of an opening: what fails is said in the server's log. */
276
286
  async prepared(name, woke) {
277
287
  try {
278
- if (woke || this.#written.get(name) !== this.own(name)) await this.#writeOwn(name);
288
+ if (woke || this.#written.get(name) !== this.own(name)) await this.#writeOwn(name, woke);
279
289
  /* Once per machine start, and once after this server started. */
280
290
  if (woke || !this.#pointed.has(name)) { await this.pointer(name); this.#pointed.add(name); }
281
291
  } catch (error) { this.#written.delete(name); console.error(`${name}: ${error.message}`); }
@@ -294,7 +304,7 @@ export class Guide {
294
304
  async tellAgain(name) {
295
305
  this.#known(name);
296
306
  if (!this.#conversations.awake?.().includes(name)) throw new Refusal(409, 'It is asleep: open it first.');
297
- try { await this.#writeOwn(name); await this.pointer(name); this.#pointed.add(name); }
307
+ try { await this.#writeOwn(name, true); await this.pointer(name); this.#pointed.add(name); }
298
308
  catch (error) { throw new Refusal(502, `Its machine could not be given its guide: ${error.message}`); }
299
309
  if (!(await this.#say(name, TELL_AGAIN))) throw new Refusal(502, 'The line could not be typed: is its tool running?');
300
310
  return { ...this.about(name), told: TELL_AGAIN };
package/server/main.mjs CHANGED
@@ -26,7 +26,8 @@ import { handleApi } from './api.mjs';
26
26
  import { Conversations, DRAWN_MS, Refusal } from './conversations.mjs';
27
27
  import { Store, JsonFile } from './store.mjs';
28
28
  import { Instance } from './instance.mjs';
29
- import { loadTools } from './tools.mjs';
29
+ import { loadTools, screenRules } from './tools.mjs';
30
+ import { SigninHelp, typeInto } from './signinhelp.mjs';
30
31
  import { Vms, runner } from './vm.mjs';
31
32
  import { Resources, WORK_TAB } from './resources.mjs';
32
33
  import { download } from './files.mjs';
@@ -338,7 +339,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
338
339
  const gitAccess = new GitAccess({ vault, dataDir, ...(gitSsh ? { ssh: gitSsh } : {}) });
339
340
  /* The tools every machine sees at /tools, read-only: see toolbox.mjs. */
340
341
  /* With /tools/CLAVARIUM.md in it: where a tool is, the same for all (guide.mjs). */
341
- const toolbox = new Toolbox({ host: asHost, vms, mntDir, notes: () => commonText(), launched: new Store(`${dataDir}/launched.json`),
342
+ const toolbox = new Toolbox({ host: asHost, vms, mntDir, notes: () => commonText(), launched: new Store(`${dataDir}/launched.json`), screens: screenRules(tools),
342
343
  launches: (name) => Boolean(tools.find((t) => t.id === all.list().find((c) => c.name === name)?.tool)?.launch) });
343
344
  const folders = resources ?? new Resources({ store: new Store(`${dataDir}/resources.json`), vms, host: asHost, dataDir, mntDir, grants, access: gitAccess, toolbox });
344
345
  /* The ready-made machine new conversations are copied from, kept fresh
@@ -470,13 +471,16 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
470
471
  let bridge;
471
472
  /* A wake-up typed is said in its chat (talk, made below: called only once a wake-up fires). */
472
473
  /* Where its chat is on, what wakes a tool is an event it acknowledges: see dockets.mjs. */
474
+ let signinHelp = null;
473
475
  const dockets = new Dockets({ store: new Store(`${dataDir}/dockets.json`), resources: folders,
474
476
  say: (name, line) => wakeups.say(name, line),
475
477
  event: (name, line) => talk.event(name, line),
476
478
  alert: (message) => { void alerts.tell({ ...message, title: `${instance.name()}: ${message.title}` }); },
477
479
  /* Not in a turn: its pulse ended, or is old (Parley's own measure). */
478
480
  idle: (name) => { const p = talk.pulse(name); return !(p?.busy === true && Date.now() - Date.parse(p.at) < PULSE_MS); },
479
- awake: () => all.awake(), chatOn: (name) => talk.isOn(name) });
481
+ awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
482
+ /* A sign-in a companion did for another conversation (signinhelp.mjs, made below): its answer typed there. */
483
+ acked: (name, e) => signinHelp?.acked(name, e) });
480
484
  const typingWatch = new TypingWatch();
481
485
  const wakeups = new Wakeups({ store: new Store(`${dataDir}/wakeups.json`), vms, conversations: all, resources: folders, warm: (name) => bridge?.warm(name), docket: dockets, typing: (name) => typingWatch.busy(name),
482
486
  fired: (name, { text }) => talk.event(name, { kind: 'wakeup', text, topic: 'Wake-up' }) });
@@ -566,6 +570,13 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
566
570
  alert: (payload) => { void alerts.tell(payload); } });
567
571
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
568
572
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
573
+ /* Its guide changed while its tool ran (15-11): its docket tells it to read it again. */
574
+ guide.told = (name, line) => { if (dockets.on(name)) dockets.post(name, { kind: 'guide-changed', text: line }); };
575
+ /* Restarted with nothing written since (15-11): its docket tells it, once its tool is ready and free. */
576
+ talk.restarted = (name, why) => {
577
+ if (!dockets.on(name)) return false;
578
+ try { dockets.post(name, { kind: 'restarted', text: `Your machine was restarted${why ? ` (${String(why).replace(/\.$/, '')})` : ''}. What ran in the background stopped with it: pick up where you were.` }); return true; } catch { return false; }
579
+ };
569
580
  /* What an owner did to a machine (start, stop, sleep, force, restart): in the journal, and a line in its chat. */
570
581
  all.machineSaid = (name, text, ok, chat) => {
571
582
  events.add({ kind: 'machine', text: `Machine of ${name}: ${text}`, conversation: name });
@@ -573,6 +584,16 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
573
584
  };
574
585
  /* A Tether call waiting for the owner is said in its conversation's thread, with Accept / Refuse. */
575
586
  tethers.announce = (name, event) => { try { return talk.event(name, event); } catch { return null; } };
587
+ /* DELEGATED SIGN-IN (15-11, #362): a tool that must sign in is signed in by another conversation's browser
588
+ (its companion), the code it reads typed back into that tool: see signinhelp.mjs. */
589
+ signinHelp = new SigninHelp({ store: new JsonFile(`${dataDir}/signin-companion.json`, {}),
590
+ conversations: () => all.list(), tools: () => tools, awake: () => all.awake(), chatOn: (name) => talk.isOn(name),
591
+ workFolder: (name) => folders.workFolder(name),
592
+ browsers: (name) => { try { return tethers.store().targets().filter((t) => t.kind === 'browser').map((t) => ({ id: t.id, level: t.grants?.[`conversation:${name}`]?.level ?? '' })).filter((b) => b.level); } catch { return []; } },
593
+ post: (name, event) => dockets.post(name, event), type: (name, text) => typeInto(vms, name, text),
594
+ event: (name, line) => talk.event(name, line) });
595
+ const stopSigninHelp = signinHelp.start();
596
+ all.signinHelp = signinHelp;
576
597
  /* A device given a conversation that talks through the app talks there too. */
577
598
  door.talk = talk;
578
599
  /* A mail cited by its reference, opened on a device that may read its mailbox (mailref.mjs). */
@@ -585,6 +606,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
585
606
  await toolbox.installIn(name).catch(() => {});
586
607
  if (!toolbox.stale(name)) continue;
587
608
  try { if (talk.event(name, { kind: 'tools-updated', text: 'Tools updated: restart it to use them all. Its work picks up where it was.', topic: 'Tools', actions: ['restart'] })) toolbox.told(name); } catch { /* its chat is off */ }
609
+ /* Its tool told too, by its docket (15-11, its owner's ask): it takes them up when it suits it, never mid-work. */
610
+ try { if (dockets.on(name)) dockets.post(name, { kind: 'tools-updated', text: `Clavarium was updated to ${JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version}: your tools (parley, docket, the MCP servers given to you) are new. When nothing runs, touch /work/.parley/restart-asked to take them up; your work picks up where it was.` }); } catch { /* its docket may be off */ }
588
611
  }
589
612
  });
590
613
  /* A TOOL THAT ASKS TO BE RESTARTED (02-11: to take up its tools, after an update): its tool restarted by this server
@@ -858,7 +881,7 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
858
881
  screen: await quick(screenNow(), 1500, null), catalogue: await quick(catalogue.providers().catch(() => []), 1500, []),
859
882
  }) });
860
883
  const { server, listening } = serve(port, all, folders, { gate, originOk, shortcuts, voice, sharing, door, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, wifi, binders, meshcentral, tethers, accounts, groups, boxes, catalogue, rooms, machineList, features, apikeys, relayJoin: host.length ? new RelayJoin({ host: asHost }) : null, bundles: new Bundles({ dir: `${dataDir}/imports`, folder: (name) => folders.folder(name) }), repair: (name) => repairTerminal(name) });
861
- server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
884
+ server.on('close', () => { closing = true; stopBinders(); stopTethers(); clearInterval(historyTimer); clearInterval(secretsTimer); history.save(); stopVmWatch(); stopShelf(); stopHealth(); stopNetworkWatch(); stopUpdates(); stopWatch(); clearInterval(mailTimer); clearInterval(restartTimer); clearInterval(expiryTimer); clearInterval(answerTimer); clearInterval(wakeTimer); clearInterval(docketTimer); clearInterval(stopSigninHelp); dockets.stop(); clearInterval(gitTimer); talk.stop(); });
862
885
  let closing = false;
863
886
  boxes.attach(server, WebSocketServer);
864
887
  browsers.attach(server, WebSocketServer); server.on('close', () => browsers.shutdown());
@@ -0,0 +1,239 @@
1
+ /* DELEGATED SIGN-IN (15-11, #362): a tool that must sign in, served by ANOTHER conversation.
2
+ *
3
+ * A tool (Claude Code, Codex...) that is not signed in, at its start or signed out on the way, shows a
4
+ * link to open in a browser. Its screen-watch (config/launch/screen-watch.mjs) reads it there, by the
5
+ * rules of config/tools.json ("signin.screen"), and asks here where it goes, in its chat folder:
6
+ *
7
+ * signin-ask.json { id, at, link, around, told? } written by screen-watch (the machine: untrusted)
8
+ * signin-route.json { id, route, companion? } written here: companion, person or done
9
+ *
10
+ * THE COMPANION: a conversation whose agent drives a browser the person already signed in to (Tether's
11
+ * browser verbs). One for all, set in Settings, and/or one per conversation that wins over it. They may
12
+ * cross (A helps B, B helps C, C helps A); one that cannot serve (asleep, its chat off, no browser,
13
+ * signing in itself) is passed over for another companion that can -- so the last one signed in serves
14
+ * the others. A companion never serves itself.
15
+ *
16
+ * WHAT HAPPENS. The link is written in the companion's docket folder (a file of its work folder, nowhere
17
+ * else), and an event of kind KIND is posted to its docket: open it in its browser, let the person click
18
+ * Authorize, read the code the page shows, give it back as the note of `docket done`. That note is typed
19
+ * here into the asking tool, once, as screen-watch types a code the person pastes. The asking chat says
20
+ * one line ("Signing in through « B »...") with a button that shows the link to the person instead.
21
+ * No answer in WAIT_MS, a failure, or no code: the link goes to the person, as before.
22
+ *
23
+ * WHAT IS KEPT AWAY. The link and the code are never in a log, a chat line, an alert, or this server's
24
+ * files: the link only in the companion's docket folder (taken away when it is over), the code only in its
25
+ * docket's answer (Dockets hides it from its chat and its owner's view), then typed. A code is typed once.
26
+ * The link must be HTTPS and lead to a domain the tool declares ("signin.links"): an agent that writes a
27
+ * forged ask in its own chat folder can have the companion open nothing else -- and the person still
28
+ * sees the page and decides to click. No link is made here, none is reachable without signing in.
29
+ */
30
+ import { lstatSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
31
+ import { join } from 'node:path';
32
+ import { CODE } from '../config/launch/screen-watch.mjs';
33
+ import { Refusal, SESSION } from './conversations.mjs';
34
+ import { SOCKET } from './tmux.mjs';
35
+
36
+ export const KIND = 'signin-help';
37
+ export const ASK = 'signin-ask.json';
38
+ export const ROUTE = 'signin-route.json';
39
+ /* The folders of a work folder they live in: its chat's (talk.mjs FOLDER) and its docket's (dockets.mjs FOLDER). */
40
+ export const CHAT = '.parley';
41
+ export const DOCKET = '.docket';
42
+ export const WAIT_MS = 10 * 60_000;
43
+ export const TICK_MS = 3000;
44
+ export const NONE = 'none';
45
+ const ASK_BYTES = 16_384;
46
+ const LINK_MAX = 4000;
47
+ const AROUND_MAX = 1000;
48
+ const ID = /^[0-9a-f-]{8,64}$/;
49
+ /* Tether's levels that may open a page (watch only reads). */
50
+ const ACTS = (level) => Boolean(level) && level !== 'off' && level !== 'watch';
51
+
52
+ const inDomain = (host, domains) => domains.some((d) => host === d || host.endsWith(`.${d}`));
53
+ /* A link the tool may send the companion to: HTTPS, to one of its declared domains, no user part. */
54
+ export function linkAllowed(link, domains = []) {
55
+ if (typeof link !== 'string' || link.length > LINK_MAX || /\s/.test(link)) return false;
56
+ let u; try { u = new URL(link); } catch { return false; }
57
+ return u.protocol === 'https:' && !u.username && !u.password && inDomain(u.hostname.toLowerCase(), domains);
58
+ }
59
+ const cut = (s, n) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}…` : t; };
60
+
61
+ /* The code typed into the tool, then Enter -- as screen-watch types a code the person pastes. Never logged. */
62
+ export async function typeInto(vms, name, text) {
63
+ const tmux = ['tmux', '-L', SOCKET, 'send-keys', '-t', `=${SESSION}:`];
64
+ if ((await vms.exec(name, [...tmux, '-l', '--', text], { timeoutMs: 30_000 })).code !== 0) return false;
65
+ return (await vms.exec(name, [...tmux, 'Enter'], { timeoutMs: 30_000 })).code === 0;
66
+ }
67
+
68
+ export class SigninHelp {
69
+ #store; #conversations; #tools; #awake; #chatOn; #work; #browsers; #post; #type; #event; #now;
70
+ /* asker -> { id (its ask), companion, event (the docket event's id), at, file, code (a code is awaited) } */
71
+ #open = new Map();
72
+ /* asker -> the id of the last ask looked at: each is routed once. */
73
+ #seen = new Map();
74
+ #busy = false;
75
+
76
+ /* `store`: { get(), set(v) } of { general, per: { name: companion | NONE } }. `conversations()`: [{ name, tool }].
77
+ `tools()`: config/tools.json as read. `awake()`, `chatOn(name)`. `workFolder(name)`. `browsers(name)`: the
78
+ browser targets it was given, [{ id, level }]. `post(name, {kind, text, data})`: its docket. `type(name, text)`:
79
+ typed into its tool, then Enter (resolves true when typed). `event(name, line)`: a line in its chat. */
80
+ constructor({ store, conversations, tools, awake, chatOn, workFolder, browsers, post, type, event = () => {}, now = () => Date.now() }) {
81
+ this.#store = store; this.#conversations = conversations; this.#tools = tools; this.#awake = awake; this.#chatOn = chatOn;
82
+ this.#work = workFolder; this.#browsers = browsers; this.#post = post; this.#type = type; this.#event = event; this.#now = now;
83
+ }
84
+
85
+ #settings() { const s = this.#store.get() ?? {}; return { general: typeof s.general === 'string' ? s.general : '', per: s.per && typeof s.per === 'object' ? { ...s.per } : {}, clicks: s.clicks === true }; }
86
+ #exists(name) { return this.#conversations().some((c) => c.name === name); }
87
+ #usable(name) { try { return (this.#browsers(name) ?? []).filter((b) => ACTS(b.level)); } catch { return []; } }
88
+
89
+ /* FOR THE PAGE: the general companion, each conversation's own, and which of them has a browser to open with. */
90
+ view() {
91
+ const s = this.#settings();
92
+ const named = new Set([s.general, ...Object.values(s.per)].filter((c) => c && c !== NONE));
93
+ return { general: s.general, per: s.per, clicks: s.clicks, browsers: Object.fromEntries([...named].map((c) => [c, this.#usable(c).map((b) => b.id)])) };
94
+ }
95
+ /* '' for none. */
96
+ setGeneral(companion) {
97
+ if (typeof companion !== 'string' || (companion && !this.#exists(companion))) throw new Refusal(400, 'Give a conversation, or nothing for none.');
98
+ this.#store.set({ ...this.#settings(), general: companion });
99
+ return this.view();
100
+ }
101
+ /* THE COMPANION CLICKS « AUTHORIZE » ITSELF (15-11, its owner's go): off unless its owner says so; then the
102
+ person has nothing to do. Only that button, on the page the link opened -- nothing else is clicked. */
103
+ setClicks(on) {
104
+ if (typeof on !== 'boolean') throw new Refusal(400, 'Say true or false.');
105
+ this.#store.set({ ...this.#settings(), clicks: on });
106
+ return this.view();
107
+ }
108
+ /* null: as the general one; NONE: none for it; else that conversation -- never itself. */
109
+ setFor(name, companion) {
110
+ if (!this.#exists(name)) throw new Refusal(404, 'No such conversation.');
111
+ if (companion !== null && (typeof companion !== 'string' || (companion !== NONE && !this.#exists(companion)))) throw new Refusal(400, 'Give a conversation, "none", or null for the general one.');
112
+ if (companion === name) throw new Refusal(400, 'A conversation cannot sign itself in: choose another one.');
113
+ const s = this.#settings();
114
+ if (companion === null) delete s.per[name]; else s.per[name] = companion;
115
+ this.#store.set(s);
116
+ return this.view();
117
+ }
118
+ /* WHO SIGNS `name` IN: its own companion, else the general one; one that cannot serve now is passed over
119
+ for any other companion that can (crossed companions, the last one signed in). Never itself. */
120
+ companionFor(name) {
121
+ const s = this.#settings();
122
+ const own = s.per[name];
123
+ if (own === NONE) return null;
124
+ const chosen = own ?? s.general;
125
+ if (!chosen) return null;
126
+ const awake = new Set(this.#awake());
127
+ const can = (c) => c && c !== NONE && c !== name && this.#exists(c) && awake.has(c) && this.#chatOn(c) && !this.#open.has(c) && this.#usable(c).length > 0;
128
+ if (can(chosen)) return chosen;
129
+ return [...new Set([s.general, ...Object.values(s.per)])].find(can) ?? null;
130
+ }
131
+
132
+ #chat(name) { return join(this.#work(name), CHAT); }
133
+ #own(dir) { const i = lstatSync(dir, { throwIfNoEntry: false }); return i !== undefined && i.isDirectory() && !i.isSymbolicLink(); }
134
+ #readAsk(name) {
135
+ const dir = this.#chat(name);
136
+ if (!this.#own(dir)) return null;
137
+ const i = lstatSync(join(dir, ASK), { throwIfNoEntry: false });
138
+ if (!i || !i.isFile() || i.size > ASK_BYTES) return null;
139
+ try { const a = JSON.parse(readFileSync(join(dir, ASK), 'utf8')); return a && typeof a === 'object' && ID.test(String(a.id)) ? a : null; } catch { return null; }
140
+ }
141
+ #route(name, route) {
142
+ const dir = this.#chat(name);
143
+ if (!this.#own(dir)) return;
144
+ try { writeFileSync(join(dir, `.${ROUTE}.new`), JSON.stringify(route)); renameSync(join(dir, `.${ROUTE}.new`), join(dir, ROUTE)); } catch { /* its chat folder cannot be written: screen-watch tells the person itself */ }
145
+ }
146
+ #readRoute(name) { try { return JSON.parse(readFileSync(join(this.#chat(name), ROUTE), 'utf8')); } catch { return null; } }
147
+ #line(name, line) { try { this.#event(name, line); } catch { /* its chat may be off */ } }
148
+ #tool(name) { const id = this.#conversations().find((c) => c.name === name)?.tool; return this.#tools().find((t) => t.id === id); }
149
+
150
+ /* Every few seconds: each new ask routed; what waited too long given back to the person. */
151
+ async tick() {
152
+ if (this.#busy) return;
153
+ this.#busy = true;
154
+ try {
155
+ for (const [name, o] of [...this.#open]) if (this.#now() - o.at > WAIT_MS) this.#toPerson(name, `« ${o.companion} » did not answer in ${Math.round(WAIT_MS / 60_000)} minutes: the sign-in link is shown to you.`);
156
+ for (const name of this.#awake()) {
157
+ if (!this.#chatOn(name)) continue;
158
+ const ask = this.#readAsk(name);
159
+ if (!ask || this.#seen.get(name) === ask.id) continue;
160
+ this.#seen.set(name, ask.id);
161
+ this.#ask(name, ask);
162
+ }
163
+ } finally { this.#busy = false; }
164
+ }
165
+
166
+ #ask(name, ask) {
167
+ const before = this.#readRoute(name);
168
+ /* Already routed (this server restarted meanwhile): what was handed over and is no longer followed goes to the person. */
169
+ if (before?.id === ask.id) { if (before.route === 'companion' && !this.#open.has(name)) this.#route(name, { id: ask.id, route: 'person' }); return; }
170
+ /* Told to the person already (this server was late): nobody else. */
171
+ if (ask.told === true) return;
172
+ const tool = this.#tool(name);
173
+ const companion = this.companionFor(name);
174
+ if (!companion || !tool?.signin || !linkAllowed(ask.link, tool.signin.links)) { this.#route(name, { id: ask.id, route: 'person' }); return; }
175
+ /* The link, in the companion's docket folder only: its agent reads it there, nobody else is told it. */
176
+ const docket = join(this.#work(companion), DOCKET);
177
+ const file = `signin-${ask.id.slice(0, 8)}.txt`;
178
+ const target = this.#usable(companion)[0].id;
179
+ const code = (tool.signin.screen ?? []).some((r) => r.startsWith('code:'));
180
+ let event;
181
+ try {
182
+ /* The link itself is not in the event (an event is shown to the companion's owner): only where it is. */
183
+ const at = `/work/${DOCKET}/${file}`;
184
+ event = this.#post(companion, { kind: KIND, text: `Sign in « ${name} » (${tool.label}) with your browser. 1) tether browser ${target} open "$(head -n1 ${at})" `
185
+ + (this.#settings().clicks
186
+ ? '2) Your owner allowed you: on that page only, click the button that authorizes (Authorize, Allow, Continue, Accept) -- nothing else, no other page. '
187
+ : '2) Tell your person, one line: "Click Authorize in your browser". ')
188
+ + (code ? `3) Read the code the page then shows (tether browser ${target} html --readable). 4) docket done ID "<the code>": the code alone, never in a chat. ` : '3) Once the page says it is done: docket done ID "ok". ')
189
+ + 'Over 10 min old, or not possible: docket failed ID "why".', data: { conversation: name, tool: tool.id, link: at, browser: target } });
190
+ if (!this.#own(docket)) throw new Error('its docket folder is not its own');
191
+ writeFileSync(join(docket, file), `${ask.link}\n${ask.around ? `\nBeside the link on its screen (a code to type on the page, maybe):\n${String(ask.around).slice(0, AROUND_MAX)}\n` : ''}`);
192
+ } catch { this.#route(name, { id: ask.id, route: 'person' }); return; }
193
+ this.#open.set(name, { id: ask.id, companion, event: event.id, at: this.#now(), file: join(docket, file), code });
194
+ this.#route(name, { id: ask.id, route: 'companion', companion });
195
+ this.#line(name, { kind: KIND, text: `Signing in through « ${companion} »…`, topic: 'Sign-in', brief: companion, actions: ['signinlink'] });
196
+ }
197
+
198
+ #end(name, route) {
199
+ const o = this.#open.get(name);
200
+ if (!o) return null;
201
+ this.#open.delete(name);
202
+ rmSync(o.file, { force: true });
203
+ this.#route(name, { id: o.id, route });
204
+ return o;
205
+ }
206
+ #toPerson(name, why) { if (this.#end(name, 'person')) this.#line(name, { kind: KIND, text: why, tone: 'warn', topic: 'Sign-in' }); }
207
+
208
+ /* THE COMPANION ANSWERED (Dockets, on an ack of a KIND event). `e`: { event, ack }. The note is never kept or said. */
209
+ async acked(companion, e) {
210
+ if (e?.event?.kind !== KIND) return;
211
+ const name = [...this.#open].find(([, o]) => o.event === e.event.id && o.companion === companion)?.[0];
212
+ if (!name) return;
213
+ const o = this.#open.get(name);
214
+ if (e.ack?.kind !== 'done') { this.#toPerson(name, `« ${companion} » could not sign it in (${cut(e.ack?.note, 120)}): the sign-in link is shown to you.`); return; }
215
+ if (!o.code) { this.#end(name, 'done'); this.#line(name, { kind: KIND, text: `Signed in through « ${companion} ».`, topic: 'Sign-in', brief: 'Signed in' }); return; }
216
+ const note = String(e.ack.note ?? '').trim();
217
+ if (!CODE.test(note)) { this.#toPerson(name, `« ${companion} » gave back no code: the sign-in link is shown to you.`); return; }
218
+ /* Once: taken out of what waits before it is typed. */
219
+ this.#end(name, 'done');
220
+ const typed = await Promise.resolve(this.#type(name, note)).catch(() => false);
221
+ if (typed) this.#line(name, { kind: KIND, text: `Signed in through « ${companion} ».`, topic: 'Sign-in', brief: 'Signed in' });
222
+ else { this.#route(name, { id: o.id, route: 'person' }); this.#line(name, { kind: KIND, text: 'The code could not be typed into the tool: the sign-in link is shown to you.', tone: 'warn', topic: 'Sign-in' }); }
223
+ }
224
+
225
+ /* THE PERSON ASKED for the link (the button of the line): shown to them, the companion's answer no longer awaited. */
226
+ showLink(name) {
227
+ if (!this.#open.has(name)) throw new Refusal(409, 'No sign-in is waiting for another conversation here.');
228
+ this.#toPerson(name, 'The sign-in link is shown to you.');
229
+ return { ok: true };
230
+ }
231
+ /* Is a sign-in of `name` waiting for a companion? (the page's line, its button) */
232
+ waiting(name) { const o = this.#open.get(name); return o ? { companion: o.companion, since: new Date(o.at).toISOString() } : null; }
233
+
234
+ start(everyMs = TICK_MS) {
235
+ const timer = setInterval(() => { void this.tick(); }, everyMs);
236
+ timer.unref?.();
237
+ return timer;
238
+ }
239
+ }
package/server/talk.mjs CHANGED
@@ -166,6 +166,8 @@ export const EVENT_LEVELS = Object.freeze({
166
166
  'docket-failed': 'needs-you',
167
167
  'docket-unhandled': 'needs-you',
168
168
  'docket-reminder': 'trace',
169
+ /* Its tool signs in through another conversation's browser (signinhelp.mjs, 15-11): handed over, signed in, or back to the person. */
170
+ 'signin-help': 'news',
169
171
  /* A Tether call its agent asks the owner to allow (tethers.mjs): offered in the thread with
170
172
  Accept / Refuse, the same block a machine problem uses. Its closing line (decided here, from
171
173
  Assets, or by the agent) is a trace that carries the call's id, so the buttons close with it. */
@@ -705,12 +707,15 @@ export class Talk {
705
707
  /* Its machine was restarted, or built again (conversations.mjs): said in
706
708
  the thread, and, the tool having started again with nothing of the
707
709
  chat in mind, REREAD is typed with the person's next message (never alone). */
710
+ /* Set by the server (15-11): its machine restarted and nothing written since -- posted to its docket, which
711
+ tells it once it is free. (name, why) -> whether it was posted. */
712
+ restarted = null;
708
713
  renewed(name, text, started = true) {
709
714
  const r = this.#store.get(name);
710
715
  if (r?.on !== true) return;
711
716
  if (text) this.event(name, started ? { kind: 'restarted', text, topic: 'Restarted' } : { kind: 'machine-problem', text, tone: 'bad', topic: 'Machine', actions: ['restart', 'terminal'] });
712
717
  if (started) {
713
- this.#store.put({ ...this.#store.get(name), reread: true });
718
+ this.#store.put({ ...this.#store.get(name), reread: true, renewedText: text || undefined });
714
719
  this.#nextTry.set(`reread:${name}`, this.#now() + this.#rereadAfter);
715
720
  }
716
721
  }
@@ -723,7 +728,10 @@ export class Talk {
723
728
  /* Typed only when the person has written since: a line typed while the tool
724
729
  reloads a long session after a restart sat in its input box, never sent
725
730
  (seen on a real deployment). By then the tool has long been ready. */
726
- if (this.#parley(name).unread() === 0) return later(RETRY_MS);
731
+ /* Nothing written since (15-11, its owner's ask): its docket says it was restarted instead -- once its
732
+ tool is ready, as below -- and the docket tells it when it is free; never a line typed into a reload. */
733
+ const told = this.#parley(name).unread() === 0;
734
+ if (told && typeof this.restarted !== 'function') return later(RETRY_MS);
727
735
  if (!this.#conversations.awake().includes(name)) return later(RETRY_MS);
728
736
  const quiet = this.#now() - (this.#typedAt.get(name) ?? 0);
729
737
  if (quiet < TYPING_QUIET_MS) return later(TYPING_QUIET_MS - quiet + 100);
@@ -736,6 +744,11 @@ export class Talk {
736
744
  if (wait > 0) return later(wait + 100);
737
745
  }
738
746
  }
747
+ if (told) {
748
+ if (!this.restarted(name, r.renewedText ?? '')) return later(RETRY_MS);
749
+ this.#store.put({ ...this.#store.get(name), reread: false, renewedText: undefined });
750
+ return 'told';
751
+ }
739
752
  if (!(await this.#type(name, this.rereadLine()).catch(() => false))) return later(RETRY_MS);
740
753
  /* Reading the whole thread, it reads what waits too: that line is not typed after it. */
741
754
  const waits = this.#parley(name).unread() > 0;
@@ -36,6 +36,8 @@ export const NOTES = 'CLAVARIUM.md';
36
36
  /* THE LAUNCHERS of the tools (config/launch of this code: config/ is in every release, also one made by an older updater): copied as they are into /tools/launch. */
37
37
  export const LAUNCH = 'launch';
38
38
  export const LAUNCHERS = fileURLToPath(new URL('../config/launch', import.meta.url));
39
+ /* Beside them: the tools' sign-in screen rules (15-11, #362), the name screen-watch.mjs reads (RULES_FILE there). */
40
+ export const SCREEN_RULES = 'screen-rules.json';
39
41
  /* What is put there: { name, archive (a path here), integrity, usage(file) }.
40
42
  Parley's archive as the registry served it, next to the code (see
41
43
  parley.mjs), with the integrity npm recorded for the version installed:
@@ -61,7 +63,7 @@ export const integrityOf = (bytes) => `sha512-${createHash('sha512').update(byte
61
63
  const firstLine = (text) => String(text ?? '').trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
62
64
 
63
65
  export class Toolbox {
64
- #host; #vms; #mnt; #uid; #gid; #sources; #notes; #launchers; #launched; #launches; #index = null; #launchHash = '';
66
+ #host; #vms; #mnt; #uid; #gid; #sources; #notes; #launchers; #launched; #launches; #screens; #index = null; #launchHash = '';
65
67
  /* What is known of Parley in each machine, as the index is now:
66
68
  conversation -> { sha256, why } (why: '' installed, or why it cannot be,
67
69
  such as a machine without npm: not asked again at each opening). */
@@ -73,8 +75,10 @@ export class Toolbox {
73
75
  may be in it: every machine reads it. */
74
76
  /* `launched`: a Store of what each tool was started with (its launchers' fingerprint): see stale(). */
75
77
  /* `launches(name)`: does its tool start through a launcher? (only those read one) */
76
- constructor({ host, vms, mntDir, uid = process.getuid(), gid = process.getgid(), sources = toolSources(), notes = null, launchers = LAUNCHERS, launched = null, launches = () => false }) {
77
- this.#launched = launched; this.#launches = launches;
78
+ /* `screens`: the sign-in rules of each tool's screen, { toolId: [rule, ...] } (config/tools.json, "signin.screen";
79
+ tools.mjs screenRules), written beside the launchers as SCREEN_RULES for screen-watch.mjs (15-11, #362). */
80
+ constructor({ host, vms, mntDir, uid = process.getuid(), gid = process.getgid(), sources = toolSources(), notes = null, launchers = LAUNCHERS, launched = null, launches = () => false, screens = {} }) {
81
+ this.#launched = launched; this.#launches = launches; this.#screens = screens;
78
82
  this.#host = host; this.#vms = vms; this.#mnt = mntDir; this.#uid = uid; this.#gid = gid; this.#sources = sources; this.#notes = notes; this.#launchers = launchers;
79
83
  }
80
84
 
@@ -114,8 +118,11 @@ export class Toolbox {
114
118
  const there = existsSync(`${launch}/${n}`) ? readFileSync(`${launch}/${n}`) : null;
115
119
  if (!there || !there.equals(bytes)) { writeFileSync(`${launch}/.${n}.new`, bytes, { mode: 0o755 }); renameSync(`${launch}/.${n}.new`, `${launch}/${n}`); }
116
120
  }
117
- for (const n of readdirSync(launch)) if (!wanted.includes(n)) rmSync(`${launch}/${n}`, { recursive: true, force: true });
118
- this.#launchHash = createHash('sha256').update(wanted.sort().map((n) => `${n}\n${readFileSync(join(this.#launchers, n), 'utf8')}`).join('\n')).digest('hex');
121
+ /* The sign-in rules of the tools' screens, beside them (screen-watch.mjs --tool): a change of them is a change of the launchers. */
122
+ const screens = `${JSON.stringify(this.#screens ?? {}, null, 2)}\n`;
123
+ if (!existsSync(`${launch}/${SCREEN_RULES}`) || readFileSync(`${launch}/${SCREEN_RULES}`, 'utf8') !== screens) { writeFileSync(`${launch}/.${SCREEN_RULES}.new`, screens, { mode: 0o644 }); renameSync(`${launch}/.${SCREEN_RULES}.new`, `${launch}/${SCREEN_RULES}`); }
124
+ for (const n of readdirSync(launch)) if (!wanted.includes(n) && n !== SCREEN_RULES) rmSync(`${launch}/${n}`, { recursive: true, force: true });
125
+ this.#launchHash = createHash('sha256').update(wanted.sort().map((n) => `${n}\n${readFileSync(join(this.#launchers, n), 'utf8')}`).join('\n') + (Object.keys(this.#screens ?? {}).length ? `\n${SCREEN_RULES}\n${screens}` : '')).digest('hex');
119
126
  const kept = new Set([...tools.map((t) => t.file), 'index.json', LAUNCH, ...(this.#notes ? [NOTES] : [])]);
120
127
  for (const name of readdirSync(dir)) if (!kept.has(name)) rmSync(`${dir}/${name}`, { recursive: true, force: true });
121
128
  const index = { tools };
package/server/tools.mjs CHANGED
@@ -11,6 +11,7 @@
11
11
  * and the checksum comes from this repository, never from the network. */
12
12
  import { readFileSync } from 'node:fs';
13
13
  import { VM_USER } from './vm.mjs';
14
+ import { rulesOf } from '../config/launch/screen-watch.mjs';
14
15
 
15
16
  export const NODE_VERSION = 'v24.20.0';
16
17
  export const NODE_SHA256 = '2f2c0da162318f0de47665410c7c8c2ed3d36c8f3105de4bbc61176c70a7cbf2';
@@ -45,6 +46,11 @@ export const NPM_WRITABLE = [
45
46
 
46
47
  const isArgv = (x) => Array.isArray(x) && x.length > 0 && x.every((a) => typeof a === 'string' && a !== '');
47
48
  const ID = /^[a-z][a-z0-9-]{0,30}$/;
49
+ /* The sign-in rules of a tool's screen (signin.screen, 15-11): how many, how long, of which kinds. */
50
+ const SCREEN_RULES_MAX = 20; const SCREEN_RULE_MAX = 400;
51
+ const SCREEN_KINDS = new Set(['link', 'keys', 'type', 'code']);
52
+ /* What the machine is given of them: { toolId: [rule, ...] }, written to /tools/launch/screen-rules.json (toolbox.mjs). */
53
+ export const screenRules = (tools) => Object.fromEntries(tools.filter((t) => t.signin?.screen).map((t) => [t.id, [...t.signin.screen]]));
48
54
  const INSTRUCTIONS = /^(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+){0,7}$/;
49
55
 
50
56
  export function readTools(text) {
@@ -77,7 +83,20 @@ export function readTools(text) {
77
83
  if (t.signin !== undefined) {
78
84
  const domains = (list) => Array.isArray(list) && list.length > 0 && list.every((d) => typeof d === 'string' && /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/.test(d));
79
85
  if (!domains(t.signin.senders) || !domains(t.signin.links)) throw new Error(`${t.id}: signin needs "senders" and "links", lists of domain names`);
80
- signin = Object.freeze({ senders: Object.freeze([...t.signin.senders]), links: Object.freeze([...t.signin.links]) });
86
+ /* Optional (15-11, #362): WHAT ITS SCREEN SAYS when it must sign in -- the rules of screen-watch
87
+ (config/launch/screen-watch.mjs), "KIND:PATTERN[=VALUE]" with KIND link, keys, type or code, each one
88
+ rule as screen-watch reads it. Given to the machine in /tools/launch/screen-rules.json: a tool that
89
+ changes its words is followed here, its launcher unchanged. `link` patterns are also checked, by the
90
+ server, against "links" before a link is handed to another conversation (signinhelp.mjs). */
91
+ let screen;
92
+ if (t.signin.screen !== undefined) {
93
+ const rules = t.signin.screen;
94
+ if (!Array.isArray(rules) || rules.length === 0 || rules.length > SCREEN_RULES_MAX || rules.some((r) => typeof r !== 'string' || r.length > SCREEN_RULE_MAX || rulesOf([r]).length !== 1 || !SCREEN_KINDS.has(rulesOf([r])[0].kind))) {
95
+ throw new Error(`${t.id}: signin "screen" is a list of screen-watch rules, "link:", "keys:", "type:" or "code:" each`);
96
+ }
97
+ screen = Object.freeze([...rules]);
98
+ }
99
+ signin = Object.freeze({ senders: Object.freeze([...t.signin.senders]), links: Object.freeze([...t.signin.links]), ...(screen ? { screen } : {}) });
81
100
  }
82
101
  /* Optional: the command that starts it taking up its last session
83
102
  ("claude --continue"); used instead of `command` once it has run on
package/web/app.js CHANGED
@@ -2732,6 +2732,7 @@
2732
2732
  void paintGuide(here);
2733
2733
  const offline = here?.offline === true;
2734
2734
  for (const b of $('network').children) b.setAttribute('aria-pressed', String((b.dataset.online === 'true') !== offline));
2735
+ void paintCompanionHere();
2735
2736
  await paintSignIn();
2736
2737
  }
2737
2738
  /* ---------- chapters (a conversation's settings, and Settings): folded or not ---------- */
@@ -3743,7 +3744,7 @@
3743
3744
  /* A message attached to a card (#180), from its menu: its id, as the card opens it again. */
3744
3745
  ...(!DEVICE ? { card: (m) => attachToCard({ kind: 'message', ref: m.id, title: String(m.short || m.text || '').replace(/\s+/g, ' ').trim().slice(0, 80) }) } : {}),
3745
3746
  /* The buttons of a line of the machine: what this screen may do. */
3746
- act: (id) => { if (id === 'seen-done') return; if (id.startsWith('salon:')) { void openSalon(id.slice('salon:'.length)); return; } if (id === 'seen') void markSeen(); else if (id === 'memory') void openMemory(); else if (id === 'disk') void openDisk(); else if (id === 'room') seeTerminal(); else if (id === 'restart') void restartMachine(false); else if (id === 'terminal') seeTerminal(); else if (tetherAct(id, () => thread?.refresh?.())) return; else if (id.startsWith('flash:')) void flashFromThread(id.slice('flash:'.length)); else if (id.startsWith('review:')) void openGit(id.slice('review:'.length)); else openCommits(id); },
3747
+ act: (id) => { if (id === 'seen-done') return; if (id.startsWith('salon:')) { void openSalon(id.slice('salon:'.length)); return; } if (id === 'seen') void markSeen(); else if (id === 'memory') void openMemory(); else if (id === 'disk') void openDisk(); else if (id === 'room') seeTerminal(); else if (id === 'restart') void restartMachine(false); else if (id === 'terminal') seeTerminal(); else if (id === 'signinlink') void signinLinkToMe(); else if (tetherAct(id, () => thread?.refresh?.())) return; else if (id.startsWith('flash:')) void flashFromThread(id.slice('flash:'.length)); else if (id.startsWith('review:')) void openGit(id.slice('review:'.length)); else openCommits(id); },
3747
3748
  /* What it opens over the thread (a picture, its media, a search...) is a step of this page's: one Back closes it. */
3748
3749
  back: { open: (name, close) => nav.over(`chat-${name}`, () => close(), { stack: true }), closed: (step) => { if (step) nav.drop(step); } },
3749
3750
  /* Files attached to a message: wherever the chat may be written in. */
@@ -3877,7 +3878,7 @@
3877
3878
  /* "commits:<repository>.<to>.<from>.<n>": those commits, in the review ("See the 3 commits"). A commit a
3878
3879
  line names (7 to 40 hexadecimal characters, a digit among them) is a link to its review, on a line about
3879
3880
  a repository; the agent's own messages are never read for this. */
3880
- const ACTIONS = { memory: 'More memory...', disk: 'Give it more disk...', room: 'See what takes room', restart: 'Restart...', terminal: 'See the terminal', review: 'Open the review', seen: '\u2713 Seen', allow: 'Accept', deny: 'Refuse', flash: 'Plug it in and start' };
3881
+ const ACTIONS = { memory: 'More memory...', disk: 'Give it more disk...', room: 'See what takes room', restart: 'Restart...', terminal: 'See the terminal', review: 'Open the review', signinlink: 'Show me the link', seen: '\u2713 Seen', allow: 'Accept', deny: 'Refuse', flash: 'Plug it in and start' };
3881
3882
  const COMMITS = /^commits:([a-z0-9][a-z0-9-]*)\.([0-9a-f]{7,40})\.([0-9a-f]{7,40})\.(\d{1,4})$/;
3882
3883
  /* A Tether call an agent asked the owner to allow, offered right in the thread: allow:<id> / deny:<id>. */
3883
3884
  const DEMANDE = /^(allow|deny|always|flash):[0-9a-f-]{36}$/;
@@ -3894,7 +3895,7 @@
3894
3895
  function machineLines(data) {
3895
3896
  if (!Array.isArray(data?.messages)) return data;
3896
3897
  const kindOf = (id) => String(id).split(':')[0];
3897
- const may = (id) => (id === 'terminal' || id === 'room' ? !noTerminal() : id === 'disk' ? !DEVICE && !narrow() : (id === 'memory' || id === 'restart' || id === 'seen' || id === 'seen-done' || DEMANDE.test(id) || /^review:[a-z0-9][a-z0-9._-]*$/.test(id) || COMMITS.test(id)) && !DEVICE);
3898
+ const may = (id) => (id === 'terminal' || id === 'room' ? !noTerminal() : id === 'disk' ? !DEVICE && !narrow() : (id === 'memory' || id === 'restart' || id === 'seen' || id === 'seen-done' || id === 'signinlink' || DEMANDE.test(id) || /^review:[a-z0-9][a-z0-9._-]*$/.test(id) || COMMITS.test(id)) && !DEVICE);
3898
3899
  const label = (id) => { const n = Number(COMMITS.exec(id)?.[4] ?? 0); return n ? (n === 1 ? 'See the commit' : `See the ${n} commits`) : ACTIONS[kindOf(id)]; };
3899
3900
  const linksOf = (m) => {
3900
3901
  const repo = DEVICE ? null : (m.actions ?? []).map((id) => /^review:([a-z0-9][a-z0-9-]*)$/.exec(id)?.[1]).find(Boolean);
@@ -3909,6 +3910,8 @@
3909
3910
  /* A problem of its machine that went away since (machine-ok): nothing left to see or to do on its line. */
3910
3911
  const fixedAt = data.messages.filter((m) => m.from === 'system' && m.event === 'machine-ok').map((m) => String(m.at ?? '')).sort().pop() ?? '';
3911
3912
  const FIXED_GOES = new Set(['seen', 'room', 'disk', 'memory']);
3913
+ /* "Show me the link" on a sign-in handed over, until the next line of that sign-in says how it went. */
3914
+ const signinAt = data.messages.filter((m) => m.from === 'system' && m.event === 'signin-help').map((m) => String(m.at ?? '')).sort().pop() ?? '';
3912
3915
  /* A Tether demande decided (here, from Assets, or by the agent) is marked done in the thread,
3913
3916
  carrying its id: Accept / Refuse are then offered no more on the line that asked. */
3914
3917
  const settled = new Map(data.messages.filter((m) => m.from === 'system' && m.event === 'tether-done' && m.brief).map((m) => [String(m.brief), m]));
@@ -3922,7 +3925,7 @@
3922
3925
  if (!may(String(r.yes?.id ?? ''))) { const { yes: _y, no: _n, others: _o, ...shown } = r; return shown; }
3923
3926
  return r;
3924
3927
  };
3925
- const actionsOf = (m) => (m.actions ?? []).filter(may).filter((id) => !(id === 'restart' && restartedAt && String(m.at ?? '') < restartedAt)).filter((id) => !(FIXED_GOES.has(id) && fixedAt && String(m.at ?? '') < fixedAt)).filter((id) => !(DEMANDE.test(id) && settled.has(id.slice(id.indexOf(':') + 1))))
3928
+ const actionsOf = (m) => (m.actions ?? []).filter(may).filter((id) => !(id === 'restart' && restartedAt && String(m.at ?? '') < restartedAt)).filter((id) => !(FIXED_GOES.has(id) && fixedAt && String(m.at ?? '') < fixedAt)).filter((id) => !(DEMANDE.test(id) && settled.has(id.slice(id.indexOf(':') + 1)))).filter((id) => !(id === 'signinlink' && String(m.at ?? '') < signinAt))
3926
3929
  .map((id) => (id === 'seen' && seenAt && String(m.at ?? '') <= seenAt ? { id: 'seen-done', label: seenWords } : { id, label: label(id) }));
3927
3930
  return { ...data, messages: data.messages.map((m) => (m.from === 'system' ? { ...m, actions: actionsOf(m), links: linksOf(m), ...(m.request && typeof m.request === 'object' ? { request: requestOf(m) } : {}) } : m)) };
3928
3931
  }
@@ -4162,6 +4165,7 @@
4162
4165
  ['docket-failed', 'Could not be handled', 'Said failed by the tool, with why'],
4163
4166
  ['docket-unhandled', 'Not handled', 'Told three times, never said done'],
4164
4167
  ['docket-reminder', 'Reminder set', 'A reminder the tool set itself'],
4168
+ ['signin-help', 'Sign-in', 'Signed in through another conversation'],
4165
4169
  ['tether-notice', 'Later news', 'A mail came back, an invitation was declined'],
4166
4170
  ['machine-problem', 'Machine in trouble', 'Memory, disk, no answer, a failed restart'],
4167
4171
  ['machine-ok', 'Machine well again', 'What was wrong with it went away'],
@@ -7812,7 +7816,7 @@
7812
7816
  : 'Development mode: anyone on this machine is the operator';
7813
7817
  $('settings-address').textContent = `Address: ${platform.address ?? 'not declared'}`;
7814
7818
  $('settings-about').textContent = `Clavarium ${platform.version ?? ''}`;
7815
- void paintInstance();
7819
+ void paintInstance(); void paintCompanionGeneral();
7816
7820
  if ($('settings-wifi-top').open) void paintWifi();
7817
7821
  if ($('settings-mesh-top').open) void paintScreen();
7818
7822
  if ($('settings-usage-top').open) void paintUsage();
@@ -8027,6 +8031,57 @@
8027
8031
  } catch (error) { $('instance-error').textContent = error.message; $('instance-error').hidden = false; }
8028
8032
  });
8029
8033
 
8034
+ /* ---------- the sign-in companion (server/signinhelp.mjs, 15-11, #362) ---------- */
8035
+ /* The conversation whose browser signs the tools in: one for all in Settings, and each conversation's own
8036
+ (or none) in its settings. Never itself; one with no browser given is said so. */
8037
+ const COMPANION_NONE = 'none';
8038
+ const readCompanions = () => fetch(`${API}/signin-companion`).then((r) => (r.ok ? r.json() : null)).catch(() => null);
8039
+ const companionWarn = (view, name) => (name && name !== COMPANION_NONE && !(view.browsers?.[name] ?? []).length ? 'No browser given to it yet' : '');
8040
+ function fillCompanions(select, first, value, except) {
8041
+ select.replaceChildren(...first.map(([v, t]) => new Option(t, v)), ...conversations.filter((c) => c.name !== except).map((c) => new Option(shownName(c), c.name)));
8042
+ select.value = [...select.options].some((o) => o.value === value) ? value : first[0][0];
8043
+ }
8044
+ async function paintCompanionGeneral() {
8045
+ if (DEVICE) return;
8046
+ const view = await readCompanions();
8047
+ if (!view) return;
8048
+ fillCompanions($('companion-general'), [['', 'None']], view.general, null);
8049
+ $('companion-general-hint').textContent = companionWarn(view, view.general) || 'Signs the tools in with its browser';
8050
+ $('companion-clicks').checked = view.clicks === true;
8051
+ }
8052
+ $('companion-clicks').addEventListener('change', async () => {
8053
+ $('companion-general-error').hidden = true;
8054
+ try { await post(`${API}/signin-companion`, { clicks: $('companion-clicks').checked }); } catch (error) { $('companion-general-error').textContent = error.message; $('companion-general-error').hidden = false; }
8055
+ await paintCompanionGeneral();
8056
+ });
8057
+ $('companion-general').addEventListener('change', async () => {
8058
+ $('companion-general-error').hidden = true;
8059
+ try { await post(`${API}/signin-companion`, { companion: $('companion-general').value }); } catch (error) { $('companion-general-error').textContent = error.message; $('companion-general-error').hidden = false; }
8060
+ await paintCompanionGeneral();
8061
+ });
8062
+ async function paintCompanionHere() {
8063
+ $('companion-here-row').hidden = DEVICE;
8064
+ if (DEVICE || !current) return;
8065
+ const name = current;
8066
+ const view = await readCompanions();
8067
+ if (!view || name !== current) return;
8068
+ const general = view.general && view.general !== name ? conversations.find((c) => c.name === view.general) : null;
8069
+ const own = view.per?.[name] ?? '';
8070
+ fillCompanions($('companion-here'), [['', general ? `As in Settings: ${shownName(general)}` : 'As in Settings: none'], [COMPANION_NONE, 'None']], own, name);
8071
+ $('companion-here-hint').textContent = companionWarn(view, own || (general ? view.general : '')) || 'Signs its tool in with its browser';
8072
+ }
8073
+ $('companion-here').addEventListener('change', async () => {
8074
+ const v = $('companion-here').value;
8075
+ $('panel-error').hidden = true;
8076
+ try { await post(`${API}/conversations/${encodeURIComponent(current)}/signin-companion`, { companion: v === '' ? null : v }); } catch (error) { $('panel-error').textContent = error.message; $('panel-error').hidden = false; }
8077
+ await paintCompanionHere();
8078
+ });
8079
+ /* The button of the line "Signing in through « B »...": the link shown to the person instead. */
8080
+ async function signinLinkToMe() {
8081
+ try { await post(`${API}/conversations/${encodeURIComponent(current)}/signin-link`, {}); } catch { /* already over: the thread says how */ }
8082
+ void thread?.refresh?.();
8083
+ }
8084
+
8030
8085
  /* ---------- Updates: what runs, what is out, how it updates itself (server/updates.mjs) ---------- */
8031
8086
  let updatesTimer; let updatesBusy = false;
8032
8087
  const RESULT_WORDS = { done: 'Done', 'rolled-back': 'Did not work: went back', failed: 'Failed' };
package/web/index.html CHANGED
@@ -267,6 +267,8 @@
267
267
  <div class="chapter-body">
268
268
  <!-- ITS ASSETS (07-11, assets step 4): one line; what it was given lives in its Assets tab (Give…, its rights). -->
269
269
  <div class="row access-assets"><button type="button" id="access-assets" class="as-link"></button></div>
270
+ <!-- ITS SIGN-IN COMPANION (15-11, #362): the conversation that signs its tool in, if not the general one. -->
271
+ <div class="set-row" id="companion-here-row"><div class="set-what"><label for="companion-here">Sign-in companion</label><small id="companion-here-hint">Signs its tool in with its browser</small></div><div class="set-control"><select id="companion-here"></select></div></div>
270
272
  <div id="signin-setup" hidden>
271
273
  <div class="panel-top"><b>Sign-in mailbox</b></div>
272
274
  <p class="hint">Its sign-in links, beside the terminal</p><p class="hint tip" hidden>A mailbox for this tool's account, read only; its password never enters the machine.</p>
@@ -1016,6 +1018,10 @@
1016
1018
  <div class="chapter-body">
1017
1019
  <form id="instance-form" class="set-row" autocomplete="off"><div class="set-what"><label for="instance-name">Name</label><small id="instance-hint">In tabs, alerts, the app icon</small><small class="tip" hidden>Empty: taken from the address</small></div><div class="set-control"><input id="instance-name" maxlength="30" spellcheck="false"><button type="submit">Save</button></div></form>
1018
1020
  <p class="error" id="instance-error" role="alert" hidden></p>
1021
+ <!-- SIGN-IN COMPANION (15-11, #362): the conversation whose browser signs the others' tools in. -->
1022
+ <div class="set-row"><div class="set-what"><label for="companion-general">Sign-in companion</label><small id="companion-general-hint">Signs the tools in with its browser</small></div><div class="set-control"><select id="companion-general"></select></div></div>
1023
+ <div class="set-row"><div class="set-what"><label for="companion-clicks">It clicks Authorize itself</label><small>You have nothing to do</small></div><div class="set-control"><input type="checkbox" id="companion-clicks"></div></div>
1024
+ <p class="error" id="companion-general-error" role="alert" hidden></p>
1019
1025
  </div>
1020
1026
  </details>
1021
1027
  <details class="chapter" id="settings-ch-about" data-chapter="s-about">