@0xmaxma/claude-gateway 2.1.13 → 2.1.14
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/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +10 -4
- package/dist/agent/runner.js.map +1 -1
- package/dist/build-provenance.json +4 -4
- package/mcp/tools/telegram/callback-failure.ts +88 -0
- package/mcp/tools/telegram/receiver-server.ts +64 -46
- package/mcp/tools/telegram/session-browser.ts +18 -2
- package/mcp/tools/telegram/task-browser.ts +10 -4
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"packageVersion": "2.1.
|
|
4
|
-
"builtAt": "2026-11-
|
|
5
|
-
"commit": "
|
|
6
|
-
"tag": "v2.1.
|
|
3
|
+
"packageVersion": "2.1.14",
|
|
4
|
+
"builtAt": "2026-11-19T03:31:57.469Z",
|
|
5
|
+
"commit": "99cf677c51cdd3ebbe52c8b4920213a45715699e",
|
|
6
|
+
"tag": "v2.1.14",
|
|
7
7
|
"dirty": false
|
|
8
8
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/** Classifies a failed agent callback (or the Telegram call after it) so a
|
|
2
|
+
* command handler can log why it failed and tell the user what to expect. */
|
|
3
|
+
export type CallbackFailureKind = 'busy' | 'unavailable' | 'failed';
|
|
4
|
+
|
|
5
|
+
/** A non-OK HTTP response from the agent callback server. */
|
|
6
|
+
export class CallbackHttpError extends Error {
|
|
7
|
+
constructor(readonly status: number, body?: unknown) {
|
|
8
|
+
const reason = rejectionReason(body);
|
|
9
|
+
super(`callback HTTP ${status}${reason ? `: ${reason}` : ''}`);
|
|
10
|
+
this.name = 'CallbackHttpError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function rejectionReason(body: unknown): string {
|
|
15
|
+
const b = body as { error?: unknown; text?: unknown } | null;
|
|
16
|
+
return typeof b?.error === 'string' && b.error ? b.error : typeof b?.text === 'string' && b.text ? b.text : '';
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A `{success:false}` callback reply, keeping the agent's own reason and
|
|
20
|
+
* error code (e.g. STOP_MENU_EXPIRED) for the log and the caller. */
|
|
21
|
+
export function callbackRejection(body: unknown, fallback = 'unavailable'): Error {
|
|
22
|
+
const reason = rejectionReason(body);
|
|
23
|
+
const code = (body as { code?: unknown } | null)?.code;
|
|
24
|
+
return Object.assign(new Error(reason ? `${fallback}: ${reason}` : fallback), typeof code === 'string' && code ? { code } : {});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Reads a /command reply, throwing with the HTTP status or the agent's own
|
|
28
|
+
* reason so a failure log keeps them. */
|
|
29
|
+
export async function readCallbackResult<T extends { success?: boolean }>(response: Response): Promise<T> {
|
|
30
|
+
const result = await response.json().catch(error => { throw response.ok ? error : new CallbackHttpError(response.status); }) as T;
|
|
31
|
+
if (!response.ok) throw new CallbackHttpError(response.status, result);
|
|
32
|
+
if (!result?.success) throw callbackRejection(result);
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Socket errors that mean nothing is listening on the callback port, usually
|
|
37
|
+
// because the agent is restarting. Node/undici put the code on `cause`; Bun,
|
|
38
|
+
// which runs the receiver, puts its own code (e.g. ConnectionRefused) on the error.
|
|
39
|
+
const UNREACHABLE = new Set(['ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'EHOSTUNREACH', 'UND_ERR_SOCKET', 'ConnectionRefused', 'ConnectionClosed']);
|
|
40
|
+
|
|
41
|
+
export interface CallbackFailure {
|
|
42
|
+
kind: CallbackFailureKind;
|
|
43
|
+
name: string;
|
|
44
|
+
timeout: boolean;
|
|
45
|
+
/** HTTP status from the agent callback. */
|
|
46
|
+
status?: number;
|
|
47
|
+
/** Telegram Bot API error code, kept apart from the callback status. */
|
|
48
|
+
telegramCode?: number;
|
|
49
|
+
code?: string;
|
|
50
|
+
message: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function classifyCallbackFailure(error: unknown): CallbackFailure {
|
|
54
|
+
const e = error as { name?: unknown; message?: unknown; cause?: { code?: unknown }; code?: unknown; error?: { code?: unknown }; error_code?: unknown; description?: unknown } | null;
|
|
55
|
+
const name = typeof e?.name === 'string' ? e.name : 'UnknownError';
|
|
56
|
+
const status = error instanceof CallbackHttpError ? error.status : undefined;
|
|
57
|
+
const telegramCode = typeof e?.error_code === 'number' ? e.error_code : undefined;
|
|
58
|
+
const rawCode = e?.cause?.code ?? e?.code;
|
|
59
|
+
const callbackCode = typeof rawCode === 'string' ? rawCode : undefined;
|
|
60
|
+
// grammy's HttpError wraps a Telegram network failure in `.error`: log its
|
|
61
|
+
// code, but it says nothing about the agent, so it never means restarting.
|
|
62
|
+
const code = callbackCode ?? (typeof e?.error?.code === 'string' ? e.error.code : undefined);
|
|
63
|
+
const timeout = name === 'TimeoutError';
|
|
64
|
+
const raw = typeof e?.description === 'string' ? e.description : typeof e?.message === 'string' ? e.message : String(error);
|
|
65
|
+
// Never log a callback URL; the message is bounded so a large body cannot flood the log.
|
|
66
|
+
const message = raw.replace(/https?:\/\/\S+/g, '[url]').replace(/\s+/g, ' ').slice(0, 160);
|
|
67
|
+
// /command answers only 200/400/500, so status never means busy or restarting.
|
|
68
|
+
const kind: CallbackFailureKind = timeout ? 'busy'
|
|
69
|
+
: callbackCode !== undefined && UNREACHABLE.has(callbackCode) ? 'unavailable'
|
|
70
|
+
: 'failed';
|
|
71
|
+
return { kind, name, timeout, ...(status !== undefined ? { status } : {}), ...(telegramCode !== undefined ? { telegramCode } : {}), ...(code ? { code } : {}), message };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function formatCallbackFailure(command: string, f: CallbackFailure): string {
|
|
75
|
+
return `telegram channel: /${command} failed (kind=${f.kind} name=${f.name} timeout=${f.timeout}` +
|
|
76
|
+
`${f.status !== undefined ? ` status=${f.status}` : ''}${f.telegramCode !== undefined ? ` telegram_code=${f.telegramCode}` : ''}${f.code ? ` code=${f.code}` : ''} message=${JSON.stringify(f.message)})`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function callbackFailureReply(kind: CallbackFailureKind, what: string, command: string): string {
|
|
80
|
+
if (kind === 'busy') return `The agent is busy and did not answer in time. Please try /${command} again in a moment.`;
|
|
81
|
+
if (kind === 'unavailable') return `The agent is restarting or unavailable. Please try /${command} again shortly.`;
|
|
82
|
+
return `Could not load ${what}. Please try /${command} again.`;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Logs a failed callback-backed command or button without replying. */
|
|
86
|
+
export function logCallbackFailure(command: string, error: unknown): void {
|
|
87
|
+
process.stderr.write(formatCallbackFailure(command, classifyCallbackFailure(error)) + '\n');
|
|
88
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
import { commandHelp } from '../../../dist/agent/command-help.js';
|
|
3
|
-
import {
|
|
3
|
+
import { requestSessionInfo } from './session-browser';
|
|
4
|
+
import { CallbackHttpError, callbackFailureReply, callbackRejection, classifyCallbackFailure, formatCallbackFailure, logCallbackFailure, readCallbackResult } from './callback-failure';
|
|
4
5
|
import { fetchModelMenuResponses, sendModelMenuReply } from './model-menu-request';
|
|
5
6
|
/**
|
|
6
7
|
* Telegram channel for Claude Gateway.
|
|
@@ -1404,9 +1405,7 @@ type VoicePicker = {menuId:string;provider:string;page:number;pages:number;gende
|
|
|
1404
1405
|
async function voicePickerRequest(chatId:string,userId:string,payload:Record<string,unknown>={}) {
|
|
1405
1406
|
if(!CALLBACK_URL_BASE)throw new Error('not_configured')
|
|
1406
1407
|
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(20000),body:JSON.stringify({command:'telegram_voices',chat_id:chatId,payload:{...payload,user_id:userId}})})
|
|
1407
|
-
|
|
1408
|
-
if(!response.ok||!result.success)throw new Error('unavailable')
|
|
1409
|
-
return result
|
|
1408
|
+
return readCallbackResult<VoicePicker & {success?:boolean;name?:string}>(response)
|
|
1410
1409
|
}
|
|
1411
1410
|
function voicePickerMenu(menu:VoicePicker) {
|
|
1412
1411
|
const keyboard=new InlineKeyboard()
|
|
@@ -1426,16 +1425,28 @@ bot.command('voices',async ctx=>{
|
|
|
1426
1425
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1427
1426
|
if(!ORCHESTRATION_ENABLED){await ctx.reply('Voice controls require orchestration mode.');return}
|
|
1428
1427
|
try{const menu=voicePickerMenu(await voicePickerRequest(String(ctx.chat.id),String(ctx.from!.id)));await ctx.reply(menu.text,{reply_markup:menu.reply_markup})}
|
|
1429
|
-
catch{await ctx
|
|
1428
|
+
catch(err){await replyCallbackFailure(ctx,err,'voices','the voice list','Voice list unavailable. Check the TTS provider configuration and try /voices again.')}
|
|
1430
1429
|
})
|
|
1431
1430
|
|
|
1432
1431
|
type TaskView = TaskDetail & {taskId:string;title:string;state:string;progress?:string;question?:string;updatedAt:number;startedAt?:number;finishedAt?:number;canStop:boolean}
|
|
1433
1432
|
type TaskBrowser = {sessionId:string;task?:TaskView;tasks?:TaskView[];page?:number;pages?:number;total?:number}
|
|
1433
|
+
// Log why a callback-backed command failed, then tell the user whether the
|
|
1434
|
+
// agent is busy, restarting, or failed. The reply itself may fail too.
|
|
1435
|
+
// `failedReply` replaces the generic text when the agent answered with an error.
|
|
1436
|
+
async function replyCallbackFailure(ctx:Context,err:unknown,command:string,what:string,failedReply?:string) {
|
|
1437
|
+
const failure=classifyCallbackFailure(err)
|
|
1438
|
+
process.stderr.write(formatCallbackFailure(command,failure)+'\n')
|
|
1439
|
+
try{await ctx.reply(failure.kind==='failed'&&failedReply?failedReply:callbackFailureReply(failure.kind,what,command))}
|
|
1440
|
+
catch(replyErr){process.stderr.write(formatCallbackFailure(`${command} reply`,classifyCallbackFailure(replyErr))+'\n')}
|
|
1441
|
+
}
|
|
1434
1442
|
async function taskBrowserRequest(chatId:string,userId:string,payload:Record<string,unknown>={}) {
|
|
1435
1443
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1436
1444
|
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),body:JSON.stringify({command:'telegram_tasks',chat_id:chatId,payload:{...payload,user_id:userId}})})
|
|
1437
|
-
const result=await response.json() as TaskBrowser & {success?:boolean}
|
|
1438
|
-
|
|
1445
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as TaskBrowser & {success?:boolean}
|
|
1446
|
+
const error=(result as {error?:unknown}|null)?.error
|
|
1447
|
+
if(error==='TASK_SESSION_CHANGED')throw Error('TASK_SESSION_CHANGED')
|
|
1448
|
+
if(!response.ok)throw new CallbackHttpError(response.status,result)
|
|
1449
|
+
if(!result?.success)throw callbackRejection(result)
|
|
1439
1450
|
if(typeof result.sessionId!=='string'||!result.sessionId)throw Error('unavailable')
|
|
1440
1451
|
return result
|
|
1441
1452
|
}
|
|
@@ -1469,6 +1480,7 @@ const liveTaskBrowser = new LiveTaskBrowser({
|
|
|
1469
1480
|
remove: (chat, id) => bot.api.deleteMessage(chat, id),
|
|
1470
1481
|
close: (chat, id) => bot.api.editMessageText(chat, id, 'Task view closed.', {reply_markup: {inline_keyboard: []}}),
|
|
1471
1482
|
allowed: (chat, user) => ORCHESTRATION_ENABLED && chat === user && loadAccess().allowFrom.includes(user),
|
|
1483
|
+
report: err => logCallbackFailure('tasks refresh', err),
|
|
1472
1484
|
persist: entries => {
|
|
1473
1485
|
mkdirSync(STATE_DIR, {recursive:true,mode:0o700})
|
|
1474
1486
|
const temp = TASK_BROWSER_FILE + '.tmp'
|
|
@@ -1480,7 +1492,7 @@ bot.command('tasks',async ctx=>{
|
|
|
1480
1492
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1481
1493
|
if(!ORCHESTRATION_ENABLED){await ctx.reply('Task controls require orchestration mode.');return}
|
|
1482
1494
|
try{await liveTaskBrowser.open(String(ctx.chat.id),String(ctx.from!.id))}
|
|
1483
|
-
catch{await ctx
|
|
1495
|
+
catch(err){await replyCallbackFailure(ctx,err,'tasks','tasks')}
|
|
1484
1496
|
})
|
|
1485
1497
|
|
|
1486
1498
|
// /pstack-setup (Telegram also takes /pstack_setup: command names cannot contain '-').
|
|
@@ -1490,15 +1502,13 @@ bot.command('tasks',async ctx=>{
|
|
|
1490
1502
|
async function pstackMenuRequest(chatId:string,userId:string,data:string) {
|
|
1491
1503
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1492
1504
|
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(20000),body:JSON.stringify({command:'telegram_pstack',chat_id:chatId,payload:{user_id:userId,data}})})
|
|
1493
|
-
|
|
1494
|
-
if(!response.ok||!result.success)throw Error('unavailable')
|
|
1495
|
-
return pstackMenuMarkup(result)
|
|
1505
|
+
return pstackMenuMarkup(await readCallbackResult<{success?:boolean}>(response))
|
|
1496
1506
|
}
|
|
1497
1507
|
bot.hears(PSTACK_MENU_COMMAND,async (ctx,next)=>{
|
|
1498
1508
|
if(ctx.chat?.type!=='private'||!CALLBACK_URL_BASE)return next()
|
|
1499
1509
|
if(!isCallbackAuthorized(ctx))return
|
|
1500
1510
|
try{const menu=await pstackMenuRequest(String(ctx.chat.id),String(ctx.from!.id),'ps:h');await ctx.reply(menu.text,{reply_markup:menu.reply_markup})}
|
|
1501
|
-
catch{await ctx
|
|
1511
|
+
catch(err){await replyCallbackFailure(ctx,err,'pstack_setup','pstack setup','pstack setup unavailable. Please try /pstack_setup again.')}
|
|
1502
1512
|
})
|
|
1503
1513
|
|
|
1504
1514
|
async function taskStopRequest(chatId: string, userId: string, menuId?: string, index?: number) {
|
|
@@ -1507,9 +1517,7 @@ async function taskStopRequest(chatId: string, userId: string, menuId?: string,
|
|
|
1507
1517
|
method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),
|
|
1508
1518
|
body:JSON.stringify({command:'task_stop',chat_id:chatId,payload:{user_id:userId,menu_id:menuId,index}}),
|
|
1509
1519
|
})
|
|
1510
|
-
|
|
1511
|
-
if (!response.ok || !result.success) throw new Error('unavailable')
|
|
1512
|
-
return result
|
|
1520
|
+
return readCallbackResult<{success?:boolean;legacy?:boolean;text?:string;menuId?:string;tasks?:Array<{title:string;state:string}>}>(response)
|
|
1513
1521
|
}
|
|
1514
1522
|
bot.command('stop',async (ctx,next)=>{
|
|
1515
1523
|
if (!ORCHESTRATION_ENABLED || ctx.chat?.type!=='private') return next()
|
|
@@ -1521,7 +1529,7 @@ bot.command('stop',async (ctx,next)=>{
|
|
|
1521
1529
|
for (const [i,task] of (result.tasks??[]).entries()) keyboard.text(`${i+1}. ${task.title.slice(0,65)} (${task.state})`,`taskstop:${result.menuId}:${i+1}`).row()
|
|
1522
1530
|
if (result.tasks?.length) keyboard.text('Dismiss',`taskstop:${result.menuId}:0`)
|
|
1523
1531
|
await ctx.reply(result.text??'Nothing to stop.',result.tasks?.length?{reply_markup:keyboard}:{})
|
|
1524
|
-
} catch { await ctx
|
|
1532
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'stop', 'tasks') }
|
|
1525
1533
|
})
|
|
1526
1534
|
|
|
1527
1535
|
// Voice settings are handled directly; no model call or TTS for this menu.
|
|
@@ -1533,8 +1541,8 @@ async function telegramVoiceSetting(chatId: string, mode?: VoiceReplyMode): Prom
|
|
|
1533
1541
|
body: JSON.stringify({ command: 'telegram_voice', chat_id: chatId, payload: { mode } }),
|
|
1534
1542
|
signal: AbortSignal.timeout(10000),
|
|
1535
1543
|
})
|
|
1536
|
-
const result = await
|
|
1537
|
-
if (
|
|
1544
|
+
const result = await readCallbackResult<{ success?: boolean; enabled?: boolean; mode?: VoiceReplyMode }>(response)
|
|
1545
|
+
if (typeof result.enabled !== 'boolean') throw new Error('invalid voice settings reply')
|
|
1538
1546
|
return result.mode ?? (result.enabled ? 'on' : 'off')
|
|
1539
1547
|
}
|
|
1540
1548
|
function voiceMenu(mode: VoiceReplyMode) {
|
|
@@ -1553,7 +1561,7 @@ bot.command('voice', async ctx => {
|
|
|
1553
1561
|
try {
|
|
1554
1562
|
const menu = voiceMenu(await telegramVoiceSetting(String(ctx.chat.id), choice ? choice as VoiceReplyMode : undefined))
|
|
1555
1563
|
await ctx.reply(menu.text, choice ? {} : { reply_markup: menu.reply_markup })
|
|
1556
|
-
} catch { await ctx
|
|
1564
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'voice', 'voice settings', 'Voice settings are unavailable. Check the agent TTS configuration.') }
|
|
1557
1565
|
})
|
|
1558
1566
|
|
|
1559
1567
|
// /call — open a live voice call as a Telegram Mini App bound to this DM. The
|
|
@@ -1575,7 +1583,7 @@ bot.command('call', async ctx => {
|
|
|
1575
1583
|
}
|
|
1576
1584
|
// web_app buttons open the Mini App with signed initData; Telegram requires HTTPS.
|
|
1577
1585
|
await ctx.reply('Tap to start a voice call. Your words and the replies also appear here.', { ...(ctx.message?.message_thread_id ? { message_thread_id: ctx.message.message_thread_id } : {}), reply_markup: new InlineKeyboard().webApp('\u{1F399} Start voice call', data.url) })
|
|
1578
|
-
} catch { await ctx
|
|
1586
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'call', 'a voice call', 'Could not start a voice call right now.') }
|
|
1579
1587
|
})
|
|
1580
1588
|
|
|
1581
1589
|
// Reuse the /tasks live-message lifecycle: serialize reads/replacement, edit only
|
|
@@ -1584,20 +1592,14 @@ const SESSION_BROWSER_FILE = join(STATE_DIR, 'session-browser.json')
|
|
|
1584
1592
|
let restoredSessionBrowsers: TaskBrowserMessage[] = []
|
|
1585
1593
|
try { const saved = JSON.parse(readFileSync(SESSION_BROWSER_FILE, 'utf8')); if (Array.isArray(saved)) restoredSessionBrowsers = saved } catch {}
|
|
1586
1594
|
const liveSessionBrowser = new LiveTaskBrowser({
|
|
1587
|
-
read:
|
|
1588
|
-
if (!CALLBACK_URL_BASE) throw new Error('not_configured')
|
|
1589
|
-
const response = await fetch(CALLBACK_URL_BASE + '/command', {
|
|
1590
|
-
method:'POST', headers:{'Content-Type':'application/json'}, signal:AbortSignal.timeout(10000),
|
|
1591
|
-
body:JSON.stringify({command:'session_info',chat_id:chat}),
|
|
1592
|
-
})
|
|
1593
|
-
return parseSessionInfo(response.ok, await response.json())
|
|
1594
|
-
},
|
|
1595
|
+
read: chat => requestSessionInfo(CALLBACK_URL_BASE, chat),
|
|
1595
1596
|
render: result => ({text:(result as {sessionId:string;text:string}).text,reply_markup:{inline_keyboard:[]}}),
|
|
1596
1597
|
send: async (chat,menu) => (await bot.api.sendMessage(chat,menu.text,{parse_mode:'HTML'})).message_id,
|
|
1597
1598
|
edit: (chat,id,menu) => bot.api.editMessageText(chat,id,menu.text,{parse_mode:'HTML'}),
|
|
1598
1599
|
remove: (chat,id) => bot.api.deleteMessage(chat,id),
|
|
1599
1600
|
close: (chat,id) => bot.api.editMessageText(chat,id,'Session view closed.'),
|
|
1600
1601
|
allowed: (chat,user) => chat === user && loadAccess().allowFrom.includes(user),
|
|
1602
|
+
report: err => logCallbackFailure('session refresh', err),
|
|
1601
1603
|
persist: entries => {
|
|
1602
1604
|
mkdirSync(STATE_DIR,{recursive:true,mode:0o700})
|
|
1603
1605
|
const temp=SESSION_BROWSER_FILE+'.tmp'
|
|
@@ -1608,7 +1610,7 @@ setInterval(()=>{void liveSessionBrowser.tick().catch(()=>{})},3000).unref()
|
|
|
1608
1610
|
bot.command('session',async ctx=>{
|
|
1609
1611
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1610
1612
|
try{await liveSessionBrowser.open(String(ctx.chat.id),String(ctx.from!.id))}
|
|
1611
|
-
catch{await ctx
|
|
1613
|
+
catch(err){await replyCallbackFailure(ctx,err,'session','session info')}
|
|
1612
1614
|
})
|
|
1613
1615
|
|
|
1614
1616
|
// /sessions — list sessions with inline keyboard for switching/deleting
|
|
@@ -1655,7 +1657,8 @@ bot.command('sessions', async ctx => {
|
|
|
1655
1657
|
lines.push('Tap a session to switch, \ud83d\uddd1 to delete')
|
|
1656
1658
|
|
|
1657
1659
|
await ctx.reply(lines.join('\n'), { reply_markup: keyboard })
|
|
1658
|
-
} catch {
|
|
1660
|
+
} catch (err) {
|
|
1661
|
+
logCallbackFailure('sessions', err)
|
|
1659
1662
|
await ctx.reply('Failed to get sessions.')
|
|
1660
1663
|
}
|
|
1661
1664
|
})
|
|
@@ -1719,10 +1722,10 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1719
1722
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1720
1723
|
const message=ctx.callbackQuery.message
|
|
1721
1724
|
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),body:JSON.stringify({command:'telegram_question',chat_id:String(message.chat.id),payload:{user_id:String(ctx.from.id),question_id:questionControl[1],action:questionControl[2],thread:'message_thread_id' in message?String(message.message_thread_id??''):''}})})
|
|
1722
|
-
const result=await response.json() as {success?:boolean;text?:string;error?:string}
|
|
1725
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as {success?:boolean;text?:string;error?:string}
|
|
1723
1726
|
const confirmation=(response.ok&&result.success?result.text:result.error)??'Question unavailable or already answered.'
|
|
1724
1727
|
await ctx.answerCallbackQuery({text:confirmation.slice(0,180)}).catch(()=>{})
|
|
1725
|
-
}catch{await ctx.answerCallbackQuery({text:'Question unavailable. Use /tasks to refresh.'}).catch(()=>{})}
|
|
1728
|
+
}catch(err){logCallbackFailure('question button',err);await ctx.answerCallbackQuery({text:'Question unavailable. Use /tasks to refresh.'}).catch(()=>{})}
|
|
1726
1729
|
return
|
|
1727
1730
|
}
|
|
1728
1731
|
|
|
@@ -1733,11 +1736,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1733
1736
|
try{
|
|
1734
1737
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1735
1738
|
const response=await fetch(CALLBACK_URL_BASE+'/command',{method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),body:JSON.stringify({command:'telegram_voice_retry',chat_id:String(ctx.callbackQuery.message.chat.id),payload:{user_id:String(ctx.from.id),input_id:voiceRetry[1]}})})
|
|
1736
|
-
const result=await response.json() as {success?:boolean;text?:string;error?:string}
|
|
1739
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as {success?:boolean;text?:string;error?:string}
|
|
1737
1740
|
await ctx.answerCallbackQuery({text:((response.ok&&result.success?result.text:result.error)??'Voice note cannot be retried.').slice(0,180)}).catch(()=>{})
|
|
1738
1741
|
// Any answer settles this button: a retry was queued, or the note cannot be retried.
|
|
1739
1742
|
if(response.ok&&result.success)await ctx.editMessageReplyMarkup({reply_markup:undefined}).catch(()=>{})
|
|
1740
|
-
}catch{await ctx.answerCallbackQuery({text:'Voice retry unavailable. Please send the voice note again.'}).catch(()=>{})}
|
|
1743
|
+
}catch(err){logCallbackFailure('voice retry button',err);await ctx.answerCallbackQuery({text:'Voice retry unavailable. Please send the voice note again.'}).catch(()=>{})}
|
|
1741
1744
|
return
|
|
1742
1745
|
}
|
|
1743
1746
|
|
|
@@ -1755,7 +1758,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1755
1758
|
if(action==='voicepick') await confirmSelection(ctx,`✅ Agent voice: ${result.name} · ${result.provider}`)
|
|
1756
1759
|
else await ctx.deleteMessage().catch(()=>{})
|
|
1757
1760
|
}
|
|
1758
|
-
}catch{await ctx.answerCallbackQuery({text:'Voice list changed or unavailable. Use /voices again.'}).catch(()=>{})}
|
|
1761
|
+
}catch(err){logCallbackFailure('voices button',err);await ctx.answerCallbackQuery({text:'Voice list changed or unavailable. Use /voices again.'}).catch(()=>{})}
|
|
1759
1762
|
return
|
|
1760
1763
|
}
|
|
1761
1764
|
|
|
@@ -1766,7 +1769,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1766
1769
|
await ctx.answerCallbackQuery().catch(()=>{})
|
|
1767
1770
|
const payload=data==='taskdismiss'?{action:'dismiss'}:taskBrowser[1]?{action:taskBrowser[1]==='taskcancel'?'cancel':'detail',task_id:taskBrowser[2]}:{page:Number(taskBrowser[4])}
|
|
1768
1771
|
await liveTaskBrowser.navigate(String(ctx.callbackQuery.message.chat.id),String(ctx.from.id),ctx.callbackQuery.message.message_id,payload)
|
|
1769
|
-
}catch
|
|
1772
|
+
}catch(err){
|
|
1773
|
+
// A button on a replaced or closed menu is expected, not a failure.
|
|
1774
|
+
if(!(err instanceof Error&&err.message==='TASK_BROWSER_EXPIRED'))logCallbackFailure('tasks button',err)
|
|
1775
|
+
await ctx.answerCallbackQuery({text:'Task unavailable. Use /tasks to refresh.'}).catch(()=>{})
|
|
1776
|
+
}
|
|
1770
1777
|
return
|
|
1771
1778
|
}
|
|
1772
1779
|
|
|
@@ -1779,7 +1786,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1779
1786
|
// Turn on/off ends the menu with its result and no buttons, as a /voice choice does.
|
|
1780
1787
|
if(menu.done){await confirmSelection(ctx,menu.text).catch(()=>{});return}
|
|
1781
1788
|
await ctx.editMessageText(menu.text,{reply_markup:menu.reply_markup}).catch(()=>{})
|
|
1782
|
-
}catch{await ctx.answerCallbackQuery({text:'pstack setup unavailable. Use /pstack_setup again.'}).catch(()=>{})}
|
|
1789
|
+
}catch(err){logCallbackFailure('pstack_setup button',err);await ctx.answerCallbackQuery({text:'pstack setup unavailable. Use /pstack_setup again.'}).catch(()=>{})}
|
|
1783
1790
|
return
|
|
1784
1791
|
}
|
|
1785
1792
|
|
|
@@ -1794,7 +1801,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1794
1801
|
await ctx.answerCallbackQuery({text:Number(taskStop[2])===0?'Dismissed':'Stop requested.'}).catch(()=>{})
|
|
1795
1802
|
await ctx.deleteMessage().catch(()=>{})
|
|
1796
1803
|
if (Number(taskStop[2])!==0) await ctx.reply(result.text??'Stop requested.')
|
|
1797
|
-
} catch
|
|
1804
|
+
} catch (err) {
|
|
1805
|
+
// A button on an expired or replaced menu is expected, not a failure.
|
|
1806
|
+
if ((err as {code?:unknown}|null)?.code !== 'STOP_MENU_EXPIRED') logCallbackFailure('stop button', err)
|
|
1807
|
+
await ctx.answerCallbackQuery({text:'Selection unavailable. Use /stop to refresh.'}).catch(()=>{})
|
|
1808
|
+
}
|
|
1798
1809
|
return
|
|
1799
1810
|
}
|
|
1800
1811
|
|
|
@@ -1813,7 +1824,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1813
1824
|
const confirmation=voiceModeConfirmation(data.slice(6))
|
|
1814
1825
|
await ctx.answerCallbackQuery({text:confirmation}).catch(()=>{})
|
|
1815
1826
|
await confirmSelection(ctx,confirmation)
|
|
1816
|
-
} catch { await ctx.answerCallbackQuery({ text: 'Could not update voice settings. Please try again.' }).catch(() => {}) }
|
|
1827
|
+
} catch (err) { logCallbackFailure('voice button', err); await ctx.answerCallbackQuery({ text: 'Could not update voice settings. Please try again.' }).catch(() => {}) }
|
|
1817
1828
|
return
|
|
1818
1829
|
}
|
|
1819
1830
|
|
|
@@ -2000,7 +2011,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2000
2011
|
} else {
|
|
2001
2012
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2002
2013
|
}
|
|
2003
|
-
} catch {
|
|
2014
|
+
} catch (err) {
|
|
2015
|
+
logCallbackFailure('model button', err)
|
|
2004
2016
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2005
2017
|
}
|
|
2006
2018
|
return
|
|
@@ -2047,7 +2059,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2047
2059
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2048
2060
|
await ctx.editMessageText(`Restart failed: ${result.error ?? 'unknown error'}`).catch(() => {})
|
|
2049
2061
|
}
|
|
2050
|
-
} catch {
|
|
2062
|
+
} catch (err) {
|
|
2063
|
+
logCallbackFailure('restart button', err)
|
|
2051
2064
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2052
2065
|
}
|
|
2053
2066
|
return
|
|
@@ -2084,7 +2097,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2084
2097
|
headers: { 'Content-Type': 'application/json' },
|
|
2085
2098
|
body: JSON.stringify({ command: 'compact_confirm', chat_id: chatId }),
|
|
2086
2099
|
})
|
|
2087
|
-
} catch {
|
|
2100
|
+
} catch (err) {
|
|
2101
|
+
logCallbackFailure('compact button', err)
|
|
2088
2102
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2089
2103
|
}
|
|
2090
2104
|
return
|
|
@@ -2118,7 +2132,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2118
2132
|
} else {
|
|
2119
2133
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2120
2134
|
}
|
|
2121
|
-
} catch {
|
|
2135
|
+
} catch (err) {
|
|
2136
|
+
logCallbackFailure('session switch button', err)
|
|
2122
2137
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2123
2138
|
}
|
|
2124
2139
|
return
|
|
@@ -2172,7 +2187,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2172
2187
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2173
2188
|
await ctx.editMessageText(`Delete failed: ${result.error ?? 'unknown error'}`).catch(() => {})
|
|
2174
2189
|
}
|
|
2175
|
-
} catch {
|
|
2190
|
+
} catch (err) {
|
|
2191
|
+
logCallbackFailure('session delete button', err)
|
|
2176
2192
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2177
2193
|
}
|
|
2178
2194
|
return
|
|
@@ -2211,7 +2227,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2211
2227
|
} else {
|
|
2212
2228
|
await ctx.reply(`\u274C Clear failed: ${result.error ?? 'Unknown error'}`).catch(() => {})
|
|
2213
2229
|
}
|
|
2214
|
-
} catch {
|
|
2230
|
+
} catch (err) {
|
|
2231
|
+
logCallbackFailure('session clear button', err)
|
|
2215
2232
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2216
2233
|
}
|
|
2217
2234
|
return
|
|
@@ -2255,7 +2272,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2255
2272
|
} else {
|
|
2256
2273
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2257
2274
|
}
|
|
2258
|
-
} catch {
|
|
2275
|
+
} catch (err) {
|
|
2276
|
+
logCallbackFailure('session new button', err)
|
|
2259
2277
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2260
2278
|
}
|
|
2261
2279
|
return
|
|
@@ -1,10 +1,26 @@
|
|
|
1
|
+
import { CallbackHttpError, callbackRejection } from './callback-failure';
|
|
2
|
+
|
|
1
3
|
/** A successful empty session is a status, not a transport failure. The empty
|
|
2
4
|
* ID binds its live message until a real session appears, when it is retired. */
|
|
3
|
-
export function parseSessionInfo(
|
|
5
|
+
export function parseSessionInfo(value: unknown): { sessionId: string; text: string } {
|
|
4
6
|
const result = value as { success?: unknown; sessionId?: unknown; text?: unknown } | null;
|
|
5
|
-
if (
|
|
7
|
+
if (result?.success !== true) throw callbackRejection(result, 'Session info unavailable');
|
|
8
|
+
if (typeof result.text !== 'string' ||
|
|
6
9
|
!(result.sessionId === null || (typeof result.sessionId === 'string' && result.sessionId.length > 0))) {
|
|
7
10
|
throw new Error('Session info unavailable');
|
|
8
11
|
}
|
|
9
12
|
return { sessionId: result.sessionId ?? '', text: result.text };
|
|
10
13
|
}
|
|
14
|
+
|
|
15
|
+
/** Reads `session_info` from the agent callback. A non-OK response throws
|
|
16
|
+
* CallbackHttpError with its status so the failure log keeps it. */
|
|
17
|
+
export async function requestSessionInfo(base: string | undefined, chatId: string, timeoutMs = 10000) {
|
|
18
|
+
if (!base) throw new Error('not_configured');
|
|
19
|
+
const response = await fetch(base + '/command', {
|
|
20
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(timeoutMs),
|
|
21
|
+
body: JSON.stringify({ command: 'session_info', chat_id: chatId }),
|
|
22
|
+
});
|
|
23
|
+
// Read the error body: it carries the agent's reason and frees the socket.
|
|
24
|
+
if (!response.ok) throw new CallbackHttpError(response.status, await response.json().catch(() => null));
|
|
25
|
+
return parseSessionInfo(await response.json());
|
|
26
|
+
}
|
|
@@ -10,7 +10,7 @@ export interface TaskBrowserResult {
|
|
|
10
10
|
page?: number;
|
|
11
11
|
}
|
|
12
12
|
export interface TaskBrowserMenu { text: string; reply_markup: unknown }
|
|
13
|
-
interface Entry extends TaskBrowserMessage { fingerprint?: string; retryAt?: number; finished?: boolean }
|
|
13
|
+
interface Entry extends TaskBrowserMessage { fingerprint?: string; retryAt?: number; finished?: boolean; refreshReported?: boolean }
|
|
14
14
|
interface Dependencies {
|
|
15
15
|
read(chat: string, user: string, payload: Record<string, unknown>): Promise<TaskBrowserResult>;
|
|
16
16
|
render(result: TaskBrowserResult): TaskBrowserMenu;
|
|
@@ -20,6 +20,8 @@ interface Dependencies {
|
|
|
20
20
|
close(chat: string, id: number): Promise<unknown>;
|
|
21
21
|
allowed(chat: string, user: string): boolean;
|
|
22
22
|
persist(entries: TaskBrowserMessage[]): void;
|
|
23
|
+
/** Called once per streak of failed background refreshes. */
|
|
24
|
+
report?(error: unknown): void;
|
|
23
25
|
now?: () => number;
|
|
24
26
|
}
|
|
25
27
|
const description = (e: any) => String(e?.description ?? e?.message ?? '');
|
|
@@ -88,10 +90,10 @@ export class LiveTaskBrowser {
|
|
|
88
90
|
if (JSON.stringify(view) !== JSON.stringify(e.view)) { e.view = view; this.persist(); }
|
|
89
91
|
const finished = !!result.task && ['completed','failed','cancelled'].includes(result.task.state);
|
|
90
92
|
const menu = this.io.render(result), fingerprint = JSON.stringify(menu);
|
|
91
|
-
if (fingerprint === e.fingerprint) { e.finished = finished; return; }
|
|
93
|
+
if (fingerprint === e.fingerprint) { e.refreshReported = false; e.finished = finished; return; }
|
|
92
94
|
try { await this.io.edit(e.chatId,e.messageId,menu); }
|
|
93
95
|
catch (error) { if (!unchanged(error)) throw error; }
|
|
94
|
-
e.fingerprint = fingerprint; e.retryAt = undefined; e.finished = finished;
|
|
96
|
+
e.fingerprint = fingerprint; e.retryAt = undefined; e.refreshReported = false; e.finished = finished;
|
|
95
97
|
}
|
|
96
98
|
private async failure(e: Entry, error: any) {
|
|
97
99
|
if (description(error).includes('TASK_SESSION_CHANGED')) { await this.retire(e); return; }
|
|
@@ -110,7 +112,11 @@ export class LiveTaskBrowser {
|
|
|
110
112
|
this.entries.delete(e.chatId); this.persist(); return;
|
|
111
113
|
}
|
|
112
114
|
try { await this.update(e,await this.io.read(e.chatId,e.userId,{...e.view,session_id:e.sessionId})); }
|
|
113
|
-
catch (error) {
|
|
115
|
+
catch (error) {
|
|
116
|
+
await this.failure(e,error).catch(() => {});
|
|
117
|
+
// A retired or expired view is normal; only a view still waiting to refresh is reported.
|
|
118
|
+
if (!e.refreshReported && this.entries.get(e.chatId) === e) { e.refreshReported = true; this.io.report?.(error); }
|
|
119
|
+
}
|
|
114
120
|
});
|
|
115
121
|
}
|
|
116
122
|
}
|