synabun 2.4.5 → 2.4.6

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 (95) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/docs/whatsapp.md +17 -1
  4. package/hooks/claude-code/session-start.mjs +21 -18
  5. package/lib/claude-global-config.js +214 -0
  6. package/lib/client-config-repair.js +17 -3
  7. package/mcp-server/dist/index.d.ts.map +1 -1
  8. package/mcp-server/dist/index.js +6 -1
  9. package/mcp-server/dist/index.js.map +1 -1
  10. package/mcp-server/dist/services/tool-catalog.js +1 -1
  11. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  12. package/mcp-server/dist/tools/agents.d.ts +2 -0
  13. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  14. package/mcp-server/dist/tools/agents.js +11 -5
  15. package/mcp-server/dist/tools/agents.js.map +1 -1
  16. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  17. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  18. package/mcp-server/dist/tools/skill-tools.js +88 -8
  19. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  20. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  21. package/mcp-server/dist/tools/tool-groups.js +19 -4
  22. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  23. package/mcp-server/package-lock.json +2 -2
  24. package/mcp-server/package.json +1 -1
  25. package/mcp-server/src/index.ts +6 -1
  26. package/mcp-server/src/services/tool-catalog.ts +1 -1
  27. package/mcp-server/src/tools/agents.ts +11 -5
  28. package/mcp-server/src/tools/skill-tools.ts +82 -9
  29. package/mcp-server/src/tools/tool-groups.ts +19 -4
  30. package/neural-interface/i18n/en.json +135 -10
  31. package/neural-interface/i18n/pt-BR.json +135 -10
  32. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  33. package/neural-interface/lib/assistant-dispatch.js +15 -1
  34. package/neural-interface/lib/assistant-runtime.js +79 -8
  35. package/neural-interface/lib/assistant-user-context.js +7 -3
  36. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  37. package/neural-interface/lib/codex-thread-history.js +144 -7
  38. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  39. package/neural-interface/lib/db.js +26 -0
  40. package/neural-interface/lib/greeting/sources.js +7 -3
  41. package/neural-interface/lib/jsonl-lines.js +10 -11
  42. package/neural-interface/lib/line-buffer.js +88 -0
  43. package/neural-interface/lib/loop-stall.js +15 -1
  44. package/neural-interface/lib/memory-list-read.js +105 -0
  45. package/neural-interface/lib/memory-timers.js +4 -1
  46. package/neural-interface/lib/native-loop-runtime.js +7 -3
  47. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  48. package/neural-interface/lib/skills/api-v2.js +18 -3
  49. package/neural-interface/lib/skills/bundle.js +2 -2
  50. package/neural-interface/lib/skills/deploy.js +169 -34
  51. package/neural-interface/lib/skills/digest.js +57 -3
  52. package/neural-interface/lib/skills/health.js +55 -1
  53. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  54. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  55. package/neural-interface/lib/skills/scan-shell.js +56 -7
  56. package/neural-interface/lib/skills/scan.js +13 -12
  57. package/neural-interface/lib/skills/service.js +7 -2
  58. package/neural-interface/lib/skills/telemetry.js +2 -2
  59. package/neural-interface/lib/teams/README.md +12 -5
  60. package/neural-interface/lib/teams/api.js +15 -4
  61. package/neural-interface/lib/teams/index.js +2 -0
  62. package/neural-interface/lib/teams/landing.js +195 -75
  63. package/neural-interface/lib/teams/scheduler.js +31 -32
  64. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  65. package/neural-interface/lib/terminal-tokens.js +18 -0
  66. package/neural-interface/lib/whatsapp/brain.js +21 -0
  67. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  68. package/neural-interface/package-lock.json +2 -2
  69. package/neural-interface/package.json +1 -1
  70. package/neural-interface/public/index.html +117 -37
  71. package/neural-interface/public/shared/agents/studio/ax-api.js +11 -0
  72. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  73. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  74. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  75. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  76. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  77. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +137 -39
  78. package/neural-interface/public/shared/agents/studio/ax-teams.js +219 -4
  79. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  80. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  81. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  82. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  83. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  84. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  85. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  86. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  87. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  88. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  89. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  90. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  91. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  92. package/neural-interface/server.js +316 -252
  93. package/npm-shrinkwrap.json +2 -2
  94. package/package.json +2 -1
  95. package/skills/skill-forge/SKILL.md +7 -3
@@ -7125,6 +7125,9 @@
7125
7125
  "state_attention": "Precisa de atenção",
7126
7126
  "state_unverified_runtime": "Arquivos verificados; execução no runtime não verificada",
7127
7127
  "state_checked": "Verificações concluídas; execução não verificada",
7128
+ "state_static_only": "Arquivos, regras de pasta e configurações verificados; aqui não há lista de runtime que o SynaBun possa consultar",
7129
+ "unverifiedRuntimes": "Ainda não confirmado: {runtimes}",
7130
+ "staticOnlyRuntimes": "Verificado sem lista (não há uma para consultar): {runtimes}",
7128
7131
  "state_error": "Falha na verificação",
7129
7132
  "issue_missing": "A pasta instalada está ausente",
7130
7133
  "issue_changed": "Os bytes instalados mudaram",
