@deepagents/experimental 7.8.0 → 7.8.1
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.
- package/README.md +16 -5
- package/dist/index.js +140 -120
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -1
- package/dist/zukhruf/control-plane/agent-thread-limit-error.d.ts +6 -0
- package/dist/zukhruf/control-plane/agent-thread-limit-error.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/agent-turn-id.d.ts +3 -0
- package/dist/zukhruf/control-plane/agent-turn-id.d.ts.map +1 -1
- package/dist/zukhruf/control-plane/stale-turn-error.d.ts +7 -0
- package/dist/zukhruf/control-plane/stale-turn-error.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/turn-not-found-error.d.ts +7 -0
- package/dist/zukhruf/control-plane/turn-not-found-error.d.ts.map +1 -0
- package/dist/zukhruf/index.d.ts +3 -0
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +140 -120
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/is-named-error.d.ts +7 -0
- package/dist/zukhruf/is-named-error.d.ts.map +1 -0
- package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/index.js +142 -136
- package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
- package/dist/zukhruf/plugins/http/index.d.ts +2 -2
- package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/http/index.js +72 -17
- package/dist/zukhruf/plugins/http/index.js.map +4 -4
- package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/http.js +44 -32
- package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
- package/dist/zukhruf/plugins/schedules/index.d.ts +2 -2
- package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/index.js +138 -143
- package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
- package/dist/zukhruf/plugins/uploads/http.js +30 -19
- package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
- package/dist/zukhruf/plugins/uploads/index.d.ts +2 -2
- package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/index.js +48 -55
- package/dist/zukhruf/plugins/uploads/index.js.map +2 -2
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +4 -1
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/runtime/agent-runtime.d.ts +19 -11
- package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +4 -4
- package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
- package/package.json +11 -11
|
@@ -4,7 +4,7 @@ import { safeParse as parseContentType } from "fast-content-type-parse";
|
|
|
4
4
|
import { Hono as Hono2 } from "hono";
|
|
5
5
|
import { bodyLimit } from "hono/body-limit";
|
|
6
6
|
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
7
|
-
import
|
|
7
|
+
import z4 from "zod";
|
|
8
8
|
|
|
9
9
|
// packages/experimental/src/zukhruf/plugins/http/index.ts
|
|
10
10
|
import { validate } from "@sdk-it/hono/runtime";
|
|
@@ -17,9 +17,20 @@ import { Hono } from "hono";
|
|
|
17
17
|
import { HTTPException } from "hono/http-exception";
|
|
18
18
|
import { basePath } from "hono/route";
|
|
19
19
|
import { streamSSE } from "hono/streaming";
|
|
20
|
-
import { validate as
|
|
21
|
-
import
|
|
20
|
+
import { validate as validateUuid2 } from "uuid";
|
|
21
|
+
import z2 from "zod";
|
|
22
22
|
import { elementsSchema } from "@deepagents/elements";
|
|
23
|
+
|
|
24
|
+
// packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
|
|
25
|
+
import { v5 as uuidv5, validate as validateUuid } from "uuid";
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
var prefix = "zukhruf-turn";
|
|
28
|
+
var agentTurnIdSchema = z.string().refine((value) => {
|
|
29
|
+
const [head, scope, turn, ...rest] = value.split(":");
|
|
30
|
+
return head === prefix && rest.length === 0 && validateUuid(scope) && validateUuid(turn);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// packages/experimental/src/zukhruf/plugins/http/index.ts
|
|
23
34
|
function projectHttp(definition, project) {
|
|
24
35
|
return {
|
|
25
36
|
project(runtime) {
|
|
@@ -30,28 +41,28 @@ function projectHttp(definition, project) {
|
|
|
30
41
|
function mountPath(context) {
|
|
31
42
|
return basePath(context).replace(/\/$/, "");
|
|
32
43
|
}
|
|
33
|
-
var sessionIdSchema =
|
|
34
|
-
var jsonSchema =
|
|
44
|
+
var sessionIdSchema = z2.string().refine(validateUuid2);
|
|
45
|
+
var jsonSchema = z2.custom(
|
|
35
46
|
(value) => typeof value === "object" && value !== null && !Array.isArray(value)
|
|
36
47
|
);
|
|
37
|
-
var clientToolsSchema =
|
|
38
|
-
|
|
39
|
-
|
|
48
|
+
var clientToolsSchema = z2.record(
|
|
49
|
+
z2.string().min(1),
|
|
50
|
+
z2.strictObject({
|
|
40
51
|
inputSchema: jsonSchema,
|
|
41
|
-
description:
|
|
52
|
+
description: z2.string().min(1)
|
|
42
53
|
})
|
|
43
54
|
).optional();
|
|
44
|
-
var turnBodySchema =
|
|
55
|
+
var turnBodySchema = z2.strictObject({
|
|
45
56
|
sessionId: sessionIdSchema,
|
|
46
|
-
message:
|
|
47
|
-
trigger:
|
|
57
|
+
message: z2.unknown(),
|
|
58
|
+
trigger: z2.enum(["submit-message", "regenerate-message"]),
|
|
48
59
|
tools: clientToolsSchema,
|
|
49
60
|
elements: elementsSchema
|
|
50
61
|
});
|
|
51
62
|
|
|
52
63
|
// packages/experimental/src/zukhruf/plugins/uploads/index.ts
|
|
53
64
|
import { tool } from "ai";
|
|
54
|
-
import
|
|
65
|
+
import z3 from "zod";
|
|
55
66
|
import { reminder } from "@deepagents/context";
|
|
56
67
|
var extensionByMediaType = {
|
|
57
68
|
"image/png": "png",
|
|
@@ -82,11 +93,11 @@ var UPLOAD_FILE_ID_PATTERN = new RegExp(
|
|
|
82
93
|
function isUploadMediaType(mediaType) {
|
|
83
94
|
return Object.hasOwn(extensionByMediaType, mediaType);
|
|
84
95
|
}
|
|
85
|
-
var publishInputSchema =
|
|
86
|
-
path:
|
|
96
|
+
var publishInputSchema = z3.object({
|
|
97
|
+
path: z3.string().startsWith("/").describe(
|
|
87
98
|
"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included)."
|
|
88
99
|
),
|
|
89
|
-
name:
|
|
100
|
+
name: z3.string().min(1).optional().describe("Display name shown to the user; defaults to the file name.")
|
|
90
101
|
});
|
|
91
102
|
|
|
92
103
|
// packages/experimental/src/zukhruf/plugins/uploads/http.ts
|
|
@@ -97,8 +108,8 @@ var NO_STORE = { "cache-control": "no-store" };
|
|
|
97
108
|
var IMMUTABLE = {
|
|
98
109
|
"cache-control": "private, max-age=31536000, immutable"
|
|
99
110
|
};
|
|
100
|
-
var sessionIdSchema2 =
|
|
101
|
-
var uploadFilenameSchema =
|
|
111
|
+
var sessionIdSchema2 = z4.uuid();
|
|
112
|
+
var uploadFilenameSchema = z4.string().min(1).transform((encoded, context) => {
|
|
102
113
|
try {
|
|
103
114
|
return decodeURIComponent(encoded);
|
|
104
115
|
} catch {
|
|
@@ -106,7 +117,7 @@ var uploadFilenameSchema = z3.string().min(1).transform((encoded, context) => {
|
|
|
106
117
|
code: "custom",
|
|
107
118
|
message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`
|
|
108
119
|
});
|
|
109
|
-
return
|
|
120
|
+
return z4.NEVER;
|
|
110
121
|
}
|
|
111
122
|
});
|
|
112
123
|
function uploadsHttp(definition, { maxBytes }) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../../src/zukhruf/plugins/uploads/http.ts", "../../../../src/zukhruf/plugins/http/index.ts", "../../../../src/zukhruf/plugins/uploads/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { validate } from '@sdk-it/hono/runtime';\nimport { safeParse as parseContentType } from 'fast-content-type-parse';\nimport { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n mountPath,\n projectHttp,\n} from '../http/index.ts';\nimport {\n UPLOAD_MEDIA_TYPES,\n type UploadMediaType,\n type Uploads,\n isUploadMediaType,\n} from './index.ts';\n\nexport const UPLOAD_FILENAME_HEADER = 'x-upload-filename';\n\nconst SESSION_UPLOADS_ROUTE_PATH = '/session/:sessionId/uploads';\nconst SESSION_UPLOAD_ROUTE_PATH = `${SESSION_UPLOADS_ROUTE_PATH}/:fileId`;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst IMMUTABLE = {\n 'cache-control': 'private, max-age=31536000, immutable',\n} as const;\nconst sessionIdSchema = z.uuid();\nconst uploadFilenameSchema = z\n .string()\n .min(1)\n .transform((encoded, context) => {\n try {\n return decodeURIComponent(encoded);\n } catch {\n context.addIssue({\n code: 'custom',\n message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`,\n });\n return z.NEVER;\n }\n });\n\n/**\n * What `POST /session/:sessionId/uploads` answers. The composer keeps it and\n * sends it back under `message.metadata.uploads` on the turn that attaches it.\n */\nexport interface UploadReceipt {\n /** Absolute sandbox path the model reads with the sandbox read tool. */\n path: string;\n /** Client file name from the `x-upload-filename` header. */\n name: string;\n mediaType: UploadMediaType;\n /** Byte length of the stored file. */\n size: number;\n /** `GET` route serving the bytes for rendering. */\n url: string;\n}\n\n/**\n * Per-session upload and retrieval bound to one `uploads()` definition.\n * The caller must choose the maximum accepted upload size in bytes.\n */\nexport function uploadsHttp(\n definition: AgentPluginDefinition<Uploads>,\n { maxBytes }: { maxBytes: number },\n): HttpProjection {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new TypeError(\n 'uploadsHttp: maxBytes must be a positive safe integer',\n );\n }\n return projectHttp(definition, (plugin) => ({\n capabilities: {\n uploads: { path: '/session', mediaTypes: UPLOAD_MEDIA_TYPES },\n },\n authenticatedRoutes: uploadRoutes(plugin, maxBytes),\n }));\n}\n\nfunction uploadRoutes(uploads: Uploads, maxBytes: number) {\n const app = new Hono<HttpEnv>();\n app.post(\n SESSION_UPLOADS_ROUTE_PATH,\n bodyLimit({\n maxSize: maxBytes,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Upload is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Upload exceeds ${maxBytes} bytes`,\n },\n });\n },\n }),\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n name: {\n select: payload.headers[UPLOAD_FILENAME_HEADER],\n against: uploadFilenameSchema,\n },\n })),\n async (context) => {\n const { sessionId, name } = context.var.input;\n const contentType = context.req.header('content-type');\n const mediaType =\n contentType === undefined\n ? undefined\n : parseContentType(contentType).type;\n if (mediaType === undefined || !isUploadMediaType(mediaType)) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'zukhruf/unsupported-media-type',\n detail: `Uploads must be one of ${UPLOAD_MEDIA_TYPES.join(', ')}`,\n },\n });\n }\n const data = new Uint8Array(await context.req.arrayBuffer());\n const { fileId, path } = await uploads.write(\n { userId: context.get('userId'), sessionId },\n { data, mediaType },\n );\n const url = new URL(\n `${mountPath(context)}/session/${sessionId}/uploads/${fileId}`,\n context.req.url,\n ).href;\n return context.json(\n {\n path,\n name,\n mediaType,\n size: data.byteLength,\n url,\n } satisfies UploadReceipt,\n 201,\n NO_STORE,\n );\n },\n );\n app.all(SESSION_UPLOADS_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.on(\n ['GET', 'HEAD'],\n SESSION_UPLOAD_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const fileId = context.req.param('fileId');\n const upload = await uploads.read(\n { userId: context.get('userId'), sessionId },\n fileId,\n );\n if (!upload) {\n throw new HTTPException(404, {\n message: 'Upload not found',\n cause: {\n code: 'zukhruf/upload-not-found',\n detail: `Upload ${fileId} does not exist in session ${sessionId}`,\n },\n });\n }\n // Byte ranges let <video>/<audio> seek and let Safari play at all; the\n // whole file is already in memory, so a range is a plain subarray.\n const total = upload.data.byteLength;\n const headers = {\n 'content-type': upload.mediaType,\n 'accept-ranges': 'bytes',\n ...IMMUTABLE,\n };\n const rangeHeader = context.req.header('range');\n const head = context.req.method === 'HEAD';\n if (rangeHeader === undefined) {\n const full = { ...headers, 'content-length': String(total) };\n return head\n ? context.body(null, 200, full)\n : context.body(upload.data, 200, full);\n }\n const range = parseByteRange(rangeHeader, total);\n if (range === undefined) {\n return context.body(null, 416, {\n ...headers,\n 'content-range': `bytes */${total}`,\n });\n }\n const partial = {\n ...headers,\n 'content-range': `bytes ${range.start}-${range.end}/${total}`,\n 'content-length': String(range.end - range.start + 1),\n };\n return head\n ? context.body(null, 206, partial)\n : context.body(\n upload.data.subarray(range.start, range.end + 1),\n 206,\n partial,\n );\n },\n );\n app.all(SESSION_UPLOAD_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n return app;\n}\n\n/**\n * One `bytes=` range (RFC 9110 \u00A714.1.2): `a-b`, `a-`, or `-n`; `undefined`\n * when the header is malformed, multi-range, or unsatisfiable.\n */\nfunction parseByteRange(\n header: string,\n total: number,\n): { start: number; end: number } | undefined {\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim());\n if (match === null || total === 0) return undefined;\n const [, first, last] = match;\n if (first === '' && last === '') return undefined;\n if (first === '') {\n const suffix = Number(last);\n if (suffix === 0) return undefined;\n return { start: Math.max(total - suffix, 0), end: total - 1 };\n }\n const start = Number(first);\n const end = last === '' ? total - 1 : Math.min(Number(last), total - 1);\n if (start > end || start >= total) return undefined;\n return { start, end };\n}\n\nfunction methodNotAllowed(\n context: { header(name: string, value: string): void },\n allow: string,\n): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { validate } from '@sdk-it/hono/runtime';\nimport { Lock } from '@zukhruf/async';\nimport {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { ConversationNotFoundError } from '../../control-plane/conversation-not-found-error.ts';\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInstance,\n} from '../../runtime/agent-runtime.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Instance extends object>(\n definition: AgentPluginDefinition<Instance>,\n project: (\n plugin: AgentPluginInstance & Instance,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n if (isConversationNotFoundError(error)) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${error.chatId} does not exist`,\n },\n error: 'Session not found',\n },\n 404,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw new HTTPException(400, {\n message: 'Invalid session ID',\n cause: {\n code: 'api/validation-failed',\n detail: 'Route and body session IDs must match',\n },\n });\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session must start with a user message',\n },\n });\n }\n if (request.trigger !== 'submit-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session cannot regenerate a response',\n },\n });\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n const writes = new Lock();\n const write = (event: OwnerEvent) =>\n writes.run(() => stream.writeSSE({ data: JSON.stringify(event) }), {\n signal: undefined,\n });\n const heartbeat = setInterval(() => {\n writes\n .run(\n async () => {\n await stream.write(': heartbeat\\n\\n');\n },\n { signal: undefined },\n )\n .catch(() => {});\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(Error.isError(error) && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success)\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail: result.error.message },\n });\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'System messages are not accepted',\n },\n });\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail:\n 'Regeneration requires the user message preceding the assistant response',\n },\n });\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\n/**\n * `name` rather than `instanceof`: this subpath is its own build entry point, so\n * the main entry's class is a different copy here.\n */\nfunction isConversationNotFoundError(\n error: unknown,\n): error is Pick<ConversationNotFoundError, 'name' | 'message' | 'chatId'> {\n return (\n Error.isError(error) &&\n error.name === 'ConversationNotFoundError' &&\n 'chatId' in error &&\n typeof error.chatId === 'string'\n );\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { reminder } from '@deepagents/context';\n\nimport type { AgentDeclaration, ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInstance,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES: readonly UploadMediaType[] =\n Object.keys(extensionByMediaType).filter(isUploadMediaType);\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInstance {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => new UploadsPlugin(directory, resolvedPublicUrl),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass UploadsPlugin implements Uploads {\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n #requiredHost = (): AgentPluginHost => {\n throw new Error(\n 'uploads plugin must be initialized before storing or reading uploads',\n );\n };\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(directory: string, publicUrl: string | undefined) {\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n configure(root: AgentDeclaration): AgentDeclaration {\n return {\n ...root,\n instructions: [...root.instructions, this.#attachedUploadsReminder()],\n };\n }\n\n initialize(host: AgentPluginHost): Promise<void> {\n this.#requiredHost = () => host;\n return Promise.resolve();\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeBinaryFile({ path, content: data });\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if ((await sandbox.sandbox.stat({ path })) === null) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.run({\n command: `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n });\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n /**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\n #attachedUploadsReminder() {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = this.#scopeFor({\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n return this.#requiredHost().sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n const bytes = await sandbox.sandbox.readBinaryFile({ path });\n if (bytes === null) return undefined;\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n /** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\n #scopeFor({ userId, sessionId }: UploadScope): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(this.#directory, userId, sessionId);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction assertPathSegment(name: string, value: string): void {\n if (\n value.length === 0 ||\n value === '.' ||\n value === '..' ||\n value.includes('/')\n ) {\n throw new Error(\n `uploads: ${name} must be a single path segment, received \"${value}\"`,\n );\n }\n}\n\nfunction attachedUploads(message: UIMessage): AttachedUpload[] {\n if (!isRecord(message.metadata) || !Array.isArray(message.metadata.uploads)) {\n return [];\n }\n return message.metadata.uploads.filter(isAttachedUpload);\n}\n\nfunction isAttachedUpload(value: unknown): value is AttachedUpload {\n return (\n isRecord(value) &&\n typeof value.path === 'string' &&\n typeof value.name === 'string' &&\n typeof value.mediaType === 'string' &&\n typeof value.size === 'number'\n );\n}\n\n/** `path` is already normalized (no `.`/`..` segments) and names something below `scope`. */\nfunction isBelow(scope: string, path: string): boolean {\n return posix.normalize(path) === path && path.startsWith(`${scope}/`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,aAAa,wBAAwB;AAC9C,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACLd,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;
|
|
6
|
-
"names": ["validate", "Hono", "HTTPException", "z", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "validate"]
|
|
3
|
+
"sources": ["../../../../src/zukhruf/plugins/uploads/http.ts", "../../../../src/zukhruf/plugins/http/index.ts", "../../../../src/zukhruf/control-plane/agent-turn-id.ts", "../../../../src/zukhruf/plugins/uploads/index.ts"],
|
|
4
|
+
"sourcesContent": ["import { validate } from '@sdk-it/hono/runtime';\nimport { safeParse as parseContentType } from 'fast-content-type-parse';\nimport { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n mountPath,\n projectHttp,\n} from '../http/index.ts';\nimport {\n UPLOAD_MEDIA_TYPES,\n type UploadMediaType,\n type Uploads,\n isUploadMediaType,\n} from './index.ts';\n\nexport const UPLOAD_FILENAME_HEADER = 'x-upload-filename';\n\nconst SESSION_UPLOADS_ROUTE_PATH = '/session/:sessionId/uploads';\nconst SESSION_UPLOAD_ROUTE_PATH = `${SESSION_UPLOADS_ROUTE_PATH}/:fileId`;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst IMMUTABLE = {\n 'cache-control': 'private, max-age=31536000, immutable',\n} as const;\nconst sessionIdSchema = z.uuid();\nconst uploadFilenameSchema = z\n .string()\n .min(1)\n .transform((encoded, context) => {\n try {\n return decodeURIComponent(encoded);\n } catch {\n context.addIssue({\n code: 'custom',\n message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`,\n });\n return z.NEVER;\n }\n });\n\n/**\n * What `POST /session/:sessionId/uploads` answers. The composer keeps it and\n * sends it back under `message.metadata.uploads` on the turn that attaches it.\n */\nexport interface UploadReceipt {\n /** Absolute sandbox path the model reads with the sandbox read tool. */\n path: string;\n /** Client file name from the `x-upload-filename` header. */\n name: string;\n mediaType: UploadMediaType;\n /** Byte length of the stored file. */\n size: number;\n /** `GET` route serving the bytes for rendering. */\n url: string;\n}\n\n/**\n * Per-session upload and retrieval bound to one `uploads()` definition.\n * The caller must choose the maximum accepted upload size in bytes.\n */\nexport function uploadsHttp(\n definition: AgentPluginDefinition<Uploads>,\n { maxBytes }: { maxBytes: number },\n): HttpProjection {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new TypeError(\n 'uploadsHttp: maxBytes must be a positive safe integer',\n );\n }\n return projectHttp(definition, (plugin) => ({\n capabilities: {\n uploads: { path: '/session', mediaTypes: UPLOAD_MEDIA_TYPES },\n },\n authenticatedRoutes: uploadRoutes(plugin, maxBytes),\n }));\n}\n\nfunction uploadRoutes(uploads: Uploads, maxBytes: number) {\n const app = new Hono<HttpEnv>();\n app.post(\n SESSION_UPLOADS_ROUTE_PATH,\n bodyLimit({\n maxSize: maxBytes,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Upload is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Upload exceeds ${maxBytes} bytes`,\n },\n });\n },\n }),\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n name: {\n select: payload.headers[UPLOAD_FILENAME_HEADER],\n against: uploadFilenameSchema,\n },\n })),\n async (context) => {\n const { sessionId, name } = context.var.input;\n const contentType = context.req.header('content-type');\n const mediaType =\n contentType === undefined\n ? undefined\n : parseContentType(contentType).type;\n if (mediaType === undefined || !isUploadMediaType(mediaType)) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'zukhruf/unsupported-media-type',\n detail: `Uploads must be one of ${UPLOAD_MEDIA_TYPES.join(', ')}`,\n },\n });\n }\n const data = new Uint8Array(await context.req.arrayBuffer());\n const { fileId, path } = await uploads.write(\n { userId: context.get('userId'), sessionId },\n { data, mediaType },\n );\n const url = new URL(\n `${mountPath(context)}/session/${sessionId}/uploads/${fileId}`,\n context.req.url,\n ).href;\n return context.json(\n {\n path,\n name,\n mediaType,\n size: data.byteLength,\n url,\n } satisfies UploadReceipt,\n 201,\n NO_STORE,\n );\n },\n );\n app.all(SESSION_UPLOADS_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.on(\n ['GET', 'HEAD'],\n SESSION_UPLOAD_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const fileId = context.req.param('fileId');\n const upload = await uploads.read(\n { userId: context.get('userId'), sessionId },\n fileId,\n );\n if (!upload) {\n throw new HTTPException(404, {\n message: 'Upload not found',\n cause: {\n code: 'zukhruf/upload-not-found',\n detail: `Upload ${fileId} does not exist in session ${sessionId}`,\n },\n });\n }\n // Byte ranges let <video>/<audio> seek and let Safari play at all; the\n // whole file is already in memory, so a range is a plain subarray.\n const total = upload.data.byteLength;\n const headers = {\n 'content-type': upload.mediaType,\n 'accept-ranges': 'bytes',\n ...IMMUTABLE,\n };\n const rangeHeader = context.req.header('range');\n const head = context.req.method === 'HEAD';\n if (rangeHeader === undefined) {\n const full = { ...headers, 'content-length': String(total) };\n return head\n ? context.body(null, 200, full)\n : context.body(upload.data, 200, full);\n }\n const range = parseByteRange(rangeHeader, total);\n if (range === undefined) {\n return context.body(null, 416, {\n ...headers,\n 'content-range': `bytes */${total}`,\n });\n }\n const partial = {\n ...headers,\n 'content-range': `bytes ${range.start}-${range.end}/${total}`,\n 'content-length': String(range.end - range.start + 1),\n };\n return head\n ? context.body(null, 206, partial)\n : context.body(\n upload.data.subarray(range.start, range.end + 1),\n 206,\n partial,\n );\n },\n );\n app.all(SESSION_UPLOAD_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n return app;\n}\n\n/**\n * One `bytes=` range (RFC 9110 \u00A714.1.2): `a-b`, `a-`, or `-n`; `undefined`\n * when the header is malformed, multi-range, or unsatisfiable.\n */\nfunction parseByteRange(\n header: string,\n total: number,\n): { start: number; end: number } | undefined {\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim());\n if (match === null || total === 0) return undefined;\n const [, first, last] = match;\n if (first === '' && last === '') return undefined;\n if (first === '') {\n const suffix = Number(last);\n if (suffix === 0) return undefined;\n return { start: Math.max(total - suffix, 0), end: total - 1 };\n }\n const start = Number(first);\n const end = last === '' ? total - 1 : Math.min(Number(last), total - 1);\n if (start > end || start >= total) return undefined;\n return { start, end };\n}\n\nfunction methodNotAllowed(\n context: { header(name: string, value: string): void },\n allow: string,\n): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { validate } from '@sdk-it/hono/runtime';\nimport { Lock } from '@zukhruf/async';\nimport {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { AgentThreadLimitError } from '../../control-plane/agent-thread-limit-error.ts';\nimport { agentTurnIdSchema } from '../../control-plane/agent-turn-id.ts';\nimport type { ConversationNotFoundError } from '../../control-plane/conversation-not-found-error.ts';\nimport type { StaleTurnError } from '../../control-plane/stale-turn-error.ts';\nimport type { TurnNotFoundError } from '../../control-plane/turn-not-found-error.ts';\nimport { isNamedError } from '../../is-named-error.ts';\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInitialization,\n} from '../../runtime/agent-runtime.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Running extends object>(\n definition: AgentPluginDefinition<Running>,\n project: (\n plugin: AgentPluginInitialization & Running,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n if (\n isNamedError<ConversationNotFoundError>(\n error,\n 'ConversationNotFoundError',\n )\n ) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${error.chatId} does not exist`,\n },\n error: 'Session not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<TurnNotFoundError>(error, 'TurnNotFoundError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${error.turnId} does not exist in session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<StaleTurnError>(error, 'StaleTurnError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-stale',\n detail: `Turn ${error.turnId} is not the latest turn of session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn is stale',\n },\n 409,\n NO_STORE,\n );\n }\n if (isNamedError<AgentThreadLimitError>(error, 'AgentThreadLimitError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/agent-thread-limit',\n detail: `Every agent slot of session ${context.req.param('sessionId')}'s tree is busy; retry when one finishes`,\n },\n error: 'Agent thread limit reached',\n },\n 429,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw new HTTPException(400, {\n message: 'Invalid session ID',\n cause: {\n code: 'api/validation-failed',\n detail: 'Route and body session IDs must match',\n },\n });\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session must start with a user message',\n },\n });\n }\n if (request.trigger !== 'submit-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session cannot regenerate a response',\n },\n });\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n const writes = new Lock();\n const write = (event: OwnerEvent) =>\n writes.run(() => stream.writeSSE({ data: JSON.stringify(event) }), {\n signal: undefined,\n });\n const heartbeat = setInterval(() => {\n writes\n .run(\n async () => {\n await stream.write(': heartbeat\\n\\n');\n },\n { signal: undefined },\n )\n .catch(() => {});\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(Error.isError(error) && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success)\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail: result.error.message },\n });\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'System messages are not accepted',\n },\n });\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail:\n 'Regeneration requires the user message preceding the assistant response',\n },\n });\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { v5 as uuidv5, validate as validateUuid } from 'uuid';\nimport { z } from 'zod';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport { TurnNotFoundError } from './turn-not-found-error.ts';\n\nconst prefix = 'zukhruf-turn';\n\n/** The shape of every AgentTurnId string; AgentTurnId.assertOwner checks whose it is. */\nexport const agentTurnIdSchema = z.string().refine((value) => {\n const [head, scope, turn, ...rest] = value.split(':');\n return (\n head === prefix &&\n rest.length === 0 &&\n validateUuid(scope) &&\n validateUuid(turn)\n );\n});\n\n/** Conversation-scoped durable identity for one caller-supplied turn key. */\nexport class AgentTurnId {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static fromRequest(\n conversation: ConversationId,\n requestId: string,\n ): AgentTurnId {\n if (!requestId.trim()) {\n throw new Error('turn id cannot be empty');\n }\n const scope = conversationNamespace(conversation);\n return new AgentTurnId(`${prefix}:${scope}:${uuidv5(requestId, scope)}`);\n }\n\n static random(conversation: ConversationId): AgentTurnId {\n return AgentTurnId.fromRequest(conversation, crypto.randomUUID());\n }\n\n static assertOwner(conversation: ConversationId, streamId: string): void {\n const expectedPrefix = `${prefix}:${conversationNamespace(conversation)}:`;\n if (!streamId.startsWith(expectedPrefix)) {\n throw new TurnNotFoundError(streamId);\n }\n }\n\n toString(): string {\n return this.#value;\n }\n}\n\nexport function conversationNamespace(conversation: ConversationId): string {\n if (!conversation.chatId.trim() || !conversation.userId.trim()) {\n throw new Error('conversation requires non-empty chatId and userId');\n }\n return uuidv5(\n JSON.stringify([conversation.userId, conversation.chatId]),\n uuidv5.URL,\n );\n}\n", "import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { reminder } from '@deepagents/context';\n\nimport type { ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInitialization,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES: readonly UploadMediaType[] =\n Object.keys(extensionByMediaType).filter(isUploadMediaType);\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInitialization {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => ({\n configure: (root) => ({\n ...root,\n instructions: [\n ...root.instructions,\n attachedUploadsReminder(directory),\n ],\n }),\n initialize: async (host) =>\n new RunningUploads(host, directory, resolvedPublicUrl),\n }),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass RunningUploads implements Uploads {\n readonly #host: AgentPluginHost;\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(\n host: AgentPluginHost,\n directory: string,\n publicUrl: string | undefined,\n ) {\n this.#host = host;\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeBinaryFile({ path, content: data });\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if ((await sandbox.sandbox.stat({ path })) === null) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.run({\n command: `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n });\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n return this.#host.sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n const bytes = await sandbox.sandbox.readBinaryFile({ path });\n if (bytes === null) return undefined;\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n #scopeFor(scope: UploadScope): string {\n return scopeFor(this.#directory, scope);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\n/**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\nfunction attachedUploadsReminder(directory: string) {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = scopeFor(directory, {\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n}\n\n/** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\nfunction scopeFor(\n directory: string,\n { userId, sessionId }: UploadScope,\n): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(directory, userId, sessionId);\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction assertPathSegment(name: string, value: string): void {\n if (\n value.length === 0 ||\n value === '.' ||\n value === '..' ||\n value.includes('/')\n ) {\n throw new Error(\n `uploads: ${name} must be a single path segment, received \"${value}\"`,\n );\n }\n}\n\nfunction attachedUploads(message: UIMessage): AttachedUpload[] {\n if (!isRecord(message.metadata) || !Array.isArray(message.metadata.uploads)) {\n return [];\n }\n return message.metadata.uploads.filter(isAttachedUpload);\n}\n\nfunction isAttachedUpload(value: unknown): value is AttachedUpload {\n return (\n isRecord(value) &&\n typeof value.path === 'string' &&\n typeof value.name === 'string' &&\n typeof value.mediaType === 'string' &&\n typeof value.size === 'number'\n );\n}\n\n/** `path` is already normalized (no `.`/`..` segments) and names something below `scope`. */\nfunction isBelow(scope: string, path: string): boolean {\n return posix.normalize(path) === path && path.startsWith(`${scope}/`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,aAAa,wBAAwB;AAC9C,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACLd,SAAS,gBAAgB;AACzB,SAAS,YAAY;AACrB;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,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AAM,CAAC,EAAE,OAAO,IAAI,IAAI;AACxB,MAAI,UAAU,MAAM,SAAS,GAAI,QAAO;AACxC,MAAI,UAAU,IAAI;AAChB,UAAM,SAAS,OAAO,IAAI;AAC1B,QAAI,WAAW,EAAG,QAAO;AACzB,WAAO,EAAE,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE;AAAA,EAC9D;AACA,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,MAAM,SAAS,KAAK,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,QAAQ,CAAC;AACtE,MAAI,QAAQ,OAAO,SAAS,MAAO,QAAO;AAC1C,SAAO,EAAE,OAAO,IAAI;AACtB;AAEA,SAAS,iBACP,SACA,OACO;AACP,UAAQ,OAAO,SAAS,KAAK;AAC7B,QAAM,IAAIA,eAAc,KAAK;AAAA,IAC3B,SAAS;AAAA,IACT,OAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,8BAA8B,KAAK;AAAA,IAC7C;AAAA,EACF,CAAC;AACH;",
|
|
6
|
+
"names": ["validate", "Hono", "HTTPException", "z", "validateUuid", "z", "z", "validateUuid", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "validate"]
|
|
7
7
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AgentPluginDefinition,
|
|
1
|
+
import type { AgentPluginDefinition, AgentPluginInitialization } from '../../runtime/agent-runtime.ts';
|
|
2
2
|
declare const extensionByMediaType: {
|
|
3
3
|
readonly 'image/png': "png";
|
|
4
4
|
readonly 'image/jpeg': "jpg";
|
|
@@ -51,7 +51,7 @@ export interface UploadsOptions {
|
|
|
51
51
|
*/
|
|
52
52
|
publicUrl?: string;
|
|
53
53
|
}
|
|
54
|
-
export interface Uploads extends
|
|
54
|
+
export interface Uploads extends AgentPluginInitialization {
|
|
55
55
|
/** Stores one file in the session's sandbox. */
|
|
56
56
|
write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;
|
|
57
57
|
read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EAErB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EAErB,yBAAyB,EAE1B,MAAM,gCAAgC,CAAC;AAExC,QAAA,MAAM,oBAAoB;;;;;;;;;;;;CAYhB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,oBAAoB,CAAC;AAEhE,eAAO,MAAM,kBAAkB,EAAE,SAAS,eAAe,EACI,CAAC;AAkB9D,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B,SAAS,EAAE,eAAe,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,cAAc;IAC7B,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,eAAgB,SAAQ,aAAa;IACpD,SAAS,EAAE,eAAe,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAUD,MAAM,WAAW,cAAc;IAC7B,sFAAsF;IACtF,SAAS,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,OAAQ,SAAQ,yBAAyB;IACxD,gDAAgD;IAChD,KAAK,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACxE,IAAI,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAAC;IAC5E;;;OAGG;IACH,OAAO,CACL,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,GAChB,SAAS,IAAI,eAAe,CAE9B;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,EACtB,SAAS,EACT,SAAS,GACV,EAAE,cAAc,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAqBjD"}
|
|
@@ -45,7 +45,16 @@ function uploads({
|
|
|
45
45
|
const resolvedPublicUrl = normalizePublicUrl(publicUrl);
|
|
46
46
|
return {
|
|
47
47
|
name: "uploads",
|
|
48
|
-
create: () =>
|
|
48
|
+
create: () => ({
|
|
49
|
+
configure: (root) => ({
|
|
50
|
+
...root,
|
|
51
|
+
instructions: [
|
|
52
|
+
...root.instructions,
|
|
53
|
+
attachedUploadsReminder(directory)
|
|
54
|
+
]
|
|
55
|
+
}),
|
|
56
|
+
initialize: async (host) => new RunningUploads(host, directory, resolvedPublicUrl)
|
|
57
|
+
})
|
|
49
58
|
};
|
|
50
59
|
}
|
|
51
60
|
var publishInputSchema = z.object({
|
|
@@ -54,14 +63,10 @@ var publishInputSchema = z.object({
|
|
|
54
63
|
),
|
|
55
64
|
name: z.string().min(1).optional().describe("Display name shown to the user; defaults to the file name.")
|
|
56
65
|
});
|
|
57
|
-
var
|
|
66
|
+
var RunningUploads = class {
|
|
67
|
+
#host;
|
|
58
68
|
#directory;
|
|
59
69
|
#publicUrl;
|
|
60
|
-
#requiredHost = () => {
|
|
61
|
-
throw new Error(
|
|
62
|
-
"uploads plugin must be initialized before storing or reading uploads"
|
|
63
|
-
);
|
|
64
|
-
};
|
|
65
70
|
tools = {
|
|
66
71
|
publish_upload: tool({
|
|
67
72
|
description: "Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.",
|
|
@@ -72,20 +77,11 @@ var UploadsPlugin = class {
|
|
|
72
77
|
)
|
|
73
78
|
})
|
|
74
79
|
};
|
|
75
|
-
constructor(directory, publicUrl) {
|
|
80
|
+
constructor(host, directory, publicUrl) {
|
|
81
|
+
this.#host = host;
|
|
76
82
|
this.#directory = directory;
|
|
77
83
|
this.#publicUrl = publicUrl;
|
|
78
84
|
}
|
|
79
|
-
configure(root) {
|
|
80
|
-
return {
|
|
81
|
-
...root,
|
|
82
|
-
instructions: [...root.instructions, this.#attachedUploadsReminder()]
|
|
83
|
-
};
|
|
84
|
-
}
|
|
85
|
-
initialize(host) {
|
|
86
|
-
this.#requiredHost = () => host;
|
|
87
|
-
return Promise.resolve();
|
|
88
|
-
}
|
|
89
85
|
async write(scope, { data, mediaType }) {
|
|
90
86
|
const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;
|
|
91
87
|
const path = this.#pathFor(scope, fileId);
|
|
@@ -138,39 +134,8 @@ var UploadsPlugin = class {
|
|
|
138
134
|
...this.#publicUrl === void 0 ? {} : { url: `${this.#publicUrl}${href}` }
|
|
139
135
|
};
|
|
140
136
|
}
|
|
141
|
-
/**
|
|
142
|
-
* Lists the turn's attachments for the model. The engine folds it into the
|
|
143
|
-
* user message being saved and hands over that chat, so only files uploaded
|
|
144
|
-
* for this chat by its owner are listed.
|
|
145
|
-
*/
|
|
146
|
-
#attachedUploadsReminder() {
|
|
147
|
-
return reminder(
|
|
148
|
-
({ currentMessage, chat }) => {
|
|
149
|
-
if (currentMessage === void 0 || chat === void 0) {
|
|
150
|
-
throw new Error(
|
|
151
|
-
"uploads: the user reminder context must carry currentMessage and chat"
|
|
152
|
-
);
|
|
153
|
-
}
|
|
154
|
-
const scope = this.#scopeFor({
|
|
155
|
-
userId: chat.userId,
|
|
156
|
-
sessionId: chat.id
|
|
157
|
-
});
|
|
158
|
-
const attached = attachedUploads(currentMessage).filter(
|
|
159
|
-
({ path }) => isBelow(scope, path)
|
|
160
|
-
);
|
|
161
|
-
if (attached.length === 0) return "";
|
|
162
|
-
return [
|
|
163
|
-
"The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.",
|
|
164
|
-
...attached.map(
|
|
165
|
-
({ path, name, mediaType, size }) => `- ${path} (${name}, ${mediaType}, ${size} bytes)`
|
|
166
|
-
)
|
|
167
|
-
].join("\n");
|
|
168
|
-
},
|
|
169
|
-
{ asPart: true }
|
|
170
|
-
);
|
|
171
|
-
}
|
|
172
137
|
#sandboxFor(scope) {
|
|
173
|
-
return this.#
|
|
138
|
+
return this.#host.sandbox({
|
|
174
139
|
chatId: scope.sessionId,
|
|
175
140
|
userId: scope.userId
|
|
176
141
|
});
|
|
@@ -184,16 +149,44 @@ var UploadsPlugin = class {
|
|
|
184
149
|
if (bytes === null) return void 0;
|
|
185
150
|
return { data: new Uint8Array(bytes), mediaType };
|
|
186
151
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
assertPathSegment("userId", userId);
|
|
190
|
-
assertPathSegment("sessionId", sessionId);
|
|
191
|
-
return posix.join(this.#directory, userId, sessionId);
|
|
152
|
+
#scopeFor(scope) {
|
|
153
|
+
return scopeFor(this.#directory, scope);
|
|
192
154
|
}
|
|
193
155
|
#pathFor(scope, fileId) {
|
|
194
156
|
return posix.join(this.#scopeFor(scope), fileId);
|
|
195
157
|
}
|
|
196
158
|
};
|
|
159
|
+
function attachedUploadsReminder(directory) {
|
|
160
|
+
return reminder(
|
|
161
|
+
({ currentMessage, chat }) => {
|
|
162
|
+
if (currentMessage === void 0 || chat === void 0) {
|
|
163
|
+
throw new Error(
|
|
164
|
+
"uploads: the user reminder context must carry currentMessage and chat"
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
const scope = scopeFor(directory, {
|
|
168
|
+
userId: chat.userId,
|
|
169
|
+
sessionId: chat.id
|
|
170
|
+
});
|
|
171
|
+
const attached = attachedUploads(currentMessage).filter(
|
|
172
|
+
({ path }) => isBelow(scope, path)
|
|
173
|
+
);
|
|
174
|
+
if (attached.length === 0) return "";
|
|
175
|
+
return [
|
|
176
|
+
"The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.",
|
|
177
|
+
...attached.map(
|
|
178
|
+
({ path, name, mediaType, size }) => `- ${path} (${name}, ${mediaType}, ${size} bytes)`
|
|
179
|
+
)
|
|
180
|
+
].join("\n");
|
|
181
|
+
},
|
|
182
|
+
{ asPart: true }
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
function scopeFor(directory, { userId, sessionId }) {
|
|
186
|
+
assertPathSegment("userId", userId);
|
|
187
|
+
assertPathSegment("sessionId", sessionId);
|
|
188
|
+
return posix.join(directory, userId, sessionId);
|
|
189
|
+
}
|
|
197
190
|
function normalizePublicUrl(publicUrl) {
|
|
198
191
|
if (publicUrl === void 0) return void 0;
|
|
199
192
|
let parsed;
|