@librechat/agents 3.1.85 → 3.1.87

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.
Files changed (166) hide show
  1. package/README.md +69 -0
  2. package/dist/cjs/agents/AgentContext.cjs +7 -2
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/events.cjs +23 -0
  5. package/dist/cjs/events.cjs.map +1 -1
  6. package/dist/cjs/graphs/Graph.cjs +133 -18
  7. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  10. package/dist/cjs/llm/anthropic/index.cjs +251 -53
  11. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  12. package/dist/cjs/llm/init.cjs +1 -5
  13. package/dist/cjs/llm/init.cjs.map +1 -1
  14. package/dist/cjs/llm/openai/index.cjs +113 -24
  15. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  16. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  17. package/dist/cjs/llm/openrouter/index.cjs +3 -1
  18. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  19. package/dist/cjs/main.cjs +18 -5
  20. package/dist/cjs/main.cjs.map +1 -1
  21. package/dist/cjs/openai/index.cjs +253 -0
  22. package/dist/cjs/openai/index.cjs.map +1 -0
  23. package/dist/cjs/responses/index.cjs +448 -0
  24. package/dist/cjs/responses/index.cjs.map +1 -0
  25. package/dist/cjs/run.cjs +108 -7
  26. package/dist/cjs/run.cjs.map +1 -1
  27. package/dist/cjs/session/AgentSession.cjs +1057 -0
  28. package/dist/cjs/session/AgentSession.cjs.map +1 -0
  29. package/dist/cjs/session/JsonlSessionStore.cjs +425 -0
  30. package/dist/cjs/session/JsonlSessionStore.cjs.map +1 -0
  31. package/dist/cjs/session/handlers.cjs +221 -0
  32. package/dist/cjs/session/handlers.cjs.map +1 -0
  33. package/dist/cjs/session/ids.cjs +22 -0
  34. package/dist/cjs/session/ids.cjs.map +1 -0
  35. package/dist/cjs/session/messageSerialization.cjs +179 -0
  36. package/dist/cjs/session/messageSerialization.cjs.map +1 -0
  37. package/dist/cjs/stream.cjs +472 -11
  38. package/dist/cjs/stream.cjs.map +1 -1
  39. package/dist/cjs/summarization/node.cjs +1 -1
  40. package/dist/cjs/summarization/node.cjs.map +1 -1
  41. package/dist/cjs/tools/ToolNode.cjs +177 -59
  42. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  43. package/dist/cjs/tools/eagerEventExecution.cjs +113 -0
  44. package/dist/cjs/tools/eagerEventExecution.cjs.map +1 -0
  45. package/dist/cjs/tools/handlers.cjs +1 -1
  46. package/dist/cjs/tools/handlers.cjs.map +1 -1
  47. package/dist/cjs/tools/streamedToolCallSeals.cjs +42 -0
  48. package/dist/cjs/tools/streamedToolCallSeals.cjs.map +1 -0
  49. package/dist/esm/agents/AgentContext.mjs +7 -2
  50. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  51. package/dist/esm/events.mjs +23 -1
  52. package/dist/esm/events.mjs.map +1 -1
  53. package/dist/esm/graphs/Graph.mjs +133 -18
  54. package/dist/esm/graphs/Graph.mjs.map +1 -1
  55. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  56. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  57. package/dist/esm/llm/anthropic/index.mjs +251 -53
  58. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  59. package/dist/esm/llm/init.mjs +1 -5
  60. package/dist/esm/llm/init.mjs.map +1 -1
  61. package/dist/esm/llm/openai/index.mjs +113 -25
  62. package/dist/esm/llm/openai/index.mjs.map +1 -1
  63. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  64. package/dist/esm/llm/openrouter/index.mjs +4 -2
  65. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  66. package/dist/esm/main.mjs +5 -1
  67. package/dist/esm/main.mjs.map +1 -1
  68. package/dist/esm/openai/index.mjs +246 -0
  69. package/dist/esm/openai/index.mjs.map +1 -0
  70. package/dist/esm/responses/index.mjs +440 -0
  71. package/dist/esm/responses/index.mjs.map +1 -0
  72. package/dist/esm/run.mjs +108 -7
  73. package/dist/esm/run.mjs.map +1 -1
  74. package/dist/esm/session/AgentSession.mjs +1054 -0
  75. package/dist/esm/session/AgentSession.mjs.map +1 -0
  76. package/dist/esm/session/JsonlSessionStore.mjs +422 -0
  77. package/dist/esm/session/JsonlSessionStore.mjs.map +1 -0
  78. package/dist/esm/session/handlers.mjs +219 -0
  79. package/dist/esm/session/handlers.mjs.map +1 -0
  80. package/dist/esm/session/ids.mjs +17 -0
  81. package/dist/esm/session/ids.mjs.map +1 -0
  82. package/dist/esm/session/messageSerialization.mjs +173 -0
  83. package/dist/esm/session/messageSerialization.mjs.map +1 -0
  84. package/dist/esm/stream.mjs +473 -12
  85. package/dist/esm/stream.mjs.map +1 -1
  86. package/dist/esm/summarization/node.mjs +1 -1
  87. package/dist/esm/summarization/node.mjs.map +1 -1
  88. package/dist/esm/tools/ToolNode.mjs +177 -59
  89. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  90. package/dist/esm/tools/eagerEventExecution.mjs +107 -0
  91. package/dist/esm/tools/eagerEventExecution.mjs.map +1 -0
  92. package/dist/esm/tools/handlers.mjs +1 -1
  93. package/dist/esm/tools/handlers.mjs.map +1 -1
  94. package/dist/esm/tools/streamedToolCallSeals.mjs +36 -0
  95. package/dist/esm/tools/streamedToolCallSeals.mjs.map +1 -0
  96. package/dist/types/events.d.ts +1 -0
  97. package/dist/types/graphs/Graph.d.ts +24 -9
  98. package/dist/types/index.d.ts +1 -0
  99. package/dist/types/llm/openai/index.d.ts +1 -0
  100. package/dist/types/openai/index.d.ts +75 -0
  101. package/dist/types/responses/index.d.ts +97 -0
  102. package/dist/types/run.d.ts +2 -0
  103. package/dist/types/session/AgentSession.d.ts +32 -0
  104. package/dist/types/session/JsonlSessionStore.d.ts +67 -0
  105. package/dist/types/session/handlers.d.ts +8 -0
  106. package/dist/types/session/ids.d.ts +4 -0
  107. package/dist/types/session/index.d.ts +5 -0
  108. package/dist/types/session/messageSerialization.d.ts +7 -0
  109. package/dist/types/session/types.d.ts +191 -0
  110. package/dist/types/tools/ToolNode.d.ts +12 -1
  111. package/dist/types/tools/eagerEventExecution.d.ts +23 -0
  112. package/dist/types/tools/streamedToolCallSeals.d.ts +13 -0
  113. package/dist/types/types/hitl.d.ts +4 -0
  114. package/dist/types/types/run.d.ts +11 -1
  115. package/dist/types/types/tools.d.ts +36 -0
  116. package/package.json +19 -2
  117. package/src/__tests__/stream.eagerEventExecution.test.ts +2458 -0
  118. package/src/agents/AgentContext.ts +7 -2
  119. package/src/agents/__tests__/AgentContext.test.ts +254 -5
  120. package/src/events.ts +29 -0
  121. package/src/graphs/Graph.ts +224 -50
  122. package/src/graphs/MultiAgentGraph.ts +1 -1
  123. package/src/graphs/__tests__/composition.smoke.test.ts +30 -0
  124. package/src/index.ts +3 -0
  125. package/src/llm/anthropic/index.ts +356 -84
  126. package/src/llm/anthropic/llm.spec.ts +64 -0
  127. package/src/llm/custom-chat-models.smoke.test.ts +175 -4
  128. package/src/llm/openai/contentBlocks.test.ts +35 -0
  129. package/src/llm/openai/deepseek.test.ts +201 -2
  130. package/src/llm/openai/index.ts +171 -26
  131. package/src/llm/openai/utils/index.ts +22 -0
  132. package/src/llm/openrouter/index.ts +4 -2
  133. package/src/openai/__tests__/openai.test.ts +337 -0
  134. package/src/openai/index.ts +404 -0
  135. package/src/responses/__tests__/responses.test.ts +652 -0
  136. package/src/responses/index.ts +677 -0
  137. package/src/run.ts +158 -8
  138. package/src/scripts/compare_pi_vs_ours.ts +592 -173
  139. package/src/scripts/session_live.ts +548 -0
  140. package/src/session/AgentSession.ts +1432 -0
  141. package/src/session/JsonlSessionStore.ts +572 -0
  142. package/src/session/__tests__/JsonlSessionStore.test.ts +1410 -0
  143. package/src/session/__tests__/handlers.test.ts +161 -0
  144. package/src/session/handlers.ts +272 -0
  145. package/src/session/ids.ts +17 -0
  146. package/src/session/index.ts +44 -0
  147. package/src/session/messageSerialization.ts +207 -0
  148. package/src/session/types.ts +275 -0
  149. package/src/specs/custom-event-await.test.ts +89 -0
  150. package/src/specs/summarization.test.ts +1 -1
  151. package/src/stream.ts +755 -48
  152. package/src/summarization/node.ts +1 -1
  153. package/src/tools/ToolNode.ts +299 -126
  154. package/src/tools/__tests__/ToolNode.eagerEventExecution.test.ts +373 -0
  155. package/src/tools/__tests__/handlers.test.ts +2 -1
  156. package/src/tools/__tests__/hitl.test.ts +206 -110
  157. package/src/tools/eagerEventExecution.ts +153 -0
  158. package/src/tools/handlers.ts +8 -4
  159. package/src/tools/streamedToolCallSeals.ts +57 -0
  160. package/src/types/hitl.ts +4 -0
  161. package/src/types/run.ts +11 -0
  162. package/src/types/tools.ts +36 -0
  163. package/dist/cjs/llm/text.cjs +0 -69
  164. package/dist/cjs/llm/text.cjs.map +0 -1
  165. package/dist/esm/llm/text.mjs +0 -67
  166. package/dist/esm/llm/text.mjs.map +0 -1
