hivedesk 0.2.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1 (security) (2026-10-17)
4
+
5
+ A security update for Code together, Lend your PC, Hive City, `--demo` and extensions. Please update.
6
+
7
+ * Guest roles are checked by the engine itself, not only by the host's browser. Every guest command carries the guest's role; a missing role counts as a viewer. A viewer can read and chat; a collaborator can also post tasks and jobs, edit files under the host's approval and bring a building into the city. Hiring agents, changing an agent's tools, rooms, settings, models and providers stay with the host.
8
+ * A building in the city can use only a model its owner lends itself. The host's own models, cloud brains and other guests' models can no longer be tied to a guest's building.
9
+ * A guest's agents join with read and check tools only. Only the host can grant more tools, and an agent from an older version that still holds write tools comes back with the safe set.
10
+ * Work that does not come from the person at this PC always waits for the host's answer, even with approval mode off: writes and saves from a guest (new files included), and every write, run or package script of a task whose model turns ran on a friend's machine. The approval card says where the action comes from, `npm run` and `npm test` show the script they would run, turning approval mode off does not approve these, and a guest cannot answer them.
11
+ * Lend your PC: Cancel now stops the model on the lender. Each pairing is a lease with a maximum duration and number of turns (60 minutes and 200 turns by default) that expires on its own. Lent turns run only on the lender's local models: never on a model the lender itself borrowed, and never on the lender's cloud keys unless the lender allows it for that pairing. A model allowlist can be set per pairing (`lend.grant`). The older `brain.chat` entry goes through the same checks, and very deep or very large remote schemas are refused.
12
+ * `--demo` runs in a temporary folder with its own home, never in a real project: a non empty `--dir` is refused, `--demo-dir <folder>` picks a folder on purpose, and a folder that holds a real hivedesk log is always refused. A demo run in a folder no longer labels later real runs as Demo.
13
+ * Extensions: each extension runs in its own sandbox process, and the engine knows which extension is calling from the process it started, not from what the process says.
14
+
3
15
  ## 0.2.0 (2026-10-17)
4
16
 
5
17
  Hive City: hivedesk becomes a small distributed system for AI agents on people's computers. The city is the new home view.
