Agent/core/session-context.ts
2026-08-06 22:17:39 +08:00

90 lines
2.7 KiB
TypeScript

// @ts-nocheck
let _state = {
currentEntity: null,
currentEmployeeId: null,
currentEmployeeName: null,
currentTeam: null,
currentYear: null,
currentMonth: null,
lastQueryType: null,
};
const _listeners = new Set();
export function getState() {
return { ..._state };
}
export function updateFromToolResult(toolResult) {
if (!toolResult || typeof toolResult !== 'object') return null;
const entity = toolResult.currentEntity;
const hasEntity = entity && entity.type;
const hasQueryType = !!toolResult.lastQueryType;
if (!hasEntity && !hasQueryType) return null;
const prev = JSON.stringify(_state);
const isTeam = hasEntity && entity.type === 'team';
const isEmployee = hasEntity && entity.type === 'employee';
_state = {
currentEntity: hasEntity
? { type: entity.type, id: entity.id || null, name: entity.name || null }
: _state.currentEntity,
currentEmployeeId: isEmployee ? (entity.id || _state.currentEmployeeId) : _state.currentEmployeeId,
currentEmployeeName: isEmployee ? (entity.name || _state.currentEmployeeName) : _state.currentEmployeeName,
currentTeam: isTeam
? (entity.name || _state.currentTeam)
: (isEmployee ? null : _state.currentTeam),
currentYear: hasEntity ? (entity.year || _state.currentYear) : _state.currentYear,
currentMonth: hasEntity ? (entity.month ?? _state.currentMonth) : _state.currentMonth,
lastQueryType: hasQueryType ? toolResult.lastQueryType : _state.lastQueryType,
};
if (JSON.stringify(_state) !== prev) {
_notify();
}
return _state.currentEntity;
}
export function clear() {
const prev = JSON.stringify(_state);
_state = {
currentEntity: null,
currentEmployeeId: null,
currentEmployeeName: null,
currentTeam: null,
currentYear: null,
currentMonth: null,
lastQueryType: null,
};
if (JSON.stringify(_state) !== prev) {
_notify();
}
}
export function updateFromUserInput(userInput) {
if (!userInput) return;
const yearMatch = String(userInput).match(/(20\d{2})\s*年(?:度)?/);
const monthMatch = String(userInput).match(/(\d{1,2})\s*月/);
const prev = JSON.stringify(_state);
if (yearMatch) _state.currentYear = parseInt(yearMatch[1], 10);
if (monthMatch) _state.currentMonth = parseInt(monthMatch[1], 10);
if (JSON.stringify(_state) !== prev) {
_notify();
}
}
export function subscribe(fn) {
_listeners.add(fn);
return () => _listeners.delete(fn);
}
function _notify() {
const snapshot = getState();
for (const fn of _listeners) {
try { fn(snapshot); } catch (e) {}
}
}