const fs = require('fs'); const path = require('path'); const { latestPath } = require('./output-paths'); const { buildClaudeSessionName } = require('./agent-runtime'); const PACKAGE_ROOT = path.resolve(__dirname, '..', '..', '..'); function sessionCommandPrefix() { const pluginsDir = path.dirname(PACKAGE_ROOT); const claudeDir = path.dirname(pluginsDir); if (path.basename(pluginsDir) === 'plugins' && path.basename(claudeDir) === '.claude') { return `npm --prefix ".claude/plugins/${path.basename(PACKAGE_ROOT)}" run`; } return 'npm run'; } function safeCustomerArgument(value) { return String(value || '企微客户') .replace(/[^\p{L}\p{N} _.-]/gu, '') .trim() .slice(0, 60) || '企微客户'; } function readSessionState(filePath = latestPath('messages', 'claude-code-sessions.json')) { try { const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); parsed.sessions ||= {}; parsed.project ||= {}; return parsed; } catch { return { version: 1, project: {}, sessions: {} }; } } function getCustomerSessionGuide(conversation = {}, options = {}) { const conversationId = String(conversation.id || conversation.conversationId || ''); const customerName = String(conversation.contact_name || conversation.displayName || '企微客户').trim(); const state = options.state || readSessionState(options.sessionFile); const session = state.sessions?.[conversationId] || null; const displayName = session?.displayName || buildClaudeSessionName({ conversation: { contact_name: customerName }, }, conversationId || customerName); const safeName = safeCustomerArgument(customerName); return { detected: Boolean(session), ready: Boolean(session?.initialized), status: !session ? 'not_created' : session.initialized ? 'ready' : 'waiting_first_run', customerName, displayName, openLocation: 'Fmode Studio → 当前企微项目 → 终端', openCommand: `${sessionCommandPrefix()} agent:session -- --customer "${safeName}"`, openMode: 'forked-review', productionSessionProtected: true, guidance: session?.initialized ? '已检测到客户专属 Claude Code Session。运行打开命令后会 fork 审阅副本,可查看完整历史、模型思考和工具记录。' : session ? '客户专属 Session 已分配,首次生成草稿后即可打开完整 Claude Code 对话。' : '该客户尚未创建 Claude Code Session;首次运行 Agent 后系统会自动创建并显示打开方式。', updatedAt: session?.updatedAt || session?.createdAt || null, }; } module.exports = { safeCustomerArgument, sessionCommandPrefix, readSessionState, getCustomerSessionGuide, };