clavarium 0.2.87-next.1 → 0.2.88-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.
package/config/tools.json CHANGED
@@ -64,6 +64,7 @@
64
64
  {
65
65
  "id": "opencode",
66
66
  "instructions": ".config/opencode/AGENTS.md",
67
+ "logs": [".local/share/opencode/log"],
67
68
  "label": "OpenCode",
68
69
  "command": [
69
70
  "opencode"
@@ -211,6 +211,18 @@ run() { if [ "$SAY" = "yes" ]; then printf '%s\n' "$*"; else exec "$@"; fi; }
211
211
  # with a letter; no trailing hyphen; 32 at most. The same rule as the server.
212
212
  is_name() { [[ "$1" =~ ^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$ ]]; }
213
213
  vm_of() { is_name "${1#clv-}" && [ "$1" != "${1#clv-}" ] || refuse "not one of our VMs: ${1:-<empty>}"; }
214
+ # The qemu process(es) of one of our machines -- a qemu-system whose disk is in
215
+ # that instance, the mapping "server room" also uses. Empty when none is left,
216
+ # which is what a suspend that freed the RAM leaves behind.
217
+ vm_qemu_pids() {
218
+ local want="$1" pid vm
219
+ for pid in $(pgrep qemu-system 2>/dev/null || true); do
220
+ vm="$(tr '\0' '\n' < "/proc/$pid/cmdline" 2>/dev/null | grep -oE '/instances/clv(shelf)?-[a-z0-9-]+/' | head -1 | cut -d/ -f3)" || vm=""
221
+ [ "$vm" = "$want" ] && printf '%s\n' "$pid"
222
+ done
223
+ }
224
+ # No qemu left for this machine after a short grace: its RAM has been freed.
225
+ vm_freed() { local v="$1" i; for i in $(seq 1 24); do [ -z "$(vm_qemu_pids "$v")" ] && return 0; sleep 0.5; done; return 1; }
214
226
  number() { [[ "$1" =~ ^[0-9]{1,6}$ ]] || refuse "not a number: ${1:-<empty>}"; }
215
227
  # A disk or partition named by its device: /dev/sdX, /dev/vdX, /dev/nvmeNnN(pN),
216
228
  # /dev/xvdX, /dev/mmcblkN(pN), with a digit or two at the end; a loop device only
@@ -770,9 +782,51 @@ case "$AREA $VERB" in
770
782
  "vm info")
771
783
  [ $# -eq 1 ] || usage; vm_of "$1"
772
784
  run "$MULTIPASS" info "$1" --format json ;;
773
- "vm start"|"vm stop"|"vm suspend")
785
+ "vm start"|"vm stop")
774
786
  [ $# -eq 1 ] || usage; vm_of "$1"
775
787
  run "$MULTIPASS" "$VERB" "$1" ;;
788
+ "vm suspend")
789
+ # Veille: suspend must save the machine's state AND free its RAM by ending
790
+ # its qemu process. Multipass saves the state reliably but at times leaves
791
+ # qemu alive (canonical/multipass #446, #2152, #5432), so the RAM stays
792
+ # taken though the machine shows "Suspended". The state being saved, we make
793
+ # the RAM come back, gentlest first: a second suspend from a clean running
794
+ # state usually ends qemu (and keeps the ~2s resume); failing that, a clean
795
+ # stop frees it for sure (it then wakes by a boot). Normally qemu is already
796
+ # gone after the first suspend and none of this runs.
797
+ [ $# -eq 1 ] || usage; vm_of "$1"
798
+ if [ "$SAY" = "yes" ]; then
799
+ printf '%s\n' "$MULTIPASS suspend $1" \
800
+ "if its qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
801
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
802
+ exit 0
803
+ fi
804
+ "$MULTIPASS" suspend "$1" || refuse "suspend of $1 failed"
805
+ vm_freed "$1" && exit 0
806
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
807
+ vm_freed "$1" && exit 0
808
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
809
+ vm_freed "$1" && exit 0
810
+ refuse "suspended $1 but its memory was not freed (its qemu stayed); the VM manager likely needs a restart" ;;
811
+ "vm reclaim")
812
+ # Free a machine that is ASLEEP but whose qemu still holds the RAM -- a
813
+ # suspend (maybe from before this existed) that did not end the process.
814
+ # Idempotent and safe for an asleep machine (nobody is using it): if its
815
+ # qemu is already gone, nothing happens. Touches only this machine, and
816
+ # never restarts the VM manager.
817
+ [ $# -eq 1 ] || usage; vm_of "$1"
818
+ if [ "$SAY" = "yes" ]; then
819
+ printf '%s\n' "if $1's qemu still holds the RAM: $MULTIPASS start $1 && $MULTIPASS suspend $1 (wake+resleep)" \
820
+ "if it still does: $MULTIPASS stop $1 (free it; it wakes by a boot)"
821
+ exit 0
822
+ fi
823
+ # Each step that frees the RAM says how, so the server can tell the owner.
824
+ vm_freed "$1" && { echo "freed-already"; exit 0; }
825
+ "$MULTIPASS" start "$1" >/dev/null 2>&1 && "$MULTIPASS" suspend "$1" >/dev/null 2>&1
826
+ vm_freed "$1" && { echo "freed-resleep"; exit 0; }
827
+ "$MULTIPASS" stop "$1" >/dev/null 2>&1 || true
828
+ vm_freed "$1" && { echo "freed-stop"; exit 0; }
829
+ refuse "could not free $1's memory (its qemu stayed); the VM manager likely needs a restart" ;;
776
830
  "vm kill")
