@adminforth/agent 3.3.0 → 3.5.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 +75 -0
  16. package/dist/domain/imageAttachments.js +71 -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 +14 -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 +17 -0
  24. package/dist/llm/middleware/attachmentsMiddleware.js +148 -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 +23 -0
  32. package/dist/tools/viewImage.js +108 -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 +38 -0
  38. package/package.json +3 -3
@@ -0,0 +1,148 @@
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 { getViewedImages } from "../../tools/viewImage.js";
13
+ import { getErrorMessage } from "../../shared/errors.js";
14
+ import { ATTACHMENTS_SENT_AT_KWARG, MISSING_IMAGE_TEXT, getAttachmentPaths, hiddenImagesText, viewedBelowImagesText, viewedImageLabel, } from "../../domain/imageAttachments.js";
15
+ /**
16
+ * The images to show now, by the message they are shown in. All the images view_image loaded in
17
+ * this turn, once each, after its latest result that has them. Besides them the kept ones: sent in
18
+ * a message or kept by an earlier view_image for `visibleMinutes`, the latest `maxVisible` only
19
+ * (more when the last images were a view_image which kept more); one loaded in this turn keeps its
20
+ * place among them but is shown after the view_image result.
21
+ */
22
+ function getShownImages(messages, now, turnId, { visibleMinutes, maxVisible }) {
23
+ var _a, _b, _c, _d;
24
+ const viewedNow = new Map();
25
+ const kept = [];
26
+ // a view_image which kept more than maxVisible widens the buffer until the next images
27
+ let bufferSize = maxVisible;
28
+ for (const message of messages) {
29
+ const filePaths = getAttachmentPaths(message);
30
+ const sentAt = (_a = message.additional_kwargs) === null || _a === void 0 ? void 0 : _a[ATTACHMENTS_SENT_AT_KWARG];
31
+ if (filePaths && sentAt) {
32
+ kept.push(...filePaths.map((filePath) => ({ filePath, message, at: Date.parse(sentAt) })));
33
+ bufferSize = maxVisible;
34
+ }
35
+ const viewed = getViewedImages(message);
36
+ if ((viewed === null || viewed === void 0 ? void 0 : viewed.turnId) === turnId) {
37
+ viewed.filePaths.forEach((filePath) => viewedNow.set(filePath, message));
38
+ bufferSize = maxVisible;
39
+ }
40
+ else if (viewed) {
41
+ const keptFilePaths = (_b = viewed.keptFilePaths) !== null && _b !== void 0 ? _b : viewed.filePaths;
42
+ kept.push(...keptFilePaths.map((filePath) => ({ filePath, message, at: Date.parse(viewed.viewedAt) })));
43
+ bufferSize = Math.max(maxVisible, keptFilePaths.length);
44
+ }
45
+ }
46
+ const visibleMs = visibleMinutes * 60000;
47
+ const latestByFilePath = new Map();
48
+ for (const { filePath, message, at } of kept) {
49
+ if (now - at < visibleMs && at > ((_d = (_c = latestByFilePath.get(filePath)) === null || _c === void 0 ? void 0 : _c.at) !== null && _d !== void 0 ? _d : 0)) {
50
+ latestByFilePath.set(filePath, { message, at });
51
+ }
52
+ }
53
+ const shown = new Map();
54
+ const show = (filePath, message) => { var _a; return shown.set(message, [...((_a = shown.get(message)) !== null && _a !== void 0 ? _a : []), filePath]); };
55
+ [...latestByFilePath]
56
+ .sort(([, a], [, b]) => b.at - a.at)
57
+ .slice(0, bufferSize)
58
+ .filter(([filePath]) => !viewedNow.has(filePath))
59
+ .forEach(([filePath, { message }]) => show(filePath, message));
60
+ viewedNow.forEach((message, filePath) => show(filePath, message));
61
+ return shown;
62
+ }
63
+ /**
64
+ * `wrapModelCall` middleware that turns the attachment paths of user messages into image
65
+ * blocks right before the model call. Placed last, so the images reach only the model and
66
+ * not the debug trace or the summarization of other middleware. Created per turn, so an
67
+ * image is loaded from the storage once for all model calls of the turn.
68
+ *
69
+ * An image is shown for `visibleMinutes` after its message is sent or a view_image keeps it, at most
70
+ * `maxVisible` at once; the other images of a message become one note with their ids and are not
71
+ * read at all. Images the model loads again with view_image are all shown for the answer of that
72
+ * turn and follow the tool results of that step as one user message: a user message between tool results is refused by providers, and provider
73
+ * adapters may send only the messages after their previous response (OpenAI previous_response_id),
74
+ * so a change in an earlier message would not reach the model. An image which can not be read
75
+ * (deleted from the storage, the storage changed) becomes a note too, so one broken file does not
76
+ * fail every next turn of the session.
77
+ */
78
+ export function createAttachmentsMiddleware(loadAsDataUrl, limits) {
79
+ const dataUrls = new Map();
80
+ const load = (filePath) => {
81
+ if (!dataUrls.has(filePath)) {
82
+ dataUrls.set(filePath, loadAsDataUrl(filePath).catch((error) => {
83
+ logger.warn(`Agent attachment "${filePath}" can not be read, the model gets a note instead: ${getErrorMessage(error)}`);
84
+ return null;
85
+ }));
86
+ }
87
+ return dataUrls.get(filePath);
88
+ };
89
+ const imageBlock = (filePath) => __awaiter(this, void 0, void 0, function* () {
90
+ const dataUrl = yield load(filePath);
91
+ return dataUrl
92
+ ? { type: "image_url", image_url: { url: dataUrl } }
93
+ : { type: "text", text: MISSING_IMAGE_TEXT };
94
+ });
95
+ return createMiddleware({
96
+ name: "AttachmentsMiddleware",
97
+ wrapModelCall(request, handler) {
98
+ return __awaiter(this, void 0, void 0, function* () {
99
+ var _a;
100
+ if (!request.messages.some((message) => getAttachmentPaths(message) || getViewedImages(message))) {
101
+ return handler(request);
102
+ }
103
+ const shownImages = getShownImages(request.messages, Date.now(), request.runtime.context.turnId, limits);
104
+ // images loaded again are shown after the tool results, their own message only points there
105
+ const viewedImages = new Set([...shownImages]
106
+ .filter(([message]) => getViewedImages(message))
107
+ .flatMap(([, filePaths]) => filePaths));
108
+ const messages = [];
109
+ let viewedInStep = [];
110
+ for (const [index, message] of request.messages.entries()) {
111
+ const shown = (_a = shownImages.get(message)) !== null && _a !== void 0 ? _a : [];
112
+ const filePaths = getAttachmentPaths(message);
113
+ if (filePaths) {
114
+ const images = yield Promise.all(filePaths.filter((filePath) => shown.includes(filePath)).map(imageBlock));
115
+ const notShown = filePaths.filter((filePath) => !shown.includes(filePath));
116
+ const viewedBelow = notShown.filter((filePath) => viewedImages.has(filePath));
117
+ const hidden = notShown.filter((filePath) => !viewedImages.has(filePath));
118
+ messages.push(new HumanMessage({
119
+ content: [
120
+ ...(message.content ? [{ type: "text", text: message.content }] : []),
121
+ ...images,
122
+ ...(viewedBelow.length ? [{ type: "text", text: viewedBelowImagesText(viewedBelow) }] : []),
123
+ ...(hidden.length ? [{ type: "text", text: hiddenImagesText(hidden) }] : []),
124
+ ],
125
+ }));
126
+ continue;
127
+ }
128
+ messages.push(message);
129
+ if (getViewedImages(message)) {
130
+ viewedInStep.push(...shown);
131
+ }
132
+ const next = request.messages[index + 1];
133
+ if (viewedInStep.length > 0 && !(next && ToolMessage.isInstance(next))) {
134
+ const blocks = yield Promise.all(viewedInStep.map((filePath) => __awaiter(this, void 0, void 0, function* () {
135
+ return [
136
+ { type: "text", text: viewedImageLabel(filePath) },
137
+ yield imageBlock(filePath),
138
+ ];
139
+ })));
140
+ messages.push(new HumanMessage({ content: blocks.flat() }));
141
+ viewedInStep = [];
142
+ }
143
+ }
144
+ return handler(Object.assign(Object.assign({}, request), { messages }));
145
+ });
146
+ },
147
+ });
148
+ }
@@ -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
+ }
@@ -3,10 +3,10 @@ export declare function createNavigateUserTool(): import("langchain").DynamicStr
3
3
  targetPath: z.ZodOptional<z.ZodString>;
