@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,135 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import YAML from "yaml";
3
-
4
- export type ToolCallEvent =
5
- | {
6
- toolCallId: string;
7
- toolName: string;
8
- toolInfo?: string;
9
- phase: "start";
10
- input: string;
11
- }
12
- | {
13
- toolCallId: string;
14
- toolName: string;
15
- phase: "end";
16
- durationMs: number;
17
- output: string | null;
18
- error: string | null;
19
- };
20
-
21
- export type ToolCallEventSink = (event: ToolCallEvent) => void;
22
-
23
- const TOOL_MESSAGE_DEBUG_KEYS = new Set([
24
- "metadata",
25
- "additional_kwargs",
26
- "response_metadata",
27
- ]);
28
-
29
- function getToolCallDebugPayload(outputRecord: Record<string, unknown>) {
30
- const lcKwargs =
31
- typeof outputRecord.lc_kwargs === "object" && outputRecord.lc_kwargs !== null
32
- ? outputRecord.lc_kwargs as Record<string, unknown>
33
- : null;
34
-
35
- if (lcKwargs && "tool_call_id" in lcKwargs) {
36
- return lcKwargs;
37
- }
38
-
39
- if ("tool_call_id" in outputRecord) {
40
- return outputRecord;
41
- }
42
-
43
- return null;
44
- }
45
-
46
- function sanitizeToolCallOutputForDebug(output: unknown) {
47
- if (typeof output !== "object" || output === null) {
48
- return output;
49
- }
50
-
51
- const outputRecord = output as Record<string, unknown>;
52
- const debugPayload = getToolCallDebugPayload(outputRecord);
53
-
54
- if (!debugPayload) {
55
- return output;
56
- }
57
-
58
- return Object.fromEntries(
59
- Object.entries(debugPayload).filter(([key]) => !TOOL_MESSAGE_DEBUG_KEYS.has(key)),
60
- );
61
- }
62
-
63
- function serializeErrorForDebug(error: unknown): unknown {
64
- if (!(error instanceof Error)) {
65
- return error;
66
- }
67
-
68
- const errorWithCause = error as Error & { cause?: unknown };
69
- const serialized: Record<string, unknown> = {
70
- name: error.name,
71
- message: error.message,
72
- };
73
-
74
- if (error.stack) {
75
- serialized.stack = error.stack;
76
- }
77
-
78
- if (errorWithCause.cause !== undefined) {
79
- serialized.cause = serializeErrorForDebug(errorWithCause.cause);
80
- }
81
-
82
- for (const key of Object.getOwnPropertyNames(error)) {
83
- if (key in serialized) {
84
- continue;
85
- }
86
-
87
- serialized[key] = (error as unknown as Record<string, unknown>)[key];
88
- }
89
-
90
- return serialized;
91
- }
92
-
93
- export function createToolCallTracker(params: {
94
- emit: ToolCallEventSink;
95
- toolCallId?: string;
96
- toolName: string;
97
- toolInfo?: string;
98
- input?: Record<string, unknown>;
99
- startedAt?: number;
100
- }) {
101
- const toolCallId = params.toolCallId ?? randomUUID();
102
- const startedAt = params.startedAt ?? Date.now();
103
-
104
- return {
105
- start() {
106
- params.emit({
107
- toolCallId,
108
- toolName: params.toolName,
109
- toolInfo: params.toolInfo,
110
- phase: "start",
111
- input: YAML.stringify(params.input ?? {}),
112
- });
113
- },
114
- finishSuccess(output: unknown) {
115
- params.emit({
116
- toolCallId,
117
- toolName: params.toolName,
118
- phase: "end",
119
- durationMs: Date.now() - startedAt,
120
- output: YAML.stringify(sanitizeToolCallOutputForDebug(output)).trimEnd(),
121
- error: null,
122
- });
123
- },
124
- finishError(error: unknown) {
125
- params.emit({
126
- toolCallId,
127
- toolName: params.toolName,
128
- phase: "end",
129
- durationMs: Date.now() - startedAt,
130
- output: null,
131
- error: YAML.stringify(serializeErrorForDebug(error)).trimEnd(),
132
- });
133
- },
134
- };
135
- }
@@ -1,28 +0,0 @@
1
- import type { IAdminForth } from "adminforth";
2
- import { prepareApiBasedTools } from "../../apiBasedTools.js";
3
- import type { ApiBasedTool } from "../../apiBasedTools.js";
4
- import { createAgentTools } from "./index.js";
5
-
6
- export class AgentToolProvider {
7
- constructor(
8
- private readonly getAdminforth: () => IAdminForth,
9
- private readonly getInternalAgentResourceIds: () => string[],
10
- ) {}
11
-
12
- getApiBasedTools(): Record<string, ApiBasedTool> {
13
- return prepareApiBasedTools(
14
- this.getAdminforth(),
15
- this.getInternalAgentResourceIds(),
16
- );
17
- }
18
-
19
- async getTools(apiBasedTools: Record<string, ApiBasedTool>) {
20
- const adminforth = this.getAdminforth();
21
-
22
- return createAgentTools(
23
- adminforth.config.customization.customComponentsDir ?? "custom",
24
- apiBasedTools,
25
- adminforth.activatedPlugins.map((plugin) => plugin.customFolderPath),
26
- );
27
- }
28
- }
@@ -1,66 +0,0 @@
1
- import { tool } from "langchain";
2
- import type { ApiBasedTool } from "../../apiBasedTools.js";
3
-
4
- const emptyToolSchema = {
5
- type: "object",
6
- properties: {},
7
- additionalProperties: true,
8
- } as const;
9
-
10
- function normalizeToolInputSchema(inputSchema: unknown) {
11
- if (!inputSchema || typeof inputSchema !== "object" || Array.isArray(inputSchema)) {
12
- return emptyToolSchema;
13
- }
14
-
15
- const schema = JSON.parse(JSON.stringify(inputSchema)) as Record<string, unknown>;
16
-
17
- if (schema.type !== "object") {
18
- return emptyToolSchema;
19
- }
20
-
21
- const notes: string[] = [];
22
-
23
- if ("if" in schema || "then" in schema || "else" in schema || "allOf" in schema) {
24
- delete schema.if;
25
- delete schema.then;
26
- delete schema.else;
27
- delete schema.allOf;
28
- notes.push("Runtime applies additional conditional validation rules.");
29
- }
30
-
31
- if ("oneOf" in schema || "anyOf" in schema || "not" in schema || "enum" in schema) {
32
- delete schema.oneOf;
33
- delete schema.anyOf;
34
- delete schema.not;
35
- delete schema.enum;
36
- notes.push("Top-level composite validation rules are omitted for tool compatibility.");
37
- }
38
-
39
- if (notes.length > 0) {
40
- schema.description = typeof schema.description === "string"
41
- ? `${schema.description}\n\n${notes.join(" ")}`
42
- : notes.join(" ");
43
- }
44
-
45
- return schema;
46
- }
47
-
48
- export function createApiTool(toolName: string, apiBasedTool: ApiBasedTool) {
49
- return tool(
50
- async (input, runtime) => {
51
- const normalizedInput = (input ?? {}) as Record<string, unknown>;
52
- return apiBasedTool.call({
53
- adminUser: runtime.context.adminUser,
54
- abortSignal: runtime.context.abortSignal,
55
- inputs: normalizedInput,
56
- userTimeZone: runtime.context.userTimeZone,
57
- });
58
- },
59
- {
60
- name: toolName,
61
- description: apiBasedTool.description ?? `${toolName} tool`,
62
- schema: normalizeToolInputSchema(apiBasedTool.input_schema),
63
- verboseParsingErrors: true,
64
- },
65
- );
66
- }
@@ -1,68 +0,0 @@
1
- import { tool } from "langchain";
2
- import { z } from "zod";
3
- import {
4
- listSkillManifests,
5
- loadSkillMarkdown,
6
- type AgentSkillManifest,
7
- } from "../skills/registry.js";
8
-
9
- const fetchSkillSchema = z.object({
10
- skillName: z
11
- .string()
12
- .describe(
13
- "Name of the custom AdminForth skill to load, for example fetch_data or mutate_data.",
14
- ),
15
- });
16
-
17
- function serializeSkillManifests(skillManifests: AgentSkillManifest[]) {
18
- return skillManifests.map((skill) => ({
19
- name: skill.name,
20
- description: skill.description,
21
- }));
22
- }
23
-
24
- export async function createFetchSkillTool(
25
- customComponentsDir: string,
26
- pluginCustomFolderPaths: string[] = [],
27
- ) {
28
- const availableSkills = await listSkillManifests(
29
- customComponentsDir,
30
- pluginCustomFolderPaths,
31
- );
32
- const availableSkillNames = availableSkills.map((skill) => skill.name);
33
-
34
- return tool(
35
- async ({ skillName }) => {
36
- try {
37
- const skillMarkdown = await loadSkillMarkdown(
38
- skillName,
39
- customComponentsDir,
40
- pluginCustomFolderPaths,
41
- );
42
-
43
- if (!skillMarkdown) {
44
- return [
45
- `Skill "${skillName}" not found.`,
46
- "Available skills:",
47
- JSON.stringify(serializeSkillManifests(availableSkills), null, 2),
48
- ].join("\n");
49
- }
50
-
51
- return skillMarkdown;
52
- } catch (error) {
53
- return `Failed to load skill "${skillName}": ${
54
- error instanceof Error ? error.message : String(error)
55
- }`;
56
- }
57
- },
58
- {
59
- name: "fetch_skill",
60
- description: `Fetch the raw SKILL.md content for a custom AdminForth skill by name.${
61
- availableSkillNames.length > 0
62
- ? ` Available skills: ${availableSkillNames.join(", ")}.`
63
- : ""
64
- }`,
65
- schema: fetchSkillSchema,
66
- },
67
- );
68
- }
@@ -1,47 +0,0 @@
1
- import { tool } from "langchain";
2
- import { z } from "zod";
3
- import type { ApiBasedTool } from "../../apiBasedTools.js";
4
-
5
- const fetchToolSchemaSchema = z.object({
6
- toolName: z
7
- .string()
8
- .describe("Name of the API-based tool to load, for example get_resource."),
9
- });
10
-
11
- export async function createFetchToolSchemaTool(
12
- apiBasedTools: Record<string, ApiBasedTool>,
13
- ) {
14
- return tool(
15
- async ({ toolName }) => {
16
- const toolDefinition = apiBasedTools[toolName];
17
-
18
- if (!toolDefinition) {
19
- return JSON.stringify(
20
- {
21
- status: 404,
22
- error: "TOOL_NOT_FOUND",
23
- message: `Tool "${toolName}" not found.`,
24
- },
25
- null,
26
- 2,
27
- );
28
- }
29
-
30
- return JSON.stringify(
31
- {
32
- status: 200,
33
- name: toolName,
34
- loaded: true,
35
- },
36
- null,
37
- 2,
38
- );
39
- },
40
- {
41
- name: "fetch_tool_schema",
42
- description:
43
- "Fetch the schema for an API-based AdminForth tool by name and load it for later use. Use this right after fetch_skill when the skill mentions non-base tools.",
44
- schema: fetchToolSchemaSchema,
45
- },
46
- );
47
- }
@@ -1,45 +0,0 @@
1
- import { tool } from "langchain";
2
- import { z } from "zod";
3
-
4
- export type CurrentPageContext = {
5
- path: string;
6
- fullPath: string;
7
- title: string;
8
- url: string;
9
- };
10
-
11
- const getUserLocationSchema = z.object({});
12
-
13
- export function createGetUserLocationTool() {
14
- return tool(
15
- async (_input, runtime) => {
16
- const currentPage = (runtime.context as { currentPage?: CurrentPageContext }).currentPage;
17
-
18
- if (!currentPage) {
19
- return JSON.stringify(
20
- {
21
- status: 404,
22
- message: "Current user location is not available.",
23
- },
24
- null,
25
- 2,
26
- );
27
- }
28
-
29
- return JSON.stringify(
30
- {
31
- status: 200,
32
- location: currentPage,
33
- },
34
- null,
35
- 2,
36
- );
37
- },
38
- {
39
- name: "get_user_location",
40
- description:
41
- "Get the user's current location in the AdminForth UI, including current page path, full path, title, and URL. Call this tool when you do not understand what the user is referring to, especially when they say here, this page, current page, opened page, or otherwise rely on page context.",
42
- schema: getUserLocationSchema,
43
- },
44
- );
45
- }
@@ -1,31 +0,0 @@
1
- import type { ClientTool } from "@langchain/core/tools";
2
- import { createFetchSkillTool } from "./fetchSkill.js";
3
- import { createFetchToolSchemaTool } from "./fetchToolSchema.js";
4
- import type { ApiBasedTool } from "../../apiBasedTools.js";
5
- import { createApiTool } from "./apiTool.js";
6
- import { createGetUserLocationTool } from "./getUserLocation.js";
7
- import { createNavigateUserTool } from "./navigateUser.js";
8
-
9
- export const ALWAYS_AVAILABLE_API_TOOL_NAMES = ["get_resource"] as const;
10
-
11
- export async function createAgentTools(
12
- customComponentsDir: string,
13
- apiBasedTools: Record<string, ApiBasedTool>,
14
- pluginCustomFolderPaths: string[] = [],
15
- ): Promise<ClientTool[]> {
16
- return [
17
- ...ALWAYS_AVAILABLE_API_TOOL_NAMES.map((toolName) => {
18
- const apiBasedTool = apiBasedTools[toolName];
19
-
20
- if (!apiBasedTool) {
21
- throw new Error(`Required base API tool "${toolName}" is missing.`);
22
- }
23
-
24
- return createApiTool(toolName, apiBasedTool);
25
- }),
26
- createGetUserLocationTool(),
27
- createNavigateUserTool(),
28
- await createFetchSkillTool(customComponentsDir, pluginCustomFolderPaths),
29
- await createFetchToolSchemaTool(apiBasedTools),
30
- ];
31
- }
@@ -1,210 +0,0 @@
1
- import { tool } from "langchain";
2
- import { z } from "zod";
3
- import type { CurrentPageContext } from "./getUserLocation.js";
4
- import type { AgentEventEmitter } from "../../agentEvents.js";
5
-
6
- const filterSchema = z.object({
7
- column: z.string().min(1).describe("Resource column name."),
8
- operator: z
9
- .string()
10
- .min(1)
11
- .describe("Filter operator suffix, for example eq, gte, lte, like, in."),
12
- value: z.unknown().describe("Filter value. Dates should be ISO strings."),
13
- });
14
-
15
- const navigateUserSchema = z
16
- .object({
17
- targetPath: z
18
- .string()
19
- .optional()
20
- .describe(
21
- "Root-relative AdminForth path to open, with optional query string and hash, for example /resource/adminuser?sort=created_at__desc.",
22
- ),
23
- resourceId: z
24
- .string()
25
- .optional()
26
- .describe("Resource id to build an AdminForth resource route for."),
27
- mode: z
28
- .enum(["list", "show", "edit", "create"])
29
- .optional()
30
- .default("list")
31
- .describe("Resource page mode. Defaults to list."),
32
- recordId: z
33
- .union([z.string(), z.number()])
34
- .optional()
35
- .describe("Record primary key for show or edit resource pages."),
36
- filters: z
37
- .array(filterSchema)
38
- .optional()
39
- .describe(
40
- "List page filters. Each item becomes filter__{column}__{operator}=JSON.stringify(value).",
41
- ),
42
- sort: z
43
- .object({
44
- column: z.string().min(1),
45
- direction: z.enum(["asc", "desc"]),
46
- })
47
- .optional()
48
- .describe("List page sort. Becomes sort={column}__{direction}."),
49
- query: z
50
- .record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
51
- .optional()
52
- .describe("Additional query parameters to append to the target URL."),
53
- })
54
- .refine((input) => input.targetPath || input.resourceId, {
55
- message: "Either targetPath or resourceId is required.",
56
- });
57
-
58
- function normalizeTargetPath(targetPath: string, currentPage?: CurrentPageContext) {
59
- const trimmed = targetPath.trim();
60
-
61
- if (!trimmed) {
62
- throw new Error("targetPath cannot be empty.");
63
- }
64
-
65
- const currentOrigin = currentPage?.url ? new URL(currentPage.url).origin : undefined;
66
-
67
- if (currentOrigin) {
68
- const targetUrl = new URL(trimmed, currentOrigin);
69
-
70
- if (targetUrl.origin !== currentOrigin) {
71
- throw new Error("Only same-origin navigation targets are allowed.");
72
- }
73
-
74
- return `${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;
75
- }
76
-
77
- const fallbackOrigin = "http://adminforth.local";
78
- const targetUrl = new URL(trimmed, fallbackOrigin);
79
-
80
- if (targetUrl.origin !== fallbackOrigin) {
81
- throw new Error("Only relative AdminForth paths are allowed when current origin is unavailable.");
82
- }
83
-
84
- return `${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`;
85
- }
86
-
87
- function appendQueryParams(path: string, params: URLSearchParams) {
88
- const queryString = params.toString();
89
-
90
- if (!queryString) {
91
- return path;
92
- }
93
-
94
- const hashIndex = path.indexOf("#");
95
- const pathWithoutHash = hashIndex === -1 ? path : path.slice(0, hashIndex);
96
- const hash = hashIndex === -1 ? "" : path.slice(hashIndex);
97
- const separator = pathWithoutHash.includes("?") ? "&" : "?";
98
-
99
- return `${pathWithoutHash}${separator}${queryString}${hash}`;
100
- }
101
-
102
- function buildResourcePath(input: z.infer<typeof navigateUserSchema>) {
103
- if (!input.resourceId) {
104
- throw new Error("resourceId is required to build a resource route.");
105
- }
106
-
107
- const resourceId = encodeURIComponent(input.resourceId);
108
- const mode = input.mode ?? "list";
109
-
110
- if (mode === "show" || mode === "edit") {
111
- if (input.recordId === undefined || input.recordId === null) {
112
- throw new Error(`recordId is required for ${mode} resource pages.`);
113
- }
114
-
115
- return `/resource/${resourceId}/${mode}/${encodeURIComponent(String(input.recordId))}`;
116
- }
117
-
118
- if (mode === "create") {
119
- return `/resource/${resourceId}/create`;
120
- }
121
-
122
- return `/resource/${resourceId}`;
123
- }
124
-
125
- function buildQueryParams(input: z.infer<typeof navigateUserSchema>) {
126
- const params = new URLSearchParams();
127
-
128
- for (const filter of input.filters ?? []) {
129
- params.set(
130
- `filter__${filter.column}__${filter.operator}`,
131
- JSON.stringify(filter.value),
132
- );
133
- }
134
-
135
- if (input.sort) {
136
- params.set("sort", `${input.sort.column}__${input.sort.direction}`);
137
- }
138
-
139
- for (const [key, value] of Object.entries(input.query ?? {})) {
140
- params.set(key, String(value));
141
- }
142
-
143
- return params;
144
- }
145
-
146
- function buildSurfaceUrl(targetPath: string, adminBaseUrl?: string, adminPublicOrigin?: string) {
147
- const normalizedBasePath = adminBaseUrl?.replace(/\/+$/, "") ?? "";
148
- const normalizedTargetPath = targetPath.replace(/^\/+/, "");
149
- const path = `${normalizedBasePath}/${normalizedTargetPath}`;
150
-
151
- return adminPublicOrigin ? new URL(path, adminPublicOrigin).toString() : path;
152
- }
153
-
154
- export function createNavigateUserTool() {
155
- return tool(
156
- async (input, runtime) => {
157
- const context = runtime.context as {
158
- currentPage?: CurrentPageContext;
159
- chatSurface?: string;
160
- adminBaseUrl?: string;
161
- adminPublicOrigin?: string;
162
- emit?: AgentEventEmitter;
163
- };
164
- const currentPage = context.currentPage;
165
- const basePath = input.targetPath
166
- ? normalizeTargetPath(input.targetPath, currentPage)
167
- : buildResourcePath(input);
168
- const targetPath = appendQueryParams(basePath, buildQueryParams(input));
169
-
170
- if (context.chatSurface) {
171
- const url = buildSurfaceUrl(targetPath, context.adminBaseUrl, context.adminPublicOrigin);
172
-
173
- return JSON.stringify(
174
- {
175
- status: 200,
176
- action: "link",
177
- surface: context.chatSurface,
178
- targetPath,
179
- url,
180
- message: `Send this link to the user: ${url}`,
181
- },
182
- null,
183
- 2,
184
- );
185
- }
186
-
187
- await context.emit?.({
188
- type: "open-page",
189
- targetPath,
190
- });
191
-
192
- return JSON.stringify(
193
- {
194
- status: 200,
195
- action: "navigate",
196
- targetPath,
197
- message: `Navigation requested to ${targetPath}.`,
198
- },
199
- null,
200
- 2,
201
- );
202
- },
203
- {
204
- name: "navigate_user",
205
- description:
206
- "Navigate the user to another AdminForth page. Use this only when the user asks to open, show, go to, or switch to a resource list/detail page, including filtered or sorted resource lists. Or if the user is asked to open something on the left. Do not use this tool in any other case.",
207
- schema: navigateUserSchema,
208
- },
209
- );
210
- }
@@ -1,36 +0,0 @@
1
- import type { AdminUser, IAdminForth } from "adminforth";
2
- import type { AgentTurnContext, BaseAgentTurnInput } from "./turnTypes.js";
3
-
4
- export type UserContextProvider = {
5
- getUserTimeZone(adminUser: AdminUser): Promise<string | null | undefined> | string | null | undefined;
6
- };
7
-
8
- export class TurnContextBuilder {
9
- constructor(
10
- private readonly getAdminforth: () => IAdminForth,
11
- private readonly userContextProvider?: UserContextProvider,
12
- ) {}
13
-
14
- async build(input: {
15
- base: BaseAgentTurnInput;
16
- turnId: string;
17
- }): Promise<AgentTurnContext> {
18
- const adminforth = this.getAdminforth();
19
-
20
- return {
21
- adminUser: input.base.adminUser,
22
- sessionId: input.base.sessionId,
23
- turnId: input.turnId,
24
- abortSignal: input.base.abortSignal,
25
- currentPage: input.base.currentPage,
26
- chatSurface: input.base.chatSurface,
27
- userTimeZone:
28
- input.base.userTimeZone
29
- ?? await this.userContextProvider?.getUserTimeZone(input.base.adminUser)
30
- ?? "UTC",
31
- adminPublicOrigin:
32
- input.base.adminPublicOrigin
33
- ?? adminforth.config.baseUrlSlashed,
34
- };
35
- }
36
- }