777
831
  # A stop that does not wait for the system inside: asked only after a
778
832
  # clean stop hung or failed (a restart the owner asked for).
@@ -1,20 +1,20 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.87-next.1",
3
+ "version": "0.2.88-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.87-next.1",
9
+ "version": "0.2.88-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.8-next.1",
14
+ "clavarium-binder": "0.1.42-next.1",
15
15
  "clavarium-docket": "0.1.1",
16
- "clavarium-parley": "0.17.11-next.1",
17
- "clavarium-tether": "0.1.0-next.16",
16
+ "clavarium-parley": "0.17.21-next.1",
17
+ "clavarium-tether": "0.1.0-next.34",
18
18
  "mermaid": "11.17.2",
19
19
  "node-pty": "^1.1.0",
20
20
  "pdfjs-dist": "6.4.299",
@@ -716,9 +716,9 @@
716
716
  }
717
717
  },
718
718
  "node_modules/clavarium-binder": {
719
- "version": "0.1.8-next.1",
720
- "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.8-next.1.tgz",
721
- "integrity": "sha512-0ZvTgn4z3IzLWjVyt5H82tnrE4g4Zdh0eb0kKrpVYjJ8vEfun6CmzHFclce9lb7vH+CC5ozKETuTAmSVYkk+lg==",
719
+ "version": "0.1.42-next.1",
720
+ "resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.42-next.1.tgz",
721
+ "integrity": "sha512-nkXe6SzcJwS4FkmM3zOvieHeW8Ao/HrKwz9wFIjaoVpLdXvGMiAJUpG+Nn8Uv6xlrxawhaEIqzEYxLF/Q6VojA==",
722
722
  "license": "MIT",
723
723
  "bin": {
724
724
  "binder": "bin/binder.mjs",
@@ -742,9 +742,9 @@
742
742
  }
743
743
  },
744
744
  "node_modules/clavarium-parley": {
745
- "version": "0.17.11-next.1",
746
- "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.11-next.1.tgz",
747
- "integrity": "sha512-IHGgFbDzHjrNVRcSR/KudWPUfvKxCeu03bNXE8+84lLMGHL7LyaiIg+iuw/cXMq4etz5BVXddVA/DGDoTUFO3A==",
745
+ "version": "0.17.21-next.1",
746
+ "resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.21-next.1.tgz",
747
+ "integrity": "sha512-rOToE7K7EAKL7AcuOMGFr6PIyzAYQVVe5lqCCGQB28uQ227H9aUAFajb8FysMhAdDAUmektXEontpp6k2m/4UQ==",
748
748
  "license": "MIT",
749
749
  "bin": {
750
750
  "parley": "bin/parley.mjs",
@@ -755,9 +755,9 @@
755
755
  }
756
756
  },
