-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathstate.ts
More file actions
188 lines (172 loc) · 5.84 KB
/
state.ts
File metadata and controls
188 lines (172 loc) · 5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import type { SessionState, ToolParameterEntry, WithParts } from "./types"
import type { Logger } from "../logger"
import { applyPendingCompressionDurations } from "../compress/timing"
import { loadSessionState, saveSessionState } from "./persistence"
import {
isSubAgentSession,
findLastCompactionTimestamp,
countTurns,
resetOnCompaction,
createPruneMessagesState,
loadPruneMessagesState,
loadPruneMap,
collectTurnNudgeAnchors,
} from "./utils"
import { getLastUserMessage } from "../messages/query"
export const checkSession = async (
client: any,
state: SessionState,
logger: Logger,
messages: WithParts[],
manualModeDefault: boolean,
): Promise<void> => {
const lastUserMessage = getLastUserMessage(messages)
if (!lastUserMessage) {
return
}
const lastSessionId = lastUserMessage.info.sessionID
if (state.sessionId === null || state.sessionId !== lastSessionId) {
logger.info(`Session changed: ${state.sessionId} -> ${lastSessionId}`)
try {
await ensureSessionInitialized(
client,
state,
lastSessionId,
logger,
messages,
manualModeDefault,
)
} catch (err: any) {
logger.error("Failed to initialize session state", { error: err.message })
}
}
const lastCompactionTimestamp = findLastCompactionTimestamp(messages)
if (lastCompactionTimestamp > state.lastCompaction) {
state.lastCompaction = lastCompactionTimestamp
resetOnCompaction(state)
logger.info("Detected compaction - reset stale state", {
timestamp: lastCompactionTimestamp,
})
saveSessionState(state, logger).catch((error) => {
logger.warn("Failed to persist state reset after compaction", {
error: error instanceof Error ? error.message : String(error),
})
})
}
state.currentTurn = countTurns(state, messages)
}
export function createSessionState(): SessionState {
return {
sessionId: null,
isSubAgent: false,
manualMode: false,
compressPermission: undefined,
pendingManualTrigger: null,
prune: {
tools: new Map<string, number>(),
messages: createPruneMessagesState(),
},
nudges: {
contextLimitAnchors: new Set<string>(),
turnNudgeAnchors: new Set<string>(),
iterationNudgeAnchors: new Set<string>(),
},
stats: {
pruneTokenCounter: 0,
totalPruneTokens: 0,
},
compressionTiming: {
startsByCallId: new Map<string, number>(),
pendingByCallId: new Map(),
},
toolParameters: new Map<string, ToolParameterEntry>(),
subAgentResultCache: new Map<string, string>(),
toolIdList: [],
messageIds: {
byRawId: new Map<string, string>(),
byRef: new Map<string, string>(),
nextRef: 1,
},
lastCompaction: 0,
currentTurn: 0,
modelContextLimit: undefined,
systemPromptTokens: undefined,
}
}
export function resetSessionState(state: SessionState): void {
state.sessionId = null
state.isSubAgent = false
state.manualMode = false
state.compressPermission = undefined
state.pendingManualTrigger = null
state.prune = {
tools: new Map<string, number>(),
messages: createPruneMessagesState(),
}
state.nudges = {
contextLimitAnchors: new Set<string>(),
turnNudgeAnchors: new Set<string>(),
iterationNudgeAnchors: new Set<string>(),
}
state.stats = {
pruneTokenCounter: 0,
totalPruneTokens: 0,
}
state.toolParameters.clear()
state.subAgentResultCache.clear()
state.toolIdList = []
state.messageIds = {
byRawId: new Map<string, string>(),
byRef: new Map<string, string>(),
nextRef: 1,
}
state.lastCompaction = 0
state.currentTurn = 0
state.modelContextLimit = undefined
state.systemPromptTokens = undefined
}
export async function ensureSessionInitialized(
client: any,
state: SessionState,
sessionId: string,
logger: Logger,
messages: WithParts[],
manualModeEnabled: boolean,
): Promise<void> {
if (state.sessionId === sessionId) {
return
}
// logger.info("session ID = " + sessionId)
// logger.info("Initializing session state", { sessionId: sessionId })
resetSessionState(state)
state.manualMode = manualModeEnabled ? "active" : false
state.sessionId = sessionId
const isSubAgent = await isSubAgentSession(client, sessionId)
state.isSubAgent = isSubAgent
// logger.info("isSubAgent = " + isSubAgent)
state.lastCompaction = findLastCompactionTimestamp(messages)
state.currentTurn = countTurns(state, messages)
state.nudges.turnNudgeAnchors = collectTurnNudgeAnchors(messages)
const persisted = await loadSessionState(sessionId, logger)
if (persisted === null) {
return
}
state.prune.tools = loadPruneMap(persisted.prune.tools)
state.prune.messages = loadPruneMessagesState(persisted.prune.messages)
state.nudges.contextLimitAnchors = new Set<string>(persisted.nudges.contextLimitAnchors || [])
state.nudges.turnNudgeAnchors = new Set<string>([
...state.nudges.turnNudgeAnchors,
...(persisted.nudges.turnNudgeAnchors || []),
])
state.nudges.iterationNudgeAnchors = new Set<string>(
persisted.nudges.iterationNudgeAnchors || [],
)
state.stats = {
pruneTokenCounter: persisted.stats?.pruneTokenCounter || 0,
totalPruneTokens: persisted.stats?.totalPruneTokens || 0,
}
const applied = applyPendingCompressionDurations(state)
if (applied > 0) {
await saveSessionState(state, logger)
}
}