@adminforth/agent 3.1.10 → 3.3.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 (45) hide show
  1. package/README.md +71 -38
  2. package/dist/application/ports.d.ts +3 -1
  3. package/dist/application/runTurnUseCase.d.ts +3 -3
  4. package/dist/application/runTurnUseCase.js +8 -6
  5. package/dist/custom/ChatSurface.vue +25 -8
  6. package/dist/custom/{skills/charts/SKILL.md → charts.md} +2 -4
  7. package/dist/custom/composables/useAgentStore.ts +0 -20
  8. package/dist/custom/composables/useAgentTransitions.ts +13 -37
  9. package/dist/custom/utils.ts +5 -0
  10. package/dist/domain/systemPrompt.d.ts +3 -2
  11. package/dist/domain/systemPrompt.js +14 -53
  12. package/dist/index.d.ts +0 -3
  13. package/dist/index.js +24 -35
  14. package/dist/llm/agentRuntime.d.ts +9 -8
  15. package/dist/llm/agentRuntime.js +134 -106
  16. package/dist/llm/langGraphLlm.d.ts +3 -0
  17. package/dist/llm/langGraphLlm.js +10 -2
  18. package/dist/llm/middleware/mcpToolsMiddleware.d.ts +7 -0
  19. package/dist/llm/middleware/{apiToolsMiddleware.js → mcpToolsMiddleware.js} +16 -36
  20. package/dist/tools/agentToolProvider.d.ts +16 -5
  21. package/dist/tools/agentToolProvider.js +26 -10
  22. package/dist/tools/fetchToolSchema.d.ts +7 -3
  23. package/dist/tools/fetchToolSchema.js +29 -22
  24. package/dist/tools/mcpConnection.d.ts +38 -0
  25. package/dist/tools/mcpConnection.js +42 -0
  26. package/dist/tools/mcpTool.d.ts +3 -0
  27. package/dist/tools/{apiTool.js → mcpTool.js} +7 -23
  28. package/dist/tools/toolLabels.d.ts +5 -0
  29. package/dist/tools/toolLabels.js +49 -0
  30. package/dist/transport/http/context.d.ts +2 -2
  31. package/dist/transport/http/sessionEndpoints.js +1 -1
  32. package/package.json +6 -4
  33. package/dist/custom/skills/analyze_data/SKILL.md +0 -25
  34. package/dist/custom/skills/fetch_data/SKILL.md +0 -31
  35. package/dist/custom/skills/mutate_data/SKILL.md +0 -121
  36. package/dist/llm/middleware/apiToolsMiddleware.d.ts +0 -3
  37. package/dist/tools/apiBasedTools.d.ts +0 -30
  38. package/dist/tools/apiBasedTools.js +0 -488
  39. package/dist/tools/apiTool.d.ts +0 -6
  40. package/dist/tools/fetchSkill.d.ts +0 -8
  41. package/dist/tools/fetchSkill.js +0 -51
  42. package/dist/tools/index.d.ts +0 -4
  43. package/dist/tools/index.js +0 -32
  44. package/dist/tools/skills/registry.d.ts +0 -11
  45. package/dist/tools/skills/registry.js +0 -107
