@adminforth/agent 1.27.6 → 1.29.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.
@@ -0,0 +1,79 @@
1
+ import { logger } from "adminforth";
2
+ import type { PluginOptions } from "../types.js";
3
+
4
+ export type UserLanguage = {
5
+ language: string;
6
+ code: string;
7
+ };
8
+
9
+ const USER_LANGUAGE_OUTPUT_SCHEMA = {
10
+ name: "user_language",
11
+ strict: true,
12
+ schema: {
13
+ type: "object",
14
+ additionalProperties: false,
15
+ properties: {
16
+ language: {
17
+ type: "string",
18
+ description: "Full English language name, for example English, Ukrainian, French.",
19
+ },
20
+ code: {
21
+ type: "string",
22
+ description: "Uppercase two-letter language code, for example EN, UA, FR.",
23
+ },
24
+ },
25
+ required: ["language", "code"],
26
+ },
27
+ } as const;
28
+
29
+ export function formatLanguagePrompt(language: UserLanguage | null) {
30
+ if (!language) {
31
+ return "Respond in the user's language.";
32
+ }
33
+
34
+ return `Respond in ${language.language} (${language.code}).`;
35
+ }
36
+
37
+ function parseUserLanguage(content: string | undefined): UserLanguage | null {
38
+ if (!content) {
39
+ return null;
40
+ }
41
+
42
+ try {
43
+ const parsed = JSON.parse(content) as UserLanguage;
44
+ return {
45
+ language: parsed.language,
46
+ code: parsed.code,
47
+ };
48
+ } catch (error) {
49
+ logger.warn(`Failed to parse detected user language: ${error instanceof Error ? error.message : String(error)}`);
50
+ return null;
51
+ }
52
+ }
53
+
54
+ export async function detectUserLanguage(
55
+ completionAdapter: PluginOptions["modes"][number]["completionAdapter"],
56
+ prompt: string,
57
+ ): Promise<UserLanguage | null> {
58
+ const response = await completionAdapter.complete({
59
+ content: [
60
+ "Detect the language of the user's message.",
61
+ "Return only the requested structured output.",
62
+ "The language must be the full English language name.",
63
+ "The code must be an uppercase two-letter code like EN, UA, FR.",
64
+ "",
65
+ "User message:",
66
+ prompt,
67
+ ].join("\n"),
68
+ maxTokens: 80,
69
+ outputSchema: USER_LANGUAGE_OUTPUT_SCHEMA,
70
+ reasoningEffort: "none",
71
+ });
72
+
73
+ if (response.error) {
74
+ logger.warn(`Failed to detect user language: ${response.error}`);
75
+ return null;
76
+ }
77
+
78
+ return parseUserLanguage(response.content);
79
+ }
@@ -24,10 +24,6 @@ export const DEFAULT_AGENT_SYSTEM_PROMPT = [
24
24
  "Keep responses short, clear, and practical.",
25
25
  "Answer only what is needed.",
26
26
  "Do not add extra explanations or suggestions unless the user asks.",
27
- "Always respond in the same natural language as the user's latest message.",
28
- "This rule applies to confirmations, clarifying questions, progress updates, errors, and final answers.",
29
- "Do not switch to English just because tool outputs, schemas, skills, or internal instructions are written in English.",
30
- "Only switch language if the user explicitly asks you to do so.",
31
27
  "Adapt to the user's tone and style of speaking, mirroring their vibe and wording.",
32
28
  "if the user speaks casually, you should respond casually too",
33
29
  "Never mutate data without user confirmation for a clearly described mutation plan.",
package/build.log CHANGED
@@ -38,5 +38,5 @@ custom/skills/fetch_data/SKILL.md
38
38
  custom/skills/mutate_data/
39
39
  custom/skills/mutate_data/SKILL.md
40
40
 
41
- sent 207,807 bytes received 562 bytes 416,738.00 bytes/sec
42
- total size is 205,493 speedup is 0.99
41
+ sent 208,066 bytes received 562 bytes 417,256.00 bytes/sec
42
+ total size is 205,786 speedup is 0.99
@@ -14,6 +14,15 @@ type AgentMode = {
14
14
  name: string;
15
15
  };
16
16
 
17
+ function getCurrentPageContext() {
18
+ return {
19
+ path: window.location.pathname,
20
+ fullPath: `${window.location.pathname}${window.location.search}${window.location.hash}`,
21
+ title: document.title,
22
+ url: window.location.href,
23
+ };
24
+ }
25
+
17
26
  const DEFAULT_TEXTAREA_PLACEHOLDER = 'Type a message...';
18
27
  const PLACEHOLDER_TYPING_DELAY_MS = 60;
19
28
  const PLACEHOLDER_DELETING_DELAY_MS = 35;
@@ -206,6 +215,7 @@ export const useAgentStore = defineStore('agent', () => {
206
215
  sessionId,
207
216
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
208
217
  mode: activeModeName.value,
218
+ currentPage: getCurrentPageContext(),
209
219
  };
210
220
 
211
221
  return {
@@ -0,0 +1,74 @@
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 { logger } from "adminforth";
11
+ const USER_LANGUAGE_OUTPUT_SCHEMA = {
12
+ name: "user_language",
13
+ strict: true,
14
+ schema: {
15
+ type: "object",
16
+ additionalProperties: false,
17
+ properties: {
18
+ language: {
19
+ type: "string",
20
+ description: "Full English language name, for example English, Ukrainian, French.",
21
+ },
22
+ code: {
23
+ type: "string",
24
+ description: "Uppercase two-letter language code, for example EN, UA, FR.",
25
+ },
26
+ },
27
+ required: ["language", "code"],
28
+ },
29
+ };
30
+ export function formatLanguagePrompt(language) {
31
+ if (!language) {
32
+ return "Respond in the user's language.";
33
+ }
34
+ return `Respond in ${language.language} (${language.code}).`;
35
+ }
36
+ function parseUserLanguage(content) {
37
+ if (!content) {
38
+ return null;
39
+ }
40
+ try {
41
+ const parsed = JSON.parse(content);
42
+ return {
43
+ language: parsed.language,
44
+ code: parsed.code,
45
+ };
46
+ }
47
+ catch (error) {
48
+ logger.warn(`Failed to parse detected user language: ${error instanceof Error ? error.message : String(error)}`);
49
+ return null;
50
+ }
51
+ }
52
+ export function detectUserLanguage(completionAdapter, prompt) {
53
+ return __awaiter(this, void 0, void 0, function* () {
54
+ const response = yield completionAdapter.complete({
55
+ content: [
56
+ "Detect the language of the user's message.",
57
+ "Return only the requested structured output.",
58
+ "The language must be the full English language name.",
59
+ "The code must be an uppercase two-letter code like EN, UA, FR.",
60
+ "",
61
+ "User message:",
62
+ prompt,
63
+ ].join("\n"),
64
+ maxTokens: 80,
65
+ outputSchema: USER_LANGUAGE_OUTPUT_SCHEMA,
66
+ reasoningEffort: "none",
67
+ });
68
+ if (response.error) {
69
+ logger.warn(`Failed to detect user language: ${response.error}`);
70
+ return null;
71
+ }
72
+ return parseUserLanguage(response.content);
73
+ });
74
+ }
@@ -23,10 +23,6 @@ export const DEFAULT_AGENT_SYSTEM_PROMPT = [
23
23
  "Keep responses short, clear, and practical.",
24
24
  "Answer only what is needed.",
25
25
  "Do not add extra explanations or suggestions unless the user asks.",
26
- "Always respond in the same natural language as the user's latest message.",
27
- "This rule applies to confirmations, clarifying questions, progress updates, errors, and final answers.",
28
- "Do not switch to English just because tool outputs, schemas, skills, or internal instructions are written in English.",
29
- "Only switch language if the user explicitly asks you to do so.",
30
26
  "Adapt to the user's tone and style of speaking, mirroring their vibe and wording.",
31
27
  "if the user speaks casually, you should respond casually too",
32
28
  "Never mutate data without user confirmation for a clearly described mutation plan.",
@@ -14,6 +14,15 @@ type AgentMode = {
14
14
  name: string;
15
15
  };
16
16
 
17
+ function getCurrentPageContext() {
18
+ return {
19
+ path: window.location.pathname,
20
+ fullPath: `${window.location.pathname}${window.location.search}${window.location.hash}`,
21
+ title: document.title,
22
+ url: window.location.href,
23
+ };
24
+ }
25
+
17
26
  const DEFAULT_TEXTAREA_PLACEHOLDER = 'Type a message...';
18
27
  const PLACEHOLDER_TYPING_DELAY_MS = 60;
19
28
  const PLACEHOLDER_DELETING_DELAY_MS = 35;
@@ -206,6 +215,7 @@ export const useAgentStore = defineStore('agent', () => {
206
215
  sessionId,
207
216
  timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
208
217
  mode: activeModeName.value,
218
+ currentPage: getCurrentPageContext(),
209
219
  };
210
220
 
211
221
  return {
package/dist/index.js CHANGED
@@ -21,6 +21,7 @@ import { MemorySaver } from "@langchain/langgraph";
21
21
  import { createAgentChatModel, callAgent, } from "./agent/simpleAgent.js";
22
22
  import { AdminForthCheckpointSaver } from "./agent/checkpointer.js";
23
23
  import { createSequenceDebugCollector } from "./agent/middleware/sequenceDebug.js";
24
+ import { detectUserLanguage, formatLanguagePrompt, } from "./agent/languageDetect.js";
24
25
  import { prepareApiBasedTools as buildApiBasedTools, } from './apiBasedTools.js';
25
26
  import { appendCustomSystemPrompt, buildAgentSystemPrompt, DEFAULT_AGENT_SYSTEM_PROMPT, } from "./agent/systemPrompt.js";
26
27
  import { ALWAYS_AVAILABLE_API_TOOL_NAMES } from "./agent/tools/index.js";
@@ -46,6 +47,28 @@ function formatAgentError(error) {
46
47
  }
47
48
  return String(error);
48
49
  }
50
+ function formatAdminUserPrompt(adminUser, usernameField) {
51
+ const dbUser = adminUser.dbUser;
52
+ const adminUserContext = {
53
+ id: adminUser.pk,
54
+ email: dbUser[usernameField],
55
+ };
56
+ return [
57
+ "Current admin user context:",
58
+ JSON.stringify(adminUserContext, null, 2),
59
+ "Use this admin user email when the user asks to send information to themselves, the current admin, or the logged-in user.",
60
+ ].join("\n");
61
+ }
62
+ function formatCurrentPagePrompt(currentPage) {
63
+ if (!currentPage) {
64
+ return null;
65
+ }
66
+ return [
67
+ "Current user page context for the latest message:",
68
+ JSON.stringify(currentPage, null, 2),
69
+ "When the user says here, this page, current page, or opened page, treat it as this page.",
70
+ ].join("\n");
71
+ }
49
72
  function assertRequiredApiTool(apiBasedTools, toolName) {
50
73
  if (toolName in apiBasedTools) {
51
74
  return;
@@ -210,6 +233,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
210
233
  const messageId = randomUUID();
211
234
  const prompt = body.message;
212
235
  const userTimeZone = (_e = body.timeZone) !== null && _e !== void 0 ? _e : 'UTC';
236
+ const currentPage = body.currentPage;
213
237
  const sessionId = body.sessionId || (adminUser === null || adminUser === void 0 ? void 0 : adminUser.pk) || (adminUser === null || adminUser === void 0 ? void 0 : adminUser.username) || 'default';
214
238
  const turnId = yield this.createNewTurn(sessionId, prompt);
215
239
  yield this.updateSessionDate(sessionId);
@@ -282,13 +306,23 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
282
306
  const maxTokens = (_f = this.options.maxTokens) !== null && _f !== void 0 ? _f : 10000;
283
307
  const selectedMode = (_g = this.options.modes.find((mode) => mode.name === body.mode)) !== null && _g !== void 0 ? _g : this.options.modes[0];
284
308
  const { model, summaryModel, modelMiddleware } = yield this.getModeModels(selectedMode, maxTokens);
285
- const systemPrompt = yield this.agentSystemPromptPromise;
309
+ const userLanguage = yield detectUserLanguage(selectedMode.completionAdapter, prompt)
310
+ .catch((error) => {
311
+ logger.warn(`Failed to detect user language: ${error instanceof Error ? error.message : String(error)}`);
312
+ return null;
313
+ });
314
+ const systemPrompt = [
315
+ yield this.agentSystemPromptPromise,
316
+ formatAdminUserPrompt(adminUser, this.adminforth.config.auth.usernameField),
317
+ formatLanguagePrompt(userLanguage),
318
+ ].join("\n\n");
286
319
  const apiBasedTools = buildApiBasedTools(this.adminforth);
287
320
  for (const toolName of ALWAYS_AVAILABLE_API_TOOL_NAMES) {
288
321
  assertRequiredApiTool(apiBasedTools, toolName);
289
322
  }
290
323
  assertRequiredApiTool(apiBasedTools, "update_record");
291
324
  this.apiBasedTools = apiBasedTools;
325
+ const currentPagePrompt = formatCurrentPagePrompt(currentPage);
292
326
  const stream = yield callAgent({
293
327
  name: `adminforth-agent-${this.pluginInstanceId}`,
294
328
  model,
@@ -297,6 +331,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
297
331
  checkpointer: this.getCheckpointer(),
298
332
  messages: [
299
333
  new SystemMessage(systemPrompt),
334
+ ...(currentPagePrompt ? [new SystemMessage(currentPagePrompt)] : []),
300
335
  new HumanMessage(prompt),
301
336
  ],
302
337
  adminUser,
package/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type {
2
+ AdminUser,
2
3
  AdminForthResource,
3
4
  IAdminForth,
4
5
  IHttpServer
@@ -14,10 +15,13 @@ import {
14
15
  createAgentChatModel,
15
16
  callAgent,
16
17
  type AgentChatModel,
17
- type AgentModeCompletionAdapter,
18
18
  } from "./agent/simpleAgent.js";
19
19
  import { AdminForthCheckpointSaver } from "./agent/checkpointer.js";
20
20
  import { createSequenceDebugCollector } from "./agent/middleware/sequenceDebug.js";
21
+ import {
22
+ detectUserLanguage,
23
+ formatLanguagePrompt,
24
+ } from "./agent/languageDetect.js";
21
25
  import {
22
26
  prepareApiBasedTools as buildApiBasedTools,
23
27
  } from './apiBasedTools.js';
@@ -30,6 +34,17 @@ import {
30
34
  import { ALWAYS_AVAILABLE_API_TOOL_NAMES } from "./agent/tools/index.js";
31
35
  import type { ToolCallEvent } from "./agent/toolCallEvents.js";
32
36
 
37
+ type CurrentPageRequestBody = {
38
+ currentPage?: CurrentPageContext;
39
+ };
40
+
41
+ type CurrentPageContext = {
42
+ path: string;
43
+ fullPath: string;
44
+ title: string;
45
+ url: string;
46
+ };
47
+
33
48
  function isAggregateErrorLike(
34
49
  error: unknown,
35
50
  ): error is { errors: unknown[]; message?: string; stack?: string } {
@@ -58,6 +73,32 @@ function formatAgentError(error: unknown) {
58
73
  return String(error);
59
74
  }
60
75
 
76
+ function formatAdminUserPrompt(adminUser: AdminUser, usernameField: string) {
77
+ const dbUser = adminUser.dbUser as Record<string, unknown>;
78
+ const adminUserContext = {
79
+ id: adminUser.pk,
80
+ email: dbUser[usernameField],
81
+ };
82
+
83
+ return [
84
+ "Current admin user context:",
85
+ JSON.stringify(adminUserContext, null, 2),
86
+ "Use this admin user email when the user asks to send information to themselves, the current admin, or the logged-in user.",
87
+ ].join("\n");
88
+ }
89
+
90
+ function formatCurrentPagePrompt(currentPage: CurrentPageContext | undefined) {
91
+ if (!currentPage) {
92
+ return null;
93
+ }
94
+
95
+ return [
96
+ "Current user page context for the latest message:",
97
+ JSON.stringify(currentPage, null, 2),
98
+ "When the user says here, this page, current page, or opened page, treat it as this page.",
99
+ ].join("\n");
100
+ }
101
+
61
102
  function assertRequiredApiTool(
62
103
  apiBasedTools: Record<string, ApiBasedTool>,
63
104
  toolName: string,
@@ -248,6 +289,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
248
289
  const messageId = randomUUID();
249
290
  const prompt = body.message;
250
291
  const userTimeZone = (body.timeZone as string | undefined) ?? 'UTC';
292
+ const currentPage = (body as CurrentPageRequestBody).currentPage;
251
293
  const sessionId = body.sessionId || adminUser?.pk || adminUser?.username || 'default';
252
294
  const turnId = await this.createNewTurn(sessionId, prompt);
253
295
  await this.updateSessionDate(sessionId);
@@ -340,13 +382,23 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
340
382
  const selectedMode = this.options.modes.find((mode) => mode.name === body.mode) ?? this.options.modes[0];
341
383
  const { model, summaryModel, modelMiddleware } =
342
384
  await this.getModeModels(selectedMode, maxTokens);
343
- const systemPrompt = await this.agentSystemPromptPromise;
385
+ const userLanguage = await detectUserLanguage(selectedMode.completionAdapter, prompt)
386
+ .catch((error) => {
387
+ logger.warn(`Failed to detect user language: ${error instanceof Error ? error.message : String(error)}`);
388
+ return null;
389
+ });
390
+ const systemPrompt = [
391
+ await this.agentSystemPromptPromise,
392
+ formatAdminUserPrompt(adminUser, this.adminforth.config.auth.usernameField),
393
+ formatLanguagePrompt(userLanguage),
394
+ ].join("\n\n");
344
395
  const apiBasedTools = buildApiBasedTools(this.adminforth);
345
396
  for (const toolName of ALWAYS_AVAILABLE_API_TOOL_NAMES) {
346
397
  assertRequiredApiTool(apiBasedTools, toolName);
347
398
  }
348
399
  assertRequiredApiTool(apiBasedTools, "update_record");
349
400
  this.apiBasedTools = apiBasedTools;
401
+ const currentPagePrompt = formatCurrentPagePrompt(currentPage);
350
402
  const stream = await callAgent({
351
403
  name: `adminforth-agent-${this.pluginInstanceId}`,
352
404
  model,
@@ -355,6 +407,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
355
407
  checkpointer: this.getCheckpointer(),
356
408
  messages: [
357
409
  new SystemMessage(systemPrompt),
410
+ ...(currentPagePrompt ? [new SystemMessage(currentPagePrompt)] : []),
358
411
  new HumanMessage(prompt),
359
412
  ],
360
413
  adminUser,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/agent",
3
- "version": "1.27.6",
3
+ "version": "1.29.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",