@adminforth/agent 3.2.0 → 3.4.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 (39) hide show
  1. package/dist/application/runTurnUseCase.d.ts +5 -1
  2. package/dist/application/runTurnUseCase.js +41 -57
  3. package/dist/custom/ChatFooter.vue +76 -36
  4. package/dist/custom/ChatSurface.vue +89 -19
  5. package/dist/custom/ComposerAttachments.vue +36 -0
  6. package/dist/custom/composables/agentStore/constants.ts +13 -0
  7. package/dist/custom/composables/agentStore/useAgentAttachments.ts +163 -0
  8. package/dist/custom/composables/agentStore/useAgentChat.ts +19 -4
  9. package/dist/custom/composables/agentStore/useAgentSessions.ts +84 -20
  10. package/dist/custom/composables/useAgentStore.ts +67 -31
  11. package/dist/custom/composables/useAgentTransitions.ts +13 -37
  12. package/dist/custom/conversation_area/MessageAttachments.vue +22 -0
  13. package/dist/custom/conversation_area/MessageRenderer.vue +15 -2
  14. package/dist/custom/types.ts +39 -0
  15. package/dist/custom/utils.ts +15 -0
  16. package/dist/domain/imageAttachments.d.ts +73 -0
  17. package/dist/domain/imageAttachments.js +63 -0
  18. package/dist/domain/turnTypes.d.ts +16 -0
  19. package/dist/index.d.ts +4 -2
  20. package/dist/index.js +30 -2
  21. package/dist/llm/agentRuntime.d.ts +11 -1
  22. package/dist/llm/agentRuntime.js +6 -1
  23. package/dist/llm/langGraphLlm.js +7 -1
  24. package/dist/llm/middleware/attachmentsMiddleware.d.ts +16 -0
  25. package/dist/llm/middleware/attachmentsMiddleware.js +139 -0
  26. package/dist/persistence/sessionStore.d.ts +11 -2
  27. package/dist/persistence/sessionStore.js +44 -9
  28. package/dist/persistence/turnAttachments.d.ts +41 -0
  29. package/dist/persistence/turnAttachments.js +112 -0
  30. package/dist/tools/navigateUser.d.ts +3 -3
  31. package/dist/tools/toolLabels.js +1 -0
  32. package/dist/tools/viewImage.d.ts +13 -0
  33. package/dist/tools/viewImage.js +57 -0
  34. package/dist/transport/http/context.d.ts +22 -3
  35. package/dist/transport/http/coreEndpoints.d.ts +36 -1
  36. package/dist/transport/http/coreEndpoints.js +104 -35
  37. package/dist/transport/http/sessionEndpoints.js +3 -4
  38. package/dist/types.d.ts +29 -0
  39. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -7,6 +7,17 @@ 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 __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
10
21
  import { AdminForthPlugin } from "adminforth";
11
22
  import { readFileSync } from "fs";
12
23
  import path from "path";
@@ -17,6 +28,8 @@ import { setupCoreEndpoints } from "./transport/http/coreEndpoints.js";
17
28
  import { setupSessionEndpoints } from "./transport/http/sessionEndpoints.js";
18
29
  import { setupChatSurfaceEndpoints } from "./transport/http/chatSurfaceEndpoints.js";
19
30
  import { AgentSessionStore } from "./persistence/sessionStore.js";
31
+ import { TurnAttachments } from "./persistence/turnAttachments.js";
32
+ import { getAttachmentsFrontendConfig, resolveImageAttachmentsLimits, } from "./domain/imageAttachments.js";
20
33
  import { ChatSurfaceService } from "./transport/surfaces/chatSurfaceService.js";
21
34
  import { RunTurnUseCase } from "./application/runTurnUseCase.js";
22
35
  import { createSequenceDebugCollector } from "./llm/middleware/sequenceDebug.js";
@@ -44,7 +57,9 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
44
57
  this.pluginsScope = "global";
45
58
  this.checkpointer = null;
46
59
  this.options = options;
47
- this.sessionStore = new AgentSessionStore(() => this.adminforth, this.options);
60
+ this.imageAttachmentsLimits = resolveImageAttachmentsLimits(options.imageAttachments);
61
+ this.turnAttachments = new TurnAttachments(() => this.adminforth, this.options);
62
+ this.sessionStore = new AgentSessionStore(() => this.adminforth, this.options, this.turnAttachments);
48
63
  this.steerBuffer = new SteerBuffer();
49
64
  const runtime = new AgentRuntime({
50
65
  name: `adminforth-agent-${this.pluginInstanceId}`,
@@ -52,11 +67,15 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
52
67
  getCheckpointer: this.getCheckpointer.bind(this),
53
68
  toolProvider: new AgentToolProvider(() => this.adminforth),
54
69
  steerBuffer: this.steerBuffer,
70
+ attachmentsEnabled: this.turnAttachments.enabled,
71
+ imageAttachmentsLimits: this.imageAttachmentsLimits,
72
+ loadAttachmentAsDataUrl: (filePath) => this.turnAttachments.loadAsDataUrl(filePath),
55
73
  });