@@ -1,13 +1,3 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { listProjectSkillManifests, } from "../tools/skills/registry.js";
11
1
  export const DEFAULT_AGENT_SYSTEM_PROMPT = [
12
2
  "You are helpful AI Assistant for Admin Panel.",
13
3
  // about admin
@@ -55,53 +45,24 @@ export function buildDynamicSystemPrompt(input) {
55
45
  var _a;
56
46
  return [
57
47
  formatAdminUserPrompt(input.adminUser, input.usernameField),
48
+ `User time zone: ${input.userTimeZone}. Read the dates the user mentions in it, and pass datetimes in tool arguments in UTC, ending with Z.`,
58
49
  input.chatSurface
59
50
  ? `Current chat surface: ${input.chatSurface}. The user is not in the AdminForth web UI, so tools cannot move their browser. When navigate_user returns a link, send that link to the user.`
60
51
  : "",
61
52
  formatLanguagePrompt((_a = input.userLanguage) !== null && _a !== void 0 ? _a : null),
62
53
  ].filter(Boolean).join("\n\n");
63
54
  }
64
- function formatResources(resources) {
65
- return resources
66
- .map((resource) => `- resourceId: ${resource.resourceId}\n label: ${resource.label}`)
67
- .join("\n");
68
- }
69
- function formatSkills(skills, label) {
70
- return skills
71
- .map((skill) => `- ${label}: ${skill.name}\n description: ${skill.description}`)
72
- .join("\n");
73
- }
74
- export function buildAgentSystemPrompt(adminforth_1) {
75
- return __awaiter(this, arguments, void 0, function* (adminforth, hiddenResourceIds = []) {
76
- var _a;
77
- const customComponentsDir = (_a = adminforth.config.customization.customComponentsDir) !== null && _a !== void 0 ? _a : "custom";
78
- const pluginCustomFolderPaths = adminforth.activatedPlugins
79
- .map((plugin) => plugin.customFolderPath);
80
- const skills = yield listProjectSkillManifests(customComponentsDir, pluginCustomFolderPaths);
81
- const adminBasePath = adminforth.config.baseUrlSlashed;
82
- const hiddenResourceIdSet = new Set(hiddenResourceIds);
83
- const visibleResources = adminforth.config.resources.filter((resource) => !hiddenResourceIdSet.has(resource.resourceId));
84
- const sections = [
85
- DEFAULT_AGENT_SYSTEM_PROMPT,
86
- `ADMIN_BASE_PATH: ${adminBasePath}`,
87
- `List of resources:\n${formatResources(visibleResources)}`,
88
- skills.length > 0
89
- ? `You have skills set:\n${formatSkills(skills, "skill_name")}`
90
- : "",
91
- "Before using any skill, call fetch_skill to load its full instructions.",
92
- "The fetched skill response starts with 'Tools mentioned in this skill'. Read that list first.",
93
- "You can use get_resource immediately to inspect resource structure and column names.",
94
- "If the user wants to create, update, delete, or run actions on records, load mutate_data first.",
95
- "If the user wants to fetch records, load fetch_data first. If the user wants analytics or charts, load analyze_data first.",
96
- "Only call fetch_tool_schema for tool names that are explicitly mentioned in a fetched skill and are not already available as base tools.",
97
- "If a fetched skill lists a non-base tool you need, call fetch_tool_schema for it immediately instead of telling the user the tool is unavailable.",
98
- "For example: for record creation load mutate_data, read its tool list, call fetch_tool_schema for create_record, describe the planned record, and then use create_record.",
99
- "When fetch_tool_schema succeeds, that tool becomes available on the next step.",
100
- "All admin links must be root-relative and start with '/'.",
101
- "Build record links as '/resource/{resourceId}/show/{primary key}'. Never use bare 'resource/{resourceId}/show/{primary key}' without the leading slash.",
102
- "When the user asks to open or show a page in the AdminForth UI, call navigate_user instead of only sending a link.",
103
- "Try to call as many tools as possible in parallel in one step.",
104
- ];
105
- return sections.filter(Boolean).join("\n\n");
106
- });
55
+ export function buildAgentSystemPrompt(adminBasePath, chartsGuide) {
56
+ return [
57
+ DEFAULT_AGENT_SYSTEM_PROMPT,
58
+ `ADMIN_BASE_PATH: ${adminBasePath}`,
59
+ "The MCP server rules above are written for every client. In this chat, the runtime approval UI replaces a confirmation in chat, and there is no limit on tool calls per request.",
60
+ "The description of fetch_tool_schema lists every admin panel tool you cannot call yet. Load a tool with fetch_tool_schema before its first call, right away instead of telling the user the tool is unavailable; it becomes available on the next step. A fetched skill lists the tools it uses under '# Tools'.",
61
+ "For example: for record creation load mutate-data, call fetch_tool_schema for create_record, describe the planned record, and then use create_record.",
62
+ "All admin links must be root-relative and start with '/'.",
63
+ "Build record links as '/resource/{resourceId}/show/{primary key}'. Never use bare 'resource/{resourceId}/show/{primary key}' without the leading slash.",
64
+ "When the user asks to open or show a page in the AdminForth UI, call navigate_user instead of only sending a link.",
65
+ "Try to call as many tools as possible in parallel in one step.",
66
+ chartsGuide,
67
+ ].join("\n\n");
107
68
  }
package/dist/index.d.ts CHANGED
@@ -4,7 +4,6 @@ import type { PluginOptions } from './types.js';
4
4
  export type { AgentEvent, AgentEventEmitter } from "./domain/agentEvents.js";
5
5
  export default class AdminForthAgentPlugin extends AdminForthPlugin {
6
6
  options: PluginOptions;
7
- agentSystemPromptPromise: Promise<string>;
8
7
  pluginsScope: "resource" | "global";
9
8
  private agentSystemPrompt;
10
9
  private checkpointer;
@@ -14,8 +13,6 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
14
13
  private speechTurnService;
15
14
  private chatSurfaceService;
16
15
  private getCheckpointer;
17
- private getInternalAgentResourceIds;
18
- private getAgentSystemPrompt;
19
16
  constructor(options: PluginOptions);
20
17
  modifyGlobalConfig(adminforth: IAdminForth): Promise<void>;
21
18
  validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
package/dist/index.js CHANGED
@@ -7,10 +7,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { AdminForthPlugin, logger } from "adminforth";
10
+ import { AdminForthPlugin } from "adminforth";
11
+ import { readFileSync } from "fs";
12
+ import path from "path";
11
13
  import { MemorySaver } from "@langchain/langgraph";
12
14
  import { AdminForthCheckpointSaver } from "./persistence/checkpointStore.js";
13
- import { appendCustomSystemPrompt, buildAgentSystemPrompt, DEFAULT_AGENT_SYSTEM_PROMPT } from "./domain/systemPrompt.js";
15
+ import { appendCustomSystemPrompt, buildAgentSystemPrompt } from "./domain/systemPrompt.js";
14
16
  import { setupCoreEndpoints } from "./transport/http/coreEndpoints.js";
15
17
  import { setupSessionEndpoints } from "./transport/http/sessionEndpoints.js";
16
18
  import { setupChatSurfaceEndpoints } from "./transport/http/chatSurfaceEndpoints.js";
@@ -23,7 +25,10 @@ import { AgentModelFactory } from "./llm/modelFactory.js";
23
25
  import { AgentRuntime } from "./llm/agentRuntime.js";
24
26
  import { SpeechTurnService } from "./transport/surfaces/speechTurnService.js";
25
27
  import { AgentToolProvider } from "./tools/agentToolProvider.js";
28
+ import { MCP_PLUGIN_CLASS_NAME } from "./tools/mcpConnection.js";
26
29
  import { SteerBuffer } from "./domain/steerBuffer.js";
30
+ // Vega-Lite guidance for the chat's chart renderer, appended to the system prompt.
31
+ const CHARTS_GUIDE_FILE = "charts.md";
27
32
  export default class AdminForthAgentPlugin extends AdminForthPlugin {
28
33
  getCheckpointer() {
29
34
  if (this.checkpointer)
@@ -33,41 +38,19 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
33
38
  : new MemorySaver();
34
39
  return this.checkpointer;
35
40
  }
36
- getInternalAgentResourceIds() {
37
- var _a;
38
- return [
39
- this.options.sessionResource.resourceId,
40
- this.options.turnResource.resourceId,
41
- (_a = this.options.checkpointResource) === null || _a === void 0 ? void 0 : _a.resourceId,
42
- ].filter((resourceId) => Boolean(resourceId));
43
- }
44
- getAgentSystemPrompt() {
45
- return __awaiter(this, void 0, void 0, function* () {
46
- if (!this.agentSystemPrompt) {
47
- const systemPrompt = yield buildAgentSystemPrompt(this.adminforth, this.getInternalAgentResourceIds()).catch((err) => {
48
- logger.error(`Failed to build agent system prompt, falling back to default: ${err instanceof Error ? err.message : String(err)}`);
49
- return DEFAULT_AGENT_SYSTEM_PROMPT;
50
- });
51
- this.agentSystemPrompt = appendCustomSystemPrompt(systemPrompt, this.options.systemPrompt);
52
- }
53
- return this.agentSystemPrompt;
54
- });
55
- }
56
41
  constructor(options) {
57
42
  var _a;
58
43
  super(options, import.meta.url);
59
44
  this.pluginsScope = "global";
60
- this.agentSystemPrompt = null;
61
45
  this.checkpointer = null;
62
46
  this.options = options;
63
47
  this.sessionStore = new AgentSessionStore(() => this.adminforth, this.options);
64
48
  this.steerBuffer = new SteerBuffer();
65
- const toolProvider = new AgentToolProvider(() => this.adminforth, this.getInternalAgentResourceIds.bind(this));
66
49
  const runtime = new AgentRuntime({
67
50
  name: `adminforth-agent-${this.pluginInstanceId}`,
68
51
  getAdminforth: () => this.adminforth,
69
52
  getCheckpointer: this.getCheckpointer.bind(this),
70
- toolProvider,
53
+ toolProvider: new AgentToolProvider(() => this.adminforth),
71
54
  steerBuffer: this.steerBuffer,
72
55
  });
73
56
  const llm = new LangGraphLlm(runtime, new AgentModelFactory((_a = this.options.maxTokens) !== null && _a !== void 0 ? _a : 1000));
@@ -77,7 +60,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
77
60
  steerBuffer: this.steerBuffer,
78
61
  modes: this.options.modes,
79
62
  getAdminforth: () => this.adminforth,
80
- getAgentSystemPrompt: this.getAgentSystemPrompt.bind(this),
63
+ getAgentSystemPrompt: () => this.agentSystemPrompt,
81
64
  hasPersistentCheckpointer: Boolean(this.options.checkpointResource),
82
65
  turnCheckpointsEnabled: Boolean(this.options.turnResource.checkpointIdField),
83
66
  sessionResource: this.options.sessionResource,
@@ -85,7 +68,6 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
85
68
  });
86
69
  this.speechTurnService = new SpeechTurnService(this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase));
87
70
  this.chatSurfaceService = new ChatSurfaceService(() => this.adminforth, this.options, this.sessionStore, this.runTurnUseCase.handleTurn.bind(this.runTurnUseCase), this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase));
88
- this.agentSystemPromptPromise = Promise.resolve(appendCustomSystemPrompt(DEFAULT_AGENT_SYSTEM_PROMPT, this.options.systemPrompt));
89
71
  this.shouldHaveSingleInstancePerWholeApp = () => false;
90
72
  }