package/PROTOCOL.md CHANGED
@@ -81,7 +81,10 @@ Job { id, request, status, approval, refine, createdAt, finishedAt?, taskId
81
81
  Brief { goal, build: string[], constraints: string[], acceptance: string[], questions: [{ question, options: string[], answer }], text }
82
82
  text is the Markdown the user sees and edits; acceptance items are "- [ ] ..." lines in it.
83
83
  Report { built, files: [{ path, op, added, removed }], checks: [{ name, ok, detail }], missing: string[], turns, seconds }
84
- Approval { id, jobId, taskId, workerId, tool, args, summary, diff?, createdAt }
84
+ Approval { id, jobId, taskId, workerId, tool, args, summary, diff?, createdAt, origin?, strict?, script? }
85
+ origin: { kind: "guest" | "remote", label, id?, brainId? } the action comes from a guest or a friend's model
86
+ strict: true waits for the host whatever the approval mode; a guest cannot answer it (0.2.1)
87
+ script: { name, body } for npm test and npm run: the package.json script that would run
85
88
  Playbook { id, title, request, prompt?, keywords: string[], tasks: [{ title, detail, assignee, dependsOn: number[] , kind }], createdAt, uses }
86
89
  Message { role: "system" | "user" | "assistant", content: string }
87
90
  ```
@@ -190,7 +193,7 @@ Message { role: "system" | "user" | "assistant", content: string }
190
193
  | `brain.probe` | `{}` | `{ hardware, options: BrainOption[], recommended }` |
191
194
  | `brain.select` | `BrainChoice` | `{ status }` |
192
195
  | `brain.download` | `{ model? }` start (or retry) the automatic model download; needed only after `--no-download` or a failure | `{}` |
193
- | `brain.attach` | `{ label, model?, ctx? }` this WebSocket becomes a remote brain (section 6) | `{ brainId }` |
196
+ | `brain.attach` | `{ label, model?, ctx?, guest? }` this WebSocket becomes a remote brain (section 6); `guest` is the Code together guest id that lends it (only that guest's building may use it) | `{ brainId }` |
194
197
  | `brain.respond` | `{ requestId, ok, result?: ChatResult, error?: string }` | `{}` |
195
198
  | `brain.token` | `{ requestId, text }` optional streaming for a pending request | none (no reply) |
196
199
  | `brain.detach` | `{ brainId }` | `{}` |
@@ -322,7 +325,8 @@ scheduler.removeBrain(brainId) // emits brain.detached; a running turn on
322
325
 
323
326
  1. A client (the lend UI on the host) sends `brain.attach { label, model, ctx }` and gets `{ brainId }`.
324
327
  2. The engine adds a relay brain to the scheduler. When it gets a turn, the engine sends `brain.request` to that same WebSocket.
325
- 3. The client carries the request to the friend (WebRTC), the friend's browser sends `brain.chat` to the friend's own hivedesk started with `--lend`, and the answer goes back the same way.
328
+ 3. The client carries the request to the friend (WebRTC), the friend's browser sends `lend.chat` (or the older `brain.chat`, which goes through the same guard) to the friend's own hivedesk started with `--lend`, and the answer goes back the same way. A `cancel` frame becomes `lend.cancel { requestId }` and aborts the turn there. The friend's engine runs lent turns only on its local models (cloud keys only when the friend allows it with `lend.grant { minutes, turns, models, cloud }`) and within a lease of minutes and turns.
329
+ Tool calls of a task whose turns a remote brain answered always wait for the host's approval (`origin.kind: "remote"`).
326
330
  4. The client answers with `brain.respond { requestId, ok, result }` (it may stream `brain.token` before). Timeout: 180 s, then the turn is re-queued on another brain.
327
331
  5. `brain.detach` or closing the WebSocket removes the brain.
328
332
 
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
  <img src="assets/banner.svg" width="900" alt="hivedesk: a whole crew of AI workers, running on your own machine. A honeycomb desktop with a timeline, a crew chat, a code window and a live preview, with Mel the bee foreman.">
3
3
  </p>
4
4
 
5
- <p align="center"><b>Your own AI crew. One command away.</b></p>
5
+ <p align="center"><b>Your own AI crew. One command away.</b><br>New in 0.2.0: <a href="#hive-city-new-in-020">Hive City</a>, where your agents live, work through rooms and borrow a friend's GPU.</p>
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://kwy404.github.io/hivedesk/">Website</a> &middot;
@@ -30,6 +30,28 @@ Run `npx hivedesk` and a short wizard sets everything up: it reads your hardware
30
30
  <img src="docs/assets/shots/hive.webp" width="900" alt="The Hive in demo mode: the timeline of a bakery landing page job, the crew chat, a live preview of the page, the Files window with a diff and the Dev worker after a turn, with the worker dock at the bottom.">
31
31
  </p>
32
32
 
33
+ ## Hive City (new in 0.2.0)
34
+
35
+ <p align="center">
36
+ <img src="docs/assets/shots/city-overview.webp" width="900" alt="Hive City in demo mode: your building on a floating island with the Design, Code, Review, Test, Ops, Library and Lobby rooms, a friend's tower across a bridge, the task board and the event feed.">
37
+ </p>
38
+
39
+ <p align="center">
40
+ <img src="docs/assets/shots/city-bridge-gpu-borrow.webp" width="440" alt="Dev borrows the friend's GPU across the lit bridge; the Machines panel shows 2 of 3 turns and a Stop the borrow button.">
41
+ <img src="docs/assets/shots/city-agent-card.webp" width="440" alt="An agent card with the level, XP, tools and private memory.">
42
+ </p>
43
+
44
+ hivedesk now opens on a small city, and the city is the state of the system: every building, room, agent and task you see is an event in the same log the crew writes ([CITY-PROTOCOL.md](CITY-PROTOCOL.md)). `npx hivedesk --demo` plays the city scenario: a friend joins, her building rises, Dev borrows her GPU across the bridge, and a task goes through every room to done.
45
+
46
+ - **Agents that stay.** Each crew worker is an agent with a home room, a level and XP from finished work, tools, and a private memory you can read, edit and pin. Agents are saved per machine in `~/.hivedesk/city/agents/`, so the same Dev keeps its level in every project, and pinned facts, preferences and decisions go into its prompts.
47
+ - **Rooms with rules.** Lobby, Design, Code, Review, Test, Ops and Library. A room decides which tools an agent has while it works there (Review only reads and checks, Ops waits for your approval and is closed to guests). Extensions can add rooms.
48
+ - **A task bus.** You put a task in a room or on an agent; idle agents in that room bid for it by skill, level and machine load, and every claim and hop is an event. A task in the Lobby goes to Mel, who plans it into crew tasks. The jobs you type in the top bar work as before, and Mel's planned tasks show up on the board too.
49
+ - **Code, Review, Test, with loops.** Design writes a spec, Code runs the crew on it, another agent reviews the diff against the criteria, Test runs the checks. A failed review or test sends the task back to its author with the issues, at most 3 times, then it is blocked. You can approve or send back a task at any hop, and a room can wait for you.
50
+ - **Machines and friends.** Your PC is a building with its GPU, model and load. A friend who joins through Code together (six words, QR or link) gets a building of their own and can bring agents that think on their machine. An agent can borrow a friend's GPU for a few turns; the friend accepts, sets the limits, sees every turn and can stop it. Only prompts and answers travel, through the existing lend relay and its limits.
51
+ - **It comes back.** Close hivedesk and open it tomorrow: the same agents, levels and memories, and the tasks that were in progress open again in their room.
52
+
53
+ What it does not do yet: Test runs the static checks (HTML, links, JS syntax, CSS, JSON), not your test suite; for tasks planned by Mel the review is those checks and the crew QA report is the test, so no extra model turns are spent; a friend's agent needs that friend's model to be lent; borrowing has no standing "lend 30 percent" setting, only limits per request; the crew job can finish a moment before the city hops of its last task. `--no-city` turns the city off and keeps the 0.1 desktop.
54
+
33
55
  ## Download
34
56
 
35
57
  | | File | Size | Start |
@@ -96,7 +118,7 @@ The choice and the reason are shown in one line, for example "NVIDIA GeForce GTX
96
118
  | `--port <n>`, `--no-open` | Pick the port; do not open the browser. |
97
119
  | `--lend`, `--join <link or words>` | Lend your model to a friend, or join one (see below). |
98
120
  | `--doctor` | Check Node, the GPU, RAM, disk and the models, then exit. |
99
- | `--no-city` | Run without Hive City (0.2.0, unreleased): no agents, rooms or task bus; the rest works the same. |
121
+ | `--no-city` | Run without Hive City: no agents, rooms or task bus; the rest works the same. |
100
122
 
101
123
  `HIVEDESK_HOME` moves the cache folder `~/.hivedesk/`.
102
124
 
@@ -161,23 +183,6 @@ The default crew is **Mel** (foreman and planner), **Dev**, **Designer**, **QA**
161
183
  - **A guided tour** with Mel on the first open; replay it from Help or the command palette.
162
184
  - **Replay** any moment from the append-only event log, a <kbd>Ctrl</kbd> <kbd>K</kbd> command palette, windows that snap, and a phone layout with stacked cards.
163
185
 
164
- ## Hive City (0.2.0, not released yet)
165
-
166
- <p align="center">
167
- <img src="assets/illustrations/hive-city.svg" width="900" alt="A sketch of Hive City: your building with rooms for Design, Code, Review, Test, Ops, Library and the Lobby, a friend's building that joined with six words, and a bridge where a bee carries model turns between the machines.">
168
- </p>
169
-
170
- In the next release the Hive becomes a small city, and the city is the state of the system: every building, room, agent and task you see is an event in the same log the crew writes. The engine side is in the repository now ([CITY-PROTOCOL.md](CITY-PROTOCOL.md)); the City view in the desktop is being built on top of it. From a clone, `node src/cli.js --demo` plays the city scenario: a friend joins, her building rises, Dev borrows her GPU across the bridge, and a task goes through every room to done.
171
-
172
- - **Agents that stay.** Each crew worker is an agent with a home room, a level and XP from finished work, tools, and a private memory you can read, edit and pin. Agents are saved per machine in `~/.hivedesk/city/agents/`, so the same Dev keeps its level in every project, and pinned facts, preferences and decisions go into its prompts.
173
- - **Rooms with rules.** Lobby, Design, Code, Review, Test, Ops and Library. A room decides which tools an agent has while it works there (Review only reads and checks, Ops waits for your approval and is closed to guests). Extensions can add rooms.
174
- - **A task bus.** You put a task in a room or on an agent; idle agents in that room bid for it by skill, level and machine load, and every claim and hop is an event. A task in the Lobby goes to Mel, who plans it into crew tasks. The jobs you type in the top bar work as before, and Mel's planned tasks show up on the board too.
175
- - **Code, Review, Test, with loops.** Design writes a spec, Code runs the crew on it, another agent reviews the diff against the criteria, Test runs the checks. A failed review or test sends the task back to its author with the issues, at most 3 times, then it is blocked. You can approve or send back a task at any hop, and a room can wait for you.
176
- - **Machines and friends.** Your PC is a building with its GPU, model and load. A friend who joins through Code together (six words, QR or link) gets a building of their own and can bring agents that think on their machine. An agent can borrow a friend's GPU for a few turns; the friend accepts, sets the limits, sees every turn and can stop it. Only prompts and answers travel, through the existing lend relay and its limits.
177
- - **It comes back.** Close hivedesk and open it tomorrow: the same agents, levels and memories, and the tasks that were in progress open again in their room.
178
-
179
- What it does not do yet: Test runs the static checks (HTML, links, JS syntax, CSS, JSON), not your test suite; for tasks planned by Mel the review is those checks and the crew QA report is the test, so no extra model turns are spent; a friend's agent needs that friend's model to be lent; borrowing has no standing "lend 30 percent" setting, only limits per request; the crew job can finish a moment before the city hops of its last task. `--no-city` turns the city off.
180
-
181
186
  ## Lend your PC
182
187
 
183
188
  <p align="center">
@@ -2,7 +2,7 @@
2
2
  <img src="../assets/banner.svg" width="900" alt="hivedesk: uma equipe inteira de agentes de IA rodando na sua própria máquina. Uma área de trabalho em favo de mel com linha do tempo, chat da equipe, janela de código e prévia ao vivo, com Mel, a abelha mestre de obras.">
3
3
  </p>
4
4
 
5
- <p align="center"><b>Sua própria equipe de IA. A um comando de distância.</b></p>
5
+ <p align="center"><b>Sua própria equipe de IA. A um comando de distância.</b><br>Novo na 0.2.0: a <a href="#hive-city-novo-na-020">Hive City</a>, onde os seus agentes vivem, passam por salas e pegam emprestada a GPU de um amigo.</p>
6
6
 
7
7
  <p align="center">
8
8
  <a href="https://kwy404.github.io/hivedesk/">Site</a> &middot;
@@ -30,6 +30,28 @@ Rode `npx hivedesk` e um assistente curto prepara tudo: lê o seu hardware, inst
30
30
  <img src="../docs/assets/shots/hive.webp" width="900" alt="A Colmeia em modo demo: a linha do tempo de uma landing page para uma padaria, o chat da equipe, a prévia ao vivo, a janela de arquivos com diff e o Dev depois de um turno, com o dock da equipe embaixo.">
31
31
  </p>
32
32
 
33
+ ## Hive City (novo na 0.2.0)
34
+
35
+ <p align="center">
36
+ <img src="../docs/assets/shots/city-overview.webp" width="900" alt="A Hive City em modo demo: o seu prédio numa ilha flutuante com as salas Design, Code, Review, Test, Ops, Library e Lobby, a torre de um amigo do outro lado da ponte, o quadro de tarefas e o feed de eventos.">
37
+ </p>
38
+
39
+ <p align="center">
40
+ <img src="../docs/assets/shots/city-bridge-gpu-borrow.webp" width="440" alt="O Dev pega emprestada a GPU da amiga pela ponte acesa; o painel Machines mostra 2 de 3 turnos e o botão para parar o empréstimo.">
41
+ <img src="../docs/assets/shots/city-agent-card.webp" width="440" alt="O cartão de um agente com nível, XP, ferramentas e memória própria.">
42
+ </p>
43
+
44
+ O hivedesk agora abre numa pequena cidade, e a cidade é o estado do sistema: cada prédio, sala, agente e tarefa que você vê é um evento no mesmo log que a equipe escreve ([CITY-PROTOCOL.md](../CITY-PROTOCOL.md), em inglês). `npx hivedesk --demo` mostra o cenário: uma amiga entra, o prédio dela sobe, o Dev pega a GPU dela emprestada pela ponte e uma tarefa passa por todas as salas até o fim.
45
+
46
+ - **Agentes que ficam.** Cada membro da equipe é um agente com sala de origem, nível e XP ganhos com trabalho concluído, ferramentas e uma memória própria (até 40 entradas curtas) que você lê, edita e fixa. Eles ficam salvos por máquina em `~/.hivedesk/city/agents/`, então o mesmo Dev mantém o nível em todos os projetos.
47
+ - **Salas com regras.** Lobby, Design, Code, Review, Test, Ops e Library. Enquanto um agente trabalha numa sala, as ferramentas dele se limitam às da sala (Review só lê e confere, Ops espera a sua aprovação e é fechada para convidados). Extensões podem criar salas.
48
+ - **Um barramento de tarefas.** Você coloca uma tarefa numa sala ou num agente; agentes livres disputam por especialidade, nível e carga da máquina, e cada passo vira um evento. Uma tarefa no Lobby vai para a Mel, que a divide em tarefas da equipe.
49
+ - **Code, Review, Test, com voltas.** Design escreve a especificação, Code roda a equipe, outro agente revisa o diff contra os critérios e Test roda as verificações. Uma revisão ou teste que falha devolve a tarefa ao autor com os problemas, no máximo 3 vezes; depois ela fica bloqueada. Você pode aprovar ou devolver em qualquer etapa.
50
+ - **Máquinas e amigos.** O seu PC é um prédio com GPU, modelo e carga. Um amigo que entra pelo Code together (seis palavras, QR ou link) ganha um prédio e pode trazer agentes que pensam na máquina dele. Um agente pode pegar a GPU de um amigo emprestada por alguns turnos; o amigo aceita, define os limites, vê cada turno e pode parar. Só prompts e respostas viajam.
51
+ - **Tudo volta.** Feche o hivedesk e abra amanhã: os mesmos agentes, níveis e memórias, e as tarefas em andamento reabrem na sala delas.
52
+
53
+ O que ainda não faz: o Test roda as verificações estáticas (HTML, links, sintaxe de JS, CSS, JSON), não a sua suíte de testes; o agente de um amigo precisa do modelo desse amigo emprestado; o empréstimo não tem uma porcentagem fixa, só limites por pedido. `--no-city` desliga a cidade e mantém a área de trabalho da 0.1.
54
+
33
55
  ## Baixar
34
56
 
35
57
  | | Arquivo | Tamanho | Como abrir |
@@ -95,6 +117,7 @@ A escolha e o motivo aparecem numa linha. Mude em Settings ou com `--model 14b|7
95
117
  | `--dir <pasta>` | A pasta do projeto. Os arquivos vão para `<pasta>/.hivedesk/`. |
96
118
  | `--port <n>`, `--no-open` | Escolhe a porta; não abre o navegador. |
97
119
  | `--lend`, `--join <link ou palavras>` | Empresta o seu modelo a um amigo, ou usa o de um amigo. |
120
+ | `--no-city` | Roda sem a Hive City: sem agentes, salas ou barramento de tarefas; o resto funciona igual. |
98
121
  | `--doctor` | Confere Node, GPU, RAM, disco e modelos, e sai. |
99
122
 
100
123
  ## Sincero sobre os limites
@@ -156,19 +179,6 @@ A equipe padrão é **Mel** (mestre de obras), **Dev**, **Designer**, **QA** e *
156
179
  - **Um tour guiado** com a Mel na primeira abertura; repita pelo Help ou pela paleta de comandos.
157
180
  - **Replay** de qualquer momento a partir do log de eventos, paleta de comandos com <kbd>Ctrl</kbd> <kbd>K</kbd>, janelas que se encaixam e um layout de celular com cartões empilhados.
158
181
 
159
- ## Chega na 0.2.0: Hive City
160
-
161
- <p align="center">
162
- <img src="../assets/illustrations/hive-city.svg" width="900" alt="Um esboço da Hive City: o seu prédio com salas de Design, Code, Review, Test, Ops, Library e o Lobby, o prédio de um amigo que entrou com seis palavras, e uma ponte onde uma abelha leva turnos do modelo entre as máquinas.">
163
- </p>
164
-
165
- A próxima versão transforma a Colmeia numa pequena cidade onde os agentes vivem. Isto é o plano em construção, não algo que dá para baixar hoje:
166
-
167
- - **Agentes que ficam:** nome, especialidade, nível ganho com trabalho concluído, ferramentas e uma memória própria que você edita. Amanhã eles continuam lá, e as tarefas inacabadas retomam.
168
- - **Salas com regras:** Design, Code, Review, Test, Ops, Library e o Lobby decidem quais ferramentas valem ali e que tarefas aceitam.
169
- - **Uma esteira de tarefas:** Code, depois Review por outro agente, depois Test, voltando quando algo falha, com a sua aprovação em qualquer etapa.
170
- - **Amigos viram prédios:** um amigo entra com seis palavras e a máquina dele aparece ao lado da sua; um agente pode pegar turnos de GPU emprestados de um amigo, que vê cada pedido e pode recusar ou parar.
171
-
172
182
  ## Empreste seu PC
173
183
 
174
184
  <p align="center">
package/i18n/de.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Nichts wartet auf dich",
41
41
  "approvals.modeOff": "Freigabemodus ist aus: Die Crew handelt, ohne zu fragen.",
42
42
  "approvals.modeOn": "Freigabemodus ist an: Zerstörerische Aktionen warten auf deine Antwort.",
43
+ "approvals.origin.guest": "Von einem Gast angefragt ({name}). Nur du kannst antworten, auch wenn der Freigabemodus aus ist.",
44
+ "approvals.origin.remote": "Kommt vom Modell eines Freundes ({name}). Prüfe es vor der Freigabe; es wartet immer auf dich.",
43
45
  "approvals.reject": "Ablehnen",
44
46
  "approvals.replayOff": "Wiedergabe: Antworten ist aus.",
47
+ "approvals.script": "Führt das npm-Skript {name} aus: {body}",
48
+ "approvals.scriptMissing": "Führt das npm-Skript {name} aus, das package.json nicht hat.",
45
49
  "approvals.title": "Freigaben",
46
50
  "approvals.turnOff": "Ausschalten",
47
51
  "approvals.turnOn": "Einschalten",
package/i18n/en.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Nothing is waiting for you",
41
41
  "approvals.modeOff": "Approval mode is off: the crew acts without asking.",
42
42
  "approvals.modeOn": "Approval mode is on: destructive actions wait for your answer.",
43
+ "approvals.origin.guest": "Asked by a guest ({name}). Only you can answer it, even with approval mode off.",
44
+ "approvals.origin.remote": "Comes from a friend's model ({name}). Check it before you approve; it always waits for you.",
43
45
  "approvals.reject": "Reject",
44
46
  "approvals.replayOff": "Replay: answering is off.",
47
+ "approvals.script": "Runs the npm script {name}: {body}",
48
+ "approvals.scriptMissing": "Runs the npm script {name}, which package.json does not have.",
45
49
  "approvals.title": "Approvals",
46
50
  "approvals.turnOff": "Turn off",
47
51
  "approvals.turnOn": "Turn on",
package/i18n/es.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "No hay nada pendiente",
41
41
  "approvals.modeOff": "El modo de aprobación está desactivado: el equipo actúa sin preguntar.",
42
42
  "approvals.modeOn": "El modo de aprobación está activado: las acciones destructivas esperan tu respuesta.",
43
+ "approvals.origin.guest": "Lo pide un invitado ({name}). Solo tú puedes responder, aunque el modo de aprobación esté desactivado.",
44
+ "approvals.origin.remote": "Viene del modelo de un amigo ({name}). Revísalo antes de aprobar; siempre te espera.",
43
45
  "approvals.reject": "Rechazar",
44
46
  "approvals.replayOff": "Repetición: no se puede responder.",
47
+ "approvals.script": "Ejecuta el script npm {name}: {body}",
48
+ "approvals.scriptMissing": "Ejecuta el script npm {name}, que package.json no tiene.",
45
49
  "approvals.title": "Aprobaciones",
46
50
  "approvals.turnOff": "Desactivar",
47
51
  "approvals.turnOn": "Activar",
package/i18n/fr.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Rien ne vous attend",
41
41
  "approvals.modeOff": "Le mode approbation est désactivé : l'équipe agit sans demander.",
42
42
  "approvals.modeOn": "Le mode approbation est activé : les actions destructives attendent votre réponse.",
43
+ "approvals.origin.guest": "Demandé par un invité ({name}). Vous seul pouvez répondre, même si le mode approbation est désactivé.",
44
+ "approvals.origin.remote": "Vient du modèle d'un ami ({name}). Vérifiez avant d'approuver ; cela vous attend toujours.",
43
45
  "approvals.reject": "Refuser",
44
46
  "approvals.replayOff": "Relecture : impossible de répondre.",
47
+ "approvals.script": "Lance le script npm {name} : {body}",
48
+ "approvals.scriptMissing": "Lance le script npm {name}, absent de package.json.",
45
49
  "approvals.title": "Approbations",
46
50
  "approvals.turnOff": "Désactiver",
47
51
  "approvals.turnOn": "Activer",
package/i18n/it.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Niente in attesa",
41
41
  "approvals.modeOff": "La modalità approvazione è disattivata: la squadra agisce senza chiedere.",
42
42
  "approvals.modeOn": "La modalità approvazione è attiva: le azioni distruttive aspettano la tua risposta.",
43
+ "approvals.origin.guest": "Richiesto da un ospite ({name}). Solo tu puoi rispondere, anche con la modalità approvazione spenta.",
44
+ "approvals.origin.remote": "Viene dal modello di un amico ({name}). Controllalo prima di approvare; aspetta sempre te.",
43
45
  "approvals.reject": "Rifiuta",
44
46
  "approvals.replayOff": "Replay: le risposte sono disattivate.",
47
+ "approvals.script": "Esegue lo script npm {name}: {body}",
48
+ "approvals.scriptMissing": "Esegue lo script npm {name}, che package.json non ha.",
45
49
  "approvals.title": "Approvazioni",
46
50
  "approvals.turnOff": "Disattiva",
47
51
  "approvals.turnOn": "Attiva",
package/i18n/ja.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "対応待ちはありません",
41
41
  "approvals.modeOff": "承認モードはオフです: クルーは確認せずに作業します。",
42
42
  "approvals.modeOn": "承認モードはオンです: 取り消せない操作はあなたの回答を待ちます。",
43
+ "approvals.origin.guest": "ゲスト({name})からの依頼です。承認モードがオフでも、答えられるのはあなただけです。",
44
+ "approvals.origin.remote": "友だちのモデル({name})から来ています。承認の前に確認してください。必ずあなたを待ちます。",
43
45
  "approvals.reject": "却下",
44
46
  "approvals.replayOff": "リプレイ中: 回答はできません。",
47
+ "approvals.script": "npm スクリプト {name} を実行します: {body}",
48
+ "approvals.scriptMissing": "npm スクリプト {name} を実行します。package.json にはありません。",
45
49
  "approvals.title": "承認",
46
50
  "approvals.turnOff": "オフにする",
47
51
  "approvals.turnOn": "オンにする",
package/i18n/ko.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "기다리는 요청이 없어요",
41
41
  "approvals.modeOff": "승인 모드가 꺼져 있어요: 팀이 묻지 않고 작업해요.",
42
42
  "approvals.modeOn": "승인 모드가 켜져 있어요: 되돌릴 수 없는 작업은 답을 기다려요.",
43
+ "approvals.origin.guest": "게스트({name})의 요청이에요. 승인 모드가 꺼져 있어도 답할 수 있는 사람은 당신뿐이에요.",
44
+ "approvals.origin.remote": "친구의 모델({name})에서 왔어요. 승인하기 전에 확인하세요. 항상 당신을 기다려요.",
43
45
  "approvals.reject": "거절",
44
46
  "approvals.replayOff": "다시 보기: 응답할 수 없어요.",
47
+ "approvals.script": "npm 스크립트 {name}을 실행해요: {body}",
48
+ "approvals.scriptMissing": "npm 스크립트 {name}을 실행해요. package.json에는 없어요.",
45
49
  "approvals.title": "승인",
46
50
  "approvals.turnOff": "끄기",
47
51
  "approvals.turnOn": "켜기",
package/i18n/pt-BR.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Nada esperando por você",
41
41
  "approvals.modeOff": "O modo de aprovação está desligado: a equipe age sem perguntar.",
42
42
  "approvals.modeOn": "O modo de aprovação está ligado: ações destrutivas esperam sua resposta.",
43
+ "approvals.origin.guest": "Pedido por um convidado ({name}). Só você pode responder, mesmo com o modo de aprovação desligado.",
44
+ "approvals.origin.remote": "Vem do modelo de um amigo ({name}). Confira antes de aprovar; sempre espera por você.",
43
45
  "approvals.reject": "Rejeitar",
44
46
  "approvals.replayOff": "Replay: não é possível responder.",
47
+ "approvals.script": "Executa o script npm {name}: {body}",
48
+ "approvals.scriptMissing": "Executa o script npm {name}, que o package.json não tem.",
45
49
  "approvals.title": "Aprovações",
46
50
  "approvals.turnOff": "Desligar",
47
51
  "approvals.turnOn": "Ligar",
package/i18n/ru.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "Ничего не ждёт вашего ответа",
41
41
  "approvals.modeOff": "Режим подтверждений выключен: команда действует, не спрашивая.",
42
42
  "approvals.modeOn": "Режим подтверждений включён: необратимые действия ждут вашего ответа.",
43
+ "approvals.origin.guest": "Запрос гостя ({name}). Ответить можете только вы, даже если режим подтверждений выключен.",
44
+ "approvals.origin.remote": "Пришло от модели друга ({name}). Проверьте перед подтверждением; это всегда ждёт вас.",
43
45
  "approvals.reject": "Отклонить",
44
46
  "approvals.replayOff": "Повтор: ответы отключены.",
47
+ "approvals.script": "Запускает npm-скрипт {name}: {body}",
48
+ "approvals.scriptMissing": "Запускает npm-скрипт {name}, которого нет в package.json.",
45
49
  "approvals.title": "Подтверждения",
46
50
  "approvals.turnOff": "Выключить",
47
51
  "approvals.turnOn": "Включить",
package/i18n/zh-CN.json CHANGED
@@ -40,8 +40,12 @@
40
40
  "approvals.empty.title": "没有等待你处理的事项",
41
41
  "approvals.modeOff": "审批模式已关闭:团队无需询问即可行动。",
42
42
  "approvals.modeOn": "审批模式已开启:破坏性操作会等待你的答复。",
43
+ "approvals.origin.guest": "来自访客({name})的请求。即使审批模式关闭,也只有你能答复。",
44
+ "approvals.origin.remote": "来自朋友的模型({name})。批准前请先检查;它总会等你。",
43
45
  "approvals.reject": "拒绝",
44
46
  "approvals.replayOff": "回放中:无法答复。",
47
+ "approvals.script": "运行 npm 脚本 {name}:{body}",
48
+ "approvals.scriptMissing": "运行 npm 脚本 {name},但 package.json 里没有它。",
45
49
  "approvals.title": "审批",
46
50
  "approvals.turnOff": "关闭",
47
51
  "approvals.turnOn": "开启",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hivedesk",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "A crew of AI workers that plan, talk and build real files on your machine with a local model.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/bus.js CHANGED
@@ -24,7 +24,8 @@ export class EventBus {
24
24
  this.state = replay(this.events, Infinity, this.meta);
25
25
  // Hive City (src/city/): the same log, its own pure reducer (CITY-PROTOCOL.md).
26
26
  this.state.city = replayCity(this.events);
27
- this.state.demo = this.demo || this.state.demo;
27
+ // This run decides the Demo label, not an old demo run in the same log.
28
+ this.state.demo = this.demo;
28
29
  this.state.lend = this.meta.lend;
29
30
  if (opts.version) this.state.version = opts.version;
30
31
  this._snapTimer = null;
@@ -134,4 +135,17 @@ export function initHome(dir) {
134
135
  return paths;
135
136
  }
136
137
 
138
+ /** True when this folder holds a hivedesk log written by a real (not demo) run. */
139
+ export function hasRealLog(dir) {
140
+ let text;
141
+ try { text = fs.readFileSync(path.join(dir, '.hivedesk', 'events.jsonl'), 'utf8'); } catch { return false; }
142
+ // emit() writes seq, ts, type, jobId and demo before data, so the label sits before "data":.
143
+ for (const line of text.split('\n')) {
144
+ if (!line.trim()) continue;
145
+ const at = line.indexOf('"data":');
146
+ if (!(at === -1 ? line : line.slice(0, at)).includes('"demo":true')) return true;
147
+ }
148
+ return false;
149
+ }
150
+
137
151
  export { initialState };
package/src/city/demo.js CHANGED
@@ -41,6 +41,7 @@ export async function runCityDemo({ city, scheduler, bus, stepMs = 1800, signal
41
41
  // 1. A friend joins: her brain is attached first (as the lend relay would), then her building.
42
42
  const brain = createDemoBrain({ id: DEMO_FRIEND.brainId, label: "Rita's PC (demo)", delayMs: stepMs ? 300 : 0, tokenDelayMs: stepMs ? 15 : 0 });
43
43
  brain.kind = 'remote';
44
+ brain.owner = DEMO_FRIEND.owner; // lent by Rita, so her building may use it
44
45
  brain.only = new Set();
45
46
  scheduler.addBrain(brain);
46
47
  step('friend', 'Rita joined with the six words. Her building rises across the bridge, and she brings Pip, a reviewer.');
package/src/city/index.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // (engine frames to every guest) replicates it, and a restart replays it.
7
7
  import os from 'node:os';
8
8
  import { ALL_TOOLS } from '../tools/index.js';
9
+ import { guestOf, checkGuest } from '../collab/policy.js';
9
10
  import { acceptanceFrom } from '../crew/brief.js';
10
11
  import {
11
12
  CITY, ROOMS, ROOM_IDS, WORK_KINDS, SPECIALIZATION, MAX_LOOPS, roomForRole, levelFor, publicMemory, statusForKind, isCityEvent
@@ -30,6 +31,8 @@ const COLOR = /^#[0-9a-fA-F]{6}$/;
30
31
  const TERMINAL = new Set(['done', 'blocked', 'cancelled']);
31
32
  /** Tools a guest's task never gets: no shell, no deletes. */
32
33
  export const GUEST_DENY = new Set(['run', 'delete_file']);
34
+ /** The tools a guest's agent comes with: it reads and checks; only the host can grant more. */
35
+ export const GUEST_TOOLS = Object.freeze(['list_files', 'read_file', 'check', 'preview']);
33
36
  export const LIMITS = Object.freeze({
34
37
  title: 200, detail: 4000, criteria: 6, criterion: 200, memoryText: 300, memoryEntries: 40, name: 40,
35
38
  guestCommands: 40, guestWindowMs: 10_000, presencePerSecond: 15, agentsPerMachine: 4, pipeline: 8,
@@ -315,8 +318,18 @@ export class City {
315
318
  const room = this.state.rooms[this.fixFor.has(task?.id) ? 'code' : ct.room];
316
319
  let tools = room && room.tools?.length ? worker.tools.filter((t) => room.tools.includes(t)) : [...worker.tools];
317
320
  if (ct.guest) tools = tools.filter((t) => !GUEST_DENY.has(t));
318
- if (tools.length === worker.tools.length) return worker;
319
- return { ...worker, tools };
321
+ const origin = this._originFor(worker, ct);
322
+ if (tools.length === worker.tools.length && !origin) return worker;
323
+ return { ...worker, tools, ...(origin ? { origin } : {}) };
324
+ }
325
+
326
+ /** A guest's task, or an agent a guest brought: its writes always wait for the host. */
327
+ _originFor(worker, ct) {
328
+ const a = this._agentByWorker(worker?.id);
329
+ const m = a && a.home !== this.machineId ? this.state.machines[a.home] : null;
330
+ if (m) return { kind: 'guest', id: String(m.owner || '').replace(/^peer:/, ''), label: m.name || 'a guest' };
331
+ if (ct?.guest) return { kind: 'guest', id: ct.createdBy?.id, label: ct.createdBy?.name || 'a guest' };
332
+ return null;
320
333
  }
321
334
 
322
335
  /** What an agent remembers goes into its prompts: pinned entries and facts, preferences, decisions. */
@@ -518,6 +531,7 @@ export class City {
518
531
  async _plan(t, agent, ctrl, x) {
519
532
  const request = [t.title, t.detail].filter(Boolean).join('\n\n');
520
533
  const { jobId, done } = this.hive.createJob({ request, ...(t.guest ? { approval: true } : {}) });
534
+ if (t.guest) this.toolbox.markOrigin?.(jobId, this._originFor(null, t));
521
535
  x.jobId = jobId;
522
536
  this.jobOwners.set(jobId, { taskId: t.id, mode: 'plan' });
523
537
  this.emit('city.task.updated', { task: { id: t.id, jobId } });
@@ -547,6 +561,7 @@ export class City {
547
561
  ].filter(Boolean).join('\n\n');
548
562
  const approval = t.guest || room.requireApproval ? { approval: true } : {};
549
563
  const { jobId, done } = this.hive.createJob({ request: t.title, plan: [{ title: t.title, detail, assignee: agent.workerId, kind }], cityTaskId: t.id, ...approval });
564
+ if (t.guest) this.toolbox.markOrigin?.(jobId, this._originFor(null, t));
550
565
  x.jobId = jobId;
551
566
  this.jobOwners.set(jobId, { taskId: t.id, mode: 'hop' });
552
567
  this.emit('city.task.updated', { task: { id: t.id, jobId } });
@@ -827,7 +842,7 @@ export class City {
827
842
  if (id === this.machineId) fail('forbidden', 'that is the host machine');
828
843
  const old = this.state.machines[id];
829
844
  if (old && old.online && old.owner !== owner) fail('forbidden', 'another person is in the city with that machine');
830
- const brainId = typeof data.brainId === 'string' && this.scheduler.brains.has(data.brainId) ? data.brainId : null;
845
+ const brainId = typeof data.brainId === 'string' && this._lentBy(data.brainId, owner) ? data.brainId : null;
831
846
  const machine = {
832
847
  id, name: str(m.name, LIMITS.name) || 'Friend', host: false, owner, online: true,
833
848
  gpu: m.gpu && typeof m.gpu === 'object' ? { name: str(m.gpu.name, 80) || undefined, vramBytes: num(m.gpu.vramBytes), backend: str(m.gpu.backend, 20) || undefined } : null,
@@ -847,6 +862,15 @@ export class City {
847
862
  return { machineId: id, agents: ids };
848
863
  }
849
864
 
865
+ /**
866
+ * True when brainId is a friend's brain that this owner lent itself (brain.attach with its guest id).
867
+ * The host's own models, cloud brains and other guests' brains never qualify.
868
+ */
869
+ _lentBy(brainId, owner) {
870
+ const slot = this.scheduler.brains.get(brainId);
871
+ return !!slot && slot.brain.kind === 'remote' && !!owner && owner !== 'host' && slot.brain.owner === owner;
872
+ }
873
+
850
874
  /** A friend's brain inside the city serves only that friend's agents and the borrows its owner accepts. */
851
875
  _restrictBrain(brainId, machineId) {
852
876
  const slot = this.scheduler.brains.get(brainId);
@@ -864,17 +888,24 @@ export class City {
864
888
  if (!local || !name) return null;
865
889
  const id = `${machineId}:${local}`;
866
890
  const role = str(a.role, 64) || 'Friend';
867
- const tools = (Array.isArray(a.tools) ? a.tools : ['list_files', 'read_file', 'check']).filter((t) => ALL_TOOLS.includes(t) && !GUEST_DENY.has(t));
891
+ // A guest's agent reads and checks only; the host grants more with city.agent.update.
868
892
  const existing = this.state.agents[id];
893
+ const granted = existing?.tools && existing.grantedBy === 'host' ? existing.tools : null;
894
+ const asked = (Array.isArray(a.tools) ? a.tools : GUEST_TOOLS).filter((t) => GUEST_TOOLS.includes(t));
895
+ const tools = granted || (asked.length ? asked : [...GUEST_TOOLS]);
869
896
  let worker = existing ? this.bus.state.crew.find((w) => w.id === existing.workerId) : null;
870
897
  if (!worker) worker = this.hive.hire({ name, role, prompt: str(a.prompt, 2000) || undefined, tools, color: a.color, avatar: a.avatar });
871
- else this.scheduler.setPaused(worker.id, false);
898
+ else {
899
+ // A worker hired by an older version may still hold write tools: it comes back with the safe set.
900
+ if (!granted && (worker.tools || []).some((t) => !tools.includes(t))) worker = this.hive.updateWorker(worker.id, { tools }) || worker;
901
+ this.scheduler.setPaused(worker.id, false);
902
+ }
872
903
  const xp = Math.min(Math.max(0, Number(a.xp) || 0), 1e6);
873
904
  const spec = cleanSpec(a.specialization, Object.keys(this.state.rooms)) || [roomForRole(role)];
874
905
  const m = this.state.machines[machineId];
875
906
  const agent = {
876
907
  id, workerId: worker.id, name, role, avatar: worker.avatar, color: worker.color, specialization: spec,
877
- level: levelFor(xp), xp, tools, permissions: perms(tools),
908
+ level: levelFor(xp), xp, tools, permissions: perms(tools), ...(granted ? { grantedBy: 'host' } : {}),
878
909
  memory: a.memory && Array.isArray(a.memory.highlights) ? { count: num(a.memory.count) || 0, highlights: a.memory.highlights.slice(0, 4).map((h) => ({ id: str(h.id, 40), kind: str(h.kind, 20), text: str(h.text, LIMITS.memoryText) })) } : { count: 0, highlights: [] },
879
910
  room: spec[0], taskId: null, status: 'idle', brain: { kind: 'remote', machineId, label: m?.model || m?.name },
880
911
  home: machineId, builtin: false, retired: false, stats: { done: 0, reviews: 0, tests: 0, loops: 0, ...(existing?.stats || {}) }
@@ -1015,11 +1046,9 @@ export class City {
1015
1046
 
1016
1047
  // ---------------------------------------------------------------- who is asking
1017
1048
  _who(d) {
1018
- if (d && d.as && typeof d.as === 'object') {
1019
- const id = str(String(d.as.id ?? ''), 24) || 'guest';
1020
- return { guest: true, id, name: str(String(d.as.name ?? ''), LIMITS.name) || 'Guest', owner: `peer:${id}` };
1021
- }
1022
- return { guest: false, id: 'h', name: 'You', owner: 'host' };
1049
+ const g = guestOf(d);
1050
+ if (g) return { guest: true, id: g.id, name: str(g.name, LIMITS.name) || 'Guest', role: g.role, owner: g.owner };
1051
+ return { guest: false, id: 'h', name: 'You', role: 'host', owner: 'host' };
1023
1052
  }
1024
1053
 
1025
1054
  _ownsAgent(who, a) {
@@ -1196,17 +1225,23 @@ export class City {
1196
1225
 
1197
1226
  updateAgent(d, who) {
1198
1227
  const a = this._agent(d);
1199
- if (!this._ownsAgent(who, a)) fail('forbidden', 'only the owner of an agent can change it');
1228
+ const owns = this._ownsAgent(who, a);
1229
+ // The host may grant tools to a guest's agent; nothing else of it changes then.
1230
+ if (!owns && (who.guest || !Array.isArray(d.tools))) fail('forbidden', 'only the owner of an agent can change it');
1200
1231
  const patch = { id: a.id };
1201
1232
  const crewPatch = {};
1202
- for (const k of ['name', 'role', 'avatar']) if (str(d[k], k === 'role' ? 64 : LIMITS.name)) { patch[k] = str(d[k], k === 'role' ? 64 : LIMITS.name); crewPatch[k] = patch[k]; }
1203
- if (COLOR.test(d.color || '')) { patch.color = d.color; crewPatch.color = d.color; }
1204
- const spec = cleanSpec(d.specialization, Object.keys(this.state.rooms));
1205
- if (spec) patch.specialization = spec;
1233
+ if (owns) {
1234
+ for (const k of ['name', 'role', 'avatar']) if (str(d[k], k === 'role' ? 64 : LIMITS.name)) { patch[k] = str(d[k], k === 'role' ? 64 : LIMITS.name); crewPatch[k] = patch[k]; }
1235
+ if (COLOR.test(d.color || '')) { patch.color = d.color; crewPatch.color = d.color; }
1236
+ const spec = cleanSpec(d.specialization, Object.keys(this.state.rooms));
1237
+ if (spec) patch.specialization = spec;
1238
+ }
1206
1239
  if (Array.isArray(d.tools)) {
1240
+ // Tools are what an agent may do on the host's disk: only the host grants them.
1241
+ if (who.guest) fail('forbidden', 'only the host can change the tools of an agent');
1207
1242
  let tools = d.tools.filter((t) => ALL_TOOLS.includes(t));
1208
1243
  if (a.home !== this.machineId) tools = tools.filter((t) => !GUEST_DENY.has(t));
1209
- if (tools.length) { patch.tools = tools; patch.permissions = perms(tools); crewPatch.tools = tools; }
1244
+ if (tools.length) { patch.tools = tools; patch.permissions = perms(tools); crewPatch.tools = tools; if (a.home !== this.machineId) patch.grantedBy = 'host'; }
1210
1245
  }
1211
1246
  const w = this.bus.state.crew.find((x) => x.id === a.workerId);
1212
1247
  if (w && Object.keys(crewPatch).length) {
@@ -1381,6 +1416,8 @@ export class City {
1381
1416
  const d = data && typeof data === 'object' ? data : {};
1382
1417
  const who = this._who(d);
1383
1418
  if (who.guest && !guest) fail('forbidden', 'only the host can do this');
1419
+ // The role of a guest is checked here too, not only in the host's browser (src/collab/policy.js).
1420
+ if (who.guest) checkGuest(who, type, (code, message) => new CityError(code, message));
1384
1421
  if (type !== 'city.presence') this._rate(who);
1385
1422
  return fn(d, who, client);
1386
1423
  });
@@ -1415,6 +1452,8 @@ export class City {
1415
1452
  if (COLOR.test(d.color || '')) patch.color = d.color;
1416
1453
  if (typeof d.brainId === 'string' && !m.host) {
1417
1454
  if (!this.scheduler.brains.has(d.brainId)) fail('not_found', 'no such brain');
1455
+ // Only the machine's owner binds a model to it, and only a model that owner lent itself.
1456
+ if (!this._lentBy(d.brainId, m.owner)) fail('forbidden', 'a building can use only the model its owner lends');
1418
1457
  patch.brainId = d.brainId;
1419
1458
  }
1420
1459
  if (m.host && patch.name) this.store.setMachineName(patch.name);