kafox-cli 0.10.0 → 0.10.2
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/package.json +1 -1
- package/src/auth.js +4 -2
- package/src/compact.js +40 -0
- package/src/gateway.js +178 -25
- package/src/mobile/auth.js +122 -0
- package/src/mobile/bridge.js +12 -1
- package/src/mobile/captcha.js +96 -0
- package/src/mobile/history.js +71 -0
- package/src/mobile/index.js +18 -0
- package/src/mobile/ratelimit.js +79 -0
- package/src/mobile/server.js +105 -3
- package/src/mobile/tui-bridge.js +1 -0
- package/src/mobile/view.js +223 -14
- package/src/tui.js +225 -45
package/package.json
CHANGED
package/src/auth.js
CHANGED
|
@@ -14,8 +14,10 @@ async function fetchApi(pathname, options = {}) {
|
|
|
14
14
|
return await fetch(url, {
|
|
15
15
|
...options,
|
|
16
16
|
headers: { ...storage.getAuthHeaders(options.headers), ...options.headers },
|
|
17
|
-
//
|
|
18
|
-
|
|
17
|
+
// Timeout por tentativa: nao deixa um host travado segurar o login.
|
|
18
|
+
// Mas se o caller passou o proprio signal (ex.: o stream do chat, que
|
|
19
|
+
// pode durar minutos), respeita ele em vez de matar em 12s.
|
|
20
|
+
signal: options.signal || (AbortSignal.timeout ? AbortSignal.timeout(12000) : undefined),
|
|
19
21
|
});
|
|
20
22
|
} catch (error) {
|
|
21
23
|
lastError = error;
|
package/src/compact.js
CHANGED
|
@@ -30,6 +30,10 @@ const { chat } = require("./gateway");
|
|
|
30
30
|
const DEFAULT_THRESHOLD_TOKENS = 60_000;
|
|
31
31
|
// Quantas mensagens recentes ficam intactas depois do resumo.
|
|
32
32
|
const DEFAULT_KEEP_MESSAGES = 8;
|
|
33
|
+
|
|
34
|
+
// Quantos turnos de usuario manter no historico enviado ao modelo. Casa com
|
|
35
|
+
// "~20 mensagens" (10 do usuario + 10 da IA). Mantem o chat leve e o custo baixo.
|
|
36
|
+
const DEFAULT_KEEP_TURNS = 10;
|
|
33
37
|
// Teto do resumo: o texto gerado vira contexto permanente, entao nao pode crescer.
|
|
34
38
|
const MAX_SUMMARY_CHARS = 4_000;
|
|
35
39
|
|
|
@@ -73,6 +77,40 @@ function safeCutIndex(messages, wantedIndex) {
|
|
|
73
77
|
return Math.max(1, index);
|
|
74
78
|
}
|
|
75
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Mantem so os ultimos `maxUserTurns` turnos do usuario no historico enviado
|
|
82
|
+
* ao modelo (mais o system). Cada turno arrasta junto a resposta do assistant
|
|
83
|
+
* e os pares de tool, entao o resultado gira em torno de `2 * maxUserTurns`
|
|
84
|
+
* mensagens — ex.: 10 turnos ~ 10 do usuario + 10 da IA.
|
|
85
|
+
*
|
|
86
|
+
* O corte e sempre seguro: usa safeCutIndex pra nao deixar tool orfao nem
|
|
87
|
+
* assistant(tool_calls) sem os resultados. Devolve sempre um array novo.
|
|
88
|
+
*/
|
|
89
|
+
function trimHistory(messages, maxUserTurns = DEFAULT_KEEP_TURNS) {
|
|
90
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
91
|
+
if (maxUserTurns <= 0 || list.length === 0) return list;
|
|
92
|
+
// Quantos turnos de usuario existem e onde comecam os ultimos N.
|
|
93
|
+
let seen = 0;
|
|
94
|
+
let wanted = 0;
|
|
95
|
+
for (let i = list.length - 1; i >= 0; i -= 1) {
|
|
96
|
+
if (list[i]?.role === "user") {
|
|
97
|
+
seen += 1;
|
|
98
|
+
if (seen >= maxUserTurns) {
|
|
99
|
+
wanted = i;
|
|
100
|
+
break;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (seen < maxUserTurns) return list.slice(); // cabem todos: nada a cortar
|
|
105
|
+
const cut = safeCutIndex(list, wanted);
|
|
106
|
+
const trimmed = list.slice(cut);
|
|
107
|
+
// Recoloca o system (que vive no indice 0) a frente, se existia.
|
|
108
|
+
if (list[0]?.role === "system" && trimmed[0]?.role !== "system") {
|
|
109
|
+
trimmed.unshift(list[0]);
|
|
110
|
+
}
|
|
111
|
+
return trimmed;
|
|
112
|
+
}
|
|
113
|
+
|
|
76
114
|
/** Texto corrido do historico, para alimentar o resumo. */
|
|
77
115
|
function transcript(messages, limitPerMessage = 1_500) {
|
|
78
116
|
return messages
|
|
@@ -334,6 +372,7 @@ module.exports = {
|
|
|
334
372
|
compactIfNeeded,
|
|
335
373
|
estimateTokens,
|
|
336
374
|
safeCutIndex,
|
|
375
|
+
trimHistory,
|
|
337
376
|
summaryPrompt,
|
|
338
377
|
buildCompactionNote,
|
|
339
378
|
scrubSecrets,
|
|
@@ -342,5 +381,6 @@ module.exports = {
|
|
|
342
381
|
SUMMARY_SECTIONS,
|
|
343
382
|
DEFAULT_THRESHOLD_TOKENS,
|
|
344
383
|
DEFAULT_KEEP_MESSAGES,
|
|
384
|
+
DEFAULT_KEEP_TURNS,
|
|
345
385
|
MAX_SUMMARY_CHARS,
|
|
346
386
|
};
|
package/src/gateway.js
CHANGED
|
@@ -117,7 +117,9 @@ function wait(ms, signal) {
|
|
|
117
117
|
resolve(value);
|
|
118
118
|
};
|
|
119
119
|
const timer = setTimeout(() => done(true), ms);
|
|
120
|
-
|
|
120
|
+
// Sem unref(): o backoff precisa manter o event loop vivo. Se este for o
|
|
121
|
+
// unico timer pendente e estiver unref'd, o Node dorme e a CLI so acorda
|
|
122
|
+
// quando o usuario digita algo — o retry ficaria "travado" ate um input.
|
|
121
123
|
function onAbort() {
|
|
122
124
|
done(false);
|
|
123
125
|
}
|
|
@@ -139,7 +141,7 @@ function errorFrom(data, status) {
|
|
|
139
141
|
* Le um stream SSE de chat completions (OpenAI-compatible) e chama os
|
|
140
142
|
* callbacks a cada delta. Devolve o resultado final.
|
|
141
143
|
*/
|
|
142
|
-
async function readStream({ response, started, onDelta, onReasoning }) {
|
|
144
|
+
async function readStream({ response, started, onDelta, onReasoning, skipPrefix = "", signal } = {}) {
|
|
143
145
|
const decoder = new TextDecoder();
|
|
144
146
|
let buffer = "";
|
|
145
147
|
let text = "";
|
|
@@ -147,6 +149,73 @@ async function readStream({ response, started, onDelta, onReasoning }) {
|
|
|
147
149
|
let usage = null;
|
|
148
150
|
const toolCalls = [];
|
|
149
151
|
|
|
152
|
+
// Watchdog de inatividade: o provedor as vezes morre sem FIN e o `for await`
|
|
153
|
+
// do body fica pendurado pra sempre (o event loop dorme e a CLI so acorda no
|
|
154
|
+
// proximo input). Se nenhum byte chega por IDLE_MS, aborta localmente e marca
|
|
155
|
+
// como retryable — o chat() reconecta por continuacao.
|
|
156
|
+
const IDLE_MS = Number(process.env.KAFOX_STREAM_IDLE_MS) || 90_000;
|
|
157
|
+
const idle = new AbortController();
|
|
158
|
+
let idleTimer = null;
|
|
159
|
+
let idleFired = false;
|
|
160
|
+
const clearIdle = () => {
|
|
161
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
162
|
+
idleTimer = null;
|
|
163
|
+
};
|
|
164
|
+
// Quando o watchdog dispara, cancelamos o reader do body: isso desbloqueia o
|
|
165
|
+
// `read()` pendurado (o signal do fetch sozinho nao interrompe um body ja
|
|
166
|
+
// iniciado se a conexao morreu sem FIN).
|
|
167
|
+
let reader = null;
|
|
168
|
+
const onIdleAbort = () => {
|
|
169
|
+
idleFired = true;
|
|
170
|
+
reader?.cancel?.().catch(() => {});
|
|
171
|
+
};
|
|
172
|
+
idle.signal.addEventListener("abort", onIdleAbort, { once: true });
|
|
173
|
+
const bumpIdle = () => {
|
|
174
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
175
|
+
idleTimer = setTimeout(() => idle.abort(new Error("stream idle timeout")), IDLE_MS);
|
|
176
|
+
};
|
|
177
|
+
bumpIdle();
|
|
178
|
+
// Continuacao: o provedor costuma repetir o inicio ja recebido antes de
|
|
179
|
+
// seguir. Segura a emissao ate passar do prefixo para nao duplicar na tela.
|
|
180
|
+
let toSkip = skipPrefix;
|
|
181
|
+
// Texto efetivamente entregue ao onDelta nesta tentativa (sem o prefixo).
|
|
182
|
+
let emitted = "";
|
|
183
|
+
|
|
184
|
+
const emitContent = (chunk) => {
|
|
185
|
+
if (toSkip) {
|
|
186
|
+
if (chunk.length <= toSkip.length) {
|
|
187
|
+
// O trecho novo ainda esta dentro do prefixo repetido: confere se bate.
|
|
188
|
+
if (toSkip.startsWith(chunk)) {
|
|
189
|
+
toSkip = toSkip.slice(chunk.length);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
// Divergiu do prefixo: o modelo recomecou; emite tudo o que veio.
|
|
193
|
+
toSkip = "";
|
|
194
|
+
emitted += chunk;
|
|
195
|
+
onDelta?.(chunk);
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
// Passou do prefixo: descarta a parte repetida e emite o resto.
|
|
199
|
+
const overlap = chunk.slice(0, toSkip.length);
|
|
200
|
+
if (overlap === toSkip || chunk.startsWith(toSkip)) {
|
|
201
|
+
const rest = chunk.slice(toSkip.length);
|
|
202
|
+
toSkip = "";
|
|
203
|
+
if (rest) {
|
|
204
|
+
emitted += rest;
|
|
205
|
+
onDelta?.(rest);
|
|
206
|
+
}
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
// Nao bateu: recomecou, emite tudo.
|
|
210
|
+
toSkip = "";
|
|
211
|
+
emitted += chunk;
|
|
212
|
+
onDelta?.(chunk);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
emitted += chunk;
|
|
216
|
+
onDelta?.(chunk);
|
|
217
|
+
};
|
|
218
|
+
|
|
150
219
|
const handleLine = (line) => {
|
|
151
220
|
if (!line.startsWith("data:")) return null;
|
|
152
221
|
const data = line.slice(5).trim();
|
|
@@ -172,48 +241,81 @@ async function readStream({ response, started, onDelta, onReasoning }) {
|
|
|
172
241
|
}
|
|
173
242
|
if (delta.content) {
|
|
174
243
|
text += delta.content;
|
|
175
|
-
|
|
244
|
+
emitContent(delta.content);
|
|
176
245
|
}
|
|
177
246
|
if (Array.isArray(delta.tool_calls)) mergeToolCalls(toolCalls, delta.tool_calls);
|
|
178
247
|
return null;
|
|
179
248
|
};
|
|
180
249
|
|
|
181
250
|
try {
|
|
182
|
-
|
|
183
|
-
|
|
251
|
+
reader = response.body.getReader();
|
|
252
|
+
while (true) {
|
|
253
|
+
const { done, value } = await reader.read();
|
|
254
|
+
if (done) break;
|
|
255
|
+
bumpIdle();
|
|
256
|
+
buffer += decoder.decode(value, { stream: true });
|
|
184
257
|
let index = buffer.indexOf("\n");
|
|
185
258
|
while (index >= 0) {
|
|
186
259
|
const line = buffer.slice(0, index).replace(/\r$/, "");
|
|
187
260
|
buffer = buffer.slice(index + 1);
|
|
188
261
|
const failure = handleLine(line);
|
|
189
|
-
if (failure) return { ok: false, error: failure.error, retryable: failure.retryable };
|
|
262
|
+
if (failure) { clearIdle(); return { ok: false, error: failure.error, retryable: failure.retryable }; }
|
|
190
263
|
index = buffer.indexOf("\n");
|
|
191
264
|
}
|
|
192
265
|
}
|
|
193
266
|
if (buffer.trim()) handleLine(buffer.trim());
|
|
267
|
+
// O cancel() do watchdog pode encerrar o reader como "done": se foi o
|
|
268
|
+
// watchdog que disparou, isso e falha e deve reconectar.
|
|
269
|
+
if (idleFired) {
|
|
270
|
+
clearIdle();
|
|
271
|
+
return {
|
|
272
|
+
ok: false,
|
|
273
|
+
error: `Stream interrompido: sem resposta do provedor por ${Math.round(IDLE_MS / 1000)}s`,
|
|
274
|
+
text,
|
|
275
|
+
emitted,
|
|
276
|
+
retryable: true,
|
|
277
|
+
};
|
|
278
|
+
}
|
|
194
279
|
} catch (error) {
|
|
195
|
-
|
|
196
|
-
|
|
280
|
+
clearIdle();
|
|
281
|
+
if (error?.name === "AbortError" || idleFired) {
|
|
282
|
+
// Abort com o signal do usuario ativo = ele apertou Esc: encerra.
|
|
283
|
+
if (signal?.aborted && !idleFired) {
|
|
284
|
+
return { ok: true, text, emitted, reasoning, toolCalls, ms: Date.now() - started, aborted: true };
|
|
285
|
+
}
|
|
286
|
+
// Sem abort do usuario, falha de conexao ou watchdog de inatividade:
|
|
287
|
+
// marca como retryable para o chat() reconectar de onde parou.
|
|
288
|
+
return {
|
|
289
|
+
ok: false,
|
|
290
|
+
error: idleFired
|
|
291
|
+
? `Stream interrompido: sem resposta do provedor por ${Math.round(IDLE_MS / 1000)}s`
|
|
292
|
+
: `Stream interrompido: ${error.message || "conexao caiu"}`,
|
|
293
|
+
text,
|
|
294
|
+
emitted,
|
|
295
|
+
retryable: true,
|
|
296
|
+
};
|
|
197
297
|
}
|
|
198
298
|
return {
|
|
199
299
|
ok: false,
|
|
200
300
|
error: `Stream interrompido: ${error.message}`,
|
|
201
301
|
text,
|
|
302
|
+
emitted,
|
|
202
303
|
retryable: retryableMessage(error.message),
|
|
203
304
|
};
|
|
204
305
|
}
|
|
306
|
+
clearIdle();
|
|
205
307
|
|
|
206
|
-
return { ok: true, text, reasoning, toolCalls: toolCalls.filter(Boolean), usage, ms: Date.now() - started };
|
|
308
|
+
return { ok: true, text, emitted, reasoning, toolCalls: toolCalls.filter(Boolean), usage, ms: Date.now() - started };
|
|
207
309
|
}
|
|
208
310
|
|
|
209
311
|
/**
|
|
210
312
|
* Uma tentativa no provedor kafox (gateway proprio): login/saldo/chave da conta
|
|
211
313
|
* e POST em `/api/chat`.
|
|
212
314
|
*/
|
|
213
|
-
async function attemptChat({ messages, model, tools, onDelta, onReasoning, signal } = {}) {
|
|
315
|
+
async function attemptChat({ messages, model, tools, onDelta, onReasoning, signal, skipPrefix } = {}) {
|
|
214
316
|
const socket = providerForModel(model);
|
|
215
317
|
if (socket.provider.kind === "openai") {
|
|
216
|
-
return attemptOpenAI({ messages, model: socket.model, provider: socket.provider, tools, onDelta, onReasoning, signal });
|
|
318
|
+
return attemptOpenAI({ messages, model: socket.model, provider: socket.provider, tools, onDelta, onReasoning, signal, skipPrefix });
|
|
217
319
|
}
|
|
218
320
|
|
|
219
321
|
const ready = await ensureReady({ model });
|
|
@@ -235,11 +337,11 @@ async function attemptChat({ messages, model, tools, onDelta, onReasoning, signa
|
|
|
235
337
|
signal,
|
|
236
338
|
});
|
|
237
339
|
} catch (error) {
|
|
238
|
-
if (error?.name === "AbortError") return { ok: false, code: "aborted", error: "Cancelado." };
|
|
340
|
+
if (error?.name === "AbortError" && signal?.aborted) return { ok: false, code: "aborted", error: "Cancelado." };
|
|
239
341
|
return {
|
|
240
342
|
ok: false,
|
|
241
|
-
error: `Falha de rede: ${error.message}`,
|
|
242
|
-
retryable: retryableMessage(error.message),
|
|
343
|
+
error: error?.name === "AbortError" ? `Falha de rede: ${error.message || "conexao caiu"}` : `Falha de rede: ${error.message}`,
|
|
344
|
+
retryable: error?.name === "AbortError" ? true : retryableMessage(error.message),
|
|
243
345
|
keyCreated: ready.keyCreated,
|
|
244
346
|
};
|
|
245
347
|
}
|
|
@@ -254,7 +356,7 @@ async function attemptChat({ messages, model, tools, onDelta, onReasoning, signa
|
|
|
254
356
|
};
|
|
255
357
|
}
|
|
256
358
|
|
|
257
|
-
const result = await readStream({ response, started, onDelta, onReasoning });
|
|
359
|
+
const result = await readStream({ response, started, onDelta, onReasoning, skipPrefix, signal });
|
|
258
360
|
return { ...result, model: ready.model, keyCreated: ready.keyCreated };
|
|
259
361
|
}
|
|
260
362
|
|
|
@@ -263,7 +365,7 @@ async function attemptChat({ messages, model, tools, onDelta, onReasoning, signa
|
|
|
263
365
|
* `{baseUrl}/chat/completions` com a chave do usuario. Sem login/saldo da conta
|
|
264
366
|
* kafox; o custo e cobrado pelo proprio provedor.
|
|
265
367
|
*/
|
|
266
|
-
async function attemptOpenAI({ messages, model, provider, tools, onDelta, onReasoning, signal } = {}) {
|
|
368
|
+
async function attemptOpenAI({ messages, model, provider, tools, onDelta, onReasoning, signal, skipPrefix } = {}) {
|
|
267
369
|
const apiKey = storage.getProviderKey(provider.id);
|
|
268
370
|
if (!apiKey) {
|
|
269
371
|
return {
|
|
@@ -292,11 +394,11 @@ async function attemptOpenAI({ messages, model, provider, tools, onDelta, onReas
|
|
|
292
394
|
signal,
|
|
293
395
|
});
|
|
294
396
|
} catch (error) {
|
|
295
|
-
if (error?.name === "AbortError") return { ok: false, code: "aborted", error: "Cancelado." };
|
|
397
|
+
if (error?.name === "AbortError" && signal?.aborted) return { ok: false, code: "aborted", error: "Cancelado." };
|
|
296
398
|
return {
|
|
297
399
|
ok: false,
|
|
298
|
-
error: `Falha de rede: ${error.message}`,
|
|
299
|
-
retryable: retryableMessage(error.message),
|
|
400
|
+
error: error?.name === "AbortError" ? `Falha de rede: ${error.message || "conexao caiu"}` : `Falha de rede: ${error.message}`,
|
|
401
|
+
retryable: error?.name === "AbortError" ? true : retryableMessage(error.message),
|
|
300
402
|
};
|
|
301
403
|
}
|
|
302
404
|
|
|
@@ -309,42 +411,93 @@ async function attemptOpenAI({ messages, model, provider, tools, onDelta, onReas
|
|
|
309
411
|
};
|
|
310
412
|
}
|
|
311
413
|
|
|
312
|
-
const result = await readStream({ response, started, onDelta, onReasoning });
|
|
414
|
+
const result = await readStream({ response, started, onDelta, onReasoning, skipPrefix, signal });
|
|
313
415
|
return { ...result, model, provider: provider.id };
|
|
314
416
|
}
|
|
315
417
|
|
|
316
418
|
/**
|
|
317
419
|
* Chat completions com stream (SSE) via /api/chat, com retry em falha de rede.
|
|
318
420
|
* onRetry avisa a TUI (tentativa, espera) para ela mostrar a contagem.
|
|
421
|
+
*
|
|
422
|
+
* Queda no meio da resposta (o pior caso: ja saiu texto e o stream morre) e
|
|
423
|
+
* reconectada por continuacao: reenvia a conversa com o trecho parcial como
|
|
424
|
+
* assistant e pede para seguir de onde parou. O `skipPrefix` faz o provedor
|
|
425
|
+
* repetir o inicio; o gateway descarta a repeticao, entao a TUI so ve o que
|
|
426
|
+
* e novo. Se a continuacao falhar, devolve o parcial para nao perder nada.
|
|
319
427
|
*/
|
|
320
428
|
async function chat({ messages, model, tools, onDelta, onReasoning, onRetry, signal, retries = RETRY_MAX } = {}) {
|
|
321
429
|
const maxAttempts = Math.max(1, Number(retries) || RETRY_MAX);
|
|
322
430
|
let attempt = 0;
|
|
323
431
|
let last = null;
|
|
324
432
|
let clearedKey = false;
|
|
433
|
+
// Acumulado entre tentativas (modo continuacao).
|
|
434
|
+
let carried = "";
|
|
435
|
+
let working = messages;
|
|
436
|
+
let skipPrefix = "";
|
|
325
437
|
|
|
326
438
|
while (attempt < maxAttempts) {
|
|
327
439
|
attempt += 1;
|
|
328
|
-
const result = await attemptChat({
|
|
440
|
+
const result = await attemptChat({
|
|
441
|
+
messages: working,
|
|
442
|
+
model,
|
|
443
|
+
tools,
|
|
444
|
+
onDelta,
|
|
445
|
+
onReasoning,
|
|
446
|
+
signal,
|
|
447
|
+
skipPrefix,
|
|
448
|
+
});
|
|
329
449
|
|
|
330
|
-
if (result.ok || result.code === "aborted")
|
|
450
|
+
if (result.ok || result.code === "aborted") {
|
|
451
|
+
if (carried && result.ok) {
|
|
452
|
+
// Junta o trecho das tentativas anteriores ao texto final.
|
|
453
|
+
const emitted = result.emitted ?? "";
|
|
454
|
+
const fullText = carried + emitted;
|
|
455
|
+
// Se o provedor mandou texto novo menor que o esperado, ainda vale o
|
|
456
|
+
// que ja foi mostrado; devolve o maior dos dois para o consumidor.
|
|
457
|
+
return { ...result, text: fullText.length >= (result.text || "").length ? fullText : result.text };
|
|
458
|
+
}
|
|
459
|
+
return result;
|
|
460
|
+
}
|
|
331
461
|
if (result.code === "invalid_api_key" && !clearedKey) {
|
|
332
462
|
clearedKey = true;
|
|
333
463
|
storage.clearApiKey();
|
|
334
464
|
continue;
|
|
335
465
|
}
|
|
336
|
-
//
|
|
337
|
-
if (!result.retryable
|
|
466
|
+
// Erro nao recuperavel (saldo, chave, modelo): devolve como veio.
|
|
467
|
+
if (!result.retryable) return carried ? { ...result, text: result.text || carried } : result;
|
|
338
468
|
last = result;
|
|
339
469
|
|
|
470
|
+
// Caiu ja com texto na tela: reconecta continuando de onde parou.
|
|
471
|
+
const partial = String(result.text || "");
|
|
472
|
+
if (partial.trim()) {
|
|
473
|
+
carried += partial;
|
|
474
|
+
skipPrefix = carried;
|
|
475
|
+
working = [
|
|
476
|
+
...messages,
|
|
477
|
+
{ role: "assistant", content: carried },
|
|
478
|
+
{
|
|
479
|
+
role: "user",
|
|
480
|
+
content:
|
|
481
|
+
"Sua resposta anterior foi interrompida por uma falha de conexao. " +
|
|
482
|
+
"Continue exatamente de onde parou, sem repetir nada do que ja foi escrito.",
|
|
483
|
+
},
|
|
484
|
+
];
|
|
485
|
+
}
|
|
486
|
+
|
|
340
487
|
if (attempt >= maxAttempts) break;
|
|
341
488
|
|
|
342
489
|
const delay = backoffMs(attempt);
|
|
343
490
|
onRetry?.({ attempt, maxAttempts, delay, error: result.error });
|
|
344
491
|
const slept = await wait(delay, signal);
|
|
345
|
-
if (!slept)
|
|
492
|
+
if (!slept) {
|
|
493
|
+
return { ok: false, code: "aborted", error: "Cancelado.", text: carried, keyCreated: result.keyCreated };
|
|
494
|
+
}
|
|
346
495
|
}
|
|
347
496
|
|
|
497
|
+
// Esgotou as tentativas: se ja tinha texto, entrega o parcial (melhor que erro).
|
|
498
|
+
if (carried.trim()) {
|
|
499
|
+
return { ...last, ok: true, text: carried, attempts: attempt, partial: true };
|
|
500
|
+
}
|
|
348
501
|
return { ...last, attempts: attempt };
|
|
349
502
|
}
|
|
350
503
|
|
package/src/mobile/auth.js
CHANGED
|
@@ -115,6 +115,128 @@ class PairingManager {
|
|
|
115
115
|
}
|
|
116
116
|
this.currentCode = null;
|
|
117
117
|
this.currentCodeHash = null;
|
|
118
|
+
// Pedidos de pareamento aguardando aprovacao do dono do terminal.
|
|
119
|
+
// requestId -> { createdAt, expiresAt, code, device, sessionTitle, status,
|
|
120
|
+
// token?, tokenExpiresAt? }
|
|
121
|
+
this.requests = new Map();
|
|
122
|
+
// Listener chamado quando chega um pedido novo (a TUI usa pra abrir modal).
|
|
123
|
+
this.onRequest = null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* PASSO 1 do novo fluxo: o celular pede entrada. NAO devolve token ainda —
|
|
128
|
+
* cria um pedido pendente e avisa o terminal (this.onRequest). O dono
|
|
129
|
+
* aprova/nega; so entao o token e emitido (ver resolveRequest/claim).
|
|
130
|
+
* @returns {{requestId:string, expiresAt:number}|null}
|
|
131
|
+
*/
|
|
132
|
+
requestPair(code, device = {}, meta = {}) {
|
|
133
|
+
if (!this.validateCode(code)) return null;
|
|
134
|
+
// Consome o codigo JA na criacao do pedido: garante uso unico (dois
|
|
135
|
+
// celulares nao podem abrir pedidos concorrentes com o mesmo codigo).
|
|
136
|
+
const codeHash = sha256(code);
|
|
137
|
+
this.pending.delete(codeHash);
|
|
138
|
+
if (this.currentCodeHash === codeHash) {
|
|
139
|
+
this.currentCode = null;
|
|
140
|
+
this.currentCodeHash = null;
|
|
141
|
+
}
|
|
142
|
+
const requestId = crypto.randomBytes(16).toString("hex");
|
|
143
|
+
const expiresAt = Date.now() + PAIR_TTL_MS;
|
|
144
|
+
const req = {
|
|
145
|
+
createdAt: Date.now(),
|
|
146
|
+
expiresAt,
|
|
147
|
+
code,
|
|
148
|
+
device,
|
|
149
|
+
sessionTitle: String(meta.sessionTitle || "").slice(0, 120),
|
|
150
|
+
sessionId: String(meta.sessionId || "").slice(0, 40),
|
|
151
|
+
status: "pending", // pending | approved | denied
|
|
152
|
+
token: null,
|
|
153
|
+
tokenExpiresAt: 0,
|
|
154
|
+
};
|
|
155
|
+
this.requests.set(requestId, req);
|
|
156
|
+
// Avisa o terminal (best-effort: se nao houver listener, so fica pendente).
|
|
157
|
+
try {
|
|
158
|
+
this.onRequest?.({ requestId, device, sessionTitle: req.sessionTitle, expiresAt });
|
|
159
|
+
} catch {
|
|
160
|
+
/* nao deixa o pedido quebrar por erro do listener */
|
|
161
|
+
}
|
|
162
|
+
this.audit("pair-request", { requestId: requestId.slice(0, 12), device });
|
|
163
|
+
return { requestId, expiresAt };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** PASSO 2 (terminal): aprova ou nega um pedido. Ao aprovar, emite o token. */
|
|
167
|
+
resolveRequest(requestId, approved, device = null) {
|
|
168
|
+
const req = this.requests.get(requestId);
|
|
169
|
+
if (!req) return false;
|
|
170
|
+
if (Date.now() > req.expiresAt) {
|
|
171
|
+
this.requests.delete(requestId);
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
if (req.status !== "pending") return false;
|
|
175
|
+
if (!approved) {
|
|
176
|
+
req.status = "denied";
|
|
177
|
+
this.audit("pair-denied", { requestId: requestId.slice(0, 12) });
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
// Aprovado: consome o codigo (single-use) e emite o token de sessao.
|
|
181
|
+
const codeHash = sha256(req.code);
|
|
182
|
+
this.pending.delete(codeHash);
|
|
183
|
+
if (this.currentCodeHash === codeHash) {
|
|
184
|
+
this.currentCode = null;
|
|
185
|
+
this.currentCodeHash = null;
|
|
186
|
+
}
|
|
187
|
+
const token = crypto.randomBytes(32).toString("hex");
|
|
188
|
+
const tokenExpiresAt = Date.now() + TOKEN_TTL_MS;
|
|
189
|
+
this.tokens.set(sha256(token), {
|
|
190
|
+
createdAt: Date.now(),
|
|
191
|
+
expiresAt: tokenExpiresAt,
|
|
192
|
+
code: req.code,
|
|
193
|
+
device: device || req.device,
|
|
194
|
+
});
|
|
195
|
+
this.persistTokens();
|
|
196
|
+
req.status = "approved";
|
|
197
|
+
req.token = token;
|
|
198
|
+
req.tokenExpiresAt = tokenExpiresAt;
|
|
199
|
+
this.audit("pair-approved", { requestId: requestId.slice(0, 12), device: req.device });
|
|
200
|
+
// Notifica o terminal: um pareamento CONCLUIU agora (some com o QR).
|
|
201
|
+
try {
|
|
202
|
+
this.onPaired?.({ requestId, device: device || req.device, sessionTitle: req.sessionTitle });
|
|
203
|
+
} catch {
|
|
204
|
+
/* listener do terminal nunca derruba o pareamento */
|
|
205
|
+
}
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* PASSO 3 (celular): consulta o status do pedido. Quando aprovado, devolve o
|
|
211
|
+
* token UMA vez e marca o pedido como consumido (nao vaza token em retries).
|
|
212
|
+
* @returns {{status:string, token?:string, expiresAt?:number}}
|
|
213
|
+
*/
|
|
214
|
+
pollRequest(requestId) {
|
|
215
|
+
const req = this.requests.get(requestId);
|
|
216
|
+
if (!req) return { status: "unknown" };
|
|
217
|
+
if (req.status === "pending" && Date.now() > req.expiresAt) {
|
|
218
|
+
this.requests.delete(requestId);
|
|
219
|
+
return { status: "expired" };
|
|
220
|
+
}
|
|
221
|
+
if (req.status === "approved") {
|
|
222
|
+
const token = req.token;
|
|
223
|
+
const expiresAt = req.tokenExpiresAt;
|
|
224
|
+
// single-shot: o token so sai do servidor uma vez.
|
|
225
|
+
this.requests.delete(requestId);
|
|
226
|
+
return { status: "approved", token, expiresAt };
|
|
227
|
+
}
|
|
228
|
+
return { status: req.status };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Pedidos pendentes (para reabrir o modal se a TUI renderizar de novo). */
|
|
232
|
+
pendingRequests() {
|
|
233
|
+
const out = [];
|
|
234
|
+
const now = Date.now();
|
|
235
|
+
for (const [id, req] of [...this.requests]) {
|
|
236
|
+
if (req.status === "pending" && now <= req.expiresAt) out.push({ requestId: id, ...req });
|
|
237
|
+
else if (now > req.expiresAt) this.requests.delete(id);
|
|
238
|
+
}
|
|
239
|
+
return out;
|
|
118
240
|
}
|
|
119
241
|
|
|
120
242
|
/**
|
package/src/mobile/bridge.js
CHANGED
|
@@ -20,6 +20,7 @@ const { EventEmitter } = require("events");
|
|
|
20
20
|
const { runAgent } = require("../agent");
|
|
21
21
|
const { estimateTokens } = require("../compact");
|
|
22
22
|
const sessions = require("../sessions");
|
|
23
|
+
const { trimHistory } = require("./history");
|
|
23
24
|
const { EventLog } = require("./protocol");
|
|
24
25
|
|
|
25
26
|
const SAVE_DEBOUNCE_MS = 400;
|
|
@@ -39,6 +40,7 @@ class SessionBridge extends EventEmitter {
|
|
|
39
40
|
super();
|
|
40
41
|
this.cwd = cwd;
|
|
41
42
|
this.sessionId = sessionId || sessions.newId();
|
|
43
|
+
this.title = null; // preenchido no snapshot a partir da 1a mensagem do usuario
|
|
42
44
|
this.sessionStartedAt = sessionStartedAt || new Date().toISOString();
|
|
43
45
|
this.messages = Array.isArray(messages) ? messages : [];
|
|
44
46
|
this.context = Array.isArray(context) ? context : [];
|
|
@@ -58,14 +60,23 @@ class SessionBridge extends EventEmitter {
|
|
|
58
60
|
|
|
59
61
|
/** Snapshot inicial para quem acabou de conectar (historico + estado). */
|
|
60
62
|
snapshot() {
|
|
63
|
+
// O celular nao sobe o chat inteiro: manda so as ultimas ~20 mensagens
|
|
64
|
+
// (10 do usuario + 10 da IA). O resto fica no PC.
|
|
65
|
+
const trimmed = trimHistory(this.messages);
|
|
61
66
|
return {
|
|
62
67
|
sessionId: this.sessionId,
|
|
68
|
+
title:
|
|
69
|
+
this.title ||
|
|
70
|
+
(this.messages.find((m) => m.role === "user")?.text || "").slice(0, 120) ||
|
|
71
|
+
null,
|
|
63
72
|
model: this.model,
|
|
64
73
|
cwd: this.cwd,
|
|
65
74
|
allowAll: this.allowAll,
|
|
66
75
|
busy: this.busy,
|
|
67
76
|
streaming: this.streaming,
|
|
68
|
-
messages:
|
|
77
|
+
messages: trimmed.messages,
|
|
78
|
+
historyTruncated: trimmed.truncated,
|
|
79
|
+
historyTotal: trimmed.total,
|
|
69
80
|
context: this.context,
|
|
70
81
|
pendingApproval: this.pendingApproval
|
|
71
82
|
? {
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Captcha proprio do kafox mobile — sem dependencia externa (sem node:crypto
|
|
3
|
+
* extra, sem servico de terceiros). Desafio aritmetico simples, renderizado
|
|
4
|
+
* como SVG inline no cliente, resolvido no servidor.
|
|
5
|
+
*
|
|
6
|
+
* Modelo de seguranca:
|
|
7
|
+
* - cada desafio e de USO UNICO e expira em CAPTCHA_TTL_MS;
|
|
8
|
+
* - a resposta fica guardada como hash (sha256), nunca em texto;
|
|
9
|
+
* - apos K tentativas o desafio morre (evita forca bruta);
|
|
10
|
+
* - limpeza oportunista dos expirados a cada emissao.
|
|
11
|
+
*
|
|
12
|
+
* Nao substitui Cloudflare Turnstile/hCaptcha, mas corta bots ingenuos e
|
|
13
|
+
* scripts que so reenviam o codigo do QR, que e o suficiente aqui.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const crypto = require("crypto");
|
|
17
|
+
|
|
18
|
+
const CAPTCHA_TTL_MS = 3 * 60 * 1000; // 3 minutos
|
|
19
|
+
const MAX_ATTEMPTS = 5;
|
|
20
|
+
|
|
21
|
+
/** @type {Map<string, {hash:string, expires:number, tries:number}>} */
|
|
22
|
+
const store = new Map();
|
|
23
|
+
|
|
24
|
+
function hash(text) {
|
|
25
|
+
return crypto.createHash("sha256").update(String(text).trim().toLowerCase()).digest("hex");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sweep() {
|
|
29
|
+
const now = Date.now();
|
|
30
|
+
for (const [id, entry] of store) {
|
|
31
|
+
if (entry.expires <= now) store.delete(id);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function randomInt(min, max) {
|
|
36
|
+
// inteiro uniforme em [min, max] usando bytes aleatorios
|
|
37
|
+
const span = max - min + 1;
|
|
38
|
+
const buf = crypto.randomBytes(4);
|
|
39
|
+
const n = buf.readUInt32BE(0);
|
|
40
|
+
return min + (n % span);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Emite um novo desafio.
|
|
45
|
+
* @returns {{ id:string, question:string, expiresAt:number }}
|
|
46
|
+
*/
|
|
47
|
+
function issue() {
|
|
48
|
+
sweep();
|
|
49
|
+
const a = randomInt(2, 9);
|
|
50
|
+
const b = randomInt(2, 9);
|
|
51
|
+
const usePlus = randomInt(0, 1) === 0;
|
|
52
|
+
let answer;
|
|
53
|
+
let question;
|
|
54
|
+
if (usePlus) {
|
|
55
|
+
answer = a + b;
|
|
56
|
+
question = `${a} + ${b} = ?`;
|
|
57
|
+
} else {
|
|
58
|
+
// subtracao sempre positiva
|
|
59
|
+
const hi = Math.max(a, b);
|
|
60
|
+
const lo = Math.min(a, b);
|
|
61
|
+
answer = hi - lo;
|
|
62
|
+
question = `${hi} - ${lo} = ?`;
|
|
63
|
+
}
|
|
64
|
+
const id = crypto.randomBytes(16).toString("hex");
|
|
65
|
+
store.set(id, { hash: hash(answer), expires: Date.now() + CAPTCHA_TTL_MS, tries: 0 });
|
|
66
|
+
return { id, question, expiresAt: Date.now() + CAPTCHA_TTL_MS };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Verifica e CONSOME o desafio (uso unico).
|
|
71
|
+
* @returns {{ ok:boolean, reason?:string }}
|
|
72
|
+
*/
|
|
73
|
+
function verify(id, answer) {
|
|
74
|
+
const entry = store.get(String(id || ""));
|
|
75
|
+
if (!entry) return { ok: false, reason: "captcha expirado ou invalido" };
|
|
76
|
+
if (entry.expires <= Date.now()) {
|
|
77
|
+
store.delete(id);
|
|
78
|
+
return { ok: false, reason: "captcha expirado" };
|
|
79
|
+
}
|
|
80
|
+
entry.tries += 1;
|
|
81
|
+
if (entry.tries > MAX_ATTEMPTS) {
|
|
82
|
+
store.delete(id);
|
|
83
|
+
return { ok: false, reason: "tentativas demais — recarregue o captcha" };
|
|
84
|
+
}
|
|
85
|
+
if (entry.hash !== hash(answer)) {
|
|
86
|
+
return { ok: false, reason: "captcha incorreto" };
|
|
87
|
+
}
|
|
88
|
+
store.delete(id); // uso unico
|
|
89
|
+
return { ok: true };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function size() {
|
|
93
|
+
return store.size;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
module.exports = { issue, verify, size, CAPTCHA_TTL_MS };
|