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.
Files changed (111) hide show
  1. package/.claude-plugin/marketplace.json +26 -0
  2. package/CHANGELOG.md +675 -0
  3. package/LICENSE +21 -0
  4. package/README.es.md +1457 -0
  5. package/README.fr.md +1435 -0
  6. package/README.md +1605 -2
  7. package/README.pt-BR.md +1373 -0
  8. package/dist/build.json +5 -0
  9. package/dist/cli/busybits.js +14708 -0
  10. package/dist/client/assets/art/framed/painting-abstract.png +0 -0
  11. package/dist/client/assets/art/framed/painting-beach.png +0 -0
  12. package/dist/client/assets/art/framed/painting-cat.png +0 -0
  13. package/dist/client/assets/art/framed/painting-city-night.png +0 -0
  14. package/dist/client/assets/art/framed/painting-mountains.png +0 -0
  15. package/dist/client/assets/art/framed/painting-rio.png +0 -0
  16. package/dist/client/assets/art/framed/painting-sunflowers.png +0 -0
  17. package/dist/client/assets/art/framed/painting-wave.png +0 -0
  18. package/dist/client/assets/art/framed/painting-wide-aurora.png +0 -0
  19. package/dist/client/assets/art/framed/painting-wide-color-fields.png +0 -0
  20. package/dist/client/assets/art/framed/painting-wide-forest-lake.png +0 -0
  21. package/dist/client/assets/art/painting-abstract.png +0 -0
  22. package/dist/client/assets/art/painting-beach.png +0 -0
  23. package/dist/client/assets/art/painting-cat.png +0 -0
  24. package/dist/client/assets/art/painting-city-night.png +0 -0
  25. package/dist/client/assets/art/painting-mountains.png +0 -0
  26. package/dist/client/assets/art/painting-rio.png +0 -0
  27. package/dist/client/assets/art/painting-sunflowers.png +0 -0
  28. package/dist/client/assets/art/painting-wave.png +0 -0
  29. package/dist/client/assets/art/painting-wide-aurora.png +0 -0
  30. package/dist/client/assets/art/painting-wide-color-fields.png +0 -0
  31. package/dist/client/assets/art/painting-wide-forest-lake.png +0 -0
  32. package/dist/client/assets/art/poster-bug.png +0 -0
  33. package/dist/client/assets/art/poster-cat.png +0 -0
  34. package/dist/client/assets/art/poster-code.png +0 -0
  35. package/dist/client/assets/art/poster-coffee.png +0 -0
  36. package/dist/client/assets/art/poster-rocket.png +0 -0
  37. package/dist/client/assets/art/poster-ship-it.png +0 -0
  38. package/dist/client/assets/brand/apple-touch-icon.png +0 -0
  39. package/dist/client/assets/brand/favicon-16.png +0 -0
  40. package/dist/client/assets/brand/favicon-32.png +0 -0
  41. package/dist/client/assets/brand/icon-192.png +0 -0
  42. package/dist/client/assets/brand/icon-512.png +0 -0
  43. package/dist/client/assets/brand/logo-detailed.png +0 -0
  44. package/dist/client/assets/brand/logo-mark.png +0 -0
  45. package/dist/client/assets/brand/logo-mark@4x.png +0 -0
  46. package/dist/client/assets/brand/signage.png +0 -0
  47. package/dist/client/assets/brand/signage@4x.png +0 -0
  48. package/dist/client/assets/emoji/LICENSE-SerenityOS.txt +28 -0
  49. package/dist/client/assets/emoji/sheet.png +0 -0
  50. package/dist/client/assets/illustrations/empty-office.png +0 -0
  51. package/dist/client/assets/manifest.json +260 -0
  52. package/dist/client/assets/og-image.png +0 -0
  53. package/dist/client/bundle/app-AwZeKIeu.js +24 -0
  54. package/dist/client/bundle/app-CoDOLwxe.css +1 -0
  55. package/dist/client/bundle/city-DPTwQLdi.css +1 -0
  56. package/dist/client/bundle/city-YoIG0FsX.js +1 -0
  57. package/dist/client/bundle/daystats-DGzYOP8l.js +1 -0
  58. package/dist/client/bundle/dom-D2vx0KTo.js +1 -0
  59. package/dist/client/bundle/en-DBfNt5uV.js +169 -0
  60. package/dist/client/bundle/es-pnWdszTE.js +169 -0
  61. package/dist/client/bundle/format-C7qb6Cn-.js +1 -0
  62. package/dist/client/bundle/fr-CY8q9pj4.js +169 -0
  63. package/dist/client/bundle/main-DktU0GfB.js +2 -0
  64. package/dist/client/bundle/pixelify-sans-cyrillic-400-normal-Ckz2YJkH.woff2 +0 -0
  65. package/dist/client/bundle/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  66. package/dist/client/bundle/pixelify-sans-cyrillic-500-normal--wrb4dVK.woff2 +0 -0
  67. package/dist/client/bundle/pixelify-sans-cyrillic-500-normal-CR9SIKMr.woff +0 -0
  68. package/dist/client/bundle/pixelify-sans-cyrillic-600-normal-B3EuUOZG.woff +0 -0
  69. package/dist/client/bundle/pixelify-sans-cyrillic-600-normal-BhqNJYOZ.woff2 +0 -0
  70. package/dist/client/bundle/pixelify-sans-cyrillic-700-normal-BrZTw8tu.woff +0 -0
  71. package/dist/client/bundle/pixelify-sans-cyrillic-700-normal-CYtG5Rfp.woff2 +0 -0
  72. package/dist/client/bundle/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  73. package/dist/client/bundle/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  74. package/dist/client/bundle/pixelify-sans-latin-500-normal-Bq6pAlou.woff +0 -0
  75. package/dist/client/bundle/pixelify-sans-latin-500-normal-DC052d-m.woff2 +0 -0
  76. package/dist/client/bundle/pixelify-sans-latin-600-normal-BNlgYbDL.woff +0 -0
  77. package/dist/client/bundle/pixelify-sans-latin-600-normal-Dd_Dy7u5.woff2 +0 -0
  78. package/dist/client/bundle/pixelify-sans-latin-700-normal-BctWAS0u.woff +0 -0
  79. package/dist/client/bundle/pixelify-sans-latin-700-normal-D3Xxx3QE.woff2 +0 -0
  80. package/dist/client/bundle/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  81. package/dist/client/bundle/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  82. package/dist/client/bundle/pixelify-sans-latin-ext-500-normal-BHT4w5qI.woff2 +0 -0
  83. package/dist/client/bundle/pixelify-sans-latin-ext-500-normal-Bkr-oq6R.woff +0 -0
  84. package/dist/client/bundle/pixelify-sans-latin-ext-600-normal-CDaIumwU.woff +0 -0
  85. package/dist/client/bundle/pixelify-sans-latin-ext-600-normal-Dha6RiOG.woff2 +0 -0
  86. package/dist/client/bundle/pixelify-sans-latin-ext-700-normal-BadXkHzZ.woff +0 -0
  87. package/dist/client/bundle/pixelify-sans-latin-ext-700-normal-ClyJstAh.woff2 +0 -0
  88. package/dist/client/bundle/ptypane-BrP-ENHg.css +1 -0
  89. package/dist/client/bundle/ptypane-NIZ2Y8QM.js +16 -0
  90. package/dist/client/bundle/room-name-CFJfHE5L.js +1 -0
  91. package/dist/client/bundle/simulator-BnBPS_Ws.js +7 -0
  92. package/dist/client/bundle/world-model-BIYmgAWC.js +1 -0
  93. package/dist/client/bundle/world-stream-BRkL9Eme.js +1 -0
  94. package/dist/client/index.html +41 -0
  95. package/dist/client/manifest.webmanifest +17 -0
  96. package/dist/server/index.js +40327 -0
  97. package/mod/README.md +193 -0
  98. package/mod/habblaud/.claude-plugin/plugin.json +11 -0
  99. package/mod/habblaud/hooks/hooks.json +4 -0
  100. package/mod/habblaud/hooks/register.ts +517 -0
  101. package/mod/habblaud-codex/hook.mjs +274 -0
  102. package/mod/habblaud-mensagens/.claude-plugin/plugin.json +11 -0
  103. package/mod/habblaud-mensagens/hooks/hooks.json +4 -0
  104. package/mod/habblaud-mensagens/hooks/register.ts +384 -0
  105. package/mod/habblaud-permissoes/.claude-plugin/plugin.json +11 -0
  106. package/mod/habblaud-permissoes/hooks/hooks.json +18 -0
  107. package/mod/habblaud-permissoes/hooks/permission-hook.mjs +265 -0
  108. package/mod/habblaud-pi/core.ts +325 -0
  109. package/mod/habblaud-pi/extension.ts +119 -0
  110. package/mod/habblaud-pi/package.json +12 -0
  111. package/package.json +96 -4
