@adminforth/agent 2.0.10 → 2.1.0

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 (187) hide show
  1. package/README.md +333 -10
  2. package/dist/application/ports.d.ts +66 -0
  3. package/dist/application/runTurnUseCase.d.ts +68 -0
  4. package/dist/application/runTurnUseCase.js +358 -0
  5. package/dist/{agentEvents.d.ts → domain/agentEvents.d.ts} +1 -1
  6. package/dist/{agent → domain}/systemPrompt.js +1 -1
  7. package/dist/{agent/turn → domain}/turnTypes.d.ts +41 -37
  8. package/dist/{agent/turn/VegaLiteStreamBuffer.d.ts → domain/vegaLiteStreamBuffer.d.ts} +1 -1
  9. package/dist/index.d.ts +3 -2
  10. package/dist/index.js +40 -35
  11. package/dist/{agent/runtime/AgentContext.d.ts → llm/agentContext.d.ts} +3 -3
  12. package/dist/{agent/simpleAgent.d.ts → llm/agentModels.d.ts} +18 -16
  13. package/dist/llm/agentModels.js +65 -0
  14. package/dist/{agent/runtime/AgentRuntime.d.ts → llm/agentRuntime.d.ts} +11 -2
  15. package/dist/{agent/runtime/AgentRuntime.js → llm/agentRuntime.js} +38 -6
  16. package/dist/llm/langGraphLlm.d.ts +25 -0
  17. package/dist/llm/langGraphLlm.js +54 -0
  18. package/dist/{agent/middleware/apiBasedTools.d.ts → llm/middleware/apiToolsMiddleware.d.ts} +1 -1
  19. package/dist/{agent/middleware/apiBasedTools.js → llm/middleware/apiToolsMiddleware.js} +8 -14
  20. package/dist/{agent → llm}/middleware/sequenceDebug.d.ts +1 -1
  21. package/dist/{agent/models/AgentModelFactory.d.ts → llm/modelFactory.d.ts} +1 -1
  22. package/dist/{agent/models/AgentModelFactory.js → llm/modelFactory.js} +1 -1
  23. package/dist/llm/streamAdapter.d.ts +18 -0
  24. package/dist/llm/streamAdapter.js +117 -0
  25. package/dist/{sessionStore.d.ts → persistence/sessionStore.d.ts} +12 -2
  26. package/dist/{sessionStore.js → persistence/sessionStore.js} +33 -0
  27. package/dist/{agent/tools/AgentToolProvider.d.ts → tools/agentToolProvider.d.ts} +1 -1
  28. package/dist/{agent/tools/AgentToolProvider.js → tools/agentToolProvider.js} +1 -1
  29. package/dist/{apiBasedTools.js → tools/apiBasedTools.js} +0 -3
  30. package/dist/{agent/tools → tools}/apiTool.d.ts +1 -1
  31. package/dist/{agent/tools → tools}/fetchSkill.js +1 -1
  32. package/dist/{agent/tools → tools}/fetchToolSchema.d.ts +1 -1
  33. package/dist/{agent/tools → tools}/index.d.ts +1 -1
  34. package/dist/{agent/tools → tools}/navigateUser.d.ts +3 -3
  35. package/dist/{endpoints → transport/http}/context.d.ts +2 -2
  36. package/dist/transport/http/context.js +1 -0
  37. package/dist/{endpoints/core.js → transport/http/coreEndpoints.js} +3 -3
  38. package/dist/{endpoints/sessions.js → transport/http/sessionEndpoints.js} +7 -1
  39. package/dist/transport/sse/sseWriter.d.ts +29 -0
  40. package/dist/{surfaces/web-sse/createSseEventEmitter.js → transport/sse/sseWriter.js} +15 -0
  41. package/dist/{chatSurfaceService.d.ts → transport/surfaces/chatSurfaceService.d.ts} +3 -3
  42. package/dist/{chatSurfaceService.js → transport/surfaces/chatSurfaceService.js} +7 -5
  43. package/dist/{agent/speech/SpeechTurnService.d.ts → transport/surfaces/speechTurnService.d.ts} +1 -1
  44. package/dist/{agent/speech/SpeechTurnService.js → transport/surfaces/speechTurnService.js} +2 -2
  45. package/dist/types.d.ts +10 -4
  46. package/package.json +11 -2
  47. package/.woodpecker/buildRelease.sh +0 -13
  48. package/.woodpecker/buildSlackNotify.sh +0 -46
  49. package/.woodpecker/release.yml +0 -57
  50. package/agent/checkpointer.ts +0 -329
  51. package/agent/languageDetect.ts +0 -92
  52. package/agent/middleware/apiBasedTools.ts +0 -174
  53. package/agent/middleware/openAiResponsesContinuation.ts +0 -92
  54. package/agent/middleware/sequenceDebug.ts +0 -429
  55. package/agent/models/AgentModeResolver.ts +0 -9
  56. package/agent/models/AgentModelFactory.ts +0 -28
  57. package/agent/runtime/AgentContext.ts +0 -30
  58. package/agent/runtime/AgentRuntime.ts +0 -89
  59. package/agent/simpleAgent.ts +0 -199
  60. package/agent/skills/registry.ts +0 -162
  61. package/agent/speech/SpeechTurnService.ts +0 -179
  62. package/agent/systemPrompt.ts +0 -133
  63. package/agent/toolCallEvents.ts +0 -135
  64. package/agent/tools/AgentToolProvider.ts +0 -28
  65. package/agent/tools/apiTool.ts +0 -66
  66. package/agent/tools/fetchSkill.ts +0 -68
  67. package/agent/tools/fetchToolSchema.ts +0 -47
  68. package/agent/tools/getUserLocation.ts +0 -45
  69. package/agent/tools/index.ts +0 -31
  70. package/agent/tools/navigateUser.ts +0 -210
  71. package/agent/turn/TurnContextBuilder.ts +0 -36
  72. package/agent/turn/TurnLifecycleService.ts +0 -47
  73. package/agent/turn/TurnPersistenceService.ts +0 -33
  74. package/agent/turn/TurnPromptBuilder.ts +0 -51
  75. package/agent/turn/TurnStreamConsumer.ts +0 -69
  76. package/agent/turn/VegaLiteStreamBuffer.ts +0 -90
  77. package/agent/turn/turnTypes.ts +0 -100
  78. package/agentEvents.ts +0 -75
  79. package/agentTurnService.ts +0 -314
  80. package/apiBasedTools.ts +0 -712
  81. package/build.log +0 -67
  82. package/chatSurfaceService.ts +0 -319
  83. package/custom/ChatFooter.vue +0 -173
  84. package/custom/ChatHeader.vue +0 -78
  85. package/custom/ChatSurface.vue +0 -160
  86. package/custom/CustomAutoScrollContainer.vue +0 -164
  87. package/custom/SessionsHistory.vue +0 -88
  88. package/custom/chat.ts +0 -82
  89. package/custom/composables/agentAudio/utils.ts +0 -220
  90. package/custom/composables/agentStore/constants.ts +0 -19
  91. package/custom/composables/agentStore/pageContext.ts +0 -8
  92. package/custom/composables/agentStore/useAgentChat.ts +0 -241
  93. package/custom/composables/agentStore/useAgentPlaceholder.ts +0 -142
  94. package/custom/composables/agentStore/useAgentSessions.ts +0 -350
  95. package/custom/composables/useAgentAudio.ts +0 -272
  96. package/custom/composables/useAgentStore.ts +0 -510
  97. package/custom/composables/useAgentTransitions.ts +0 -58
  98. package/custom/conversation_area/ConversationArea.vue +0 -301
  99. package/custom/conversation_area/MessageRenderer.vue +0 -49
  100. package/custom/conversation_area/ProcessingTimeline.vue +0 -286
  101. package/custom/conversation_area/ReasoningRenderer.vue +0 -79
  102. package/custom/conversation_area/SystemMessageRenderer.vue +0 -28
  103. package/custom/conversation_area/TextRenderer.vue +0 -182
  104. package/custom/conversation_area/ThreeDotsAnimation.vue +0 -35
  105. package/custom/conversation_area/ToolApprovalRenderer.vue +0 -98
  106. package/custom/conversation_area/ToolRenderer.vue +0 -178
  107. package/custom/conversation_area/ToolsGroup.vue +0 -59
  108. package/custom/env.d.ts +0 -7
  109. package/custom/incremark_code_renderers/IncremarkShikiCodeBlock.vue +0 -393
  110. package/custom/incremark_code_renderers/incremarkCodeHighlight.ts +0 -285
  111. package/custom/incremark_code_renderers/incremarkRenderer.ts +0 -653
  112. package/custom/incremark_code_renderers/renderIncremarkMarkdown.ts +0 -118
  113. package/custom/package.json +0 -30
  114. package/custom/pnpm-lock.yaml +0 -2394
  115. package/custom/public/agentAudio/agent-processing.mp3 +0 -0
  116. package/custom/skills/analyze_data/SKILL.md +0 -25
  117. package/custom/skills/charts/SKILL.md +0 -193
  118. package/custom/skills/fetch_data/SKILL.md +0 -31
  119. package/custom/skills/mutate_data/SKILL.md +0 -121
  120. package/custom/speech_recognition_frontend/AudioLines.vue +0 -43
  121. package/custom/speech_recognition_frontend/MicrophoneButon.vue +0 -185
  122. package/custom/speech_recognition_frontend/types/voice-activity-detection.d.ts +0 -22
  123. package/custom/speech_recognition_frontend/voiceActivityDetection.ts +0 -62
  124. package/custom/tsconfig.json +0 -15
  125. package/custom/types.ts +0 -108
  126. package/custom/utils.ts +0 -38
  127. package/dist/agent/middleware/openAiResponsesContinuation.d.ts +0 -1
  128. package/dist/agent/middleware/openAiResponsesContinuation.js +0 -66
  129. package/dist/agent/models/AgentModeResolver.d.ts +0 -9
  130. package/dist/agent/models/AgentModeResolver.js +0 -9
  131. package/dist/agent/simpleAgent.js +0 -118
  132. package/dist/agent/turn/TurnContextBuilder.d.ts +0 -14
  133. package/dist/agent/turn/TurnContextBuilder.js +0 -31
  134. package/dist/agent/turn/TurnLifecycleService.d.ts +0 -24
  135. package/dist/agent/turn/TurnLifecycleService.js +0 -47
  136. package/dist/agent/turn/TurnPersistenceService.d.ts +0 -13
  137. package/dist/agent/turn/TurnPersistenceService.js +0 -35
  138. package/dist/agent/turn/TurnPromptBuilder.d.ts +0 -19
  139. package/dist/agent/turn/TurnPromptBuilder.js +0 -43
  140. package/dist/agent/turn/TurnStreamConsumer.d.ts +0 -11
  141. package/dist/agent/turn/TurnStreamConsumer.js +0 -84
  142. package/dist/agentTurnService.d.ts +0 -24
  143. package/dist/agentTurnService.js +0 -269
  144. package/dist/surfaces/web-sse/createSseEventEmitter.d.ts +0 -14
  145. package/endpoints/chatSurfaces.ts +0 -66
  146. package/endpoints/context.ts +0 -52
  147. package/endpoints/core.ts +0 -181
  148. package/endpoints/sessions.ts +0 -183
  149. package/errors.ts +0 -10
  150. package/index.ts +0 -192
  151. package/pnpm-workspace.yaml +0 -4
  152. package/sanitizeSpeechText.ts +0 -32
  153. package/sessionStore.ts +0 -105
  154. package/surfaces/web-sse/createSseEventEmitter.ts +0 -311
  155. package/tsconfig.json +0 -14
  156. package/types.ts +0 -127
  157. /package/dist/{agent/turn/turnTypes.js → application/ports.js} +0 -0
  158. /package/dist/{agentEvents.js → domain/agentEvents.js} +0 -0
  159. /package/dist/{agent → domain}/languageDetect.d.ts +0 -0
  160. /package/dist/{agent → domain}/languageDetect.js +0 -0
  161. /package/dist/{agent → domain}/systemPrompt.d.ts +0 -0
  162. /package/dist/{agent → domain}/toolCallEvents.d.ts +0 -0
  163. /package/dist/{agent → domain}/toolCallEvents.js +0 -0
  164. /package/dist/{endpoints/context.js → domain/turnTypes.js} +0 -0
  165. /package/dist/{agent/turn/VegaLiteStreamBuffer.js → domain/vegaLiteStreamBuffer.js} +0 -0
  166. /package/dist/{agent/runtime/AgentContext.js → llm/agentContext.js} +0 -0
  167. /package/dist/{agent → llm}/middleware/sequenceDebug.js +0 -0
  168. /package/dist/{agent/checkpointer.d.ts → persistence/checkpointStore.d.ts} +0 -0
  169. /package/dist/{agent/checkpointer.js → persistence/checkpointStore.js} +0 -0
  170. /package/dist/{errors.d.ts → shared/errors.d.ts} +0 -0
  171. /package/dist/{errors.js → shared/errors.js} +0 -0
  172. /package/dist/{sanitizeSpeechText.d.ts → shared/sanitizeSpeechText.d.ts} +0 -0
  173. /package/dist/{sanitizeSpeechText.js → shared/sanitizeSpeechText.js} +0 -0
  174. /package/dist/{apiBasedTools.d.ts → tools/apiBasedTools.d.ts} +0 -0
  175. /package/dist/{agent/tools → tools}/apiTool.js +0 -0
  176. /package/dist/{agent/tools → tools}/fetchSkill.d.ts +0 -0
  177. /package/dist/{agent/tools → tools}/fetchToolSchema.js +0 -0
  178. /package/dist/{agent/tools → tools}/getUserLocation.d.ts +0 -0
  179. /package/dist/{agent/tools → tools}/getUserLocation.js +0 -0
  180. /package/dist/{agent/tools → tools}/index.js +0 -0
  181. /package/dist/{agent/tools → tools}/navigateUser.js +0 -0
  182. /package/dist/{agent → tools}/skills/registry.d.ts +0 -0
  183. /package/dist/{agent → tools}/skills/registry.js +0 -0
  184. /package/dist/{endpoints/chatSurfaces.d.ts → transport/http/chatSurfaceEndpoints.d.ts} +0 -0
  185. /package/dist/{endpoints/chatSurfaces.js → transport/http/chatSurfaceEndpoints.js} +0 -0
  186. /package/dist/{endpoints/core.d.ts → transport/http/coreEndpoints.d.ts} +0 -0
  187. /package/dist/{endpoints/sessions.d.ts → transport/http/sessionEndpoints.d.ts} +0 -0
