@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
@@ -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;
@@ -7,20 +7,35 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
+ import { logger } from "adminforth";
10
11
  import { z } from "zod";
11
12
  import { createSseEventEmitter } from "../sse/sseWriter.js";
13
+ import { getErrorMessage } from "../../shared/errors.js";
12
14
  const currentPageContextSchema = z.object({
13
15
  path: z.string(),
14
16
  fullPath: z.string(),
15
17
  title: z.string(),
16
18
  url: z.string(),
17
19
  }).strict();
18
- const agentResponseBodySchema = z.object({
19
- message: z.string(),
20
+ const attachmentRefSchema = z.object({
21
+ filePath: z.string(),
22
+ token: z.string(),
23
+ }).strict();
24
+ function buildAgentResponseBodySchema({ maxPerMessage }) {
25
+ return z.object({
26
+ message: z.string(),
27
+ sessionId: z.string(),
28
+ mode: z.string().nullish(),
29
+ timeZone: z.string().optional(),
30
+ currentPage: currentPageContextSchema.optional(),
31
+ attachments: z.array(attachmentRefSchema).max(maxPerMessage).optional(),
32
+ }).strict();
33
+ }
34
+ const attachmentUploadUrlBodySchema = z.object({
20
35
  sessionId: z.string(),
21
- mode: z.string().nullish(),
22
- timeZone: z.string().optional(),
23
- currentPage: currentPageContextSchema.optional(),
36
+ filename: z.string(),
37
+ contentType: z.string(),
38
+ size: z.number().int().positive(),
24
39
  }).strict();
25
40
  const agentApprovalBodySchema = z.object({
26
41
  sessionId: z.string(),
@@ -31,14 +46,23 @@ const agentSteerBodySchema = z.object({
31
46
  sessionId: z.string(),
32
47
  message: z.string().min(1),
33
48
  }).strict();
34
- const agentEditBodySchema = z.object({
49
+ const agentEditFields = {
35
50
  sessionId: z.string(),
36
51
  turnId: z.string(),
37
- message: z.string().min(1),
38
52
  mode: z.string().nullish(),
39
53
  timeZone: z.string().optional(),
40
54
  currentPage: currentPageContextSchema.optional(),
41
- }).strict();
55
+ };
56
+ // An edited message keeps text, images or both. Written as a union, not a refine: the
57
+ // request schema is checked as JSON Schema, which has no place for a refine.
58
+ export function buildAgentEditBodySchema({ maxPerMessage }) {
59
+ // images the edited turn keeps are sent without a token
60
+ const editAttachmentsSchema = z.array(attachmentRefSchema.partial({ token: true })).max(maxPerMessage);
61
+ return z.union([
62
+ z.object(Object.assign(Object.assign({}, agentEditFields), { message: z.string().min(1), attachments: editAttachmentsSchema.optional() })).strict(),
63
+ z.object(Object.assign(Object.assign({}, agentEditFields), { message: z.string(), attachments: editAttachmentsSchema.min(1) })).strict(),
64
+ ]);
65
+ }
42
66
  // Sent as multipart/form-data (via multer), so every field arrives as a plain string on the wire.
43
67
  // `currentPage` is JSON.stringify'd by the client into a form field and must be parsed back into
44
68
  // an object. Zod -> JSON-Schema conversion cannot represent `.transform()` at all (it throws), so
@@ -67,7 +91,27 @@ const agentSpeechResponseBodySchema = agentSpeechResponseShapeSchema.extend({
67
91
  }
68
92
  }),
69
93
  });
94
+ /**
95
+ * Runs a turn on the already open event stream. A failure before the agent starts (the edited
96
+ * turn was deleted in another tab, no pending approval) comes as an error event: a thrown error
97
+ * would cut the stream, and the client would see only a network error.
98
+ */
99
+ function runOnStream(emit, run) {
100
+ return __awaiter(this, void 0, void 0, function* () {
101
+ try {
102
+ yield run();
103
+ }
104
+ catch (error) {
105
+ const message = getErrorMessage(error);
106
+ logger.error(`Agent turn failed before it started: ${message}`);
107
+ yield emit({ type: "error", error: message });
108
+ yield emit({ type: "finish" });
109
+ }
110
+ });
111
+ }
70
112
  export function setupCoreEndpoints(ctx, server) {
113
+ const agentResponseBodySchema = buildAgentResponseBodySchema(ctx.imageAttachmentsLimits);
114
+ const agentEditBodySchema = buildAgentEditBodySchema(ctx.imageAttachmentsLimits);
71
115
  server.endpoint({
72
116
  method: 'POST',
73
117
  path: `/agent/get-placeholder-messages`,
@@ -97,23 +141,26 @@ export function setupCoreEndpoints(ctx, server) {
97
141
  },
98
142
  request_schema: agentResponseBodySchema,
99
143
  handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, _raw_express_res, abortSignal }) {
100
- var _b;
101
144
  const data = body;
102
145
  const emit = createSseEventEmitter(_raw_express_res, {
103
146
  vercelAiUiMessageStream: true,
104
147
  closeActiveBlockOnToolStart: true,
105
148
  });
106
- yield ctx.handleTurn({
107
- prompt: data.message,
108
- sessionId: data.sessionId,
109
- modeName: data.mode,
110
- userTimeZone: (_b = data.timeZone) !== null && _b !== void 0 ? _b : 'UTC',
111
- currentPage: data.currentPage,
112
- abortSignal,
113
- adminUser: adminUser,
114
- emit,
115
- failureLogMessage: "Agent response streaming failed",
116
- abortLogMessage: "Agent response streaming aborted by the client",
149
+ yield runOnStream(emit, () => {
150
+ var _a;
151
+ return ctx.handleTurn({
152
+ prompt: data.message,
153
+ sessionId: data.sessionId,
154
+ modeName: data.mode,
155
+ userTimeZone: (_a = data.timeZone) !== null && _a !== void 0 ? _a : 'UTC',
156
+ currentPage: data.currentPage,
157
+ attachments: data.attachments,
158
+ abortSignal,
159
+ adminUser: adminUser,
160
+ emit,
161
+ failureLogMessage: "Agent response streaming failed",
162
+ abortLogMessage: "Agent response streaming aborted by the client",
163
+ });
117
164
  });
118
165
  return null;
119
166
  })
@@ -126,24 +173,27 @@ export function setupCoreEndpoints(ctx, server) {
126
173
  },
127
174
  request_schema: agentEditBodySchema,
128
175
  handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, _raw_express_res, abortSignal }) {
129
- var _b;
130
176
  const data = body;
131
177
  const emit = createSseEventEmitter(_raw_express_res, {
132
178
  vercelAiUiMessageStream: true,
133
179
  closeActiveBlockOnToolStart: true,
134
180
  });
135
- yield ctx.handleEditTurn({
136
- prompt: data.message,
137
- turnId: data.turnId,
138
- sessionId: data.sessionId,
139
- modeName: data.mode,
140
- userTimeZone: (_b = data.timeZone) !== null && _b !== void 0 ? _b : 'UTC',
141
- currentPage: data.currentPage,
142
- abortSignal,
143
- adminUser: adminUser,
144
- emit,
145
- failureLogMessage: "Agent message edit streaming failed",
146
- abortLogMessage: "Agent message edit streaming aborted by the client",
181
+ yield runOnStream(emit, () => {
182
+ var _a;
183
+ return ctx.handleEditTurn({
184
+ prompt: data.message,
185
+ turnId: data.turnId,
186
+ sessionId: data.sessionId,
187
+ modeName: data.mode,
188
+ userTimeZone: (_a = data.timeZone) !== null && _a !== void 0 ? _a : 'UTC',
189
+ currentPage: data.currentPage,
190
+ attachments: data.attachments,
191
+ abortSignal,
192
+ adminUser: adminUser,
193
+ emit,
194
+ failureLogMessage: "Agent message edit streaming failed",
195
+ abortLogMessage: "Agent message edit streaming aborted by the client",
196
+ });
147
197
  });
148
198
  return null;
149
199
  })
@@ -161,7 +211,7 @@ export function setupCoreEndpoints(ctx, server) {
161
211
  vercelAiUiMessageStream: true,
162
212
  closeActiveBlockOnToolStart: true,
163
213
  });
164
- yield ctx.handleTurn({
214
+ yield runOnStream(emit, () => ctx.handleTurn({
165
215
  prompt: "",
166
216
  sessionId: data.sessionId,
167
217
  modeName: data.mode,
@@ -171,7 +221,7 @@ export function setupCoreEndpoints(ctx, server) {
171
221
  emit,
172
222
  failureLogMessage: "Agent approval response streaming failed",
173
223
  abortLogMessage: "Agent approval response streaming aborted by the client",
174
- });
224
+ }));
175
225
  return null;
176
226
  })
