busybits 2.0.1 → 2.2.0

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 (31) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +13 -1
  3. package/README.md +11 -0
  4. package/dist/build.json +2 -2
  5. package/dist/cli/busybits.js +269 -15
  6. package/dist/client/bundle/app-BqhKcvbt.js +24 -0
  7. package/dist/client/bundle/{app-CoDOLwxe.css → app-Y2N0l58V.css} +1 -1
  8. package/dist/client/bundle/city-DMPsypEv.js +1 -0
  9. package/dist/client/bundle/{daystats-CJyNq6hu.js → daystats-BJLg6u8w.js} +1 -1
  10. package/dist/client/bundle/{dom-slmnBOjx.js → dom-Co5ozWIR.js} +1 -1
  11. package/dist/client/bundle/{en-BQQEHqmG.js → en-DRc2Oulk.js} +23 -3
  12. package/dist/client/bundle/{es-BgBoKwEe.js → es-DslAKAxR.js} +23 -3
  13. package/dist/client/bundle/{format-CvlPqloO.js → format-k7wUh6fM.js} +1 -1
  14. package/dist/client/bundle/{fr-PI_gjIFq.js → fr-Chqn4K83.js} +23 -3
  15. package/dist/client/bundle/{main-DTHUta25.js → main-DBC-FPBX.js} +2 -2
  16. package/dist/client/bundle/{ptypane-9pL54zR0.js → ptypane-UBqz8-gA.js} +1 -1
  17. package/dist/client/bundle/room-name-B0XrI0hp.js +1 -0
  18. package/dist/client/bundle/{simulator-B45JPgSp.js → simulator-B0dhttuF.js} +1 -1
  19. package/dist/client/bundle/world-model-DZTQjqjZ.js +1 -0
  20. package/dist/client/bundle/{world-stream-CUfry7aL.js → world-stream-EkZAApmC.js} +1 -1
  21. package/dist/client/index.html +1 -1
  22. package/dist/server/index.js +1563 -842
  23. package/mod/habblaud/.claude-plugin/plugin.json +1 -1
  24. package/mod/habblaud-mensagens/.claude-plugin/plugin.json +1 -1
  25. package/mod/habblaud-permissoes/.claude-plugin/plugin.json +1 -1
  26. package/mod/habblaud-pi/package.json +1 -1
  27. package/package.json +2 -1
  28. package/dist/client/bundle/app-QYGBa260.js +0 -24
  29. package/dist/client/bundle/city-UYDbxWIy.js +0 -1
  30. package/dist/client/bundle/room-name-Bv6N672f.js +0 -1
  31. package/dist/client/bundle/world-model-BgjMjmrp.js +0 -1