@@ -1,429 +0,0 @@
1
- import { AIMessage } from "@langchain/core/messages";
2
- import { createMiddleware } from "langchain";
3
- import YAML from "yaml";
4
- import type { ToolCallEvent } from "../toolCallEvents.js";
5
-
6
- export type SequenceDebugResultType = "tool_calls" | "final_text";
7
-
8
- type SequenceDebugToolCall = {
9
- toolCallId: string;
10
- toolName: string;
11
- input: string;
12
- output: string | null;
13
- error: string | null;
14
- };
15
-
16
- type PendingSequenceDebugToolCall = SequenceDebugToolCall & {
17
- completed: boolean;
18
- };
19
-
20
- export type SequenceDebug = {
21
- sequenceId: number;
22
- startedAt: string;
23
- prompt: string;
24
- promptTokens: number;
25
- reasoning: string;
26
- reasoningTokens: number;
27
- text: string;
28
- textTokens: number;
29
- uncachedInputTokens: number;
30
- cachedInputTokens: number;
31
- outputTokens: number;
32
- cachedTokens: number;
33
- responseId: string | null;
34
- toolCalls: SequenceDebugToolCall[];
35
- endedAt: string;
36
- resultType: SequenceDebugResultType;
37
- };
38
-
39
- type PendingSequenceDebug = Omit<SequenceDebug, "toolCalls" | "endedAt" | "resultType"> & {
40
- toolCalls: PendingSequenceDebugToolCall[];
41
- pendingToolCalls: number;
42
- resultType: SequenceDebugResultType | null;
43
- };
44
-
45
- type SequenceDebugModelCall = {
46
- promptTokens: number;
47
- reasoning: string;
48
- reasoningTokens: number;
49
- text: string;
50
- textTokens: number;
51
- uncachedInputTokens: number;
52
- cachedInputTokens: number;
53
- outputTokens: number;
54
- cachedTokens: number;
55
- responseId: string | null;
56
- resultType: SequenceDebugResultType;
57
- };
58
-
59
- type OpenAiUsageMetadata = {
60
- input_tokens?: number;
61
- output_tokens?: number;
62
- input_token_details?: {
63
- cache_read?: number;
64
- };
65
- };
66
-
67
- type OpenAiResponseMetadata = {
68
- id?: string;
69
- };
70
-
71
- export type SequenceDebugModelCallSink = {
72
- handleModelCallStart: (prompt: string) => void;
73
- handleModelCallComplete: (params: SequenceDebugModelCall) => void;
74
- };
75
-
76
- export type SequenceDebugCollector = SequenceDebugModelCallSink & {
77
- handleToolCallEvent: (event: ToolCallEvent) => void;
78
- flush: () => void;
79
- getHistory: () => SequenceDebug[];
80
- };
81
-
82
- function createPendingSequenceDebug(sequenceId: number): PendingSequenceDebug {
83
- return {
84
- sequenceId,
85
- startedAt: new Date().toISOString(),
86
- prompt: "",
87
- promptTokens: 0,
88
- reasoning: "",
89
- reasoningTokens: 0,
90
- text: "",
91
- textTokens: 0,
92
- uncachedInputTokens: 0,
93
- cachedInputTokens: 0,
94
- outputTokens: 0,
95
- cachedTokens: 0,
96
- responseId: null,
97
- toolCalls: [],
98
- pendingToolCalls: 0,
99
- resultType: null,
100
- };
101
- }
102
-
103
- function hasSequenceDebugContent(sequence: PendingSequenceDebug | null): sequence is PendingSequenceDebug {
104
- return Boolean(
105
- sequence &&
106
- (
107
- sequence.prompt ||
108
- sequence.reasoning ||
109
- sequence.text ||
110
- sequence.toolCalls.length > 0
111
- ),
112
- );
113
- }
114
-
115
- function finalizeSequenceDebug(sequence: PendingSequenceDebug): SequenceDebug {
116
- return {
117
- sequenceId: sequence.sequenceId,
118
- startedAt: sequence.startedAt,
119
- prompt: sequence.prompt,
120
- promptTokens: sequence.promptTokens,
121
- reasoning: sequence.reasoning,
122
- reasoningTokens: sequence.reasoningTokens,
123
- text: sequence.text,
124
- textTokens: sequence.textTokens,
125
- uncachedInputTokens: sequence.uncachedInputTokens,
126
- cachedInputTokens: sequence.cachedInputTokens,
127
- outputTokens: sequence.outputTokens,
128
- cachedTokens: sequence.cachedTokens,
129
- responseId: sequence.responseId,
130
- toolCalls: sequence.toolCalls.map(({ completed: _completed, ...toolCall }) => toolCall),
131
- endedAt: new Date().toISOString(),
132
- resultType: sequence.resultType ?? "final_text",
133
- };
134
- }
135
-
136
- type SequenceDebugPromptModel = {
137
- getName?: () => string;
138
- model?: string;
139
- _defaultConfig?: {
140
- modelProvider?: string;
141
- };
142
- invocationParams?: (options?: Record<string, unknown>) => Record<string, unknown>;
143
- };
144
-
145
- function getDebugModelName(model: SequenceDebugPromptModel) {
146
- return typeof model.getName === "function" ? model.getName() : undefined;
147
- }
148
-
149
- function getDebugToolName(tool: unknown) {
150
- if (!tool || typeof tool !== "object") {
151
- return null;
152
- }
153
-
154
- const name = (tool as { name?: unknown }).name;
155
- return typeof name === "string" ? name : null;
156
- }
157
-
158
- function formatToolsForDebug(tools: unknown[]) {
159
- return tools.map((tool) => ({
160
- name: getDebugToolName(tool),
161
- }));
162
- }
163
-
164
- function stringifyPromptForDebug(params: {
165
- model: SequenceDebugPromptModel;
166
- systemMessage: { text: string };
167
- messages: unknown[];
168
- tools: unknown[];
169
- toolChoice?: unknown;
170
- modelSettings?: Record<string, unknown>;
171
- }) {
172
- const { model, systemMessage, messages, tools, toolChoice, modelSettings } = params;
173
- const invocationParams =
174
- typeof model.invocationParams === "function"
175
- ? model.invocationParams({
176
- ...(modelSettings ?? {}),
177
- ...(tools.length > 0 ? { tools } : {}),
178
- ...(toolChoice !== undefined ? { tool_choice: toolChoice } : {}),
179
- })
180
- : null;
181
-
182
- return YAML.stringify({
183
- model: {
184
- name: getDebugModelName(model) ?? null,
185
- provider: model._defaultConfig?.modelProvider ?? null,
186
- configuredModel:
187
- typeof model.model === "string" ? model.model : null,
188
- },
189
- systemMessage,
190
- messages,
191
- ...(tools.length > 0 ? { tools: formatToolsForDebug(tools) } : {}),
192
- ...(toolChoice !== undefined ? { toolChoice } : {}),
193
- ...(modelSettings ? { modelSettings } : {}),
194
- ...(invocationParams ? { invocationParams } : {}),
195
- });
196
- }
197
-
198
- function getMessageBlocks(message: {
199
- contentBlocks?: unknown;
200
- content?: unknown;
201
- }) {
202
- if (Array.isArray(message.contentBlocks)) {
203
- return message.contentBlocks;
204
- }
205
-
206
- if (Array.isArray(message.content)) {
207
- return message.content;
208
- }
209
-
210
- return [];
211
- }
212
-
213
- function hasToolCallSignal(message: {
214
- tool_calls?: unknown;
215
- tool_call_chunks?: unknown;
216
- additional_kwargs?: { tool_calls?: unknown };
217
- }) {
218
- return Boolean(
219
- (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) ||
220
- (Array.isArray(message.tool_call_chunks) && message.tool_call_chunks.length > 0) ||
221
- (Array.isArray(message.additional_kwargs?.tool_calls) &&
222
- message.additional_kwargs.tool_calls.length > 0),
223
- );
224
- }
225
-
226
- function hasTokenCounter(model: unknown): model is {
227
- getNumTokens: (content: string) => Promise<number>;
228
- } {
229
- return (
230
- typeof model === "object" &&
231
- model !== null &&
232
- "getNumTokens" in model &&
233
- typeof model.getNumTokens === "function"
234
- );
235
- }
236
-
237
- async function countTokens(model: unknown, content: string) {
238
- if (!content) {
239
- return 0;
240
- }
241
-
242
- if (!hasTokenCounter(model)) {
243
- return 0;
244
- }
245
-
246
- return await model.getNumTokens(content);
247
- }
248
-
249
- function extractSequenceResponseDebug(message: AIMessage): SequenceDebugModelCall {
250
- const usageMetadata = message.usage_metadata as OpenAiUsageMetadata | undefined;
251
- const promptTokens = usageMetadata?.input_tokens ?? 0;
252
- const cachedInputTokens = usageMetadata?.input_token_details?.cache_read ?? 0;
253
- const blocks = getMessageBlocks(message);
254
- const reasoning = blocks
255
- .filter((block: any) => block?.type === "reasoning")
256
- .map((block: any) => String(block.reasoning ?? ""))
257
- .join("");
258
- const textFromBlocks = blocks
259
- .filter((block: any) => block?.type === "text")
260
- .map((block: any) => String(block.text ?? ""))
261
- .join("");
262
-
263
- return {
264
- promptTokens,
265
- reasoning,
266
- reasoningTokens: 0,
267
- text: textFromBlocks || (typeof message.content === "string" ? message.content : ""),
268
- textTokens: 0,
269
- uncachedInputTokens: Math.max(promptTokens - cachedInputTokens, 0),
270
- cachedInputTokens,
271
- outputTokens: usageMetadata?.output_tokens ?? 0,
272
- cachedTokens: cachedInputTokens,
273
- responseId:
274
- (message.response_metadata as OpenAiResponseMetadata | undefined)?.id ??
275
- null,
276
- resultType: hasToolCallSignal(message) ? "tool_calls" : "final_text",
277
- };
278
- }
279
-
280
- export function createSequenceDebugCollector(): SequenceDebugCollector {
281
- let nextSequenceId = 1;
282
- let currentSequenceDebug: PendingSequenceDebug | null = null;
283
- const history: SequenceDebug[] = [];
284
-
285
- const ensureSequenceDebug = () => {
286
- if (!currentSequenceDebug) {
287
- currentSequenceDebug = createPendingSequenceDebug(nextSequenceId++);
288
- }
289
-
290
- return currentSequenceDebug;
291
- };
292
-
293
- const flush = () => {
294
- if (!hasSequenceDebugContent(currentSequenceDebug)) {
295
- currentSequenceDebug = null;
296
- return;
297
- }
298
-
299
- const finalizedSequenceDebug = finalizeSequenceDebug(currentSequenceDebug);
300
- history.push(finalizedSequenceDebug);
301
- currentSequenceDebug = null;
302
- };
303
-
304
- return {
305
- handleModelCallStart(prompt) {
306
- if (
307
- currentSequenceDebug?.resultType &&
308
- currentSequenceDebug.pendingToolCalls === 0
309
- ) {
310
- flush();
311
- }
312
-
313
- const sequenceDebug = ensureSequenceDebug();
314
- sequenceDebug.prompt = prompt;
315
- },
316
- handleModelCallComplete(params) {
317
- const sequenceDebug = ensureSequenceDebug();
318
- sequenceDebug.promptTokens = params.promptTokens;
319
- sequenceDebug.reasoning = params.reasoning;
320
- sequenceDebug.reasoningTokens = params.reasoningTokens;
321
- sequenceDebug.text = params.text;
322
- sequenceDebug.textTokens = params.textTokens;
323
- sequenceDebug.uncachedInputTokens = params.uncachedInputTokens;
324
- sequenceDebug.cachedInputTokens = params.cachedInputTokens;
325
- sequenceDebug.outputTokens = params.outputTokens;
326
- sequenceDebug.cachedTokens = params.cachedTokens;
327
- sequenceDebug.responseId = params.responseId;
328
- sequenceDebug.resultType = params.resultType;
329
-
330
- if (
331
- sequenceDebug.resultType === "final_text" &&
332
- sequenceDebug.pendingToolCalls === 0
333
- ) {
334
- flush();
335
- }
336
- },
337
- handleToolCallEvent(event) {
338
- const sequenceDebug = ensureSequenceDebug();
339
-
340
- if (event.phase === "start") {
341
- sequenceDebug.toolCalls.push({
342
- toolCallId: event.toolCallId,
343
- toolName: event.toolName,
344
- input: event.input,
345
- output: null,
346
- error: null,
347
- completed: false,
348
- });
349
- sequenceDebug.pendingToolCalls += 1;
350
- return;
351
- }
352
-
353
- const pendingToolCall = sequenceDebug.toolCalls.find(
354
- (toolCall) => toolCall.toolCallId === event.toolCallId && !toolCall.completed,
355
- );
356
-
357
- if (pendingToolCall) {
358
- pendingToolCall.output = event.output;
359
- pendingToolCall.error = event.error;
360
- pendingToolCall.completed = true;
361
- } else {
362
- sequenceDebug.toolCalls.push({
363
- toolCallId: event.toolCallId,
364
- toolName: event.toolName,
365
- input: "",
366
- output: event.output,
367
- error: event.error,
368
- completed: true,
369
- });
370
- }
371
-
372
- sequenceDebug.pendingToolCalls = Math.max(
373
- 0,
374
- sequenceDebug.pendingToolCalls - 1,
375
- );
376
-
377
- if (
378
- sequenceDebug.resultType === "tool_calls" &&
379
- sequenceDebug.pendingToolCalls === 0
380
- ) {
381
- flush();
382
- }
383
- },
384
- flush,
385
- getHistory() {
386
- return history;
387
- },
388
- };
389
- }
390
-
391
- export function createSequenceDebugMiddleware(
392
- sink: SequenceDebugModelCallSink,
393
- ) {
394
- return createMiddleware({
395
- name: "SequenceDebugMiddleware",
396
- async wrapModelCall(request, handler) {
397
- const prompt = stringifyPromptForDebug({
398
- model: request.model as unknown as SequenceDebugPromptModel,
399
- systemMessage: request.systemMessage,
400
- messages: request.messages,
401
- tools: request.tools,
402
- toolChoice: request.toolChoice,
403
- modelSettings: request.modelSettings,
404
- });
405
-
406
- sink.handleModelCallStart(
407
- prompt,
408
- );
409
-
410
- const response = await handler(request) as AIMessage;
411
- const debug = extractSequenceResponseDebug(response);
412
- const [promptTokens, reasoningTokens, textTokens] = await Promise.all([
413
- debug.promptTokens || countTokens(request.model, prompt),
414
- countTokens(request.model, debug.reasoning),
415
- countTokens(request.model, debug.text),
416
- ]);
417
-
418
- sink.handleModelCallComplete({
419
- ...debug,
420
- promptTokens,
421
- reasoningTokens,
422
- textTokens,
423
- uncachedInputTokens: debug.promptTokens ? debug.uncachedInputTokens : promptTokens,
424
- outputTokens: debug.outputTokens || reasoningTokens + textTokens,
425
- });
426
- return response;
427
- },
428
- });
429
- }
@@ -1,9 +0,0 @@
1
- import type { PluginOptions } from "../../types.js";
2
-
3
- export class AgentModeResolver {
4
- constructor(private readonly options: PluginOptions) {}
5
-
6
- resolve(modeName?: string | null) {
7
- return this.options.modes.find((mode) => mode.name === modeName) ?? this.options.modes[0];
8
- }
9
- }
@@ -1,28 +0,0 @@
1
- import type { CompletionAdapter } from "adminforth";
2
- import { createAgentChatModel } from "../simpleAgent.js";
3
- import type { AgentTurnModels } from "../turn/turnTypes.js";
4
-
5
- export class AgentModelFactory {
6
- constructor(private readonly maxTokens: number) {}
7
-
8
- async create(completionAdapter: CompletionAdapter): Promise<AgentTurnModels> {
9
- const [primaryModelSpec, summaryModelSpec] = await Promise.all([
10
- createAgentChatModel({
11
- adapter: completionAdapter,
12
- maxTokens: this.maxTokens,
13
- purpose: "primary",
14
- }),
15
- createAgentChatModel({
16
- adapter: completionAdapter,
17
- maxTokens: this.maxTokens,
18
- purpose: "summary",
19
- }),
20
- ]);
21
-
22
- return {
23
- model: primaryModelSpec.model,
24
- summaryModel: summaryModelSpec.model,
25
- modelMiddleware: primaryModelSpec.middleware,
26
- };
27
- }
28
- }
@@ -1,30 +0,0 @@
1
- import type { AdminUser } from "adminforth";
2
- import { z } from "zod";
3
- import type { AgentEventEmitter } from "../../agentEvents.js";
4
- import type { SequenceDebugCollector } from "../middleware/sequenceDebug.js";
5
- import type { CurrentPageContext } from "../tools/getUserLocation.js";
6
- import type { AgentTurnContext } from "../turn/turnTypes.js";
7
-
8
- export const contextSchema = z.object({
9
- adminUser: z.custom<AdminUser>(),
10
- userTimeZone: z.string(),
11
- sessionId: z.string(),
12
- turnId: z.string(),
13
- abortSignal: z.custom<AbortSignal>().optional(),
14
- currentPage: z.custom<CurrentPageContext>().optional(),
15
- chatSurface: z.string().optional(),
16
- adminBaseUrl: z.string().optional(),
17
- adminPublicOrigin: z.string().optional(),
18
- emit: z.custom<AgentEventEmitter>().optional(),
19
- sequenceDebugSink: z.custom<SequenceDebugCollector>(),
20
- });
21
-
22
- export function toLangchainAgentContext(
23
- context: AgentTurnContext & {
24
- adminBaseUrl: string;
25
- emit?: AgentEventEmitter;
26
- sequenceDebugSink: SequenceDebugCollector;
27
- },
28
- ) {
29
- return context;
30
- }
@@ -1,89 +0,0 @@
1
- import type { IAdminForth } from "adminforth";
2
- import { createAgent, summarizationMiddleware, humanInTheLoopMiddleware } from "langchain";
3
- import type { BaseCheckpointSaver } from "@langchain/langgraph";
4
- import { createApiBasedToolsMiddleware } from "../middleware/apiBasedTools.js";
5
- import { createSequenceDebugMiddleware } from "../middleware/sequenceDebug.js";
6
- import { createAgentLlmMetricsLogger } from "../simpleAgent.js";
7
- import type { AgentToolProvider } from "../tools/AgentToolProvider.js";
8
- import type { AgentRuntimeRunInput } from "../turn/turnTypes.js";
9
- import { contextSchema, toLangchainAgentContext } from "./AgentContext.js";
10
- import type { ApiBasedTool } from "../../apiBasedTools.js";
11
-
12
- function createHumanInTheLoopInterrupts(
13
- apiBasedTools: Record<string, ApiBasedTool>,
14
- ): Record<string, { allowedDecisions: ("approve" | "reject" | "edit")[] }> {
15
- return Object.fromEntries(
16
- Object.entries(apiBasedTools)
17
- .filter(([, apiBasedTool]) => apiBasedTool.agent?.isDangerous === true)
18
- .map(([toolName]) => [
19
- toolName,
20
- {
21
- allowedDecisions: ["approve", "reject"],
22
- },
23
- ]),
24
- );
25
- }
26
-
27
- export type AgentRuntimeOptions = {
28
- name: string;
29
- getAdminforth: () => IAdminForth;
30
- getCheckpointer: () => BaseCheckpointSaver;
31
- toolProvider: AgentToolProvider;
32
- };
33
-
34
- export class AgentRuntime {
35
- constructor(private readonly options: AgentRuntimeOptions) {}
36
-
37
- async stream(input: AgentRuntimeRunInput) {
38
- const apiBasedTools = this.options.toolProvider.getApiBasedTools();
39
- const tools = await this.options.toolProvider.getTools(apiBasedTools);
40
- const adminforth = this.options.getAdminforth();
41
- const apiBasedToolsMiddleware = createApiBasedToolsMiddleware(
42
- apiBasedTools,
43
- adminforth,
44
- );
45
- const sequenceDebugMiddleware = createSequenceDebugMiddleware(
46
- input.observability.sequenceDebugSink,
47
- );
48
- const hitlMiddleware = humanInTheLoopMiddleware({
49
- interruptOn: createHumanInTheLoopInterrupts(apiBasedTools),
50
- descriptionPrefix: "Tool execution pending approval",
51
- });
52
- const middleware = [
53
- apiBasedToolsMiddleware,
54
- hitlMiddleware,
55
- ...(input.models.modelMiddleware ?? []),
56
- sequenceDebugMiddleware,
57
- summarizationMiddleware({
58
- model: input.models.summaryModel,
59
- trigger: { tokens: 1024 * 64 },
60
- keep: { messages: 10 },
61
- }),
62
- ] as const;
63
-
64
- const agent = createAgent({
65
- name: this.options.name,
66
- model: input.models.model,
67
- checkpointer: this.options.getCheckpointer(),
68
- tools,
69
- contextSchema,
70
- middleware,
71
- });
72
-
73
- return agent.stream(input.input as any, {
74
- streamMode: ["messages", "updates"],
75
- recursionLimit: 100,
76
- callbacks: [createAgentLlmMetricsLogger()],
77
- signal: input.context.abortSignal,
78
- configurable: {
79
- thread_id: input.context.sessionId,
80
- },
81
- context: toLangchainAgentContext({
82
- ...input.context,
83
- adminBaseUrl: adminforth.config.baseUrlSlashed,
84
- emit: input.observability.emit,
85
- sequenceDebugSink: input.observability.sequenceDebugSink,
86
- }),
87
- });
88
- }
89
- }