@0xmaxma/claude-gateway 2.1.13 โ 2.1.15
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/model-catalog.d.ts +10 -0
- package/dist/agent/model-catalog.d.ts.map +1 -1
- package/dist/agent/model-catalog.js +93 -25
- package/dist/agent/model-catalog.js.map +1 -1
- package/dist/agent/model-registry.d.ts +15 -0
- package/dist/agent/model-registry.d.ts.map +1 -1
- package/dist/agent/model-registry.js +26 -0
- package/dist/agent/model-registry.js.map +1 -1
- package/dist/agent/runner.d.ts +5 -1
- package/dist/agent/runner.d.ts.map +1 -1
- package/dist/agent/runner.js +57 -32
- package/dist/agent/runner.js.map +1 -1
- package/dist/api/gateway-router.js +2 -2
- package/dist/api/gateway-router.js.map +1 -1
- package/dist/api/packages.d.ts.map +1 -1
- package/dist/api/packages.js +12 -11
- package/dist/api/packages.js.map +1 -1
- package/dist/api/router.d.ts.map +1 -1
- package/dist/api/router.js +9 -7
- package/dist/api/router.js.map +1 -1
- package/dist/build-provenance.json +4 -4
- package/dist/cli/commands/update.d.ts.map +1 -1
- package/dist/cli/commands/update.js +18 -7
- package/dist/cli/commands/update.js.map +1 -1
- package/dist/cron/manager.d.ts.map +1 -1
- package/dist/cron/manager.js +6 -3
- package/dist/cron/manager.js.map +1 -1
- package/dist/cron/scheduler.d.ts +1 -0
- package/dist/cron/scheduler.d.ts.map +1 -1
- package/dist/cron/scheduler.js +76 -5
- package/dist/cron/scheduler.js.map +1 -1
- package/dist/cron/validate.d.ts +10 -0
- package/dist/cron/validate.d.ts.map +1 -0
- package/dist/cron/validate.js +37 -0
- package/dist/cron/validate.js.map +1 -0
- package/dist/heartbeat/parser.d.ts +12 -3
- package/dist/heartbeat/parser.d.ts.map +1 -1
- package/dist/heartbeat/parser.js +35 -97
- package/dist/heartbeat/parser.js.map +1 -1
- package/dist/orchestration/bridge.d.ts +2 -0
- package/dist/orchestration/bridge.d.ts.map +1 -1
- package/dist/orchestration/bridge.js +54 -14
- package/dist/orchestration/bridge.js.map +1 -1
- package/dist/orchestration/runtime.d.ts +2 -0
- package/dist/orchestration/runtime.d.ts.map +1 -1
- package/dist/orchestration/runtime.js +2 -2
- package/dist/orchestration/runtime.js.map +1 -1
- package/dist/orchestration/tasks/driver.d.ts.map +1 -1
- package/dist/orchestration/tasks/driver.js +4 -0
- package/dist/orchestration/tasks/driver.js.map +1 -1
- package/dist/orchestration/tasks/service.d.ts +3 -0
- package/dist/orchestration/tasks/service.d.ts.map +1 -1
- package/dist/orchestration/tasks/service.js +24 -3
- package/dist/orchestration/tasks/service.js.map +1 -1
- package/dist/orchestration/token-ledger.d.ts +6 -0
- package/dist/orchestration/token-ledger.d.ts.map +1 -1
- package/dist/orchestration/token-ledger.js +2 -1
- package/dist/orchestration/token-ledger.js.map +1 -1
- package/dist/orchestration/types.d.ts +4 -0
- package/dist/orchestration/types.d.ts.map +1 -1
- package/dist/orchestration/types.js.map +1 -1
- package/dist/packages/npm-staging.d.ts +55 -0
- package/dist/packages/npm-staging.d.ts.map +1 -0
- package/dist/packages/npm-staging.js +349 -0
- package/dist/packages/npm-staging.js.map +1 -0
- package/dist/packages/registry.d.ts +24 -10
- package/dist/packages/registry.d.ts.map +1 -1
- package/dist/packages/registry.js +125 -66
- package/dist/packages/registry.js.map +1 -1
- package/dist/types.d.ts +12 -3
- package/dist/types.d.ts.map +1 -1
- package/mcp/tools/telegram/callback-failure.ts +94 -0
- package/mcp/tools/telegram/model-menu-request.ts +4 -1
- package/mcp/tools/telegram/receiver-server.ts +107 -95
- package/mcp/tools/telegram/session-browser.ts +18 -2
- package/mcp/tools/telegram/session-list.ts +82 -0
- package/mcp/tools/telegram/task-browser.ts +12 -5
- package/package.json +1 -1
|
@@ -1,6 +1,8 @@
|
|
|
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 { listSessionsRequest, sessionListMenu } from './session-list';
|
|
5
|
+
import { CallbackHttpError, callbackFailureReply, callbackRejection, classifyCallbackFailure, formatCallbackFailure, logCallbackFailure, readCallbackResult } from './callback-failure';
|
|
4
6
|
import { fetchModelMenuResponses, sendModelMenuReply } from './model-menu-request';
|
|
5
7
|
/**
|
|
6
8
|
* Telegram channel for Claude Gateway.
|
|
@@ -29,7 +31,7 @@ import { Bot, GrammyError, InlineKeyboard, InputFile, type Context } from 'gramm
|
|
|
29
31
|
import type { ReactionTypeEmoji } from 'grammy/types'
|
|
30
32
|
import { randomBytes } from 'crypto'
|
|
31
33
|
import { confirmSelection, voiceModeConfirmation } from './selection-confirmation'
|
|
32
|
-
import { LiveTaskBrowser, type TaskBrowserMessage } from './task-browser'
|
|
34
|
+
import { LiveTaskBrowser, unchanged, type TaskBrowserMessage } from './task-browser'
|
|
33
35
|
import { PSTACK_MENU_COMMAND, pstackMenuMarkup } from './pstack-menu'
|
|
34
36
|
import { ReceiverSpool } from '../receiver-spool'
|
|
35
37
|
const orchestrationSpool = process.env.GATEWAY_ORCHESTRATION_INGRESS_DIR && process.env.CLAUDE_CHANNEL_CALLBACK
|
|
@@ -1250,13 +1252,15 @@ bot.command('model', async ctx => {
|
|
|
1250
1252
|
method: 'POST',
|
|
1251
1253
|
headers: { 'Content-Type': 'application/json' },
|
|
1252
1254
|
body: JSON.stringify({ command: 'get_model', chat_id: String(ctx.chat.id) }),
|
|
1255
|
+
signal: AbortSignal.timeout(10_000),
|
|
1253
1256
|
})
|
|
1257
|
+
if (!res.ok) throw new CallbackHttpError(res.status)
|
|
1254
1258
|
const data = (await res.json()) as { model?: string }
|
|
1255
1259
|
await ctx.reply(groupAccess && groupInput
|
|
1256
1260
|
? telegramGroupModelReply(groupAccess, groupInput, data.model ?? 'unknown') ?? 'Current model: unknown'
|
|
1257
1261
|
: `Current model: ${data.model ?? 'unknown'}`)
|
|
1258
1262
|
} catch (err) {
|
|
1259
|
-
await ctx
|
|
1263
|
+
await replyCallbackFailure(ctx, err, 'model', 'model info')
|
|
1260
1264
|
}
|
|
1261
1265
|
})
|
|
1262
1266
|
|
|
@@ -1315,17 +1319,11 @@ bot.command('models', async ctx => {
|
|
|
1315
1319
|
reply_markup: keyboard,
|
|
1316
1320
|
}, signal as Parameters<Context['reply']>[2]))
|
|
1317
1321
|
} catch (err) {
|
|
1318
|
-
const errorName = err instanceof Error ? err.name : 'UnknownError'
|
|
1319
|
-
process.stderr.write(`telegram channel: /models ${stage} failed (${errorName})\n`)
|
|
1320
1322
|
// A failed send may already have reached Telegram. Only a callback failure
|
|
1321
1323
|
// is known to have occurred before any menu message was sent.
|
|
1322
|
-
if (stage !== 'callback') return
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
} catch (replyErr) {
|
|
1326
|
-
const replyErrorName = replyErr instanceof Error ? replyErr.name : 'UnknownError'
|
|
1327
|
-
process.stderr.write(`telegram channel: /models fallback send failed (${replyErrorName})\n`)
|
|
1328
|
-
}
|
|
1324
|
+
if (stage !== 'callback') { logCallbackFailure('models send', err); return }
|
|
1325
|
+
await replyCallbackFailure(ctx, err, 'models', 'model info', undefined,
|
|
1326
|
+
text => sendModelMenuReply(signal => ctx.reply(text, {}, signal as Parameters<Context['reply']>[2])))
|
|
1329
1327
|
}
|
|
1330
1328
|
})
|
|
1331
1329
|
|
|
@@ -1404,9 +1402,7 @@ type VoicePicker = {menuId:string;provider:string;page:number;pages:number;gende
|
|
|
1404
1402
|
async function voicePickerRequest(chatId:string,userId:string,payload:Record<string,unknown>={}) {
|
|
1405
1403
|
if(!CALLBACK_URL_BASE)throw new Error('not_configured')
|
|
1406
1404
|
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
|
|
1405
|
+
return readCallbackResult<VoicePicker & {success?:boolean;name?:string}>(response)
|
|
1410
1406
|
}
|
|
1411
1407
|
function voicePickerMenu(menu:VoicePicker) {
|
|
1412
1408
|
const keyboard=new InlineKeyboard()
|
|
@@ -1426,16 +1422,29 @@ bot.command('voices',async ctx=>{
|
|
|
1426
1422
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1427
1423
|
if(!ORCHESTRATION_ENABLED){await ctx.reply('Voice controls require orchestration mode.');return}
|
|
1428
1424
|
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
|
|
1425
|
+
catch(err){await replyCallbackFailure(ctx,err,'voices','the voice list','Voice list unavailable. Check the TTS provider configuration and try /voices again.')}
|
|
1430
1426
|
})
|
|
1431
1427
|
|
|
1432
1428
|
type TaskView = TaskDetail & {taskId:string;title:string;state:string;progress?:string;question?:string;updatedAt:number;startedAt?:number;finishedAt?:number;canStop:boolean}
|
|
1433
1429
|
type TaskBrowser = {sessionId:string;task?:TaskView;tasks?:TaskView[];page?:number;pages?:number;total?:number}
|
|
1430
|
+
// Log why a callback-backed command failed, then tell the user whether the
|
|
1431
|
+
// agent timed out, is restarting, or failed. The reply itself may fail too.
|
|
1432
|
+
// `failedReply` replaces the generic text when the agent answered with an error.
|
|
1433
|
+
// `send` replaces ctx.reply, e.g. to bound a send that Telegram may stall.
|
|
1434
|
+
async function replyCallbackFailure(ctx:Context,err:unknown,command:string,what:string,failedReply?:string,send:(text:string)=>Promise<unknown>=text=>ctx.reply(text)) {
|
|
1435
|
+
const failure=classifyCallbackFailure(err)
|
|
1436
|
+
process.stderr.write(formatCallbackFailure(command,failure)+'\n')
|
|
1437
|
+
try{await send(failure.kind==='failed'&&failedReply&&failure.telegramCode===undefined?failedReply:callbackFailureReply(failure.kind,what,command,failure.telegramCode))}
|
|
1438
|
+
catch(replyErr){process.stderr.write(formatCallbackFailure(`${command} reply`,classifyCallbackFailure(replyErr))+'\n')}
|
|
1439
|
+
}
|
|
1434
1440
|
async function taskBrowserRequest(chatId:string,userId:string,payload:Record<string,unknown>={}) {
|
|
1435
1441
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1436
1442
|
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
|
-
|
|
1443
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as TaskBrowser & {success?:boolean}
|
|
1444
|
+
const error=(result as {error?:unknown}|null)?.error
|
|
1445
|
+
if(error==='TASK_SESSION_CHANGED')throw Error('TASK_SESSION_CHANGED')
|
|
1446
|
+
if(!response.ok)throw new CallbackHttpError(response.status,result)
|
|
1447
|
+
if(!result?.success)throw callbackRejection(result)
|
|
1439
1448
|
if(typeof result.sessionId!=='string'||!result.sessionId)throw Error('unavailable')
|
|
1440
1449
|
return result
|
|
1441
1450
|
}
|
|
@@ -1469,6 +1478,7 @@ const liveTaskBrowser = new LiveTaskBrowser({
|
|
|
1469
1478
|
remove: (chat, id) => bot.api.deleteMessage(chat, id),
|
|
1470
1479
|
close: (chat, id) => bot.api.editMessageText(chat, id, 'Task view closed.', {reply_markup: {inline_keyboard: []}}),
|
|
1471
1480
|
allowed: (chat, user) => ORCHESTRATION_ENABLED && chat === user && loadAccess().allowFrom.includes(user),
|
|
1481
|
+
report: err => logCallbackFailure('tasks refresh', err),
|
|
1472
1482
|
persist: entries => {
|
|
1473
1483
|
mkdirSync(STATE_DIR, {recursive:true,mode:0o700})
|
|
1474
1484
|
const temp = TASK_BROWSER_FILE + '.tmp'
|
|
@@ -1480,7 +1490,7 @@ bot.command('tasks',async ctx=>{
|
|
|
1480
1490
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1481
1491
|
if(!ORCHESTRATION_ENABLED){await ctx.reply('Task controls require orchestration mode.');return}
|
|
1482
1492
|
try{await liveTaskBrowser.open(String(ctx.chat.id),String(ctx.from!.id))}
|
|
1483
|
-
catch{await ctx
|
|
1493
|
+
catch(err){await replyCallbackFailure(ctx,err,'tasks','tasks')}
|
|
1484
1494
|
})
|
|
1485
1495
|
|
|
1486
1496
|
// /pstack-setup (Telegram also takes /pstack_setup: command names cannot contain '-').
|
|
@@ -1490,15 +1500,13 @@ bot.command('tasks',async ctx=>{
|
|
|
1490
1500
|
async function pstackMenuRequest(chatId:string,userId:string,data:string) {
|
|
1491
1501
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1492
1502
|
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)
|
|
1503
|
+
return pstackMenuMarkup(await readCallbackResult<{success?:boolean}>(response))
|
|
1496
1504
|
}
|
|
1497
1505
|
bot.hears(PSTACK_MENU_COMMAND,async (ctx,next)=>{
|
|
1498
1506
|
if(ctx.chat?.type!=='private'||!CALLBACK_URL_BASE)return next()
|
|
1499
1507
|
if(!isCallbackAuthorized(ctx))return
|
|
1500
1508
|
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
|
|
1509
|
+
catch(err){await replyCallbackFailure(ctx,err,'pstack_setup','pstack setup','pstack setup unavailable. Please try /pstack_setup again.')}
|
|
1502
1510
|
})
|
|
1503
1511
|
|
|
1504
1512
|
async function taskStopRequest(chatId: string, userId: string, menuId?: string, index?: number) {
|
|
@@ -1507,9 +1515,7 @@ async function taskStopRequest(chatId: string, userId: string, menuId?: string,
|
|
|
1507
1515
|
method:'POST',headers:{'Content-Type':'application/json'},signal:AbortSignal.timeout(10000),
|
|
1508
1516
|
body:JSON.stringify({command:'task_stop',chat_id:chatId,payload:{user_id:userId,menu_id:menuId,index}}),
|
|
1509
1517
|
})
|
|
1510
|
-
|
|
1511
|
-
if (!response.ok || !result.success) throw new Error('unavailable')
|
|
1512
|
-
return result
|
|
1518
|
+
return readCallbackResult<{success?:boolean;legacy?:boolean;text?:string;menuId?:string;tasks?:Array<{title:string;state:string}>}>(response)
|
|
1513
1519
|
}
|
|
1514
1520
|
bot.command('stop',async (ctx,next)=>{
|
|
1515
1521
|
if (!ORCHESTRATION_ENABLED || ctx.chat?.type!=='private') return next()
|
|
@@ -1521,7 +1527,7 @@ bot.command('stop',async (ctx,next)=>{
|
|
|
1521
1527
|
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
1528
|
if (result.tasks?.length) keyboard.text('Dismiss',`taskstop:${result.menuId}:0`)
|
|
1523
1529
|
await ctx.reply(result.text??'Nothing to stop.',result.tasks?.length?{reply_markup:keyboard}:{})
|
|
1524
|
-
} catch { await ctx
|
|
1530
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'stop', 'tasks') }
|
|
1525
1531
|
})
|
|
1526
1532
|
|
|
1527
1533
|
// Voice settings are handled directly; no model call or TTS for this menu.
|
|
@@ -1533,8 +1539,8 @@ async function telegramVoiceSetting(chatId: string, mode?: VoiceReplyMode): Prom
|
|
|
1533
1539
|
body: JSON.stringify({ command: 'telegram_voice', chat_id: chatId, payload: { mode } }),
|
|
1534
1540
|
signal: AbortSignal.timeout(10000),
|
|
1535
1541
|
})
|
|
1536
|
-
const result = await
|
|
1537
|
-
if (
|
|
1542
|
+
const result = await readCallbackResult<{ success?: boolean; enabled?: boolean; mode?: VoiceReplyMode }>(response)
|
|
1543
|
+
if (typeof result.enabled !== 'boolean') throw new Error('invalid voice settings reply')
|
|
1538
1544
|
return result.mode ?? (result.enabled ? 'on' : 'off')
|
|
1539
1545
|
}
|
|
1540
1546
|
function voiceMenu(mode: VoiceReplyMode) {
|
|
@@ -1553,7 +1559,7 @@ bot.command('voice', async ctx => {
|
|
|
1553
1559
|
try {
|
|
1554
1560
|
const menu = voiceMenu(await telegramVoiceSetting(String(ctx.chat.id), choice ? choice as VoiceReplyMode : undefined))
|
|
1555
1561
|
await ctx.reply(menu.text, choice ? {} : { reply_markup: menu.reply_markup })
|
|
1556
|
-
} catch { await ctx
|
|
1562
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'voice', 'voice settings', 'Voice settings are unavailable. Check the agent TTS configuration.') }
|
|
1557
1563
|
})
|
|
1558
1564
|
|
|
1559
1565
|
// /call โ open a live voice call as a Telegram Mini App bound to this DM. The
|
|
@@ -1575,7 +1581,7 @@ bot.command('call', async ctx => {
|
|
|
1575
1581
|
}
|
|
1576
1582
|
// web_app buttons open the Mini App with signed initData; Telegram requires HTTPS.
|
|
1577
1583
|
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
|
|
1584
|
+
} catch (err) { await replyCallbackFailure(ctx, err, 'call', 'a voice call', 'Could not start a voice call right now.') }
|
|
1579
1585
|
})
|
|
1580
1586
|
|
|
1581
1587
|
// Reuse the /tasks live-message lifecycle: serialize reads/replacement, edit only
|
|
@@ -1584,20 +1590,14 @@ const SESSION_BROWSER_FILE = join(STATE_DIR, 'session-browser.json')
|
|
|
1584
1590
|
let restoredSessionBrowsers: TaskBrowserMessage[] = []
|
|
1585
1591
|
try { const saved = JSON.parse(readFileSync(SESSION_BROWSER_FILE, 'utf8')); if (Array.isArray(saved)) restoredSessionBrowsers = saved } catch {}
|
|
1586
1592
|
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
|
-
},
|
|
1593
|
+
read: chat => requestSessionInfo(CALLBACK_URL_BASE, chat),
|
|
1595
1594
|
render: result => ({text:(result as {sessionId:string;text:string}).text,reply_markup:{inline_keyboard:[]}}),
|
|
1596
1595
|
send: async (chat,menu) => (await bot.api.sendMessage(chat,menu.text,{parse_mode:'HTML'})).message_id,
|
|
1597
1596
|
edit: (chat,id,menu) => bot.api.editMessageText(chat,id,menu.text,{parse_mode:'HTML'}),
|
|
1598
1597
|
remove: (chat,id) => bot.api.deleteMessage(chat,id),
|
|
1599
1598
|
close: (chat,id) => bot.api.editMessageText(chat,id,'Session view closed.'),
|
|
1600
1599
|
allowed: (chat,user) => chat === user && loadAccess().allowFrom.includes(user),
|
|
1600
|
+
report: err => logCallbackFailure('session refresh', err),
|
|
1601
1601
|
persist: entries => {
|
|
1602
1602
|
mkdirSync(STATE_DIR,{recursive:true,mode:0o700})
|
|
1603
1603
|
const temp=SESSION_BROWSER_FILE+'.tmp'
|
|
@@ -1608,10 +1608,11 @@ setInterval(()=>{void liveSessionBrowser.tick().catch(()=>{})},3000).unref()
|
|
|
1608
1608
|
bot.command('session',async ctx=>{
|
|
1609
1609
|
if(ctx.chat?.type!=='private'||!isCallbackAuthorized(ctx))return
|
|
1610
1610
|
try{await liveSessionBrowser.open(String(ctx.chat.id),String(ctx.from!.id))}
|
|
1611
|
-
catch{await ctx
|
|
1611
|
+
catch(err){await replyCallbackFailure(ctx,err,'session','session info')}
|
|
1612
1612
|
})
|
|
1613
1613
|
|
|
1614
|
-
// /sessions โ list sessions with inline keyboard for switching/deleting
|
|
1614
|
+
// /sessions โ list sessions with inline keyboard for switching/deleting.
|
|
1615
|
+
// Paged so one keyboard stays under Telegram's button limit (#686).
|
|
1615
1616
|
bot.command('sessions', async ctx => {
|
|
1616
1617
|
if (ctx.chat?.type !== 'private') return
|
|
1617
1618
|
const access = loadAccess()
|
|
@@ -1619,44 +1620,11 @@ bot.command('sessions', async ctx => {
|
|
|
1619
1620
|
if (!CALLBACK_URL_BASE) return
|
|
1620
1621
|
|
|
1621
1622
|
try {
|
|
1622
|
-
const
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
const data = (await res.json()) as {
|
|
1628
|
-
sessions?: Array<{ id: string; name: string; messageCount: number; lastActive: number }>
|
|
1629
|
-
activeSessionId?: string
|
|
1630
|
-
}
|
|
1631
|
-
const sessions = data.sessions ?? []
|
|
1632
|
-
const activeId = data.activeSessionId ?? ''
|
|
1633
|
-
|
|
1634
|
-
const keyboard = new InlineKeyboard()
|
|
1635
|
-
for (const s of sessions) {
|
|
1636
|
-
const isActive = s.id === activeId
|
|
1637
|
-
const label = isActive ? `\ud83d\udfe2 ${s.name}` : s.name
|
|
1638
|
-
if (sessions.length > 1) {
|
|
1639
|
-
keyboard.text(label, `session_switch:${s.id}`).text('\ud83d\uddd1', `session_delete:${s.id}`).row()
|
|
1640
|
-
} else {
|
|
1641
|
-
keyboard.text(label, `session_switch:${s.id}`).row()
|
|
1642
|
-
}
|
|
1643
|
-
}
|
|
1644
|
-
keyboard.text('\u2795 New Session', 'session_new').row()
|
|
1645
|
-
keyboard.text('Dismiss', 'session_back')
|
|
1646
|
-
|
|
1647
|
-
const lines = [`\ud83d\uddc2 Sessions (${sessions.length})`, '']
|
|
1648
|
-
for (const s of sessions) {
|
|
1649
|
-
const isActive = s.id === activeId
|
|
1650
|
-
const ago = Math.round((Date.now() - s.lastActive) / 60000)
|
|
1651
|
-
const ageStr = ago < 60 ? `${ago}m ago` : `${Math.round(ago / 60)}h ago`
|
|
1652
|
-
lines.push(`${isActive ? '\ud83d\udfe2' : '\u26aa'} ${s.name} \u00b7 ${s.messageCount} msgs \u00b7 ${ageStr}`)
|
|
1653
|
-
}
|
|
1654
|
-
lines.push('')
|
|
1655
|
-
lines.push('Tap a session to switch, \ud83d\uddd1 to delete')
|
|
1656
|
-
|
|
1657
|
-
await ctx.reply(lines.join('\n'), { reply_markup: keyboard })
|
|
1658
|
-
} catch {
|
|
1659
|
-
await ctx.reply('Failed to get sessions.')
|
|
1623
|
+
const { sessions, activeId } = await listSessionsRequest(CALLBACK_URL_BASE, String(ctx.chat.id))
|
|
1624
|
+
const menu = sessionListMenu(sessions, activeId, 0)
|
|
1625
|
+
await ctx.reply(menu.text, { reply_markup: menu.reply_markup })
|
|
1626
|
+
} catch (err) {
|
|
1627
|
+
await replyCallbackFailure(ctx, err, 'sessions', 'sessions')
|
|
1660
1628
|
}
|
|
1661
1629
|
})
|
|
1662
1630
|
|
|
@@ -1719,10 +1687,10 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1719
1687
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1720
1688
|
const message=ctx.callbackQuery.message
|
|
1721
1689
|
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}
|
|
1690
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as {success?:boolean;text?:string;error?:string}
|
|
1723
1691
|
const confirmation=(response.ok&&result.success?result.text:result.error)??'Question unavailable or already answered.'
|
|
1724
1692
|
await ctx.answerCallbackQuery({text:confirmation.slice(0,180)}).catch(()=>{})
|
|
1725
|
-
}catch{await ctx.answerCallbackQuery({text:'Question unavailable. Use /tasks to refresh.'}).catch(()=>{})}
|
|
1693
|
+
}catch(err){logCallbackFailure('question button',err);await ctx.answerCallbackQuery({text:'Question unavailable. Use /tasks to refresh.'}).catch(()=>{})}
|
|
1726
1694
|
return
|
|
1727
1695
|
}
|
|
1728
1696
|
|
|
@@ -1733,11 +1701,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1733
1701
|
try{
|
|
1734
1702
|
if(!CALLBACK_URL_BASE)throw Error('not_configured')
|
|
1735
1703
|
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}
|
|
1704
|
+
const result=await response.json().catch(error=>{throw response.ok?error:new CallbackHttpError(response.status)}) as {success?:boolean;text?:string;error?:string}
|
|
1737
1705
|
await ctx.answerCallbackQuery({text:((response.ok&&result.success?result.text:result.error)??'Voice note cannot be retried.').slice(0,180)}).catch(()=>{})
|
|
1738
1706
|
// Any answer settles this button: a retry was queued, or the note cannot be retried.
|
|
1739
1707
|
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(()=>{})}
|
|
1708
|
+
}catch(err){logCallbackFailure('voice retry button',err);await ctx.answerCallbackQuery({text:'Voice retry unavailable. Please send the voice note again.'}).catch(()=>{})}
|
|
1741
1709
|
return
|
|
1742
1710
|
}
|
|
1743
1711
|
|
|
@@ -1755,7 +1723,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1755
1723
|
if(action==='voicepick') await confirmSelection(ctx,`โ
Agent voice: ${result.name} ยท ${result.provider}`)
|
|
1756
1724
|
else await ctx.deleteMessage().catch(()=>{})
|
|
1757
1725
|
}
|
|
1758
|
-
}catch{await ctx.answerCallbackQuery({text:'Voice list changed or unavailable. Use /voices again.'}).catch(()=>{})}
|
|
1726
|
+
}catch(err){logCallbackFailure('voices button',err);await ctx.answerCallbackQuery({text:'Voice list changed or unavailable. Use /voices again.'}).catch(()=>{})}
|
|
1759
1727
|
return
|
|
1760
1728
|
}
|
|
1761
1729
|
|
|
@@ -1766,7 +1734,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1766
1734
|
await ctx.answerCallbackQuery().catch(()=>{})
|
|
1767
1735
|
const payload=data==='taskdismiss'?{action:'dismiss'}:taskBrowser[1]?{action:taskBrowser[1]==='taskcancel'?'cancel':'detail',task_id:taskBrowser[2]}:{page:Number(taskBrowser[4])}
|
|
1768
1736
|
await liveTaskBrowser.navigate(String(ctx.callbackQuery.message.chat.id),String(ctx.from.id),ctx.callbackQuery.message.message_id,payload)
|
|
1769
|
-
}catch
|
|
1737
|
+
}catch(err){
|
|
1738
|
+
// A button on a replaced or closed menu is expected, not a failure.
|
|
1739
|
+
if(!(err instanceof Error&&err.message==='TASK_BROWSER_EXPIRED'))logCallbackFailure('tasks button',err)
|
|
1740
|
+
await ctx.answerCallbackQuery({text:'Task unavailable. Use /tasks to refresh.'}).catch(()=>{})
|
|
1741
|
+
}
|
|
1770
1742
|
return
|
|
1771
1743
|
}
|
|
1772
1744
|
|
|
@@ -1779,7 +1751,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1779
1751
|
// Turn on/off ends the menu with its result and no buttons, as a /voice choice does.
|
|
1780
1752
|
if(menu.done){await confirmSelection(ctx,menu.text).catch(()=>{});return}
|
|
1781
1753
|
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(()=>{})}
|
|
1754
|
+
}catch(err){logCallbackFailure('pstack_setup button',err);await ctx.answerCallbackQuery({text:'pstack setup unavailable. Use /pstack_setup again.'}).catch(()=>{})}
|
|
1783
1755
|
return
|
|
1784
1756
|
}
|
|
1785
1757
|
|
|
@@ -1794,7 +1766,11 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1794
1766
|
await ctx.answerCallbackQuery({text:Number(taskStop[2])===0?'Dismissed':'Stop requested.'}).catch(()=>{})
|
|
1795
1767
|
await ctx.deleteMessage().catch(()=>{})
|
|
1796
1768
|
if (Number(taskStop[2])!==0) await ctx.reply(result.text??'Stop requested.')
|
|
1797
|
-
} catch
|
|
1769
|
+
} catch (err) {
|
|
1770
|
+
// A button on an expired or replaced menu is expected, not a failure.
|
|
1771
|
+
if ((err as {code?:unknown}|null)?.code !== 'STOP_MENU_EXPIRED') logCallbackFailure('stop button', err)
|
|
1772
|
+
await ctx.answerCallbackQuery({text:'Selection unavailable. Use /stop to refresh.'}).catch(()=>{})
|
|
1773
|
+
}
|
|
1798
1774
|
return
|
|
1799
1775
|
}
|
|
1800
1776
|
|
|
@@ -1813,7 +1789,7 @@ bot.on('callback_query:data', async ctx => {
|
|
|
1813
1789
|
const confirmation=voiceModeConfirmation(data.slice(6))
|
|
1814
1790
|
await ctx.answerCallbackQuery({text:confirmation}).catch(()=>{})
|
|
1815
1791
|
await confirmSelection(ctx,confirmation)
|
|
1816
|
-
} catch { await ctx.answerCallbackQuery({ text: 'Could not update voice settings. Please try again.' }).catch(() => {}) }
|
|
1792
|
+
} catch (err) { logCallbackFailure('voice button', err); await ctx.answerCallbackQuery({ text: 'Could not update voice settings. Please try again.' }).catch(() => {}) }
|
|
1817
1793
|
return
|
|
1818
1794
|
}
|
|
1819
1795
|
|
|
@@ -2000,7 +1976,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2000
1976
|
} else {
|
|
2001
1977
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2002
1978
|
}
|
|
2003
|
-
} catch {
|
|
1979
|
+
} catch (err) {
|
|
1980
|
+
logCallbackFailure('model button', err)
|
|
2004
1981
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2005
1982
|
}
|
|
2006
1983
|
return
|
|
@@ -2047,7 +2024,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2047
2024
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2048
2025
|
await ctx.editMessageText(`Restart failed: ${result.error ?? 'unknown error'}`).catch(() => {})
|
|
2049
2026
|
}
|
|
2050
|
-
} catch {
|
|
2027
|
+
} catch (err) {
|
|
2028
|
+
logCallbackFailure('restart button', err)
|
|
2051
2029
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2052
2030
|
}
|
|
2053
2031
|
return
|
|
@@ -2084,12 +2062,42 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2084
2062
|
headers: { 'Content-Type': 'application/json' },
|
|
2085
2063
|
body: JSON.stringify({ command: 'compact_confirm', chat_id: chatId }),
|
|
2086
2064
|
})
|
|
2087
|
-
} catch {
|
|
2065
|
+
} catch (err) {
|
|
2066
|
+
logCallbackFailure('compact button', err)
|
|
2088
2067
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2089
2068
|
}
|
|
2090
2069
|
return
|
|
2091
2070
|
}
|
|
2092
2071
|
|
|
2072
|
+
// Handle /sessions paging: session_page:<n>
|
|
2073
|
+
const sessionPage = /^session_page:(\d{1,4})$/.exec(data)
|
|
2074
|
+
if (sessionPage) {
|
|
2075
|
+
if (ctx.callbackQuery.message?.chat.type !== 'private' || !isCallbackAuthorized(ctx)) {
|
|
2076
|
+
await ctx.answerCallbackQuery({ text: 'Not authorized.' }).catch(() => {})
|
|
2077
|
+
return
|
|
2078
|
+
}
|
|
2079
|
+
if (!CALLBACK_URL_BASE) {
|
|
2080
|
+
await ctx.answerCallbackQuery({ text: 'Not available.' }).catch(() => {})
|
|
2081
|
+
return
|
|
2082
|
+
}
|
|
2083
|
+
try {
|
|
2084
|
+
const { sessions, activeId } = await listSessionsRequest(CALLBACK_URL_BASE, String(ctx.callbackQuery.message?.chat.id ?? ctx.from.id))
|
|
2085
|
+
const menu = sessionListMenu(sessions, activeId, Number(sessionPage[1]))
|
|
2086
|
+
await ctx.editMessageText(menu.text, { reply_markup: menu.reply_markup })
|
|
2087
|
+
await ctx.answerCallbackQuery().catch(() => {})
|
|
2088
|
+
} catch (err) {
|
|
2089
|
+
// Tapping the page already shown leaves the text unchanged; nothing failed.
|
|
2090
|
+
if (unchanged(err)) {
|
|
2091
|
+
await ctx.answerCallbackQuery().catch(() => {})
|
|
2092
|
+
return
|
|
2093
|
+
}
|
|
2094
|
+
const failure = classifyCallbackFailure(err)
|
|
2095
|
+
process.stderr.write(formatCallbackFailure('sessions page', failure) + '\n')
|
|
2096
|
+
await ctx.answerCallbackQuery({ text: callbackFailureReply(failure.kind, 'sessions', 'sessions', failure.telegramCode).slice(0, 180) }).catch(() => {})
|
|
2097
|
+
}
|
|
2098
|
+
return
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2093
2101
|
// Handle session switch: session_switch:<sessionId>
|
|
2094
2102
|
const switchMatch = /^session_switch:(.+)$/.exec(data)
|
|
2095
2103
|
if (switchMatch) {
|
|
@@ -2118,7 +2126,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2118
2126
|
} else {
|
|
2119
2127
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2120
2128
|
}
|
|
2121
|
-
} catch {
|
|
2129
|
+
} catch (err) {
|
|
2130
|
+
logCallbackFailure('session switch button', err)
|
|
2122
2131
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2123
2132
|
}
|
|
2124
2133
|
return
|
|
@@ -2172,7 +2181,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2172
2181
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2173
2182
|
await ctx.editMessageText(`Delete failed: ${result.error ?? 'unknown error'}`).catch(() => {})
|
|
2174
2183
|
}
|
|
2175
|
-
} catch {
|
|
2184
|
+
} catch (err) {
|
|
2185
|
+
logCallbackFailure('session delete button', err)
|
|
2176
2186
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2177
2187
|
}
|
|
2178
2188
|
return
|
|
@@ -2211,7 +2221,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2211
2221
|
} else {
|
|
2212
2222
|
await ctx.reply(`\u274C Clear failed: ${result.error ?? 'Unknown error'}`).catch(() => {})
|
|
2213
2223
|
}
|
|
2214
|
-
} catch {
|
|
2224
|
+
} catch (err) {
|
|
2225
|
+
logCallbackFailure('session clear button', err)
|
|
2215
2226
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2216
2227
|
}
|
|
2217
2228
|
return
|
|
@@ -2255,7 +2266,8 @@ bot.on('callback_query:data', async ctx => {
|
|
|
2255
2266
|
} else {
|
|
2256
2267
|
await ctx.answerCallbackQuery({ text: result.error ?? 'Failed' }).catch(() => {})
|
|
2257
2268
|
}
|
|
2258
|
-
} catch {
|
|
2269
|
+
} catch (err) {
|
|
2270
|
+
logCallbackFailure('session new button', err)
|
|
2259
2271
|
await ctx.answerCallbackQuery({ text: 'Request failed' }).catch(() => {})
|
|
2260
2272
|
}
|
|
2261
2273
|
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
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { InlineKeyboard } from 'grammy'
|
|
2
|
+
import { CallbackHttpError, callbackRejection } from './callback-failure'
|
|
3
|
+
|
|
4
|
+
export type SessionListEntry = { id: string; name: string; messageCount: number; lastActive: number }
|
|
5
|
+
|
|
6
|
+
/** Sessions shown per /sessions page. Each costs up to two buttons, so a page
|
|
7
|
+
* stays far below Telegram's 100-button limit on one inline keyboard. */
|
|
8
|
+
export const SESSIONS_PER_PAGE = 8
|
|
9
|
+
/** Telegram caps callback_data at 64 UTF-8 bytes. */
|
|
10
|
+
const MAX_DATA_BYTES = 64
|
|
11
|
+
|
|
12
|
+
const fits = (data: string) => Buffer.byteLength(data, 'utf8') <= MAX_DATA_BYTES
|
|
13
|
+
// Cut on code points: a split surrogate pair is invalid UTF-8 and Telegram
|
|
14
|
+
// rejects the whole message. An empty button label is rejected too.
|
|
15
|
+
const clip = (value: string, max: number) => {
|
|
16
|
+
const chars = [...value.replace(/\s+/g, ' ').trim()]
|
|
17
|
+
return chars.length > max ? chars.slice(0, max - 1).join('') + 'โฆ' : chars.join('') || 'Untitled'
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function age(now: number, lastActive: number): string {
|
|
21
|
+
const minutes = Math.max(0, Math.round((now - lastActive) / 60000))
|
|
22
|
+
return minutes < 60 ? `${minutes}m ago` : `${Math.round(minutes / 60)}h ago`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Builds one page of the /sessions menu, newest first. `page` is clamped, so a
|
|
26
|
+
* stale Prev/Next button after a delete still lands on a real page. */
|
|
27
|
+
export function sessionListMenu(sessions: SessionListEntry[], activeId: string, page: number, now = Date.now()): { text: string; reply_markup: InlineKeyboard; page: number; pages: number } {
|
|
28
|
+
// A session whose callback would exceed 64 bytes cannot be switched to or
|
|
29
|
+
// deleted from a button, so it is listed in the count but never sent as one.
|
|
30
|
+
// Each tap re-reads the list, so a session active between taps moves to page 1.
|
|
31
|
+
const sorted = [...sessions].sort((a, b) => b.lastActive - a.lastActive || a.id.localeCompare(b.id))
|
|
32
|
+
const pages = Math.max(1, Math.ceil(sorted.length / SESSIONS_PER_PAGE))
|
|
33
|
+
const current = Math.min(Math.max(0, Number.isInteger(page) ? page : 0), pages - 1)
|
|
34
|
+
const shown = sorted.slice(current * SESSIONS_PER_PAGE, (current + 1) * SESSIONS_PER_PAGE)
|
|
35
|
+
|
|
36
|
+
const keyboard = new InlineKeyboard()
|
|
37
|
+
for (const s of shown) {
|
|
38
|
+
const switchData = `session_switch:${s.id}`
|
|
39
|
+
if (!fits(switchData)) continue
|
|
40
|
+
const label = s.id === activeId ? `๐ข ${clip(s.name, 38)}` : clip(s.name, 40)
|
|
41
|
+
keyboard.text(label, switchData)
|
|
42
|
+
if (sorted.length > 1 && fits(`session_delete_confirm:${s.id}`)) keyboard.text('๐', `session_delete:${s.id}`)
|
|
43
|
+
keyboard.row()
|
|
44
|
+
}
|
|
45
|
+
if (current > 0) keyboard.text('โน Prev', `session_page:${current - 1}`)
|
|
46
|
+
if (current + 1 < pages) keyboard.text('Next โบ', `session_page:${current + 1}`)
|
|
47
|
+
if (pages > 1) keyboard.row()
|
|
48
|
+
keyboard.text('โ New Session', 'session_new').row()
|
|
49
|
+
keyboard.text('Dismiss', 'session_back')
|
|
50
|
+
|
|
51
|
+
const lines = [`๐ Sessions (${sorted.length})${pages > 1 ? ` ยท Page ${current + 1}/${pages}` : ''}`, '']
|
|
52
|
+
for (const s of shown) {
|
|
53
|
+
lines.push(`${s.id === activeId ? '๐ข' : 'โช'} ${clip(s.name, 60)} ยท ${s.messageCount} msgs ยท ${age(now, s.lastActive)}`)
|
|
54
|
+
}
|
|
55
|
+
lines.push('', 'Tap a session to switch, ๐ to delete')
|
|
56
|
+
return { text: lines.join('\n'), reply_markup: keyboard, page: current, pages }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Reads the chat's sessions from the agent (`list_sessions`). Throws with the
|
|
60
|
+
* HTTP status or the agent's reason so the failure log keeps the cause. */
|
|
61
|
+
export async function listSessionsRequest(base: string | undefined, chatId: string, timeoutMs = 10000): Promise<{ sessions: SessionListEntry[]; activeId: string }> {
|
|
62
|
+
if (!base) throw Error('not_configured')
|
|
63
|
+
const response = await fetch(base + '/command', {
|
|
64
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: AbortSignal.timeout(timeoutMs),
|
|
65
|
+
body: JSON.stringify({ command: 'list_sessions', chat_id: chatId }),
|
|
66
|
+
})
|
|
67
|
+
const result = await response.json().catch(error => { throw response.ok ? error : new CallbackHttpError(response.status) }) as { success?: boolean; sessions?: unknown; activeSessionId?: unknown } | null
|
|
68
|
+
if (!response.ok) throw new CallbackHttpError(response.status, result)
|
|
69
|
+
// A successful list_sessions reply carries `sessions` and no `success` flag.
|
|
70
|
+
if (result?.success === false || !Array.isArray(result?.sessions)) throw callbackRejection(result)
|
|
71
|
+
// Only the id is needed to switch or delete; the other fields are display-only,
|
|
72
|
+
// so a row missing them is still listed (an unnamed one shows as Untitled).
|
|
73
|
+
const rows = result.sessions as Array<Partial<SessionListEntry> | null>
|
|
74
|
+
const sessions = rows.filter(s => typeof s?.id === 'string' && s.id !== '').map(s => ({
|
|
75
|
+
id: s!.id!,
|
|
76
|
+
name: typeof s!.name === 'string' ? s!.name : '',
|
|
77
|
+
messageCount: Number.isFinite(s!.messageCount) ? s!.messageCount! : 0,
|
|
78
|
+
lastActive: Number.isFinite(s!.lastActive) ? s!.lastActive! : 0,
|
|
79
|
+
}))
|
|
80
|
+
if (sessions.length < rows.length) process.stderr.write(`telegram channel: /sessions skipped ${rows.length - sessions.length} session row(s) without an id\n`)
|
|
81
|
+
return { sessions, activeId: typeof result.activeSessionId === 'string' ? result.activeSessionId : '' }
|
|
82
|
+
}
|
|
@@ -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,11 +20,14 @@ 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 ?? '');
|
|
26
28
|
const absent = (e: any) => /message to (?:edit|delete) not found|message_id_invalid/i.test(description(e));
|
|
27
|
-
|
|
29
|
+
/** Telegram refused an edit because the message already shows this content. */
|
|
30
|
+
export const unchanged = (e: any) => /message is not modified/i.test(description(e));
|
|
28
31
|
export class LiveTaskBrowser {
|
|
29
32
|
private entries = new Map<string, Entry>();
|
|
30
33
|
private locks = new Map<string, Promise<unknown>>();
|
|
@@ -88,10 +91,10 @@ export class LiveTaskBrowser {
|
|
|
88
91
|
if (JSON.stringify(view) !== JSON.stringify(e.view)) { e.view = view; this.persist(); }
|
|
89
92
|
const finished = !!result.task && ['completed','failed','cancelled'].includes(result.task.state);
|
|
90
93
|
const menu = this.io.render(result), fingerprint = JSON.stringify(menu);
|
|
91
|
-
if (fingerprint === e.fingerprint) { e.finished = finished; return; }
|
|
94
|
+
if (fingerprint === e.fingerprint) { e.refreshReported = false; e.finished = finished; return; }
|
|
92
95
|
try { await this.io.edit(e.chatId,e.messageId,menu); }
|
|
93
96
|
catch (error) { if (!unchanged(error)) throw error; }
|
|
94
|
-
e.fingerprint = fingerprint; e.retryAt = undefined; e.finished = finished;
|
|
97
|
+
e.fingerprint = fingerprint; e.retryAt = undefined; e.refreshReported = false; e.finished = finished;
|
|
95
98
|
}
|
|
96
99
|
private async failure(e: Entry, error: any) {
|
|
97
100
|
if (description(error).includes('TASK_SESSION_CHANGED')) { await this.retire(e); return; }
|
|
@@ -110,7 +113,11 @@ export class LiveTaskBrowser {
|
|
|
110
113
|
this.entries.delete(e.chatId); this.persist(); return;
|
|
111
114
|
}
|
|
112
115
|
try { await this.update(e,await this.io.read(e.chatId,e.userId,{...e.view,session_id:e.sessionId})); }
|
|
113
|
-
catch (error) {
|
|
116
|
+
catch (error) {
|
|
117
|
+
await this.failure(e,error).catch(() => {});
|
|
118
|
+
// A retired or expired view is normal; only a view still waiting to refresh is reported.
|
|
119
|
+
if (!e.refreshReported && this.entries.get(e.chatId) === e) { e.refreshReported = true; this.io.report?.(error); }
|
|
120
|
+
}
|
|
114
121
|
});
|
|
115
122
|
}
|
|
116
123
|
}
|