4
4
  resourceId: z.ZodOptional<z.ZodString>;
5
5
  mode: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
6
+ create: "create";
6
7
  list: "list";
7
8
  show: "show";
8
9
  edit: "edit";
9
- create: "create";
10
10
  }>>>;
11
11
  recordId: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
12
12
  filters: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -23,7 +23,7 @@ export declare function createNavigateUserTool(): import("langchain").DynamicStr
23
23
  }, z.core.$strip>>;
24
24
  query: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>>>;
25
25
  }, z.core.$strip>, {
26
- mode: "list" | "show" | "edit" | "create";
26
+ mode: "create" | "list" | "show" | "edit";
27
27
  targetPath?: string | undefined;
28
28
  resourceId?: string | undefined;
29
29
  recordId?: string | number | undefined;
@@ -40,7 +40,7 @@ export declare function createNavigateUserTool(): import("langchain").DynamicStr
40
40
  }, {
41
41
  targetPath?: string | undefined;
42
42
  resourceId?: string | undefined;
43
- mode?: "list" | "show" | "edit" | "create" | undefined;
43
+ mode?: "create" | "list" | "show" | "edit" | undefined;
44
44
  recordId?: string | number | undefined;
45
45
  filters?: {
46
46
  column: string;
@@ -41,6 +41,7 @@ const TOOL_LABELS = {
41
41
  create_record: ({ resourceLabel }) => `Create ${resourceLabel}`,
42
42
  update_record: ({ resourceLabel }) => `Update ${resourceLabel}`,
43
43
  delete_record: ({ resourceLabel }) => `Delete ${resourceLabel}`,
44
+ view_image: () => "Look at an earlier image",
44
45
  };
45
46
  /** Human-readable label of a tool call for the processing timeline; undefined for tools without one. */
46
47
  export function formatToolCall(adminforth, toolName, inputs) {
@@ -0,0 +1,23 @@
1
+ import { type BaseMessage } from "langchain";
2
+ import { z } from "zod";
3
+ import { type ImageAttachmentsLimits, type ViewImageArtifact } from "../domain/imageAttachments.js";
4
+ /** What a view_image result loaded; a failed call (bad arguments, tool off) has no artifact. */
5
+ export declare function getViewedImages(message: BaseMessage): ViewImageArtifact | null;
6
+ /**
7
+ * Shows again images of earlier user messages, once per answer: the model has to pick all the
8
+ * likely messages at once and not search them one call after another. An id loads all images of
9
+ * its message, the model can not tell which image of a message holds what it needs. Messages go in
10
+ * the order of the ids, the most likely first, while they fit into `maxViewedPerTurn` images. The
11
+ * loaded images go to the artifact of the tool result: the attachments middleware shows all of
12
+ * them for the answer of this turn, and the kept ones for a while after it.
13
+ */
14
+ export declare function createViewImageTool({ visibleMinutes, maxVisible, maxViewedPerTurn }: ImageAttachmentsLimits): import("langchain").DynamicStructuredTool<z.ZodObject<{
15
+ imageIds: z.ZodArray<z.ZodString>;
16
+ keepImageIds: z.ZodArray<z.ZodString>;
17
+ }, z.core.$strip>, {
18
+ imageIds: string[];
19
+ keepImageIds: string[];
20
+ }, {
21
+ imageIds: string[];
22
+ keepImageIds: string[];
23
+ }, [string, ViewImageArtifact], unknown, "view_image">;
@@ -0,0 +1,108 @@
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 path from "path";
11
+ import { ToolMessage, tool } from "langchain";
12
+ import { z } from "zod";
13
+ import { VIEW_IMAGE_TOOL_NAME, getAttachmentPaths, } from "../domain/imageAttachments.js";
14
+ /**
15
+ * The storage path of the image the model means. Models tend to pass only the file name of the
16
+ * id from the note, with or without the extension, so a unique file name is accepted too.
17
+ */
18
+ function resolveImagePath(filePaths, imageId) {
19
+ if (filePaths.includes(imageId)) {
20
+ return imageId;
21
+ }
22
+ const byFileName = filePaths.filter((filePath) => {
23
+ const { base, name } = path.posix.parse(filePath);
24
+ return imageId === base || imageId === name;
25
+ });
26
+ return byFileName.length === 1 ? byFileName[0] : null;
27
+ }
28
+ /** What a view_image result loaded; a failed call (bad arguments, tool off) has no artifact. */
29
+ export function getViewedImages(message) {
30
+ var _a;
31
+ return ToolMessage.isInstance(message) && message.name === VIEW_IMAGE_TOOL_NAME
32
+ ? (_a = message.artifact) !== null && _a !== void 0 ? _a : null
33
+ : null;
34
+ }
35
+ /**
36
+ * Shows again images of earlier user messages, once per answer: the model has to pick all the
37
+ * likely messages at once and not search them one call after another. An id loads all images of
38
+ * its message, the model can not tell which image of a message holds what it needs. Messages go in
39
+ * the order of the ids, the most likely first, while they fit into `maxViewedPerTurn` images. The
40
+ * loaded images go to the artifact of the tool result: the attachments middleware shows all of
41
+ * them for the answer of this turn, and the kept ones for a while after it.
42
+ */
43
+ export function createViewImageTool({ visibleMinutes, maxVisible, maxViewedPerTurn }) {
44
+ const viewImageSchema = z.object({
45
+ imageIds: z
46
+ .array(z.string())
47
+ .min(1)
48
+ .max(maxViewedPerTurn)
49
+ .describe("Ids copied from the notes shown in place of the images, never made up; the most likely message first."),
50
+ keepImageIds: z
51
+ .array(z.string())
52
+ .max(maxViewedPerTurn)
53
+ .describe(`Ids out of imageIds to keep seeing in the next messages: the ones the conversation is about, usually up to ${maxVisible}. More are kept only until the next images. Empty when none is needed later.`),
54
+ });
55
+ return tool((_a, runtime_1) => __awaiter(this, [_a, runtime_1], void 0, function* ({ imageIds, keepImageIds }, runtime) {
56
+ // the agent passes its state and its context to every tool call next to the run config
57
+ const { state, context } = runtime;
58
+ const viewedAt = new Date().toISOString();
59
+ if (state.messages.some((message) => { var _a; return ((_a = getViewedImages(message)) === null || _a === void 0 ? void 0 : _a.turnId) === context.turnId; })) {
60
+ return [
61
+ JSON.stringify({
62
+ error: "ALREADY_VIEWED",
63
+ message: "This answer already loaded images. Answer from them, or ask the user which images matter or to send them again.",
64
+ }, null, 2),
65
+ { filePaths: [], keptFilePaths: [], turnId: context.turnId, viewedAt },
66
+ ];
67
+ }
68
+ const imagesByMessage = state.messages.flatMap((message) => {
69
+ const filePaths = getAttachmentPaths(message);
70
+ return filePaths ? [filePaths] : [];
71
+ });
72
+ const filePathsInHistory = [...new Set(imagesByMessage.flat())];
73
+ const resolve = (imageId) => resolveImagePath(filePathsInHistory, imageId);
74
+ const resolved = imageIds.map((imageId) => ({ imageId, filePath: resolve(imageId) }));
75
+ const notFound = resolved.filter(({ filePath }) => !filePath).map(({ imageId }) => imageId);
76
+ // the messages of the found images, in the order of the ids
77
+ const groups = [...new Set(resolved.flatMap(({ filePath }) => (filePath ? [imagesByMessage.find((filePaths) => filePaths.includes(filePath))] : [])))];
78
+ let filePaths = [];
79
+ const overLimit = [];
80
+ for (const group of groups) {
81
+ const withGroup = [...new Set([...filePaths, ...group])];
82
+ if (withGroup.length > maxViewedPerTurn) {
83
+ overLimit.push(...group.filter((filePath) => !filePaths.includes(filePath)));
84
+ }
85
+ else {
86
+ filePaths = withGroup;
87
+ }
88
+ }
89
+ const keptFilePaths = [...new Set(keepImageIds.map(resolve))].filter((filePath) => (filePath !== null && filePaths.includes(filePath)));
90
+ return [
91
+ JSON.stringify({ shown: filePaths, kept: keptFilePaths, notFound, overLimit }, null, 2),
92
+ { filePaths, keptFilePaths, turnId: context.turnId, viewedAt },
93
+ ];
94
+ }), {
95
+ name: VIEW_IMAGE_TOOL_NAME,
96
+ description: [
97
+ "Shows again images of earlier messages which are replaced with notes, by the ids written in these notes.",
98
+ "Call it before answering anything that depends on what such an image shows: your earlier replies about it are a retelling, not a source, and miss details.",
99
+ "Don't call it for images you see in messages, they are already in full quality, and for a message with new images and no text, it is about the new images only.",
100
+ "Pick the messages by the conversation: your reply right after a user message is about the images of that message.",
101
+ "Call it once per answer, a second call is refused: pass one id of every message whose texts or replies may match the request, the most likely first; an id loads all images of its message.",
102
+ `It loads ${maxViewedPerTurn} images at most; messages over it are not loaded and are listed in overLimit, if the loaded ones are not enough ask the user which images matter or to send them again.`,
103
+ `You see them for this answer and keep seeing the ones in keepImageIds for ${visibleMinutes} minutes.`,
104
+ ].join(" "),
105
+ schema: viewImageSchema,
106
+ responseFormat: "content_and_artifact",
107
+ });
108
+ }