@@ -7132,6 +7135,7 @@
7132
7135
  "issue_not_discoverable": "As regras de descoberta do runtime não a encontram",
7133
7136
  "issue_disabled": "Desativada nas configurações do runtime",
7134
7137
  "issue_not_listed": "O runtime não a listou",
7138
+ "issue_static_check_failed": "A verificação estática desta instalação falhou",
7135
7139
  "issue_scan_review": "Os achados de segurança precisam de revisão",
7136
7140
  "issue_scan_blocked": "A verificação de segurança bloqueia o uso destes bytes",
7137
7141
  "issue_check_error": "Não foi possível concluir todas as verificações",
@@ -8434,7 +8438,18 @@
8434
8438
  "no-answer": "O {runtime} não respondeu, então não foi possível perguntar: verifique de novo daqui a pouco",
8435
8439
  "no-list": "O {runtime} não tem uma lista para consultar; as regras de pasta dele foram verificadas no lugar",
8436
8440
  "terminal-only": "O {runtime} no terminal lê esta pasta; o painel do {runtime} do SynaBun não, então ele não foi consultado"
8437
- }
8441
+ },
8442
+ "eligibilityRuntime": {
8443
+ "enabled": "{runtime}: ativada nas configurações dele",
8444
+ "disabled": "{runtime}: desligada nas configurações dele",
8445
+ "unknown": "{runtime}: as configurações dele não puderam ser lidas",
8446
+ "not-checked": "{runtime}: configurações não verificadas (o SynaBun não as lê)"
8447
+ },
8448
+ "probe": {
8449
+ "cannot-probe": "Não dá para perguntar ao {runtime}: ele não tem uma lista (as regras de pasta dele foram verificadas)",
8450
+ "not-probed": "O {runtime} ainda não foi consultado: Verificar pergunta a ele"
8451
+ },
8452
+ "checkFailed": "A verificação depois da instalação falhou ({error}); a instalação está no lugar. Verificar confere de novo."
8438
8453
  },
8439
8454
  "readBy": "Lida por {runtimes}",
8440
8455
  "blocked": {
@@ -9382,12 +9397,99 @@
9382
9397
  "unreachableTitle": "O Estúdio de Agentes não conseguiu falar com o servidor"
9383
9398
  },
