@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
package/README.md CHANGED
@@ -5,8 +5,9 @@
5
5
  [![Ask AI](https://tluma.ai/badge)](https://tluma.ai/ask-ai/devforth/adminforth)
6
6
 
7
7
  Adds a native, tool-calling AI agent to your AdminForth application. The agent lives in a
8
- chat panel inside the admin UI, can inspect and mutate your resources through safe
9
- API-based tools, streams its answers token-by-token, and keeps persistent chat sessions.
8
+ chat panel inside the admin UI, can inspect and mutate your resources through the tools of
9
+ the [AdminForth MCP server](https://adminforth.dev/docs/tutorial/Plugins/mcp/), streams its
10
+ answers token-by-token, and keeps persistent chat sessions.
10
11
 
11
12
  > Full tutorial: [AdminForth Agent Documentation](https://adminforth.dev/docs/tutorial/Plugins/agent/)
12
13
 
@@ -14,7 +15,8 @@ API-based tools, streams its answers token-by-token, and keeps persistent chat s
14
15
 
15
16
  - **Chat agent in the admin UI** — a streaming chat surface injected into every page.
16
17
  - **Tool calling over your resources** — the agent reads and (optionally) mutates records
17
- through AdminForth's own API layer, so your access rules and validation still apply.
18
+ through the `@adminforth/mcp` plugin, which runs AdminForth's own API handlers as the user,
19
+ so your access rules, hooks and validation still apply.
18
20
  - **Progressive tool & skill disclosure** — the agent loads only the tools it needs, guided
19
21
  by Markdown *skills* you can extend.
20
22
  - **Human-in-the-loop approvals** — tools you mark as dangerous pause for explicit
@@ -35,10 +37,11 @@ Built on [LangChain / LangGraph](https://github.com/langchain-ai/langgraphjs).
35
37
 
36
38
  ## How it works
37
39
 
38
- For each user message the plugin creates a *turn*, builds the system prompt (including the
39
- list of your resources and available skills), streams the model's output back over SSE, and
40
- persists the prompt/response to your turn resource. Tools are executed through AdminForth's
41
- API endpoints; conversation memory is kept per session (`thread_id = sessionId`).
40
+ For each user message the plugin creates a *turn*, opens an in-process connection to the
41
+ `@adminforth/mcp` server as the user, builds the system prompt (the MCP server instructions
42
+ with its skills, followed by the agent's own rules), streams the model's output back over SSE,
43
+ and persists the prompt/response to your turn resource. Every tool call is an MCP `tools/call`
44
+ on that connection; conversation memory is kept per session (`thread_id = sessionId`).
42
45
 
43
46
  ## Architecture
44
47
 
@@ -50,7 +53,7 @@ completion adapter, the checkpointer) sit behind ports and never leak into the t
50
53
  | Domain — prompt building, event vocabulary, buffers | [domain/](domain/) | adminforth types only |
51
54
  | Application — the turn use case + ports | [application/](application/) | domain |
52
55
  | LLM runtime — LangChain/LangGraph behind `LlmPort` | [llm/](llm/) | application, domain, tools |
53
- | Tools & skills — API tools, progressive disclosure | [tools/](tools/) | AdminForth API layer |
56
+ | Tools — MCP connection, progressive disclosure | [tools/](tools/) | `@adminforth/mcp` |
54
57
  | Persistence — sessions, turns, checkpoints | [persistence/](persistence/) | AdminForth resources |
55
58
  | Transport — HTTP endpoints, SSE, external surfaces | [transport/](transport/) | application |
56
59
  | Frontend — Vue 3 + Pinia chat surface | [custom/](custom/) | HTTP + SSE contract |
@@ -62,9 +65,10 @@ flowchart TB
62
65
  APP["application/<br/>RunTurnUseCase + LlmPort"]
63
66
  DOM["domain/<br/>prompt building, steer buffer,<br/>events, language detection"]
64
67
  LLMS["llm/<br/>LangGraph agent, middleware chain, models"]
65
- TLS["tools/<br/>API tools + skills,<br/>progressive disclosure"]
68
+ TLS["tools/<br/>MCP connection,<br/>progressive disclosure"]
66
69
  PRS["persistence/<br/>sessions, turns, checkpoints"]
67
70
 
71
+ MCPS(["@adminforth/mcp<br/>tools, skills, 2FA confirmation"])
68
72
  AF[("AdminForth core<br/>resources, API layer, auth")]
69
73
  MODEL(["Completion adapter<br/>OpenAI / Anthropic / Gemini"])
70
74
  ADPT(["Audio and chat surface adapters<br/>STT / TTS, Telegram"])
@@ -79,12 +83,15 @@ flowchart TB
79
83
  LLMS --> MODEL
80
84
  LLMS --> TLS
81
85
  LLMS -->|"checkpointer"| PRS
82
- TLS --> AF
86
+ TLS -->|"in-process MCP"| MCPS
87
+ MCPS --> AF
83
88
  PRS --> AF
84
89
  ```
85
90
 
86
91
  Every arrow into `AdminForth core` goes through its ordinary resource/API layer, so your
87
92
  access rules, hooks and validation apply to the agent exactly as they do to a human admin.
93
+ The agent has exactly the permissions of the user it runs for: the MCP `readOnly` option
94
+ applies to MCP clients only.
88
95
 
89
96
  ### One turn, end to end
90
97
 
@@ -98,7 +105,7 @@ sequenceDiagram
98
105
  participant DB as sessions and turns
99
106
  participant LLM as LangGraphLlm + AgentRuntime
100
107
  participant M as Model (completion adapter)
101
- participant T as API tool (AdminForth API layer)
108
+ participant T as MCP tool (@adminforth/mcp)
102
109
 
103
110
  U->>UI: type a message
104
111
  UI->>EP: message, sessionId, mode, timeZone, currentPage
@@ -115,14 +122,14 @@ sequenceDiagram
115
122
  M-->>LLM: reasoning and text deltas
116
123
  LLM-->>UI: reasoning-delta and text-delta frames
117
124
  M-->>LLM: tool call
118
- alt tool has agent.requiresHumanApproval
125
+ alt tool has destructiveHint (agent.requiresHumanApproval)
119
126
  LLM-->>UI: data-interrupt, generation pauses
120
127
  U->>UI: approve or reject
121
128
  UI->>EP: POST /agent/approval
122
129
  EP->>UC: resume the interrupted graph
123
130
  else safe tool
124
- LLM->>T: execute through the API layer
125
- T-->>LLM: YAML result plus durationMs
131
+ LLM->>T: tools/call on the in-process MCP connection
132
+ T-->>LLM: YAML result
126
133
  LLM-->>UI: data-tool-call start and end
127
134
  end
128
135
  end
@@ -146,21 +153,23 @@ Two side channels run on top of that flow:
146
153
 
147
154
  ```mermaid
148
155
  flowchart LR
149
- A["Turn starts"] --> B["Exposed tools:<br/>get_resource, get_user_location,<br/>navigate_user, fetch_skill, fetch_tool_schema"]
156
+ A["Turn starts"] --> B["Exposed tools: MCP get_resources_list,<br/>get_resource, fetch_skill, wait_for_confirmation,<br/>and get_user_location, navigate_user, fetch_tool_schema"]
150
157
  B --> C{"Needs more than<br/>reading schema?"}
151
158
  C -- no --> D["Answer with the base tools"]
152
- C -- yes --> E["fetch_skill returns the SKILL.md<br/>for the matching skill"]
153
- E --> F["fetch_tool_schema loads one<br/>API tool schema by name"]
154
- F --> G["ApiBasedToolsMiddleware sees the<br/>status 200 tool message and adds that<br/>tool to the next model call"]
155
- G --> H{"agent.requiresHumanApproval?"}
159
+ C -- yes --> E["MCP fetch_skill returns<br/>the matching skill"]
160
+ E --> F["fetch_tool_schema loads one<br/>MCP tool by name"]
161
+ F --> G["McpToolsMiddleware sees the<br/>status 200 tool message and adds that<br/>tool to the next model call"]
162
+ G --> H{"destructiveHint?"}
156
163
  H -- yes --> I["humanInTheLoopMiddleware interrupt,<br/>approve or reject in the UI"]
157
- H -- no --> J["Execute through the AdminForth API layer"]
164
+ H -- no --> J["tools/call on the MCP server"]
158
165
  I -- approved --> J
159
166
  ```
160
167
 
161
168
  ## Requirements
162
169
 
163
170
  - An AdminForth app (`adminforth >= 3.8.2`, declared as a peer dependency).
171
+ - The [`@adminforth/mcp`](https://adminforth.dev/docs/tutorial/Plugins/mcp/) plugin in the same
172
+ app: the agent calls every admin panel tool through it and fails to start without it.
164
173
  - A **completion adapter** that supports agent/tool-calling. Any of these work:
165
174
  - [`@adminforth/completion-adapter-openai-responses`](https://www.npmjs.com/package/@adminforth/completion-adapter-openai-responses)
166
175
  - [`@adminforth/completion-adapter-anthropic-messages`](https://www.npmjs.com/package/@adminforth/completion-adapter-anthropic-messages)
@@ -171,13 +180,15 @@ flowchart LR
171
180
  ## Installation
172
181
 
173
182
  ```bash
174
- npm install @adminforth/agent @adminforth/completion-adapter-openai-responses
183
+ pnpm add @adminforth/agent @adminforth/mcp @adminforth/completion-adapter-openai-responses
175
184
  ```
176
185
 
177
186
  ## Setup
178
187
 
179
188
  Setup has three parts: (1) create the storage resources, (2) configure the plugin, and
180
- (3) register both in your AdminForth config.
189
+ (3) register both in your AdminForth config. Set up the
190
+ [MCP plugin](https://adminforth.dev/docs/tutorial/Plugins/mcp/) as its documentation describes
191
+ and add it to the same `globalPlugins`.
181
192
 
182
193
  ### 1. Create the storage resources
183
194
 
@@ -203,6 +214,10 @@ const sessionsResource: AdminForthResourceInput = {
203
214
  { name: 'asker_id', type: AdminForthDataTypes.STRING },
204
215
  { name: 'created_at', type: AdminForthDataTypes.DATETIME, fillOnCreate: () => new Date().toISOString() },
205
216
  ],
217
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
218
+ options: {
219
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
220
+ },
206
221
  };
207
222
 
208
223
  export default sessionsResource;
@@ -233,6 +248,10 @@ const turnsResource: AdminForthResourceInput = {
233
248
  // Optional: add a `debug` TEXT column and map it via turnResource.debugField
234
249
  // to store per-turn debug traces.
235
250
  ],
251
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
252
+ options: {
253
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
254
+ },
236
255
  };
237
256
 
238
257
  export default turnsResource;
@@ -269,6 +288,10 @@ const checkpointsResource: AdminForthResourceInput = {
269
288
  { name: 'writes_payload', type: AdminForthDataTypes.TEXT },
270
289
  { name: 'schema_version', type: AdminForthDataTypes.INTEGER },
271
290
  ],
291
+ // Agent-internal data: closed to admin users and MCP clients, the agent works with it directly.
292
+ options: {
293
+ allowedActions: { list: false, show: false, create: false, edit: false, delete: false },
294
+ },
272
295
  };
273
296
 
274
297
  export default checkpointsResource;
@@ -400,29 +423,35 @@ plus two optional ones:
400
423
 
401
424
  ## Tools & skills
402
425
 
403
- The agent works through **API-based tools** generated from your AdminForth resources
404
- (reading records, inspecting schema, and — through skills — creating/updating/deleting
405
- records and running actions). Tools run via AdminForth's own API layer, so per-resource
406
- permissions and validation are enforced.
426
+ The agent has no tools of its own for your data: it is an MCP client of the
427
+ [`@adminforth/mcp`](https://adminforth.dev/docs/tutorial/Plugins/mcp/) server, connected in
428
+ process for each turn as the user who sends the message. The MCP server runs AdminForth's API
429
+ handlers, so per-resource permissions, hooks and validation are enforced, and it shows only the
430
+ resources the user may list or show.
407
431
 
408
432
  To keep the model focused, tools are disclosed progressively:
409
433
 
410
- - Always available: `get_resource` (inspect resource structure), `get_user_location`,
411
- `navigate_user`, and the two discovery tools `fetch_skill` / `fetch_tool_schema`.
412
- - The agent reads a **skill** (a `SKILL.md` file) to learn which tools a task needs, then
413
- loads those tool schemas on demand.
434
+ - Always available: the MCP tools `get_resources_list`, `get_resource`, `fetch_skill` and, with
435
+ two-factor authentication set up, `wait_for_confirmation`; and the agent's own
436
+ `get_user_location`, `navigate_user` and `fetch_tool_schema`.
437
+ - Every other MCP tool is named, with the first sentence of its description, in the
438
+ description of `fetch_tool_schema`, the way MCP clients that load tool schemas on demand
439
+ list them. The agent loads a tool with `fetch_tool_schema` before its first call, and a
440
+ **skill** loaded with `fetch_skill` tells it which tools a task needs.
414
441
 
415
- Built-in skills cover fetching data, analytics/charts, and mutating data. You can add your
416
- own skills by placing a `SKILL.md` (with `name` and `description` frontmatter) in a
417
- `skills/<skill-name>/` directory under your custom components dir; plugin-provided skill
418
- directories are also discovered.
442
+ Skills come from the MCP server: its built-in `fetch-data`, `analyze-data` and `mutate-data`, plus
443
+ every `skills/<skill-name>/SKILL.md` in your custom components dir and in other plugins. The
444
+ agent's own system prompt adds the rules of this chat and the guide for Vega-Lite charts.
445
+
446
+ Datetimes in `get_resource_data` results come in the user's time zone, which the chat UI sends
447
+ with every message.
419
448
 
420
449
  ## Human-in-the-loop approvals
421
450
 
422
- Tools whose endpoint sets `agent.requiresHumanApproval` (or the older `agent.isDangerous`) trigger an
423
- approval interrupt: generation pauses and the UI shows an approve/reject prompt. The client
424
- resolves it via `POST /agent/approval`, and the run resumes (or, on reject, the model is
425
- told the action was declined).
451
+ Tools whose endpoint sets `agent.requiresHumanApproval`, which the MCP server marks with
452
+ `destructiveHint`, trigger an approval interrupt: generation pauses and the UI shows an
453
+ approve/reject prompt. The client resolves it via `POST /agent/approval`, and the run resumes
454
+ (or, on reject, the model is told the action was declined).
426
455
 
427
456
  The prompt names the resource and columns by their labels and lists every value the tool
428
457
  would write; for `update_record` each field shows its current value next to the new one.
@@ -432,6 +461,10 @@ Where the pending approval lives depends on your setup: with `checkpointResource
432
461
  the LangGraph checkpoint is authoritative, so a resume survives a restart and works across
433
462
  instances; with the in-memory fallback the state is held per process instance.
434
463
 
464
+ Actions that need a two-factor verification run after the user confirms them on the MCP
465
+ confirmation page of the admin panel: the agent shows the link and waits with
466
+ `wait_for_confirmation`.
467
+
435
468
  ## Voice
436
469
 
437
470
  Provide an `audioAdapter` (e.g. [`@adminforth/audio-adapter-openai`](https://www.npmjs.com/package/@adminforth/audio-adapter-openai))
@@ -1,4 +1,4 @@
1
- import type { CompletionAdapter } from "adminforth";
1
+ import type { AdminUser, CompletionAdapter } from "adminforth";
2
2
  import type { DetectedLanguage, PreviousUserMessage } from "../domain/languageDetect.js";
3
3
  import type { AgentMessage, AgentStreamChunk, AgentTurnContext, AgentTurnObservability, PendingInterrupt } from "../domain/turnTypes.js";
4
4
  export type AgentModelPurpose = "primary" | "summary";
@@ -65,6 +65,7 @@ export interface LlmPort {
65
65
  getPendingInterrupts(input: {
66
66
  completionAdapter: AgentModeCompletionAdapter;
67
67
  sessionId: string;
68
+ adminUser: AdminUser;
68
69
  }): Promise<PendingInterrupt[]>;
69
70
  /**
70
71
  * Return the session thread's latest (tip) checkpoint id, or null when the thread
@@ -74,6 +75,7 @@ export interface LlmPort {
74
75
  getLatestCheckpointId(input: {
75
76
  completionAdapter: AgentModeCompletionAdapter;
76
77
  sessionId: string;
78
+ adminUser: AdminUser;
77
79
  }): Promise<string | null>;
78
80
  /**
79
81
  * Drop the entire LangGraph checkpoint thread for a session. Used when editing the
@@ -1,4 +1,4 @@
1
- import { type IAdminForth } from "adminforth";
1
+ import { type AdminUser, type IAdminForth } from "adminforth";
2
2
  import type { AgentSessionStore } from "../persistence/sessionStore.js";
3
3
  import type { SteerBuffer } from "../domain/steerBuffer.js";
4
4
  import type { PluginOptions } from "../types.js";
@@ -39,7 +39,7 @@ export type RunTurnUseCaseDeps = {
39
39
  steerBuffer: SteerBuffer;
40
40
  modes: PluginOptions["modes"];
41
41
  getAdminforth: () => IAdminForth;
42
- getAgentSystemPrompt: () => Promise<string>;
42
+ getAgentSystemPrompt: () => string;
43
43
  /** True when a persistent checkpointer is configured (not the in-memory MemorySaver). */
44
44
  hasPersistentCheckpointer: boolean;
45
45
  /**
@@ -79,7 +79,7 @@ export declare class RunTurnUseCase {
79
79
  * page reload would otherwise leave the user with no way to answer it. Empty when
80
80
  * nothing is pending.
81
81
  */
82
- getPendingApprovals(sessionId: string, modeName?: string | null): Promise<ApprovalDescription[]>;
82
+ getPendingApprovals(sessionId: string, adminUser: AdminUser, modeName?: string | null): Promise<ApprovalDescription[]>;
83
83
  private requiresSessionOwnership;
84
84
  /** Verify the session exists and belongs to the requesting admin user. */
85
85
  assertSessionOwnership(sessionId: string, adminUser: BaseAgentTurnInput["adminUser"]): Promise<void>;
@@ -101,7 +101,7 @@ export class RunTurnUseCase {
101
101
  * checkpoint is authoritative (correct across instances and restarts); with the in-memory
102
102
  * MemorySaver the in-process cache is authoritative (single process, cannot be stale).
103
103
  */
104
- resolvePendingInterrupts(sessionId, mode) {
104
+ resolvePendingInterrupts(sessionId, mode, adminUser) {
105
105
  return __awaiter(this, void 0, void 0, function* () {
106
106
  var _a;
107
107
  if (this.deps.hasPersistentCheckpointer) {
@@ -112,6 +112,7 @@ export class RunTurnUseCase {
112
112
  return yield this.deps.llm.getPendingInterrupts({
113
113
  completionAdapter: mode.completionAdapter,
114
114
  sessionId,
115
+ adminUser,
115
116
  });
116
117
  }
117
118
  catch (error) {
@@ -135,12 +136,12 @@ export class RunTurnUseCase {
135
136
  * page reload would otherwise leave the user with no way to answer it. Empty when
136
137
  * nothing is pending.
137
138
  */
138
- getPendingApprovals(sessionId, modeName) {
139
+ getPendingApprovals(sessionId, adminUser, modeName) {
139
140
  return __awaiter(this, void 0, void 0, function* () {
140
141
  // Loading a conversation must not fail because the checkpoint store is unhappy
141
142
  // (already logged by resolvePendingInterrupts). Without the prompt the user simply
142
143
  // falls back to the implicit reject in `prepareTurn`.
143
- const interrupts = yield this.resolvePendingInterrupts(sessionId, this.resolveMode(modeName))
144
+ const interrupts = yield this.resolvePendingInterrupts(sessionId, this.resolveMode(modeName), adminUser)
144
145
  .catch(() => []);
145
146
  return this.describeApprovals(interrupts);
146
147
  });
@@ -239,7 +240,7 @@ export class RunTurnUseCase {
239
240
  let initialResponse;
240
241
  let resume;
241
242
  if (shouldResume) {
242
- const resumeInterrupts = yield this.resolvePendingInterrupts(input.sessionId, mode);
243
+ const resumeInterrupts = yield this.resolvePendingInterrupts(input.sessionId, mode, input.adminUser);
243
244
  if (resumeInterrupts.length === 0) {
244
245
  throw new Error(`No pending approval interrupt found for session "${input.sessionId}".`);
245
246
  }
@@ -255,7 +256,7 @@ export class RunTurnUseCase {
255
256
  // pending call is rejected as part of this turn and the prompt rides along in
256
257
  // the rejection. Reached whenever the approval UI is gone — after a page
257
258
  // reload, from a second tab, or from a chat surface.
258
- const pending = yield this.resolvePendingInterrupts(input.sessionId, mode);
259
+ const pending = yield this.resolvePendingInterrupts(input.sessionId, mode, input.adminUser);
259
260
  previousUserMessages = yield this.deps.sessions.getPreviousUserMessages(input.sessionId);
260
261
  turnId = yield this.deps.sessions.createNewTurn(input.sessionId, input.prompt);
261
262
  yield this.deps.sessions.touchSession(input.sessionId);
@@ -341,7 +342,7 @@ export class RunTurnUseCase {
341
342
  : { messages: this.buildMessages(prepared) };
342
343
  const stream = yield this.deps.llm.streamTurn({
343
344
  completionAdapter: prepared.mode.completionAdapter,
344
- systemPrompt: yield this.deps.getAgentSystemPrompt(),
345
+ systemPrompt: this.deps.getAgentSystemPrompt(),
345
346
  input: streamInput,
346
347
  context: Object.assign(Object.assign({}, prepared.context), { userLanguage }),
347
348
  observability: prepared.observability,
@@ -440,6 +441,7 @@ export class RunTurnUseCase {
440
441
  checkpointId = yield this.deps.llm.getLatestCheckpointId({
441
442
  completionAdapter: prepared.mode.completionAdapter,
442
443
  sessionId: prepared.sessionId,
444
+ adminUser: prepared.context.adminUser,
443
445
  });
444
446
  }
445
447
  catch (error) {
@@ -52,7 +52,7 @@
52
52
  <script setup lang="ts">
53
53
  import { IconBot } from '@iconify-prerendered/vue-lucide';
54
54
  import { Button } from '@/afcl';
55
- import { useTemplateRef, onMounted, ref, onUnmounted } from 'vue';
55
+ import { useTemplateRef, onMounted, ref, onUnmounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
56
56
  import { onClickOutside } from '@vueuse/core'
57
57
  import ConversationArea from './conversation_area/ConversationArea.vue';
58
58
  import ChatHeader from './ChatHeader.vue';
@@ -60,7 +60,7 @@ import ChatFooter from './ChatFooter.vue';
60
60
  import { useAgentStore } from './composables/useAgentStore';
61
61
  import { useAgentTransitions } from './composables/useAgentTransitions';
62
62
  import { useCoreStore } from '@/stores/core';
63
- import { remToPx } from './utils';
63
+ import { remToPx, getLayoutElements } from './utils';
64
64
 
65
65
  const props = defineProps<{
66
66
  meta: {
@@ -87,6 +87,9 @@ const dvh = ref(window.visualViewport?.height || window.innerHeight);
87
87
  let startX = 0
88
88
  let startWidth = 0
89
89
 
90
+ const layoutPaddingRight = computed(() => agentStore.isTeleportedToBody && agentStore.isChatOpen ? `${remToPx(agentStore.chatWidth)}px` : '');
91
+ watch(layoutPaddingRight, setLayoutPaddingRight);
92
+
90
93
  onClickOutside(chatSurface as any, () => {if (!agentStore.isTeleportedToBody && !agentStore.isFullScreen) agentStore.setIsChatOpen(false);});
91
94
 
92
95
  onMounted(async () => {
@@ -108,9 +111,21 @@ onMounted(async () => {
108
111
  agentStore.setIsChatOpen(true);
109
112
  }
110
113
  }
114
+ // the header is re-created after a re-login, so the room for the chat is made on every mount
115
+ setLayoutPaddingRight(layoutPaddingRight.value);
116
+ nextTick(() => {
117
+ agentTransitions.setAppRootTransition(false);
118
+ agentTransitions.setChatSurfaceTransition(false);
119
+ });
111
120
  await agentStore.fetchSessionsList();
112
121
  });
113
122
 
123
+ // on logout the header goes away with this component, but #app stays and must not keep the room for the chat
124
+ onBeforeUnmount(() => {
125
+ agentTransitions.setAppRootTransition(true);
126
+ setLayoutPaddingRight('');
127
+ })
128
+
114
129
  onUnmounted(() => {
115
130
  window.removeEventListener('resize', updateHeight)
116
131
  })
@@ -139,16 +154,18 @@ const stopResize = () => {
139
154
  document.removeEventListener('mousemove', onResize)
140
155
  document.removeEventListener('mouseup', stopResize)
141
156
 
142
- const appRoot = document.getElementById('app');
143
- const header = document.getElementById('af-header-nav');
144
- if (appRoot && header) {
145
- agentTransitions.setAppRootTransition(false);
146
- agentTransitions.setChatSurfaceTransition(false);
147
- }
157
+ agentTransitions.setAppRootTransition(false);
158
+ agentTransitions.setChatSurfaceTransition(false);
148
159
  }
149
160
 
150
161
  function updateHeight() {
151
162
  dvh.value = Math.round(window.visualViewport?.height || window.innerHeight);
152
163
  }
153
164
 
165
+ function setLayoutPaddingRight(paddingRight: string) {
166
+ for (const element of getLayoutElements()) {
167
+ element.style.paddingRight = paddingRight;
168
+ }
169
+ }
170
+
154
171
  </script>
@@ -1,8 +1,6 @@
1
- name: charts
2
- description: Create Vega-Lite chart specs for AdminForth analytics responses. Always use this skill when the user asks for a chart or when a chart would help illustrate the insights from an analytics query.
3
- ---
1
+ # Charts
4
2
 
5
- # Instructions
3
+ Add a chart when the user asks for one or when it helps to illustrate the insights of an analytics answer. The chat renders Vega-Lite specs.
6
4
 
7
5
  Use Vega-Lite syntax for charts.
8
6
 
@@ -49,8 +49,6 @@ export const useAgentStore = defineStore('agent', () => {
49
49
  isTeleportedToBody.value = isTeleported;
50
50
  }
51
51
  const coreStore = useCoreStore();
52
- const appRoot = ref<HTMLElement | null>(null);
53
- const header = ref<HTMLElement | null>(null);
54
52
  const lastSessionId = ref<string | null>(null);
55
53
  const chatWidth = ref(DEFAULT_CHAT_WIDTH);
56
54
  const availableModes = ref<AgentMode[]>([]);
@@ -336,13 +334,6 @@ export const useAgentStore = defineStore('agent', () => {
336
334
  if (coreStore.isMobile) {
337
335
  setChatWidth(window.innerWidth);
338
336
  }
339
- appRoot.value = document.getElementById('app');
340
- header.value = document.getElementById('af-header-nav');
341
- if (appRoot.value && header.value) {
342
- nextTick(() => {
343
- agentTransitions.setAppRootTransition(false);
344
- });
345
- }
346
337
  })
347
338
 
348
339
  const isFullScreen = ref(false);
@@ -381,17 +372,6 @@ export const useAgentStore = defineStore('agent', () => {
381
372
  chatWidth.value = pxToRem(width);
382
373
 
383
374
  }
384
- watch([isTeleportedToBody, isChatOpen, chatWidth], ([newIsTeleportedToBody, newIsChatOpen, newChatWidth]: [boolean, boolean, number]) => {
385
- if (appRoot.value && header.value) {
386
- if (newIsTeleportedToBody && newIsChatOpen) {
387
- appRoot.value.style.paddingRight = `${remToPx(chatWidth.value)}px`;
388
- header.value.style.paddingRight = `${remToPx(chatWidth.value)}px`;
389
- } else {
390
- appRoot.value.style.paddingRight = '';
391
- header.value.style.paddingRight = '';
392
- }
393
- }
394
- })
395
375
 
396
376
  function setAvailableModes(modes: AgentMode[], defaultModeName?: string | null) {
397
377
  availableModes.value = modes;
@@ -1,53 +1,29 @@
1
1
  import { defineStore } from 'pinia';
2
- import { ref, nextTick,onMounted } from 'vue';
3
2
  import { useAgentStore } from './useAgentStore';
3
+ import { getLayoutElements } from '../utils';
4
4
 
5
5
 
6
6
  export const useAgentTransitions = defineStore('agentTransitions', () => {
7
7
  const TRANSITION_DURATION = 300;
8
8
 
9
9
  const agentStore = useAgentStore();
10
- const appRoot = ref<HTMLElement | null>(null);
11
- const header = ref<HTMLElement | null>(null);
12
10
 
13
- const chatRoot = ref<HTMLElement | null>(null);
14
-
15
- onMounted(() => {
16
- appRoot.value = document.getElementById('app');
17
- header.value = document.getElementById('af-header-nav');
18
- chatRoot.value = document.getElementById('adminforth-agent-chat-surface');
19
- if (appRoot.value && header.value) {
20
- nextTick(() => {
21
- setAppRootTransition(false);
22
- });
23
- }
24
- if (chatRoot.value) {
25
- nextTick(() => {
26
- setChatSurfaceTransition(false);
27
- });
28
- }
29
- });
11
+ // elements are looked up on every call, the header and the chat surface are re-created after a re-login
30
12
  function setAppRootTransition(blockTransition = true) {
31
- if (appRoot.value && header.value) {
32
- if (blockTransition) {
33
- appRoot.value.style.transition = '';
34
- header.value.style.transition = '';
35
- } else {
36
- appRoot.value.style.transition = `padding-right ${TRANSITION_DURATION}ms ease-in-out`;
37
- header.value.style.transition = `padding-right ${TRANSITION_DURATION}ms ease-in-out`;
38
- }
13
+ const transition = blockTransition ? '' : `padding-right ${TRANSITION_DURATION}ms ease-in-out`;
14
+ for (const element of getLayoutElements()) {
15
+ element.style.transition = transition;
39
16
  }
40
17
  }
41
18
  function setChatSurfaceTransition(blockTransition = true) {
42
- if (chatRoot.value) {
43
- if (blockTransition) {
44
- chatRoot.value.style.transition = '';
45
- } else {
46
- chatRoot.value.style.transition = `
47
- transform ${TRANSITION_DURATION}ms ease-in-out,
48
- width ${TRANSITION_DURATION}ms ease-in-out
49
- `;
50
- }
19
+ const chatRoot = document.getElementById('adminforth-agent-chat-surface')!;
20
+ if (blockTransition) {
21
+ chatRoot.style.transition = '';
22
+ } else {
23
+ chatRoot.style.transition = `
24
+ transform ${TRANSITION_DURATION}ms ease-in-out,
25
+ width ${TRANSITION_DURATION}ms ease-in-out
26
+ `;
51
27
  }
52
28
  }
53
29
  return {
@@ -10,6 +10,11 @@ export function pxToRem(px: number): number {
10
10
  return px / rootFontSize;
11
11
  }
12
12
 
13
+ // #app and the header make room for the docked chat, both exist while ChatSurface is mounted in the header
14
+ export function getLayoutElements(): HTMLElement[] {
15
+ return [document.getElementById('app')!, document.getElementById('af-header-nav')!];
16
+ }
17
+
13
18
 
14
19
  export function getMessageParts(message: IMessage): IPart[] {
15
20
  return message.parts?.length
@@ -1,11 +1,12 @@
1
- import type { AdminUser, IAdminForth } from "adminforth";
1
+ import type { AdminUser } from "adminforth";
2
2
  import type { DetectedLanguage } from "./languageDetect.js";
3
3
  export declare const DEFAULT_AGENT_SYSTEM_PROMPT: string;
4
4
  export declare function appendCustomSystemPrompt(systemPrompt: string, customSystemPrompt?: string): string;
5
5
  export declare function buildDynamicSystemPrompt(input: {
6
6
  adminUser: AdminUser;
7
7
  usernameField: string;
8
+ userTimeZone: string;
8
9
  userLanguage?: DetectedLanguage | null;
9
10
  chatSurface?: string;
10
11
  }): string;
11
- export declare function buildAgentSystemPrompt(adminforth: IAdminForth, hiddenResourceIds?: Iterable<string>): Promise<string>;
12
+ export declare function buildAgentSystemPrompt(adminBasePath: string, chartsGuide: string): string;