@deepagents/experimental 7.1.1 → 7.1.3
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 +0 -1
- package/dist/index.js +252 -290
- package/dist/index.js.map +4 -4
- package/dist/providers/account-tokens.d.ts.map +1 -1
- package/dist/providers/claude/index.js +59 -51
- package/dist/providers/claude/index.js.map +2 -2
- package/dist/providers/claude/local-credentials.d.ts +1 -1
- package/dist/providers/claude/local-credentials.d.ts.map +1 -1
- package/dist/providers/codex/index.js +57 -49
- package/dist/providers/codex/index.js.map +2 -2
- package/dist/providers/codex/local-credentials.d.ts +1 -1
- package/dist/providers/codex/local-credentials.d.ts.map +1 -1
- package/dist/zukhruf/index.d.ts +0 -1
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +252 -290
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
- package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/index.js +12 -0
- package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
- package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/http/index.js +20 -164
- 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 +37 -180
- package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
- package/dist/zukhruf/plugins/schedules/index.js +14 -1
- package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
- package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/http.js +30 -173
- package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +6 -2
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
- package/package.json +29 -13
- package/dist/zukhruf/plugins/http/parse.d.ts +0 -3
- package/dist/zukhruf/plugins/http/parse.d.ts.map +0 -1
- package/dist/zukhruf/plugins/http/validator.d.ts +0 -34
- package/dist/zukhruf/plugins/http/validator.d.ts.map +0 -1
- package/dist/zukhruf/render-turn.d.ts +0 -9
- package/dist/zukhruf/render-turn.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduled-tasks.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/schedules/scheduled-tasks.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,EAAE,EACF,iBAAiB,EAEjB,MAAM,EACN,KAAK,EACN,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;
|
|
1
|
+
{"version":3,"file":"scheduled-tasks.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/schedules/scheduled-tasks.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,EAAE,EACF,iBAAiB,EAEjB,MAAM,EACN,KAAK,EACN,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAsGnE,MAAM,MAAM,mBAAmB,GAC7B,QAAQ,GAAG,QAAQ,GAAG,WAAW,GAAG,UAAU,CAAC;AACjD,MAAM,MAAM,kBAAkB,GAC5B,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AACnE,MAAM,MAAM,wBAAwB,GAClC,gBAAgB,GAAG,UAAU,GAAG,UAAU,CAAC;AAE7C,MAAM,MAAM,uBAAuB,GACjC,eAAe,GAAG,WAAW,GAAG,UAAU,CAAC;AAC7C,MAAM,MAAM,sBAAsB,GAAG,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http.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/http.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/http.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AAC5E,OAAO,EAEL,KAAK,cAAc,EAGpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,OAAO,EAEb,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,sBAAsB,sBAAsB,CAAC;AAwB1D;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,IAAI,EAAE,MAAM,CAAC;IACb,4DAA4D;IAC5D,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,eAAe,CAAC;IAC3B,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,mDAAmD;IACnD,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,UAAU,EAAE,qBAAqB,CAAC,OAAO,CAAC,EAC1C,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,GACjC,cAAc,CAYhB"}
|
|
@@ -1,167 +1,24 @@
|
|
|
1
1
|
// packages/experimental/src/zukhruf/plugins/uploads/http.ts
|
|
2
|
-
import {
|
|
2
|
+
import { validate as validate2 } from "@sdk-it/hono/runtime";
|
|
3
|
+
import { safeParse as parseContentType } from "fast-content-type-parse";
|
|
3
4
|
import { Hono as Hono2 } from "hono";
|
|
4
5
|
import { bodyLimit } from "hono/body-limit";
|
|
5
|
-
import { HTTPException as
|
|
6
|
-
import
|
|
6
|
+
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
7
|
+
import z3 from "zod";
|
|
7
8
|
|
|
8
9
|
// packages/experimental/src/zukhruf/plugins/http/index.ts
|
|
10
|
+
import { validate } from "@sdk-it/hono/runtime";
|
|
9
11
|
import {
|
|
10
12
|
createUIMessageStreamResponse,
|
|
11
13
|
safeValidateUIMessages
|
|
12
14
|
} from "ai";
|
|
13
15
|
import { Hono } from "hono";
|
|
14
|
-
import { HTTPException
|
|
16
|
+
import { HTTPException } from "hono/http-exception";
|
|
15
17
|
import { basePath } from "hono/route";
|
|
16
18
|
import { streamSSE } from "hono/streaming";
|
|
17
19
|
import { validate as validateUuid } from "uuid";
|
|
18
|
-
import
|
|
20
|
+
import z from "zod";
|
|
19
21
|
import { elementsSchema } from "@deepagents/elements";
|
|
20
|
-
|
|
21
|
-
// packages/experimental/src/zukhruf/plugins/http/validator.ts
|
|
22
|
-
import { parse as parseContentType } from "fast-content-type-parse";
|
|
23
|
-
import { createMiddleware } from "hono/factory";
|
|
24
|
-
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
25
|
-
import z2 from "zod";
|
|
26
|
-
|
|
27
|
-
// packages/experimental/src/zukhruf/plugins/http/parse.ts
|
|
28
|
-
import { HTTPException } from "hono/http-exception";
|
|
29
|
-
import "zod";
|
|
30
|
-
async function parse(schema, input) {
|
|
31
|
-
const result = await schema.safeParseAsync(input);
|
|
32
|
-
if (!result.success) {
|
|
33
|
-
const errors = result.error.flatten((issue) => ({
|
|
34
|
-
message: issue.message,
|
|
35
|
-
code: issue.code,
|
|
36
|
-
path: issue.path.join(".")
|
|
37
|
-
})).fieldErrors;
|
|
38
|
-
throw new HTTPException(400, {
|
|
39
|
-
message: "Validation failed",
|
|
40
|
-
cause: {
|
|
41
|
-
code: "api/validation-failed",
|
|
42
|
-
detail: "The input data is invalid",
|
|
43
|
-
errors
|
|
44
|
-
}
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
return result.data;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// packages/experimental/src/zukhruf/plugins/http/validator.ts
|
|
51
|
-
function inputSchema(config) {
|
|
52
|
-
const shape = Object.fromEntries(
|
|
53
|
-
Object.entries(config).map(([key, { against }]) => [key, against])
|
|
54
|
-
);
|
|
55
|
-
assertInputShape(shape, config);
|
|
56
|
-
return z2.object(shape);
|
|
57
|
-
}
|
|
58
|
-
function assertInputShape(shape, config) {
|
|
59
|
-
const keys = Object.keys(config);
|
|
60
|
-
if (Object.keys(shape).length !== keys.length || keys.some((key) => shape[key] !== config[key]?.against)) {
|
|
61
|
-
throw new Error("The input schema does not match its selectors");
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
function validate(expectedContentTypeOrSelector, selector) {
|
|
65
|
-
const expectedContentType = typeof expectedContentTypeOrSelector === "string" ? expectedContentTypeOrSelector : void 0;
|
|
66
|
-
const _selector = typeof expectedContentTypeOrSelector === "function" ? expectedContentTypeOrSelector : selector;
|
|
67
|
-
void _selector;
|
|
68
|
-
if (!_selector) {
|
|
69
|
-
throw new Error("Selector function is required");
|
|
70
|
-
}
|
|
71
|
-
return createMiddleware(async (c, next) => {
|
|
72
|
-
const ct = c.req.header("content-type");
|
|
73
|
-
if (c.req.method === "GET" && ct) {
|
|
74
|
-
throw new HTTPException2(415, {
|
|
75
|
-
message: "Unsupported Media Type",
|
|
76
|
-
cause: {
|
|
77
|
-
code: "api/unsupported-media-type",
|
|
78
|
-
detail: `GET requests cannot have a content type header`
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
if (expectedContentType) {
|
|
83
|
-
void verifyContentType(ct, expectedContentType);
|
|
84
|
-
}
|
|
85
|
-
const contentType = ct ? parseContentType(ct) : null;
|
|
86
|
-
let body = null;
|
|
87
|
-
switch (contentType?.type) {
|
|
88
|
-
case "application/json":
|
|
89
|
-
body = await parseJson(c);
|
|
90
|
-
break;
|
|
91
|
-
case "application/x-www-form-urlencoded":
|
|
92
|
-
case "multipart/form-data":
|
|
93
|
-
body = await c.req.parseBody();
|
|
94
|
-
break;
|
|
95
|
-
default:
|
|
96
|
-
body = {};
|
|
97
|
-
}
|
|
98
|
-
const payload = {
|
|
99
|
-
body,
|
|
100
|
-
query: parseQueryParams(c.req.query()),
|
|
101
|
-
queries: parseQueriesParams(c.req.queries()),
|
|
102
|
-
params: c.req.param(),
|
|
103
|
-
headers: c.req.header()
|
|
104
|
-
};
|
|
105
|
-
const config = _selector(payload);
|
|
106
|
-
const input = Object.fromEntries(
|
|
107
|
-
Object.entries(config).map(([key, { select }]) => [key, select])
|
|
108
|
-
);
|
|
109
|
-
c.set("input", await parse(inputSchema(config), input));
|
|
110
|
-
await next();
|
|
111
|
-
});
|
|
112
|
-
}
|
|
113
|
-
function verifyContentType(actual, expected) {
|
|
114
|
-
if (!actual) {
|
|
115
|
-
throw new HTTPException2(415, {
|
|
116
|
-
message: "Unsupported Media Type",
|
|
117
|
-
cause: {
|
|
118
|
-
code: "api/unsupported-media-type",
|
|
119
|
-
detail: "Missing content type header"
|
|
120
|
-
}
|
|
121
|
-
});
|
|
122
|
-
}
|
|
123
|
-
const { type: incomingContentType } = parseContentType(actual);
|
|
124
|
-
if (incomingContentType !== expected) {
|
|
125
|
-
throw new HTTPException2(415, {
|
|
126
|
-
message: "Unsupported Media Type",
|
|
127
|
-
cause: {
|
|
128
|
-
code: "api/unsupported-media-type",
|
|
129
|
-
detail: `Expected content type: ${expected}, but got: ${incomingContentType}`
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
async function parseJson(context) {
|
|
135
|
-
try {
|
|
136
|
-
return await context.req.json();
|
|
137
|
-
} catch (error) {
|
|
138
|
-
throw new HTTPException2(400, {
|
|
139
|
-
message: "The request body is not valid JSON",
|
|
140
|
-
cause: {
|
|
141
|
-
code: "api/invalid-json",
|
|
142
|
-
detail: error instanceof Error ? error.message : String(error)
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
function parseQueryParams(queryParams) {
|
|
148
|
-
return Object.fromEntries(
|
|
149
|
-
Object.entries(queryParams).map(([key, value]) => [
|
|
150
|
-
key,
|
|
151
|
-
value === "null" ? null : value
|
|
152
|
-
])
|
|
153
|
-
);
|
|
154
|
-
}
|
|
155
|
-
function parseQueriesParams(queriesParams) {
|
|
156
|
-
return Object.fromEntries(
|
|
157
|
-
Object.entries(queriesParams).map(([key, values]) => [
|
|
158
|
-
key,
|
|
159
|
-
values.map((value) => value === "null" ? null : value)
|
|
160
|
-
])
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// packages/experimental/src/zukhruf/plugins/http/index.ts
|
|
165
22
|
function projectHttp(definition, project) {
|
|
166
23
|
return {
|
|
167
24
|
project(runtime) {
|
|
@@ -172,28 +29,28 @@ function projectHttp(definition, project) {
|
|
|
172
29
|
function mountPath(context) {
|
|
173
30
|
return basePath(context).replace(/\/$/, "");
|
|
174
31
|
}
|
|
175
|
-
var sessionIdSchema =
|
|
176
|
-
var jsonSchema =
|
|
32
|
+
var sessionIdSchema = z.string().refine(validateUuid);
|
|
33
|
+
var jsonSchema = z.custom(
|
|
177
34
|
(value) => typeof value === "object" && value !== null && !Array.isArray(value)
|
|
178
35
|
);
|
|
179
|
-
var clientToolsSchema =
|
|
180
|
-
|
|
181
|
-
|
|
36
|
+
var clientToolsSchema = z.record(
|
|
37
|
+
z.string().min(1),
|
|
38
|
+
z.strictObject({
|
|
182
39
|
inputSchema: jsonSchema,
|
|
183
|
-
description:
|
|
40
|
+
description: z.string().min(1)
|
|
184
41
|
})
|
|
185
42
|
).optional();
|
|
186
|
-
var turnBodySchema =
|
|
43
|
+
var turnBodySchema = z.strictObject({
|
|
187
44
|
sessionId: sessionIdSchema,
|
|
188
|
-
message:
|
|
189
|
-
trigger:
|
|
45
|
+
message: z.unknown(),
|
|
46
|
+
trigger: z.enum(["submit-message", "regenerate-message"]),
|
|
190
47
|
tools: clientToolsSchema,
|
|
191
48
|
elements: elementsSchema
|
|
192
49
|
});
|
|
193
50
|
|
|
194
51
|
// packages/experimental/src/zukhruf/plugins/uploads/index.ts
|
|
195
52
|
import { tool } from "ai";
|
|
196
|
-
import
|
|
53
|
+
import z2 from "zod";
|
|
197
54
|
import { reminder } from "@deepagents/context";
|
|
198
55
|
var extensionByMediaType = {
|
|
199
56
|
"image/png": "png",
|
|
@@ -224,11 +81,11 @@ var UPLOAD_FILE_ID_PATTERN = new RegExp(
|
|
|
224
81
|
function isUploadMediaType(mediaType) {
|
|
225
82
|
return Object.hasOwn(extensionByMediaType, mediaType);
|
|
226
83
|
}
|
|
227
|
-
var publishInputSchema =
|
|
228
|
-
path:
|
|
84
|
+
var publishInputSchema = z2.object({
|
|
85
|
+
path: z2.string().startsWith("/").describe(
|
|
229
86
|
"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)."
|
|
230
87
|
),
|
|
231
|
-
name:
|
|
88
|
+
name: z2.string().min(1).optional().describe("Display name shown to the user; defaults to the file name.")
|
|
232
89
|
});
|
|
233
90
|
|
|
234
91
|
// packages/experimental/src/zukhruf/plugins/uploads/http.ts
|
|
@@ -239,8 +96,8 @@ var NO_STORE = { "cache-control": "no-store" };
|
|
|
239
96
|
var IMMUTABLE = {
|
|
240
97
|
"cache-control": "private, max-age=31536000, immutable"
|
|
241
98
|
};
|
|
242
|
-
var sessionIdSchema2 =
|
|
243
|
-
var uploadFilenameSchema =
|
|
99
|
+
var sessionIdSchema2 = z3.uuid();
|
|
100
|
+
var uploadFilenameSchema = z3.string().min(1).transform((encoded, context) => {
|
|
244
101
|
try {
|
|
245
102
|
return decodeURIComponent(encoded);
|
|
246
103
|
} catch {
|
|
@@ -248,7 +105,7 @@ var uploadFilenameSchema = z5.string().min(1).transform((encoded, context) => {
|
|
|
248
105
|
code: "custom",
|
|
249
106
|
message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`
|
|
250
107
|
});
|
|
251
|
-
return
|
|
108
|
+
return z3.NEVER;
|
|
252
109
|
}
|
|
253
110
|
});
|
|
254
111
|
function uploadsHttp(definition, { maxBytes }) {
|
|
@@ -271,7 +128,7 @@ function uploadRoutes(uploads, maxBytes) {
|
|
|
271
128
|
bodyLimit({
|
|
272
129
|
maxSize: maxBytes,
|
|
273
130
|
onError: () => {
|
|
274
|
-
throw new
|
|
131
|
+
throw new HTTPException2(413, {
|
|
275
132
|
message: "Upload is too large",
|
|
276
133
|
cause: {
|
|
277
134
|
code: "api/payload-too-large",
|
|
@@ -280,7 +137,7 @@ function uploadRoutes(uploads, maxBytes) {
|
|
|
280
137
|
});
|
|
281
138
|
}
|
|
282
139
|
}),
|
|
283
|
-
|
|
140
|
+
validate2((payload) => ({
|
|
284
141
|
sessionId: {
|
|
285
142
|
select: payload.params.sessionId,
|
|
286
143
|
against: sessionIdSchema2
|
|
@@ -293,9 +150,9 @@ function uploadRoutes(uploads, maxBytes) {
|
|
|
293
150
|
async (context) => {
|
|
294
151
|
const { sessionId, name } = context.var.input;
|
|
295
152
|
const contentType = context.req.header("content-type");
|
|
296
|
-
const mediaType = contentType === void 0 ? void 0 :
|
|
153
|
+
const mediaType = contentType === void 0 ? void 0 : parseContentType(contentType).type;
|
|
297
154
|
if (mediaType === void 0 || !isUploadMediaType(mediaType)) {
|
|
298
|
-
throw new
|
|
155
|
+
throw new HTTPException2(415, {
|
|
299
156
|
message: "Unsupported Media Type",
|
|
300
157
|
cause: {
|
|
301
158
|
code: "zukhruf/unsupported-media-type",
|
|
@@ -332,7 +189,7 @@ function uploadRoutes(uploads, maxBytes) {
|
|
|
332
189
|
app.on(
|
|
333
190
|
["GET", "HEAD"],
|
|
334
191
|
SESSION_UPLOAD_ROUTE_PATH,
|
|
335
|
-
|
|
192
|
+
validate2((payload) => ({
|
|
336
193
|
sessionId: {
|
|
337
194
|
select: payload.params.sessionId,
|
|
338
195
|
against: sessionIdSchema2
|
|
@@ -346,7 +203,7 @@ function uploadRoutes(uploads, maxBytes) {
|
|
|
346
203
|
fileId
|
|
347
204
|
);
|
|
348
205
|
if (!upload) {
|
|
349
|
-
throw new
|
|
206
|
+
throw new HTTPException2(404, {
|
|
350
207
|
message: "Upload not found",
|
|
351
208
|
cause: {
|
|
352
209
|
code: "zukhruf/upload-not-found",
|
|
@@ -408,7 +265,7 @@ function parseByteRange(header, total) {
|
|
|
408
265
|
}
|
|
409
266
|
function methodNotAllowed(context, allow) {
|
|
410
267
|
context.header("Allow", allow);
|
|
411
|
-
throw new
|
|
268
|
+
throw new HTTPException2(405, {
|
|
412
269
|
message: "Method not allowed",
|
|
413
270
|
cause: {
|
|
414
271
|
code: "api/method-not-allowed",
|
|
@@ -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/
|
|
4
|
-
"sourcesContent": ["import { 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 { validate } from '../http/validator.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 {\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 { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInstance,\n} from '../../runtime/agent-runtime.ts';\nimport { validate } from './validator.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 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 invalidSessionId('Route and body session IDs must match');\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 invalidMessage('A new session must start with a user message');\n }\n if (request.trigger !== 'submit-message') {\n throw invalidMessage('A new session cannot regenerate a response');\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 let lastWrite: Promise<unknown> = Promise.resolve();\n const write = (event: OwnerEvent) => {\n const next = lastWrite.then(() =>\n stream.writeSSE({ data: JSON.stringify(event) }),\n );\n lastWrite = next.catch(() => {});\n return next;\n };\n const heartbeat = setInterval(() => {\n const next = lastWrite.then(async () => {\n await stream.write(': heartbeat\\n\\n');\n });\n lastWrite = next.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 instanceof 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) throw invalidMessage(result.error.message);\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw invalidMessage('System messages are not accepted');\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 invalidMessage(\n 'Regeneration requires the user message preceding the assistant response',\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\nfunction invalidMessage(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nfunction invalidSessionId(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid session ID',\n cause: { code: 'api/validation-failed', detail },\n });\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 { parse as parseContentType } from 'fast-content-type-parse';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport { parse } from './parse.ts';\n\ntype ContentType =\n | 'application/json'\n | 'application/x-www-form-urlencoded'\n | 'multipart/form-data'\n | 'text/plain';\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodTypeAny }\n>;\n\n/** Each selected input's schema, under the input's name. */\ntype InputShape<T extends ValidatorConfig> = {\n [K in keyof T]: T[K]['against'];\n};\n\ntype ExtractInput<T extends ValidatorConfig> = z.output<\n ReturnType<typeof inputSchema<T>>\n>;\n\n/** The parsed request parts a selector picks its inputs from. */\ninterface RequestPayload {\n body: unknown;\n query: Record<string, string | null | undefined>;\n queries: Record<string, (string | null)[]>;\n params: Record<string, string>;\n headers: Record<string, string | undefined>;\n}\n\ntype SelectorFn<T> = (payload: RequestPayload) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<{\n Variables: {\n input: ExtractInput<T>;\n };\n}>;\n\nfunction inputSchema<T extends ValidatorConfig>(config: T) {\n const shape = Object.fromEntries(\n Object.entries(config).map(([key, { against }]) => [key, against]),\n );\n assertInputShape(shape, config);\n return z.object(shape);\n}\n\nfunction assertInputShape<T extends ValidatorConfig>(\n shape: Record<string, z.ZodTypeAny>,\n config: T,\n): asserts shape is InputShape<T> {\n const keys = Object.keys(config);\n if (\n Object.keys(shape).length !== keys.length ||\n keys.some((key) => shape[key] !== config[key]?.against)\n ) {\n throw new Error('The input schema does not match its selectors');\n }\n}\n\nexport function validate<T extends ValidatorConfig>(\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType,\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType | SelectorFn<T>,\n selector?: SelectorFn<T>,\n): ValidateMiddleware<T> {\n const expectedContentType =\n typeof expectedContentTypeOrSelector === 'string'\n ? expectedContentTypeOrSelector\n : undefined;\n const _selector =\n typeof expectedContentTypeOrSelector === 'function'\n ? expectedContentTypeOrSelector\n : selector;\n void _selector;\n if (!_selector) {\n throw new Error('Selector function is required');\n }\n\n return createMiddleware(async (c, next) => {\n const ct = c.req.header('content-type');\n if (c.req.method === 'GET' && ct) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `GET requests cannot have a content type header`,\n },\n });\n }\n if (expectedContentType) {\n void verifyContentType(ct, expectedContentType);\n }\n\n const contentType = ct ? parseContentType(ct) : null;\n let body: unknown = null;\n\n switch (contentType?.type) {\n case 'application/json':\n body = await parseJson(c);\n break;\n case 'application/x-www-form-urlencoded':\n case 'multipart/form-data':\n body = await c.req.parseBody();\n break;\n default:\n body = {};\n }\n\n const payload: RequestPayload = {\n body,\n query: parseQueryParams(c.req.query()),\n queries: parseQueriesParams(c.req.queries()),\n params: c.req.param(),\n headers: c.req.header(),\n };\n\n const config = _selector(payload);\n const input = Object.fromEntries(\n Object.entries(config).map(([key, { select }]) => [key, select]),\n );\n c.set('input', await parse(inputSchema(config), input));\n await next();\n });\n}\n\nexport const openapi = validate;\n\nexport const consume = (contentType: ContentType) => {\n return createMiddleware(async (context, next) => {\n verifyContentType(context.req.header('content-type'), contentType);\n await next();\n });\n};\n\nexport function verifyContentType(\n actual: string | undefined,\n expected: ContentType,\n): asserts actual is ContentType {\n if (!actual) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: 'Missing content type header',\n },\n });\n }\n const { type: incomingContentType } = parseContentType(actual);\n if (incomingContentType !== expected) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,\n },\n });\n }\n}\n\nasync function parseJson(context: Context) {\n try {\n return await context.req.json();\n } catch (error) {\n throw new HTTPException(400, {\n message: 'The request body is not valid JSON',\n cause: {\n code: 'api/invalid-json',\n detail: error instanceof Error ? error.message : String(error),\n },\n });\n }\n}\n\nfunction parseQueryParams(\n queryParams: Record<string, string | undefined>,\n): Record<string, string | null | undefined> {\n return Object.fromEntries(\n Object.entries(queryParams).map(([key, value]) => [\n key,\n value === 'null' ? null : value,\n ]),\n );\n}\n\nfunction parseQueriesParams(\n queriesParams: Record<string, string[]>,\n): Record<string, (string | null)[]> {\n return Object.fromEntries(\n Object.entries(queriesParams).map(([key, values]) => [\n key,\n values.map((value) => (value === 'null' ? null : value)),\n ]),\n );\n}\n", "import { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ninterface ValidationIssue {\n message: string;\n code: string;\n path: string;\n}\n\nexport async function parse<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n input: unknown,\n) {\n const result = await schema.safeParseAsync(input);\n if (!result.success) {\n const errors: z.inferFlattenedErrors<\n z.ZodObject<T>,\n ValidationIssue\n >['fieldErrors'] = result.error.flatten((issue) => ({\n message: issue.message,\n code: issue.code,\n path: issue.path.join('.'),\n })).fieldErrors;\n\n throw new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n detail: 'The input data is invalid',\n errors,\n },\n });\n }\n return result.data;\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 #host: AgentPluginHost | 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(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.#host = 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.writeFiles([{ path, content: Buffer.from(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.exists(path))) {\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.executeCommand(\n `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 if (this.#host === undefined) {\n throw new Error(\n 'uploads plugin must be initialized before storing or reading uploads',\n );\n }\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 if (!(await sandbox.sandbox.exists(path))) return undefined;\n const bytes = await sandbox.sandbox.readFile(path, { encoding: 'binary' });\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,
|
|
6
|
-
"names": ["
|
|
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 {\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 { 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 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 invalidSessionId('Route and body session IDs must match');\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 invalidMessage('A new session must start with a user message');\n }\n if (request.trigger !== 'submit-message') {\n throw invalidMessage('A new session cannot regenerate a response');\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 let lastWrite: Promise<unknown> = Promise.resolve();\n const write = (event: OwnerEvent) => {\n const next = lastWrite.then(() =>\n stream.writeSSE({ data: JSON.stringify(event) }),\n );\n lastWrite = next.catch(() => {});\n return next;\n };\n const heartbeat = setInterval(() => {\n const next = lastWrite.then(async () => {\n await stream.write(': heartbeat\\n\\n');\n });\n lastWrite = next.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 instanceof 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) throw invalidMessage(result.error.message);\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw invalidMessage('System messages are not accepted');\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 invalidMessage(\n 'Regeneration requires the user message preceding the assistant response',\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\nfunction invalidMessage(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nfunction invalidSessionId(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid session ID',\n cause: { code: 'api/validation-failed', detail },\n });\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 { 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 #host: AgentPluginHost | 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(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.#host = 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.writeFiles([{ path, content: Buffer.from(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.exists(path))) {\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.executeCommand(\n `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 if (this.#host === undefined) {\n throw new Error(\n 'uploads plugin must be initialized before storing or reading uploads',\n );\n }\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 if (!(await sandbox.sandbox.exists(path))) return undefined;\n const bytes = await sandbox.sandbox.readFile(path, { encoding: 'binary' });\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;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;AACzC,OAAO,OAAO;AAEd,SAAS,sBAAsB;AA8CxB,SAAS,YACd,YACA,SAIgB;AAChB,SAAO;AAAA,IACL,QAAQ,SAAS;AACf,aAAO,QAAQ,QAAQ,OAAO,UAAU,GAAG,OAAO;AAAA,IACpD;AAAA,EACF;AACF;AAgBO,SAAS,UAAU,SAA0B;AAClD,SAAO,SAAS,OAAO,EAAE,QAAQ,OAAO,EAAE;AAC5C;AAGA,IAAM,kBAAkB,EAAE,OAAO,EAAE,OAAO,YAAY;AACtD,IAAM,aAAa,EAAE;AAAA,EACnB,CAAC,UACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AACvE;AACA,IAAM,oBAAoB,EACvB;AAAA,EACC,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChB,EAAE,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC;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AAA,IACN;AAAA,EACF;AACA,MAAI;AAAA,IAAI;AAAA,IAA2B,CAAC,YAClC,iBAAiB,SAAS,WAAW;AAAA,EACvC;AAEA,SAAO;AACT;AAMA,SAAS,eACP,QACA,OAC4C;AAC5C,QAAM,QAAQ,sBAAsB,KAAK,OAAO,KAAK,CAAC;AACtD,MAAI,UAAU,QAAQ,UAAU,EAAG,QAAO;AAC1C,QAAM,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", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "validate"]
|
|
7
7
|
}
|
|
@@ -39,10 +39,14 @@ export interface PgBossTurnQueueOptions {
|
|
|
39
39
|
*/
|
|
40
40
|
export declare class PgBossTurnQueue extends TurnQueue {
|
|
41
41
|
#private;
|
|
42
|
-
constructor(
|
|
42
|
+
private constructor();
|
|
43
|
+
/**
|
|
44
|
+
* Opens the queue: creates the turn queue and its dead-letter queue when
|
|
45
|
+
* they are missing, and checks that the schema is the PgBoss schema.
|
|
46
|
+
*/
|
|
47
|
+
static create(boss: PgBoss, options?: PgBossTurnQueueOptions): Promise<PgBossTurnQueue>;
|
|
43
48
|
get queue(): string;
|
|
44
49
|
get deadLetterQueue(): string;
|
|
45
|
-
initialize(): Promise<void>;
|
|
46
50
|
push(turn: TurnRef): Promise<void>;
|
|
47
51
|
getTurnActivity(conversation: Pick<TurnRef, 'chatId' | 'userId'>): Promise<TurnActivity>;
|
|
48
52
|
getCurrentTurn(conversation: Pick<TurnRef, 'chatId' | 'userId'>): Promise<TurnRef | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg-boss.turn-queue.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss.turn-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,MAAM,EAAE,MAAM,SAAS,CAAC;AAMvD,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,SAAS,EACT,KAAK,OAAO,EACb,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,sBAAsB;IACrC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;
|
|
1
|
+
{"version":3,"file":"pg-boss.turn-queue.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss.turn-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,MAAM,EAAE,MAAM,SAAS,CAAC;AAMvD,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,SAAS,EACT,KAAK,OAAO,EACb,MAAM,i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