91
73
  modifyGlobalConfig(adminforth) {
@@ -93,7 +75,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
93
75
  modifyGlobalConfig: { get: () => super.modifyGlobalConfig }
94
76
  });
95
77
  return __awaiter(this, void 0, void 0, function* () {
96
- var _a, _b;
78
+ var _a, _b, _c;
97
79
  _super.modifyGlobalConfig.call(this, adminforth);
98
80
  if (!((_a = this.options.modes) === null || _a === void 0 ? void 0 : _a.length)) {
99
81
  throw new Error("modes is required for AdminForthAgentPlugin");
@@ -115,6 +97,17 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
115
97
  if (!this.options.sessionResource) {
116
98
  throw new Error("sessionResource is required for AdminForthAgentPlugin");
117
99
  }
100
+ // Chat history and checkpoints of the agent are not data for agents to work with.
101
+ const internalResourceIds = [
102
+ this.options.sessionResource.resourceId,
103
+ this.options.turnResource.resourceId,
104
+ (_c = this.options.checkpointResource) === null || _c === void 0 ? void 0 : _c.resourceId,
105
+ ];
106
+ for (const resource of adminforth.config.resources) {
107
+ if (internalResourceIds.includes(resource.resourceId)) {
108
+ resource.options.agent = Object.assign(Object.assign({}, resource.options.agent), { hiddenFromAgents: true });
109
+ }
110
+ }
118
111
  });
119
112
  }
