busybits 0.0.0-stage → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +26 -0
- package/CHANGELOG.md +692 -0
- package/LICENSE +21 -0
- package/README.es.md +1457 -0
- package/README.fr.md +1435 -0
- package/README.md +1623 -2
- package/README.pt-BR.md +1373 -0
- package/dist/build.json +5 -0
- package/dist/cli/busybits.js +14724 -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-CoDOLwxe.css +1 -0
- package/dist/client/bundle/app-QYGBa260.js +24 -0
- package/dist/client/bundle/city-DPTwQLdi.css +1 -0
- package/dist/client/bundle/city-UYDbxWIy.js +1 -0
- package/dist/client/bundle/daystats-CJyNq6hu.js +1 -0
- package/dist/client/bundle/dom-slmnBOjx.js +1 -0
- package/dist/client/bundle/en-BQQEHqmG.js +169 -0
- package/dist/client/bundle/es-BgBoKwEe.js +169 -0
- package/dist/client/bundle/format-CvlPqloO.js +1 -0
- package/dist/client/bundle/fr-PI_gjIFq.js +169 -0
- package/dist/client/bundle/main-DTHUta25.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-9pL54zR0.js +16 -0
- package/dist/client/bundle/ptypane-BrP-ENHg.css +1 -0
- package/dist/client/bundle/room-name-Bv6N672f.js +1 -0
- package/dist/client/bundle/simulator-B45JPgSp.js +7 -0
- package/dist/client/bundle/world-model-BgjMjmrp.js +1 -0
- package/dist/client/bundle/world-stream-CUfry7aL.js +1 -0
- package/dist/client/index.html +41 -0
- package/dist/client/manifest.webmanifest +17 -0
- package/dist/server/index.js +40342 -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 +100 -4
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Hook do Habblaud para o OpenAI Codex (CLI `codex` e o app desktop, que gravam no mesmo CODEX_HOME): mostra no
|
|
3
|
+
// escritório o que as sessões do Codex fazem e deixa aprovar ou recusar pelo escritório os pedidos de aprovação
|
|
4
|
+
// (PermissionRequest). `npm run codex:install` acrescenta em <CODEX_HOME>/hooks.json, no FIM da lista de cada evento,
|
|
5
|
+
// um grupo que roda:
|
|
6
|
+
//
|
|
7
|
+
// node "/caminho/do/habblaud/mod/habblaud-codex/hook.mjs"
|
|
8
|
+
//
|
|
9
|
+
// O comando nunca leva opções: o Codex guarda a confiança de cada hook (aprovada por você em /hooks) num hash que
|
|
10
|
+
// inclui o comando. Porta e espera ficam em ~/.habblaud/codex-hook.json ({port, permissionTimeoutS}, gravado pelo
|
|
11
|
+
// instalador); HABBLAUD_PORT vale como reserva (o ambiente do hook é o do processo que subiu o daemon do Codex, então
|
|
12
|
+
// variáveis exportadas no seu shell nem sempre chegam aqui).
|
|
13
|
+
//
|
|
14
|
+
// O hook:
|
|
15
|
+
// 1. lê do stdin o JSON do evento (session_id, hook_event_name, cwd, transcript_path...);
|
|
16
|
+
// 2. manda o evento, com os textos cortados, para POST http://127.0.0.1:<porta>/api/codex/events (prazo curto), com
|
|
17
|
+
// a conta (basename do CODEX_HOME, como o servidor calcula) e o caminho do CODEX_HOME;
|
|
18
|
+
// 3. só no PermissionRequest: registra o pedido em POST /api/permissions (provider "codex") e espera a decisão em
|
|
19
|
+
// GET /api/permissions/:id/wait até a espera do arquivo (padrão 25 s, entre 5 e 120). Aprovado: imprime a decisão
|
|
20
|
+
// allow; recusado: deny com o motivo. Qualquer outra coisa ("responder no terminal", tempo esgotado, Habblaud fora
|
|
21
|
+
// do ar ou sem página aberta): sai sem imprimir nada e o Codex segue a aprovação normal. Atenção: o Codex só mostra
|
|
22
|
+
// a aprovação no terminal DEPOIS que o hook termina (enquanto isso, o terminal mostra o statusMessage do hook).
|
|
23
|
+
//
|
|
24
|
+
// Regras: Node puro (22+), só `node:*`, sem dependências; nunca trava nem quebra a sessão: todo erro = sair com 0 e
|
|
25
|
+
// sem saída (nunca com 2, que no Codex recusa o pedido). Nunca imprime updatedInput, updatedPermissions nem interrupt
|
|
26
|
+
// (o Codex não os aceita: o hook "falha" sem decidir). Nos eventos de observação, nada vai para o stdout (no
|
|
27
|
+
// UserPromptSubmit e no SessionStart ele viraria contexto do modelo). Só fala com 127.0.0.1.
|
|
28
|
+
// HABBLAUD_HOOK_DEBUG=1 escreve o que acontece no stderr.
|
|
29
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
30
|
+
import { homedir } from 'node:os';
|
|
31
|
+
import { basename, isAbsolute, join, resolve } from 'node:path';
|
|
32
|
+
import { fileURLToPath } from 'node:url';
|
|
33
|
+
|
|
34
|
+
export const DEFAULT_PORT = 4747;
|
|
35
|
+
/** Espera padrão por uma decisão no escritório (segundos). */
|
|
36
|
+
export const DEFAULT_WAIT_S = 25;
|
|
37
|
+
export const MIN_WAIT_S = 5;
|
|
38
|
+
export const MAX_WAIT_S = 120;
|
|
39
|
+
/** Arquivo de configuração, em ~/.habblaud (o instalador grava). */
|
|
40
|
+
export const CONFIG_FILE = 'codex-hook.json';
|
|
41
|
+
/** Eventos mandados ao Habblaud (o PermissionRequest também, antes de registrar o pedido). */
|
|
42
|
+
export const OBSERVED = new Set(['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'PreToolUse', 'PostToolUse', 'Stop', 'SubagentStart', 'SubagentStop', 'PermissionRequest']);
|
|
43
|
+
/** Prazo do envio de um evento: o Habblaud responde na hora (e o hook não pode atrasar o Codex). */
|
|
44
|
+
const EVENT_TIMEOUT_MS = 1_500;
|
|
45
|
+
/** O SessionEnd tem só 1 s no Codex (e roda sempre em primeiro plano). */
|
|
46
|
+
const SESSION_END_TIMEOUT_MS = 600;
|
|
47
|
+
/** Registrar o pedido: se o Habblaud não responder nisso, ele está fora do ar (ou travado). */
|
|
48
|
+
const REGISTER_TIMEOUT_MS = 2_000;
|
|
49
|
+
/** Espera máxima de cada long-poll (o servidor responde "pending" e o hook pergunta de novo). */
|
|
50
|
+
const POLL_S = 25;
|
|
51
|
+
const STDIN_TIMEOUT_MS = 5_000;
|
|
52
|
+
const MAX_STDIN = 8 * 1024 * 1024;
|
|
53
|
+
/** Textos do evento e dos argumentos mandados ao Habblaud (o servidor só mostra prévias). */
|
|
54
|
+
const MAX_STRING = 8_000;
|
|
55
|
+
/** Corpo do pedido (o servidor recusa acima de 256 KB). */
|
|
56
|
+
const MAX_BODY = 200_000;
|
|
57
|
+
|
|
58
|
+
const debug = process.env.HABBLAUD_HOOK_DEBUG === '1' ? (msg) => process.stderr.write(`[habblaud-codex] ${msg}\n`) : () => {};
|
|
59
|
+
|
|
60
|
+
const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
61
|
+
const validPort = (p) => Number.isInteger(p) && p > 0 && p < 65_536;
|
|
62
|
+
|
|
63
|
+
/** Caminho absoluto, com `~`/`$HOME` expandidos e sem barra final (como o servidor normaliza as pastas das contas). */
|
|
64
|
+
function expandHome(p, home) {
|
|
65
|
+
const abs = resolve(p.trim().replace(/^~(?=[\\/]|$)/, home).replace(/\$\{HOME\}|\$HOME\b/g, home));
|
|
66
|
+
return abs.length > 1 ? abs.replace(/[\\/]+$/, '') : abs;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Porta e espera: ~/.habblaud/codex-hook.json ({port, permissionTimeoutS}); sem porta no arquivo, HABBLAUD_PORT;
|
|
71
|
+
* senão os padrões. Arquivo ausente ou ilegível = padrões.
|
|
72
|
+
*/
|
|
73
|
+
export function readConfig(env = process.env) {
|
|
74
|
+
const home = env.HOME || homedir();
|
|
75
|
+
let file;
|
|
76
|
+
try {
|
|
77
|
+
file = JSON.parse(readFileSync(join(home, '.habblaud', CONFIG_FILE), 'utf8'));
|
|
78
|
+
} catch {
|
|
79
|
+
file = undefined;
|
|
80
|
+
}
|
|
81
|
+
const f = isObject(file) ? file : {};
|
|
82
|
+
const filePort = Number(f.port);
|
|
83
|
+
const envPort = Number.parseInt(env.HABBLAUD_PORT ?? '', 10);
|
|
84
|
+
const wait = Number(f.permissionTimeoutS);
|
|
85
|
+
return {
|
|
86
|
+
port: validPort(filePort) ? filePort : validPort(envPort) ? envPort : DEFAULT_PORT,
|
|
87
|
+
waitMs: (Number.isFinite(wait) && wait > 0 ? Math.min(MAX_WAIT_S, Math.max(MIN_WAIT_S, wait)) : DEFAULT_WAIT_S) * 1_000,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* CODEX_HOME da sessão: a variável, se veio; senão a pasta acima de sessions/AAAA/MM/DD/ (ou de archived_sessions/)
|
|
93
|
+
* no transcript_path; senão ~/.codex.
|
|
94
|
+
*/
|
|
95
|
+
export function codexHomeOf(env, input) {
|
|
96
|
+
const home = env.HOME || homedir();
|
|
97
|
+
const fromEnv = typeof env.CODEX_HOME === 'string' ? env.CODEX_HOME.trim() : '';
|
|
98
|
+
if (fromEnv) return expandHome(fromEnv, home);
|
|
99
|
+
const t = typeof input?.transcript_path === 'string' ? input.transcript_path : '';
|
|
100
|
+
const m = /^(.+)[\\/]sessions[\\/]\d{4}[\\/]\d{2}[\\/]\d{2}[\\/][^\\/]+$/.exec(t) ?? /^(.+)[\\/]archived_sessions[\\/][^\\/]+$/.exec(t);
|
|
101
|
+
if (m && isAbsolute(m[1])) return expandHome(m[1], home);
|
|
102
|
+
return join(home, '.codex');
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Id da conta = basename do CODEX_HOME (como o servidor dá ids às contas; colisões ele resolve pelo caminho). */
|
|
106
|
+
export function accountOf(codexHome) {
|
|
107
|
+
return basename(codexHome) || codexHome;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Corta textos longos (saída de comando, patch enorme...). */
|
|
111
|
+
export function trimInput(v, max = MAX_STRING, depth = 0) {
|
|
112
|
+
if (typeof v === 'string') return v.length > max ? v.slice(0, max) : v;
|
|
113
|
+
if (depth > 8 || v === null || typeof v !== 'object') return v;
|
|
114
|
+
if (Array.isArray(v)) return v.slice(0, 200).map((x) => trimInput(x, max, depth + 1));
|
|
115
|
+
const out = {};
|
|
116
|
+
for (const [k, x] of Object.entries(v)) out[k] = trimInput(x, max, depth + 1);
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** O valor com os textos cortados; se ainda ficar grande demais no corpo, corta mais curto. */
|
|
121
|
+
function fitted(v, size) {
|
|
122
|
+
let out = v;
|
|
123
|
+
for (const max of [MAX_STRING, 1_000, 200]) {
|
|
124
|
+
out = trimInput(v, max);
|
|
125
|
+
if (size(out) <= MAX_BODY) break;
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Corpo de POST /api/codex/events: o stdin do hook inteiro, com os textos cortados. */
|
|
131
|
+
export function eventBody(input, account, codexHome) {
|
|
132
|
+
const body = { account, codexHome, event: input };
|
|
133
|
+
body.event = fitted(input, (event) => JSON.stringify({ ...body, event }).length);
|
|
134
|
+
return body;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Corpo de POST /api/permissions: só o que o Habblaud usa (nada do transcript_path). */
|
|
138
|
+
export function permissionBody(input, account, codexHome, timeoutMs) {
|
|
139
|
+
const body = { provider: 'codex', account, codexHome, session_id: input.session_id, tool_name: input.tool_name, tool_input: {}, timeout_ms: timeoutMs };
|
|
140
|
+
for (const k of ['agent_id', 'agent_type', 'cwd', 'turn_id']) if (typeof input[k] === 'string') body[k] = input[k];
|
|
141
|
+
body.tool_input = fitted(isObject(input.tool_input) ? input.tool_input : {}, (toolInput) => JSON.stringify({ ...body, tool_input: toolInput }).length);
|
|
142
|
+
return body;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Saída do hook para uma decisão do Habblaud (undefined = sair sem decidir). Só allow e deny (+ message). */
|
|
146
|
+
export function decisionOutput(result) {
|
|
147
|
+
if (!result || result.status !== 'decided') return undefined;
|
|
148
|
+
if (result.behavior === 'allow') return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'allow' } } };
|
|
149
|
+
if (result.behavior === 'deny') {
|
|
150
|
+
const reason = typeof result.message === 'string' && result.message.trim() ? result.message.trim().slice(0, 1_000) : '';
|
|
151
|
+
const message = reason ? `Recusado pelo usuário no Habblaud: ${reason}` : 'Recusado pelo usuário no Habblaud.';
|
|
152
|
+
return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision: { behavior: 'deny', message } } };
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function readStdin() {
|
|
158
|
+
return new Promise((ok) => {
|
|
159
|
+
const chunks = [];
|
|
160
|
+
let size = 0;
|
|
161
|
+
const finish = (text) => {
|
|
162
|
+
clearTimeout(timer);
|
|
163
|
+
ok(text);
|
|
164
|
+
};
|
|
165
|
+
const timer = setTimeout(() => finish(undefined), STDIN_TIMEOUT_MS);
|
|
166
|
+
process.stdin.on('data', (c) => {
|
|
167
|
+
size += c.length;
|
|
168
|
+
if (size > MAX_STDIN) return finish(undefined);
|
|
169
|
+
chunks.push(c);
|
|
170
|
+
});
|
|
171
|
+
process.stdin.on('end', () => finish(Buffer.concat(chunks).toString('utf8')));
|
|
172
|
+
process.stdin.on('error', () => finish(undefined));
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Requisição ao Habblaud local; null = fora do ar, tempo esgotado ou resposta ilegível. */
|
|
177
|
+
async function call(base, method, path, body, timeoutMs) {
|
|
178
|
+
try {
|
|
179
|
+
const res = await fetch(`${base}${path}`, {
|
|
180
|
+
method,
|
|
181
|
+
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
|
|
182
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
183
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
184
|
+
});
|
|
185
|
+
const text = await res.text();
|
|
186
|
+
let json;
|
|
187
|
+
try {
|
|
188
|
+
json = text ? JSON.parse(text) : undefined;
|
|
189
|
+
} catch {
|
|
190
|
+
json = undefined;
|
|
191
|
+
}
|
|
192
|
+
return { status: res.status, json };
|
|
193
|
+
} catch (err) {
|
|
194
|
+
debug(`${method} ${path}: ${err?.name ?? 'erro'} ${err?.message ?? ''}`);
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Manda o evento e, no PermissionRequest, decide o pedido (ou não). Devolve a saída a imprimir, ou undefined. Nunca lança. */
|
|
200
|
+
export async function run(env = process.env, stdinText) {
|
|
201
|
+
const startedAt = Date.now();
|
|
202
|
+
try {
|
|
203
|
+
const raw = stdinText ?? (await readStdin());
|
|
204
|
+
if (!raw) return undefined;
|
|
205
|
+
let input;
|
|
206
|
+
try {
|
|
207
|
+
input = JSON.parse(raw);
|
|
208
|
+
} catch {
|
|
209
|
+
return undefined;
|
|
210
|
+
}
|
|
211
|
+
if (!isObject(input) || typeof input.hook_event_name !== 'string' || typeof input.session_id !== 'string' || !input.session_id) return undefined;
|
|
212
|
+
const event = input.hook_event_name;
|
|
213
|
+
if (!OBSERVED.has(event)) return undefined;
|
|
214
|
+
|
|
215
|
+
const cfg = readConfig(env);
|
|
216
|
+
const codexHome = codexHomeOf(env, input);
|
|
217
|
+
const account = accountOf(codexHome);
|
|
218
|
+
const base = `http://127.0.0.1:${cfg.port}`;
|
|
219
|
+
const sent = await call(base, 'POST', '/api/codex/events', eventBody(input, account, codexHome), event === 'SessionEnd' ? SESSION_END_TIMEOUT_MS : EVENT_TIMEOUT_MS);
|
|
220
|
+
debug(`${event}: ${sent ? `${sent.status} ${JSON.stringify(sent.json ?? null)}` : 'Habblaud fora do ar'}`);
|
|
221
|
+
if (event !== 'PermissionRequest' || typeof input.tool_name !== 'string' || !input.tool_name) return undefined;
|
|
222
|
+
// Sem resposta nem ao evento: o Habblaud está fora do ar (ou travado); a aprovação segue no terminal.
|
|
223
|
+
if (!sent) return undefined;
|
|
224
|
+
|
|
225
|
+
// A espera conta desde o início do hook (o Codex só mostra a aprovação no terminal quando ele termina).
|
|
226
|
+
const deadline = startedAt + cfg.waitMs;
|
|
227
|
+
const reg = await call(base, 'POST', '/api/permissions', permissionBody(input, account, codexHome, Math.max(0, deadline - Date.now())), REGISTER_TIMEOUT_MS);
|
|
228
|
+
if (!reg || reg.status !== 201 || typeof reg.json?.id !== 'string') {
|
|
229
|
+
debug(`sem desvio (${reg ? `${reg.status} ${JSON.stringify(reg.json ?? null)}` : 'Habblaud fora do ar'})`);
|
|
230
|
+
return undefined;
|
|
231
|
+
}
|
|
232
|
+
const id = encodeURIComponent(reg.json.id);
|
|
233
|
+
for (;;) {
|
|
234
|
+
const left = deadline - Date.now();
|
|
235
|
+
if (left <= 0) {
|
|
236
|
+
debug('tempo esgotado: vale o terminal');
|
|
237
|
+
return undefined;
|
|
238
|
+
}
|
|
239
|
+
const waitS = Math.max(0.05, Math.min(POLL_S, left / 1_000));
|
|
240
|
+
const r = await call(base, 'GET', `/api/permissions/${id}/wait?timeout=${waitS}`, undefined, waitS * 1_000 + 5_000);
|
|
241
|
+
if (!r || r.status !== 200) return undefined;
|
|
242
|
+
if (r.json?.status === 'pending') continue;
|
|
243
|
+
debug(`resposta: ${JSON.stringify(r.json)}`);
|
|
244
|
+
return decisionOutput(r.json);
|
|
245
|
+
}
|
|
246
|
+
} catch (err) {
|
|
247
|
+
debug(`erro: ${err?.message ?? err}`);
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export async function main() {
|
|
253
|
+
const { waitMs } = readConfig();
|
|
254
|
+
// Rede de segurança: nada mantém o processo vivo além da espera (o Codex também tem o tempo limite do hook).
|
|
255
|
+
setTimeout(() => process.exit(0), waitMs + 15_000).unref();
|
|
256
|
+
const out = await run();
|
|
257
|
+
// Sem process.exit() logo depois do fetch: no Windows (Node 23 até 24.19) ele derruba o processo com 0xC0000409
|
|
258
|
+
// enquanto o V8 ainda compila em segundo plano o parser do fetch (nodejs/node#56645). O processo sai sozinho quando
|
|
259
|
+
// o loop esvazia, o que também espera a escrita da decisão no pipe; se algo ainda segurar o loop, o process.exit
|
|
260
|
+
// vem 1 s depois.
|
|
261
|
+
const finish = () => setTimeout(() => process.exit(0), 1_000).unref();
|
|
262
|
+
if (out) process.stdout.write(`${JSON.stringify(out)}\n`, finish);
|
|
263
|
+
else finish();
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function isMain() {
|
|
267
|
+
try {
|
|
268
|
+
return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
269
|
+
} catch {
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (isMain()) main().catch(() => process.exit(0));
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "busybits-messages",
|
|
3
|
+
"displayName": "Busybits: messages from the office",
|
|
4
|
+
"version": "2.0.1",
|
|
5
|
+
"description": "Delivers to the Claude Code session the messages you type in Busybits (agent panel or terminal), as if you had typed them in the terminal.",
|
|
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", "messages", "prompt"]
|
|
11
|
+
}
|