hivedesk 1.0.0 → 1.0.2

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +143 -111
  2. package/README.md +307 -303
  3. package/desktop/controller.js +85 -7
  4. package/desktop/native.js +4 -1
  5. package/desktop/release-notes/1.0.1.json +12 -0
  6. package/desktop/release-notes/1.0.2.json +12 -0
  7. package/desktop/scripts/package.mjs +11 -0
  8. package/desktop/shell.html +5 -2
  9. package/desktop/workarea.js +440 -0
  10. package/i18n/README.pt-BR.md +308 -304
  11. package/i18n/de.json +247 -4
  12. package/i18n/en.json +247 -4
  13. package/i18n/es.json +247 -4
  14. package/i18n/fr.json +247 -4
  15. package/i18n/it.json +247 -4
  16. package/i18n/ja.json +247 -4
  17. package/i18n/ko.json +247 -4
  18. package/i18n/parts/downloads.de.json +29 -0
  19. package/i18n/parts/downloads.en.json +29 -0
  20. package/i18n/parts/downloads.es.json +29 -0
  21. package/i18n/parts/downloads.fr.json +29 -0
  22. package/i18n/parts/downloads.it.json +29 -0
  23. package/i18n/parts/downloads.ja.json +29 -0
  24. package/i18n/parts/downloads.ko.json +29 -0
  25. package/i18n/parts/downloads.pt-BR.json +29 -0
  26. package/i18n/parts/downloads.ru.json +29 -0
  27. package/i18n/parts/downloads.zh-CN.json +29 -0
  28. package/i18n/parts/office.de.json +184 -0
  29. package/i18n/parts/office.en.json +184 -0
  30. package/i18n/parts/office.es.json +184 -0
  31. package/i18n/parts/office.fr.json +184 -0
  32. package/i18n/parts/office.it.json +184 -0
  33. package/i18n/parts/office.ja.json +184 -0
  34. package/i18n/parts/office.ko.json +184 -0
  35. package/i18n/parts/office.pt-BR.json +184 -0
  36. package/i18n/parts/office.ru.json +184 -0
  37. package/i18n/parts/office.zh-CN.json +184 -0
  38. package/i18n/pt-BR.json +247 -4
  39. package/i18n/ru.json +247 -4
  40. package/i18n/zh-CN.json +247 -4
  41. package/package.json +3 -2
  42. package/src/brain/manager.js +23 -7
  43. package/src/brain/models.js +146 -30
  44. package/src/brain/runtime.js +61 -13
  45. package/src/crew/domains/flow.js +2 -1
  46. package/src/crew/engine.js +172 -22
  47. package/src/crew/legacy.js +72 -0
  48. package/src/crew/planner.js +14 -1
  49. package/src/crew/talk.js +110 -3
  50. package/src/crew/taskgraph.js +12 -2
  51. package/src/crew/worker.js +60 -2
  52. package/src/index.js +4 -1
  53. package/src/p2p/doctor.js +4 -1
  54. package/src/phone/hub.js +15 -3
  55. package/src/phone/port.js +1 -1
  56. package/src/replay/reduce.js +1 -0
  57. package/src/tools/check.js +2 -0
  58. package/src/voice/index.js +1 -1
  59. package/src/voice/piper.js +10 -4
  60. package/src/voice/store.js +2 -1
  61. package/src/voice/whisper.js +63 -25
  62. package/ui/city/activity.js +4 -1
  63. package/ui/city/city.js +5 -5
  64. package/ui/city/scene.js +2 -1
  65. package/ui/css/hive.css +20 -0
  66. package/ui/js/dock.js +2 -2
  67. package/ui/js/dom.js +23 -18
  68. package/ui/js/i18n.js +12 -0
  69. package/ui/js/main.js +43 -3
  70. package/ui/js/md.js +130 -0
  71. package/ui/js/net.js +6 -0
  72. package/ui/js/palette.js +2 -2
  73. package/ui/js/store.js +20 -2
  74. package/ui/js/topbar.js +2 -2
  75. package/ui/js/voice/index.js +3 -2
  76. package/ui/js/widgets/brief.js +28 -10
  77. package/ui/js/widgets/chat.js +16 -4
  78. package/ui/js/widgets/files.js +3 -3
  79. package/ui/js/widgets/memory.js +3 -3
  80. package/ui/js/widgets/replay.js +3 -3
  81. package/ui/js/widgets/settings.js +2 -2
  82. package/ui/js/widgets/timeline.js +2 -2
  83. package/ui/js/widgets/worker.js +17 -6
  84. package/ui/models/index.js +3 -2
  85. package/ui/models/window.js +2 -2
  86. package/ui/office/office.js +145 -106
  87. package/ui/office/popout.js +4 -3
  88. package/ui/office/scene.js +47 -28
  89. package/ui/phone/core/client.js +11 -5
  90. package/ui/phone/desktop.js +2 -1
  91. package/ui/widget.html +8 -8
  92. package/ui/widget.js +35 -20
  93. package/ui/workbench/searchview.js +3 -3
@@ -1,7 +1,7 @@
1
1
  // One worker doing one task: a loop of model turns, each producing exactly one JSON action.
2
2
  import { TOOLS, actionSchema } from '../tools/index.js';
3
3
  import { checkWorkspace } from '../tools/check.js';
4
- import { assembleTaskPrompt } from './prompts/index.js';
4
+ import { assembleTaskPrompt, estimateTokens, FAMILY } from './prompts/index.js';
5
5
 
6
6
  export const MAX_TURNS = 10;
7
7
  const HISTORY_PAIRS = 6;
@@ -133,6 +133,53 @@ function capResult(tool, text) {
133
133
  return s.length > cap ? s.slice(0, cap) + `\n[cut, ${s.length - cap} more chars]` : s;
134
134
  }
135
135
 