120
113
  validateConfigAfterDiscover(adminforth, resourceConfig) {
@@ -123,12 +116,8 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
123
116
  for (const chatSurfaceAdapter of (_b = this.options.chatSurfaceAdapters) !== null && _b !== void 0 ? _b : []) {
124
117
  chatSurfaceAdapter.validate();
125
118
  }
126
- this.agentSystemPromptPromise = buildAgentSystemPrompt(adminforth, this.getInternalAgentResourceIds())
127
- .then((systemPrompt) => {
128
- const finalPrompt = appendCustomSystemPrompt(systemPrompt, this.options.systemPrompt);
129
- this.agentSystemPrompt = finalPrompt;
130
- return finalPrompt;
131
- });
119
+ adminforth.getPluginByClassName(MCP_PLUGIN_CLASS_NAME);
120
+ this.agentSystemPrompt = appendCustomSystemPrompt(buildAgentSystemPrompt(adminforth.config.baseUrlSlashed, readFileSync(path.join(this.customFolderPath, CHARTS_GUIDE_FILE), "utf8")), this.options.systemPrompt);
132
121
  }
133
122
  instanceUniqueRepresentation(pluginOptions) {
134
123
  return `single`;
@@ -147,7 +136,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
147
136
  }),
148
137
  runAndPersistAgentResponse: this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase),
149
138
  getSessionTurns: this.sessionStore.getSessionTurns.bind(this.sessionStore),
150
- getPendingApprovals: (sessionId) => this.runTurnUseCase.getPendingApprovals(sessionId),
139
+ getPendingApprovals: (sessionId, adminUser) => this.runTurnUseCase.getPendingApprovals(sessionId, adminUser),
151
140
  createNewTurn: this.sessionStore.createNewTurn.bind(this.sessionStore),
152
141
  createSystemTurn: this.sessionStore.createSystemTurn.bind(this.sessionStore),
153
142
  appendSteerToCurrentTurn: this.sessionStore.appendSteerToCurrentTurn.bind(this.sessionStore),
@@ -1,4 +1,4 @@
1
- import type { IAdminForth } from "adminforth";
1
+ import type { AdminUser, IAdminForth } from "adminforth";
2
2
  import type { BaseCheckpointSaver } from "@langchain/langgraph";
3
3
  import type { SteerBuffer } from "../domain/steerBuffer.js";
4
4
  import type { AgentToolProvider } from "../tools/agentToolProvider.js";