9384
9399
  "rail": {
9400
+ "work": "Trabalho",
9401
+ "agents": "Agentes",
9385
9402
  "library": "Biblioteca",
9386
9403
  "create": "Criar",
9387
- "review": "Revisão",
9404
+ "review": "Revisões de definições",
9388
9405
  "teams": "Equipes",
9389
9406
  "waiting": "esperando revisão",
9390
- "byStatus": "Por situação"
9407
+ "taskStatus": "Situação das tarefas"
9408
+ },
9409
+ "work": {
9410
+ "title": "Trabalho",
9411
+ "needsYou": "Precisa de você",
9412
+ "active": "Em andamento",
9413
+ "inReview": "Em revisão",
9414
+ "finished": "Concluídas",
9415
+ "task": "Tarefa",
9416
+ "progress": "Progresso",
9417
+ "who": "Projeto / workers",
9418
+ "oneWorker": "1 worker",
9419
+ "teamOf": "Equipe de {count}",
9420
+ "noWorkers": "Sem workers",
9421
+ "noProject": "Projeto indisponível",
9422
+ "untitled": "Tarefa sem título",
9423
+ "answer": "Responder",
9424
+ "openTask": "Abrir tarefa",
9425
+ "viewProgress": "Ver progresso",
9426
+ "reviewLand": "Revisar e integrar em {branch}",
9427
+ "readReport": "Ler relatório",
9428
+ "viewOutcome": "Ver resultado",
9429
+ "waiting": "Aguardando sua resposta.",
9430
+ "waitingOn": "Aguardando sua resposta sobre {subject}.",
9431
+ "permission": "Um worker precisa da sua permissão.",
9432
+ "decision": "Um worker aguarda sua decisão.",
9433
+ "failedPart": "{part} não conseguiu terminar.",
9434
+ "failedTests": "Os testes de {part} falharam.",
9435
+ "failedTestsSafe": "Os testes de {part} falharam. As mudanças de {other} estão seguras.",
9436
+ "failedTask": "O worker não conseguiu terminar.",
9437
+ "teamFailed": "A equipe não conseguiu terminar.",
9438
+ "noCommand": "{count} partes reunidas. Nenhum comando de teste definido.",
9439
+ "noCommandOne": "1 parte reunida. Nenhum comando de teste definido.",
9440
+ "noCommandUnknown": "Nenhum comando de teste definido.",
9441
+ "noPass": "Nenhuma verificação passou no commit atual.",
9442
+ "branchMissing": "A branch de destino {branch} não existe.",
9443
+ "branchMoved": "A branch de destino {branch} mudou.",
9444
+ "landingBlocked": "A equipe ainda não consegue integrar as mudanças.",
9445
+ "previewMissing": "As verificações de integração estão indisponíveis.",
9446
+ "attention": "A equipe precisa da sua atenção.",
9447
+ "partial": "Chegaram {arrived} relatórios. {missing} revisores não enviaram relatório.",
9448
+ "partialOneMissing": "Chegaram {arrived} relatórios. 1 revisor não enviou relatório.",
9449
+ "partialOneArrived": "Chegou 1 relatório. {missing} revisores não enviaram relatório.",
9450
+ "partialOneEach": "Chegou 1 relatório. 1 revisor não enviou relatório.",
9451
+ "reportsUnknown": "Revisão concluída. Ainda não foi possível confirmar os relatórios disponíveis.",
9452
+ "reportsReady": "Revisão concluída. Todos os {count} relatórios estão disponíveis.",
9453
+ "reportReady": "Revisão concluída. O relatório está disponível.",
9454
+ "onBranch": "As mudanças estão em {branch}. Confira o que falta.",
9455
+ "landedCheck": "Mudanças integradas. Confira se ainda há algo a fazer.",
9456
+ "copies": "Mudanças integradas em {branch}. Restam {count} cópias de trabalho.",
9457
+ "copy": "Mudanças integradas em {branch}. Resta 1 cópia de trabalho.",
9458
+ "dirty": "{part} tem {count} arquivos sem commit.",
9459
+ "dirtyOne": "{part} tem 1 arquivo sem commit.",
9460
+ "landed": "Mudanças integradas e cópias de trabalho removidas.",
9461
+ "discarded": "A tarefa foi descartada.",
9462
+ "discardedCheck": "A tarefa foi descartada. Confira se ainda há algo a fazer.",
9463
+ "working": "Trabalho em andamento.",
9464
+ "workingPart": "{part} está em andamento.",
9465
+ "workingJoined": "{count} partes reunidas. {part} em andamento.",
9466
+ "workingJoinedOne": "1 parte reunida. {part} em andamento.",
9467
+ "ready": "Verificações aprovadas. Tudo pronto para integrar em {branch}.",
9468
+ "queued": "Aguardando um worker começar.",
9469
+ "paused": "Trabalho pausado.",
9470
+ "idle": "O worker aguarda mais trabalho.",
9471
+ "stopped": "Trabalho interrompido.",
9472
+ "completed": "Trabalho concluído.",
9473
+ "reportKept": "Trabalho concluído. O relatório está disponível.",
9474
+ "loading": "Carregando tarefas",
9475
+ "empty": "Nada precisa de resposta ou revisão",
9476
+ "missingTeams": "As tarefas de equipe estão indisponíveis.",
9477
+ "missingRuns": "As tarefas e perguntas dos workers estão indisponíveis.",
9478
+ "missingDetails": "Alguns detalhes das equipes estão indisponíveis.",
9479
+ "offline": "Conexão perdida. Reconecte para atualizar as tarefas.",
9480
+ "retry": "Tentar reconectar",
9481
+ "refresh": "Atualizar tarefas",
9482
+ "capped": "Exibindo os últimos 500 registros de workers. Tarefas anteriores podem ficar de fora.",
9483
+ "freeText": "Sua resposta",
9484
+ "custom": "Outra resposta",
9485
+ "yes": "Sim",
9486
+ "no": "Não",
9487
+ "submit": "Enviar resposta",
9488
+ "sent": "Resposta enviada.",
9489
+ "stale": "A pergunta já foi respondida em outro lugar ou foi encerrada.",
9490
+ "answerFailed": "Não foi possível enviar a resposta. Tente novamente.",
9491
+ "answerUnsupported": "Este servidor não aceita respostas por aqui.",
9492
+ "required": "Responda a cada pergunta obrigatória."
9391
9493
  },
9392
9494
  "tab": {
9393
9495
  "edit": "Editar",
@@ -9573,7 +9675,7 @@
9573
9675
  "layout": "Disposição",
9574
9676
  "layoutCards": "Cartões",
9575
9677
  "layoutList": "Lista",
9576
- "newAgent": "Novo agente",
9678
+ "newAgent": "Criar agente",
9577
9679
  "fromTemplate": "De um modelo",
9578
9680
  "import": "Importar",
9579
9681
  "exportAll": "Exportar tudo",
@@ -9766,7 +9868,7 @@
9766
9868
  },
9767
9869
  "describe": {
9768
9870
  "name": "Descrever",
9769
- "desc": "Diga ao Assistente o que você precisa. Ele rascunha o agente e o envia para Revisão."
9871
+ "desc": "Diga ao Assistente o que você precisa. Ele prepara um rascunho do agente para você revisar."
9770
9872
  }
9771
9873
  },
9772
9874
  "step": {
@@ -9817,9 +9919,9 @@
9817
9919
  "send": "Enviar ao Assistente",
9818
9920
  "review": "O rascunho chega na fila de revisão.",
9819
9921
  "required": "Descreva o agente primeiro.",
9820
- "sent": "Enviado ao Assistente. O rascunho aparece em Revisão quando estiver pronto.",
9821
- "arrived": "Um rascunho chegou em Revisão.",
9822
- "openReview": "Abrir Revisão",
9922
+ "sent": "Enviado ao Assistente. O rascunho aparece em Revisões de definições quando estiver pronto.",
9923
+ "arrived": "Um rascunho está pronto para revisão.",
9924
+ "openReview": "Abrir revisões de definições",
9823
9925
  "request": "Rascunhe uma definição de agente do SynaBun a partir desta descrição, verifique-a e envie-a para a minha revisão no Estúdio de Agentes (não a aprove):",
9824
9926
  "requestGlobal": "Ponha-o na biblioteca global.",
9825
9927
  "requestProject": "Fixe-o no projeto {path}."
@@ -9982,6 +10084,7 @@
9982
10084
  "nothingHelp": "Salve um rascunho primeiro."
9983
10085
  },
