@adminforth/agent 3.3.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 (38) 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 +64 -11
  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 -11
  11. package/dist/custom/conversation_area/MessageAttachments.vue +22 -0
  12. package/dist/custom/conversation_area/MessageRenderer.vue +15 -2
  13. package/dist/custom/types.ts +39 -0
  14. package/dist/custom/utils.ts +10 -0
  15. package/dist/domain/imageAttachments.d.ts +73 -0
  16. package/dist/domain/imageAttachments.js +63 -0
  17. package/dist/domain/turnTypes.d.ts +16 -0
  18. package/dist/index.d.ts +4 -2
  19. package/dist/index.js +30 -2
  20. package/dist/llm/agentRuntime.d.ts +11 -1
  21. package/dist/llm/agentRuntime.js +6 -1
  22. package/dist/llm/langGraphLlm.js +7 -1
  23. package/dist/llm/middleware/attachmentsMiddleware.d.ts +16 -0
  24. package/dist/llm/middleware/attachmentsMiddleware.js +139 -0
  25. package/dist/persistence/sessionStore.d.ts +11 -2
  26. package/dist/persistence/sessionStore.js +44 -9
  27. package/dist/persistence/turnAttachments.d.ts +41 -0
  28. package/dist/persistence/turnAttachments.js +112 -0
  29. package/dist/tools/navigateUser.d.ts +3 -3
  30. package/dist/tools/toolLabels.js +1 -0
  31. package/dist/tools/viewImage.d.ts +13 -0
  32. package/dist/tools/viewImage.js +57 -0
  33. package/dist/transport/http/context.d.ts +22 -3
  34. package/dist/transport/http/coreEndpoints.d.ts +36 -1
  35. package/dist/transport/http/coreEndpoints.js +104 -35
  36. package/dist/transport/http/sessionEndpoints.js +3 -4
  37. package/dist/types.d.ts +29 -0
  38. package/package.json +3 -3
@@ -10,6 +10,10 @@
10
10
  :message="message"
11
11
  :isLastMessageInChat="isLastMessageInChat"
12
12
  />
13
+ <MessageAttachments
14
+ v-if="shownAttachments.length && shouldBeShownWhileEditing"
15
+ :attachments="shownAttachments"
16
+ />
13
17
  <template
14
18
  v-for="(part, index) in getMessageParts(message)"
15
19
  :key="part.type"
@@ -17,7 +21,8 @@
17
21
  <!-- a text part drops the margin of its last block, so a part that follows another one (the stream
18
22
  splits the text at every chart and tool call) brings back the gap between markdown blocks -->
19
23
  <TextRenderer
20
- v-if="part.type === 'text' && !checkIfMessageSystemMessage(part.text ?? '') && shouldBeShownWhileEditing"
24
+ v-if="part.type === 'text' && !checkIfMessageSystemMessage(part.text ?? '') && shouldBeShownWhileEditing
25
+ && (part.text || !isUserMessage || isBeingEditedMessage)"
21
26
  class="[&+&]:mt-2"
22
27
  :message="isBeingEditedMessage ? agentStore.userMessageInput : part.text"
23
28
  :role="props.message.role"
@@ -78,6 +83,7 @@
78
83
  import ProcessingTimeline from './ProcessingTimeline.vue';
79
84
  import SystemMessageRenderer from './SystemMessageRenderer.vue';
80
85
  import ToolApprovalRenderer from './ToolApprovalRenderer.vue';
86
+ import MessageAttachments from './MessageAttachments.vue';
81
87
  import { RESERVED_SYSTEM_MESSAGE_CONTENT } from '../composables/agentStore/constants';
82
88
  import { useAgentStore } from '../composables/useAgentStore';
83
89
  import { useAdminforth } from '@/adminforth';
@@ -110,6 +116,13 @@
110
116
 
111
117
  const isUserMessage = computed(() => props.message.role === 'user');
112
118
 