56
74
  const llm = new LangGraphLlm(runtime, new AgentModelFactory((_a = this.options.maxTokens) !== null && _a !== void 0 ? _a : 1000));
57
75
  this.runTurnUseCase = new RunTurnUseCase({
58
76
  llm,
59
77
  sessions: this.sessionStore,
78
+ attachments: this.turnAttachments,
60
79
  steerBuffer: this.steerBuffer,
61
80
  modes: this.options.modes,
62
81
  getAdminforth: () => this.adminforth,
@@ -92,6 +111,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
92
111
  stickByDefault: (_b = this.options.stickByDefault) !== null && _b !== void 0 ? _b : false,
93
112
  hasAudioAdapter: Boolean(this.options.audioAdapter),
94
113
  editingEnabled: Boolean(this.options.checkpointResource && this.options.turnResource.checkpointIdField),
114
+ attachments: this.turnAttachments.enabled ? getAttachmentsFrontendConfig(this.imageAttachmentsLimits) : null,
95
115
  }
96
116
  });
97
117
  if (!this.options.sessionResource) {
@@ -110,13 +130,14 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
110
130
  }
111
131
  });
112
132
  }
113
- validateConfigAfterDiscover(adminforth, resourceConfig) {
133
+ validateConfigAfterDiscover(adminforth) {
114
134
  var _a, _b;
115
135
  (_a = this.options.audioAdapter) === null || _a === void 0 ? void 0 : _a.validate();
116
136
  for (const chatSurfaceAdapter of (_b = this.options.chatSurfaceAdapters) !== null && _b !== void 0 ? _b : []) {
117
137
  chatSurfaceAdapter.validate();
118
138
  }
119
139
  adminforth.getPluginByClassName(MCP_PLUGIN_CLASS_NAME);
140
+ this.turnAttachments.resolveUploadPlugin();
120
141
  this.agentSystemPrompt = appendCustomSystemPrompt(buildAgentSystemPrompt(adminforth.config.baseUrlSlashed, readFileSync(path.join(this.customFolderPath, CHARTS_GUIDE_FILE), "utf8")), this.options.systemPrompt);
121
142
  }
122
143
  instanceUniqueRepresentation(pluginOptions) {
@@ -126,6 +147,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
126
147
  const endpointContext = {
127
148
  adminforth: this.adminforth,
128
149
  options: this.options,
150
+ imageAttachmentsLimits: this.imageAttachmentsLimits,
129
151
  handleTurn: this.runTurnUseCase.handleTurn.bind(this.runTurnUseCase),
130
152
  handleEditTurn: this.runTurnUseCase.handleEditTurn.bind(this.runTurnUseCase),
131
153
  handleSpeechTurn: this.speechTurnService.handle.bind(this.speechTurnService),
@@ -134,10 +156,16 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
134
156
  const { id } = this.steerBuffer.add(sessionId, message);
135
157
  return { id, queued: this.steerBuffer.size(sessionId) };
136
158
  }),
159
+ createAttachmentUploadUrl: (_a) => __awaiter(this, void 0, void 0, function* () {
160
+ var { adminUser } = _a, input = __rest(_a, ["adminUser"]);
161
+ yield this.runTurnUseCase.assertSessionOwnership(input.sessionId, adminUser);
162
+ return this.turnAttachments.createUploadUrl(input);
163
+ }),
137
164
  runAndPersistAgentResponse: this.runTurnUseCase.runAndPersistAgentResponse.bind(this.runTurnUseCase),
138
165
  getSessionTurns: this.sessionStore.getSessionTurns.bind(this.sessionStore),
139
166
  getPendingApprovals: (sessionId, adminUser) => this.runTurnUseCase.getPendingApprovals(sessionId, adminUser),
140
167
  createNewTurn: this.sessionStore.createNewTurn.bind(this.sessionStore),
168
+ deleteSession: this.sessionStore.deleteSession.bind(this.sessionStore),
141
169
  createSystemTurn: this.sessionStore.createSystemTurn.bind(this.sessionStore),
142
170
  appendSteerToCurrentTurn: this.sessionStore.appendSteerToCurrentTurn.bind(this.sessionStore),
143
171
  handleChatSurfaceMessage: this.chatSurfaceService.handleMessage.bind(this.chatSurfaceService),
@@ -1,5 +1,6 @@
1
1
  import type { AdminUser, IAdminForth } from "adminforth";
2
2
  import type { BaseCheckpointSaver } from "@langchain/langgraph";
3
+ import type { ImageAttachmentsLimits } from "../domain/imageAttachments.js";
3
4
  import type { SteerBuffer } from "../domain/steerBuffer.js";
4
5
  import type { AgentToolProvider } from "../tools/agentToolProvider.js";
5
6
  import type { AgentRuntimeRunInput, AgentTurnModels } from "./agentModels.js";
@@ -9,11 +10,20 @@ export type AgentRuntimeOptions = {
9
10
  getCheckpointer: () => BaseCheckpointSaver;
10
11
  toolProvider: Pick<AgentToolProvider, "open">;
11
12
  steerBuffer: SteerBuffer;
13
+ attachmentsEnabled: boolean;
14
+ imageAttachmentsLimits: ImageAttachmentsLimits;
15
+ loadAttachmentAsDataUrl: (filePath: string) => Promise<string>;
12
16
  };
13
17
  export declare class AgentRuntime {
14
18
  private readonly options;
15
19
  constructor(options: AgentRuntimeOptions);
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>>;
20
+ 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)[] | readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool | import("langchain").DynamicStructuredTool<import("zod").ZodObject<{
21
+ imageIds: import("zod").ZodArray<import("zod").ZodString>;
22
+ }, import("zod/v4/core").$strip>, {
23
+ imageIds: string[];
24
+ }, {
25
+ imageIds: string[];
26
+ }, [string, import("../domain/imageAttachments.js").ViewImageArtifact], unknown, "view_image">)[]>>>, "jumpTo">>], void, any>>;
17
27
  private getThreadState;