@@ -0,0 +1,265 @@
1
+ #!/usr/bin/env node
2
+ // Hook PermissionRequest do Habblaud: deixa aprovar ou recusar pelo escritório os pedidos de permissão
3
+ // do Claude Code ("Do you want to…") e responder as perguntas do AskUserQuestion. Chega à sessão de um
4
+ // destes jeitos (este arquivo é a fonte única dos dois):
5
+ //
6
+ // - plugin `busybits-permissions` do marketplace do repositório (Claude Code 2.1.287+): o hooks.json ao
7
+ // lado roda `node "${CLAUDE_PLUGIN_ROOT}/hooks/permission-hook.mjs"`, com a porta vinda de HABBLAUD_PORT.
8
+ // O Claude Code copia SÓ a pasta do plugin para o cache de plugins: por isso nada de imports fora de
9
+ // `node:*` aqui;
10
+ // - `npm run hooks:install` (versões anteriores), que grava em cada <conta>/settings.json:
11
+ //
12
+ // node /caminho/do/habblaud/mod/habblaud-permissoes/hooks/permission-hook.mjs [--port 4747] [--timeout 300]
13
+ //
14
+ // O Claude Code mostra o diálogo no terminal e roda este hook AO MESMO TEMPO (vale o que responder
15
+ // primeiro); em subagentes em segundo plano o diálogo só aparece depois que o hook termina. O hook:
16
+ // 1. lê do stdin o JSON do pedido (session_id, tool_name, tool_input, permission_suggestions...);
17
+ // 2. manda para POST http://127.0.0.1:<porta>/api/permissions. Se o Habblaud não responder, recusar
18
+ // (recurso desligado) ou disser que não há página aberta ou que não conhece a sessão, sai na hora,
19
+ // sem decidir: o terminal segue normal;
20
+ // 3. senão, espera a decisão em GET /api/permissions/:id/wait (respostas de até 25 s, em laço) até o
21
+ // tempo limite (padrão 5 min: --timeout <s> ou HABBLAUD_PERMISSION_TIMEOUT);
22
+ // 4. aprovado/recusado: imprime a decisão (hookSpecificOutput.decision). Pergunta respondida: aprova
23
+ // a chamada com a entrada ORIGINAL mais `answers` ({texto da pergunta: rótulos escolhidos}, como a
24
+ // documentação dos hooks manda responder o AskUserQuestion); a página escolhe por posição e os textos
25
+ // vêm do stdin. "Responder no terminal", tempo esgotado ou qualquer erro: sai sem imprimir nada, e
26
+ // vale o que você responder no terminal.
27
+ //
28
+ // Regras: Node puro (22+), sem dependências; nunca trava nem quebra a sessão (todo erro = sair sem
29
+ // decidir). Só fala com 127.0.0.1. HABBLAUD_HOOK_DEBUG=1 escreve o que acontece no stderr.
30
+ import { realpathSync } from 'node:fs';
31
+ import { fileURLToPath } from 'node:url';
32
+
33
+ export const DEFAULT_PORT = 4747;
34
+ export const DEFAULT_TIMEOUT_S = 300;
35
+ const MIN_TIMEOUT_S = 5;
36
+ const MAX_TIMEOUT_S = 86_400;
37
+ /** Espera máxima de cada long-poll (o servidor responde "pending" e o hook pergunta de novo). */
38
+ const WAIT_S = 25;
39
+ /** Registrar o pedido: se o Habblaud não responder nisso, ele está fora do ar (ou travado). */
40
+ const REGISTER_TIMEOUT_MS = 2_000;
41
+ const STDIN_TIMEOUT_MS = 5_000;
42
+ const MAX_STDIN = 8 * 1024 * 1024;
43
+ /** Textos dos argumentos mandados ao Habblaud (o servidor só mostra uma prévia). */
44
+ const MAX_STRING = 8_000;
45
+ /** Corpo do pedido (o servidor recusa acima de 256 KB). */
46
+ const MAX_BODY = 200_000;
47
+ /** Ferramenta das perguntas ao usuário: a resposta é uma escolha (decisão `answer`), não aprovar/recusar. */
48
+ const ASK_TOOL = 'AskUserQuestion';
49
+
50
+ const debug = process.env.HABBLAUD_HOOK_DEBUG === '1' ? (msg) => process.stderr.write(`[habblaud-hook] ${msg}\n`) : () => {};
51
+
52
+ /** Porta e tempo limite: argumentos (--port, --timeout) ou ambiente (HABBLAUD_PORT, HABBLAUD_PERMISSION_TIMEOUT). */
53
+ export function parseOptions(argv, env = process.env) {
54
+ const arg = (name) => {
55
+ const i = argv.indexOf(`--${name}`);
56
+ return i >= 0 ? argv[i + 1] : undefined;
57
+ };
58
+ const port = Number.parseInt(arg('port') ?? env.HABBLAUD_PORT ?? '', 10);
59
+ const timeout = Number(arg('timeout') ?? env.HABBLAUD_PERMISSION_TIMEOUT ?? '');
60
+ return {
61
+ port: Number.isInteger(port) && port > 0 && port < 65_536 ? port : DEFAULT_PORT,
62
+ timeoutMs: (Number.isFinite(timeout) && timeout > 0 ? Math.min(MAX_TIMEOUT_S, Math.max(MIN_TIMEOUT_S, timeout)) : DEFAULT_TIMEOUT_S) * 1_000,
63
+ };
64
+ }
65
+
66
+ /** Corta textos longos dos argumentos (conteúdo de um Write enorme, por exemplo). */
67
+ export function trimInput(v, max = MAX_STRING, depth = 0) {
68
+ if (typeof v === 'string') return v.length > max ? v.slice(0, max) : v;
69
+ if (depth > 8 || v === null || typeof v !== 'object') return v;
70
+ if (Array.isArray(v)) return v.slice(0, 200).map((x) => trimInput(x, max, depth + 1));
71
+ const out = {};
72
+ for (const [k, x] of Object.entries(v)) out[k] = trimInput(x, max, depth + 1);
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * Corpo mandado ao Habblaud: só o que ele usa (nada de transcript_path nem do resto do stdin). Se ainda
78
+ * ficar grande (muitas edições de uma vez), os textos são cortados mais curtos.
79
+ */
80
+ export function requestBody(input, timeoutMs) {
81
+ const body = { session_id: input.session_id, tool_name: input.tool_name, tool_input: {}, timeout_ms: timeoutMs };
82
+ for (const k of ['agent_id', 'agent_type', 'cwd']) if (typeof input[k] === 'string') body[k] = input[k];
83
+ if (Array.isArray(input.permission_suggestions)) body.permission_suggestions = input.permission_suggestions;
84
+ for (const max of [MAX_STRING, 1_000, 200]) {
85
+ body.tool_input = trimInput(input.tool_input ?? {}, max);
86
+ if (JSON.stringify(body).length <= MAX_BODY) break;
87
+ }
88
+ return body;
89
+ }
90
+
91
+ /** Texto não vazio (as respostas usam os textos do stdin como vieram, sem aparar). */
92
+ const text = (v) => typeof v === 'string' && v.trim() !== '';
93
+
94
+ /**
95
+ * `answers` do AskUserQuestion ({texto ORIGINAL da pergunta: rótulos ORIGINAIS das opções escolhidas, na ordem
96
+ * delas, e o texto livre no fim, juntos com ", "}) a partir das respostas por posição vindas do Habblaud.
97
+ * undefined = não dá para responder (sai sem decidir e vale o terminal): entrada sem `questions`, pergunta
98
+ * sem resposta ou respondida duas vezes, posição inválida, sem multiSelect mais de uma escolha, perguntas
99
+ * com o mesmo texto.
100
+ */
101
+ export function answersFor(answers, toolInput) {
102
+ const questions = Array.isArray(toolInput?.questions) ? toolInput.questions : undefined;
103
+ if (!questions || !Array.isArray(answers) || !answers.length) return undefined;
104
+ const out = {};
105
+ const done = new Set();
106
+ for (const a of answers) {
107
+ const q = a && Number.isInteger(a.question) ? questions[a.question] : undefined;
108
+ if (!q || typeof q !== 'object' || !text(q.question) || done.has(a.question) || Object.hasOwn(out, q.question)) return undefined;
109
+ done.add(a.question);
110
+ const options = Array.isArray(q.options) ? q.options : [];
111
+ const parts = [];
112
+ for (const i of Array.isArray(a.options) ? a.options : []) {
113
+ const label = Number.isInteger(i) && i >= 0 ? options[i]?.label : undefined;
114
+ if (!text(label)) return undefined;
115
+ parts.push(label);
116
+ }
117
+ if (text(a.other)) parts.push(a.other.trim());
118
+ if (!parts.length || (q.multiSelect !== true && parts.length > 1)) return undefined;
119
+ out[q.question] = parts.join(', ');
120
+ }
121
+ // Toda pergunta de verdade precisa de resposta (as inválidas o Habblaud nem mostrou).
122
+ if (questions.some((q, i) => q && typeof q === 'object' && text(q.question) && !done.has(i))) return undefined;
123
+ return out;
124
+ }
125
+
126
+ /**
127
+ * Saída do hook para uma decisão do Habblaud (undefined = sair sem decidir). Uma regra "sempre permitir"
128
+ * escolhida na página volta só como a POSIÇÃO: aplica-se a sugestão original que o Claude Code mandou.
129
+ * Pergunta (AskUserQuestion): só `answer` aprova (sem `answers` a chamada não teria resposta); recusar vale.
130
+ */
131
+ export function decisionOutput(result, input) {
132
+ if (!result || result.status !== 'decided') return undefined;
133
+ const ask = input?.tool_name === ASK_TOOL;
134
+ if (result.behavior === 'answer') {
135
+ const answers = ask ? answersFor(result.answers, input.tool_input) : undefined;
136
+ if (!answers) return undefined;
137
+ const decision = { behavior: 'allow', updatedInput: { ...input.tool_input, answers } };
138
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } };
139
+ }
140
+ if (result.behavior === 'allow') {
141
+ if (ask) return undefined;
142
+ const decision = { behavior: 'allow' };
143
+ const list = Array.isArray(input?.permission_suggestions) ? input.permission_suggestions : [];
144
+ const chosen = Number.isInteger(result.suggestion) ? list[result.suggestion] : undefined;
145
+ if (chosen && typeof chosen === 'object') decision.updatedPermissions = [chosen];
146
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } };
147
+ }
148
+ if (result.behavior === 'deny') {
149
+ const reason = typeof result.message === 'string' && result.message.trim() ? result.message.trim().slice(0, 1_000) : '';
150
+ const decision = { behavior: 'deny', message: reason ? `Recusado pelo usuário no Habblaud: ${reason}` : 'Recusado pelo usuário no Habblaud.' };
151
+ if (result.interrupt === true) decision.interrupt = true;
152
+ return { hookSpecificOutput: { hookEventName: 'PermissionRequest', decision } };
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
+ /** Decide o pedido (ou não). Devolve a saída a imprimir, ou undefined. Nunca lança. */
200
+ export async function run(argv = process.argv.slice(2), env = process.env, stdinText) {
201
+ try {
202
+ const opts = parseOptions(argv, env);
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 (!input || typeof input !== 'object' || typeof input.session_id !== 'string' || typeof input.tool_name !== 'string') return undefined;
212
+ if (input.hook_event_name !== undefined && input.hook_event_name !== 'PermissionRequest') return undefined;
213
+
214
+ const base = `http://127.0.0.1:${opts.port}`;
215
+ const deadline = Date.now() + opts.timeoutMs;
216
+ const reg = await call(base, 'POST', '/api/permissions', requestBody(input, opts.timeoutMs), REGISTER_TIMEOUT_MS);
217
+ if (!reg || reg.status !== 201 || typeof reg.json?.id !== 'string') {
218
+ debug(`sem desvio (${reg ? `${reg.status} ${JSON.stringify(reg.json ?? null)}` : 'Habblaud fora do ar'})`);
219
+ return undefined;
220
+ }
221
+ const id = encodeURIComponent(reg.json.id);
222
+ for (;;) {
223
+ const left = deadline - Date.now();
224
+ if (left <= 0) {
225
+ debug('tempo esgotado: vale o terminal');
226
+ return undefined;
227
+ }
228
+ const waitS = Math.max(0.05, Math.min(WAIT_S, left / 1_000));
229
+ const r = await call(base, 'GET', `/api/permissions/${id}/wait?timeout=${waitS}`, undefined, waitS * 1_000 + 5_000);
230
+ if (!r || r.status !== 200) return undefined;
231
+ const status = r.json?.status;
232
+ if (status === 'pending') continue;
233
+ debug(`resposta: ${JSON.stringify(r.json)}`);
234
+ return decisionOutput(r.json, input);
235
+ }
236
+ } catch (err) {
237
+ debug(`erro: ${err?.message ?? err}`);
238
+ return undefined;
239
+ }
240
+ }
241
+
242
+ /** Ponto de entrada (exportado para o atalho do caminho antigo, scripts/permission-hook.mjs). */
243
+ export async function main() {
244
+ const { timeoutMs } = parseOptions(process.argv.slice(2));
245
+ // Rede de segurança: nada mantém o processo vivo além do tempo limite.
246
+ setTimeout(() => process.exit(0), timeoutMs + 15_000).unref();
247
+ const out = await run();
248
+ // Sem process.exit() logo depois do fetch: no Windows (Node 23 até 24.19) ele derruba o processo com
249
+ // 0xC0000409 enquanto o V8 ainda compila em segundo plano o parser do fetch (assert do libuv,
250
+ // nodejs/node#56645). O processo sai sozinho quando o loop esvazia, o que também espera a escrita da
251
+ // decisão no pipe (assíncrona no macOS); se algo ainda segurar o loop, o process.exit vem 1 s depois.
252
+ const finish = () => setTimeout(() => process.exit(0), 1_000).unref();
253
+ if (out) process.stdout.write(`${JSON.stringify(out)}\n`, finish);
254
+ else finish();
255
+ }
256
+
257
+ function isMain() {
258
+ try {
259
+ return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
260
+ } catch {
261
+ return false;
262
+ }
263
+ }
264
+
265
+ if (isMain()) main().catch(() => process.exit(0));
@@ -0,0 +1,325 @@
1
+ // Núcleo da extensão habblaud-pi (Gentle Shell / Pi): funções puras e clientes HTTP sem nenhuma dependência do Pi, para
2
+ // testar sem sessão (server/test/habblaud-pi.test.ts). O extension.ts só liga estes pedaços aos eventos do Pi.
3
+ //
4
+ // Fala só com o Habblaud local (127.0.0.1) e só usa rotas que já existem:
5
+ // - mensagens: POST /api/mod/inbox {session} → {messages: [{id, text}]} e POST /api/mod/inbox/ack (o mesmo protocolo do
6
+ // plugin busybits-messages do Claude Code); POST /api/mod/commands com os comandos de barra da sessão;
7
+ // - "precisa de você": POST /api/permissions com `answerable: false` (o gentle-pi pergunta pela caixa do terminal, que
8
+ // nenhuma extensão consegue responder de fora), espera em GET /api/permissions/:id/wait e devolve ao terminal em
9
+ // POST /api/permissions/:id/decision {behavior: "terminal"} quando a caixa fecha.
10
+
11
+ export const DEFAULT_PORT = 4747;
12
+ /** Intervalo das rodadas da caixa de entrada; fora do ar ou com o recurso desligado, o de espera longa. */
13
+ export const POLL_MS = 2_000;
14
+ export const BACKOFF_MS = 30_000;
15
+ /** Os comandos de barra são publicados quando mudam e, no mais, de minuto em minuto. */
16
+ export const COMMANDS_EVERY_MS = 60_000;
17
+ const REQUEST_TIMEOUT_MS = 2_000;
18
+ const WAIT_SECONDS = 25;
19
+ /** O pedido de aviso vale por este tempo (o servidor limita a 24 h); ele é devolvido assim que a caixa fecha. */
20
+ export const PROMPT_TIMEOUT_MS = 24 * 60 * 60_000;
21
+ const COMMAND_MAX = 300;
22
+
23
+ export interface PiEnv {
24
+ HABBLAUD_PORT?: string;
25
+ /** `0`, `false`, `off` ou `no` desligam a extensão. */
26
+ HABBLAUD_PI?: string;
27
+ /** Definida pelo gentle-pi nos subagentes (processos filhos): eles não são o agente principal do escritório. */
28
+ GENTLE_PI_AGENTS_CHILD?: string;
29
+ }
30
+
31
+ export function settingsFrom(env: PiEnv): { port: number; enabled: boolean } {
32
+ const port = Number.parseInt(env.HABBLAUD_PORT ?? '', 10);
33
+ const off = /^(0|false|off|no)$/i.test((env.HABBLAUD_PI ?? '').trim());
34
+ return { port: Number.isInteger(port) && port > 0 && port < 65_536 ? port : DEFAULT_PORT, enabled: !off && env.GENTLE_PI_AGENTS_CHILD !== '1' };
35
+ }
36
+
37
+ // ------------------------------------------------------------------ HTTP
38
+
39
+ export interface HttpResult {
40
+ status: number;
41
+ body: unknown;
42
+ }
43
+
44
+ /** Subconjunto do `fetch` que o cliente usa (injetável nos testes). */
45
+ export type FetchLike = (url: string, init: { method: string; headers?: Record<string, string>; body?: string; signal?: AbortSignal }) => Promise<{ status: number; json(): Promise<unknown> }>;
46
+
47
+ /** Cliente do Habblaud local. Nunca lança: falha de rede = undefined. */
48
+ export class HabblaudClient {
49
+ constructor(
50
+ readonly port: number,
51
+ private readonly fetchImpl: FetchLike = (url, init) => fetch(url, init),
52
+ ) {}
53
+
54
+ private url(path: string): string {
55
+ return `http://127.0.0.1:${this.port}${path}`;
56
+ }
57
+
58
+ async request(method: 'GET' | 'POST', path: string, body?: unknown, opts: { timeoutMs?: number; signal?: AbortSignal } = {}): Promise<HttpResult | undefined> {
59
+ const signals = [AbortSignal.timeout(opts.timeoutMs ?? REQUEST_TIMEOUT_MS)];
60
+ if (opts.signal) signals.push(opts.signal);
61
+ try {
62
+ const res = await this.fetchImpl(this.url(path), {
63
+ method,
64
+ ...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
65
+ signal: AbortSignal.any(signals),
66
+ });
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = await res.json();
70
+ } catch {
71
+ parsed = undefined;
72
+ }
73
+ return { status: res.status, body: parsed };
74
+ } catch {
75
+ return undefined;
76
+ }
77
+ }
78
+ }
79
+
80
+ type Rec = Record<string, unknown>;
81
+ const rec = (v: unknown): Rec | undefined => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Rec) : undefined);
82
+
83
+ // ------------------------------------------------------------------ mensagens
84
+
85
+ export interface PiCommand {
86
+ name: string;
87
+ description?: string;
88
+ source: string;
89
+ }
90
+
91
+ export interface WireCommand {
92
+ name: string;
93
+ description: string;
94
+ source: 'plugin' | 'user';
95
+ }
96
+
97
+ /** Comandos de barra do Pi no formato do Habblaud (extensão → plugin; prompt e skill → user). */
98
+ export function toWireCommands(list: readonly PiCommand[]): WireCommand[] {
99
+ return list.map((c) => ({ name: c.name, description: (c.description ?? '').slice(0, COMMAND_MAX), source: c.source === 'extension' ? ('plugin' as const) : ('user' as const) }));
100
+ }
101
+
102
+ export interface SendOptions {
103
+ deliverAs?: 'followUp';
104
+ expandPromptTemplates?: true;
105
+ }
106
+
107
+ export type Delivery = { ok: true; options: SendOptions } | { ok: false; error: string };
108
+
109
+ /**
110
+ * Como entregar uma mensagem do escritório: o texto vai como foi digitado. Sessão no meio de um turno: `followUp` (entra
111
+ * quando o turno acaba, como o plugin do Claude Code). `/nome args` de um comando da sessão (extensão, prompt ou skill)
112
+ * roda como comando (`expandPromptTemplates`); texto que começa por `/` e não é um deles falha com o motivo, sem ir à
113
+ * sessão (o `sendUserMessage` o mandaria ao modelo como texto, e os comandos embutidos do Pi não rodam por ele).
114
+ */
115
+ export function planDelivery(text: string, ctx: { idle: boolean; commands: ReadonlySet<string> }): Delivery {
116
+ const options: SendOptions = {};
117
+ if (!ctx.idle) options.deliverAs = 'followUp';
118
+ const m = /^\/(\S+)/.exec(text);
119
+ if (m) {
120
+ if (!ctx.commands.has(m[1])) return { ok: false, error: `/${m[1]} não é um comando de extensão, prompt ou skill desta sessão do Pi (os comandos embutidos só rodam no terminal)` };
121
+ options.expandPromptTemplates = true;
122
+ }
123
+ return { ok: true, options };
124
+ }
125
+
126
+ export interface SessionLike {
127
+ /** Id da sessão do Pi (o mesmo do nome do transcript); undefined = ainda sem sessão. */
128
+ sessionId(): string | undefined;
129
+ isIdle(): boolean;
130
+ send(text: string, options: SendOptions): void;
131
+ commands(): readonly PiCommand[];
132
+ }
133
+
134
+ /** Uma rodada da caixa de entrada: busca, entrega na ordem e confirma. */
135
+ export class MessagePump {
136
+ private lastCommands = '';
137
+ private commandsAt = -Infinity;
138
+
139
+ constructor(
140
+ private readonly client: HabblaudClient,
141
+ private readonly session: SessionLike,
142
+ private readonly now: () => number = Date.now,
143
+ ) {}
144
+
145
+ /** 'ok' = o Habblaud respondeu; 'down' = fora do ar ou recurso desligado (200 é o único bom). */
146
+ async round(): Promise<'ok' | 'down' | 'idle'> {
147
+ const sessionId = this.session.sessionId();
148
+ if (!sessionId) return 'idle';
149
+ const res = await this.client.request('POST', '/api/mod/inbox', { session: sessionId });
150
+ if (!res || res.status !== 200) return 'down';
151
+ const messages = rec(res.body)?.messages;
152
+ const results: Array<{ id: string; ok: boolean; error?: string }> = [];
153
+ for (const raw of Array.isArray(messages) ? messages : []) {
154
+ const m = rec(raw);
155
+ if (!m || typeof m.id !== 'string' || typeof m.text !== 'string') continue;
156
+ results.push({ id: m.id, ...this.deliver(m.text) });
157
+ }
158
+ if (results.length) await this.client.request('POST', '/api/mod/inbox/ack', { session: sessionId, results });
159
+ await this.publishCommands(sessionId);
160
+ return 'ok';
161
+ }
162
+
163
+ private deliver(text: string): { ok: boolean; error?: string } {
164
+ try {
165
+ const plan = planDelivery(text, { idle: this.session.isIdle(), commands: new Set(this.session.commands().map((c) => c.name)) });
166
+ if (!plan.ok) return { ok: false, error: plan.error };
167
+ this.session.send(text, plan.options);
168
+ return { ok: true };
169
+ } catch (err) {
170
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
171
+ }
172
+ }
173
+
174
+ private async publishCommands(sessionId: string): Promise<void> {
175
+ const commands = toWireCommands(this.session.commands());
176
+ const key = JSON.stringify(commands);
177
+ const now = this.now();
178
+ if (key === this.lastCommands && now - this.commandsAt < COMMANDS_EVERY_MS) return;
179
+ const res = await this.client.request('POST', '/api/mod/commands', { session: sessionId, commands });
180
+ if (res?.status === 200) {
181
+ this.lastCommands = key;
182
+ this.commandsAt = now;
183
+ }
184
+ }
185
+ }
186
+
187
+ // ------------------------------------------------------------------ "precisa de você"
188
+
189
+ /** Uma chamada de ferramenta do modelo que ainda não terminou (candidata ao que a caixa de permissão pergunta). */
190
+ export interface PendingCall {
191
+ id: string;
192
+ name: string;
193
+ input: Rec;
194
+ }
195
+
196
+ /** Acompanha as chamadas em aberto: o evento ui_prompt_start traz só o título da caixa, não o comando. */
197
+ export class CallTracker {
198
+ private calls = new Map<string, PendingCall>();
199
+
200
+ /** Mensagem do assistente (message_end): guarda os blocos `toolCall`. */
201
+ onMessage(message: unknown): void {
202
+ const m = rec(message);
203
+ if (!m || m.role !== 'assistant' || !Array.isArray(m.content)) return;
204
+ for (const block of m.content) {
205
+ const b = rec(block);
206
+ if (b?.type === 'toolCall' && typeof b.id === 'string' && typeof b.name === 'string') this.add({ id: b.id, name: b.name, input: rec(b.arguments) ?? {} });
207
+ }
208
+ }
209
+
210
+ add(call: PendingCall): void {
211
+ this.calls.set(call.id, call);
212
+ // Chamadas que nunca terminam (turno abortado) não se acumulam.
213
+ if (this.calls.size > 64) this.calls.delete(this.calls.keys().next().value as string);
214
+ }
215
+
216
+ done(id: string): void {
217
+ this.calls.delete(id);
218
+ }
219
+
220
+ clear(): void {
221
+ this.calls.clear();
222
+ }
223
+
224
+ /** A chamada que está sendo barrada: a mais antiga em aberto (as ferramentas rodam na ordem em que o modelo as pediu). */
225
+ current(): PendingCall | undefined {
226
+ return this.calls.values().next().value;
227
+ }
228
+ }
229
+
230
+ export interface PromptEvent {
231
+ kind: string;
232
+ title?: string;
233
+ }
234
+
235
+ /**
236
+ * Corpo de POST /api/permissions para uma caixa do terminal. A ferramenta do Pi vira o nome do Claude Code que o Habblaud
237
+ * sabe descrever (bash → Bash); sem chamada em aberto o aviso é só o título da caixa.
238
+ */
239
+ export function promptRequest(sessionId: string, cwd: string | undefined, prompt: PromptEvent, call: PendingCall | undefined): Rec {
240
+ let tool = 'Pi';
241
+ let input: Rec = {};
242
+ if (call) {
243
+ const name = call.name.toLowerCase();
244
+ if (name === 'bash') {
245
+ tool = 'Bash';
246
+ input = { command: typeof call.input.command === 'string' ? call.input.command : '' };
247
+ } else if (name === 'edit' || name === 'write') {
248
+ tool = name === 'edit' ? 'Edit' : 'Write';
249
+ const path = call.input.path ?? call.input.file_path;
250
+ input = typeof path === 'string' ? { file_path: path } : {};
251
+ } else {
252
+ tool = call.name;
253
+ }
254
+ }
255
+ const body: Rec = { session_id: sessionId, tool_name: tool, tool_input: input, timeout_ms: PROMPT_TIMEOUT_MS, answerable: false };
256
+ if (cwd) body.cwd = cwd;
257
+ if (prompt.title) body.prompt_title = prompt.title.slice(0, 300);
258
+ else body.prompt_title = `${prompt.kind}`;
259
+ return body;
260
+ }
261
+
262
+ /** Mantém o aviso enquanto a caixa estiver aberta: registra, espera em laço e devolve ao terminal quando ela fecha. */
263
+ export class PromptWatcher {
264
+ private active: { abort: AbortController; id?: string } | undefined;
265
+
266
+ constructor(
267
+ private readonly client: HabblaudClient,
268
+ private readonly session: Pick<SessionLike, 'sessionId'> & { cwd(): string | undefined },
269
+ private readonly calls: CallTracker,
270
+ ) {}
271
+
272
+ get open(): boolean {
273
+ return !!this.active;
274
+ }
275
+
276
+ /** A caixa abriu com o agente trabalhando. */
277
+ async start(prompt: PromptEvent): Promise<void> {
278
+ await this.end();
279
+ const sessionId = this.session.sessionId();
280
+ if (!sessionId) return;
281
+ const abort = new AbortController();
282
+ const mine = { abort } as { abort: AbortController; id?: string };
283
+ this.active = mine;
284
+ const res = await this.client.request('POST', '/api/permissions', promptRequest(sessionId, this.session.cwd(), prompt, this.calls.current()));
285
+ const body = rec(res?.body);
286
+ // 201 {id}: registrado. 200 {skip}, 4xx ou fora do ar: o terminal segue sozinho.
287
+ if (res?.status !== 201 || typeof body?.id !== 'string' || this.active !== mine) {
288
+ if (this.active === mine) this.active = undefined;
289
+ if (res?.status === 201 && typeof body?.id === 'string') await this.release(body.id);
290
+ return;
291
+ }
292
+ mine.id = body.id;
293
+ void this.watch(mine, body.id);
294
+ }
295
+
296
+ /** A caixa fechou (respondida no terminal): o aviso sai do escritório na hora. */
297
+ async end(): Promise<void> {
298
+ const current = this.active;
299
+ if (!current) return;
300
+ this.active = undefined;
301
+ current.abort.abort();
302
+ if (current.id) await this.release(current.id);
303
+ }
304
+
305
+ private async release(id: string): Promise<void> {
306
+ await this.client.request('POST', `/api/permissions/${encodeURIComponent(id)}/decision`, { behavior: 'terminal' });
307
+ }
308
+
309
+ /** O hook também espera: sem alguém no long-poll o servidor dá o pedido por órfão e o tira. */
310
+ private async watch(mine: { abort: AbortController }, id: string): Promise<void> {
311
+ while (this.active === mine && !mine.abort.signal.aborted) {
312
+ const res = await this.client.request('GET', `/api/permissions/${encodeURIComponent(id)}/wait?timeout=${WAIT_SECONDS}`, undefined, { timeoutMs: (WAIT_SECONDS + 5) * 1_000, signal: mine.abort.signal });
313
+ if (!res) {
314
+ if (mine.abort.signal.aborted) return;
315
+ await new Promise((r) => setTimeout(r, 1_000).unref?.());
316
+ continue;
317
+ }
318
+ if (rec(res.body)?.status !== 'pending') {
319
+ // decided/released pelo servidor (expirou, o Habblaud devolveu ao terminal) ou id desconhecido: nada mais a fazer.
320
+ if (this.active === mine) this.active = undefined;
321
+ return;
322
+ }
323
+ }
324
+ }
325
+ }