136
+ /**
137
+ * For a top level path that does not exist: the one existing file with the same name inside a folder
138
+ * (www/index.html for index.html), or null.
139
+ * @param {string} target @param {{ exists: (p: string) => boolean, list: () => Array<{ path: string }> }} ws
140
+ */
141
+ export function folderTwin(target, ws) {
142
+ if (!target || target.includes('/') || ws.exists(target)) return null;
143
+ const same = ws.list().map((f) => f.path).filter((p) => p.includes('/') && p.split('/').pop() === target && !/^(test|tests|node_modules)\//.test(p));
144
+ return same.length === 1 ? same[0] : null;
145
+ }
146
+
147
+ /**
148
+ * Keeps a worker's turn inside the model's context: an older read of a file that is read again later is
149
+ * shortened (the newer copy is the one that counts), then the oldest steps go and the longest results are
150
+ * cut until the prompt and the reply fit. A local model on a 6 GB card is reloaded with a longer context
151
+ * (and slows down to about 1 token per second) when a turn does not fit, so this matters for speed too.
152
+ * @param {Array<{ role: string, content: string }>} messages system, first user message, then assistant/user pairs
153
+ * @param {number} limit the prompt tokens allowed
154
+ * @returns {Array<{ role: string, content: string }>}
155
+ */
156
+ export function fitHistory(messages, limit) {
157
+ const out = messages.map((m) => ({ ...m }));
158
+ const readAt = new Map();
159
+ for (let i = 2; i < out.length - 1; i += 2) {
160
+ let a = null;
161
+ try { a = JSON.parse(out[i].content); } catch { /* not an action */ }
162
+ // Only a read that really returned the file counts (a repeated read gets "you already did this").
163
+ if (a?.tool !== 'read_file' || typeof a.args?.path !== 'string' || !String(out[i + 1].content).startsWith('Result:')) continue;
164
+ const prev = readAt.get(a.args.path);
165
+ if (prev !== undefined && out[prev].content.length > 200) out[prev].content = `[the content of ${a.args.path} is shown again further down]`;
166
+ readAt.set(a.args.path, i + 1);
167
+ }
168
+ const cost = () => out.reduce((n, m) => n + estimateTokens(m.content) + 4, 0);
169
+ // The oldest pairs go first; the last two steps always stay.
170
+ while (cost() > limit && out.length > 6) out.splice(2, 2);
171
+ for (let guard = 0; cost() > limit && guard < 20; guard++) {
172
+ let longest = -1;
173
+ for (let i = 3; i < out.length; i += 2) if (longest === -1 || out[i].content.length > out[longest].content.length) longest = i;
174
+ if (longest === -1 || out[longest].content.length < 400) break;
175
+ const over = Math.ceil((cost() - limit) * 3.5) + 100;
176
+ const keep = Math.max(300, out[longest].content.length - over);
177
+ out[longest].content = `${out[longest].content.slice(0, keep)}
178
+ [cut to fit the context]`;
179
+ }
180
+ return out;
181
+ }
182
+
136
183
  /**
137
184
  * Runs a task to the end.
138
185
  * @param {{
@@ -202,7 +249,11 @@ export async function runTask(ctx) {
202
249
  let result;
203
250
  try {
204
251
  if (hint) messages[messages.length - 1] = { ...messages[messages.length - 1], content: `${messages[messages.length - 1].content}\n\n${hint}` };
205
- result = await scheduler.turn({ workerId: worker.id, taskId: task.id, jobId: job.id, messages, options: { schema, maxTokens: ctx.family === 'cloud' ? 4096 : 2000, temperature: 0.2 }, budget: assembled.budget, signal });
252
+ // The reply budget the prompt was assembled for, and the history trimmed to fit next to it.
253
+ const fam = FAMILY[ctx.family] || FAMILY.small;
254
+ const maxTokens = ctx.family === 'cloud' ? 4096 : fam.replyTokens;
255
+ const fitted = ctx.family === 'cloud' ? messages : fitHistory(messages, (ctx.contextTokens || fam.contextTokens) - maxTokens - 100);
256
+ result = await scheduler.turn({ workerId: worker.id, taskId: task.id, jobId: job.id, messages: fitted, options: { schema, maxTokens, temperature: 0.2 }, budget: assembled.budget, signal });
206
257
  hint = '';
207
258
  } catch (err) {
208
259
  if (signal?.aborted) throw err;
@@ -272,6 +323,13 @@ export async function runTask(ctx) {
272
323
  steps.push({ action, result: `Error: ${target} already exists and you have not read it. Read it first with read_file, then change it with a small edit_file.` });
273
324
  continue;
274
325
  }
326
+ // A new top level file next to a project file of the same name in a folder (index.html when the
327
+ // skeleton has www/index.html): the model forgot the folder, so it is told which file to change.
328
+ const twin = ['edit_file', 'write_file', 'read_file'].includes(action.tool) ? folderTwin(target, toolbox.ws) : null;
329
+ if (twin) {
330
+ steps.push({ action, result: `Error: there is no ${target} at the top of the project; the project's file is ${twin}. Read ${twin} with read_file, then change ${twin}.` });
331
+ continue;
332
+ }
275
333
  bus.emit('worker.status', { workerId: worker.id, status: 'tool', detail: `${action.tool}${action.args?.path ? ' ' + action.args.path : ''}`, taskId: task.id }, jobOpt);
276
334
  const out = await toolbox.execute(action.tool, action.args, {
277
335
  jobId: job.id, taskId: task.id, workerId: worker.id, allowed: worker.tools,
package/src/index.js CHANGED
@@ -207,7 +207,10 @@ export async function startHive(opts) {
207
207
  let phone = null;
208
208
  if (fs.existsSync(path.join(PACKAGE_ROOT, 'src', 'phone', 'index.js'))) {
209
209
  try {
210
- phone = await (await import('./phone/index.js')).default({ bus, server: { route: server.route, command: server.command }, home, p2p, hostName: () => opts.name || os.hostname(), run: (type, data) => server.runCommand(type, data, null, { kind: 'user' }) });
210
+ // The name the phone shows for this computer: --name, the profile name, the OS host name, then "hivedesk".
211
+ const { hostLabel } = await import('./phone/hub.js');
212
+ const hostName = () => hostLabel(opts.name, profile?.store?.profile?.name, os.hostname());
213
+ phone = await (await import('./phone/index.js')).default({ bus, server: { route: server.route, command: server.command }, home, p2p, hostName, run: (type, data) => server.runCommand(type, data, null, { kind: 'user' }) });
211
214
  } catch (err) { log(`phone remote failed to load: ${err.message}`); }
212
215
  }
213
216
 
package/src/p2p/doctor.js CHANGED
@@ -121,7 +121,10 @@ export function probeBroker(url, { timeoutMs = 4000, tlsOptions = {} } = {}) {
121
121
  socket.destroy();
122
122
  resolve({ url, ok, ms: Date.now() - started, detail });
123
123
  };
124
- const socket = tls.connect({ host: u.hostname, port: Number(u.port) || 443, servername: u.hostname, ...tlsOptions }, () => {
124
+ // SNI takes a host name only: an IP address as the server name is deprecated (DEP0123) and ignored.
125
+ const host = u.hostname.replace(/^\[|\]$/g, '');
126
+ const sni = net.isIP(host) ? {} : { servername: host };
127
+ const socket = tls.connect({ host, port: Number(u.port) || 443, ...sni, ...tlsOptions }, () => {
125
128
  const key = crypto.randomBytes(16).toString('base64');
126
129
  socket.write(`GET ${u.pathname || '/'} HTTP/1.1\r\nHost: ${u.host}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Protocol: mqtt\r\n\r\n`);
127
130
  });
package/src/phone/hub.js CHANGED
@@ -13,7 +13,7 @@ import path from 'node:path';
13
13
  import crypto from 'node:crypto';
14
14
  import { PhoneStore, loadHostKey, publicRecord } from './store.js';
15
15
  import { statusView, chatView, approvalCard, feedItem, noticeOf, SNAPSHOT_EVENTS } from './view.js';
16
- import { PairHost, KnownHost, PhoneHandshakeError, failMessage, parseHs } from '../../ui/phone/core/handshake.js';
16
+ import { PairHost, KnownHost, PhoneHandshakeError, failMessage, parseHs, cleanName } from '../../ui/phone/core/handshake.js';
17
17
  import { FrameSession } from '../../ui/phone/core/session.js';
18
18
  import { b64u, fromB64u, randomBytes } from '../../ui/phone/core/crypto.js';
19
19
  import { inviteLink, deriveInvite, homeTopic, homeSeal, INVITE_MS, PAGE_URL } from '../../ui/phone/core/invite.js';
@@ -55,6 +55,15 @@ const userOnly = (origin) => {
55
55
  if (!origin || origin.kind !== 'user') throw new PhoneError('forbidden', 'only the person at this computer can do that');
56
56
  };
57
57
 
58
+ /** The computer's name for the phones: the first usable name in the list, else "hivedesk". */
59
+ export function hostLabel(...names) {
60
+ for (const n of names) {
61
+ const s = typeof n === 'string' ? cleanName(n, '') : '';
62
+ if (s) return s;
63
+ }
64
+ return 'hivedesk';
65
+ }
66
+
58
67
  export class PhoneHub extends EventEmitter {
59
68
  /**
60
69
  * @param {{ home: string, run: (type: string, data: object) => Promise<any>, state: () => any,
@@ -67,7 +76,9 @@ export class PhoneHub extends EventEmitter {
67
76
  this.run = o.run;
68
77
  this.getState = o.state;
69
78
  this.auditFn = o.audit || (() => null);
70
- this.hostName = o.hostName || (() => 'hivedesk');
79
+ const hostName = o.hostName || (() => null);
80
+ // Every name the phones see goes through here: never null, empty or hidden characters.
81
+ this.hostName = () => { try { return hostLabel(hostName()); } catch { return 'hivedesk'; } };
71
82
  this.peerId = o.peerId || (() => null);
72
83
  this.now = o.now || (() => Date.now());
73
84
  this.inviteMs = o.inviteMs ?? INVITE_MS;
@@ -457,7 +468,8 @@ export class PhoneHub extends EventEmitter {
457
468
  }
458
469
  case 'chat.send': {
459
470
  const channel = a.channel === undefined || a.channel === 'general' ? 'general' : `dm:${worker(String(a.channel).replace(/^dm:/, ''))}`;
460
- return this.run('chat.send', { channel, text: str(a.text, 2000, 'text') });
471
+ // phone.crew also lets the phone start jobs (job.create): a request typed in the chat starts one too, in the phone's language.
472
+ return this.run('chat.send', { channel, text: str(a.text, 2000, 'text'), jobs: true, ...(typeof a.lang === 'string' && /^[a-zA-Z-]{2,10}$/.test(a.lang) ? { lang: a.lang } : {}) });
461
473
  }
462
474
  case 'chat.log':
463
475
  return chatView(state, typeof a.channel === 'string' ? a.channel : 'general');
package/src/phone/port.js CHANGED
@@ -84,7 +84,7 @@ export function createPhonePort(hub, o = {}) {
84
84
  },
85
85
  peer(deviceId) {
86
86
  const p = hub.store?.get(deviceId);
87
- return p ? { peerId: p.deviceId, name: p.name, words: p.words, publicKey: p.publicKey, trust: 'known', kind: 'phone' } : null;
87
+ return p ? { peerId: p.deviceId, name: p.name || 'Phone', words: p.words, publicKey: p.publicKey, trust: 'known', kind: 'phone' } : null;
88
88
  },
89
89
  send(sessionId, stream, type, body) {
90
90
  const rec = live(sessionId);
@@ -234,6 +234,7 @@ export function reduce(state, event) {
234
234
  if (d.i18n) m.i18n = d.i18n;
235
235
  if (d.choices) m.choices = d.choices;
236
236
  if (d.replyTo) m.replyTo = d.replyTo;
237
+ if (event.jobId) m.jobId = event.jobId;
237
238
  // The question card this line announces (src/crew/domains/, docs/1.0/DOMAINS.md).
238
239
  if (d.question) m.question = String(d.question).slice(0, 80);
239
240
  state.chat[ch].push(m);
@@ -46,6 +46,8 @@ export function checkHtml(file, html, exists) {
46
46
  while ((m = refRe.exec(html))) {
47
47
  const ref = m[1].trim();
48
48
  if (!ref || /^(https?:|mailto:|tel:|data:|javascript:|\/\/)/i.test(ref)) continue;
49
+ // The Neutralinojs client library is put in place by the neu CLI (neu update), not written by the crew.
50
+ if (/(^|\/)neutralino\.js$/i.test(ref)) continue;
49
51
  const target = path.posix.normalize(path.posix.join(path.posix.dirname(file), ref.replace(/^\//, '')));
50
52
  if (exists && !exists(target) && !exists(target.replace(/\/$/, '') + '/index.html')) issues.push(`${file}: links to ${ref}, which does not exist`);
51
53
  }
@@ -128,7 +128,7 @@ export function createVoiceEngine(o) {
128
128
  o.bus.emit('voice.installed', { id: p.id, kind: p.kind });
129
129
  o.bus.live('voice.download', { id: p.id, received: p.bytes, total: p.bytes, done: true });
130
130
  })
131
- .catch((err) => o.bus.live('voice.download', { id: p.id, error: String(err.message || err), code: err.code || 'failed' }))
131
+ .catch((err) => o.bus.live('voice.download', { id: p.id, error: String(err.message || err), code: err.code || 'failed', ...(err.hint ? { hint: err.hint } : {}), ...(err.status ? { status: err.status } : {}), ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}) }))
132
132
  .finally(() => downloads.delete(p.id));
133
133
  return { id: p.id, downloading: true };
134
134
  }
@@ -5,6 +5,7 @@ import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import { spawn } from 'node:child_process';
7
7
  import { pcmToWav } from './wav.js';
8
+ import { startError, relativeTo } from './whisper.js';
8
9
 
9
10
  export const MAX_TTS_CHARS = 600;
10
11
 
@@ -21,11 +22,16 @@ export function piperSpeak(o) {
21
22
  const text = String(o.text || '').replace(/\s+/g, ' ').trim().slice(0, MAX_TTS_CHARS);
22
23
  if (!text) return Promise.reject(Object.assign(new Error('nothing to say'), { code: 'bad_request' }));
23
24
  const rate = o.rate || voiceRate(o.config);
24
- const args = ['-m', o.model, '-c', o.config, '--output_raw', '-q'];
25
+ // Piper, like whisper.cpp, reads ANSI arguments on Windows: paths relative to the voice folder keep
26
+ // accented user folders out of them (its espeak-ng data too, found next to the program).
27
+ const cwd = path.dirname(o.model);
28
+ const args = ['-m', relativeTo(cwd, o.model), '-c', relativeTo(cwd, o.config), '--output_raw', '-q'];
29
+ const espeak = path.join(path.dirname(o.binary), 'espeak-ng-data');
30
+ if (fs.existsSync(espeak)) args.push('--espeak_data', relativeTo(cwd, espeak));
25
31
  if (o.lengthScale && Number.isFinite(o.lengthScale)) args.push('--length_scale', String(Math.min(2, Math.max(0.5, o.lengthScale))));
26
32
  return new Promise((resolve, reject) => {
27
33
  const sp = o.spawnImpl || spawn;
28
- const child = sp(o.binary, args, { cwd: path.dirname(o.binary), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
34
+ const child = sp(o.binary, args, { cwd, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
29
35
  const chunks = [];
30
36
  let err = '';
31
37
  const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, o.timeoutMs || 30000);
@@ -33,13 +39,13 @@ export function piperSpeak(o) {
33
39
  o.signal?.addEventListener('abort', onAbort, { once: true });
34
40
  child.stdout.on('data', (c) => chunks.push(c));
35
41
  child.stderr?.on('data', (c) => { err = (err + c).slice(-1500); });
36
- child.on('error', (e) => { clearTimeout(timer); reject(Object.assign(new Error(`piper: ${e.message}`), { code: 'tts_failed' })); });
42
+ child.on('error', (e) => { clearTimeout(timer); reject(Object.assign(new Error(`piper: ${startError(-1, '', e, o.binary).message}`), { code: e.code === 'ENOENT' ? 'tts_missing' : 'tts_failed' })); });
37
43
  child.on('close', (code) => {
38
44
  clearTimeout(timer);
39
45
  o.signal?.removeEventListener('abort', onAbort);
40
46
  const pcm = Buffer.concat(chunks);
41
47
  if (o.signal?.aborted) return reject(Object.assign(new Error('stopped'), { code: 'aborted' }));
42
- if (code !== 0 || !pcm.length) return reject(Object.assign(new Error(`piper: ${err.trim().split(/\r?\n/).pop() || `exit ${code}`}`), { code: 'tts_failed' }));
48
+ if (code !== 0 || !pcm.length) return reject(Object.assign(new Error(`piper: ${code !== 0 ? startError(code, err, null, o.binary).message.replace(/^whisper-server stopped: /, '') : err.trim().split(/\r?\n/).pop() || 'no audio'}`), { code: 'tts_failed' }));
43
49
  resolve(pcmToWav(pcm.length % 2 ? pcm.subarray(0, pcm.length - 1) : pcm, rate));
44
50
  });
45
51
  child.stdin.end(`${text}\n`);
@@ -83,7 +83,8 @@ export class VoiceStore {
83
83
  if (pkg.binary) {
84
84
  await (opts.untar || untar)(file, dir);
85
85
  fs.rmSync(file, { force: true });
86
- if (!this.binaryOf(pkg)) throw Object.assign(new Error(`${pkg.binary} was not found in ${pkg.file}`), { code: 'install_failed' });
86
+ // An antivirus that quarantines the program right after unpacking leaves no file behind.
87
+ if (!this.binaryOf(pkg)) throw Object.assign(new Error(`${pkg.binary} is missing after unpacking ${pkg.file}; an antivirus may have quarantined it.`), { code: 'quarantined', hint: 'Allow the hivedesk folder in the antivirus, then press Retry.' });
87
88
  if (process.platform !== 'win32') { try { fs.chmodSync(this.binaryOf(pkg), 0o755); } catch { /* read only */ } }
