busybits 0.0.0-stage → 2.0.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.
- package/.claude-plugin/marketplace.json +26 -0
- package/CHANGELOG.md +675 -0
- package/LICENSE +21 -0
- package/README.es.md +1457 -0
- package/README.fr.md +1435 -0
- package/README.md +1605 -2
- package/README.pt-BR.md +1373 -0
- package/dist/build.json +5 -0
- package/dist/cli/busybits.js +14708 -0
- package/dist/client/assets/art/framed/painting-abstract.png +0 -0
- package/dist/client/assets/art/framed/painting-beach.png +0 -0
- package/dist/client/assets/art/framed/painting-cat.png +0 -0
- package/dist/client/assets/art/framed/painting-city-night.png +0 -0
- package/dist/client/assets/art/framed/painting-mountains.png +0 -0
- package/dist/client/assets/art/framed/painting-rio.png +0 -0
- package/dist/client/assets/art/framed/painting-sunflowers.png +0 -0
- package/dist/client/assets/art/framed/painting-wave.png +0 -0
- package/dist/client/assets/art/framed/painting-wide-aurora.png +0 -0
- package/dist/client/assets/art/framed/painting-wide-color-fields.png +0 -0
- package/dist/client/assets/art/framed/painting-wide-forest-lake.png +0 -0
- package/dist/client/assets/art/painting-abstract.png +0 -0
- package/dist/client/assets/art/painting-beach.png +0 -0
- package/dist/client/assets/art/painting-cat.png +0 -0
- package/dist/client/assets/art/painting-city-night.png +0 -0
- package/dist/client/assets/art/painting-mountains.png +0 -0
- package/dist/client/assets/art/painting-rio.png +0 -0
- package/dist/client/assets/art/painting-sunflowers.png +0 -0
- package/dist/client/assets/art/painting-wave.png +0 -0
- package/dist/client/assets/art/painting-wide-aurora.png +0 -0
- package/dist/client/assets/art/painting-wide-color-fields.png +0 -0
- package/dist/client/assets/art/painting-wide-forest-lake.png +0 -0
- package/dist/client/assets/art/poster-bug.png +0 -0
- package/dist/client/assets/art/poster-cat.png +0 -0
- package/dist/client/assets/art/poster-code.png +0 -0
- package/dist/client/assets/art/poster-coffee.png +0 -0
- package/dist/client/assets/art/poster-rocket.png +0 -0
- package/dist/client/assets/art/poster-ship-it.png +0 -0
- package/dist/client/assets/brand/apple-touch-icon.png +0 -0
- package/dist/client/assets/brand/favicon-16.png +0 -0
- package/dist/client/assets/brand/favicon-32.png +0 -0
- package/dist/client/assets/brand/icon-192.png +0 -0
- package/dist/client/assets/brand/icon-512.png +0 -0
- package/dist/client/assets/brand/logo-detailed.png +0 -0
- package/dist/client/assets/brand/logo-mark.png +0 -0
- package/dist/client/assets/brand/logo-mark@4x.png +0 -0
- package/dist/client/assets/brand/signage.png +0 -0
- package/dist/client/assets/brand/signage@4x.png +0 -0
- package/dist/client/assets/emoji/LICENSE-SerenityOS.txt +28 -0
- package/dist/client/assets/emoji/sheet.png +0 -0
- package/dist/client/assets/illustrations/empty-office.png +0 -0
- package/dist/client/assets/manifest.json +260 -0
- package/dist/client/assets/og-image.png +0 -0
- package/dist/client/bundle/app-AwZeKIeu.js +24 -0
- package/dist/client/bundle/app-CoDOLwxe.css +1 -0
- package/dist/client/bundle/city-DPTwQLdi.css +1 -0
- package/dist/client/bundle/city-YoIG0FsX.js +1 -0
- package/dist/client/bundle/daystats-DGzYOP8l.js +1 -0
- package/dist/client/bundle/dom-D2vx0KTo.js +1 -0
- package/dist/client/bundle/en-DBfNt5uV.js +169 -0
- package/dist/client/bundle/es-pnWdszTE.js +169 -0
- package/dist/client/bundle/format-C7qb6Cn-.js +1 -0
- package/dist/client/bundle/fr-CY8q9pj4.js +169 -0
- package/dist/client/bundle/main-DktU0GfB.js +2 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-400-normal-Ckz2YJkH.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-500-normal--wrb4dVK.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-500-normal-CR9SIKMr.woff +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-600-normal-B3EuUOZG.woff +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-600-normal-BhqNJYOZ.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-700-normal-BrZTw8tu.woff +0 -0
- package/dist/client/bundle/pixelify-sans-cyrillic-700-normal-CYtG5Rfp.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-500-normal-Bq6pAlou.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-500-normal-DC052d-m.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-600-normal-BNlgYbDL.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-600-normal-Dd_Dy7u5.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-700-normal-BctWAS0u.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-700-normal-D3Xxx3QE.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-500-normal-BHT4w5qI.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-500-normal-Bkr-oq6R.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-600-normal-CDaIumwU.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-600-normal-Dha6RiOG.woff2 +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-700-normal-BadXkHzZ.woff +0 -0
- package/dist/client/bundle/pixelify-sans-latin-ext-700-normal-ClyJstAh.woff2 +0 -0
- package/dist/client/bundle/ptypane-BrP-ENHg.css +1 -0
- package/dist/client/bundle/ptypane-NIZ2Y8QM.js +16 -0
- package/dist/client/bundle/room-name-CFJfHE5L.js +1 -0
- package/dist/client/bundle/simulator-BnBPS_Ws.js +7 -0
- package/dist/client/bundle/world-model-BIYmgAWC.js +1 -0
- package/dist/client/bundle/world-stream-BRkL9Eme.js +1 -0
- package/dist/client/index.html +41 -0
- package/dist/client/manifest.webmanifest +17 -0
- package/dist/server/index.js +40327 -0
- package/mod/README.md +193 -0
- package/mod/habblaud/.claude-plugin/plugin.json +11 -0
- package/mod/habblaud/hooks/hooks.json +4 -0
- package/mod/habblaud/hooks/register.ts +517 -0
- package/mod/habblaud-codex/hook.mjs +274 -0
- package/mod/habblaud-mensagens/.claude-plugin/plugin.json +11 -0
- package/mod/habblaud-mensagens/hooks/hooks.json +4 -0
- package/mod/habblaud-mensagens/hooks/register.ts +384 -0
- package/mod/habblaud-permissoes/.claude-plugin/plugin.json +11 -0
- package/mod/habblaud-permissoes/hooks/hooks.json +18 -0
- package/mod/habblaud-permissoes/hooks/permission-hook.mjs +265 -0
- package/mod/habblaud-pi/core.ts +325 -0
- package/mod/habblaud-pi/extension.ts +119 -0
- package/mod/habblaud-pi/package.json +12 -0
- package/package.json +96 -4
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
// Mensagens pelo escritório (Claude Code 2.1.287+): leva para a sessão o que você digita no Habblaud (no painel
|
|
2
|
+
// do agente ou no terminal da tecla T), como se você tivesse digitado no terminal.
|
|
3
|
+
//
|
|
4
|
+
// O que faz, e `claude plugin validate` lista exatamente o que o módulo chama (a saída está no mod/README.md):
|
|
5
|
+
//
|
|
6
|
+
// 1. A cada 2 s, só onde a sessão desenha (`$.session.surfaces()` vazia = `claude -p`/SDK: nada a fazer) ou numa
|
|
7
|
+
// sessão do app desktop (CLAUDE_CODE_ENTRYPOINT=claude-desktop: SDK por baixo, sem superfície fora da tela), pergunta
|
|
8
|
+
// ao Habblaud local se há mensagens para ela: POST http://127.0.0.1:<HABBLAUD_PORT ou 4747>/api/mod/inbox com
|
|
9
|
+
// {session, account}. A pergunta também marca a presença da sessão: é ela que acende, no escritório, a caixa de
|
|
10
|
+
// mensagem deste agente. Fora do ar, ou respondendo qualquer coisa que não seja 2xx (403 = mensagens desligadas
|
|
11
|
+
// no Habblaud; 404 = uma versão sem a rota), passa a perguntar a cada 30 s até ele voltar.
|
|
12
|
+
// 2. Cada mensagem, na ordem, vai para a sessão por `$.prompt.submit({ text, asUser: true })`: o modelo a lê como
|
|
13
|
+
// sua, sem o "The busybits-messages plugin sent a message" (o registro da sessão ainda nomeia o plugin). O
|
|
14
|
+
// texto vai exatamente como chegou. `{drop}` (um hook recusou) ou exceção = falha, com o motivo.
|
|
15
|
+
// Com a sessão no meio de um turno, o Claude Code guarda o prompt até ela ficar livre e a chamada pode demorar a
|
|
16
|
+
// voltar: a espera por mensagem é de no máximo 2 s. Passou disso, a mensagem está na fila da sessão e conta
|
|
17
|
+
// como entregue, e as seguintes da mesma rodada vão em seguida, na ordem, sem esperar. Assim a rodada nunca
|
|
18
|
+
// passa de uns poucos segundos: a presença (10 s no servidor) e a confirmação (30 s) não vencem por uma
|
|
19
|
+
// sessão ocupada. O preço: um hook que recuse a mensagem depois desses 2 s não chega ao escritório.
|
|
20
|
+
// Exceção: a mensagem que começa por `/nome argumentos` e cujo `nome` é um comando da sessão (`$.command.list()`)
|
|
21
|
+
// roda por `$.command.run({ command, args })`, como se você o tivesse digitado, em vez de virar prompt (o
|
|
22
|
+
// Claude Code recusa em `$.prompt.submit` qualquer texto que comece por `/`). Texto que começa por `/` e não é
|
|
23
|
+
// um comando da sessão (`/x`, `/etc/hosts`) falha com o motivo, sem ir à sessão. Se a lista de comandos não vem,
|
|
24
|
+
// quem decide é o próprio `$.command.run`, que rejeita nome desconhecido. Texto comum segue por
|
|
25
|
+
// `$.prompt.submit`, como sempre. Mesma espera de 2 s por mensagem. Comando que abre um menu interativo (/model
|
|
26
|
+
// sem argumento, /config) não tem o que mostrar no escritório.
|
|
27
|
+
// 3. Um único POST /api/mod/inbox/ack com {session, results: [{id, ok, error?}]}. Sem mensagens, sem ack.
|
|
28
|
+
// 4. Junto da rodada, publica a lista de comandos da sessão (nome, descrição, fonte e plugin) em
|
|
29
|
+
// POST /api/mod/commands com {session, account, commands}: é ela que alimenta o autocompletar da caixa de
|
|
30
|
+
// mensagem do Habblaud. Só quando a lista muda e, de minuto em minuto, para o Habblaud que reiniciou.
|
|
31
|
+
//
|
|
32
|
+
// Por que um plugin à parte do mod `habblaud`: aquele só observa (uso do plano, aviso embaixo do prompt,
|
|
33
|
+
// /habblaud) e nunca muda o que a sessão faz. Este age: digita na sessão em seu nome. Separado, dá para ficar sem
|
|
34
|
+
// ele (npm run mod:install -- --sem-mensagens) e a análise estática de cada um continua curta.
|
|
35
|
+
//
|
|
36
|
+
// Regras: nenhum hook lança (um hook que lança é pulado, mas o que ele deixou pela metade fica): cada passo tem seu
|
|
37
|
+
// try/catch e falha = silêncio. Uma rodada por vez (um Habblaud lento não acumula perguntas). Nada de $.process,
|
|
38
|
+
// $.model, $.fs, leitura da conversa nem decisão de ferramenta; a rede é só 127.0.0.1. O estado fica em variáveis
|
|
39
|
+
// do módulo: um hot reload recomeça do zero (uma mensagem buscada e não confirmada falha no servidor em 30 s).
|
|
40
|
+
// O Claude Code pode carregar o plugin de uma cópia só dele: os ajudantes de caminho são cópias dos de
|
|
41
|
+
// mod/habblaud/hooks/register.ts, não importações.
|
|
42
|
+
//
|
|
43
|
+
// Análise estática do Claude Code: cada chamada é escrita por extenso ($.noun.método), o nome do evento é
|
|
44
|
+
// sempre uma string literal e `$` só é passado para funções declaradas no topo deste arquivo.
|
|
45
|
+
import type { CommandInfo, EngineInterface, HttpResponse, Register } from 'claude-code'
|
|
46
|
+
|
|
47
|
+
/** Porta padrão do Habblaud (a mesma do servidor, do mod e do docker-compose). */
|
|
48
|
+
export const DEFAULT_PORT = 4747
|
|
49
|
+
/** Intervalo das perguntas ao Habblaud; fora do ar, recua para o segundo até ele voltar. */
|
|
50
|
+
export const POLL_MS = 2_000
|
|
51
|
+
export const OFFLINE_POLL_MS = 30_000
|
|
52
|
+
/** Quanto esperar o Habblaud local responder (`$.http.fetch` não aceita AbortSignal: a corrida é com um timer). */
|
|
53
|
+
export const FETCH_TIMEOUT_MS = 2_000
|
|
54
|
+
/** Quanto esperar `$.prompt.submit` voltar antes de dar a mensagem como na fila da sessão. */
|
|
55
|
+
export const SUBMIT_WAIT_MS = 2_000
|
|
56
|
+
/** Tamanho máximo do motivo de uma falha (vem de um hook ou de uma exceção; o texto da mensagem nunca é cortado). */
|
|
57
|
+
export const MAX_REASON = 500
|
|
58
|
+
/** Motivo da falha de uma mensagem que começa por `/` e não é um comando da sessão. */
|
|
59
|
+
export const UNKNOWN_COMMAND = 'a mensagem começa por "/" mas não é um comando desta sessão (para falar de um caminho, comece por outra palavra)'
|
|
60
|
+
/** De quanto em quanto tempo a lista de comandos é publicada de novo mesmo sem mudar (o Habblaud pode ter reiniciado). */
|
|
61
|
+
export const COMMANDS_REFRESH_MS = 60_000
|
|
62
|
+
|
|
63
|
+
/** Mensagem como POST /api/mod/inbox entrega (shared/types.ts, InboxMessage). */
|
|
64
|
+
export interface InboxMessage {
|
|
65
|
+
id: string
|
|
66
|
+
/** O texto como foi digitado; vazio quando o servidor mandou algo que não é texto. */
|
|
67
|
+
text: string
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Resultado de uma mensagem, como POST /api/mod/inbox/ack recebe. */
|
|
71
|
+
export interface AckResult {
|
|
72
|
+
id: string
|
|
73
|
+
ok: boolean
|
|
74
|
+
error?: string
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Desfecho de um `$.prompt.submit`. */
|
|
78
|
+
type Submitted = { ok: true } | { ok: false; error: string }
|
|
79
|
+
|
|
80
|
+
interface ModEnv {
|
|
81
|
+
/** Id da conta (o nome da pasta, como o servidor chama); ausente sem HOME (ou USERPROFILE) nem CLAUDE_CONFIG_DIR. */
|
|
82
|
+
accountId?: string
|
|
83
|
+
port: number
|
|
84
|
+
/** Sessão do app desktop do Claude (CLAUDE_CODE_ENTRYPOINT=claude-desktop): roda como SDK e só tem superfície
|
|
85
|
+
* enquanto está na tela do app, mas é interativa e recebe prompts mesmo assim. */
|
|
86
|
+
desktop: boolean
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ---------------------------------------------------------------------------------------------
|
|
90
|
+
// Funções puras (testadas em tests/habblaud-mensagens.test.ts)
|
|
91
|
+
// ---------------------------------------------------------------------------------------------
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Normaliza um caminho (barras repetidas, `.`, `..` e a barra do fim): o ambiente do mod não tem node:path. Cópia
|
|
95
|
+
* de mod/habblaud: caminhos do Windows (com drive ou UNC) saem com `/` e o drive conta como raiz; nos outros, `\`
|
|
96
|
+
* é parte do nome.
|
|
97
|
+
*/
|
|
98
|
+
export function normalizePath(p: string): string {
|
|
99
|
+
const win = /^(?:[A-Za-z]:|\\\\)/.test(p)
|
|
100
|
+
const slashed = win ? p.replace(/\\/g, '/') : p
|
|
101
|
+
const drive = /^[A-Za-z]:(?=\/|$)/.exec(slashed)?.[0] ?? (win && slashed.startsWith('//') ? '/' : '')
|
|
102
|
+
const rest = slashed.slice(drive.length)
|
|
103
|
+
const abs = rest.startsWith('/')
|
|
104
|
+
const out: string[] = []
|
|
105
|
+
for (const seg of rest.split('/')) {
|
|
106
|
+
if (!seg || seg === '.') continue
|
|
107
|
+
if (seg === '..') {
|
|
108
|
+
if (out.length && out[out.length - 1] !== '..') out.pop()
|
|
109
|
+
else if (!abs) out.push(seg)
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
out.push(seg)
|
|
113
|
+
}
|
|
114
|
+
const joined = out.join('/')
|
|
115
|
+
return drive + (abs ? `/${joined}` : joined || (drive ? '' : '.'))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** `~` no começo vira o HOME. */
|
|
119
|
+
function expandHome(p: string, home: string | undefined): string {
|
|
120
|
+
return home && /^~(?=[\\/]|$)/.test(p) ? home + p.slice(1) : p
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Config dir da conta: o primeiro item de CLAUDE_CONFIG_DIR (com `~` expandido) ou ~/.claude. */
|
|
124
|
+
export function configDirOf(claudeConfigDir: string | undefined, home: string | undefined): string | undefined {
|
|
125
|
+
const first = (claudeConfigDir ?? '').split(',')[0]?.trim() ?? ''
|
|
126
|
+
if (first) return normalizePath(expandHome(first, home))
|
|
127
|
+
return home ? normalizePath(`${home}/.claude`) : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Id da conta = nome da pasta (AccountInfo.id do servidor, ex.: ".claude-conta2"). */
|
|
131
|
+
export function accountIdOf(configDir: string): string | undefined {
|
|
132
|
+
const name = configDir.split('/').filter(Boolean).pop()
|
|
133
|
+
return name && name !== '.' && name !== '..' ? name : undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function portOf(raw: string | undefined): number {
|
|
137
|
+
const n = Number.parseInt(raw ?? '', 10)
|
|
138
|
+
return Number.isInteger(n) && n > 0 && n < 65_536 ? n : DEFAULT_PORT
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Corpo de POST /api/mod/inbox: a conta só quando se sabe qual é. */
|
|
142
|
+
export function inboxBody(session: string, account: string | undefined): string {
|
|
143
|
+
return JSON.stringify(account ? { session, account } : { session })
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Corpo de POST /api/mod/commands: a conta só quando se sabe qual é, e de cada comando só os quatro campos. */
|
|
147
|
+
export function commandsBody(session: string, account: string | undefined, list: readonly CommandInfo[]): string {
|
|
148
|
+
const commands = list.map((c) => ({ name: c.name, description: c.description, source: c.source, ...(c.plugin ? { plugin: c.plugin } : {}) }))
|
|
149
|
+
return JSON.stringify(account ? { session, account, commands } : { session, commands })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* `/nome argumentos` no começo do texto (espaços antes não contam, como no Claude Code): o nome e os argumentos
|
|
154
|
+
* aparados. Outra coisa (`oi /x`, `/etc/hosts`, `/`) = undefined. Se o nome é de um comando da sessão, quem decide é
|
|
155
|
+
* o chamador.
|
|
156
|
+
*/
|
|
157
|
+
export function parseSlash(text: string): { name: string; args: string } | undefined {
|
|
158
|
+
const m = /^\s*\/([^\s/]+)(?:\s+([\s\S]*))?$/.exec(text)
|
|
159
|
+
return m ? { name: m[1], args: (m[2] ?? '').trim() } : undefined
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Corpo de POST /api/mod/inbox/ack. */
|
|
163
|
+
export function ackBody(session: string, results: readonly AckResult[]): string {
|
|
164
|
+
return JSON.stringify({ session, results })
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Lê a resposta de POST /api/mod/inbox; fora do formato = undefined (vale "fora do ar"). Item sem id fica de fora
|
|
169
|
+
* (não há como confirmá-lo); com id e sem texto, entra com texto vazio, para ser confirmado como falha em vez de o
|
|
170
|
+
* servidor esperar 30 s.
|
|
171
|
+
*/
|
|
172
|
+
export function parseInbox(text: string): InboxMessage[] | undefined {
|
|
173
|
+
let j: unknown
|
|
174
|
+
try {
|
|
175
|
+
j = JSON.parse(text)
|
|
176
|
+
} catch {
|
|
177
|
+
return undefined
|
|
178
|
+
}
|
|
179
|
+
if (!j || typeof j !== 'object' || Array.isArray(j)) return undefined
|
|
180
|
+
const list = (j as Record<string, unknown>).messages
|
|
181
|
+
if (!Array.isArray(list)) return undefined
|
|
182
|
+
const out: InboxMessage[] = []
|
|
183
|
+
for (const item of list) {
|
|
184
|
+
if (!item || typeof item !== 'object') continue
|
|
185
|
+
const m = item as Record<string, unknown>
|
|
186
|
+
if (typeof m.id !== 'string' || !m.id) continue
|
|
187
|
+
out.push({ id: m.id, text: typeof m.text === 'string' ? m.text : '' })
|
|
188
|
+
}
|
|
189
|
+
return out
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** O motivo de uma falha numa linha só, com tamanho limitado: o texto de um `{drop}` ou a mensagem de uma exceção. */
|
|
193
|
+
export function reasonText(raw: unknown, fallback: string): string {
|
|
194
|
+
const msg = typeof raw === 'string' ? raw : raw && typeof (raw as { message?: unknown }).message === 'string' ? (raw as { message: string }).message : ''
|
|
195
|
+
const line = msg.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim()
|
|
196
|
+
if (!line) return fallback
|
|
197
|
+
return line.length > MAX_REASON ? `${line.slice(0, MAX_REASON - 1)}…` : line
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ---------------------------------------------------------------------------------------------
|
|
201
|
+
// Estado do módulo (some num hot reload) e o que fala com o Claude Code
|
|
202
|
+
// ---------------------------------------------------------------------------------------------
|
|
203
|
+
|
|
204
|
+
let env: ModEnv | undefined
|
|
205
|
+
let timer: { cancel: () => void } | undefined
|
|
206
|
+
let timerMs = 0
|
|
207
|
+
/** Uma rodada por vez: um Habblaud lento ou uma sessão ocupada não empilham rodadas. */
|
|
208
|
+
let polling = false
|
|
209
|
+
/** A última publicação de comandos (o corpo e quando): igual e recente = não publica de novo. */
|
|
210
|
+
let publishedBody: string | undefined
|
|
211
|
+
let publishedAt = 0
|
|
212
|
+
|
|
213
|
+
/** O ambiente da sessão, lido uma vez por carga (cada nome escrito por extenso, como a análise exige). */
|
|
214
|
+
async function readEnv($: EngineInterface): Promise<ModEnv> {
|
|
215
|
+
if (env) return env
|
|
216
|
+
// No Windows, HOME só existe se alguém o definir: vale o USERPROFILE (a mesma ordem do mod habblaud).
|
|
217
|
+
const home = (await $.env.get('HOME'))?.trim() || (await $.env.get('USERPROFILE'))?.trim() || undefined
|
|
218
|
+
const configDir = configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), home)
|
|
219
|
+
const next: ModEnv = {
|
|
220
|
+
port: portOf(await $.env.get('HABBLAUD_PORT')),
|
|
221
|
+
desktop: (await $.env.get('CLAUDE_CODE_ENTRYPOINT'))?.trim() === 'claude-desktop',
|
|
222
|
+
}
|
|
223
|
+
const accountId = configDir ? accountIdOf(configDir) : undefined
|
|
224
|
+
if (accountId) next.accountId = accountId
|
|
225
|
+
env = next
|
|
226
|
+
return next
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** O que `promise` resolver em até `ms`; passou disso, undefined (a promessa segue sozinha). */
|
|
230
|
+
async function waitAtMost<T>($: EngineInterface, promise: Promise<T>, ms: number): Promise<T | undefined> {
|
|
231
|
+
let wait: { cancel: () => void } | undefined
|
|
232
|
+
const timeout = new Promise<undefined>((resolve) => {
|
|
233
|
+
wait = $.clock.after(ms, () => resolve(undefined))
|
|
234
|
+
})
|
|
235
|
+
try {
|
|
236
|
+
return await Promise.race([promise, timeout])
|
|
237
|
+
} finally {
|
|
238
|
+
wait?.cancel()
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** POST de um JSON ao Habblaud local com prazo de 2 s: a resposta, ou undefined (fora do ar, travado). Nunca lança. */
|
|
243
|
+
async function postJson($: EngineInterface, port: number, path: string, body: string): Promise<HttpResponse | undefined> {
|
|
244
|
+
try {
|
|
245
|
+
const request = $.http.fetch(`http://127.0.0.1:${port}${path}`, {
|
|
246
|
+
method: 'POST',
|
|
247
|
+
// Sem o Content-Type, o guarda do servidor recusa o POST (415).
|
|
248
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
249
|
+
body,
|
|
250
|
+
})
|
|
251
|
+
return await waitAtMost($, request, FETCH_TIMEOUT_MS)
|
|
252
|
+
} catch {
|
|
253
|
+
return undefined
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Uma mensagem para a sessão, como se você a tivesse digitado. Nunca lança. */
|
|
258
|
+
async function submitOne($: EngineInterface, text: string): Promise<Submitted> {
|
|
259
|
+
try {
|
|
260
|
+
const r = await $.prompt.submit({ text, asUser: true })
|
|
261
|
+
if (typeof r?.drop === 'string') return { ok: false, error: reasonText(r.drop, 'um hook da sessão recusou a mensagem') }
|
|
262
|
+
return { ok: true }
|
|
263
|
+
} catch (err) {
|
|
264
|
+
return { ok: false, error: reasonText(err, 'a sessão não aceitou a mensagem') }
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Um comando de barra da sessão, como se você o tivesse digitado. Nunca lança. */
|
|
269
|
+
async function runOne($: EngineInterface, command: string, args: string): Promise<Submitted> {
|
|
270
|
+
try {
|
|
271
|
+
await $.command.run({ command, args })
|
|
272
|
+
return { ok: true }
|
|
273
|
+
} catch (err) {
|
|
274
|
+
return { ok: false, error: reasonText(err, 'a sessão não rodou o comando') }
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Os comandos da sessão agora, ou undefined se a lista não vem (em 2 s). Nunca lança. */
|
|
279
|
+
async function listCommands($: EngineInterface): Promise<CommandInfo[] | undefined> {
|
|
280
|
+
try {
|
|
281
|
+
const list = await waitAtMost($, $.command.list(), FETCH_TIMEOUT_MS)
|
|
282
|
+
return Array.isArray(list) ? list : undefined
|
|
283
|
+
} catch {
|
|
284
|
+
return undefined
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Publica a lista no Habblaud se ela mudou ou se passou COMMANDS_REFRESH_MS. Falhou = tenta no próximo prazo. Nunca lança. */
|
|
289
|
+
async function publishCommands($: EngineInterface, e: ModEnv, session: string, list: readonly CommandInfo[]): Promise<void> {
|
|
290
|
+
try {
|
|
291
|
+
const body = commandsBody(session, e.accountId, list)
|
|
292
|
+
const now = await $.clock.now()
|
|
293
|
+
if (body === publishedBody && now - publishedAt < COMMANDS_REFRESH_MS) return
|
|
294
|
+
publishedBody = body
|
|
295
|
+
publishedAt = now
|
|
296
|
+
await postJson($, e.port, '/api/mod/commands', body)
|
|
297
|
+
} catch {
|
|
298
|
+
// sem a lista, a caixa do Habblaud só não completa os comandos
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Manda as mensagens à sessão, na ordem, e devolve o resultado de cada uma. `commands` = os nomes dos comandos da
|
|
304
|
+
* sessão (undefined = a lista não veio): `/nome args` de um deles roda como comando; outro texto com `/` no começo
|
|
305
|
+
* falha; o resto vai como prompt. Nunca lança.
|
|
306
|
+
*/
|
|
307
|
+
async function deliver($: EngineInterface, messages: readonly InboxMessage[], commands: ReadonlySet<string> | undefined): Promise<AckResult[]> {
|
|
308
|
+
const results: AckResult[] = []
|
|
309
|
+
/** Uma chamada passou do prazo: a sessão está ocupada e as seguintes entram na fila atrás dela, sem esperar. */
|
|
310
|
+
let queued = false
|
|
311
|
+
for (const m of messages) {
|
|
312
|
+
if (!m.text.trim()) {
|
|
313
|
+
results.push({ id: m.id, ok: false, error: 'mensagem vazia' })
|
|
314
|
+
continue
|
|
315
|
+
}
|
|
316
|
+
const slash = parseSlash(m.text)
|
|
317
|
+
if (!(slash && (!commands || commands.has(slash.name))) && /^\s*\//.test(m.text)) {
|
|
318
|
+
results.push({ id: m.id, ok: false, error: UNKNOWN_COMMAND })
|
|
319
|
+
continue
|
|
320
|
+
}
|
|
321
|
+
const submitted = slash ? runOne($, slash.name, slash.args) : submitOne($, m.text)
|
|
322
|
+
if (queued) {
|
|
323
|
+
void submitted
|
|
324
|
+
results.push({ id: m.id, ok: true })
|
|
325
|
+
continue
|
|
326
|
+
}
|
|
327
|
+
const out = await waitAtMost($, submitted, SUBMIT_WAIT_MS)
|
|
328
|
+
if (!out) {
|
|
329
|
+
queued = true
|
|
330
|
+
results.push({ id: m.id, ok: true })
|
|
331
|
+
} else results.push(out.ok ? { id: m.id, ok: true } : { id: m.id, ok: false, error: out.error })
|
|
332
|
+
}
|
|
333
|
+
return results
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** (Re)agenda as rodadas: 2 s com o Habblaud no ar, 30 s fora do ar. */
|
|
337
|
+
function schedule($: EngineInterface, ms: number): void {
|
|
338
|
+
if (timer && timerMs === ms) return
|
|
339
|
+
timer?.cancel()
|
|
340
|
+
timerMs = ms
|
|
341
|
+
timer = $.clock.every(ms, () => {
|
|
342
|
+
void round($)
|
|
343
|
+
})
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Uma rodada: busca as mensagens desta sessão, manda cada uma e confirma. Nunca lança. */
|
|
347
|
+
async function round($: EngineInterface): Promise<void> {
|
|
348
|
+
if (polling) return
|
|
349
|
+
polling = true
|
|
350
|
+
try {
|
|
351
|
+
const e = await readEnv($)
|
|
352
|
+
const surfaces = await $.session.surfaces()
|
|
353
|
+
if (!surfaces.length && !e.desktop) return
|
|
354
|
+
const session = await $.session.id()
|
|
355
|
+
const res = await postJson($, e.port, '/api/mod/inbox', inboxBody(session, e.accountId))
|
|
356
|
+
const messages = res?.ok ? parseInbox(res.text) : undefined
|
|
357
|
+
if (!messages) {
|
|
358
|
+
schedule($, OFFLINE_POLL_MS)
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
schedule($, POLL_MS)
|
|
362
|
+
const list = await listCommands($)
|
|
363
|
+
if (list) void publishCommands($, e, session, list)
|
|
364
|
+
if (!messages.length) return
|
|
365
|
+
const results = await deliver($, messages, list ? new Set(list.map((c) => c.name)) : undefined)
|
|
366
|
+
// Falhou a confirmação: o servidor dá as mensagens como falhas em 30 s ("a sessão não confirmou a entrega").
|
|
367
|
+
await postJson($, e.port, '/api/mod/inbox/ack', ackBody(session, results))
|
|
368
|
+
} catch {
|
|
369
|
+
// silêncio: a próxima rodada tenta de novo
|
|
370
|
+
} finally {
|
|
371
|
+
polling = false
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export const register: Register = (on) => {
|
|
376
|
+
on('session.start', async ($, e, next) => {
|
|
377
|
+
try {
|
|
378
|
+
schedule($, POLL_MS)
|
|
379
|
+
} catch {
|
|
380
|
+
// sem as rodadas, a sessão segue como sempre
|
|
381
|
+
}
|
|
382
|
+
return next(e)
|
|
383
|
+
})
|
|
384
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "busybits-permissions",
|
|
3
|
+
"displayName": "Busybits: permissions from the office",
|
|
4
|
+
"version": "2.0.0",
|
|
5
|
+
"description": "PermissionRequest hook that lets you approve or deny Claude Code permission requests and answer AskUserQuestion prompts from Busybits; the dialog stays in the terminal and whichever answer comes first wins.",
|
|
6
|
+
"author": { "name": "Márcio Junior", "url": "https://github.com/marmottajr" },
|
|
7
|
+
"homepage": "https://github.com/marmottajr/habblaud#readme",
|
|
8
|
+
"repository": "https://github.com/marmottajr/habblaud",
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"keywords": ["busybits", "habblaud", "office", "permissions", "hooks"]
|
|
11
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "Responder pelo escritório: manda cada pedido de permissão (e pergunta do AskUserQuestion) para o Habblaud local (porta em HABBLAUD_PORT, padrão 4747) e espera a resposta por até 5 min (até 24 h com HABBLAUD_PERMISSION_TIMEOUT); fora do ar ou sem página aberta, sai na hora e vale o terminal.",
|
|
3
|
+
"hooks": {
|
|
4
|
+
"PermissionRequest": [
|
|
5
|
+
{
|
|
6
|
+
"matcher": "*",
|
|
7
|
+
"hooks": [
|
|
8
|
+
{
|
|
9
|
+
"type": "command",
|
|
10
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/permission-hook.mjs\"",
|
|
11
|
+
"timeout": 86430,
|
|
12
|
+
"statusMessage": "Aguardando resposta no Busybits"
|
|
13
|
+
}
|
|
14
|
+
]
|
|
15
|
+
}
|
|
16
|
+
]
|
|
17
|
+
}
|
|
18
|
+
}
|