177
227
  });
@@ -195,6 +245,25 @@ export function setupCoreEndpoints(ctx, server) {
195
245
  return { ok: true, id, queued };
196
246
  })
197
247
  });
248
+ server.endpoint({
249
+ method: 'POST',
250
+ path: `/agent/attachment-upload-url`,
251
+ agent: {
252
+ hiddenFromAgents: true,
253
+ },
254
+ request_schema: attachmentUploadUrlBodySchema,
255
+ handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
256
+ const data = body;
257
+ try {
258
+ return yield ctx.createAttachmentUploadUrl(Object.assign(Object.assign({}, data), { adminUser: adminUser }));
259
+ }
260
+ catch (error) {
261
+ // A disallowed extension or a too large file is the user's input, not a server failure.
262
+ response.setStatus(400);
263
+ return { error: getErrorMessage(error) };
264
+ }
265
+ })
266
+ });
198
267
  server.endpoint({
199
268
  method: 'POST',
200
269
  path: `/agent/speech-response`,
@@ -101,11 +101,12 @@ export function setupSessionEndpoints(ctx, server) {
101
101
  });
102
102
  return messages;
103
103
  }
104
- if (turn.prompt) {
104
+ if (turn.prompt || turn.attachments.length > 0) {
105
105
  messages.push({
106
106
  text: turn.prompt,
107
107
  role: 'user',
108
108
  turnId: turn.id,
109
+ attachments: turn.attachments,
109
110
  });
110
111
  }
111
112
  if (turn.response && turn.response !== "not_finished") {
@@ -171,9 +172,7 @@ export function setupSessionEndpoints(ctx, server) {
171
172
  error: 'Unauthorized'
172
173
  };
173
174
  }
174
- yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).delete(sessionId);
175
- const turns = yield ctx.adminforth.resource(ctx.options.turnResource.resourceId).list([Filters.EQ(ctx.options.turnResource.sessionIdField, sessionId)]);
176
- yield Promise.all(turns.map(turn => ctx.adminforth.resource(ctx.options.turnResource.resourceId).delete(turn[ctx.options.turnResource.idField])));
175
+ yield ctx.deleteSession(sessionId);
177
176
  return {
178
177
  ok: true
179
178
  };