@@ -0,0 +1,1057 @@
1
+ 'use strict';
2
+
3
+ var langgraph = require('@langchain/langgraph');
4
+ var messages = require('@langchain/core/messages');
5
+ var AgentContext = require('../agents/AgentContext.cjs');
6
+ var _enum = require('../common/enum.cjs');
7
+ var run = require('../run.cjs');
8
+ var ids = require('./ids.cjs');
9
+ var messageSerialization = require('./messageSerialization.cjs');
10
+ var JsonlSessionStore = require('./JsonlSessionStore.cjs');
11
+ var handlers = require('./handlers.cjs');
12
+ var node = require('../summarization/node.cjs');
13
+
14
+ function isBaseMessage(value) {
15
+ return (value instanceof messages.BaseMessage ||
16
+ (value != null &&
17
+ typeof value === 'object' &&
18
+ '_getType' in value &&
19
+ typeof value._getType === 'function'));
20
+ }
21
+ function normalizeInput(input) {
22
+ if (typeof input === 'string') {
23
+ const messages$1 = [new messages.HumanMessage(input)];
24
+ return { messages: messages$1, state: { messages: messages$1 } };
25
+ }
26
+ if (Array.isArray(input)) {
27
+ return { messages: input, state: { messages: input } };
28
+ }
29
+ if (isBaseMessage(input)) {
30
+ const messages = [input];
31
+ return { messages, state: { messages } };
32
+ }
33
+ return { messages: input.messages, state: input };
34
+ }
35
+ function contentToText(content) {
36
+ const chunks = [];
37
+ for (const part of content) {
38
+ if (!part) {
39
+ continue;
40
+ }
41
+ if (part.type === _enum.ContentTypes.TEXT && typeof part.text === 'string') {
42
+ chunks.push(part.text);
43
+ }
44
+ }
45
+ return chunks.join('');
46
+ }
47
+ function normalizeConfig(config) {
48
+ if ('runConfig' in config) {
49
+ return {
50
+ runConfig: config.runConfig,
51
+ cwd: config.cwd ?? process.cwd(),
52
+ sessionPath: config.sessionPath,
53
+ name: config.name,
54
+ ephemeral: config.ephemeral,
55
+ checkpointing: config.checkpointing,
56
+ };
57
+ }
58
+ const { cwd, sessionPath, name, ephemeral, checkpointing, sessionId: _sessionId, ...runConfig } = config;
59
+ return {
60
+ runConfig: {
61
+ ...runConfig,
62
+ runId: config.runId ?? ids.createRunId(),
63
+ },
64
+ cwd: cwd ?? process.cwd(),
65
+ sessionPath,
66
+ name,
67
+ ephemeral,
68
+ checkpointing,
69
+ };
70
+ }
71
+ function isMissingSessionError(error) {
72
+ if (error == null || typeof error !== 'object') {
73
+ return false;
74
+ }
75
+ const candidate = error;
76
+ if (candidate.code === 'ENOENT') {
77
+ return true;
78
+ }
79
+ return candidate.message?.startsWith('Session not found:') === true;
80
+ }
81
+ async function createStore(params) {
82
+ if (params.ephemeral === true) {
83
+ return undefined;
84
+ }
85
+ if (params.sessionPath != null && params.sessionPath !== '') {
86
+ try {
87
+ return await JsonlSessionStore.JsonlSessionStore.openPath(params.sessionPath);
88
+ }
89
+ catch (error) {
90
+ if (!isMissingSessionError(error)) {
91
+ throw error;
92
+ }
93
+ return JsonlSessionStore.JsonlSessionStore.create({
94
+ path: params.sessionPath,
95
+ cwd: params.cwd,
96
+ name: params.name,
97
+ sessionId: params.sessionId,
98
+ });
99
+ }
100
+ }
101
+ return JsonlSessionStore.JsonlSessionStore.create({
102
+ cwd: params.cwd,
103
+ name: params.name,
104
+ sessionId: params.sessionId,
105
+ });
106
+ }
107
+ function mergeInitialSummary(existing, sessionSummary) {
108
+ if (!existing) {
109
+ return sessionSummary;
110
+ }
111
+ if (!sessionSummary) {
112
+ return existing;
113
+ }
114
+ if (existing.text === sessionSummary.text) {
115
+ return existing;
116
+ }
117
+ return {
118
+ text: `${existing.text}\n\n${sessionSummary.text}`,
119
+ tokenCount: existing.tokenCount + sessionSummary.tokenCount,
120
+ };
121
+ }
122
+ function applyInitialSummaryToAgent(agent, initialSummary) {
123
+ const merged = mergeInitialSummary(agent.initialSummary, initialSummary);
124
+ return merged ? { ...agent, initialSummary: merged } : agent;
125
+ }
126
+ function applyInitialSummaryToGraphConfig(graphConfig, initialSummary) {
127
+ if (!initialSummary) {
128
+ return graphConfig;
129
+ }
130
+ if ('agents' in graphConfig) {
131
+ return {
132
+ ...graphConfig,
133
+ agents: graphConfig.agents.map((agent) => applyInitialSummaryToAgent(agent, initialSummary)),
134
+ };
135
+ }
136
+ return {
137
+ ...graphConfig,
138
+ initialSummary: mergeInitialSummary(graphConfig.initialSummary, initialSummary),
139
+ };
140
+ }
141
+ function isCheckpointSaver(value) {
142
+ if (value == null || typeof value !== 'object') {
143
+ return false;
144
+ }
145
+ const candidate = value;
146
+ return (typeof candidate.getTuple === 'function' &&
147
+ typeof candidate.list === 'function' &&
148
+ typeof candidate.put === 'function' &&
149
+ typeof candidate.putWrites === 'function' &&
150
+ typeof candidate.deleteThread === 'function');
151
+ }
152
+ function getGraphCheckpointer(graphConfig) {
153
+ const checkpointer = graphConfig.compileOptions?.checkpointer;
154
+ return isCheckpointSaver(checkpointer) ? checkpointer : undefined;
155
+ }
156
+ function createCheckpointingState(runConfig, checkpointing) {
157
+ const graphCheckpointer = getGraphCheckpointer(runConfig.graphConfig);
158
+ if (checkpointing === false) {
159
+ return {
160
+ enabled: false,
161
+ disableGraphCheckpointer: true,
162
+ };
163
+ }
164
+ if (typeof checkpointing === 'object') {
165
+ if (checkpointing.enabled === false) {
166
+ return {
167
+ enabled: false,
168
+ disableGraphCheckpointer: true,
169
+ };
170
+ }
171
+ return {
172
+ enabled: true,
173
+ checkpointer: checkpointing.checkpointer ?? graphCheckpointer ?? new langgraph.MemorySaver(),
174
+ };
175
+ }
176
+ if (checkpointing === true || runConfig.humanInTheLoop?.enabled === true) {
177
+ return {
178
+ enabled: true,
179
+ checkpointer: graphCheckpointer ?? new langgraph.MemorySaver(),
180
+ };
181
+ }
182
+ return {
183
+ enabled: graphCheckpointer != null,
184
+ checkpointer: graphCheckpointer,
185
+ };
186
+ }
187
+ function removeCheckpointerFromGraphConfig(graphConfig) {
188
+ if (graphConfig.compileOptions?.checkpointer == null) {
189
+ return graphConfig;
190
+ }
191
+ const { checkpointer: _checkpointer, ...compileOptions } = graphConfig.compileOptions;
192
+ return {
193
+ ...graphConfig,
194
+ compileOptions,
195
+ };
196
+ }
197
+ function applyCheckpointerToGraphConfig(graphConfig, checkpointer) {
198
+ if (!checkpointer) {
199
+ return graphConfig;
200
+ }
201
+ if (graphConfig.compileOptions?.checkpointer === checkpointer) {
202
+ return graphConfig;
203
+ }
204
+ return {
205
+ ...graphConfig,
206
+ compileOptions: {
207
+ ...(graphConfig.compileOptions ?? {}),
208
+ checkpointer,
209
+ },
210
+ };
211
+ }
212
+ function applyCheckpointingToGraphConfig(graphConfig, checkpointing) {
213
+ if (checkpointing.disableGraphCheckpointer === true) {
214
+ return removeCheckpointerFromGraphConfig(graphConfig);
215
+ }
216
+ return applyCheckpointerToGraphConfig(graphConfig, checkpointing.checkpointer);
217
+ }
218
+ function getConfigString(config, key) {
219
+ const configurable = config?.configurable;
220
+ const value = configurable?.[key];
221
+ return typeof value === 'string' && value !== '' ? value : undefined;
222
+ }
223
+ function getConfigOptionalString(config, key) {
224
+ const configurable = config?.configurable;
225
+ if (configurable == null ||
226
+ !Object.prototype.hasOwnProperty.call(configurable, key)) {
227
+ return undefined;
228
+ }
229
+ const value = configurable[key];
230
+ return typeof value === 'string' ? value : undefined;
231
+ }
232
+ function createCallerConfig(threadId, options) {
233
+ return {
234
+ recursionLimit: 50,
235
+ ...(options.config ?? {}),
236
+ configurable: {
237
+ ...(options.config?.configurable ?? {}),
238
+ thread_id: threadId,
239
+ },
240
+ version: options.config?.version ?? 'v2',
241
+ };
242
+ }
243
+ function createCheckpointLookupConfig(config) {
244
+ const threadId = getConfigString(config, 'thread_id');
245
+ if (threadId == null) {
246
+ return config;
247
+ }
248
+ const checkpointNs = getConfigString(config, 'checkpoint_ns') ?? '';
249
+ const checkpointId = getConfigString(config, 'checkpoint_id');
250
+ return {
251
+ configurable: {
252
+ ...config.configurable,
253
+ thread_id: threadId,
254
+ checkpoint_ns: checkpointNs,
255
+ ...(checkpointId != null ? { checkpoint_id: checkpointId } : {}),
256
+ },
257
+ };
258
+ }
259
+ function applyCheckpointReferenceToConfig(config, checkpoint, options) {
260
+ if (checkpoint?.checkpointId == null ||
261
+ checkpoint.checkpointId === '' ||
262
+ (options?.overwrite !== true &&
263
+ getConfigString(config, 'checkpoint_id') != null)) {
264
+ return config;
265
+ }
266
+ return {
267
+ ...config,
268
+ configurable: {
269
+ ...config.configurable,
270
+ checkpoint_id: checkpoint.checkpointId,
271
+ checkpoint_ns: checkpoint.checkpointNs ?? '',
272
+ },
273
+ };
274
+ }
275
+ function getStoredCheckpointForConfig(store, threadId, config) {
276
+ const requestedCheckpointNs = getConfigOptionalString(config, 'checkpoint_ns');
277
+ if (requestedCheckpointNs == null) {
278
+ return store?.getLatestCheckpoint(threadId);
279
+ }
280
+ const checkpoints = store?.getCheckpoints(threadId) ?? [];
281
+ for (let i = checkpoints.length - 1; i >= 0; i--) {
282
+ const checkpoint = checkpoints[i];
283
+ if (checkpoint.data.source === 'reset') {
284
+ return undefined;
285
+ }
286
+ if ((checkpoint.data.checkpointNs ?? '') === requestedCheckpointNs) {
287
+ return checkpoint;
288
+ }
289
+ }
290
+ return undefined;
291
+ }
292
+ function createLatestCheckpointLookupConfig(config) {
293
+ const lookup = createCheckpointLookupConfig(config);
294
+ const { checkpoint_id: _checkpointId, ...configurable } = lookup.configurable ?? {};
295
+ return { configurable };
296
+ }
297
+ async function getLatestCheckpointTuple(checkpointer, config) {
298
+ if (!checkpointer) {
299
+ return undefined;
300
+ }
301
+ const lookupConfig = createLatestCheckpointLookupConfig(config);
302
+ const tuple = await checkpointer.getTuple(lookupConfig);
303
+ if (tuple) {
304
+ return tuple;
305
+ }
306
+ for await (const checkpoint of checkpointer.list(lookupConfig, {
307
+ limit: 1,
308
+ })) {
309
+ return checkpoint;
310
+ }
311
+ return undefined;
312
+ }
313
+ async function getSelectedCheckpointTuple(checkpointer, config) {
314
+ return checkpointer?.getTuple(createCheckpointLookupConfig(config));
315
+ }
316
+ function createCheckpointReference(params) {
317
+ const checkpointNs = getConfigString(params.tuple.config, 'checkpoint_ns') ?? '';
318
+ const parentCheckpointId = getConfigString(params.tuple.parentConfig, 'checkpoint_id');
319
+ return {
320
+ provider: 'langgraph',
321
+ threadId: params.threadId,
322
+ checkpointId: params.tuple.checkpoint.id,
323
+ checkpointNs,
324
+ ...(parentCheckpointId != null ? { parentCheckpointId } : {}),
325
+ };
326
+ }
327
+ function createSessionRunState(entries) {
328
+ const messages = [];
329
+ let initialSummary;
330
+ for (const entry of entries) {
331
+ if (entry.type === 'summary') {
332
+ initialSummary = {
333
+ text: entry.data.text,
334
+ tokenCount: typeof entry.data.tokenCount === 'number' &&
335
+ Number.isFinite(entry.data.tokenCount)
336
+ ? entry.data.tokenCount
337
+ : 0,
338
+ };
339
+ messages.length = 0;
340
+ continue;
341
+ }
342
+ if (entry.type === 'message') {
343
+ messages.push(messageSerialization.deserializeMessage(entry.data.message));
344
+ }
345
+ }
346
+ return { messages, initialSummary };
347
+ }
348
+ function isMessageEntry(entry) {
349
+ return entry.type === 'message';
350
+ }
351
+ function getSessionBranchTarget(store, entryId, position) {
352
+ const entry = store.getEntry(entryId);
353
+ if (!entry) {
354
+ throw new Error(`Entry not found: ${entryId}`);
355
+ }
356
+ if (position === 'at') {
357
+ return entry;
358
+ }
359
+ return entry.parentId == null ? undefined : store.getEntry(entry.parentId);
360
+ }
361
+ function getAbandonedPathForBranch(store, previousLeafId, targetLeafId) {
362
+ const previousPath = store.getPath(previousLeafId ?? undefined);
363
+ if (previousPath.length === 0) {
364
+ return [];
365
+ }
366
+ const targetPath = targetLeafId == null ? [] : store.getPath(targetLeafId);
367
+ const maxSharedLength = Math.min(previousPath.length, targetPath.length);
368
+ let sharedLength = 0;
369
+ while (sharedLength < maxSharedLength &&
370
+ previousPath[sharedLength].id === targetPath[sharedLength].id) {
371
+ sharedLength++;
372
+ }
373
+ return previousPath.slice(sharedLength);
374
+ }
375
+ function createAgentInputFromGraphConfig(graphConfig, initialSummary, retainRecentTurns, instructions) {
376
+ let agent;
377
+ if ('agents' in graphConfig) {
378
+ if (graphConfig.agents.length === 0) {
379
+ throw new Error('Cannot compact a session with no agents');
380
+ }
381
+ agent = graphConfig.agents[0];
382
+ }
383
+ else {
384
+ const { type: _type, llmConfig, signal: _signal, tools = [], ...agentInputs } = graphConfig;
385
+ const { provider, ...clientOptions } = llmConfig;
386
+ agent = {
387
+ ...agentInputs,
388
+ tools,
389
+ provider,
390
+ clientOptions,
391
+ agentId: 'default',
392
+ };
393
+ }
394
+ const summarizationConfig = {
395
+ ...(agent.summarizationConfig ?? {}),
396
+ ...(instructions != null && instructions !== ''
397
+ ? { prompt: instructions }
398
+ : {}),
399
+ retainRecent: {
400
+ ...(agent.summarizationConfig?.retainRecent ?? {}),
401
+ ...(retainRecentTurns != null ? { turns: retainRecentTurns } : {}),
402
+ },
403
+ };
404
+ return {
405
+ ...applyInitialSummaryToAgent(agent, initialSummary),
406
+ summarizationEnabled: true,
407
+ summarizationConfig,
408
+ };
409
+ }
410
+ function createManualCompactGraph(params) {
411
+ const contentData = [];
412
+ const contentIndexMap = new Map();
413
+ const result = {
414
+ graph: {
415
+ contentData,
416
+ contentIndexMap,
417
+ runId: params.runId,
418
+ isMultiAgent: false,
419
+ hookRegistry: params.hooks,
420
+ dispatchRunStep: async (runStep) => {
421
+ contentData.push(runStep);
422
+ contentIndexMap.set(runStep.id, runStep.index);
423
+ await params.customHandlers?.[_enum.GraphEvents.ON_RUN_STEP]?.handle(_enum.GraphEvents.ON_RUN_STEP, runStep);
424
+ },
425
+ dispatchRunStepCompleted: async (stepId, completed) => {
426
+ const runStep = contentData.find((step) => step.id === stepId);
427
+ const resultWithStep = {
428
+ ...completed,
429
+ id: stepId,
430
+ index: runStep?.index ?? 0,
431
+ };
432
+ if (completed.type === 'summary') {
433
+ result.completedSummary = completed.summary;
434
+ }
435
+ await params.customHandlers?.[_enum.GraphEvents.ON_RUN_STEP_COMPLETED]?.handle(_enum.GraphEvents.ON_RUN_STEP_COMPLETED, {
436
+ result: resultWithStep,
437
+ });
438
+ },
439
+ },
440
+ };
441
+ return result;
442
+ }
443
+ function getSummaryText(summary) {
444
+ const firstBlock = summary?.content?.[0];
445
+ return firstBlock != null &&
446
+ typeof firstBlock === 'object' &&
447
+ 'text' in firstBlock &&
448
+ typeof firstBlock.text === 'string'
449
+ ? firstBlock.text
450
+ : '';
451
+ }
452
+ function getSummaryTokenCount(summary) {
453
+ return typeof summary?.tokenCount === 'number' &&
454
+ Number.isFinite(summary.tokenCount)
455
+ ? summary.tokenCount
456
+ : 0;
457
+ }
458
+ function filterRemoveMessages(messages) {
459
+ return messages.filter((message) => message._getType() !== 'remove');
460
+ }
461
+ class LiveAgentSessionStream {
462
+ resultPromise;
463
+ events = [];
464
+ waiters = [];
465
+ closed = false;
466
+ failed = false;
467
+ error;
468
+ setResultPromise(resultPromise) {
469
+ this.resultPromise = resultPromise;
470
+ }
471
+ push(event) {
472
+ if (this.closed) {
473
+ return;
474
+ }
475
+ const waiter = this.waiters.shift();
476
+ if (waiter) {
477
+ waiter.resolve({ value: event, done: false });
478
+ return;
479
+ }
480
+ this.events.push(event);
481
+ }
482
+ complete() {
483
+ this.closed = true;
484
+ for (const waiter of this.waiters.splice(0)) {
485
+ waiter.resolve({
486
+ value: undefined,
487
+ done: true,
488
+ });
489
+ }
490
+ }
491
+ fail(error) {
492
+ this.error = error;
493
+ this.failed = true;
494
+ this.closed = true;
495
+ for (const waiter of this.waiters.splice(0)) {
496
+ waiter.reject(error);
497
+ }
498
+ }
499
+ nextEvent() {
500
+ const event = this.events.shift();
501
+ if (event !== undefined) {
502
+ return Promise.resolve({ value: event, done: false });
503
+ }
504
+ if (this.failed) {
505
+ return Promise.reject(this.error);
506
+ }
507
+ if (this.closed) {
508
+ return Promise.resolve({
509
+ value: undefined,
510
+ done: true,
511
+ });
512
+ }
513
+ return new Promise((resolve, reject) => {
514
+ this.waiters.push({ resolve, reject });
515
+ });
516
+ }
517
+ async *[Symbol.asyncIterator]() {
518
+ for (;;) {
519
+ const next = await this.nextEvent();
520
+ if (next.done === true) {
521
+ return;
522
+ }
523
+ yield next.value;
524
+ }
525
+ }
526
+ async *toTextStream() {
527
+ for await (const event of this) {
528
+ if (event.type !== 'message.delta' || event.data == null) {
529
+ continue;
530
+ }
531
+ const data = event.data;
532
+ if (typeof data === 'object' && !Array.isArray(data)) {
533
+ const delta = data.delta;
534
+ if (delta != null &&
535
+ typeof delta === 'object' &&
536
+ !Array.isArray(delta)) {
537
+ const content = delta.content;
538
+ if (Array.isArray(content)) {
539
+ for (const part of content) {
540
+ if (part != null &&
541
+ typeof part === 'object' &&
542
+ !Array.isArray(part) &&
543
+ typeof part.text === 'string') {
544
+ yield part.text;
545
+ }
546
+ }
547
+ }
548
+ }
549
+ }
550
+ }
551
+ }
552
+ finalResult() {
553
+ if (!this.resultPromise) {
554
+ return Promise.reject(new Error('Session stream has not started'));
555
+ }
556
+ return this.resultPromise;
557
+ }
558
+ }
559
+ class AgentSession {
560
+ runConfig;
561
+ store;
562
+ calibrationRatio;
563
+ checkpointing;
564
+ cwd;
565
+ threadId;
566
+ constructor(params) {
567
+ this.runConfig = params.runConfig;
568
+ this.cwd = params.cwd;
569
+ this.threadId = params.threadId;
570
+ this.store = params.store;
571
+ this.checkpointing = params.checkpointing;
572
+ }
573
+ static async create(config) {
574
+ const normalized = normalizeConfig(config);
575
+ const explicitSessionId = 'sessionId' in config && typeof config.sessionId === 'string'
576
+ ? config.sessionId
577
+ : undefined;
578
+ const store = await createStore({
579
+ cwd: normalized.cwd,
580
+ sessionPath: normalized.sessionPath,
581
+ name: normalized.name,
582
+ sessionId: explicitSessionId,
583
+ ephemeral: normalized.ephemeral,
584
+ });
585
+ return new AgentSession({
586
+ runConfig: normalized.runConfig,
587
+ cwd: normalized.cwd,
588
+ threadId: store?.header.id ?? explicitSessionId ?? ids.createSessionId(),
589
+ checkpointing: createCheckpointingState(normalized.runConfig, normalized.checkpointing),
590
+ store,
591
+ });
592
+ }
593
+ get sessionPath() {
594
+ return this.store?.path;
595
+ }
596
+ getSessionStore() {
597
+ return this.store;
598
+ }
599
+ getCheckpointer() {
600
+ return this.checkpointing.checkpointer;
601
+ }
602
+ async getLatestCheckpoint(options = {}) {
603
+ const threadId = options.threadId ?? this.threadId;
604
+ const baseConfig = options.config ?? {};
605
+ const config = createCheckpointLookupConfig({
606
+ ...baseConfig,
607
+ configurable: {
608
+ ...(baseConfig.configurable ?? {}),
609
+ thread_id: threadId,
610
+ ...(options.checkpointNs != null
611
+ ? { checkpoint_ns: options.checkpointNs }
612
+ : {}),
613
+ },
614
+ });
615
+ const tuple = await getLatestCheckpointTuple(this.checkpointing.checkpointer, config);
616
+ return tuple ? createCheckpointReference({ threadId, tuple }) : undefined;
617
+ }
618
+ async hasCheckpointState(config) {
619
+ if (!this.checkpointing.enabled) {
620
+ return false;
621
+ }
622
+ const tuple = await getSelectedCheckpointTuple(this.checkpointing.checkpointer, config);
623
+ return tuple != null;
624
+ }
625
+ async recordCheckpoint(params) {
626
+ if (!this.checkpointing.enabled) {
627
+ return;
628
+ }
629
+ const checkpointConfig = applyCheckpointReferenceToConfig(params.config, {
630
+ checkpointId: params.checkpointId,
631
+ checkpointNs: params.checkpointNs,
632
+ }, { overwrite: true });
633
+ const tuple = params.checkpointId != null && params.checkpointId !== ''
634
+ ? await getSelectedCheckpointTuple(this.checkpointing.checkpointer, checkpointConfig)
635
+ : await getLatestCheckpointTuple(this.checkpointing.checkpointer, params.config);
636
+ if (!tuple) {
637
+ return;
638
+ }
639
+ const reference = createCheckpointReference({
640
+ threadId: params.threadId,
641
+ tuple,
642
+ });
643
+ await this.store?.appendCheckpoint({
644
+ source: params.source,
645
+ runId: params.runId,
646
+ threadId: params.threadId,
647
+ checkpointId: reference.checkpointId,
648
+ checkpointNs: reference.checkpointNs,
649
+ parentCheckpointId: reference.parentCheckpointId,
650
+ });
651
+ }
652
+ getCheckpointThreadIds() {
653
+ const threadIds = new Set([this.threadId]);
654
+ for (const checkpoint of this.store?.getCheckpoints() ?? []) {
655
+ threadIds.add(checkpoint.data.threadId);
656
+ }
657
+ return [...threadIds];
658
+ }
659
+ async resetCheckpointThreads(reason) {
660
+ const checkpointer = this.checkpointing.checkpointer;
661
+ if (!this.checkpointing.enabled || checkpointer == null) {
662
+ return;
663
+ }
664
+ for (const threadId of this.getCheckpointThreadIds()) {
665
+ await checkpointer.deleteThread(threadId);
666
+ await this.store?.appendCheckpoint({
667
+ source: 'reset',
668
+ threadId,
669
+ reason,
670
+ });
671
+ }
672
+ }
673
+ async runInternal(input, options = {}, onEvent) {
674
+ const runId = options.runId ?? ids.createRunId();
675
+ const threadId = options.threadId ?? this.threadId;
676
+ const isSessionThread = threadId === this.threadId;
677
+ const normalizedInput = normalizeInput(input);
678
+ const inputMessages = normalizedInput.messages;
679
+ const callerConfig = createCallerConfig(threadId, options);
680
+ const useCheckpointState = await this.hasCheckpointState(callerConfig);
681
+ let parentId = this.store?.getLeafEntry()?.id ?? null;
682
+ if (isSessionThread) {
683
+ for (const message of inputMessages) {
684
+ const entry = await this.store?.appendMessage(message, parentId);
685
+ parentId = entry?.id ?? parentId;
686
+ }
687
+ }
688
+ await this.store?.appendRunEvent('run.started', undefined, {
689
+ runId,
690
+ threadId,
691
+ });
692
+ const handlerResult = handlers.createRunHandlers({
693
+ runId,
694
+ threadId,
695
+ userHandlers: this.runConfig.customHandlers,
696
+ onEvent,
697
+ });
698
+ const emitTerminalEvent = (event) => {
699
+ const streamEvent = {
700
+ ...event,
701
+ sequence: handlerResult.events.length,
702
+ runId,
703
+ threadId,
704
+ timestamp: new Date().toISOString(),
705
+ };
706
+ handlerResult.events.push(streamEvent);
707
+ onEvent?.(streamEvent);
708
+ };
709
+ const sessionState = createSessionRunState(isSessionThread ? (this.store?.getPath() ?? []) : []);
710
+ try {
711
+ const runConfig = {
712
+ ...this.runConfig,
713
+ runId,
714
+ graphConfig: applyCheckpointingToGraphConfig(applyInitialSummaryToGraphConfig(this.runConfig.graphConfig, sessionState.initialSummary), this.checkpointing),
715
+ returnContent: true,
716
+ calibrationRatio: this.calibrationRatio,
717
+ customHandlers: {
718
+ ...(this.runConfig.customHandlers ?? {}),
719
+ ...handlerResult.handlers,
720
+ },
721
+ };
722
+ const run$1 = await run.Run.create(runConfig);
723
+ let messages = inputMessages;
724
+ if (!useCheckpointState && sessionState.messages.length > 0) {
725
+ messages = sessionState.messages;
726
+ }
727
+ const content = await run$1.processStream({ ...normalizedInput.state, messages }, callerConfig, options.streamOptions);
728
+ const runMessages = run$1.getRunMessages() ?? [];
729
+ if (isSessionThread) {
730
+ for (const message of runMessages) {
731
+ await this.store?.appendMessage(message);
732
+ }
733
+ }
734
+ this.calibrationRatio = run$1.getCalibrationRatio();
735
+ const interrupt = run$1.getInterrupt();
736
+ const haltedReason = run$1.getHaltReason();
737
+ if (interrupt) {
738
+ emitTerminalEvent({ type: 'run.interrupted' });
739
+ await this.store?.appendRunEvent('run.interrupted', interrupt, {
740
+ runId,
741
+ threadId,
742
+ });
743
+ }
744
+ else if (haltedReason != null && haltedReason !== '') {
745
+ emitTerminalEvent({ type: 'run.halted', data: haltedReason });
746
+ await this.store?.appendRunEvent('run.halted', haltedReason, {
747
+ runId,
748
+ threadId,
749
+ });
750
+ }
751
+ else {
752
+ emitTerminalEvent({ type: 'run.completed' });
753
+ await this.store?.appendRunEvent('run.completed', undefined, {
754
+ runId,
755
+ threadId,
756
+ });
757
+ }
758
+ await this.recordCheckpoint({
759
+ source: 'run',
760
+ runId,
761
+ threadId,
762
+ config: callerConfig,
763
+ checkpointId: interrupt?.checkpointId,
764
+ checkpointNs: interrupt?.checkpointNs,
765
+ });
766
+ const contentParts = (content ?? handlerResult.contentParts).filter((part) => part != null);
767
+ return {
768
+ text: contentToText(contentParts),
769
+ content: contentParts,
770
+ messages: runMessages,
771
+ usage: handlerResult.usage,
772
+ steps: handlerResult.steps,
773
+ interrupt,
774
+ haltedReason,
775
+ runId,
776
+ threadId,
777
+ };
778
+ }
779
+ catch (error) {
780
+ emitTerminalEvent({
781
+ type: 'run.failed',
782
+ data: error instanceof Error ? error.message : String(error),
783
+ });
784
+ await this.store?.appendRunEvent('run.failed', error, {
785
+ runId,
786
+ threadId,
787
+ });
788
+ await this.recordCheckpoint({
789
+ source: 'run',
790
+ runId,
791
+ threadId,
792
+ config: callerConfig,
793
+ });
794
+ throw error;
795
+ }
796
+ }
797
+ async run(input, options = {}) {
798
+ return this.runInternal(input, options);
799
+ }
800
+ stream(input, options = {}) {
801
+ const stream = new LiveAgentSessionStream();
802
+ const resultPromise = this.runInternal(input, options, (event) => {
803
+ stream.push(event);
804
+ }).then((result) => {
805
+ stream.complete();
806
+ return result;
807
+ }, (error) => {
808
+ stream.fail(error);
809
+ throw error;
810
+ });
811
+ stream.setResultPromise(resultPromise);
812
+ return stream;
813
+ }
814
+ async resumeSession(pathOrId) {
815
+ if (pathOrId == null || pathOrId === '') {
816
+ const sessions = await JsonlSessionStore.JsonlSessionStore.list(this.cwd);
817
+ if (sessions.length === 0) {
818
+ throw new Error(`No sessions found for ${this.cwd}`);
819
+ }
820
+ this.store = await JsonlSessionStore.JsonlSessionStore.open(sessions[0].path);
821
+ this.cwd = this.store.header.cwd;
822
+ this.threadId = this.store.header.id;
823
+ return this;
824
+ }
825
+ this.store = await JsonlSessionStore.JsonlSessionStore.open(pathOrId);
826
+ this.cwd = this.store.header.cwd;
827
+ this.threadId = this.store.header.id;
828
+ return this;
829
+ }
830
+ async clone(options = {}) {
831
+ if (!this.store) {
832
+ throw new Error('Cannot clone an ephemeral session');
833
+ }
834
+ const store = await this.store.clone(options);
835
+ return new AgentSession({
836
+ runConfig: this.runConfig,
837
+ cwd: store.header.cwd,
838
+ threadId: store.header.id,
839
+ checkpointing: this.checkpointing,
840
+ store,
841
+ });
842
+ }
843
+ async fork(entryId, options = {}) {
844
+ if (!this.store) {
845
+ throw new Error('Cannot fork an ephemeral session');
846
+ }
847
+ const store = await this.store.fork(entryId, options);
848
+ return new AgentSession({
849
+ runConfig: this.runConfig,
850
+ cwd: store.header.cwd,
851
+ threadId: store.header.id,
852
+ checkpointing: this.checkpointing,
853
+ store,
854
+ });
855
+ }
856
+ async branch(entryId, options = {}) {
857
+ const store = this.store;
858
+ if (!store) {
859
+ throw new Error('Cannot branch an ephemeral session');
860
+ }
861
+ const target = getSessionBranchTarget(store, entryId, options.position ?? 'at');
862
+ const previousLeafId = store.getLeafEntry()?.id ?? null;
863
+ let leafId = target?.id ?? null;
864
+ const summarizeAbandoned = options.summarizeAbandoned;
865
+ if (summarizeAbandoned !== undefined && summarizeAbandoned !== false) {
866
+ const instructions = typeof summarizeAbandoned === 'object'
867
+ ? summarizeAbandoned.instructions
868
+ : undefined;
869
+ const abandonedPath = getAbandonedPathForBranch(store, previousLeafId, leafId);
870
+ const summary = await this.compactActivePath({ instructions, retainRecentTurns: 0 }, leafId, abandonedPath);
871
+ leafId = summary?.id ?? leafId;
872
+ }
873
+ if (leafId === previousLeafId) {
874
+ return;
875
+ }
876
+ await store.setLeaf(leafId);
877
+ await this.resetCheckpointThreads('branch');
878
+ }
879
+ async compact(options = {}) {
880
+ const summary = await this.compactActivePath(options, null);
881
+ if (summary) {
882
+ await this.resetCheckpointThreads('compact');
883
+ }
884
+ }
885
+ async compactActivePath(options = {}, parentId, path) {
886
+ const store = this.store;
887
+ if (!store) {
888
+ throw new Error('Cannot compact an ephemeral session');
889
+ }
890
+ const activePath = path ?? store.getPath();
891
+ const sessionState = createSessionRunState(activePath);
892
+ const messageEntries = activePath.filter(isMessageEntry);
893
+ if (sessionState.messages.length === 0) {
894
+ return undefined;
895
+ }
896
+ const compactRunId = ids.createRunId();
897
+ const agentContext = AgentContext.AgentContext.fromConfig(createAgentInputFromGraphConfig(this.runConfig.graphConfig, sessionState.initialSummary, options.retainRecentTurns, options.instructions), this.runConfig.tokenCounter);
898
+ const graph = createManualCompactGraph({
899
+ runId: compactRunId,
900
+ customHandlers: this.runConfig.customHandlers,
901
+ hooks: this.runConfig.hooks,
902
+ });
903
+ const summarizeNode = node.createSummarizeNode({
904
+ agentContext,
905
+ graph: graph.graph,
906
+ generateStepId: (stepKey) => [
907
+ `${stepKey}-${compactRunId}`,
908
+ graph.graph.contentData.length,
909
+ ],
910
+ });
911
+ const summarizedState = await summarizeNode({
912
+ messages: sessionState.messages,
913
+ summarizationRequest: {
914
+ remainingContextTokens: agentContext.maxContextTokens ?? 0,
915
+ agentId: agentContext.agentId,
916
+ },
917
+ }, {
918
+ configurable: { thread_id: this.threadId },
919
+ metadata: { run_id: compactRunId },
920
+ });
921
+ const completedSummaryText = getSummaryText(graph.completedSummary);
922
+ const contextSummaryText = agentContext.getSummaryText();
923
+ let summaryText = completedSummaryText;
924
+ if (summaryText === '' && contextSummaryText != null) {
925
+ summaryText = contextSummaryText;
926
+ }
927
+ if (summaryText === '') {
928
+ return undefined;
929
+ }
930
+ const retainedMessages = filterRemoveMessages(summarizedState.messages ?? []);
931
+ let retainedEntryIds = [];
932
+ if (retainedMessages.length > 0) {
933
+ retainedEntryIds = messageEntries
934
+ .slice(-retainedMessages.length)
935
+ .map((entry) => entry.id);
936
+ }
937
+ const retainedEntryIdSet = new Set(retainedEntryIds);
938
+ const summarized = messageEntries.filter((entry) => !retainedEntryIdSet.has(entry.id));
939
+ const summary = await store.appendEntryForCompaction({
940
+ text: summaryText,
941
+ tokenCount: getSummaryTokenCount(graph.completedSummary),
942
+ retainedEntryIds,
943
+ summarizedEntryIds: summarized.map((entry) => entry.id),
944
+ instructions: options.instructions,
945
+ parentId,
946
+ });
947
+ let retainedParentId = summary.id;
948
+ for (const message of retainedMessages) {
949
+ const retainedMessage = await store.appendMessage(message, retainedParentId);
950
+ retainedParentId = retainedMessage.id;
951
+ }
952
+ await store.appendCompactionEntry({
953
+ summaryEntryId: summary.id,
954
+ retainedEntryIds,
955
+ summarizedEntryIds: summarized.map((entry) => entry.id),
956
+ });
957
+ return summary;
958
+ }
959
+ async resumeInterrupt(resumeValue, options = {}) {
960
+ const runId = options.runId ?? ids.createRunId();
961
+ const threadId = options.threadId ?? this.threadId;
962
+ const isSessionThread = threadId === this.threadId;
963
+ const baseCallerConfig = createCallerConfig(threadId, options);
964
+ const callerConfig = applyCheckpointReferenceToConfig(baseCallerConfig, getStoredCheckpointForConfig(this.store, threadId, baseCallerConfig)?.data);
965
+ await this.store?.appendRunEvent('run.started', undefined, {
966
+ runId,
967
+ threadId,
968
+ });
969
+ const handlerResult = handlers.createRunHandlers({
970
+ runId,
971
+ threadId,
972
+ userHandlers: this.runConfig.customHandlers,
973
+ });
974
+ const sessionState = createSessionRunState(isSessionThread ? (this.store?.getPath() ?? []) : []);
975
+ try {
976
+ const run$1 = await run.Run.create({
977
+ ...this.runConfig,
978
+ runId,
979
+ graphConfig: applyCheckpointingToGraphConfig(applyInitialSummaryToGraphConfig(this.runConfig.graphConfig, sessionState.initialSummary), this.checkpointing),
980
+ returnContent: true,
981
+ calibrationRatio: this.calibrationRatio,
982
+ customHandlers: {
983
+ ...(this.runConfig.customHandlers ?? {}),
984
+ ...handlerResult.handlers,
985
+ },
986
+ });
987
+ const content = await run$1.resume(resumeValue, callerConfig);
988
+ const runMessages = run$1.getRunMessages() ?? [];
989
+ if (isSessionThread) {
990
+ for (const message of runMessages) {
991
+ await this.store?.appendMessage(message);
992
+ }
993
+ }
994
+ this.calibrationRatio = run$1.getCalibrationRatio();
995
+ const interrupt = run$1.getInterrupt();
996
+ const haltedReason = run$1.getHaltReason();
997
+ if (interrupt) {
998
+ await this.store?.appendRunEvent('run.interrupted', interrupt, {
999
+ runId,
1000
+ threadId,
1001
+ });
1002
+ }
1003
+ else if (haltedReason != null && haltedReason !== '') {
1004
+ await this.store?.appendRunEvent('run.halted', haltedReason, {
1005
+ runId,
1006
+ threadId,
1007
+ });
1008
+ }
1009
+ else {
1010
+ await this.store?.appendRunEvent('run.completed', undefined, {
1011
+ runId,
1012
+ threadId,
1013
+ });
1014
+ }
1015
+ await this.recordCheckpoint({
1016
+ source: 'resume',
1017
+ runId,
1018
+ threadId,
1019
+ config: callerConfig,
1020
+ checkpointId: interrupt?.checkpointId,
1021
+ checkpointNs: interrupt?.checkpointNs,
1022
+ });
1023
+ const contentParts = (content ?? handlerResult.contentParts).filter((part) => part != null);
1024
+ return {
1025
+ text: contentToText(contentParts),
1026
+ content: contentParts,
1027
+ messages: runMessages,
1028
+ usage: handlerResult.usage,
1029
+ steps: handlerResult.steps,
1030
+ interrupt,
1031
+ haltedReason,
1032
+ runId,
1033
+ threadId,
1034
+ };
1035
+ }
1036
+ catch (error) {
1037
+ await this.store?.appendRunEvent('run.failed', error, {
1038
+ runId,
1039
+ threadId,
1040
+ });
1041
+ await this.recordCheckpoint({
1042
+ source: 'resume',
1043
+ runId,
1044
+ threadId,
1045
+ config: callerConfig,
1046
+ });
1047
+ throw error;
1048
+ }
1049
+ }
1050
+ }
1051
+ function createAgentSession(config) {
1052
+ return AgentSession.create(config);
1053
+ }
1054
+
1055
+ exports.AgentSession = AgentSession;
1056
+ exports.createAgentSession = createAgentSession;
1057
+ //# sourceMappingURL=AgentSession.cjs.map