9984
10086
  "teams": {
10087
+ "manage": "Gerenciar equipes",
9985
10088
  "readOnly": "Workers somente de leitura. Os resultados não precisam de integração nem de merge.",
9986
10089
  "sub": "Uma tarefa dada a vários agentes, cada um na sua própria worktree.",
9987
10090
  "emptyTitle": "Nenhuma equipe ainda",
@@ -9991,7 +10094,7 @@
9991
10094
  "notRunning": "Este servidor tem as rotas de equipes, mas o agendador de equipes ainda não está em execução: ele começa com o Assistente.",
9992
10095
  "goneTitle": "Esta equipe não está disponível",
9993
10096
  "goneHelp": "Ela foi removida ou descartada, ou este servidor ainda não tem as rotas de equipes.",
9994
- "backToList": "Todas as equipes",
10097
+ "backToList": "Voltar",
9995
10098
  "summary": "Resumo da equipe",
9996
10099
  "status": "Situação",
9997
10100
  "project": "Projeto",
@@ -10047,6 +10150,28 @@
10047
10150
  "yourBranch": "o seu ramo",
10048
10151
  "landedToast": "Integração iniciada.",
10049
10152
  "landFailed": "Não foi possível integrar a equipe: {error}",
10153
+ "landTip": "Ponta atual",
10154
+ "landTipMissing": "Ramo não encontrado",
10155
+ "landHead": "Ponta da integração",
10156
+ "landTests": "Testes nesta ponta",
10157
+ "landTestsNotPassed": "Não passaram",
10158
+ "landNoTestCommand": "Sem comando de teste",
10159
+ "landStale": "O ramo ou o trabalho da equipe mudou desde que este diálogo foi aberto. Nada foi integrado.",
10160
+ "landStaleAgain": "Estes são os valores de agora. Confirme de novo para integrá-los, ou cancele.",
10161
+ "landUntested": "Integrar sem testes",
10162
+ "landUntestedHelp": "Decisão sua: integrar um trabalho que nenhum teste verificou",
10163
+ "landUntestedTitle": "Integrar \"{name}\" sem testes?",
10164
+ "landUntestedAsk": "{branch} será movido para o resultado integrado da equipe.",
10165
+ "landUntestedWarn": "Este trabalho não foi verificado por testes: nenhuma execução de testes passou nesta ponta. Integrá-lo é uma decisão sua.",
10166
+ "landWhy": {
10167
+ "TESTS_NOT_PASSED": "A integração não é oferecida: os testes não passaram na ponta da integração.",
10168
+ "NO_TEST_COMMAND": "A integração não é oferecida: esta equipe não tem comando de teste, então nenhum teste verificou o trabalho dela.",
10169
+ "NOT_FAST_FORWARD": "A integração não é oferecida: {branch} tem commits que o trabalho da equipe não tem, então não pode ser avançado até ele.",
10170
+ "NOTHING_TO_LAND": "Nada a integrar: {branch} já tem tudo o que a equipe integrou.",
10171
+ "TEAM_NOT_READY": "A integração ainda não é oferecida: nem todas as fatias foram juntadas no ramo de integração.",
10172
+ "TARGET_NOT_FOUND": "A integração não é oferecida: o ramo {branch} não está neste projeto.",
10173
+ "other": "A integração não é oferecida para esta equipe agora."
10174
+ },
10050
10175
  "discard": "Descartar",
10051
10176
  "discardTitle": "Descartar \"{name}\"?",
10052
10177
  "discardAsk": "Os workers da equipe são parados e as worktrees e os ramos dela são removidos. Uma worktree ou ramo com trabalho que nunca foi integrado é mantido: você pode apagá-lo depois.",
@@ -10254,7 +10379,7 @@
10254
10379
  "testStarted": "Execução de teste iniciada.",
10255
10380
  "focusFailed": "Não foi possível focar a execução: {error}",
10256
10381
  "sentToAssistant": "Enviado ao Assistente.",
10257
- "draftArrived": "Um rascunho novo chegou em Revisão."
10382
+ "draftArrived": "Um novo rascunho está pronto para revisão."
10258
10383
  }
10259
10384
  },