88
89
  }
89
90
  return dir;
@@ -40,6 +40,29 @@ export function cleanTranscript(text) {
40
40
  .trim();
41
41
  }
42
42
 
43
+ /** A path as seen from a working folder: relative (plain ASCII here) when it is inside it, else as it is. */
44
+ export function relativeTo(cwd, file) {
45
+ const r = path.relative(cwd, file);
46
+ return r && !path.isAbsolute(r) ? r : file;
47
+ }
48
+
49
+ /**
50
+ * Why whisper-server could not start, in words: gone (an antivirus quarantine), blocked, a missing DLL,
51
+ * a processor without the instructions of the build, a taken port, a bad model file. Never only an exit code.
52
+ */
53
+ export function startError(code, tail, spawnErr, binary) {
54
+ const err = (c, message, extra) => Object.assign(new Error(message), { code: c, ...extra });
55
+ const last = String(tail || '').split(/\r?\n/).filter(Boolean).slice(-2).join(' ');
56
+ if (spawnErr?.code === 'ENOENT') return err('stt_missing', `The speech program is missing (${binary}); an antivirus may have quarantined it.`);
57
+ if (spawnErr) return err('stt_blocked', `Windows or an antivirus blocked the speech program from starting (${spawnErr.code || spawnErr.message}).`);
58
+ if (/bind|address already in use|EADDRINUSE/i.test(last)) return err('stt_failed', `whisper-server could not use its port: ${last}`, { portInUse: true });
59
+ const u = Number(code) >>> 0;
60
+ if (u === 0xC0000135 || u === 0xC0000139 || u === 0xC000007B) return err('stt_start', `The speech program could not start: a system library (DLL) it needs is missing (0x${u.toString(16).toUpperCase()}).`);
61
+ if (u === 0xC000001D) return err('stt_start', 'The speech program could not start: this processor lacks an instruction the build needs.');
62
+ if (/failed to (load|read|open|initialize)|invalid model|bad magic/i.test(last)) return err('stt_model', `whisper-server could not read the speech model: ${last}`);
63
+ return err('stt_failed', `whisper-server stopped: ${last || `exit ${code}`}`);
64
+ }
65
+
43
66
  export class WhisperServer {
44
67
  /**
45
68
  * @param {{ binary: string, model: string, gpu?: boolean, threads?: number, idleMs?: number, spawnImpl?: typeof spawn, fetchImpl?: typeof fetch, log?: (s: string) => void }} o
@@ -62,38 +85,53 @@ export class WhisperServer {
62
85
 
63
86
  async start() {
64
87
  if (this.ready) return this.ready;
88
+ // A port taken between the probe and the bind (another program got there first): another port, twice at most.
65
89
  this.ready = (async () => {
66
- this.port = await freePort();
67
- const args = ['-m', this.o.model, '--host', '127.0.0.1', '--port', String(this.port), '-t', String(this.o.threads), '-l', 'auto', '-nt', '-sns'];
68
- if (!this.o.gpu) args.push('-ng');
69
- const sp = this.o.spawnImpl || spawn;
70
- const child = sp(this.o.binary, args, { cwd: path.dirname(this.o.binary), windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
71
- this.child = child;
72
- let tail = '';
73
- const onData = (c) => { tail = (tail + c).slice(-3000); };
74
- child.stdout?.on('data', onData);
75
- child.stderr?.on('data', onData);
76
- const exited = new Promise((resolve) => child.on('exit', (code) => resolve(code)));
77
- child.on('error', (err) => { tail += String(err.message); });
78
- exited.then(() => { if (this.child === child) { this.child = null; this.ready = null; } });
79
- const f = this.o.fetchImpl || fetch;
80
- const deadline = Date.now() + 60000;
81
- while (Date.now() < deadline) {
82
- const code = await Promise.race([exited, new Promise((r) => setTimeout(() => r(undefined), 250))]);
83
- if (code !== undefined) throw Object.assign(new Error(`whisper-server stopped: ${tail.split(/\r?\n/).filter(Boolean).slice(-2).join(' ') || `exit ${code}`}`), { code: 'stt_failed' });
84
- try {
85
- // The server answers only after the model is loaded.
86
- const r = await f(`http://127.0.0.1:${this.port}/health`, { signal: AbortSignal.timeout(1000) });
87
- if (r.status) return;
88
- } catch { /* not up yet */ }
90
+ for (let attempt = 0; ; attempt++) {
91
+ try { return await this._launch(); } catch (err) { if (!err.portInUse || attempt >= 2) throw err; }
89
92
  }