18
28
  /**
19
29
  * Read the pending human-in-the-loop interrupts persisted for a thread from the
@@ -36,6 +36,8 @@ import { createAgent, summarizationMiddleware, humanInTheLoopMiddleware, dynamic
36
36
  import { createMcpToolsMiddleware } from "./middleware/mcpToolsMiddleware.js";
37
37
  import { createSequenceDebugMiddleware } from "./middleware/sequenceDebug.js";
38
38
  import { createSteerMiddleware } from "./middleware/steerMiddleware.js";
39
+ import { createAttachmentsMiddleware } from "./middleware/attachmentsMiddleware.js";
40
+ import { createViewImageTool } from "../tools/viewImage.js";
39
41
  import { createAgentLlmMetricsLogger } from "./agentModels.js";
40
42
  import { contextSchema, toLangchainAgentContext } from "./agentContext.js";
41
43
  import { createLegacySystemMessagesMiddleware } from "./middleware/legacySystemMessages.js";
@@ -98,6 +100,7 @@ export class AgentRuntime {
98
100
  trigger: { tokens: 1024 * 64 },
99
101
  keep: { messages: 10 },
100
102
  }),
103
+ createAttachmentsMiddleware(this.options.loadAttachmentAsDataUrl, this.options.imageAttachmentsLimits),
101
104
  ];
102
105
  const agent = createAgent({
103
106
  name: this.options.name,
@@ -109,7 +112,9 @@ export class AgentRuntime {
109
112
  // come first: the agent's own rules refine them for this chat.
110
113
  systemPrompt: `${toolSet.instructions}\n\n${input.systemPrompt}`,
111
114
  checkpointer: this.options.getCheckpointer(),
112
- tools: toolSet.baseTools,
115
+ tools: this.options.attachmentsEnabled
116
+ ? [...toolSet.baseTools, createViewImageTool(this.options.imageAttachmentsLimits)]
117
+ : toolSet.baseTools,
113
118
  contextSchema,
114
119
  middleware,
115
120
  });
@@ -11,8 +11,14 @@ import { Command } from "@langchain/langgraph";
11
11
  import { HumanMessage } from "langchain";
12
12
  import { detectUserLanguage } from "../domain/languageDetect.js";
13
13
  import { adaptRawStream, normalizeInterrupts } from "./streamAdapter.js";
14
+ import { ATTACHMENTS_KWARG, ATTACHMENTS_SENT_AT_KWARG } from "../domain/imageAttachments.js";
14
15
  function toLangchainMessages(messages) {
15
- return messages.map((message) => new HumanMessage(message.content));
16
+ return messages.map((message) => new HumanMessage({
17
+ content: message.content,
18
+ additional_kwargs: message.attachments.length > 0
19
+ ? { [ATTACHMENTS_KWARG]: message.attachments, [ATTACHMENTS_SENT_AT_KWARG]: new Date().toISOString() }
20
+ : {},
21
+ }));
16
22
  }
17
23
  /**
18
24
  * LangChain/LangGraph implementation of {@link LlmPort}. This is the single
@@ -0,0 +1,16 @@
1
+ import { type ImageAttachmentsLimits } from "../../domain/imageAttachments.js";
2
+ /**
3
+ * `wrapModelCall` middleware that turns the attachment paths of user messages into image
4
+ * blocks right before the model call. Placed last, so the images reach only the model and
5
+ * not the debug trace or the summarization of other middleware. Created per turn, so an
6
+ * image is loaded from the storage once for all model calls of the turn.
7
+ *
8
+ * An image is shown for `visibleMinutes` after its message is sent, at most `maxVisible` at once; any other image becomes a note with its id and is not
9
+ * read at all. Images the model loads again with view_image follow the tool results of that step
10
+ * as one user message: a user message between tool results is refused by providers, and provider
11
+ * adapters may send only the messages after their previous response (OpenAI previous_response_id),
12
+ * so a change in an earlier message would not reach the model. An image which can not be read
13
+ * (deleted from the storage, the storage changed) becomes a note too, so one broken file does not
14
+ * fail every next turn of the session.
15
+ */
16
+ export declare function createAttachmentsMiddleware(loadAsDataUrl: (filePath: string) => Promise<string>, limits: ImageAttachmentsLimits): import("langchain").AgentMiddleware<undefined, undefined, unknown, readonly (import("@langchain/core/tools").ClientTool | import("@langchain/core/tools").ServerTool)[]>;
@@ -0,0 +1,139 @@
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
+ import { HumanMessage, ToolMessage, createMiddleware } from "langchain";
12
+ import { getErrorMessage } from "../../shared/errors.js";
13
+ import { ATTACHMENTS_SENT_AT_KWARG, MISSING_IMAGE_TEXT, VIEW_IMAGE_TOOL_NAME, getAttachmentPaths, hiddenImageText, viewedBelowImageText, viewedImageLabel, } from "../../domain/imageAttachments.js";
14
+ /** What a view_image result loaded; a failed call (bad arguments, tool off) has no artifact. */
15
+ function getViewedImages(message) {
16
+ var _a;
17
+ return ToolMessage.isInstance(message) && message.name === VIEW_IMAGE_TOOL_NAME
18
+ ? (_a = message.artifact) !== null && _a !== void 0 ? _a : null
19
+ : null;
20
+ }
21
+ /**
22
+ * The images to show now, by the message they are shown in: the message they were sent with,
23
+ * or the view_image result which loaded them again. Shown for `visibleMinutes` after that, the
24
+ * latest `maxVisible` only.
25
+ */
26
+ function getShownImages(messages, now, { visibleMinutes, maxVisible }) {
27
+ var _a;
28
+ const visibleMs = visibleMinutes * 60000;
29
+ const latestByFilePath = new Map();
30
+ const show = (filePath, message, at) => {
31
+ var _a, _b;
32
+ if (now - at < visibleMs && at > ((_b = (_a = latestByFilePath.get(filePath)) === null || _a === void 0 ? void 0 : _a.at) !== null && _b !== void 0 ? _b : 0)) {
33
+ latestByFilePath.set(filePath, { message, at });
34
+ }
35
+ };
36
+ for (const message of messages) {
37
+ const filePaths = getAttachmentPaths(message);
38
+ const sentAt = (_a = message.additional_kwargs) === null || _a === void 0 ? void 0 : _a[ATTACHMENTS_SENT_AT_KWARG];
39
+ if (filePaths && sentAt) {
40
+ filePaths.forEach((filePath) => show(filePath, message, Date.parse(sentAt)));
41
+ }
42
+ const viewed = getViewedImages(message);
43
+ if (viewed) {
44
+ viewed.filePaths.forEach((filePath) => show(filePath, message, Date.parse(viewed.viewedAt)));
45
+ }
46
+ }
47
+ const shown = new Map();
48
+ [...latestByFilePath]
49
+ .sort(([, a], [, b]) => b.at - a.at)
50
+ .slice(0, maxVisible)
51
+ .forEach(([filePath, { message }]) => { var _a; return shown.set(message, [...((_a = shown.get(message)) !== null && _a !== void 0 ? _a : []), filePath]); });
52
+ return shown;
53
+ }
54
+ /**
55
+ * `wrapModelCall` middleware that turns the attachment paths of user messages into image
56
+ * blocks right before the model call. Placed last, so the images reach only the model and
57
+ * not the debug trace or the summarization of other middleware. Created per turn, so an
58
+ * image is loaded from the storage once for all model calls of the turn.
59
+ *
60
+ * An image is shown for `visibleMinutes` after its message is sent, at most `maxVisible` at once; any other image becomes a note with its id and is not
61
+ * read at all. Images the model loads again with view_image follow the tool results of that step
62
+ * as one user message: a user message between tool results is refused by providers, and provider
63
+ * adapters may send only the messages after their previous response (OpenAI previous_response_id),
64
+ * so a change in an earlier message would not reach the model. An image which can not be read
65
+ * (deleted from the storage, the storage changed) becomes a note too, so one broken file does not
66
+ * fail every next turn of the session.
67
+ */
68
+ export function createAttachmentsMiddleware(loadAsDataUrl, limits) {
69
+ const dataUrls = new Map();
70
+ const load = (filePath) => {
71
+ if (!dataUrls.has(filePath)) {
72
+ dataUrls.set(filePath, loadAsDataUrl(filePath).catch((error) => {
73
+ logger.warn(`Agent attachment "${filePath}" can not be read, the model gets a note instead: ${getErrorMessage(error)}`);
74
+ return null;
75
+ }));
76
+ }
77
+ return dataUrls.get(filePath);
78
+ };
79
+ const imageBlock = (filePath) => __awaiter(this, void 0, void 0, function* () {
80
+ const dataUrl = yield load(filePath);
81
+ return dataUrl
82
+ ? { type: "image_url", image_url: { url: dataUrl } }
83
+ : { type: "text", text: MISSING_IMAGE_TEXT };
84
+ });
85
+ return createMiddleware({
86
+ name: "AttachmentsMiddleware",
87
+ wrapModelCall(request, handler) {
88
+ return __awaiter(this, void 0, void 0, function* () {
89
+ var _a;
90
+ if (!request.messages.some((message) => getAttachmentPaths(message) || getViewedImages(message))) {
91
+ return handler(request);
92
+ }
93
+ const shownImages = getShownImages(request.messages, Date.now(), limits);
94
+ // images loaded again are shown after the tool results, their own message only points there
95
+ const viewedImages = new Set([...shownImages]
96
+ .filter(([message]) => getViewedImages(message))
97
+ .flatMap(([, filePaths]) => filePaths));
98
+ const messages = [];
99
+ let viewedInStep = [];
100
+ for (const [index, message] of request.messages.entries()) {
101
+ const shown = (_a = shownImages.get(message)) !== null && _a !== void 0 ? _a : [];
102
+ const filePaths = getAttachmentPaths(message);
103
+ if (filePaths) {
104
+ const images = yield Promise.all(filePaths.map((filePath) => {
105
+ if (shown.includes(filePath)) {
106
+ return imageBlock(filePath);
107
+ }
108
+ const text = viewedImages.has(filePath) ? viewedBelowImageText(filePath) : hiddenImageText(filePath);
109
+ return { type: "text", text };
110
+ }));
111
+ messages.push(new HumanMessage({
112
+ content: [
113
+ ...(message.content ? [{ type: "text", text: message.content }] : []),
114
+ ...images,
115
+ ],
116
+ }));
117
+ continue;
118
+ }
119
+ messages.push(message);
120
+ if (getViewedImages(message)) {
121
+ viewedInStep.push(...shown);
122
+ }
123
+ const next = request.messages[index + 1];
124
+ if (viewedInStep.length > 0 && !(next && ToolMessage.isInstance(next))) {
125
+ const blocks = yield Promise.all(viewedInStep.map((filePath) => __awaiter(this, void 0, void 0, function* () {
126
+ return [
127
+ { type: "text", text: viewedImageLabel(filePath) },
128
+ yield imageBlock(filePath),
129
+ ];
130
+ })));
131
+ messages.push(new HumanMessage({ content: blocks.flat() }));
132
+ viewedInStep = [];
133
+ }
134
+ }
135
+ return handler(Object.assign(Object.assign({}, request), { messages }));
136
+ });
137
+ },
138
+ });
139
+ }
@@ -2,13 +2,16 @@ import type { AdminUser, IAdminForth } from "adminforth";
2
2
  import type { ChatSurfaceIncomingMessage } from "adminforth";
