feat: /last and bind button for previous Q/A context (v0.3.4)
After attaching a session, show a button and /last command that load the latest human/assistant turn via session.history so phone users can continue with context. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -3,6 +3,7 @@ import type { Context } from '@deepseek-ai/cordis'
|
||||
/** Loose ApiProxy surface used by catalog + model helpers. */
|
||||
export type ApiProxySessions = {
|
||||
list?: (req: { rpcId: string; payload: unknown }) => Promise<unknown>
|
||||
history?: (req: { rpcId: string; payload: unknown }) => Promise<unknown>
|
||||
models?: (req: { rpcId: string; payload: unknown }) => Promise<unknown>
|
||||
selectModel?: (req: { rpcId: string; payload: unknown }) => Promise<unknown>
|
||||
}
|
||||
|
||||
+35
-2
@@ -20,8 +20,9 @@ import {
|
||||
type TelegramClientLike,
|
||||
type TelegramUpdate,
|
||||
} from './client.js'
|
||||
import { MSG, parseCommand } from './commands.js'
|
||||
import { MSG, LAST_CB, parseCommand } from './commands.js'
|
||||
import { markdownToHtml, splitMessage } from './format.js'
|
||||
import { formatLastTurn, loadLastTurn } from './history.js'
|
||||
import { describeAgent, displayLabel } from './label.js'
|
||||
import {
|
||||
formatModel,
|
||||
@@ -67,6 +68,12 @@ const EFFORT_CB = 'me:'
|
||||
const BACK_MODEL_CB = 'mb'
|
||||
const MAX_BUTTONS = 40
|
||||
|
||||
function lastContextKeyboard(): InlineKeyboardMarkup {
|
||||
return {
|
||||
inline_keyboard: [[{ text: '查看上次对话', callback_data: LAST_CB }]],
|
||||
}
|
||||
}
|
||||
|
||||
const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
|
||||
function contentToText(content: readonly ContentBlock[]): string {
|
||||
@@ -115,6 +122,7 @@ export class TelegramBridge {
|
||||
void this.client.setMyCommands([
|
||||
{ command: 'start', description: '欢迎与用法' },
|
||||
{ command: 'sessions', description: '按工作区列出并附着会话' },
|
||||
{ command: 'last', description: '查看上次问答(续接上下文)' },
|
||||
{ command: 'model', description: '切换当前绑定会话的模型' },
|
||||
{ command: 'status', description: '查看当前绑定' },
|
||||
{ command: 'unbind', description: '断开手机绑定(不关闭本机会话)' },
|
||||
@@ -174,6 +182,9 @@ export class TelegramBridge {
|
||||
case 'sessions':
|
||||
await this.sendWorkspacePicker(chatId)
|
||||
return
|
||||
case 'last':
|
||||
await this.sendLastTurn(chatId)
|
||||
return
|
||||
case 'model':
|
||||
await this.sendModelPicker(chatId)
|
||||
return
|
||||
@@ -210,6 +221,11 @@ export class TelegramBridge {
|
||||
const data = cq.data ?? ''
|
||||
const picker = this.pickers.get(String(chatId))
|
||||
|
||||
if (data === LAST_CB) {
|
||||
await this.client.answerCallbackQuery(cq.id)
|
||||
await this.sendLastTurn(chatId)
|
||||
return
|
||||
}
|
||||
if (data === BACK_WS_CB) {
|
||||
await this.client.answerCallbackQuery(cq.id)
|
||||
await this.sendWorkspacePicker(chatId, picker?.catalog)
|
||||
@@ -384,7 +400,24 @@ export class TelegramBridge {
|
||||
: displayLabel(parts)
|
||||
this.bindings.set(String(chatId), { chatId, sessionId: String(agent.id), label })
|
||||
await this.client.answerCallbackQuery(callbackId, '已附着')
|
||||
await this.client.sendMessage(chatId, MSG.BOUND(label))
|
||||
await this.client.sendMessage(chatId, MSG.BOUND(label), undefined, lastContextKeyboard())
|
||||
}
|
||||
|
||||
private async sendLastTurn(chatId: number): Promise<void> {
|
||||
const binding = this.bindings.get(String(chatId))
|
||||
if (!binding) {
|
||||
await this.client.sendMessage(chatId, MSG.NEED_BIND)
|
||||
return
|
||||
}
|
||||
const agent = await this.ensureLiveAgent(binding.sessionId)
|
||||
try {
|
||||
const turn = await loadLastTurn(this.ctx, binding.sessionId, agent)
|
||||
const text = formatLastTurn(turn)
|
||||
await this.deliver(chatId, text)
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn(`dsh-telegram-channel: /last failed: ${this.redact(err)}`)
|
||||
await this.client.sendMessage(chatId, MSG.LAST_FAILED)
|
||||
}
|
||||
}
|
||||
|
||||
private async sendModelPicker(chatId: number): Promise<void> {
|
||||
|
||||
+10
-1
@@ -7,6 +7,7 @@ export const MSG = {
|
||||
].join('\n'),
|
||||
HELP: [
|
||||
'/sessions — 按工作区列出本机会话(与 Web 对齐,排除归档)并附着',
|
||||
'/last — 查看绑定会话的上次问答(便于续接)',
|
||||
'/model — 切换当前绑定会话的模型(下一回合生效)',
|
||||
'/status — 查看当前绑定',
|
||||
'/unbind — 断开绑定(不关闭本机会话)',
|
||||
@@ -25,7 +26,7 @@ export const MSG = {
|
||||
PICKER_STALE: '列表已过期,请重新发送 /sessions。',
|
||||
RESUME_FAILED: '无法附着该会话(resume 失败)。请确认会话存在于 Web,或先在电脑打开后再试。',
|
||||
BOUND(label: string): string {
|
||||
return `已附着本机会话:${label}\n此后消息将进入该会话(与 Web 同轨迹)。`
|
||||
return `已附着本机会话:${label}\n此后消息将进入该会话(与 Web 同轨迹)。\n需要续接时可点「查看上次对话」,或发送 /last。`
|
||||
},
|
||||
UNBOUND: '已断开绑定。本机会话仍在运行。',
|
||||
STATUS_NONE: '当前未绑定任何本机会话。发送 /sessions 选择。',
|
||||
@@ -36,6 +37,7 @@ export const MSG = {
|
||||
return `当前绑定:${label}\n(会话当前未在内存中运行;发消息时会自动 resume。)`
|
||||
},
|
||||
GONE: '绑定的会话已不可用。请重新 /sessions。',
|
||||
LAST_FAILED: '无法读取上次对话。请确认已绑定,且本机 dsh web / apiProxy 可用。',
|
||||
MODEL_UNAVAILABLE(detail?: string): string {
|
||||
const tip = '无法读取模型列表。请确认已绑定会话,且本机 dsh web 已加载 host-apiproxy。'
|
||||
if (!detail) return tip
|
||||
@@ -60,6 +62,7 @@ export type ParsedCommand =
|
||||
| { type: 'start'; text: string }
|
||||
| { type: 'help'; text: string }
|
||||
| { type: 'sessions'; text: string }
|
||||
| { type: 'last'; text: string }
|
||||
| { type: 'model'; text: string }
|
||||
| { type: 'status'; text: string }
|
||||
| { type: 'unbind'; text: string }
|
||||
@@ -78,6 +81,9 @@ export function parseCommand(text: string): ParsedCommand {
|
||||
case '/sessions':
|
||||
case '/list':
|
||||
return { type: 'sessions', text }
|
||||
case '/last':
|
||||
case '/context':
|
||||
return { type: 'last', text }
|
||||
case '/model':
|
||||
return { type: 'model', text }
|
||||
case '/status':
|
||||
@@ -92,3 +98,6 @@ export function parseCommand(text: string): ParsedCommand {
|
||||
|
||||
/** @deprecated Prefer short index callbacks (ws:/sid:); kept for old messages. */
|
||||
export const BIND_CB_PREFIX = 'bind:'
|
||||
|
||||
/** Inline button: fetch last Q/A for the bound session. */
|
||||
export const LAST_CB = 'last'
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { ContentBlock, TextBlock } from '@deepseek-ai/dsh-llm/types'
|
||||
import { resolveApiProxy } from './apiproxy.js'
|
||||
|
||||
export interface LastTurn {
|
||||
userText?: string
|
||||
assistantText?: string
|
||||
}
|
||||
|
||||
type ApiFn = (req: { rpcId: string; payload: unknown }) => Promise<unknown>
|
||||
|
||||
function unwrap<T>(res: unknown): T | undefined {
|
||||
const r = res as { result?: { ok?: boolean; value?: T; error?: { message?: string } } } | undefined
|
||||
if (r?.result?.ok === true) return r.result.value
|
||||
return undefined
|
||||
}
|
||||
|
||||
function contentToText(content: unknown): string {
|
||||
if (!Array.isArray(content)) return ''
|
||||
return (content as ContentBlock[])
|
||||
.filter((block): block is TextBlock => block?.type === 'text' && typeof block.text === 'string')
|
||||
.map((block) => block.text)
|
||||
.join('')
|
||||
.trim()
|
||||
}
|
||||
|
||||
type LooseEvent = {
|
||||
type?: string
|
||||
data?: {
|
||||
source?: { kind?: string }
|
||||
content?: unknown
|
||||
message?: { content?: unknown; source?: { kind?: string } }
|
||||
text?: string
|
||||
}
|
||||
}
|
||||
|
||||
/** Extract the latest human Q + assistant A from a session event list. */
|
||||
export function extractLastTurn(events: readonly LooseEvent[]): LastTurn {
|
||||
let lastUser: string | undefined
|
||||
let lastAssistant: string | undefined
|
||||
|
||||
for (const ev of events) {
|
||||
if (ev.type === 'user/message') {
|
||||
const sourceKind = ev.data?.source?.kind ?? ev.data?.message?.source?.kind
|
||||
// Prefer real human prompts; skip plugin-injected context noise.
|
||||
if (sourceKind && sourceKind !== 'user') continue
|
||||
const text = contentToText(ev.data?.content ?? ev.data?.message?.content)
|
||||
if (text) {
|
||||
lastUser = text
|
||||
// New user turn resets prior assistant for pairing.
|
||||
lastAssistant = undefined
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (ev.type === 'assistant/message') {
|
||||
const text = contentToText(ev.data?.message?.content ?? ev.data?.content)
|
||||
if (text) lastAssistant = text
|
||||
continue
|
||||
}
|
||||
if (ev.type === 'compaction/summary') {
|
||||
const text = typeof ev.data?.text === 'string' ? ev.data.text.trim() : ''
|
||||
if (text && !lastAssistant) lastAssistant = `(摘要)${text}`
|
||||
}
|
||||
}
|
||||
|
||||
return { userText: lastUser, assistantText: lastAssistant }
|
||||
}
|
||||
|
||||
export function formatLastTurn(turn: LastTurn, maxEach = 3500): string {
|
||||
if (!turn.userText && !turn.assistantText) {
|
||||
return '暂无上次问答(会话可能为空或尚未产生用户回合)。'
|
||||
}
|
||||
const clip = (s: string) => {
|
||||
const chars = [...s]
|
||||
if (chars.length <= maxEach) return s
|
||||
return `${chars.slice(0, maxEach - 1).join('')}…`
|
||||
}
|
||||
const parts: string[] = ['—— 上次对话 ——']
|
||||
if (turn.userText) {
|
||||
parts.push('', '【用户】', clip(turn.userText))
|
||||
}
|
||||
if (turn.assistantText) {
|
||||
parts.push('', '【助手】', clip(turn.assistantText))
|
||||
}
|
||||
return parts.join('\n')
|
||||
}
|
||||
|
||||
async function historyViaApi(ctx: Context, sessionId: string): Promise<LooseEvent[] | undefined> {
|
||||
const api = resolveApiProxy(ctx)
|
||||
const history = api?.sessions?.history as ApiFn | undefined
|
||||
if (typeof history !== 'function') return undefined
|
||||
const raw = await history({
|
||||
rpcId: randomUUID(),
|
||||
payload: { sessionId, maxMessages: 8 },
|
||||
})
|
||||
const value = unwrap<{ events: Array<{ event?: LooseEvent } | LooseEvent> }>(raw)
|
||||
if (!value?.events) return undefined
|
||||
return value.events.map((entry) => {
|
||||
if (entry && typeof entry === 'object' && 'event' in entry && entry.event) {
|
||||
return entry.event
|
||||
}
|
||||
return entry as LooseEvent
|
||||
})
|
||||
}
|
||||
|
||||
function historyViaAgent(agent: Agent | undefined): LooseEvent[] | undefined {
|
||||
const events = (agent as { session?: { events?: readonly LooseEvent[] } } | undefined)?.session?.events
|
||||
if (!events || events.length === 0) return undefined
|
||||
return [...events]
|
||||
}
|
||||
|
||||
/** Load last Q/A for a bound session (apiProxy history, else live agent events). */
|
||||
export async function loadLastTurn(
|
||||
ctx: Context,
|
||||
sessionId: string,
|
||||
agent?: Agent,
|
||||
): Promise<LastTurn> {
|
||||
let events: LooseEvent[] | undefined
|
||||
try {
|
||||
events = await historyViaApi(ctx, sessionId)
|
||||
} catch {
|
||||
events = undefined
|
||||
}
|
||||
if (!events || events.length === 0) {
|
||||
events = historyViaAgent(agent)
|
||||
}
|
||||
if (!events || events.length === 0) return {}
|
||||
return extractLastTurn(events)
|
||||
}
|
||||
Reference in New Issue
Block a user