90
- this.stop();
91
- throw Object.assign(new Error('whisper-server did not start within a minute'), { code: 'stt_failed' });
92
93
  })();
93
94
  try { await this.ready; } catch (err) { this.ready = null; throw err; }
94
95
  return this.ready;
95
96
  }
96
97
 
98
+ async _launch() {
99
+ this.port = await freePort();
100
+ // No shell, so spaces stay inside one argument. whisper.cpp reads its arguments in the ANSI code page on
101
+ // Windows, so a user folder like C:UsersJosé turns into garbage: the model is passed relative to the
102
+ // working folder, which Windows sets from the full Unicode path.
103
+ const cwd = path.dirname(this.o.model);
104
+ const args = ['-m', relativeTo(cwd, this.o.model), '--host', '127.0.0.1', '--port', String(this.port), '-t', String(this.o.threads), '-l', 'auto', '-nt', '-sns'];
105
+ if (!this.o.gpu) args.push('-ng');
106
+ const sp = this.o.spawnImpl || spawn;
107
+ const child = sp(this.o.binary, args, { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
108
+ this.child = child;
109
+ let tail = '';
110
+ let spawnErr = null;
111
+ const onData = (c) => { tail = (tail + c).slice(-3000); };
112
+ child.stdout?.on('data', onData);
113
+ child.stderr?.on('data', onData);
114
+ // A program that cannot start (gone, blocked) emits error and maybe no exit: both end the wait.
115
+ const exited = new Promise((resolve) => {
116
+ child.on('exit', (code) => resolve(code));
117
+ child.on('error', (err) => { spawnErr = err; resolve(-1); });
118
+ });
119
+ exited.then(() => { if (this.child === child) this.child = null; });
120
+ const f = this.o.fetchImpl || fetch;
121
+ const deadline = Date.now() + 60000;
122
+ while (Date.now() < deadline) {
123
+ const code = await Promise.race([exited, new Promise((r) => setTimeout(() => r(undefined), 250))]);
124
+ if (code !== undefined) throw startError(code, tail, spawnErr, this.o.binary);
125
+ try {
126
+ // The server answers only after the model is loaded.
127
+ const r = await f(`http://127.0.0.1:${this.port}/health`, { signal: AbortSignal.timeout(1000) });
128
+ if (r.status) return;
129
+ } catch { /* not up yet */ }
130
+ }
131
+ this.stop();
132
+ throw Object.assign(new Error('whisper-server did not start within a minute'), { code: 'stt_failed' });
133
+ }
134
+
97
135
  /**
98
136
  * One turn of speech to text, one at a time.
99
137
  * @param {Buffer} wav 16 kHz mono 16 bit
@@ -5,9 +5,12 @@
5
5
  // Lines carry an i18n key and its parameters (`key`, `p`), so the UI renders them in any language
6
6
  // and the export can use the English text it is given.
7
7
 
8
+ import { mdLine } from '../js/md.js';
9
+
8
10
  export const KINDS = ['task', 'job', 'peer', 'grant', 'approval', 'file', 'git', 'agent', 'city'];
9
11
 
10
- const short = (s, n = 160) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n - 1)}...` : t; };
12
+ // One line each: model text loses its markdown marks (ui/js/md.js).
13
+ const short = (s, n = 160) => { const t = mdLine(String(s ?? '')); return t.length > n ? `${t.slice(0, n - 1)}...` : t; };
11
14
 
12
15
  /**
13
16
  * One activity entry for an event, or null.
package/ui/city/city.js CHANGED
@@ -7,7 +7,7 @@ import { h, clear, append, reducedMotion } from '/js/dom.js';
7
7
  import * as net from '/js/net.js';
8
8
  import * as wm from '/js/wm.js';
9
9
  import * as menu from '/js/menu.js';
10
- import { S, ui, extra, onEvent } from '/js/store.js';
10
+ import { S, ui, extra, onEvent, roleName } from '/js/store.js';
11
11
  import { t, onLocale, fmtNumber, locale } from '/js/i18n.js';
12
12
  import { notify } from '/js/notify.js';
13
13
  import { beeAvatar } from '/js/bees.js';
@@ -553,7 +553,7 @@ function noteMenu(id) {
553
553
  return [
554
554
  { header: x.title },
555
555
  { label: tr('city.tp.open'), icon: 'plan', action: () => openTask(id) },
556
- { label: tr('city.menu.handTo'), icon: 'hire', disabled: off, items: Object.values(st.view.agents).map((a) => ({ label: `${a.name} (${a.role})`, iconEl: beeAvatar(avatarOf(a), 18, { ring: false }), action: () => cmd('city.task.assign', { taskId: id, agentId: a.id }).catch(() => {}) })) },
556
+ { label: tr('city.menu.handTo'), icon: 'hire', disabled: off, items: Object.values(st.view.agents).map((a) => ({ label: `${a.name} (${roleName(a.role)})`, iconEl: beeAvatar(avatarOf(a), 18, { ring: false }), action: () => cmd('city.task.assign', { taskId: id, agentId: a.id }).catch(() => {}) })) },
557
557
  { label: tr('city.menu.sendTo'), icon: 'arrow', disabled: off, items: Object.keys(st.view.rooms).map((k) => ({ label: roomName(k), action: () => cmd('city.task.move', { taskId: id, room: k }).catch(() => {}) })) },
558
558
  { sep: true },
559
559
  { label: tr('city.task.approve'), icon: 'check', disabled: !x.awaiting, action: () => cmd('city.task.approve', { taskId: id }).catch(() => {}) },
@@ -765,7 +765,7 @@ function syncHits(sc) {
765
765
  b.style.height = `${Math.round(hit.h)}px`;
766
766
  }
767
767
  const a = st.view.agents[hit.id];
768
- const label = a ? `${a.name}, ${a.role}, ${tr('city.card.level', { n: a.level })}. ${tr(`city.agent.status.${a.status}`)}. ${roomName(a.room)}.` : hit.id;
768
+ const label = a ? `${a.name}, ${roleName(a.role)}, ${tr('city.card.level', { n: a.level })}. ${tr(`city.agent.status.${a.status}`)}. ${roomName(a.room)}.` : hit.id;
769
769
  if (b._label !== label) { b._label = label; b.setAttribute('aria-label', label); }
770
770
  }
771
771
  for (const [id, b] of bees) if (!seen.has(id)) { b.remove(); bees.delete(id); }
@@ -789,7 +789,7 @@ function agentMenu(id) {
789
789
  const a = st.view.agents[id];
790
790
  if (!a) return null;
791
791
  return [
792
- { header: `${a.name} · ${a.role} · ${tr('city.card.level', { n: a.level })}` },
792
+ { header: `${a.name} · ${roleName(a.role)} · ${tr('city.card.level', { n: a.level })}` },
793
793
  { label: tr('city.card.open'), icon: 'hire', action: () => openSide({ kind: 'agent', id }) },
794
794
  { label: tr('city.card.moveTo'), icon: 'arrow', items: Object.keys(st.view.rooms).map((k) => ({ label: roomName(k), checked: a.room === k, action: () => cmd('city.agent.move', { agentId: id, room: k }).catch(() => {}) })) },
795
795
  { label: tr('city.card.chat'), icon: 'chat', action: () => chatWith(a) },
@@ -889,7 +889,7 @@ function agentCard(id) {
889
889
  h('div', { class: 'ct-av', style: `--c:${a.color}` }, beeAvatar(avatarOf(a), 58, { ring: true, status: a.status === 'working' ? 'thinking' : undefined })),
890
890
  h('div', { class: 'ct-agent-n' },
891
891
  h('strong', { text: a.name }),
892
- h('div', { class: 'ct-faint', text: a.role }),
892
+ h('div', { class: 'ct-faint', text: roleName(a.role) }),
893
893
  h('div', { class: 'ct-lvrow' }, h('span', { class: 'ct-lv', text: tr('city.card.level', { n: lv }) }),
894
894
  h('div', { class: 'of-xp ct-xp', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(Math.round(xpProgress(a) * 100)) }, h('i', { style: `width:${Math.round(xpProgress(a) * 100)}%` }), h('b'))),
895
895
  h('div', { class: 'ct-faint tiny', text: tr('city.card.xp', { xp: fmtNumber(a.xp), left: fmtNumber(Math.max(0, next - a.xp)), next: lv + 1 }) }))),
package/ui/city/scene.js CHANGED
@@ -9,6 +9,7 @@
9
9
  // the last QA verdict. Colors come from the theme tokens through ui/js/art.js.
10
10
 
11
11
  import { beeSvg } from '/js/bees.js';
12
+ import { mdLine } from '/js/md.js';
12
13
  import {
13
14
  nightFactor, goldenFactor, roundRect, hexPath, hexScreen, wrap, drawNameTag, drawBubble, drawPill,
14
15
  iconCheck, drawNoteIcon, drawParcel,
@@ -1762,7 +1763,7 @@ export class CityScene {
1762
1763
  if (a.bubble && A >= 20) {
1763
1764
  const age = now - a.bubble.at;
1764
1765
  ctx.globalAlpha = Math.min(clamp(age / 0.2), clamp((a.bubble.until - now) / 0.25)) * a.alpha;
1765
- drawBubble(ctx, a.sx, headY, a.bubble.text, clamp(A * 0.4, 10.5, 12.5), this.w, a.ag.color);
1766
+ drawBubble(ctx, a.sx, headY, mdLine(a.bubble.text, 140), clamp(A * 0.4, 10.5, 12.5), this.w, a.ag.color);
1766
1767
  }
1767
1768
  ctx.globalAlpha = 1;
1768
1769
  }
package/ui/css/hive.css CHANGED
@@ -343,6 +343,26 @@ button { font: inherit; color: inherit; }
343
343
  .msg-b .ic { font-family: var(--font-mono); font-size: var(--fs-12); padding: 1px 5px; border-radius: var(--r-sm); background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--honey-2); }
344
344
  .msg-b .cb { margin: 6px 0 2px; padding: 9px 11px; border-radius: var(--r-ctl); background: var(--bg-2); border: 1px solid var(--line); font-size: var(--fs-12); overflow: auto; color: var(--text-2); }
345
345
  .msg-b strong { color: var(--text); }
346
+ /* Safe markdown (ui/js/md.js): model text in chats, the last turn, briefs, reports, tasks and Activity. */
347
+ .md { min-width: 0; overflow-wrap: anywhere; }
348
+ .md > :first-child { margin-top: 0; }
349
+ .md > :last-child { margin-bottom: 0; }
350
+ .md p { margin: 0 0 6px; }
351
+ .md ul, .md ol { margin: 2px 0 6px; padding-left: 20px; }
352
+ .md li { margin: 1px 0; }
353
+ .md li::marker { color: var(--faint); }
354
+ .md .md-h { margin: 8px 0 4px; font-size: var(--fs-13); font-weight: var(--fw-semi); color: var(--text); line-height: 1.4; }
355
+ .md h4.md-h { font-size: var(--fs-14, 14px); }
356
+ .md strong { color: var(--text); font-weight: var(--fw-semi); }
357
+ .md a { color: var(--honey-2); text-decoration: underline; text-underline-offset: 2px; }
358
+ .md blockquote { margin: 4px 0; padding: 2px 10px; border-left: 2px solid var(--line); color: var(--muted-t); }
359
+ .md hr { border: 0; border-top: 1px solid var(--line); margin: 8px 0; }
360
+ .md .ic { font-family: var(--font-mono); font-size: var(--fs-12); padding: 1px 5px; border-radius: var(--r-sm); background: color-mix(in srgb, var(--text) 7%, transparent); color: var(--honey-2); }
361
+ .md .md-code { position: relative; margin: 6px 0 4px; }
362
+ .md .cb { margin: 0; padding: 9px 11px; border-radius: var(--r-ctl); background: var(--bg-2); border: 1px solid var(--line); font-size: var(--fs-12); overflow: auto; color: var(--text-2); white-space: pre; font-family: var(--font-mono); }
363
+ .md .md-copy { position: absolute; top: 5px; right: 5px; opacity: .75; }
364
+ .md .md-code:hover .md-copy, .md .md-copy:focus-visible { opacity: 1; }
365
+ .stream .md-turn { padding: 9px 11px; max-height: 260px; overflow: auto; font-size: var(--fs-12); line-height: 1.55; color: var(--text-2); }
346
366
  .msg.cont { padding-top: 1px; }
347
367
  .msg.cont .bee-av, .msg.cont .msg-h { visibility: hidden; height: 0; }
348
368
  .msg.cont .bee-av { height: 0; }
package/ui/js/dock.js CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { h, icon, clear } from './dom.js';
5
5
  import { beeAvatar } from './bees.js';
6
- import { S, rev, ui, worker } from './store.js';
6
+ import { S, rev, ui, worker, roleName } from './store.js';
7
7
  import * as wm from './wm.js';
8
8
  import { provide } from './menu.js';
9
9
  import { workerMenu, workerStatus } from './widgets/worker.js';
@@ -99,7 +99,7 @@ export function init(el, desktopMenu) {
99
99
  clear(crewBox);
100
100
  for (const w of s.crew) {
101
101
  const st = workerStatus(w.id);
102
- const b = dockBtn(`worker:${w.id}`, { raw: w.name, sub: () => t('dock.workerSub', { role: w.role || t('dock.worker'), status: workerStatus(w.id).label }) }, beeAvatar(w, 38, { ring: true, status: st.key }), () => wm.toggleFromDock('worker', w.id));
102
+ const b = dockBtn(`worker:${w.id}`, { raw: w.name, sub: () => t('dock.workerSub', { role: roleName(w) || t('dock.worker'), status: workerStatus(w.id).label }) }, beeAvatar(w, 38, { ring: true, status: st.key }), () => wm.toggleFromDock('worker', w.id));
103
103
  b.dataset.status = st.key;
104
104
  const unread = ui.unread[`dm:${w.id}`];
105
105
  if (unread) b.append(h('span', { class: 'badge-n', text: String(unread) }));
package/ui/js/dom.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // (see store.js) and these helpers only build nodes.
3
3
 
4
4
  import { t, fmtBytes as iBytes, fmtTime as iTime, fmtDuration as iDuration, fmtAgo } from './i18n.js';
5
+ import { mdToHtml } from './md.js';
5
6
 
6
7
  /**
7
8
  * Creates an element. `props` keys: class, text, html (trusted strings only), style,
@@ -118,25 +119,29 @@ export function copyText(text) {
118
119
 
119
120
  export function uid(p = 'u') { return `${p}${Math.random().toString(36).slice(2, 9)}`; }
120
121
 
121
- /** Very small markdown: code blocks, inline code, bold, links as text. Returns a fragment. */
122
+ /** Safe markdown (ui/js/md.js) as a fragment: model text in chats, briefs, reports, tasks and Activity. */
122
123
  export function richText(text) {
124
+ const box = mdNode(text);
123
125
  const frag = document.createDocumentFragment();
124
- const parts = String(text ?? '').split(/```(\w*)\n?([\s\S]*?)```/g);
125
- for (let i = 0; i < parts.length; i++) {
126
- if (i % 3 === 0) {
127
- const lines = parts[i].split('\n');
128
- lines.forEach((line, li) => {
129
- for (const seg of line.split(/(`[^`]+`|\*\*[^*]+\*\*)/g)) {
130
- if (!seg) continue;
131
- if (seg.startsWith('`') && seg.endsWith('`') && seg.length > 1) frag.append(h('code', { class: 'ic', text: seg.slice(1, -1) }));
132
- else if (seg.startsWith('**') && seg.endsWith('**')) frag.append(h('strong', { text: seg.slice(2, -2) }));
133
- else frag.append(seg);
134
- }
135
- if (li < lines.length - 1) frag.append(h('br'));
136
- });
137
- } else if (i % 3 === 2) {
138
- frag.append(h('pre', { class: 'cb' }, h('code', { text: parts[i].replace(/\n$/, '') })));
139
- }
140
- }
126
+ frag.append(...box.childNodes);
141
127
  return frag;
142
128
  }
129
+
130
+ /** Safe markdown in a <div class="md">: escaped first, no raw HTML, no images, http and https links only. */
131
+ export function mdNode(text, cls = '') {
132
+ return h('div', { class: `md${cls ? ` ${cls}` : ''}`, html: mdToHtml(text, { copyLabel: t('md.copy') }) });
133
+ }
134
+
135
+ // The copy button of a markdown code block, anywhere in the page.
136
+ if (typeof document !== 'undefined') {
137
+ document.addEventListener('click', (e) => {
138
+ const b = e.target?.closest?.('[data-md-copy]');
139
+ if (!b) return;
140
+ const code = b.parentElement?.querySelector('pre code');
141
+ if (!code) return;
142
+ copyText(code.textContent).then(() => {
143
+ b.textContent = t('md.copied');
144
+ setTimeout(() => { b.textContent = t('md.copy'); }, 1500);
145
+ }, () => {});
146
+ });
147
+ }
package/ui/js/i18n.js CHANGED
@@ -168,3 +168,15 @@ export function fmtKeys(kb) {
168
168
  export function fmtList(items, type = 'conjunction') {
169
169
  try { return new Intl.ListFormat(code, { style: 'long', type }).format(items); } catch { return items.join(', '); }
170
170
  }
171
+
172
+ /**
173
+ * A download, install or load failure in the user's language, from its code: what happened and what to
174
+ * do. The engine's own English line (sizes, paths, the HTTP status) stays as the detail under it.
175
+ * @param {{ code?: string, message?: string, detail?: string, hint?: string, status?: number }} d
176
+ */
177
+ export function dlError(d = {}) {
178
+ const key = `dl.err.${d.code}`;
179
+ const raw = d.message || d.detail || '';
180
+ if (d.code && has(key)) return { text: t(key, { status: d.status ?? '' }), detail: raw };
181
+ return { text: [raw, d.hint].filter(Boolean).join(' ') || t('dl.err.unknown'), detail: '' };
182
+ }