757
757
  "node_modules/clavarium-tether": {
758
- "version": "0.1.0-next.16",
759
- "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.16.tgz",
760
- "integrity": "sha512-OluUIv32Ot5oh+PbrcDBT/MnklJ8+kUjQQbtvbhQuEnBO1tnXWaBNIA2TLpEyWysu7hFe2jCehm19ljsZrvy7w==",
758
+ "version": "0.1.0-next.34",
759
+ "resolved": "https://registry.npmjs.org/clavarium-tether/-/clavarium-tether-0.1.0-next.34.tgz",
760
+ "integrity": "sha512-6AOHSkdeHE+K5W9NK3q282Hwx9QcETaxNAJb6rDyrEa8ddAHKjKkokJDsAYB/xjRI8Z0txl8GpQb0f4sfFC43Q==",
761
761
  "license": "MIT",
762
762
  "bin": {
763
763
  "tether": "bin/cli.mjs",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.87-next.1",
3
+ "version": "0.2.88-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.",
@@ -44,10 +44,10 @@
44
44
  "dependencies": {
45
45
  "@xterm/addon-fit": "^0.11.0",
46
46
  "@xterm/xterm": "^6.0.0",
47
- "clavarium-binder": "0.1.8-next.1",
47
+ "clavarium-binder": "0.1.42-next.1",
48
48
  "clavarium-docket": "0.1.1",
49
- "clavarium-parley": "0.17.11-next.1",
50
- "clavarium-tether": "0.1.0-next.16",
49
+ "clavarium-parley": "0.17.21-next.1",
50
+ "clavarium-tether": "0.1.0-next.34",
51
51
  "mermaid": "11.17.2",
52
52
  "node-pty": "^1.1.0",
53
53
  "pdfjs-dist": "6.4.299",
@@ -16,6 +16,11 @@
16
16
  * own open-source desktop client, verified for all three: Google over IMAP +
17
17
  * CalDAV/CardDAV, Microsoft over Microsoft Graph (mail, calendar and contacts).
18
18
  *
19
+ * A CLASSIC ACCOUNT (OVH, Infomaniak, Nextcloud... any IMAP/SMTP + CalDAV/CardDAV host)
20
+ * has no token: it signs in with its password. The password is kept the same way, a
21
+ * host-only secret the keeper reveals to the connector alone; each kind is tried live
22
+ * before anything is kept, so a wrong server or password is said at once.
23
+ *
19
24
  * A CREATED TARGET IS GIVEN TO NO ONE. The person grants it per conversation, at
20
25
  * its own level, from the page (Assets > Access) -- like git: one mailbox, many
21
26
  * conversations, each its own rights.
@@ -39,12 +44,20 @@ const PENDING_MAX = 20;
39
44
  Tether kind each becomes, and whether the target needs the email address. */
40
45
  const KIND = {
41
46
  mail: { connector: 'mail', kind: 'mail', title: 'Mail', needsUser: true },
42
- calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: false },
47
+ calendar: { connector: 'calendar', kind: 'calendar', title: 'Agenda', needsUser: true },
43
48
  contacts: { connector: 'contacts', kind: 'contacts', title: 'Contacts', needsUser: true },
44
49
  };
45
50
  /* What each provider's built-in (Thunderbird) client grants a refresh token for. */
46
51
  const SUPPORTED = { google: ['mail', 'calendar', 'contacts'], microsoft: ['mail', 'calendar', 'contacts'] };
47
52
 
53
+ /* Servers of common classic hosts, by the address's domain (what ISPDB lacks: the
54
+ calendar and contacts addresses). */
55
+ const CLASSIC = {
56
+ 'ovh.net': { imap: 'ssl0.ovh.net', smtp: 'ssl0.ovh.net' },
57
+ 'infomaniak.com': { imap: 'mail.infomaniak.com', smtp: 'mail.infomaniak.com', caldav: 'https://sync.infomaniak.com', carddav: 'https://sync.infomaniak.com' },
58
+ 'ik.me': { imap: 'mail.infomaniak.com', smtp: 'mail.infomaniak.com', caldav: 'https://sync.infomaniak.com', carddav: 'https://sync.infomaniak.com' },
59
+ 'fastmail.com': { imap: 'imap.fastmail.com', smtp: 'smtp.fastmail.com', caldav: 'https://caldav.fastmail.com', carddav: 'https://carddav.fastmail.com' },
60
+ };
48
61
  const emailOk = (s) => /^[^\s@]{1,64}@[^\s@]{1,190}\.[^\s@]{2,}$/.test(s);
49
62
  /* A deterministic, valid secret name for an account's token: a short slug of the
50
63
  address plus a hash of it, so reconnecting the same account reuses the name
@@ -62,10 +75,73 @@ export class Accounts {
62
75
 
63
76
  /* `secrets`: the vault (set host-only, by name). `targets`: { put(spec) } onto
64
77
  the Tether store. `fetch`: injected for tests. */
65
- constructor({ secrets, targets, fetch = globalThis.fetch }) {
78
+ #probe;
79
+ constructor({ secrets, targets, fetch = globalThis.fetch, probe = null }) {
66
80
  if (!secrets?.set) throw new Error('accounts needs the secret store');
67
81
  if (!targets?.put) throw new Error('accounts needs the Tether target store');
68
- this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch;
82
+ this.#secrets = secrets; this.#targets = targets; this.#fetch = fetch; this.#probe = probe;
83
+ }
84
+
85
+ /* The servers of a classic address, as far as they can be known: a few common
86
+ hosts, else the public Thunderbird database of mail providers (ISPDB). What
87
+ is not known stays empty for the person to fill. */
88
+ async lookup({ user } = {}) {
89
+ const address = String(user ?? '').trim();
90
+ if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
91
+ const domain = address.split('@')[1].toLowerCase();
92
+ const known = Object.entries(CLASSIC).find(([d]) => domain === d || domain.endsWith(`.${d}`))?.[1];
93
+ const out = { imap: '', smtp: '', caldav: '', carddav: '', ...(known ?? {}) };
94
+ if (!out.imap || !out.smtp) {
95
+ try {
96
+ const r = await this.#fetch(`https://autoconfig.thunderbird.net/v1.1/${encodeURIComponent(domain)}`);
97
+ if (r.ok) {
98
+ const xml = await r.text();
99
+ const servers = (kind) => [...xml.matchAll(new RegExp(`<(incomingServer|outgoingServer) type="${kind}">([\\s\\S]*?)</\\1>`, 'g'))].map((m) => ({ host: /<hostname>([^<]+)</.exec(m[2])?.[1] ?? '', port: /<port>(\\d+)</.exec(m[2])?.[1] ?? '', socket: /<socketType>([^<]+)</.exec(m[2])?.[1] ?? '' }));
100
+ const imap = servers('imap').find((x) => x.socket === 'SSL') ?? null;
101
+ const smtp = servers('smtp').find((x) => x.socket === 'STARTTLS') ?? null;
102
+ if (!out.imap && imap?.host) out.imap = `${imap.host}${imap.port && imap.port !== '993' ? `:${imap.port}` : ''}`;
103
+ if (!out.smtp && smtp?.host) out.smtp = `${smtp.host}${smtp.port && smtp.port !== '587' ? `:${smtp.port}` : ''}`;
104
+ }
105
+ } catch { /* not known there: the person fills it */ }
106
+ }
107
+ return out;
108
+ }
109
+
110
+ /* Connect a classic account: its password kept host-only, a target per kind,
111
+ each tried live first (nothing is kept if one fails). */
112
+ async classic({ user, password, imap, smtp, caldav, carddav, kinds } = {}) {
113
+ const address = String(user ?? '').trim();
114
+ if (!emailOk(address)) throw new Refusal(400, 'The account needs its email address.');
115
+ const secret = String(password ?? '');
116
+ if (!secret) throw new Refusal(400, 'The account needs its password.');
117
+ const wanted = (Array.isArray(kinds) && kinds.length ? kinds : ['mail']).map(String).filter((k) => KIND[k]);
118
+ if (!wanted.length) throw new Refusal(400, 'Choose at least mail, calendar or contacts.');
119
+ const hostPort = (v, what, port) => {
120
+ const m = /^([a-z0-9.-]+\.[a-z]{2,})(?::(\d{1,5}))?$/i.exec(String(v ?? '').trim());
121
+ if (!m) throw new Refusal(400, `The ${what} server is a name like mail.example.com.`);
122
+ return { host: m[1].toLowerCase(), port: Number(m[2] ?? port) };
123
+ };
124
+ const davUrl = (v, what) => {
125
+ let u; try { u = new URL(/^https?:\/\//i.test(String(v ?? '').trim()) ? String(v).trim() : `https://${String(v ?? '').trim()}`); } catch { u = null; }
126
+ if (!u || u.protocol !== 'https:' || !u.hostname.includes('.')) throw new Refusal(400, `The ${what} address is an https address, like https://dav.example.com.`);
127
+ return u.href;
128
+ };
129
+ const name = secretName('classic', address);
130
+ const specs = [];
131
+ for (const k of wanted) {
132
+ const config = { user: address };
133
+ if (k === 'mail') { const i = hostPort(imap, 'mail (IMAP)', 993); const o = hostPort(smtp, 'sending (SMTP)', 587); Object.assign(config, { host: i.host, port: i.port, smtpHost: o.host, smtpPort: o.port }); }
134
+ if (k === 'calendar') config.caldav = davUrl(caldav, 'calendar (CalDAV)');
135
+ if (k === 'contacts') config.carddav = davUrl(carddav, 'contacts (CardDAV)');
136
+ specs.push({ id: targetId(k, 'classic', address), title: `${KIND[k].title} — ${address}`, kind: KIND[k].kind, connector: KIND[k].connector, config, secrets: { password: name } });
137
+ }
138
+ if (this.#probe) for (const t of specs) {
139
+ try { await this.#probe(t, secret); }
140
+ catch (e) { throw new Refusal(400, `${KIND[t.connector === 'mail' ? 'mail' : t.connector].title}: ${String(e?.message ?? e).replace(/^.*?: /, '')}`); }
141
+ }
142
+ this.#secrets.set({ name, value: secret, hostOnly: true });
143
+ const made = specs.map((t) => { const saved = this.#targets.put(t); return { id: saved?.id ?? t.id, title: saved?.title ?? t.title, kind: t.kind }; });
144
+ return { provider: 'classic', user: address, targets: made, authorized: wanted, denied: [] };
69
145
  }
70
146
 
71
147
  /* Which kinds may be connected, per provider, for the page to offer. */
package/server/api.mjs CHANGED
@@ -12,6 +12,7 @@
12
12
  * GET /api/conversations/<name>/health what was last seen of its machine
13
13
  * POST /api/conversations/<name>/health look now (never wakes a machine)
14
14
  * POST /api/conversations/<name>/health/seen what it says now no longer calls its owner (Needs you)
15
+ * POST /api/conversations/<name>/exit-report why its tool ended: { now (read in its machine, if it runs), last (kept at its end) }
15
16
  * POST /api/conversations/<name>/archive
16
17
  * 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
17
18
  * POST /api/conversations/<name>/resume {on}: its tool takes up its last session when it starts (true), or starts fresh
@@ -19,6 +20,7 @@
19
20
  * POST /api/conversations/<name>/talk {text, answers?, files?, via?}: written in its chat; files from .../talk/file; via 'voice': dictated
20
21
  * POST /api/conversations/<name>/talk/react {to, reaction}: the owner's reaction to a message of the tool (null: taken back)
21
22
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
23
+ * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
22
24
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
23
25
  * POST /api/conversations/<name>/talk/file?name=<file name> the body IS a file the person attaches -> {path, name, size}
24
26
  * GET /api/conversations/<name>/talk?last=|days=|before=|from=|since= a part of its chat: the newest messages, those of the
@@ -151,6 +153,9 @@ function readBody(request, max = BODY_MAX) {
151
153
  }
152
154
 
153
155
  /* Returns true when the request was an API request (answered here). */
156
+ /* This run of the server: a page's count of binder changes is of one run, and starts again with the next. */
157
+ const BOOT = Math.random().toString(36).slice(2, 10);
158
+
154
159
  export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups) {
155
160
  const { pathname } = new URL(request.url ?? '/', 'http://local');
156
161
  if (!pathname.startsWith('/api/')) return false;
@@ -299,7 +304,7 @@ export async function handleApi(request, response, conversations, headers, resou
299
304
  if (pathname === '/api/wifi/scan' && wifi) return send(200, await wifi.scan()), true;
300
305
  if (pathname === '/api/meshcentral' && meshcentral) return send(200, await meshcentral.status()), true;
301
306
  if (pathname === '/api/operators') return send(200, team ? { operators: team.list(), me: identity } : { local: true }), true;
302
- if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: binders.changes() }), true;
307
+ if (pathname === '/api/binder/people' && binders) return send(200, { people: binders.people(identity), changes: `${BOOT}:${binders.changes()}` }), true;
303
308
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
304
309
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
305
310
  if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
@@ -430,12 +435,24 @@ export async function handleApi(request, response, conversations, headers, resou
430
435
  kept host-only, a Tether target made): see accounts.mjs. */
431
436
  if (pathname === '/api/accounts/consent' && accounts) return send(200, accounts.consent(body)), true;
432
437
  if (pathname === '/api/accounts/connect' && accounts) { const made = await accounts.connect(body); return send(201, made), true; }
438
+ if (pathname === '/api/accounts/lookup' && accounts) return send(200, await accounts.lookup(body)), true;
439
+ if (pathname === '/api/accounts/classic' && accounts) { const made = await accounts.classic(body); return send(201, made), true; }
433
440
  if (pathname === '/api/accounts/verify' && accounts) { const r = await accounts.verify(body); return send(200, r), true; }
434
441
  /* Assets > Access: the owner sets a conversation's level and rules on a
435
442
  target, decides a call that waited, or removes a target. Each is an op the
436
443
  keeper runs as the owner (person), never as an agent. */
437
444
  const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume)$/.exec(pathname);
438
445
  if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
446
+ /* A mailbox's signature (Markdown), added under what the agent sends from it. */
447
+ if (pathname === '/api/tether/signature' && tethers) {
448
+ const t = tethers.store().target(String(body.target ?? ''));
449
+ if (!t || t.kind !== 'mail') throw new Refusal(404, 'No such mailbox.');
450
+ const signature = String(body.signature ?? '').replace(/\r\n?/g, '\n').trim();
451
+ if (signature.length > 2000) throw new Refusal(400, 'A signature is 2000 characters at most.');
452
+ const { signature: _old, ...config } = t.config ?? {};
453
+ tethers.store().putTarget({ ...t, config: signature ? { ...config, signature } : config });
454
+ return send(200, { ok: true, signature }), true;
455
+ }
439
456
  if (pathname === '/api/shortcuts' && shortcuts) return send(201, shortcuts.add(body)), true;
440
457
  if (pathname === '/api/secrets' && secrets) { const made = secrets.set(body); setup?.secretAdded(made.name); return send(201, made), true; }
441
458
  /* Asset groups (groups.mjs): a folder-style tidy-up, not a right. */
@@ -613,6 +630,15 @@ export async function handleApi(request, response, conversations, headers, resou
613
630
  }
614
631
  const moved = /^\/api\/conversations\/([^/]+)\/work$/.exec(pathname);
615
632
  if (moved) return send(202, await conversations.moveWork(decodeURIComponent(moved[1]), body.to)), true;
633
+ /* Why its tool ended: read now in its machine when it runs, else the last kept at its end. */
634
+ const exitOf = /^\/api\/conversations\/([^/]+)\/exit-report$/.exec(pathname);
635
+ if (exitOf) {
636
+ const conversation = decodeURIComponent(exitOf[1]);
637
+ const c = conversations.list().find((x) => x.name === conversation);
638
+ if (!c) throw new Refusal(404, 'No such conversation.');
639
+ const now = await conversations.exitReport(conversation).catch(() => null);
640
+ return send(200, { now, last: c.lastExit ?? null }), true;
641
+ }
616
642
  /* "Seen": what its machine says now no longer calls its owner (health.mjs). */
617
643
  const seenOf = /^\/api\/conversations\/([^/]+)\/health\/seen$/.exec(pathname);
618
644
  if (seenOf && health) {
@@ -638,6 +664,8 @@ export async function handleApi(request, response, conversations, headers, resou
638
664
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
639
665
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
640
666
  if (naming) return send(200, conversations.setChatName(decodeURIComponent(naming[1]), body.name)), true;
667
+ const beside = /^\/api\/conversations\/([^/]+)\/tasks-binder$/.exec(pathname);
668
+ if (beside) return send(200, conversations.setTasksBinder(decodeURIComponent(beside[1]), body.binder)), true;
641
669
  /* The list: folders and order, the same on every device (conversations.mjs). */
642
670
  if (pathname === '/api/instance' && instance) return send(200, instance.setName(body.name)), true;
643
671
  if (pathname === '/api/dictation' && voice) return send(200, voice.set(body)), true;
@@ -45,7 +45,7 @@ export class Binders {
45
45
  the owner's devices (optional), told of a card a person owns that came due. */
46
46
  constructor({ dataDir, resources, conversations, dockets = null, team = null, alert = null, now = () => Date.now() }) {
47
47
  this.#resources = resources; this.#conversations = conversations; this.#dockets = dockets; this.#team = team; this.#alert = alert;
48
- this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now });
48
+ this.#keeper = keeper(`${dataDir}/binder`, { sides: () => this.#sides(), now, people: () => this.people() });
49
49
  this.#keeper.store.onChange((line) => { this.#changes++; this.#heard(line); });
50
50
  }
51
51
 
@@ -110,9 +110,12 @@ export class Binders {
110
110
  }
111
111
  /* Who may own a record, or be given a list. */
112
112
  people(identity = '') {
113
+ /* Who signed in, as the store names their ownership ('me' resolves to this). The matrix
114
+ colours a card "à moi" by matching this, so the page is told which entry is the viewer. */
115
+ const meId = `person:${identity || 'owner'}`;
113
116
  const persons = (this.#team?.list?.() ?? []).map((o) => ({ id: `person:${String(o.email ?? o.id ?? '').toLowerCase()}`, kind: 'person', name: String(o.email ?? o.id ?? '') })).filter((p) => p.name);
114
- if (!persons.length) persons.push({ id: `person:${identity || 'owner'}`, kind: 'person', name: identity || 'Owner' });
115
- return [...persons, ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
117
+ if (!persons.length) persons.push({ id: meId, kind: 'person', name: identity || 'Owner' });
118
+ return [...persons.map((p) => (p.id === meId ? { ...p, me: true } : p)), ...this.#conversations().map((name) => ({ id: `${AGENT}${name}`, kind: 'agent', name }))];
116
119
  }
117
120
  /* What each conversation was given: { name: { lists, waiting } }, waiting being the
118
121
  records of those lists that wait for a person's tick (a list with a gate, not approved). */
@@ -49,6 +49,13 @@ export const RESERVE_DISK_MAX_MB = 1024 * 1024;
49
49
  export const RESERVE_MEMORY_MAX_MB = 256 * 1024;
50
50
  export const ROOM_MS = 10_000;
51
51
  export const USAGE_MS = 5 * 60_000;
52
+ /* A sleeping machine whose qemu still holds at least this much host memory is a
53
+ suspend that did not free it (see the host program's `vm suspend`); the watch
54
+ reclaims it. */
55
+ export const RECLAIM_MIN_MB = 128;
56
+ /* The same machine is not reclaimed again within this, so a stubborn one (rare,
57
+ needs a VM-manager restart) is reported once, not looped on. */
58
+ export const RECLAIM_EVERY_MS = 30 * 60_000;
52
59
  /* The page shows its small gauge when disk or memory is fuller than this, or
53
60
  when what is free is under this many times the reserve. */
54
61
  export const HIGH_PERCENT = 85;
@@ -92,7 +99,7 @@ const percent = (part, all) => (all > 0 ? Math.round((part / all) * 100) : 0);
92
99
  export class Capacity {
93
100
  /* What the machines take on their disk, as last measured (MB), or undefined. */
94
101
  machinesUsedMb() { const u = this.#usage; if (!u) return undefined; return Object.values(u.machines ?? {}).reduce((a, b) => a + b, 0) + (u.shelf ?? 0) + (u.images ?? 0); }
95
- #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
102
+ #run; #store; #conversations; #shelf; #now; #roomMs; #sleep; #alert; #say; #reclaim; #reclaimEveryMs; #sweeping = false; #short = { disk: false, memory: false }; #room = null; #roomAt = -Infinity; #usage = null; #usageAt = -Infinity; #going = null; #measuring = null;
96
103
 
97
104
  /* `run(argv)`: the host program. `store`: where the reserve is kept.
98
105
  `conversations`: what each machine was given. `shelf`: how large a
@@ -100,8 +107,8 @@ export class Capacity {
100
107
  /* `roomMs`: how long what is free is taken as known (ROOM_MS). */
101
108
  /* `sleep(name)`, `alert(payload)`, `say(name, text)`: what watch() does
102
109
  when what is free falls under the reserve. */
103
- constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null }) {
104
- this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say;
110
+ constructor({ run, store, conversations, shelf = null, now = () => Date.now(), roomMs = ROOM_MS, sleep = null, alert = null, say = null, reclaim = null, reclaimEveryMs = RECLAIM_EVERY_MS }) {
111
+ this.#roomMs = roomMs; this.#sleep = sleep; this.#alert = alert; this.#say = say; this.#reclaim = reclaim; this.#reclaimEveryMs = reclaimEveryMs;
105
112
  this.#run = run; this.#store = store; this.#conversations = conversations; this.#shelf = shelf; this.#now = now;
106
113
  }
107
114
 
@@ -288,9 +295,53 @@ export class Capacity {
288
295
  return done;
289
296
  }
290
297
 
298
+ /* WATCHED too, and on its own: machines that are ASLEEP (not awake) yet whose
299
+ qemu still holds the host RAM -- a suspend that did not end the process,
300
+ including ones left stuck before this ran. Each is freed through the host
301
+ program (`vm reclaim`: wake+resleep, then a clean stop if needed), the owner
302
+ told, and not tried again within reclaimEveryMs, so a stubborn one (rare,
303
+ the VM manager would need a restart) is reported once, not looped on. Only
304
+ asleep machines are touched; the others are never disturbed, and the VM
305
+ manager is never restarted. Resolves with what was reclaimed. */
306
+ async reclaimSleepers() {
307
+ if (!this.#reclaim || this.#sweeping) return [];
308
+ this.#sweeping = true;
309
+ try {
310
+ const f = this.#figures(await this.room({ fresh: true }).catch(() => null));
311
+ if (!f) return [];
312
+ const awake = new Set(this.#conversations.awake?.() ?? []);
313
+ const holding = f.machines.filter((m) => m.name && !m.shelf && !awake.has(m.name) && m.rssMb >= RECLAIM_MIN_MB);
314
+ if (!holding.length) return [];
315
+ const now = this.#now();
316
+ const at = this.#store.get('reclaim')?.at ?? {};
317
+ const done = [];
318
+ for (const m of holding) {
319
+ if (at[m.name] && now - at[m.name] < this.#reclaimEveryMs) continue;
320
+ at[m.name] = now;
321
+ this.#store.put({ name: 'reclaim', at });
322
+ const held = m.rssMb;
323
+ const how = await Promise.resolve(this.#reclaim(m.name)).then((x) => String(x || ''), () => '');
324
+ const by = how.includes('resleep') ? ' by waking it and putting it back to sleep'
325
+ : how.includes('stop') ? ' with a clean stop (it will boot when you open it)'
326
+ : '';
327
+ const after = this.#figures(await this.room({ fresh: true }).catch(() => null));
328
+ const freed = !after?.machines.some((x) => x.name === m.name && !awake.has(x.name) && x.rssMb >= RECLAIM_MIN_MB);
329
+ this.#alert?.(freed
330
+ ? { title: "Reclaimed a sleeping machine's memory", body: `${m.name} was asleep but still held ${gb(held)} (its sleep had not freed it); its memory was reclaimed${by}.`, url: '/?open=settings&at=resources' }
331
+ : { title: 'A sleeping machine still holds memory', body: `${m.name} was asleep but still held ${gb(held)} and could not be freed; the VM manager may need a restart.`, url: '/?open=settings&at=resources' });
332
+ this.#say?.(m.name, freed
333
+ ? `This machine was asleep but still held ${gb(held)} of memory (its sleep had not freed it). Its memory was reclaimed${by}; it still wakes when you open it.`
334
+ : `This machine was asleep but still held ${gb(held)} of memory, and it could not be freed automatically — the VM manager may need a restart.`);
335
+ done.push({ name: m.name, heldMb: held, freed });
336
+ }
337
+ return done;
338
+ } finally { this.#sweeping = false; }
339
+ }
340
+
291
341
  /* Watches every `everyMs`; returns what stops it. */
292
342
  start(everyMs = WATCH_MS) {
293
- const timer = setInterval(() => { void this.watch().catch(() => {}); }, everyMs);
343
+ const tick = () => { void this.watch().catch(() => {}).finally(() => { void this.reclaimSleepers().catch(() => {}); }); };
344
+ const timer = setInterval(tick, everyMs);
294
345
  timer.unref?.();
295
346
  return () => clearInterval(timer);
296
347
  }
@@ -608,6 +608,18 @@ export class Conversations {
608
608
  return this.#store.get(name);
609
609
  }
610
610
 
611
+ /* WHICH BINDER ITS CHAT SHOWS BESIDE IT (the side panel), the same on every device:
612
+ '' for the automatic choice (the first binder of batches it was given), '-' for none,
613
+ else a binder's id. Which binders it was given is Binder's: one it no longer has
614
+ falls back to the automatic choice on the page. */
615
+ setTasksBinder(name, given) {
616
+ const c = this.#store.get(name);
617
+ if (!c) throw new Refusal(404, 'No such conversation.');
618
+ if (typeof given !== 'string' || given.length > 100 || !/^(|-|[a-z0-9][a-z0-9._-]*)$/.test(given)) throw new Refusal(400, 'Give a binder\'s id, "-" for none, or nothing for the automatic choice.');
619
+ this.#store.patch(name, { tasksBinder: given || undefined });
620
+ return this.#store.get(name);
621
+ }
622
+
611
623
  /* THE NAME A PERSON READS, changed at any time; its identifier stays.
612
624
  Kept only when it differs from the identifier: a conversation made
613
625
  before free names is read by its identifier, and nothing is rewritten. */
@@ -1024,6 +1036,11 @@ export class Conversations {
1024
1036
  const alive = await this.#vms.exec(name, ['tmux', '-L', SOCKET, 'has-session', '-t', `=${SESSION}`]);
1025
1037
  /* true: the tool is still there, only the channel to it dropped. */
1026
1038
  if (alive.code === 0) return true;
1039
+ /* Before its machine stops (and its kernel's memory of the night with it): why the tool
1040
+ ended, kept on the conversation and said -- a person without access to the server
1041
+ sees it in Machine, and is told at once when it was cut for lack of memory. */
1042
+ const report = await this.exitReport(name).catch(() => null);
1043
+ if (report) { this.#store.patch(name, { lastExit: report }); try { this.onToolExit?.(name, report); } catch { /* telling is best effort */ } }
1027
1044
  this.#cancelStop(name);
1028
1045
  const timer = setTimeout(() => {
1029
1046
  this.#timers.delete(name);
@@ -1034,6 +1051,28 @@ export class Conversations {
1034
1051
  return false;
1035
1052
  }
1036
1053
 
1054
+ /* WHY ITS TOOL ENDED, read inside the machine while it still runs: the kernel's kills for
1055
+ lack of memory since it started (with the program's name), its memory, and the last
1056
+ lines of the tool's own log (`logs` in config/tools.json). Read as the machine's
1057
+ ordinary user; dmesg through sudo when it may. Nothing is changed. */
1058
+ async exitReport(name) {
1059
+ const c = this.#store.get(name);
1060
+ if (!c) throw new Refusal(404, 'No such conversation.');
1061
+ if (await this.#vms.state(name) !== 'Running') throw new Refusal(409, 'Its machine is not running.');
1062
+ const tool = this.#tools.find((t) => t.id === c.tool);
1063
+ const logs = Array.isArray(tool?.logs) ? tool.logs.filter((d) => /^[A-Za-z0-9._/-]+$/.test(d)) : [];
1064
+ const script = [
1065
+ '( sudo -n dmesg -T 2>/dev/null || dmesg -T 2>/dev/null ) | grep -E "Killed process|Out of memory|Memory cgroup out of memory" | tail -n 4 | sed "s/^/oom /"',
1066
+ 'awk \'/^MemTotal:/{print "memory", int($2/1024)}\' /proc/meminfo',
1067
+ 'for d in "$@"; do f=$(ls -t "$HOME/$d"/*.log 2>/dev/null | head -1); [ -n "$f" ] && { echo "logfile $f"; tail -n 25 "$f" | cut -c1-300 | sed "s/^/log /"; }; done; true',
1068
+ ].join('\n');
1069
+ const r = await this.#vms.exec(name, ['bash', '-c', script, 'report', ...logs], { timeoutMs: 20_000 });
1070
+ const lines = String(r.stdout ?? '').split('\n');
1071
+ const pick = (p) => lines.filter((l) => l.startsWith(`${p} `)).map((l) => l.slice(p.length + 1));
1072
+ const memoryMb = Number(pick('memory')[0]) || null;
1073
+ return { at: new Date().toISOString(), oom: pick('oom'), memoryMb, logFile: pick('logfile')[0] ?? null, log: pick('log') };
1074
+ }
1075
+
1037
1076
  /* ONE FILE OF THE MACHINE'S OWN DISK, read for the person who asked to
1038
1077
  see it (a path on their screen, clicked). Only under /work, only a
1039
1078
  plain path, only a regular file of a modest size; read as the
@@ -696,7 +696,11 @@ export class GitKeeper {
696
696
  /* Its machine did not run them: tried again later, when it may. */
697
697
  if (checks.status !== 'unavailable') held.done.set(b, tip.id);
698
698
  const why = checks.status === 'failed' ? `the checks failed in the machine of ${conversation}` : checks.status === 'none' ? 'automatic sending needs passing checks, and none is set (no pre-push hook, no check command)' : `the checks could not run: the machine of ${conversation} does not run`;
699
- return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent` } : {}) }), false;
699
+ /* On a failure the agent is given the END OF THE CHECK OUTPUT, not only
700
+ that it failed: it is the one that can fix it, and guessing without the
701
+ output wastes its time. */
702
+ const tail = String(checks.output ?? '').trim();
703
+ return once(`checks-${checks.status}`, { what: `Not sent: ${why}.`, tell: true, ...(checks.status === 'failed' ? { ai: `the checks failed for ${plain(b)}, it was not sent${tail ? `. The end of the output:\n\n${tail}` : ''}` } : {}) }), false;
700
704
  }
701
705
  }
702
706
  const checked = s.checks ? 'checks passed' : 'no checks asked for';
package/server/main.mjs CHANGED
@@ -411,7 +411,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
411
411
  /* Connecting a mailbox, calendar or address book by token: the consent happens
412
412
  in the owner's browser, the refresh token is kept host-only (never in a
413
413
  machine) and a Tether target is made for it: see accounts.mjs. */
414
- const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() } });
414
+ const accounts = new Accounts({ secrets, targets: { put: (spec) => tethers.store().putTarget(spec), all: () => tethers.store().targets() }, probe: (target, password) => tethers.probe(target, password) });
415
+ /* A calendar target made before it needed the account address (Google CalDAV
416
+ puts it in the URL) carries none. The same account's mailbox or address book
417
+ has it -- they share the one refresh token -- so fill it in from a sibling,
418
+ once, with no reconnection asked of anyone. */
419
+ (() => {
420
+ const store = tethers.store();
421
+ for (const t of store.targets()) {
422
+ if (t.kind !== 'calendar' || t.config?.user || !t.secrets?.refresh) continue;
423
+ const sib = store.targets().find((o) => o.secrets?.refresh === t.secrets.refresh && o.config?.user);
424
+ if (sib) store.putTarget({ ...t, config: { ...t.config, user: sib.config.user } });
425
+ }
426
+ })();
415
427
  /* A repository's origin kept up to date, checks run in the machine, and
416
428
  automatic sending to the branches the owner listed: see gitkeeper.mjs. */
417
429
  /* What could not be read is told to the agents that write in the repository, where they can act. */
@@ -458,6 +470,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
458
470
  alert: (payload) => { void alerts.tell(payload); } });
459
471
  /* Its machine restarted or built again: said in its chat, and the tool told to read it again. */
460
472
  all.renewed = (name, text, running) => talk.renewed(name, text, running);
473
+ /* A Tether call waiting for the owner is said in its conversation's thread, with Accept / Refuse. */
474
+ tethers.announce = (name, event) => { try { return talk.event(name, event); } catch { return null; } };
461
475
  /* A device given a conversation that talks through the app talks there too. */
462
476
  door.talk = talk;
463
477
  /* AFTER AN UPDATE, the machines that run get the new tools at once (parley, docket: they serve from
@@ -512,8 +526,19 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
512
526
  const capacity = new Capacity({ run: asHost, store: new Store(`${dataDir}/server.json`), conversations: all, shelf, ...(serverRoomMs === undefined ? {} : { roomMs: serverRoomMs }),
513
527
  /* Under the reserve: the machine that takes the most put to sleep, the owner told, and its chat. */
514
528
  sleep: (name) => { events.add({ kind: 'machine', text: `Machine of ${name} put to sleep: this server was short of room`, conversation: name }); return all.sleep(name); }, alert: (payload) => { events.add({ kind: 'server', text: `${payload.title}: ${payload.body ?? ''}`.trim() }); void alerts.tell(payload); },
529
+ /* A machine asleep but still holding its RAM (a suspend that did not free it): its memory reclaimed, only that machine touched. */
530
+ reclaim: (name) => { events.add({ kind: 'machine', text: `Machine of ${name}: memory reclaimed (it was asleep but still held RAM)`, conversation: name }); return vms.reclaim(name).then((r) => (r.stdout || '').trim()); },
515
531
  say: (name, text) => { try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ } } });
516
532
  all.room = (ask) => capacity.check(ask);
533
+ /* A tool that ended cut for lack of memory: said in the events, to the owner, and in its chat. */
534
+ all.onToolExit = (name, report) => {
535
+ if (!report?.oom?.length) return;
536
+ const size = report.memoryMb ? ` (${Math.round(report.memoryMb / 1024 * 10) / 10} GB)` : '';
537
+ const text = `Its tool was stopped: the machine ran out of memory${size}. Give it more in Settings → Machine → Memory, or start it fresh.`;
538
+ events.add({ kind: 'machine', text: `Machine of ${name}: its tool was stopped for lack of memory${size}`, conversation: name });
539
+ void alerts.tell({ title: `${name}: its tool ran out of memory`, body: text, url: `/?c=${encodeURIComponent(name)}&open=settings` });
540
+ try { talk.event(name, { kind: 'machine-problem', text, tone: 'warn', topic: 'Machine' }); } catch { /* its chat may be off */ }
541
+ };
517
542
  const stopWatch = capacity.start();
518
543
  /* The curves of the resources (history.mjs): one look a minute, from what the server knows already. */
519
544
  const history = new History({ file: `${dataDir}/history.json` });