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
@@ -10,12 +10,16 @@ import { modelFamily } from './prompts/index.js';
10
10
  import { runWithOrigin, crewOrigin } from '../core/origin.js';
11
11
  import { BRIEF_SCHEMA, briefMessages, normalizeBrief, briefText, acceptanceFrom, answerBrief, isVague, REPORT_SCHEMA, reportMessages, buildReport, fallbackPrompt } from './brief.js';
12
12
  import { say, localeOf, languageName } from './say.js';
13
- import { INTENT_SCHEMA, keywordIntent, decideIntent, intentMessages, replyMessages, cleanReply } from './talk.js';
13
+ import { INTENT_SCHEMA, keywordIntent, decideIntent, intentMessages, replyMessages, cleanReply, briefReply, isStatusQuestion, isRefusal, claimsWork } from './talk.js';
14
14
  import { looksLikeGitIntent, parseRules } from '../github/intent.js';
15
15
  import { validate, extractJson } from '../brain/schema.js';
16
16
  import { startDomain, jobCrew } from './domains/flow.js';
17
+ import { tagLegacyChat } from './legacy.js';
17
18
 
18
19
  const MAX_FIX_ROUNDS = 3;
20
+ /** The buttons under the line that says a brief is ready: use it, keep the original, open the Brief window to edit. */
21
+ const BRIEF_CHOICES = ['use', 'original', 'open'].map((id) => ({ id, key: `crew.talk.choice.${id}` }));
22
+ const shortRequest = (r) => { const s = String(r || ''); return s.length > 160 ? `${s.slice(0, 157)}...` : s; };
19
23
  /** Mel stops a job that uses more model turns than this (a loop that does not converge). */
20
24
  const JOB_TURN_BUDGET = 160;
21
25
  let chatSeq = 0;