10260
10385
  "context": {
@@ -59,6 +59,7 @@ import { createHash, randomBytes } from 'node:crypto';
59
59
  import { lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
60
60
  import { basename, dirname, extname, isAbsolute, join, resolve } from 'node:path';
61
61
  import { pathToFileURL } from 'node:url';
62
+ import { timeBlockingWork } from '../loop-stall.js';
62
63
  import { createAcpClientHost } from './acp-client-host.js';
63
64
  import { acpErrorInfo, createAcpConnection, isAuthRequired } from './acp-connection.js';
64
65
  import { allowOnceOption, bypassRail, rejectOnceOption } from './bypass.js';
@@ -627,9 +628,12 @@ export function createAntigravityPanelBridge({
627
628
  onLog: (line) => log(`[antigravity] ${line}`),
628
629
  onUpdate: (params) => {
629
630
  if (!params || typeof params.sessionId !== 'string') return;
630
- const session = sessions.get(params.sessionId);
631
- noteSubagent(params.sessionId, params.update);
632
- send({ type: 'session:update', sessionId: params.sessionId, update: params.update, replay: !!session?.replaying });
631
+ // One ACP update handed on to the page, on the server's own thread: timed by name (lib/loop-stall.js).
632
+ timeBlockingWork('antigravity:acp-update', () => {
633
+ const session = sessions.get(params.sessionId);
634
+ noteSubagent(params.sessionId, params.update);
635
+ send({ type: 'session:update', sessionId: params.sessionId, update: params.update, replay: !!session?.replaying });
636
+ });
633
637
  },
634
638
  onPermission: (params) => new Promise((resolve) => {
635
639
  const requestId = randomBytes(8).toString('hex');
@@ -2743,7 +2743,8 @@ export function createAssistantDispatcher({
2743
2743
  liveState.steer = null;
2744
2744
  const steerPrompt = buildFollowUpPrompt(steer.text, state, { turn: liveState.turnCounter + 1, maxTurns: entry.maxTurns, origin: 'steer', testDensity: changedTestDensity(entry) });
2745
2745
  const followPrompt = out.notSent && out.prompt ? `${out.prompt}\n\n${steerPrompt}` : steerPrompt;
2746
- out = await runInnerTurn(followPrompt, meta, { origin: 'steer', label: clip(steer.text, 80), followUp: steer.text, taskId: steer.taskId || entry.taskId || null, outboxId: steer.outboxId || null });
2746
+ try { out = await runInnerTurn(followPrompt, meta, { origin: 'steer', label: clip(steer.text, 80), followUp: steer.text, taskId: steer.taskId || entry.taskId || null, outboxId: steer.outboxId || null }); }
2747
+ catch (error) { throw undeliveredSteer(entry, liveState, error); }
2747
2748
  }
2748
2749
  return out;
2749
2750
  };
@@ -2944,6 +2945,19 @@ export function createAssistantDispatcher({
2944
2945
  // The provider never had the cut turn's prompt (it was still starting): the steer's turn carries it again.
2945
2946
  return { steered: true, turn: turnNumber, notSent: error?.notSent === true, prompt };
2946
2947
  }
2948
+ /**
2949
+ * The turn that carries a steer after the turn it cut failed (the provider is gone, or ended that turn by itself):
2950
+ * the run fails and says so (completionReason `steer_undelivered`, its error names the steer), never ends
2951
+ * as completed with no outcome, which is how an unexplained AbortError reads (handleTurnError). A stop, a shutdown
2952
+ * and a budget's cap keep their own error. What the error carries (cost, usage) is kept for the booking.
2953
+ */
2954
+ function undeliveredSteer(entry, liveState, error) {
2955
+ if (liveState.abortReason || liveState.suspending || liveState.dead || error?.code === 'BUDGET_CAP' || budgetStopReason(entry.completionReason)) return error;
2956
+ entry.completionReason = 'steer_undelivered';
2957
+ const why = clip(error?.message || String(error), 300);
2958
+ return Object.assign(new Error(`The steer could not be delivered: the turn that carries it failed (${why}).`, { cause: error }),
2959
+ error && typeof error === 'object' ? { ...error } : {}, { name: 'Error', code: 'STEER_UNDELIVERED' });
2960
+ }
2947
2961
  /**
2948
2962
  * Steer a run: the user changed what it is doing. A turn in flight is interrupted at the provider (the session stays
2949
2963
  * warm, its context kept, tool calls already done stay done), a pending permission or question is denied, and the
@@ -2293,9 +2293,8 @@ export function createAssistantRuntime({
2293
2293
  // (lib/skills/api-v2.js principalOf) take it; whatsapp_send_file takes it and then only the active WhatsApp
2294
2294
  // conversation's session (lib/whatsapp/service.js sendFile).
2295
2295
  live.brainCredential = mintBrainCredential();
2296
- // The brain's own pin (its session id, for the brains that name it) is proven by this same credential: its MCP
2297
- // presents it with X-Synabun-Terminal, and a process that only names the session gets nothing (lib/terminal-tokens.js).
2298
- if (BRAIN_PIN_PROVIDERS.has(brain.provider)) { try { terminalTokens?.bind?.(live.record.id, live.brainCredential); } catch { /* the brain starts; its pin stays as it was */ } }
2296
+ // (It becomes the proof of the brain's own pin right before the brain is made, below: nothing is bound for a
2297
+ // launch that fails while its options are still being put together.)
2299
2298
  const cliCap = brain.provider === 'claude-code' ? brainCliCap(live) : null;
2300
2299
  const deps = {
2301
2300
  ClaudeSession, sdkVersion, PACKAGE_ROOT, handleCodexSkinWebSocket, ensureIsolatedServe, stopIsolatedServe, setupOpencodeSidepanelConfig,
@@ -2362,7 +2361,20 @@ export function createAssistantRuntime({
2362
2361
  live.brainCliCap = cliCap;
2363
2362
  live.brainBudgetVersion = budgetSettingNow()?.version ?? null;
2364
2363
  startMeter(live, brain.provider);
2365
- const created = factory({ session: live.record, sink, deps, persona, hooks });
2364
+ // The brain's own pin (its session id, for the brains that name it) is proven by this launch's credential: its MCP
2365
+ // presents it with X-Synabun-Terminal, and a process that only names the session gets nothing (lib/terminal-tokens.js).
2366
+ const pinned = BRAIN_PIN_PROVIDERS.has(brain.provider);
2367
+ if (pinned) { try { terminalTokens?.bind?.(live.record.id, live.brainCredential); } catch { /* the brain starts; its pin stays as it was */ } }
2368
+ let created;
2369
+ try {
2370
+ created = factory({ session: live.record, sink, deps, persona, hooks });
2371
+ } catch (error) {
2372
+ // No brain was made, so disposeBrain has nothing to dispose and would leave the credential bound (and known to
2373
+ // the scrubbers) for as long as the server runs: it ends here.
2374
+ live.brainCredential = null;
2375
+ if (pinned) { try { terminalTokens?.revoke?.(live.record.id); } catch { /* the failure goes on */ } }
2376
+ throw error;
2377
+ }
2366
2378
  live.brain = created;
2367
2379
  live.brainSkipAllowed = remote ? deps.remoteLevel === 'autonomous' : null;
2368
2380
  live.brainComputerMode = computerMode;
@@ -2582,6 +2594,24 @@ export function createAssistantRuntime({
2582
2594
  if (budgetBlock) return refuse(live, budgetBlock.code, budgetBlock.message, { request });
2583
2595
  if (live.switching) await live.switching;
2584
2596
  if (cancelled()) return dropTurn(live, request);
2597
+ // A refusal for the account names the soonest reset when every subscription is limited.
2598
+ const accountRefusal = (error) => ({ ...refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }), ...(error.resetsAt ? { resetsAt: error.resetsAt } : {}) });
2599
+ // A WhatsApp conversation on an account nothing put on Auto: it moves to Auto when the account
2600
+ // cannot run, or when the Default account starts a provider conversation (phoneAccountMoves).
2601
+ if (live.record.brain.accountPolicy !== 'auto' && isPhoneSession(live) && ['claude-code', 'codex'].includes(live.record.brain.provider)) {
2602
+ await accountUsage?.refresh(live.record.brain.provider);
2603
+ if (cancelled()) return dropTurn(live, request);
2604
+ const rows = conversationAccounts(live.record.brain, live);
2605
+ if (rows.length && phoneAccountMoves(live, rows)) {
2606
+ try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2607
+ catch (error) {
2608
+ // No signed-in subscription at all (only API keys, or all signed out): the account stays as
2609
+ // it is, and runs (a key) or is refused below with why (signed out, removed).
2610
+ if (error?.code !== 'ACCOUNT_NO_SUBSCRIPTION') return accountRefusal(error);
2611
+ }
2612
+ if (cancelled()) return dropTurn(live, request);
2613
+ }
2614
+ }
2585
2615
  if (live.record.brain.accountPolicy === 'auto') {
2586
2616
  await accountUsage?.refresh(live.record.brain.provider);
2587
2617
  if (cancelled()) return dropTurn(live, request);
@@ -2589,7 +2619,7 @@ export function createAssistantRuntime({
2589
2619
  const active = rows.find(row => row.id === live.record.brain.accountId);
2590
2620
  if (!active || active.signedIn !== true || active.mode !== 'subscription' || active.usage?.limited) {
2591
2621
  try { await updateSession(live.record.id, { brain: { accountId: 'auto' } }, { fromTurn: true }); }
2592
- catch (error) { return refuse(live, error.code || 'ACCOUNT_UNAVAILABLE', error.message, { request }); }
2622
+ catch (error) { return accountRefusal(error); }
2593
2623
  if (cancelled()) return dropTurn(live, request);
2594
2624
  }
2595
2625
  }
@@ -3240,12 +3270,49 @@ export function createAssistantRuntime({
3240
3270
  }
3241
3271
  return { ...brain, accountId: row.id, accountPolicy: 'auto' };
3242
3272
  }
3273
+ /** A conversation held from WhatsApp (bridge-made: `channel`, `remote.channel`). */
3274
+ function isPhoneSession(live) { return (live.record.channel || live.record.remote?.channel || null) === 'whatsapp'; }
3275
+ /**
3276
+ * Whether a WhatsApp conversation's account (Claude Code, Codex; not on Auto) moves to Auto · most
3277
+ * usage left before this turn. Nobody on a phone can switch an account that ran out, so there the
3278
+ * account follows usage within what was chosen (docs/whatsapp.md → The account):
3279
+ * - an account that cannot run moves: removed, signed out, or limited (its usage reading, or a limit
3280
+ * this conversation hit: conversationAccounts);
3281
+ * - the Default account moves while there is no provider conversation yet (a new conversation, or
3282
+ * one just switched to this provider): the panel's untouched brain names Default too, so it is
3283
+ * no deliberate choice, and Auto keeps it whenever it has the most usage left;
3284
+ * - an API-key account stays (a configuration, with no quota), and so does a named subscription
3285
+ * with usage left, and Default once its provider conversation exists (continuity).
3286
+ */
3287
+ function phoneAccountMoves(live, rows) {
3288
+ const active = rows.find(row => row.id === (live.record.brain.accountId || 'default'));
3289
+ if (!active) return true;
3290
+ if (active.mode === 'apiKey' || active.mode === 'api') return false;
3291
+ if (active.signedIn === false || active.usage?.limited === true) return true;
3292
+ const fresh = !live.brain && !live.record.providerSessionId && !live.record.providerThreadId;
3293
+ return fresh && active.id === 'default' && active.mode === 'subscription' && active.signedIn === true;
3294
+ }
3295
+ /**
3296
+ * The account a new session starts on. Auto picks the subscription with the most usage left
3297
+ * now, also when the brain names an account an earlier pick chose (the panel's last-used
3298
+ * brain, which "Same as the Assistant" on WhatsApp copies): a new session has no provider
3299
+ * conversation to keep. When nothing can be picked now (no signed-in subscription, all
3300
+ * limited) the named account stays, and the first turn's account check says why it cannot run.
3301
+ */
3302
+ async function startingAccount(brain) {
3303
+ if (brain.accountPolicy !== 'auto' || brain.accountId === 'auto' || !['claude-code', 'codex'].includes(brain.provider)) return resolveAutoAccount(brain);
3304
+ try { return await resolveAutoAccount({ ...brain, accountId: 'auto' }); }
3305
+ catch (error) {
3306
+ if (error?.code !== 'ACCOUNT_NO_SUBSCRIPTION' && error?.code !== 'ACCOUNTS_ALL_LIMITED') throw error;
3307
+ return brain;
3308
+ }
3309
+ }
3243
3310
  async function createSession({ brain = {}, label = null, cwd = null, windowId = null, fallback = false, channel = null, draft = false } = {}, internal = {}) {
3244
3311
  if (brain?.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
3245
3312
  const id = `assistant-${randomUUID()}`;
3246
3313
  const requested = normalizeSessionBrain({ ...brain, cwd: brain?.cwd || cwd || settings.defaultBrain.cwd || PACKAGE_ROOT }, settings.defaultBrain, { catalog: catalog?.peek?.() || null });
3247
3314
  const enabled = await enabledBrain(requested, { fallback: fallback === true, named: !!brain?.model });
3248
- const normalized = await resolveAutoAccount(enabled.brain);
3315
+ const normalized = await startingAccount(enabled.brain);
3249
3316
  const record = {
3250
3317
  id, brain: normalized, title: label ? clip(label, 60) : DEFAULT_SESSION_TITLE, project: detectProject(normalized.cwd) || 'global',
3251
3318
  createdAt: iso(now()), updatedAt: iso(now()), lastActiveAt: null, status: 'idle', providerSessionId: null, providerThreadId: null,
@@ -3333,9 +3400,13 @@ export function createAssistantRuntime({
3333
3400
  if ('agentDensity' in patch) applyAgentDensity(live, patch.agentDensity); // agents-p4
3334
3401
  if (patch.brain && typeof patch.brain === 'object') {
3335
3402
  // A provider switch that names no model starts from the new provider's
3336
- // default, never from the old provider's model id.
3403
+ // default, never from the old provider's model id. The same for the account: an
3404
+ // id is one provider's (a Claude account id means nothing to Codex), so a switch
3405
+ // that names none runs on the new provider's Default account.
3337
3406
  const switching = BRAIN_PROVIDERS.has(patch.brain.provider) && patch.brain.provider !== live.record.brain.provider;
3338
- const base = switching && !patch.brain.model ? { ...live.record.brain, model: null } : live.record.brain;
3407
+ const base = switching
3408
+ ? { ...live.record.brain, ...(!patch.brain.model ? { model: null } : {}), accountId: null, accountPolicy: 'manual' }
3409
+ : live.record.brain;
3339
3410
  // Public picker updates use arrays; stored records still convert on read.
3340
3411
  const input = { ...base, ...patch.brain, model: patch.brain.model || base.model };
3341
3412
  if (patch.brain.mcpProfile !== undefined) throw Object.assign(new Error('Use tools: [group ids].'), { code: 'MCP_PROFILE_REMOVED', status: 400 });
@@ -151,6 +151,10 @@ export function createUserContextStore({
151
151
  return ensured;
152
152
  }
153
153
 
154
+ // The reads below say `+trashed_at IS NULL`: the plus keeps SQLite from choosing the index on `trashed_at` (it has
155
+ // no statistics, and that index names every live memory: 36,868 rows read whole to find 217, 30 ms on an idle
156
+ // machine and 1-3.8 s on a busy one, on the server's thread, 27 times in a day's stall log). With it the category's
157
+ // index is used: the same rows in under 2 ms.
154
158
  /** Every live, not superseded memory of the knowledge categories, parsed, newest first. Cached for 5 s. */
155
159
  function listKnowledge({ fresh = false } = {}) {
156
160
  if (!fresh && cache && Date.now() - cache.at < CACHE_MS) return cache.rows;
@@ -162,13 +166,13 @@ export function createUserContextStore({
162
166
  rows = db.prepare(`SELECT m.id, m.content, m.category, m.subcategory, m.project, m.importance, m.created_at, m.updated_at, m.related_memory_ids,
163
167
  md.kind, md.source_ref, (SELECT MAX(r.revision) FROM memory_revisions r WHERE r.memory_id = m.id) AS revision
164
168
  FROM memories m LEFT JOIN memory_metadata md ON md.memory_id = m.id
165
- WHERE m.trashed_at IS NULL AND m.category IN (${marks(names.length)})
169
+ WHERE +m.trashed_at IS NULL AND m.category IN (${marks(names.length)})
166
170
  AND NOT EXISTS (SELECT 1 FROM memory_relations s WHERE s.kind = 'supersedes' AND s.active = 1 AND s.to_id = m.id)
167
171
  ORDER BY m.updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
168
172
  } catch {
169
173
  // A store without the v2 tables: the memories alone.
170
174
  rows = db.prepare(`SELECT id, content, category, subcategory, project, importance, created_at, updated_at, related_memory_ids
171
- FROM memories WHERE trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
175
+ FROM memories WHERE +trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
172
176
  }
173
177
  } catch (error) { log('user-context:read-error', error?.message || String(error)); rows = []; }
174
178
  const parsed = rows.map((row) => parseKnowledge(row)).filter((item) => item.id && item.statement);
@@ -196,7 +200,7 @@ export function createUserContextStore({
196
200
  const names = categories();
197
201
  let vectors = [];
198
202
  try {
199
- vectors = getDb().prepare(`SELECT id, vector FROM memories WHERE trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
203
+ vectors = getDb().prepare(`SELECT id, vector FROM memories WHERE +trashed_at IS NULL AND category IN (${marks(names.length)}) ORDER BY updated_at DESC LIMIT ?`).all(...names, DIGEST.readLimit);
200
204
  } catch (error) { log('user-context:read-error', error?.message || String(error)); return []; }
201
205
  let query = null;
202
206
  try { query = await embed(String(text ?? '').slice(0, LEARN.messageClip)); } catch (error) { log('user-context:embed-error', error?.message || String(error)); return []; }
@@ -1,4 +1,5 @@
1
1
  import { redactProviderSecrets } from './provider-panel-api-key-auth.js';
2
+ import { timeBlockingWork } from './loop-stall.js';
2
3
  import { applyClaudeLaunchEnv, CLAUDE_CREDENTIAL_ENV } from './claude-accounts.js';
3
4
  import { claudeStallSeconds } from './claude-stall-policy.js';
4
5
  import { detectProject as memoryProject } from '../../mcp-server/dist/config.js';
@@ -769,6 +770,10 @@ export class ClaudeSession {
769
770
  try { token = deps.terminalTokens.rotate(this.synabunOwnerKey) || null; } catch { token = null; }
770
771
  if (token) {
771
772
  this._terminalToken = token;
773
+ // The registry holds a proof for this tab from now on, whatever a later start does (one without the SynaBun
774
+ // server resets _terminalToken above and mints nothing): destroy() revokes by this, so that proof never
775
+ // outlives the tab as a secret the scrubbers keep looking for.
776
+ this._terminalTokenIssued = true;
772
777
  options.mcpServers.SynaBun.headers[TERMINAL_TOKEN_HEADER_NAME] = `\${${TERMINAL_TOKEN_ENV_NAME}}`;
773
778
  options.env = { ...options.env, [TERMINAL_TOKEN_ENV_NAME]: token };
774
779
  }
@@ -922,7 +927,9 @@ export class ClaudeSession {
922
927
  // client — its late results would corrupt the new query's turn accounting.
923
928
  if (this.q !== q) break;
924
929
  this.lastEventTime = Date.now();
925
- try { this._translate(m); } catch (err) { log('translate error:', err.message); }
930
+ // One SDK message translated, redacted and sent on, on the server's own thread: timed by name, so a stall
931
+ // of the event loop names it (lib/loop-stall.js).
932
+ try { timeBlockingWork('claude:sdk-message', () => this._translate(m)); } catch (err) { log('translate error:', err.message); }
926
933
  }
927
934
  // Generator ended (input closed / process exit). If a turn was in flight
928
935
  // and this wasn't a deliberate teardown, surface it.
@@ -3360,7 +3367,11 @@ export class ClaudeSession {
3360
3367
  // grace-reap once no owners remain. Best-effort, in-process on the NI side.
3361
3368
  try { deps.releaseBrowserOwner?.(this.synabunOwnerKey); } catch {}
3362
3369
  // The tab's terminal token ends with its session (nothing may act as it from now on).
3363
- if (this.panel && this._terminalToken) { try { deps.terminalTokens?.revoke?.(this.synabunOwnerKey); } catch {} this._terminalToken = null; }
3370
+ if (this.panel && (this._terminalToken || this._terminalTokenIssued)) {
3371
+ try { deps.terminalTokens?.revoke?.(this.synabunOwnerKey); } catch {}
3372
+ this._terminalToken = null;
3373
+ this._terminalTokenIssued = false;
3374
+ }
3364
3375
  _allSessions.delete(this);
3365
3376
  }
3366
3377
  }