3
3
  import type { PreviousUserMessage } from "../domain/languageDetect.js";
4
4
  import type { PluginOptions } from "../types.js";
5
+ import type { TurnAttachments } from "./turnAttachments.js";
5
6
  export declare const AGENT_SYSTEM_TURN_PROMPT = "__adminforth_system_message__";
6
7
  export declare const STEER_PROMPT_MARKER = "__adminforth_steer__:";
7
8
  export declare class AgentSessionStore {
8
9
  private getAdminforth;
9
10
  private options;
10
- constructor(getAdminforth: () => IAdminForth, options: PluginOptions);
11
- createNewTurn(sessionId: string, prompt: string, response?: string): Promise<any>;
11
+ private attachments;
12
+ constructor(getAdminforth: () => IAdminForth, options: PluginOptions, attachments: TurnAttachments);
13
+ private getTurnAttachments;
14
+ createNewTurn(sessionId: string, prompt: string, attachments?: string[]): Promise<any>;
12
15
  createSystemTurn(sessionId: string, systemMessage: string): Promise<any>;
13
16
  /**
14
17
  * Append a mid-turn steer to the current (running) turn's prompt instead of creating a
@@ -20,6 +23,7 @@ export declare class AgentSessionStore {
20
23
  id: any;
21
24
  prompt: any;
22
25
  response: any;
26
+ attachments: import("../domain/turnTypes.js").TurnAttachment[];
23
27
  }[]>;
24
28
  /**
25
29
  * Ordered non-system (real conversation) turns with their stored checkpoint id.
@@ -30,6 +34,7 @@ export declare class AgentSessionStore {
30
34
  id: any;
31
35
  prompt: any;
32
36
  response: any;
37
+ attachments: string[];
33
38
  checkpointId: string | null;
34
39
  }[]>;
35
40
  /**
@@ -38,12 +43,16 @@ export declare class AgentSessionStore {
38
43
  * an interruption can only leave a consistent "truncated, edit-not-yet-applied"
39
44
  * state (recoverable by retry) — never "edited but stale later turns remain".
40
45
  * (AdminForth's resource API has no transactions, hence the deliberate ordering.)
46
+ * Files of the deleted turns and the images dropped by the edit are released.
41
47
  */
42
48
  editTurnAndTruncateAfter(input: {
43
49
  sessionId: string;
44
50
  turnId: string;
45
51
  newPrompt: string;
52
+ newAttachments: string[];
46
53
  }): Promise<void>;
54
+ /** Delete the session with its turns and release their attachments. */
55
+ deleteSession(sessionId: string): Promise<void>;
47
56
  getPreviousUserMessages(sessionId: string): Promise<PreviousUserMessage[]>;
48
57
  getLatestTurn(sessionId: string): Promise<any>;
49
58
  getChatSurfaceSessionId(incoming: ChatSurfaceIncomingMessage): string;
@@ -12,20 +12,30 @@ import { randomUUID } from "crypto";
12
12
  export const AGENT_SYSTEM_TURN_PROMPT = "__adminforth_system_message__";
13
13
  export const STEER_PROMPT_MARKER = "__adminforth_steer__:";
14
14
  export class AgentSessionStore {
15
- constructor(getAdminforth, options) {
15
+ constructor(getAdminforth, options, attachments) {
16
16
  this.getAdminforth = getAdminforth;
17
17
  this.options = options;
18
+ this.attachments = attachments;
18
19
  }
19
- createNewTurn(sessionId, prompt, response) {
20
- return __awaiter(this, void 0, void 0, function* () {
20
+ getTurnAttachments(turn) {
21
+ var _a;
22
+ const attachmentsField = this.options.turnResource.attachmentsField;
23
+ return attachmentsField ? (_a = turn[attachmentsField]) !== null && _a !== void 0 ? _a : [] : [];
24
+ }
25
+ createNewTurn(sessionId_1, prompt_1) {
26
+ return __awaiter(this, arguments, void 0, function* (sessionId, prompt, attachments = []) {
21
27
  const turnId = randomUUID();
22
28
  const turnRecord = {
23
29
  [this.options.turnResource.idField]: turnId,
24
30
  [this.options.turnResource.sessionIdField]: sessionId,
25
31
  [this.options.turnResource.promptField]: prompt,
26
- [this.options.turnResource.responseField]: response !== null && response !== void 0 ? response : "not_finished",
32
+ [this.options.turnResource.responseField]: "not_finished",
27
33
  };
34
+ if (attachments.length > 0) {
35
+ turnRecord[this.options.turnResource.attachmentsField] = attachments;
36
+ }
28
37
  const newTurn = yield this.getAdminforth().resource(this.options.turnResource.resourceId).create(turnRecord);
38
+ yield this.attachments.markUsed(attachments);
29
39
  return newTurn.createdRecord[this.options.turnResource.idField];
30
40
  });
31
41
  }
@@ -64,11 +74,14 @@ export class AgentSessionStore {
64
74
  getSessionTurns(sessionId) {
65
75
  return __awaiter(this, void 0, void 0, function* () {
66
76
  const turns = yield this.getAdminforth().resource(this.options.turnResource.resourceId).list([Filters.EQ(this.options.turnResource.sessionIdField, sessionId)], undefined, undefined, [Sorts.ASC(this.options.turnResource.createdAtField), Sorts.ASC(this.options.turnResource.idField)]);
67
- return turns.map(turn => ({
68
- id: turn[this.options.turnResource.idField],
69
- prompt: turn[this.options.turnResource.promptField],
70
- response: turn[this.options.turnResource.responseField],
71
- }));
77
+ return Promise.all(turns.map((turn) => __awaiter(this, void 0, void 0, function* () {
78
+ return ({
79
+ id: turn[this.options.turnResource.idField],
80
+ prompt: turn[this.options.turnResource.promptField],
81
+ response: turn[this.options.turnResource.responseField],
82
+ attachments: yield this.attachments.withUrls(this.getTurnAttachments(turn)),
83
+ });
84
+ })));
72
85
  });
73
86
  }
74
87
  /**
@@ -86,6 +99,7 @@ export class AgentSessionStore {
86
99
  id: turn[this.options.turnResource.idField],
87
100
  prompt: turn[this.options.turnResource.promptField],
88
101
  response: turn[this.options.turnResource.responseField],
102
+ attachments: this.getTurnAttachments(turn),
89
103
  checkpointId: checkpointIdField
90
104
  ? (turn[checkpointIdField] ? String(turn[checkpointIdField]) : null)
91
105
  : null,
@@ -98,6 +112,7 @@ export class AgentSessionStore {
98
112
  * an interruption can only leave a consistent "truncated, edit-not-yet-applied"
99
113
  * state (recoverable by retry) — never "edited but stale later turns remain".
100
114
  * (AdminForth's resource API has no transactions, hence the deliberate ordering.)
115
+ * Files of the deleted turns and the images dropped by the edit are released.
101
116
  */
102
117
  editTurnAndTruncateAfter(input) {
103
118
  return __awaiter(this, void 0, void 0, function* () {
@@ -108,6 +123,7 @@ export class AgentSessionStore {
108
123
  if (targetIndex === -1) {
109
124
  throw new Error(`Turn "${input.turnId}" not found in session "${input.sessionId}".`);
110
125
  }
126
+ const oldAttachments = this.getTurnAttachments(turns[targetIndex]);
111
127
  const laterTurns = turns.slice(targetIndex + 1);
112
128
  for (const turn of laterTurns) {
113
129
  yield resource.delete(turn[r.idField]);
@@ -119,7 +135,26 @@ export class AgentSessionStore {
119
135
  if (r.checkpointIdField) {
120
136
  updates[r.checkpointIdField] = null;
121
137
  }
138
+ if (r.attachmentsField) {
139
+ updates[r.attachmentsField] = input.newAttachments;
140
+ }
122
141
  yield resource.update(input.turnId, updates);
142
+ yield Promise.all([
143
+ this.attachments.markUsed(input.newAttachments.filter((filePath) => !oldAttachments.includes(filePath))),
144
+ this.attachments.markUnused([...oldAttachments, ...laterTurns.flatMap((turn) => this.getTurnAttachments(turn))]
145
+ .filter((filePath) => !input.newAttachments.includes(filePath))),
146
+ ]);
147
+ });
148
+ }
149
+ /** Delete the session with its turns and release their attachments. */
150
+ deleteSession(sessionId) {
151
+ return __awaiter(this, void 0, void 0, function* () {
152
+ const r = this.options.turnResource;
153
+ const turnResource = this.getAdminforth().resource(r.resourceId);
154
+ yield this.getAdminforth().resource(this.options.sessionResource.resourceId).delete(sessionId);
155
+ const turns = yield turnResource.list([Filters.EQ(r.sessionIdField, sessionId)]);
156
+ yield Promise.all(turns.map((turn) => turnResource.delete(turn[r.idField])));
157
+ yield this.attachments.markUnused(turns.flatMap((turn) => this.getTurnAttachments(turn)));
123
158
  });
124
159
  }
125
160
  getPreviousUserMessages(sessionId) {
@@ -0,0 +1,41 @@
1
+ import type { IAdminForth } from "adminforth";
2
+ import type { PluginOptions } from "../types.js";
3
+ import type { AttachmentRef, TurnAttachment } from "../domain/turnTypes.js";
4
+ /**
5
+ * Image attachments of user messages, stored by the UploadPlugin installed on
6
+ * `turnResource.attachmentsField`. The browser uploads straight to the storage, so the
7
+ * file paths it reports back are bound to the session with a signed token.
8
+ */
9
+ export declare class TurnAttachments {
10
+ private getAdminforth;
11
+ private options;
12
+ private uploadPlugin;
13
+ constructor(getAdminforth: () => IAdminForth, options: PluginOptions);
14
+ get enabled(): boolean;
15
+ /** Binds the UploadPlugin of `turnResource.attachmentsField`, once all plugins are activated. */
16
+ resolveUploadPlugin(): void;
17
+ createUploadUrl(input: {
18
+ sessionId: string;
19
+ filename: string;
20
+ contentType: string;
21
+ size: number;
22
+ }): Promise<{
23
+ uploadUrl: string;
24
+ uploadExtraParams: Record<string, string> | undefined;
25
+ contentType: string;
26
+ filePath: string;
27
+ previewUrl: string;
28
+ token: string;
29
+ }>;
30
+ /**
31
+ * Returns the paths of attachments uploaded to this session. A ref without a token is
32
+ * accepted only when its file is in `alreadyAttached` (an edited turn keeping its images).
33
+ */
34
+ verify(sessionId: string, refs: AttachmentRef[], alreadyAttached?: string[]): Promise<string[]>;
35
+ markUsed(filePaths: string[]): Promise<void>;
36
+ markUnused(filePaths: string[]): Promise<void>;
37
+ private getPreviewUrl;
38
+ withUrls(filePaths: string[]): Promise<TurnAttachment[]>;
39
+ /** The image as a data URL, the form every completion adapter accepts in a message. */
40
+ loadAsDataUrl(filePath: string): Promise<string>;
41
+ }
@@ -0,0 +1,112 @@
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 { ATTACHMENT_TOKEN_TYPE, BYTES_IN_MB, IMAGE_EXTENSIONS, MAX_IMAGE_SIZE_MB, PREVIEW_URL_EXPIRES_IN_SECONDS, } from "../domain/imageAttachments.js";
11
+ /**
12
+ * Image attachments of user messages, stored by the UploadPlugin installed on
13
+ * `turnResource.attachmentsField`. The browser uploads straight to the storage, so the
14
+ * file paths it reports back are bound to the session with a signed token.
15
+ */
16
+ export class TurnAttachments {
17
+ constructor(getAdminforth, options) {
18
+ this.getAdminforth = getAdminforth;
19
+ this.options = options;
20
+ }
21
+ get enabled() {
22
+ return Boolean(this.options.turnResource.attachmentsField);
23
+ }
24
+ /** Binds the UploadPlugin of `turnResource.attachmentsField`, once all plugins are activated. */
25
+ resolveUploadPlugin() {
26
+ var _a;
27
+ const { resourceId, attachmentsField } = this.options.turnResource;
28
+ if (!attachmentsField) {
29
+ return;
30
+ }
31
+ const adminforth = this.getAdminforth();
32
+ const column = adminforth.config.resources
33
+ .find((resource) => resource.resourceId === resourceId)
34
+ .columns.find((resourceColumn) => resourceColumn.name === attachmentsField);
35
+ if (!((_a = column === null || column === void 0 ? void 0 : column.isArray) === null || _a === void 0 ? void 0 : _a.enabled)) {
36
+ throw new Error(`turnResource.attachmentsField "${attachmentsField}" must be an isArray column of resource "${resourceId}"`);
37
+ }
38
+ const plugin = adminforth.getPluginsByClassName("UploadPlugin").find((uploadPlugin) => uploadPlugin.resourceConfig.resourceId === resourceId
39
+ && uploadPlugin.pluginOptions.pathColumnName === attachmentsField);
40
+ if (!plugin) {
41
+ throw new Error(`turnResource.attachmentsField "${attachmentsField}" requires UploadPlugin installed on this column of resource "${resourceId}"`);
42
+ }
43
+ const extensions = plugin.pluginOptions.allowedFileExtensions;
44
+ if (!(extensions === null || extensions === void 0 ? void 0 : extensions.length) || extensions.some((extension) => !IMAGE_EXTENSIONS.includes(extension))) {
45
+ throw new Error(`UploadPlugin on "${resourceId}.${attachmentsField}" must limit allowedFileExtensions to images: ${IMAGE_EXTENSIONS.join(", ")}`);
46
+ }
47
+ this.uploadPlugin = plugin;
48
+ }
49
+ createUploadUrl(input) {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ if (input.size > MAX_IMAGE_SIZE_MB * BYTES_IN_MB) {
52
+ throw new Error(`The image is too large: ${(input.size / BYTES_IN_MB).toFixed(1)} MB, at most ${MAX_IMAGE_SIZE_MB} MB can be sent to the model.`);
53
+ }
54
+ const { uploadUrl, uploadExtraParams, contentType, filePath } = yield this.uploadPlugin.getUploadUrl({
55
+ filename: input.filename,
56
+ contentType: input.contentType,
57
+ size: input.size,
58
+ });
59
+ const token = this.getAdminforth().auth.issueJWT({ sessionId: input.sessionId, filePath }, ATTACHMENT_TOKEN_TYPE);
60
+ // `contentType` is picked by the server from the extension, the upload must send exactly it;
61
+ // `previewUrl` lets the chat show the stored file, the one the model gets
62
+ return { uploadUrl, uploadExtraParams, contentType, filePath, previewUrl: yield this.getPreviewUrl(filePath), token };
63
+ });
64
+ }
65
+ /**
66
+ * Returns the paths of attachments uploaded to this session. A ref without a token is
67
+ * accepted only when its file is in `alreadyAttached` (an edited turn keeping its images).
68
+ */
69
+ verify(sessionId_1, refs_1) {
70
+ return __awaiter(this, arguments, void 0, function* (sessionId, refs, alreadyAttached = []) {
71
+ return Promise.all(refs.map((_a) => __awaiter(this, [_a], void 0, function* ({ filePath, token }) {
72
+ if (!token && alreadyAttached.includes(filePath)) {
73
+ return filePath;
74
+ }
75
+ const payload = token
76
+ ? yield this.getAdminforth().auth.verify(token, ATTACHMENT_TOKEN_TYPE, false)
77
+ : null;
78
+ if ((payload === null || payload === void 0 ? void 0 : payload.sessionId) !== sessionId || payload.filePath !== filePath) {
79
+ throw new Error(`Attachment "${filePath}" was not uploaded to this session.`);
80
+ }
81
+ return filePath;
82
+ })));
83
+ });
84
+ }
85
+ markUsed(filePaths) {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ yield Promise.all(filePaths.map((filePath) => this.uploadPlugin.markKeyForNotDeletion(filePath)));
88
+ });
89
+ }
90
+ markUnused(filePaths) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ yield Promise.all(filePaths.map((filePath) => this.uploadPlugin.markKeyForDeletion(filePath)));
93
+ });
94
+ }
95
+ getPreviewUrl(filePath) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ const { preview, storageAdapter } = this.uploadPlugin.pluginOptions;
98
+ return (preview === null || preview === void 0 ? void 0 : preview.previewUrl)
99
+ ? preview.previewUrl({ filePath })
100
+ : storageAdapter.getDownloadUrl(filePath, PREVIEW_URL_EXPIRES_IN_SECONDS);
101
+ });
102
+ }
103
+ withUrls(filePaths) {
104
+ return __awaiter(this, void 0, void 0, function* () {
105
+ return Promise.all(filePaths.map((filePath) => __awaiter(this, void 0, void 0, function* () { return ({ filePath, url: yield this.getPreviewUrl(filePath) }); })));
106
+ });
107
+ }
108
+ /** The image as a data URL, the form every completion adapter accepts in a message. */
109
+ loadAsDataUrl(filePath) {
110
+ return this.uploadPlugin.pluginOptions.storageAdapter.getKeyAsDataURL(filePath);
111
+ }
112
+ }