@@ -106,8 +110,11 @@ export class Hive {
106
110
  for (const w of BUILTIN) if (!have.has(w.id)) this.bus.emit('crew.hired', { worker: w });
107
111
  const known = new Set(this.state.playbooks.map((p) => p.id));
108
112
  for (const p of this.playbooks.list()) if (!known.has(p.id)) this.bus.emit('playbook.saved', { playbook: p });
113
+ // Chat lines from before 1.0 have no i18n key: give them one, so they show in the desktop language.
114
+ tagLegacyChat(this.state.chat);
109
115
  for (const j of this.state.jobs) {
110
- if (j.status === 'planning' || j.status === 'running') {
116
+ // A brief that waited for the user still waits: approving it starts the job again (_revive).
117
+ if (j.status === 'planning' || j.status === 'running' || j.status === 'refining' || (j.status === 'awaiting_brief' && !j.briefProposed)) {
111
118
  for (const id of j.taskIds) {
112
119
  const t = this.state.tasks[id];
113
120
  if (t && (t.status === 'running' || t.status === 'pending' || t.status === 'review')) this.bus.emit('task.status', { taskId: id, status: 'skipped', note: 'hivedesk stopped' }, { jobId: j.id });
@@ -245,7 +252,8 @@ export class Hive {
245
252
  /** Is this worker busy with a task or with planning in a running job? */
246
253
  _inJob(workerId) {
247
254
  for (const run of this.active.values()) {
248
- if (!run.graph) { if (workerId === 'mel') return true; continue; }
255
+ // Mel is not busy while a brief waits for the user.
256
+ if (!run.graph) { if (workerId === 'mel' && !run.briefWaiter) return true; continue; }
249
257
  if (run.graph.all().some((t) => t.status === 'running' && t.assignee === workerId)) return true;
250
258
  }
251
259
  return false;
@@ -278,6 +286,12 @@ export class Hive {
278
286
  }
279
287
 
280
288
  async _talk({ id, channel, text, who, lang, running, jobs }) {
289
+ // A brief waits for the user: "ok", "pode continuar" approve it, a change request edits it.
290
+ const waiting = jobs ? this._briefWaiting() : null;
291
+ const reply = waiting ? briefReply(text, lang) : null;
292
+ if (reply) return this._briefFromChat(waiting, reply, { channel, who, lang, text, replyTo: id });
293
+ // "cade a landingpage?": the status comes from the engine, never from the model.
294
+ if (isStatusQuestion(text)) return this._status({ channel, who, lang, replyTo: id, jobs });
281
295
  const c = await this._classify(text, who, lang);
282
296
  this.bus.live('chat.intent', { messageId: id, channel, intent: c.intent, model: c.model?.intent || null, keywords: c.keywords.intent || null });
283
297
  if (c.intent === 'request') {
@@ -302,8 +316,17 @@ export class Hive {
302
316
 
303
317
  /** The command `chat.choose`: the user picked "start as a task" or "just talk" for a message. */
304
318
  chooseChat(messageId, choice, opts = {}) {
305
- const ask = this.choices.get(messageId);
319
+ const id = String(messageId || '');
320
+ const ask = this.choices.get(id) || (id.startsWith('brief:') ? { kind: 'brief', jobId: id.slice(6), channel: 'general', who: 'mel' } : null);
306
321
  if (!ask) throw Object.assign(new Error('that choice is no longer open'), { code: 'conflict' });
322
+ if (ask.kind === 'brief') {
323
+ if (!['use', 'original'].includes(choice)) throw Object.assign(new Error('choice must be use or original'), { code: 'bad_request' });
324
+ if (opts.lang) this.setLang(opts.lang);
325
+ const job = this.state.jobs.find((j) => j.id === ask.jobId);
326
+ if (!job || !this._briefWaiting() || this._briefWaiting().id !== job.id) throw Object.assign(new Error('that choice is no longer open'), { code: 'conflict' });
327
+ this._briefFromChat(job, choice === 'use' ? 'approve' : 'original', { channel: ask.channel, who: ask.who, lang: opts.lang ? this.lang : ask.lang || job.lang || this.lang, replyTo: id });
328
+ return { jobId: job.id };
329
+ }
307
330
  if (!['task', 'chat'].includes(choice)) throw Object.assign(new Error('choice must be task or chat'), { code: 'bad_request' });
308
331
  if (opts.lang) this.setLang(opts.lang);
309
332
  this.choices.delete(messageId);
@@ -346,12 +369,97 @@ export class Hive {
346
369
  const r = await this._chatTurn(who, messages, { maxTokens: 320, temperature: 0.5, talk: true }, this.answerTimeoutMs);
347
370
  const answer = cleanReply(r.text, worker);
348
371
  if (!answer) return this.say(who, 'crew.talk.empty', {}, { lang, channel, replyTo });
372
+ // Never the generic "I am an AI and cannot create files", never a promise of work no job is doing:
373
+ // the real status from the engine instead.
374
+ if (isRefusal(answer) || claimsWork(answer)) return this._status({ channel, who, lang, replyTo });
349
375
  return this.chat(who, answer, undefined, channel, undefined, { replyTo });
350
376
  } catch (err) {
351
377
  return this.say(who, 'crew.talk.failed', { error: String(err.message || err).slice(0, 200) }, { lang, channel, replyTo });
352
378
  }
353
379
  }
354
380
 
381
+ /** The job whose brief waits for the user (live, or left waiting when hivedesk stopped). */
382
+ _briefWaiting() {
383
+ for (let i = this.state.jobs.length - 1; i >= 0; i--) {
384
+ const j = this.state.jobs[i];
385
+ if (j.status !== 'awaiting_brief') continue;
386
+ const run = this.active.get(j.id);
387
+ if (run ? run.briefWaiter : j.briefProposed) return j;
388
+ }
389
+ return null;
390
+ }
391
+
392
+ /** The user answered a waiting brief in the chat (or with the buttons under Mel's line). */
393
+ _briefFromChat(job, reply, { channel, who, lang, text, replyTo }) {
394
+ const o = { lang, channel, replyTo, jobId: job.id };
395
+ if (reply === 'cancel') {
396
+ if (this.active.has(job.id)) this.cancelJob(job.id);
397
+ else this.bus.emit('job.cancelled', { by: 'user' }, { jobId: job.id });
398
+ this._closeBriefChoices(job.id, 'cancel');
399
+ return this.say(who, 'crew.talk.brief.cancel', { request: shortRequest(job.request) }, o);
400
+ }
401
+ const use = reply === 'approve' ? 'refined' : reply === 'original' ? 'original' : 'edited';
402
+ const proposed = this.state.jobs.find((j) => j.id === job.id)?.briefProposed;
403
+ const edited = use === 'edited' ? { text: `${proposed?.text || job.request}
404
+
405
+ Change asked by the user: ${String(text || '').slice(0, 2000)}` } : {};
406
+ // Mel says it first, then the job moves on.
407
+ const said = this.say(who, `crew.talk.brief.${reply}`, { request: shortRequest(job.request) }, o);
408
+ try {
409
+ this.approveBrief(job.id, { use, ...edited });
410
+ } catch (err) {
411
+ return this.say(who, 'crew.talk.startFailed', { error: String(err.message || err).slice(0, 200) }, o);
412
+ }
413
+ return said;
414
+ }
415
+
416
+ /** Takes the brief buttons away from the chat once the brief is decided. */
417
+ _closeBriefChoices(jobId, choice) {
418
+ for (const [mid, ask] of [...this.choices]) {
419
+ if (ask.kind !== 'brief' || ask.jobId !== jobId) continue;
420
+ this.choices.delete(mid);
421
+ this.bus.emit('chat.chosen', { messageId: mid, channel: ask.channel, choice });
422
+ }
423
+ const mid = `brief:${jobId}`;
424
+ for (const [ch, list] of Object.entries(this.state.chat || {})) {
425
+ if ((list || []).some((m) => m.replyTo === mid && m.choices && !m.chosen)) this.bus.emit('chat.chosen', { messageId: mid, channel: ch, choice });
426
+ }
427
+ }
428
+
429
+ /** The job the user is most likely asking about: the one going on, else the last one. */
430
+ _currentJob() {
431
+ const jobs = this.state.jobs.filter((j) => !j.cityTaskId);
432
+ for (let i = jobs.length - 1; i >= 0; i--) if (['refining', 'awaiting_brief', 'planning', 'running'].includes(jobs[i].status)) return jobs[i];
433
+ return jobs[jobs.length - 1] || null;
434
+ }
435
+
436
+ /** "Where is the landing page?": what the job waits for, what is done and what is next, from the engine state. */
437
+ _status({ channel, who, lang, replyTo, jobs = true }) {
438
+ const job = this._currentJob();
439
+ const o = { lang, channel, replyTo };
440
+ if (!job) return this.say(who, 'crew.status.none', {}, o);
441
+ o.jobId = job.id;
442
+ const request = shortRequest(job.request);
443
+ const files = this.toolbox.ws.list().map((f) => f.path);
444
+ const fileList = files.length ? files.slice(0, 6).join(', ') + (files.length > 6 ? ` (+${files.length - 6})` : '') : say(lang, 'crew.status.noFiles');
445
+ if (job.status === 'awaiting_brief') {
446
+ if (jobs && this._briefWaiting()?.id === job.id) o.choices = this._offer(replyTo, { kind: 'brief', jobId: job.id, channel, who, lang }, ['use', 'original', 'open']);
447
+ return this.say(who, 'crew.status.brief', { request }, o);
448
+ }
449
+ if (job.status === 'refining') return this.say(who, 'crew.status.refining', { request }, o);
450
+ if (job.status === 'planning') return this.say(who, 'crew.status.planning', { request }, o);
451
+ if (job.status === 'running') {
452
+ const tasks = (job.taskIds || []).map((id) => this.state.tasks[id]).filter(Boolean);
453
+ const done = tasks.filter((t) => t.status === 'done').length;
454
+ const now = tasks.find((t) => t.status === 'running') || tasks.find((t) => t.status === 'pending');
455
+ const name = now ? this.crewById().get(now.assignee)?.name || now.assignee : '';
456
+ return this.say(who, 'crew.status.running', { request, done, count: tasks.length, now: now ? `${name}: ${now.title}` : '-', files: fileList }, o);
457
+ }
458
+ if (job.status === 'done') return this.say(who, 'crew.status.done', { request, files: fileList }, o);
459
+ if (job.status === 'failed') return this.say(who, 'crew.status.failed', { request, error: String(job.error || '').slice(0, 200) }, o);
460
+ return this.say(who, 'crew.status.cancelled', { request }, o);
461
+ }
462
+
355
463
  // ---- jobs ----
356
464
  /**
357
465
  * @param {{ request: string, approval?: boolean, playbookId?: string }} spec
@@ -386,8 +494,14 @@ export class Hive {
386
494
  this.active.set(jobId, run);
387
495
  const created = this.bus.emit('job.created', { job }, { jobId });
388
496
  // Everything the job does from here is the crew's doing, caused by job.created (src/core/origin.js).
389
- run.promise = runWithOrigin(crewOrigin('mel'), () => (plan ? this._runPlanned(job, run, plan) : this._runJob(job, run, spec.playbookId)), created.seq).catch((err) => {
390
- if (ctrl.signal.aborted) return;
497
+ this._launch(jobId, run, () => (plan ? this._runPlanned(job, run, plan) : this._runJob(job, run, spec.playbookId)), created.seq);
498
+ return { jobId, done: run.promise };
499
+ }
500
+
501
+ /** Runs a job's work as the crew, failing the job on an error and putting busy workers back to idle. */
502
+ _launch(jobId, run, fn, cause) {
503
+ run.promise = runWithOrigin(crewOrigin('mel'), fn, cause).catch((err) => {
504
+ if (run.ctrl.signal.aborted) return;
391
505
  this.bus.emit('job.failed', { error: String(err?.message || err) }, { jobId });
392
506
  }).finally(() => {
393
507
  this.active.delete(jobId);
@@ -397,7 +511,15 @@ export class Hive {
397
511
  }
398
512
  }
399
513
  });
400
- return { jobId, done: run.promise };
514
+ }
515
+
516
+ /** A job whose brief waited when hivedesk stopped: the user's decision on it starts it again from the brief. */
517
+ _revive(job, decision) {
518
+ const copy = { ...job, refine: true, taskIds: [...(job.taskIds || [])] };
519
+ const run = { ctrl: new AbortController(), notes: new Map(), promise: null, preDecision: decision };
520
+ this.active.set(job.id, run);
521
+ this._launch(job.id, run, () => this._runJob(copy, run));
522
+ return run;
401
523
  }
402
524
 
403
525
  _busyElsewhere(workerId) {
@@ -434,7 +556,7 @@ export class Hive {
434
556
  const crewById = this.crewById();
435
557
  // 1. The prompt refiner: Mel turns the request into a brief, the user approves, edits or keeps the original.
436
558
  if (job.refine) {
437
- this._jobSay(job, 'mel', 'crew.say.onItBrief', { request: job.request }, undefined, run.replyTo);
559
+ if (!run.preDecision) this._jobSay(job, 'mel', 'crew.say.onItBrief', { request: job.request }, undefined, run.replyTo);
438
560
  await this._refine(job, run);
439
561
  if (signal.aborted) return;
440
562
  } else {
@@ -469,7 +591,7 @@ export class Hive {
469
591
  const files = this.toolbox.ws.list().map((f) => f.path);
470
592
  const lead = job.lead ? crewById.get(job.lead) : null;
471
593
  const leadNote = lead ? [`The user asked ${lead.name} (${lead.role}) directly: ${lead.name} leads this job, so give the main work to ${lead.id}.`] : [];
472
- const plan = await makePlan({ scheduler: this.scheduler, request: work, crew, playbook, files, merge: modelFamily(this.state.brain) === 'small', notes: [...dom.notes, ...leadNote, ...run.memories.map((m) => `memory: ${m}`), ...this.memory.crew(4)], jobId, signal, domain: dom.domain });
594
+ const plan = await makePlan({ scheduler: this.scheduler, request: work, crew, playbook, files, merge: modelFamily(this.state.brain) !== 'cloud', notes: [...dom.notes, ...leadNote, ...run.memories.map((m) => `memory: ${m}`), ...this.memory.crew(4)], jobId, signal, domain: dom.domain });
473
595
  if (signal.aborted) return;
474
596
  // The plan came from a remote brain: every write and run of this job now needs the host (SEC-3).
475
597
  if (plan.remote && !this.toolbox.originOf?.({ jobId })) {
@@ -700,6 +822,33 @@ export class Hive {
700
822
 
701
823
  // ---- prompt refiner ----
702
824
  async _refine(job, run) {
825
+ const jobId = job.id;
826
+ const ev = { jobId };
827
+ let brief;
828
+ let decision;
829
+ if (run.preDecision && job.briefProposed) {
830
+ // Revived after a restart: the brief was proposed before and the user just decided.
831
+ brief = { ...job.briefProposed };
832
+ decision = run.preDecision;
833
+ } else {
834
+ const r = await this._proposeBrief(job, run);
835
+ if (!r) return;
836
+ ({ brief, decision } = r);
837
+ }
838
+ if (!decision) return;
839
+ if (decision.answers && decision.use !== 'original') brief = answerBrief(brief, decision.answers);
840
+ let text = brief.text;
841
+ let source = 'refined';
842
+ if (decision.use === 'original') { text = job.request; source = 'original'; }
843
+ else if (decision.use === 'edited' && typeof decision.text === 'string' && decision.text.trim()) { text = decision.text.trim().slice(0, 8000); source = 'edited'; }
844
+ job.brief = source === 'original' ? null : text;
845
+ job.acceptance = source === 'original' ? [] : acceptanceFrom(text);
846
+ this.bus.emit('brief.approved', { brief: source === 'refined' ? brief : null, text, source, ...(decision.by ? { by: decision.by } : {}) }, ev);
847
+ this._closeBriefChoices(jobId, decision.use === 'original' ? 'original' : 'use');
848
+ }
849
+
850
+ /** Mel writes the brief and waits for the user's decision (or the auto approve). null: no brief, the job goes on with the request. */
851
+ async _proposeBrief(job, run) {
703
852
  const jobId = job.id;
704
853
  const ev = { jobId };
705
854
  this.bus.emit('job.refining', { workerId: 'mel' }, ev);
@@ -714,15 +863,18 @@ ${job.decisions}` : job.request, this.toolbox.ws.list().map((f) => f.path)),
714
863
  });
715
864
  brief = normalizeBrief(r.json, job.request);
716
865
  } catch (err) {
717
- if (run.ctrl.signal.aborted) return;
866
+ if (run.ctrl.signal.aborted) return null;
718
867
  this._jobSay(job, 'system', 'crew.say.briefFailed', { error: err.message });
719
868
  job.brief = null;
720
869
  this.bus.emit('brief.approved', { brief: null, text: job.request, source: 'original' }, ev);
721
- return;
870
+ return null;
722
871
  }
723
872
  brief.text = briefText(brief);
724
873
  this.bus.emit('brief.proposed', { original: job.request, brief, vague: isVague(job.request) }, ev);
725
- this._jobSay(job, 'mel', 'crew.say.briefReady');
874
+ // Mel waits for the user now, she is not thinking: the status says so.
875
+ if (!this.scheduler.waiting.some((i) => i.workerId === 'mel')) this.bus.emit('worker.status', { workerId: 'mel', status: 'idle' });
876
+ // The line carries the buttons, so the brief never waits unseen: use it, keep the request, open it to edit.
877
+ this.say('mel', 'crew.say.briefReady', {}, { lang: job.lang || 'en', jobId, replyTo: `brief:${jobId}`, choices: BRIEF_CHOICES });
726
878
  const decision = await new Promise((resolve, reject) => {
727
879
  run.briefWaiter = resolve;
728
880
  if (this.autoApproveBriefMs) {
@@ -732,22 +884,20 @@ ${job.decisions}` : job.request, this.toolbox.ws.list().map((f) => f.path)),
732
884
  run.ctrl.signal.addEventListener('abort', () => reject(new Error('cancelled')), { once: true });
733
885
  }).catch(() => null);
734
886
  run.briefWaiter = null;
735
- if (!decision) return;
736
- if (decision.answers && decision.use !== 'original') brief = answerBrief(brief, decision.answers);
737
- let text = brief.text;
738
- let source = 'refined';
739
- if (decision.use === 'original') { text = job.request; source = 'original'; }
740
- else if (decision.use === 'edited' && typeof decision.text === 'string' && decision.text.trim()) { text = decision.text.trim().slice(0, 8000); source = 'edited'; }
741
- job.brief = source === 'original' ? null : text;
742
- job.acceptance = source === 'original' ? [] : acceptanceFrom(text);
743
- this.bus.emit('brief.approved', { brief: source === 'refined' ? brief : null, text, source, ...(decision.by ? { by: decision.by } : {}) }, ev);
887
+ return { brief, decision };
744
888
  }
745
889
 
746
890
  /** The command `brief.approve`. */
747
891
  approveBrief(jobId, { use = 'refined', text, answers } = {}) {
892
+ if (!['refined', 'edited', 'original'].includes(use)) throw Object.assign(new Error('use must be refined, edited or original'), { code: 'bad_request' });
748
893
  const run = this.active.get(jobId);
894
+ const job = this.state.jobs.find((j) => j.id === jobId);
895
+ // A brief left waiting when hivedesk stopped: the decision starts the job again from it.
896
+ if (!run && job?.status === 'awaiting_brief' && job.briefProposed) {
897
+ this._revive(job, { use, text, answers, by: 'user' });
898
+ return {};
899
+ }
749
900
  if (!run || !run.briefWaiter) throw Object.assign(new Error('no brief is waiting for that job'), { code: 'conflict' });
750
- if (!['refined', 'edited', 'original'].includes(use)) throw Object.assign(new Error('use must be refined, edited or original'), { code: 'bad_request' });
751
901
  run.briefWaiter({ use, text, answers, by: 'user' });
752
902
  return {};
753
903
  }
@@ -0,0 +1,72 @@
1
+ // Chat lines written before 1.0 kept no i18n key, so a pt-BR desktop showed them in English
2
+ // ("On it: ... First I will write it up as a clear brief", "Job cancelled...", the old canned
3
+ // "Got it. Type a request in the top bar..."). legacyKey() finds the key and the parameters of such a
4
+ // line from the English texts, so the desktop shows it in its language like any other crew line.
5
+ import { raw } from './say.js';
6
+
7
+ // English texts that changed since they were written, and lines that no longer exist.
8
+ const OLD = {
9
+ 'crew.say.briefReady': ['Here is the brief. Use it, edit it, or keep your original request.'],
10
+ 'crew.legacy.topBar': ['Got it. Type a request in the top bar and the crew will start a job.']
11
+ };
12
+ // The crew lines that can be found in an old chat log, from their current English text.
13
+ const KEYS = [
14
+ 'crew.say.onItBrief', 'crew.say.onItPlan', 'crew.say.briefReady', 'crew.say.cancelled', 'crew.say.noModel', 'crew.say.briefFailed',
15
+ 'crew.talk.started', 'crew.talk.startedLead', 'crew.talk.startedMel', 'crew.talk.startedFlow', 'crew.talk.noted', 'crew.talk.ambiguous',
16
+ 'crew.talk.noModel', 'crew.talk.empty', 'crew.talk.hostOnly'
17
+ ];
18
+
19
+ const reEsc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+
21
+ /** A template with simple {name} parameters as a regular expression; null for plurals and selects. */
22
+ function pattern(template) {
23
+ if (!template || /\{\w+,/.test(template)) return null;
24
+ const names = [];
25
+ const src = template.split(/(\{\w+\})/).map((part) => {
26
+ const m = /^\{(\w+)\}$/.exec(part);
27
+ if (!m) return reEsc(part);
28
+ names.push(m[1]);
29
+ return '([\\s\\S]+?)';
30
+ }).join('');
31
+ return { re: new RegExp(`^${src}$`), names };
32
+ }
33
+
34
+ let table = null;
35
+ function patterns() {
36
+ if (table) return table;
37
+ table = [];
38
+ for (const key of KEYS) {
39
+ const p = pattern(raw('en', key));
40
+ if (p) table.push({ key, ...p });
41
+ }
42
+ for (const [key, texts] of Object.entries(OLD)) for (const text of texts) table.push({ key, re: new RegExp(`^${reEsc(text)}$`), names: [] });
43
+ return table;
44
+ }
45
+
46
+ /**
47
+ * The i18n key of an old English crew line, or null.
48
+ * @param {string} text
49
+ * @returns {{ key: string, params: Record<string, string> } | null}
50
+ */
51
+ export function legacyKey(text) {
52
+ const s = String(text || '').trim();
53
+ if (!s || s.length > 2000) return null;
54
+ for (const p of patterns()) {
55
+ const m = p.re.exec(s);
56
+ if (m) return { key: p.key, params: Object.fromEntries(p.names.map((n, i) => [n, m[i + 1]])) };
57
+ }
58
+ return null;
59
+ }
60
+
61
+ /** Gives the old crew lines of a chat state their i18n key (in place); returns how many were found. */
62
+ export function tagLegacyChat(chat) {
63
+ let n = 0;
64
+ for (const list of Object.values(chat || {})) {
65
+ for (const m of list || []) {
66
+ if (!m || m.i18n || m.from === 'user' || typeof m.text !== 'string') continue;
67
+ const hit = legacyKey(m.text);
68
+ if (hit) { m.i18n = hit; n++; }
69
+ }
70
+ }
71
+ return n;
72
+ }
@@ -147,6 +147,17 @@ export function mergeByWorker(tasks) {
147
147
  });
148
148
  }
149
149
 
150
+ /** Each build task waits for the build task before it (QA still waits for all of them). */
151
+ export function chainBuild(tasks) {
152
+ let prev = -1;
153
+ return tasks.map((t, i) => {
154
+ if (t.kind === 'qa') return t;
155
+ const out = prev >= 0 && !t.dependsOn.includes(prev) ? { ...t, dependsOn: [...t.dependsOn, prev].sort((a, b) => a - b) } : t;
156
+ prev = i;
157
+ return out;
158
+ });
159
+ }
160
+
150
161
  export async function makePlan({ scheduler, request, crew, playbook, files, notes, jobId, signal, merge = false, domain }) {
151
162
  const ids = crew.map((w) => w.id);
152
163
  const prefer = DOMAINS[domain]?.specialist || undefined;
@@ -158,7 +169,9 @@ export async function makePlan({ scheduler, request, crew, playbook, files, note
158
169
  options: { schema: planSchema(assignees), maxTokens: 1200, temperature: 0.2 }
159
170
  });
160
171
  let tasks = normalizePlan(result.json, ids, request, prefer);
161
- if (merge) tasks = mergeByWorker(tasks);
172
+ // One local model serves one turn at a time, so parallel build tasks only make workers edit the
173
+ // same files at once: they run one after the other.
174
+ if (merge) tasks = chainBuild(mergeByWorker(tasks));
162
175
  // A plan written by a model on another machine is untrusted: the caller marks the whole job with its origin.
163
176
  return { tasks, summary: String(result.json?.summary || '').slice(0, 400), source: 'model', ...(result.remote ? { remote: result.remote } : {}) };
164
177
  } catch (err) {
package/src/crew/talk.js CHANGED
@@ -159,7 +159,7 @@ export function replyMessages({ worker, text, lang, files = [], jobs = [], tasks
159
159
  const topic = topicOf(text);
160
160
  const jobLines = jobs.slice(-4).map((j) => {
161
161
  const list = (j.taskIds || []).map((id) => tasks[id]).filter(Boolean).map((t) => `${t.title} (${crew.find((w) => w.id === t.assignee)?.name || t.assignee}, ${t.status})`);
162
- return `- ${j.id} ${j.status}: ${String(j.request).slice(0, 200)}${list.length ? `\n tasks: ${list.slice(0, 8).join('; ')}` : ''}${j.summary ? `\n result: ${j.summary}` : ''}`;
162
+ return `- ${j.id} ${JOB_STATE[j.status] || j.status}: ${String(j.request).slice(0, 200)}${list.length ? `\n tasks: ${list.slice(0, 8).join('; ')}` : ''}${j.summary ? `\n result: ${j.summary}` : ''}`;
163
163
  });
164
164
  const past = history.slice(-6).map((m) => `${m.from === 'user' ? 'User' : crew.find((w) => w.id === m.from)?.name || m.from}: ${String(m.text).slice(0, 300)}`);
165
165
  return [
@@ -170,8 +170,9 @@ export function replyMessages({ worker, text, lang, files = [], jobs = [], tasks
170
170
  String(worker.prompt || '').slice(0, 600),
171
171
  `Reply in ${language} (${lang}) only, as ${worker.name}, in one to four short sentences of plain text. No Markdown headings, no code unless the user asks for code.`,
172
172
  ...(topic ? [`${EXPERTISE[topic]} For this technical question give the real answer an experienced engineer would give: the concrete steps, commands or API names and the main tradeoff, in up to six short sentences. Say plainly when something needs a tool or account the user may not have.`] : []),
173
- 'This reply cannot build or change files. When the user wants something built or changed, tell them to ask for it here and the crew starts a job.',
174
- 'Only talk about work that is listed below; never say a file or job exists when it is not listed.',
173
+ 'The crew writes real files in the project workspace on this computer when a job runs. Never say you are an AI, an assistant or a language model, and never say you cannot create files or sites.',
174
+ 'This reply itself does not build anything: never say you will start, continue or prepare work. When the user wants something built or changed, tell them to ask for it here and the crew starts a job.',
175
+ 'Only talk about work that is listed below; never say a file or job exists when it is not listed. A job that waits for the brief only moves when the user approves it.',
175
176
  '',
176
177
  `Files in the project workspace: ${files.length ? files.slice(0, 40).join(', ') : 'none yet'}.`,
177
178
  `Jobs: ${jobLines.length ? `\n${jobLines.join('\n')}` : 'none yet.'}`,
@@ -182,6 +183,17 @@ export function replyMessages({ worker, text, lang, files = [], jobs = [], tasks
182
183
  ];
183
184
  }
184
185
 
186
+ /** The job states in plain words for the talk prompt. */
187
+ const JOB_STATE = {
188
+ refining: 'Mel is writing the brief',
189
+ awaiting_brief: 'waiting for the user to approve the brief (the Brief window has Use the brief, Edit and Keep my request; replying "ok" here also approves it)',
190
+ planning: 'brief approved, Mel is planning the tasks',
191
+ running: 'the crew is building',
192
+ done: 'done',
193
+ failed: 'failed',
194
+ cancelled: 'cancelled'
195
+ };
196
+
185
197
  /** A model answer cleaned for the chat: no name prefix, no JSON, no endless text. */
186
198
  export function cleanReply(text, worker) {
187
199
  let s = String(text || '').trim();
@@ -190,3 +202,98 @@ export function cleanReply(text, worker) {
190
202
  if (s.length > 1500) s = `${s.slice(0, 1500).replace(/\s+\S*$/, '')}...`;
191
203
  return s;
192
204
  }
205
+
206
+ // ---- while a brief waits, status questions and answers the engine gives itself ----
207
+
208
+ const foldSet = (list) => new Set(list.map((w) => fold(w)));
209
+
210
+ // Words that confirm a waiting brief in the 10 languages (folded: lower case, no accents). A message made
211
+ // only of these and of filler words ("ok. aceito", "certo, pode continuar]", "go ahead") approves the brief.
212
+ const CONFIRM = foldSet([
213
+ 'ok', 'okay', 'okey', 'oki', 'okk', 'sim', 'yes', 'yep', 'yeah', 'yup', 'sure', 'go', 'ahead', 'aceito', 'aceita', 'aceitar', 'aprovo', 'aprovado', 'aprovada', 'aprova', 'aprovar',
214
+ 'pode', 'podem', 'continuar', 'continue', 'continua', 'continuem', 'seguir', 'segue', 'siga', 'prossiga', 'prosseguir', 'manda', 'mande', 'ver', 'fazer', 'faz', 'faca', 'facam',
215
+ 'certo', 'beleza', 'blz', 'perfeito', 'otimo', 'bom', 'boa', 'vai', 'vamos', 'fechado', 'combinado', 'show', 'massa', 'usar', 'use', 'usa', 'comecar', 'comece', 'comeca',
216
+ 'start', 'proceed', 'do', 'lets', 'fine', 'good', 'great', 'looks', 'lgtm', 'approve', 'approved', 'accept', 'accepted', 'agreed', 'alright', 'cool', 'perfect', 'nice',
217
+ 'si', 'vale', 'adelante', 'claro', 'dale', 'acepto', 'sigue', 'oui', 'accord', 'daccord', 'allez', 'parfait', 'vas', 'ja', 'jawohl', 'mach', 'weiter', 'los', 'gut', 'passt',
218
+ 'einverstanden', 'va', 'bene', 'procedi', 'avanti', 'perfetto', 'accetto', 'accordo',
219
+ 'ок', 'окей', 'да', 'давай', 'хорошо', 'продолжай', 'ладно', 'согласен', 'поехали', 'вперед'
220
+ ]);
221
+ const FILLER = foldSet([
222
+ 'o', 'a', 'os', 'as', 'e', 'de', 'do', 'da', 'pra', 'para', 'por', 'favor', 'please', 'pls', 'pfv', 'plz', 'the', 'it', 'this', 'that', 'esse', 'essa', 'isso', 'este', 'esta', 'ai',
223
+ 'brief', 'briefing', 'mel', 'agora', 'now', 'entao', 'then', 'tudo', 'all', 'bem', 'well', 'with', 'com', 'can', 'you', 'voce', 'vc', 's', 'y', 'd', 'l', 'el', 'le',
224
+ 'la', 'lo', 'il', 'es', 'est', 'c', 'so', 'just', 'on', 'gracias', 'merci', 'danke', 'grazie', 'obrigado', 'obrigada', 'valeu', 'thanks', 'thank', 'favore',
225
+ 'bitte', 'plait', 'te', 'vous', 'пожалуйста', 'mesmo', 'um', 'uma', 'me', 'nur', 'pure', 'aussi'
226
+ ]);
227
+ // Japanese, Korean and Chinese confirmations have no spaces: the whole message is compared.
228
+ const CONFIRM_CJK = ['はい', 'お願いします', 'おねがいします', '進めて', '進めてください', 'いいよ', 'いいです', 'それで', '네', '좋아요', '좋아', '진행해', '진행해주세요', '진행', '그래', '好', '好的', '可以', '继续', '开始', '开始吧', '行', '没问题', '是的', '确认'];
229
+ const ORIGINAL = /\b(?:original|meu pedido|minha mensagem|my request|my words|mi pedido|ma demande|meine anfrage|la mia richiesta)\b/;
230
+ const CANCEL = /^(?:cancela|cancele|cancelar|cancel|stop|pare|esquece|deixa pra la|annule|annuler|abbrechen|annulla|cancelalo|отмена|отмени)\b/;
231
+
232
+ /** True when the text is one or more of the phrases, back to back ("네 진행해주세요"). */
233
+ function onlyPhrases(text, phrases) {
234
+ const list = [...phrases].sort((a, b) => b.length - a.length);
235
+ let rest = text;
236
+ for (let guard = 0; rest && guard < 8; guard++) {
237
+ const p = list.find((x) => rest.startsWith(x));
238
+ if (!p) return false;
239
+ rest = rest.slice(p.length);
240
+ }
241
+ return !rest && text.length > 0;
242
+ }
243
+
244
+ /**
245
+ * What a message means for a brief that waits for the user: approve it, keep the original request,
246
+ * cancel the job, or change it (a build or change request). null: something else (a question, talk).
247
+ * @returns {'approve'|'original'|'cancel'|'edit'|null}
248
+ */
249
+ export function briefReply(text, lang = 'en') {
250
+ const original = String(text || '').trim();
251
+ const f = fold(original);
252
+ if (!f || f.includes('?')) return null;
253
+ const words = f.split(' ').filter(Boolean);
254
+ if (CANCEL.test(f) && words.length <= 4) return 'cancel';
255
+ if (ORIGINAL.test(f) && words.length <= 8) return 'original';
256
+ // fold() decomposes Hangul: compare the composed forms.
257
+ const compact = f.normalize('NFC').replace(/\s+/g, '');
258
+ if (onlyPhrases(compact, CONFIRM_CJK)) return 'approve';
259
+ if (words.length <= 8 && words.some((w) => CONFIRM.has(w)) && words.every((w) => CONFIRM.has(w) || FILLER.has(w))) return 'approve';
260
+ if (keywordIntent(original, lang).intent === 'request') return 'edit';
261
+ return null;
262
+ }
263
+
264
+ // "cade a landingpage?", "where is it", "is it ready", "o que falta": the job status, from the engine.
265
+ const STATUS = [
266
+ /^(?:e )?(?:cade|kd)\b/, /\bonde (?:esta|ta|fica|estao)\b/, /\bwhere (?:is|s|are)\b/, /^where\b/, /\b(?:esta|ta|ficou|fica) pronto\b/, /\bpronto\s*\?/,
267
+ /\b(?:terminou|acabou|terminaram|acabaram)\b/, /\bo que falta\b/, /\bque falta\b/, /\bfalta muito\b/, /\b(?:status|progresso|andamento|progress)\b/,
268
+ /\bcomo (?:esta|ta|vai) (?:o|a) (?:job|trabalho|site|pagina|projeto|landing|landingpage|tarefa|app)\b/, /\bhow (?:is|s) it going\b/, /\bwhat s left\b/, /\bwhats left\b/,
269
+ /\b(?:is it|are you) (?:done|ready|finished)\b/, /\b(?:done|ready|finished) yet\b/, /\bdonde esta\b/, /\besta listo\b/, /\bou en est\b/, /\bc est pret\b/, /\best ce pret\b/,
270
+ /\bwo ist\b/, /\bist es fertig\b/, /\bwie weit\b/, /\bdov e\b/, /\be pronto\b/, /\ba che punto\b/, /где/, /готово/, /できた/, /進捗/, /どこ/, /진행 ?상황/, /다 ?됐/, /어디/, /进度/, /好了吗/, /在哪/
271
+ ];
272
+
273
+ /** True for a question about how the work is going: answered from the engine state, not by the model. */
274
+ export function isStatusQuestion(text) {
275
+ const f = fold(text).normalize('NFC');
276
+ if (!f || f.split(' ').length > 12) return false;
277
+ return STATUS.some((re) => re.test(f));
278
+ }
279
+
280
+ // A crew answer must never be a generic assistant disclaimer: the crew writes real files when a job runs.
281
+ const REFUSAL = [
282
+ /\b(?:sou|como) (?:um |uma )?(?:assistente|modelo de linguagem|ia|inteligencia artificial)\b/, /\binteligencia artificial\b/, /\bassistente (?:virtual|de ia)\b/,
283
+ /\bas an ai\b/, /\bi (?:am|m) (?:an|just an) (?:ai|language model|assistant)\b/, /\blanguage model\b/, /\bai assistant\b/,
284
+ /\bnao (?:tenho|possuo) (?:a )?(?:capacidade|habilidade|acesso)\b/, /\bnao (?:consigo|posso) (?:criar|gerar|escrever|construir) (?:arquivos|sites|paginas|o site|a pagina)\b/,
285
+ /\bi (?:cannot|can t|can not|am unable to|m unable to|do not have the ability to|don t have the ability to) (?:create|build|make|write|generate) (?:files|websites|sites|a website|web pages)\b/,
286
+ /\bi (?:do not|don t) have (?:the ability|access to your (?:computer|files))\b/, /\bdirectly on your (?:computer|machine)\b/, /\bdiretamente (?:em|no) seu computador\b/,
287
+ /\bcomo (?:modelo|ia)\b/, /языковая модель/, /\bcomme (?:une )?ia\b/, /\bals (?:eine )?ki\b/, /\bcome (?:un )?(?:ia|assistente)\b/, /\bcomo (?:una )?ia\b/
288
+ ];
289
+ // The chat answer cannot start or continue work; a reply that says it does is replaced with the real status.
290
+ const CLAIM = [
291
+ /\b(?:vou|vamos|irei|iremos|estou|estamos) (?:comecar|continuar|criar|fazer|preparar|construir|seguir|iniciar|trabalhar|comecando|continuando|criando|fazendo|preparando|construindo|trabalhando)\b/,
292
+ /\bestamos prontos para comecar\b/, /\b(?:i ll|i will|we ll|we will|i am going to|we are going to|i m going to) (?:start|continue|begin|create|build|get started|work on|prepare|make)\b/,
293
+ /\b(?:i m|i am|we re|we are) (?:starting|continuing|creating|building|working on|preparing)\b/, /\blet s get started\b/
294
+ ];
295
+
296
+ /** A crew answer that is a generic assistant disclaimer (or says it cannot create files). */
297
+ export const isRefusal = (text) => { const f = fold(text); return REFUSAL.some((re) => re.test(f)); };
298
+ /** A crew answer that says it starts or continues work, which only a job does. */
299
+ export const claimsWork = (text) => { const f = fold(text); return CLAIM.some((re) => re.test(f)); };
@@ -32,9 +32,18 @@ export class TaskGraph {
32
32
  return t;
33
33
  }
34
34
 
35
- /** Pending tasks whose dependencies are all done. */
35
+ /**
36
+ * Pending tasks whose dependencies are all done. A QA task also runs when some of its dependencies
37
+ * failed, once they all ended and at least one is done: its review starts the fix rounds for them.
38
+ */
36
39
  ready() {
37
- return this.all().filter((t) => t.status === 'pending' && t.dependsOn.every((d) => this.tasks.get(d)?.status === 'done'));
40
+ return this.all().filter((t) => t.status === 'pending' && (t.dependsOn.every((d) => this.tasks.get(d)?.status === 'done') || this._reviewable(t)));
41
+ }
42
+
43
+ _reviewable(t) {
44
+ if (t.kind !== 'qa' || !t.dependsOn.length) return false;
45
+ const st = t.dependsOn.map((d) => this.tasks.get(d)?.status);
46
+ return st.some((s) => s === 'done') && st.every((s) => ['done', 'failed', 'blocked', 'skipped'].includes(s));
38
47
  }
39
48
 
40
49
  /**
@@ -48,6 +57,7 @@ export class TaskGraph {
48
57
  again = false;
49
58
  for (const t of this.all()) {
50
59
  if (t.status !== 'pending') continue;
60
+ if (t.kind === 'qa' && t.dependsOn.some((d) => ['done', 'pending', 'running', 'review', 'ready'].includes(this.tasks.get(d)?.status))) continue;
51
61
  if (t.dependsOn.some((d) => ['failed', 'blocked', 'skipped'].includes(this.tasks.get(d)?.status))) {
52
62
  t.status = 'blocked';
53
63
  changed.push(t);