@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
@@ -1,12 +1,12 @@
1
1
  import { defineStore } from 'pinia';
2
- import { IAgentSession, IApprovalDescription, ISessionsListItem } from '../types';
2
+ import { IAgentSession, IApprovalDescription, IAttachmentRef, IComposerAttachment, ISessionsListItem } from '../types';
3
3
  import { ref, nextTick, computed, watch, onMounted } from 'vue';
4
4
  import { useRouter } from 'vue-router';
5
5
  import { useAdminforth } from '@/adminforth';
6
6
  import { useCoreStore } from '@/stores/core';
7
7
  import { useAgentTransitions } from './useAgentTransitions';
8
8
  import { useWindowSize } from '@vueuse/core';
9
- import { remToPx, pxToRem } from '../utils';
9
+ import { remToPx, pxToRem, getErrorMessage, t } from '../utils';
10
10
  import {
11
11
  type AgentMode,
12
12
  DEFAULT_CHAT_WIDTH,
@@ -19,6 +19,7 @@ import { createAgentChatManager } from './agentStore/useAgentChat';
19
19
  import { createAgentPlaceholderController } from './agentStore/useAgentPlaceholder';
20
20
  import { createAgentSessionManager } from './agentStore/useAgentSessions';
21
21
  import { createAgentSteerQueue } from './agentStore/useAgentSteerQueue';
22
+ import { createAgentAttachments } from './agentStore/useAgentAttachments';
22
23
  import { STEER_PERSIST_PREFIX } from './agentStore/constants';
23
24
 
24
25
  export const useAgentStore = defineStore('agent', () => {
@@ -42,15 +43,17 @@ export const useAgentStore = defineStore('agent', () => {
42
43
  const editingMessageId = ref<string | null>(null);
43
44
  const editingMessageTurnId = ref<string | null>(null);
44
45
  const savedUserInput = ref('');
46
+ const savedAttachments = ref<IComposerAttachment[]>([]);
45
47
  const isEditingMessage = computed(() => editingMessageId.value !== null);
46
48
  const lastMessage = ref('');
49
+ const lastAttachments = ref<IAttachmentRef[]>([]);
50
+ const composerAttachments = createAgentAttachments({ alert: adminforth.alert });
51
+ const hasAttachments = computed(() => composerAttachments.attachments.value.length > 0);
47
52
  const isTeleportedToBody = ref(false);
48
53
  const setIsTeleportedToBody = (isTeleported: boolean) => {
49
54
  isTeleportedToBody.value = isTeleported;
50
55
  }
51
56
  const coreStore = useCoreStore();
52
- const appRoot = ref<HTMLElement | null>(null);
53
- const header = ref<HTMLElement | null>(null);
54
57
  const lastSessionId = ref<string | null>(null);
55
58
  const chatWidth = ref(DEFAULT_CHAT_WIDTH);
56
59
  const availableModes = ref<AgentMode[]>([]);
@@ -65,8 +68,10 @@ export const useAgentStore = defineStore('agent', () => {
65
68
  abortCurrentChatRequest,
66
69
  submitToolApproval: submitToolApprovalResponse,
67
70
  sendEditMessage,
71
+ dropChat,
68
72
  } = createAgentChatManager({
69
73
  lastMessage,
74
+ lastAttachments,
70
75
  activeModeName,
71
76
  onOpenPage: openAgentPage,
72
77
  onToolApprovalRequest: addToolApprovalPart,
@@ -162,7 +167,7 @@ export const useAgentStore = defineStore('agent', () => {
162
167
  } catch (error) {
163
168
  if (approvalPart?.data) {
164
169
  approvalPart.data.status = 'pending';
165
- approvalPart.data.error = error instanceof Error ? error.message : String(error);
170
+ approvalPart.data.error = getErrorMessage(error);
166
171
  }
167
172
  console.error('Error submitting tool approval', error);
168
173
  }
@@ -195,6 +200,8 @@ export const useAgentStore = defineStore('agent', () => {
195
200
  const blockCloseOfChat = ref(false);
196
201
  const {
197
202
  sendMessage,
203
+ refreshAttachmentUrls,
204
+ reloadSession,
198
205
  createPreSession,
199
206
  setActiveSession,
200
207
  fetchSessionsList,
@@ -218,9 +225,12 @@ export const useAgentStore = defineStore('agent', () => {
218
225
  isMessageInputBlocked,
219
226
  userMessageInput,
220
227
  lastMessage,
228
+ lastAttachments,
229
+ composerAttachments,
221
230
  blockCloseOfChat,
222
231
  adminforth,
223
232
  setCurrentChat,
233
+ dropChat,
224
234
  restorePendingToolApproval: addToolApprovalPart,
225
235
  });
226
236
 
@@ -252,13 +262,22 @@ export const useAgentStore = defineStore('agent', () => {
252
262
 
253
263
  // Submitting while a turn is active buffers the message (it shows up in the steer
254
264
  // queue, where the user can steer it or let it send); otherwise it sends right away.
265
+ // The queue keeps text only, so a message with images waits for the turn to end.
266
+ // images go with the text chat only, the voice chat has no composer to show them
267
+ const canAttachImages = computed(() => Boolean(composerAttachments.config.value) && !isAudioChatMode.value);
268
+
269
+ const canSubmitUserMessage = computed(() =>
270
+ Boolean(trimmedUserMessage.value || hasAttachments.value)
271
+ && !(isTurnActive.value && hasAttachments.value)
272
+ && !composerAttachments.isUploading.value
273
+ );
274
+
255
275
  function submitUserMessage() {
256
- const message = trimmedUserMessage.value;
257
- if (!message) {
276
+ if (!canSubmitUserMessage.value) {
258
277
  return;
259
278
  }
260
279
  if (isTurnActive.value) {
261
- steerBuffer.enqueue(message);
280
+ steerBuffer.enqueue(trimmedUserMessage.value);
262
281
  userMessageInput.value = '';
263
282
  return;
264
283
  }
@@ -293,6 +312,7 @@ export const useAgentStore = defineStore('agent', () => {
293
312
  watch(activeSessionId, (newVal: string | null) => {
294
313
  // The edited message lives in the outgoing session's chat, so drop edit mode.
295
314
  if (editingMessageId.value !== null) {
315
+ composerAttachments.discardNewFiles();
296
316
  exitEditMode();
297
317
  }
298
318
  if (newVal) {
@@ -336,13 +356,6 @@ export const useAgentStore = defineStore('agent', () => {
336
356
  if (coreStore.isMobile) {
337
357
  setChatWidth(window.innerWidth);
338
358
  }
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
359
  })
347
360
 
348
361
  const isFullScreen = ref(false);
@@ -381,17 +394,6 @@ export const useAgentStore = defineStore('agent', () => {
381
394
  chatWidth.value = pxToRem(width);
382
395
 
383
396
  }
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
397
 
396
398
  function setAvailableModes(modes: AgentMode[], defaultModeName?: string | null) {
397
399
  availableModes.value = modes;
@@ -499,11 +501,13 @@ export const useAgentStore = defineStore('agent', () => {
499
501
  }
500
502
  if (editingMessageId.value === null) {
501
503
  savedUserInput.value = userMessageInput.value ?? '';
504
+ savedAttachments.value = composerAttachments.attachments.value;
502
505
  }
503
506
  const text = getCompiledMessageTextWithSteeredParts(message);
504
507
  editingMessageId.value = messageId;
505
508
  editingMessageTurnId.value = turnId;
506
509
  userMessageInput.value = text;
510
+ composerAttachments.setFromMessage(message.metadata?.attachments ?? []);
507
511
  nextTick(() => focusTextInput());
508
512
  }
509
513
 
@@ -511,6 +515,8 @@ export const useAgentStore = defineStore('agent', () => {
511
515
  function exitEditMode() {
512
516
  userMessageInput.value = savedUserInput.value;
513
517
  savedUserInput.value = '';
518
+ composerAttachments.attachments.value = savedAttachments.value;
519
+ savedAttachments.value = [];
514
520
  editingMessageId.value = null;
515
521
  editingMessageTurnId.value = null;
516
522
  }
@@ -519,6 +525,7 @@ export const useAgentStore = defineStore('agent', () => {
519
525
  if (editingMessageId.value === null) {
520
526
  return;
521
527
  }
528
+ composerAttachments.discardNewFiles();
522
529
  exitEditMode();
523
530
  nextTick(() => focusTextInput());
524
531
  }
@@ -528,19 +535,37 @@ export const useAgentStore = defineStore('agent', () => {
528
535
  return false;
529
536
  }
530
537
  const text = trimmedUserMessage.value;
531
- if (!text) {
538
+ const attachments = composerAttachments.attachments.value;
539
+ if ((!text && attachments.length === 0) || composerAttachments.isUploading.value) {
532
540
  return false;
533
541
  }
534
542
  const messageId = editingMessageId.value;
535
543
  const turnId = editingMessageTurnId.value!;
544
+ const editedMessage = currentChat.value?.messages.find((m: any) => m.id === messageId);
545
+ const lastMessageText = getCompiledMessageTextWithSteeredParts(editedMessage);
546
+ const lastFilePaths = (editedMessage?.metadata?.attachments ?? []).map((attachment: any) => attachment.filePath);
547
+ const isUnchanged = lastMessageText.trim() === text
548
+ && attachments.length === lastFilePaths.length
549
+ && attachments.every((attachment, index) => attachment.filePath === lastFilePaths[index]);
550
+ if (isUnchanged) {
551
+ exitEditMode();
552
+ return false;
553
+ }
554
+ // Upload before leaving edit mode, so a failed upload keeps the edit to retry.
555
+ const uploaded = await composerAttachments.upload(activeSessionId.value!, attachments);
556
+ if (!uploaded) {
557
+ return false;
558
+ }
536
559
  steerBuffer.clear();
537
560
  // Restore the stashed input and leave edit mode before the regeneration streams in.
538
561
  exitEditMode();
539
- const lastMessageText = getCompiledMessageTextWithSteeredParts(currentChat.value?.messages.find((m: any) => m.id === messageId));
540
- if (lastMessageText.trim() === text.trim()) {
541
- return false;
562
+ await sendEditMessage({ messageId, turnId, text, attachments: uploaded });
563
+ // the edit failed (e.g. the message was changed in another tab): the chat in the tab is out
564
+ // of date, so it is replaced with the one the server has
565
+ if (currentChat.value?.status === 'error') {
566
+ adminforth.alert({ message: t('The message could not be edited, the chat is reloaded'), variant: 'warning' });
567
+ await reloadSession(activeSessionId.value!);
542
568
  }
543
- await sendEditMessage({ messageId, turnId, text });
544
569
  return true;
545
570
  }
546
571
 
@@ -651,7 +676,18 @@ export const useAgentStore = defineStore('agent', () => {
651
676
  openAgentPage,
652
677
  setCurrentChatStatus,
653
678
  updateLastAgentMessage,
679
+ //_________-Attachments-_____________
680
+ attachments: composerAttachments.attachments,
681
+ refreshAttachmentUrls: () => refreshAttachmentUrls(activeSessionId.value!),
682
+ attachmentsConfig: composerAttachments.config,
683
+ canAttachImages,
684
+ setAttachmentsConfig: composerAttachments.setConfig,
685
+ isUploadingAttachments: composerAttachments.isUploading,
686
+ addAttachmentFiles: composerAttachments.addFiles,
687
+ removeAttachment: composerAttachments.removeAttachment,
688
+ //___________________________________
654
689
  //_________-Steer queue-_____________
690
+ canSubmitUserMessage,
655
691
  submitUserMessage,
656
692
  isTurnActive,
657
693
  isFinalResponseStreaming,
@@ -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 {
@@ -0,0 +1,22 @@
1
+ <template>
2
+ <div class="af-agent-message-attachments self-end flex flex-wrap justify-end gap-2 mr-4 mb-1">
3
+ <ZoomableImage
4
+ v-for="attachment in attachments"
5
+ :key="attachment.url"
6
+ :src="attachment.url"
7
+ class="max-w-48 max-h-24 rounded-default border border-lightInputBorder dark:border-darkInputBorder"
8
+ @error="agentStore.refreshAttachmentUrls()"
9
+ />
10
+ </div>
11
+ </template>
12
+
13
+ <script setup lang="ts">
14
+ import { ZoomableImage } from '@/afcl';
15
+ import { useAgentStore } from '../composables/useAgentStore';
16
+
17
+ defineProps<{
18
+ attachments: Array<{ url: string }>;
19
+ }>();
20
+
21
+ const agentStore = useAgentStore();
22
+ </script>
@@ -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;
@@ -10,6 +20,11 @@ export function pxToRem(px: number): number {
10
20
  return px / rootFontSize;
11
21
  }
12
22
 
23
+ // #app and the header make room for the docked chat, both exist while ChatSurface is mounted in the header
24
+ export function getLayoutElements(): HTMLElement[] {
25
+ return [document.getElementById('app')!, document.getElementById('af-header-nav')!];
26
+ }
27
+
13
28
 
14
29
  export function getMessageParts(message: IMessage): IPart[] {
15
30
  return message.parts?.length
@@ -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
  }