@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
@@ -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,13 @@
1
+ import { z } from "zod";
2
+ import { type ImageAttachmentsLimits, type ViewImageArtifact } from "../domain/imageAttachments.js";
3
+ /**
4
+ * Shows again images of earlier user messages. The images it found go to the artifact of the
5
+ * tool result: the attachments middleware shows them after the tool results for a while.
6
+ */
7
+ export declare function createViewImageTool({ visibleMinutes, maxVisible }: ImageAttachmentsLimits): import("langchain").DynamicStructuredTool<z.ZodObject<{
8
+ imageIds: z.ZodArray<z.ZodString>;
9
+ }, z.core.$strip>, {
10
+ imageIds: string[];
11
+ }, {
12
+ imageIds: string[];
13
+ }, [string, ViewImageArtifact], unknown, "view_image">;
@@ -0,0 +1,57 @@
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 { 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
+ /**
29
+ * Shows again images of earlier user messages. The images it found go to the artifact of the
30
+ * tool result: the attachments middleware shows them after the tool results for a while.
31
+ */
32
+ export function createViewImageTool({ visibleMinutes, maxVisible }) {
33
+ const viewImageSchema = z.object({
34
+ imageIds: z
35
+ .array(z.string())
36
+ .min(1)
37
+ .max(maxVisible)
38
+ .describe("Ids of the images, from the notes shown in place of them."),
39
+ });
40
+ return tool((_a, runtime_1) => __awaiter(this, [_a, runtime_1], void 0, function* ({ imageIds }, runtime) {
41
+ // the agent passes its state to every tool call next to the run config
42
+ const { messages } = runtime.state;
43
+ const filePathsInHistory = [...new Set(messages.flatMap((message) => { var _a; return (_a = getAttachmentPaths(message)) !== null && _a !== void 0 ? _a : []; }))];
44
+ const resolved = imageIds.map((imageId) => ({ imageId, filePath: resolveImagePath(filePathsInHistory, imageId) }));
45
+ const filePaths = [...new Set(resolved.flatMap(({ filePath }) => (filePath ? [filePath] : [])))];
46
+ const notFound = resolved.filter(({ filePath }) => !filePath).map(({ imageId }) => imageId);
47
+ return [
48
+ JSON.stringify({ shown: filePaths, notFound }, null, 2),
49
+ { filePaths, viewedAt: new Date().toISOString() },
50
+ ];
51
+ }), {
52
+ name: VIEW_IMAGE_TOOL_NAME,
53
+ description: `Shows again images of earlier user messages, which are replaced with notes when they are not shown any more. Call it when the images matter for the answer, with all the ids you need at once. The images are shown after the tool result, for ${visibleMinutes} minutes.`,
54
+ schema: viewImageSchema,
55
+ responseFormat: "content_and_artifact",
56
+ });
57
+ }
@@ -2,14 +2,18 @@ import type { AdminUser, ChatSurfaceAdapter, ChatSurfaceEventSink, ChatSurfaceIn
2
2
  import type { HandleEditTurnInput, HandleSpeechTurnInput, HandleTurnInput, RunAndPersistAgentResponseInput, RunAndPersistAgentResponseResult } from "../../domain/turnTypes.js";
3
3
  import type { PluginOptions } from "../../types.js";
4
4
  import type { ApprovalDescription } from "../../tools/approvalFormatter.js";
5
+ import type { TurnAttachment } from "../../domain/turnTypes.js";
6
+ import type { ImageAttachmentsLimits } from "../../domain/imageAttachments.js";
5
7
  export type SessionTurn = {
6
8
  id: string;
7
9
  prompt: string;
8
10
  response: string;
11
+ attachments: TurnAttachment[];
9
12
  };
10
13
  export type AgentEndpointsContext = {
11
14
  adminforth: IAdminForth;
12
15
  options: PluginOptions;
16
+ imageAttachmentsLimits: ImageAttachmentsLimits;
13
17
  handleTurn(input: HandleTurnInput): Promise<RunAndPersistAgentResponseResult>;
14
18
  handleEditTurn(input: HandleEditTurnInput): Promise<RunAndPersistAgentResponseResult>;
15
19
  handleSpeechTurn(input: HandleSpeechTurnInput): Promise<RunAndPersistAgentResponseResult | null>;
@@ -21,14 +25,29 @@ export type AgentEndpointsContext = {
21
25
  id: string;
22
26
  queued: number;
23
27
  }>;
28
+ createAttachmentUploadUrl(input: {
29
+ sessionId: string;
30
+ filename: string;
31
+ contentType: string;
32
+ size: number;
33
+ adminUser: AdminUser;
34
+ }): Promise<{
35
+ uploadUrl: string;
36
+ uploadExtraParams?: Record<string, string>;
37
+ contentType: string;
38
+ filePath: string;
39
+ previewUrl: string;
40
+ token: string;
41
+ }>;
24
42
  runAndPersistAgentResponse(input: RunAndPersistAgentResponseInput): Promise<RunAndPersistAgentResponseResult>;
25
43
  getSessionTurns(sessionId: string): Promise<SessionTurn[]>;
26
44
  getPendingApprovals(sessionId: string, adminUser: AdminUser): Promise<ApprovalDescription[]>;
27
- createNewTurn(sessionId: string, prompt: string, response?: string): Promise<string>;
45
+ createNewTurn(sessionId: string, prompt: string, attachments?: string[]): Promise<string>;
46
+ deleteSession(sessionId: string): Promise<void>;
28
47
  createSystemTurn(sessionId: string, systemMessage: string): Promise<string>;
29
48
  appendSteerToCurrentTurn(sessionId: string, steerText: string): Promise<void>;
30
49
  handleChatSurfaceMessage(adapter: ChatSurfaceAdapter, incoming: ChatSurfaceIncomingMessage, sink: ChatSurfaceEventSink, request: IAdminForthEndpointHandlerInput): Promise<void>;
31
50
  };
32
- export type CoreEndpointsContext = Pick<AgentEndpointsContext, "options" | "handleTurn" | "handleEditTurn" | "handleSpeechTurn" | "steer">;
33
- export type SessionEndpointsContext = Pick<AgentEndpointsContext, "adminforth" | "options" | "getSessionTurns" | "getPendingApprovals" | "createNewTurn" | "createSystemTurn" | "appendSteerToCurrentTurn">;
51
+ export type CoreEndpointsContext = Pick<AgentEndpointsContext, "options" | "imageAttachmentsLimits" | "handleTurn" | "handleEditTurn" | "handleSpeechTurn" | "steer" | "createAttachmentUploadUrl">;
52
+ export type SessionEndpointsContext = Pick<AgentEndpointsContext, "adminforth" | "options" | "getSessionTurns" | "getPendingApprovals" | "createNewTurn" | "createSystemTurn" | "appendSteerToCurrentTurn" | "deleteSession">;
34
53
  export type ChatSurfaceEndpointsContext = Pick<AgentEndpointsContext, "adminforth" | "options" | "handleChatSurfaceMessage">;
@@ -1,3 +1,38 @@
1
- import type { IHttpServer } from "adminforth";
1
+ import { type IHttpServer } from "adminforth";
2
+ import { z } from "zod";
2
3
  import type { CoreEndpointsContext } from "./context.js";
4
+ import type { ImageAttachmentsLimits } from "../../domain/imageAttachments.js";
5
+ export declare function buildAgentEditBodySchema({ maxPerMessage }: ImageAttachmentsLimits): z.ZodUnion<readonly [z.ZodObject<{
6
+ message: z.ZodString;
7
+ attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
8
+ filePath: z.ZodString;
9
+ token: z.ZodOptional<z.ZodString>;
10
+ }, z.core.$strict>>>;
11
+ sessionId: z.ZodString;
12
+ turnId: z.ZodString;
13
+ mode: z.ZodOptional<z.ZodNullable<z.ZodString>>;
14
+ timeZone: z.ZodOptional<z.ZodString>;
15
+ currentPage: z.ZodOptional<z.ZodObject<{
16
+ path: z.ZodString;
17
+ fullPath: z.ZodString;
18
+ title: z.ZodString;
19
+ url: z.ZodString;
20
+ }, z.core.$strict>>;
21
+ }, z.core.$strict>, z.ZodObject<{
22
+ message: z.ZodString;
23
+ attachments: z.ZodArray<z.ZodObject<{
24
+ filePath: z.ZodString;
25
+ token: z.ZodOptional<z.ZodString>;
26
+ }, z.core.$strict>>;
27
+ sessionId: z.ZodString;
28
+ turnId: z.ZodString;
29
+ mode: z.ZodOptional<z.ZodNullable<z.ZodString>>;
30
+ timeZone: z.ZodOptional<z.ZodString>;
31
+ currentPage: z.ZodOptional<z.ZodObject<{
32
+ path: z.ZodString;
33
+ fullPath: z.ZodString;
34
+ title: z.ZodString;
35
+ url: z.ZodString;
36
+ }, z.core.$strict>>;
37
+ }, z.core.$strict>]>;
3
38
  export declare function setupCoreEndpoints(ctx: CoreEndpointsContext, server: IHttpServer): void;