@adminforth/agent 3.1.9 → 3.2.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.
- package/README.md +71 -38
- package/dist/application/ports.d.ts +3 -1
- package/dist/application/runTurnUseCase.d.ts +3 -3
- package/dist/application/runTurnUseCase.js +8 -6
- package/dist/custom/ChatHeader.vue +1 -1
- package/dist/custom/{skills/charts/SKILL.md → charts.md} +2 -4
- package/dist/domain/systemPrompt.d.ts +3 -2
- package/dist/domain/systemPrompt.js +14 -53
- package/dist/index.d.ts +0 -3
- package/dist/index.js +24 -35
- package/dist/llm/agentRuntime.d.ts +9 -8
- package/dist/llm/agentRuntime.js +134 -106
- package/dist/llm/langGraphLlm.d.ts +3 -0
- package/dist/llm/langGraphLlm.js +10 -2
- package/dist/llm/middleware/mcpToolsMiddleware.d.ts +7 -0
- package/dist/llm/middleware/{apiToolsMiddleware.js → mcpToolsMiddleware.js} +16 -36
- package/dist/tools/agentToolProvider.d.ts +16 -5
- package/dist/tools/agentToolProvider.js +26 -10
- package/dist/tools/fetchToolSchema.d.ts +7 -3
- package/dist/tools/fetchToolSchema.js +29 -22
- package/dist/tools/mcpConnection.d.ts +38 -0
- package/dist/tools/mcpConnection.js +42 -0
- package/dist/tools/mcpTool.d.ts +3 -0
- package/dist/tools/{apiTool.js → mcpTool.js} +7 -23
- package/dist/tools/toolLabels.d.ts +5 -0
- package/dist/tools/toolLabels.js +49 -0
- package/dist/transport/http/context.d.ts +2 -2
- package/dist/transport/http/sessionEndpoints.js +1 -1
- package/package.json +6 -4
- package/dist/custom/skills/analyze_data/SKILL.md +0 -25
- package/dist/custom/skills/fetch_data/SKILL.md +0 -31
- package/dist/custom/skills/mutate_data/SKILL.md +0 -121
- package/dist/llm/middleware/apiToolsMiddleware.d.ts +0 -3
- package/dist/tools/apiBasedTools.d.ts +0 -30
- package/dist/tools/apiBasedTools.js +0 -488
- package/dist/tools/apiTool.d.ts +0 -6
- package/dist/tools/fetchSkill.d.ts +0 -8
- package/dist/tools/fetchSkill.js +0 -51
- package/dist/tools/index.d.ts +0 -4
- package/dist/tools/index.js +0 -32
- package/dist/tools/skills/registry.d.ts +0 -11
- package/dist/tools/skills/registry.js +0 -107
|
@@ -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<
|
|
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.
|
|
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.
|
|
30
|
-
*
|
|
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
|
package/dist/llm/agentRuntime.js
CHANGED
|
@@ -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 {
|
|
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
|
|
19
|
-
return
|
|
20
|
-
.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
:
|
|
91
|
-
|
|
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.
|
|
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
|
|
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.
|
|
127
|
-
*
|
|
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
|
|
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;
|
package/dist/llm/langGraphLlm.js
CHANGED
|
@@ -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({
|
|
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({
|
|
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)[]>;
|
|
@@ -11,12 +11,10 @@ import { ToolMessage } from "@langchain/core/messages";
|
|
|
11
11
|
import { isGraphInterrupt } from "@langchain/langgraph";
|
|
12
12
|
import { createMiddleware } from "langchain";
|
|
13
13
|
import { logger } from "adminforth";
|
|
14
|
-
import {
|
|
14
|
+
import { formatToolCall } from "../../tools/toolLabels.js";
|
|
15
15
|
import { createToolCallTracker, } from "../../domain/toolCallEvents.js";
|
|
16
|
-
import { ALWAYS_AVAILABLE_API_TOOL_NAMES } from "../../tools/index.js";
|
|
17
|
-
import { createApiTool } from "../../tools/apiTool.js";
|
|
18
16
|
import { isAbortError } from "../../shared/errors.js";
|
|
19
|
-
function
|
|
17
|
+
function getEnabledToolNames(messages) {
|
|
20
18
|
const enabledToolNames = new Set();
|
|
21
19
|
for (const message of messages) {
|
|
22
20
|
if (!ToolMessage.isInstance(message) || message.name !== "fetch_tool_schema") {
|
|
@@ -43,22 +41,20 @@ function getEnabledApiToolNames(messages) {
|
|
|
43
41
|
}
|
|
44
42
|
return enabledToolNames;
|
|
45
43
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
]));
|
|
44
|
+
/**
|
|
45
|
+
* Adds the MCP tools loaded with fetch_tool_schema to the next model calls, routes their calls,
|
|
46
|
+
* and reports every tool call to the processing timeline.
|
|
47
|
+
*/
|
|
48
|
+
export function createMcpToolsMiddleware(dynamicTools, adminforth) {
|
|
49
|
+
const loadedDynamicToolNames = (messages) => [...getEnabledToolNames(messages)].filter((toolName) => toolName in dynamicTools);
|
|
52
50
|
return createMiddleware({
|
|
53
|
-
name: "
|
|
51
|
+
name: "McpToolsMiddleware",
|
|
54
52
|
wrapModelCall(request, handler) {
|
|
55
53
|
return __awaiter(this, void 0, void 0, function* () {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const availableTools = [...request.tools, ...tools];
|
|
61
|
-
return handler(Object.assign(Object.assign({}, request), { tools: availableTools }));
|
|
54
|
+
return handler(Object.assign(Object.assign({}, request), { tools: [
|
|
55
|
+
...request.tools,
|
|
56
|
+
...loadedDynamicToolNames(request.state.messages).map((toolName) => dynamicTools[toolName]),
|
|
57
|
+
] }));
|
|
62
58
|
});
|
|
63
59
|
},
|
|
64
60
|
wrapToolCall(request, handler) {
|
|
@@ -69,7 +65,7 @@ export function createApiBasedToolsMiddleware(apiBasedTools, adminforth) {
|
|
|
69
65
|
throw new Error(`Tool call "${request.toolCall.name}" has no id.`);
|
|
70
66
|
}
|
|
71
67
|
const toolCallId = request.toolCall.id;
|
|
72
|
-
const {
|
|
68
|
+
const { abortSignal, emit, sequenceDebugSink } = request.runtime.context;
|
|
73
69
|
const emitToolCall = (event) => {
|
|
74
70
|
sequenceDebugSink.handleToolCallEvent(event);
|
|
75
71
|
void (emit === null || emit === void 0 ? void 0 : emit({
|
|
@@ -78,33 +74,17 @@ export function createApiBasedToolsMiddleware(apiBasedTools, adminforth) {
|
|
|
78
74
|
}));
|
|
79
75
|
};
|
|
80
76
|
const toolArgs = ((_a = request.toolCall.args) !== null && _a !== void 0 ? _a : {});
|
|
81
|
-
let toolInfo;
|
|
82
|
-
if (request.toolCall.name === "fetch_skill") {
|
|
83
|
-
toolInfo = `Load ${toolArgs.skillName.split("_").join(" ")} skill`;
|
|
84
|
-
}
|
|
85
|
-
else if (request.toolCall.name === "fetch_tool_schema") {
|
|
86
|
-
toolInfo = `Load ${toolArgs.toolName.split("_").join(" ")} tool `;
|
|
87
|
-
}
|
|
88
|
-
else {
|
|
89
|
-
toolInfo = yield formatApiBasedToolCall({
|
|
90
|
-
adminforth,
|
|
91
|
-
adminUser,
|
|
92
|
-
inputs: toolArgs,
|
|
93
|
-
toolName: request.toolCall.name,
|
|
94
|
-
userTimeZone,
|
|
95
|
-
});
|
|
96
|
-
}
|
|
97
77
|
const toolCallTracker = createToolCallTracker({
|
|
98
78
|
emit: emitToolCall,
|
|
99
79
|
toolCallId,
|
|
100
80
|
toolName: request.toolCall.name,
|
|
101
|
-
toolInfo,
|
|
81
|
+
toolInfo: formatToolCall(adminforth, request.toolCall.name, toolArgs),
|
|
102
82
|
input: toolArgs,
|
|
103
83
|
startedAt,
|
|
104
84
|
});
|
|
105
85
|
toolCallTracker.start();
|
|
106
86
|
try {
|
|
107
|
-
const result =
|
|
87
|
+
const result = loadedDynamicToolNames(request.state.messages).includes(request.toolCall.name)
|
|
108
88
|
? yield handler(Object.assign(Object.assign({}, request), { tool: dynamicTools[request.toolCall.name] }))
|
|
109
89
|
: yield handler(request);
|
|
110
90
|
toolCallTracker.finishSuccess(result);
|
|
@@ -1,9 +1,20 @@
|
|
|
1
1
|
import type { IAdminForth } from "adminforth";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ClientTool } from "@langchain/core/tools";
|
|
3
|
+
import { type McpConnectionInput } from "./mcpConnection.js";
|
|
4
|
+
/** The tools of one agent turn, backed by one MCP connection that `close` ends. */
|
|
5
|
+
export type AgentToolSet = {
|
|
6
|
+
/** MCP server instructions, sent ahead of the agent's own system prompt. */
|
|
7
|
+
instructions: string;
|
|
8
|
+
/** Tools the model can call from the first step. */
|
|
9
|
+
baseTools: ClientTool[];
|
|
10
|
+
/** MCP tools the model loads on demand with fetch_tool_schema, by name. */
|
|
11
|
+
dynamicTools: Record<string, ClientTool>;
|
|
12
|
+
/** Tools that pause for the user's approval before they run. */
|
|
13
|
+
approvalToolNames: string[];
|
|
14
|
+
close(): Promise<void>;
|
|
15
|
+
};
|
|
3
16
|
export declare class AgentToolProvider {
|
|
4
17
|
private readonly getAdminforth;
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
getApiBasedTools(): Record<string, ApiBasedTool>;
|
|
8
|
-
getTools(apiBasedTools: Record<string, ApiBasedTool>): Promise<import("@langchain/core/tools").ClientTool[]>;
|
|
18
|
+
constructor(getAdminforth: () => IAdminForth);
|
|
19
|
+
open(input: Omit<McpConnectionInput, "requestUrl">): Promise<AgentToolSet>;
|
|
9
20
|
}
|
|
@@ -7,21 +7,37 @@ 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 {
|
|
11
|
-
import {
|
|
10
|
+
import { connectMcp, MCP_PLUGIN_CLASS_NAME } from "./mcpConnection.js";
|
|
11
|
+
import { createMcpTool } from "./mcpTool.js";
|
|
12
|
+
import { createFetchToolSchemaTool } from "./fetchToolSchema.js";
|
|
13
|
+
import { createGetUserLocationTool } from "./getUserLocation.js";
|
|
14
|
+
import { createNavigateUserTool } from "./navigateUser.js";
|
|
15
|
+
// MCP tools the model can call from the first step; it loads the others with fetch_tool_schema.
|
|
16
|
+
const BASE_MCP_TOOL_NAMES = new Set(["fetch_skill", "get_resources_list", "get_resource", "wait_for_confirmation"]);
|
|
12
17
|
export class AgentToolProvider {
|
|
13
|
-
constructor(getAdminforth
|
|
18
|
+
constructor(getAdminforth) {
|
|
14
19
|
this.getAdminforth = getAdminforth;
|
|
15
|
-
this.getInternalAgentResourceIds = getInternalAgentResourceIds;
|
|
16
20
|
}
|
|
17
|
-
|
|
18
|
-
return prepareApiBasedTools(this.getAdminforth(), this.getInternalAgentResourceIds());
|
|
19
|
-
}
|
|
20
|
-
getTools(apiBasedTools) {
|
|
21
|
+
open(input) {
|
|
21
22
|
return __awaiter(this, void 0, void 0, function* () {
|
|
22
|
-
var _a;
|
|
23
23
|
const adminforth = this.getAdminforth();
|
|
24
|
-
|
|
24
|
+
const connection = yield connectMcp(adminforth.getPluginByClassName(MCP_PLUGIN_CLASS_NAME), Object.assign(Object.assign({}, input), { requestUrl: adminforth.config.baseUrlSlashed }));
|
|
25
|
+
const baseMcpTools = connection.tools.filter((mcpTool) => BASE_MCP_TOOL_NAMES.has(mcpTool.name));
|
|
26
|
+
const dynamicMcpTools = connection.tools.filter((mcpTool) => !BASE_MCP_TOOL_NAMES.has(mcpTool.name));
|
|
27
|
+
return {
|
|
28
|
+
instructions: connection.instructions,
|
|
29
|
+
baseTools: [
|
|
30
|
+
...baseMcpTools.map((mcpTool) => createMcpTool(mcpTool, connection)),
|
|
31
|
+
createGetUserLocationTool(),
|
|
32
|
+
createNavigateUserTool(),
|
|
33
|
+
createFetchToolSchemaTool(connection.tools, dynamicMcpTools),
|
|
34
|
+
],
|
|
35
|
+
dynamicTools: Object.fromEntries(dynamicMcpTools.map((mcpTool) => [mcpTool.name, createMcpTool(mcpTool, connection)])),
|
|
36
|
+
approvalToolNames: connection.tools
|
|
37
|
+
.filter((mcpTool) => { var _a; return (_a = mcpTool.annotations) === null || _a === void 0 ? void 0 : _a.destructiveHint; })
|
|
38
|
+
.map((mcpTool) => mcpTool.name),
|
|
39
|
+
close: connection.close,
|
|
40
|
+
};
|
|
25
41
|
});
|
|
26
42
|
}
|
|
27
43
|
}
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
+
import type { Tool } from "@modelcontextprotocol/client";
|
|
1
2
|
import { z } from "zod";
|
|
2
|
-
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* Loads an MCP tool for later steps: the tools middleware adds every tool this returned status 200 for.
|
|
5
|
+
* Like MCP clients that load tool schemas on demand, its description names every tool it can load.
|
|
6
|
+
*/
|
|
7
|
+
export declare function createFetchToolSchemaTool(mcpTools: Tool[], loadableTools: Tool[]): import("langchain").DynamicStructuredTool<z.ZodObject<{
|
|
4
8
|
toolName: z.ZodString;
|
|
5
9
|
}, z.core.$strip>, {
|
|
6
10
|
toolName: string;
|
|
7
11
|
}, {
|
|
8
12
|
toolName: string;
|
|
9
|
-
}, string, unknown, "fetch_tool_schema"
|
|
13
|
+
}, string, unknown, "fetch_tool_schema">;
|
|
@@ -9,31 +9,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
};
|
|
10
10
|
import { tool } from "langchain";
|
|
11
11
|
import { z } from "zod";
|
|
12
|
+
// The catalog shows the first sentence of each tool description; the full one comes with the loaded tool.
|
|
13
|
+
const FIRST_SENTENCE_RE = /^[\s\S]*?[.!?](?=\s|$)/;
|
|
14
|
+
const WHITESPACE_RE = /\s+/g;
|
|
12
15
|
const fetchToolSchemaSchema = z.object({
|
|
13
16
|
toolName: z
|
|
14
17
|
.string()
|
|
15
|
-
.describe("Name of the
|
|
18
|
+
.describe("Name of the admin panel tool to load, for example create_record."),
|
|
16
19
|
});
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
20
|
+
function catalogEntry({ name, description }) {
|
|
21
|
+
var _a, _b;
|
|
22
|
+
if (!description)
|
|
23
|
+
return `- ${name}`;
|
|
24
|
+
const summary = ((_b = (_a = description.match(FIRST_SENTENCE_RE)) === null || _a === void 0 ? void 0 : _a[0]) !== null && _b !== void 0 ? _b : description).replace(WHITESPACE_RE, " ");
|
|
25
|
+
return `- ${name}: ${summary}`;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Loads an MCP tool for later steps: the tools middleware adds every tool this returned status 200 for.
|
|
29
|
+
* Like MCP clients that load tool schemas on demand, its description names every tool it can load.
|
|
30
|
+
*/
|
|
31
|
+
export function createFetchToolSchemaTool(mcpTools, loadableTools) {
|
|
32
|
+
const mcpToolNames = new Set(mcpTools.map((mcpTool) => mcpTool.name));
|
|
33
|
+
return tool((_a) => __awaiter(this, [_a], void 0, function* ({ toolName }) {
|
|
34
|
+
return JSON.stringify(mcpToolNames.has(toolName)
|
|
35
|
+
? { status: 200, name: toolName, loaded: true }
|
|
36
|
+
: { status: 404, error: "TOOL_NOT_FOUND", message: `Tool "${toolName}" not found.` }, null, 2);
|
|
37
|
+
}), {
|
|
38
|
+
name: "fetch_tool_schema",
|
|
39
|
+
description: [
|
|
40
|
+
"Loads an admin panel tool so you can call it from the next step. Load a tool before its first call, right after fetch_skill when the skill lists tools you cannot call yet.",
|
|
41
|
+
"Tools you can load:",
|
|
42
|
+
...loadableTools.map(catalogEntry),
|
|
43
|
+
].join("\n"),
|
|
44
|
+
schema: fetchToolSchemaSchema,
|
|
38
45
|
});
|
|
39
46
|
}
|