@@ -17,7 +17,7 @@ function applyBusybitsAliases(env) {
17
17
  applyBusybitsAliases(process.env);
18
18
 
19
19
  // server/index.ts
20
- import { existsSync as existsSync13, readFileSync as readFileSync29 } from "node:fs";
20
+ import { existsSync as existsSync13, readFileSync as readFileSync30 } from "node:fs";
21
21
  import http4 from "node:http";
22
22
  import { join as join33 } from "node:path";
23
23
 
@@ -521,6 +521,7 @@ var EN = {
521
521
  "O job falhou e vai sair do escrit\xF3rio.": "The job failed and is leaving the office.",
522
522
  "Job do Agent Hub": "Agent Hub job",
523
523
  "Agent Hub": "Agent Hub",
524
+ "Gentle Shell": "Gentle Shell",
524
525
  "Somente leitura: o Agent Hub gerencia este job": "Read-only: Agent Hub owns this job",
525
526
  "Na fila do Agent Hub": "Queued in Agent Hub",
526
527
  "Erro": "Error",
@@ -3662,7 +3663,7 @@ var EN = {
3662
3663
  "Estilo padr\xE3o salvo para novos agentes.": "Default style saved for new agents.",
3663
3664
  "Estilo padr\xE3o restaurado para aleat\xF3rio.": "Default style restored to random.",
3664
3665
  "N\xE3o foi poss\xEDvel salvar o estilo padr\xE3o (erro {0}).": "Could not save the default style (error {0}).",
3665
- 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': 'Usage: busybits <command> [options]\n\nCommands:\n setup install or update Busybits extensions and services\n start start the server in the foreground\n status show status of installed components and services\n update update Busybits to the latest version\n uninstall remove installed extensions and services\n pair pair this machine as a satellite to a central Busybits\n\nOptions for setup:\n --service install and start the user service (systemd/launchd)\n --port <n> server port\n --no-claude leave Claude Code alone\n --no-pi leave Pi alone\n --no-codex leave the Codex hooks alone\n --dry-run only show what would be done\n --after-update used by "busybits update": restart the service even if the unit did not change\n --rebuild rebuild (install from a clone)\n --ignore-node skip the Node version check\n\nOptions for update:\n --check only shows the current and the latest version\n --rollback goes back to the previous version\n --to <version> updates to that version instead of the latest\n --global also updates the global busybits (npm i -g)\n\nOptions for uninstall:\n --purge also delete the Busybits data\n --dry-run only show what would be done\n\nOptions for pair:\n --pairing <text> pairing text from the central (default: standard input)\n --label <name> how this machine appears in the office\n --codex-wait install the Codex hooks and wait for your answer\n\nGlobal options:\n --help, -h show this help\n --version, -v show installed version',
3666
+ 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n post deixa um item na mesa do seu escrit\xF3rio (a caixa de entrada)\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es de post:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio)\n --body <texto> detalhes em texto simples\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item (e o reabre se estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': 'Usage: busybits <command> [options]\n\nCommands:\n setup install or update Busybits extensions and services\n start start the server in the foreground\n status show status of installed components and services\n update update Busybits to the latest version\n uninstall remove installed extensions and services\n pair pair this machine as a satellite to a central Busybits\n post leave an item on your office desk (the inbox)\n\nOptions for setup:\n --service install and start the user service (systemd/launchd)\n --port <n> server port\n --no-claude leave Claude Code alone\n --no-pi leave Pi alone\n --no-codex leave the Codex hooks alone\n --dry-run only show what would be done\n --after-update used by "busybits update": restart the service even if the unit did not change\n --rebuild rebuild (install from a clone)\n --ignore-node skip the Node version check\n\nOptions for update:\n --check only shows the current and the latest version\n --rollback goes back to the previous version\n --to <version> updates to that version instead of the latest\n --global also updates the global busybits (npm i -g)\n\nOptions for uninstall:\n --purge also delete the Busybits data\n --dry-run only show what would be done\n\nOptions for pair:\n --pairing <text> pairing text from the central (default: standard input)\n --label <name> how this machine appears in the office\n --codex-wait install the Codex hooks and wait for your answer\n\nOptions for post:\n --title <text> item title (required)\n --body <text> details as plain text\n --link <url> http(s) link the item opens\n --key <key> the same key updates the item (and reopens it if it was resolved)\n --source <name> who is leaving the item (shown when it is not an agent)\n\nGlobal options:\n --help, -h show this help\n --version, -v show installed version',
3666
3667
  "No Windows, use scripts/windows/install-satellite.ps1 a partir de um clone (o busybits ainda n\xE3o instala servi\xE7o no Windows).": "On Windows, use scripts/windows/install-satellite.ps1 from a clone (busybits does not install a service on Windows yet).",
3667
3668
  "comando desconhecido: {0}": "unknown command: {0}",
3668
3669
  "{0} precisa de um valor": "{0} needs a value",
@@ -3686,7 +3687,46 @@ var EN = {
3686
3687
  "Voltei para a v{0}.": "Went back to v{0}.",
3687
3688
  "a vers\xE3o {0} n\xE3o tem um payload completo em {1}": "version {0} has no complete payload in {1}",
3688
3689
  "O Busybits precisa do Node 22.12+ ou 24, e nenhum foi encontrado. Instale um (por exemplo com o nvm: nvm install 24) e rode de novo.": "Busybits needs Node 22.12+ or 24, and none was found. Install one (for example with nvm: nvm install 24) and run it again.",
3689
- "servi\xE7o antigo {0} removido": "old service {0} removed"
3690
+ "servi\xE7o antigo {0} removido": "old service {0} removed",
3691
+ "os itens da mesa s\xF3 s\xE3o resolvidos pelo pr\xF3prio computador (http://localhost ou http://127.0.0.1)": "desk items are only resolved from the computer itself (http://localhost or http://127.0.0.1)",
3692
+ "s\xF3 o pr\xF3prio computador deixa itens na mesa (http://localhost ou http://127.0.0.1)": "only the computer itself leaves items on the desk (http://localhost or http://127.0.0.1)",
3693
+ "a mesa s\xF3 vale pelo pr\xF3prio computador ou pelo acesso remoto com login": "the desk only works from the computer itself or through remote access with login",
3694
+ "a mesa j\xE1 tem {0} itens abertos: resolva alguns antes de deixar outros": "the desk already has {0} open items: resolve some before leaving more",
3695
+ "item n\xE3o encontrado": "item not found",
3696
+ "inbox.json ileg\xEDvel ({0}); come\xE7ando sem itens.": "inbox.json unreadable ({0}); starting with no items.",
3697
+ "corpo inv\xE1lido": "invalid body",
3698
+ "t\xEDtulo obrigat\xF3rio": "title required",
3699
+ "t\xEDtulo longo demais (m\xE1x. {0} caracteres)": "title too long (max {0} characters)",
3700
+ "texto inv\xE1lido": "invalid text",
3701
+ "texto longo demais (m\xE1x. {0} KB)": "text too long (max {0} KB)",
3702
+ "link inv\xE1lido": "invalid link",
3703
+ "o link precisa ser http ou https": "the link must be http or https",
3704
+ "chave inv\xE1lida": "invalid key",
3705
+ "chave longa demais (m\xE1x. {0} caracteres)": "key too long (max {0} characters)",
3706
+ "origem inv\xE1lida": "invalid source",
3707
+ "ancestrais inv\xE1lidos": "invalid ancestors",
3708
+ 'Uso: busybits post --title <texto> [op\xE7\xF5es]\n\nDeixa um item na mesa do seu escrit\xF3rio (o painel "Mesa" abre ao clicar no monte de pap\xE9is).\n\nOp\xE7\xF5es:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio, at\xE9 200 caracteres)\n --body <texto> detalhes em texto simples (at\xE9 8 KB)\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item em vez de duplicar (e o reabre se j\xE1 estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nExemplo:\n busybits post --title "ROO7-1234 rejeitado no QA" --link https://example.com/ROO7-1234 --key ROO7-1234': 'Usage: busybits post --title <text> [options]\n\nLeaves an item on your office desk (the "Desk" panel opens when you click the stack of papers).\n\nOptions:\n --title <text> item title (required, up to 200 characters)\n --body <text> details as plain text (up to 8 KB)\n --link <url> http(s) link the item opens\n --key <key> the same key updates the item instead of duplicating it (and reopens it if it was already resolved)\n --source <name> who is leaving the item (shown when it is not an agent)\n\nExample:\n busybits post --title "ROO7-1234 rejected in QA" --link https://example.com/ROO7-1234 --key ROO7-1234',
3709
+ "falta --title": "missing --title",
3710
+ "N\xE3o consegui falar com o Busybits na porta {0}. Ele est\xE1 rodando? (busybits start; outra porta: HABBLAUD_PORT)": "Could not reach Busybits on port {0}. Is it running? (busybits start; another port: HABBLAUD_PORT)",
3711
+ "O Busybits recusou o item ({0}): {1}": "Busybits refused the item ({0}): {1}",
3712
+ "Item reaberto na mesa: {0}": "Item reopened on the desk: {0}",
3713
+ "Item atualizado na mesa: {0}": "Item updated on the desk: {0}",
3714
+ "Item deixado na mesa: {0}": "Item left on the desk: {0}",
3715
+ "A mesa s\xF3 funciona com o escrit\xF3rio ao vivo.": "The desk only works with the live office.",
3716
+ "N\xE3o foi poss\xEDvel resolver o item (erro {0}).": "Could not resolve the item (error {0}).",
3717
+ "um agente": "an agent",
3718
+ "um script": "a script",
3719
+ "resolvido {0}": "resolved {0}",
3720
+ "de {0}": "from {0}",
3721
+ "Resolver": "Resolve",
3722
+ "Nada por aqui.": "Nothing here.",
3723
+ "Sua mesa est\xE1 limpa: nada esperando.": "Your desk is clear: nothing waiting.",
3724
+ "Ocultar resolvidos": "Hide resolved",
3725
+ "Mostrar resolvidos ({0})": "Show resolved ({0})",
3726
+ "Itens deixados na sua mesa. Clique para abrir.": "Items left on your desk. Click to open.",
3727
+ "na mesa": "on desk",
3728
+ "Na sua mesa": "On your desk",
3729
+ "Mensageiro": "Courier"
3690
3730
  };
3691
3731
 
3692
3732
  // shared/locales/es.ts
@@ -4184,6 +4224,7 @@ var ES = {
4184
4224
  "O job falhou e vai sair do escrit\xF3rio.": "El trabajo fall\xF3 y saldr\xE1 de la oficina.",
4185
4225
  "Job do Agent Hub": "Trabajo de Agent Hub",
4186
4226
  "Agent Hub": "Agent Hub",
4227
+ "Gentle Shell": "Gentle Shell",
4187
4228
  "Somente leitura: o Agent Hub gerencia este job": "Solo lectura: Agent Hub gestiona este trabajo",
4188
4229
  "Na fila do Agent Hub": "En la cola de Agent Hub",
4189
4230
  "Erro": "Error",
@@ -7325,7 +7366,7 @@ var ES = {
7325
7366
  "Estilo padr\xE3o salvo para novos agentes.": "Estilo predeterminado guardado para nuevos agentes.",
7326
7367
  "Estilo padr\xE3o restaurado para aleat\xF3rio.": "Estilo predeterminado restaurado a aleatorio.",
7327
7368
  "N\xE3o foi poss\xEDvel salvar o estilo padr\xE3o (erro {0}).": "No se pudo guardar el estilo predeterminado (error {0}).",
7328
- 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': 'Uso: busybits <comando> [opciones]\n\nComandos:\n setup instala o actualiza las extensiones y servicios de Busybits\n start inicia el servidor en primer plano\n status muestra el estado de la instalaci\xF3n y los servicios\n update actualiza Busybits a la \xFAltima versi\xF3n\n uninstall desinstala extensiones y servicios instalados\n pair empareja este equipo como sat\xE9lite de un Busybits central\n\nOpciones de setup:\n --service instala e inicia el servicio de usuario (systemd/launchd)\n --port <n> puerto del servidor\n --no-claude no toca Claude Code\n --no-pi no toca Pi\n --no-codex no toca los hooks de Codex\n --dry-run solo muestra lo que se har\xEDa\n --after-update usado por "busybits update": reinicia el servicio aunque la unidad no haya cambiado\n --rebuild recompila (instalaci\xF3n desde un clon)\n --ignore-node omite la comprobaci\xF3n de la versi\xF3n de Node\n\nOpciones de update:\n --check solo muestra la versi\xF3n actual y la \xFAltima\n --rollback vuelve a la versi\xF3n anterior\n --to <versi\xF3n> actualiza a esa versi\xF3n en lugar de la \xFAltima\n --global actualiza tambi\xE9n el busybits global (npm i -g)\n\nOpciones de uninstall:\n --purge borra tambi\xE9n los datos de Busybits\n --dry-run solo muestra lo que se har\xEDa\n\nOpciones de pair:\n --pairing <texto> texto de emparejamiento de la central (por defecto: entrada est\xE1ndar)\n --label <nombre> c\xF3mo aparece esta m\xE1quina en la oficina\n --codex-wait instala los hooks de Codex y espera su respuesta\n\nOpciones globales:\n --help, -h muestra esta ayuda\n --version, -v muestra la versi\xF3n instalada',
7369
+ 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n post deixa um item na mesa do seu escrit\xF3rio (a caixa de entrada)\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es de post:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio)\n --body <texto> detalhes em texto simples\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item (e o reabre se estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': 'Uso: busybits <comando> [opciones]\n\nComandos:\n setup instala o actualiza las extensiones y servicios de Busybits\n start inicia el servidor en primer plano\n status muestra el estado de la instalaci\xF3n y los servicios\n update actualiza Busybits a la \xFAltima versi\xF3n\n uninstall desinstala extensiones y servicios instalados\n pair empareja este equipo como sat\xE9lite de un Busybits central\n post deja un elemento en el escritorio de tu oficina (la bandeja)\n\nOpciones de setup:\n --service instala e inicia el servicio de usuario (systemd/launchd)\n --port <n> puerto del servidor\n --no-claude no toca Claude Code\n --no-pi no toca Pi\n --no-codex no toca los hooks de Codex\n --dry-run solo muestra lo que se har\xEDa\n --after-update usado por "busybits update": reinicia el servicio aunque la unidad no haya cambiado\n --rebuild recompila (instalaci\xF3n desde un clon)\n --ignore-node omite la comprobaci\xF3n de la versi\xF3n de Node\n\nOpciones de update:\n --check solo muestra la versi\xF3n actual y la \xFAltima\n --rollback vuelve a la versi\xF3n anterior\n --to <versi\xF3n> actualiza a esa versi\xF3n en lugar de la \xFAltima\n --global actualiza tambi\xE9n el busybits global (npm i -g)\n\nOpciones de uninstall:\n --purge borra tambi\xE9n los datos de Busybits\n --dry-run solo muestra lo que se har\xEDa\n\nOpciones de pair:\n --pairing <texto> texto de emparejamiento de la central (por defecto: entrada est\xE1ndar)\n --label <nombre> c\xF3mo aparece esta m\xE1quina en la oficina\n --codex-wait instala los hooks de Codex y espera su respuesta\n\nOpciones de post:\n --title <texto> t\xEDtulo del elemento (obligatorio)\n --body <texto> detalles en texto simple\n --link <url> enlace http(s) que abre el elemento\n --key <clave> la misma clave actualiza el elemento (y lo reabre si estaba resuelto)\n --source <nombre> qui\xE9n deja el elemento (se muestra cuando no es un agente)\n\nOpciones globales:\n --help, -h muestra esta ayuda\n --version, -v muestra la versi\xF3n instalada',
7329
7370
  "No Windows, use scripts/windows/install-satellite.ps1 a partir de um clone (o busybits ainda n\xE3o instala servi\xE7o no Windows).": "En Windows, usa scripts/windows/install-satellite.ps1 desde un clon (busybits a\xFAn no instala servicio en Windows).",
7330
7371
  "comando desconhecido: {0}": "comando desconocido: {0}",
7331
7372
  "{0} precisa de um valor": "{0} necesita un valor",
@@ -7349,7 +7390,46 @@ var ES = {
7349
7390
  "Voltei para a v{0}.": "Volv\xED a la v{0}.",
7350
7391
  "a vers\xE3o {0} n\xE3o tem um payload completo em {1}": "la versi\xF3n {0} no tiene un payload completo en {1}",
7351
7392
  "O Busybits precisa do Node 22.12+ ou 24, e nenhum foi encontrado. Instale um (por exemplo com o nvm: nvm install 24) e rode de novo.": "Busybits necesita Node 22.12+ o 24, y no se encontr\xF3 ninguno. Instala uno (por ejemplo con nvm: nvm install 24) y ejec\xFAtalo de nuevo.",
7352
- "servi\xE7o antigo {0} removido": "servicio antiguo {0} eliminado"
7393
+ "servi\xE7o antigo {0} removido": "servicio antiguo {0} eliminado",
7394
+ "os itens da mesa s\xF3 s\xE3o resolvidos pelo pr\xF3prio computador (http://localhost ou http://127.0.0.1)": "los elementos del escritorio solo se resuelven desde el propio ordenador (http://localhost o http://127.0.0.1)",
7395
+ "s\xF3 o pr\xF3prio computador deixa itens na mesa (http://localhost ou http://127.0.0.1)": "solo el propio ordenador deja elementos en el escritorio (http://localhost o http://127.0.0.1)",
7396
+ "a mesa s\xF3 vale pelo pr\xF3prio computador ou pelo acesso remoto com login": "el escritorio solo vale desde el propio ordenador o por el acceso remoto con inicio de sesi\xF3n",
7397
+ "a mesa j\xE1 tem {0} itens abertos: resolva alguns antes de deixar outros": "el escritorio ya tiene {0} elementos abiertos: resuelve algunos antes de dejar m\xE1s",
7398
+ "item n\xE3o encontrado": "elemento no encontrado",
7399
+ "inbox.json ileg\xEDvel ({0}); come\xE7ando sem itens.": "inbox.json ilegible ({0}); empezando sin elementos.",
7400
+ "corpo inv\xE1lido": "cuerpo inv\xE1lido",
7401
+ "t\xEDtulo obrigat\xF3rio": "t\xEDtulo obligatorio",
7402
+ "t\xEDtulo longo demais (m\xE1x. {0} caracteres)": "t\xEDtulo demasiado largo (m\xE1x. {0} caracteres)",
7403
+ "texto inv\xE1lido": "texto inv\xE1lido",
7404
+ "texto longo demais (m\xE1x. {0} KB)": "texto demasiado largo (m\xE1x. {0} KB)",
7405
+ "link inv\xE1lido": "enlace inv\xE1lido",
7406
+ "o link precisa ser http ou https": "el enlace debe ser http o https",
7407
+ "chave inv\xE1lida": "clave inv\xE1lida",
7408
+ "chave longa demais (m\xE1x. {0} caracteres)": "clave demasiado larga (m\xE1x. {0} caracteres)",
7409
+ "origem inv\xE1lida": "origen inv\xE1lido",
7410
+ "ancestrais inv\xE1lidos": "ancestros inv\xE1lidos",
7411
+ 'Uso: busybits post --title <texto> [op\xE7\xF5es]\n\nDeixa um item na mesa do seu escrit\xF3rio (o painel "Mesa" abre ao clicar no monte de pap\xE9is).\n\nOp\xE7\xF5es:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio, at\xE9 200 caracteres)\n --body <texto> detalhes em texto simples (at\xE9 8 KB)\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item em vez de duplicar (e o reabre se j\xE1 estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nExemplo:\n busybits post --title "ROO7-1234 rejeitado no QA" --link https://example.com/ROO7-1234 --key ROO7-1234': 'Uso: busybits post --title <texto> [opciones]\n\nDeja un elemento en el escritorio de tu oficina (el panel "Escritorio" se abre al hacer clic en la pila de papeles).\n\nOpciones:\n --title <texto> t\xEDtulo del elemento (obligatorio, hasta 200 caracteres)\n --body <texto> detalles en texto simple (hasta 8 KB)\n --link <url> enlace http(s) que abre el elemento\n --key <clave> la misma clave actualiza el elemento en lugar de duplicarlo (y lo reabre si ya estaba resuelto)\n --source <nombre> qui\xE9n deja el elemento (se muestra cuando no es un agente)\n\nEjemplo:\n busybits post --title "ROO7-1234 rechazado en QA" --link https://example.com/ROO7-1234 --key ROO7-1234',
7412
+ "falta --title": "falta --title",
7413
+ "N\xE3o consegui falar com o Busybits na porta {0}. Ele est\xE1 rodando? (busybits start; outra porta: HABBLAUD_PORT)": "No pude hablar con Busybits en el puerto {0}. \xBFEst\xE1 en marcha? (busybits start; otro puerto: HABBLAUD_PORT)",
7414
+ "O Busybits recusou o item ({0}): {1}": "Busybits rechaz\xF3 el elemento ({0}): {1}",
7415
+ "Item reaberto na mesa: {0}": "Elemento reabierto en el escritorio: {0}",
7416
+ "Item atualizado na mesa: {0}": "Elemento actualizado en el escritorio: {0}",
7417
+ "Item deixado na mesa: {0}": "Elemento dejado en el escritorio: {0}",
7418
+ "A mesa s\xF3 funciona com o escrit\xF3rio ao vivo.": "El escritorio solo funciona con la oficina en vivo.",
7419
+ "N\xE3o foi poss\xEDvel resolver o item (erro {0}).": "No se pudo resolver el elemento (error {0}).",
7420
+ "um agente": "un agente",
7421
+ "um script": "un script",
7422
+ "resolvido {0}": "resuelto {0}",
7423
+ "de {0}": "de {0}",
7424
+ "Resolver": "Resolver",
7425
+ "Nada por aqui.": "Nada por aqu\xED.",
7426
+ "Sua mesa est\xE1 limpa: nada esperando.": "Tu escritorio est\xE1 despejado: nada esperando.",
7427
+ "Ocultar resolvidos": "Ocultar resueltos",
7428
+ "Mostrar resolvidos ({0})": "Mostrar resueltos ({0})",
7429
+ "Itens deixados na sua mesa. Clique para abrir.": "Elementos dejados en tu escritorio. Haz clic para abrir.",
7430
+ "na mesa": "en el escritorio",
7431
+ "Na sua mesa": "En tu escritorio",
7432
+ "Mensageiro": "Mensajero"
7353
7433
  };
7354
7434
 
7355
7435
  // shared/locales/fr.ts
@@ -7840,6 +7920,7 @@ var FR = {
7840
7920
  "O job falhou e vai sair do escrit\xF3rio.": "Le job a \xE9chou\xE9 et quitte le bureau.",
7841
7921
  "Job do Agent Hub": "Job Agent Hub",
7842
7922
  "Agent Hub": "Agent Hub",
7923
+ "Gentle Shell": "Gentle Shell",
7843
7924
  "Somente leitura: o Agent Hub gerencia este job": "Lecture seule : Agent Hub g\xE8re ce job",
7844
7925
  "Na fila do Agent Hub": "Dans la file d'attente d'Agent Hub",
7845
7926
  "Erro": "Erreur",
@@ -11003,7 +11084,7 @@ var FR = {
11003
11084
  "Estilo padr\xE3o salvo para novos agentes.": "Style par d\xE9faut enregistr\xE9 pour les nouveaux agents.",
11004
11085
  "Estilo padr\xE3o restaurado para aleat\xF3rio.": "Style par d\xE9faut restaur\xE9 \xE0 al\xE9atoire.",
11005
11086
  "N\xE3o foi poss\xEDvel salvar o estilo padr\xE3o (erro {0}).": "Impossible d'enregistrer le style par d\xE9faut (erreur {0}).",
11006
- 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': "Utilisation\xA0: busybits <commande> [options]\n\nCommandes\xA0:\n setup installe ou met \xE0 jour les extensions et services Busybits\n start d\xE9marre le serveur au premier plan\n status affiche l'\xE9tat de l'installation et des services\n update met \xE0 jour Busybits vers la derni\xE8re version\n uninstall supprime les extensions et services install\xE9s\n pair associe cette machine comme satellite d'un Busybits central\n\nOptions de setup :\n --service installe et d\xE9marre le service utilisateur (systemd/launchd)\n --port <n> port du serveur\n --no-claude ne touche pas \xE0 Claude Code\n --no-pi ne touche pas \xE0 Pi\n --no-codex ne touche pas aux hooks Codex\n --dry-run montre seulement ce qui serait fait\n --after-update utilis\xE9 par \xAB busybits update \xBB : red\xE9marre le service m\xEAme si l'unit\xE9 n'a pas chang\xE9\n --rebuild recompile (installation depuis un clone)\n --ignore-node ignore la v\xE9rification de la version de Node\n\nOptions de update :\n --check affiche seulement la version actuelle et la derni\xE8re\n --rollback revient \xE0 la version pr\xE9c\xE9dente\n --to <version> met \xE0 jour vers cette version au lieu de la derni\xE8re\n --global met aussi \xE0 jour le busybits global (npm i -g)\n\nOptions de uninstall :\n --purge supprime aussi les donn\xE9es de Busybits\n --dry-run montre seulement ce qui serait fait\n\nOptions de pair :\n --pairing <texte> texte d'appairage de la centrale (par d\xE9faut : entr\xE9e standard)\n --label <nom> comment cette machine appara\xEEt dans le bureau\n --codex-wait installe les hooks Codex et attend votre r\xE9ponse\n\nOptions globales\xA0:\n --help, -h affiche cette aide\n --version, -v affiche la version install\xE9e",
11087
+ 'Uso: busybits <comando> [op\xE7\xF5es]\n\nComandos:\n setup instala ou atualiza as extens\xF5es e servi\xE7os do Busybits\n start inicia o servidor em primeiro plano\n status mostra o estado da instala\xE7\xE3o e dos servi\xE7os\n update atualiza o Busybits para a vers\xE3o mais recente\n uninstall remove extens\xF5es e servi\xE7os instalados\n pair emparelha esta m\xE1quina como sat\xE9lite de um Busybits central\n post deixa um item na mesa do seu escrit\xF3rio (a caixa de entrada)\n\nOp\xE7\xF5es de setup:\n --service instala e inicia o servi\xE7o de usu\xE1rio (systemd/launchd)\n --port <n> porta do servidor\n --no-claude n\xE3o mexe no Claude Code\n --no-pi n\xE3o mexe no Pi\n --no-codex n\xE3o mexe nos hooks do Codex\n --dry-run s\xF3 mostra o que seria feito\n --after-update usado por "busybits update": reinicia o servi\xE7o mesmo sem mudan\xE7a na unidade\n --rebuild refaz o build (instala\xE7\xE3o a partir de um clone)\n --ignore-node ignora a verifica\xE7\xE3o da vers\xE3o do Node\n\nOp\xE7\xF5es de update:\n --check s\xF3 mostra a vers\xE3o atual e a mais recente\n --rollback volta para a vers\xE3o anterior\n --to <vers\xE3o> atualiza para essa vers\xE3o em vez da mais recente\n --global atualiza tamb\xE9m o busybits global (npm i -g)\n\nOp\xE7\xF5es de uninstall:\n --purge apaga tamb\xE9m os dados do Busybits\n --dry-run s\xF3 mostra o que seria feito\n\nOp\xE7\xF5es de pair:\n --pairing <texto> texto de pareamento da central (padr\xE3o: entrada padr\xE3o)\n --label <nome> como esta m\xE1quina aparece no escrit\xF3rio\n --codex-wait instala os hooks do Codex com espera pela sua resposta\n\nOp\xE7\xF5es de post:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio)\n --body <texto> detalhes em texto simples\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item (e o reabre se estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nOp\xE7\xF5es globais:\n --help, -h mostra esta ajuda\n --version, -v mostra a vers\xE3o instalada': "Utilisation\xA0: busybits <commande> [options]\n\nCommandes\xA0:\n setup installe ou met \xE0 jour les extensions et services Busybits\n start d\xE9marre le serveur au premier plan\n status affiche l'\xE9tat de l'installation et des services\n update met \xE0 jour Busybits vers la derni\xE8re version\n uninstall supprime les extensions et services install\xE9s\n pair associe cette machine comme satellite d'un Busybits central\n post d\xE9pose un \xE9l\xE9ment sur le bureau de votre bureau (la bo\xEEte de r\xE9ception)\n\nOptions de setup :\n --service installe et d\xE9marre le service utilisateur (systemd/launchd)\n --port <n> port du serveur\n --no-claude ne touche pas \xE0 Claude Code\n --no-pi ne touche pas \xE0 Pi\n --no-codex ne touche pas aux hooks Codex\n --dry-run montre seulement ce qui serait fait\n --after-update utilis\xE9 par \xAB busybits update \xBB : red\xE9marre le service m\xEAme si l'unit\xE9 n'a pas chang\xE9\n --rebuild recompile (installation depuis un clone)\n --ignore-node ignore la v\xE9rification de la version de Node\n\nOptions de update :\n --check affiche seulement la version actuelle et la derni\xE8re\n --rollback revient \xE0 la version pr\xE9c\xE9dente\n --to <version> met \xE0 jour vers cette version au lieu de la derni\xE8re\n --global met aussi \xE0 jour le busybits global (npm i -g)\n\nOptions de uninstall :\n --purge supprime aussi les donn\xE9es de Busybits\n --dry-run montre seulement ce qui serait fait\n\nOptions de pair :\n --pairing <texte> texte d'appairage de la centrale (par d\xE9faut : entr\xE9e standard)\n --label <nom> comment cette machine appara\xEEt dans le bureau\n --codex-wait installe les hooks Codex et attend votre r\xE9ponse\n\nOptions de post :\n --title <texte> titre de l'\xE9l\xE9ment (obligatoire)\n --body <texte> d\xE9tails en texte simple\n --link <url> lien http(s) que l'\xE9l\xE9ment ouvre\n --key <cl\xE9> la m\xEAme cl\xE9 met \xE0 jour l'\xE9l\xE9ment (et le rouvre s'il \xE9tait r\xE9solu)\n --source <nom> qui d\xE9pose l'\xE9l\xE9ment (affich\xE9 quand ce n'est pas un agent)\n\nOptions globales\xA0:\n --help, -h affiche cette aide\n --version, -v affiche la version install\xE9e",
11007
11088
  "No Windows, use scripts/windows/install-satellite.ps1 a partir de um clone (o busybits ainda n\xE3o instala servi\xE7o no Windows).": "Sous Windows, utilisez scripts/windows/install-satellite.ps1 depuis un clone (busybits n'installe pas encore de service sous Windows).",
11008
11089
  "comando desconhecido: {0}": "commande inconnue\xA0: {0}",
11009
11090
  "{0} precisa de um valor": "{0} n\xE9cessite une valeur",
@@ -11027,7 +11108,58 @@ var FR = {
11027
11108
  "Voltei para a v{0}.": "Retour \xE0 la v{0}.",
11028
11109
  "a vers\xE3o {0} n\xE3o tem um payload completo em {1}": "la version {0} n'a pas de payload complet dans {1}",
11029
11110
  "O Busybits precisa do Node 22.12+ ou 24, e nenhum foi encontrado. Instale um (por exemplo com o nvm: nvm install 24) e rode de novo.": "Busybits a besoin de Node 22.12+ ou 24, et aucun n'a \xE9t\xE9 trouv\xE9. Installez-en un (par exemple avec nvm : nvm install 24) et relancez.",
11030
- "servi\xE7o antigo {0} removido": "ancien service {0} supprim\xE9"
11111
+ "servi\xE7o antigo {0} removido": "ancien service {0} supprim\xE9",
11112
+ "os itens da mesa s\xF3 s\xE3o resolvidos pelo pr\xF3prio computador (http://localhost ou http://127.0.0.1)": "les \xE9l\xE9ments du bureau ne se r\xE9solvent que depuis l'ordinateur lui-m\xEAme (http://localhost ou http://127.0.0.1)",
11113
+ "s\xF3 o pr\xF3prio computador deixa itens na mesa (http://localhost ou http://127.0.0.1)": "seul l'ordinateur lui-m\xEAme d\xE9pose des \xE9l\xE9ments sur le bureau (http://localhost ou http://127.0.0.1)",
11114
+ "a mesa s\xF3 vale pelo pr\xF3prio computador ou pelo acesso remoto com login": "le bureau ne fonctionne que depuis l'ordinateur lui-m\xEAme ou par l'acc\xE8s \xE0 distance avec connexion",
11115
+ "a mesa j\xE1 tem {0} itens abertos: resolva alguns antes de deixar outros": "le bureau a d\xE9j\xE0 {0} \xE9l\xE9ments ouverts : r\xE9solvez-en avant d'en d\xE9poser d'autres",
11116
+ "item n\xE3o encontrado": "\xE9l\xE9ment introuvable",
11117
+ "inbox.json ileg\xEDvel ({0}); come\xE7ando sem itens.": "inbox.json illisible ({0}) ; d\xE9marrage sans \xE9l\xE9ments.",
11118
+ "corpo inv\xE1lido": "corps invalide",
11119
+ "t\xEDtulo obrigat\xF3rio": "titre obligatoire",
11120
+ "t\xEDtulo longo demais (m\xE1x. {0} caracteres)": "titre trop long (max {0} caract\xE8res)",
11121
+ "texto inv\xE1lido": "texte invalide",
11122
+ "texto longo demais (m\xE1x. {0} KB)": "texte trop long (max {0} Ko)",
11123
+ "link inv\xE1lido": "lien invalide",
11124
+ "o link precisa ser http ou https": "le lien doit \xEAtre http ou https",
11125
+ "chave inv\xE1lida": "cl\xE9 invalide",
11126
+ "chave longa demais (m\xE1x. {0} caracteres)": "cl\xE9 trop longue (max {0} caract\xE8res)",
11127
+ "origem inv\xE1lida": "source invalide",
11128
+ "ancestrais inv\xE1lidos": "anc\xEAtres invalides",
11129
+ 'Uso: busybits post --title <texto> [op\xE7\xF5es]\n\nDeixa um item na mesa do seu escrit\xF3rio (o painel "Mesa" abre ao clicar no monte de pap\xE9is).\n\nOp\xE7\xF5es:\n --title <texto> t\xEDtulo do item (obrigat\xF3rio, at\xE9 200 caracteres)\n --body <texto> detalhes em texto simples (at\xE9 8 KB)\n --link <url> link http(s) que o item abre\n --key <chave> a mesma chave atualiza o item em vez de duplicar (e o reabre se j\xE1 estava resolvido)\n --source <nome> quem est\xE1 deixando o item (aparece quando n\xE3o \xE9 um agente)\n\nExemplo:\n busybits post --title "ROO7-1234 rejeitado no QA" --link https://example.com/ROO7-1234 --key ROO7-1234': `Utilisation : busybits post --title <texte> [options]
11130
+
11131
+ D\xE9pose un \xE9l\xE9ment sur le bureau de votre bureau (le panneau \xAB Bureau \xBB s'ouvre en cliquant sur la pile de papiers).
11132
+
11133
+ Options :
11134
+ --title <texte> titre de l'\xE9l\xE9ment (obligatoire, jusqu'\xE0 200 caract\xE8res)
11135
+ --body <texte> d\xE9tails en texte simple (jusqu'\xE0 8 Ko)
11136
+ --link <url> lien http(s) que l'\xE9l\xE9ment ouvre
11137
+ --key <cl\xE9> la m\xEAme cl\xE9 met \xE0 jour l'\xE9l\xE9ment au lieu de le dupliquer (et le rouvre s'il \xE9tait d\xE9j\xE0 r\xE9solu)
11138
+ --source <nom> qui d\xE9pose l'\xE9l\xE9ment (affich\xE9 quand ce n'est pas un agent)
11139
+
11140
+ Exemple :
11141
+ busybits post --title "ROO7-1234 rejet\xE9 en QA" --link https://example.com/ROO7-1234 --key ROO7-1234`,
11142
+ "falta --title": "--title manquant",
11143
+ "N\xE3o consegui falar com o Busybits na porta {0}. Ele est\xE1 rodando? (busybits start; outra porta: HABBLAUD_PORT)": "Impossible de joindre Busybits sur le port {0}. Est-il lanc\xE9 ? (busybits start ; autre port : HABBLAUD_PORT)",
11144
+ "O Busybits recusou o item ({0}): {1}": "Busybits a refus\xE9 l'\xE9l\xE9ment ({0}) : {1}",
11145
+ "Item reaberto na mesa: {0}": "\xC9l\xE9ment rouvert sur le bureau : {0}",
11146
+ "Item atualizado na mesa: {0}": "\xC9l\xE9ment mis \xE0 jour sur le bureau : {0}",
11147
+ "Item deixado na mesa: {0}": "\xC9l\xE9ment d\xE9pos\xE9 sur le bureau : {0}",
11148
+ "A mesa s\xF3 funciona com o escrit\xF3rio ao vivo.": "Le bureau ne fonctionne qu'avec le bureau en direct.",
11149
+ "N\xE3o foi poss\xEDvel resolver o item (erro {0}).": "Impossible de r\xE9soudre l'\xE9l\xE9ment (erreur {0}).",
11150
+ "um agente": "un agent",
11151
+ "um script": "un script",
11152
+ "resolvido {0}": "r\xE9solu {0}",
11153
+ "de {0}": "de {0}",
11154
+ "Resolver": "R\xE9soudre",
11155
+ "Nada por aqui.": "Rien ici.",
11156
+ "Sua mesa est\xE1 limpa: nada esperando.": "Votre bureau est d\xE9gag\xE9 : rien en attente.",
11157
+ "Ocultar resolvidos": "Masquer les r\xE9solus",
11158
+ "Mostrar resolvidos ({0})": "Afficher les r\xE9solus ({0})",
11159
+ "Itens deixados na sua mesa. Clique para abrir.": "\xC9l\xE9ments laiss\xE9s sur votre bureau. Cliquez pour ouvrir.",
11160
+ "na mesa": "sur le bureau",
11161
+ "Na sua mesa": "Sur votre bureau",
11162
+ "Mensageiro": "Coursier"
11031
11163
  };
11032
11164
 
11033
11165
  // shared/locales/all.ts
@@ -11219,10 +11351,10 @@ var ALIAS_TOOLS = {
11219
11351
  dir: /\bCODEX_HOME=(?:"([^"]*)"|'([^']*)'|([^\s;&|]+))/
11220
11352
  }
11221
11353
  };
11222
- function parseToolAliases(text2, home, tool) {
11354
+ function parseToolAliases(text3, home, tool) {
11223
11355
  const { invokes, dir: dirRe } = ALIAS_TOOLS[tool];
11224
11356
  const out = [];
11225
- for (const line2 of text2.split(/\r?\n/)) {
11357
+ for (const line2 of text3.split(/\r?\n/)) {
11226
11358
  const m = ALIAS_RE.exec(line2);
11227
11359
  if (!m) continue;
11228
11360
  const body2 = m[2] ?? m[3]?.replace(/\\(.)/g, "$1") ?? "";
@@ -12067,12 +12199,12 @@ function readBody(req, max = 8 * 1024) {
12067
12199
  });
12068
12200
  }
12069
12201
  var CA_PATH = "/remote/ca.crt";
12070
- function esc(text2) {
12071
- return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
12202
+ function esc(text3) {
12203
+ return text3.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
12072
12204
  }
12073
12205
  function loginPage(opts) {
12074
12206
  const ca = opts.caDownload ? `<p class="ca">${esc(tr("Primeira vez neste celular?"))} <a href="${CA_PATH}" download="habblaud-ca.crt">${esc(tr("Instale o certificado do Habblaud"))}</a> ${esc(tr("para tirar o aviso de seguran\xE7a (confira a impress\xE3o digital que o npm run remote:setup mostrou)."))}</p>` : "";
12075
- const js = (text2) => JSON.stringify(text2).replace(/</g, "\\u003c");
12207
+ const js = (text3) => JSON.stringify(text3).replace(/</g, "\\u003c");
12076
12208
  return `<!doctype html>
12077
12209
  <html lang="${getLocale()}">
12078
12210
  <head>
@@ -12432,6 +12564,11 @@ function namespaceDelivery(machine, d) {
12432
12564
  function namespaceDetail(machine, d) {
12433
12565
  return { ...d, agent: namespaceAgent(machine, d.agent) };
12434
12566
  }
12567
+ function namespaceInboxItem(machine, i) {
12568
+ const out = { ...i, id: pre(machine, i.id), machine };
12569
+ if (i.from.kind === "agent") out.from = { kind: "agent", agentId: pre(machine, i.from.agentId) };
12570
+ return out;
12571
+ }
12435
12572
  function namespaceState(machine, s2) {
12436
12573
  const online = machine.state === "online";
12437
12574
  const id = machine.id;
@@ -12607,9 +12744,9 @@ function userEnvFile(env = process.env, home = env.HOME || homedir3()) {
12607
12744
  if (explicit) return resolve3(explicit.replace(/^~(?=\/|$)/, home));
12608
12745
  return join4(env.XDG_CONFIG_HOME?.trim() || join4(home, ".config"), "habblaud", "env");
12609
12746
  }
12610
- function parseEnvFile(text2) {
12747
+ function parseEnvFile(text3) {
12611
12748
  const out = {};
12612
- for (const raw of text2.split(/\r?\n/)) {
12749
+ for (const raw of text3.split(/\r?\n/)) {
12613
12750
  const line2 = raw.trim().replace(/^export\s+/, "");
12614
12751
  if (!line2 || line2.startsWith("#")) continue;
12615
12752
  const eq = line2.indexOf("=");
@@ -12624,14 +12761,14 @@ function parseEnvFile(text2) {
12624
12761
  }
12625
12762
  function applyUserEnvFile(env = process.env, home = env.HOME || homedir3()) {
12626
12763
  const file = userEnvFile(env, home);
12627
- let text2;
12764
+ let text3;
12628
12765
  try {
12629
- text2 = readFileSync4(file, "utf8");
12766
+ text3 = readFileSync4(file, "utf8");
12630
12767
  } catch {
12631
12768
  return void 0;
12632
12769
  }
12633
12770
  const keys = [];
12634
- for (const [k, v] of Object.entries(parseEnvFile(text2))) {
12771
+ for (const [k, v] of Object.entries(parseEnvFile(text3))) {
12635
12772
  if (env[k] !== void 0) continue;
12636
12773
  env[k] = v;
12637
12774
  keys.push(k);
@@ -12851,11 +12988,11 @@ function domainOf(url) {
12851
12988
  function str3(v) {
12852
12989
  return typeof v === "string" ? v : "";
12853
12990
  }
12854
- function make(kind, icon, text2, detail) {
12991
+ function make(kind, icon, text3, detail) {
12855
12992
  return {
12856
12993
  kind,
12857
12994
  icon,
12858
- text: truncate(maskSecrets(text2.slice(0, MAX_TEXT * 8)), MAX_TEXT),
12995
+ text: truncate(maskSecrets(text3.slice(0, MAX_TEXT * 8)), MAX_TEXT),
12859
12996
  ...detail ? { detail: truncate(maskSecrets(detail.slice(0, MAX_DETAIL * 4)), MAX_DETAIL) } : {}
12860
12997
  };
12861
12998
  }
@@ -13245,9 +13382,9 @@ function describeWords(w, depth) {
13245
13382
  if (!w.length) return void 0;
13246
13383
  const prog = basename3(w[0]);
13247
13384
  const args = w.slice(1);
13248
- const text2 = w.join(" ");
13385
+ const text3 = w.join(" ");
13249
13386
  const mk = (kind, icon, t) => make(kind, icon, t);
13250
- if (/\b(vitest|jest|pytest|phpunit|mocha|ava|rspec)\b|\b(go|cargo|deno|bun)\s+test\b|playwright\s+test|\b(npm|pnpm|yarn|bun)\s+(run\s+)?test\b|\bnode\s+--test\b|-m\s+(pytest|unittest)\b/.test(text2)) {
13387
+ if (/\b(vitest|jest|pytest|phpunit|mocha|ava|rspec)\b|\b(go|cargo|deno|bun)\s+test\b|playwright\s+test|\b(npm|pnpm|yarn|bun)\s+(run\s+)?test\b|\bnode\s+--test\b|-m\s+(pytest|unittest)\b/.test(text3)) {
13251
13388
  return mk("test", "\u{1F9EA}", tr("Rodando testes"));
13252
13389
  }
13253
13390
  if (prog === "git") {
@@ -13258,19 +13395,19 @@ function describeWords(w, depth) {
13258
13395
  return mk("git", icon, t);
13259
13396
  }
13260
13397
  if (prog === "gh") return mk("git", "\u{1F419}", tr("GitHub CLI: gh {0}", [args.slice(0, 2).join(" ")]).trim());
13261
- if (/\b(npm|pnpm|yarn|bun)\s+(i|install|add|ci)\b|\bpip3?\s+install\b|\bbrew\s+install\b|\bcomposer\s+(install|require)\b|\bpoetry\s+(add|install)\b|\bcargo\s+add\b|\bgo\s+get\b|\buv\s+(add|sync|pip\s+install)\b/.test(text2)) {
13398
+ if (/\b(npm|pnpm|yarn|bun)\s+(i|install|add|ci)\b|\bpip3?\s+install\b|\bbrew\s+install\b|\bcomposer\s+(install|require)\b|\bpoetry\s+(add|install)\b|\bcargo\s+add\b|\bgo\s+get\b|\buv\s+(add|sync|pip\s+install)\b/.test(text3)) {
13262
13399
  return mk("run", "\u{1F4E6}", tr("Instalando depend\xEAncias"));
13263
13400
  }
13264
- if (prog === "tsc" && args.includes("--noEmit") || /\b(npm|pnpm|yarn|bun)\s+(run\s+)?(typecheck|type-check|check-types)\b/.test(text2)) {
13401
+ if (prog === "tsc" && args.includes("--noEmit") || /\b(npm|pnpm|yarn|bun)\s+(run\s+)?(typecheck|type-check|check-types)\b/.test(text3)) {
13265
13402
  return mk("run", "\u{1F50D}", tr("Conferindo os tipos (TypeScript)"));
13266
13403
  }
13267
- if (/\b(npm|pnpm|yarn|bun)\s+(run\s+)?build\b|\bvite\s+build\b|^tsc\b|\bwebpack\b|\bcargo\s+build\b|\bgo\s+build\b|^make\b|\bgradle\b|\bmvn\b|\besbuild\b|\brollup\b/.test(text2)) {
13404
+ if (/\b(npm|pnpm|yarn|bun)\s+(run\s+)?build\b|\bvite\s+build\b|^tsc\b|\bwebpack\b|\bcargo\s+build\b|\bgo\s+build\b|^make\b|\bgradle\b|\bmvn\b|\besbuild\b|\brollup\b/.test(text3)) {
13268
13405
  return mk("run", "\u{1F3D7}\uFE0F", tr("Compilando o projeto"));
13269
13406
  }
13270
- if (/\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|preview)\b|^vite(\s|$)(?!build)|^(next|nuxt|astro)\s+dev\b|^expo\s+start\b|^nodemon\b|^tsx\s+watch\b/.test(text2)) {
13271
- return mk("run", "\u25B6\uFE0F", /\bpreview\b/.test(text2) ? tr("Subindo o preview do build") : tr("Subindo o servidor de dev"));
13407
+ if (/\b(npm|pnpm|yarn|bun)\s+(run\s+)?(dev|start|serve|preview)\b|^vite(\s|$)(?!build)|^(next|nuxt|astro)\s+dev\b|^expo\s+start\b|^nodemon\b|^tsx\s+watch\b/.test(text3)) {
13408
+ return mk("run", "\u25B6\uFE0F", /\bpreview\b/.test(text3) ? tr("Subindo o preview do build") : tr("Subindo o servidor de dev"));
13272
13409
  }
13273
- if (/\b(eslint|prettier|ruff|black|biome|rubocop|phpcs|stylelint|oxlint)\b|\b(npm|pnpm|yarn)\s+(run\s+)?(lint|format)\b/.test(text2)) {
13410
+ if (/\b(eslint|prettier|ruff|black|biome|rubocop|phpcs|stylelint|oxlint)\b|\b(npm|pnpm|yarn)\s+(run\s+)?(lint|format)\b/.test(text3)) {
13274
13411
  return mk("run", "\u{1F9F9}", tr("Rodando o linter"));
13275
13412
  }
13276
13413
  if (/^(npm|pnpm|yarn|bun)$/.test(prog) && args[0] === "run" && args[1]) return mk("run", "\u25B6\uFE0F", tr("Rodando o script {0}", [args[1]]));
@@ -13343,8 +13480,8 @@ function describeWords(w, depth) {
13343
13480
  if (/^(\.{0,2}\/|~\/)/.test(w[0]) || /\.(sh|bash|zsh|py|rb|mjs|js|ts)$/.test(w[0])) return mk("run", "\u25B6\uFE0F", tr("Executando {0}", [prog]));
13344
13481
  return void 0;
13345
13482
  }
13346
- function describeLine(text2, depth) {
13347
- const lines = text2.replace(/\\\r?\n/g, " ").split(/\r?\n/);
13483
+ function describeLine(text3, depth) {
13484
+ const lines = text3.replace(/\\\r?\n/g, " ").split(/\r?\n/);
13348
13485
  for (let li = 0; li < lines.length; li++) {
13349
13486
  const line2 = lines[li].trim();
13350
13487
  if (!line2 || line2.startsWith("#")) continue;
@@ -13393,8 +13530,8 @@ function describeCommand(command, description) {
13393
13530
  const desc = description?.trim();
13394
13531
  if (desc && looksPortuguese(desc)) return make("run", "\u{1F4BB}", desc, detail);
13395
13532
  const prog = basename3(found.prog ?? "");
13396
- const text2 = /^[A-Za-z][\w.+-]{0,23}$/.test(prog) ? tr("Rodando {0}", [prog]) : tr("Rodando um comando no terminal");
13397
- return make("run", "\u{1F4BB}", text2, desc ? `${desc} \u2014 ${detail}` : detail);
13533
+ const text3 = /^[A-Za-z][\w.+-]{0,23}$/.test(prog) ? tr("Rodando {0}", [prog]) : tr("Rodando um comando no terminal");
13534
+ return make("run", "\u{1F4BB}", text3, desc ? `${desc} \u2014 ${detail}` : detail);
13398
13535
  }
13399
13536
  function humanize(id) {
13400
13537
  return id.replace(/[_-]+/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").trim().toLowerCase();
@@ -13530,8 +13667,8 @@ function describeTool(name, rawInput) {
13530
13667
  return make("other", "\u{1F6E0}\uFE0F", tr("Usando {0}", [name]));
13531
13668
  }
13532
13669
  }
13533
- function describePrompt(text2) {
13534
- return make("prompt", "\u{1F4E8}", tr("Nova tarefa: \u201C{0}\u201D", [truncate(text2, 30)]), text2);
13670
+ function describePrompt(text3) {
13671
+ return make("prompt", "\u{1F4E8}", tr("Nova tarefa: \u201C{0}\u201D", [truncate(text3, 30)]), text3);
13535
13672
  }
13536
13673
  function formatDuration(ms) {
13537
13674
  const s2 = Math.round(ms / 1e3);
@@ -13563,7 +13700,7 @@ function fitLabel(prefix, label, suffix = "") {
13563
13700
  }
13564
13701
  var SPECIAL = {
13565
13702
  think: () => make("think", "\u{1F4AD}", tr("Pensando\u2026")),
13566
- respond: (text2) => make("respond", "\u{1F4AC}", tr("Escrevendo a resposta"), text2),
13703
+ respond: (text3) => make("respond", "\u{1F4AC}", tr("Escrevendo a resposta"), text3),
13567
13704
  turnDone: (ms) => make("done", "\u2705", ms ? tr("Concluiu em {0}", [formatDuration(ms)]) : tr("Concluiu")),
13568
13705
  error: (tool, detail) => make("error", "\u26A0\uFE0F", tool ? tr("Erro em {0}", [tool]) : tr("Algo deu errado"), detail),
13569
13706
  interrupted: () => make("wait", "\u270B", tr("Interrompido por voc\xEA")),
@@ -13669,9 +13806,9 @@ function readSubagentMeta(metaPath) {
13669
13806
  }
13670
13807
  }
13671
13808
  var JOURNAL_DONE = /^(completed?|finished|done|failed|errored|error|killed|cancell?ed|stopped|succeeded|result)$/i;
13672
- function parseJournal(text2) {
13809
+ function parseJournal(text3) {
13673
13810
  const out = /* @__PURE__ */ new Map();
13674
- for (const line2 of text2.split("\n")) {
13811
+ for (const line2 of text3.split("\n")) {
13675
13812
  if (!line2.trim()) continue;
13676
13813
  let j;
13677
13814
  try {
@@ -13974,8 +14111,8 @@ function scriptSegments(command) {
13974
14111
  let q = null;
13975
14112
  let depth = 0;
13976
14113
  const cut3 = (end, next) => {
13977
- const text2 = src.slice(start, end).trim();
13978
- if (text2) segs.push({ words: shellWords(text2), next });
14114
+ const text3 = src.slice(start, end).trim();
14115
+ if (text3) segs.push({ words: shellWords(text3), next });
13979
14116
  else if (segs.length && next) segs[segs.length - 1].next = next;
13980
14117
  };
13981
14118
  for (let i = 0; i < src.length; i++) {
@@ -14188,8 +14325,8 @@ function ciFromJson(j) {
14188
14325
  }
14189
14326
  return void 0;
14190
14327
  }
14191
- function parseJson(text2) {
14192
- const t = text2.trim();
14328
+ function parseJson(text3) {
14329
+ const t = text3.trim();
14193
14330
  if (!t || t[0] !== "{" && t[0] !== "[" || t.length > 2e5) return void 0;
14194
14331
  try {
14195
14332
  return JSON.parse(t);
@@ -14197,10 +14334,10 @@ function parseJson(text2) {
14197
14334
  return void 0;
14198
14335
  }
14199
14336
  }
14200
- function ciFromText(text2, ops) {
14337
+ function ciFromText(text3, ops) {
14201
14338
  const run3 = ops.includes("run_watch") || ops.includes("run_view");
14202
14339
  if (run3) {
14203
- const h = RUN_HEADER.exec(text2);
14340
+ const h = RUN_HEADER.exec(text3);
14204
14341
  if (h?.[1] === "*") return "pending";
14205
14342
  if (h) {
14206
14343
  const r = { result: h[1] === "\u2713" || h[1] === "\u2714" ? "passed" : "failed", branch: h[2] };
@@ -14208,14 +14345,14 @@ function ciFromText(text2, ops) {
14208
14345
  if (wf) r.workflow = wf;
14209
14346
  return r;
14210
14347
  }
14211
- const d = RUN_DONE.exec(text2);
14348
+ const d = RUN_DONE.exec(text3);
14212
14349
  const c = d ? conclusion(d[2]) : void 0;
14213
14350
  if (d && c) return { result: c, workflow: d[1].slice(0, 40) };
14214
14351
  }
14215
- const whole = parseJson(text2);
14352
+ const whole = parseJson(text3);
14216
14353
  const fromWhole = whole === void 0 ? void 0 : ciFromJson(whole);
14217
14354
  if (fromWhole) return fromWhole;
14218
- const lines = text2.split("\n").map((l) => l.trim()).filter(Boolean);
14355
+ const lines = text3.split("\n").map((l) => l.trim()).filter(Boolean);
14219
14356
  if (run3) {
14220
14357
  for (const l of lines.slice(0, 20)) {
14221
14358
  const j = parseJson(l);
@@ -14228,16 +14365,16 @@ function ciFromText(text2, ops) {
14228
14365
  if (c && ops.includes("run_view")) return { result: c };
14229
14366
  }
14230
14367
  if (ops.includes("pr_checks")) {
14231
- if (/\bAll checks were successful\b/.test(text2)) return { result: "passed" };
14232
- if (/\bSome checks were not successful\b/.test(text2) || /\b[1-9]\d* failing\b/.test(text2)) return { result: "failed" };
14233
- if (/\bSome checks are still pending\b/.test(text2)) return "pending";
14368
+ if (/\bAll checks were successful\b/.test(text3)) return { result: "passed" };
14369
+ if (/\bSome checks were not successful\b/.test(text3) || /\b[1-9]\d* failing\b/.test(text3)) return { result: "failed" };
14370
+ if (/\bSome checks are still pending\b/.test(text3)) return "pending";
14234
14371
  const states = lines.map((l) => /^(.+?)\t(pass|fail|pending|skipping|cancel)\t/.exec(l)).filter((m) => !!m).map((m) => ({ name: m[1], state: m[2] }));
14235
14372
  return aggregateChecks(states);
14236
14373
  }
14237
14374
  return void 0;
14238
14375
  }
14239
- function exitCodeOf(text2) {
14240
- const m = /^Exit code (\d+)/.exec(text2.trimStart());
14376
+ function exitCodeOf(text3) {
14377
+ const m = /^Exit code (\d+)/.exec(text3.trimStart());
14241
14378
  return m ? Number(m[1]) : void 0;
14242
14379
  }
14243
14380
  function ciFromExit(call2, code2) {
@@ -14281,41 +14418,41 @@ function gitOperationEvent(call2, tur) {
14281
14418
  return void 0;
14282
14419
  }
14283
14420
  function detectGitHubResult(call2, r) {
14284
- let text2 = textOf(r.content);
14285
- if (!text2 && typeof r.tur.stdout === "string") text2 = `${r.tur.stdout}
14421
+ let text3 = textOf(r.content);
14422
+ if (!text3 && typeof r.tur.stdout === "string") text3 = `${r.tur.stdout}
14286
14423
  ${typeof r.tur.stderr === "string" ? r.tur.stderr : ""}`;
14287
- text2 = text2.slice(0, 2e5);
14424
+ text3 = text3.slice(0, 2e5);
14288
14425
  const ops = call2.ops;
14289
- if (call2.tool !== "Bash") return mcpEvent(call2, text2, r.isError, r.branch);
14426
+ if (call2.tool !== "Bash") return mcpEvent(call2, text3, r.isError, r.branch);
14290
14427
  if (!r.isError) {
14291
14428
  const fromOp = gitOperationEvent(call2, r.tur);
14292
14429
  if (fromOp) return fromOp;
14293
14430
  }
14294
- if (ops.includes("pr_merge") && !call2.auto && !r.isError && !MERGE_FAIL.test(text2)) {
14431
+ if (ops.includes("pr_merge") && !call2.auto && !r.isError && !MERGE_FAIL.test(text3)) {
14295
14432
  const ev = { kind: "pr_merged" };
14296
- const n2 = call2.number ?? num2(/\bpull request (?:[\w.-]+\/[\w.-]+)?#(\d+)/i.exec(text2)?.[1]);
14433
+ const n2 = call2.number ?? num2(/\bpull request (?:[\w.-]+\/[\w.-]+)?#(\d+)/i.exec(text3)?.[1]);
14297
14434
  if (n2 !== void 0) ev.number = n2;
14298
14435
  if (call2.repo) ev.repo = call2.repo;
14299
14436
  return ev;
14300
14437
  }
14301
- if (ops.includes("pr_create") && !r.isError && !PR_EXISTS.test(text2)) {
14302
- const urls = [...text2.matchAll(PR_URL)];
14438
+ if (ops.includes("pr_create") && !r.isError && !PR_EXISTS.test(text3)) {
14439
+ const urls = [...text3.matchAll(PR_URL)];
14303
14440
  const m = urls.at(-1);
14304
14441
  if (m) return { kind: "pr_opened", number: Number(m[2]), repo: m[1], url: m[0] };
14305
14442
  }
14306
14443
  if (ops.includes("release_create") && !call2.draft && !r.isError) {
14307
- const m = RELEASE_URL.exec(text2);
14444
+ const m = RELEASE_URL.exec(text3);
14308
14445
  if (m && !m[2].startsWith("untagged-")) return { kind: "release", tag: safeDecode(m[2]).slice(0, 60), repo: m[1], url: m[0] };
14309
14446
  }
14310
14447
  if (ops.some((o) => o === "run_watch" || o === "run_view" || o === "pr_checks")) {
14311
- const read = ciFromText(text2, ops);
14312
- const code2 = r.isError ? exitCodeOf(text2) : 0;
14448
+ const read = ciFromText(text3, ops);
14449
+ const code2 = r.isError ? exitCodeOf(text3) : 0;
14313
14450
  const ci = read === "pending" ? void 0 : read ?? (code2 !== void 0 ? ciFromExit(call2, code2) : void 0);
14314
14451
  if (ci) return ciEvent(call2, ci, r.branch);
14315
14452
  }
14316
- if (ops.includes("push") && !call2.noPush && !PUSH_FAIL.test(text2)) {
14317
- const to = PUSH_TO.exec(text2);
14318
- const m = to ? PUSH_OK.exec(text2.slice(to.index)) : null;
14453
+ if (ops.includes("push") && !call2.noPush && !PUSH_FAIL.test(text3)) {
14454
+ const to = PUSH_TO.exec(text3);
14455
+ const m = to ? PUSH_OK.exec(text3.slice(to.index)) : null;
14319
14456
  if (m) return { kind: "push", branch: m[1].replace(/^refs\/heads\//, "") };
14320
14457
  }
14321
14458
  return void 0;
@@ -14327,13 +14464,13 @@ function safeDecode(s2) {
14327
14464
  return s2;
14328
14465
  }
14329
14466
  }
14330
- function mcpEvent(call2, text2, isError, branch) {
14467
+ function mcpEvent(call2, text3, isError, branch) {
14331
14468
  if (isError) return void 0;
14332
14469
  const op = call2.ops[0];
14333
- const j = parseJson(text2);
14470
+ const j = parseJson(text3);
14334
14471
  const o = j && typeof j === "object" && !Array.isArray(j) ? j : void 0;
14335
14472
  if (op === "pr_create") {
14336
- const m = [...text2.matchAll(PR_URL)][0];
14473
+ const m = [...text3.matchAll(PR_URL)][0];
14337
14474
  const n2 = (m ? Number(m[2]) : void 0) ?? num2(o?.number);
14338
14475
  if (n2 === void 0) return void 0;
14339
14476
  const ev = { kind: "pr_opened", number: n2 };
@@ -14343,7 +14480,7 @@ function mcpEvent(call2, text2, isError, branch) {
14343
14480
  return ev;
14344
14481
  }
14345
14482
  if (op === "pr_merge") {
14346
- const merged = o ? o.merged === true : /\bmerged\b/i.test(text2) && !MERGE_FAIL.test(text2);
14483
+ const merged = o ? o.merged === true : /\bmerged\b/i.test(text3) && !MERGE_FAIL.test(text3);
14347
14484
  if (!merged) return void 0;
14348
14485
  const ev = { kind: "pr_merged" };
14349
14486
  if (call2.number !== void 0) ev.number = call2.number;
@@ -14723,8 +14860,8 @@ function firstLine(s2, max = 140) {
14723
14860
  const line2 = s2.split("\n").find((l) => l.trim());
14724
14861
  return line2 ? truncate(line2.replace(/<\/?[a-z_-]+>/gi, ""), max) : void 0;
14725
14862
  }
14726
- function parseTaskNotification(text2) {
14727
- const tag = (name) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(text2)?.[1]?.trim() || void 0;
14863
+ function parseTaskNotification(text3) {
14864
+ const tag = (name) => new RegExp(`<${name}>([\\s\\S]*?)</${name}>`).exec(text3)?.[1]?.trim() || void 0;
14728
14865
  return {
14729
14866
  taskId: tag("task-id") ?? tag("task_id"),
14730
14867
  toolUseId: tag("tool-use-id") ?? tag("tool_use_id"),
@@ -14944,8 +15081,8 @@ var LineParser = class {
14944
15081
  if (cur?.kind === "think" && (cur.msgId === msgId || this.at - cur.at < 3e4)) return;
14945
15082
  this.push(SPECIAL.think(), { suffix, msgId });
14946
15083
  } else if (b.type === "text") {
14947
- const text2 = str5(b.text);
14948
- if (text2) this.push(SPECIAL.respond(text2), { suffix, msgId });
15084
+ const text3 = str5(b.text);
15085
+ if (text3) this.push(SPECIAL.respond(text3), { suffix, msgId });
14949
15086
  } else if (b.type === "tool_use") {
14950
15087
  this.toolUse(b, suffix, msgId);
14951
15088
  }
@@ -15080,15 +15217,15 @@ var LineParser = class {
15080
15217
  this.push(SPECIAL.interrupted(), { suffix: ":int" });
15081
15218
  }
15082
15219
  userText(raw) {
15083
- const text2 = raw.trimStart();
15084
- if (!text2) return;
15085
- if (text2.includes("<task-notification>")) return this.notification(text2, true);
15086
- if (INTERRUPTED.test(text2)) return this.interrupted();
15087
- if (SYSTEM_TAG.test(text2) || text2.startsWith("Caveat:")) return;
15088
- let prompt = text2;
15089
- if (/^<command-(name|message|args)>/.test(text2)) {
15090
- const cmd = /<command-name>([\s\S]*?)<\/command-name>/.exec(text2)?.[1]?.trim();
15091
- const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text2)?.[1]?.trim() ?? "";
15220
+ const text3 = raw.trimStart();
15221
+ if (!text3) return;
15222
+ if (text3.includes("<task-notification>")) return this.notification(text3, true);
15223
+ if (INTERRUPTED.test(text3)) return this.interrupted();
15224
+ if (SYSTEM_TAG.test(text3) || text3.startsWith("Caveat:")) return;
15225
+ let prompt = text3;
15226
+ if (/^<command-(name|message|args)>/.test(text3)) {
15227
+ const cmd = /<command-name>([\s\S]*?)<\/command-name>/.exec(text3)?.[1]?.trim();
15228
+ const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text3)?.[1]?.trim() ?? "";
15092
15229
  if (!cmd || LOCAL_COMMANDS.has(cmd)) return;
15093
15230
  prompt = `${cmd} ${args}`.trim();
15094
15231
  }
@@ -15096,8 +15233,8 @@ var LineParser = class {
15096
15233
  this.meta("lastPrompt", truncate(maskSecrets(prompt.slice(0, 1e3)), 200));
15097
15234
  this.push(describePrompt(prompt));
15098
15235
  }
15099
- notification(text2, withActivity) {
15100
- const n2 = parseTaskNotification(text2);
15236
+ notification(text3, withActivity) {
15237
+ const n2 = parseTaskNotification(text3);
15101
15238
  const sig = { type: "notification" };
15102
15239
  if (n2.toolUseId) sig.toolUseId = n2.toolUseId;
15103
15240
  if (n2.taskId) sig.taskId = n2.taskId;
@@ -15207,9 +15344,9 @@ var LineParser = class {
15207
15344
  }
15208
15345
  }
15209
15346
  };
15210
- function forkDirective(text2) {
15211
- const end = text2.lastIndexOf("</fork-boilerplate>");
15212
- const rest = end >= 0 ? text2.slice(end + "</fork-boilerplate>".length) : text2;
15347
+ function forkDirective(text3) {
15348
+ const end = text3.lastIndexOf("</fork-boilerplate>");
15349
+ const rest = end >= 0 ? text3.slice(end + "</fork-boilerplate>".length) : text3;
15213
15350
  return rest.trim().replace(/^your directive:\s*/i, "").trim();
15214
15351
  }
15215
15352
  var PRESCAN_MIN_CHARS = 64 * 1024;
@@ -15414,8 +15551,8 @@ function marked(p) {
15414
15551
  \u2026` : p.text;
15415
15552
  }
15416
15553
  function oneLine(raw, max, reminders = true) {
15417
- const { text: text2, cut: cut3 } = safeText(raw, max * 4 + TAIL_GUARD * 2, reminders);
15418
- const lines = text2.split("\n");
15554
+ const { text: text3, cut: cut3 } = safeText(raw, max * 4 + TAIL_GUARD * 2, reminders);
15555
+ const lines = text3.split("\n");
15419
15556
  const i = lines.findIndex((l) => l.trim());
15420
15557
  if (i < 0) return "";
15421
15558
  const line2 = truncate(lines[i], max);
@@ -15427,10 +15564,10 @@ function lineAndDetail(raw, max = SYSTEM_TEXT_MAX) {
15427
15564
  return line2.endsWith("\u2026") ? { line: line2, detail: raw } : { line: line2 };
15428
15565
  }
15429
15566
  var TAGS = /* @__PURE__ */ new Map();
15430
- function inner(text2, tag) {
15567
+ function inner(text3, tag) {
15431
15568
  let re = TAGS.get(tag);
15432
15569
  if (!re) TAGS.set(tag, re = new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`));
15433
- return re.exec(text2)?.[1];
15570
+ return re.exec(text3)?.[1];
15434
15571
  }
15435
15572
  function relPath(p, cwd) {
15436
15573
  if (!cwd || !p.startsWith("/")) return p;
@@ -15467,8 +15604,8 @@ function jsonInput(input, omit = [], cwd) {
15467
15604
  }
15468
15605
  return textInput(json, "json");
15469
15606
  }
15470
- function prefixLines(text2, prefix, budget, sourceCut) {
15471
- const src = text2.replace(/\n$/, "");
15607
+ function prefixLines(text3, prefix, budget, sourceCut) {
15608
+ const src = text3.replace(/\n$/, "");
15472
15609
  const out = [];
15473
15610
  let used = 0;
15474
15611
  let start = 0;
@@ -15497,8 +15634,8 @@ function diffText(oldRaw, newRaw, budget = INPUT_MAX) {
15497
15634
  return [oldPart, newPart].filter(Boolean).join("\n");
15498
15635
  }
15499
15636
  function diffInput(oldRaw, newRaw) {
15500
- const text2 = diffText(oldRaw, newRaw);
15501
- return text2 ? { input: text2, inputKind: "diff" } : {};
15637
+ const text3 = diffText(oldRaw, newRaw);
15638
+ return text3 ? { input: text3, inputKind: "diff" } : {};
15502
15639
  }
15503
15640
  var TODO_MARK = { completed: "\u2612", in_progress: "\u25D0", pending: "\u2610" };
15504
15641
  var TASK_STATUS = { completed: tr("conclu\xEDda"), in_progress: tr("em andamento"), pending: "pendente", deleted: "removida" };
@@ -15531,8 +15668,8 @@ function toolView(name, input, cwd) {
15531
15668
  case "MultiEdit": {
15532
15669
  const edits = Array.isArray(input.edits) ? input.edits.map(rec2).filter((e) => !!e) : [];
15533
15670
  const per = Math.max(200, Math.floor(INPUT_MAX / Math.max(1, edits.length)));
15534
- const text2 = edits.slice(0, 12).map((e) => diffText(typeof e.old_string === "string" ? e.old_string : "", typeof e.new_string === "string" ? e.new_string : "", per)).filter(Boolean).join("\n@@\n");
15535
- return { title: titled("MultiEdit", rel2), ...text2 ? { input: marked(clip(text2, INPUT_MAX)), inputKind: "diff" } : {} };
15671
+ const text3 = edits.slice(0, 12).map((e) => diffText(typeof e.old_string === "string" ? e.old_string : "", typeof e.new_string === "string" ? e.new_string : "", per)).filter(Boolean).join("\n@@\n");
15672
+ return { title: titled("MultiEdit", rel2), ...text3 ? { input: marked(clip(text3, INPUT_MAX)), inputKind: "diff" } : {} };
15536
15673
  }
15537
15674
  case "Write":
15538
15675
  return { title: titled("Write", rel2), ...diffInput("", typeof input.content === "string" ? input.content : "") };
@@ -15666,13 +15803,13 @@ var Parser = class {
15666
15803
  }
15667
15804
  // ---------------------------------------------------------------- entradas
15668
15805
  userEntry(c, raw) {
15669
- const text2 = marked(prepare(raw, TEXT_MAX));
15670
- if (text2) this.emit({ kind: "user", id: `${c.uuid}:u`, at: c.at, text: text2 });
15806
+ const text3 = marked(prepare(raw, TEXT_MAX));
15807
+ if (text3) this.emit({ kind: "user", id: `${c.uuid}:u`, at: c.at, text: text3 });
15671
15808
  }
15672
15809
  /** `text` deve vir numa linha só (oneLine) ou ser fixo; a máscara aqui é a última garantia. */
15673
- sys(c, text2, o = {}) {
15674
- if (!text2) return;
15675
- const e = { kind: "system", id: `${c.uuid}${o.suffix ?? ":s"}`, at: c.at, text: maskSecrets(text2), level: o.level ?? "info" };
15810
+ sys(c, text3, o = {}) {
15811
+ if (!text3) return;
15812
+ const e = { kind: "system", id: `${c.uuid}${o.suffix ?? ":s"}`, at: c.at, text: maskSecrets(text3), level: o.level ?? "info" };
15676
15813
  if (o.turnDone) {
15677
15814
  e.turnDone = true;
15678
15815
  e.doneLabel = tr("pronto {0}", ["{0}"]);
@@ -15695,8 +15832,8 @@ var Parser = class {
15695
15832
  if (j.isMeta === true) return;
15696
15833
  const content = rec2(j.message)?.content;
15697
15834
  if (j.isCompactSummary === true) {
15698
- const text2 = typeof content === "string" ? content : resultText(content);
15699
- this.sys(c, tr("Resumo da conversa compactada"), { detail: text2 });
15835
+ const text3 = typeof content === "string" ? content : resultText(content);
15836
+ this.sys(c, tr("Resumo da conversa compactada"), { detail: text3 });
15700
15837
  return;
15701
15838
  }
15702
15839
  if (typeof content === "string") return this.userText(c, content);
@@ -15724,59 +15861,59 @@ var Parser = class {
15724
15861
  if (texts.length || images && !results) this.userText(c, texts.join("\n"), results ? 0 : images);
15725
15862
  }
15726
15863
  userText(c, raw, images = 0) {
15727
- const text2 = (raw.includes("<system-reminder>") ? raw.replace(REMINDER, "") : raw).trim();
15864
+ const text3 = (raw.includes("<system-reminder>") ? raw.replace(REMINDER, "") : raw).trim();
15728
15865
  const pics = images ? Array.from({ length: Math.min(images, 10) }, () => tr("[imagem]")).join(" ") : "";
15729
- if (!text2) {
15866
+ if (!text3) {
15730
15867
  if (pics) this.userEntry(c, pics);
15731
15868
  return;
15732
15869
  }
15733
- if (text2.startsWith("<task-notification>")) return this.notification(c, text2);
15734
- if (INTERRUPTED2.test(text2)) return this.sys(c, tr("Interrompido pelo usu\xE1rio"), { level: "warn" });
15735
- if (text2.startsWith("Caveat:")) return;
15736
- const tag = /^<([a-z][\w-]*)/.exec(text2)?.[1];
15870
+ if (text3.startsWith("<task-notification>")) return this.notification(c, text3);
15871
+ if (INTERRUPTED2.test(text3)) return this.sys(c, tr("Interrompido pelo usu\xE1rio"), { level: "warn" });
15872
+ if (text3.startsWith("Caveat:")) return;
15873
+ const tag = /^<([a-z][\w-]*)/.exec(text3)?.[1];
15737
15874
  switch (tag) {
15738
15875
  case "command-name":
15739
15876
  case "command-message":
15740
15877
  case "command-args": {
15741
- const msg = inner(text2, "command-message")?.trim();
15742
- const name = inner(text2, "command-name")?.trim() || (msg ? `/${msg}` : void 0);
15878
+ const msg = inner(text3, "command-message")?.trim();
15879
+ const name = inner(text3, "command-name")?.trim() || (msg ? `/${msg}` : void 0);
15743
15880
  if (!name) return;
15744
15881
  const cmd = name.startsWith("/") ? name : `/${name}`;
15745
15882
  this.lastCommand = cmd;
15746
- this.userEntry(c, `${cmd} ${inner(text2, "command-args")?.trim() ?? ""}`.trim());
15883
+ this.userEntry(c, `${cmd} ${inner(text3, "command-args")?.trim() ?? ""}`.trim());
15747
15884
  return;
15748
15885
  }
15749
15886
  case "local-command-stdout":
15750
15887
  case "local-command-stderr":
15751
15888
  case "command-stdout":
15752
15889
  case "command-stderr": {
15753
- const out = OUTPUT_TAGS.map((t) => inner(text2, t)?.trim()).filter(Boolean).join("\n");
15890
+ const out = OUTPUT_TAGS.map((t) => inner(text3, t)?.trim()).filter(Boolean).join("\n");
15754
15891
  if (out) this.sys(c, this.lastCommand ? tr("Sa\xEDda de {0}", [this.lastCommand]) : tr("Sa\xEDda do comando"), { detail: out });
15755
15892
  return;
15756
15893
  }
15757
15894
  case "bash-input": {
15758
- const cmd = inner(text2, "bash-input")?.trim();
15895
+ const cmd = inner(text3, "bash-input")?.trim();
15759
15896
  if (cmd) this.userEntry(c, `! ${cmd}`);
15760
15897
  return;
15761
15898
  }
15762
15899
  case "bash-stdout":
15763
15900
  case "bash-stderr": {
15764
- const out = [inner(text2, "bash-stdout"), inner(text2, "bash-stderr")].map((x) => x?.trim()).filter(Boolean).join("\n");
15901
+ const out = [inner(text3, "bash-stdout"), inner(text3, "bash-stderr")].map((x) => x?.trim()).filter(Boolean).join("\n");
15765
15902
  this.sys(c, tr("Sa\xEDda do comando"), { detail: out || tr("(sem sa\xEDda)") });
15766
15903
  return;
15767
15904
  }
15768
15905
  case "scheduled-task": {
15769
- const body2 = text2.replace(/^<scheduled-task\b[^>]*>/, "").replace(/<\/scheduled-task>\s*$/, "");
15906
+ const body2 = text3.replace(/^<scheduled-task\b[^>]*>/, "").replace(/<\/scheduled-task>\s*$/, "");
15770
15907
  if (body2.trim()) this.userEntry(c, body2);
15771
15908
  return;
15772
15909
  }
15773
15910
  case "fork-boilerplate": {
15774
- const directive = forkDirective(text2);
15911
+ const directive = forkDirective(text3);
15775
15912
  if (directive) this.userEntry(c, directive);
15776
15913
  return;
15777
15914
  }
15778
15915
  case "user-memory-input": {
15779
- const memory = inner(text2, "user-memory-input")?.trim();
15916
+ const memory = inner(text3, "user-memory-input")?.trim();
15780
15917
  if (memory) this.userEntry(c, `# ${memory}`);
15781
15918
  return;
15782
15919
  }
@@ -15786,14 +15923,14 @@ var Parser = class {
15786
15923
  default:
15787
15924
  break;
15788
15925
  }
15789
- this.userEntry(c, pics && !/\[Image\b/.test(text2) ? `${text2}
15790
- ${pics}` : text2);
15926
+ this.userEntry(c, pics && !/\[Image\b/.test(text3) ? `${text3}
15927
+ ${pics}` : text3);
15791
15928
  }
15792
- notification(c, text2) {
15793
- const n2 = parseTaskNotification(text2);
15929
+ notification(c, text3) {
15930
+ const n2 = parseTaskNotification(text3);
15794
15931
  const status2 = n2.status?.toLowerCase();
15795
- const result = inner(text2, "result")?.trim();
15796
- const event = inner(text2, "event")?.trim();
15932
+ const result = inner(text3, "result")?.trim();
15933
+ const event = inner(text3, "event")?.trim();
15797
15934
  let label = tr("Notifica\xE7\xE3o de tarefa em segundo plano");
15798
15935
  let level = "info";
15799
15936
  if (status2 === "completed") label = tr("Tarefa em segundo plano conclu\xEDda");
@@ -15852,8 +15989,8 @@ ${pics}` : text2);
15852
15989
  }
15853
15990
  const synthetic = m.model === "<synthetic>";
15854
15991
  if (c.j.isApiErrorMessage === true || synthetic && str6(c.j.error)) {
15855
- const text2 = blocks.map((b) => rec2(b)?.text).filter((t) => typeof t === "string").join("\n");
15856
- return this.sysContent(c, text2 || tr("Erro da API"), "error");
15992
+ const text3 = blocks.map((b) => rec2(b)?.text).filter((t) => typeof t === "string").join("\n");
15993
+ return this.sysContent(c, text3 || tr("Erro da API"), "error");
15857
15994
  }
15858
15995
  const msgId = str6(m.id) ?? c.uuid;
15859
15996
  blocks.forEach((raw, i) => {
@@ -15868,8 +16005,8 @@ ${pics}` : text2);
15868
16005
  if (!NO_RESPONSE.test(t.trim())) this.sysContent(c, t, "info", void 0, `:${i}`);
15869
16006
  return;
15870
16007
  }
15871
- const text2 = marked(prepare(t, TEXT_MAX));
15872
- if (text2) this.emit({ kind: "assistant", id, at: c.at, text: text2 });
16008
+ const text3 = marked(prepare(t, TEXT_MAX));
16009
+ if (text3) this.emit({ kind: "assistant", id, at: c.at, text: text3 });
15873
16010
  return;
15874
16011
  }
15875
16012
  case "thinking":
@@ -15879,8 +16016,8 @@ ${pics}` : text2);
15879
16016
  if (this.repeated(msgId, `k${t.length}:${t.slice(0, 64)}:${sig.length}:${sig.slice(-24)}`)) return;
15880
16017
  const e = { kind: "thinking", id, at: c.at };
15881
16018
  if (b.type === "thinking" && t.trim()) {
15882
- const text2 = marked(prepare(t, THINKING_MAX));
15883
- if (text2) e.text = text2;
16019
+ const text3 = marked(prepare(t, THINKING_MAX));
16020
+ if (text3) e.text = text3;
15884
16021
  }
15885
16022
  this.emit(e);
15886
16023
  return;
@@ -15939,9 +16076,9 @@ ${pics}` : text2);
15939
16076
  attachment(c) {
15940
16077
  const a = rec2(c.j.attachment);
15941
16078
  if (!a || a.type !== "queued_command" || a.isMeta === true || c.j.isMeta === true) return;
15942
- let text2 = "";
16079
+ let text3 = "";
15943
16080
  let images = 0;
15944
- if (typeof a.prompt === "string") text2 = a.prompt;
16081
+ if (typeof a.prompt === "string") text3 = a.prompt;
15945
16082
  else if (Array.isArray(a.prompt)) {
15946
16083
  const texts = [];
15947
16084
  for (const raw of a.prompt) {
@@ -15949,11 +16086,11 @@ ${pics}` : text2);
15949
16086
  if (b?.type === "text" && typeof b.text === "string") texts.push(b.text);
15950
16087
  else if (b?.type === "image") images++;
15951
16088
  }
15952
- text2 = texts.join("\n");
16089
+ text3 = texts.join("\n");
15953
16090
  }
15954
- if (text2.trimStart().startsWith("<task-notification>")) return this.notification(c, text2.trim());
16091
+ if (text3.trimStart().startsWith("<task-notification>")) return this.notification(c, text3.trim());
15955
16092
  if (a.commandMode !== void 0 && a.commandMode !== "prompt") return;
15956
- this.userText(c, text2, images);
16093
+ this.userText(c, text3, images);
15957
16094
  }
15958
16095
  };
15959
16096
  function createTerminalParser() {
@@ -17199,8 +17336,8 @@ async function readSessionMeta(path, size) {
17199
17336
  function isTitleLine(line2) {
17200
17337
  return TITLE_MARKERS.some((m) => line2.includes(m));
17201
17338
  }
17202
- function splitLines(text2, dropFirst, dropLast) {
17203
- const lines = text2.split("\n");
17339
+ function splitLines(text3, dropFirst, dropLast) {
17340
+ const lines = text3.split("\n");
17204
17341
  if (dropFirst) lines.shift();
17205
17342
  if (dropLast) lines.pop();
17206
17343
  return lines.map((l) => l.replace(/\r$/, "")).filter((l) => l.trim());
@@ -18231,6 +18368,96 @@ function checkFile(path, fs = { realpath: process.platform === "win32" ? realpat
18231
18368
  // server/central/hub.ts
18232
18369
  import { randomBytes as randomBytes3 } from "node:crypto";
18233
18370
 
18371
+ // shared/inbox.ts
18372
+ var INBOX_TITLE_MAX = 200;
18373
+ var INBOX_BODY_MAX_BYTES = 8 * 1024;
18374
+ var INBOX_KEY_MAX = 128;
18375
+ var INBOX_SOURCE_MAX = 64;
18376
+ var INBOX_LINK_MAX = 2048;
18377
+ var INBOX_OPEN_MAX = 200;
18378
+ var INBOX_RESOLVED_KEEP_MS = 7 * 24 * 60 * 60 * 1e3;
18379
+ var INBOX_RESOLVED_SHOWN = 20;
18380
+ var INBOX_ANCESTORS_MAX = 64;
18381
+ var utf8Len = (s2) => new TextEncoder().encode(s2).length;
18382
+ var BAD = /* @__PURE__ */ Symbol("bad");
18383
+ function text2(v) {
18384
+ if (v === void 0 || v === null) return void 0;
18385
+ return typeof v === "string" ? v : BAD;
18386
+ }
18387
+ function isHttpUrl(v) {
18388
+ try {
18389
+ const u = new URL(v);
18390
+ return u.protocol === "http:" || u.protocol === "https:";
18391
+ } catch {
18392
+ return false;
18393
+ }
18394
+ }
18395
+ function parseInboxPost(raw) {
18396
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, error: tr("corpo inv\xE1lido") };
18397
+ const r = raw;
18398
+ const rawTitle = text2(r.title);
18399
+ const title = typeof rawTitle === "string" ? rawTitle.trim() : "";
18400
+ if (!title) return { ok: false, error: tr("t\xEDtulo obrigat\xF3rio") };
18401
+ if (title.length > INBOX_TITLE_MAX) return { ok: false, error: tr("t\xEDtulo longo demais (m\xE1x. {0} caracteres)", [INBOX_TITLE_MAX]) };
18402
+ const post = { title, ancestors: [] };
18403
+ const body2 = text2(r.body);
18404
+ if (body2 === BAD) return { ok: false, error: tr("texto inv\xE1lido") };
18405
+ if (body2 !== void 0 && body2.trim()) {
18406
+ if (utf8Len(body2) > INBOX_BODY_MAX_BYTES) return { ok: false, error: tr("texto longo demais (m\xE1x. {0} KB)", [INBOX_BODY_MAX_BYTES / 1024]) };
18407
+ post.body = body2;
18408
+ }
18409
+ const rawLink = text2(r.link);
18410
+ if (rawLink === BAD) return { ok: false, error: tr("link inv\xE1lido") };
18411
+ const link = rawLink?.trim();
18412
+ if (link) {
18413
+ if (link.length > INBOX_LINK_MAX || !isHttpUrl(link)) return { ok: false, error: tr("o link precisa ser http ou https") };
18414
+ post.link = link;
18415
+ }
18416
+ const rawKey = text2(r.key);
18417
+ if (rawKey === BAD) return { ok: false, error: tr("chave inv\xE1lida") };
18418
+ const key = rawKey?.trim();
18419
+ if (key) {
18420
+ if (key.length > INBOX_KEY_MAX) return { ok: false, error: tr("chave longa demais (m\xE1x. {0} caracteres)", [INBOX_KEY_MAX]) };
18421
+ post.key = key;
18422
+ }
18423
+ const rawSource = text2(r.source);
18424
+ if (rawSource === BAD) return { ok: false, error: tr("origem inv\xE1lida") };
18425
+ const source = rawSource?.trim();
18426
+ if (source) post.source = source.slice(0, INBOX_SOURCE_MAX);
18427
+ if (r.ancestors !== void 0) {
18428
+ if (!Array.isArray(r.ancestors)) return { ok: false, error: tr("ancestrais inv\xE1lidos") };
18429
+ post.ancestors = r.ancestors.filter((n2) => Number.isInteger(n2) && n2 > 0).slice(0, INBOX_ANCESTORS_MAX);
18430
+ }
18431
+ return { ok: true, post };
18432
+ }
18433
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18434
+ var num5 = (v) => typeof v === "number" && Number.isFinite(v);
18435
+ function parseSender(v) {
18436
+ if (!isObj(v)) return void 0;
18437
+ if (v.kind === "agent" && typeof v.agentId === "string" && v.agentId) return { kind: "agent", agentId: v.agentId };
18438
+ if (v.kind === "script" && (v.name === void 0 || typeof v.name === "string")) return { kind: "script", ...typeof v.name === "string" ? { name: v.name } : {} };
18439
+ return void 0;
18440
+ }
18441
+ function parseInboxItem(v) {
18442
+ if (!isObj(v)) return void 0;
18443
+ const from = parseSender(v.from);
18444
+ if (typeof v.id !== "string" || !v.id || typeof v.title !== "string" || !v.title || !from) return void 0;
18445
+ if (v.status !== "open" && v.status !== "resolved") return void 0;
18446
+ if (!num5(v.createdAt) || !num5(v.updatedAt)) return void 0;
18447
+ const item = { id: v.id, title: v.title.slice(0, INBOX_TITLE_MAX), from, scope: "local", status: v.status, createdAt: v.createdAt, updatedAt: v.updatedAt };
18448
+ if (typeof v.key === "string" && v.key) item.key = v.key.slice(0, INBOX_KEY_MAX);
18449
+ if (typeof v.body === "string" && utf8Len(v.body) <= INBOX_BODY_MAX_BYTES) item.body = v.body;
18450
+ if (typeof v.link === "string" && v.link.length <= INBOX_LINK_MAX && isHttpUrl(v.link)) item.link = v.link;
18451
+ if (num5(v.resolvedAt)) item.resolvedAt = v.resolvedAt;
18452
+ if (typeof v.machine === "string" && v.machine) item.machine = v.machine;
18453
+ return item;
18454
+ }
18455
+ function visibleInbox(items, resolvedShown = INBOX_RESOLVED_SHOWN) {
18456
+ const open3 = items.filter((i) => i.status === "open").sort((a, b) => b.updatedAt - a.updatedAt);
18457
+ const done = items.filter((i) => i.status === "resolved").sort((a, b) => (b.resolvedAt ?? b.updatedAt) - (a.resolvedAt ?? a.updatedAt)).slice(0, resolvedShown);
18458
+ return [...open3, ...done];
18459
+ }
18460
+
18234
18461
  // server/host-wait.ts
18235
18462
  var HOST_WAIT_MS = 2e4;
18236
18463
  var HostWait = class {
@@ -18282,11 +18509,11 @@ async function pollWithWait(wait, take, ms, signal) {
18282
18509
  }
18283
18510
 
18284
18511
  // shared/perf.ts
18285
- var num5 = (v) => typeof v === "number" && Number.isFinite(v);
18512
+ var num6 = (v) => typeof v === "number" && Number.isFinite(v);
18286
18513
  var rec3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18287
- var allNum = (o, keys) => rec3(o) && keys.every((k) => num5(o[k]));
18514
+ var allNum = (o, keys) => rec3(o) && keys.every((k) => num6(o[k]));
18288
18515
  function parsePerfSample(body2) {
18289
- if (!rec3(body2) || !num5(body2.at) || !num5(body2.uptime)) return void 0;
18516
+ if (!rec3(body2) || !num6(body2.at) || !num6(body2.uptime)) return void 0;
18290
18517
  const { cpu, memory, eventLoop, work } = body2;
18291
18518
  if (!allNum(cpu, ["oneCore", "allCores"]) || !allNum(memory, ["rss", "heapUsed", "external"])) return void 0;
18292
18519
  if (!allNum(eventLoop, ["p50", "p99", "max"])) return void 0;
@@ -18497,27 +18724,31 @@ var DELIVERED_GRACE_MS = 5e3;
18497
18724
  var SEEN_MAX2 = 1e3;
18498
18725
  var TICK_MS = 1e3;
18499
18726
  var weigh = (a) => (a.type === "message.send" ? a.text.length + a.images.reduce((n2, i) => n2 + i.data.length, 0) : 0) + 512;
18500
- var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18727
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18501
18728
  var isStr = (v) => typeof v === "string";
18502
18729
  var bad = () => {
18503
18730
  throw new HttpError(400, tr("JSON inv\xE1lido"));
18504
18731
  };
18505
- var all = (v, ok) => Array.isArray(v) && v.every((x) => isObj(x) && ok(x));
18732
+ var all = (v, ok) => Array.isArray(v) && v.every((x) => isObj2(x) && ok(x));
18506
18733
  function validState(body2) {
18507
- if (!isObj(body2) || body2.protocol !== 1 || !isStr(body2.boot) || !body2.boot || typeof body2.seq !== "number" || !Number.isFinite(body2.seq)) return bad();
18734
+ if (!isObj2(body2) || body2.protocol !== 1 || !isStr(body2.boot) || !body2.boot || typeof body2.seq !== "number" || !Number.isFinite(body2.seq)) return bad();
18508
18735
  const s2 = body2.snapshot;
18509
- if (!isObj(s2)) return bad();
18736
+ if (!isObj2(s2)) return bad();
18510
18737
  if (!all(s2.rooms, (r) => isStr(r.id) && isStr(r.name) && isStr(r.path)) || !all(s2.agents, (a) => isStr(a.id) && isStr(a.roomId) && isStr(a.account)) || !all(s2.accounts, (a) => isStr(a.id) && isStr(a.name)))
18511
18738
  return bad();
18512
- if (!all(body2.feed, (f) => isStr(f.id) && isStr(f.agentId) && isStr(f.roomId)) || !all(body2.notices, (n2) => isStr(n2.id)) || !all(body2.relayed, (r) => isStr(r.actionId) && isObj(r.message) && isStr(r.message.id) && isStr(r.message.agentId)))
18739
+ if (!all(body2.feed, (f) => isStr(f.id) && isStr(f.agentId) && isStr(f.roomId)) || !all(body2.notices, (n2) => isStr(n2.id)) || !all(body2.relayed, (r) => isStr(r.actionId) && isObj2(r.message) && isStr(r.message.id) && isStr(r.message.agentId)))
18513
18740
  return bad();
18741
+ if (body2.inbox !== void 0) {
18742
+ if (!Array.isArray(body2.inbox)) return bad();
18743
+ body2.inbox = body2.inbox.map(parseInboxItem).filter((i) => !!i).slice(0, INBOX_OPEN_MAX + INBOX_RESOLVED_SHOWN);
18744
+ }
18514
18745
  if (body2.ptys !== void 0) {
18515
18746
  const ptys2 = body2.ptys;
18516
- if (!isObj(ptys2) || !isObj(ptys2.status) || typeof ptys2.status.enabled !== "boolean" || !Array.isArray(ptys2.list))
18747
+ if (!isObj2(ptys2) || !isObj2(ptys2.status) || typeof ptys2.status.enabled !== "boolean" || !Array.isArray(ptys2.list))
18517
18748
  return bad();
18518
- const num10 = (v) => v === void 0 || typeof v === "number" && Number.isFinite(v);
18749
+ const num12 = (v) => v === void 0 || typeof v === "number" && Number.isFinite(v);
18519
18750
  ptys2.list = ptys2.list.filter(
18520
- (p) => isObj(p) && isStr(p.id) && isStr(p.agentId) && isStr(p.account) && isStr(p.cwd) && typeof p.pid === "number" && Number.isFinite(p.pid) && num10(p.startedAt) && num10(p.exitedAt) && num10(p.exitCode) && (p.fromAgent === void 0 || isStr(p.fromAgent)) && (p.resumed === void 0 || isStr(p.resumed))
18751
+ (p) => isObj2(p) && isStr(p.id) && isStr(p.agentId) && isStr(p.account) && isStr(p.cwd) && typeof p.pid === "number" && Number.isFinite(p.pid) && num12(p.startedAt) && num12(p.exitedAt) && num12(p.exitCode) && (p.fromAgent === void 0 || isStr(p.fromAgent)) && (p.resumed === void 0 || isStr(p.resumed))
18521
18752
  ).slice(0, 32);
18522
18753
  }
18523
18754
  return body2;
@@ -18536,6 +18767,9 @@ var CentralHub = class {
18536
18767
  relayedCbs = /* @__PURE__ */ new Set();
18537
18768
  ptyOutputCbs = /* @__PURE__ */ new Set();
18538
18769
  satellitePerf = /* @__PURE__ */ new Map();
18770
+ /** Per machine: id -> "status:updatedAt" of the inbox items seen; tells a live arrival from the first sight. */
18771
+ inboxSeen = /* @__PURE__ */ new Map();
18772
+ inboxCbs = /* @__PURE__ */ new Set();
18539
18773
  ticker;
18540
18774
  counter = 0;
18541
18775
  constructor(opts) {
@@ -18590,6 +18824,49 @@ var CentralHub = class {
18590
18824
  }
18591
18825
  return out;
18592
18826
  }
18827
+ /**
18828
+ * The office inbox items of the paired machines the office still shows, ids prefixed and `machine` set. An offline
18829
+ * machine keeps its items on the desk (they are still there); resolving one then fails as "offline".
18830
+ */
18831
+ inboxItems() {
18832
+ const now = this.now();
18833
+ const out = [];
18834
+ for (const [id, e] of this.entries) {
18835
+ if (now - e.at >= HIDE_AFTER_MS || !e.state.inbox) continue;
18836
+ for (const i of e.state.inbox) out.push(namespaceInboxItem(id, i));
18837
+ }
18838
+ return out;
18839
+ }
18840
+ /** Called when a machine's inbox changed; `arrived` is a new (or reopened) open item seen live. */
18841
+ onInbox(cb) {
18842
+ this.inboxCbs.add(cb);
18843
+ return () => void this.inboxCbs.delete(cb);
18844
+ }
18845
+ /** The satellite confirmed the resolve: show it now instead of at its next state. */
18846
+ markInboxResolved(machine, localId) {
18847
+ const e = this.entries.get(machine);
18848
+ const item = e?.state.inbox?.find((i) => i.id === localId);
18849
+ if (!item || item.status === "resolved") return;
18850
+ const at = this.now();
18851
+ item.status = "resolved";
18852
+ item.resolvedAt = at;
18853
+ item.updatedAt = at;
18854
+ this.inboxSeen.get(machine)?.set(item.id, `resolved:${item.updatedAt}`);
18855
+ for (const cb of this.inboxCbs) cb();
18856
+ }
18857
+ noteInbox(machine, items) {
18858
+ const seen = this.inboxSeen.get(machine);
18859
+ const next = new Map(items.map((i) => [i.id, `${i.status}:${i.updatedAt}`]));
18860
+ this.inboxSeen.set(machine, next);
18861
+ let changed = next.size !== (seen?.size ?? 0);
18862
+ let arrived;
18863
+ for (const i of items) {
18864
+ const before = seen?.get(i.id);
18865
+ if (before !== next.get(i.id)) changed = true;
18866
+ if (seen && i.status === "open" && (before === void 0 || before.startsWith("resolved:")) && !arrived) arrived = namespaceInboxItem(machine, i);
18867
+ }
18868
+ if (changed || arrived) for (const cb of this.inboxCbs) cb(arrived);
18869
+ }
18593
18870
  isOnline(machine) {
18594
18871
  const e = this.entries.get(machine);
18595
18872
  return !!e && this.now() - e.at < OFFLINE_AFTER_MS;
@@ -18667,6 +18944,7 @@ var CentralHub = class {
18667
18944
  const freshNotices = notices.filter((n2) => this.remember(entry.noticeSeen, n2.id));
18668
18945
  if (freshFeed.length || freshNotices.length) this.office.addRemoteFrames(freshFeed, freshNotices);
18669
18946
  for (const r of s2.relayed) for (const cb of this.relayedCbs) cb(m.id, r);
18947
+ if (s2.inbox || this.inboxSeen.has(m.id)) this.noteInbox(m.id, s2.inbox ?? []);
18670
18948
  this.office.markDirty();
18671
18949
  return reply2();
18672
18950
  }
@@ -18706,7 +18984,7 @@ var CentralHub = class {
18706
18984
  }
18707
18985
  results(m, body2) {
18708
18986
  this.assertPaired(m);
18709
- if (!isObj(body2) || !all(body2.results, (r) => isStr(r.actionId) && typeof r.ok === "boolean")) bad();
18987
+ if (!isObj2(body2) || !all(body2.results, (r) => isStr(r.actionId) && typeof r.ok === "boolean")) bad();
18710
18988
  for (const r of body2.results) {
18711
18989
  const p = this.pending.get(r.actionId);
18712
18990
  if (!p || p.machine !== m.id) continue;
@@ -18717,7 +18995,7 @@ var CentralHub = class {
18717
18995
  ptyOutput(m, ptyId, body2) {
18718
18996
  this.assertPaired(m);
18719
18997
  if (!/^p\d+-\d+$/.test(ptyId)) return bad();
18720
- if (!isObj(body2)) return bad();
18998
+ if (!isObj2(body2)) return bad();
18721
18999
  const sequence = body2.sequence;
18722
19000
  if (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence < 1) return bad();
18723
19001
  let output;
@@ -18843,14 +19121,14 @@ var CentralHub = class {
18843
19121
  const now = this.now();
18844
19122
  const id = `a-${now.toString(36)}-${++this.counter}-${randomBytes3(4).toString("hex")}`;
18845
19123
  const timeoutMs = Math.max(1, opts.timeoutMs ?? ACTION_RESULT_TIMEOUT_MS);
18846
- let resolve14;
19124
+ let resolve15;
18847
19125
  let reject2;
18848
19126
  const result = new Promise((ok, fail3) => {
18849
- resolve14 = ok;
19127
+ resolve15 = ok;
18850
19128
  reject2 = fail3;
18851
19129
  });
18852
19130
  result.catch(() => void 0);
18853
- const p = { id, machine, action: { ...action, id }, status: "queued", deadline: now + timeoutMs, timer: void 0, resolve: resolve14, reject: reject2 };
19131
+ const p = { id, machine, action: { ...action, id }, status: "queued", deadline: now + timeoutMs, timer: void 0, resolve: resolve15, reject: reject2 };
18854
19132
  this.pending.set(id, p);
18855
19133
  this.rearm(p, timeoutMs);
18856
19134
  this.hostWait(machine).wake();
@@ -18860,6 +19138,7 @@ var CentralHub = class {
18860
19138
  revoke(id) {
18861
19139
  this.machines.revoke(id);
18862
19140
  this.entries.delete(id);
19141
+ if (this.inboxSeen.delete(id)) for (const cb of this.inboxCbs) cb();
18863
19142
  this.satellitePerf.delete(id);
18864
19143
  for (const p of [...this.pending.values()]) if (p.machine === id) this.fail(p, "revoked");
18865
19144
  this.closeReads(id, new HubError("revoked"));
@@ -18921,9 +19200,9 @@ var CentralHub = class {
18921
19200
 
18922
19201
  // server/central/reads.ts
18923
19202
  var BUFFER_TIMEOUT_MS = 3e4;
18924
- var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19203
+ var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
18925
19204
  function rewriteIds(machine, body2, kind) {
18926
- if (!isObj2(body2)) throw new Error("corpo inesperado");
19205
+ if (!isObj3(body2)) throw new Error("corpo inesperado");
18927
19206
  switch (kind) {
18928
19207
  case "detail":
18929
19208
  return namespaceDetail(machine, body2);
@@ -19098,11 +19377,11 @@ function deliver(o, body2, res, ctx) {
19098
19377
  }
19099
19378
  var FANOUT_TIMEOUT_MS = 3e3;
19100
19379
  function readOne(hub2, machine, path, search, timeoutMs, map) {
19101
- return new Promise((resolve14) => {
19380
+ return new Promise((resolve15) => {
19102
19381
  const running = bufferedNow.get(machine) ?? 0;
19103
- if (running >= BUFFERED_MAX) return resolve14({ kind: "missing" });
19382
+ if (running >= BUFFERED_MAX) return resolve15({ kind: "missing" });
19104
19383
  const r = hub2.startRead(machine, path, search);
19105
- if ("error" in r) return resolve14({ kind: "missing" });
19384
+ if ("error" in r) return resolve15({ kind: "missing" });
19106
19385
  bufferedNow.set(machine, running + 1);
19107
19386
  let done = false;
19108
19387
  let body2;
@@ -19115,7 +19394,7 @@ function readOne(hub2, machine, path, search, timeoutMs, map) {
19115
19394
  else bufferedNow.set(machine, n2);
19116
19395
  if (cancel) r.cancel();
19117
19396
  body2?.destroy();
19118
- resolve14(out);
19397
+ resolve15(out);
19119
19398
  };
19120
19399
  const timer = setTimeout(() => finish({ kind: "missing" }, true), timeoutMs);
19121
19400
  timer.unref();
@@ -19616,6 +19895,24 @@ function createApiHandler(deps) {
19616
19895
  } else deps.attention(req, res, path);
19617
19896
  return true;
19618
19897
  }
19898
+ if (path === "/api/inbox" || path.startsWith("/api/inbox/")) {
19899
+ if (!deps.inbox) {
19900
+ req.resume();
19901
+ sendJson2(res, 404, { error: tr("rota desconhecida") });
19902
+ } else if (isRead) {
19903
+ if (!attentionAllowed(req)) sendJson2(res, 403, { error: tr("a mesa s\xF3 vale pelo pr\xF3prio computador ou pelo acesso remoto com login") });
19904
+ else deps.inbox(req, res, path);
19905
+ } else if (path !== "/api/inbox") {
19906
+ if (!trusted(req, "messages")) {
19907
+ req.resume();
19908
+ sendJson2(res, 403, { error: denied(req, tr("os itens da mesa s\xF3 s\xE3o resolvidos pelo pr\xF3prio computador (http://localhost ou http://127.0.0.1)")) });
19909
+ } else deps.inbox(req, res, path);
19910
+ } else if (isRemote(req) || !isLoopbackHost(req.headers.host) || !deps.inDocker && !isLoopbackAddress(req.socket.remoteAddress)) {
19911
+ req.resume();
19912
+ sendJson2(res, 403, { error: tr("s\xF3 o pr\xF3prio computador deixa itens na mesa (http://localhost ou http://127.0.0.1)") });
19913
+ } else deps.inbox(req, res, path);
19914
+ return true;
19915
+ }
19619
19916
  if (path === "/api/avatar") {
19620
19917
  if (!deps.avatar) {
19621
19918
  req.resume();
@@ -20396,16 +20693,16 @@ function centralCertTargets(name, ips) {
20396
20693
  var MESSAGE_MAX = 2e4;
20397
20694
  var MESSAGE_TOOL = "HabblaudMessage";
20398
20695
  var DETAIL_MAX2 = 300;
20399
- function describeMessage(text2, images = 0) {
20400
- const typed = truncate(maskSecrets(text2.slice(0, DETAIL_MAX2 * 4)), DETAIL_MAX2);
20696
+ function describeMessage(text3, images = 0) {
20697
+ const typed = truncate(maskSecrets(text3.slice(0, DETAIL_MAX2 * 4)), DETAIL_MAX2);
20401
20698
  const extra = images > 0 ? images === 1 ? tr("com 1 imagem") : tr("com {0} imagens", [images]) : "";
20402
20699
  const detail = typed && extra ? `${typed} \xB7 ${extra}` : typed || extra;
20403
20700
  return { kind: "communicate", icon: "\u2709\uFE0F", text: tr("Mensagem pelo Habblaud"), tool: MESSAGE_TOOL, ...detail ? { detail } : {} };
20404
20701
  }
20405
20702
  var MESSAGE_IMAGES_MAX = 8;
20406
20703
  var MESSAGE_IMAGE_BYTES_MAX = 15 * 1024 * 1024;
20407
- function isSlashCommand(text2) {
20408
- return /^\s*\/[^\s/]+(?:\s[\s\S]*)?$/.test(text2);
20704
+ function isSlashCommand(text3) {
20705
+ return /^\s*\/[^\s/]+(?:\s[\s\S]*)?$/.test(text3);
20409
20706
  }
20410
20707
 
20411
20708
  // server/messages/registry.ts
@@ -20598,7 +20895,7 @@ var MessageRegistry = class {
20598
20895
  let open3 = 0;
20599
20896
  for (const e of this.messages.values()) if (e.msg.agentId === agent.id && !isFinal(e)) open3++;
20600
20897
  if (open3 >= MAX_OPEN2) return { error: "too-many" };
20601
- let text2 = typed;
20898
+ let text3 = typed;
20602
20899
  let files = 0;
20603
20900
  if (attachments2.length) {
20604
20901
  const images = this.opts.images;
@@ -20612,7 +20909,7 @@ var MessageRegistry = class {
20612
20909
  if (demo) images.discard(taken);
20613
20910
  else {
20614
20911
  try {
20615
- text2 = promptWithAttachments(typed, images.save(taken));
20912
+ text3 = promptWithAttachments(typed, images.save(taken));
20616
20913
  } catch (err) {
20617
20914
  log.warnOnce(`messages-images:${errMsg(err)}`, tr("Mensagens: n\xE3o deu para gravar as imagens ({0}).", [errMsg(err)]));
20618
20915
  return { error: "images", code: "write", reason: tr("n\xE3o deu para guardar as imagens no computador") };
@@ -20621,7 +20918,7 @@ var MessageRegistry = class {
20621
20918
  }
20622
20919
  const now = this.now();
20623
20920
  const id = `m-${now.toString(36)}-${++this.seq}-${randomBytes4(9).toString("base64url")}`;
20624
- const entry = { msg: { id, agentId: agent.id, status: "queued", createdAt: now, updatedAt: now }, text: text2, activity: describeMessage(typed, files), target: agent.sessionId };
20921
+ const entry = { msg: { id, agentId: agent.id, status: "queued", createdAt: now, updatedAt: now }, text: text3, activity: describeMessage(typed, files), target: agent.sessionId };
20625
20922
  if (demo) entry.demo = true;
20626
20923
  else if (real?.provider === "codex") entry.codex = true;
20627
20924
  this.messages.set(id, entry);
@@ -20898,7 +21195,7 @@ function createMessageRoutes(registry, remote) {
20898
21195
  if ("error" in r) return sendJson2(res, r.status, { error: r.error });
20899
21196
  sendJson2(res, 201, r);
20900
21197
  };
20901
- const inbox = async (req, res) => {
21198
+ const inbox2 = async (req, res) => {
20902
21199
  sendJson2(res, 200, { messages: registry.inbox(await readJson(req)) });
20903
21200
  };
20904
21201
  const ack = async (req, res) => {
@@ -20939,7 +21236,7 @@ function createMessageRoutes(registry, remote) {
20939
21236
  }).catch((err) => fail(res, err));
20940
21237
  return;
20941
21238
  }
20942
- if (path === "/api/mod/inbox") return post(req, res, inbox);
21239
+ if (path === "/api/mod/inbox") return post(req, res, inbox2);
20943
21240
  if (path === "/api/mod/inbox/ack") return post(req, res, ack);
20944
21241
  if (path === "/api/mod/commands") return post(req, res, commands);
20945
21242
  const c = COMMANDS.exec(path);
@@ -21020,7 +21317,7 @@ var RemoteMessages = class {
21020
21317
  send(raw) {
21021
21318
  const peek = raw?.agentId;
21022
21319
  if (typeof peek !== "string" || !parseRemoteId(peek)) return void 0;
21023
- const { agentId, text: text2, attachments: attachments2 } = parseSend(raw);
21320
+ const { agentId, text: text3, attachments: attachments2 } = parseSend(raw);
21024
21321
  const ref = parseRemoteId(agentId);
21025
21322
  if (!ref) return void 0;
21026
21323
  if (!this.hub.isOnline(ref.machine)) return { error: "unavailable", reason: ERR_MACHINE_OFFLINE2 };
@@ -21035,7 +21332,7 @@ var RemoteMessages = class {
21035
21332
  if (attachments2.length) {
21036
21333
  const store = this.images;
21037
21334
  if (!store) return { error: "images", code: "off", reason: tr("imagens desligadas") };
21038
- if (isSlashCommand(text2)) return { error: "images", code: "slash", reason: tr("comandos de barra n\xE3o levam imagens: tire as imagens ou mande o comando sozinho") };
21335
+ if (isSlashCommand(text3)) return { error: "images", code: "slash", reason: tr("comandos de barra n\xE3o levam imagens: tire as imagens ou mande o comando sozinho") };
21039
21336
  if (store.peekSize(attachments2) > REMOTE_IMAGES_MAX_BYTES) {
21040
21337
  return { error: "images", code: "size", reason: tr("as imagens passam de {0} MB: mande menos imagens", [REMOTE_IMAGES_MAX_BYTES / (1024 * 1024)]) };
21041
21338
  }
@@ -21050,7 +21347,7 @@ var RemoteMessages = class {
21050
21347
  const action = {
21051
21348
  type: "message.send",
21052
21349
  agentId: ref.local,
21053
- text: text2,
21350
+ text: text3,
21054
21351
  images
21055
21352
  };
21056
21353
  const q = this.hub.enqueue(ref.machine, action, { timeoutMs: QUEUED_TIMEOUT_MS2 });
@@ -21270,8 +21567,8 @@ function codexToolView(tool, input, cwd) {
21270
21567
  const more = files.length > 1 ? ` +${files.length - 1}` : "";
21271
21568
  const title = first ? `apply_patch(${line(relPath2(first.path, cwd), TITLE_ARG_MAX)}${more})` : "apply_patch";
21272
21569
  const name = first ? line(basename3(first.path), TEXT_MAX3) : "";
21273
- const [text2, icon] = files.length > 1 ? [tr("Editando {0} arquivos", [files.length]), "\u270F\uFE0F"] : first?.op === "Add" ? [tr("Criando {0}", [name]), "\u{1F4DD}"] : first?.op === "Delete" ? [tr("Apagando {0}", [name]), "\u{1F5D1}\uFE0F"] : [first ? tr("Editando {0}", [name]) : tr("Aplicando um patch"), "\u270F\uFE0F"];
21274
- return { title, text: truncate(text2, TEXT_MAX3), icon, ...shown(patch, "diff") };
21570
+ const [text3, icon] = files.length > 1 ? [tr("Editando {0} arquivos", [files.length]), "\u270F\uFE0F"] : first?.op === "Add" ? [tr("Criando {0}", [name]), "\u{1F4DD}"] : first?.op === "Delete" ? [tr("Apagando {0}", [name]), "\u{1F5D1}\uFE0F"] : [first ? tr("Editando {0}", [name]) : tr("Aplicando um patch"), "\u270F\uFE0F"];
21571
+ return { title, text: truncate(text3, TEXT_MAX3), icon, ...shown(patch, "diff") };
21275
21572
  }
21276
21573
  case "request_permissions": {
21277
21574
  const view = toolView(tool, input, cwd);
@@ -21432,8 +21729,8 @@ function askFormat(raw) {
21432
21729
  function askCount(raw) {
21433
21730
  if (!Array.isArray(raw)) return 0;
21434
21731
  return raw.filter((q) => {
21435
- const text2 = rec6(q)?.question;
21436
- return typeof text2 === "string" && !!text2.trim();
21732
+ const text3 = rec6(q)?.question;
21733
+ return typeof text3 === "string" && !!text3.trim();
21437
21734
  }).length;
21438
21735
  }
21439
21736
  function fitsFormat(f, a) {
@@ -21598,8 +21895,8 @@ var PermissionRegistry = class {
21598
21895
  const now = this.now();
21599
21896
  const id = `p-${now.toString(36)}-${++this.seq}-${randomBytes5(9).toString("base64url")}`;
21600
21897
  const view = "title" in desc ? desc : toolView(req.tool, req.input, req.cwd);
21601
- const text2 = only && req.promptTitle ? truncate(maskSecrets(req.promptTitle), 120) : desc.text;
21602
- const info = { id, tool: req.tool, title: view.title, text: text2, icon: desc.icon, createdAt: now, expiresAt: now + req.timeoutMs };
21898
+ const text3 = only && req.promptTitle ? truncate(maskSecrets(req.promptTitle), 120) : desc.text;
21899
+ const info = { id, tool: req.tool, title: view.title, text: text3, icon: desc.icon, createdAt: now, expiresAt: now + req.timeoutMs };
21603
21900
  if (codex2) info.provider = "codex";
21604
21901
  if (only) info.terminalOnly = true;
21605
21902
  if (view.input) info.input = view.input;
@@ -21628,8 +21925,8 @@ var PermissionRegistry = class {
21628
21925
  this.opts.office.addActivity(target.id, { id: `${target.id}#perm:${id}`, at: now, kind: "wait", icon: "\u2753", text: truncate(tr("Pergunta: {0}", [first]), 46), detail: truncate(all2, 300), tool: "PermissionRequest" }, false);
21629
21926
  this.opts.office.noticePermission(target.id, `${truncate(first, 120)}${by}`, "question");
21630
21927
  } else {
21631
- this.opts.office.addActivity(target.id, { id: `${target.id}#perm:${id}`, at: now, kind: "wait", icon: "\u{1F510}", text: truncate(tr("Pede permiss\xE3o: {0}", [text2]), 46), detail: view.title, tool: "PermissionRequest" }, false);
21632
- this.opts.office.noticePermission(target.id, only ? `${text2} \xB7 ${view.title}` : `${desc.text}${by}`);
21928
+ this.opts.office.addActivity(target.id, { id: `${target.id}#perm:${id}`, at: now, kind: "wait", icon: "\u{1F510}", text: truncate(tr("Pede permiss\xE3o: {0}", [text3]), 46), detail: view.title, tool: "PermissionRequest" }, false);
21929
+ this.opts.office.noticePermission(target.id, only ? `${text3} \xB7 ${view.title}` : `${desc.text}${by}`);
21633
21930
  }
21634
21931
  this.opts.office.markDirty();
21635
21932
  return { id, expiresAt: info.expiresAt + EXPIRY_GRACE_MS2 };
@@ -22086,8 +22383,8 @@ var CODE_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
22086
22383
  var LABEL_MAX = 40;
22087
22384
  var hashToken = (token) => createHash2("sha256").update(token, "utf8").digest("hex");
22088
22385
  function cleanLabel(label) {
22089
- const text2 = cleanMachineLabel(label).slice(0, LABEL_MAX).trim();
22090
- return text2 || void 0;
22386
+ const text3 = cleanMachineLabel(label).slice(0, LABEL_MAX).trim();
22387
+ return text3 || void 0;
22091
22388
  }
22092
22389
  var MachineStore = class {
22093
22390
  file;
@@ -22566,6 +22863,7 @@ var Satellite = class {
22566
22863
  applied;
22567
22864
  ptyProvider;
22568
22865
  maintenanceCallback;
22866
+ inbox;
22569
22867
  /** Aleatório por processo (P9): a central troca a parte da máquina quando ele muda. */
22570
22868
  boot = randomBytes7(9).toString("base64url");
22571
22869
  seq = Date.now();
@@ -22601,6 +22899,7 @@ var Satellite = class {
22601
22899
  this.now = opts.now ?? (() => performance.now());
22602
22900
  this.ptyProvider = opts.ptys ?? (() => void 0);
22603
22901
  this.maintenanceCallback = opts.maintenance ?? (() => void 0);
22902
+ this.inbox = opts.inbox;
22604
22903
  this.applied = new AppliedActions({ now: Date.now });
22605
22904
  }
22606
22905
  start() {
@@ -22618,6 +22917,7 @@ var Satellite = class {
22618
22917
  else this.notices = [...this.notices, data].slice(-NOTICE_KEEP);
22619
22918
  })
22620
22919
  );
22920
+ if (this.inbox) this.offs.push(this.inbox.onChange(() => this.schedule()));
22621
22921
  this.heartbeat = this.timers.setInterval(() => void this.post(), HEARTBEAT_MS);
22622
22922
  unref(this.heartbeat);
22623
22923
  this.maintenance = this.timers.setInterval(() => this.optsMaintenance(), 1e3);
@@ -22704,6 +23004,7 @@ var Satellite = class {
22704
23004
  const snap = this.snap ?? this.hub.current();
22705
23005
  const meta = { version: snap.meta.version };
22706
23006
  if (snap.meta.messages !== void 0) meta.messages = snap.meta.messages;
23007
+ const inbox2 = this.inbox?.items();
22707
23008
  return {
22708
23009
  protocol: 1,
22709
23010
  boot: this.boot,
@@ -22716,7 +23017,8 @@ var Satellite = class {
22716
23017
  },
22717
23018
  feed,
22718
23019
  notices,
22719
- relayed
23020
+ relayed,
23021
+ ...inbox2 ? { inbox: inbox2 } : {}
22720
23022
  };
22721
23023
  }
22722
23024
  ptys() {
@@ -23689,14 +23991,14 @@ function handleRead(a, deps) {
23689
23991
  if (active.size >= READ_OPEN_MAX) return Promise.resolve(refuse(a, 429, tr("leituras abertas demais nesta m\xE1quina")));
23690
23992
  const request = deps.request ?? http3.request;
23691
23993
  const host = `127.0.0.1:${deps.port}`;
23692
- return new Promise((resolve14) => {
23994
+ return new Promise((resolve15) => {
23693
23995
  let out;
23694
23996
  let upstream;
23695
23997
  let settled = false;
23696
23998
  const settle = (r) => {
23697
23999
  if (settled) return;
23698
24000
  settled = true;
23699
- resolve14(r);
24001
+ resolve15(r);
23700
24002
  };
23701
24003
  const req = request({ host: readHost(deps.host), port: deps.port, method: "GET", path: target.path + target.search, headers: { Host: host, Accept: "*/*" } });
23702
24004
  const close = () => {
@@ -23798,25 +24100,25 @@ function cut2(s2, max) {
23798
24100
  const sp = head.lastIndexOf(" ");
23799
24101
  return `${(sp > max * 0.6 ? head.slice(0, sp) : head).replace(/[\s,;:.-]+$/, "")}\u2026`;
23800
24102
  }
23801
- function paragraphs(text2) {
23802
- return text2.replace(/`{3}[\s\S]*?`{3}/g, "\n\n").split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
24103
+ function paragraphs(text3) {
24104
+ return text3.replace(/`{3}[\s\S]*?`{3}/g, "\n\n").split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
23803
24105
  }
23804
24106
  var isProse = (p) => !/^(\||#|>|[-*+]\s|\d+[.)]\s|`{3})/.test(p) && !/^[A-Z_ ]+:\s/.test(p);
23805
- function headlineOf(text2) {
23806
- const first = paragraphs(text2).find(isProse) ?? paragraphs(text2)[0] ?? "";
24107
+ function headlineOf(text3) {
24108
+ const first = paragraphs(text3).find(isProse) ?? paragraphs(text3)[0] ?? "";
23807
24109
  const plain = stripMarkdown(first);
23808
24110
  const m = /^(.+?[.!?])(\s|$)/.exec(plain);
23809
24111
  return cut2(m ? m[1] : plain, HEADLINE_MAX);
23810
24112
  }
23811
- function summaryOf(text2, headline) {
23812
- const paras = paragraphs(text2).filter(isProse);
24113
+ function summaryOf(text3, headline) {
24114
+ const paras = paragraphs(text3).filter(isProse);
23813
24115
  const last = paras[paras.length - 1];
23814
24116
  if (!last || paras.length < 2) return void 0;
23815
24117
  const plain = stripMarkdown(last);
23816
24118
  if (plain.length < 60 || plain.startsWith(headline.replace(/…$/, ""))) return void 0;
23817
24119
  return cut2(plain, SUMMARY_MAX2);
23818
24120
  }
23819
- function linkedFiles(text2, project, platform = process.platform) {
24121
+ function linkedFiles(text3, project, platform = process.platform) {
23820
24122
  const P = platform === "win32" ? win32 : posix;
23821
24123
  const out = /* @__PURE__ */ new Set();
23822
24124
  const add = (raw) => {
@@ -23836,8 +24138,8 @@ function linkedFiles(text2, project, platform = process.platform) {
23836
24138
  p = P.normalize(p);
23837
24139
  if (!pathProblem(p, platform)) out.add(p);
23838
24140
  };
23839
- for (const m of text2.matchAll(LINK_RE)) add(m[1]);
23840
- for (const m of text2.matchAll(BARE_RE)) add(m[1]);
24141
+ for (const m of text3.matchAll(LINK_RE)) add(m[1]);
24142
+ for (const m of text3.matchAll(BARE_RE)) add(m[1]);
23841
24143
  return [...out];
23842
24144
  }
23843
24145
  function newTurn(start) {
@@ -23982,13 +24284,13 @@ var DeliveryIndex = class {
23982
24284
  }
23983
24285
  }
23984
24286
  toDelivery(s2, t, files) {
23985
- const text2 = t.text.trim();
23986
- if (!t.tools || text2.length < MIN_TEXT || t.marksStop && !t.ended) return void 0;
24287
+ const text3 = t.text.trim();
24288
+ if (!t.tools || text3.length < MIN_TEXT || t.marksStop && !t.ended) return void 0;
23987
24289
  const id = `${s2.account}:${s2.sessionId}:${t.start.id}`;
23988
24290
  const attachments2 = [];
23989
24291
  const paths = /* @__PURE__ */ new Map();
23990
24292
  for (const f of t.files) if (!pathProblem(f.path) && !paths.has(f.path)) paths.set(f.path, f.caption);
23991
- for (const p of linkedFiles(text2, s2.project)) if (!paths.has(p)) paths.set(p, void 0);
24293
+ for (const p of linkedFiles(text3, s2.project)) if (!paths.has(p)) paths.set(p, void 0);
23992
24294
  for (const [path, caption] of paths) {
23993
24295
  const ft = fileType(path);
23994
24296
  if (!ft) continue;
@@ -24003,8 +24305,8 @@ var DeliveryIndex = class {
24003
24305
  files.set(aid, { kind: "capture", type: c.type, data: Buffer.from(c.data, "base64"), name });
24004
24306
  attachments2.push({ id: aid, name, kind: "image", caption: tr("Tela capturada pelo agente"), capture: true });
24005
24307
  });
24006
- const headline = headlineOf(text2);
24007
- const summary = summaryOf(text2, headline);
24308
+ const headline = headlineOf(text3);
24309
+ const summary = summaryOf(text3, headline);
24008
24310
  const agentName2 = s2.agentId ? this.opts.agentName?.(s2.agentId) : void 0;
24009
24311
  const provider = s2.provider;
24010
24312
  return {
@@ -24018,7 +24320,7 @@ var DeliveryIndex = class {
24018
24320
  request: cut2(stripMarkdown(t.start.text), REQUEST_MAX),
24019
24321
  headline,
24020
24322
  ...summary ? { summary } : {},
24021
- text: text2.slice(0, 4e4),
24323
+ text: text3.slice(0, 4e4),
24022
24324
  startedAt: t.start.at,
24023
24325
  finishedAt: t.textAt,
24024
24326
  tools: t.tools,
@@ -24029,7 +24331,7 @@ var DeliveryIndex = class {
24029
24331
  };
24030
24332
 
24031
24333
  // server/central/merge.ts
24032
- var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
24334
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
24033
24335
  var partialOf = (r) => r.missing.length ? { partial: true, unavailable: r.missing } : {};
24034
24336
  function withoutRemote(snap) {
24035
24337
  return {
@@ -24051,9 +24353,9 @@ function addTotals(into, from) {
24051
24353
  }
24052
24354
  var cloneTotals = (t) => ({ ...t, ms: { ...t.ms }, counts: { ...t.counts } });
24053
24355
  function validDay(body2) {
24054
- if (!isObj3(body2) || !isObj3(body2.stats)) throw new Error("corpo inesperado");
24356
+ if (!isObj4(body2) || !isObj4(body2.stats)) throw new Error("corpo inesperado");
24055
24357
  const s2 = body2.stats;
24056
- if (!isObj3(s2.totals) || !isObj3(s2.totals.ms) || !isObj3(s2.totals.counts) || !Array.isArray(s2.rooms) || !Array.isArray(s2.accounts) || !Array.isArray(s2.hours) || !Array.isArray(s2.waits)) throw new Error("corpo inesperado");
24358
+ if (!isObj4(s2.totals) || !isObj4(s2.totals.ms) || !isObj4(s2.totals.counts) || !Array.isArray(s2.rooms) || !Array.isArray(s2.accounts) || !Array.isArray(s2.hours) || !Array.isArray(s2.waits)) throw new Error("corpo inesperado");
24057
24359
  return body2;
24058
24360
  }
24059
24361
  function mergeDayStats(local, remotes) {
@@ -24103,7 +24405,7 @@ function createCentralMerge(hub2, opts = {}) {
24103
24405
  const r = await fanOutAll(hub2, "/api/deliveries", {
24104
24406
  timeoutMs,
24105
24407
  map: (m, b) => {
24106
- if (!isObj3(b) || !Array.isArray(b.deliveries)) throw new Error("corpo inesperado");
24408
+ if (!isObj4(b) || !Array.isArray(b.deliveries)) throw new Error("corpo inesperado");
24107
24409
  return b.deliveries.map((d) => namespaceDelivery(m, d));
24108
24410
  }
24109
24411
  });
@@ -24116,7 +24418,7 @@ function createCentralMerge(hub2, opts = {}) {
24116
24418
  const r = await fanOutAll(hub2, "/api/sessions/recent", {
24117
24419
  timeoutMs,
24118
24420
  map: (m, b) => {
24119
- if (!isObj3(b) || !Array.isArray(b.sessions)) throw new Error("corpo inesperado");
24421
+ if (!isObj4(b) || !Array.isArray(b.sessions)) throw new Error("corpo inesperado");
24120
24422
  return b.sessions.map((s2) => namespaceSession(m, s2));
24121
24423
  }
24122
24424
  });
@@ -24137,7 +24439,7 @@ function createCentralMerge(hub2, opts = {}) {
24137
24439
  timeoutMs,
24138
24440
  search,
24139
24441
  map: (_m, b) => {
24140
- if (!isObj3(b) || !Array.isArray(b.days) || !b.days.every((d) => typeof d === "string")) throw new Error("corpo inesperado");
24442
+ if (!isObj4(b) || !Array.isArray(b.days) || !b.days.every((d) => typeof d === "string")) throw new Error("corpo inesperado");
24141
24443
  return b.days;
24142
24444
  }
24143
24445
  });
@@ -24648,8 +24950,8 @@ function demoCodexPermission(id, src, rng, now) {
24648
24950
  }
24649
24951
 
24650
24952
  // shared/demo/terminal.ts
24651
- function startsWithText(text2, key) {
24652
- return text2.startsWith(key.split("{0}")[0]) || text2.startsWith(tr(key, ["\0"]).split("\0")[0]);
24953
+ function startsWithText(text3, key) {
24954
+ return text3.startsWith(key.split("{0}")[0]) || text3.startsWith(tr(key, ["\0"]).split("\0")[0]);
24653
24955
  }
24654
24956
  var POOLS = {
24655
24957
  ts: ["src/app.ts", "src/utils/format.ts", "src/components/Item.tsx", "tests/app.test.ts"],
@@ -24665,7 +24967,7 @@ function pickFiles(pool, seed, n2) {
24665
24967
  return Array.from({ length: Math.min(n2, pool.length) }, (_, k) => pool[(seed + k) % pool.length]);
24666
24968
  }
24667
24969
  var pick = (arr, seed) => arr[seed % arr.length];
24668
- var num6 = (seed, min, max) => min + seed % (max - min + 1);
24970
+ var num7 = (seed, min, max) => min + seed % (max - min + 1);
24669
24971
  var hex = (seed) => seed.toString(16).padStart(8, "0").slice(0, 7);
24670
24972
  function rel(path, ctx) {
24671
24973
  return ctx.root && path.startsWith(`${ctx.root}/`) ? path.slice(ctx.root.length + 1) : path;
@@ -24754,7 +25056,7 @@ function editPair(file, seed) {
24754
25056
  function commandOutput(command, seed, ctx) {
24755
25057
  const branch = ctx.agent.gitBranch ?? "main";
24756
25058
  const [f1, f2] = pickFiles(ctx.pool, seed, 2);
24757
- const n2 = (min, max) => num6(seed, min, max);
25059
+ const n2 = (min, max) => num7(seed, min, max);
24758
25060
  const secs = `${n2(1, 9)}.${n2(10, 99)}`;
24759
25061
  if (/playwright\s+test/.test(command)) return `Running ${n2(8, 30)} tests using 4 workers
24760
25062
 
@@ -24827,7 +25129,7 @@ function isBackground(i, ctx) {
24827
25129
  }
24828
25130
  function shellCall(out, a, i, command, seed, ctx, output) {
24829
25131
  const bg = isBackground(i, ctx);
24830
- const result = bg ? ctx.codex ? tr("Comando rodando em segundo plano (sess\xE3o {0}).", [num6(seed, 1e3, 9999)]) : tr("Comando rodando em segundo plano (id b{0}). Voc\xEA recebe um aviso quando ele terminar.", [hex(seed)]) : output ?? commandOutput(command, seed, ctx);
25132
+ const result = bg ? ctx.codex ? tr("Comando rodando em segundo plano (sess\xE3o {0}).", [num7(seed, 1e3, 9999)]) : tr("Comando rodando em segundo plano (id b{0}). Voc\xEA recebe um aviso quando ele terminar.", [hex(seed)]) : output ?? commandOutput(command, seed, ctx);
24831
25133
  const firstLine5 = command.split("\n")[0];
24832
25134
  const tool = ctx.codex ? "Shell" : "Bash";
24833
25135
  call(out, a, tool, `${tool}(${firstLine5}${command.includes("\n") ? " \u2026" : ""})`, result, { input: command, inputKind: "command" });
@@ -24868,8 +25170,8 @@ function entriesFor(a, i, ctx, out) {
24868
25170
  out.push({ kind: "user", id: `${a.id}:u`, at: a.at, text: detail ?? quoted(a.text) ?? a.text });
24869
25171
  return;
24870
25172
  case "think": {
24871
- const text2 = startsWithText(a.text, tr("Pensando")) ? seed % 3 === 0 ? void 0 : pick(THOUGHTS, seed >>> 3) : tr("Os subagentes terminaram; vou juntar o que cada um encontrou.");
24872
- out.push(text2 ? { kind: "thinking", id: `${a.id}:k`, at: a.at, text: text2 } : { kind: "thinking", id: `${a.id}:k`, at: a.at });
25173
+ const text3 = startsWithText(a.text, tr("Pensando")) ? seed % 3 === 0 ? void 0 : pick(THOUGHTS, seed >>> 3) : tr("Os subagentes terminaram; vou juntar o que cada um encontrou.");
25174
+ out.push(text3 ? { kind: "thinking", id: `${a.id}:k`, at: a.at, text: text3 } : { kind: "thinking", id: `${a.id}:k`, at: a.at });
24873
25175
  return;
24874
25176
  }
24875
25177
  case "respond":
@@ -24912,7 +25214,7 @@ function entriesFor(a, i, ctx, out) {
24912
25214
  return;
24913
25215
  }
24914
25216
  const files = pickFiles(ctx.pool, seed, 1 + seed % 3);
24915
- const matches = files.map((f, k) => `${f}:${num6(hash32(`${a.id}:${k}`), 3, 180)}: ${/^\w+$/.test(pattern) ? `const resultado = ${pattern}(dados);` : pattern}`);
25217
+ const matches = files.map((f, k) => `${f}:${num7(hash32(`${a.id}:${k}`), 3, 180)}: ${/^\w+$/.test(pattern) ? `const resultado = ${pattern}(dados);` : pattern}`);
24916
25218
  if (ctx.codex) shellCall(out, a, i, `rg -n ${JSON.stringify(pattern)}`, seed, ctx, matches.join("\n"));
24917
25219
  else call(out, a, "Grep", `Grep(${pattern})`, matches.join("\n"), { input: '{\n "output_mode": "content"\n}', inputKind: "json" });
24918
25220
  return;
@@ -24975,8 +25277,8 @@ function entriesFor(a, i, ctx, out) {
24975
25277
  });
24976
25278
  return;
24977
25279
  case "done": {
24978
- const text2 = ctx.agent.kind === "sub" && ctx.agent.title ? tr("Entrega: {0}. Resumo enviado ao agente principal.", [ctx.agent.title]) : pick(SUMMARIES, seed);
24979
- out.push({ kind: "assistant", id: `${a.id}:a`, at: a.at, text: text2 });
25280
+ const text3 = ctx.agent.kind === "sub" && ctx.agent.title ? tr("Entrega: {0}. Resumo enviado ao agente principal.", [ctx.agent.title]) : pick(SUMMARIES, seed);
25281
+ out.push({ kind: "assistant", id: `${a.id}:a`, at: a.at, text: text3 });
24980
25282
  const took = /Concluiu em (.+)$/.exec(a.text)?.[1];
24981
25283
  if (took) out.push({ kind: "system", id: `${a.id}:s`, at: a.at, text: tr("Turno conclu\xEDdo em {0}", [took]), level: "info" });
24982
25284
  return;
@@ -25916,8 +26218,8 @@ function githubEventKey(ev) {
25916
26218
  }
25917
26219
  function describeGitHubEvent(ev, agentName2, roomName) {
25918
26220
  const pr = ev.number !== void 0 ? tr("o PR #{0}", [ev.number]) : tr("um PR");
25919
- const act = (icon, text2, detail, error = false) => {
25920
- const d = { kind: "git", icon, text: clean2(text2, MAX_TEXT4), tool: GITHUB_TOOL };
26221
+ const act = (icon, text3, detail, error = false) => {
26222
+ const d = { kind: "git", icon, text: clean2(text3, MAX_TEXT4), tool: GITHUB_TOOL };
25921
26223
  const det = detail ?? ev.url ?? ev.repo;
25922
26224
  if (det) d.detail = clean2(det, 300);
25923
26225
  if (error) d.error = true;
@@ -25969,8 +26271,8 @@ var RoomEffects = class {
25969
26271
  /** Aplica um evento à sala; true se o efeito visível mudou. */
25970
26272
  apply(roomId, ev, now, agentId) {
25971
26273
  const slots = this.rooms.get(roomId) ?? {};
25972
- const make2 = (kind, text2, ms) => {
25973
- const fx = { kind, text: text2, at: now, until: now + ms };
26274
+ const make2 = (kind, text3, ms) => {
26275
+ const fx = { kind, text: text3, at: now, until: now + ms };
25974
26276
  if (agentId) fx.agentId = agentId;
25975
26277
  return fx;
25976
26278
  };
@@ -26253,15 +26555,15 @@ var DemoSimulator = class {
26253
26555
  * atividade "Mensagem pelo Habblaud" e, se ele estava à toa, o próximo turno começa logo, como se respondesse.
26254
26556
  * false = agente desconhecido, subagente ou que já saiu.
26255
26557
  */
26256
- receiveMessage(agentId, text2, now = Date.now()) {
26558
+ receiveMessage(agentId, text3, now = Date.now()) {
26257
26559
  const a = this.agents.get(agentId);
26258
26560
  if (!a || a.info.kind !== "main" || a.removeAt !== void 0 || a.phase === "leaving") return false;
26259
26561
  if (a.info.provider === "codex") {
26260
- (a.inbox ??= []).push(text2);
26261
- a.inboxAt = Math.max(a.inboxAt ?? 0, now + (CODEX_QUEUE_MIN_MS + hash32(`${agentId}:${text2}:${now}`) % CODEX_QUEUE_SPREAD_MS) / this.speed);
26562
+ (a.inbox ??= []).push(text3);
26563
+ a.inboxAt = Math.max(a.inboxAt ?? 0, now + (CODEX_QUEUE_MIN_MS + hash32(`${agentId}:${text3}:${now}`) % CODEX_QUEUE_SPREAD_MS) / this.speed);
26262
26564
  return true;
26263
26565
  }
26264
- this.activity(a, now, describeMessage(text2));
26566
+ this.activity(a, now, describeMessage(text3));
26265
26567
  if (a.phase === "idle") a.phaseUntil = Math.min(a.phaseUntil, now + this.ms(1500, 3e3));
26266
26568
  return true;
26267
26569
  }
@@ -26637,7 +26939,7 @@ var DemoSimulator = class {
26637
26939
  if (a.removeAt !== void 0) return;
26638
26940
  if (a.info.kind === "sub") return this.stepSub(a, now);
26639
26941
  if (a.inbox?.length && a.phase === "idle" && now >= (a.inboxAt ?? 0)) {
26640
- for (const text2 of a.inbox.splice(0)) this.activity(a, now, describeMessage(text2));
26942
+ for (const text3 of a.inbox.splice(0)) this.activity(a, now, describeMessage(text3));
26641
26943
  a.phaseUntil = Math.min(a.phaseUntil, now + 1500 / this.speed);
26642
26944
  a.closeAt = Math.max(a.closeAt, now + 3e4 / this.speed);
26643
26945
  }
@@ -26919,8 +27221,8 @@ var DemoSimulator = class {
26919
27221
  });
26920
27222
  this.dirty = true;
26921
27223
  }
26922
- notice(now, level, text2, agentId, roomId) {
26923
- const n2 = { id: `${this.prefix}${this.tag}-n${++this.seq}`, level, text: text2, at: now };
27224
+ notice(now, level, text3, agentId, roomId) {
27225
+ const n2 = { id: `${this.prefix}${this.tag}-n${++this.seq}`, level, text: text3, at: now };
26924
27226
  if (agentId) n2.agentId = agentId;
26925
27227
  if (roomId) n2.roomId = roomId;
26926
27228
  this.pendingNotices.push(n2);
@@ -27681,8 +27983,10 @@ var SlotAllocator = class {
27681
27983
 
27682
27984
  // shared/room-name.ts
27683
27985
  var AGENT_HUB_ROOM_ID = "agent-hub";
27986
+ var GENTLE_SHELL_ROOM_ID = "gentle-shell-delegated";
27684
27987
  function roomDisplayName(room) {
27685
27988
  if (room.id === AGENT_HUB_ROOM_ID) return tr("Agent Hub");
27989
+ if (room.id === GENTLE_SHELL_ROOM_ID) return tr("Gentle Shell");
27686
27990
  if (room.custom && (!room.name.trim() || room.name.trim() === room.id)) return tr("Favoritos");
27687
27991
  return room.name;
27688
27992
  }
@@ -27966,6 +28270,7 @@ var Office = class {
27966
28270
  }
27967
28271
  roomName(roomId) {
27968
28272
  if (roomId === AGENT_HUB_ROOM_ID) return tr("Agent Hub");
28273
+ if (roomId === GENTLE_SHELL_ROOM_ID) return tr("Gentle Shell");
27969
28274
  const custom = this.customRooms.get(roomId);
27970
28275
  if (custom) return roomDisplayName({ ...custom, custom: true });
27971
28276
  return this.roomNames.get(roomId) ?? roomId.split("/").filter(Boolean).pop() ?? roomId;
@@ -28183,8 +28488,8 @@ var Office = class {
28183
28488
  this.addActivity(id, act, true, { feed: live });
28184
28489
  if (!live || outcome === "killed") return;
28185
28490
  const room = this.roomName(info.roomId);
28186
- const text2 = outcome === "ok" ? tr("\u2705 {0}: shell terminou em {1} \u2014 {2}", [info.name, room, job.label]) : tr("\u274C {0}: shell falhou em {1} \u2014 {2}", [info.name, room, job.label]);
28187
- this.notice("shellDone", id, outcome === "ok" ? "success" : "warn", text2, info.roomId, { dedupeKey: `${id}|shellDone|${job.id}` });
28491
+ const text3 = outcome === "ok" ? tr("\u2705 {0}: shell terminou em {1} \u2014 {2}", [info.name, room, job.label]) : tr("\u274C {0}: shell falhou em {1} \u2014 {2}", [info.name, room, job.label]);
28492
+ this.notice("shellDone", id, outcome === "ok" ? "success" : "warn", text3, info.roomId, { dedupeKey: `${id}|shellDone|${job.id}` });
28188
28493
  }
28189
28494
  /**
28190
28495
  * Evento do GitHub visto no transcript (PR aberto/mergeado, push, CI, release; ver shared/github.ts):
@@ -28456,8 +28761,8 @@ var Office = class {
28456
28761
  const info = this.agents.get(id)?.info;
28457
28762
  if (!info) return;
28458
28763
  const room = this.roomName(info.roomId);
28459
- const text2 = kind === "question" ? tr("\u2753 {0} tem uma pergunta em {1}: {2}", [info.name, room, what]) : tr("\u{1F510} {0} pede permiss\xE3o em {1}: {2}", [info.name, room, what]);
28460
- this.notice("wait", id, "alert", text2, info.roomId);
28764
+ const text3 = kind === "question" ? tr("\u2753 {0} tem uma pergunta em {1}: {2}", [info.name, room, what]) : tr("\u{1F510} {0} pede permiss\xE3o em {1}: {2}", [info.name, room, what]);
28765
+ this.notice("wait", id, "alert", text3, info.roomId);
28461
28766
  this.markDirty();
28462
28767
  }
28463
28768
  /** Decisão para um pedido fictício do demo. true = o pedido era do demo (e foi respondido). */
@@ -28479,10 +28784,10 @@ var Office = class {
28479
28784
  return this.demoSnap?.agents.find((a) => a.id === id);
28480
28785
  }
28481
28786
  /** Entrega fictícia de uma mensagem a um agente do demo. false = ele já saiu (ou o demo foi desligado). */
28482
- deliverDemoMessage(agentId, text2) {
28787
+ deliverDemoMessage(agentId, text3) {
28483
28788
  if (!this.demo) return false;
28484
28789
  const now = this.now();
28485
- if (!this.demo.receiveMessage(agentId, text2, now)) return false;
28790
+ if (!this.demo.receiveMessage(agentId, text3, now)) return false;
28486
28791
  this.demoSnap = this.demo.snapshot(now);
28487
28792
  this.markDirty();
28488
28793
  return true;
@@ -28524,8 +28829,8 @@ var Office = class {
28524
28829
  else delete info.parts;
28525
28830
  info.custom = true;
28526
28831
  const room = this.roomName(info.roomId);
28527
- const text2 = before === input.name ? tr("\u270F\uFE0F {0} mudou de visual em {1}", [input.name, room]) : tr("\u270F\uFE0F {0} agora \xE9 {1} em {2}", [before, input.name, room]);
28528
- this.notice("character", id, "info", text2, info.roomId, { dedupeMs: 0 });
28832
+ const text3 = before === input.name ? tr("\u270F\uFE0F {0} mudou de visual em {1}", [input.name, room]) : tr("\u270F\uFE0F {0} agora \xE9 {1} em {2}", [before, input.name, room]);
28833
+ this.notice("character", id, "info", text3, info.roomId, { dedupeMs: 0 });
28529
28834
  this.markDirty();
28530
28835
  return { result: "ok" };
28531
28836
  }
@@ -28807,13 +29112,13 @@ var Office = class {
28807
29112
  for (let i = 0; i < ordered.length; i++) ordered[i].duplicateSession = { count: ordered.length, newest: i === ordered.length - 1 };
28808
29113
  if (!previous || previous.has(key) || this.booting) continue;
28809
29114
  const newest = ordered[ordered.length - 1];
28810
- const text2 = tr("\u{1F6A8} Intrus\xE3o! A conversa de {0} est\xE1 aberta em {1} terminais", [newest.name, ordered.length]);
28811
- const effect = { kind: "intrusion", text: text2, at: now, until: now + ALARM_MS, panicUntil: now + INTRUSION_PANIC_MS, agentIds: ordered.map((agent) => agent.id) };
29115
+ const text3 = tr("\u{1F6A8} Intrus\xE3o! A conversa de {0} est\xE1 aberta em {1} terminais", [newest.name, ordered.length]);
29116
+ const effect = { kind: "intrusion", text: text3, at: now, until: now + ALARM_MS, panicUntil: now + INTRUSION_PANIC_MS, agentIds: ordered.map((agent) => agent.id) };
28812
29117
  this.intrusions.set(key, effect);
28813
29118
  this.buildingEffect = effect;
28814
29119
  const id = `intrusion:${++this.seq}`;
28815
29120
  const roomName = rooms.find((room) => room.id === newest.roomId)?.name ?? newest.roomId;
28816
- const activity = { id, kind: "other", icon: "\u{1F6A8}", text: tr("Intrus\xE3o no pr\xE9dio"), detail: text2, at: now };
29121
+ const activity = { id, kind: "other", icon: "\u{1F6A8}", text: tr("Intrus\xE3o no pr\xE9dio"), detail: text3, at: now };
28817
29122
  this.pushFeed([{
28818
29123
  id,
28819
29124
  agentId: newest.id,
@@ -28823,7 +29128,7 @@ var Office = class {
28823
29128
  account: newest.account,
28824
29129
  activity
28825
29130
  }]);
28826
- this.pendingNotices.push({ id, level: "alert", text: text2, agentId: newest.id, roomId: newest.roomId, at: now });
29131
+ this.pendingNotices.push({ id, level: "alert", text: text3, agentId: newest.id, roomId: newest.roomId, at: now });
28827
29132
  }
28828
29133
  this.duplicateGroups = current2;
28829
29134
  for (const key of this.intrusions.keys()) if (!current2.has(key)) this.intrusions.delete(key);
@@ -28884,6 +29189,10 @@ var Office = class {
28884
29189
  this.roomNames.set(id, tr("Agent Hub"));
28885
29190
  continue;
28886
29191
  }
29192
+ if (id === GENTLE_SHELL_ROOM_ID) {
29193
+ this.roomNames.set(id, tr("Gentle Shell"));
29194
+ continue;
29195
+ }
28887
29196
  const custom = this.customRooms.get(id);
28888
29197
  if (custom) {
28889
29198
  this.roomNames.set(id, roomDisplayName({ ...custom, custom: true }));
@@ -28912,7 +29221,7 @@ var Office = class {
28912
29221
  this.feed.push(...items);
28913
29222
  if (this.feed.length > FEED_LIMIT) this.feed.splice(0, this.feed.length - FEED_LIMIT);
28914
29223
  }
28915
- notice(kind, key, level, text2, roomId, opts = {}) {
29224
+ notice(kind, key, level, text3, roomId, opts = {}) {
28916
29225
  if (this.booting) return;
28917
29226
  const now = this.now();
28918
29227
  const k = opts.dedupeKey ?? `${key}|${kind}`;
@@ -28923,7 +29232,7 @@ var Office = class {
28923
29232
  if (this.noticeAt.size > 2e3) {
28924
29233
  for (const [nk, t] of this.noticeAt) if (now - t > Math.max(NOTICE_DEDUPE_MS, SHELL_NOTICE_DEDUPE_MS)) this.noticeAt.delete(nk);
28925
29234
  }
28926
- const n2 = { id: `n-${now.toString(36)}-${++this.seq}`, level, text: text2, at: now };
29235
+ const n2 = { id: `n-${now.toString(36)}-${++this.seq}`, level, text: text3, at: now };
28927
29236
  if (kind !== "room") n2.agentId = key;
28928
29237
  if (roomId) n2.roomId = roomId;
28929
29238
  this.pendingNotices.push(n2);
@@ -29554,6 +29863,261 @@ function createAvatarRoutes(store, hub2) {
29554
29863
  };
29555
29864
  }
29556
29865
 
29866
+ // server/inbox/store.ts
29867
+ import { randomBytes as randomBytes9 } from "node:crypto";
29868
+ import { mkdirSync as mkdirSync13, readFileSync as readFileSync18, renameSync as renameSync12, writeFileSync as writeFileSync12 } from "node:fs";
29869
+ import { dirname as dirname11 } from "node:path";
29870
+ var InboxStore = class {
29871
+ constructor(file, opts = {}) {
29872
+ this.file = file;
29873
+ this.now = opts.now ?? Date.now;
29874
+ this.newId = opts.id ?? (() => randomBytes9(6).toString("hex"));
29875
+ this.items = this.load();
29876
+ this.dropOldResolved();
29877
+ }
29878
+ file;
29879
+ items;
29880
+ now;
29881
+ newId;
29882
+ listeners = /* @__PURE__ */ new Set();
29883
+ /** Every stored item (open and resolved), oldest first. */
29884
+ list() {
29885
+ return structuredClone(this.items);
29886
+ }
29887
+ get(id) {
29888
+ const i = this.items.find((x) => x.id === id);
29889
+ return i ? structuredClone(i) : void 0;
29890
+ }
29891
+ openCount() {
29892
+ return this.items.filter((i) => i.status === "open").length;
29893
+ }
29894
+ onChange(cb) {
29895
+ this.listeners.add(cb);
29896
+ return () => void this.listeners.delete(cb);
29897
+ }
29898
+ post(input, from) {
29899
+ const now = this.now();
29900
+ const existing = input.key ? this.items.find((i) => i.key === input.key) : void 0;
29901
+ const reopened = existing?.status === "resolved";
29902
+ if ((!existing || reopened) && this.openCount() >= INBOX_OPEN_MAX) return { error: "full" };
29903
+ let item;
29904
+ if (existing) {
29905
+ item = existing;
29906
+ item.title = input.title;
29907
+ if (input.body !== void 0) item.body = input.body;
29908
+ else delete item.body;
29909
+ if (input.link !== void 0) item.link = input.link;
29910
+ else delete item.link;
29911
+ item.from = from;
29912
+ item.status = "open";
29913
+ item.updatedAt = now;
29914
+ delete item.resolvedAt;
29915
+ } else {
29916
+ item = { id: this.newId(), title: input.title, from, scope: "local", status: "open", createdAt: now, updatedAt: now };
29917
+ if (input.key) item.key = input.key;
29918
+ if (input.body !== void 0) item.body = input.body;
29919
+ if (input.link !== void 0) item.link = input.link;
29920
+ this.items.push(item);
29921
+ }
29922
+ this.save();
29923
+ const created = !existing;
29924
+ const out = structuredClone(item);
29925
+ this.emit(created || reopened ? { kind: "arrived", item: out } : { kind: "changed" });
29926
+ return { item: out, created, reopened };
29927
+ }
29928
+ /** Marks the item resolved (idempotent); undefined for an unknown id. */
29929
+ resolve(id) {
29930
+ const item = this.items.find((i) => i.id === id);
29931
+ if (!item) return void 0;
29932
+ if (item.status === "open") {
29933
+ const now = this.now();
29934
+ item.status = "resolved";
29935
+ item.resolvedAt = now;
29936
+ item.updatedAt = now;
29937
+ this.save();
29938
+ this.emit({ kind: "changed" });
29939
+ }
29940
+ return structuredClone(item);
29941
+ }
29942
+ /** Drops resolved items older than 7 days; true when something was dropped. */
29943
+ purge() {
29944
+ if (!this.dropOldResolved()) return false;
29945
+ this.save();
29946
+ this.emit({ kind: "changed" });
29947
+ return true;
29948
+ }
29949
+ dropOldResolved() {
29950
+ const limit = this.now() - INBOX_RESOLVED_KEEP_MS;
29951
+ const before = this.items.length;
29952
+ this.items = this.items.filter((i) => !(i.status === "resolved" && (i.resolvedAt ?? i.updatedAt) <= limit));
29953
+ return this.items.length !== before;
29954
+ }
29955
+ emit(e) {
29956
+ for (const cb of this.listeners) cb(e);
29957
+ }
29958
+ load() {
29959
+ if (!this.file) return [];
29960
+ try {
29961
+ const j = JSON.parse(readFileSync18(this.file, "utf8"));
29962
+ if (!Array.isArray(j.items)) return [];
29963
+ return j.items.map(parseInboxItem).filter((i) => !!i);
29964
+ } catch (err) {
29965
+ if (err.code !== "ENOENT") log.warn(tr("inbox.json ileg\xEDvel ({0}); come\xE7ando sem itens.", [errMsg(err)]));
29966
+ return [];
29967
+ }
29968
+ }
29969
+ save() {
29970
+ if (!this.file) return;
29971
+ try {
29972
+ mkdirSync13(dirname11(this.file), { recursive: true });
29973
+ writeFileSync12(`${this.file}.tmp`, JSON.stringify({ version: 1, items: this.items }, null, 2));
29974
+ renameSync12(`${this.file}.tmp`, this.file);
29975
+ } catch (err) {
29976
+ log.warn(tr("N\xE3o consegui gravar {0}: {1}", [this.file, errMsg(err)]));
29977
+ }
29978
+ }
29979
+ };
29980
+
29981
+ // server/inbox/sender.ts
29982
+ var PID_ID = /:(\d+)$/;
29983
+ function senderFor(post, agents2) {
29984
+ const byPid = /* @__PURE__ */ new Map();
29985
+ for (const a of agents2) {
29986
+ if (a.parentId || a.id.startsWith("@")) continue;
29987
+ const m = PID_ID.exec(a.id);
29988
+ if (m) byPid.set(Number(m[1]), a.id);
29989
+ }
29990
+ for (const pid of post.ancestors) {
29991
+ const id = byPid.get(pid);
29992
+ if (id) return { kind: "agent", agentId: id };
29993
+ }
29994
+ return post.source ? { kind: "script", name: post.source } : { kind: "script" };
29995
+ }
29996
+
29997
+ // server/inbox/service.ts
29998
+ var InboxService = class {
29999
+ store;
30000
+ agents;
30001
+ remote;
30002
+ offRemote;
30003
+ frameCbs = /* @__PURE__ */ new Set();
30004
+ constructor(opts) {
30005
+ this.store = opts.store;
30006
+ this.agents = opts.agents;
30007
+ this.store.onChange((e) => this.emit(e.kind === "arrived" ? e.item : void 0));
30008
+ }
30009
+ /** Central: also list (and resolve) the items of the paired machines. */
30010
+ setRemote(remote) {
30011
+ this.offRemote?.();
30012
+ this.remote = remote;
30013
+ this.offRemote = remote?.onChange((arrived) => this.emit(arrived));
30014
+ }
30015
+ /** What the page shows: open items first, then the recently resolved ones. */
30016
+ frame(arrived) {
30017
+ const items = visibleInbox([...this.store.list(), ...this.remote?.items() ?? []]);
30018
+ return arrived ? { items, arrived } : { items };
30019
+ }
30020
+ onFrame(cb) {
30021
+ this.frameCbs.add(cb);
30022
+ return () => void this.frameCbs.delete(cb);
30023
+ }
30024
+ /** Leaves an item on this machine's desk; the sender comes from the CLI's process tree. */
30025
+ post(post) {
30026
+ return this.store.post(post, senderFor(post, this.agents()));
30027
+ }
30028
+ async resolve(id) {
30029
+ if (parseRemoteId(id)) return this.remote ? this.remote.resolve(id) : { ok: false, status: 404, error: "unknown" };
30030
+ const item = this.store.resolve(id);
30031
+ return item ? { ok: true, item } : { ok: false, status: 404, error: "unknown" };
30032
+ }
30033
+ emit(arrived) {
30034
+ if (!this.frameCbs.size) return;
30035
+ const f = this.frame(arrived);
30036
+ for (const cb of this.frameCbs) cb(f);
30037
+ }
30038
+ };
30039
+
30040
+ // server/inbox/http.ts
30041
+ var RESOLVE_ROUTE = /^\/api\/inbox\/([^/]+)\/resolve$/;
30042
+ function createInboxRoutes(service) {
30043
+ const fail3 = (res, err) => {
30044
+ if (res.headersSent) return void res.destroy();
30045
+ if (err instanceof HttpError) sendJson2(res, err.status, { error: err.message });
30046
+ else sendJson2(res, 500, { error: tr("erro interno") });
30047
+ };
30048
+ const post = async (req, res) => {
30049
+ const parsed = parseInboxPost(await readJson(req));
30050
+ if (!parsed.ok) throw new HttpError(400, parsed.error);
30051
+ const r = service.post(parsed.post);
30052
+ if ("error" in r) throw new HttpError(429, tr("a mesa j\xE1 tem {0} itens abertos: resolva alguns antes de deixar outros", [INBOX_OPEN_MAX]));
30053
+ sendJson2(res, r.created ? 201 : 200, { ok: true, item: r.item, created: r.created, ...r.created ? {} : { reopened: r.reopened } });
30054
+ };
30055
+ const resolve15 = async (res, id) => {
30056
+ const r = await service.resolve(id);
30057
+ if (!r.ok) throw new HttpError(r.status, r.status === 404 ? tr("item n\xE3o encontrado") : r.error);
30058
+ sendJson2(res, 200, { ok: true, ...r.item ? { item: r.item } : {} });
30059
+ };
30060
+ return (req, res, path) => {
30061
+ const method = req.method ?? "GET";
30062
+ const m = RESOLVE_ROUTE.exec(path);
30063
+ if (m) {
30064
+ if (method !== "POST") {
30065
+ res.setHeader("Allow", "POST");
30066
+ return sendJson2(res, 405, { error: tr("m\xE9todo n\xE3o permitido") });
30067
+ }
30068
+ let id;
30069
+ try {
30070
+ id = decodeURIComponent(m[1]);
30071
+ } catch {
30072
+ return sendJson2(res, 404, { error: tr("item n\xE3o encontrado") });
30073
+ }
30074
+ req.resume();
30075
+ resolve15(res, id).catch((err) => fail3(res, err));
30076
+ } else if (method === "GET" || method === "HEAD") sendJson2(res, 200, service.frame());
30077
+ else if (method === "POST") post(req, res).catch((err) => fail3(res, err));
30078
+ else {
30079
+ res.setHeader("Allow", "GET, POST");
30080
+ sendJson2(res, 405, { error: tr("m\xE9todo n\xE3o permitido") });
30081
+ }
30082
+ };
30083
+ }
30084
+
30085
+ // server/central/inbox.ts
30086
+ var RemoteInboxItems = class {
30087
+ constructor(hub2) {
30088
+ this.hub = hub2;
30089
+ }
30090
+ hub;
30091
+ items() {
30092
+ return this.hub.inboxItems();
30093
+ }
30094
+ onChange(cb) {
30095
+ return this.hub.onInbox(cb);
30096
+ }
30097
+ async resolve(id) {
30098
+ const ref = parseRemoteId(id);
30099
+ if (!ref) return { ok: false, status: 404, error: "unknown" };
30100
+ const q = this.hub.enqueue(ref.machine, { type: "inbox.resolve", itemId: ref.local });
30101
+ if ("error" in q) return { ok: false, status: 503, error: "offline" };
30102
+ try {
30103
+ const r = await q.result;
30104
+ if (!r.ok) return { ok: false, status: r.data === "not-found" ? 404 : r.status ?? 502, error: r.error ?? "failed" };
30105
+ } catch {
30106
+ return { ok: false, status: 504, error: "timeout" };
30107
+ }
30108
+ this.hub.markInboxResolved(ref.machine, ref.local);
30109
+ return { ok: true };
30110
+ }
30111
+ };
30112
+ function createInboxResolveHandler(opts) {
30113
+ return async (a, deadline) => {
30114
+ if (a.type !== "inbox.resolve") return { actionId: a.id, ok: false, error: "unsupported" };
30115
+ if (Date.now() > deadline) return { actionId: a.id, ok: false, error: "expired" };
30116
+ const item = opts.store.resolve(a.itemId);
30117
+ return item ? { actionId: a.id, ok: true, data: "ok" } : { actionId: a.id, ok: false, data: "not-found", status: 404, error: "not-found" };
30118
+ };
30119
+ }
30120
+
29557
30121
  // server/attention/drain.ts
29558
30122
  function drainAttention(relay, hub2) {
29559
30123
  for (const close of relay.expire()) hub2.broadcast("attention", close);
@@ -29691,8 +30255,8 @@ function findCodexBin(env, isExecutable = canExecute) {
29691
30255
  }
29692
30256
  return void 0;
29693
30257
  }
29694
- function queueArgs(thread, text2) {
29695
- return ["queue", `--thread=${thread}`, `--message=${text2}`];
30258
+ function queueArgs(thread, text3) {
30259
+ return ["queue", `--thread=${thread}`, `--message=${text3}`];
29696
30260
  }
29697
30261
  function firstLine2(s2) {
29698
30262
  const line2 = (s2 ?? "").split(/\r?\n/).map((l) => l.trim()).find(Boolean);
@@ -29720,7 +30284,7 @@ function createCodexQueueRunner(bin, opts = {}) {
29720
30284
  }
29721
30285
 
29722
30286
  // server/messages/images.ts
29723
- import { randomBytes as randomBytes9 } from "node:crypto";
30287
+ import { randomBytes as randomBytes10 } from "node:crypto";
29724
30288
  function sniffImage(data) {
29725
30289
  if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return { type: "image/png", ext: "png" };
29726
30290
  if (data.length >= 3 && data[0] === 255 && data[1] === 216 && data[2] === 255) return { type: "image/jpeg", ext: "jpg" };
@@ -29751,7 +30315,7 @@ var MessageImages = class {
29751
30315
  constructor(opts = {}) {
29752
30316
  this.store = opts.store ?? new AttachmentStore();
29753
30317
  this.root = opts.root;
29754
- this.folderId = opts.folderId ?? (() => randomBytes9(6).toString("hex"));
30318
+ this.folderId = opts.folderId ?? (() => randomBytes10(6).toString("hex"));
29755
30319
  this.write = opts.write ?? writeAttachments;
29756
30320
  }
29757
30321
  upload(raw) {
@@ -29919,7 +30483,7 @@ function rec8(v) {
29919
30483
  function str10(v) {
29920
30484
  return typeof v === "string" && v.trim() ? v : void 0;
29921
30485
  }
29922
- function num7(v) {
30486
+ function num8(v) {
29923
30487
  return typeof v === "number" && Number.isFinite(v) ? v : void 0;
29924
30488
  }
29925
30489
  function toMs3(v) {
@@ -29976,12 +30540,12 @@ function parseSessionMeta(payload, at) {
29976
30540
  var WINDOW_BY_MINUTES = { 300: "fiveHour", 10080: "sevenDay" };
29977
30541
  function usageWindow(raw) {
29978
30542
  const w = rec8(raw);
29979
- const minutes = num7(w?.window_minutes);
29980
- const used = num7(w?.used_percent);
30543
+ const minutes = num8(w?.window_minutes);
30544
+ const used = num8(w?.used_percent);
29981
30545
  const key = minutes !== void 0 ? WINDOW_BY_MINUTES[minutes] : void 0;
29982
30546
  if (!w || !key || used === void 0) return void 0;
29983
30547
  const window = { utilization: Math.min(100, Math.max(0, used)) };
29984
- const resets = num7(w.resets_at);
30548
+ const resets = num8(w.resets_at);
29985
30549
  if (resets !== void 0) window.resetsAt = resets < 1e12 ? Math.round(resets * 1e3) : Math.round(resets);
29986
30550
  return { key, window };
29987
30551
  }
@@ -30023,8 +30587,8 @@ function fileChanges(raw) {
30023
30587
  const p = str10(path);
30024
30588
  if (!p) return;
30025
30589
  const kind = changeKind(c.type ?? c.kind);
30026
- const text2 = str10(c.unified_diff) ?? str10(c.diff) ?? str10(c.content) ?? "";
30027
- const e = { path: p, kind, text: text2 };
30590
+ const text3 = str10(c.unified_diff) ?? str10(c.diff) ?? str10(c.content) ?? "";
30591
+ const e = { path: p, kind, text: text3 };
30028
30592
  const move = str10(c.move_path) ?? str10(rec8(c.kind)?.move_path);
30029
30593
  if (move) e.movePath = move;
30030
30594
  out.push(e);
@@ -30064,8 +30628,8 @@ function mcpName(server2, tool) {
30064
30628
  }
30065
30629
  function userMessagingText(server2, tool, args) {
30066
30630
  if (!/user_messag(?:e|ing)[_.]*send_message$/i.test(`${String(server2 ?? "")}__${String(tool ?? "")}`)) return void 0;
30067
- const text2 = rec8(args)?.text ?? parseArguments(args).text;
30068
- return typeof text2 === "string" && text2.trim() ? text2 : void 0;
30631
+ const text3 = rec8(args)?.text ?? parseArguments(args).text;
30632
+ return typeof text3 === "string" && text3.trim() ? text3 : void 0;
30069
30633
  }
30070
30634
  var DELIVERY_COMPLETE = "codex:code-mode-delivery:v1:complete";
30071
30635
  var DELIVERY_INCOMPLETE = "codex:code-mode-delivery:v1:incomplete:";
@@ -30073,16 +30637,16 @@ function deliveredMessage(line2) {
30073
30637
  const marker = str10(rec8(line2.metadata)?.delivered_assistant_message);
30074
30638
  const p = rec8(line2.payload);
30075
30639
  if (!marker || !p || p.type !== "message" || p.role !== "assistant") return void 0;
30076
- let text2 = "";
30077
- if (marker === DELIVERY_COMPLETE) text2 = contentText(p.content).text;
30078
- else if (marker.startsWith(DELIVERY_INCOMPLETE)) text2 = marker.slice(DELIVERY_INCOMPLETE.length);
30079
- if (!text2.trim()) return void 0;
30640
+ let text3 = "";
30641
+ if (marker === DELIVERY_COMPLETE) text3 = contentText(p.content).text;
30642
+ else if (marker.startsWith(DELIVERY_INCOMPLETE)) text3 = marker.slice(DELIVERY_INCOMPLETE.length);
30643
+ if (!text3.trim()) return void 0;
30080
30644
  const id = str10(p.id);
30081
- return id ? { id, text: text2 } : { text: text2 };
30645
+ return id ? { id, text: text3 } : { text: text3 };
30082
30646
  }
30083
- function describeCodexPrompt(text2) {
30084
- const shown2 = truncate(maskSecrets(text2.slice(0, 1e3)), 34);
30085
- return { ...describePrompt(text2), text: truncate(tr("Recebeu \u201C{0}\u201D", [shown2]), 46) };
30647
+ function describeCodexPrompt(text3) {
30648
+ const shown2 = truncate(maskSecrets(text3.slice(0, 1e3)), 34);
30649
+ return { ...describePrompt(text3), text: truncate(tr("Recebeu \u201C{0}\u201D", [shown2]), 46) };
30086
30650
  }
30087
30651
  var PLAN_STATUS = /* @__PURE__ */ new Set(["pending", "in_progress", "completed"]);
30088
30652
  function planTasks(args) {
@@ -30180,15 +30744,15 @@ function contentText(content) {
30180
30744
  return { text: texts.join(""), images };
30181
30745
  }
30182
30746
  function promptText(raw) {
30183
- const text2 = raw.trim();
30184
- if (!text2 || INJECTED.test(text2)) return "";
30185
- return text2;
30747
+ const text3 = raw.trim();
30748
+ if (!text3 || INJECTED.test(text3)) return "";
30749
+ return text3;
30186
30750
  }
30187
30751
  function outputOf(raw) {
30188
30752
  if (typeof raw === "string") {
30189
30753
  try {
30190
30754
  const j = rec8(JSON.parse(raw));
30191
- if (j && typeof j.output === "string") return { text: j.output, exitCode: num7(rec8(j.metadata)?.exit_code) };
30755
+ if (j && typeof j.output === "string") return { text: j.output, exitCode: num8(rec8(j.metadata)?.exit_code) };
30192
30756
  } catch {
30193
30757
  }
30194
30758
  const exit = /^Exit code:\s*(-?\d+)/m.exec(raw.slice(0, 500))?.[1];
@@ -30223,7 +30787,7 @@ var RolloutLineParser = class {
30223
30787
  * mais a posição dentro da linha. Uma releitura do arquivo gera as mesmas chaves (o Office não duplica).
30224
30788
  */
30225
30789
  autoKey() {
30226
- const ordinal = num7(this.j.ordinal);
30790
+ const ordinal = num8(this.j.ordinal);
30227
30791
  const base = ordinal !== void 0 ? `o${ordinal}` : `t${this.at.toString(36)}`;
30228
30792
  const n2 = this.autoKeys++;
30229
30793
  return n2 ? `${base}:${n2}` : base;
@@ -30293,7 +30857,7 @@ var RolloutLineParser = class {
30293
30857
  case "task_complete":
30294
30858
  case "turn_complete": {
30295
30859
  this.endTurn(false);
30296
- const ms = num7(p.duration_ms);
30860
+ const ms = num8(p.duration_ms);
30297
30861
  const err = rec8(p.error);
30298
30862
  const turn = str10(p.turn_id) ?? this.autoKey();
30299
30863
  if (err) this.push(SPECIAL.error(void 0, firstLine3(str10(err.message) ?? "")), { key: `${turn}:err`, current: false });
@@ -30316,8 +30880,8 @@ var RolloutLineParser = class {
30316
30880
  case "agent_message": {
30317
30881
  if (this.paginated()) return;
30318
30882
  this.s.mode ??= "legacy";
30319
- const text2 = str10(p.message);
30320
- if (text2) this.push(SPECIAL.respond(text2));
30883
+ const text3 = str10(p.message);
30884
+ if (text3) this.push(SPECIAL.respond(text3));
30321
30885
  this.progress();
30322
30886
  return;
30323
30887
  }
@@ -30326,7 +30890,7 @@ var RolloutLineParser = class {
30326
30890
  return this.think();
30327
30891
  case "exec_command_end":
30328
30892
  if (this.paginated()) return;
30329
- return this.command({ id: str10(p.call_id), command: p.command, exitCode: num7(p.exit_code), output: str10(p.aggregated_output) ?? str10(p.formatted_output) ?? str10(p.stdout) ?? "", status: str10(p.status) });
30893
+ return this.command({ id: str10(p.call_id), command: p.command, exitCode: num8(p.exit_code), output: str10(p.aggregated_output) ?? str10(p.formatted_output) ?? str10(p.stdout) ?? "", status: str10(p.status) });
30330
30894
  case "patch_apply_end":
30331
30895
  if (this.paginated()) return;
30332
30896
  return this.fileChange(str10(p.call_id), p.changes, p.success === false ? "failed" : str10(p.status));
@@ -30354,8 +30918,8 @@ var RolloutLineParser = class {
30354
30918
  tokens(p) {
30355
30919
  const total2 = rec8(rec8(p.info)?.total_token_usage);
30356
30920
  if (total2) {
30357
- const tin = num7(total2.input_tokens) ?? 0;
30358
- const tout = num7(total2.output_tokens) ?? 0;
30921
+ const tin = num8(total2.input_tokens) ?? 0;
30922
+ const tout = num8(total2.output_tokens) ?? 0;
30359
30923
  if (tin !== this.s.stats.tokensIn || tout !== this.s.stats.tokensOut) {
30360
30924
  this.s.stats.tokensIn = tin;
30361
30925
  this.s.stats.tokensOut = tout;
@@ -30377,13 +30941,13 @@ var RolloutLineParser = class {
30377
30941
  this.push(SPECIAL.think(), { key });
30378
30942
  }
30379
30943
  prompt(raw, images, key) {
30380
- const text2 = promptText(raw) || (images ? tr("[imagem]") : "");
30381
- if (!text2) return;
30944
+ const text3 = promptText(raw) || (images ? tr("[imagem]") : "");
30945
+ if (!text3) return;
30382
30946
  if (this.s.title === void 0) {
30383
- this.s.title = truncate(maskSecrets(text2.slice(0, 1e3)), TITLE_MAX2);
30947
+ this.s.title = truncate(maskSecrets(text3.slice(0, 1e3)), TITLE_MAX2);
30384
30948
  this.changed();
30385
30949
  }
30386
- this.push(describeCodexPrompt(text2), { key });
30950
+ this.push(describeCodexPrompt(text3), { key });
30387
30951
  }
30388
30952
  // ---------------------------------------------------------------- item_completed (paginated)
30389
30953
  item(item) {
@@ -30392,13 +30956,13 @@ var RolloutLineParser = class {
30392
30956
  switch (item.type) {
30393
30957
  case "UserMessage": {
30394
30958
  this.sawPaginated();
30395
- const { text: text2, images } = contentText(item.content);
30396
- return this.prompt(text2, images, id);
30959
+ const { text: text3, images } = contentText(item.content);
30960
+ return this.prompt(text3, images, id);
30397
30961
  }
30398
30962
  case "AgentMessage": {
30399
30963
  this.sawPaginated();
30400
- const text2 = contentText(item.content).text.trim();
30401
- if (text2) this.push(SPECIAL.respond(text2), { key: id });
30964
+ const text3 = contentText(item.content).text.trim();
30965
+ if (text3) this.push(SPECIAL.respond(text3), { key: id });
30402
30966
  this.progress();
30403
30967
  return;
30404
30968
  }
@@ -30410,7 +30974,7 @@ var RolloutLineParser = class {
30410
30974
  this.sawPaginated();
30411
30975
  this.s.stats.toolCalls++;
30412
30976
  this.changed();
30413
- return this.command({ id, command: item.command, exitCode: num7(item.exit_code), output: str10(item.aggregated_output) ?? "", status: str10(item.status) });
30977
+ return this.command({ id, command: item.command, exitCode: num8(item.exit_code), output: str10(item.aggregated_output) ?? "", status: str10(item.status) });
30414
30978
  case "FileChange":
30415
30979
  this.sawPaginated();
30416
30980
  this.s.stats.toolCalls++;
@@ -30836,7 +31400,7 @@ function rec9(v) {
30836
31400
  function str11(v) {
30837
31401
  return typeof v === "string" && v.trim() ? v : void 0;
30838
31402
  }
30839
- function num8(v) {
31403
+ function num9(v) {
30840
31404
  return typeof v === "number" && Number.isFinite(v) ? v : void 0;
30841
31405
  }
30842
31406
  function toMs4(v) {
@@ -30929,19 +31493,19 @@ var CodexTerminalParser = class {
30929
31493
  user(id, at, raw, images = 0) {
30930
31494
  const clean4 = promptText(raw);
30931
31495
  const pics = images ? Array.from({ length: Math.min(images, 10) }, () => tr("[imagem]")).join(" ") : "";
30932
- const text2 = marked(prepare([clean4, pics].filter(Boolean).join("\n"), TEXT_MAX));
30933
- if (text2) this.emit({ kind: "user", id: `${id}:u`, at, text: text2 });
31496
+ const text3 = marked(prepare([clean4, pics].filter(Boolean).join("\n"), TEXT_MAX));
31497
+ if (text3) this.emit({ kind: "user", id: `${id}:u`, at, text: text3 });
30934
31498
  }
30935
31499
  assistant(id, at, raw) {
30936
- const text2 = marked(prepare(raw, TEXT_MAX));
30937
- if (text2) this.emit({ kind: "assistant", id, at, text: text2 });
31500
+ const text3 = marked(prepare(raw, TEXT_MAX));
31501
+ if (text3) this.emit({ kind: "assistant", id, at, text: text3 });
30938
31502
  }
30939
31503
  thinking(id, at, raw) {
30940
- const text2 = raw.trim() ? marked(prepare(raw, THINKING_MAX)) : "";
30941
- this.emit(text2 ? { kind: "thinking", id, at, text: text2 } : { kind: "thinking", id, at });
31504
+ const text3 = raw.trim() ? marked(prepare(raw, THINKING_MAX)) : "";
31505
+ this.emit(text3 ? { kind: "thinking", id, at, text: text3 } : { kind: "thinking", id, at });
30942
31506
  }
30943
- sys(id, at, text2, o = {}) {
30944
- const e = { kind: "system", id: `${id}:s`, at, text: maskSecrets(text2), level: o.level ?? "info" };
31507
+ sys(id, at, text3, o = {}) {
31508
+ const e = { kind: "system", id: `${id}:s`, at, text: maskSecrets(text3), level: o.level ?? "info" };
30945
31509
  if (o.turnDone) {
30946
31510
  e.turnDone = true;
30947
31511
  e.doneLabel = tr("pronto {0}", ["{0}"]);
@@ -30974,7 +31538,7 @@ var CodexTerminalParser = class {
30974
31538
  return this.item(rec9(p.item), at, key);
30975
31539
  case "task_complete":
30976
31540
  case "turn_complete": {
30977
- const ms = num8(p.duration_ms);
31541
+ const ms = num9(p.duration_ms);
30978
31542
  const err = rec9(p.error);
30979
31543
  if (err) this.sys(`${str11(p.turn_id) ?? key}:err`, at, tr("Erro: {0}", [oneLine(str11(err.message) ?? tr("desconhecido"), 160)]), { level: "error" });
30980
31544
  if (ms !== void 0 && ms >= 0) this.sys(`${str11(p.turn_id) ?? key}:done`, at, tr("Turno conclu\xEDdo em {0}", [formatDuration(ms)]), { turnDone: true });
@@ -30997,7 +31561,7 @@ var CodexTerminalParser = class {
30997
31561
  return this.thinking(key, at, str11(p.text) ?? "");
30998
31562
  case "exec_command_end":
30999
31563
  if (this.mode === "paginated") return;
31000
- return this.command(str11(p.call_id) ?? key, at, p.command, str11(p.aggregated_output) ?? str11(p.formatted_output) ?? str11(p.stdout) ?? "", num8(p.exit_code), str11(p.status));
31564
+ return this.command(str11(p.call_id) ?? key, at, p.command, str11(p.aggregated_output) ?? str11(p.formatted_output) ?? str11(p.stdout) ?? "", num9(p.exit_code), str11(p.status));
31001
31565
  case "context_compacted":
31002
31566
  if (this.mode === "paginated") return;
31003
31567
  return this.sys(key, at, tr("Conversa compactada"));
@@ -31011,8 +31575,8 @@ var CodexTerminalParser = class {
31011
31575
  switch (item.type) {
31012
31576
  case "UserMessage": {
31013
31577
  this.mode ??= "paginated";
31014
- const { text: text2, images } = contentText(item.content);
31015
- return this.user(id, at, text2, images);
31578
+ const { text: text3, images } = contentText(item.content);
31579
+ return this.user(id, at, text3, images);
31016
31580
  }
31017
31581
  case "AgentMessage":
31018
31582
  this.mode ??= "paginated";
@@ -31024,7 +31588,7 @@ var CodexTerminalParser = class {
31024
31588
  }
31025
31589
  case "CommandExecution":
31026
31590
  this.mode ??= "paginated";
31027
- return this.command(id, at, item.command, str11(item.aggregated_output) ?? "", num8(item.exit_code), str11(item.status));
31591
+ return this.command(id, at, item.command, str11(item.aggregated_output) ?? "", num9(item.exit_code), str11(item.status));
31028
31592
  case "FileChange":
31029
31593
  this.mode ??= "paginated";
31030
31594
  return this.fileChange(id, at, item.changes, str11(item.status));
@@ -31059,8 +31623,8 @@ var CodexTerminalParser = class {
31059
31623
  this.tool(id, at, "Bash", toolView("Bash", { command }, this.cwd));
31060
31624
  if (status2 === "declined") return this.result(id, at, tr("Recusado pelo usu\xE1rio"), true);
31061
31625
  const failed = status2 === "failed" || exitCode !== void 0 && exitCode !== 0;
31062
- const text2 = failed && exitCode !== void 0 && exitCode !== 0 ? tr("C\xF3digo de sa\xEDda {0}\n{1}", [exitCode, output]) : output;
31063
- this.result(id, at, text2, failed);
31626
+ const text3 = failed && exitCode !== void 0 && exitCode !== 0 ? tr("C\xF3digo de sa\xEDda {0}\n{1}", [exitCode, output]) : output;
31627
+ this.result(id, at, text3, failed);
31064
31628
  }
31065
31629
  fileChange(id, at, raw, status2) {
31066
31630
  const changes = fileChanges(raw);
@@ -31108,9 +31672,9 @@ ${body2}`;
31108
31672
  case "custom_tool_call_output": {
31109
31673
  const id = str11(p.call_id);
31110
31674
  if (!id || !this.calls.has(id)) return;
31111
- const text2 = resultText2(p.output);
31112
- const exit = /^Exit code:\s*(-?\d+)/m.exec(text2.slice(0, 500))?.[1];
31113
- return this.result(id, at, text2, exit !== void 0 && exit !== "0");
31675
+ const text3 = resultText2(p.output);
31676
+ const exit = /^Exit code:\s*(-?\d+)/m.exec(text3.slice(0, 500))?.[1];
31677
+ return this.result(id, at, text3, exit !== void 0 && exit !== "0");
31114
31678
  }
31115
31679
  default:
31116
31680
  return;
@@ -32137,10 +32701,10 @@ async function scanPrefix2(path, end, idPrefix, keep) {
32137
32701
 
32138
32702
  // server/sources/gentle-shell/accounts.ts
32139
32703
  import { homedir as homedir6 } from "node:os";
32140
- import { basename as basename8, dirname as dirname11, join as join23, resolve as resolve10 } from "node:path";
32704
+ import { basename as basename8, dirname as dirname12, join as join23, resolve as resolve10 } from "node:path";
32141
32705
 
32142
32706
  // server/sources/gentle-shell/files.ts
32143
- import { closeSync as closeSync5, openSync as openSync5, readdirSync as readdirSync14, readFileSync as readFileSync18, readSync as readSync5, statSync as statSync20 } from "node:fs";
32707
+ import { closeSync as closeSync5, openSync as openSync5, readdirSync as readdirSync14, readFileSync as readFileSync19, readSync as readSync5, statSync as statSync20 } from "node:fs";
32144
32708
  import { join as join22 } from "node:path";
32145
32709
 
32146
32710
  // server/sources/gentle-shell/pi.ts
@@ -32150,7 +32714,7 @@ function rec11(v) {
32150
32714
  function str13(v) {
32151
32715
  return typeof v === "string" && v.trim() ? v : void 0;
32152
32716
  }
32153
- function num9(v) {
32717
+ function num10(v) {
32154
32718
  return typeof v === "number" && Number.isFinite(v) ? v : void 0;
32155
32719
  }
32156
32720
  function toMs5(v) {
@@ -32186,7 +32750,7 @@ function todoTasks(raw) {
32186
32750
  const t = rec11(r);
32187
32751
  const title = str13(t?.title);
32188
32752
  if (!t || !title) return;
32189
- out.push({ id: String(num9(t.id) ?? str13(t.id) ?? i + 1), title: truncate(maskSecrets(title.slice(0, 480)), 120), status: todoStatus(t.status) });
32753
+ out.push({ id: String(num10(t.id) ?? str13(t.id) ?? i + 1), title: truncate(maskSecrets(title.slice(0, 480)), 120), status: todoStatus(t.status) });
32190
32754
  });
32191
32755
  return out;
32192
32756
  }
@@ -32301,8 +32865,8 @@ var PiLineParser = class {
32301
32865
  }
32302
32866
  }
32303
32867
  user(id, m) {
32304
- const { text: text2, images } = contentText2(m.content);
32305
- const clean4 = text2.trim() || (images ? tr("[imagem]") : "");
32868
+ const { text: text3, images } = contentText2(m.content);
32869
+ const clean4 = text3.trim() || (images ? tr("[imagem]") : "");
32306
32870
  this.s.turnOpen = true;
32307
32871
  this.s.turnStartAt = this.at;
32308
32872
  this.s.pending.clear();
@@ -32326,8 +32890,8 @@ var PiLineParser = class {
32326
32890
  if (cur?.kind === "think" && this.at - cur.at < 3e4) return;
32327
32891
  this.push(SPECIAL.think(), `${id}:t${i}`);
32328
32892
  } else if (part.type === "text") {
32329
- const text2 = str13(part.text)?.trim();
32330
- if (text2) this.push(SPECIAL.respond(text2), `${id}:x${i}`);
32893
+ const text3 = str13(part.text)?.trim();
32894
+ if (text3) this.push(SPECIAL.respond(text3), `${id}:x${i}`);
32331
32895
  } else if (part.type === "toolCall") {
32332
32896
  this.toolCall(id, i, part);
32333
32897
  }
@@ -32348,9 +32912,9 @@ var PiLineParser = class {
32348
32912
  }
32349
32913
  usage(u) {
32350
32914
  if (!u) return;
32351
- const tin = (num9(u.input) ?? 0) + (num9(u.cacheRead) ?? 0) + (num9(u.cacheWrite) ?? 0);
32352
- const tout = num9(u.output) ?? 0;
32353
- const cost = num9(rec11(u.cost)?.total);
32915
+ const tin = (num10(u.input) ?? 0) + (num10(u.cacheRead) ?? 0) + (num10(u.cacheWrite) ?? 0);
32916
+ const tout = num10(u.output) ?? 0;
32917
+ const cost = num10(rec11(u.cost)?.total);
32354
32918
  this.s.stats.tokensIn += tin;
32355
32919
  this.s.stats.tokensOut += tout;
32356
32920
  if (cost !== void 0) this.s.stats.costUSD = (this.s.stats.costUSD ?? 0) + cost;
@@ -32438,8 +33002,8 @@ function parsePiHead(lines) {
32438
33002
  } else if (j.type === "message") {
32439
33003
  const m = rec11(j.message);
32440
33004
  if (m?.role !== "user") continue;
32441
- const { text: text2, images } = contentText2(m.content);
32442
- const clean4 = text2.trim() || (images ? tr("[imagem]") : "");
33005
+ const { text: text3, images } = contentText2(m.content);
33006
+ const clean4 = text3.trim() || (images ? tr("[imagem]") : "");
32443
33007
  if (clean4) {
32444
33008
  head.title = truncate(maskSecrets(clean4.slice(0, 1e3)), TITLE_MAX3);
32445
33009
  break;
@@ -32479,7 +33043,7 @@ function parseSessionFileName(name) {
32479
33043
  function readJson2(path, max) {
32480
33044
  try {
32481
33045
  if (statSync20(path).size > max) return void 0;
32482
- return JSON.parse(readFileSync18(path, "utf8"));
33046
+ return JSON.parse(readFileSync19(path, "utf8"));
32483
33047
  } catch {
32484
33048
  return void 0;
32485
33049
  }
@@ -32582,9 +33146,9 @@ function readFirstLine(path, max) {
32582
33146
  try {
32583
33147
  const buf = Buffer.alloc(max);
32584
33148
  const n2 = readSync5(fd, buf, 0, max, 0);
32585
- const text2 = buf.subarray(0, n2).toString("utf8");
32586
- const nl = text2.indexOf("\n");
32587
- return nl === -1 ? n2 < max ? text2 : void 0 : text2.slice(0, nl);
33149
+ const text3 = buf.subarray(0, n2).toString("utf8");
33150
+ const nl = text3.indexOf("\n");
33151
+ return nl === -1 ? n2 < max ? text3 : void 0 : text3.slice(0, nl);
32588
33152
  } finally {
32589
33153
  closeSync5(fd);
32590
33154
  }
@@ -32686,7 +33250,7 @@ function discoverGentleShellDirs(env = process.env, home = env.HOME || homedir6(
32686
33250
  function baseId(dir) {
32687
33251
  const d = resolve10(dir);
32688
33252
  const name = basename8(d);
32689
- if (name === "agent") return basename8(dirname11(d)) || name;
33253
+ if (name === "agent") return basename8(dirname12(d)) || name;
32690
33254
  return name || d;
32691
33255
  }
32692
33256
  function detectGentleShellAccounts(dirs, opts = {}) {
@@ -32714,7 +33278,7 @@ function detectGentleShellAccounts(dirs, opts = {}) {
32714
33278
  }
32715
33279
 
32716
33280
  // server/sources/gentle-shell/source.ts
32717
- import { join as join24, resolve as resolve11, sep as sep5 } from "node:path";
33281
+ import { join as join26, resolve as resolve13, sep as sep5 } from "node:path";
32718
33282
 
32719
33283
  // server/sources/gentle-shell/terminal.ts
32720
33284
  var SEEN_MAX4 = 2e4;
@@ -32782,9 +33346,9 @@ var GentleShellTerminalParser = class {
32782
33346
  if (m.role === "toolResult") return this.result(id, at, m);
32783
33347
  }
32784
33348
  user(id, at, m) {
32785
- const { text: text2, images } = contentText2(m.content);
33349
+ const { text: text3, images } = contentText2(m.content);
32786
33350
  const pics = images ? Array.from({ length: Math.min(images, 10) }, () => tr("[imagem]")).join(" ") : "";
32787
- const shown2 = marked(prepare([text2.trim(), pics].filter(Boolean).join("\n"), TEXT_MAX));
33351
+ const shown2 = marked(prepare([text3.trim(), pics].filter(Boolean).join("\n"), TEXT_MAX));
32788
33352
  if (shown2) this.emit({ kind: "user", id: `${id}:u`, at, text: shown2 });
32789
33353
  }
32790
33354
  assistant(id, at, m) {
@@ -32793,11 +33357,11 @@ var GentleShellTerminalParser = class {
32793
33357
  const part = rec11(raw);
32794
33358
  if (!part) return;
32795
33359
  if (part.type === "thinking") {
32796
- const text2 = str14(part.thinking)?.trim() ? marked(prepare(String(part.thinking), THINKING_MAX)) : "";
32797
- this.emit(text2 ? { kind: "thinking", id: `${id}:t${i}`, at, text: text2 } : { kind: "thinking", id: `${id}:t${i}`, at });
33360
+ const text3 = str14(part.thinking)?.trim() ? marked(prepare(String(part.thinking), THINKING_MAX)) : "";
33361
+ this.emit(text3 ? { kind: "thinking", id: `${id}:t${i}`, at, text: text3 } : { kind: "thinking", id: `${id}:t${i}`, at });
32798
33362
  } else if (part.type === "text") {
32799
- const text2 = marked(prepare(String(part.text ?? ""), TEXT_MAX));
32800
- if (text2) this.emit({ kind: "assistant", id: `${id}:x${i}`, at, text: text2 });
33363
+ const text3 = marked(prepare(String(part.text ?? ""), TEXT_MAX));
33364
+ if (text3) this.emit({ kind: "assistant", id: `${id}:x${i}`, at, text: text3 });
32801
33365
  } else if (part.type === "toolCall") {
32802
33366
  const name = str14(part.name);
32803
33367
  if (!name) return;
@@ -32828,387 +33392,10 @@ function createGentleShellTerminalParser() {
32828
33392
  return new GentleShellTerminalParser();
32829
33393
  }
32830
33394
 
32831
- // server/sources/gentle-shell/source.ts
32832
- var PRESENCE_STALE_MS = 3e4;
32833
- var FALLBACK_RECENT_MS2 = 30 * 6e4;
32834
- var WORKING_QUIET_MS2 = 30 * 6e4;
32835
- var TASK_STALE_MS = 30 * 6e4;
32836
- var CLOSE_AFTER_MISSING_MS3 = 1500;
32837
- var BACKLOG_MAX2 = 400;
32838
- var ACTIVE_TASK = /* @__PURE__ */ new Set(["queued", "running", "waiting", "pending", "starting", "in_progress"]);
32839
- var MAIN_ROLE2 = tr("Agente principal (Gentle Shell)");
32840
- var SUB_ROLE2 = tr("Subagente (Gentle Shell)");
32841
- function roleOf2(raw) {
32842
- const r = raw?.trim();
32843
- return r ? `${r[0].toUpperCase()}${r.slice(1)}` : SUB_ROLE2;
32844
- }
32845
- var GentleShellSource = class {
32846
- constructor(opts) {
32847
- this.opts = opts;
32848
- this.now = opts.now ?? Date.now;
32849
- this.tailBytes = opts.tailBytes ?? 2 * 1024 * 1024;
32850
- const others = opts.accounts.entries();
32851
- this.detected = detectGentleShellAccounts(opts.dirs, {
32852
- taken: { shorts: [...others, ...opts.accounts.entriesOf("codex")].map((e) => e.detected.short), colors: [...others, ...opts.accounts.entriesOf("codex")].map((e) => e.detected.color) }
32853
- });
32854
- this.entries = opts.accounts.setProviderAccounts(
32855
- "gentle-shell",
32856
- opts.dirs.map((dir, i) => ({ dir, detected: this.detected[i] }))
32857
- );
32858
- this.accs = this.entries.map((e) => ({ id: e.id, dir: e.dir, configDir: e.detected.configDir, index: new SessionIndex(e.dir, this.now), tasks: new TaskStore(e.dir), recent: /* @__PURE__ */ new Map(), recentAt: -Infinity }));
32859
- }
32860
- opts;
32861
- provider = "gentle-shell";
32862
- accs = [];
32863
- entries = [];
32864
- detected = [];
32865
- trackers = /* @__PURE__ */ new Map();
32866
- timer = null;
32867
- now;
32868
- tailBytes;
32869
- /** Contas do Gentle Shell (ids finais, no AccountsService). */
32870
- accountEntries() {
32871
- return this.entries;
32872
- }
32873
- start() {
32874
- this.boot();
32875
- this.timer = setInterval(() => this.safePoll(), this.opts.pollMs ?? 1e3);
32876
- this.timer.unref?.();
32877
- }
32878
- /** Reconstrói as sessões abertas sem gerar avisos. Síncrono e curto. */
32879
- boot() {
32880
- this.opts.office.beginBoot();
32881
- try {
32882
- this.poll(true);
32883
- } finally {
32884
- this.opts.office.endBoot();
32885
- }
32886
- }
32887
- stop() {
32888
- if (this.timer) clearInterval(this.timer);
32889
- this.timer = null;
32890
- }
32891
- sources() {
32892
- return this.accs.map((acc) => {
32893
- let sessions = 0;
32894
- for (const t of this.trackers.values()) if (t.acc === acc && t.kind === "main" && t.inOffice) sessions++;
32895
- const info = { label: acc.id, provider: "gentle-shell", path: acc.configDir, sessions, ok: !acc.error };
32896
- if (acc.error) info.error = acc.error;
32897
- return info;
32898
- });
32899
- }
32900
- transcriptPathOf(agentId) {
32901
- const t = this.trackers.get(agentId);
32902
- return t?.inOffice ? t.path : void 0;
32903
- }
32904
- terminalParser(agentId) {
32905
- return this.trackers.has(agentId) ? createGentleShellTerminalParser() : void 0;
32906
- }
32907
- watchedTranscripts() {
32908
- return this.trackers.size;
32909
- }
32910
- // ---------------------------------------------------------------- polling
32911
- safePoll() {
32912
- try {
32913
- this.poll(false);
32914
- } catch (err) {
32915
- log.warnOnce(`gentle-shell-poll:${errMsg(err)}`, tr("Gentle Shell: falha no ciclo de leitura: {0}", [errMsg(err)]));
32916
- }
32917
- }
32918
- poll(boot = false) {
32919
- const now = this.now();
32920
- const seen = /* @__PURE__ */ new Set();
32921
- for (const acc of this.accs) {
32922
- for (const [sessionId, workspace] of this.presentSessions(acc, now)) {
32923
- const key = `${acc.id}:${sessionId}`;
32924
- let t = this.trackers.get(key);
32925
- if (!t) {
32926
- t = this.newTracker(acc, key, "main", sessionId);
32927
- this.trackers.set(key, t);
32928
- }
32929
- if (workspace) t.workspace = workspace;
32930
- try {
32931
- this.syncMain(t, now);
32932
- } catch (err) {
32933
- log.warnOnce(`gentle-shell-session:${key}:${errMsg(err)}`, tr("Gentle Shell: sess\xE3o {0}: {1}", [key, errMsg(err)]));
32934
- }
32935
- seen.add(key);
32936
- }
32937
- }
32938
- for (const [key, t] of [...this.trackers]) {
32939
- if (t.kind !== "main" || seen.has(key)) continue;
32940
- t.missingSince ??= now;
32941
- if (!boot && now - t.missingSince < CLOSE_AFTER_MISSING_MS3) continue;
32942
- this.leaveMain(t);
32943
- this.trackers.delete(key);
32944
- }
32945
- for (const acc of this.accs) {
32946
- try {
32947
- this.syncSubs(acc, now);
32948
- } catch (err) {
32949
- log.warnOnce(`gentle-shell-tasks:${acc.id}:${errMsg(err)}`, tr("Gentle Shell: falha ao ler os subagentes: {0}", [errMsg(err)]));
32950
- }
32951
- }
32952
- }
32953
- /** Sessões abertas de uma conta (id → projeto da presença, quando houver). */
32954
- presentSessions(acc, now) {
32955
- const out = /* @__PURE__ */ new Map();
32956
- acc.index.refresh();
32957
- const presence = readPresence(acc.dir);
32958
- if (presence) {
32959
- const fresh = presence.filter((p) => now - p.heartbeat <= PRESENCE_STALE_MS);
32960
- const known = new Set(fresh.flatMap((p) => p.sessionId ? [p.sessionId] : []));
32961
- for (const p of fresh) {
32962
- const id = this.sessionOf(acc, p, known);
32963
- if (id) {
32964
- out.set(id, p.workspace);
32965
- known.add(id);
32966
- }
32967
- }
32968
- return out;
32969
- }
32970
- if (now - acc.recentAt >= 1e4) {
32971
- acc.recentAt = now;
32972
- acc.recent = new Map(acc.index.all().map((f) => [f.sessionId, f.mtimeMs]));
32973
- }
32974
- for (const [sessionId, mtime] of acc.recent) {
32975
- const t = this.trackers.get(`${acc.id}:${sessionId}`);
32976
- if (now - Math.max(mtime, t?.lastWriteAt ?? 0) <= FALLBACK_RECENT_MS2) out.set(sessionId, void 0);
32977
- }
32978
- return out;
32979
- }
32980
- /** Sessão de uma encarnação: a do discovery ou, sem ela, o transcript mais recente do projeto ainda sem dono. */
32981
- sessionOf(acc, p, taken) {
32982
- if (p.sessionId) return p.sessionId;
32983
- if (!p.workspace) return void 0;
32984
- return acc.index.latestFor(p.workspace, taken)?.sessionId;
32985
- }
32986
- newTracker(acc, key, kind, rawId) {
32987
- return { key, acc, kind, rawId, state: createPiState(), backlog: [], inOffice: false, status: kind === "sub" ? "working" : "idle", statusAt: 0 };
32988
- }
32989
- // ---------------------------------------------------------------- principais
32990
- syncMain(t, now) {
32991
- delete t.missingSince;
32992
- if (t.inOffice && !this.opts.office.has(t.key)) t.inOffice = false;
32993
- if (!t.tail) {
32994
- const file = t.acc.index.find(t.rawId);
32995
- if (!file) return;
32996
- this.load(t, file.path);
32997
- } else {
32998
- this.pump(t);
32999
- }
33000
- const cwd = t.state.cwd ?? t.workspace;
33001
- if (cwd && !t.inOffice && t.tail) this.enter(t, cwd, now);
33002
- if (t.inOffice) {
33003
- this.quietCheck(t, now);
33004
- this.opts.office.fillWorkingActivity(t.key);
33005
- }
33006
- }
33007
- enter(t, cwd, now) {
33008
- const office2 = this.opts.office;
33009
- office2.addMain({
33010
- id: t.key,
33011
- provider: "gentle-shell",
33012
- account: t.acc.id,
33013
- sessionId: t.rawId,
33014
- cwd,
33015
- role: MAIN_ROLE2,
33016
- startedAt: t.state.startedAt ?? t.state.firstAt ?? now,
33017
- status: t.status,
33018
- waitingFor: t.waitingFor
33019
- });
33020
- t.inOffice = office2.has(t.key);
33021
- if (!t.inOffice) return;
33022
- office2.setStatus(t.key, t.status, t.waitingFor);
33023
- this.flushBacklog(t);
33024
- this.applySummary(t);
33025
- }
33026
- leaveMain(t) {
33027
- if (!t.inOffice) return;
33028
- this.opts.office.closeMain(t.key);
33029
- t.inOffice = false;
33030
- }
33031
- // ---------------------------------------------------------------- subagentes
33032
- syncSubs(acc, now) {
33033
- const tasks = acc.tasks.read();
33034
- const active2 = /* @__PURE__ */ new Map();
33035
- for (const task of tasks) {
33036
- if (!ACTIVE_TASK.has(task.status)) continue;
33037
- if (now - (task.lastAt ?? task.startedAt ?? 0) > TASK_STALE_MS) continue;
33038
- active2.set(`${acc.id}:${task.id}`, task);
33039
- }
33040
- for (const [key, task] of active2) {
33041
- const parent = this.trackers.get(`${acc.id}:${task.parentSessionId}`);
33042
- if (!parent?.inOffice || this.opts.office.isSubDone(parent.key)) continue;
33043
- let t = this.trackers.get(key);
33044
- if (!t) {
33045
- t = this.newTracker(acc, key, "sub", task.id);
33046
- this.trackers.set(key, t);
33047
- }
33048
- t.task = task;
33049
- this.syncSub(t, parent, now);
33050
- }
33051
- for (const [key, t] of [...this.trackers]) {
33052
- if (t.kind !== "sub" || t.acc !== acc) continue;
33053
- const parent = this.trackers.get(`${acc.id}:${t.task?.parentSessionId}`);
33054
- if (active2.has(key) && parent?.inOffice) continue;
33055
- if (t.inOffice) this.opts.office.completeSub(t.key);
33056
- this.trackers.delete(key);
33057
- }
33058
- }
33059
- syncSub(t, parent, now) {
33060
- const task = t.task;
33061
- const path = this.subPath(t.acc, task);
33062
- if (path && path !== t.path) this.load(t, path);
33063
- else if (t.tail) this.pump(t);
33064
- if (!t.inOffice) {
33065
- const added = this.opts.office.addSub({
33066
- id: t.key,
33067
- parentId: parent.key,
33068
- sessionId: task.id,
33069
- role: roleOf2(task.agent),
33070
- title: task.label,
33071
- background: task.mode === "background",
33072
- startedAt: task.startedAt ?? t.state.firstAt ?? now
33073
- });
33074
- if (!added) return;
33075
- t.inOffice = true;
33076
- this.flushBacklog(t);
33077
- }
33078
- if (this.opts.office.isSubDone(t.key)) this.opts.office.reactivateSub(t.key);
33079
- this.applySummary(t);
33080
- }
33081
- /** Transcript do subagente (só dentro das pastas de sessões do Gentle Shell). */
33082
- subPath(acc, task) {
33083
- if (!task.sessionPath) return void 0;
33084
- const p = resolve11(task.sessionPath);
33085
- const roots = [join24(resolve11(acc.dir), SUB_SESSIONS_DIR), join24(resolve11(acc.dir), SESSIONS_DIR2)];
33086
- return p.endsWith(".jsonl") && roots.some((r) => p.startsWith(r + sep5)) ? p : void 0;
33087
- }
33088
- // ---------------------------------------------------------------- transcript
33089
- /** Lê o começo (cwd, título, modelo) e a janela do fim do transcript. */
33090
- load(t, path) {
33091
- const head = parsePiHead(readHeadLines(path));
33092
- const tail = new FileTail(path);
33093
- tail.seekTail(this.tailBytes);
33094
- t.tail = tail;
33095
- t.path = path;
33096
- t.state = createPiState();
33097
- t.state.sessionId = head.sessionId;
33098
- t.state.cwd = head.cwd;
33099
- t.state.startedAt = head.startedAt;
33100
- t.state.model = head.model;
33101
- t.state.title = head.title;
33102
- t.backlog = [];
33103
- for (let i = 0; i < 64; i++) {
33104
- const r = tail.read();
33105
- for (const line2 of r.lines) this.apply(t, parsePiLine(t.state, line2, { idPrefix: t.key, now: this.now() }), false);
33106
- if (!r.more) break;
33107
- }
33108
- t.lastWriteAt = tail.mtimeMs;
33109
- if (t.inOffice) {
33110
- this.flushBacklog(t);
33111
- this.statusToOffice(t);
33112
- }
33113
- }
33114
- pump(t) {
33115
- const tail = t.tail;
33116
- if (!tail) return;
33117
- for (let i = 0; i < 4; i++) {
33118
- let r;
33119
- try {
33120
- r = tail.read();
33121
- } catch (err) {
33122
- log.warnOnce(`gentle-shell-read:${t.key}`, tr("Gentle Shell: transcript de {0} ileg\xEDvel ({1}).", [t.key, errMsg(err)]));
33123
- return;
33124
- }
33125
- if (r.missing) {
33126
- delete t.tail;
33127
- delete t.path;
33128
- return;
33129
- }
33130
- t.lastWriteAt = tail.mtimeMs;
33131
- if (r.reset) {
33132
- this.load(t, tail.path);
33133
- return;
33134
- }
33135
- for (const line2 of r.lines) this.apply(t, parsePiLine(t.state, line2, { idPrefix: t.key, now: this.now() }), true);
33136
- if (r.lines.length) this.applySummary(t);
33137
- if (!r.more) break;
33138
- }
33139
- }
33140
- /** Aplica um resultado de linha: ao vivo vai direto ao escritório; na carga inicial, fica no backlog. */
33141
- apply(t, r, live) {
33142
- if (t.kind === "main") {
33143
- for (const sig of r.signals) {
33144
- switch (sig.type) {
33145
- case "turnStart":
33146
- this.decide(t, "working", r.at, void 0, live);
33147
- break;
33148
- case "turnEnd":
33149
- this.decide(t, "idle", r.at, void 0, live);
33150
- break;
33151
- case "waiting":
33152
- this.decide(t, "waiting", r.at, sig.reason, live);
33153
- break;
33154
- case "progress":
33155
- if (t.status === "waiting") this.decide(t, "working", r.at, void 0, live);
33156
- break;
33157
- }
33158
- }
33159
- }
33160
- if (!live || !t.inOffice) {
33161
- if (r.activities.length) {
33162
- t.backlog.push(r);
33163
- if (t.backlog.length > BACKLOG_MAX2) t.backlog.splice(0, t.backlog.length - BACKLOG_MAX2);
33164
- }
33165
- return;
33166
- }
33167
- this.toOffice(t, r, true);
33168
- }
33169
- toOffice(t, r, live) {
33170
- for (const a of r.activities) this.opts.office.addActivity(t.key, a.activity, a.current, { feed: live });
33171
- }
33172
- flushBacklog(t) {
33173
- const backlog = t.backlog;
33174
- t.backlog = [];
33175
- for (const r of backlog) this.toOffice(t, r, false);
33176
- }
33177
- /** Muda o status por uma borda do transcript: informação mais velha que a última decisão não vale. */
33178
- decide(t, status2, at, waitingFor, live) {
33179
- if (at < t.statusAt) return;
33180
- t.statusAt = at;
33181
- t.status = status2;
33182
- if (waitingFor) t.waitingFor = waitingFor;
33183
- else delete t.waitingFor;
33184
- if (live) this.statusToOffice(t);
33185
- }
33186
- statusToOffice(t) {
33187
- if (t.inOffice && t.kind === "main") this.opts.office.setStatus(t.key, t.status, t.waitingFor);
33188
- }
33189
- /** 'working' sem nenhuma escrita por muito tempo (turno morto num crash): vira 'idle'. */
33190
- quietCheck(t, now) {
33191
- if (t.status !== "working") return;
33192
- if (now - Math.max(t.lastWriteAt ?? 0, t.statusAt) > WORKING_QUIET_MS2) this.decide(t, "idle", now, void 0, true);
33193
- }
33194
- applySummary(t) {
33195
- if (!t.inOffice) return;
33196
- const s2 = t.state;
33197
- const summary = { tasks: s2.tasks, stats: { ...s2.stats } };
33198
- const title = t.kind === "sub" ? t.task?.label ?? s2.title : s2.title;
33199
- if (title) summary.title = title;
33200
- const model = s2.model ?? t.task?.model;
33201
- if (model) summary.model = model;
33202
- if (s2.firstAt !== void 0) summary.firstAt = s2.firstAt;
33203
- if (s2.lastAt !== void 0) summary.lastAt = s2.lastAt;
33204
- this.opts.office.applyTranscript(t.key, summary);
33205
- }
33206
- };
33207
-
33208
33395
  // server/sources/agent-hub/source.ts
33209
- import { closeSync as closeSync6, lstatSync as lstatSync2, openSync as openSync6, readFileSync as readFileSync20, readSync as readSync6, readdirSync as readdirSync15 } from "node:fs";
33396
+ import { closeSync as closeSync6, lstatSync as lstatSync2, openSync as openSync6, readFileSync as readFileSync21, readSync as readSync6, readdirSync as readdirSync15 } from "node:fs";
33210
33397
  import { lstat, readdir as readdir3 } from "node:fs/promises";
33211
- import { basename as basename9, dirname as dirname12, isAbsolute as isAbsolute5, join as join26, resolve as resolve12 } from "node:path";
33398
+ import { basename as basename9, dirname as dirname13, isAbsolute as isAbsolute5, join as join25, resolve as resolve11 } from "node:path";
33212
33399
 
33213
33400
  // server/sources/agent-hub/events/agy.ts
33214
33401
  function object(value) {
@@ -33359,19 +33546,19 @@ function adaptCopilotEvent(line2, offset) {
33359
33546
  }
33360
33547
 
33361
33548
  // server/sources/agent-hub/events/plain.ts
33362
- function adaptPlainChunk(text2, offset, at = Date.now()) {
33363
- if (!text2.trim()) return void 0;
33364
- return { id: `offset:${offset}`, at, ...SPECIAL.respond(text2) };
33549
+ function adaptPlainChunk(text3, offset, at = Date.now()) {
33550
+ if (!text3.trim()) return void 0;
33551
+ return { id: `offset:${offset}`, at, ...SPECIAL.respond(text3) };
33365
33552
  }
33366
- function adaptAgentHubEvent(agent, text2, offset) {
33367
- if (agent === "copilot") return adaptCopilotEvent(text2, offset);
33368
- if (agent === "agy") return adaptAgyEvent(text2, offset);
33369
- return adaptPlainChunk(text2, offset);
33553
+ function adaptAgentHubEvent(agent, text3, offset) {
33554
+ if (agent === "copilot") return adaptCopilotEvent(text3, offset);
33555
+ if (agent === "agy") return adaptAgyEvent(text3, offset);
33556
+ return adaptPlainChunk(text3, offset);
33370
33557
  }
33371
33558
 
33372
33559
  // server/sources/agent-hub/terminal.ts
33373
- import { lstatSync, readFileSync as readFileSync19 } from "node:fs";
33374
- import { join as join25 } from "node:path";
33560
+ import { lstatSync, readFileSync as readFileSync20 } from "node:fs";
33561
+ import { join as join24 } from "node:path";
33375
33562
  var SEEN_MAX5 = 2e4;
33376
33563
  var MAX_PROMPT_BYTES = 128 * 1024;
33377
33564
  var MAX_RESPONSE_BYTES = 128 * 1024;
@@ -33389,22 +33576,22 @@ function toMs7(v) {
33389
33576
  }
33390
33577
  function readPrompt(jobDir) {
33391
33578
  if (!jobDir) return void 0;
33392
- const path = join25(jobDir, "prompt.txt");
33579
+ const path = join24(jobDir, "prompt.txt");
33393
33580
  try {
33394
33581
  const st = lstatSync(path);
33395
33582
  if (!st.isFile() || st.size > MAX_PROMPT_BYTES) return void 0;
33396
- return readFileSync19(path, "utf8").trim() || void 0;
33583
+ return readFileSync20(path, "utf8").trim() || void 0;
33397
33584
  } catch {
33398
33585
  return void 0;
33399
33586
  }
33400
33587
  }
33401
33588
  function readResponse(jobDir) {
33402
33589
  if (!jobDir) return void 0;
33403
- const path = join25(jobDir, "response.txt");
33590
+ const path = join24(jobDir, "response.txt");
33404
33591
  try {
33405
33592
  const st = lstatSync(path);
33406
33593
  if (!st.isFile() || st.size > MAX_RESPONSE_BYTES) return void 0;
33407
- return readFileSync19(path, "utf8").trim() || void 0;
33594
+ return readFileSync20(path, "utf8").trim() || void 0;
33408
33595
  } catch {
33409
33596
  return void 0;
33410
33597
  }
@@ -33516,15 +33703,15 @@ var AgentHubTerminalParser = class {
33516
33703
  }
33517
33704
  if (type === "tool.execution_complete") {
33518
33705
  const callId = str15(data.toolCallId) ?? id;
33519
- let text2 = "";
33706
+ let text3 = "";
33520
33707
  const res = data.result;
33521
33708
  if (typeof res === "string") {
33522
- text2 = res;
33709
+ text3 = res;
33523
33710
  } else if (rec12(res)) {
33524
33711
  const r = res;
33525
- text2 = str15(r.content) ?? str15(r.output) ?? str15(r.text) ?? JSON.stringify(r);
33712
+ text3 = str15(r.content) ?? str15(r.output) ?? str15(r.text) ?? JSON.stringify(r);
33526
33713
  }
33527
- const p = prepare(text2, RESULT_MAX, RESULT_MAX_LINES);
33714
+ const p = prepare(text3, RESULT_MAX, RESULT_MAX_LINES);
33528
33715
  const entry = {
33529
33716
  kind: "result",
33530
33717
  id: `${callId}:r`,
@@ -33660,10 +33847,10 @@ var AgentHubTerminalParser = class {
33660
33847
  }
33661
33848
  }
33662
33849
  plain(raw) {
33663
- const text2 = raw.trim();
33664
- if (!text2) return;
33850
+ const text3 = raw.trim();
33851
+ if (!text3) return;
33665
33852
  const at = this.lastAt || this.now();
33666
- const p = prepare(text2, TEXT_MAX);
33853
+ const p = prepare(text3, TEXT_MAX);
33667
33854
  this.emit({
33668
33855
  kind: "assistant",
33669
33856
  id: `plain:${++this.seq}`,
@@ -33713,11 +33900,11 @@ function status(value) {
33713
33900
  return value === "queued" || value === "running" || value === "succeeded" || value === "failed" || value === "cancelled" ? value : "unknown";
33714
33901
  }
33715
33902
  function readPrompt2(jobDir) {
33716
- const path = join26(jobDir, "prompt.txt");
33903
+ const path = join25(jobDir, "prompt.txt");
33717
33904
  try {
33718
33905
  const st = lstatSync2(path);
33719
33906
  if (!st.isFile() || st.size > MAX_PROMPT_BYTES2) return void 0;
33720
- return str16(readFileSync20(path, "utf8"));
33907
+ return str16(readFileSync21(path, "utf8"));
33721
33908
  } catch {
33722
33909
  return void 0;
33723
33910
  }
@@ -33778,7 +33965,7 @@ function jobFiles(runsDir, now) {
33778
33965
  const files = [];
33779
33966
  for (const entry of entries) {
33780
33967
  if (!entry.isDirectory()) continue;
33781
- const path = join26(runsDir, entry.name, "result.json");
33968
+ const path = join25(runsDir, entry.name, "result.json");
33782
33969
  try {
33783
33970
  const file = jobFileOf(entry.name, path, lstatSync2(path), now);
33784
33971
  if (file) files.push(file);
@@ -33801,7 +33988,7 @@ async function jobFilesAsync(runsDir, now) {
33801
33988
  const files = [];
33802
33989
  for (let i = 0; i < dirs.length; i += JOB_STAT_BATCH) {
33803
33990
  const batch = await Promise.all(dirs.slice(i, i + JOB_STAT_BATCH).map(async (entry) => {
33804
- const path = join26(runsDir, entry.name, "result.json");
33991
+ const path = join25(runsDir, entry.name, "result.json");
33805
33992
  try {
33806
33993
  return jobFileOf(entry.name, path, await lstat(path), now);
33807
33994
  } catch {
@@ -33835,21 +34022,21 @@ function officeStatus(job) {
33835
34022
  }
33836
34023
  function deriveProject(cwd, repoRoot, repoName) {
33837
34024
  const candidate = repoRoot || cwd;
33838
- const gitPath = join26(candidate, ".git");
34025
+ const gitPath = join25(candidate, ".git");
33839
34026
  try {
33840
34027
  const st = lstatSync2(gitPath);
33841
34028
  if (st.isFile()) {
33842
- const content = readFileSync20(gitPath, "utf8");
34029
+ const content = readFileSync21(gitPath, "utf8");
33843
34030
  const match = /^gitdir:\s*(.+)$/m.exec(content);
33844
34031
  if (match) {
33845
34032
  let gitDir = match[1].trim();
33846
34033
  if (!isAbsolute5(gitDir)) {
33847
- gitDir = resolve12(candidate, gitDir);
34034
+ gitDir = resolve11(candidate, gitDir);
33848
34035
  }
33849
34036
  try {
33850
- const commonRel = readFileSync20(join26(gitDir, "commondir"), "utf8").trim();
33851
- const commonDir = resolve12(gitDir, commonRel);
33852
- return basename9(dirname12(commonDir));
34037
+ const commonRel = readFileSync21(join25(gitDir, "commondir"), "utf8").trim();
34038
+ const commonDir = resolve11(gitDir, commonRel);
34039
+ return basename9(dirname13(commonDir));
33853
34040
  } catch {
33854
34041
  const wtMatch = /^(.*)[/\\]\.git[/\\]worktrees[/\\][^/\\]+$/.exec(gitDir);
33855
34042
  if (wtMatch) {
@@ -33916,7 +34103,7 @@ var AgentHubSource = class {
33916
34103
  const tracker = this.trackers.get(agentId);
33917
34104
  const jobId = tracker ? tracker.job.id : agentId.startsWith("agent-hub:") ? agentId.slice("agent-hub:".length) : void 0;
33918
34105
  if (!jobId) return void 0;
33919
- const path = join26(this.opts.runsDir, jobId, "stdout.log");
34106
+ const path = join25(this.opts.runsDir, jobId, "stdout.log");
33920
34107
  try {
33921
34108
  if (lstatSync2(path).isFile()) return path;
33922
34109
  } catch {
@@ -33931,7 +34118,7 @@ var AgentHubSource = class {
33931
34118
  const tracker = this.trackers.get(agentId);
33932
34119
  const jobId = tracker ? tracker.job.id : agentId.startsWith("agent-hub:") ? agentId.slice("agent-hub:".length) : void 0;
33933
34120
  if (!jobId) return void 0;
33934
- const jobDir = join26(this.opts.runsDir, jobId);
34121
+ const jobDir = join25(this.opts.runsDir, jobId);
33935
34122
  return createAgentHubTerminalParser({
33936
34123
  agent: tracker?.job.agent,
33937
34124
  jobDir,
@@ -33956,8 +34143,8 @@ var AgentHubSource = class {
33956
34143
  const list = this.opts.listFilesAsync ?? jobFilesAsync;
33957
34144
  const files = await Promise.race([
33958
34145
  list(this.opts.runsDir, this.now()),
33959
- new Promise((resolve14) => {
33960
- timer = setTimeout(() => resolve14(void 0), limit);
34146
+ new Promise((resolve15) => {
34147
+ timer = setTimeout(() => resolve15(void 0), limit);
33961
34148
  timer.unref?.();
33962
34149
  })
33963
34150
  ]);
@@ -33980,7 +34167,7 @@ var AgentHubSource = class {
33980
34167
  if (!cached || cached.mtimeMs !== file.mtimeMs || cached.size !== file.size) {
33981
34168
  let job2;
33982
34169
  try {
33983
- job2 = parseJob(readFileSync20(file.path, "utf8"), file.name, file.mtimeMs, join26(this.opts.runsDir, file.name));
34170
+ job2 = parseJob(readFileSync21(file.path, "utf8"), file.name, file.mtimeMs, join25(this.opts.runsDir, file.name));
33984
34171
  } catch {
33985
34172
  job2 = void 0;
33986
34173
  }
@@ -34100,7 +34287,7 @@ var AgentHubSource = class {
34100
34287
  stats: { toolCalls: 0, tokensIn: 0, tokensOut: 0, subagents: 0 },
34101
34288
  model: job.model
34102
34289
  });
34103
- const jobDir = join26(this.opts.runsDir, job.id);
34290
+ const jobDir = join25(this.opts.runsDir, job.id);
34104
34291
  if (job.status === "running" && !tracker.started) {
34105
34292
  this.opts.office.addActivity(id, {
34106
34293
  id: `${id}#started`,
@@ -34112,9 +34299,9 @@ var AgentHubSource = class {
34112
34299
  }, true, { feed: !boot });
34113
34300
  tracker.started = true;
34114
34301
  }
34115
- this.readOutput(tracker, id, join26(jobDir, "stdout.log"), job.agent);
34302
+ this.readOutput(tracker, id, join25(jobDir, "stdout.log"), job.agent);
34116
34303
  if (terminal) {
34117
- this.readResponse(tracker, id, join26(jobDir, "response.txt"), job.updatedAt ?? this.now());
34304
+ this.readResponse(tracker, id, join25(jobDir, "response.txt"), job.updatedAt ?? this.now());
34118
34305
  const error = tracker.failure ?? job.error;
34119
34306
  this.opts.office.finishMain(id, mappedStatus, error ? truncate(maskSecrets(error), 300) : void 0);
34120
34307
  }
@@ -34184,9 +34371,9 @@ var AgentHubSource = class {
34184
34371
  if (activity) this.addOutputActivity(tracker, id, activity);
34185
34372
  }
34186
34373
  } else if (lines.length) {
34187
- const text2 = `${lines.map(({ line: line2 }) => line2).join("\n")}
34374
+ const text3 = `${lines.map(({ line: line2 }) => line2).join("\n")}
34188
34375
  `;
34189
- const activity = adaptPlainChunk(text2, lines[0].offset, this.now());
34376
+ const activity = adaptPlainChunk(text3, lines[0].offset, this.now());
34190
34377
  if (activity) this.addOutputActivity(tracker, id, activity);
34191
34378
  }
34192
34379
  } catch {
@@ -34223,8 +34410,531 @@ var AgentHubSource = class {
34223
34410
  }
34224
34411
  };
34225
34412
 
34413
+ // server/sources/gentle-shell/delegation.ts
34414
+ import { execFileSync } from "node:child_process";
34415
+ import { readdirSync as readdirSync16, readlinkSync } from "node:fs";
34416
+ import { basename as basename10, resolve as resolve12 } from "node:path";
34417
+ var START_BEFORE_MS2 = 1e4;
34418
+ var START_AFTER_MS2 = 6e4;
34419
+ var MAX_DEPTH = 32;
34420
+ var PID_ID2 = /:(\d+)$/;
34421
+ var AGENT_BIN = /^(claude|codex)(\.exe)?$/i;
34422
+ function knownAgentPids(agents2) {
34423
+ const out = /* @__PURE__ */ new Set();
34424
+ for (const a of agents2) {
34425
+ if (a.parentId || a.id.startsWith("@")) continue;
34426
+ const m = PID_ID2.exec(a.id);
34427
+ if (m) out.add(Number(m[1]));
34428
+ }
34429
+ return out;
34430
+ }
34431
+ function isGentleShell(args) {
34432
+ return args.slice(0, 2).some((a) => /^(gentle-shell|pi)(\.m?js)?$/.test(basename10(a)) || /[/\\]pi-coding-agent[/\\]/.test(a));
34433
+ }
34434
+ function printMode(args) {
34435
+ return args.some((a) => a === "-p" || a === "--print");
34436
+ }
34437
+ function classifyDelegation(cwd, startedAt2, known, table) {
34438
+ try {
34439
+ const want = resolve12(cwd);
34440
+ const cands = [];
34441
+ for (const pid of table.pids()) {
34442
+ const args = table.args(pid);
34443
+ if (!args || !isGentleShell(args)) continue;
34444
+ const pcwd = table.cwd(pid);
34445
+ if (pcwd && resolve12(pcwd) === want) cands.push(pid);
34446
+ }
34447
+ let use = cands;
34448
+ if (startedAt2 !== void 0) {
34449
+ const near = cands.filter((p) => {
34450
+ const s2 = table.startMs(p);
34451
+ return s2 !== void 0 && s2 >= startedAt2 - START_AFTER_MS2 && s2 <= startedAt2 + START_BEFORE_MS2;
34452
+ });
34453
+ if (near.length) use = near;
34454
+ }
34455
+ if (!use.length) return { delegated: false };
34456
+ const set = new Set(use);
34457
+ const ancestors = (pid) => {
34458
+ const out = [];
34459
+ let p = table.ppid(pid);
34460
+ for (let i = 0; p !== void 0 && p > 1 && i < MAX_DEPTH; i++) {
34461
+ out.push(p);
34462
+ p = table.ppid(p);
34463
+ }
34464
+ return out;
34465
+ };
34466
+ const agentAbove = (pid) => ancestors(pid).some((a) => known.has(a) || AGENT_BIN.test(basename10(table.args(a)?.[0] ?? "")));
34467
+ const roots = /* @__PURE__ */ new Map();
34468
+ for (const pid of use) {
34469
+ let root = pid;
34470
+ for (const a of ancestors(pid)) if (set.has(a)) root = a;
34471
+ const d = printMode(table.args(pid) ?? []) || agentAbove(pid);
34472
+ roots.set(root, (roots.get(root) ?? false) || d);
34473
+ }
34474
+ return { delegated: [...roots.values()].every(Boolean), pid: use[0] };
34475
+ } catch {
34476
+ return { delegated: false };
34477
+ }
34478
+ }
34479
+ var num11 = (s2) => /^\d+$/.test(s2) ? Number(s2) : void 0;
34480
+ function linuxProcTable(proc = realProc) {
34481
+ return {
34482
+ pids: () => {
34483
+ try {
34484
+ return readdirSync16("/proc").flatMap((n2) => num11(n2) !== void 0 ? [Number(n2)] : []);
34485
+ } catch {
34486
+ return [];
34487
+ }
34488
+ },
34489
+ args: (pid) => proc.cmdline(pid)?.split("\0").filter(Boolean),
34490
+ cwd: (pid) => {
34491
+ try {
34492
+ return readlinkSync(`/proc/${pid}/cwd`);
34493
+ } catch {
34494
+ return void 0;
34495
+ }
34496
+ },
34497
+ ppid: (pid) => {
34498
+ const stat3 = proc.stat(pid);
34499
+ if (!stat3) return void 0;
34500
+ return num11(stat3.slice(stat3.lastIndexOf(")") + 1).trim().split(/\s+/)[1] ?? "");
34501
+ },
34502
+ startMs: (pid) => processStartMs(pid, proc)
34503
+ };
34504
+ }
34505
+ function psProcTable(run3 = (c, a) => execFileSync(c, a, { encoding: "utf8", timeout: 1500, stdio: ["ignore", "pipe", "ignore"] })) {
34506
+ let rows2;
34507
+ const load = () => {
34508
+ if (rows2) return rows2;
34509
+ rows2 = /* @__PURE__ */ new Map();
34510
+ const now = Date.now();
34511
+ for (const line2 of run3("ps", ["-axo", "pid=,ppid=,etime=,command="]).split("\n")) {
34512
+ const m = /^\s*(\d+)\s+(\d+)\s+(?:(?:(\d+)-)?(?:(\d+):)?)(\d+):(\d+)\s+(.*)$/.exec(line2);
34513
+ if (!m) continue;
34514
+ const secs = Number(m[3] ?? 0) * 86400 + Number(m[4] ?? 0) * 3600 + Number(m[5]) * 60 + Number(m[6]);
34515
+ rows2.set(Number(m[1]), { ppid: Number(m[2]), startMs: now - secs * 1e3, args: m[7].split(/\s+/).filter(Boolean) });
34516
+ }
34517
+ return rows2;
34518
+ };
34519
+ const cwds = /* @__PURE__ */ new Map();
34520
+ return {
34521
+ pids: () => [...load().keys()],
34522
+ args: (pid) => load().get(pid)?.args,
34523
+ ppid: (pid) => load().get(pid)?.ppid,
34524
+ startMs: (pid) => load().get(pid)?.startMs,
34525
+ cwd: (pid) => {
34526
+ if (!cwds.has(pid)) {
34527
+ try {
34528
+ const out = run3("lsof", ["-a", "-d", "cwd", "-Fn", "-p", String(pid)]);
34529
+ cwds.set(pid, /^n(.+)$/m.exec(out)?.[1]);
34530
+ } catch {
34531
+ cwds.set(pid, void 0);
34532
+ }
34533
+ }
34534
+ return cwds.get(pid);
34535
+ }
34536
+ };
34537
+ }
34538
+ var EMPTY = { pids: () => [], args: () => void 0, cwd: () => void 0, ppid: () => void 0, startMs: () => void 0 };
34539
+ function defaultProcTable(platform = process.platform) {
34540
+ if (platform === "linux") return linuxProcTable();
34541
+ if (platform === "darwin") return psProcTable();
34542
+ return EMPTY;
34543
+ }
34544
+
34545
+ // server/sources/gentle-shell/source.ts
34546
+ var PRESENCE_STALE_MS = 3e4;
34547
+ var FALLBACK_RECENT_MS2 = 30 * 6e4;
34548
+ var WORKING_QUIET_MS2 = 30 * 6e4;
34549
+ var TASK_STALE_MS = 30 * 6e4;
34550
+ var CLOSE_AFTER_MISSING_MS3 = 1500;
34551
+ var BACKLOG_MAX2 = 400;
34552
+ var ACTIVE_TASK = /* @__PURE__ */ new Set(["queued", "running", "waiting", "pending", "starting", "in_progress"]);
34553
+ var MAIN_ROLE2 = tr("Agente principal (Gentle Shell)");
34554
+ var SUB_ROLE2 = tr("Subagente (Gentle Shell)");
34555
+ function roleOf2(raw) {
34556
+ const r = raw?.trim();
34557
+ return r ? `${r[0].toUpperCase()}${r.slice(1)}` : SUB_ROLE2;
34558
+ }
34559
+ var GentleShellSource = class {
34560
+ constructor(opts) {
34561
+ this.opts = opts;
34562
+ this.now = opts.now ?? Date.now;
34563
+ this.tailBytes = opts.tailBytes ?? 2 * 1024 * 1024;
34564
+ const others = opts.accounts.entries();
34565
+ this.detected = detectGentleShellAccounts(opts.dirs, {
34566
+ taken: { shorts: [...others, ...opts.accounts.entriesOf("codex")].map((e) => e.detected.short), colors: [...others, ...opts.accounts.entriesOf("codex")].map((e) => e.detected.color) }
34567
+ });
34568
+ this.entries = opts.accounts.setProviderAccounts(
34569
+ "gentle-shell",
34570
+ opts.dirs.map((dir, i) => ({ dir, detected: this.detected[i] }))
34571
+ );
34572
+ this.accs = this.entries.map((e) => ({ id: e.id, dir: e.dir, configDir: e.detected.configDir, index: new SessionIndex(e.dir, this.now), tasks: new TaskStore(e.dir), recent: /* @__PURE__ */ new Map(), recentAt: -Infinity }));
34573
+ }
34574
+ opts;
34575
+ provider = "gentle-shell";
34576
+ accs = [];
34577
+ entries = [];
34578
+ detected = [];
34579
+ trackers = /* @__PURE__ */ new Map();
34580
+ timer = null;
34581
+ now;
34582
+ tailBytes;
34583
+ procTable;
34584
+ /** Contas do Gentle Shell (ids finais, no AccountsService). */
34585
+ accountEntries() {
34586
+ return this.entries;
34587
+ }
34588
+ start() {
34589
+ this.boot();
34590
+ this.timer = setInterval(() => this.safePoll(), this.opts.pollMs ?? 1e3);
34591
+ this.timer.unref?.();
34592
+ }
34593
+ /** Reconstrói as sessões abertas sem gerar avisos. Síncrono e curto. */
34594
+ boot() {
34595
+ this.opts.office.beginBoot();
34596
+ try {
34597
+ this.poll(true);
34598
+ } finally {
34599
+ this.opts.office.endBoot();
34600
+ }
34601
+ }
34602
+ stop() {
34603
+ if (this.timer) clearInterval(this.timer);
34604
+ this.timer = null;
34605
+ }
34606
+ sources() {
34607
+ return this.accs.map((acc) => {
34608
+ let sessions = 0;
34609
+ for (const t of this.trackers.values()) if (t.acc === acc && t.kind === "main" && t.inOffice) sessions++;
34610
+ const info = { label: acc.id, provider: "gentle-shell", path: acc.configDir, sessions, ok: !acc.error };
34611
+ if (acc.error) info.error = acc.error;
34612
+ return info;
34613
+ });
34614
+ }
34615
+ transcriptPathOf(agentId) {
34616
+ const t = this.trackers.get(agentId);
34617
+ return t?.inOffice ? t.path : void 0;
34618
+ }
34619
+ terminalParser(agentId) {
34620
+ return this.trackers.has(agentId) ? createGentleShellTerminalParser() : void 0;
34621
+ }
34622
+ watchedTranscripts() {
34623
+ return this.trackers.size;
34624
+ }
34625
+ // ---------------------------------------------------------------- polling
34626
+ safePoll() {
34627
+ try {
34628
+ this.poll(false);
34629
+ } catch (err) {
34630
+ log.warnOnce(`gentle-shell-poll:${errMsg(err)}`, tr("Gentle Shell: falha no ciclo de leitura: {0}", [errMsg(err)]));
34631
+ }
34632
+ }
34633
+ poll(boot = false) {
34634
+ const now = this.now();
34635
+ const seen = /* @__PURE__ */ new Set();
34636
+ for (const acc of this.accs) {
34637
+ for (const [sessionId, workspace] of this.presentSessions(acc, now)) {
34638
+ const key = `${acc.id}:${sessionId}`;
34639
+ let t = this.trackers.get(key);
34640
+ if (!t) {
34641
+ t = this.newTracker(acc, key, "main", sessionId);
34642
+ this.trackers.set(key, t);
34643
+ }
34644
+ if (workspace) t.workspace = workspace;
34645
+ try {
34646
+ this.syncMain(t, now);
34647
+ } catch (err) {
34648
+ log.warnOnce(`gentle-shell-session:${key}:${errMsg(err)}`, tr("Gentle Shell: sess\xE3o {0}: {1}", [key, errMsg(err)]));
34649
+ }
34650
+ seen.add(key);
34651
+ }
34652
+ }
34653
+ for (const [key, t] of [...this.trackers]) {
34654
+ if (t.kind !== "main" || seen.has(key)) continue;
34655
+ t.missingSince ??= now;
34656
+ if (!boot && now - t.missingSince < CLOSE_AFTER_MISSING_MS3) continue;
34657
+ this.leaveMain(t);
34658
+ this.trackers.delete(key);
34659
+ }
34660
+ for (const acc of this.accs) {
34661
+ try {
34662
+ this.syncSubs(acc, now);
34663
+ } catch (err) {
34664
+ log.warnOnce(`gentle-shell-tasks:${acc.id}:${errMsg(err)}`, tr("Gentle Shell: falha ao ler os subagentes: {0}", [errMsg(err)]));
34665
+ }
34666
+ }
34667
+ }
34668
+ /** Sessões abertas de uma conta (id → projeto da presença, quando houver). */
34669
+ presentSessions(acc, now) {
34670
+ const out = /* @__PURE__ */ new Map();
34671
+ acc.index.refresh();
34672
+ const presence = readPresence(acc.dir);
34673
+ if (presence) {
34674
+ const fresh = presence.filter((p) => now - p.heartbeat <= PRESENCE_STALE_MS);
34675
+ const known = new Set(fresh.flatMap((p) => p.sessionId ? [p.sessionId] : []));
34676
+ for (const p of fresh) {
34677
+ const id = this.sessionOf(acc, p, known);
34678
+ if (id) {
34679
+ out.set(id, p.workspace);
34680
+ known.add(id);
34681
+ }
34682
+ }
34683
+ return out;
34684
+ }
34685
+ if (now - acc.recentAt >= 1e4) {
34686
+ acc.recentAt = now;
34687
+ acc.recent = new Map(acc.index.all().map((f) => [f.sessionId, f.mtimeMs]));
34688
+ }
34689
+ for (const [sessionId, mtime] of acc.recent) {
34690
+ const t = this.trackers.get(`${acc.id}:${sessionId}`);
34691
+ if (now - Math.max(mtime, t?.lastWriteAt ?? 0) <= FALLBACK_RECENT_MS2) out.set(sessionId, void 0);
34692
+ }
34693
+ return out;
34694
+ }
34695
+ /** Sessão de uma encarnação: a do discovery ou, sem ela, o transcript mais recente do projeto ainda sem dono. */
34696
+ sessionOf(acc, p, taken) {
34697
+ if (p.sessionId) return p.sessionId;
34698
+ if (!p.workspace) return void 0;
34699
+ return acc.index.latestFor(p.workspace, taken)?.sessionId;
34700
+ }
34701
+ newTracker(acc, key, kind, rawId) {
34702
+ return { key, acc, kind, rawId, state: createPiState(), backlog: [], inOffice: false, status: kind === "sub" ? "working" : "idle", statusAt: 0 };
34703
+ }
34704
+ // ---------------------------------------------------------------- principais
34705
+ syncMain(t, now) {
34706
+ delete t.missingSince;
34707
+ if (t.inOffice && !this.opts.office.has(t.key)) t.inOffice = false;
34708
+ if (!t.tail) {
34709
+ const file = t.acc.index.find(t.rawId);
34710
+ if (!file) return;
34711
+ this.load(t, file.path);
34712
+ } else {
34713
+ this.pump(t);
34714
+ }
34715
+ const cwd = t.state.cwd ?? t.workspace;
34716
+ if (cwd && !t.inOffice && t.tail) this.enter(t, cwd, now);
34717
+ if (t.inOffice) {
34718
+ this.quietCheck(t, now);
34719
+ this.opts.office.fillWorkingActivity(t.key);
34720
+ }
34721
+ }
34722
+ enter(t, cwd, now) {
34723
+ const office2 = this.opts.office;
34724
+ const delegated = this.delegatedOf(t, cwd);
34725
+ office2.addMain({
34726
+ id: t.key,
34727
+ provider: "gentle-shell",
34728
+ account: t.acc.id,
34729
+ sessionId: t.rawId,
34730
+ cwd,
34731
+ ...delegated ? { roomId: GENTLE_SHELL_ROOM_ID, project: deriveProject(cwd) } : {},
34732
+ role: MAIN_ROLE2,
34733
+ startedAt: t.state.startedAt ?? t.state.firstAt ?? now,
34734
+ status: t.status,
34735
+ waitingFor: t.waitingFor
34736
+ });
34737
+ t.inOffice = office2.has(t.key);
34738
+ if (!t.inOffice) return;
34739
+ office2.setStatus(t.key, t.status, t.waitingFor);
34740
+ this.flushBacklog(t);
34741
+ this.applySummary(t);
34742
+ }
34743
+ /** Veredito de sessão delegada: uma varredura de processos por sessão, guardada no tracker. */
34744
+ delegatedOf(t, cwd) {
34745
+ if (t.delegated !== void 0) return t.delegated;
34746
+ this.procTable ??= this.opts.procTable ?? defaultProcTable();
34747
+ const known = knownAgentPids(this.opts.office.list());
34748
+ for (const o of this.trackers.values()) if (o.pid !== void 0 && o.delegated !== void 0) known.add(o.pid);
34749
+ const r = classifyDelegation(cwd, t.state.startedAt ?? t.state.firstAt, known, this.procTable);
34750
+ t.delegated = r.delegated;
34751
+ t.pid = r.pid;
34752
+ return r.delegated;
34753
+ }
34754
+ leaveMain(t) {
34755
+ if (!t.inOffice) return;
34756
+ this.opts.office.closeMain(t.key);
34757
+ t.inOffice = false;
34758
+ }
34759
+ // ---------------------------------------------------------------- subagentes
34760
+ syncSubs(acc, now) {
34761
+ const tasks = acc.tasks.read();
34762
+ const active2 = /* @__PURE__ */ new Map();
34763
+ for (const task of tasks) {
34764
+ if (!ACTIVE_TASK.has(task.status)) continue;
34765
+ if (now - (task.lastAt ?? task.startedAt ?? 0) > TASK_STALE_MS) continue;
34766
+ active2.set(`${acc.id}:${task.id}`, task);
34767
+ }
34768
+ for (const [key, task] of active2) {
34769
+ const parent = this.trackers.get(`${acc.id}:${task.parentSessionId}`);
34770
+ if (!parent?.inOffice || this.opts.office.isSubDone(parent.key)) continue;
34771
+ let t = this.trackers.get(key);
34772
+ if (!t) {
34773
+ t = this.newTracker(acc, key, "sub", task.id);
34774
+ this.trackers.set(key, t);
34775
+ }
34776
+ t.task = task;
34777
+ this.syncSub(t, parent, now);
34778
+ }
34779
+ for (const [key, t] of [...this.trackers]) {
34780
+ if (t.kind !== "sub" || t.acc !== acc) continue;
34781
+ const parent = this.trackers.get(`${acc.id}:${t.task?.parentSessionId}`);
34782
+ if (active2.has(key) && parent?.inOffice) continue;
34783
+ if (t.inOffice) this.opts.office.completeSub(t.key);
34784
+ this.trackers.delete(key);
34785
+ }
34786
+ }
34787
+ syncSub(t, parent, now) {
34788
+ const task = t.task;
34789
+ const path = this.subPath(t.acc, task);
34790
+ if (path && path !== t.path) this.load(t, path);
34791
+ else if (t.tail) this.pump(t);
34792
+ if (!t.inOffice) {
34793
+ const added = this.opts.office.addSub({
34794
+ id: t.key,
34795
+ parentId: parent.key,
34796
+ sessionId: task.id,
34797
+ role: roleOf2(task.agent),
34798
+ title: task.label,
34799
+ background: task.mode === "background",
34800
+ startedAt: task.startedAt ?? t.state.firstAt ?? now
34801
+ });
34802
+ if (!added) return;
34803
+ t.inOffice = true;
34804
+ this.flushBacklog(t);
34805
+ }
34806
+ if (this.opts.office.isSubDone(t.key)) this.opts.office.reactivateSub(t.key);
34807
+ this.applySummary(t);
34808
+ }
34809
+ /** Transcript do subagente (só dentro das pastas de sessões do Gentle Shell). */
34810
+ subPath(acc, task) {
34811
+ if (!task.sessionPath) return void 0;
34812
+ const p = resolve13(task.sessionPath);
34813
+ const roots = [join26(resolve13(acc.dir), SUB_SESSIONS_DIR), join26(resolve13(acc.dir), SESSIONS_DIR2)];
34814
+ return p.endsWith(".jsonl") && roots.some((r) => p.startsWith(r + sep5)) ? p : void 0;
34815
+ }
34816
+ // ---------------------------------------------------------------- transcript
34817
+ /** Lê o começo (cwd, título, modelo) e a janela do fim do transcript. */
34818
+ load(t, path) {
34819
+ const head = parsePiHead(readHeadLines(path));
34820
+ const tail = new FileTail(path);
34821
+ tail.seekTail(this.tailBytes);
34822
+ t.tail = tail;
34823
+ t.path = path;
34824
+ t.state = createPiState();
34825
+ t.state.sessionId = head.sessionId;
34826
+ t.state.cwd = head.cwd;
34827
+ t.state.startedAt = head.startedAt;
34828
+ t.state.model = head.model;
34829
+ t.state.title = head.title;
34830
+ t.backlog = [];
34831
+ for (let i = 0; i < 64; i++) {
34832
+ const r = tail.read();
34833
+ for (const line2 of r.lines) this.apply(t, parsePiLine(t.state, line2, { idPrefix: t.key, now: this.now() }), false);
34834
+ if (!r.more) break;
34835
+ }
34836
+ t.lastWriteAt = tail.mtimeMs;
34837
+ if (t.inOffice) {
34838
+ this.flushBacklog(t);
34839
+ this.statusToOffice(t);
34840
+ }
34841
+ }
34842
+ pump(t) {
34843
+ const tail = t.tail;
34844
+ if (!tail) return;
34845
+ for (let i = 0; i < 4; i++) {
34846
+ let r;
34847
+ try {
34848
+ r = tail.read();
34849
+ } catch (err) {
34850
+ log.warnOnce(`gentle-shell-read:${t.key}`, tr("Gentle Shell: transcript de {0} ileg\xEDvel ({1}).", [t.key, errMsg(err)]));
34851
+ return;
34852
+ }
34853
+ if (r.missing) {
34854
+ delete t.tail;
34855
+ delete t.path;
34856
+ return;
34857
+ }
34858
+ t.lastWriteAt = tail.mtimeMs;
34859
+ if (r.reset) {
34860
+ this.load(t, tail.path);
34861
+ return;
34862
+ }
34863
+ for (const line2 of r.lines) this.apply(t, parsePiLine(t.state, line2, { idPrefix: t.key, now: this.now() }), true);
34864
+ if (r.lines.length) this.applySummary(t);
34865
+ if (!r.more) break;
34866
+ }
34867
+ }
34868
+ /** Aplica um resultado de linha: ao vivo vai direto ao escritório; na carga inicial, fica no backlog. */
34869
+ apply(t, r, live) {
34870
+ if (t.kind === "main") {
34871
+ for (const sig of r.signals) {
34872
+ switch (sig.type) {
34873
+ case "turnStart":
34874
+ this.decide(t, "working", r.at, void 0, live);
34875
+ break;
34876
+ case "turnEnd":
34877
+ this.decide(t, "idle", r.at, void 0, live);
34878
+ break;
34879
+ case "waiting":
34880
+ this.decide(t, "waiting", r.at, sig.reason, live);
34881
+ break;
34882
+ case "progress":
34883
+ if (t.status === "waiting") this.decide(t, "working", r.at, void 0, live);
34884
+ break;
34885
+ }
34886
+ }
34887
+ }
34888
+ if (!live || !t.inOffice) {
34889
+ if (r.activities.length) {
34890
+ t.backlog.push(r);
34891
+ if (t.backlog.length > BACKLOG_MAX2) t.backlog.splice(0, t.backlog.length - BACKLOG_MAX2);
34892
+ }
34893
+ return;
34894
+ }
34895
+ this.toOffice(t, r, true);
34896
+ }
34897
+ toOffice(t, r, live) {
34898
+ for (const a of r.activities) this.opts.office.addActivity(t.key, a.activity, a.current, { feed: live });
34899
+ }
34900
+ flushBacklog(t) {
34901
+ const backlog = t.backlog;
34902
+ t.backlog = [];
34903
+ for (const r of backlog) this.toOffice(t, r, false);
34904
+ }
34905
+ /** Muda o status por uma borda do transcript: informação mais velha que a última decisão não vale. */
34906
+ decide(t, status2, at, waitingFor, live) {
34907
+ if (at < t.statusAt) return;
34908
+ t.statusAt = at;
34909
+ t.status = status2;
34910
+ if (waitingFor) t.waitingFor = waitingFor;
34911
+ else delete t.waitingFor;
34912
+ if (live) this.statusToOffice(t);
34913
+ }
34914
+ statusToOffice(t) {
34915
+ if (t.inOffice && t.kind === "main") this.opts.office.setStatus(t.key, t.status, t.waitingFor);
34916
+ }
34917
+ /** 'working' sem nenhuma escrita por muito tempo (turno morto num crash): vira 'idle'. */
34918
+ quietCheck(t, now) {
34919
+ if (t.status !== "working") return;
34920
+ if (now - Math.max(t.lastWriteAt ?? 0, t.statusAt) > WORKING_QUIET_MS2) this.decide(t, "idle", now, void 0, true);
34921
+ }
34922
+ applySummary(t) {
34923
+ if (!t.inOffice) return;
34924
+ const s2 = t.state;
34925
+ const summary = { tasks: s2.tasks, stats: { ...s2.stats } };
34926
+ const title = t.kind === "sub" ? t.task?.label ?? s2.title : s2.title;
34927
+ if (title) summary.title = title;
34928
+ const model = s2.model ?? t.task?.model;
34929
+ if (model) summary.model = model;
34930
+ if (s2.firstAt !== void 0) summary.firstAt = s2.firstAt;
34931
+ if (s2.lastAt !== void 0) summary.lastAt = s2.lastAt;
34932
+ this.opts.office.applyTranscript(t.key, summary);
34933
+ }
34934
+ };
34935
+
34226
34936
  // server/build.ts
34227
- import { readFileSync as readFileSync21, statSync as statSync21 } from "node:fs";
34937
+ import { readFileSync as readFileSync22, statSync as statSync21 } from "node:fs";
34228
34938
  import { join as join27 } from "node:path";
34229
34939
  var BUNDLE = /bundle\/(main-[\w-]+)\.js/;
34230
34940
  function createBuildReader(rootDir) {
@@ -34236,7 +34946,7 @@ function createBuildReader(rootDir) {
34236
34946
  const m = statSync21(file).mtimeMs;
34237
34947
  if (m !== mtime) {
34238
34948
  mtime = m;
34239
- id = BUNDLE.exec(readFileSync21(file, "utf8"))?.[1];
34949
+ id = BUNDLE.exec(readFileSync22(file, "utf8"))?.[1];
34240
34950
  }
34241
34951
  } catch {
34242
34952
  mtime = -1;
@@ -34248,7 +34958,7 @@ function createBuildReader(rootDir) {
34248
34958
  var UNKNOWN = { commit: "unknown", dirty: false };
34249
34959
  function readBuildInfo(rootDir) {
34250
34960
  try {
34251
- const raw = JSON.parse(readFileSync21(join27(rootDir, "dist", "build.json"), "utf8"));
34961
+ const raw = JSON.parse(readFileSync22(join27(rootDir, "dist", "build.json"), "utf8"));
34252
34962
  if (typeof raw.commit !== "string" || !/^([0-9a-f]{40}([0-9a-f]{24})?|unknown)$/.test(raw.commit) || typeof raw.dirty !== "boolean") return { ...UNKNOWN };
34253
34963
  const stamp2 = { commit: raw.commit, dirty: raw.dirty };
34254
34964
  if (typeof raw.builtAt === "string" && raw.builtAt.length <= 40) stamp2.builtAt = raw.builtAt;
@@ -34259,8 +34969,8 @@ function readBuildInfo(rootDir) {
34259
34969
  }
34260
34970
 
34261
34971
  // server/updates/checker.ts
34262
- import { mkdirSync as mkdirSync13, readFileSync as readFileSync22, renameSync as renameSync12, writeFileSync as writeFileSync12 } from "node:fs";
34263
- import { dirname as dirname13 } from "node:path";
34972
+ import { mkdirSync as mkdirSync14, readFileSync as readFileSync23, renameSync as renameSync13, writeFileSync as writeFileSync13 } from "node:fs";
34973
+ import { dirname as dirname14 } from "node:path";
34264
34974
 
34265
34975
  // server/updates/npm.ts
34266
34976
  var NPM_PACKAGE = "busybits";
@@ -34372,7 +35082,7 @@ var UpdateChecker = class {
34372
35082
  const pkg = this.opts.package;
34373
35083
  if (!this.opts.file || !this.enabled || !pkg) return;
34374
35084
  try {
34375
- const j = JSON.parse(readFileSync22(this.opts.file, "utf8"));
35085
+ const j = JSON.parse(readFileSync23(this.opts.file, "utf8"));
34376
35086
  if (j.package !== pkg || typeof j.checkedAt !== "number" || !Number.isFinite(j.checkedAt)) return;
34377
35087
  const latest = typeof j.latest === "string" && parseVersion(j.latest) ? j.latest : void 0;
34378
35088
  this.cache = {
@@ -34458,11 +35168,11 @@ var UpdateChecker = class {
34458
35168
  const file = this.opts.file;
34459
35169
  if (!file || !this.cache) return;
34460
35170
  try {
34461
- mkdirSync13(dirname13(file), { recursive: true });
35171
+ mkdirSync14(dirname14(file), { recursive: true });
34462
35172
  const tmp = `${file}.tmp`;
34463
- writeFileSync12(tmp, `${JSON.stringify(this.cache, null, 2)}
35173
+ writeFileSync13(tmp, `${JSON.stringify(this.cache, null, 2)}
34464
35174
  `);
34465
- renameSync12(tmp, file);
35175
+ renameSync13(tmp, file);
34466
35176
  } catch (err) {
34467
35177
  log.warnOnce("updates:save", tr("N\xE3o deu para gravar {0}: {1}.", [file, errMsg(err)]));
34468
35178
  }
@@ -34488,12 +35198,12 @@ function describeError(err) {
34488
35198
  }
34489
35199
 
34490
35200
  // server/updates/apply.ts
34491
- import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync15 } from "node:fs";
34492
- import { dirname as dirname14, join as join29 } from "node:path";
35201
+ import { appendFileSync as appendFileSync2, mkdirSync as mkdirSync16 } from "node:fs";
35202
+ import { dirname as dirname15, join as join29 } from "node:path";
34493
35203
 
34494
35204
  // scripts/cli/layout.ts
34495
- import { cpSync, existsSync as existsSync11, mkdirSync as mkdirSync14, readdirSync as readdirSync16, readFileSync as readFileSync23, realpathSync as realpathSync6, renameSync as renameSync13, rmSync as rmSync6, statSync as statSync22, symlinkSync, writeFileSync as writeFileSync13 } from "node:fs";
34496
- import { isAbsolute as isAbsolute6, join as join28, relative as relative3, resolve as resolve13 } from "node:path";
35205
+ import { cpSync, existsSync as existsSync11, mkdirSync as mkdirSync15, readdirSync as readdirSync17, readFileSync as readFileSync24, realpathSync as realpathSync6, renameSync as renameSync14, rmSync as rmSync6, statSync as statSync22, symlinkSync, writeFileSync as writeFileSync14 } from "node:fs";
35206
+ import { isAbsolute as isAbsolute6, join as join28, relative as relative3, resolve as resolve14 } from "node:path";
34497
35207
  function layoutOf(dir) {
34498
35208
  return {
34499
35209
  dir,
@@ -34508,7 +35218,7 @@ function layoutOf(dir) {
34508
35218
  }
34509
35219
  function readLockPid(l) {
34510
35220
  try {
34511
- const n2 = Number.parseInt(readFileSync23(l.lockFile, "utf8").trim(), 10);
35221
+ const n2 = Number.parseInt(readFileSync24(l.lockFile, "utf8").trim(), 10);
34512
35222
  return Number.isInteger(n2) && n2 > 0 ? n2 : void 0;
34513
35223
  } catch {
34514
35224
  return void 0;
@@ -34535,14 +35245,14 @@ async function startUpdate(o) {
34535
35245
  if (lockHolder(o.layout, o.alive) !== void 0) return { status: 409, error: tr("j\xE1 est\xE1 rodando uma atualiza\xE7\xE3o") };
34536
35246
  const c = updateCommand({ bin: o.layout.bin, platform: o.platform, env: o.env, now: o.now });
34537
35247
  const child = o.spawn(c.cmd, c.args, { detached: c.detached, stdio: "ignore", env: o.env });
34538
- const failure = await new Promise((resolve14) => {
34539
- child.once?.("error", (err) => resolve14(err));
34540
- child.once?.("spawn", () => resolve14(void 0));
34541
- if (!child.once) resolve14(void 0);
35248
+ const failure = await new Promise((resolve15) => {
35249
+ child.once?.("error", (err) => resolve15(err));
35250
+ child.once?.("spawn", () => resolve15(void 0));
35251
+ if (!child.once) resolve15(void 0);
34542
35252
  });
34543
35253
  if (failure) {
34544
35254
  try {
34545
- mkdirSync15(dirname14(o.layout.logFile), { recursive: true });
35255
+ mkdirSync16(dirname15(o.layout.logFile), { recursive: true });
34546
35256
  appendFileSync2(o.layout.logFile, `[${new Date(o.now ?? Date.now()).toISOString()}] could not start the update: ${failure.message}
34547
35257
  `);
34548
35258
  } catch {
@@ -34856,9 +35566,9 @@ var CONTROL3 = /[\x00-\x1f\x7f]/g;
34856
35566
  function clean3(s2, max) {
34857
35567
  return s2.replace(ANSI2, "").replace(CONTROL3, "").trim().slice(0, max);
34858
35568
  }
34859
- function parseJson2(text2) {
35569
+ function parseJson2(text3) {
34860
35570
  try {
34861
- return JSON.parse(text2);
35571
+ return JSON.parse(text3);
34862
35572
  } catch {
34863
35573
  return void 0;
34864
35574
  }
@@ -34891,8 +35601,8 @@ function createHerdrExec(bin, env, timeoutMs = HERDR_TIMEOUT_MS) {
34891
35601
  if (json !== void 0 && !errorOf(json)) return ok({ ok: true, json });
34892
35602
  const e2 = errorOf(json);
34893
35603
  if (e2) return ok({ ok: false, ...e2 });
34894
- const text2 = firstLine4(out, stderr);
34895
- return ok(text2 ? { ok: false, error: text2 } : { ok: false, error: tr("herdr: sa\xEDda inv\xE1lida"), code: "empty_output" });
35604
+ const text3 = firstLine4(out, stderr);
35605
+ return ok(text3 ? { ok: false, error: text3 } : { ok: false, error: tr("herdr: sa\xEDda inv\xE1lida"), code: "empty_output" });
34896
35606
  }
34897
35607
  const e = errorOf(parseJson2(stderr ?? "")) ?? errorOf(parseJson2(out ?? ""));
34898
35608
  if (e) return ok({ ok: false, ...e });
@@ -35031,8 +35741,8 @@ var HerdrClient = class {
35031
35741
  await this.call(["agent", "wait", paneId, "--until", "idle", "--until", "done", "--timeout", String(ms)], ms + TIMEOUT_SLACK_MS);
35032
35742
  }
35033
35743
  /** O texto vai depois de `--`: um pedido que começa com `-` não vira opção do herdr. */
35034
- async prompt(paneId, text2) {
35035
- await this.call(["agent", "prompt", paneId, text2]);
35744
+ async prompt(paneId, text3) {
35745
+ await this.call(["agent", "prompt", paneId, text3]);
35036
35746
  }
35037
35747
  /** Foca o agente do painel; se o herdr recusar, ao menos a aba. */
35038
35748
  async focus(pane) {
@@ -35176,17 +35886,17 @@ async function launchInHerdr(client, req, opts = {}) {
35176
35886
  };
35177
35887
  const takenNames = () => client.agentNames().catch(() => /* @__PURE__ */ new Set());
35178
35888
  const deliverToGentle = async (r, known, at) => {
35179
- const inbox = opts.inbox;
35180
- if (!inbox) return tr("o escrit\xF3rio n\xE3o tem a caixa de entrada de mensagens ligada");
35889
+ const inbox2 = opts.inbox;
35890
+ if (!inbox2) return tr("o escrit\xF3rio n\xE3o tem a caixa de entrada de mensagens ligada");
35181
35891
  const until = Math.min(now() + (opts.inboxWaitMs ?? INBOX_WAIT_MS), end);
35182
35892
  let why = tr("n\xE3o achei a sess\xE3o do Gentle Shell no escrit\xF3rio (a extens\xE3o habblaud-pi est\xE1 instalada e a sess\xE3o aberta?)");
35183
35893
  let wait = pollMs;
35184
35894
  for (; ; ) {
35185
35895
  if (state.over) return late2;
35186
35896
  try {
35187
- const agent = matchGentle(inbox.agents(), known, r.folder, at);
35897
+ const agent = matchGentle(inbox2.agents(), known, r.folder, at);
35188
35898
  if (agent) {
35189
- const res = inbox.send(agent.id, r.prompt);
35899
+ const res = inbox2.send(agent.id, r.prompt);
35190
35900
  if (res.ok) return void 0;
35191
35901
  why = res.reason;
35192
35902
  if (!res.retry) return why;
@@ -35295,7 +36005,7 @@ function detectProviders(env, find = {}) {
35295
36005
  }
35296
36006
 
35297
36007
  // server/spawn/attachments-prune.ts
35298
- import { lstatSync as lstatSync3, readdirSync as readdirSync17, rmSync as rmSync7 } from "node:fs";
36008
+ import { lstatSync as lstatSync3, readdirSync as readdirSync18, rmSync as rmSync7 } from "node:fs";
35299
36009
  import { join as join31 } from "node:path";
35300
36010
  var ATTACHMENT_DIR_RE = /^\d{8}-\d{6}-[0-9a-f]+$/;
35301
36011
  var DAY_MS2 = 864e5;
@@ -35306,7 +36016,7 @@ function pruneAttachments(root, days, now = Date.now(), remove = (p) => rmSync7(
35306
36016
  const limit = now - days * DAY_MS2;
35307
36017
  let names2;
35308
36018
  try {
35309
- names2 = readdirSync17(root);
36019
+ names2 = readdirSync18(root);
35310
36020
  } catch {
35311
36021
  return out;
35312
36022
  }
@@ -35343,8 +36053,8 @@ function startAttachmentsPruner(opts) {
35343
36053
  }
35344
36054
 
35345
36055
  // server/settings/attachments.ts
35346
- import { mkdirSync as mkdirSync16, readFileSync as readFileSync24, renameSync as renameSync14, writeFileSync as writeFileSync14 } from "node:fs";
35347
- import { dirname as dirname15 } from "node:path";
36056
+ import { mkdirSync as mkdirSync17, readFileSync as readFileSync25, renameSync as renameSync15, writeFileSync as writeFileSync15 } from "node:fs";
36057
+ import { dirname as dirname16 } from "node:path";
35348
36058
  var RETENTION_CHOICES = [1, 3, 7, 30];
35349
36059
  var DEFAULT_RETENTION_DAYS = 7;
35350
36060
  function parseRetention(raw) {
@@ -35372,7 +36082,7 @@ var AttachmentSettingsStore = class {
35372
36082
  load() {
35373
36083
  if (!this.file) return null;
35374
36084
  try {
35375
- return parseRetention(JSON.parse(readFileSync24(this.file, "utf8")));
36085
+ return parseRetention(JSON.parse(readFileSync25(this.file, "utf8")));
35376
36086
  } catch (err) {
35377
36087
  if (err.code !== "ENOENT") log.warn(tr("attachments.json ileg\xEDvel ({0}); usando o padr\xE3o de {1} dias.", [errMsg(err), DEFAULT_RETENTION_DAYS]));
35378
36088
  return null;
@@ -35381,9 +36091,9 @@ var AttachmentSettingsStore = class {
35381
36091
  save() {
35382
36092
  if (!this.file) return;
35383
36093
  try {
35384
- mkdirSync16(dirname15(this.file), { recursive: true });
35385
- writeFileSync14(`${this.file}.tmp`, JSON.stringify({ version: 1, ...this.current }, null, 2));
35386
- renameSync14(`${this.file}.tmp`, this.file);
36094
+ mkdirSync17(dirname16(this.file), { recursive: true });
36095
+ writeFileSync15(`${this.file}.tmp`, JSON.stringify({ version: 1, ...this.current }, null, 2));
36096
+ renameSync15(`${this.file}.tmp`, this.file);
35387
36097
  } catch (err) {
35388
36098
  log.warn(tr("N\xE3o consegui gravar {0}: {1}", [this.file, errMsg(err)]));
35389
36099
  }
@@ -35444,7 +36154,7 @@ function recentFolders(sessions, rooms, limit = FOLDERS_LIMIT) {
35444
36154
 
35445
36155
  // server/dictation/whisper.ts
35446
36156
  import { execFile as execFile6 } from "node:child_process";
35447
- import { existsSync as existsSync12, mkdtempSync as mkdtempSync2, readFileSync as readFileSync25, rmSync as rmSync8, writeFileSync as writeFileSync15 } from "node:fs";
36157
+ import { existsSync as existsSync12, mkdtempSync as mkdtempSync2, readFileSync as readFileSync26, rmSync as rmSync8, writeFileSync as writeFileSync16 } from "node:fs";
35448
36158
  import { homedir as homedir7, tmpdir } from "node:os";
35449
36159
  import { delimiter as delimiter2, join as join32 } from "node:path";
35450
36160
  var TRANSCRIBE_TIMEOUT_MS = 12e4;
@@ -35481,8 +36191,8 @@ function run2(bin, args, timeoutMs) {
35481
36191
  }
35482
36192
  function parseWhisperJson(raw) {
35483
36193
  const d = JSON.parse(raw);
35484
- const text2 = (d.transcription ?? []).map((t) => typeof t.text === "string" ? t.text : "").join(" ").replace(/\[(BLANK_AUDIO|MUSIC|Música|SILENCE)\]|\((?:silence|música|music)\)/gi, "").replace(/\s+/g, " ").trim();
35485
- return { text: text2, lang: typeof d.result?.language === "string" ? d.result.language : "" };
36194
+ const text3 = (d.transcription ?? []).map((t) => typeof t.text === "string" ? t.text : "").join(" ").replace(/\[(BLANK_AUDIO|MUSIC|Música|SILENCE)\]|\((?:silence|música|music)\)/gi, "").replace(/\s+/g, " ").trim();
36195
+ return { text: text3, lang: typeof d.result?.language === "string" ? d.result.language : "" };
35486
36196
  }
35487
36197
  function createWhisperTranscriber(setup, timeoutMs = TRANSCRIBE_TIMEOUT_MS) {
35488
36198
  return async (audio) => {
@@ -35490,14 +36200,14 @@ function createWhisperTranscriber(setup, timeoutMs = TRANSCRIBE_TIMEOUT_MS) {
35490
36200
  try {
35491
36201
  const input = join32(dir, "audio.in");
35492
36202
  const wav = join32(dir, "audio.wav");
35493
- writeFileSync15(input, audio, { mode: 384 });
36203
+ writeFileSync16(input, audio, { mode: 384 });
35494
36204
  const conv = await run2(setup.ffmpeg, ["-nostdin", "-loglevel", "error", "-y", "-i", input, "-ar", "16000", "-ac", "1", "-c:a", "pcm_s16le", wav], timeoutMs);
35495
36205
  if (!conv.ok) throw new Error(tr("n\xE3o deu para ler o \xE1udio ({0})", [conv.error]));
35496
36206
  const pass = async (lang) => {
35497
36207
  const out = join32(dir, `out-${lang}`);
35498
36208
  const r = await run2(setup.bin, ["-m", setup.model, "-l", lang, "-f", wav, "-nt", "-np", "-oj", "-of", out], timeoutMs);
35499
36209
  if (!r.ok) throw new Error(tr("o Whisper falhou ({0})", [r.error]));
35500
- return parseWhisperJson(readFileSync25(`${out}.json`, "utf8"));
36210
+ return parseWhisperJson(readFileSync26(`${out}.json`, "utf8"));
35501
36211
  };
35502
36212
  const first = await pass("auto");
35503
36213
  if (!first.lang || setup.langs.includes(first.lang) || !first.text) return first;
@@ -35511,7 +36221,7 @@ function createWhisperTranscriber(setup, timeoutMs = TRANSCRIBE_TIMEOUT_MS) {
35511
36221
 
35512
36222
  // server/deliveries/fetcher.ts
35513
36223
  import { randomUUID as randomUUID4 } from "node:crypto";
35514
- import { readFileSync as readFileSync26 } from "node:fs";
36224
+ import { readFileSync as readFileSync27 } from "node:fs";
35515
36225
  var HOST_PRESENCE_MS3 = 1e4;
35516
36226
  var WAIT_MS = 2e4;
35517
36227
  var CACHE_MAX_BYTES = 80 * 1024 * 1024;
@@ -35594,7 +36304,7 @@ var FileFetcher = class {
35594
36304
  const c = (this.opts.check ?? checkFile)(path);
35595
36305
  if ("error" in c) return { error: c.error, status: c.error === tr("arquivo n\xE3o encontrado") ? 404 : 403 };
35596
36306
  try {
35597
- const data = (this.opts.read ?? readFileSync26)(c.path);
36307
+ const data = (this.opts.read ?? readFileSync27)(c.path);
35598
36308
  this.remember(path, data);
35599
36309
  return { data };
35600
36310
  } catch {
@@ -35952,7 +36662,7 @@ function worldLastError(code2) {
35952
36662
  var RESYNC_GAP_MS = 5e3;
35953
36663
  var MAX_SCENE_PLAYERS = 200;
35954
36664
  var COORD_MAX = 1e6;
35955
- var isObj4 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
36665
+ var isObj5 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
35956
36666
  var isNum = (v) => typeof v === "number" && Number.isFinite(v);
35957
36667
  var DIRS = ["n", "s", "e", "w"];
35958
36668
  var isDir5 = (v) => typeof v === "string" && DIRS.includes(v);
@@ -35960,20 +36670,20 @@ var isId = (v) => typeof v === "string" && /^[\x21-\x7e]{1,64}$/.test(v);
35960
36670
  var isCount = (v) => isNum(v) && Number.isInteger(v) && v >= 0 && v <= 1e9;
35961
36671
  var CODE_TYPED = /^[A-Za-z0-9 _-]{1,16}$/;
35962
36672
  function parseCityStatus(v) {
35963
- if (!isObj4(v) || !isCount(v.lit)) return void 0;
36673
+ if (!isObj5(v) || !isCount(v.lit)) return void 0;
35964
36674
  const out = { lit: v.lit };
35965
36675
  const g = v.goal;
35966
- if (isObj4(g) && typeof g.id === "string" && g.id.length <= 64 && CITY_GOAL_IDS.includes(g.label) && isNum(g.target) && g.target > 0 && isNum(g.progress) && g.progress >= 0 && isNum(g.until)) {
36676
+ if (isObj5(g) && typeof g.id === "string" && g.id.length <= 64 && CITY_GOAL_IDS.includes(g.label) && isNum(g.target) && g.target > 0 && isNum(g.progress) && g.progress >= 0 && isNum(g.until)) {
35967
36677
  out.goal = { id: g.id, label: g.label, target: g.target, progress: g.progress, until: g.until };
35968
36678
  }
35969
36679
  if (isNum(v.tokensBand) && Number.isInteger(v.tokensBand) && v.tokensBand >= 0 && v.tokensBand <= 5) out.tokensBand = v.tokensBand;
35970
36680
  return out;
35971
36681
  }
35972
36682
  function parseAwaySummary(v) {
35973
- if (!isObj4(v) || typeof v.since !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v.since) || !isCount(v.visits) || !isCount(v.likes)) return void 0;
36683
+ if (!isObj5(v) || typeof v.since !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(v.since) || !isCount(v.visits) || !isCount(v.likes)) return void 0;
35974
36684
  const stamps = [];
35975
36685
  for (const st of Array.isArray(v.stamps) ? v.stamps : []) {
35976
- if (!isObj4(st) || !STAMP_IDS.includes(st.stampId) || !isCount(st.count) || st.count === 0) continue;
36686
+ if (!isObj5(st) || !STAMP_IDS.includes(st.stampId) || !isCount(st.count) || st.count === 0) continue;
35977
36687
  if (stamps.some((x) => x.stampId === st.stampId)) continue;
35978
36688
  stamps.push({ stampId: st.stampId, count: st.count });
35979
36689
  }
@@ -35983,11 +36693,11 @@ function summaryHasNews(s2) {
35983
36693
  return !!s2 && (s2.visits > 0 || s2.likes > 0 || s2.stamps.some((x) => x.count > 0));
35984
36694
  }
35985
36695
  function position(v) {
35986
- if (!isObj4(v) || !isNum(v.x) || !isNum(v.y)) return void 0;
36696
+ if (!isObj5(v) || !isNum(v.x) || !isNum(v.y)) return void 0;
35987
36697
  return { x: v.x, y: v.y, dir: isDir5(v.dir) ? v.dir : "s", moving: v.moving === true };
35988
36698
  }
35989
36699
  function parseSceneCommand(v) {
35990
- if (!isObj4(v) || typeof v.t !== "string" || !WORLD_SCENE_COMMANDS.includes(v.t)) return null;
36700
+ if (!isObj5(v) || typeof v.t !== "string" || !WORLD_SCENE_COMMANDS.includes(v.t)) return null;
35991
36701
  switch (v.t) {
35992
36702
  case "move": {
35993
36703
  if (!isNum(v.x) || !isNum(v.y) || Math.abs(v.x) > COORD_MAX || Math.abs(v.y) > COORD_MAX) return null;
@@ -36045,18 +36755,18 @@ function reduceSceneBatch(cmds) {
36045
36755
  }
36046
36756
  function sceneMeFrom(welcome) {
36047
36757
  const me = welcome.me;
36048
- if (!isObj4(me) || !isId(me.id) || typeof me.name !== "string" || me.look !== "f" && me.look !== "m") return void 0;
36758
+ if (!isObj5(me) || !isId(me.id) || typeof me.name !== "string" || me.look !== "f" && me.look !== "m") return void 0;
36049
36759
  const out = {
36050
36760
  id: me.id,
36051
36761
  name: me.name,
36052
36762
  look: me.look,
36053
- parts: isObj4(me.parts) ? me.parts : {},
36763
+ parts: isObj5(me.parts) ? me.parts : {},
36054
36764
  traits: Array.isArray(me.traits) ? me.traits.filter((t) => typeof t === "string") : []
36055
36765
  };
36056
36766
  if (typeof me.intro === "string") out.intro = me.intro;
36057
36767
  if (typeof me.country === "string") out.country = me.country;
36058
36768
  const b = welcome.building;
36059
- if (isObj4(b) && isId(b.id)) out.buildingId = b.id;
36769
+ if (isObj5(b) && isId(b.id)) out.buildingId = b.id;
36060
36770
  return out;
36061
36771
  }
36062
36772
  var SceneState = class _SceneState {
@@ -36104,7 +36814,7 @@ var SceneState = class _SceneState {
36104
36814
  this.likesToday = void 0;
36105
36815
  this.summary = void 0;
36106
36816
  this.me = sceneMeFrom(msg);
36107
- const city = isObj4(msg.city) ? msg.city : void 0;
36817
+ const city = isObj5(msg.city) ? msg.city : void 0;
36108
36818
  const d = Array.isArray(city?.districts) ? city.districts[0] : void 0;
36109
36819
  this.district = typeof d === "string" ? d : void 0;
36110
36820
  }
@@ -36150,7 +36860,7 @@ var SceneState = class _SceneState {
36150
36860
  case "players": {
36151
36861
  if (!Array.isArray(msg.players)) return { forward: false };
36152
36862
  for (const e of msg.players) {
36153
- if (!isObj4(e) || !isId(e.id)) continue;
36863
+ if (!isObj5(e) || !isId(e.id)) continue;
36154
36864
  const pos = position(e.pos);
36155
36865
  if (!pos) continue;
36156
36866
  if (e.id === this.me?.id) {
@@ -36160,7 +36870,7 @@ var SceneState = class _SceneState {
36160
36870
  const p = this.players.get(e.id);
36161
36871
  if (!p) continue;
36162
36872
  p.pos = pos;
36163
- if (isObj4(e.greeting) && typeof e.greeting.id === "string" && isNum(e.greeting.until)) {
36873
+ if (isObj5(e.greeting) && typeof e.greeting.id === "string" && isNum(e.greeting.until)) {
36164
36874
  p.greeting = { id: e.greeting.id, until: e.greeting.until };
36165
36875
  }
36166
36876
  }
@@ -36168,7 +36878,7 @@ var SceneState = class _SceneState {
36168
36878
  }
36169
36879
  case "player.join": {
36170
36880
  const p = msg.player;
36171
- if (!isObj4(p) || !isId(p.id) || !position(p.pos) || p.id === this.me?.id) return { forward: false };
36881
+ if (!isObj5(p) || !isId(p.id) || !position(p.pos) || p.id === this.me?.id) return { forward: false };
36172
36882
  if (!this.players.has(p.id) && this.players.size >= MAX_SCENE_PLAYERS) return { forward: false };
36173
36883
  this.players.set(p.id, structuredClone(p));
36174
36884
  return { forward: true };
@@ -36186,7 +36896,7 @@ var SceneState = class _SceneState {
36186
36896
  }
36187
36897
  case "minimap": {
36188
36898
  if (!Array.isArray(msg.blocks)) return { forward: false };
36189
- this.minimap = msg.blocks.filter((b) => isObj4(b) && isNum(b.x) && isNum(b.y) && isNum(b.lit)).map((b) => ({ x: b.x, y: b.y, lit: b.lit }));
36899
+ this.minimap = msg.blocks.filter((b) => isObj5(b) && isNum(b.x) && isNum(b.y) && isNum(b.lit)).map((b) => ({ x: b.x, y: b.y, lit: b.lit }));
36190
36900
  return { forward: true };
36191
36901
  }
36192
36902
  case "afk":
@@ -36209,7 +36919,7 @@ var SceneState = class _SceneState {
36209
36919
  }
36210
36920
  case "profile": {
36211
36921
  const p = msg.player;
36212
- if (!isObj4(p) || !isId(p.id)) return { forward: false };
36922
+ if (!isObj5(p) || !isId(p.id)) return { forward: false };
36213
36923
  if (this.players.has(p.id) && position(p.pos)) this.players.set(p.id, structuredClone(p));
36214
36924
  return { forward: true };
36215
36925
  }
@@ -36283,7 +36993,7 @@ var SceneState = class _SceneState {
36283
36993
  area(msg) {
36284
36994
  if (!isId(msg.chunk) || !isNum(msg.rev) || !Array.isArray(msg.buildings)) return { forward: false };
36285
36995
  const buildings = /* @__PURE__ */ new Map();
36286
- for (const b of msg.buildings) if (isObj4(b) && isId(b.id)) buildings.set(b.id, structuredClone(b));
36996
+ for (const b of msg.buildings) if (isObj5(b) && isId(b.id)) buildings.set(b.id, structuredClone(b));
36287
36997
  this.chunks.set(msg.chunk, { rev: msg.rev, buildings });
36288
36998
  this.resyncAt.delete(msg.chunk);
36289
36999
  return { forward: true };
@@ -36296,7 +37006,7 @@ var SceneState = class _SceneState {
36296
37006
  if (!c) return this.gap(msg.chunk);
36297
37007
  if (msg.rev <= c.rev) return { forward: false };
36298
37008
  if (msg.rev !== c.rev + 1) return this.gap(msg.chunk);
36299
- const changes = msg.changes.filter((x) => isObj4(x) && isId(x.id));
37009
+ const changes = msg.changes.filter((x) => isObj5(x) && isId(x.id));
36300
37010
  if (changes.some((x) => x.lot === void 0 && !c.buildings.has(x.id))) return this.gap(msg.chunk);
36301
37011
  for (const x of changes) {
36302
37012
  const id = x.id;
@@ -36311,7 +37021,7 @@ var SceneState = class _SceneState {
36311
37021
  /** `building`: o interior inteiro, que substitui tudo (mesmo com `rev` menor). Daqui em diante estou dentro. */
36312
37022
  enterBuilding(msg) {
36313
37023
  const d = msg.detail;
36314
- if (!isNum(msg.rev) || !isObj4(d) || !isObj4(d.building) || !isId(d.building.id) || !Array.isArray(d.floors)) return { forward: false };
37024
+ if (!isNum(msg.rev) || !isObj5(d) || !isObj5(d.building) || !isId(d.building.id) || !Array.isArray(d.floors)) return { forward: false };
36315
37025
  this.inside = { id: d.building.id, rev: msg.rev, detail: structuredClone(d) };
36316
37026
  this.buildingResyncAt = void 0;
36317
37027
  return { forward: true };
@@ -36329,7 +37039,7 @@ var SceneState = class _SceneState {
36329
37039
  return { forward: false, resyncBuilding: inside.id };
36330
37040
  }
36331
37041
  if (msg.floors !== void 0 && !Array.isArray(msg.floors)) return { forward: false };
36332
- if (msg.building !== void 0 && (!isObj4(msg.building) || msg.building.id !== inside.id)) return { forward: false };
37042
+ if (msg.building !== void 0 && (!isObj5(msg.building) || msg.building.id !== inside.id)) return { forward: false };
36333
37043
  if (msg.visitors !== void 0 && !isNum(msg.visitors)) return { forward: false };
36334
37044
  const detail = inside.detail;
36335
37045
  if (msg.floors) detail.floors = structuredClone(msg.floors);
@@ -36375,7 +37085,7 @@ var SceneState = class _SceneState {
36375
37085
  var SUMMARY_SEEN_GRACE_MS = 2e4;
36376
37086
  var UNBLOCK_GRACE_MS = 6e4;
36377
37087
  var MAX_BLOCKED = 500;
36378
- var isObj5 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
37088
+ var isObj6 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
36379
37089
  var count = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 1e9 ? v : void 0;
36380
37090
  var ID_RE = /^[\x21-\x7e]{1,64}$/;
36381
37091
  var CODE_RE = /^HB-[2-9A-HJKMNP-TV-Z]{4}$/;
@@ -36391,10 +37101,10 @@ function summaryWithin(b, a) {
36391
37101
  return b.stamps.every((x) => x.count <= (a.stamps.find((y) => y.stampId === x.stampId)?.count ?? 0));
36392
37102
  }
36393
37103
  function parseMeBuilding(raw) {
36394
- if (!isObj5(raw) || !STATES.includes(raw.state)) return void 0;
37104
+ if (!isObj6(raw) || !STATES.includes(raw.state)) return void 0;
36395
37105
  const lot = raw.lot;
36396
- if (!isObj5(lot) || typeof lot.district !== "string" || lot.district.length > 32 || !Number.isInteger(lot.x) || !Number.isInteger(lot.y)) return void 0;
36397
- const a = isObj5(raw.agents) ? raw.agents : {};
37106
+ if (!isObj6(lot) || typeof lot.district !== "string" || lot.district.length > 32 || !Number.isInteger(lot.x) || !Number.isInteger(lot.y)) return void 0;
37107
+ const a = isObj6(raw.agents) ? raw.agents : {};
36398
37108
  const b = {
36399
37109
  state: raw.state,
36400
37110
  paused: raw.paused === true,
@@ -36404,7 +37114,7 @@ function parseMeBuilding(raw) {
36404
37114
  likes: count(raw.likes) ?? 0,
36405
37115
  firstOnlineMonth: typeof raw.firstOnlineMonth === "string" && /^\d{4}-\d{2}$/.test(raw.firstOnlineMonth) ? raw.firstOnlineMonth : ""
36406
37116
  };
36407
- if (isObj5(raw.tokens)) {
37117
+ if (isObj6(raw.tokens)) {
36408
37118
  const day = band(raw.tokens.day);
36409
37119
  const week = band(raw.tokens.week);
36410
37120
  if (day !== void 0 && week !== void 0) b.tokens = { day, week };
@@ -36421,7 +37131,7 @@ function parseBlocked(raw) {
36421
37131
  const out = [];
36422
37132
  for (const x of raw) {
36423
37133
  if (out.length >= MAX_BLOCKED) break;
36424
- if (!isObj5(x) || typeof x.id !== "string" || !ID_RE.test(x.id) || typeof x.name !== "string" || x.name.length > 64) continue;
37134
+ if (!isObj6(x) || typeof x.id !== "string" || !ID_RE.test(x.id) || typeof x.name !== "string" || x.name.length > 64) continue;
36425
37135
  if (!out.some((y) => y.id === x.id)) out.push({ id: x.id, name: x.name });
36426
37136
  }
36427
37137
  return out;
@@ -36580,7 +37290,7 @@ async function body(req, res) {
36580
37290
  sendError(res, status2, code2, err.message);
36581
37291
  return null;
36582
37292
  }
36583
- if (!isObj5(raw)) {
37293
+ if (!isObj6(raw)) {
36584
37294
  sendError(res, 400, "invalid", tr("esperado um objeto JSON"));
36585
37295
  return null;
36586
37296
  }
@@ -36616,8 +37326,8 @@ function socialRoutes(social) {
36616
37326
  }
36617
37327
 
36618
37328
  // server/world/settings.ts
36619
- import { chmodSync as chmodSync7, mkdirSync as mkdirSync17, readFileSync as readFileSync27, renameSync as renameSync15, rmSync as rmSync9, statSync as statSync24, writeFileSync as writeFileSync16 } from "node:fs";
36620
- import { dirname as dirname16 } from "node:path";
37329
+ import { chmodSync as chmodSync7, mkdirSync as mkdirSync18, readFileSync as readFileSync28, renameSync as renameSync16, rmSync as rmSync9, statSync as statSync24, writeFileSync as writeFileSync17 } from "node:fs";
37330
+ import { dirname as dirname17 } from "node:path";
36621
37331
  var DEVICE_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
36622
37332
  var TOKEN_RE = /^[A-Za-z0-9_-]{16,256}$/;
36623
37333
  var MAX_FILE = 64 * 1024;
@@ -36663,7 +37373,7 @@ var WorldSettingsStore = class {
36663
37373
  const st = statSync24(this.file);
36664
37374
  if (st.size > MAX_FILE) throw new Error("too large");
36665
37375
  if ((st.mode & 63) !== 0) chmodSync7(this.file, 384);
36666
- const raw = JSON.parse(readFileSync27(this.file, "utf8"));
37376
+ const raw = JSON.parse(readFileSync28(this.file, "utf8"));
36667
37377
  const obj4 = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
36668
37378
  if (isWorldThemeChoice(obj4.theme)) this.theme = obj4.theme;
36669
37379
  this.session = parseWorldSession(raw);
@@ -36726,10 +37436,10 @@ var WorldSettingsStore = class {
36726
37436
  }
36727
37437
  const tmp = `${this.file}.${process.pid}.tmp`;
36728
37438
  try {
36729
- mkdirSync17(dirname16(this.file), { recursive: true });
36730
- writeFileSync16(tmp, JSON.stringify(data), { mode: 384 });
37439
+ mkdirSync18(dirname17(this.file), { recursive: true });
37440
+ writeFileSync17(tmp, JSON.stringify(data), { mode: 384 });
36731
37441
  chmodSync7(tmp, 384);
36732
- renameSync15(tmp, this.file);
37442
+ renameSync16(tmp, this.file);
36733
37443
  log.clearOnce("world-write");
36734
37444
  return true;
36735
37445
  } catch (err) {
@@ -36938,7 +37648,7 @@ var WorldClient = class {
36938
37648
  const signal = o.signal ? AbortSignal.any([timeout, o.signal]) : timeout;
36939
37649
  const fail3 = (status2, code3, retryAfter) => retryAfter === void 0 ? { ok: false, status: status2, code: code3 } : { ok: false, status: status2, code: code3, retryAfter };
36940
37650
  let res;
36941
- let text2;
37651
+ let text3;
36942
37652
  try {
36943
37653
  res = await this.fetchImpl(`${this.base}${path}`, { method, headers, body: body2, redirect: "manual", signal });
36944
37654
  const length = Number(res.headers.get("content-length") ?? "0");
@@ -36946,16 +37656,16 @@ var WorldClient = class {
36946
37656
  await res.body?.cancel().catch(() => void 0);
36947
37657
  return fail3(502, CLIENT_ERROR.badResponse);
36948
37658
  }
36949
- text2 = await res.text();
37659
+ text3 = await res.text();
36950
37660
  } catch (err) {
36951
37661
  o.signal?.throwIfAborted();
36952
37662
  return err?.name === "TimeoutError" || timeout.aborted ? fail3(504, CLIENT_ERROR.timeout) : fail3(502, CLIENT_ERROR.unreachable);
36953
37663
  }
36954
- if (text2.length > max) return fail3(502, CLIENT_ERROR.badResponse);
37664
+ if (text3.length > max) return fail3(502, CLIENT_ERROR.badResponse);
36955
37665
  let raw;
36956
- if (text2.trim()) {
37666
+ if (text3.trim()) {
36957
37667
  try {
36958
- raw = JSON.parse(text2);
37668
+ raw = JSON.parse(text3);
36959
37669
  } catch {
36960
37670
  raw = void 0;
36961
37671
  if (res.ok) return fail3(502, CLIENT_ERROR.badResponse);
@@ -37392,8 +38102,8 @@ function createWorldRoutes(service, viewer, social) {
37392
38102
  }
37393
38103
 
37394
38104
  // server/world/uplink.ts
37395
- import { chmodSync as chmodSync8, mkdirSync as mkdirSync18, readFileSync as readFileSync28, renameSync as renameSync16, rmSync as rmSync10, writeFileSync as writeFileSync17 } from "node:fs";
37396
- import { dirname as dirname17 } from "node:path";
38105
+ import { chmodSync as chmodSync8, mkdirSync as mkdirSync19, readFileSync as readFileSync29, renameSync as renameSync17, rmSync as rmSync10, writeFileSync as writeFileSync18 } from "node:fs";
38106
+ import { dirname as dirname18 } from "node:path";
37397
38107
 
37398
38108
  // shared/world/appearance-flat.ts
37399
38109
  var SKINS = ["#ffe2cc", "#f6cfb0", "#eab894", "#d69f78", "#bd8560", "#9a6444", "#7a4a31", "#5a3623"];
@@ -37760,7 +38470,7 @@ function toWorldAgent(c, widOf, name, input) {
37760
38470
  }
37761
38471
 
37762
38472
  // server/world/ids.ts
37763
- import { randomBytes as randomBytes10, randomInt } from "node:crypto";
38473
+ import { randomBytes as randomBytes11, randomInt } from "node:crypto";
37764
38474
  var ID_LIFETIME_MS = 24 * 36e5;
37765
38475
  var ID_JITTER_MS = 6 * 36e5;
37766
38476
  var toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
@@ -37772,7 +38482,7 @@ var WorldIds = class {
37772
38482
  bytes;
37773
38483
  jitter;
37774
38484
  constructor(opts = {}) {
37775
- this.bytes = opts.randomBytes ?? ((n2) => randomBytes10(n2));
38485
+ this.bytes = opts.randomBytes ?? ((n2) => randomBytes11(n2));
37776
38486
  this.jitter = opts.jitter ?? (() => randomInt(-ID_JITTER_MS, ID_JITTER_MS + 1));
37777
38487
  }
37778
38488
  floorId(roomId, now) {
@@ -38454,7 +39164,7 @@ var BuildingUplink = class {
38454
39164
  this.deviceId = s2?.deviceId;
38455
39165
  if (!file) return;
38456
39166
  try {
38457
- const raw = JSON.parse(readFileSync28(file, "utf8"));
39167
+ const raw = JSON.parse(readFileSync29(file, "utf8"));
38458
39168
  const ok = raw && typeof raw === "object" && typeof raw.deviceId === "string" && typeof raw.at === "number" && typeof raw.bytes === "number" && raw.uplink && typeof raw.uplink === "object" && Array.isArray(raw.uplink.floors);
38459
39169
  if (!ok || raw.deviceId !== s2?.deviceId) return this.removeLast();
38460
39170
  this.last = raw;
@@ -38466,10 +39176,10 @@ var BuildingUplink = class {
38466
39176
  if (!file || !this.last) return;
38467
39177
  const tmp = `${file}.${process.pid}.tmp`;
38468
39178
  try {
38469
- mkdirSync18(dirname17(file), { recursive: true });
38470
- writeFileSync17(tmp, JSON.stringify(this.last), { mode: 384 });
39179
+ mkdirSync19(dirname18(file), { recursive: true });
39180
+ writeFileSync18(tmp, JSON.stringify(this.last), { mode: 384 });
38471
39181
  chmodSync8(tmp, 384);
38472
- renameSync16(tmp, file);
39182
+ renameSync17(tmp, file);
38473
39183
  } catch (err) {
38474
39184
  try {
38475
39185
  rmSync10(tmp, { force: true });
@@ -39127,8 +39837,8 @@ var BuildingTokens = class {
39127
39837
  };
39128
39838
 
39129
39839
  // server/world/viewer.ts
39130
- import { randomBytes as randomBytes11 } from "node:crypto";
39131
- var isObj6 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
39840
+ import { randomBytes as randomBytes12 } from "node:crypto";
39841
+ var isObj7 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
39132
39842
  var WorldViewer = class {
39133
39843
  link;
39134
39844
  now;
@@ -39147,7 +39857,7 @@ var WorldViewer = class {
39147
39857
  this.state = new SceneState(this.now);
39148
39858
  this.pingMs = o.pingMs ?? 15e3;
39149
39859
  this.maxBuffered = o.maxBuffered ?? 1024 * 1024;
39150
- this.newId = o.streamId ?? (() => randomBytes11(12).toString("base64url"));
39860
+ this.newId = o.streamId ?? (() => randomBytes12(12).toString("base64url"));
39151
39861
  }
39152
39862
  /** Liga à conexão do prédio (que chama `opened`, `closed` e `message` daqui). */
39153
39863
  attach(link) {
@@ -39223,7 +39933,7 @@ var WorldViewer = class {
39223
39933
  /** POST /api/world/cmd {stream, cmds}. */
39224
39934
  command(body2) {
39225
39935
  const max = WORLD_SCENE_LIMITS.cmdsPerBatch;
39226
- if (!isObj6(body2) || typeof body2.stream !== "string" || !Array.isArray(body2.cmds) || body2.cmds.length === 0 || body2.cmds.length > max) {
39936
+ if (!isObj7(body2) || typeof body2.stream !== "string" || !Array.isArray(body2.cmds) || body2.cmds.length === 0 || body2.cmds.length > max) {
39227
39937
  return { ok: false, status: 400, code: "invalid" };
39228
39938
  }
39229
39939
  const s2 = this.streams.get(body2.stream);
@@ -39701,6 +40411,12 @@ hub.setInitialFrames(() => {
39701
40411
  });
39702
40412
  var avatar = new AvatarStore(join33(config.dataDir, "avatar.json"));
39703
40413
  hub.setInitialFrames(() => [["avatar", avatar.get()]]);
40414
+ var inboxStore = new InboxStore(join33(config.dataDir, "inbox.json"));
40415
+ var inbox = new InboxService({ store: inboxStore, agents: () => office.list() });
40416
+ inbox.onFrame((f) => hub.broadcast("inbox", f));
40417
+ hub.setInitialFrames(() => [["inbox", inbox.frame()]]);
40418
+ var inboxPurgeTimer = setInterval(() => inboxStore.purge(), 60 * 6e4);
40419
+ inboxPurgeTimer.unref();
39704
40420
  hub.setInitialFrames(() => [["defaultLook", defaultLook2.get()]]);
39705
40421
  var perfSampler = new PerfSampler({
39706
40422
  workCounters: {
@@ -39735,6 +40451,7 @@ if (config.satellite) {
39735
40451
  if (!registry) return { actionId: a.id, ok: false, error: tr("permiss\xF5es desligadas nesta m\xE1quina"), status: 403 };
39736
40452
  return createPermissionDecideHandler({ registry })(a, deadline);
39737
40453
  },
40454
+ "inbox.resolve": createInboxResolveHandler({ store: inboxStore }),
39738
40455
  // Leituras da central (detalhe, terminal, comandos, arquivos de entrega): cada uma é um GET na rota local desta máquina.
39739
40456
  ...createReadHandlers({ port: config.port, host: config.host, link: satelliteLink }),
39740
40457
  "pty.create": async (a, deadline) => remoteSatellitePtys?.handlers()["pty.create"]?.(a, deadline) ?? { actionId: a.id, ok: false, status: 503, error: ptyOff ?? tr("desligado nesta m\xE1quina") },
@@ -39751,7 +40468,8 @@ if (config.satellite) {
39751
40468
  handlers,
39752
40469
  perfSampler,
39753
40470
  ptys: () => remoteSatellitePtys,
39754
- maintenance: () => remoteSatellitePtys?.tick()
40471
+ maintenance: () => remoteSatellitePtys?.tick(),
40472
+ inbox: { items: () => visibleInbox(inboxStore.list()), onChange: (cb) => inboxStore.onChange(cb) }
39755
40473
  });
39756
40474
  }
39757
40475
  }
@@ -39872,8 +40590,8 @@ var providers = config.inDocker ? () => DOCKER_PROVIDERS.map((p) => ({ ...p }))
39872
40590
  };
39873
40591
  var gentleInbox = () => messages && {
39874
40592
  agents: () => office.list().filter((a) => a.provider === "gentle-shell" && a.kind === "main").map((a) => ({ id: a.id, cwd: office.roomPath(a.roomId), startedAt: a.startedAt })),
39875
- send: (agentId, text2) => {
39876
- const r = messages.send({ agentId, text: text2 });
40593
+ send: (agentId, text3) => {
40594
+ const r = messages.send({ agentId, text: text3 });
39877
40595
  if ("message" in r) return { ok: true };
39878
40596
  if (r.error === "unavailable") return { ok: false, retry: true, reason: r.reason };
39879
40597
  if (r.error === "too-many") return { ok: false, retry: false, reason: tr("o agente j\xE1 tem mensagens demais esperando") };
@@ -39898,7 +40616,7 @@ var messages = config.messages ? new MessageRegistry({
39898
40616
  office,
39899
40617
  images: messageImages,
39900
40618
  demoAgent: (id) => office.demoAgent(id),
39901
- demoDeliver: (id, text2) => office.deliverDemoMessage(id, text2),
40619
+ demoDeliver: (id, text3) => office.deliverDemoMessage(id, text3),
39902
40620
  codex: {
39903
40621
  run: codexBin ? createCodexQueueRunner(codexBin) : void 0,
39904
40622
  homeOf: (account) => accounts.entriesOf("codex").find((e) => e.id === account)?.detected.configDir
@@ -40006,6 +40724,7 @@ var api = createApiHandler({
40006
40724
  // Central: `remotePermissions` nasce mais abaixo; id que não é remoto cai no registro local.
40007
40725
  permissions: permissions ? createPermissionRoutes(permissions, config.central ? { detail: (id, res) => late.remotePermissions?.detail(id, res) ?? false, decide: async (id, raw) => late.remotePermissions?.decide(id, raw) } : void 0) : void 0,
40008
40726
  attention: createAttentionRoutes(attention, hub),
40727
+ inbox: createInboxRoutes(inbox),
40009
40728
  avatar: createAvatarRoutes(avatar, hub),
40010
40729
  defaultLook: createDefaultLookRoutes(defaultLook2, () => {
40011
40730
  late.office?.markDirty();
@@ -40185,6 +40904,7 @@ if (config.central) {
40185
40904
  late.remotePtys.start();
40186
40905
  late.centralRoutes = createCentralRoutes({ machines, hub: centralHub, name: central.name, port: central.port, fingerprint: () => caFingerprint(tlsPaths(central.tlsBase)) });
40187
40906
  late.remotePermissions = new RemotePermissions({ hub: centralHub });
40907
+ inbox.setRemote(new RemoteInboxItems(centralHub));
40188
40908
  centralHub.start();
40189
40909
  if (messages) {
40190
40910
  late.remoteMessages = new RemoteMessages({ hub: centralHub, office, images: messageImages });
@@ -40218,7 +40938,7 @@ if (config.central) {
40218
40938
  listener = startCentralListener({
40219
40939
  host: bind.host,
40220
40940
  port: central.port,
40221
- tls: { key: readFileSync29(paths.serverKey), cert: readFileSync29(paths.serverCert), ca: readFileSync29(paths.caCert) },
40941
+ tls: { key: readFileSync30(paths.serverKey), cert: readFileSync30(paths.serverCert), ca: readFileSync30(paths.caCert) },
40222
40942
  machines,
40223
40943
  routes: centralHub
40224
40944
  });
@@ -40326,6 +41046,7 @@ function shutdown(signal) {
40326
41046
  centralStopped = true;
40327
41047
  if (centralRetry) clearTimeout(centralRetry);
40328
41048
  if (remoteMessagesTimer) clearInterval(remoteMessagesTimer);
41049
+ clearInterval(inboxPurgeTimer);
40329
41050
  late.remoteMessages?.stop();
40330
41051
  late.remotePtys?.dispose();
40331
41052
  late.centralHub?.stop();