119
+ // The edited message shows the images of the composer, as its text follows the input.
120
+ const shownAttachments = computed<Array<{ url: string }>>(() =>
121
+ isBeingEditedMessage.value
122
+ ? agentStore.attachments
123
+ : props.message.metadata?.attachments ?? []
124
+ );
125
+
113
126
  const copyableText = computed(() =>
114
127
  (props.message.parts ?? [])
115
128
  .filter((part: any) => part.type === 'text' && !checkIfMessageSystemMessage(part.text ?? ''))
@@ -130,7 +143,7 @@
130
143
  // never shift the chat or change its scroll height.
131
144
  const reservesActionsRow = computed(() =>
132
145
  shouldBeShownWhileEditing.value
133
- && Boolean(copyableText.value.trim())
146
+ && (Boolean(copyableText.value.trim()) || shownAttachments.value.length > 0)
134
147
  && (!isUserMessage.value || agentStore.editingEnabled)
135
148
  );
136
149
 
@@ -44,10 +44,49 @@ export interface IMessage {
44
44
  parts: IPart[];
45
45
  }
46
46
 
47
+ /** Limits of image attachments, set by the backend; null when attachments are off. */
48
+ export interface IAttachmentsConfig {
49
+ maxPerMessage: number;
50
+ mimeTypes: string[];
51
+ }
52
+
53
+ /** Meta of the chat surface injection, set by the plugin backend. */
54
+ export interface IChatSurfaceMeta {
55
+ pluginInstanceId: string;
56
+ modes: Array<{
57
+ name: string;
58
+ }>;
59
+ defaultModeName: string | null;
60
+ stickByDefault: boolean;
61
+ hasAudioAdapter: boolean;
62
+ editingEnabled: boolean;
63
+ attachments: IAttachmentsConfig | null;
64
+ }
65
+
66
+ /** An image in the composer: a new file to upload, or one the edited message already has. */
67
+ export interface IComposerAttachment {
68
+ id: string;
69
+ url: string;
70
+ file?: File;
71
+ filePath?: string;
72
+ }
73
+
74
+ export interface IMessageAttachment {
75
+ filePath: string;
76
+ url: string;
77
+ }
78
+
79
+ /** An image sent to the agent; the token proves it was uploaded to this session. */
80
+ export interface IAttachmentRef {
81
+ filePath: string;
82
+ token?: string;
83
+ }
84
+
47
85
  export interface IStoredMessage {
48
86
  role: 'user' | 'assistant' | 'system';
49
87
  text: string;
50
88
  turnId?: string;
89
+ attachments?: IMessageAttachment[];
51
90
  }
52
91
 
53
92
  export interface IAgentSession {
@@ -1,5 +1,15 @@
1
+ import { i18nInstance } from '@/i18n';
1
2
  import { IMessage, IPart } from "./types";
2
3
 
4
+ export function getErrorMessage(error: unknown): string {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
7
+
8
+ /** Translates outside of components, where `$t` is not available. */
9
+ export function t(key: string, values: Record<string, unknown> = {}): string {
10
+ return i18nInstance?.global.t(key, values) ?? key;
11
+ }
12
+
3
13
  export function remToPx(rem: number): number {
4
14
  const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
5
15
  return rem * rootFontSize;
@@ -0,0 +1,73 @@
1
+ import type { StorageAdapter } from "adminforth";
2
+ import type { IImageAttachmentsOptions } from "../types.js";
3
+ /**
4
+ * `additional_kwargs` keys of a user message with images: the storage paths and the time the
5
+ * message was sent. The paths, not the images, stay in the agent state, so checkpoints (each
6
+ * one keeps the whole history) do not repeat the base64 of every image.
7
+ */
8
+ export declare const ATTACHMENTS_KWARG = "adminforthAttachments";
9
+ export declare const ATTACHMENTS_SENT_AT_KWARG = "adminforthAttachmentsSentAt";
10
+ export declare function getAttachmentPaths(message: {
11
+ additional_kwargs?: Record<string, unknown>;
12
+ }): string[] | undefined;
13
+ export declare const VIEW_IMAGE_TOOL_NAME = "view_image";
14
+ /**
15
+ * An image goes to the model as base64, a third bigger than the file: 3.75 MB becomes 5 MB, the
16
+ * smallest per-image limit of the providers (Anthropic). A bigger image would fail every model
17
+ * call while it is shown. The upload URL is bound to the size, so the size the client names is
18
+ * the size of the stored file.
19
+ */
20
+ export declare const MAX_IMAGE_SIZE_MB = 3.75;
21
+ export declare const BYTES_IN_MB: number;
22
+ export declare const IMAGE_EXTENSIONS: string[];
23
+ export declare const ATTACHMENT_TOKEN_TYPE = "agent-attachment";
24
+ export declare const PREVIEW_URL_EXPIRES_IN_SECONDS = 1800;
25
+ export type ImageAttachmentsLimits = Required<IImageAttachmentsOptions>;
26
+ export declare const DEFAULT_IMAGE_ATTACHMENTS_LIMITS: ImageAttachmentsLimits;
27
+ /** The `imageAttachments` options with the defaults for the ones not set; each is a whole number from 1. */
28
+ export declare function resolveImageAttachmentsLimits(options?: IImageAttachmentsOptions): ImageAttachmentsLimits;
29
+ /** Limits of the chat composer, passed to the frontend so both sides share them. */
30
+ export declare function getAttachmentsFrontendConfig(limits: ImageAttachmentsLimits): {
31
+ maxPerMessage: number;
32
+ mimeTypes: string[];
33
+ };
34
+ export declare const MISSING_IMAGE_TEXT = "[An image of this message is no longer available]";
35
+ export declare const hiddenImageText: (filePath: string) => string;
36
+ export declare const viewedBelowImageText: (filePath: string) => string;
37
+ export declare const viewedImageLabel: (filePath: string) => string;
38
+ /**
39
+ * What view_image loaded, kept as the artifact of its tool result: the attachments middleware
40
+ * reads it there, the text the model gets is separate.
41
+ */
42
+ export type ViewImageArtifact = {
43
+ filePaths: string[];
44
+ viewedAt: string;
45
+ };
46
+ /** The part of the UploadPlugin (@adminforth/upload) the agent relies on. */
47
+ export type UploadPlugin = {
48
+ resourceConfig: {
49
+ resourceId: string;
50
+ };
51
+ pluginOptions: {
52
+ pathColumnName: string;
53
+ allowedFileExtensions?: string[];
54
+ storageAdapter: StorageAdapter;
55
+ preview?: {
56
+ previewUrl?: (input: {
57
+ filePath: string;
58
+ }) => string;
59
+ };
60
+ };
61
+ getUploadUrl(input: {
62
+ filename: string;
63
+ contentType: string;
64
+ size: number;
65
+ }): Promise<{
66
+ uploadUrl: string;
67
+ uploadExtraParams?: Record<string, string>;
68
+ contentType: string;
69
+ filePath: string;
70
+ }>;
71
+ markKeyForDeletion(filePath: string): Promise<void>;
72
+ markKeyForNotDeletion(filePath: string): Promise<void>;
73
+ };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `additional_kwargs` keys of a user message with images: the storage paths and the time the
3
+ * message was sent. The paths, not the images, stay in the agent state, so checkpoints (each
4
+ * one keeps the whole history) do not repeat the base64 of every image.
5
+ */
6
+ export const ATTACHMENTS_KWARG = "adminforthAttachments";
7
+ export const ATTACHMENTS_SENT_AT_KWARG = "adminforthAttachmentsSentAt";
8
+ export function getAttachmentPaths(message) {
9
+ var _a;
10
+ return (_a = message.additional_kwargs) === null || _a === void 0 ? void 0 : _a[ATTACHMENTS_KWARG];
11
+ }
12
+ export const VIEW_IMAGE_TOOL_NAME = "view_image";
13
+ /**
14
+ * An image goes to the model as base64, a third bigger than the file: 3.75 MB becomes 5 MB, the
15
+ * smallest per-image limit of the providers (Anthropic). A bigger image would fail every model
16
+ * call while it is shown. The upload URL is bound to the size, so the size the client names is
17
+ * the size of the stored file.
18
+ */
19
+ export const MAX_IMAGE_SIZE_MB = 3.75;
20
+ export const BYTES_IN_MB = 1024 * 1024;
21
+ const IMAGE_MIME_TYPES_BY_EXTENSION = {
22
+ png: "image/png",
23
+ jpg: "image/jpeg",
24
+ jpeg: "image/jpeg",
25
+ webp: "image/webp",
26
+ };
27
+ export const IMAGE_EXTENSIONS = Object.keys(IMAGE_MIME_TYPES_BY_EXTENSION);
28
+ // a token binds the path of an uploaded image to the session it was uploaded to
29
+ export const ATTACHMENT_TOKEN_TYPE = "agent-attachment";
30
+ // signed preview urls of private storages; the chat asks for fresh ones when they expire
31
+ export const PREVIEW_URL_EXPIRES_IN_SECONDS = 1800;
32
+ export const DEFAULT_IMAGE_ATTACHMENTS_LIMITS = {
33
+ maxPerMessage: 5,
34
+ visibleMinutes: 30,
35
+ maxVisible: 5,
36
+ };
37
+ /** The `imageAttachments` options with the defaults for the ones not set; each is a whole number from 1. */
38
+ export function resolveImageAttachmentsLimits(options = {}) {
39
+ var _a, _b, _c;
40
+ const limits = {
41
+ maxPerMessage: (_a = options.maxPerMessage) !== null && _a !== void 0 ? _a : DEFAULT_IMAGE_ATTACHMENTS_LIMITS.maxPerMessage,
42
+ visibleMinutes: (_b = options.visibleMinutes) !== null && _b !== void 0 ? _b : DEFAULT_IMAGE_ATTACHMENTS_LIMITS.visibleMinutes,
43
+ maxVisible: (_c = options.maxVisible) !== null && _c !== void 0 ? _c : DEFAULT_IMAGE_ATTACHMENTS_LIMITS.maxVisible,
44
+ };
45
+ for (const [name, value] of Object.entries(limits)) {
46
+ if (!Number.isInteger(value) || value < 1) {
47
+ throw new Error(`imageAttachments.${name} must be a whole number from 1, got ${value}`);
48
+ }
49
+ }
50
+ return limits;
51
+ }
52
+ /** Limits of the chat composer, passed to the frontend so both sides share them. */
53
+ export function getAttachmentsFrontendConfig(limits) {
54
+ return {
55
+ maxPerMessage: limits.maxPerMessage,
56
+ mimeTypes: [...new Set(Object.values(IMAGE_MIME_TYPES_BY_EXTENSION))],
57
+ };
58
+ }
59
+ // notes the model gets in place of images which are not shown
60
+ export const MISSING_IMAGE_TEXT = "[An image of this message is no longer available]";
61
+ export const hiddenImageText = (filePath) => `[Image with id "${filePath}" is not shown any more. Call ${VIEW_IMAGE_TOOL_NAME} with this whole id to see it again.]`;
62
+ export const viewedBelowImageText = (filePath) => `[Image with id "${filePath}" is shown further below, loaded again with ${VIEW_IMAGE_TOOL_NAME}.]`;
63
+ export const viewedImageLabel = (filePath) => `[Image with id "${filePath}", loaded with ${VIEW_IMAGE_TOOL_NAME}]`;
@@ -21,6 +21,19 @@ export type PendingInterrupt = {
21
21
  /** The pending tool calls, normalized so they can be described to the user. */
22
22
  requests: ApprovalRequest[];
23
23
  };
24
+ /**
25
+ * An image sent with a user message. `token` proves the file was uploaded through this
26
+ * session's upload URL; it may be omitted only for a file the edited turn already has.
27
+ */
28
+ export type AttachmentRef = {
29
+ filePath: string;
30
+ token?: string;
31
+ };
32
+ /** An image of a stored turn: its storage path and a signed url to show it. */
33
+ export type TurnAttachment = {
34
+ filePath: string;
35
+ url: string;
36
+ };
24
37
  export type BaseAgentTurnInput = {
25
38
  prompt: string;
26
39
  sessionId: string;
@@ -29,6 +42,7 @@ export type BaseAgentTurnInput = {
29
42
  currentPage?: CurrentPageContext;
30
43
  chatSurface?: string;
31
44
  adminPublicOrigin?: string;
45
+ attachments?: AttachmentRef[];
32
46
  abortSignal?: AbortSignal;
33
47
  adminUser: AdminUser;
34
48
  };
@@ -85,6 +99,8 @@ export type HandleEditTurnInput = TextAgentTurnInput & {
85
99
  export type AgentMessage = {
86
100
  role: "user";
87
101
  content: string;
102
+ /** Storage paths of attached images; turned into image blocks only for the model call. */
103
+ attachments: string[];
88
104
  };
89
105
  /**
90
106
  * Normalized unit of a streamed agent turn. The LLM port converts the raw
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AdminForthResource, IAdminForth, IHttpServer } from "adminforth";
1
+ import type { IAdminForth, IHttpServer } from "adminforth";
2
2
  import { AdminForthPlugin } from "adminforth";
3
3
  import type { PluginOptions } from './types.js';
4
4
  export type { AgentEvent, AgentEventEmitter } from "./domain/agentEvents.js";
@@ -8,6 +8,8 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
8
8
  private agentSystemPrompt;
9
9
  private checkpointer;
10
10
  private sessionStore;
11
+ private turnAttachments;
12
+ private imageAttachmentsLimits;
11
13
  private steerBuffer;
12
14
  private runTurnUseCase;
13
15
  private speechTurnService;
@@ -15,7 +17,7 @@ export default class AdminForthAgentPlugin extends AdminForthPlugin {
15
17
  private getCheckpointer;
16
18
  constructor(options: PluginOptions);
17
19
  modifyGlobalConfig(adminforth: IAdminForth): Promise<void>;
18
- validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
20
+ validateConfigAfterDiscover(adminforth: IAdminForth): void;
19
21
  instanceUniqueRepresentation(pluginOptions: any): string;
20
22
  setupEndpoints(server: IHttpServer): void;
21
23
  }
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
+ }