@@ -7,31 +7,32 @@ export type AgentRuntimeOptions = {
7
7
  name: string;
8
8
  getAdminforth: () => IAdminForth;
9
9
  getCheckpointer: () => BaseCheckpointSaver;
10
- toolProvider: AgentToolProvider;
11
- /** Per-session buffer of mid-turn steering instructions drained by the steer middleware. */
10
+ toolProvider: Pick<AgentToolProvider, "open">;
12
11
  steerBuffer: SteerBuffer;
13
12
  };
14
13
  export declare class AgentRuntime {
15
14
  private readonly options;
16
15
  constructor(options: AgentRuntimeOptions);
17
- stream(input: AgentRuntimeRunInput): Promise<import("@langchain/core/utils/stream").IterableReadableStream<["messages", [import("langchain").BaseMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>, import("@langchain/core/messages").MessageType>, Record<string, any>]] | ["updates", Record<string, Omit<import("langchain").BuiltInState<import("@langchain/core/messages").MessageStructure<import("langchain").ToolsToMessageToolSet<readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[]>>>, "jumpTo">>]>>;
16
+ stream(input: AgentRuntimeRunInput): Promise<AsyncGenerator<["messages", [import("langchain").BaseMessage<import("@langchain/core/messages").MessageStructure<import("@langchain/core/messages").MessageToolSet>, import("@langchain/core/messages").MessageType>, Record<string, any>]] | ["updates", Record<string, Omit<import("langchain").BuiltInState<import("@langchain/core/messages").MessageStructure<import("langchain").ToolsToMessageToolSet<readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[]>>>, "jumpTo">>], void, any>>;
17
+ private getThreadState;
18
18
  /**
19
19
  * Read the pending human-in-the-loop interrupts persisted for a thread from the
20
- * checkpointer. Builds a minimal agent (model + checkpointer + HITL middleware) and
21
- * queries its state — no model call is made. Returns raw LangGraph interrupt objects.
20
+ * checkpointer. Returns raw LangGraph interrupt objects.
22
21
  */
23
22
  getPendingInterrupts(input: {
24
23
  models: AgentTurnModels;
25
24
  sessionId: string;
25
+ adminUser: AdminUser;
26
26
  }): Promise<unknown[]>;
27
27
  /**
28
28
  * Return the thread's latest (tip) checkpoint id, or null when the thread has no
29
- * persisted state. Builds a minimal agent and reads its state — no model call is
30
- * made. Called after a turn completes to record the turn's fork point for editing.
29
+ * persisted state. Called after a turn completes to record the turn's fork point
30
+ * for editing.
31
31
  */
32
32
  getLatestCheckpointId(input: {
33
33
  models: AgentTurnModels;
34
34
  sessionId: string;
35
+ adminUser: AdminUser;
35
36
  }): Promise<string | null>;
36
37
  /**
37
38
  * Drop the entire LangGraph checkpoint thread for a session. Used when editing the
@@ -7,23 +7,60 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
11
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
12
+ var m = o[Symbol.asyncIterator], i;
13
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
14
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
15
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
16
+ };
17
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
18
+ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
19
+ var i, p;
20
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
21
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
22
+ };
23
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
24
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
25
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
26
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
27
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
28
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
29
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
30
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
31
+ function fulfill(value) { resume("next", value); }
32
+ function reject(value) { resume("throw", value); }
33
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
34
+ };
10
35
  import { createAgent, summarizationMiddleware, humanInTheLoopMiddleware, dynamicSystemPromptMiddleware, } from "langchain";
11
- import { createApiBasedToolsMiddleware } from "./middleware/apiToolsMiddleware.js";
36
+ import { createMcpToolsMiddleware } from "./middleware/mcpToolsMiddleware.js";
12
37
  import { createSequenceDebugMiddleware } from "./middleware/sequenceDebug.js";
13
38
  import { createSteerMiddleware } from "./middleware/steerMiddleware.js";
14
39
  import { createAgentLlmMetricsLogger } from "./agentModels.js";
15
40
  import { contextSchema, toLangchainAgentContext } from "./agentContext.js";
16
41
  import { createLegacySystemMessagesMiddleware } from "./middleware/legacySystemMessages.js";
17
42
  import { buildDynamicSystemPrompt } from "../domain/systemPrompt.js";
18
- function createHumanInTheLoopInterrupts(apiBasedTools) {
19
- return Object.fromEntries(Object.entries(apiBasedTools)
20
- .filter(([, { agent }]) => (agent === null || agent === void 0 ? void 0 : agent.requiresHumanApproval) || (agent === null || agent === void 0 ? void 0 : agent.isDangerous))
21
- .map(([toolName]) => [
22
- toolName,
23
- {
24
- allowedDecisions: ["approve", "reject"],
25
- },
26
- ]));
43
+ function createApprovalMiddleware(toolSet) {
44
+ return humanInTheLoopMiddleware({
45
+ interruptOn: Object.fromEntries(toolSet.approvalToolNames.map((toolName) => [
46
+ toolName,
47
+ {
48
+ allowedDecisions: ["approve", "reject"],
49
+ },
50
+ ])),
51
+ descriptionPrefix: "Tool execution pending approval",
52
+ });
53
+ }
54
+ /** Keeps the turn's MCP connection open until its stream is drained or abandoned. */
55
+ function closeAfter(stream, close) {
56
+ return __asyncGenerator(this, arguments, function* closeAfter_1() {
57
+ try {
58
+ yield __await(yield* __asyncDelegator(__asyncValues(stream)));
59
+ }
60
+ finally {
61
+ yield __await(close());
62
+ }
63
+ });
27
64
  }
28
65
  export class AgentRuntime {
29
66
  constructor(options) {
@@ -32,121 +69,112 @@ export class AgentRuntime {
32
69
  stream(input) {
33
70
  return __awaiter(this, void 0, void 0, function* () {
34
71
  var _a;
35
- const apiBasedTools = this.options.toolProvider.getApiBasedTools();
36
- const tools = yield this.options.toolProvider.getTools(apiBasedTools);
37
- const adminforth = this.options.getAdminforth();
38
- const apiBasedToolsMiddleware = createApiBasedToolsMiddleware(apiBasedTools, adminforth);
39
- // The domain exposes only the narrow DebugSink; the concrete collector (with the
40
- // model-call hooks the debug middleware needs) is an llm-layer detail.
41
- const sequenceDebugSink = input.observability.sequenceDebugSink;
42
- const sequenceDebugMiddleware = createSequenceDebugMiddleware(sequenceDebugSink);
43
- const hitlMiddleware = humanInTheLoopMiddleware({
44
- interruptOn: createHumanInTheLoopInterrupts(apiBasedTools),
45
- descriptionPrefix: "Tool execution pending approval",
46
- });
47
- const steerMiddleware = createSteerMiddleware(this.options.steerBuffer);
48
- const legacySystemMessagesMiddleware = createLegacySystemMessagesMiddleware();
49
- const usernameField = adminforth.config.auth.usernameField;
50
- const dynamicPromptMiddleware = dynamicSystemPromptMiddleware((_state, runtime) => buildDynamicSystemPrompt({
51
- adminUser: runtime.context.adminUser,
52
- usernameField,
53
- userLanguage: runtime.context.userLanguage,
54
- chatSurface: runtime.context.chatSurface,
55
- }));
56
- const middleware = [
57
- steerMiddleware,
58
- apiBasedToolsMiddleware,
59
- hitlMiddleware,
60
- legacySystemMessagesMiddleware,
61
- dynamicPromptMiddleware,
62
- ...((_a = input.models.modelMiddleware) !== null && _a !== void 0 ? _a : []),
63
- sequenceDebugMiddleware,
64
- summarizationMiddleware({
65
- model: input.models.summaryModel,
66
- trigger: { tokens: 1024 * 64 },
67
- keep: { messages: 10 },
68
- }),
69
- ];
70
- const agent = createAgent({
71
- name: this.options.name,
72
- model: input.models.model,
73
- // Passed as a plain string on purpose: LangChain normalizes it to a single text
74
- // block, and DynamicSystemPromptMiddleware appends the per-turn half as a second
75
- // one. That block split is all the agent owes the provider — whether the boundary
76
- // becomes a cache breakpoint is the adapter's call.
77
- systemPrompt: input.systemPrompt,
78
- checkpointer: this.options.getCheckpointer(),
79
- tools,
80
- contextSchema,
81
- middleware,
72
+ const toolSet = yield this.options.toolProvider.open({
73
+ adminUser: input.context.adminUser,
74
+ sessionId: input.context.sessionId,
75
+ userTimeZone: input.context.userTimeZone,
82
76
  });
83
- return agent.stream(input.input, {
84
- streamMode: ["messages", "updates"],
85
- recursionLimit: 100,
86
- callbacks: [createAgentLlmMetricsLogger()],
87
- signal: input.context.abortSignal,
88
- configurable: Object.assign({ thread_id: input.context.sessionId }, (input.branchFromCheckpointId
89
- ? { checkpoint_id: input.branchFromCheckpointId }
90
- : {})),
91
- context: toLangchainAgentContext(Object.assign(Object.assign({}, input.context), { adminBaseUrl: adminforth.config.baseUrlSlashed, emit: input.observability.emit, sequenceDebugSink })),
77
+ try {
78
+ const adminforth = this.options.getAdminforth();
79
+ const sequenceDebugSink = input.observability.sequenceDebugSink;
80
+ const usernameField = adminforth.config.auth.usernameField;
81
+ const dynamicPromptMiddleware = dynamicSystemPromptMiddleware((_state, runtime) => buildDynamicSystemPrompt({
82
+ adminUser: runtime.context.adminUser,
83
+ usernameField,
84
+ userTimeZone: runtime.context.userTimeZone,
85
+ userLanguage: runtime.context.userLanguage,
86
+ chatSurface: runtime.context.chatSurface,
87
+ }));
88
+ const middleware = [
89
+ createSteerMiddleware(this.options.steerBuffer),
90
+ createMcpToolsMiddleware(toolSet.dynamicTools, adminforth),
91
+ createApprovalMiddleware(toolSet),
92
+ createLegacySystemMessagesMiddleware(),
93
+ dynamicPromptMiddleware,
94
+ ...((_a = input.models.modelMiddleware) !== null && _a !== void 0 ? _a : []),
95
+ createSequenceDebugMiddleware(sequenceDebugSink),
96
+ summarizationMiddleware({
97
+ model: input.models.summaryModel,
98
+ trigger: { tokens: 1024 * 64 },
99
+ keep: { messages: 10 },
100
+ }),
101
+ ];
102
+ const agent = createAgent({
103
+ name: this.options.name,
104
+ model: input.models.model,
105
+ // Passed as a plain string on purpose: LangChain normalizes it to a single text
106
+ // block, and DynamicSystemPromptMiddleware appends the per-turn half as a second
107
+ // one. That block split is all the agent owes the provider — whether the boundary
108
+ // becomes a cache breakpoint is the adapter's call. The MCP server instructions
109
+ // come first: the agent's own rules refine them for this chat.
110
+ systemPrompt: `${toolSet.instructions}\n\n${input.systemPrompt}`,
111
+ checkpointer: this.options.getCheckpointer(),
112
+ tools: toolSet.baseTools,
113
+ contextSchema,
114
+ middleware,
115
+ });
116
+ const stream = yield agent.stream(input.input, {
117
+ streamMode: ["messages", "updates"],
118
+ recursionLimit: 100,
119
+ callbacks: [createAgentLlmMetricsLogger()],
120
+ signal: input.context.abortSignal,
121
+ configurable: Object.assign({ thread_id: input.context.sessionId }, (input.branchFromCheckpointId
122
+ ? { checkpoint_id: input.branchFromCheckpointId }
123
+ : {})),
124
+ context: toLangchainAgentContext(Object.assign(Object.assign({}, input.context), { adminBaseUrl: adminforth.config.baseUrlSlashed, emit: input.observability.emit, sequenceDebugSink })),
125
+ });
126
+ return closeAfter(stream, toolSet.close);
127
+ }
128
+ catch (error) {
129
+ yield toolSet.close();
130
+ throw error;
131
+ }
132
+ });
133
+ }
134
+ getThreadState(input) {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ const toolSet = yield this.options.toolProvider.open({
137
+ adminUser: input.adminUser,
138
+ sessionId: input.sessionId,
92
139
  });
140
+ try {
141
+ const agent = createAgent({
142
+ name: this.options.name,
143
+ model: input.models.model,
144
+ checkpointer: this.options.getCheckpointer(),
145
+ tools: toolSet.baseTools,
146
+ contextSchema,
147
+ middleware: [createApprovalMiddleware(toolSet)],
148
+ });
149
+ return yield agent.getState({
150
+ configurable: { thread_id: input.sessionId },
151
+ });
152
+ }
153
+ finally {
154
+ yield toolSet.close();
155
+ }
93
156
  });
94
157
  }
95
158
  /**
96
159
  * Read the pending human-in-the-loop interrupts persisted for a thread from the
97
- * checkpointer. Builds a minimal agent (model + checkpointer + HITL middleware) and
98
- * queries its state — no model call is made. Returns raw LangGraph interrupt objects.
160
+ * checkpointer. Returns raw LangGraph interrupt objects.
99
161
  */
100
162
  getPendingInterrupts(input) {
101
163
  return __awaiter(this, void 0, void 0, function* () {
102
- const apiBasedTools = this.options.toolProvider.getApiBasedTools();
103
- const tools = yield this.options.toolProvider.getTools(apiBasedTools);
104
- const agent = createAgent({
105
- name: this.options.name,
106
- model: input.models.model,
107
- checkpointer: this.options.getCheckpointer(),
108
- tools,
109
- contextSchema,
110
- middleware: [
111
- humanInTheLoopMiddleware({
112
- interruptOn: createHumanInTheLoopInterrupts(apiBasedTools),
113
- descriptionPrefix: "Tool execution pending approval",
114
- }),
115
- ],
116
- });
117
- const state = yield agent.getState({
118
- configurable: { thread_id: input.sessionId },
119
- });
164
+ const state = yield this.getThreadState(input);
120
165
  const tasks = Array.isArray(state === null || state === void 0 ? void 0 : state.tasks) ? state.tasks : [];
121
166
  return tasks.flatMap((task) => (Array.isArray(task === null || task === void 0 ? void 0 : task.interrupts) ? task.interrupts : []));
122
167
  });
123
168
  }
124
169
  /**
125
170
  * Return the thread's latest (tip) checkpoint id, or null when the thread has no
126
- * persisted state. Builds a minimal agent and reads its state — no model call is
127
- * made. Called after a turn completes to record the turn's fork point for editing.
171
+ * persisted state. Called after a turn completes to record the turn's fork point
172
+ * for editing.
128
173
  */
129
174
  getLatestCheckpointId(input) {
130
175
  return __awaiter(this, void 0, void 0, function* () {
131
176
  var _a, _b;
132
- const apiBasedTools = this.options.toolProvider.getApiBasedTools();
133
- const tools = yield this.options.toolProvider.getTools(apiBasedTools);
134
- const agent = createAgent({
135
- name: this.options.name,
136
- model: input.models.model,
137
- checkpointer: this.options.getCheckpointer(),
138
- tools,
139
- contextSchema,
140
- middleware: [
141
- humanInTheLoopMiddleware({
142
- interruptOn: createHumanInTheLoopInterrupts(apiBasedTools),
143
- descriptionPrefix: "Tool execution pending approval",
144
- }),
145
- ],
146
- });
147
- const state = yield agent.getState({
148
- configurable: { thread_id: input.sessionId },
149
- });
177
+ const state = yield this.getThreadState(input);
150
178
  const checkpointId = (_b = (_a = state === null || state === void 0 ? void 0 : state.config) === null || _a === void 0 ? void 0 : _a.configurable) === null || _b === void 0 ? void 0 : _b.checkpoint_id;
151
179
  return checkpointId ? String(checkpointId) : null;
152
180
  });
@@ -1,3 +1,4 @@
1
+ import type { AdminUser } from "adminforth";
1
2
  import type { AgentRuntime } from "./agentRuntime.js";
2
3
  import type { AgentModelFactory } from "./modelFactory.js";
3
4
  import { type PreviousUserMessage } from "../domain/languageDetect.js";
@@ -21,10 +22,12 @@ export declare class LangGraphLlm implements LlmPort {
21
22
  getPendingInterrupts(input: {
22
23
  completionAdapter: AgentModeCompletionAdapter;
23
24
  sessionId: string;
25
+ adminUser: AdminUser;
24
26
  }): Promise<PendingInterrupt[]>;
25
27
  getLatestCheckpointId(input: {
26
28
  completionAdapter: AgentModeCompletionAdapter;
27
29
  sessionId: string;
30
+ adminUser: AdminUser;
28
31
  }): Promise<string | null>;
29
32
  resetThreadCheckpoints(input: {
30
33
  completionAdapter: AgentModeCompletionAdapter;
@@ -47,14 +47,22 @@ export class LangGraphLlm {
47
47
  getPendingInterrupts(input) {
48
48
  return __awaiter(this, void 0, void 0, function* () {
49
49
  const models = yield this.modelFactory.create(input.completionAdapter);
50
- const raw = yield this.runtime.getPendingInterrupts({ models, sessionId: input.sessionId });
50
+ const raw = yield this.runtime.getPendingInterrupts({
51
+ models,
52
+ sessionId: input.sessionId,
53
+ adminUser: input.adminUser,
54
+ });
51
55
  return normalizeInterrupts(raw);
52
56
  });
53
57
  }
54
58
  getLatestCheckpointId(input) {
55
59
  return __awaiter(this, void 0, void 0, function* () {
56
60
  const models = yield this.modelFactory.create(input.completionAdapter);
57
- return this.runtime.getLatestCheckpointId({ models, sessionId: input.sessionId });
61
+ return this.runtime.getLatestCheckpointId({
62
+ models,
63
+ sessionId: input.sessionId,
64
+ adminUser: input.adminUser,
65
+ });
58
66
  });
59
67
  }
60
68
  resetThreadCheckpoints(input) {
@@ -0,0 +1,7 @@
1
+ import type { ClientTool } from "@langchain/core/tools";
2
+ import { type IAdminForth } from "adminforth";
3
+ /**
4
+ * Adds the MCP tools loaded with fetch_tool_schema to the next model calls, routes their calls,
5
+ * and reports every tool call to the processing timeline.
6
+ */
7
+ export declare function createMcpToolsMiddleware(dynamicTools: Record<string, ClientTool>, adminforth: IAdminForth): import("langchain").AgentMiddleware<undefined, undefined, unknown, readonly (ClientTool | import("@langchain/core/tools").ServerTool)[]>;