package/dist/types.d.ts CHANGED
@@ -22,6 +22,40 @@ interface ITurnResource {
22
22
  responseField: string;
23
23
  debugField?: string;
24
24
  checkpointIdField?: string;
25
+ /**
26
+ * Optional array column with image attachments of the user message. Enables pasting
27
+ * and attaching images in the chat. Requires UploadPlugin installed on this column
28
+ * with `allowedFileExtensions` limited to images (png, jpg, jpeg, webp).
29
+ */
30
+ attachmentsField?: string;
31
+ }
32
+ export interface IImageAttachmentsOptions {
33
+ /**
34
+ * How many images one message can have, at most `maxViewedPerTurn`: the `view_image` tool
35
+ * loads all images of a message at once.
36
+ * Default is 5
37
+ */
38
+ maxPerMessage?: number;
39
+ /**
40
+ * How many minutes the model sees an image after it was sent or loaded again with the
41
+ * `view_image` tool. Every shown image costs tokens on every model call.
42
+ * Default is 30
43
+ */
44
+ visibleMinutes?: number;
45
+ /**
46
+ * How many images the model keeps seeing, the latest ones; the others become notes the
47
+ * model can load again with the `view_image` tool. A `view_image` can keep more of the images
48
+ * it loaded, up to `maxViewedPerTurn`, until the next images are sent or loaded.
49
+ * Default is 5
50
+ */
51
+ maxVisible?: number;
52
+ /**
53
+ * How many images the model can load again with the `view_image` tool during one answer: one
54
+ * call, whole messages, the most likely first. It sees all of them for that answer and keeps the
55
+ * ones it picks for the next messages; past the limit it asks the user which images matter.
56
+ * Default is 10
57
+ */
58
+ maxViewedPerTurn?: number;
25
59
  }
26
60
  interface ICheckpointResource {
27
61
  resourceId: string;
@@ -88,6 +122,10 @@ export interface PluginOptions extends PluginsCommonOptions {
88
122
  * Resource configuration for turns.
89
123
  */
90
124
  turnResource: ITurnResource;
125
+ /**
126
+ * Limits of the image attachments of `turnResource.attachmentsField`, whole numbers from 1.
127
+ */
128
+ imageAttachments?: IImageAttachmentsOptions;
91
129
  /**
92
130
  * Makes chat sticky by default. By default this prop is false
93
131
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adminforth/agent",
3
- "version": "3.3.0",
3
+ "version": "3.5.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
@@ -37,7 +37,7 @@
37
37
  "@modelcontextprotocol/server": "2.3.1",
38
38
  "@types/jest": "^30.0.0",
39
39
  "@types/node": "latest",
40
- "adminforth": "^4.14.0",
40
+ "adminforth": "^4.21.0",
41
41
  "jest": "^30.3.0",
42
42
  "semantic-release": "^24.2.1",
43
43
  "semantic-release-slack-bot": "^4.0.2",
@@ -81,7 +81,7 @@
81
81
  }
82
82
  ],
83
83
  "peerDependencies": {
84
- "adminforth": "^4.7.3",
84
+ "adminforth": "^4.21.0",
85
85
  "@adminforth/mcp": "^3.2.0"
86
86
  }
87
87
  }